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.

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