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.

422 lines
19 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 Eficent Business and IT Consulting Services S.L.
  3. # (http://www.eficent.com)
  4. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  5. from datetime import datetime, timedelta
  6. from odoo.tools.misc import DEFAULT_SERVER_DATE_FORMAT
  7. from odoo import api, fields, models
  8. class CustomerActivityStatement(models.AbstractModel):
  9. """Model of Customer Activity Statement"""
  10. _name = 'report.customer_activity_statement.statement'
  11. def _format_date_to_partner_lang(self, str_date, partner_id):
  12. lang_code = self.env['res.partner'].browse(partner_id).lang
  13. lang = self.env['res.lang']._lang_get(lang_code)
  14. date = datetime.strptime(str_date, DEFAULT_SERVER_DATE_FORMAT).date()
  15. return date.strftime(lang.date_format)
  16. def _initial_balance_sql_q1(self, partners, date_start):
  17. return """
  18. SELECT l.partner_id, l.currency_id, l.company_id,
  19. CASE WHEN l.currency_id is not null AND l.amount_currency > 0.0
  20. THEN sum(l.amount_currency)
  21. ELSE sum(l.debit)
  22. END as debit,
  23. CASE WHEN l.currency_id is not null AND l.amount_currency < 0.0
  24. THEN sum(l.amount_currency * (-1))
  25. ELSE sum(l.credit)
  26. END as credit
  27. FROM account_move_line l
  28. JOIN account_account_type at ON (at.id = l.user_type_id)
  29. JOIN account_move m ON (l.move_id = m.id)
  30. WHERE l.partner_id IN (%s) AND at.type = 'receivable'
  31. AND l.date < '%s' AND not l.blocked
  32. GROUP BY l.partner_id, l.currency_id, l.amount_currency,
  33. l.company_id
  34. """ % (partners, date_start)
  35. def _initial_balance_sql_q2(self, company_id):
  36. return """
  37. SELECT Q1.partner_id, debit-credit AS balance,
  38. COALESCE(Q1.currency_id, c.currency_id) AS currency_id
  39. FROM Q1
  40. JOIN res_company c ON (c.id = Q1.company_id)
  41. WHERE c.id = %s
  42. """ % company_id
  43. def _get_account_initial_balance(self, company_id, partner_ids,
  44. date_start):
  45. res = dict(map(lambda x: (x, []), partner_ids))
  46. partners = ', '.join([str(i) for i in partner_ids])
  47. date_start = datetime.strptime(
  48. date_start, DEFAULT_SERVER_DATE_FORMAT).date()
  49. # pylint: disable=E8103
  50. self.env.cr.execute("""WITH Q1 AS (%s), Q2 AS (%s)
  51. SELECT partner_id, currency_id, balance
  52. FROM Q2""" % (self._initial_balance_sql_q1(partners, date_start),
  53. self._initial_balance_sql_q2(company_id)))
  54. for row in self.env.cr.dictfetchall():
  55. res[row.pop('partner_id')].append(row)
  56. return res
  57. def _display_lines_sql_q1(self, partners, date_start, date_end):
  58. return """
  59. SELECT m.name AS move_id, l.partner_id, l.date, l.name,
  60. l.ref, l.blocked, l.currency_id, l.company_id,
  61. CASE WHEN (l.currency_id is not null AND l.amount_currency > 0.0)
  62. THEN sum(l.amount_currency)
  63. ELSE sum(l.debit)
  64. END as debit,
  65. CASE WHEN (l.currency_id is not null AND l.amount_currency < 0.0)
  66. THEN sum(l.amount_currency * (-1))
  67. ELSE sum(l.credit)
  68. END as credit,
  69. CASE WHEN l.date_maturity is null
  70. THEN l.date
  71. ELSE l.date_maturity
  72. END as date_maturity
  73. FROM account_move_line l
  74. JOIN account_account_type at ON (at.id = l.user_type_id)
  75. JOIN account_move m ON (l.move_id = m.id)
  76. WHERE l.partner_id IN (%s) AND at.type = 'receivable'
  77. AND '%s' <= l.date AND l.date <= '%s'
  78. GROUP BY l.partner_id, m.name, l.date, l.date_maturity, l.name,
  79. l.ref, l.blocked, l.currency_id,
  80. l.amount_currency, l.company_id
  81. """ % (partners, date_start, date_end)
  82. def _display_lines_sql_q2(self, company_id):
  83. return """
  84. SELECT Q1.partner_id, move_id, date, date_maturity, Q1.name, ref,
  85. debit, credit, debit-credit as amount, blocked,
  86. COALESCE(Q1.currency_id, c.currency_id) AS currency_id
  87. FROM Q1
  88. JOIN res_company c ON (c.id = Q1.company_id)
  89. WHERE c.id = %s
  90. """ % company_id
  91. def _get_account_display_lines(self, company_id, partner_ids, date_start,
  92. date_end):
  93. res = dict(map(lambda x: (x, []), partner_ids))
  94. partners = ', '.join([str(i) for i in partner_ids])
  95. date_start = datetime.strptime(
  96. date_start, DEFAULT_SERVER_DATE_FORMAT).date()
  97. date_end = datetime.strptime(
  98. date_end, DEFAULT_SERVER_DATE_FORMAT).date()
  99. self.env.cr.execute("""WITH Q1 AS (%s), Q2 AS (%s)
  100. SELECT partner_id, move_id, date, date_maturity, name, ref, debit,
  101. credit, amount, blocked, currency_id
  102. FROM Q2
  103. ORDER BY date, date_maturity, move_id""" % (
  104. self._display_lines_sql_q1(partners, date_start, date_end),
  105. self._display_lines_sql_q2(company_id)))
  106. for row in self.env.cr.dictfetchall():
  107. res[row.pop('partner_id')].append(row)
  108. return res
  109. def _get_credit_date(self):
  110. return """
  111. SELECT apr.id, aml.date as credit_date
  112. FROM account_partial_reconcile apr
  113. LEFT JOIN account_move_line aml
  114. ON aml.id = apr.credit_move_id
  115. """
  116. def _get_debit_date(self):
  117. return """
  118. SELECT apr.id, aml.date as debit_date
  119. FROM account_partial_reconcile apr
  120. LEFT JOIN account_move_line aml
  121. ON aml.id = apr.debit_move_id
  122. """
  123. def _get_reconcile_date(self):
  124. return """
  125. SELECT pr2.id,
  126. CASE WHEN Q0a.credit_date > Q0b.debit_date
  127. THEN Q0a.credit_date
  128. ELSE Q0b.debit_date
  129. END AS max_date
  130. FROM account_partial_reconcile pr2
  131. LEFT JOIN (%s) as Q0a ON Q0a.id = pr2.id
  132. LEFT JOIN (%s) as Q0b ON Q0b.id = pr2.id
  133. GROUP BY pr2.id, Q0a.credit_date, Q0b.debit_date
  134. """ % (self._get_credit_date(), self._get_debit_date())
  135. def _show_buckets_sql_q0(self, date_end):
  136. return """
  137. SELECT l1.id,
  138. CASE WHEN l1.reconciled = TRUE and l1.balance > 0.0
  139. THEN max(pd.max_date)
  140. WHEN l1.reconciled = TRUE and l1.balance < 0.0
  141. THEN max(pc.max_date)
  142. ELSE null
  143. END as reconciled_date
  144. FROM account_move_line l1
  145. LEFT JOIN (SELECT pr.*, Q0c.max_date
  146. FROM account_partial_reconcile pr
  147. INNER JOIN account_move_line l2
  148. ON pr.credit_move_id = l2.id
  149. LEFT JOIN (%s) as Q0c ON Q0c.id = pr.id
  150. WHERE l2.date <= '%s'
  151. ) as pd ON pd.debit_move_id = l1.id
  152. LEFT JOIN (SELECT pr.*, Q0c.max_date
  153. FROM account_partial_reconcile pr
  154. INNER JOIN account_move_line l2
  155. ON pr.debit_move_id = l2.id
  156. LEFT JOIN (%s) as Q0c ON Q0c.id = pr.id
  157. WHERE l2.date <= '%s'
  158. ) as pc ON pc.credit_move_id = l1.id
  159. GROUP BY l1.id
  160. """ % (self._get_reconcile_date(), date_end,
  161. self._get_reconcile_date(), date_end)
  162. def _show_buckets_sql_q1(self, partners, date_end):
  163. return """
  164. SELECT l.partner_id, l.currency_id, l.company_id, l.move_id,
  165. CASE WHEN l.balance > 0.0
  166. THEN l.balance - sum(coalesce(pd.amount, 0.0))
  167. ELSE l.balance + sum(coalesce(pc.amount, 0.0))
  168. END AS open_due,
  169. CASE WHEN l.balance > 0.0
  170. THEN l.amount_currency - sum(coalesce(pd.amount_currency, 0.0))
  171. ELSE l.amount_currency + sum(coalesce(pc.amount_currency, 0.0))
  172. END AS open_due_currency,
  173. CASE WHEN l.date_maturity is null
  174. THEN l.date
  175. ELSE l.date_maturity
  176. END as date_maturity
  177. FROM account_move_line l
  178. JOIN account_account_type at ON (at.id = l.user_type_id)
  179. JOIN account_move m ON (l.move_id = m.id)
  180. LEFT JOIN Q0 ON Q0.id = l.id
  181. LEFT JOIN (SELECT pr.*
  182. FROM account_partial_reconcile pr
  183. INNER JOIN account_move_line l2
  184. ON pr.credit_move_id = l2.id
  185. WHERE l2.date <= '%s'
  186. ) as pd ON pd.debit_move_id = l.id
  187. LEFT JOIN (SELECT pr.*
  188. FROM account_partial_reconcile pr
  189. INNER JOIN account_move_line l2
  190. ON pr.debit_move_id = l2.id
  191. WHERE l2.date <= '%s'
  192. ) as pc ON pc.credit_move_id = l.id
  193. WHERE l.partner_id IN (%s) AND at.type = 'receivable'
  194. AND (Q0.reconciled_date is null or
  195. Q0.reconciled_date > '%s')
  196. AND l.date <= '%s' AND not l.blocked
  197. GROUP BY l.partner_id, l.currency_id, l.date, l.date_maturity,
  198. l.amount_currency, l.balance, l.move_id,
  199. l.company_id
  200. """ % (date_end, date_end, partners, date_end, date_end)
  201. def _show_buckets_sql_q2(self, date_end, minus_30, minus_60, minus_90,
  202. minus_120):
  203. return """
  204. SELECT partner_id, currency_id, date_maturity, open_due,
  205. open_due_currency, move_id, company_id,
  206. CASE
  207. WHEN '%s' <= date_maturity AND currency_id is null
  208. THEN open_due
  209. WHEN '%s' <= date_maturity AND currency_id is not null
  210. THEN open_due_currency
  211. ELSE 0.0
  212. END as current,
  213. CASE
  214. WHEN '%s' < date_maturity AND date_maturity < '%s'
  215. AND currency_id is null THEN open_due
  216. WHEN '%s' < date_maturity AND date_maturity < '%s'
  217. AND currency_id is not null
  218. THEN open_due_currency
  219. ELSE 0.0
  220. END as b_1_30,
  221. CASE
  222. WHEN '%s' < date_maturity AND date_maturity <= '%s'
  223. AND currency_id is null THEN open_due
  224. WHEN '%s' < date_maturity AND date_maturity <= '%s'
  225. AND currency_id is not null
  226. THEN open_due_currency
  227. ELSE 0.0
  228. END as b_30_60,
  229. CASE
  230. WHEN '%s' < date_maturity AND date_maturity <= '%s'
  231. AND currency_id is null THEN open_due
  232. WHEN '%s' < date_maturity AND date_maturity <= '%s'
  233. AND currency_id is not null
  234. THEN open_due_currency
  235. ELSE 0.0
  236. END as b_60_90,
  237. CASE
  238. WHEN '%s' < date_maturity AND date_maturity <= '%s'
  239. AND currency_id is null THEN open_due
  240. WHEN '%s' < date_maturity AND date_maturity <= '%s'
  241. AND currency_id is not null
  242. THEN open_due_currency
  243. ELSE 0.0
  244. END as b_90_120,
  245. CASE
  246. WHEN date_maturity <= '%s' AND currency_id is null
  247. THEN open_due
  248. WHEN date_maturity <= '%s' AND currency_id is not null
  249. THEN open_due_currency
  250. ELSE 0.0
  251. END as b_over_120
  252. FROM Q1
  253. GROUP BY partner_id, currency_id, date_maturity, open_due,
  254. open_due_currency, move_id, company_id
  255. """ % (date_end, date_end, minus_30, date_end, minus_30, date_end,
  256. minus_60, minus_30, minus_60, minus_30, minus_90, minus_60,
  257. minus_90, minus_60, minus_120, minus_90, minus_120, minus_90,
  258. minus_120, minus_120)
  259. def _show_buckets_sql_q3(self, company_id):
  260. return """
  261. SELECT Q2.partner_id, current, b_1_30, b_30_60, b_60_90, b_90_120,
  262. b_over_120,
  263. COALESCE(Q2.currency_id, c.currency_id) AS currency_id
  264. FROM Q2
  265. JOIN res_company c ON (c.id = Q2.company_id)
  266. WHERE c.id = %s
  267. """ % company_id
  268. def _show_buckets_sql_q4(self):
  269. return """
  270. SELECT partner_id, currency_id, sum(current) as current,
  271. sum(b_1_30) as b_1_30,
  272. sum(b_30_60) as b_30_60,
  273. sum(b_60_90) as b_60_90,
  274. sum(b_90_120) as b_90_120,
  275. sum(b_over_120) as b_over_120
  276. FROM Q3
  277. GROUP BY partner_id, currency_id
  278. """
  279. def _get_bucket_dates(self, date_end):
  280. return {
  281. 'date_end': date_end,
  282. 'minus_30': date_end - timedelta(days=30),
  283. 'minus_60': date_end - timedelta(days=60),
  284. 'minus_90': date_end - timedelta(days=90),
  285. 'minus_120': date_end - timedelta(days=120),
  286. }
  287. def _get_account_show_buckets(self, company_id, partner_ids, date_end):
  288. res = dict(map(lambda x: (x, []), partner_ids))
  289. partners = ', '.join([str(i) for i in partner_ids])
  290. date_end = datetime.strptime(
  291. date_end, DEFAULT_SERVER_DATE_FORMAT).date()
  292. full_dates = self._get_bucket_dates(date_end)
  293. # pylint: disable=E8103
  294. self.env.cr.execute("""
  295. WITH Q0 AS (%s), Q1 AS (%s), Q2 AS (%s), Q3 AS (%s), Q4 AS (%s)
  296. SELECT partner_id, currency_id, current, b_1_30, b_30_60, b_60_90,
  297. b_90_120, b_over_120,
  298. current+b_1_30+b_30_60+b_60_90+b_90_120+b_over_120
  299. AS balance
  300. FROM Q4
  301. GROUP BY partner_id, currency_id, current, b_1_30, b_30_60, b_60_90,
  302. b_90_120, b_over_120""" % (
  303. self._show_buckets_sql_q0(date_end),
  304. self._show_buckets_sql_q1(partners, date_end),
  305. self._show_buckets_sql_q2(
  306. full_dates['date_end'],
  307. full_dates['minus_30'],
  308. full_dates['minus_60'],
  309. full_dates['minus_90'],
  310. full_dates['minus_120']),
  311. self._show_buckets_sql_q3(company_id),
  312. self._show_buckets_sql_q4()))
  313. for row in self.env.cr.dictfetchall():
  314. res[row.pop('partner_id')].append(row)
  315. return res
  316. @api.multi
  317. def render_html(self, docids, data):
  318. company_id = data['company_id']
  319. partner_ids = data['partner_ids']
  320. date_start = data['date_start']
  321. date_end = data['date_end']
  322. today = fields.Date.today()
  323. balance_start_to_display, buckets_to_display = {}, {}
  324. lines_to_display, amount_due = {}, {}
  325. currency_to_display = {}
  326. today_display, date_start_display, date_end_display = {}, {}, {}
  327. balance_start = self._get_account_initial_balance(
  328. company_id, partner_ids, date_start)
  329. for partner_id in partner_ids:
  330. balance_start_to_display[partner_id] = {}
  331. for line in balance_start[partner_id]:
  332. currency = self.env['res.currency'].browse(line['currency_id'])
  333. if currency not in balance_start_to_display[partner_id]:
  334. balance_start_to_display[partner_id][currency] = []
  335. balance_start_to_display[partner_id][currency] = \
  336. line['balance']
  337. lines = self._get_account_display_lines(
  338. company_id, partner_ids, date_start, date_end)
  339. for partner_id in partner_ids:
  340. lines_to_display[partner_id], amount_due[partner_id] = {}, {}
  341. currency_to_display[partner_id] = {}
  342. today_display[partner_id] = self._format_date_to_partner_lang(
  343. today, partner_id)
  344. date_start_display[partner_id] = self._format_date_to_partner_lang(
  345. date_start, partner_id)
  346. date_end_display[partner_id] = self._format_date_to_partner_lang(
  347. date_end, partner_id)
  348. for line in lines[partner_id]:
  349. currency = self.env['res.currency'].browse(line['currency_id'])
  350. if currency not in lines_to_display[partner_id]:
  351. lines_to_display[partner_id][currency] = []
  352. currency_to_display[partner_id][currency] = currency
  353. if currency in balance_start_to_display[partner_id]:
  354. amount_due[partner_id][currency] = \
  355. balance_start_to_display[partner_id][currency]
  356. else:
  357. amount_due[partner_id][currency] = 0.0
  358. if not line['blocked']:
  359. amount_due[partner_id][currency] += line['amount']
  360. line['balance'] = amount_due[partner_id][currency]
  361. line['date'] = self._format_date_to_partner_lang(
  362. line['date'], partner_id)
  363. line['date_maturity'] = self._format_date_to_partner_lang(
  364. line['date_maturity'], partner_id)
  365. lines_to_display[partner_id][currency].append(line)
  366. if data['show_aging_buckets']:
  367. buckets = self._get_account_show_buckets(
  368. company_id, partner_ids, date_end)
  369. for partner_id in partner_ids:
  370. buckets_to_display[partner_id] = {}
  371. for line in buckets[partner_id]:
  372. currency = self.env['res.currency'].browse(
  373. line['currency_id'])
  374. if currency not in buckets_to_display[partner_id]:
  375. buckets_to_display[partner_id][currency] = []
  376. buckets_to_display[partner_id][currency] = line
  377. docargs = {
  378. 'doc_ids': partner_ids,
  379. 'doc_model': 'res.partner',
  380. 'docs': self.env['res.partner'].browse(partner_ids),
  381. 'Amount_Due': amount_due,
  382. 'Balance_forward': balance_start_to_display,
  383. 'Lines': lines_to_display,
  384. 'Buckets': buckets_to_display,
  385. 'Currencies': currency_to_display,
  386. 'Show_Buckets': data['show_aging_buckets'],
  387. 'Filter_non_due_partners': data['filter_non_due_partners'],
  388. 'Date_start': date_start_display,
  389. 'Date_end': date_end_display,
  390. 'Date': today_display,
  391. }
  392. return self.env['report'].render(
  393. 'customer_activity_statement.statement', values=docargs)