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.

203 lines
8.5 KiB

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