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.

291 lines
12 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. # before done_parsing: {(domain, mode): set(account_codes)}
  52. # after done_parsing: {(domain, mode): set(account_ids)}
  53. self._map_account_ids = defaultdict(set)
  54. self._set_all_accounts = set() # set((domain, mode))
  55. self._account_ids_by_code = defaultdict(set)
  56. def _load_account_codes(self, account_codes, account_domain):
  57. account_model = self.env['account.account']
  58. # TODO: account_obj is necessary because _get_children_and_consol
  59. # does not work in new API?
  60. account_obj = self.env.registry('account.account')
  61. exact_codes = set()
  62. like_codes = set()
  63. for account_code in account_codes:
  64. if account_code in self._account_ids_by_code:
  65. continue
  66. if '%' in account_code:
  67. like_codes.add(account_code)
  68. else:
  69. exact_codes.add(account_code)
  70. for account in account_model.\
  71. search([('code', 'in', list(exact_codes))] + account_domain):
  72. if account.type in ('view', 'consolidation'):
  73. self._account_ids_by_code[account.code].update(
  74. account_obj._get_children_and_consol(
  75. self.env.cr, self.env.uid,
  76. [account.id],
  77. self.env.context))
  78. else:
  79. self._account_ids_by_code[account.code].add(account.id)
  80. for like_code in like_codes:
  81. for account in account_model.\
  82. search([('code', 'like', like_code)] + account_domain):
  83. if account.type in ('view', 'consolidation'):
  84. self._account_ids_by_code[like_code].update(
  85. account_obj._get_children_and_consol(
  86. self.env.cr, self.env.uid,
  87. [account.id],
  88. self.env.context))
  89. else:
  90. self._account_ids_by_code[like_code].add(account.id)
  91. def _parse_mo(self, mo):
  92. """Split a match object corresponding to an accounting variable
  93. Returns field, mode, [account codes], [domain expression].
  94. """
  95. field, mode, account_codes, domain = mo.groups()
  96. if not mode:
  97. mode = MODE_VARIATION
  98. elif mode == 's':
  99. mode = MODE_END
  100. if account_codes.startswith('_'):
  101. account_codes = account_codes[1:]
  102. else:
  103. account_codes = account_codes[1:-1]
  104. if account_codes.strip():
  105. account_codes = [a.strip() for a in account_codes.split(',')]
  106. else:
  107. account_codes = None
  108. domain = domain or '[]'
  109. domain = tuple(safe_eval(domain))
  110. return field, mode, account_codes, domain
  111. def parse_expr(self, expr):
  112. """Parse an expression, extracting accounting variables.
  113. Domains and accounts are extracted and stored in the map
  114. so when all expressions have been parsed, we know what to query.
  115. """
  116. for mo in self.ACC_RE.finditer(expr):
  117. _, mode, account_codes, domain = self._parse_mo(mo)
  118. key = (domain, mode)
  119. if account_codes:
  120. self._map_account_ids[key].update(account_codes)
  121. else:
  122. self._set_all_accounts.add(key)
  123. def done_parsing(self, account_domain):
  124. # load account codes and replace account codes by account ids in _map
  125. for key, account_codes in self._map_account_ids.items():
  126. self._load_account_codes(account_codes, account_domain)
  127. account_ids = set()
  128. for account_code in account_codes:
  129. account_ids.update(self._account_ids_by_code[account_code])
  130. self._map_account_ids[key] = list(account_ids)
  131. def get_aml_domain_for_expr(self, expr):
  132. """ Get a domain on account.move.line for an expression.
  133. Only accounting expression in mode 'p' and 'e' are considered.
  134. Prerequisite: done_parsing() must have been invoked.
  135. Returns a domain that can be used to search on account.move.line.
  136. """
  137. aml_domains = []
  138. for mo in self.ACC_RE.finditer(expr):
  139. field, mode, account_codes, domain = self._parse_mo(mo)
  140. if mode == MODE_INITIAL:
  141. continue
  142. aml_domain = list(domain)
  143. if account_codes:
  144. account_ids = set()
  145. for account_code in account_codes:
  146. account_ids.update(self._account_ids_by_code[account_code])
  147. aml_domain.append(('account_id', 'in', tuple(account_ids)))
  148. if field == 'crd':
  149. aml_domain.append(('credit', '>', 0))
  150. elif field == 'deb':
  151. aml_domain.append(('debit', '>', 0))
  152. aml_domains.append(expression.normalize_domain(aml_domain))
  153. return expression.OR(aml_domains)
  154. def get_aml_domain_for_dates(self, date_start, date_end, mode):
  155. if mode != MODE_VARIATION:
  156. raise RuntimeError("") # TODO
  157. return [('date', '>=', date_start), ('date', '<=', date_end)]
  158. def get_aml_domain_for_periods(self, period_start, period_end, mode):
  159. period_obj = self.env['account.period']
  160. move_obj = self.env['account.move']
  161. domain_list = []
  162. if mode == MODE_VARIATION:
  163. compute_period_ids = period_obj.build_ctx_periods(
  164. period_start.id,
  165. period_end.id)
  166. domain_list.extend([('period_id', 'in', compute_period_ids)])
  167. else:
  168. period_to = period_end
  169. if mode == MODE_INITIAL:
  170. # Processing to get the first period which isn't special
  171. # before end period
  172. move = move_obj\
  173. .search([('period_id.special', '=', False),
  174. ('period_id.date_start', '<',
  175. period_to.date_start)],
  176. order="period_id desc", limit=1)
  177. if move.id:
  178. computed_period_to = move.period_id
  179. else:
  180. computed_period_to = period_obj.search(
  181. [('company_id', '=', period_start.company_id.id)],
  182. order='date_start desc', limit=1)
  183. # Change start period to search correctly period from
  184. period_to = computed_period_to
  185. move = move_obj.search(
  186. [('period_id.special', '=', True),
  187. ('period_id.date_start', '<=',
  188. period_to.date_start)],
  189. order="period_id desc", limit=1)
  190. if move.id:
  191. computed_period_from = move.period_id
  192. else:
  193. computed_period_from = period_obj.search(
  194. [('company_id', '=', period_start.company_id.id)],
  195. order='date_start', limit=1)
  196. compute_period_ids = period_obj.build_ctx_periods(
  197. computed_period_from.id, period_to.id)
  198. domain_list.extend([('period_id', 'in', compute_period_ids)])
  199. return domain_list
  200. def do_queries(self, period_domain, period_domain_i, period_domain_e):
  201. aml_model = self.env['account.move.line']
  202. # {(domain, mode): {account_id: (debit, credit)}}
  203. self._data = defaultdict(dict)
  204. # fetch sum of debit/credit, grouped by account_id
  205. for key in self._map_account_ids:
  206. domain, mode = key
  207. if mode == MODE_VARIATION:
  208. domain = list(domain) + period_domain
  209. elif mode == MODE_INITIAL:
  210. domain = list(domain) + period_domain_i
  211. elif mode == MODE_END:
  212. domain = list(domain) + period_domain_e
  213. else:
  214. raise RuntimeError("unexpected mode %s" % (mode,))
  215. domain.append(('account_id', 'in', self._map_account_ids[key]))
  216. accs = aml_model.read_group(domain,
  217. ['debit', 'credit', 'account_id'],
  218. ['account_id'])
  219. for acc in accs:
  220. self._data[key][acc['account_id'][0]] = \
  221. (acc['debit'] or 0.0, acc['credit'] or 0.0)
  222. # fetch sum of debit/credit for expressions with no account
  223. for key in self._set_all_accounts:
  224. domain, mode = key
  225. if mode == MODE_VARIATION:
  226. domain = list(domain) + period_domain
  227. elif mode == MODE_INITIAL:
  228. domain = list(domain) + period_domain_i
  229. elif mode == MODE_END:
  230. domain = list(domain) + period_domain_e
  231. else:
  232. raise RuntimeError("unexpected mode %s" % (mode,))
  233. accs = aml_model.read_group(domain,
  234. ['debit', 'credit'],
  235. [])
  236. assert len(accs) == 1
  237. self._data[key][None] = \
  238. (accs[0]['debit'] or 0.0, accs[0]['credit'] or 0.0)
  239. def replace_expr(self, expr):
  240. """Replace accounting variables in an expression by their amount.
  241. Returns a new expression.
  242. This method must be executed after do_queries().
  243. """
  244. def f(mo):
  245. field, mode, account_codes, domain = self._parse_mo(mo)
  246. key = (domain, mode)
  247. account_ids_data = self._data[key]
  248. v = 0.0
  249. for account_code in account_codes or [None]:
  250. if account_code:
  251. account_ids = self._account_ids_by_code[account_code]
  252. else:
  253. account_ids = [None]
  254. for account_id in account_ids:
  255. debit, credit = \
  256. account_ids_data.get(account_id, (0.0, 0.0))
  257. if field == 'bal':
  258. v += debit - credit
  259. elif field == 'deb':
  260. v += debit
  261. elif field == 'crd':
  262. v += credit
  263. return '(' + repr(v) + ')'
  264. return self.ACC_RE.sub(f, expr)