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.

427 lines
17 KiB

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