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.

352 lines
15 KiB

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