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.

259 lines
11 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 import fields
  7. from openerp.models import expression
  8. from openerp.tools.safe_eval import safe_eval
  9. from .accounting_none import AccountingNone
  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. # {account_code: account_id} where account_code can be
  60. # - None for all accounts
  61. # - NNN% for a like
  62. # - NNN for a code with an exact match
  63. self._account_ids_by_code = defaultdict(set)
  64. def _load_account_codes(self, account_codes, company):
  65. account_model = self.env['account.account']
  66. exact_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. # None means we want all accounts
  72. account_ids = account_model.\
  73. search([]).ids
  74. self._account_ids_by_code[account_code].update(account_ids)
  75. elif '%' in account_code:
  76. account_ids = account_model.\
  77. search([('code', 'like', account_code),
  78. ('company_id', '=', company.id)]).ids
  79. self._account_ids_by_code[account_code].update(account_ids)
  80. else:
  81. # search exact codes after the loop to do less queries
  82. exact_codes.add(account_code)
  83. for account in account_model.\
  84. search([('code', 'in', list(exact_codes)),
  85. ('company_id', '=', company.id)]):
  86. self._account_ids_by_code[account.code].add(account.id)
  87. def _parse_match_object(self, mo):
  88. """Split a match object corresponding to an accounting variable
  89. Returns field, mode, [account codes], (domain expression).
  90. """
  91. field, mode, account_codes, domain = mo.groups()
  92. if not mode:
  93. mode = MODE_VARIATION
  94. elif mode == 's':
  95. mode = MODE_END
  96. if account_codes.startswith('_'):
  97. account_codes = account_codes[1:]
  98. else:
  99. account_codes = account_codes[1:-1]
  100. if account_codes.strip():
  101. account_codes = [a.strip() for a in account_codes.split(',')]
  102. else:
  103. account_codes = [None] # None means we want all accounts
  104. domain = domain or '[]'
  105. domain = tuple(safe_eval(domain))
  106. return field, mode, account_codes, domain
  107. def parse_expr(self, expr):
  108. """Parse an expression, extracting accounting variables.
  109. Domains and accounts are extracted and stored in the map
  110. so when all expressions have been parsed, we know which
  111. account codes to query for each domain and mode.
  112. """
  113. for mo in self.ACC_RE.finditer(expr):
  114. _, mode, account_codes, domain = self._parse_match_object(mo)
  115. key = (domain, mode)
  116. self._map_account_ids[key].update(account_codes)
  117. def done_parsing(self, company):
  118. """Load account codes and replace account codes by
  119. account ids in map."""
  120. for key, account_codes in self._map_account_ids.items():
  121. # TODO _load_account_codes could be done
  122. # for all account_codes at once (also in v8)
  123. self._load_account_codes(account_codes, company)
  124. account_ids = set()
  125. for account_code in account_codes:
  126. account_ids.update(self._account_ids_by_code[account_code])
  127. self._map_account_ids[key] = list(account_ids)
  128. @classmethod
  129. def has_account_var(cls, expr):
  130. """Test if an string contains an accounting variable."""
  131. return bool(cls.ACC_RE.search(expr))
  132. def get_aml_domain_for_expr(self, expr,
  133. date_from, date_to,
  134. target_move, company):
  135. """ Get a domain on account.move.line for an expression.
  136. Prerequisite: done_parsing() must have been invoked.
  137. Returns a domain that can be used to search on account.move.line.
  138. """
  139. aml_domains = []
  140. date_domain_by_mode = {}
  141. for mo in self.ACC_RE.finditer(expr):
  142. field, mode, account_codes, domain = self._parse_match_object(mo)
  143. aml_domain = list(domain)
  144. account_ids = set()
  145. for account_code in account_codes:
  146. account_ids.update(self._account_ids_by_code[account_code])
  147. aml_domain.append(('account_id', 'in', tuple(account_ids)))
  148. if field == 'crd':
  149. aml_domain.append(('credit', '>', 0))
  150. elif field == 'deb':
  151. aml_domain.append(('debit', '>', 0))
  152. aml_domains.append(expression.normalize_domain(aml_domain))
  153. if mode not in date_domain_by_mode:
  154. date_domain_by_mode[mode] = \
  155. self.get_aml_domain_for_dates(date_from, date_to,
  156. mode, target_move,
  157. company)
  158. return expression.OR(aml_domains) + \
  159. expression.OR(date_domain_by_mode.values())
  160. def get_aml_domain_for_dates(self, date_from, date_to,
  161. mode,
  162. target_move, company):
  163. if mode == MODE_VARIATION:
  164. domain = [('date', '>=', date_from), ('date', '<=', date_to)]
  165. else:
  166. # for income and expense account, get balance from the beginning
  167. # of the current fiscal year
  168. date_from_date = fields.Date.from_string(date_from)
  169. fy_date_from = \
  170. company.compute_fiscalyear_dates(date_from_date)['date_from']
  171. domain = ['|',
  172. ('date', '>=', fy_date_from),
  173. ('account_id.user_type_id.include_initial_balance', '=',
  174. True)]
  175. if mode == MODE_INITIAL:
  176. domain.append(('date', '<', date_from))
  177. elif mode == MODE_END:
  178. domain.append(('date', '<=', date_to))
  179. if target_move == 'posted':
  180. domain.append(('move_id.state', '=', 'posted'))
  181. return expression.normalize_domain(domain)
  182. def do_queries(self, date_from, date_to,
  183. target_move, company, additional_move_line_filter=None):
  184. """Query sums of debit and credit for all accounts and domains
  185. used in expressions.
  186. This method must be executed after done_parsing().
  187. """
  188. aml_model = self.env['account.move.line']
  189. # {(domain, mode): {account_id: (debit, credit)}}
  190. self._data = defaultdict(dict)
  191. domain_by_mode = {}
  192. for key in self._map_account_ids:
  193. domain, mode = key
  194. if mode not in domain_by_mode:
  195. domain_by_mode[mode] = \
  196. self.get_aml_domain_for_dates(date_from, date_to,
  197. mode, target_move, company)
  198. domain = list(domain) + domain_by_mode[mode]
  199. domain.append(('account_id', 'in', self._map_account_ids[key]))
  200. if additional_move_line_filter:
  201. domain.extend(additional_move_line_filter)
  202. # fetch sum of debit/credit, grouped by account_id
  203. accs = aml_model.read_group(domain,
  204. ['debit', 'credit', 'account_id'],
  205. ['account_id'])
  206. for acc in accs:
  207. self._data[key][acc['account_id'][0]] = \
  208. (acc['debit'] or 0.0, acc['credit'] or 0.0)
  209. def replace_expr(self, expr):
  210. """Replace accounting variables in an expression by their amount.
  211. Returns a new expression string.
  212. This method must be executed after do_queries().
  213. """
  214. def f(mo):
  215. field, mode, account_codes, domain = self._parse_match_object(mo)
  216. key = (domain, mode)
  217. account_ids_data = self._data[key]
  218. v = AccountingNone
  219. for account_code in account_codes:
  220. account_ids = self._account_ids_by_code[account_code]
  221. for account_id in account_ids:
  222. debit, credit = \
  223. account_ids_data.get(account_id,
  224. (AccountingNone, AccountingNone))
  225. if field == 'bal':
  226. v += debit - credit
  227. elif field == 'deb':
  228. v += debit
  229. elif field == 'crd':
  230. v += credit
  231. return '(' + repr(v) + ')'
  232. return self.ACC_RE.sub(f, expr)