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.

275 lines
15 KiB

  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Author: Guewen Baconnier
  5. # Copyright Camptocamp SA 2011
  6. # SQL inspired from OpenERP original code
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU Affero General Public License as
  10. # published by the Free Software Foundation, either version 3 of the
  11. # License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Affero General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Affero General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. ##############################################################################
  22. from collections import defaultdict
  23. from operator import add
  24. from common_balance_reports import CommonBalanceReportHeaderWebkit
  25. from common_partner_reports import CommonPartnersReportHeaderWebkit
  26. class CommonPartnerBalanceReportHeaderWebkit(CommonBalanceReportHeaderWebkit, CommonPartnersReportHeaderWebkit):
  27. """Define common helper for balance (trial balance, P&L, BS oriented financial report"""
  28. def _get_account_partners_details(self, account_by_ids, main_filter, target_move, start,
  29. stop, initial_balance_mode, partner_filter_ids=False):
  30. res = {}
  31. filter_from = False
  32. if main_filter in ('filter_period', 'filter_no', 'filter_opening'):
  33. filter_from = 'period'
  34. elif main_filter == 'filter_date':
  35. filter_from = 'date'
  36. partners_init_balances_by_ids = {}
  37. for account_id, account_details in account_by_ids.iteritems():
  38. partners_init_balances_by_ids.update(self._get_partners_initial_balances(account_id,
  39. start,
  40. initial_balance_mode,
  41. partner_filter_ids=partner_filter_ids,
  42. exclude_reconcile=False)) # we'll never exclude reconciled entries in the legal reports
  43. opening_mode = 'exclude_opening'
  44. if main_filter == 'filter_opening':
  45. opening_mode = 'include_opening'
  46. # get credit and debit for partner
  47. details = self._get_partners_totals_account(filter_from,
  48. account_id,
  49. start,
  50. stop,
  51. target_move,
  52. partner_filter_ids=partner_filter_ids,
  53. mode=opening_mode)
  54. # merge initial balances in partner details
  55. if partners_init_balances_by_ids.get(account_id):
  56. for partner_id, initial_balances in partners_init_balances_by_ids[account_id].iteritems():
  57. if initial_balances.get('init_balance'):
  58. details[partner_id].update({'init_balance': initial_balances['init_balance']})
  59. # compute balance for the partner
  60. for partner_id, partner_details in details.iteritems():
  61. details[partner_id]['balance'] = details[partner_id].get('init_balance', 0.0) +\
  62. details[partner_id].get('debit', 0.0) -\
  63. details[partner_id].get('credit', 0.0)
  64. res[account_id] = details
  65. return res
  66. def _get_partners_initial_balances(self, account_ids, start_period, initial_balance_mode, partner_filter_ids=None, exclude_reconcile=False):
  67. # we get the initial balance from the opening period (opening_balance) when the opening period is included in the start period and
  68. # when there is at least one entry in the opening period. Otherwise we compute it from previous periods
  69. if initial_balance_mode == 'opening_balance':
  70. opening_period_selected = self.get_included_opening_period(start_period)
  71. res = self._compute_partners_initial_balances(account_ids, start_period, partner_filter_ids, force_period_ids=opening_period_selected, exclude_reconcile=exclude_reconcile)
  72. elif initial_balance_mode == 'initial_balance':
  73. res = self._compute_partners_initial_balances(account_ids, start_period, partner_filter_ids, exclude_reconcile=exclude_reconcile)
  74. else:
  75. res = {}
  76. return res
  77. def _get_partners_totals_account(self, filter_from, account_id, start, stop, target_move, partner_filter_ids=None, mode='exclude_opening'):
  78. final_res = defaultdict(dict)
  79. sql_select = """
  80. SELECT account_move_line.partner_id,
  81. sum(account_move_line.debit) AS debit,
  82. sum(account_move_line.credit) AS credit
  83. FROM account_move_line"""
  84. sql_joins = ''
  85. sql_where = "WHERE account_move_line.account_id = %(account_id)s AND account_move_line.state = 'valid' "
  86. sql_conditions, search_params = getattr(self, '_get_query_params_from_'+filter_from+'s')(start, stop, mode=mode)
  87. sql_where += sql_conditions
  88. if partner_filter_ids:
  89. sql_where += " AND account_move_line.partner_id in %(partner_ids)s"
  90. search_params.update({'partner_ids': tuple(partner_filter_ids),})
  91. if target_move == 'posted':
  92. sql_joins += "INNER JOIN account_move ON account_move_line.move_id = account_move.id"
  93. sql_where += " AND account_move.state = %(target_move)s"
  94. search_params.update({'target_move': target_move,})
  95. sql_groupby = "GROUP BY account_move_line.partner_id"
  96. search_params.update({'account_id': account_id,})
  97. query = ' '.join((sql_select, sql_joins, sql_where, sql_groupby))
  98. self.cursor.execute(query, search_params)
  99. res = self.cursor.dictfetchall()
  100. if res:
  101. for row in res:
  102. final_res[row['partner_id']] = row
  103. return final_res
  104. def _get_filter_type(self, result_selection):
  105. filter_type = ('payable', 'receivable')
  106. if result_selection == 'customer':
  107. filter_type = ('receivable',)
  108. if result_selection == 'supplier':
  109. filter_type = ('payable',)
  110. return filter_type
  111. def _get_partners_comparison_details(self, data, account_ids, target_move, comparison_filter, index, partner_filter_ids=False):
  112. """
  113. @param data: data of the wizard form
  114. @param account_ids: ids of the accounts to get details
  115. @param comparison_filter: selected filter on the form for the comparison (filter_no, filter_year, filter_period, filter_date)
  116. @param index: index of the fields to get (ie. comp1_fiscalyear_id where 1 is the index)
  117. @param partner_filter_ids: list of ids of partners to select
  118. @return: dict of account details (key = account id)
  119. """
  120. fiscalyear = self._get_info(data, "comp%s_fiscalyear_id" % (index,), 'account.fiscalyear')
  121. start_period = self._get_info(data, "comp%s_period_from" % (index,), 'account.period')
  122. stop_period = self._get_info(data, "comp%s_period_to" % (index,), 'account.period')
  123. start_date = self._get_form_param("comp%s_date_from" % (index,), data)
  124. stop_date = self._get_form_param("comp%s_date_to" % (index,), data)
  125. init_balance = self.is_initial_balance_enabled(comparison_filter)
  126. comp_params = {}
  127. accounts_details_by_ids = defaultdict(dict)
  128. if comparison_filter != 'filter_no':
  129. start_period, stop_period, start, stop = \
  130. self._get_start_stop_for_filter(comparison_filter, fiscalyear, start_date, stop_date, start_period, stop_period)
  131. details_filter = comparison_filter
  132. if comparison_filter == 'filter_year':
  133. details_filter = 'filter_no'
  134. initial_balance_mode = init_balance and self._get_initial_balance_mode(start) or False
  135. accounts_by_ids = self._get_account_details(account_ids, target_move, fiscalyear, details_filter, start, stop, initial_balance_mode)
  136. partner_details_by_ids = self._get_account_partners_details(accounts_by_ids, details_filter,
  137. target_move, start, stop, initial_balance_mode,
  138. partner_filter_ids=partner_filter_ids)
  139. for account_id in account_ids:
  140. accounts_details_by_ids[account_id]['account'] = accounts_by_ids[account_id]
  141. accounts_details_by_ids[account_id]['partners_amounts'] = partner_details_by_ids[account_id]
  142. comp_params = {
  143. 'comparison_filter': comparison_filter,
  144. 'fiscalyear': fiscalyear,
  145. 'start': start,
  146. 'stop': stop,
  147. 'initial_balance_mode': initial_balance_mode,
  148. }
  149. return accounts_details_by_ids, comp_params
  150. def compute_partner_balance_data(self, data, filter_report_type=None):
  151. new_ids = data['form']['account_ids'] or data['form']['chart_account_id']
  152. max_comparison = self._get_form_param('max_comparison', data, default=0)
  153. main_filter = self._get_form_param('filter', data, default='filter_no')
  154. comp_filters, nb_comparisons, comparison_mode = self._comp_filters(data, max_comparison)
  155. fiscalyear = self.get_fiscalyear_br(data)
  156. start_period = self.get_start_period_br(data)
  157. stop_period = self.get_end_period_br(data)
  158. target_move = self._get_form_param('target_move', data, default='all')
  159. start_date = self._get_form_param('date_from', data)
  160. stop_date = self._get_form_param('date_to', data)
  161. chart_account = self._get_chart_account_id_br(data)
  162. result_selection = self._get_form_param('result_selection', data)
  163. partner_ids = self._get_form_param('partner_ids', data)
  164. filter_type = self._get_filter_type(result_selection)
  165. start_period, stop_period, start, stop = \
  166. self._get_start_stop_for_filter(main_filter, fiscalyear, start_date, stop_date, start_period, stop_period)
  167. initial_balance = self.is_initial_balance_enabled(main_filter)
  168. initial_balance_mode = initial_balance and self._get_initial_balance_mode(start) or False
  169. # Retrieving accounts
  170. account_ids = self.get_all_accounts(new_ids, only_type=filter_type,
  171. filter_report_type=filter_report_type)
  172. # get details for each accounts, total of debit / credit / balance
  173. accounts_by_ids = self._get_account_details(account_ids, target_move, fiscalyear, main_filter, start, stop, initial_balance_mode)
  174. partner_details_by_ids = self._get_account_partners_details(accounts_by_ids,
  175. main_filter,
  176. target_move,
  177. start,
  178. stop,
  179. initial_balance_mode,
  180. partner_filter_ids=partner_ids)
  181. comparison_params = []
  182. comp_accounts_by_ids = []
  183. for index in range(max_comparison):
  184. if comp_filters[index] != 'filter_no':
  185. comparison_result, comp_params = self._get_partners_comparison_details(data, account_ids,
  186. target_move, comp_filters[index],
  187. index, partner_filter_ids=partner_ids)
  188. comparison_params.append(comp_params)
  189. comp_accounts_by_ids.append(comparison_result)
  190. objects = []
  191. for account in self.pool.get('account.account').browse(self.cursor, self.uid, account_ids):
  192. if not account.parent_id: # hide top level account
  193. continue
  194. account.debit = accounts_by_ids[account.id]['debit']
  195. account.credit = accounts_by_ids[account.id]['credit']
  196. account.balance = accounts_by_ids[account.id]['balance']
  197. account.init_balance = accounts_by_ids[account.id].get('init_balance', 0.0)
  198. account.partners_amounts = partner_details_by_ids[account.id]
  199. comp_accounts = []
  200. for comp_account_by_id in comp_accounts_by_ids:
  201. values = comp_account_by_id.get(account.id)
  202. values['account'].update(self._get_diff(account.balance, values['account'].get('balance', 0.0)))
  203. comp_accounts.append(values)
  204. for partner_id, partner_values in values['partners_amounts'].copy().iteritems():
  205. base_partner_balance = account.partners_amounts[partner_id]['balance'] if \
  206. account.partners_amounts.get(partner_id) else 0.0
  207. partner_values.update(self._get_diff(base_partner_balance,
  208. partner_values.get('balance', 0.0)))
  209. values['partners_amounts'][partner_id].update(partner_values)
  210. account.comparisons = comp_accounts
  211. all_partner_ids = reduce(add, [comp['partners_amounts'].keys() for comp in comp_accounts],
  212. account.partners_amounts.keys())
  213. account.partners_order = self._order_partners(all_partner_ids)
  214. objects.append(account)
  215. context_report_values = {
  216. 'fiscalyear': fiscalyear,
  217. 'start_date': start_date,
  218. 'stop_date': stop_date,
  219. 'start_period': start_period,
  220. 'stop_period': stop_period,
  221. 'chart_account': chart_account,
  222. 'comparison_mode': comparison_mode,
  223. 'nb_comparison': nb_comparisons,
  224. 'comp_params': comparison_params,
  225. 'initial_balance_mode': initial_balance_mode,
  226. 'compute_diff': self._get_diff,
  227. }
  228. return objects, new_ids, context_report_values