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.

221 lines
9.1 KiB

  1. import re
  2. from collections import defaultdict
  3. from openerp.osv import expression
  4. from openerp.tools.safe_eval import safe_eval
  5. MODE_VARIATION = 'p'
  6. MODE_INITIAL = 'i'
  7. MODE_END = 'e'
  8. class AccountingExpressionProcessor(object):
  9. """ Processor for accounting expressions.
  10. Expressions of the form <field><mode>[accounts][optional move line domain]
  11. are supported, where:
  12. * field is bal, crd, deb
  13. * mode is i (initial balance), e (ending balance),
  14. p (moves over period)
  15. * accounts is a list of accounts, possibly containing % wildcards
  16. * an optional domain on analytic lines allowing filters on eg analytic
  17. accounts or journal
  18. Examples:
  19. * bal[70]: balance of moves on account 70 over the period
  20. (it is the same as balp[70]);
  21. * bali[70,60]: initial balance of accounts 70 and 60;
  22. * bale[1%]: balance of accounts starting with 1 at end of period.
  23. How to use:
  24. * repeatedly invoke parse_expr() for each expression containing
  25. accounting variables as described above; this let the processor
  26. group domains and modes and accounts;
  27. * when all expressions have been parsed, invoke done_parsing()
  28. to notify the processor that it can prepare to query (mainly
  29. search all accounts - children, consolidation - that will need to
  30. be queried;
  31. * for each period, call do_queries(), then call replace_expr() for each
  32. expression to replace accounting variables with their resulting value
  33. for the given period.
  34. How it works:
  35. * by accumulating the expressions before hand, it ensure to do the
  36. strict minimum number of queries to the database (for each period,
  37. one query per domain and mode);
  38. * it queries using the orm read_group which reduces to a query with
  39. sum on debit and credit and group by on account_id (note: it seems
  40. the orm then does one query per account to fetch the account
  41. name...);
  42. * additionally, one query per view/consolidation account is done to
  43. discover the children accounts.
  44. """
  45. ACC_RE = re.compile(r"(?P<field>\bbal|\bcrd|\bdeb)"
  46. r"(?P<mode>[pise])?"
  47. r"(?P<accounts>_[0-9]+|\[.*?\])"
  48. r"(?P<domain>\[.*?\])?")
  49. def __init__(self, env):
  50. self.env = env
  51. self._map = defaultdict(set) # {(domain, mode): set(account_ids)}
  52. self._account_ids_by_code = defaultdict(set)
  53. def _load_account_codes(self, account_codes, account_domain):
  54. account_model = self.env['account.account']
  55. # TODO: account_obj is necessary because _get_children_and_consol
  56. # does not work in new API?
  57. account_obj = self.env.registry('account.account')
  58. exact_codes = set()
  59. like_codes = set()
  60. for account_code in account_codes:
  61. if account_code in self._account_ids_by_code:
  62. continue
  63. if '%' in account_code:
  64. like_codes.add(account_code)
  65. else:
  66. exact_codes.add(account_code)
  67. for account in account_model.\
  68. search([('code', 'in', list(exact_codes))] + account_domain):
  69. if account.type in ('view', 'consolidation'):
  70. self._account_ids_by_code[account.code].update(
  71. account_obj._get_children_and_consol(
  72. self.env.cr, self.env.uid,
  73. [account.id],
  74. self.env.context))
  75. else:
  76. self._account_ids_by_code[account.code].add(account.id)
  77. for like_code in like_codes:
  78. for account in account_model.\
  79. search([('code', 'like', like_code)] + account_domain):
  80. if account.type in ('view', 'consolidation'):
  81. self._account_ids_by_code[like_code].update(
  82. account_obj._get_children_and_consol(
  83. self.env.cr, self.env.uid,
  84. [account.id],
  85. self.env.context))
  86. else:
  87. self._account_ids_by_code[like_code].add(account.id)
  88. def _parse_mo(self, mo):
  89. """Split a match object corresponding to an accounting variable
  90. Returns field, mode, [account codes], [domain expression].
  91. """
  92. field, mode, account_codes, domain = mo.groups()
  93. if not mode:
  94. mode = MODE_VARIATION
  95. elif mode == 's':
  96. mode = MODE_END
  97. if account_codes.startswith('_'):
  98. account_codes = account_codes[1:]
  99. else:
  100. account_codes = account_codes[1:-1]
  101. account_codes = [a.strip() for a in account_codes.split(',')]
  102. domain = domain or '[]'
  103. domain = tuple(safe_eval(domain))
  104. return field, mode, account_codes, domain
  105. def parse_expr(self, expr):
  106. """Parse an expression, extracting accounting variables.
  107. Domains and accounts are extracted and stored in the map
  108. so when all expressions have been parsed, we know what to query.
  109. """
  110. for mo in self.ACC_RE.finditer(expr):
  111. field, mode, account_codes, domain = self._parse_mo(mo)
  112. key = (domain, mode)
  113. self._map[key].update(account_codes)
  114. def done_parsing(self, account_domain):
  115. # load account codes and replace account codes by account ids in _map
  116. for key, account_codes in self._map.items():
  117. self._load_account_codes(account_codes, account_domain)
  118. account_ids = set()
  119. for account_code in account_codes:
  120. account_ids.update(self._account_ids_by_code[account_code])
  121. self._map[key] = list(account_ids)
  122. def get_aml_domain_for_expr(self, expr):
  123. """ Get a domain on account.move.line for an expression.
  124. Only accounting expression in mode 'p' and 'e' are considered.
  125. Prerequisite: done_parsing() must have been invoked.
  126. Returns a domain that can be used to search on account.move.line.
  127. """
  128. domains = []
  129. for mo in self.ACC_RE.finditer(expr):
  130. field, mode, account_codes, domain_partial = self._parse_mo(mo)
  131. if mode == MODE_INITIAL:
  132. continue
  133. account_ids = set()
  134. for account_code in account_codes:
  135. account_ids.update(self._account_ids_by_code[account_code])
  136. domain = [('account_id', 'in', tuple(account_ids))]
  137. domain.extend(list(domain_partial))
  138. if field == 'crd':
  139. domain.append(('credit', '>', 0))
  140. elif field == 'deb':
  141. domain.append(('debit', '>', 0))
  142. domain.extend(domain)
  143. domains.append(expression.normalize_domain(domain))
  144. return expression.OR(domains)
  145. def get_aml_domain_for_dates(self, date_start, date_end, mode):
  146. if mode != MODE_VARIATION:
  147. raise RuntimeError("") # TODO
  148. return [('date', '>=', date_start), ('date', '<=', date_end)]
  149. def get_aml_domain_for_periods(self, period_start, period_end, mode):
  150. # TODO
  151. raise RuntimeError("not implemented")
  152. def do_queries(self, period_domain, period_domain_i, period_domain_e):
  153. aml_model = self.env['account.move.line']
  154. self._data = {} # {(domain, mode): {account_id: (debit, credit)}}
  155. for key in self._map:
  156. self._data[key] = {}
  157. domain, mode = key
  158. if mode == MODE_VARIATION:
  159. domain = list(domain) + period_domain
  160. elif mode == MODE_INITIAL:
  161. domain = list(domain) + period_domain_i
  162. elif mode == MODE_END:
  163. domain = list(domain) + period_domain_e
  164. else:
  165. raise RuntimeError("unexpected mode %s" % (mode,))
  166. domain = [('account_id', 'in', self._map[key])] + domain
  167. accs = aml_model.read_group(domain,
  168. ['debit', 'credit', 'account_id'],
  169. ['account_id'])
  170. for acc in accs:
  171. self._data[key][acc['account_id'][0]] = \
  172. (acc['debit'], acc['credit'])
  173. def replace_expr(self, expr):
  174. """Replace accounting variables in an expression by their amount.
  175. Returns a new expression.
  176. This method must be executed after do_queries().
  177. """
  178. def f(mo):
  179. field, mode, account_codes, domain = self._parse_mo(mo)
  180. key = (domain, mode)
  181. account_ids_data = self._data[key]
  182. v = 0.0
  183. for account_code in account_codes:
  184. for account_id in self._account_ids_by_code[account_code]:
  185. debit, credit = \
  186. account_ids_data.get(account_id, (0.0, 0.0))
  187. if field == 'deb':
  188. v += debit
  189. elif field == 'crd':
  190. v += credit
  191. elif field == 'bal':
  192. v += debit - credit
  193. return '(' + repr(v) + ')'
  194. return self.ACC_RE.sub(f, expr)