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.

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