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. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # OpenERP, Open Source Management Solution
  5. #
  6. # Copyright (c) 2014 Noviat nv/sa (www.noviat.com). All rights reserved.
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU Affero General Public License as
  10. # published by the Free Software Foundation, either version 3 of the
  11. # License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Affero General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Affero General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. ##############################################################################
  22. import time
  23. from openerp.report import report_sxw
  24. from openerp.tools.translate import translate
  25. import logging
  26. _logger = logging.getLogger(__name__)
  27. _ir_translation_name = 'nov.account.journal.print'
  28. class nov_journal_print(report_sxw.rml_parse):
  29. def set_context(self, objects, data, ids, report_type=None):
  30. # _logger.warn('set_context, objects = %s, data = %s,
  31. # ids = %s', objects, data, ids)
  32. super(nov_journal_print, self).set_context(objects, data, ids)
  33. j_obj = self.pool.get('account.journal')
  34. p_obj = self.pool.get('account.period')
  35. fy_obj = self.pool.get('account.fiscalyear')
  36. self.sort_selection = data['sort_selection']
  37. if data['target_move'] == 'posted':
  38. self.move_states = ['posted']
  39. else:
  40. self.move_states = ['draft', 'posted']
  41. self.display_currency = self.localcontext[
  42. 'display_currency'] = data['display_currency']
  43. self.group_entries = data['group_entries']
  44. self.print_by = data['print_by']
  45. self.report_type = report_type
  46. if self.print_by == 'period':
  47. journal_period_ids = data['journal_period_ids']
  48. objects = []
  49. for jp in journal_period_ids:
  50. journal = j_obj.browse(self.cr, self.uid, jp[0], self.context)
  51. periods = p_obj.browse(self.cr, self.uid, jp[1], self.context)
  52. objects.extend([(journal, period) for period in periods])
  53. self.localcontext['objects'] = self.objects = objects
  54. else:
  55. journal_fy_ids = data['journal_fy_ids']
  56. objects = []
  57. for jf in journal_fy_ids:
  58. journal = j_obj.browse(self.cr, self.uid, jf[0], self.context)
  59. fiscalyear = fy_obj.browse(
  60. self.cr, self.uid, jf[1], self.context)
  61. objects.append((journal, fiscalyear))
  62. self.localcontext['objects'] = self.objects = objects
  63. def __init__(self, cr, uid, name, context):
  64. if context is None:
  65. context = {}
  66. super(nov_journal_print, self).__init__(cr, uid, name, context=context)
  67. self.localcontext.update({
  68. 'time': time,
  69. 'title': self._title,
  70. 'amount_title': self._amount_title,
  71. 'lines': self._lines,
  72. 'sum1': self._sum1,
  73. 'sum2': self._sum2,
  74. 'tax_codes': self._tax_codes,
  75. 'sum_vat': self._sum_vat,
  76. '_': self._,
  77. })
  78. self.context = context
  79. def _(self, src):
  80. lang = self.context.get('lang', 'en_US')
  81. return translate(self.cr, _ir_translation_name, 'report', lang, src) \
  82. or src
  83. def _title(self, object):
  84. return ((self.print_by == 'period' and self._('Period') or
  85. self._('Fiscal Year')) + ' ' + object[1].name, object[0].name)
  86. def _amount_title(self):
  87. return self.display_currency and \
  88. (self._('Amount'), self._('Currency')) or (
  89. self._('Debit'), self._('Credit'))
  90. def _lines(self, object):
  91. j_obj = self.pool['account.journal']
  92. _ = self._
  93. journal = object[0]
  94. journal_id = journal.id
  95. if self.print_by == 'period':
  96. period = object[1]
  97. period_id = period.id
  98. period_ids = [period_id]
  99. # update status period
  100. ids_journal_period = self.pool['account.journal.period'].\
  101. search(self.cr, self.uid, [('journal_id', '=', journal_id),
  102. ('period_id', '=', period_id)])
  103. if ids_journal_period:
  104. self.cr.execute(
  105. '''update account_journal_period set state=%s
  106. where journal_id=%s and period_id=%s and state=%s''',
  107. ('printed', journal_id, period_id, 'draft'))
  108. else:
  109. self.pool.get('account.journal.period').create(
  110. self.cr, self.uid,
  111. {'name': (journal.code or journal.name) + ':' +
  112. (period.name or ''),
  113. 'journal_id': journal.id,
  114. 'period_id': period.id,
  115. 'state': 'printed',
  116. })
  117. _logger.error("""The Entry for Period '%s', Journal '%s' was
  118. missing in 'account.journal.period' and
  119. has been fixed now !""",
  120. period.name, journal.name)
  121. else:
  122. fiscalyear = object[1]
  123. period_ids = [x.id for x in fiscalyear.period_ids]
  124. select_extra, join_extra, where_extra = j_obj._report_xls_query_extra(
  125. self.cr, self.uid, self.context)
  126. # SQL select for performance reasons, as a consequence, there are no
  127. # field value translations.
  128. # If performance is no issue, you can adapt the _report_xls_template in
  129. # an inherited module to add field value translations.
  130. self.cr.execute("SELECT l.move_id AS move_id, l.id AS aml_id, "
  131. "am.name AS move_name, "
  132. "coalesce(am.ref,'') AS move_ref, "
  133. "am.date AS move_date, "
  134. "aa.id AS account_id, aa.code AS acc_code, "
  135. "aa.name AS acc_name, "
  136. "aj.name AS journal, aj.code AS journal_code, "
  137. "coalesce(rp.name,'') AS partner_name, "
  138. "coalesce(rp.ref,'') AS partner_ref, "
  139. "rp.id AS partner_id, "
  140. "coalesce(l.name,'') AS aml_name, "
  141. "l.date_maturity AS date_maturity, "
  142. "coalesce(ap.code, ap.name) AS period, "
  143. "coalesce(atc.code,'') AS tax_code, "
  144. "atc.id AS tax_code_id, "
  145. "coalesce(l.tax_amount,0.0) AS tax_amount, "
  146. "coalesce(l.debit,0.0) AS debit, "
  147. "coalesce(l.credit,0.0) AS credit, "
  148. "coalesce(amr.name,'') AS reconcile, "
  149. "coalesce(amrp.name,'') AS reconcile_partial, "
  150. "ana.name AS an_acc_name, "
  151. "coalesce(ana.code,'') AS an_acc_code, "
  152. "coalesce(l.amount_currency,0.0) AS amount_currency, "
  153. "rc.id AS currency_id, rc.name AS currency_name, "
  154. "rc.symbol AS currency_symbol, "
  155. "coalesce(ai.internal_number,'-') AS inv_number, "
  156. "coalesce(abs.name,'-') AS st_number, "
  157. "coalesce(av.number,'-') AS voucher_number " +
  158. select_extra +
  159. "FROM account_move_line l "
  160. "INNER JOIN account_move am ON l.move_id = am.id "
  161. "INNER JOIN account_account aa "
  162. "ON l.account_id = aa.id "
  163. "INNER JOIN account_journal aj "
  164. "ON l.journal_id = aj.id "
  165. "INNER JOIN account_period ap ON l.period_id = ap.id "
  166. "LEFT OUTER JOIN account_invoice ai "
  167. "ON ai.move_id = am.id "
  168. "LEFT OUTER JOIN account_voucher av "
  169. "ON av.move_id = am.id "
  170. "LEFT OUTER JOIN account_bank_statement abs "
  171. "ON l.statement_id = abs.id "
  172. "LEFT OUTER JOIN res_partner rp "
  173. "ON l.partner_id = rp.id "
  174. "LEFT OUTER JOIN account_tax_code atc "
  175. "ON l.tax_code_id = atc.id "
  176. "LEFT OUTER JOIN account_move_reconcile amr "
  177. "ON l.reconcile_id = amr.id "
  178. "LEFT OUTER JOIN account_move_reconcile amrp "
  179. "ON l.reconcile_partial_id = amrp.id "
  180. "LEFT OUTER JOIN account_analytic_account ana "
  181. "ON l.analytic_account_id = ana.id "
  182. "LEFT OUTER JOIN res_currency rc "
  183. "ON l.currency_id = rc.id " + join_extra +
  184. "WHERE l.period_id IN %s AND l.journal_id = %s "
  185. "AND am.state IN %s " + where_extra +
  186. "ORDER BY " + self.sort_selection +
  187. ", move_date, move_id, acc_code",
  188. (tuple(period_ids), journal_id,
  189. tuple(self.move_states)))
  190. lines = self.cr.dictfetchall()
  191. # add reference of corresponding origin document
  192. if journal.type in ('sale', 'sale_refund', 'purchase',
  193. 'purchase_refund'):
  194. [x.update({'docname': (_('Invoice') + ': ' + x['inv_number']) or
  195. (_('Voucher') + ': ' + x['voucher_number']) or '-'})
  196. for x in lines]
  197. elif journal.type in ('bank', 'cash'):
  198. [x.update({'docname': (_('Statement') + ': ' + x['st_number']) or
  199. (_('Voucher') + ': ' + x['voucher_number']) or '-'})
  200. for x in lines]
  201. else:
  202. code_string = j_obj._report_xls_document_extra(
  203. self.cr, self.uid, self.context)
  204. # _logger.warn('code_string= %s', code_string)
  205. [x.update({'docname': eval(code_string) or '-'}) for x in lines]
  206. # group lines
  207. if self.group_entries:
  208. lines = self._group_lines(lines)
  209. # format debit, credit, amount_currency for pdf report
  210. if self.display_currency and self.report_type == 'pdf':
  211. curr_obj = self.pool.get('res.currency')
  212. [x.update({
  213. 'amount1': self.formatLang(x['debit'] - x['credit']),
  214. 'amount2': self.formatLang(
  215. x['amount_currency'], monetary=True,
  216. currency_obj=curr_obj.browse(self.cr,
  217. self.uid, x['currency_id'])),
  218. }) for x in lines]
  219. else:
  220. [x.update({'amount1': self.formatLang(x['debit']),
  221. 'amount2': self.formatLang(x['credit'])})
  222. for x in lines]
  223. # insert a flag in every move_line to indicate the end of a move
  224. # this flag will be used to draw a full line between moves
  225. for cnt in range(len(lines) - 1):
  226. if lines[cnt]['move_id'] != lines[cnt + 1]['move_id']:
  227. lines[cnt]['draw_line'] = 1
  228. else:
  229. lines[cnt]['draw_line'] = 0
  230. lines[-1]['draw_line'] = 1
  231. return lines
  232. def _group_lines(self, lines_in):
  233. _ = self._
  234. def group_move(lines_in):
  235. if len(lines_in) == 1:
  236. return lines_in
  237. lines_grouped = {}
  238. for line in lines_in:
  239. key = (line['account_id'],
  240. line['tax_code_id'],
  241. line['partner_id'])
  242. if key not in lines_grouped:
  243. lines_grouped[key] = line
  244. else:
  245. lines_grouped[key]['debit'] += line['debit']
  246. lines_grouped[key]['credit'] += line['credit']
  247. lines_grouped[key]['tax_amount'] += line['tax_amount']
  248. lines_grouped[key]['aml_name'] = _('Grouped Entries')
  249. lines_out = lines_grouped.values()
  250. lines_out.sort(key=lambda x: x['acc_code'])
  251. return lines_out
  252. lines_out = []
  253. grouped_lines = [lines_in[0]]
  254. move_id = lines_in[0]['move_id']
  255. line_cnt = len(lines_in)
  256. for i in range(1, line_cnt):
  257. line = lines_in[i]
  258. if line['move_id'] == move_id:
  259. grouped_lines.append(line)
  260. if i == line_cnt - 1:
  261. lines_out += group_move(grouped_lines)
  262. else:
  263. lines_out += group_move(grouped_lines)
  264. grouped_lines = [line]
  265. move_id = line['move_id']
  266. return lines_out
  267. def _tax_codes(self, object):
  268. journal_id = object[0].id
  269. if self.print_by == 'period':
  270. period_id = object[1].id
  271. period_ids = [period_id]
  272. else:
  273. fiscalyear = object[1]
  274. period_ids = [x.id for x in fiscalyear.period_ids]
  275. self.cr.execute(
  276. "SELECT distinct tax_code_id FROM account_move_line l "
  277. "INNER JOIN account_move am ON l.move_id = am.id "
  278. "WHERE l.period_id in %s AND l.journal_id=%s "
  279. "AND l.tax_code_id IS NOT NULL AND am.state IN %s",
  280. (tuple(period_ids), journal_id, tuple(self.move_states)))
  281. ids = map(lambda x: x[0], self.cr.fetchall())
  282. if ids:
  283. self.cr.execute(
  284. 'SELECT id FROM account_tax_code WHERE id IN %s ORDER BY code',
  285. (tuple(ids),))
  286. tax_code_ids = map(lambda x: x[0], self.cr.fetchall())
  287. else:
  288. tax_code_ids = []
  289. tax_codes = self.pool.get('account.tax.code').browse(
  290. self.cr, self.uid, tax_code_ids, self.context)
  291. return tax_codes
  292. def _totals(self, field, object, tax_code_id=None):
  293. journal_id = object[0].id
  294. if self.print_by == 'period':
  295. period_id = object[1].id
  296. period_ids = [period_id]
  297. else:
  298. fiscalyear = object[1]
  299. period_ids = [x.id for x in fiscalyear.period_ids]
  300. select = "SELECT sum(" + field + ") FROM account_move_line l " \
  301. "INNER JOIN account_move am ON l.move_id = am.id " \
  302. "WHERE l.period_id IN %s AND l.journal_id=%s AND am.state IN %s"
  303. if field == 'tax_amount':
  304. select += " AND tax_code_id=%s" % tax_code_id
  305. self.cr.execute(
  306. select, (tuple(period_ids), journal_id, tuple(self.move_states)))
  307. return self.cr.fetchone()[0] or 0.0
  308. def _sum1(self, object):
  309. return self._totals('debit', object)
  310. def _sum2(self, object):
  311. if self.display_currency:
  312. return ''
  313. else:
  314. return self._totals('credit', object)
  315. def _sum_vat(self, object, tax_code):
  316. return self._totals('tax_amount', object, tax_code.id)
  317. def formatLang(self, value, digits=None, date=False, date_time=False,
  318. grouping=True, monetary=False, dp=False,
  319. currency_obj=False):
  320. if isinstance(value, (float, int)) and not value:
  321. return ''
  322. else:
  323. return super(nov_journal_print, self).formatLang(
  324. value, digits,
  325. date, date_time, grouping, monetary, dp, currency_obj)
  326. report_sxw.report_sxw(
  327. 'report.nov.account.journal.print', 'account.journal',
  328. 'addons/account_journal_report_xls/report/nov_account_journal.rml',
  329. parser=nov_journal_print, header=False)