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.

213 lines
9.8 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. elif initial_balance_mode == 'opening_balance':
  94. init_balance_memoizer = self._read_opening_balance(accounts, start)
  95. ledger_lines_memoizer = self._compute_account_ledger_lines(accounts, init_balance_memoizer,
  96. main_filter, target_move, start, stop)
  97. objects = []
  98. for account in self.pool.get('account.account').browse(self.cursor, self.uid, accounts):
  99. if do_centralize and account.centralized and ledger_lines_memoizer.get(account.id):
  100. account.ledger_lines = self._centralize_lines(main_filter, ledger_lines_memoizer.get(account.id, []))
  101. else:
  102. account.ledger_lines = ledger_lines_memoizer.get(account.id, [])
  103. account.init_balance = init_balance_memoizer.get(account.id, {})
  104. objects.append(account)
  105. self.localcontext.update({
  106. 'fiscalyear': fiscalyear,
  107. 'start_date': start_date,
  108. 'stop_date': stop_date,
  109. 'start_period': start_period,
  110. 'stop_period': stop_period,
  111. 'chart_account': chart_account,
  112. 'initial_balance_mode': initial_balance_mode,
  113. })
  114. return super(GeneralLedgerWebkit, self).set_context(objects, data, new_ids,
  115. report_type=report_type)
  116. def _centralize_lines(self, filter, ledger_lines, context=None):
  117. """ Group by period in filter mode 'period' or on one line in filter mode 'date'
  118. ledger_lines parameter is a list of dict built by _get_ledger_lines"""
  119. def group_lines(lines):
  120. if not lines:
  121. return {}
  122. sums = reduce(lambda line, memo: dict((key, value + memo[key]) for key, value
  123. in line.iteritems() if key in ('balance', 'debit', 'credit')), lines)
  124. res_lines = {
  125. 'balance': sums['balance'],
  126. 'debit': sums['debit'],
  127. 'credit': sums['credit'],
  128. 'lname': _('Centralized Entries'),
  129. 'account_id': lines[0]['account_id'],
  130. }
  131. return res_lines
  132. centralized_lines = []
  133. if filter == 'filter_date':
  134. # by date we centralize all entries in only one line
  135. centralized_lines.append(group_lines(ledger_lines))
  136. else: # by period
  137. # by period we centralize all entries in one line per period
  138. period_obj = self.pool.get('account.period')
  139. # we need to sort the lines per period in order to use groupby
  140. # unique ids of each used period id in lines
  141. period_ids = list(set([line['lperiod_id'] for line in ledger_lines ]))
  142. # search on account.period in order to sort them by date_start
  143. sorted_period_ids = period_obj.search(self.cr, self.uid,
  144. [('id', 'in', period_ids)],
  145. order='special desc, date_start',
  146. context=context)
  147. sorted_ledger_lines = sorted(ledger_lines, key=lambda x: sorted_period_ids.index(x['lperiod_id']))
  148. for period_id, lines_per_period_iterator in groupby(sorted_ledger_lines, itemgetter('lperiod_id')):
  149. lines_per_period = list(lines_per_period_iterator)
  150. if not lines_per_period:
  151. continue
  152. group_per_period = group_lines(lines_per_period)
  153. group_per_period.update({
  154. 'lperiod_id': period_id,
  155. 'period_code': lines_per_period[0]['period_code'], # period code is anyway the same on each line per period
  156. })
  157. centralized_lines.append(group_per_period)
  158. return centralized_lines
  159. def _compute_account_ledger_lines(self, accounts_ids, init_balance_memoizer, main_filter,
  160. target_move, start, stop):
  161. res = {}
  162. for acc_id in accounts_ids:
  163. move_line_ids = self.get_move_lines_ids(acc_id, main_filter, start, stop, target_move)
  164. if not move_line_ids:
  165. res[acc_id] = []
  166. continue
  167. lines = self._get_ledger_lines(move_line_ids, acc_id)
  168. res[acc_id] = lines
  169. return res
  170. def _get_ledger_lines(self, move_line_ids, account_id):
  171. if not move_line_ids:
  172. return []
  173. res = self._get_move_line_datas(move_line_ids)
  174. ## computing counter part is really heavy in term of ressouces consuption
  175. ## looking for a king of SQL to help me improve it
  176. move_ids = [x.get('move_id') for x in res]
  177. counter_parts = self._get_moves_counterparts(move_ids, account_id)
  178. for line in res:
  179. line['counterparts'] = counter_parts.get(line.get('move_id'), '')
  180. return res
  181. HeaderFooterTextWebKitParser('report.account.account_report_general_ledger_webkit',
  182. 'account.account',
  183. 'addons/account_financial_report_webkit/report/templates/account_report_general_ledger.mako',
  184. parser=GeneralLedgerWebkit)