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.

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