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.

270 lines
12 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. from openerp.modules.registry import RegistryManager
  27. from openerp.osv import osv
  28. from openerp.report import report_sxw
  29. from openerp.tools.translate import _
  30. from openerp.addons.report_webkit import report_helper
  31. from .common_partner_reports import CommonPartnersReportHeaderWebkit
  32. from .webkit_parser_header_fix import HeaderFooterTextWebKitParser
  33. from openerp.modules.module import get_module_resource
  34. def get_mako_template(obj, *args):
  35. template_path = 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 = RegistryManager.get(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, ledger_lines):
  76. account_br.grouped_ledger_lines = {}
  77. if not ledger_lines:
  78. return
  79. for part_id, plane_lines in 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_special_period()
  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 = self.pool.get('account.account').browse(self.cursor,
  130. self.uid,
  131. account_ids)
  132. ledger_lines = {}
  133. init_balance = {}
  134. partners_order = {}
  135. for account in objects:
  136. ledger_lines[account.id] = ledger_lines_memoizer.get(account.id,
  137. {})
  138. init_balance[account.id] = init_balance_memoizer.get(account.id,
  139. {})
  140. # we have to compute partner order based on inital balance
  141. # and ledger line as we may have partner with init bal
  142. # that are not in ledger line and vice versa
  143. ledg_lines_pids = ledger_lines_memoizer.get(account.id, {}).keys()
  144. non_null_init_balances = dict([
  145. (ib, amounts) for ib, amounts
  146. in init_balance[account.id].iteritems()
  147. if amounts['init_balance'] or
  148. amounts['init_balance_currency']])
  149. init_bal_lines_pids = non_null_init_balances.keys()
  150. partners_order[account.id] = self._order_partners(
  151. ledg_lines_pids, init_bal_lines_pids)
  152. ledger_lines[account.id] = ledger_lines_memoizer.get(account.id,
  153. {})
  154. if group_by_currency:
  155. self._group_lines_by_currency(
  156. account, ledger_lines[account.id])
  157. self.localcontext.update({
  158. 'fiscalyear': fiscalyear,
  159. 'start_date': start_date,
  160. 'stop_date': stop_date,
  161. 'start_period': start_period,
  162. 'stop_period': stop_period,
  163. 'date_until': date_until,
  164. 'partner_ids': partner_ids,
  165. 'chart_account': chart_account,
  166. 'ledger_lines': ledger_lines,
  167. 'init_balance': init_balance,
  168. 'partners_order': partners_order
  169. })
  170. return super(PartnersOpenInvoicesWebkit, self).set_context(
  171. objects, data, new_ids, report_type=report_type)
  172. def _compute_open_transactions_lines(self, accounts_ids, main_filter,
  173. target_move, start, stop,
  174. date_until=False,
  175. partner_filter=False):
  176. res = defaultdict(dict)
  177. # we check if until date and date stop have the same value
  178. if main_filter in ('filter_period', 'filter_no'):
  179. date_stop = stop.date_stop
  180. date_until_match = (date_stop == date_until)
  181. elif main_filter == 'filter_date':
  182. date_stop = stop
  183. date_until_match = (stop == date_until)
  184. else:
  185. raise osv.except_osv(_('Unsuported filter'),
  186. _('Filter has to be in filter date, period, \
  187. or none'))
  188. initial_move_lines_per_account = {}
  189. if main_filter in ('filter_period', 'filter_no'):
  190. initial_move_lines_per_account = self._tree_move_line_ids(
  191. self._partners_initial_balance_line_ids(accounts_ids,
  192. start,
  193. partner_filter,
  194. exclude_reconcile=True,
  195. force_period_ids=False,
  196. date_stop=date_stop),
  197. key='id')
  198. for account_id in accounts_ids:
  199. initial_move_lines_ids_per_partner = \
  200. initial_move_lines_per_account.get(account_id, {})
  201. # We get the move line ids of the account
  202. move_line_ids_per_partner = self.get_partners_move_lines_ids(
  203. account_id, main_filter, start, stop, target_move,
  204. exclude_reconcile=True, partner_filter=partner_filter)
  205. if not initial_move_lines_ids_per_partner \
  206. and not move_line_ids_per_partner:
  207. continue
  208. for partner_id in list(
  209. set(initial_move_lines_ids_per_partner.keys() +
  210. move_line_ids_per_partner.keys())):
  211. partner_line_ids = (
  212. move_line_ids_per_partner.get(partner_id, []) +
  213. initial_move_lines_ids_per_partner.get(partner_id, []))
  214. clearance_line_ids = []
  215. if date_until and not date_until_match and partner_line_ids:
  216. clearance_line_ids = self._get_clearance_move_line_ids(
  217. partner_line_ids, date_stop, date_until)
  218. partner_line_ids += clearance_line_ids
  219. lines = self._get_move_line_datas(list(set(partner_line_ids)))
  220. for line in lines:
  221. if line['id'] in initial_move_lines_ids_per_partner.\
  222. get(partner_id, []):
  223. line['is_from_previous_periods'] = True
  224. if line['id'] in clearance_line_ids:
  225. line['is_clearance_line'] = True
  226. res[account_id][partner_id] = lines
  227. return res
  228. HeaderFooterTextWebKitParser(
  229. 'report.account.account_report_open_invoices_webkit',
  230. 'account.account',
  231. 'addons/account_financial_report_webkit/report/templates/\
  232. account_report_open_invoices.mako',
  233. parser=PartnersOpenInvoicesWebkit)