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.

382 lines
16 KiB

10 years ago
  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>_[a-zA-Z0-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. """
  178. aml_domains = []
  179. date_domain_by_mode = {}
  180. for mo in self.ACC_RE.finditer(expr):
  181. field, mode, account_codes, domain = self._parse_match_object(mo)
  182. aml_domain = list(domain)
  183. account_ids = set()
  184. for account_code in account_codes:
  185. account_ids.update(self._account_ids_by_code[account_code])
  186. aml_domain.append(('account_id', 'in', tuple(account_ids)))
  187. if field == 'crd':
  188. aml_domain.append(('credit', '>', 0))
  189. elif field == 'deb':
  190. aml_domain.append(('debit', '>', 0))
  191. aml_domains.append(expression.normalize_domain(aml_domain))
  192. if mode not in date_domain_by_mode:
  193. date_domain_by_mode[mode] = \
  194. self.get_aml_domain_for_dates(date_from, date_to,
  195. period_from, period_to,
  196. mode, target_move)
  197. return expression.OR(aml_domains) + \
  198. expression.OR(date_domain_by_mode.values())
  199. def _period_has_moves(self, period):
  200. move_model = self.env['account.move']
  201. return bool(move_model.search([('period_id', '=', period.id)],
  202. limit=1))
  203. def _get_previous_opening_period(self, period, company_id):
  204. period_model = self.env['account.period']
  205. periods = period_model.search(
  206. [('date_start', '<=', period.date_start),
  207. ('special', '=', True),
  208. ('company_id', '=', company_id)],
  209. order="date_start desc",
  210. limit=1)
  211. return periods and periods[0]
  212. def _get_previous_normal_period(self, period, company_id):
  213. period_model = self.env['account.period']
  214. periods = period_model.search(
  215. [('date_start', '<', period.date_start),
  216. ('special', '=', False),
  217. ('company_id', '=', company_id)],
  218. order="date_start desc",
  219. limit=1)
  220. return periods and periods[0]
  221. def _get_first_normal_period(self, company_id):
  222. period_model = self.env['account.period']
  223. periods = period_model.search(
  224. [('special', '=', False),
  225. ('company_id', '=', company_id)],
  226. order="date_start asc",
  227. limit=1)
  228. return periods and periods[0]
  229. def _get_period_ids_between(self, period_from, period_to, company_id):
  230. period_model = self.env['account.period']
  231. periods = period_model.search(
  232. [('date_start', '>=', period_from.date_start),
  233. ('date_stop', '<=', period_to.date_stop),
  234. ('special', '=', False),
  235. ('company_id', '=', company_id)])
  236. period_ids = [p.id for p in periods]
  237. if period_from.special:
  238. period_ids.append(period_from.id)
  239. return period_ids
  240. def _get_period_company_ids(self, period_from, period_to):
  241. period_model = self.env['account.period']
  242. periods = period_model.search(
  243. [('date_start', '>=', period_from.date_start),
  244. ('date_stop', '<=', period_to.date_stop),
  245. ('special', '=', False)])
  246. return set([p.company_id.id for p in periods])
  247. def _get_period_ids_for_mode(self, period_from, period_to, mode):
  248. assert not period_from.special
  249. assert not period_to.special
  250. assert period_from.company_id == period_to.company_id
  251. assert period_from.date_start <= period_to.date_start
  252. period_ids = []
  253. for company_id in self._get_period_company_ids(period_from, period_to):
  254. if mode == MODE_VARIATION:
  255. period_ids.extend(self._get_period_ids_between(
  256. period_from, period_to, company_id))
  257. else:
  258. if mode == MODE_INITIAL:
  259. period_to = self._get_previous_normal_period(
  260. period_from, company_id)
  261. # look for opening period with moves
  262. opening_period = self._get_previous_opening_period(
  263. period_from, company_id)
  264. if opening_period and \
  265. self._period_has_moves(opening_period[0]):
  266. # found opening period with moves
  267. if opening_period.date_start == period_from.date_start and\
  268. mode == MODE_INITIAL:
  269. # if the opening period has the same start date as
  270. # period_from, then we'll find the initial balance
  271. # in the initial period and that's it
  272. period_ids.append(opening_period[0].id)
  273. continue
  274. period_from = opening_period[0]
  275. else:
  276. # no opening period with moves,
  277. # use very first normal period
  278. period_from = self._get_first_normal_period(company_id)
  279. if period_to:
  280. period_ids.extend(self._get_period_ids_between(
  281. period_from, period_to, company_id))
  282. return period_ids
  283. def get_aml_domain_for_dates(self, date_from, date_to,
  284. period_from, period_to,
  285. mode,
  286. target_move):
  287. if period_from and period_to:
  288. period_ids = self._get_period_ids_for_mode(
  289. period_from, period_to, mode)
  290. domain = [('period_id', 'in', period_ids)]
  291. else:
  292. if mode == MODE_VARIATION:
  293. domain = [('date', '>=', date_from), ('date', '<=', date_to)]
  294. else:
  295. raise Warning(_("Modes i and e are only applicable for "
  296. "fiscal periods"))
  297. if target_move == 'posted':
  298. domain.append(('move_id.state', '=', 'posted'))
  299. return expression.normalize_domain(domain)
  300. def do_queries(self, date_from, date_to, period_from, period_to,
  301. target_move):
  302. """Query sums of debit and credit for all accounts and domains
  303. used in expressions.
  304. This method must be executed after done_parsing().
  305. """
  306. aml_model = self.env['account.move.line']
  307. # {(domain, mode): {account_id: (debit, credit)}}
  308. self._data = defaultdict(dict)
  309. domain_by_mode = {}
  310. for key in self._map_account_ids:
  311. domain, mode = key
  312. if mode not in domain_by_mode:
  313. domain_by_mode[mode] = \
  314. self.get_aml_domain_for_dates(date_from, date_to,
  315. period_from, period_to,
  316. mode, target_move)
  317. domain = list(domain) + domain_by_mode[mode]
  318. domain.append(('account_id', 'in', self._map_account_ids[key]))
  319. # fetch sum of debit/credit, grouped by account_id
  320. accs = aml_model.read_group(domain,
  321. ['debit', 'credit', 'account_id'],
  322. ['account_id'])
  323. for acc in accs:
  324. self._data[key][acc['account_id'][0]] = \
  325. (acc['debit'] or 0.0, acc['credit'] or 0.0)
  326. def replace_expr(self, expr):
  327. """Replace accounting variables in an expression by their amount.
  328. Returns a new expression string.
  329. This method must be executed after do_queries().
  330. """
  331. def f(mo):
  332. field, mode, account_codes, domain = self._parse_match_object(mo)
  333. key = (domain, mode)
  334. account_ids_data = self._data[key]
  335. v = 0.0
  336. for account_code in account_codes:
  337. account_ids = self._account_ids_by_code[account_code]
  338. for account_id in account_ids:
  339. debit, credit = \
  340. account_ids_data.get(account_id, (0.0, 0.0))
  341. if field == 'bal':
  342. v += debit - credit
  343. elif field == 'deb':
  344. v += debit
  345. elif field == 'crd':
  346. v += credit
  347. return '(' + repr(v) + ')'
  348. return self.ACC_RE.sub(f, expr)