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.

259 lines
11 KiB

11 years ago
  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 collections import defaultdict
  22. from datetime import datetime
  23. from itertools import groupby
  24. from operator import itemgetter
  25. from mako.template import Template
  26. import openerp.addons
  27. from openerp import pooler
  28. from openerp.osv import osv
  29. from openerp.report import report_sxw
  30. from openerp.tools.translate import _
  31. from openerp.addons.report_webkit import report_helper
  32. from .common_partner_reports import CommonPartnersReportHeaderWebkit
  33. from .webkit_parser_header_fix import HeaderFooterTextWebKitParser
  34. def get_mako_template(obj, *args):
  35. template_path = openerp.addons.get_module_resource(*args)
  36. return Template(filename=template_path, input_encoding='utf-8')
  37. report_helper.WebKitHelper.get_mako_template = get_mako_template
  38. class PartnersOpenInvoicesWebkit(report_sxw.rml_parse,
  39. CommonPartnersReportHeaderWebkit):
  40. def __init__(self, cursor, uid, name, context):
  41. super(PartnersOpenInvoicesWebkit, self).__init__(
  42. cursor, uid, name, context=context)
  43. self.pool = pooler.get_pool(self.cr.dbname)
  44. self.cursor = self.cr
  45. company = self.pool.get('res.users').browse(
  46. self.cr, uid, uid, context=context).company_id
  47. header_report_name = ' - '.join((_('OPEN INVOICES REPORT'),
  48. company.name,
  49. company.currency_id.name))
  50. footer_date_time = self.formatLang(
  51. str(datetime.today()), date_time=True)
  52. self.localcontext.update({
  53. 'cr': cursor,
  54. 'uid': uid,
  55. 'report_name': _('Open Invoices Report'),
  56. 'display_account_raw': self._get_display_account_raw,
  57. 'filter_form': self._get_filter,
  58. 'target_move': self._get_target_move,
  59. 'amount_currency': self._get_amount_currency,
  60. 'display_partner_account': self._get_display_partner_account,
  61. 'display_target_move': self._get_display_target_move,
  62. 'additional_args': [
  63. ('--header-font-name', 'Helvetica'),
  64. ('--footer-font-name', 'Helvetica'),
  65. ('--header-font-size', '10'),
  66. ('--footer-font-size', '6'),
  67. ('--header-left', header_report_name),
  68. ('--header-spacing', '2'),
  69. ('--footer-left', footer_date_time),
  70. ('--footer-right',
  71. ' '.join((_('Page'), '[page]', _('of'), '[topage]'))),
  72. ('--footer-line',),
  73. ],
  74. })
  75. def _group_lines_by_currency(self, account_br):
  76. account_br.grouped_ledger_lines = {}
  77. if not account_br.ledger_lines:
  78. return
  79. for part_id, plane_lines in account_br.ledger_lines.items():
  80. account_br.grouped_ledger_lines[part_id] = []
  81. plane_lines.sort(key=itemgetter('currency_code'))
  82. for curr, lines in groupby(plane_lines,
  83. key=itemgetter('currency_code')):
  84. tmp = [x for x in lines]
  85. account_br.grouped_ledger_lines[part_id].append(
  86. (curr, tmp)) # I want to reiter many times
  87. def set_context(self, objects, data, ids, report_type=None):
  88. """Populate a ledger_lines attribute on each browse record that will
  89. be used by mako template"""
  90. new_ids = data['form']['chart_account_id']
  91. # Account initial balance memoizer
  92. init_balance_memoizer = {}
  93. # Reading form
  94. main_filter = self._get_form_param('filter', data, default='filter_no')
  95. target_move = self._get_form_param('target_move', data, default='all')
  96. start_date = self._get_form_param('date_from', data)
  97. stop_date = self._get_form_param('date_to', data)
  98. start_period = self.get_start_period_br(data)
  99. stop_period = self.get_end_period_br(data)
  100. fiscalyear = self.get_fiscalyear_br(data)
  101. partner_ids = self._get_form_param('partner_ids', data)
  102. result_selection = self._get_form_param('result_selection', data)
  103. date_until = self._get_form_param('until_date', data)
  104. chart_account = self._get_chart_account_id_br(data)
  105. group_by_currency = self._get_form_param('group_by_currency', data)
  106. if main_filter == 'filter_no' and fiscalyear:
  107. start_period = self.get_first_fiscalyear_period(fiscalyear)
  108. stop_period = self.get_last_fiscalyear_period(fiscalyear)
  109. # Retrieving accounts
  110. filter_type = ('payable', 'receivable')
  111. if result_selection == 'customer':
  112. filter_type = ('receivable',)
  113. if result_selection == 'supplier':
  114. filter_type = ('payable',)
  115. account_ids = self.get_all_accounts(
  116. new_ids, exclude_type=['view'], only_type=filter_type)
  117. if not account_ids:
  118. raise osv.except_osv(_('Error'), _('No accounts to print.'))
  119. # computation of ledeger lines
  120. if main_filter == 'filter_date':
  121. start = start_date
  122. stop = stop_date
  123. else:
  124. start = start_period
  125. stop = stop_period
  126. ledger_lines_memoizer = self._compute_open_transactions_lines(
  127. account_ids, main_filter, target_move, start, stop, date_until,
  128. partner_filter=partner_ids)
  129. objects = []
  130. for account in self.pool.get('account.account').browse(self.cursor,
  131. self.uid,
  132. account_ids):
  133. account.ledger_lines = ledger_lines_memoizer.get(account.id, {})
  134. account.init_balance = init_balance_memoizer.get(account.id, {})
  135. # we have to compute partner order based on inital balance
  136. # and ledger line as we may have partner with init bal
  137. # that are not in ledger line and vice versa
  138. ledg_lines_pids = ledger_lines_memoizer.get(account.id, {}).keys()
  139. non_null_init_balances = dict([
  140. (ib, amounts) for ib, amounts
  141. in account.init_balance.iteritems()
  142. if amounts['init_balance']
  143. or amounts['init_balance_currency']])
  144. init_bal_lines_pids = non_null_init_balances.keys()
  145. account.partners_order = self._order_partners(
  146. ledg_lines_pids, init_bal_lines_pids)
  147. account.ledger_lines = ledger_lines_memoizer.get(account.id, {})
  148. if group_by_currency:
  149. self._group_lines_by_currency(account)
  150. objects.append(account)
  151. self.localcontext.update({
  152. 'fiscalyear': fiscalyear,
  153. 'start_date': start_date,
  154. 'stop_date': stop_date,
  155. 'start_period': start_period,
  156. 'stop_period': stop_period,
  157. 'date_until': date_until,
  158. 'partner_ids': partner_ids,
  159. 'chart_account': chart_account,
  160. })
  161. return super(PartnersOpenInvoicesWebkit, self).set_context(
  162. objects, data, new_ids, report_type=report_type)
  163. def _compute_open_transactions_lines(self, accounts_ids, main_filter,
  164. target_move, start, stop,
  165. date_until=False,
  166. partner_filter=False):
  167. res = defaultdict(dict)
  168. # we check if until date and date stop have the same value
  169. if main_filter in ('filter_period', 'filter_no'):
  170. date_stop = stop.date_stop
  171. date_until_match = (date_stop == date_until)
  172. elif main_filter == 'filter_date':
  173. date_stop = stop
  174. date_until_match = (stop == date_until)
  175. else:
  176. raise osv.except_osv(_('Unsuported filter'),
  177. _('Filter has to be in filter date, period, \
  178. or none'))
  179. initial_move_lines_per_account = {}
  180. if main_filter in ('filter_period', 'filter_no'):
  181. initial_move_lines_per_account = self._tree_move_line_ids(
  182. self._partners_initial_balance_line_ids(accounts_ids,
  183. start,
  184. partner_filter,
  185. exclude_reconcile=True,
  186. force_period_ids=False,
  187. date_stop=date_stop),
  188. key='id')
  189. for account_id in accounts_ids:
  190. initial_move_lines_ids_per_partner = \
  191. initial_move_lines_per_account.get(account_id, {})
  192. # We get the move line ids of the account
  193. move_line_ids_per_partner = self.get_partners_move_lines_ids(
  194. account_id, main_filter, start, stop, target_move,
  195. exclude_reconcile=True, partner_filter=partner_filter)
  196. if not initial_move_lines_ids_per_partner \
  197. and not move_line_ids_per_partner:
  198. continue
  199. for partner_id in list(
  200. set(initial_move_lines_ids_per_partner.keys() +
  201. move_line_ids_per_partner.keys())):
  202. partner_line_ids = (
  203. move_line_ids_per_partner.get(partner_id, []) +
  204. initial_move_lines_ids_per_partner.get(partner_id, []))
  205. clearance_line_ids = []
  206. if date_until and not date_until_match and partner_line_ids:
  207. clearance_line_ids = self._get_clearance_move_line_ids(
  208. partner_line_ids, date_stop, date_until)
  209. partner_line_ids += clearance_line_ids
  210. lines = self._get_move_line_datas(list(set(partner_line_ids)))
  211. for line in lines:
  212. if line['id'] in initial_move_lines_ids_per_partner.\
  213. get(partner_id, []):
  214. line['is_from_previous_periods'] = True
  215. if line['id'] in clearance_line_ids:
  216. line['is_clearance_line'] = True
  217. res[account_id][partner_id] = lines
  218. return res
  219. HeaderFooterTextWebKitParser(
  220. 'report.account.account_report_open_invoices_webkit',
  221. 'account.account',
  222. 'addons/account_financial_report_webkit/report/templates/\
  223. account_report_open_invoices.mako',
  224. parser=PartnersOpenInvoicesWebkit)