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.

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