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.

388 lines
18 KiB

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