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.

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