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.

347 lines
15 KiB

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