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.

430 lines
19 KiB

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