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.

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