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.

211 lines
9.6 KiB

  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Author: Nicolas Bessi, Guewen Baconnier
  5. # Copyright Camptocamp SA 2011
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as
  9. # published by the Free Software Foundation, either version 3 of the
  10. # License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. from report import report_sxw
  22. from tools.translate import _
  23. import pooler
  24. from operator import itemgetter
  25. from itertools import groupby
  26. from datetime import datetime
  27. from common_reports import CommonReportHeaderWebkit
  28. from webkit_parser_header_fix import HeaderFooterTextWebKitParser
  29. class GeneralLedgerWebkit(report_sxw.rml_parse, CommonReportHeaderWebkit):
  30. def __init__(self, cursor, uid, name, context):
  31. super(GeneralLedgerWebkit, self).__init__(cursor, uid, name, context=context)
  32. self.pool = pooler.get_pool(self.cr.dbname)
  33. self.cursor = self.cr
  34. company = self.pool.get('res.users').browse(self.cr, uid, uid, context=context).company_id
  35. header_report_name = ' - '.join((_('GENERAL LEDGER'), company.name, company.currency_id.name))
  36. footer_date_time = self.formatLang(str(datetime.today()), date_time=True)
  37. self.localcontext.update({
  38. 'cr': cursor,
  39. 'uid': uid,
  40. 'report_name': _('General Ledger'),
  41. 'display_account': self._get_display_account,
  42. 'display_account_raw': self._get_display_account_raw,
  43. 'filter_form': self._get_filter,
  44. 'target_move': self._get_target_move,
  45. 'initial_balance': self._get_initial_balance,
  46. 'amount_currency': self._get_amount_currency,
  47. 'display_target_move': self._get_display_target_move,
  48. 'accounts': self._get_accounts_br,
  49. 'additional_args': [
  50. ('--header-font-name', 'Helvetica'),
  51. ('--footer-font-name', 'Helvetica'),
  52. ('--header-font-size', '10'),
  53. ('--footer-font-size', '6'),
  54. ('--header-left', header_report_name),
  55. ('--header-spacing', '2'),
  56. ('--footer-left', footer_date_time),
  57. ('--footer-right', ' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
  58. ('--footer-line',),
  59. ],
  60. })
  61. def set_context(self, objects, data, ids, report_type=None):
  62. """Populate a ledger_lines attribute on each browse record that will be used
  63. by mako template"""
  64. new_ids = data['form']['account_ids'] or data['form']['chart_account_id']
  65. # Account initial balance memoizer
  66. init_balance_memoizer = {}
  67. # Reading form
  68. main_filter = self._get_form_param('filter', data, default='filter_no')
  69. target_move = self._get_form_param('target_move', data, default='all')
  70. start_date = self._get_form_param('date_from', data)
  71. stop_date = self._get_form_param('date_to', data)
  72. do_centralize = self._get_form_param('centralize', data)
  73. start_period = self.get_start_period_br(data)
  74. stop_period = self.get_end_period_br(data)
  75. fiscalyear = self.get_fiscalyear_br(data)
  76. chart_account = self._get_chart_account_id_br(data)
  77. if main_filter == 'filter_no':
  78. start_period = self.get_first_fiscalyear_period(fiscalyear)
  79. stop_period = self.get_last_fiscalyear_period(fiscalyear)
  80. # computation of ledger lines
  81. if main_filter == 'filter_date':
  82. start = start_date
  83. stop = stop_date
  84. else:
  85. start = start_period
  86. stop = stop_period
  87. initial_balance = self.is_initial_balance_enabled(main_filter)
  88. initial_balance_mode = initial_balance and self._get_initial_balance_mode(start) or False
  89. # Retrieving accounts
  90. accounts = self.get_all_accounts(new_ids, exclude_type=['view'])
  91. if initial_balance_mode == 'initial_balance':
  92. init_balance_memoizer = self._compute_initial_balances(accounts, start, fiscalyear)
  93. ledger_lines_memoizer = self._compute_account_ledger_lines(accounts, init_balance_memoizer,
  94. main_filter, target_move, start, stop)
  95. objects = []
  96. for account in self.pool.get('account.account').browse(self.cursor, self.uid, accounts):
  97. if do_centralize and account.centralized and ledger_lines_memoizer.get(account.id):
  98. account.ledger_lines = self._centralize_lines(main_filter, ledger_lines_memoizer.get(account.id, []))
  99. else:
  100. account.ledger_lines = ledger_lines_memoizer.get(account.id, [])
  101. account.init_balance = init_balance_memoizer.get(account.id, {})
  102. objects.append(account)
  103. self.localcontext.update({
  104. 'fiscalyear': fiscalyear,
  105. 'start_date': start_date,
  106. 'stop_date': stop_date,
  107. 'start_period': start_period,
  108. 'stop_period': stop_period,
  109. 'chart_account': chart_account,
  110. 'initial_balance_mode': initial_balance_mode,
  111. })
  112. return super(GeneralLedgerWebkit, self).set_context(objects, data, new_ids,
  113. report_type=report_type)
  114. def _centralize_lines(self, filter, ledger_lines, context=None):
  115. """ Group by period in filter mode 'period' or on one line in filter mode 'date'
  116. ledger_lines parameter is a list of dict built by _get_ledger_lines"""
  117. def group_lines(lines):
  118. if not lines:
  119. return {}
  120. sums = reduce(lambda line, memo: dict((key, value + memo[key]) for key, value
  121. in line.iteritems() if key in ('balance', 'debit', 'credit')), lines)
  122. res_lines = {
  123. 'balance': sums['balance'],
  124. 'debit': sums['debit'],
  125. 'credit': sums['credit'],
  126. 'lname': _('Centralized Entries'),
  127. 'account_id': lines[0]['account_id'],
  128. }
  129. return res_lines
  130. centralized_lines = []
  131. if filter == 'filter_date':
  132. # by date we centralize all entries in only one line
  133. centralized_lines.append(group_lines(ledger_lines))
  134. else: # by period
  135. # by period we centralize all entries in one line per period
  136. period_obj = self.pool.get('account.period')
  137. # we need to sort the lines per period in order to use groupby
  138. # unique ids of each used period id in lines
  139. period_ids = list(set([line['lperiod_id'] for line in ledger_lines ]))
  140. # search on account.period in order to sort them by date_start
  141. sorted_period_ids = period_obj.search(self.cr, self.uid,
  142. [('id', 'in', period_ids)],
  143. order='special desc, date_start',
  144. context=context)
  145. sorted_ledger_lines = sorted(ledger_lines, key=lambda x: sorted_period_ids.index(x['lperiod_id']))
  146. for period_id, lines_per_period_iterator in groupby(sorted_ledger_lines, itemgetter('lperiod_id')):
  147. lines_per_period = list(lines_per_period_iterator)
  148. if not lines_per_period:
  149. continue
  150. group_per_period = group_lines(lines_per_period)
  151. group_per_period.update({
  152. 'lperiod_id': period_id,
  153. 'period_code': lines_per_period[0]['period_code'], # period code is anyway the same on each line per period
  154. })
  155. centralized_lines.append(group_per_period)
  156. return centralized_lines
  157. def _compute_account_ledger_lines(self, accounts_ids, init_balance_memoizer, main_filter,
  158. target_move, start, stop):
  159. res = {}
  160. for acc_id in accounts_ids:
  161. move_line_ids = self.get_move_lines_ids(acc_id, main_filter, start, stop, target_move)
  162. if not move_line_ids:
  163. res[acc_id] = []
  164. continue
  165. lines = self._get_ledger_lines(move_line_ids, acc_id)
  166. res[acc_id] = lines
  167. return res
  168. def _get_ledger_lines(self, move_line_ids, account_id):
  169. if not move_line_ids:
  170. return []
  171. res = self._get_move_line_datas(move_line_ids)
  172. ## computing counter part is really heavy in term of ressouces consuption
  173. ## looking for a king of SQL to help me improve it
  174. move_ids = [x.get('move_id') for x in res]
  175. counter_parts = self._get_moves_counterparts(move_ids, account_id)
  176. for line in res:
  177. line['counterparts'] = counter_parts.get(line.get('move_id'), '')
  178. return res
  179. HeaderFooterTextWebKitParser('report.account.account_report_general_ledger_webkit',
  180. 'account.account',
  181. 'addons/account_financial_report_webkit/report/templates/account_report_general_ledger.mako',
  182. parser=GeneralLedgerWebkit)