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.

384 lines
17 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.exceptions import Warning
  27. from openerp.osv import expression
  28. from openerp.tools.safe_eval import safe_eval
  29. from openerp.tools.translate import _
  30. MODE_VARIATION = 'p'
  31. MODE_INITIAL = 'i'
  32. MODE_END = 'e'
  33. class AccountingExpressionProcessor(object):
  34. """ Processor for accounting expressions.
  35. Expressions of the form <field><mode>[accounts][optional move line domain]
  36. are supported, where:
  37. * field is bal, crd, deb
  38. * mode is i (initial balance), e (ending balance),
  39. p (moves over period)
  40. * accounts is a list of accounts, possibly containing % wildcards
  41. * an optional domain on move lines allowing filters on eg analytic
  42. accounts or journal
  43. Examples:
  44. * bal[70]: variation of the balance of moves on account 70
  45. over the period (it is the same as balp[70]);
  46. * bali[70,60]: balance of accounts 70 and 60 at the start of period;
  47. * bale[1%]: balance of accounts starting with 1 at end of period.
  48. How to use:
  49. * repeatedly invoke parse_expr() for each expression containing
  50. accounting variables as described above; this lets the processor
  51. group domains and modes and accounts;
  52. * when all expressions have been parsed, invoke done_parsing()
  53. to notify the processor that it can prepare to query (mainly
  54. search all accounts - children, consolidation - that will need to
  55. be queried;
  56. * for each period, call do_queries(), then call replace_expr() for each
  57. expression to replace accounting variables with their resulting value
  58. for the given period.
  59. How it works:
  60. * by accumulating the expressions before hand, it ensures to do the
  61. strict minimum number of queries to the database (for each period,
  62. one query per domain and mode);
  63. * it queries using the orm read_group which reduces to a query with
  64. sum on debit and credit and group by on account_id (note: it seems
  65. the orm then does one query per account to fetch the account
  66. name...);
  67. * additionally, one query per view/consolidation account is done to
  68. discover the children accounts.
  69. """
  70. ACC_RE = re.compile(r"(?P<field>\bbal|\bcrd|\bdeb)"
  71. r"(?P<mode>[pise])?"
  72. r"(?P<accounts>_[0-9]+|\[.*?\])"
  73. r"(?P<domain>\[.*?\])?")
  74. def __init__(self, env):
  75. self.env = env
  76. # before done_parsing: {(domain, mode): set(account_codes)}
  77. # after done_parsing: {(domain, mode): list(account_ids)}
  78. self._map_account_ids = defaultdict(set)
  79. self._account_ids_by_code = defaultdict(set)
  80. def _load_account_codes(self, account_codes, root_account):
  81. account_model = self.env['account.account']
  82. # TODO: account_obj is necessary because _get_children_and_consol
  83. # does not work in new API?
  84. account_obj = self.env.registry('account.account')
  85. exact_codes = set()
  86. like_codes = set()
  87. for account_code in account_codes:
  88. if account_code in self._account_ids_by_code:
  89. continue
  90. if account_code is None:
  91. # by convention the root account is keyed as
  92. # None in _account_ids_by_code, so it is consistent
  93. # with what _parse_match_object returns for an
  94. # empty list of account codes, ie [None]
  95. exact_codes.add(root_account.code)
  96. elif '%' in account_code:
  97. like_codes.add(account_code)
  98. else:
  99. exact_codes.add(account_code)
  100. for account in account_model.\
  101. search([('code', 'in', list(exact_codes)),
  102. ('parent_id', 'child_of', root_account.id)]):
  103. if account.code == root_account.code:
  104. code = None
  105. else:
  106. code = account.code
  107. if account.type in ('view', 'consolidation'):
  108. self._account_ids_by_code[code].update(
  109. account_obj._get_children_and_consol(
  110. self.env.cr, self.env.uid,
  111. [account.id],
  112. self.env.context))
  113. else:
  114. self._account_ids_by_code[code].add(account.id)
  115. for like_code in like_codes:
  116. for account in account_model.\
  117. search([('code', 'like', like_code),
  118. ('parent_id', 'child_of', root_account.id)]):
  119. if account.type in ('view', 'consolidation'):
  120. self._account_ids_by_code[like_code].update(
  121. account_obj._get_children_and_consol(
  122. self.env.cr, self.env.uid,
  123. [account.id],
  124. self.env.context))
  125. else:
  126. self._account_ids_by_code[like_code].add(account.id)
  127. def _parse_match_object(self, mo):
  128. """Split a match object corresponding to an accounting variable
  129. Returns field, mode, [account codes], (domain expression).
  130. """
  131. field, mode, account_codes, domain = mo.groups()
  132. if not mode:
  133. mode = MODE_VARIATION
  134. elif mode == 's':
  135. mode = MODE_END
  136. if account_codes.startswith('_'):
  137. account_codes = account_codes[1:]
  138. else:
  139. account_codes = account_codes[1:-1]
  140. if account_codes.strip():
  141. account_codes = [a.strip() for a in account_codes.split(',')]
  142. else:
  143. account_codes = [None]
  144. domain = domain or '[]'
  145. domain = tuple(safe_eval(domain))
  146. return field, mode, account_codes, domain
  147. def parse_expr(self, expr):
  148. """Parse an expression, extracting accounting variables.
  149. Domains and accounts are extracted and stored in the map
  150. so when all expressions have been parsed, we know which
  151. account codes to query for each domain and mode.
  152. """
  153. for mo in self.ACC_RE.finditer(expr):
  154. _, mode, account_codes, domain = self._parse_match_object(mo)
  155. key = (domain, mode)
  156. self._map_account_ids[key].update(account_codes)
  157. def done_parsing(self, root_account):
  158. """Load account codes and replace account codes by
  159. account ids in map."""
  160. for key, account_codes in self._map_account_ids.items():
  161. self._load_account_codes(account_codes, root_account)
  162. account_ids = set()
  163. for account_code in account_codes:
  164. account_ids.update(self._account_ids_by_code[account_code])
  165. self._map_account_ids[key] = list(account_ids)
  166. @classmethod
  167. def has_account_var(cls, expr):
  168. """Test if an string contains an accounting variable."""
  169. return bool(cls.ACC_RE.search(expr))
  170. def get_aml_domain_for_expr(self, expr,
  171. date_from, date_to,
  172. period_from, period_to,
  173. target_move):
  174. """ Get a domain on account.move.line for an expression.
  175. Prerequisite: done_parsing() must have been invoked.
  176. Returns a domain that can be used to search on account.move.line.
  177. To be meaningful, this domain must be extended with a domain
  178. obtained from get_aml_domain_for_dates()
  179. """
  180. aml_domains = []
  181. domain_by_mode = {}
  182. for mo in self.ACC_RE.finditer(expr):
  183. field, mode, account_codes, domain = self._parse_match_object(mo)
  184. aml_domain = list(domain)
  185. account_ids = set()
  186. for account_code in account_codes:
  187. account_ids.update(self._account_ids_by_code[account_code])
  188. aml_domain.append(('account_id', 'in', tuple(account_ids)))
  189. if field == 'crd':
  190. aml_domain.append(('credit', '>', 0))
  191. elif field == 'deb':
  192. aml_domain.append(('debit', '>', 0))
  193. aml_domains.append(expression.normalize_domain(aml_domain))
  194. if mode not in domain_by_mode:
  195. domain_by_mode[mode] = \
  196. self.get_aml_domain_for_dates(date_from, date_to,
  197. period_from, period_to,
  198. mode, target_move)
  199. return expression.OR(aml_domains) + \
  200. expression.OR(domain_by_mode.values())
  201. def _period_has_moves(self, period):
  202. move_model = self.env['account.move']
  203. return bool(move_model.search([('period_id', '=', period.id)],
  204. limit=1))
  205. def _get_previous_opening_period(self, period, company_id):
  206. period_model = self.env['account.period']
  207. periods = period_model.search(
  208. [('date_start', '<=', period.date_start),
  209. ('special', '=', True),
  210. ('company_id', '=', company_id)],
  211. order="date_start desc",
  212. limit=1)
  213. return periods and periods[0]
  214. def _get_previous_normal_period(self, period, company_id):
  215. period_model = self.env['account.period']
  216. periods = period_model.search(
  217. [('date_start', '<', period.date_start),
  218. ('special', '=', False),
  219. ('company_id', '=', company_id)],
  220. order="date_start desc",
  221. limit=1)
  222. return periods and periods[0]
  223. def _get_first_normal_period(self, company_id):
  224. period_model = self.env['account.period']
  225. periods = period_model.search(
  226. [('special', '=', False),
  227. ('company_id', '=', company_id)],
  228. order="date_start asc",
  229. limit=1)
  230. return periods and periods[0]
  231. def _get_period_ids_between(self, period_from, period_to, company_id):
  232. period_model = self.env['account.period']
  233. periods = period_model.search(
  234. [('date_start', '>=', period_from.date_start),
  235. ('date_stop', '<=', period_to.date_stop),
  236. ('special', '=', False),
  237. ('company_id', '=', company_id)])
  238. period_ids = [p.id for p in periods]
  239. if period_from.special:
  240. period_ids.append(period_from.id)
  241. return period_ids
  242. def _get_period_company_ids(self, period_from, period_to):
  243. period_model = self.env['account.period']
  244. periods = period_model.search(
  245. [('date_start', '>=', period_from.date_start),
  246. ('date_stop', '<=', period_to.date_stop),
  247. ('special', '=', False)])
  248. return set([p.company_id.id for p in periods])
  249. def _get_period_ids_for_mode(self, period_from, period_to, mode):
  250. assert not period_from.special
  251. assert not period_to.special
  252. assert period_from.company_id == period_to.company_id
  253. assert period_from.date_start <= period_to.date_start
  254. period_ids = []
  255. for company_id in self._get_period_company_ids(period_from, period_to):
  256. if mode == MODE_VARIATION:
  257. period_ids.extend(self._get_period_ids_between(
  258. period_from, period_to, company_id))
  259. else:
  260. if mode == MODE_INITIAL:
  261. period_to = self._get_previous_normal_period(
  262. period_from, company_id)
  263. # look for opening period with moves
  264. opening_period = self._get_previous_opening_period(
  265. period_from, company_id)
  266. if opening_period and \
  267. self._period_has_moves(opening_period[0]):
  268. # found opening period with moves
  269. if opening_period.date_start == period_from.date_start and \
  270. mode == MODE_INITIAL:
  271. # if the opening period has the same start date as
  272. # period_from, then we'll find the initial balance
  273. # in the initial period and that's it
  274. period_ids.append(opening_period[0].id)
  275. continue
  276. period_from = opening_period[0]
  277. else:
  278. # no opening period with moves,
  279. # use very first normal period
  280. period_from = self._get_first_normal_period(company_id)
  281. if period_to:
  282. period_ids.extend(self._get_period_ids_between(
  283. period_from, period_to, company_id))
  284. return period_ids
  285. def get_aml_domain_for_dates(self, date_from, date_to,
  286. period_from, period_to,
  287. mode,
  288. target_move):
  289. if period_from and period_to:
  290. period_ids = self._get_period_ids_for_mode(
  291. period_from, period_to, mode)
  292. domain = [('period_id', 'in', period_ids)]
  293. else:
  294. if mode == MODE_VARIATION:
  295. domain = [('date', '>=', date_from), ('date', '<=', date_to)]
  296. else:
  297. raise Warning(_("Modes i and e are only applicable for "
  298. "fiscal periods"))
  299. if target_move == 'posted':
  300. domain.append(('move_id.state', '=', 'posted'))
  301. return expression.normalize_domain(domain)
  302. def do_queries(self, date_from, date_to, period_from, period_to,
  303. target_move):
  304. """Query sums of debit and credit for all accounts and domains
  305. used in expressions.
  306. This method must be executed after done_parsing().
  307. """
  308. aml_model = self.env['account.move.line']
  309. # {(domain, mode): {account_id: (debit, credit)}}
  310. self._data = defaultdict(dict)
  311. domain_by_mode = {}
  312. for key in self._map_account_ids:
  313. domain, mode = key
  314. if mode not in domain_by_mode:
  315. domain_by_mode[mode] = \
  316. self.get_aml_domain_for_dates(date_from, date_to,
  317. period_from, period_to,
  318. mode, target_move)
  319. domain = list(domain) + domain_by_mode[mode]
  320. domain.append(('account_id', 'in', self._map_account_ids[key]))
  321. # fetch sum of debit/credit, grouped by account_id
  322. accs = aml_model.read_group(domain,
  323. ['debit', 'credit', 'account_id'],
  324. ['account_id'])
  325. for acc in accs:
  326. self._data[key][acc['account_id'][0]] = \
  327. (acc['debit'] or 0.0, acc['credit'] or 0.0)
  328. def replace_expr(self, expr):
  329. """Replace accounting variables in an expression by their amount.
  330. Returns a new expression string.
  331. This method must be executed after do_queries().
  332. """
  333. def f(mo):
  334. field, mode, account_codes, domain = self._parse_match_object(mo)
  335. key = (domain, mode)
  336. account_ids_data = self._data[key]
  337. v = 0.0
  338. for account_code in account_codes:
  339. account_ids = self._account_ids_by_code[account_code]
  340. for account_id in account_ids:
  341. debit, credit = \
  342. account_ids_data.get(account_id, (0.0, 0.0))
  343. if field == 'bal':
  344. v += debit - credit
  345. elif field == 'deb':
  346. v += debit
  347. elif field == 'crd':
  348. v += credit
  349. return '(' + repr(v) + ')'
  350. return self.ACC_RE.sub(f, expr)