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.

277 lines
11 KiB

  1. # -*- coding: utf-8 -*-
  2. # Author: Damien Crier
  3. # Author: Julien Coux
  4. # Copyright 2016 Camptocamp SA
  5. # Copyright 2017 Akretion - Alexis de Lattre
  6. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  7. from odoo import api, fields, models, _
  8. from odoo.tools.safe_eval import safe_eval
  9. from odoo.exceptions import ValidationError
  10. import time
  11. class GeneralLedgerReportWizard(models.TransientModel):
  12. """General ledger report wizard."""
  13. _name = "general.ledger.report.wizard"
  14. _description = "General Ledger Report Wizard"
  15. company_id = fields.Many2one(
  16. comodel_name='res.company',
  17. default=lambda self: self.env.user.company_id,
  18. required=False,
  19. string='Company'
  20. )
  21. date_range_id = fields.Many2one(
  22. comodel_name='date.range',
  23. string='Date range'
  24. )
  25. date_from = fields.Date(required=True,
  26. default=lambda self: self._init_date_from())
  27. date_to = fields.Date(required=True,
  28. default=fields.Date.context_today)
  29. fy_start_date = fields.Date(compute='_compute_fy_start_date')
  30. target_move = fields.Selection([('posted', 'All Posted Entries'),
  31. ('all', 'All Entries')],
  32. string='Target Moves',
  33. required=True,
  34. default='all')
  35. account_ids = fields.Many2many(
  36. comodel_name='account.account',
  37. string='Filter accounts',
  38. )
  39. centralize = fields.Boolean(string='Activate centralization',
  40. default=True)
  41. hide_account_at_0 = fields.Boolean(
  42. string='Hide account ending balance at 0',
  43. help='Use this filter to hide an account or a partner '
  44. 'with an ending balance at 0. '
  45. 'If partners are filtered, '
  46. 'debits and credits totals will not match the trial balance.'
  47. )
  48. show_analytic_tags = fields.Boolean(
  49. string='Show analytic tags',
  50. )
  51. receivable_accounts_only = fields.Boolean()
  52. payable_accounts_only = fields.Boolean()
  53. partner_ids = fields.Many2many(
  54. comodel_name='res.partner',
  55. string='Filter partners',
  56. default=lambda self: self._default_partners(),
  57. )
  58. journal_ids = fields.Many2many(
  59. comodel_name="account.journal",
  60. string="Filter journals",
  61. )
  62. cost_center_ids = fields.Many2many(
  63. comodel_name='account.analytic.account',
  64. string='Filter cost centers',
  65. )
  66. not_only_one_unaffected_earnings_account = fields.Boolean(
  67. readonly=True,
  68. string='Not only one unaffected earnings account'
  69. )
  70. foreign_currency = fields.Boolean(
  71. string='Show foreign currency',
  72. default=lambda self: self._default_foreign_currency(),
  73. help='Display foreign currency for move lines, unless '
  74. 'account currency is not setup through chart of accounts '
  75. 'will display initial and final balance in that currency.'
  76. )
  77. analytic_tag_ids = fields.Many2many(
  78. comodel_name='account.analytic.tag',
  79. string='Filter accounts',
  80. )
  81. def _default_foreign_currency(self):
  82. if self.env.user.has_group('base.group_multi_currency'):
  83. return True
  84. def _default_partners(self):
  85. context = self.env.context
  86. if context.get('active_ids') and context.get('active_model') \
  87. == 'res.partner':
  88. partner_ids = context['active_ids']
  89. corp_partners = self.env['res.partner'].browse(partner_ids). \
  90. filtered(lambda p: p.parent_id)
  91. partner_ids = set(partner_ids) - set(corp_partners.ids)
  92. partner_ids |= set(corp_partners.mapped('parent_id.id'))
  93. return list(partner_ids)
  94. def _init_date_from(self):
  95. """set start date to begin of current year if fiscal year running"""
  96. today = fields.Date.context_today(self)
  97. cur_month = int(fields.Date.from_string(today).strftime('%m'))
  98. cur_day = int(fields.Date.from_string(today).strftime('%d'))
  99. last_fsc_month = self.env.user.company_id.fiscalyear_last_month
  100. last_fsc_day = self.env.user.company_id.fiscalyear_last_day
  101. if cur_month < last_fsc_month \
  102. or cur_month == last_fsc_month and cur_day <= last_fsc_day:
  103. return time.strftime('%Y-01-01')
  104. @api.depends('date_from')
  105. def _compute_fy_start_date(self):
  106. for wiz in self.filtered('date_from'):
  107. date = fields.Datetime.from_string(wiz.date_from)
  108. res = self.company_id.compute_fiscalyear_dates(date)
  109. wiz.fy_start_date = res['date_from']
  110. @api.onchange('company_id')
  111. def onchange_company_id(self):
  112. """Handle company change."""
  113. account_type = self.env.ref('account.data_unaffected_earnings')
  114. count = self.env['account.account'].search_count(
  115. [
  116. ('user_type_id', '=', account_type.id),
  117. ('company_id', '=', self.company_id.id)
  118. ])
  119. self.not_only_one_unaffected_earnings_account = count != 1
  120. if self.company_id and self.date_range_id.company_id and \
  121. self.date_range_id.company_id != self.company_id:
  122. self.date_range_id = False
  123. if self.company_id and self.journal_ids:
  124. self.journal_ids = self.journal_ids.filtered(
  125. lambda p: p.company_id == self.company_id or
  126. not p.company_id)
  127. if self.company_id and self.partner_ids:
  128. self.partner_ids = self.partner_ids.filtered(
  129. lambda p: p.company_id == self.company_id or
  130. not p.company_id)
  131. if self.company_id and self.account_ids:
  132. if self.receivable_accounts_only or self.payable_accounts_only:
  133. self.onchange_type_accounts_only()
  134. else:
  135. self.account_ids = self.account_ids.filtered(
  136. lambda a: a.company_id == self.company_id)
  137. if self.company_id and self.cost_center_ids:
  138. self.cost_center_ids = self.cost_center_ids.filtered(
  139. lambda c: c.company_id == self.company_id)
  140. res = {'domain': {'account_ids': [],
  141. 'journal_ids': [],
  142. 'partner_ids': [],
  143. 'cost_center_ids': [],
  144. 'date_range_id': []
  145. }
  146. }
  147. if not self.company_id:
  148. return res
  149. else:
  150. res['domain']['account_ids'] += [
  151. ('company_id', '=', self.company_id.id)]
  152. res['domain']['journal_ids'] += [
  153. ('company_id', '=', self.company_id.id)]
  154. res['domain']['partner_ids'] += [
  155. '&',
  156. '|', ('company_id', '=', self.company_id.id),
  157. ('company_id', '=', False),
  158. ('parent_id', '=', False)
  159. ]
  160. res['domain']['cost_center_ids'] += [
  161. ('company_id', '=', self.company_id.id)]
  162. res['domain']['date_range_id'] += [
  163. '|', ('company_id', '=', self.company_id.id),
  164. ('company_id', '=', False)]
  165. return res
  166. @api.onchange('date_range_id')
  167. def onchange_date_range_id(self):
  168. """Handle date range change."""
  169. if self.date_range_id:
  170. self.date_from = self.date_range_id.date_start
  171. self.date_to = self.date_range_id.date_end
  172. @api.multi
  173. @api.constrains('company_id', 'date_range_id')
  174. def _check_company_id_date_range_id(self):
  175. for rec in self.sudo():
  176. if rec.company_id and rec.date_range_id.company_id and\
  177. rec.company_id != rec.date_range_id.company_id:
  178. raise ValidationError(
  179. _('The Company in the General Ledger Report Wizard and in '
  180. 'Date Range must be the same.'))
  181. @api.onchange('receivable_accounts_only', 'payable_accounts_only')
  182. def onchange_type_accounts_only(self):
  183. """Handle receivable/payable accounts only change."""
  184. if self.receivable_accounts_only or self.payable_accounts_only:
  185. domain = [('company_id', '=', self.company_id.id)]
  186. if self.receivable_accounts_only and self.payable_accounts_only:
  187. domain += [('internal_type', 'in', ('receivable', 'payable'))]
  188. elif self.receivable_accounts_only:
  189. domain += [('internal_type', '=', 'receivable')]
  190. elif self.payable_accounts_only:
  191. domain += [('internal_type', '=', 'payable')]
  192. self.account_ids = self.env['account.account'].search(domain)
  193. else:
  194. self.account_ids = None
  195. @api.onchange('partner_ids')
  196. def onchange_partner_ids(self):
  197. """Handle partners change."""
  198. if (
  199. self.partner_ids and
  200. not self.receivable_accounts_only and
  201. not self.payable_accounts_only):
  202. self.receivable_accounts_only = self.payable_accounts_only = True
  203. @api.multi
  204. def button_export_html(self):
  205. self.ensure_one()
  206. action = self.env.ref(
  207. 'account_financial_report_qweb.action_report_general_ledger')
  208. vals = action.read()[0]
  209. context1 = vals.get('context', {})
  210. if isinstance(context1, basestring):
  211. context1 = safe_eval(context1)
  212. model = self.env['report_general_ledger_qweb']
  213. report = model.create(self._prepare_report_general_ledger())
  214. report.compute_data_for_report()
  215. context1['active_id'] = report.id
  216. context1['active_ids'] = report.ids
  217. vals['context'] = context1
  218. return vals
  219. @api.multi
  220. def button_export_pdf(self):
  221. self.ensure_one()
  222. report_type = 'qweb-pdf'
  223. return self._export(report_type)
  224. @api.multi
  225. def button_export_xlsx(self):
  226. self.ensure_one()
  227. report_type = 'xlsx'
  228. return self._export(report_type)
  229. def _prepare_report_general_ledger(self):
  230. self.ensure_one()
  231. return {
  232. 'date_from': self.date_from,
  233. 'date_to': self.date_to,
  234. 'only_posted_moves': self.target_move == 'posted',
  235. 'hide_account_at_0': self.hide_account_at_0,
  236. 'foreign_currency': self.foreign_currency,
  237. 'show_analytic_tags': self.show_analytic_tags,
  238. 'company_id': self.company_id.id,
  239. 'filter_account_ids': [(6, 0, self.account_ids.ids)],
  240. 'filter_partner_ids': [(6, 0, self.partner_ids.ids)],
  241. 'filter_journal_ids': [(6, 0, self.journal_ids.ids)],
  242. 'filter_cost_center_ids': [(6, 0, self.cost_center_ids.ids)],
  243. 'filter_analytic_tag_ids': [(6, 0, self.analytic_tag_ids.ids)],
  244. 'centralize': self.centralize,
  245. 'fy_start_date': self.fy_start_date,
  246. }
  247. def _export(self, report_type):
  248. """Default export is PDF."""
  249. model = self.env['report_general_ledger_qweb']
  250. report = model.create(self._prepare_report_general_ledger())
  251. report.compute_data_for_report()
  252. return report.print_report(report_type)