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.

339 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 operator import add
  23. from .common_reports import CommonReportHeaderWebkit
  24. class CommonBalanceReportHeaderWebkit(CommonReportHeaderWebkit):
  25. """Define common helper for balance (trial balance, P&L, BS oriented
  26. financial report"""
  27. def _get_numbers_display(self, data):
  28. return self._get_form_param('numbers_display', data)
  29. @staticmethod
  30. def find_key_by_value_in_list(dic, value):
  31. return [key for key, val in dic.iteritems() if value in val][0]
  32. def _get_account_details(self, account_ids, target_move, fiscalyear,
  33. main_filter, start, stop, initial_balance_mode,
  34. context=None):
  35. """
  36. Get details of accounts to display on the report
  37. @param account_ids: ids of accounts to get details
  38. @param target_move: selection filter for moves (all or posted)
  39. @param fiscalyear: browse of the fiscalyear
  40. @param main_filter: selection filter period / date or none
  41. @param start: start date or start period browse instance
  42. @param stop: stop date or stop period browse instance
  43. @param initial_balance_mode: False: no calculation,
  44. 'opening_balance': from the opening period,
  45. 'initial_balance': computed from previous year / periods
  46. @return: dict of list containing accounts details, keys are
  47. the account ids
  48. """
  49. if context is None:
  50. context = {}
  51. account_obj = self.pool.get('account.account')
  52. period_obj = self.pool.get('account.period')
  53. use_period_ids = main_filter in (
  54. 'filter_no', 'filter_period', 'filter_opening')
  55. if use_period_ids:
  56. if main_filter == 'filter_opening':
  57. period_ids = [start.id]
  58. else:
  59. period_ids = period_obj.build_ctx_periods(
  60. self.cursor, self.uid, start.id, stop.id)
  61. # never include the opening in the debit / credit amounts
  62. period_ids = self.exclude_opening_periods(period_ids)
  63. init_balance = False
  64. if initial_balance_mode == 'opening_balance':
  65. init_balance = self._read_opening_balance(account_ids, start)
  66. elif initial_balance_mode:
  67. init_balance = self._compute_initial_balances(
  68. account_ids, start, fiscalyear)
  69. ctx = context.copy()
  70. ctx.update({'state': target_move,
  71. 'all_fiscalyear': True})
  72. if use_period_ids:
  73. ctx.update({'periods': period_ids})
  74. elif main_filter == 'filter_date':
  75. ctx.update({'date_from': start,
  76. 'date_to': stop})
  77. accounts = account_obj.read(
  78. self.cursor,
  79. self.uid,
  80. account_ids,
  81. ['type', 'code', 'name', 'debit', 'credit',
  82. 'balance', 'parent_id', 'level', 'child_id'],
  83. ctx)
  84. accounts_by_id = {}
  85. for account in accounts:
  86. if init_balance:
  87. # sum for top level views accounts
  88. child_ids = account_obj._get_children_and_consol(
  89. self.cursor, self.uid, account['id'], ctx)
  90. if child_ids:
  91. child_init_balances = [
  92. init_bal['init_balance']
  93. for acnt_id, init_bal in init_balance.iteritems()
  94. if acnt_id in child_ids]
  95. top_init_balance = reduce(add, child_init_balances)
  96. account['init_balance'] = top_init_balance
  97. else:
  98. account.update(init_balance[account['id']])
  99. account['balance'] = account['init_balance'] + \
  100. account['debit'] - account['credit']
  101. accounts_by_id[account['id']] = account
  102. return accounts_by_id
  103. def _get_comparison_details(self, data, account_ids, target_move,
  104. comparison_filter, index):
  105. """
  106. @param data: data of the wizard form
  107. @param account_ids: ids of the accounts to get details
  108. @param comparison_filter: selected filter on the form for
  109. the comparison (filter_no, filter_year, filter_period,
  110. filter_date)
  111. @param index: index of the fields to get
  112. (ie. comp1_fiscalyear_id where 1 is the index)
  113. @return: dict of account details (key = account id)
  114. """
  115. fiscalyear = self._get_info(
  116. data, "comp%s_fiscalyear_id" % (index,), 'account.fiscalyear')
  117. start_period = self._get_info(
  118. data, "comp%s_period_from" % (index,), 'account.period')
  119. stop_period = self._get_info(
  120. data, "comp%s_period_to" % (index,), 'account.period')
  121. start_date = self._get_form_param("comp%s_date_from" % (index,), data)
  122. stop_date = self._get_form_param("comp%s_date_to" % (index,), data)
  123. init_balance = self.is_initial_balance_enabled(comparison_filter)
  124. accounts_by_ids = {}
  125. comp_params = {}
  126. details_filter = comparison_filter
  127. if comparison_filter != 'filter_no':
  128. start_period, stop_period, start, stop = \
  129. self._get_start_stop_for_filter(
  130. comparison_filter, fiscalyear, start_date, stop_date,
  131. start_period, stop_period)
  132. if comparison_filter == 'filter_year':
  133. details_filter = 'filter_no'
  134. initial_balance_mode = init_balance \
  135. and self._get_initial_balance_mode(start) or False
  136. accounts_by_ids = self._get_account_details(
  137. account_ids, target_move, fiscalyear, details_filter,
  138. start, stop, initial_balance_mode)
  139. comp_params = {
  140. 'comparison_filter': comparison_filter,
  141. 'fiscalyear': fiscalyear,
  142. 'start': start,
  143. 'stop': stop,
  144. 'initial_balance': init_balance,
  145. 'initial_balance_mode': initial_balance_mode,
  146. }
  147. return accounts_by_ids, comp_params
  148. def _get_diff(self, balance, previous_balance):
  149. """
  150. @param balance: current balance
  151. @param previous_balance: last balance
  152. @return: dict of form {'diff': difference,
  153. 'percent_diff': diff in percentage}
  154. """
  155. diff = balance - previous_balance
  156. obj_precision = self.pool.get('decimal.precision')
  157. precision = obj_precision.precision_get(
  158. self.cursor, self.uid, 'Account')
  159. # round previous balance with account precision to avoid big numbers
  160. # if previous balance is 0.0000001 or a any very small number
  161. if round(previous_balance, precision) == 0:
  162. percent_diff = False
  163. else:
  164. percent_diff = round(diff / previous_balance * 100, precision)
  165. return {'diff': diff, 'percent_diff': percent_diff}
  166. def _comp_filters(self, data, comparison_number):
  167. """
  168. @param data: data of the report
  169. @param comparison_number: number of comparisons
  170. @return: list of comparison filters, nb of comparisons used and
  171. comparison mode (no_comparison, single, multiple)
  172. """
  173. comp_filters = []
  174. for index in range(comparison_number):
  175. comp_filters.append(
  176. self._get_form_param("comp%s_filter" % (index,), data,
  177. default='filter_no'))
  178. nb_comparisons = len(
  179. [comp_filter for comp_filter in comp_filters
  180. if comp_filter != 'filter_no'])
  181. if not nb_comparisons:
  182. comparison_mode = 'no_comparison'
  183. elif nb_comparisons > 1:
  184. comparison_mode = 'multiple'
  185. else:
  186. comparison_mode = 'single'
  187. return comp_filters, nb_comparisons, comparison_mode
  188. def _get_start_stop_for_filter(self, main_filter, fiscalyear, start_date,
  189. stop_date, start_period, stop_period):
  190. if main_filter in ('filter_no', 'filter_year'):
  191. start_period = self.get_first_fiscalyear_period(fiscalyear)
  192. stop_period = self.get_last_fiscalyear_period(fiscalyear)
  193. elif main_filter == 'filter_opening':
  194. opening_period = self._get_st_fiscalyear_period(
  195. fiscalyear, special=True)
  196. start_period = stop_period = opening_period
  197. if main_filter == 'filter_date':
  198. start = start_date
  199. stop = stop_date
  200. else:
  201. start = start_period
  202. stop = stop_period
  203. return start_period, stop_period, start, stop
  204. def compute_balance_data(self, data, filter_report_type=None):
  205. new_ids = data['form']['account_ids'] or data[
  206. 'form']['chart_account_id']
  207. max_comparison = self._get_form_param(
  208. 'max_comparison', data, default=0)
  209. main_filter = self._get_form_param('filter', data, default='filter_no')
  210. comp_filters, nb_comparisons, comparison_mode = self._comp_filters(
  211. data, max_comparison)
  212. fiscalyear = self.get_fiscalyear_br(data)
  213. start_period = self.get_start_period_br(data)
  214. stop_period = self.get_end_period_br(data)
  215. target_move = self._get_form_param('target_move', data, default='all')
  216. start_date = self._get_form_param('date_from', data)
  217. stop_date = self._get_form_param('date_to', data)
  218. chart_account = self._get_chart_account_id_br(data)
  219. start_period, stop_period, start, stop = \
  220. self._get_start_stop_for_filter(main_filter, fiscalyear,
  221. start_date, stop_date,
  222. start_period, stop_period)
  223. init_balance = self.is_initial_balance_enabled(main_filter)
  224. initial_balance_mode = init_balance and self._get_initial_balance_mode(
  225. start) or False
  226. # Retrieving accounts
  227. account_ids = self.get_all_accounts(
  228. new_ids, only_type=filter_report_type)
  229. # get details for each accounts, total of debit / credit / balance
  230. accounts_by_ids = self._get_account_details(
  231. account_ids, target_move, fiscalyear, main_filter, start, stop,
  232. initial_balance_mode)
  233. comparison_params = []
  234. comp_accounts_by_ids = []
  235. for index in range(max_comparison):
  236. if comp_filters[index] != 'filter_no':
  237. comparison_result, comp_params = self._get_comparison_details(
  238. data, account_ids, target_move, comp_filters[index], index)
  239. comparison_params.append(comp_params)
  240. comp_accounts_by_ids.append(comparison_result)
  241. to_display = dict.fromkeys(account_ids, True)
  242. objects = []
  243. for account in self.pool.get('account.account').browse(
  244. self.cursor, self.uid, account_ids, context=self.localcontext):
  245. if not account.parent_id: # hide top level account
  246. continue
  247. if account.type == 'consolidation':
  248. to_display.update(
  249. dict([(a.id, False) for a in account.child_consol_ids]))
  250. elif account.type == 'view':
  251. to_display.update(
  252. dict([(a.id, True) for a in account.child_id]))
  253. account.debit = accounts_by_ids[account.id]['debit']
  254. account.credit = accounts_by_ids[account.id]['credit']
  255. account.balance = accounts_by_ids[account.id]['balance']
  256. account.init_balance = accounts_by_ids[
  257. account.id].get('init_balance', 0.0)
  258. # if any amount is != 0 in comparisons, we have to display the
  259. # whole account
  260. display_account = False
  261. comp_accounts = []
  262. for comp_account_by_id in comp_accounts_by_ids:
  263. values = comp_account_by_id.get(account.id)
  264. values.update(
  265. self._get_diff(account.balance, values['balance']))
  266. display_account = any((values.get('credit', 0.0),
  267. values.get('debit', 0.0),
  268. values.get('balance', 0.0),
  269. values.get('init_balance', 0.0)))
  270. comp_accounts.append(values)
  271. account.comparisons = comp_accounts
  272. # we have to display the account if a comparison as an amount or
  273. # if we have an amount in the main column
  274. # we set it as a property to let the data in the report if someone
  275. # want to use it in a custom report
  276. display_account = display_account or any((account.debit,
  277. account.credit,
  278. account.balance,
  279. account.init_balance))
  280. to_display.update(
  281. {account.id: display_account and to_display[account.id]})
  282. objects.append(account)
  283. for account in objects:
  284. account.to_display = to_display[account.id]
  285. context_report_values = {
  286. 'fiscalyear': fiscalyear,
  287. 'start_date': start_date,
  288. 'stop_date': stop_date,
  289. 'start_period': start_period,
  290. 'stop_period': stop_period,
  291. 'chart_account': chart_account,
  292. 'comparison_mode': comparison_mode,
  293. 'nb_comparison': nb_comparisons,
  294. 'initial_balance': init_balance,
  295. 'initial_balance_mode': initial_balance_mode,
  296. 'comp_params': comparison_params,
  297. }
  298. return objects, new_ids, context_report_values