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.

276 lines
11 KiB

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