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.

177 lines
7.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 do_queries(self, period_domain, period_domain_i, period_domain_e):
  118. aml_model = self.env['account.move.line']
  119. self._data = {} # {(domain, mode): {account_id: (debit, credit)}}
  120. for key in self._map:
  121. self._data[key] = {}
  122. domain, mode = key
  123. if mode == 'p':
  124. domain = list(domain) + period_domain
  125. elif mode == 'i':
  126. domain = list(domain) + period_domain_i
  127. elif mode == 'e':
  128. domain = list(domain) + period_domain_e
  129. else:
  130. raise RuntimeError("unexpected mode %s" % (mode,))
  131. domain = [('account_id', 'in', self._map[key])] + domain
  132. accs = aml_model.read_group(domain,
  133. ['debit', 'credit', 'account_id'],
  134. ['account_id'])
  135. for acc in accs:
  136. self._data[key][acc['account_id'][0]] = \
  137. (acc['debit'], acc['credit'])
  138. def replace_expr(self, expr):
  139. """Replace accounting variables in an expression by their amount.
  140. Returns a new expression.
  141. This method must be executed after do_queries().
  142. """
  143. def f(mo):
  144. field, mode, account_codes, domain = self._parse_mo(mo)
  145. key = (domain, mode)
  146. account_ids_data = self._data[key]
  147. v = 0.0
  148. for account_code in account_codes:
  149. for account_id in self._account_ids_by_code[account_code]:
  150. debit, credit = \
  151. account_ids_data.get(account_id, (0.0, 0.0))
  152. if field == 'deb':
  153. v += debit
  154. elif field == 'crd':
  155. v += credit
  156. elif field == 'bal':
  157. v += debit - credit
  158. return '(' + repr(v) + ')'
  159. return self.ACC_RE.sub(f, expr)