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.

291 lines
14 KiB

  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # OpenERP, Open Source Management Solution
  5. #
  6. # Copyright (c) 2013 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. self.cr.execute("SELECT l.move_id AS move_id, l.id AS aml_id, "
  113. "am.name AS move_name, coalesce(am.ref,'') AS move_ref, am.date AS move_date, "
  114. "aa.id AS account_id, aa.code AS acc_code, "
  115. "coalesce(rp.name,'') AS partner_name, coalesce(rp.ref,'') AS partner_ref, rp.id AS partner_id, "
  116. "coalesce(l.name,'') AS aml_name, "
  117. "l.date_maturity AS date_maturity, "
  118. "coalesce(ap.code, ap.name) AS period, "
  119. "coalesce(atc.code,'') AS tax_code, atc.id AS tax_code_id, coalesce(l.tax_amount,0.0) AS tax_amount, "
  120. "coalesce(l.debit,0.0) AS debit, coalesce(l.credit,0.0) AS credit, "
  121. "coalesce(amr.name,'') AS reconcile, coalesce(amrp.name,'') AS reconcile_partial, "
  122. "coalesce(l.amount_currency,0.0) AS amount_currency, "
  123. "rc.id AS currency_id, rc.name AS currency_name, rc.symbol AS currency_symbol, "
  124. "coalesce(ai.internal_number,'-') AS inv_number, coalesce(abs.name,'-') AS st_number, coalesce(av.number,'-') AS voucher_number "
  125. + select_extra +
  126. "FROM account_move_line l "
  127. "INNER JOIN account_move am ON l.move_id = am.id "
  128. "INNER JOIN account_account aa ON l.account_id = aa.id "
  129. "INNER JOIN account_period ap ON l.period_id = ap.id "
  130. "LEFT OUTER JOIN account_invoice ai ON ai.move_id = am.id "
  131. "LEFT OUTER JOIN account_voucher av ON av.move_id = am.id "
  132. "LEFT OUTER JOIN account_bank_statement abs ON l.statement_id = abs.id "
  133. "LEFT OUTER JOIN res_partner rp ON l.partner_id = rp.id "
  134. "LEFT OUTER JOIN account_tax_code atc ON l.tax_code_id = atc.id "
  135. "LEFT OUTER JOIN account_move_reconcile amr ON l.reconcile_id = amr.id "
  136. "LEFT OUTER JOIN account_move_reconcile amrp ON l.reconcile_partial_id = amrp.id "
  137. "LEFT OUTER JOIN res_currency rc ON l.currency_id = rc.id "
  138. + join_extra +
  139. "WHERE l.period_id IN %s AND l.journal_id = %s "
  140. "AND am.state IN %s "
  141. + where_extra +
  142. "ORDER BY " + self.sort_selection + ", move_date, move_id, acc_code",
  143. (tuple(period_ids), journal_id, tuple(self.move_states)))
  144. lines = self.cr.dictfetchall()
  145. # add reference of corresponding origin document
  146. if journal.type in ('sale', 'sale_refund', 'purchase', 'purchase_refund'):
  147. [x.update({'docname': (_('Invoice') + ': ' + x['inv_number']) or (_('Voucher') + ': ' + x['voucher_number']) or '-'}) for x in lines]
  148. elif journal.type in ('bank', 'cash'):
  149. [x.update({'docname': (_('Statement') + ': ' + x['st_number']) or (_('Voucher') + ': ' + x['voucher_number']) or '-'}) for x in lines]
  150. else:
  151. code_string = j_obj._report_xls_document_extra(self.cr, self.uid, self.context)
  152. #_logger.warn('code_string= %s', code_string)
  153. [x.update({'docname': eval(code_string) or '-'}) for x in lines]
  154. # format debit, credit, amount_currency for pdf report
  155. if self.display_currency and self.report_type == 'pdf':
  156. curr_obj = self.pool.get('res.currency')
  157. [x.update({
  158. 'amount1': self.formatLang(x['debit'] - x['credit']),
  159. 'amount2': self.formatLang(x['amount_currency'], monetary=True, currency_obj=curr_obj.browse(self.cr, self.uid, x['currency_id'])),
  160. }) for x in lines]
  161. else:
  162. [x.update({'amount1': self.formatLang(x['debit']), 'amount2': self.formatLang(x['credit'])}) for x in lines]
  163. # group lines
  164. if self.group_entries:
  165. lines = self._group_lines(lines)
  166. # insert a flag in every move_line to indicate the end of a move
  167. # this flag will be used to draw a full line between moves
  168. for cnt in range(len(lines) - 1):
  169. if lines[cnt]['move_id'] != lines[cnt + 1]['move_id']:
  170. lines[cnt]['draw_line'] = 1
  171. else:
  172. lines[cnt]['draw_line'] = 0
  173. lines[-1]['draw_line'] = 1
  174. return lines
  175. def _group_lines(self, lines_in):
  176. _ = self._
  177. def group_move(lines_in):
  178. if len(lines_in) == 1:
  179. return lines_in
  180. lines_grouped = {}
  181. for line in lines_in:
  182. key = (line['account_id'], line['tax_code_id'], line['partner_id'])
  183. if not key in lines_grouped:
  184. lines_grouped[key] = line
  185. else:
  186. lines_grouped[key]['debit'] += line['debit']
  187. lines_grouped[key]['credit'] += line['credit']
  188. lines_grouped[key]['tax_amount'] += line['tax_amount']
  189. lines_grouped[key]['aml_name'] = _('Grouped Entries')
  190. lines_out = lines_grouped.values()
  191. lines_out.sort(key=lambda x: x['acc_code'])
  192. return lines_out
  193. lines_out = []
  194. grouped_lines = [lines_in[0]]
  195. move_id = lines_in[0]['move_id']
  196. line_cnt = len(lines_in)
  197. for i in range(1,line_cnt):
  198. line = lines_in[i]
  199. if line['move_id'] == move_id:
  200. grouped_lines.append(line)
  201. if i == line_cnt - 1:
  202. lines_out += group_move(grouped_lines)
  203. else:
  204. lines_out += group_move(grouped_lines)
  205. grouped_lines = [line]
  206. move_id = line['move_id']
  207. return lines_out
  208. def _tax_codes(self, object):
  209. journal_id = object[0].id
  210. if self.print_by == 'period':
  211. period_id = object[1].id
  212. period_ids = [period_id]
  213. else:
  214. fiscalyear = object[1]
  215. period_ids = [x.id for x in fiscalyear.period_ids]
  216. self.cr.execute(
  217. "SELECT distinct tax_code_id FROM account_move_line l "
  218. "INNER JOIN account_move am ON l.move_id = am.id "
  219. "WHERE l.period_id in %s AND l.journal_id=%s AND l.tax_code_id IS NOT NULL AND am.state IN %s",
  220. (tuple(period_ids), journal_id, tuple(self.move_states)))
  221. ids = map(lambda x: x[0], self.cr.fetchall())
  222. if ids:
  223. self.cr.execute('SELECT id FROM account_tax_code WHERE id IN %s ORDER BY code', (tuple(ids),))
  224. tax_code_ids = map(lambda x: x[0], self.cr.fetchall())
  225. else:
  226. tax_code_ids = []
  227. tax_codes = self.pool.get('account.tax.code').browse(self.cr, self.uid, tax_code_ids, self.context)
  228. return tax_codes
  229. def _totals(self, field, object, tax_code_id=None):
  230. journal_id = object[0].id
  231. if self.print_by == 'period':
  232. period_id = object[1].id
  233. period_ids = [period_id]
  234. else:
  235. fiscalyear = object[1]
  236. period_ids = [x.id for x in fiscalyear.period_ids]
  237. select = "SELECT sum(" + field + ") FROM account_move_line l " \
  238. "INNER JOIN account_move am ON l.move_id = am.id " \
  239. "WHERE l.period_id IN %s AND l.journal_id=%s AND am.state IN %s"
  240. if field == 'tax_amount':
  241. select += " AND tax_code_id=%s" % tax_code_id
  242. self.cr.execute(select, (tuple(period_ids), journal_id, tuple(self.move_states)))
  243. return self.cr.fetchone()[0] or 0.0
  244. def _sum1(self, object):
  245. return self._totals('debit', object)
  246. def _sum2(self, object):
  247. if self.display_currency:
  248. return ''
  249. else:
  250. return self._totals('credit', object)
  251. def _sum_vat(self, object, tax_code):
  252. return self._totals('tax_amount', object, tax_code.id)
  253. def formatLang(self, value, digits=None, date=False, date_time=False, grouping=True, monetary=False, dp=False, currency_obj=False):
  254. if isinstance(value, (float, int)) and not value:
  255. return ''
  256. else:
  257. return super(nov_journal_print, self).formatLang(value, digits, date, date_time, grouping, monetary, dp, currency_obj)
  258. report_sxw.report_sxw('report.nov.account.journal.print', 'account.journal',
  259. 'addons/account_journal_report_xls/report/nov_account_journal.rml',
  260. parser=nov_journal_print, header=False)
  261. # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: