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.

297 lines
14 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, ids = %s', objects, data, ids)
  31. super(nov_journal_print, self).set_context(objects, data, ids)
  32. j_obj = self.pool.get('account.journal')
  33. p_obj = self.pool.get('account.period')
  34. fy_obj = self.pool.get('account.fiscalyear')
  35. self.sort_selection = data['sort_selection']
  36. if data['target_move'] == 'posted':
  37. self.move_states = ['posted']
  38. else:
  39. self.move_states = ['draft', 'posted']
  40. self.display_currency = self.localcontext['display_currency'] = data['display_currency']
  41. self.group_entries = data['group_entries']
  42. self.print_by = data['print_by']
  43. self.report_type = report_type
  44. if self.print_by == 'period':
  45. journal_period_ids = data['journal_period_ids']
  46. objects = []
  47. for jp in journal_period_ids:
  48. journal = j_obj.browse(self.cr, self.uid, jp[0], self.context)
  49. periods = p_obj.browse(self.cr, self.uid, jp[1], self.context)
  50. objects.extend([(journal, period) for period in periods])
  51. self.localcontext['objects'] = self.objects = objects
  52. else:
  53. journal_fy_ids = data['journal_fy_ids']
  54. objects = []
  55. for jf in journal_fy_ids:
  56. journal = j_obj.browse(self.cr, self.uid, jf[0], self.context)
  57. fiscalyear = fy_obj.browse(self.cr, self.uid, jf[1], self.context)
  58. objects.append((journal, fiscalyear))
  59. self.localcontext['objects'] = self.objects = objects
  60. def __init__(self, cr, uid, name, context):
  61. if context is None:
  62. context = {}
  63. super(nov_journal_print, self).__init__(cr, uid, name, context=context)
  64. self.localcontext.update({
  65. 'time': time,
  66. 'title': self._title,
  67. 'amount_title': self._amount_title,
  68. 'lines': self._lines,
  69. 'sum1': self._sum1,
  70. 'sum2': self._sum2,
  71. 'tax_codes': self._tax_codes,
  72. 'sum_vat': self._sum_vat,
  73. '_': self._,
  74. })
  75. self.context = context
  76. def _(self, src):
  77. lang = self.context.get('lang', 'en_US')
  78. return translate(self.cr, _ir_translation_name, 'report', lang, src) or src
  79. def _title(self, object):
  80. return ((self.print_by == 'period' and self._('Period') or self._('Fiscal Year')) + ' ' + object[1].name, object[0].name)
  81. def _amount_title(self):
  82. return self.display_currency and (self._('Amount'), self._('Currency')) or (self._('Debit'), self._('Credit'))
  83. def _lines(self, object):
  84. j_obj = self.pool.get('account.journal')
  85. _ = self._
  86. journal = object[0]
  87. journal_id = journal.id
  88. if self.print_by == 'period':
  89. period = object[1]
  90. period_id = period.id
  91. period_ids = [period_id]
  92. # update status period
  93. ids_journal_period = self.pool.get('account.journal.period').search(self.cr, self.uid,
  94. [('journal_id', '=', journal_id), ('period_id', '=', period_id)])
  95. if ids_journal_period:
  96. self.cr.execute(
  97. 'update account_journal_period set state=%s where journal_id=%s and period_id=%s and state=%s',
  98. ('printed', journal_id, period_id, 'draft'))
  99. else:
  100. self.pool.get('account.journal.period').create(self.cr, self.uid, {
  101. 'name': (journal.code or journal.name) + ':' + (period.name or ''),
  102. 'journal_id': journal.id,
  103. 'period_id': period.id,
  104. 'state': 'printed',
  105. })
  106. _logger.error("The Entry for Period '%s', Journal '%s' was missing in 'account.journal.period' and has been fixed now !",
  107. period.name, journal.name)
  108. else:
  109. fiscalyear = object[1]
  110. period_ids = [x.id for x in fiscalyear.period_ids]
  111. select_extra, join_extra, where_extra = j_obj._report_xls_query_extra(self.cr, self.uid, self.context)
  112. # SQL select for performance reasons, as a consequence, there are no field value translations.
  113. # If performance is no issue, you can adapt the _report_xls_template in an inherited module to add field value translations.
  114. self.cr.execute("SELECT l.move_id AS move_id, l.id AS aml_id, "
  115. "am.name AS move_name, coalesce(am.ref,'') AS move_ref, am.date AS move_date, "
  116. "aa.id AS account_id, aa.code AS acc_code, aa.name AS acc_name, "
  117. "aj.name AS journal, aj.code AS journal_code, "
  118. "coalesce(rp.name,'') AS partner_name, coalesce(rp.ref,'') AS partner_ref, rp.id AS partner_id, "
  119. "coalesce(l.name,'') AS aml_name, "
  120. "l.date_maturity AS date_maturity, "
  121. "coalesce(ap.code, ap.name) AS period, "
  122. "coalesce(atc.code,'') AS tax_code, atc.id AS tax_code_id, coalesce(l.tax_amount,0.0) AS tax_amount, "
  123. "coalesce(l.debit,0.0) AS debit, coalesce(l.credit,0.0) AS credit, "
  124. "coalesce(amr.name,'') AS reconcile, coalesce(amrp.name,'') AS reconcile_partial, "
  125. "ana.name AS an_acc_name, coalesce(ana.code,'') AS an_acc_code, "
  126. "coalesce(l.amount_currency,0.0) AS amount_currency, "
  127. "rc.id AS currency_id, rc.name AS currency_name, rc.symbol AS currency_symbol, "
  128. "coalesce(ai.internal_number,'-') AS inv_number, coalesce(abs.name,'-') AS st_number, coalesce(av.number,'-') AS voucher_number "
  129. + select_extra +
  130. "FROM account_move_line l "
  131. "INNER JOIN account_move am ON l.move_id = am.id "
  132. "INNER JOIN account_account aa ON l.account_id = aa.id "
  133. "INNER JOIN account_journal aj ON l.journal_id = aj.id "
  134. "INNER JOIN account_period ap ON l.period_id = ap.id "
  135. "LEFT OUTER JOIN account_invoice ai ON ai.move_id = am.id "
  136. "LEFT OUTER JOIN account_voucher av ON av.move_id = am.id "
  137. "LEFT OUTER JOIN account_bank_statement abs ON l.statement_id = abs.id "
  138. "LEFT OUTER JOIN res_partner rp ON l.partner_id = rp.id "
  139. "LEFT OUTER JOIN account_tax_code atc ON l.tax_code_id = atc.id "
  140. "LEFT OUTER JOIN account_move_reconcile amr ON l.reconcile_id = amr.id "
  141. "LEFT OUTER JOIN account_move_reconcile amrp ON l.reconcile_partial_id = amrp.id "
  142. "LEFT OUTER JOIN account_analytic_account ana ON l.analytic_account_id = ana.id "
  143. "LEFT OUTER JOIN res_currency rc ON l.currency_id = rc.id "
  144. + join_extra +
  145. "WHERE l.period_id IN %s AND l.journal_id = %s "
  146. "AND am.state IN %s "
  147. + where_extra +
  148. "ORDER BY " + self.sort_selection + ", move_date, move_id, acc_code",
  149. (tuple(period_ids), journal_id, tuple(self.move_states)))
  150. lines = self.cr.dictfetchall()
  151. # add reference of corresponding origin document
  152. if journal.type in ('sale', 'sale_refund', 'purchase', 'purchase_refund'):
  153. [x.update({'docname': (_('Invoice') + ': ' + x['inv_number']) or (_('Voucher') + ': ' + x['voucher_number']) or '-'}) for x in lines]
  154. elif journal.type in ('bank', 'cash'):
  155. [x.update({'docname': (_('Statement') + ': ' + x['st_number']) or (_('Voucher') + ': ' + x['voucher_number']) or '-'}) for x in lines]
  156. else:
  157. code_string = j_obj._report_xls_document_extra(self.cr, self.uid, self.context)
  158. #_logger.warn('code_string= %s', code_string)
  159. [x.update({'docname': eval(code_string) or '-'}) for x in lines]
  160. # group lines
  161. if self.group_entries:
  162. lines = self._group_lines(lines)
  163. # format debit, credit, amount_currency for pdf report
  164. if self.display_currency and self.report_type == 'pdf':
  165. curr_obj = self.pool.get('res.currency')
  166. [x.update({
  167. 'amount1': self.formatLang(x['debit'] - x['credit']),
  168. 'amount2': self.formatLang(x['amount_currency'], monetary=True, currency_obj=curr_obj.browse(self.cr, self.uid, x['currency_id'])),
  169. }) for x in lines]
  170. else:
  171. [x.update({'amount1': self.formatLang(x['debit']), 'amount2': self.formatLang(x['credit'])}) for x in lines]
  172. # insert a flag in every move_line to indicate the end of a move
  173. # this flag will be used to draw a full line between moves
  174. for cnt in range(len(lines) - 1):
  175. if lines[cnt]['move_id'] != lines[cnt + 1]['move_id']:
  176. lines[cnt]['draw_line'] = 1
  177. else:
  178. lines[cnt]['draw_line'] = 0
  179. lines[-1]['draw_line'] = 1
  180. return lines
  181. def _group_lines(self, lines_in):
  182. _ = self._
  183. def group_move(lines_in):
  184. if len(lines_in) == 1:
  185. return lines_in
  186. lines_grouped = {}
  187. for line in lines_in:
  188. key = (line['account_id'], line['tax_code_id'], line['partner_id'])
  189. if not key in lines_grouped:
  190. lines_grouped[key] = line
  191. else:
  192. lines_grouped[key]['debit'] += line['debit']
  193. lines_grouped[key]['credit'] += line['credit']
  194. lines_grouped[key]['tax_amount'] += line['tax_amount']
  195. lines_grouped[key]['aml_name'] = _('Grouped Entries')
  196. lines_out = lines_grouped.values()
  197. lines_out.sort(key=lambda x: x['acc_code'])
  198. return lines_out
  199. lines_out = []
  200. grouped_lines = [lines_in[0]]
  201. move_id = lines_in[0]['move_id']
  202. line_cnt = len(lines_in)
  203. for i in range(1, line_cnt):
  204. line = lines_in[i]
  205. if line['move_id'] == move_id:
  206. grouped_lines.append(line)
  207. if i == line_cnt - 1:
  208. lines_out += group_move(grouped_lines)
  209. else:
  210. lines_out += group_move(grouped_lines)
  211. grouped_lines = [line]
  212. move_id = line['move_id']
  213. return lines_out
  214. def _tax_codes(self, object):
  215. journal_id = object[0].id
  216. if self.print_by == 'period':
  217. period_id = object[1].id
  218. period_ids = [period_id]
  219. else:
  220. fiscalyear = object[1]
  221. period_ids = [x.id for x in fiscalyear.period_ids]
  222. self.cr.execute(
  223. "SELECT distinct tax_code_id FROM account_move_line l "
  224. "INNER JOIN account_move am ON l.move_id = am.id "
  225. "WHERE l.period_id in %s AND l.journal_id=%s AND l.tax_code_id IS NOT NULL AND am.state IN %s",
  226. (tuple(period_ids), journal_id, tuple(self.move_states)))
  227. ids = map(lambda x: x[0], self.cr.fetchall())
  228. if ids:
  229. self.cr.execute('SELECT id FROM account_tax_code WHERE id IN %s ORDER BY code', (tuple(ids),))
  230. tax_code_ids = map(lambda x: x[0], self.cr.fetchall())
  231. else:
  232. tax_code_ids = []
  233. tax_codes = self.pool.get('account.tax.code').browse(self.cr, self.uid, tax_code_ids, self.context)
  234. return tax_codes
  235. def _totals(self, field, object, tax_code_id=None):
  236. journal_id = object[0].id
  237. if self.print_by == 'period':
  238. period_id = object[1].id
  239. period_ids = [period_id]
  240. else:
  241. fiscalyear = object[1]
  242. period_ids = [x.id for x in fiscalyear.period_ids]
  243. select = "SELECT sum(" + field + ") FROM account_move_line l " \
  244. "INNER JOIN account_move am ON l.move_id = am.id " \
  245. "WHERE l.period_id IN %s AND l.journal_id=%s AND am.state IN %s"
  246. if field == 'tax_amount':
  247. select += " AND tax_code_id=%s" % tax_code_id
  248. self.cr.execute(select, (tuple(period_ids), journal_id, tuple(self.move_states)))
  249. return self.cr.fetchone()[0] or 0.0
  250. def _sum1(self, object):
  251. return self._totals('debit', object)
  252. def _sum2(self, object):
  253. if self.display_currency:
  254. return ''
  255. else:
  256. return self._totals('credit', object)
  257. def _sum_vat(self, object, tax_code):
  258. return self._totals('tax_amount', object, tax_code.id)
  259. def formatLang(self, value, digits=None, date=False, date_time=False, grouping=True, monetary=False, dp=False, currency_obj=False):
  260. if isinstance(value, (float, int)) and not value:
  261. return ''
  262. else:
  263. return super(nov_journal_print, self).formatLang(value, digits, date, date_time, grouping, monetary, dp, currency_obj)
  264. report_sxw.report_sxw('report.nov.account.journal.print', 'account.journal',
  265. 'addons/account_journal_report_xls/report/nov_account_journal.rml',
  266. parser=nov_journal_print, header=False)
  267. # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: