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.

366 lines
16 KiB

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