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.

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