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.

364 lines
16 KiB

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