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.

263 lines
11 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. MODE_VARIATION = 'p'
  29. MODE_INITIAL = 'i'
  30. MODE_END = 'e'
  31. class AccountingExpressionProcessor(object):
  32. """ Processor for accounting expressions.
  33. Expressions of the form <field><mode>[accounts][optional move line domain]
  34. are supported, where:
  35. * field is bal, crd, deb
  36. * mode is i (initial balance), e (ending balance),
  37. p (moves over period)
  38. * accounts is a list of accounts, possibly containing % wildcards
  39. * an optional domain on move lines allowing filters on eg analytic
  40. accounts or journal
  41. Examples:
  42. * bal[70]: variation of the balance of moves on account 70
  43. over the period (it is the same as balp[70]);
  44. * bali[70,60]: balance of accounts 70 and 60 at the start of period;
  45. * bale[1%]: balance of accounts starting with 1 at end of period.
  46. How to use:
  47. * repeatedly invoke parse_expr() for each expression containing
  48. accounting variables as described above; this lets the processor
  49. group domains and modes and accounts;
  50. * when all expressions have been parsed, invoke done_parsing()
  51. to notify the processor that it can prepare to query (mainly
  52. search all accounts - children, consolidation - that will need to
  53. be queried;
  54. * for each period, call do_queries(), then call replace_expr() for each
  55. expression to replace accounting variables with their resulting value
  56. for the given period.
  57. How it works:
  58. * by accumulating the expressions before hand, it ensures to do the
  59. strict minimum number of queries to the database (for each period,
  60. one query per domain and mode);
  61. * it queries using the orm read_group which reduces to a query with
  62. sum on debit and credit and group by on account_id (note: it seems
  63. the orm then does one query per account to fetch the account
  64. name...);
  65. * additionally, one query per view/consolidation account is done to
  66. discover the children accounts.
  67. """
  68. ACC_RE = re.compile(r"(?P<field>\bbal|\bcrd|\bdeb)"
  69. r"(?P<mode>[pise])?"
  70. r"(?P<accounts>_[a-zA-Z0-9]+|\[.*?\])"
  71. r"(?P<domain>\[.*?\])?")
  72. def __init__(self, env):
  73. self.env = env
  74. # before done_parsing: {(domain, mode): set(account_codes)}
  75. # after done_parsing: {(domain, mode): list(account_ids)}
  76. self._map_account_ids = defaultdict(set)
  77. # {account_code: account_id} where account_code can be
  78. # - None for all accounts
  79. # - NNN% for a like
  80. # - NNN for a code with an exact match
  81. self._account_ids_by_code = defaultdict(set)
  82. def _load_account_codes(self, account_codes):
  83. account_model = self.env['account.account']
  84. exact_codes = set()
  85. for account_code in account_codes:
  86. if account_code in self._account_ids_by_code:
  87. continue
  88. if account_code is None:
  89. # None means we want all accounts
  90. account_ids = account_model.\
  91. search([]).mapped('id')
  92. self._account_ids_by_code[account_code].update(account_ids)
  93. elif '%' in account_code:
  94. account_ids = account_model.\
  95. search([('code', 'like', account_code)]).mapped('id')
  96. self._account_ids_by_code[account_code].update(account_ids)
  97. else:
  98. # search exact codes after the loop to do less queries
  99. exact_codes.add(account_code)
  100. for account in account_model.\
  101. search([('code', 'in', list(exact_codes))]):
  102. self._account_ids_by_code[account.code].add(account.id)
  103. def _parse_match_object(self, mo):
  104. """Split a match object corresponding to an accounting variable
  105. Returns field, mode, [account codes], (domain expression).
  106. """
  107. field, mode, account_codes, domain = mo.groups()
  108. if not mode:
  109. mode = MODE_VARIATION
  110. elif mode == 's':
  111. mode = MODE_END
  112. if account_codes.startswith('_'):
  113. account_codes = account_codes[1:]
  114. else:
  115. account_codes = account_codes[1:-1]
  116. if account_codes.strip():
  117. account_codes = [a.strip() for a in account_codes.split(',')]
  118. else:
  119. account_codes = [None] # None means we want all accounts
  120. domain = domain or '[]'
  121. domain = tuple(safe_eval(domain))
  122. return field, mode, account_codes, domain
  123. def parse_expr(self, expr):
  124. """Parse an expression, extracting accounting variables.
  125. Domains and accounts are extracted and stored in the map
  126. so when all expressions have been parsed, we know which
  127. account codes to query for each domain and mode.
  128. """
  129. for mo in self.ACC_RE.finditer(expr):
  130. _, mode, account_codes, domain = self._parse_match_object(mo)
  131. key = (domain, mode)
  132. self._map_account_ids[key].update(account_codes)
  133. def done_parsing(self):
  134. """Load account codes and replace account codes by
  135. account ids in map."""
  136. for key, account_codes in self._map_account_ids.items():
  137. # TODO _load_account_codes could be done
  138. # for all account_codes at once (also in v8)
  139. self._load_account_codes(account_codes)
  140. account_ids = set()
  141. for account_code in account_codes:
  142. account_ids.update(self._account_ids_by_code[account_code])
  143. self._map_account_ids[key] = list(account_ids)
  144. @classmethod
  145. def has_account_var(cls, expr):
  146. """Test if an string contains an accounting variable."""
  147. return bool(cls.ACC_RE.search(expr))
  148. def get_aml_domain_for_expr(self, expr,
  149. date_from, date_to,
  150. target_move):
  151. """ Get a domain on account.move.line for an expression.
  152. Prerequisite: done_parsing() must have been invoked.
  153. Returns a domain that can be used to search on account.move.line.
  154. """
  155. aml_domains = []
  156. date_domain_by_mode = {}
  157. for mo in self.ACC_RE.finditer(expr):
  158. field, mode, account_codes, domain = self._parse_match_object(mo)
  159. aml_domain = list(domain)
  160. account_ids = set()
  161. for account_code in account_codes:
  162. account_ids.update(self._account_ids_by_code[account_code])
  163. aml_domain.append(('account_id', 'in', tuple(account_ids)))
  164. if field == 'crd':
  165. aml_domain.append(('credit', '>', 0))
  166. elif field == 'deb':
  167. aml_domain.append(('debit', '>', 0))
  168. aml_domains.append(expression.normalize_domain(aml_domain))
  169. if mode not in date_domain_by_mode:
  170. date_domain_by_mode[mode] = \
  171. self.get_aml_domain_for_dates(date_from, date_to,
  172. mode, target_move)
  173. return expression.OR(aml_domains) + \
  174. expression.OR(date_domain_by_mode.values())
  175. def get_aml_domain_for_dates(self, date_from, date_to,
  176. mode,
  177. target_move):
  178. if mode == MODE_VARIATION:
  179. domain = [('date', '>=', date_from), ('date', '<=', date_to)]
  180. elif mode == MODE_INITIAL:
  181. domain = [('date', '<', date_from)]
  182. elif mode == MODE_END:
  183. domain = [('date', '<=', date_to)]
  184. if target_move == 'posted':
  185. domain.append(('move_id.state', '=', 'posted'))
  186. return expression.normalize_domain(domain)
  187. def do_queries(self, date_from, date_to,
  188. target_move, additional_move_line_filter=None):
  189. """Query sums of debit and credit for all accounts and domains
  190. used in expressions.
  191. This method must be executed after done_parsing().
  192. """
  193. aml_model = self.env['account.move.line']
  194. # {(domain, mode): {account_id: (debit, credit)}}
  195. self._data = defaultdict(dict)
  196. domain_by_mode = {}
  197. for key in self._map_account_ids:
  198. domain, mode = key
  199. if mode not in domain_by_mode:
  200. domain_by_mode[mode] = \
  201. self.get_aml_domain_for_dates(date_from, date_to,
  202. mode, target_move)
  203. domain = list(domain) + domain_by_mode[mode]
  204. domain.append(('account_id', 'in', self._map_account_ids[key]))
  205. if additional_move_line_filter:
  206. domain.extend(additional_move_line_filter)
  207. # fetch sum of debit/credit, grouped by account_id
  208. accs = aml_model.read_group(domain,
  209. ['debit', 'credit', 'account_id'],
  210. ['account_id'])
  211. for acc in accs:
  212. self._data[key][acc['account_id'][0]] = \
  213. (acc['debit'] or 0.0, acc['credit'] or 0.0)
  214. def replace_expr(self, expr):
  215. """Replace accounting variables in an expression by their amount.
  216. Returns a new expression string.
  217. This method must be executed after do_queries().
  218. """
  219. def f(mo):
  220. field, mode, account_codes, domain = self._parse_match_object(mo)
  221. key = (domain, mode)
  222. account_ids_data = self._data[key]
  223. v = 0.0
  224. for account_code in account_codes:
  225. account_ids = self._account_ids_by_code[account_code]
  226. for account_id in account_ids:
  227. debit, credit = \
  228. account_ids_data.get(account_id, (0.0, 0.0))
  229. if field == 'bal':
  230. v += debit - credit
  231. elif field == 'deb':
  232. v += debit
  233. elif field == 'crd':
  234. v += credit
  235. return '(' + repr(v) + ')'
  236. return self.ACC_RE.sub(f, expr)