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.

428 lines
17 KiB

5 years ago
  1. # Copyright 2018 Eficent Business and IT Consulting Services S.L.
  2. # (http://www.eficent.com)
  3. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  4. from datetime import datetime, timedelta
  5. from odoo.tools.misc import DEFAULT_SERVER_DATE_FORMAT
  6. from odoo import api, fields, models, _
  7. class ReportStatementCommon(models.AbstractModel):
  8. """Abstract Report Statement for use in other models"""
  9. _name = 'statement.common'
  10. _description = 'Statement Reports Common'
  11. def _get_invoice_address(self, part):
  12. inv_addr_id = part.address_get(['invoice']).get('invoice', part.id)
  13. return self.env["res.partner"].browse(inv_addr_id)
  14. def _format_date_to_partner_lang(
  15. self,
  16. date,
  17. date_format=DEFAULT_SERVER_DATE_FORMAT
  18. ):
  19. if isinstance(date, str):
  20. date = datetime.strptime(date, DEFAULT_SERVER_DATE_FORMAT)
  21. return date.strftime(date_format) if date else ''
  22. def _get_account_display_lines(self, company_id, partner_ids, date_start,
  23. date_end, account_type):
  24. raise NotImplementedError
  25. def _get_account_initial_balance(self, company_id, partner_ids,
  26. date_start, account_type):
  27. return {}
  28. def _show_buckets_sql_q1(self, partners, date_end, account_type):
  29. return str(self._cr.mogrify("""
  30. SELECT l.partner_id, l.currency_id, l.company_id, l.move_id,
  31. CASE WHEN l.balance > 0.0
  32. THEN l.balance - sum(coalesce(pd.amount, 0.0))
  33. ELSE l.balance + sum(coalesce(pc.amount, 0.0))
  34. END AS open_due,
  35. CASE WHEN l.balance > 0.0
  36. THEN l.amount_currency - sum(coalesce(pd.amount_currency, 0.0))
  37. ELSE l.amount_currency + sum(coalesce(pc.amount_currency, 0.0))
  38. END AS open_due_currency,
  39. CASE WHEN l.date_maturity is null
  40. THEN l.date
  41. ELSE l.date_maturity
  42. END as date_maturity
  43. FROM account_move_line l
  44. JOIN account_account_type at ON (at.id = l.user_type_id)
  45. JOIN account_move m ON (l.move_id = m.id)
  46. LEFT JOIN (SELECT pr.*
  47. FROM account_partial_reconcile pr
  48. INNER JOIN account_move_line l2
  49. ON pr.credit_move_id = l2.id
  50. WHERE l2.date <= %(date_end)s
  51. ) as pd ON pd.debit_move_id = l.id
  52. LEFT JOIN (SELECT pr.*
  53. FROM account_partial_reconcile pr
  54. INNER JOIN account_move_line l2
  55. ON pr.debit_move_id = l2.id
  56. WHERE l2.date <= %(date_end)s
  57. ) as pc ON pc.credit_move_id = l.id
  58. WHERE l.partner_id IN %(partners)s AND at.type = %(account_type)s
  59. AND (
  60. (pd.id IS NOT NULL AND
  61. pd.max_date <= %(date_end)s) OR
  62. (pc.id IS NOT NULL AND
  63. pc.max_date <= %(date_end)s) OR
  64. (pd.id IS NULL AND pc.id IS NULL)
  65. ) AND l.date <= %(date_end)s AND not l.blocked
  66. AND m.state IN ('posted')
  67. GROUP BY l.partner_id, l.currency_id, l.date, l.date_maturity,
  68. l.amount_currency, l.balance, l.move_id,
  69. l.company_id, l.id
  70. """, locals()), "utf-8")
  71. def _show_buckets_sql_q2(self, date_end, minus_30, minus_60, minus_90,
  72. minus_120):
  73. return str(self._cr.mogrify("""
  74. SELECT partner_id, currency_id, date_maturity, open_due,
  75. open_due_currency, move_id, company_id,
  76. CASE
  77. WHEN %(date_end)s <= date_maturity AND currency_id is null
  78. THEN open_due
  79. WHEN %(date_end)s <= date_maturity AND currency_id is not null
  80. THEN open_due_currency
  81. ELSE 0.0
  82. END as current,
  83. CASE
  84. WHEN %(minus_30)s < date_maturity
  85. AND date_maturity < %(date_end)s
  86. AND currency_id is null
  87. THEN open_due
  88. WHEN %(minus_30)s < date_maturity
  89. AND date_maturity < %(date_end)s
  90. AND currency_id is not null
  91. THEN open_due_currency
  92. ELSE 0.0
  93. END as b_1_30,
  94. CASE
  95. WHEN %(minus_60)s < date_maturity
  96. AND date_maturity <= %(minus_30)s
  97. AND currency_id is null
  98. THEN open_due
  99. WHEN %(minus_60)s < date_maturity
  100. AND date_maturity <= %(minus_30)s
  101. AND currency_id is not null
  102. THEN open_due_currency
  103. ELSE 0.0
  104. END as b_30_60,
  105. CASE
  106. WHEN %(minus_90)s < date_maturity
  107. AND date_maturity <= %(minus_60)s
  108. AND currency_id is null
  109. THEN open_due
  110. WHEN %(minus_90)s < date_maturity
  111. AND date_maturity <= %(minus_60)s
  112. AND currency_id is not null
  113. THEN open_due_currency
  114. ELSE 0.0
  115. END as b_60_90,
  116. CASE
  117. WHEN %(minus_120)s < date_maturity
  118. AND date_maturity <= %(minus_90)s
  119. AND currency_id is null
  120. THEN open_due
  121. WHEN %(minus_120)s < date_maturity
  122. AND date_maturity <= %(minus_90)s
  123. AND currency_id is not null
  124. THEN open_due_currency
  125. ELSE 0.0
  126. END as b_90_120,
  127. CASE
  128. WHEN date_maturity <= %(minus_120)s
  129. AND currency_id is null
  130. THEN open_due
  131. WHEN date_maturity <= %(minus_120)s
  132. AND currency_id is not null
  133. THEN open_due_currency
  134. ELSE 0.0
  135. END as b_over_120
  136. FROM Q1
  137. GROUP BY partner_id, currency_id, date_maturity, open_due,
  138. open_due_currency, move_id, company_id
  139. """, locals()), "utf-8")
  140. def _show_buckets_sql_q3(self, company_id):
  141. return str(self._cr.mogrify("""
  142. SELECT Q2.partner_id, current, b_1_30, b_30_60, b_60_90, b_90_120,
  143. b_over_120,
  144. COALESCE(Q2.currency_id, c.currency_id) AS currency_id
  145. FROM Q2
  146. JOIN res_company c ON (c.id = Q2.company_id)
  147. WHERE c.id = %(company_id)s
  148. """, locals()), "utf-8")
  149. def _show_buckets_sql_q4(self):
  150. return """
  151. SELECT partner_id, currency_id, sum(current) as current,
  152. sum(b_1_30) as b_1_30,
  153. sum(b_30_60) as b_30_60,
  154. sum(b_60_90) as b_60_90,
  155. sum(b_90_120) as b_90_120,
  156. sum(b_over_120) as b_over_120
  157. FROM Q3
  158. GROUP BY partner_id, currency_id
  159. """
  160. def _get_bucket_dates(self, date_end, aging_type):
  161. return getattr(
  162. self, '_get_bucket_dates_%s' % aging_type,
  163. self._get_bucket_dates_days
  164. )(date_end)
  165. def _get_bucket_dates_days(self, date_end):
  166. return {
  167. 'date_end': date_end,
  168. 'minus_30': date_end - timedelta(days=30),
  169. 'minus_60': date_end - timedelta(days=60),
  170. 'minus_90': date_end - timedelta(days=90),
  171. 'minus_120': date_end - timedelta(days=120),
  172. }
  173. def _get_bucket_dates_months(self, date_end):
  174. res = {}
  175. d = date_end
  176. for k in (
  177. "date_end",
  178. "minus_30",
  179. "minus_60",
  180. "minus_90",
  181. "minus_120",
  182. ):
  183. res[k] = d
  184. d = d.replace(day=1) - timedelta(days=1)
  185. return res
  186. def _get_account_show_buckets(self, company_id, partner_ids, date_end,
  187. account_type, aging_type):
  188. buckets = dict(map(lambda x: (x, []), partner_ids))
  189. partners = tuple(partner_ids)
  190. full_dates = self._get_bucket_dates(date_end, aging_type)
  191. # pylint: disable=E8103
  192. # All input queries are properly escaped - false positive
  193. self.env.cr.execute("""
  194. WITH Q1 AS (%s),
  195. Q2 AS (%s),
  196. Q3 AS (%s),
  197. Q4 AS (%s)
  198. SELECT partner_id, currency_id, current, b_1_30, b_30_60, b_60_90,
  199. b_90_120, b_over_120,
  200. current+b_1_30+b_30_60+b_60_90+b_90_120+b_over_120
  201. AS balance
  202. FROM Q4
  203. GROUP BY partner_id, currency_id, current, b_1_30, b_30_60,
  204. b_60_90, b_90_120, b_over_120""" % (
  205. self._show_buckets_sql_q1(partners, date_end, account_type),
  206. self._show_buckets_sql_q2(
  207. full_dates['date_end'],
  208. full_dates['minus_30'],
  209. full_dates['minus_60'],
  210. full_dates['minus_90'],
  211. full_dates['minus_120']),
  212. self._show_buckets_sql_q3(company_id),
  213. self._show_buckets_sql_q4()))
  214. for row in self.env.cr.dictfetchall():
  215. buckets[row.pop('partner_id')].append(row)
  216. return buckets
  217. def _get_bucket_labels(self, date_end, aging_type):
  218. return getattr(
  219. self, '_get_bucket_labels_%s' % aging_type,
  220. self._get_bucket_dates_days
  221. )(date_end)
  222. def _get_bucket_labels_days(self, date_end):
  223. return [
  224. _('Current'),
  225. _('1 - 30 Days'),
  226. _('31 - 60 Days'),
  227. _('61 - 90 Days'),
  228. _('91 - 120 Days'),
  229. _('121 Days +'),
  230. _('Total'),
  231. ]
  232. def _get_bucket_labels_months(self, date_end):
  233. return [
  234. _('Current'),
  235. _('1 Month'),
  236. _('2 Months'),
  237. _('3 Months'),
  238. _('4 Months'),
  239. _('Older'),
  240. _('Total'),
  241. ]
  242. def _get_line_currency_defaults(self, currency_id, currencies,
  243. balance_forward):
  244. if currency_id not in currencies:
  245. # This will only happen if currency is inactive
  246. currencies[currency_id] = (
  247. self.env['res.currency'].browse(currency_id)
  248. )
  249. return (
  250. {
  251. 'lines': [],
  252. 'buckets': [],
  253. 'balance_forward': balance_forward,
  254. 'amount_due': balance_forward,
  255. },
  256. currencies
  257. )
  258. @api.multi
  259. def _get_report_values(self, docids, data):
  260. """
  261. @return: returns a dict of parameters to pass to qweb report.
  262. the most important pair is {'data': res} which contains all
  263. the data for each partner. It is structured like:
  264. {partner_id: {
  265. 'start': date string,
  266. 'end': date_string,
  267. 'today': date_string
  268. 'currencies': {
  269. currency_id: {
  270. 'lines': [{'date': date string, ...}, ...],
  271. 'balance_forward': float,
  272. 'amount_due': float,
  273. 'buckets': {
  274. 'p1': float, 'p2': ...
  275. }
  276. }
  277. }
  278. }
  279. """
  280. company_id = data['company_id']
  281. partner_ids = data['partner_ids']
  282. date_start = data.get('date_start')
  283. if date_start and isinstance(date_start, str):
  284. date_start = datetime.strptime(
  285. date_start, DEFAULT_SERVER_DATE_FORMAT
  286. ).date()
  287. date_end = data['date_end']
  288. if isinstance(date_end, str):
  289. date_end = datetime.strptime(
  290. date_end, DEFAULT_SERVER_DATE_FORMAT
  291. ).date()
  292. account_type = data['account_type']
  293. aging_type = data['aging_type']
  294. today = fields.Date.today()
  295. amount_field = data.get('amount_field', 'amount')
  296. # There should be relatively few of these, so to speed performance
  297. # we cache them - default needed if partner lang not set
  298. self._cr.execute("""
  299. SELECT p.id, l.date_format
  300. FROM res_partner p LEFT JOIN res_lang l ON p.lang=l.code
  301. WHERE p.id IN %(partner_ids)s
  302. """, {"partner_ids": tuple(partner_ids)})
  303. date_formats = {r[0]: r[1] for r in self._cr.fetchall()}
  304. default_fmt = self.env["res.lang"]._lang_get(
  305. self.env.user.lang).date_format
  306. currencies = {x.id: x for x in self.env['res.currency'].search([])}
  307. res = {}
  308. # get base data
  309. lines = self._get_account_display_lines(
  310. company_id, partner_ids, date_start, date_end, account_type)
  311. balances_forward = self._get_account_initial_balance(
  312. company_id, partner_ids, date_start, account_type)
  313. if data['show_aging_buckets']:
  314. buckets = self._get_account_show_buckets(
  315. company_id, partner_ids, date_end, account_type, aging_type)
  316. bucket_labels = self._get_bucket_labels(date_end, aging_type)
  317. else:
  318. bucket_labels = {}
  319. # organise and format for report
  320. format_date = self._format_date_to_partner_lang
  321. partners_to_remove = set()
  322. for partner_id in partner_ids:
  323. res[partner_id] = {
  324. 'today': format_date(
  325. today,
  326. date_formats.get(partner_id, default_fmt)
  327. ),
  328. 'start': format_date(
  329. date_start,
  330. date_formats.get(partner_id, default_fmt)
  331. ),
  332. 'end': format_date(
  333. date_end,
  334. date_formats.get(partner_id, default_fmt)
  335. ),
  336. 'currencies': {},
  337. }
  338. currency_dict = res[partner_id]['currencies']
  339. for line in balances_forward.get(partner_id, []):
  340. currency_dict[line['currency_id']], currencies = (
  341. self._get_line_currency_defaults(
  342. line['currency_id'], currencies, line['balance'])
  343. )
  344. for line in lines[partner_id]:
  345. if line['currency_id'] not in currency_dict:
  346. currency_dict[line['currency_id']], currencies = (
  347. self._get_line_currency_defaults(
  348. line['currency_id'], currencies, 0.0)
  349. )
  350. line_currency = currency_dict[line['currency_id']]
  351. if not line['blocked']:
  352. line_currency['amount_due'] += line[amount_field]
  353. line['balance'] = line_currency['amount_due']
  354. line['date'] = format_date(
  355. line['date'], date_formats.get(partner_id, default_fmt)
  356. )
  357. line['date_maturity'] = format_date(
  358. line['date_maturity'],
  359. date_formats.get(partner_id, default_fmt)
  360. )
  361. line_currency['lines'].append(line)
  362. if data['show_aging_buckets']:
  363. for line in buckets[partner_id]:
  364. if line['currency_id'] not in currency_dict:
  365. currency_dict[line['currency_id']], currencies = (
  366. self._get_line_currency_defaults(
  367. line['currency_id'], currencies, 0.0)
  368. )
  369. line_currency = currency_dict[line['currency_id']]
  370. line_currency['buckets'] = line
  371. if len(partner_ids) > 1:
  372. values = currency_dict.values()
  373. if not any(
  374. [v['lines'] or v['balance_forward'] for v in values]
  375. ):
  376. if data["filter_non_due_partners"]:
  377. partners_to_remove.add(partner_id)
  378. continue
  379. else:
  380. res[partner_id]['no_entries'] = True
  381. if data["filter_negative_balances"]:
  382. if not all([v['amount_due'] >= 0.0 for v in values]):
  383. partners_to_remove.add(partner_id)
  384. for partner in partners_to_remove:
  385. del res[partner]
  386. partner_ids.remove(partner)
  387. return {
  388. 'doc_ids': partner_ids,
  389. 'doc_model': 'res.partner',
  390. 'docs': self.env['res.partner'].browse(partner_ids),
  391. 'data': res,
  392. 'company': self.env['res.company'].browse(company_id),
  393. 'Currencies': currencies,
  394. 'account_type': account_type,
  395. 'bucket_labels': bucket_labels,
  396. 'get_inv_addr': self._get_invoice_address,
  397. }