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.

351 lines
15 KiB

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