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.

264 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. 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. # {account_code: account_id} where account_code can be
  79. # - None for all accounts
  80. # - NNN% for a like
  81. # - NNN for a code with an exact match
  82. self._account_ids_by_code = defaultdict(set)
  83. def _load_account_codes(self, account_codes):
  84. account_model = self.env['account.account']
  85. exact_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. # None means we want all accounts
  91. account_ids = account_model.\
  92. search([]).mapped('id')
  93. self._account_ids_by_code[account_code].update(account_ids)
  94. elif '%' in account_code:
  95. account_ids = account_model.\
  96. search([('code', 'like', account_code)]).mapped('id')
  97. self._account_ids_by_code[account_code].update(account_ids)
  98. else:
  99. # search exact codes after the loop to do less queries
  100. exact_codes.add(account_code)
  101. for account in account_model.\
  102. search([('code', 'in', list(exact_codes))]):
  103. self._account_ids_by_code[account.code].add(account.id)
  104. def _parse_match_object(self, mo):
  105. """Split a match object corresponding to an accounting variable
  106. Returns field, mode, [account codes], (domain expression).
  107. """
  108. field, mode, account_codes, domain = mo.groups()
  109. if not mode:
  110. mode = MODE_VARIATION
  111. elif mode == 's':
  112. mode = MODE_END
  113. if account_codes.startswith('_'):
  114. account_codes = account_codes[1:]
  115. else:
  116. account_codes = account_codes[1:-1]
  117. if account_codes.strip():
  118. account_codes = [a.strip() for a in account_codes.split(',')]
  119. else:
  120. account_codes = [None] # None means we want all accounts
  121. domain = domain or '[]'
  122. domain = tuple(safe_eval(domain))
  123. return field, mode, account_codes, domain
  124. def parse_expr(self, expr):
  125. """Parse an expression, extracting accounting variables.
  126. Domains and accounts are extracted and stored in the map
  127. so when all expressions have been parsed, we know which
  128. account codes to query for each domain and mode.
  129. """
  130. for mo in self.ACC_RE.finditer(expr):
  131. _, mode, account_codes, domain = self._parse_match_object(mo)
  132. key = (domain, mode)
  133. self._map_account_ids[key].update(account_codes)
  134. def done_parsing(self):
  135. """Load account codes and replace account codes by
  136. account ids in map."""
  137. for key, account_codes in self._map_account_ids.items():
  138. # TODO _load_account_codes could be done
  139. # for all account_codes at once (also in v8)
  140. self._load_account_codes(account_codes)
  141. account_ids = set()
  142. for account_code in account_codes:
  143. account_ids.update(self._account_ids_by_code[account_code])
  144. self._map_account_ids[key] = list(account_ids)
  145. @classmethod
  146. def has_account_var(cls, expr):
  147. """Test if an string contains an accounting variable."""
  148. return bool(cls.ACC_RE.search(expr))
  149. def get_aml_domain_for_expr(self, expr,
  150. date_from, date_to,
  151. target_move):
  152. """ Get a domain on account.move.line for an expression.
  153. Prerequisite: done_parsing() must have been invoked.
  154. Returns a domain that can be used to search on account.move.line.
  155. """
  156. aml_domains = []
  157. date_domain_by_mode = {}
  158. for mo in self.ACC_RE.finditer(expr):
  159. field, mode, account_codes, domain = self._parse_match_object(mo)
  160. aml_domain = list(domain)
  161. account_ids = set()
  162. for account_code in account_codes:
  163. account_ids.update(self._account_ids_by_code[account_code])
  164. aml_domain.append(('account_id', 'in', tuple(account_ids)))
  165. if field == 'crd':
  166. aml_domain.append(('credit', '>', 0))
  167. elif field == 'deb':
  168. aml_domain.append(('debit', '>', 0))
  169. aml_domains.append(expression.normalize_domain(aml_domain))
  170. if mode not in date_domain_by_mode:
  171. date_domain_by_mode[mode] = \
  172. self.get_aml_domain_for_dates(date_from, date_to,
  173. mode, target_move)
  174. return expression.OR(aml_domains) + \
  175. expression.OR(date_domain_by_mode.values())
  176. def get_aml_domain_for_dates(self, date_from, date_to,
  177. mode,
  178. target_move):
  179. if mode == MODE_VARIATION:
  180. domain = [('date', '>=', date_from), ('date', '<=', date_to)]
  181. elif mode == MODE_INITIAL:
  182. domain = [('date', '<', date_from)]
  183. elif mode == MODE_END:
  184. domain = [('date', '<=', date_to)]
  185. if target_move == 'posted':
  186. domain.append(('move_id.state', '=', 'posted'))
  187. return expression.normalize_domain(domain)
  188. def do_queries(self, date_from, date_to,
  189. target_move, additional_move_line_filter=None):
  190. """Query sums of debit and credit for all accounts and domains
  191. used in expressions.
  192. This method must be executed after done_parsing().
  193. """
  194. aml_model = self.env['account.move.line']
  195. # {(domain, mode): {account_id: (debit, credit)}}
  196. self._data = defaultdict(dict)
  197. domain_by_mode = {}
  198. for key in self._map_account_ids:
  199. domain, mode = key
  200. if mode not in domain_by_mode:
  201. domain_by_mode[mode] = \
  202. self.get_aml_domain_for_dates(date_from, date_to,
  203. mode, target_move)
  204. domain = list(domain) + domain_by_mode[mode]
  205. domain.append(('account_id', 'in', self._map_account_ids[key]))
  206. if additional_move_line_filter:
  207. domain.extend(additional_move_line_filter)
  208. # fetch sum of debit/credit, grouped by account_id
  209. accs = aml_model.read_group(domain,
  210. ['debit', 'credit', 'account_id'],
  211. ['account_id'])
  212. for acc in accs:
  213. self._data[key][acc['account_id'][0]] = \
  214. (acc['debit'] or 0.0, acc['credit'] or 0.0)
  215. def replace_expr(self, expr):
  216. """Replace accounting variables in an expression by their amount.
  217. Returns a new expression string.
  218. This method must be executed after do_queries().
  219. """
  220. def f(mo):
  221. field, mode, account_codes, domain = self._parse_match_object(mo)
  222. key = (domain, mode)
  223. account_ids_data = self._data[key]
  224. v = 0.0
  225. for account_code in account_codes:
  226. account_ids = self._account_ids_by_code[account_code]
  227. for account_id in account_ids:
  228. debit, credit = \
  229. account_ids_data.get(account_id, (0.0, 0.0))
  230. if field == 'bal':
  231. v += debit - credit
  232. elif field == 'deb':
  233. v += debit
  234. elif field == 'crd':
  235. v += credit
  236. return '(' + repr(v) + ')'
  237. return self.ACC_RE.sub(f, expr)