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.

439 lines
19 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 itertools import izip
  7. from openerp import fields
  8. from openerp.models import expression
  9. from openerp.tools.safe_eval import safe_eval
  10. from openerp.tools.float_utils import float_is_zero
  11. from .accounting_none import AccountingNone
  12. class AccountingExpressionProcessor(object):
  13. """ Processor for accounting expressions.
  14. Expressions of the form <field><mode>[accounts][optional move line domain]
  15. are supported, where:
  16. * field is bal, crd, deb
  17. * mode is i (initial balance), e (ending balance),
  18. p (moves over period)
  19. * there is also a special u mode (unallocated P&L) which computes
  20. the sum from the beginning until the beginning of the fiscal year
  21. of the period; it is only meaningful for P&L accounts
  22. * accounts is a list of accounts, possibly containing % wildcards
  23. * an optional domain on move lines allowing filters on eg analytic
  24. accounts or journal
  25. Examples:
  26. * bal[70]: variation of the balance of moves on account 70
  27. over the period (it is the same as balp[70]);
  28. * bali[70,60]: balance of accounts 70 and 60 at the start of period;
  29. * bale[1%]: balance of accounts starting with 1 at end of period.
  30. How to use:
  31. * repeatedly invoke parse_expr() for each expression containing
  32. accounting variables as described above; this lets the processor
  33. group domains and modes and accounts;
  34. * when all expressions have been parsed, invoke done_parsing()
  35. to notify the processor that it can prepare to query (mainly
  36. search all accounts - children, consolidation - that will need to
  37. be queried;
  38. * for each period, call do_queries(), then call replace_expr() for each
  39. expression to replace accounting variables with their resulting value
  40. for the given period.
  41. How it works:
  42. * by accumulating the expressions before hand, it ensures to do the
  43. strict minimum number of queries to the database (for each period,
  44. one query per domain and mode);
  45. * it queries using the orm read_group which reduces to a query with
  46. sum on debit and credit and group by on account_id (note: it seems
  47. the orm then does one query per account to fetch the account
  48. name...);
  49. * additionally, one query per view/consolidation account is done to
  50. discover the children accounts.
  51. """
  52. MODE_VARIATION = 'p'
  53. MODE_INITIAL = 'i'
  54. MODE_END = 'e'
  55. MODE_UNALLOCATED = 'u'
  56. _ACC_RE = re.compile(r"(?P<field>\bbal|\bcrd|\bdeb)"
  57. r"(?P<mode>[piseu])?"
  58. r"(?P<accounts>_[a-zA-Z0-9]+|\[.*?\])"
  59. r"(?P<domain>\[.*?\])?")
  60. def __init__(self, env):
  61. self.env = env
  62. # before done_parsing: {(domain, mode): set(account_codes)}
  63. # after done_parsing: {(domain, mode): list(account_ids)}
  64. self._map_account_ids = defaultdict(set)
  65. # {account_code: account_id} where account_code can be
  66. # - None for all accounts
  67. # - NNN% for a like
  68. # - NNN for a code with an exact match
  69. self._account_ids_by_code = defaultdict(set)
  70. # smart ending balance (returns AccountingNone if there
  71. # are no moves in period and 0 initial balance), implies
  72. # a first query to get the initial balance and another
  73. # to get the variation, so it's a bit slower
  74. self.smart_end = True
  75. def _load_account_codes(self, account_codes, company):
  76. account_model = self.env['account.account']
  77. exact_codes = set()
  78. for account_code in account_codes:
  79. if account_code in self._account_ids_by_code:
  80. continue
  81. if account_code is None:
  82. # None means we want all accounts
  83. account_ids = account_model.\
  84. search([('company_id', '=', company.id)]).ids
  85. self._account_ids_by_code[account_code].update(account_ids)
  86. elif '%' in account_code:
  87. account_ids = account_model.\
  88. search([('code', '=like', account_code),
  89. ('company_id', '=', company.id)]).ids
  90. self._account_ids_by_code[account_code].update(account_ids)
  91. else:
  92. # search exact codes after the loop to do less queries
  93. exact_codes.add(account_code)
  94. for account in account_model.\
  95. search([('code', 'in', list(exact_codes)),
  96. ('company_id', '=', company.id)]):
  97. self._account_ids_by_code[account.code].add(account.id)
  98. def _parse_match_object(self, mo):
  99. """Split a match object corresponding to an accounting variable
  100. Returns field, mode, [account codes], (domain expression).
  101. """
  102. field, mode, account_codes, domain = mo.groups()
  103. if not mode:
  104. mode = self.MODE_VARIATION
  105. elif mode == 's':
  106. mode = self.MODE_END
  107. if account_codes.startswith('_'):
  108. account_codes = account_codes[1:]
  109. else:
  110. account_codes = account_codes[1:-1]
  111. if account_codes.strip():
  112. account_codes = [a.strip() for a in account_codes.split(',')]
  113. else:
  114. account_codes = [None] # None means we want all accounts
  115. domain = domain or '[]'
  116. domain = tuple(safe_eval(domain))
  117. return field, mode, account_codes, domain
  118. def parse_expr(self, expr):
  119. """Parse an expression, extracting accounting variables.
  120. Domains and accounts are extracted and stored in the map
  121. so when all expressions have been parsed, we know which
  122. account codes to query for each domain and mode.
  123. """
  124. for mo in self._ACC_RE.finditer(expr):
  125. _, mode, account_codes, domain = self._parse_match_object(mo)
  126. if mode == self.MODE_END and self.smart_end:
  127. modes = (self.MODE_INITIAL, self.MODE_VARIATION, self.MODE_END)
  128. else:
  129. modes = (mode, )
  130. for mode in modes:
  131. key = (domain, mode)
  132. self._map_account_ids[key].update(account_codes)
  133. def done_parsing(self, company):
  134. """Load account codes and replace account codes by
  135. account ids in map."""
  136. for key, account_codes in self._map_account_ids.items():
  137. # TODO _load_account_codes could be done
  138. # for all account_codes at once (also in v8)
  139. self._load_account_codes(account_codes, company)
  140. account_ids = set()
  141. for account_code in account_codes:
  142. account_ids.update(self._account_ids_by_code[account_code])
  143. self._map_account_ids[key] = list(account_ids)
  144. @classmethod
  145. def has_account_var(cls, expr):
  146. """Test if an string contains an accounting variable."""
  147. return bool(cls._ACC_RE.search(expr))
  148. def get_aml_domain_for_expr(self, expr,
  149. date_from, date_to,
  150. target_move, company,
  151. account_id=None):
  152. """ Get a domain on account.move.line for an expression.
  153. Prerequisite: done_parsing() must have been invoked.
  154. Returns a domain that can be used to search on account.move.line.
  155. """
  156. aml_domains = []
  157. date_domain_by_mode = {}
  158. for mo in self._ACC_RE.finditer(expr):
  159. field, mode, account_codes, domain = self._parse_match_object(mo)
  160. aml_domain = list(domain)
  161. account_ids = set()
  162. for account_code in account_codes:
  163. account_ids.update(self._account_ids_by_code[account_code])
  164. if not account_id:
  165. aml_domain.append(('account_id', 'in', tuple(account_ids)))
  166. else:
  167. # filter on account_id
  168. if account_id in account_ids:
  169. aml_domain.append(('account_id', '=', account_id))
  170. else:
  171. continue
  172. if field == 'crd':
  173. aml_domain.append(('credit', '>', 0))
  174. elif field == 'deb':
  175. aml_domain.append(('debit', '>', 0))
  176. aml_domains.append(expression.normalize_domain(aml_domain))
  177. if mode not in date_domain_by_mode:
  178. date_domain_by_mode[mode] = \
  179. self.get_aml_domain_for_dates(date_from, date_to,
  180. mode, target_move,
  181. company)
  182. assert aml_domains
  183. return expression.OR(aml_domains) + \
  184. expression.OR(date_domain_by_mode.values())
  185. def get_aml_domain_for_dates(self, date_from, date_to,
  186. mode,
  187. target_move, company):
  188. if mode == self.MODE_VARIATION:
  189. domain = [('date', '>=', date_from), ('date', '<=', date_to)]
  190. elif mode in (self.MODE_INITIAL, self.MODE_END):
  191. # for income and expense account, sum from the beginning
  192. # of the current fiscal year only, for balance sheet accounts
  193. # sum from the beginning of time
  194. date_from_date = fields.Date.from_string(date_from)
  195. fy_date_from = \
  196. company.compute_fiscalyear_dates(date_from_date)['date_from']
  197. domain = ['|',
  198. ('date', '>=', fields.Date.to_string(fy_date_from)),
  199. ('user_type_id.include_initial_balance', '=', True)]
  200. if mode == self.MODE_INITIAL:
  201. domain.append(('date', '<', date_from))
  202. elif mode == self.MODE_END:
  203. domain.append(('date', '<=', date_to))
  204. elif mode == self.MODE_UNALLOCATED:
  205. date_from_date = fields.Date.from_string(date_from)
  206. fy_date_from = \
  207. company.compute_fiscalyear_dates(date_from_date)['date_from']
  208. domain = [('date', '<', fields.Date.to_string(fy_date_from)),
  209. ('user_type_id.include_initial_balance', '=', False)]
  210. if target_move == 'posted':
  211. domain.append(('move_id.state', '=', 'posted'))
  212. return expression.normalize_domain(domain)
  213. def do_queries(self, company, date_from, date_to,
  214. target_move='posted', additional_move_line_filter=None):
  215. """Query sums of debit and credit for all accounts and domains
  216. used in expressions.
  217. This method must be executed after done_parsing().
  218. """
  219. aml_model = self.env['account.move.line']
  220. # {(domain, mode): {account_id: (debit, credit)}}
  221. self._data = defaultdict(dict)
  222. domain_by_mode = {}
  223. ends = []
  224. for key in self._map_account_ids:
  225. domain, mode = key
  226. if mode == self.MODE_END and self.smart_end:
  227. # postpone computation of ending balance
  228. ends.append((domain, mode))
  229. continue
  230. if mode not in domain_by_mode:
  231. domain_by_mode[mode] = \
  232. self.get_aml_domain_for_dates(date_from, date_to,
  233. mode, target_move, company)
  234. domain = list(domain) + domain_by_mode[mode]
  235. domain.append(('account_id', 'in', self._map_account_ids[key]))
  236. if additional_move_line_filter:
  237. domain.extend(additional_move_line_filter)
  238. # fetch sum of debit/credit, grouped by account_id
  239. accs = aml_model.read_group(domain,
  240. ['debit', 'credit', 'account_id'],
  241. ['account_id'])
  242. for acc in accs:
  243. debit = acc['debit'] or 0.0
  244. credit = acc['credit'] or 0.0
  245. if mode in (self.MODE_INITIAL, self.MODE_UNALLOCATED) and \
  246. float_is_zero(debit-credit, precision_rounding=2):
  247. # in initial mode, ignore accounts with 0 balance
  248. continue
  249. self._data[key][acc['account_id'][0]] = (debit, credit)
  250. # compute ending balances by summing initial and variation
  251. for key in ends:
  252. domain, mode = key
  253. initial_data = self._data[(domain, self.MODE_INITIAL)]
  254. variation_data = self._data[(domain, self.MODE_VARIATION)]
  255. account_ids = set(initial_data.keys()) | set(variation_data.keys())
  256. for account_id in account_ids:
  257. di, ci = initial_data.get(account_id,
  258. (AccountingNone, AccountingNone))
  259. dv, cv = variation_data.get(account_id,
  260. (AccountingNone, AccountingNone))
  261. self._data[key][account_id] = (di + dv, ci + cv)
  262. def replace_expr(self, expr):
  263. """Replace accounting variables in an expression by their amount.
  264. Returns a new expression string.
  265. This method must be executed after do_queries().
  266. """
  267. def f(mo):
  268. field, mode, account_codes, domain = self._parse_match_object(mo)
  269. key = (domain, mode)
  270. account_ids_data = self._data[key]
  271. v = AccountingNone
  272. for account_code in account_codes:
  273. account_ids = self._account_ids_by_code[account_code]
  274. for account_id in account_ids:
  275. debit, credit = \
  276. account_ids_data.get(account_id,
  277. (AccountingNone, AccountingNone))
  278. if field == 'bal':
  279. v += debit - credit
  280. elif field == 'deb':
  281. v += debit
  282. elif field == 'crd':
  283. v += credit
  284. # in initial balance mode, assume 0 is None
  285. # as it does not make sense to distinguish 0 from "no data"
  286. if v is not AccountingNone and \
  287. mode in (self.MODE_INITIAL, self.MODE_UNALLOCATED) and \
  288. float_is_zero(v, precision_rounding=2):
  289. v = AccountingNone
  290. return '(' + repr(v) + ')'
  291. return self._ACC_RE.sub(f, expr)
  292. def replace_exprs_by_account_id(self, exprs):
  293. """Replace accounting variables in a list of expression
  294. by their amount, iterating by accounts involved in the expression.
  295. yields account_id, replaced_expr
  296. This method must be executed after do_queries().
  297. """
  298. def f(mo):
  299. field, mode, account_codes, domain = self._parse_match_object(mo)
  300. key = (domain, mode)
  301. account_ids_data = self._data[key]
  302. debit, credit = \
  303. account_ids_data.get(account_id,
  304. (AccountingNone, AccountingNone))
  305. if field == 'bal':
  306. v = debit - credit
  307. elif field == 'deb':
  308. v = debit
  309. elif field == 'crd':
  310. v = credit
  311. # in initial balance mode, assume 0 is None
  312. # as it does not make sense to distinguish 0 from "no data"
  313. if v is not AccountingNone and \
  314. mode in (self.MODE_INITIAL, self.MODE_UNALLOCATED) and \
  315. float_is_zero(v, precision_rounding=2):
  316. v = AccountingNone
  317. return '(' + repr(v) + ')'
  318. account_ids = set()
  319. for expr in exprs:
  320. for mo in self._ACC_RE.finditer(expr):
  321. field, mode, account_codes, domain = \
  322. self._parse_match_object(mo)
  323. key = (domain, mode)
  324. account_ids_data = self._data[key]
  325. for account_code in account_codes:
  326. for account_id in self._account_ids_by_code[account_code]:
  327. if account_id in account_ids_data:
  328. account_ids.add(account_id)
  329. for account_id in account_ids:
  330. yield account_id, [self._ACC_RE.sub(f, expr) for expr in exprs]
  331. @classmethod
  332. def _get_balances(cls, mode, company, date_from, date_to,
  333. target_move='posted'):
  334. expr = 'deb{mode}[], crd{mode}[]'.format(mode=mode)
  335. aep = AccountingExpressionProcessor(company.env)
  336. # disable smart_end to have the data at once, instead
  337. # of initial + variation
  338. aep.smart_end = False
  339. aep.parse_expr(expr)
  340. aep.done_parsing(company)
  341. aep.do_queries(company, date_from, date_to, target_move)
  342. return aep._data[((), mode)]
  343. @classmethod
  344. def get_balances_initial(cls, company, date, target_move='posted'):
  345. """ A convenience method to obtain the initial balances of all accounts
  346. at a given date.
  347. It is the same as get_balances_end(date-1).
  348. :param company:
  349. :param date:
  350. :param target_move: if 'posted', consider only posted moves
  351. Returns a dictionary: {account_id, (debit, credit)}
  352. """
  353. return cls._get_balances(cls.MODE_INITIAL, company,
  354. date, date, target_move)
  355. @classmethod
  356. def get_balances_end(cls, company, date, target_move='posted'):
  357. """ A convenience method to obtain the ending balances of all accounts
  358. at a given date.
  359. It is the same as get_balances_init(date+1).
  360. :param company:
  361. :param date:
  362. :param target_move: if 'posted', consider only posted moves
  363. Returns a dictionary: {account_id, (debit, credit)}
  364. """
  365. return cls._get_balances(cls.MODE_END, company,
  366. date, date, target_move)
  367. @classmethod
  368. def get_balances_variation(cls, company, date_from, date_to,
  369. target_move='posted'):
  370. """ A convenience method to obtain the variantion of the
  371. balances of all accounts over a period.
  372. :param company:
  373. :param date:
  374. :param target_move: if 'posted', consider only posted moves
  375. Returns a dictionary: {account_id, (debit, credit)}
  376. """
  377. return cls._get_balances(cls.MODE_VARIATION, company,
  378. date_from, date_to, target_move)
  379. @classmethod
  380. def get_unallocated_pl(cls, company, date, target_move='posted'):
  381. """ A convenience method to obtain the unallocated profit/loss
  382. of the previous fiscal years at a given date.
  383. :param company:
  384. :param date:
  385. :param target_move: if 'posted', consider only posted moves
  386. Returns a tuple (debit, credit)
  387. """
  388. # TODO shoud we include here the accounts of type "unaffected"
  389. # or leave that to the caller?
  390. bals = cls._get_balances(cls.MODE_UNALLOCATED, company,
  391. date, date, target_move)
  392. return tuple(map(sum, izip(*bals.values())))