company.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. # -*- coding: utf-8 -*-
  2. from datetime import timedelta, datetime, date
  3. import calendar
  4. from odoo import fields, models, api, _
  5. from odoo.exceptions import ValidationError, UserError, RedirectWarning
  6. from odoo.tools.mail import is_html_empty
  7. from odoo.tools.misc import format_date
  8. from odoo.tools.float_utils import float_round, float_is_zero
  9. from odoo.addons.account.models.account_move import MAX_HASH_VERSION
  10. MONTH_SELECTION = [
  11. ('1', 'January'),
  12. ('2', 'February'),
  13. ('3', 'March'),
  14. ('4', 'April'),
  15. ('5', 'May'),
  16. ('6', 'June'),
  17. ('7', 'July'),
  18. ('8', 'August'),
  19. ('9', 'September'),
  20. ('10', 'October'),
  21. ('11', 'November'),
  22. ('12', 'December'),
  23. ]
  24. ONBOARDING_STEP_STATES = [
  25. ('not_done', "Not done"),
  26. ('just_done', "Just done"),
  27. ('done', "Done"),
  28. ]
  29. DASHBOARD_ONBOARDING_STATES = ONBOARDING_STEP_STATES + [('closed', 'Closed')]
  30. class ResCompany(models.Model):
  31. _name = "res.company"
  32. _inherit = ["res.company", "mail.thread"]
  33. #TODO check all the options/fields are in the views (settings + company form view)
  34. fiscalyear_last_day = fields.Integer(default=31, required=True)
  35. fiscalyear_last_month = fields.Selection(MONTH_SELECTION, default='12', required=True)
  36. period_lock_date = fields.Date(
  37. string="Journals Entries Lock Date",
  38. tracking=True,
  39. help="Only users with the 'Adviser' role can edit accounts prior to and inclusive of this"
  40. " date. Use it for period locking inside an open fiscal year, for example.")
  41. fiscalyear_lock_date = fields.Date(
  42. string="All Users Lock Date",
  43. tracking=True,
  44. help="No users, including Advisers, can edit accounts prior to and inclusive of this date."
  45. " Use it for fiscal year locking for example.")
  46. tax_lock_date = fields.Date(
  47. string="Tax Return Lock Date",
  48. tracking=True,
  49. help="No users can edit journal entries related to a tax prior and inclusive of this date.")
  50. transfer_account_id = fields.Many2one('account.account',
  51. domain="[('reconcile', '=', True), ('account_type', '=', 'asset_current'), ('deprecated', '=', False)]", string="Inter-Banks Transfer Account", help="Intermediary account used when moving money from a liqity account to another")
  52. expects_chart_of_accounts = fields.Boolean(string='Expects a Chart of Accounts', default=True)
  53. chart_template_id = fields.Many2one('account.chart.template', help='The chart template for the company (if any)')
  54. bank_account_code_prefix = fields.Char(string='Prefix of the bank accounts')
  55. cash_account_code_prefix = fields.Char(string='Prefix of the cash accounts')
  56. default_cash_difference_income_account_id = fields.Many2one('account.account', string="Cash Difference Income Account")
  57. default_cash_difference_expense_account_id = fields.Many2one('account.account', string="Cash Difference Expense Account")
  58. account_journal_suspense_account_id = fields.Many2one('account.account', string='Journal Suspense Account')
  59. account_journal_payment_debit_account_id = fields.Many2one('account.account', string='Journal Outstanding Receipts Account')
  60. account_journal_payment_credit_account_id = fields.Many2one('account.account', string='Journal Outstanding Payments Account')
  61. account_journal_early_pay_discount_gain_account_id = fields.Many2one(comodel_name='account.account', string='Cash Discount Write-Off Gain Account')
  62. account_journal_early_pay_discount_loss_account_id = fields.Many2one(comodel_name='account.account', string='Cash Discount Write-Off Loss Account')
  63. early_pay_discount_computation = fields.Selection([
  64. ('included', 'On early payment'),
  65. ('excluded', 'Never'),
  66. ('mixed', 'Always (upon invoice)')
  67. ], string='Cash Discount Tax Reduction', readonly=False, store=True, compute='_compute_early_pay_discount_computation')
  68. transfer_account_code_prefix = fields.Char(string='Prefix of the transfer accounts')
  69. account_sale_tax_id = fields.Many2one('account.tax', string="Default Sale Tax")
  70. account_purchase_tax_id = fields.Many2one('account.tax', string="Default Purchase Tax")
  71. tax_calculation_rounding_method = fields.Selection([
  72. ('round_per_line', 'Round per Line'),
  73. ('round_globally', 'Round Globally'),
  74. ], default='round_per_line', string='Tax Calculation Rounding Method')
  75. currency_exchange_journal_id = fields.Many2one('account.journal', string="Exchange Gain or Loss Journal", domain=[('type', '=', 'general')])
  76. income_currency_exchange_account_id = fields.Many2one(
  77. comodel_name='account.account',
  78. string="Gain Exchange Rate Account",
  79. domain="[('deprecated', '=', False), ('company_id', '=', id), \
  80. ('account_type', 'in', ('income', 'income_other'))]")
  81. expense_currency_exchange_account_id = fields.Many2one(
  82. comodel_name='account.account',
  83. string="Loss Exchange Rate Account",
  84. domain="[('deprecated', '=', False), ('company_id', '=', id), \
  85. ('account_type', '=', 'expense')]")
  86. anglo_saxon_accounting = fields.Boolean(string="Use anglo-saxon accounting")
  87. property_stock_account_input_categ_id = fields.Many2one('account.account', string="Input Account for Stock Valuation")
  88. property_stock_account_output_categ_id = fields.Many2one('account.account', string="Output Account for Stock Valuation")
  89. property_stock_valuation_account_id = fields.Many2one('account.account', string="Account Template for Stock Valuation")
  90. bank_journal_ids = fields.One2many('account.journal', 'company_id', domain=[('type', '=', 'bank')], string='Bank Journals')
  91. incoterm_id = fields.Many2one('account.incoterms', string='Default incoterm',
  92. help='International Commercial Terms are a series of predefined commercial terms used in international transactions.')
  93. qr_code = fields.Boolean(string='Display QR-code on invoices')
  94. invoice_is_email = fields.Boolean('Email by default', default=True)
  95. invoice_is_print = fields.Boolean('Print by default', default=True)
  96. account_use_credit_limit = fields.Boolean(
  97. string='Sales Credit Limit', help='Enable the use of credit limit on partners.')
  98. #Fields of the setup step for opening move
  99. account_opening_move_id = fields.Many2one(string='Opening Journal Entry', comodel_name='account.move', help="The journal entry containing the initial balance of all this company's accounts.")
  100. account_opening_journal_id = fields.Many2one(string='Opening Journal', comodel_name='account.journal', related='account_opening_move_id.journal_id', help="Journal where the opening entry of this company's accounting has been posted.", readonly=False)
  101. account_opening_date = fields.Date(string='Opening Entry', default=lambda self: fields.Date.context_today(self).replace(month=1, day=1), required=True, help="That is the date of the opening entry.")
  102. # Fields marking the completion of a setup step
  103. account_setup_bank_data_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding bank data step", default='not_done')
  104. account_setup_fy_data_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding fiscal year step", default='not_done')
  105. account_setup_coa_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding charts of account step", default='not_done')
  106. account_setup_taxes_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding Taxes step", default='not_done')
  107. account_onboarding_invoice_layout_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding invoice layout step", default='not_done')
  108. account_onboarding_create_invoice_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding create invoice step", compute='_compute_account_onboarding_create_invoice_state')
  109. #this field must be there to ensure that the create_invoice_state stay complete and because we can't use a dependencies on account move
  110. account_onboarding_create_invoice_state_flag = fields.Boolean(default=False, store=True)
  111. account_onboarding_sale_tax_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding sale tax step", default='not_done')
  112. # account dashboard onboarding
  113. account_invoice_onboarding_state = fields.Selection(DASHBOARD_ONBOARDING_STATES, string="State of the account invoice onboarding panel", default='not_done')
  114. account_dashboard_onboarding_state = fields.Selection(DASHBOARD_ONBOARDING_STATES, string="State of the account dashboard onboarding panel", default='not_done')
  115. invoice_terms = fields.Html(string='Default Terms and Conditions', translate=True)
  116. terms_type = fields.Selection([('plain', 'Add a Note'), ('html', 'Add a link to a Web Page')],
  117. string='Terms & Conditions format', default='plain')
  118. invoice_terms_html = fields.Html(string='Default Terms and Conditions as a Web page', translate=True,
  119. sanitize_attributes=False,
  120. compute='_compute_invoice_terms_html', store=True, readonly=False)
  121. account_setup_bill_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding bill step", default='not_done')
  122. # Needed in the Point of Sale
  123. account_default_pos_receivable_account_id = fields.Many2one('account.account', string="Default PoS Receivable Account")
  124. # Accrual Accounting
  125. expense_accrual_account_id = fields.Many2one('account.account',
  126. help="Account used to move the period of an expense",
  127. domain="[('internal_group', '=', 'liability'), ('account_type', 'not in', ('asset_receivable', 'liability_payable')), ('company_id', '=', id)]")
  128. revenue_accrual_account_id = fields.Many2one('account.account',
  129. help="Account used to move the period of a revenue",
  130. domain="[('internal_group', '=', 'asset'), ('account_type', 'not in', ('asset_receivable', 'liability_payable')), ('company_id', '=', id)]")
  131. automatic_entry_default_journal_id = fields.Many2one('account.journal', help="Journal used by default for moving the period of an entry", domain="[('type', '=', 'general')]")
  132. # Technical field to hide country specific fields in company form view
  133. country_code = fields.Char(related='country_id.code', depends=['country_id'])
  134. # Taxes
  135. account_fiscal_country_id = fields.Many2one(
  136. string="Fiscal Country",
  137. comodel_name='res.country',
  138. compute='compute_account_tax_fiscal_country',
  139. store=True,
  140. readonly=False,
  141. help="The country to use the tax reports from for this company")
  142. account_enabled_tax_country_ids = fields.Many2many(
  143. string="l10n-used countries",
  144. comodel_name='res.country',
  145. compute='_compute_account_enabled_tax_country_ids',
  146. help="Technical field containing the countries for which this company is using tax-related features"
  147. "(hence the ones for which l10n modules need to show tax-related fields).")
  148. # Cash basis taxes
  149. tax_exigibility = fields.Boolean(string='Use Cash Basis')
  150. tax_cash_basis_journal_id = fields.Many2one(
  151. comodel_name='account.journal',
  152. string="Cash Basis Journal")
  153. account_cash_basis_base_account_id = fields.Many2one(
  154. comodel_name='account.account',
  155. domain=[('deprecated', '=', False)],
  156. string="Base Tax Received Account",
  157. help="Account that will be set on lines created in cash basis journal entry and used to keep track of the "
  158. "tax base amount.")
  159. # Storno Accounting
  160. account_storno = fields.Boolean(string="Storno accounting", readonly=False)
  161. # Multivat
  162. fiscal_position_ids = fields.One2many(comodel_name="account.fiscal.position", inverse_name="company_id")
  163. multi_vat_foreign_country_ids = fields.Many2many(
  164. string="Foreign VAT countries",
  165. help="Countries for which the company has a VAT number",
  166. comodel_name='res.country',
  167. compute='_compute_multi_vat_foreign_country',
  168. )
  169. # Fiduciary mode
  170. quick_edit_mode = fields.Selection(
  171. selection=[
  172. ('out_invoices', 'Customer Invoices'),
  173. ('in_invoices', 'Vendor Bills'),
  174. ('out_and_in_invoices', 'Customer Invoices and Vendor Bills')],
  175. string="Quick encoding")
  176. @api.constrains('account_opening_move_id', 'fiscalyear_last_day', 'fiscalyear_last_month')
  177. def _check_fiscalyear_last_day(self):
  178. # if the user explicitly chooses the 29th of February we allow it:
  179. # there is no "fiscalyear_last_year" so we do not know his intentions.
  180. for rec in self:
  181. if rec.fiscalyear_last_day == 29 and rec.fiscalyear_last_month == '2':
  182. continue
  183. if rec.account_opening_date:
  184. year = rec.account_opening_date.year
  185. else:
  186. year = datetime.now().year
  187. max_day = calendar.monthrange(year, int(rec.fiscalyear_last_month))[1]
  188. if rec.fiscalyear_last_day > max_day:
  189. raise ValidationError(_("Invalid fiscal year last day"))
  190. @api.depends('fiscal_position_ids.foreign_vat')
  191. def _compute_multi_vat_foreign_country(self):
  192. company_to_foreign_vat_country = {
  193. val['company_id'][0]: val['country_ids']
  194. for val in self.env['account.fiscal.position'].read_group(
  195. domain=[('company_id', 'in', self.ids), ('foreign_vat', '!=', False)],
  196. fields=['country_ids:array_agg(country_id)'],
  197. groupby='company_id',
  198. )
  199. }
  200. for company in self:
  201. company.multi_vat_foreign_country_ids = self.env['res.country'].browse(company_to_foreign_vat_country.get(company.id))
  202. @api.depends('country_id')
  203. def compute_account_tax_fiscal_country(self):
  204. for record in self:
  205. if not record.account_fiscal_country_id:
  206. record.account_fiscal_country_id = record.country_id
  207. @api.depends('account_fiscal_country_id')
  208. def _compute_account_enabled_tax_country_ids(self):
  209. for record in self:
  210. foreign_vat_fpos = self.env['account.fiscal.position'].search([('company_id', '=', record.id), ('foreign_vat', '!=', False)])
  211. record.account_enabled_tax_country_ids = foreign_vat_fpos.country_id + record.account_fiscal_country_id
  212. @api.depends('account_onboarding_create_invoice_state_flag')
  213. def _compute_account_onboarding_create_invoice_state(self):
  214. for record in self:
  215. if record.account_onboarding_create_invoice_state_flag:
  216. record.account_onboarding_create_invoice_state = 'done'
  217. elif self.env['account.move'].search([('company_id', '=', record.id), ('move_type', '=', 'out_invoice')], limit=1):
  218. record.account_onboarding_create_invoice_state = 'just_done'
  219. record.account_onboarding_create_invoice_state_flag = True
  220. else:
  221. record.account_onboarding_create_invoice_state = 'not_done'
  222. @api.depends('terms_type')
  223. def _compute_invoice_terms_html(self):
  224. for company in self.filtered(lambda company: is_html_empty(company.invoice_terms_html) and company.terms_type == 'html'):
  225. html = self.env['ir.qweb']._render('account.account_default_terms_and_conditions',
  226. {'company_name': company.name, 'company_country': company.country_id.name},
  227. raise_if_not_found=False)
  228. if html:
  229. company.invoice_terms_html = html
  230. def get_and_update_account_invoice_onboarding_state(self):
  231. """ This method is called on the controller rendering method and ensures that the animations
  232. are displayed only one time. """
  233. return self._get_and_update_onboarding_state(
  234. 'account_invoice_onboarding_state',
  235. self.get_account_invoice_onboarding_steps_states_names()
  236. )
  237. # YTI FIXME: Define only one method that returns {'account': [], 'sale': [], ...}
  238. def get_account_invoice_onboarding_steps_states_names(self):
  239. """ Necessary to add/edit steps from other modules (payment provider in this case). """
  240. return [
  241. 'base_onboarding_company_state',
  242. 'account_onboarding_invoice_layout_state',
  243. 'account_onboarding_create_invoice_state',
  244. ]
  245. def get_and_update_account_dashboard_onboarding_state(self):
  246. """ This method is called on the controller rendering method and ensures that the animations
  247. are displayed only one time. """
  248. return self._get_and_update_onboarding_state(
  249. 'account_dashboard_onboarding_state',
  250. self.get_account_dashboard_onboarding_steps_states_names()
  251. )
  252. def get_account_dashboard_onboarding_steps_states_names(self):
  253. """ Necessary to add/edit steps from other modules (account_winbooks_import in this case). """
  254. return [
  255. 'account_setup_bank_data_state',
  256. 'account_setup_fy_data_state',
  257. 'account_setup_coa_state',
  258. 'account_setup_taxes_state',
  259. ]
  260. def get_new_account_code(self, current_code, old_prefix, new_prefix):
  261. digits = len(current_code)
  262. return new_prefix + current_code.replace(old_prefix, '', 1).lstrip('0').rjust(digits-len(new_prefix), '0')
  263. def reflect_code_prefix_change(self, old_code, new_code):
  264. accounts = self.env['account.account'].search([('code', 'like', old_code), ('account_type', 'in', ('asset_cash', 'liability_credit_card')),
  265. ('company_id', '=', self.id)], order='code asc')
  266. for account in accounts:
  267. if account.code.startswith(old_code):
  268. account.write({'code': self.get_new_account_code(account.code, old_code, new_code)})
  269. def _get_fiscalyear_lock_statement_lines_redirect_action(self, unreconciled_statement_lines):
  270. """ Get the action redirecting to the statement lines that are not already reconciled when setting a fiscal
  271. year lock date.
  272. :param unreconciled_statement_lines: The statement lines.
  273. :return: A dictionary representing a window action.
  274. """
  275. action = {
  276. 'name': _("Unreconciled Transactions"),
  277. 'type': 'ir.actions.act_window',
  278. 'res_model': 'account.bank.statement.line',
  279. 'context': {'create': False},
  280. }
  281. if len(unreconciled_statement_lines) == 1:
  282. action.update({
  283. 'view_mode': 'form',
  284. 'res_id': unreconciled_statement_lines.id,
  285. })
  286. else:
  287. action.update({
  288. 'view_mode': 'list,form',
  289. 'domain': [('id', 'in', unreconciled_statement_lines.ids)],
  290. })
  291. return action
  292. def _validate_fiscalyear_lock(self, values):
  293. if values.get('fiscalyear_lock_date'):
  294. draft_entries = self.env['account.move'].search([
  295. ('company_id', 'in', self.ids),
  296. ('state', '=', 'draft'),
  297. ('date', '<=', values['fiscalyear_lock_date'])])
  298. if draft_entries:
  299. error_msg = _('There are still unposted entries in the period you want to lock. You should either post or delete them.')
  300. action_error = {
  301. 'view_mode': 'tree',
  302. 'name': _('Unposted Entries'),
  303. 'res_model': 'account.move',
  304. 'type': 'ir.actions.act_window',
  305. 'domain': [('id', 'in', draft_entries.ids)],
  306. 'search_view_id': [self.env.ref('account.view_account_move_filter').id, 'search'],
  307. 'views': [[self.env.ref('account.view_move_tree').id, 'list'], [self.env.ref('account.view_move_form').id, 'form']],
  308. }
  309. raise RedirectWarning(error_msg, action_error, _('Show unposted entries'))
  310. unreconciled_statement_lines = self.env['account.bank.statement.line'].search([
  311. ('company_id', 'in', self.ids),
  312. ('is_reconciled', '=', False),
  313. ('date', '<=', values['fiscalyear_lock_date']),
  314. ('move_id.state', 'in', ('draft', 'posted')),
  315. ])
  316. if unreconciled_statement_lines:
  317. error_msg = _("There are still unreconciled bank statement lines in the period you want to lock."
  318. "You should either reconcile or delete them.")
  319. action_error = self._get_fiscalyear_lock_statement_lines_redirect_action(unreconciled_statement_lines)
  320. raise RedirectWarning(error_msg, action_error, _('Show Unreconciled Bank Statement Line'))
  321. def _get_user_fiscal_lock_date(self):
  322. """Get the fiscal lock date for this company depending on the user"""
  323. if not self:
  324. return date.min
  325. self.ensure_one()
  326. lock_date = max(self.period_lock_date or date.min, self.fiscalyear_lock_date or date.min)
  327. if self.user_has_groups('account.group_account_manager'):
  328. lock_date = self.fiscalyear_lock_date or date.min
  329. return lock_date
  330. def write(self, values):
  331. #restrict the closing of FY if there are still unposted entries
  332. self._validate_fiscalyear_lock(values)
  333. # Reflect the change on accounts
  334. for company in self:
  335. if values.get('bank_account_code_prefix'):
  336. new_bank_code = values.get('bank_account_code_prefix') or company.bank_account_code_prefix
  337. company.reflect_code_prefix_change(company.bank_account_code_prefix, new_bank_code)
  338. if values.get('cash_account_code_prefix'):
  339. new_cash_code = values.get('cash_account_code_prefix') or company.cash_account_code_prefix
  340. company.reflect_code_prefix_change(company.cash_account_code_prefix, new_cash_code)
  341. #forbid the change of currency_id if there are already some accounting entries existing
  342. if 'currency_id' in values and values['currency_id'] != company.currency_id.id:
  343. if self.env['account.move.line'].search([('company_id', '=', company.id)]):
  344. raise UserError(_('You cannot change the currency of the company since some journal items already exist'))
  345. return super(ResCompany, self).write(values)
  346. @api.model
  347. def setting_init_bank_account_action(self):
  348. """ Called by the 'Bank Accounts' button of the setup bar."""
  349. view_id = self.env.ref('account.setup_bank_account_wizard').id
  350. return {'type': 'ir.actions.act_window',
  351. 'name': _('Create a Bank Account'),
  352. 'res_model': 'account.setup.bank.manual.config',
  353. 'target': 'new',
  354. 'view_mode': 'form',
  355. 'views': [[view_id, 'form']],
  356. }
  357. @api.model
  358. def setting_init_fiscal_year_action(self):
  359. """ Called by the 'Fiscal Year Opening' button of the setup bar."""
  360. company = self.env.company
  361. new_wizard = self.env['account.financial.year.op'].create({'company_id': company.id})
  362. view_id = self.env.ref('account.setup_financial_year_opening_form').id
  363. return {
  364. 'type': 'ir.actions.act_window',
  365. 'name': _('Accounting Periods'),
  366. 'view_mode': 'form',
  367. 'res_model': 'account.financial.year.op',
  368. 'target': 'new',
  369. 'res_id': new_wizard.id,
  370. 'views': [[view_id, 'form']],
  371. }
  372. @api.model
  373. def setting_chart_of_accounts_action(self):
  374. """ Called by the 'Chart of Accounts' button of the setup bar."""
  375. company = self.env.company
  376. company.sudo().set_onboarding_step_done('account_setup_coa_state')
  377. # If an opening move has already been posted, we open the tree view showing all the accounts
  378. if company.opening_move_posted():
  379. return 'account.action_account_form'
  380. # Then, we open will open a custom tree view allowing to edit opening balances of the account
  381. view_id = self.env.ref('account.init_accounts_tree').id
  382. # Hide the current year earnings account as it is automatically computed
  383. domain = [('account_type', '!=', 'equity_unaffected'), ('company_id', '=', company.id)]
  384. return {
  385. 'type': 'ir.actions.act_window',
  386. 'name': _('Chart of Accounts'),
  387. 'res_model': 'account.account',
  388. 'view_mode': 'tree',
  389. 'limit': 99999999,
  390. 'search_view_id': [self.env.ref('account.view_account_search').id],
  391. 'views': [[view_id, 'list']],
  392. 'domain': domain,
  393. }
  394. @api.model
  395. def create_op_move_if_non_existant(self):
  396. """ Creates an empty opening move in 'draft' state for the current company
  397. if there wasn't already one defined. For this, the function needs at least
  398. one journal of type 'general' to exist (required by account.move).
  399. """
  400. self.ensure_one()
  401. if not self.account_opening_move_id:
  402. default_journal = self.env['account.journal'].search([('type', '=', 'general'), ('company_id', '=', self.id)], limit=1)
  403. if not default_journal:
  404. raise UserError(_("Please install a chart of accounts or create a miscellaneous journal before proceeding."))
  405. opening_date = self.account_opening_date - timedelta(days=1)
  406. self.account_opening_move_id = self.env['account.move'].create({
  407. 'ref': _('Opening Journal Entry'),
  408. 'company_id': self.id,
  409. 'journal_id': default_journal.id,
  410. 'date': opening_date,
  411. })
  412. def opening_move_posted(self):
  413. """ Returns true if this company has an opening account move and this move is posted."""
  414. return bool(self.account_opening_move_id) and self.account_opening_move_id.state == 'posted'
  415. def get_unaffected_earnings_account(self):
  416. """ Returns the unaffected earnings account for this company, creating one
  417. if none has yet been defined.
  418. """
  419. unaffected_earnings_type = "equity_unaffected"
  420. account = self.env['account.account'].search([('company_id', '=', self.id),
  421. ('account_type', '=', unaffected_earnings_type)])
  422. if account:
  423. return account[0]
  424. # Do not assume '999999' doesn't exist since the user might have created such an account
  425. # manually.
  426. code = 999999
  427. while self.env['account.account'].search([('code', '=', str(code)), ('company_id', '=', self.id)]):
  428. code -= 1
  429. return self.env['account.account'].create({
  430. 'code': str(code),
  431. 'name': _('Undistributed Profits/Losses'),
  432. 'account_type': unaffected_earnings_type,
  433. 'company_id': self.id,
  434. })
  435. def get_opening_move_differences(self, opening_move_lines):
  436. currency = self.currency_id
  437. balancing_move_line = opening_move_lines.filtered(lambda x: x.account_id == self.get_unaffected_earnings_account())
  438. debits_sum = credits_sum = 0.0
  439. for line in opening_move_lines:
  440. if line != balancing_move_line:
  441. #skip the autobalancing move line
  442. debits_sum += line.debit
  443. credits_sum += line.credit
  444. difference = abs(debits_sum - credits_sum)
  445. debit_diff = (debits_sum > credits_sum) and float_round(difference, precision_rounding=currency.rounding) or 0.0
  446. credit_diff = (debits_sum < credits_sum) and float_round(difference, precision_rounding=currency.rounding) or 0.0
  447. return debit_diff, credit_diff
  448. def _auto_balance_opening_move(self):
  449. """ Checks the opening_move of this company. If it has not been posted yet
  450. and is unbalanced, balances it with a automatic account.move.line in the
  451. current year earnings account.
  452. """
  453. if self.account_opening_move_id and self.account_opening_move_id.state == 'draft':
  454. balancing_account = self.get_unaffected_earnings_account()
  455. currency = self.currency_id
  456. balancing_move_line = self.account_opening_move_id.line_ids.filtered(lambda x: x.account_id == balancing_account)
  457. # There could be multiple lines if we imported the balance from unaffected earnings account too
  458. if len(balancing_move_line) > 1:
  459. self.with_context(check_move_validity=False).account_opening_move_id.line_ids -= balancing_move_line[1:]
  460. balancing_move_line = balancing_move_line[0]
  461. debit_diff, credit_diff = self.get_opening_move_differences(self.account_opening_move_id.line_ids)
  462. if float_is_zero(debit_diff + credit_diff, precision_rounding=currency.rounding):
  463. if balancing_move_line:
  464. # zero difference and existing line : delete the line
  465. self.account_opening_move_id.line_ids -= balancing_move_line
  466. else:
  467. if balancing_move_line:
  468. # Non-zero difference and existing line : edit the line
  469. balancing_move_line.write({'debit': credit_diff, 'credit': debit_diff})
  470. else:
  471. # Non-zero difference and no existing line : create a new line
  472. self.env['account.move.line'].create({
  473. 'name': _('Automatic Balancing Line'),
  474. 'move_id': self.account_opening_move_id.id,
  475. 'account_id': balancing_account.id,
  476. 'debit': credit_diff,
  477. 'credit': debit_diff,
  478. })
  479. @api.model
  480. def action_close_account_invoice_onboarding(self):
  481. """ Mark the invoice onboarding panel as closed. """
  482. self.env.company.account_invoice_onboarding_state = 'closed'
  483. @api.model
  484. def action_close_account_dashboard_onboarding(self):
  485. """ Mark the dashboard onboarding panel as closed. """
  486. self.env.company.account_dashboard_onboarding_state = 'closed'
  487. @api.model
  488. def action_open_account_onboarding_sale_tax(self):
  489. """ Onboarding step for the invoice layout. """
  490. action = self.env["ir.actions.actions"]._for_xml_id("account.action_open_account_onboarding_sale_tax")
  491. action['res_id'] = self.env.company.id
  492. return action
  493. @api.model
  494. def action_open_account_onboarding_create_invoice(self):
  495. return self.env["ir.actions.actions"]._for_xml_id("account.action_open_account_onboarding_create_invoice")
  496. @api.model
  497. def action_open_taxes_onboarding(self):
  498. """ Called by the 'Taxes' button of the setup bar."""
  499. company = self.env.company
  500. company.sudo().set_onboarding_step_done('account_setup_taxes_state')
  501. view_id_list = self.env.ref('account.view_onboarding_tax_tree').id
  502. view_id_form = self.env.ref('account.view_tax_form').id
  503. return {
  504. 'type': 'ir.actions.act_window',
  505. 'name': _('Taxes'),
  506. 'res_model': 'account.tax',
  507. 'target': 'current',
  508. 'views': [[view_id_list, 'list'], [view_id_form, 'form']],
  509. 'context': {'search_default_sale': True, 'search_default_purchase': True, 'active_test': False},
  510. }
  511. def action_save_onboarding_invoice_layout(self):
  512. """ Set the onboarding step as done """
  513. if bool(self.external_report_layout_id):
  514. self.set_onboarding_step_done('account_onboarding_invoice_layout_state')
  515. def action_save_onboarding_sale_tax(self):
  516. """ Set the onboarding step as done """
  517. self.set_onboarding_step_done('account_onboarding_sale_tax_state')
  518. def get_chart_of_accounts_or_fail(self):
  519. account = self.env['account.account'].search([('company_id', '=', self.id)], limit=1)
  520. if len(account) == 0:
  521. action = self.env.ref('account.action_account_config')
  522. msg = _(
  523. "We cannot find a chart of accounts for this company, you should configure it. \n"
  524. "Please go to Account Configuration and select or install a fiscal localization.")
  525. raise RedirectWarning(msg, action.id, _("Go to the configuration panel"))
  526. return account
  527. @api.model
  528. def _action_check_hash_integrity(self):
  529. return self.env.ref('account.action_report_account_hash_integrity').report_action(self.id)
  530. def _check_hash_integrity(self):
  531. """Checks that all posted moves have still the same data as when they were posted
  532. and raises an error with the result.
  533. """
  534. if not self.env.user.has_group('account.group_account_user'):
  535. raise UserError(_('Please contact your accountant to print the Hash integrity result.'))
  536. def build_move_info(move):
  537. return(move.name, move.inalterable_hash, fields.Date.to_string(move.date))
  538. journals = self.env['account.journal'].search([('company_id', '=', self.id)])
  539. results_by_journal = {
  540. 'results': [],
  541. 'printing_date': format_date(self.env, fields.Date.to_string(fields.Date.context_today(self)))
  542. }
  543. for journal in journals:
  544. rslt = {
  545. 'journal_name': journal.name,
  546. 'journal_code': journal.code,
  547. 'restricted_by_hash_table': journal.restrict_mode_hash_table and 'V' or 'X',
  548. 'msg_cover': '',
  549. 'first_hash': 'None',
  550. 'first_move_name': 'None',
  551. 'first_move_date': 'None',
  552. 'last_hash': 'None',
  553. 'last_move_name': 'None',
  554. 'last_move_date': 'None',
  555. }
  556. if not journal.restrict_mode_hash_table:
  557. rslt.update({'msg_cover': _('This journal is not in strict mode.')})
  558. results_by_journal['results'].append(rslt)
  559. continue
  560. # We need the `sudo()` to ensure that all the moves are searched, no matter the user's access rights.
  561. # This is required in order to generate consistent hashs.
  562. # It is not an issue, since the data is only used to compute a hash and not to return the actual values.
  563. all_moves_count = self.env['account.move'].sudo().search_count([('state', '=', 'posted'), ('journal_id', '=', journal.id)])
  564. moves = self.env['account.move'].sudo().search([('state', '=', 'posted'), ('journal_id', '=', journal.id),
  565. ('secure_sequence_number', '!=', 0)], order="secure_sequence_number ASC")
  566. if not moves:
  567. rslt.update({
  568. 'msg_cover': _('There isn\'t any journal entry flagged for data inalterability yet for this journal.'),
  569. })
  570. results_by_journal['results'].append(rslt)
  571. continue
  572. previous_hash = u''
  573. start_move_info = []
  574. hash_corrupted = False
  575. current_hash_version = 1
  576. for move in moves:
  577. computed_hash = move.with_context(hash_version=current_hash_version)._compute_hash(previous_hash=previous_hash)
  578. while move.inalterable_hash != computed_hash and current_hash_version < MAX_HASH_VERSION:
  579. current_hash_version += 1
  580. computed_hash = move.with_context(hash_version=current_hash_version)._compute_hash(previous_hash=previous_hash)
  581. if move.inalterable_hash != computed_hash:
  582. rslt.update({'msg_cover': _('Corrupted data on journal entry with id %s.', move.id)})
  583. results_by_journal['results'].append(rslt)
  584. hash_corrupted = True
  585. break
  586. if not previous_hash:
  587. #save the date and sequence number of the first move hashed
  588. start_move_info = build_move_info(move)
  589. previous_hash = move.inalterable_hash
  590. end_move_info = build_move_info(move)
  591. if hash_corrupted:
  592. continue
  593. rslt.update({
  594. 'first_move_name': start_move_info[0],
  595. 'first_hash': start_move_info[1],
  596. 'first_move_date': format_date(self.env, start_move_info[2]),
  597. 'last_move_name': end_move_info[0],
  598. 'last_hash': end_move_info[1],
  599. 'last_move_date': format_date(self.env, end_move_info[2]),
  600. })
  601. if len(moves) == all_moves_count:
  602. rslt.update({'msg_cover': _('All entries are hashed.')})
  603. else:
  604. rslt.update({'msg_cover': _('Entries are hashed from %s (%s)') % (start_move_info[0], format_date(self.env, start_move_info[2]))})
  605. results_by_journal['results'].append(rslt)
  606. return results_by_journal
  607. def compute_fiscalyear_dates(self, current_date):
  608. """
  609. The role of this method is to provide a fallback when account_accounting is not installed.
  610. As the fiscal year is irrelevant when account_accounting is not installed, this method returns the calendar year.
  611. :param current_date: A datetime.date/datetime.datetime object.
  612. :return: A dictionary containing:
  613. * date_from
  614. * date_to
  615. """
  616. return {'date_from': datetime(year=current_date.year, month=1, day=1).date(),
  617. 'date_to': datetime(year=current_date.year, month=12, day=31).date()}
  618. @api.depends('country_code')
  619. def _compute_early_pay_discount_computation(self):
  620. for company in self:
  621. if company.country_code == 'BE':
  622. company.early_pay_discount_computation = 'mixed'
  623. elif company.country_code == 'NL':
  624. company.early_pay_discount_computation = 'excluded'
  625. else:
  626. company.early_pay_discount_computation = 'included'