You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

351 lines
15 KiB

  1. import re
  2. from collections import defaultdict
  3. from openerp.exceptions import Warning
  4. from openerp.osv import expression
  5. from openerp.tools.safe_eval import safe_eval
  6. from openerp.tools.translate import _
  7. MODE_VARIATION = 'p'
  8. MODE_INITIAL = 'i'
  9. MODE_END = 'e'
  10. class AccountingExpressionProcessor(object):
  11. """ Processor for accounting expressions.
  12. Expressions of the form <field><mode>[accounts][optional move line domain]
  13. are supported, where:
  14. * field is bal, crd, deb
  15. * mode is i (initial balance), e (ending balance),
  16. p (moves over period)
  17. * accounts is a list of accounts, possibly containing % wildcards
  18. * an optional domain on move lines allowing filters on eg analytic
  19. accounts or journal
  20. Examples:
  21. * bal[70]: variation of the balance of moves on account 70
  22. over the period (it is the same as balp[70]);
  23. * bali[70,60]: initial balance of accounts 70 and 60;
  24. * bale[1%]: balance of accounts starting with 1 at end of period.
  25. How to use:
  26. * repeatedly invoke parse_expr() for each expression containing
  27. accounting variables as described above; this lets the processor
  28. group domains and modes and accounts;
  29. * when all expressions have been parsed, invoke done_parsing()
  30. to notify the processor that it can prepare to query (mainly
  31. search all accounts - children, consolidation - that will need to
  32. be queried;
  33. * for each period, call do_queries(), then call replace_expr() for each
  34. expression to replace accounting variables with their resulting value
  35. for the given period.
  36. How it works:
  37. * by accumulating the expressions before hand, it ensures to do the
  38. strict minimum number of queries to the database (for each period,
  39. one query per domain and mode);
  40. * it queries using the orm read_group which reduces to a query with
  41. sum on debit and credit and group by on account_id (note: it seems
  42. the orm then does one query per account to fetch the account
  43. name...);
  44. * additionally, one query per view/consolidation account is done to
  45. discover the children accounts.
  46. """
  47. ACC_RE = re.compile(r"(?P<field>\bbal|\bcrd|\bdeb)"
  48. r"(?P<mode>[pise])?"
  49. r"(?P<accounts>_[0-9]+|\[.*?\])"
  50. r"(?P<domain>\[.*?\])?")
  51. def __init__(self, env):
  52. self.env = env
  53. # before done_parsing: {(domain, mode): set(account_codes)}
  54. # after done_parsing: {(domain, mode): set(account_ids)}
  55. self._map_account_ids = defaultdict(set)
  56. self._account_ids_by_code = defaultdict(set)
  57. def _load_account_codes(self, account_codes, root_account):
  58. account_model = self.env['account.account']
  59. # TODO: account_obj is necessary because _get_children_and_consol
  60. # does not work in new API?
  61. account_obj = self.env.registry('account.account')
  62. exact_codes = set()
  63. like_codes = set()
  64. for account_code in account_codes:
  65. if account_code in self._account_ids_by_code:
  66. continue
  67. if account_code is None:
  68. # by convention the root account is keyed as
  69. # None in _account_ids_by_code, so it is consistent
  70. # with what _parse_match_object returns for an
  71. # empty list of account codes, ie [None]
  72. exact_codes.add(root_account.code)
  73. elif '%' in account_code:
  74. like_codes.add(account_code)
  75. else:
  76. exact_codes.add(account_code)
  77. for account in account_model.\
  78. search([('code', 'in', list(exact_codes)),
  79. ('parent_id', 'child_of', root_account.id)]):
  80. if account.code == root_account.code:
  81. code = None
  82. else:
  83. code = account.code
  84. if account.type in ('view', 'consolidation'):
  85. self._account_ids_by_code[code].update(
  86. account_obj._get_children_and_consol(
  87. self.env.cr, self.env.uid,
  88. [account.id],
  89. self.env.context))
  90. else:
  91. self._account_ids_by_code[code].add(account.id)
  92. for like_code in like_codes:
  93. for account in account_model.\
  94. search([('code', 'like', like_code),
  95. ('parent_id', 'child_of', root_account.id)]):
  96. if account.type in ('view', 'consolidation'):
  97. self._account_ids_by_code[like_code].update(
  98. account_obj._get_children_and_consol(
  99. self.env.cr, self.env.uid,
  100. [account.id],
  101. self.env.context))
  102. else:
  103. self._account_ids_by_code[like_code].add(account.id)
  104. def _parse_match_object(self, mo):
  105. """Split a match object corresponding to an accounting variable
  106. Returns field, mode, [account codes], [domain expression].
  107. """
  108. field, mode, account_codes, domain = mo.groups()
  109. if not mode:
  110. mode = MODE_VARIATION
  111. elif mode == 's':
  112. mode = MODE_END
  113. if account_codes.startswith('_'):
  114. account_codes = account_codes[1:]
  115. else:
  116. account_codes = account_codes[1:-1]
  117. if account_codes.strip():
  118. account_codes = [a.strip() for a in account_codes.split(',')]
  119. else:
  120. account_codes = [None]
  121. domain = domain or '[]'
  122. domain = tuple(safe_eval(domain))
  123. return field, mode, account_codes, domain
  124. def parse_expr(self, expr):
  125. """Parse an expression, extracting accounting variables.
  126. Domains and accounts are extracted and stored in the map
  127. so when all expressions have been parsed, we know what to query.
  128. """
  129. for mo in self.ACC_RE.finditer(expr):
  130. _, mode, account_codes, domain = self._parse_match_object(mo)
  131. key = (domain, mode)
  132. self._map_account_ids[key].update(account_codes)
  133. def done_parsing(self, root_account):
  134. # load account codes and replace account codes by account ids in _map
  135. for key, account_codes in self._map_account_ids.items():
  136. self._load_account_codes(account_codes, root_account)
  137. account_ids = set()
  138. for account_code in account_codes:
  139. account_ids.update(self._account_ids_by_code[account_code])
  140. self._map_account_ids[key] = list(account_ids)
  141. def has_account_var(self, expr):
  142. return bool(self.ACC_RE.search(expr))
  143. def get_aml_domain_for_expr(self, expr,
  144. date_from, date_to,
  145. period_from, period_to,
  146. target_move):
  147. """ Get a domain on account.move.line for an expression.
  148. Prerequisite: done_parsing() must have been invoked.
  149. Returns a domain that can be used to search on account.move.line.
  150. To be meaningful, this domain must be extended with a domain
  151. obtained from get_aml_domain_for_dates()
  152. """
  153. aml_domains = []
  154. domain_by_mode = {}
  155. for mo in self.ACC_RE.finditer(expr):
  156. field, mode, account_codes, domain = self._parse_match_object(mo)
  157. aml_domain = list(domain)
  158. account_ids = set()
  159. for account_code in account_codes:
  160. account_ids.update(self._account_ids_by_code[account_code])
  161. aml_domain.append(('account_id', 'in', tuple(account_ids)))
  162. if field == 'crd':
  163. aml_domain.append(('credit', '>', 0))
  164. elif field == 'deb':
  165. aml_domain.append(('debit', '>', 0))
  166. aml_domains.append(expression.normalize_domain(aml_domain))
  167. if mode not in domain_by_mode:
  168. domain_by_mode[mode] = \
  169. self.get_aml_domain_for_dates(date_from, date_to,
  170. period_from, period_to,
  171. mode, target_move)
  172. return expression.OR(aml_domains) + \
  173. expression.OR(domain_by_mode.values())
  174. def _period_has_moves(self, period):
  175. move_model = self.env['account.move']
  176. return bool(move_model.search([('period_id', '=', period.id)],
  177. limit=1))
  178. def _get_previous_opening_period(self, period, company_id):
  179. period_model = self.env['account.period']
  180. periods = period_model.search(
  181. [('date_start', '<=', period.date_start),
  182. ('special', '=', True),
  183. ('company_id', '=', company_id)],
  184. order="date_start desc",
  185. limit=1)
  186. return periods and periods[0]
  187. def _get_previous_normal_period(self, period, company_id):
  188. period_model = self.env['account.period']
  189. periods = period_model.search(
  190. [('date_start', '<', period.date_start),
  191. ('special', '=', False),
  192. ('company_id', '=', company_id)],
  193. order="date_start desc",
  194. limit=1)
  195. return periods and periods[0]
  196. def _get_first_normal_period(self, company_id):
  197. period_model = self.env['account.period']
  198. periods = period_model.search(
  199. [('special', '=', False),
  200. ('company_id', '=', company_id)],
  201. order="date_start asc",
  202. limit=1)
  203. return periods and periods[0]
  204. def _get_period_ids_between(self, period_from, period_to, company_id):
  205. period_model = self.env['account.period']
  206. periods = period_model.search(
  207. [('date_start', '>=', period_from.date_start),
  208. ('date_stop', '<=', period_to.date_stop),
  209. ('special', '=', False),
  210. ('company_id', '=', company_id)])
  211. period_ids = [p.id for p in periods]
  212. if period_from.special:
  213. period_ids.append(period_from.id)
  214. return period_ids
  215. def _get_period_company_ids(self, period_from, period_to):
  216. period_model = self.env['account.period']
  217. periods = period_model.search(
  218. [('date_start', '>=', period_from.date_start),
  219. ('date_stop', '<=', period_to.date_stop),
  220. ('special', '=', False)])
  221. return set([p.company_id.id for p in periods])
  222. def _get_period_ids_for_mode(self, period_from, period_to, mode):
  223. assert not period_from.special
  224. assert not period_to.special
  225. assert period_from.company_id == period_to.company_id
  226. assert period_from.date_start <= period_to.date_start
  227. period_ids = []
  228. for company_id in self._get_period_company_ids(period_from, period_to):
  229. if mode == MODE_VARIATION:
  230. period_ids.extend(self._get_period_ids_between(
  231. period_from, period_to, company_id))
  232. else:
  233. if mode == MODE_INITIAL:
  234. period_to = self._get_previous_normal_period(
  235. period_from, company_id)
  236. # look for opening period with moves
  237. opening_period = self._get_previous_opening_period(
  238. period_from, company_id)
  239. if opening_period and \
  240. self._period_has_moves(opening_period[0]):
  241. # found opening period with moves
  242. if opening_period.date_start == period_from.date_start and \
  243. mode == MODE_INITIAL:
  244. # if the opening period has the same start date as
  245. # period_from, then we'll find the initial balance
  246. # in the initial period and that's it
  247. period_ids.append(opening_period[0].id)
  248. continue
  249. period_from = opening_period[0]
  250. else:
  251. # no opening period with moves,
  252. # use very first normal period
  253. period_from = self._get_first_normal_period(company_id)
  254. if period_to:
  255. period_ids.extend(self._get_period_ids_between(
  256. period_from, period_to, company_id))
  257. return period_ids
  258. def get_aml_domain_for_dates(self, date_from, date_to,
  259. period_from, period_to,
  260. mode,
  261. target_move):
  262. if period_from and period_to:
  263. period_ids = self._get_period_ids_for_mode(
  264. period_from, period_to, mode)
  265. domain = [('period_id', 'in', period_ids)]
  266. else:
  267. if mode == MODE_VARIATION:
  268. domain = [('date', '>=', date_from), ('date', '<=', date_to)]
  269. else:
  270. raise Warning(_("Modes i and e are only applicable for "
  271. "fiscal periods"))
  272. if target_move == 'posted':
  273. domain.append(('move_id.state', '=', 'posted'))
  274. return expression.normalize_domain(domain)
  275. def do_queries(self, date_from, date_to, period_from, period_to,
  276. target_move):
  277. aml_model = self.env['account.move.line']
  278. # {(domain, mode): {account_id: (debit, credit)}}
  279. self._data = defaultdict(dict)
  280. domain_by_mode = {}
  281. for key in self._map_account_ids:
  282. domain, mode = key
  283. if mode not in domain_by_mode:
  284. domain_by_mode[mode] = \
  285. self.get_aml_domain_for_dates(date_from, date_to,
  286. period_from, period_to,
  287. mode, target_move)
  288. domain = list(domain) + domain_by_mode[mode]
  289. domain.append(('account_id', 'in', self._map_account_ids[key]))
  290. # fetch sum of debit/credit, grouped by account_id
  291. accs = aml_model.read_group(domain,
  292. ['debit', 'credit', 'account_id'],
  293. ['account_id'])
  294. for acc in accs:
  295. self._data[key][acc['account_id'][0]] = \
  296. (acc['debit'] or 0.0, acc['credit'] or 0.0)
  297. def replace_expr(self, expr):
  298. """Replace accounting variables in an expression by their amount.
  299. Returns a new expression.
  300. This method must be executed after do_queries().
  301. """
  302. def f(mo):
  303. field, mode, account_codes, domain = self._parse_match_object(mo)
  304. key = (domain, mode)
  305. account_ids_data = self._data[key]
  306. v = 0.0
  307. for account_code in account_codes:
  308. account_ids = self._account_ids_by_code[account_code]
  309. for account_id in account_ids:
  310. debit, credit = \
  311. account_ids_data.get(account_id, (0.0, 0.0))
  312. if field == 'bal':
  313. v += debit - credit
  314. elif field == 'deb':
  315. v += debit
  316. elif field == 'crd':
  317. v += credit
  318. return '(' + repr(v) + ')'
  319. return self.ACC_RE.sub(f, expr)