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.

284 lines
12 KiB

  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # mis_builder module for Odoo, Management Information System Builder
  5. # Copyright (C) 2014-2015 ACSONE SA/NV (<http://acsone.eu>)
  6. #
  7. # This file is a part of mis_builder
  8. #
  9. # mis_builder is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU Affero General Public License v3 or later
  11. # as published by the Free Software Foundation, either version 3 of the
  12. # License, or (at your option) any later version.
  13. #
  14. # mis_builder is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU Affero General Public License v3 or later for more details.
  18. #
  19. # You should have received a copy of the GNU Affero General Public License
  20. # v3 or later along with this program.
  21. # If not, see <http://www.gnu.org/licenses/>.
  22. #
  23. ##############################################################################
  24. import re
  25. from collections import defaultdict
  26. from openerp.osv import expression
  27. from openerp.tools.safe_eval import safe_eval
  28. from openerp.tools.translate import _
  29. MODE_VARIATION = 'p'
  30. MODE_INITIAL = 'i'
  31. MODE_END = 'e'
  32. class AccountingExpressionProcessor(object):
  33. """ Processor for accounting expressions.
  34. Expressions of the form <field><mode>[accounts][optional move line domain]
  35. are supported, where:
  36. * field is bal, crd, deb
  37. * mode is i (initial balance), e (ending balance),
  38. p (moves over period)
  39. * accounts is a list of accounts, possibly containing % wildcards
  40. * an optional domain on move lines allowing filters on eg analytic
  41. accounts or journal
  42. Examples:
  43. * bal[70]: variation of the balance of moves on account 70
  44. over the period (it is the same as balp[70]);
  45. * bali[70,60]: balance of accounts 70 and 60 at the start of period;
  46. * bale[1%]: balance of accounts starting with 1 at end of period.
  47. How to use:
  48. * repeatedly invoke parse_expr() for each expression containing
  49. accounting variables as described above; this lets the processor
  50. group domains and modes and accounts;
  51. * when all expressions have been parsed, invoke done_parsing()
  52. to notify the processor that it can prepare to query (mainly
  53. search all accounts - children, consolidation - that will need to
  54. be queried;
  55. * for each period, call do_queries(), then call replace_expr() for each
  56. expression to replace accounting variables with their resulting value
  57. for the given period.
  58. How it works:
  59. * by accumulating the expressions before hand, it ensures to do the
  60. strict minimum number of queries to the database (for each period,
  61. one query per domain and mode);
  62. * it queries using the orm read_group which reduces to a query with
  63. sum on debit and credit and group by on account_id (note: it seems
  64. the orm then does one query per account to fetch the account
  65. name...);
  66. * additionally, one query per view/consolidation account is done to
  67. discover the children accounts.
  68. """
  69. ACC_RE = re.compile(r"(?P<field>\bbal|\bcrd|\bdeb)"
  70. r"(?P<mode>[pise])?"
  71. r"(?P<accounts>_[a-zA-Z0-9]+|\[.*?\])"
  72. r"(?P<domain>\[.*?\])?")
  73. def __init__(self, env):
  74. self.env = env
  75. # before done_parsing: {(domain, mode): set(account_codes)}
  76. # after done_parsing: {(domain, mode): list(account_ids)}
  77. self._map_account_ids = defaultdict(set)
  78. self._account_ids_by_code = defaultdict(set)
  79. def _load_account_codes(self, account_codes, root_account):
  80. account_model = self.env['account.account']
  81. # TODO: account_obj is necessary because _get_children_and_consol
  82. # does not work in new API?
  83. account_obj = self.env.registry('account.account')
  84. exact_codes = set()
  85. like_codes = set()
  86. for account_code in account_codes:
  87. if account_code in self._account_ids_by_code:
  88. continue
  89. if account_code is None:
  90. # by convention the root account is keyed as
  91. # None in _account_ids_by_code, so it is consistent
  92. # with what _parse_match_object returns for an
  93. # empty list of account codes, ie [None]
  94. exact_codes.add(root_account.code)
  95. elif '%' in account_code:
  96. like_codes.add(account_code)
  97. else:
  98. exact_codes.add(account_code)
  99. for account in account_model.\
  100. search([('code', 'in', list(exact_codes)),
  101. ('parent_id', 'child_of', root_account.id)]):
  102. if account.code == root_account.code:
  103. code = None
  104. else:
  105. code = account.code
  106. if account.type in ('view', 'consolidation'):
  107. self._account_ids_by_code[code].update(
  108. account_obj._get_children_and_consol(
  109. self.env.cr, self.env.uid,
  110. [account.id],
  111. self.env.context))
  112. else:
  113. self._account_ids_by_code[code].add(account.id)
  114. for like_code in like_codes:
  115. for account in account_model.\
  116. search([('code', 'like', like_code),
  117. ('parent_id', 'child_of', root_account.id)]):
  118. if account.type in ('view', 'consolidation'):
  119. self._account_ids_by_code[like_code].update(
  120. account_obj._get_children_and_consol(
  121. self.env.cr, self.env.uid,
  122. [account.id],
  123. self.env.context))
  124. else:
  125. self._account_ids_by_code[like_code].add(account.id)
  126. def _parse_match_object(self, mo):
  127. """Split a match object corresponding to an accounting variable
  128. Returns field, mode, [account codes], (domain expression).
  129. """
  130. field, mode, account_codes, domain = mo.groups()
  131. if not mode:
  132. mode = MODE_VARIATION
  133. elif mode == 's':
  134. mode = MODE_END
  135. if account_codes.startswith('_'):
  136. account_codes = account_codes[1:]
  137. else:
  138. account_codes = account_codes[1:-1]
  139. if account_codes.strip():
  140. account_codes = [a.strip() for a in account_codes.split(',')]
  141. else:
  142. account_codes = [None]
  143. domain = domain or '[]'
  144. domain = tuple(safe_eval(domain))
  145. return field, mode, account_codes, domain
  146. def parse_expr(self, expr):
  147. """Parse an expression, extracting accounting variables.
  148. Domains and accounts are extracted and stored in the map
  149. so when all expressions have been parsed, we know which
  150. account codes to query for each domain and mode.
  151. """
  152. for mo in self.ACC_RE.finditer(expr):
  153. _, mode, account_codes, domain = self._parse_match_object(mo)
  154. key = (domain, mode)
  155. self._map_account_ids[key].update(account_codes)
  156. def done_parsing(self, root_account):
  157. """Load account codes and replace account codes by
  158. account ids in map."""
  159. for key, account_codes in self._map_account_ids.items():
  160. self._load_account_codes(account_codes, root_account)
  161. account_ids = set()
  162. for account_code in account_codes:
  163. account_ids.update(self._account_ids_by_code[account_code])
  164. self._map_account_ids[key] = list(account_ids)
  165. @classmethod
  166. def has_account_var(cls, expr):
  167. """Test if an string contains an accounting variable."""
  168. return bool(cls.ACC_RE.search(expr))
  169. def get_aml_domain_for_expr(self, expr,
  170. date_from, date_to,
  171. target_move):
  172. """ Get a domain on account.move.line for an expression.
  173. Prerequisite: done_parsing() must have been invoked.
  174. Returns a domain that can be used to search on account.move.line.
  175. """
  176. aml_domains = []
  177. date_domain_by_mode = {}
  178. for mo in self.ACC_RE.finditer(expr):
  179. field, mode, account_codes, domain = self._parse_match_object(mo)
  180. aml_domain = list(domain)
  181. account_ids = set()
  182. for account_code in account_codes:
  183. account_ids.update(self._account_ids_by_code[account_code])
  184. aml_domain.append(('account_id', 'in', tuple(account_ids)))
  185. if field == 'crd':
  186. aml_domain.append(('credit', '>', 0))
  187. elif field == 'deb':
  188. aml_domain.append(('debit', '>', 0))
  189. aml_domains.append(expression.normalize_domain(aml_domain))
  190. if mode not in date_domain_by_mode:
  191. date_domain_by_mode[mode] = \
  192. self.get_aml_domain_for_dates(date_from, date_to,
  193. mode, target_move)
  194. return expression.OR(aml_domains) + \
  195. expression.OR(date_domain_by_mode.values())
  196. def get_aml_domain_for_dates(self, date_from, date_to,
  197. mode,
  198. target_move):
  199. if mode == MODE_VARIATION:
  200. domain = [('date', '>=', date_from), ('date', '<=', date_to)]
  201. elif mode == MODE_INITIAL:
  202. domain = [('date', '<', date_from)]
  203. elif mode == MODE_END:
  204. domain = [('date', '<=', date_to)]
  205. if target_move == 'posted':
  206. domain.append(('move_id.state', '=', 'posted'))
  207. return expression.normalize_domain(domain)
  208. def do_queries(self, date_from, date_to,
  209. target_move, additional_move_line_filter=None):
  210. """Query sums of debit and credit for all accounts and domains
  211. used in expressions.
  212. This method must be executed after done_parsing().
  213. """
  214. aml_model = self.env['account.move.line']
  215. # {(domain, mode): {account_id: (debit, credit)}}
  216. self._data = defaultdict(dict)
  217. domain_by_mode = {}
  218. for key in self._map_account_ids:
  219. domain, mode = key
  220. if mode not in domain_by_mode:
  221. domain_by_mode[mode] = \
  222. self.get_aml_domain_for_dates(date_from, date_to,
  223. mode, target_move)
  224. domain = list(domain) + domain_by_mode[mode]
  225. domain.append(('account_id', 'in', self._map_account_ids[key]))
  226. if additional_move_line_filter:
  227. domain.extend(additional_move_line_filter)
  228. # fetch sum of debit/credit, grouped by account_id
  229. accs = aml_model.read_group(domain,
  230. ['debit', 'credit', 'account_id'],
  231. ['account_id'])
  232. for acc in accs:
  233. self._data[key][acc['account_id'][0]] = \
  234. (acc['debit'] or 0.0, acc['credit'] or 0.0)
  235. def replace_expr(self, expr):
  236. """Replace accounting variables in an expression by their amount.
  237. Returns a new expression string.
  238. This method must be executed after do_queries().
  239. """
  240. def f(mo):
  241. field, mode, account_codes, domain = self._parse_match_object(mo)
  242. key = (domain, mode)
  243. account_ids_data = self._data[key]
  244. v = 0.0
  245. for account_code in account_codes:
  246. account_ids = self._account_ids_by_code[account_code]
  247. for account_id in account_ids:
  248. debit, credit = \
  249. account_ids_data.get(account_id, (0.0, 0.0))
  250. if field == 'bal':
  251. v += debit - credit
  252. elif field == 'deb':
  253. v += debit
  254. elif field == 'crd':
  255. v += credit
  256. return '(' + repr(v) + ')'
  257. return self.ACC_RE.sub(f, expr)