account_account.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. # -*- coding: utf-8 -*-
  2. from odoo import api, fields, models, _, tools
  3. from odoo.osv import expression
  4. from odoo.exceptions import UserError, ValidationError
  5. from odoo.tools.float_utils import float_is_zero
  6. from bisect import bisect_left
  7. from collections import defaultdict
  8. import re
  9. ACCOUNT_REGEX = re.compile(r'(?:(\S*\d+\S*))?(.*)')
  10. ACCOUNT_CODE_REGEX = re.compile(r'^[A-Za-z0-9.]+$')
  11. class AccountAccount(models.Model):
  12. _name = "account.account"
  13. _inherit = ['mail.thread']
  14. _description = "Account"
  15. _order = "is_off_balance, code, company_id"
  16. _check_company_auto = True
  17. @api.constrains('account_type', 'reconcile')
  18. def _check_reconcile(self):
  19. for account in self:
  20. if account.account_type in ('asset_receivable', 'liability_payable') and not account.reconcile:
  21. raise ValidationError(_('You cannot have a receivable/payable account that is not reconcilable. (account code: %s)', account.code))
  22. @api.constrains('account_type')
  23. def _check_account_type_unique_current_year_earning(self):
  24. result = self._read_group(
  25. domain=[('account_type', '=', 'equity_unaffected')],
  26. fields=['company_id', 'ids:array_agg(id)'],
  27. groupby=['company_id'],
  28. )
  29. for res in result:
  30. if res.get('company_id_count', 0) >= 2:
  31. account_unaffected_earnings = self.browse(res['ids'])
  32. raise ValidationError(_('You cannot have more than one account with "Current Year Earnings" as type. (accounts: %s)', [a.code for a in account_unaffected_earnings]))
  33. name = fields.Char(string="Account Name", required=True, index='trigram', tracking=True)
  34. currency_id = fields.Many2one('res.currency', string='Account Currency', tracking=True,
  35. help="Forces all journal items in this account to have a specific currency (i.e. bank journals). If no currency is set, entries can use any currency.")
  36. code = fields.Char(size=64, required=True, tracking=True)
  37. deprecated = fields.Boolean(default=False, tracking=True)
  38. used = fields.Boolean(compute='_compute_used', search='_search_used')
  39. account_type = fields.Selection(
  40. selection=[
  41. ("asset_receivable", "Receivable"),
  42. ("asset_cash", "Bank and Cash"),
  43. ("asset_current", "Current Assets"),
  44. ("asset_non_current", "Non-current Assets"),
  45. ("asset_prepayments", "Prepayments"),
  46. ("asset_fixed", "Fixed Assets"),
  47. ("liability_payable", "Payable"),
  48. ("liability_credit_card", "Credit Card"),
  49. ("liability_current", "Current Liabilities"),
  50. ("liability_non_current", "Non-current Liabilities"),
  51. ("equity", "Equity"),
  52. ("equity_unaffected", "Current Year Earnings"),
  53. ("income", "Income"),
  54. ("income_other", "Other Income"),
  55. ("expense", "Expenses"),
  56. ("expense_depreciation", "Depreciation"),
  57. ("expense_direct_cost", "Cost of Revenue"),
  58. ("off_balance", "Off-Balance Sheet"),
  59. ],
  60. string="Type", tracking=True,
  61. required=True,
  62. compute='_compute_account_type', store=True, readonly=False, precompute=True,
  63. help="Account Type is used for information purpose, to generate country-specific legal reports, and set the rules to close a fiscal year and generate opening entries."
  64. )
  65. include_initial_balance = fields.Boolean(string="Bring Accounts Balance Forward",
  66. help="Used in reports to know if we should consider journal items from the beginning of time instead of from the fiscal year only. Account types that should be reset to zero at each new fiscal year (like expenses, revenue..) should not have this option set.",
  67. compute="_compute_include_initial_balance",
  68. store=True)
  69. internal_group = fields.Selection(
  70. selection=[
  71. ('equity', 'Equity'),
  72. ('asset', 'Asset'),
  73. ('liability', 'Liability'),
  74. ('income', 'Income'),
  75. ('expense', 'Expense'),
  76. ('off_balance', 'Off Balance'),
  77. ],
  78. string="Internal Group", readonly=True, compute="_compute_internal_group", store=True
  79. )
  80. #has_unreconciled_entries = fields.Boolean(compute='_compute_has_unreconciled_entries',
  81. # help="The account has at least one unreconciled debit and credit since last time the invoices & payments matching was performed.")
  82. reconcile = fields.Boolean(string='Allow Reconciliation', tracking=True,
  83. compute='_compute_reconcile', store=True, readonly=False,
  84. help="Check this box if this account allows invoices & payments matching of journal items.")
  85. tax_ids = fields.Many2many('account.tax', 'account_account_tax_default_rel',
  86. 'account_id', 'tax_id', string='Default Taxes',
  87. check_company=True,
  88. context={'append_type_to_tax_name': True})
  89. note = fields.Text('Internal Notes', tracking=True)
  90. company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True,
  91. default=lambda self: self.env.company)
  92. tag_ids = fields.Many2many('account.account.tag', 'account_account_account_tag', string='Tags', help="Optional tags you may want to assign for custom reporting", ondelete='restrict')
  93. group_id = fields.Many2one('account.group', compute='_compute_account_group', store=True, readonly=True,
  94. help="Account prefixes can determine account groups.")
  95. root_id = fields.Many2one('account.root', compute='_compute_account_root', store=True)
  96. allowed_journal_ids = fields.Many2many('account.journal', string="Allowed Journals", help="Define in which journals this account can be used. If empty, can be used in all journals.")
  97. opening_debit = fields.Monetary(string="Opening Debit", compute='_compute_opening_debit_credit', inverse='_set_opening_debit')
  98. opening_credit = fields.Monetary(string="Opening Credit", compute='_compute_opening_debit_credit', inverse='_set_opening_credit')
  99. opening_balance = fields.Monetary(string="Opening Balance", compute='_compute_opening_debit_credit', inverse='_set_opening_balance')
  100. is_off_balance = fields.Boolean(compute='_compute_is_off_balance', default=False, store=True, readonly=True)
  101. current_balance = fields.Float(compute='_compute_current_balance')
  102. related_taxes_amount = fields.Integer(compute='_compute_related_taxes_amount')
  103. _sql_constraints = [
  104. ('code_company_uniq', 'unique (code,company_id)', 'The code of the account must be unique per company !')
  105. ]
  106. non_trade = fields.Boolean(default=False,
  107. help="If set, this account will belong to Non Trade Receivable/Payable in reports and filters.\n"
  108. "If not, this account will belong to Trade Receivable/Payable in reports and filters.")
  109. @api.constrains('reconcile', 'internal_group', 'tax_ids')
  110. def _constrains_reconcile(self):
  111. for record in self:
  112. if record.internal_group == 'off_balance':
  113. if record.reconcile:
  114. raise UserError(_('An Off-Balance account can not be reconcilable'))
  115. if record.tax_ids:
  116. raise UserError(_('An Off-Balance account can not have taxes'))
  117. @api.constrains('allowed_journal_ids')
  118. def _constrains_allowed_journal_ids(self):
  119. self.env['account.move.line'].flush_model(['account_id', 'journal_id'])
  120. self.flush_recordset(['allowed_journal_ids'])
  121. self._cr.execute("""
  122. SELECT aml.id
  123. FROM account_move_line aml
  124. WHERE aml.account_id in %s
  125. AND EXISTS (SELECT 1 FROM account_account_account_journal_rel WHERE account_account_id = aml.account_id)
  126. AND NOT EXISTS (SELECT 1 FROM account_account_account_journal_rel WHERE account_account_id = aml.account_id AND account_journal_id = aml.journal_id)
  127. """, [tuple(self.ids)])
  128. ids = self._cr.fetchall()
  129. if ids:
  130. raise ValidationError(_('Some journal items already exist with this account but in other journals than the allowed ones.'))
  131. @api.constrains('currency_id')
  132. def _check_journal_consistency(self):
  133. ''' Ensure the currency set on the journal is the same as the currency set on the
  134. linked accounts.
  135. '''
  136. if not self:
  137. return
  138. self.env['account.account'].flush_model(['currency_id'])
  139. self.env['account.journal'].flush_model([
  140. 'currency_id',
  141. 'default_account_id',
  142. 'suspense_account_id',
  143. ])
  144. self.env['account.payment.method'].flush_model(['payment_type'])
  145. self.env['account.payment.method.line'].flush_model(['payment_method_id', 'payment_account_id'])
  146. self._cr.execute('''
  147. SELECT
  148. account.id,
  149. journal.id
  150. FROM account_journal journal
  151. JOIN res_company company ON company.id = journal.company_id
  152. JOIN account_account account ON account.id = journal.default_account_id
  153. WHERE journal.currency_id IS NOT NULL
  154. AND journal.currency_id != company.currency_id
  155. AND account.currency_id != journal.currency_id
  156. AND account.id IN %(accounts)s
  157. UNION ALL
  158. SELECT
  159. account.id,
  160. journal.id
  161. FROM account_journal journal
  162. JOIN res_company company ON company.id = journal.company_id
  163. JOIN account_payment_method_line apml ON apml.journal_id = journal.id
  164. JOIN account_payment_method apm on apm.id = apml.payment_method_id
  165. JOIN account_account account ON account.id = COALESCE(apml.payment_account_id, company.account_journal_payment_debit_account_id)
  166. WHERE journal.currency_id IS NOT NULL
  167. AND journal.currency_id != company.currency_id
  168. AND account.currency_id != journal.currency_id
  169. AND apm.payment_type = 'inbound'
  170. AND account.id IN %(accounts)s
  171. UNION ALL
  172. SELECT
  173. account.id,
  174. journal.id
  175. FROM account_journal journal
  176. JOIN res_company company ON company.id = journal.company_id
  177. JOIN account_payment_method_line apml ON apml.journal_id = journal.id
  178. JOIN account_payment_method apm on apm.id = apml.payment_method_id
  179. JOIN account_account account ON account.id = COALESCE(apml.payment_account_id, company.account_journal_payment_credit_account_id)
  180. WHERE journal.currency_id IS NOT NULL
  181. AND journal.currency_id != company.currency_id
  182. AND account.currency_id != journal.currency_id
  183. AND apm.payment_type = 'outbound'
  184. AND account.id IN %(accounts)s
  185. ''', {
  186. 'accounts': tuple(self.ids)
  187. })
  188. res = self._cr.fetchone()
  189. if res:
  190. account = self.env['account.account'].browse(res[0])
  191. journal = self.env['account.journal'].browse(res[1])
  192. raise ValidationError(_(
  193. "The foreign currency set on the journal '%(journal)s' and the account '%(account)s' must be the same.",
  194. journal=journal.display_name,
  195. account=account.display_name
  196. ))
  197. @api.constrains('company_id')
  198. def _check_company_consistency(self):
  199. if not self:
  200. return
  201. self.env['account.move.line'].flush_model(['account_id', 'company_id'])
  202. self.flush_recordset(['company_id'])
  203. self._cr.execute('''
  204. SELECT line.id
  205. FROM account_move_line line
  206. JOIN account_account account ON account.id = line.account_id
  207. WHERE line.account_id IN %s
  208. AND line.company_id != account.company_id
  209. ''', [tuple(self.ids)])
  210. if self._cr.fetchone():
  211. raise UserError(_("You can't change the company of your account since there are some journal items linked to it."))
  212. @api.constrains('account_type')
  213. def _check_account_type_sales_purchase_journal(self):
  214. if not self:
  215. return
  216. self.env['account.account'].flush_model(['account_type'])
  217. self.env['account.journal'].flush_model(['type', 'default_account_id'])
  218. self._cr.execute('''
  219. SELECT account.id
  220. FROM account_account account
  221. JOIN account_journal journal ON journal.default_account_id = account.id
  222. WHERE account.id IN %s
  223. AND account.account_type IN ('asset_receivable', 'liability_payable')
  224. AND journal.type IN ('sale', 'purchase')
  225. LIMIT 1;
  226. ''', [tuple(self.ids)])
  227. if self._cr.fetchone():
  228. raise ValidationError(_("The account is already in use in a 'sale' or 'purchase' journal. This means that the account's type couldn't be 'receivable' or 'payable'."))
  229. @api.constrains('reconcile')
  230. def _check_used_as_journal_default_debit_credit_account(self):
  231. accounts = self.filtered(lambda a: not a.reconcile)
  232. if not accounts:
  233. return
  234. self.flush_recordset(['reconcile'])
  235. self.env['account.journal'].flush_model(['company_id', 'default_account_id'])
  236. self.env['res.company'].flush_model(['account_journal_payment_credit_account_id', 'account_journal_payment_debit_account_id'])
  237. self.env['account.payment.method.line'].flush_model(['journal_id', 'payment_account_id'])
  238. self._cr.execute('''
  239. SELECT journal.id
  240. FROM account_journal journal
  241. JOIN res_company company on journal.company_id = company.id
  242. LEFT JOIN account_payment_method_line apml ON journal.id = apml.journal_id
  243. WHERE (
  244. company.account_journal_payment_credit_account_id IN %(accounts)s
  245. AND company.account_journal_payment_credit_account_id != journal.default_account_id
  246. ) OR (
  247. company.account_journal_payment_debit_account_id in %(accounts)s
  248. AND company.account_journal_payment_debit_account_id != journal.default_account_id
  249. ) OR (
  250. apml.payment_account_id IN %(accounts)s
  251. AND apml.payment_account_id != journal.default_account_id
  252. )
  253. ''', {
  254. 'accounts': tuple(accounts.ids),
  255. })
  256. rows = self._cr.fetchall()
  257. if rows:
  258. journals = self.env['account.journal'].browse([r[0] for r in rows])
  259. raise ValidationError(_(
  260. "This account is configured in %(journal_names)s journal(s) (ids %(journal_ids)s) as payment debit or credit account. This means that this account's type should be reconcilable.",
  261. journal_names=journals.mapped('display_name'),
  262. journal_ids=journals.ids
  263. ))
  264. @api.constrains('code')
  265. def _check_account_code(self):
  266. for account in self:
  267. if not re.match(ACCOUNT_CODE_REGEX, account.code):
  268. raise ValidationError(_(
  269. "The account code can only contain alphanumeric characters and dots."
  270. ))
  271. @api.constrains('account_type')
  272. def _check_account_is_bank_journal_bank_account(self):
  273. self.env['account.account'].flush_model(['account_type'])
  274. self.env['account.journal'].flush_model(['type', 'default_account_id'])
  275. self._cr.execute('''
  276. SELECT journal.id
  277. FROM account_journal journal
  278. JOIN account_account account ON journal.default_account_id = account.id
  279. WHERE account.account_type IN ('asset_receivable', 'liability_payable')
  280. AND account.id IN %s
  281. LIMIT 1;
  282. ''', [tuple(self.ids)])
  283. if self._cr.fetchone():
  284. raise ValidationError(_("You cannot change the type of an account set as Bank Account on a journal to Receivable or Payable."))
  285. @api.depends('code')
  286. def _compute_account_root(self):
  287. # this computes the first 2 digits of the account.
  288. # This field should have been a char, but the aim is to use it in a side panel view with hierarchy, and it's only supported by many2one fields so far.
  289. # So instead, we make it a many2one to a psql view with what we need as records.
  290. for record in self:
  291. record.root_id = (ord(record.code[0]) * 1000 + ord(record.code[1:2] or '\x00')) if record.code else False
  292. @api.depends('code')
  293. def _compute_account_group(self):
  294. if self.ids:
  295. self.env['account.group']._adapt_accounts_for_account_groups(self)
  296. else:
  297. self.group_id = False
  298. def _search_used(self, operator, value):
  299. if operator not in ['=', '!='] or not isinstance(value, bool):
  300. raise UserError(_('Operation not supported'))
  301. if operator != '=':
  302. value = not value
  303. self._cr.execute("""
  304. SELECT id FROM account_account account
  305. WHERE EXISTS (SELECT 1 FROM account_move_line aml WHERE aml.account_id = account.id LIMIT 1)
  306. """)
  307. return [('id', 'in' if value else 'not in', [r[0] for r in self._cr.fetchall()])]
  308. def _compute_used(self):
  309. ids = set(self._search_used('=', True)[0][2])
  310. for record in self:
  311. record.used = record.id in ids
  312. @api.model
  313. def _search_new_account_code(self, company, digits, prefix):
  314. for num in range(1, 10000):
  315. new_code = str(prefix.ljust(digits - 1, '0')) + str(num)
  316. rec = self.search([('code', '=', new_code), ('company_id', '=', company.id)], limit=1)
  317. if not rec:
  318. return new_code
  319. raise UserError(_('Cannot generate an unused account code.'))
  320. def _compute_current_balance(self):
  321. balances = {
  322. read['account_id'][0]: read['balance']
  323. for read in self.env['account.move.line']._read_group(
  324. domain=[('account_id', 'in', self.ids), ('parent_state', '=', 'posted')],
  325. fields=['balance', 'account_id'],
  326. groupby=['account_id'],
  327. )
  328. }
  329. for record in self:
  330. record.current_balance = balances.get(record.id, 0)
  331. def _compute_related_taxes_amount(self):
  332. for record in self:
  333. record.related_taxes_amount = self.env['account.tax'].search_count([
  334. '|',
  335. ('invoice_repartition_line_ids.account_id', '=', record.id),
  336. ('refund_repartition_line_ids.account_id', '=', record.id),
  337. ])
  338. def _compute_opening_debit_credit(self):
  339. self.opening_debit = 0
  340. self.opening_credit = 0
  341. self.opening_balance = 0
  342. if not self.ids:
  343. return
  344. self.env.cr.execute("""
  345. SELECT line.account_id,
  346. SUM(line.balance) AS balance,
  347. SUM(line.debit) AS debit,
  348. SUM(line.credit) AS credit
  349. FROM account_move_line line
  350. JOIN res_company comp ON comp.id = line.company_id
  351. WHERE line.move_id = comp.account_opening_move_id
  352. AND line.account_id IN %s
  353. GROUP BY line.account_id
  354. """, [tuple(self.ids)])
  355. result = {r['account_id']: r for r in self.env.cr.dictfetchall()}
  356. for record in self:
  357. res = result.get(record.id) or {'debit': 0, 'credit': 0, 'balance': 0}
  358. record.opening_debit = res['debit']
  359. record.opening_credit = res['credit']
  360. record.opening_balance = res['balance']
  361. @api.depends('code')
  362. def _compute_account_type(self):
  363. """ Compute the account type based on the account code.
  364. Search for the closest parent account code and sets the account type according to the parent.
  365. If there is no parent (e.g. the account code is lower than any other existing account code),
  366. the account type will be set to 'asset_current'.
  367. """
  368. accounts_to_process = self.filtered(lambda r: r.code and not r.account_type)
  369. all_accounts = self.search_read(
  370. domain=[('company_id', 'in', accounts_to_process.company_id.ids)],
  371. fields=['code', 'account_type', 'company_id'],
  372. order='code',
  373. )
  374. accounts_with_codes = defaultdict(dict)
  375. # We want to group accounts by company to only search for account codes of the current company
  376. for account in all_accounts:
  377. accounts_with_codes[account['company_id'][0]][account['code']] = account['account_type']
  378. for account in accounts_to_process:
  379. codes_list = list(accounts_with_codes[account.company_id.id].keys())
  380. closest_index = bisect_left(codes_list, account.code) - 1
  381. account.account_type = accounts_with_codes[account.company_id.id][codes_list[closest_index]] if closest_index != -1 else 'asset_current'
  382. @api.depends('internal_group')
  383. def _compute_is_off_balance(self):
  384. for account in self:
  385. account.is_off_balance = account.internal_group == "off_balance"
  386. @api.depends('account_type')
  387. def _compute_include_initial_balance(self):
  388. for account in self:
  389. account.include_initial_balance = account.account_type not in ('income', 'income_other', 'expense', 'expense_depreciation', 'expense_direct_cost', 'off_balance')
  390. @api.depends('account_type')
  391. def _compute_internal_group(self):
  392. for account in self:
  393. if account.account_type:
  394. account.internal_group = 'off_balance' if account.account_type == 'off_balance' else account.account_type.split('_')[0]
  395. @api.depends('account_type')
  396. def _compute_reconcile(self):
  397. for account in self:
  398. account.reconcile = account.account_type in ('asset_receivable', 'liability_payable')
  399. def _set_opening_debit(self):
  400. for record in self:
  401. record._set_opening_debit_credit(record.opening_debit, 'debit')
  402. def _set_opening_credit(self):
  403. for record in self:
  404. record._set_opening_debit_credit(record.opening_credit, 'credit')
  405. def _set_opening_balance(self):
  406. for account in self:
  407. if account.opening_balance:
  408. side = 'debit' if account.opening_balance > 0 else 'credit'
  409. account._set_opening_debit_credit(abs(account.opening_balance), side)
  410. def _set_opening_debit_credit(self, amount, field):
  411. """ Generic function called by both opening_debit and opening_credit's
  412. inverse function. 'Amount' parameter is the value to be set, and field
  413. either 'debit' or 'credit', depending on which one of these two fields
  414. got assigned.
  415. """
  416. # only set the opening debit/credit if the amount is not zero,
  417. # otherwise return early
  418. if float_is_zero(amount, precision_digits=2):
  419. return
  420. self.company_id.create_op_move_if_non_existant()
  421. opening_move = self.company_id.account_opening_move_id
  422. if opening_move.state == 'draft':
  423. # check whether we should create a new move line or modify an existing one
  424. account_op_lines = self.env['account.move.line'].search([('account_id', '=', self.id),
  425. ('move_id','=', opening_move.id),
  426. (field,'!=', False),
  427. (field,'!=', 0.0)]) # 0.0 condition important for import
  428. if account_op_lines:
  429. op_aml_debit = sum(account_op_lines.mapped('debit'))
  430. op_aml_credit = sum(account_op_lines.mapped('credit'))
  431. # There might be more than one line on this account if the opening entry was manually edited
  432. # If so, we need to merge all those lines into one before modifying its balance
  433. opening_move_line = account_op_lines[0]
  434. if len(account_op_lines) > 1:
  435. merge_write_cmd = [(1, opening_move_line.id, {'debit': op_aml_debit, 'credit': op_aml_credit, 'partner_id': None ,'name': _("Opening balance")})]
  436. unlink_write_cmd = [(2, line.id) for line in account_op_lines[1:]]
  437. opening_move.write({'line_ids': merge_write_cmd + unlink_write_cmd})
  438. if amount:
  439. # modify the line
  440. opening_move_line.with_context(check_move_validity=False)[field] = amount
  441. else:
  442. # delete the line (no need to keep a line with value = 0)
  443. opening_move_line.with_context(check_move_validity=False).unlink()
  444. elif amount:
  445. # create a new line, as none existed before
  446. self.env['account.move.line'].with_context(check_move_validity=False).create({
  447. 'name': _('Opening balance'),
  448. field: amount,
  449. 'move_id': opening_move.id,
  450. 'account_id': self.id,
  451. })
  452. # Then, we automatically balance the opening move, to make sure it stays valid
  453. if not 'import_file' in self.env.context:
  454. # When importing a file, avoid recomputing the opening move for each account and do it at the end, for better performances
  455. self.company_id._auto_balance_opening_move()
  456. @api.model
  457. def default_get(self, default_fields):
  458. """If we're creating a new account through a many2one, there are chances that we typed the account code
  459. instead of its name. In that case, switch both fields values.
  460. """
  461. if 'name' not in default_fields and 'code' not in default_fields:
  462. return super().default_get(default_fields)
  463. default_name = self._context.get('default_name')
  464. default_code = self._context.get('default_code')
  465. if default_name and not default_code:
  466. try:
  467. default_code = int(default_name)
  468. except ValueError:
  469. pass
  470. if default_code:
  471. default_name = False
  472. contextual_self = self.with_context(default_name=default_name, default_code=default_code)
  473. return super(AccountAccount, contextual_self).default_get(default_fields)
  474. @api.model
  475. def _get_most_frequent_accounts_for_partner(self, company_id, partner_id, move_type, filter_never_user_accounts=False, limit=None):
  476. """
  477. Returns the accounts ordered from most frequent to least frequent for a given partner
  478. and filtered according to the move type
  479. :param company_id: the company id
  480. :param partner_id: the partner id for which we want to retrieve the most frequent accounts
  481. :param move_type: the type of the move to know which type of accounts to retrieve
  482. :param filter_never_user_accounts: True if we should filter out accounts never used for the partner
  483. :param limit: the maximum number of accounts to retrieve
  484. :returns: List of account ids, ordered by frequency (from most to least frequent)
  485. """
  486. join = "INNER JOIN" if filter_never_user_accounts else "LEFT JOIN"
  487. limit = f"LIMIT {limit:d}" if limit else ""
  488. where_internal_group = ""
  489. if move_type in self.env['account.move'].get_inbound_types(include_receipts=True):
  490. where_internal_group = "AND account.internal_group = 'income'"
  491. elif move_type in self.env['account.move'].get_outbound_types(include_receipts=True):
  492. where_internal_group = "AND account.internal_group = 'expense'"
  493. self._cr.execute(f"""
  494. SELECT account.id
  495. FROM account_account account
  496. {join} account_move_line aml
  497. ON aml.account_id = account.id
  498. AND aml.partner_id = %s
  499. AND account.company_id = aml.company_id
  500. AND aml.date >= now() - interval '2 years'
  501. WHERE account.company_id = %s
  502. AND account.deprecated = FALSE
  503. {where_internal_group}
  504. GROUP BY account.id
  505. ORDER BY COUNT(aml.id) DESC, account.code
  506. {limit}
  507. """, [partner_id, company_id])
  508. return [r[0] for r in self._cr.fetchall()]
  509. @api.model
  510. def _get_most_frequent_account_for_partner(self, company_id, partner_id, move_type=None):
  511. most_frequent_account = self._get_most_frequent_accounts_for_partner(company_id, partner_id, move_type, filter_never_user_accounts=True, limit=1)
  512. return most_frequent_account[0] if most_frequent_account else False
  513. @api.model
  514. def _order_accounts_by_frequency_for_partner(self, company_id, partner_id, move_type=None):
  515. return self._get_most_frequent_accounts_for_partner(company_id, partner_id, move_type)
  516. @api.model
  517. def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
  518. if not name and self._context.get('partner_id') and self._context.get('move_type'):
  519. return self._order_accounts_by_frequency_for_partner(
  520. self.env.company.id, self._context.get('partner_id'), self._context.get('move_type'))
  521. args = args or []
  522. domain = []
  523. if name:
  524. if operator in ('=', '!='):
  525. domain = ['|', ('code', '=', name.split(' ')[0]), ('name', operator, name)]
  526. else:
  527. domain = ['|', ('code', '=ilike', name.split(' ')[0] + '%'), ('name', operator, name)]
  528. if operator in expression.NEGATIVE_TERM_OPERATORS:
  529. domain = ['&', '!'] + domain[1:]
  530. return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
  531. @api.onchange('account_type')
  532. def _onchange_account_type(self):
  533. if self.internal_group == 'off_balance':
  534. self.tax_ids = False
  535. def _split_code_name(self, code_name):
  536. # We only want to split the name on the first word if there is a digit in it
  537. code, name = ACCOUNT_REGEX.match(code_name or '').groups()
  538. return code, name.strip()
  539. @api.onchange('name')
  540. def _onchange_name(self):
  541. code, name = self._split_code_name(self.name)
  542. if code and not self.code:
  543. self.name = name
  544. self.code = code
  545. def name_get(self):
  546. result = []
  547. for account in self:
  548. name = account.code + ' ' + account.name
  549. result.append((account.id, name))
  550. return result
  551. @api.returns('self', lambda value: value.id)
  552. def copy(self, default=None):
  553. default = dict(default or {})
  554. if default.get('code', False):
  555. return super(AccountAccount, self).copy(default)
  556. try:
  557. default['code'] = (str(int(self.code) + 10) or '').zfill(len(self.code))
  558. default.setdefault('name', _("%s (copy)") % (self.name or ''))
  559. while self.env['account.account'].search([('code', '=', default['code']),
  560. ('company_id', '=', default.get('company_id', False) or self.company_id.id)], limit=1):
  561. default['code'] = (str(int(default['code']) + 10) or '')
  562. default['name'] = _("%s (copy)") % (self.name or '')
  563. except ValueError:
  564. default['code'] = _("%s.copy") % (self.code or '')
  565. default['name'] = self.name
  566. return super(AccountAccount, self).copy(default)
  567. @api.model
  568. def load(self, fields, data):
  569. """ Overridden for better performances when importing a list of account
  570. with opening debit/credit. In that case, the auto-balance is postpone
  571. until the whole file has been imported.
  572. """
  573. rslt = super(AccountAccount, self).load(fields, data)
  574. if 'import_file' in self.env.context and 'opening_balance' in fields:
  575. companies = self.search([('id', 'in', rslt['ids'])]).mapped('company_id')
  576. for company in companies:
  577. if company.account_opening_move_id.filtered(lambda m: m.state == "posted"):
  578. raise UserError(
  579. _('You cannot import the "openning_balance" if the opening move (%s) is already posted. \
  580. If you are absolutely sure you want to modify the opening balance of your accounts, reset the move to draft.',
  581. company.account_opening_move_id.name))
  582. company._auto_balance_opening_move()
  583. # the current_balance of the account only includes posted moves and
  584. # would always amount to 0 after the import if we didn't post the opening move
  585. company.account_opening_move_id.action_post()
  586. return rslt
  587. def _toggle_reconcile_to_true(self):
  588. '''Toggle the `reconcile´ boolean from False -> True
  589. Note that: lines with debit = credit = amount_currency = 0 are set to `reconciled´ = True
  590. '''
  591. if not self.ids:
  592. return None
  593. query = """
  594. UPDATE account_move_line SET
  595. reconciled = CASE WHEN debit = 0 AND credit = 0 AND amount_currency = 0
  596. THEN true ELSE false END,
  597. amount_residual = (debit-credit),
  598. amount_residual_currency = amount_currency
  599. WHERE full_reconcile_id IS NULL and account_id IN %s
  600. """
  601. self.env.cr.execute(query, [tuple(self.ids)])
  602. def _toggle_reconcile_to_false(self):
  603. '''Toggle the `reconcile´ boolean from True -> False
  604. Note that it is disallowed if some lines are partially reconciled.
  605. '''
  606. if not self.ids:
  607. return None
  608. partial_lines_count = self.env['account.move.line'].search_count([
  609. ('account_id', 'in', self.ids),
  610. ('full_reconcile_id', '=', False),
  611. ('|'),
  612. ('matched_debit_ids', '!=', False),
  613. ('matched_credit_ids', '!=', False),
  614. ])
  615. if partial_lines_count > 0:
  616. raise UserError(_('You cannot switch an account to prevent the reconciliation '
  617. 'if some partial reconciliations are still pending.'))
  618. query = """
  619. UPDATE account_move_line
  620. SET amount_residual = 0, amount_residual_currency = 0
  621. WHERE full_reconcile_id IS NULL AND account_id IN %s
  622. """
  623. self.env.cr.execute(query, [tuple(self.ids)])
  624. @api.model
  625. def name_create(self, name):
  626. """ Split the account name into account code and account name in import.
  627. When importing a file with accounts, the account code and name may be both entered in the name column.
  628. In this case, the name will be split into code and name.
  629. """
  630. if 'import_file' in self.env.context:
  631. code, name = self._split_code_name(name)
  632. return self.create({'code': code, 'name': name}).name_get()[0]
  633. raise ValidationError(_("Please create new accounts from the Chart of Accounts menu."))
  634. def write(self, vals):
  635. # Do not allow changing the company_id when account_move_line already exist
  636. if vals.get('company_id', False):
  637. move_lines = self.env['account.move.line'].search([('account_id', 'in', self.ids)], limit=1)
  638. for account in self:
  639. if (account.company_id.id != vals['company_id']) and move_lines:
  640. raise UserError(_('You cannot change the owner company of an account that already contains journal items.'))
  641. if 'reconcile' in vals:
  642. if vals['reconcile']:
  643. self.filtered(lambda r: not r.reconcile)._toggle_reconcile_to_true()
  644. else:
  645. self.filtered(lambda r: r.reconcile)._toggle_reconcile_to_false()
  646. if vals.get('currency_id'):
  647. for account in self:
  648. if self.env['account.move.line'].search_count([('account_id', '=', account.id), ('currency_id', 'not in', (False, vals['currency_id']))]):
  649. raise UserError(_('You cannot set a currency on this account as it already has some journal entries having a different foreign currency.'))
  650. return super(AccountAccount, self).write(vals)
  651. @api.ondelete(at_uninstall=False)
  652. def _unlink_except_contains_journal_items(self):
  653. if self.env['account.move.line'].search([('account_id', 'in', self.ids)], limit=1):
  654. raise UserError(_('You cannot perform this action on an account that contains journal items.'))
  655. @api.ondelete(at_uninstall=False)
  656. def _unlink_except_account_set_on_customer(self):
  657. #Checking whether the account is set as a property to any Partner or not
  658. values = ['account.account,%s' % (account_id,) for account_id in self.ids]
  659. partner_prop_acc = self.env['ir.property'].sudo().search([('value_reference', 'in', values)], limit=1)
  660. if partner_prop_acc:
  661. account_name = partner_prop_acc.get_by_record().display_name
  662. raise UserError(
  663. _('You cannot remove/deactivate the account %s which is set on a customer or vendor.', account_name)
  664. )
  665. @api.ondelete(at_uninstall=False)
  666. def _unlink_except_linked_to_fiscal_position(self):
  667. if self.env['account.fiscal.position.account'].search(['|', ('account_src_id', 'in', self.ids), ('account_dest_id', 'in', self.ids)], limit=1):
  668. raise UserError(_('You cannot remove/deactivate the accounts "%s" which are set on the account mapping of a fiscal position.', ', '.join(f"{a.code} - {a.name}" for a in self)))
  669. @api.ondelete(at_uninstall=False)
  670. def _unlink_except_linked_to_tax_repartition_line(self):
  671. if self.env['account.tax.repartition.line'].search([('account_id', 'in', self.ids)], limit=1):
  672. raise UserError(_('You cannot remove/deactivate the accounts "%s" which are set on a tax repartition line.', ', '.join(f"{a.code} - {a.name}" for a in self)))
  673. def action_read_account(self):
  674. self.ensure_one()
  675. return {
  676. 'name': self.display_name,
  677. 'type': 'ir.actions.act_window',
  678. 'view_type': 'form',
  679. 'view_mode': 'form',
  680. 'res_model': 'account.account',
  681. 'res_id': self.id,
  682. }
  683. def action_duplicate_accounts(self):
  684. for account in self.browse(self.env.context['active_ids']):
  685. account.copy()
  686. def action_open_related_taxes(self):
  687. related_taxes_ids = self.env['account.tax'].search([
  688. '|',
  689. ('invoice_repartition_line_ids.account_id', '=', self.id),
  690. ('refund_repartition_line_ids.account_id', '=', self.id),
  691. ]).ids
  692. return {
  693. 'type': 'ir.actions.act_window',
  694. 'name': _('Taxes'),
  695. 'res_model': 'account.tax',
  696. 'view_type': 'list',
  697. 'view_mode': 'list',
  698. 'views': [[False, 'list'], [False, 'form']],
  699. 'domain': [('id', 'in', related_taxes_ids)],
  700. }
  701. @api.model
  702. def get_import_templates(self):
  703. return [{
  704. 'label': _('Import Template for Chart of Accounts'),
  705. 'template': '/account/static/xls/coa_import_template.xlsx'
  706. }]
  707. def _merge_method(self, destination, source):
  708. raise UserError(_("You cannot merge accounts."))
  709. class AccountGroup(models.Model):
  710. _name = "account.group"
  711. _description = 'Account Group'
  712. _parent_store = True
  713. _order = 'code_prefix_start'
  714. parent_id = fields.Many2one('account.group', index=True, ondelete='cascade', readonly=True)
  715. parent_path = fields.Char(index=True, unaccent=False)
  716. name = fields.Char(required=True)
  717. code_prefix_start = fields.Char()
  718. code_prefix_end = fields.Char()
  719. company_id = fields.Many2one('res.company', required=True, readonly=True, default=lambda self: self.env.company)
  720. _sql_constraints = [
  721. (
  722. 'check_length_prefix',
  723. 'CHECK(char_length(COALESCE(code_prefix_start, \'\')) = char_length(COALESCE(code_prefix_end, \'\')))',
  724. 'The length of the starting and the ending code prefix must be the same'
  725. ),
  726. ]
  727. @api.onchange('code_prefix_start')
  728. def _onchange_code_prefix_start(self):
  729. if not self.code_prefix_end or self.code_prefix_end < self.code_prefix_start:
  730. self.code_prefix_end = self.code_prefix_start
  731. @api.onchange('code_prefix_end')
  732. def _onchange_code_prefix_end(self):
  733. if not self.code_prefix_start or self.code_prefix_start > self.code_prefix_end:
  734. self.code_prefix_start = self.code_prefix_end
  735. def name_get(self):
  736. result = []
  737. for group in self:
  738. prefix = group.code_prefix_start and str(group.code_prefix_start)
  739. if prefix and group.code_prefix_end != group.code_prefix_start:
  740. prefix += '-' + str(group.code_prefix_end)
  741. name = (prefix and (prefix + ' ') or '') + group.name
  742. result.append((group.id, name))
  743. return result
  744. @api.model
  745. def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
  746. args = args or []
  747. if operator == 'ilike' and not (name or '').strip():
  748. domain = []
  749. else:
  750. criteria_operator = ['|'] if operator not in expression.NEGATIVE_TERM_OPERATORS else ['&', '!']
  751. domain = criteria_operator + [('code_prefix_start', '=ilike', name + '%'), ('name', operator, name)]
  752. return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
  753. @api.constrains('code_prefix_start', 'code_prefix_end')
  754. def _constraint_prefix_overlap(self):
  755. self.flush_model()
  756. query = """
  757. SELECT other.id FROM account_group this
  758. JOIN account_group other
  759. ON char_length(other.code_prefix_start) = char_length(this.code_prefix_start)
  760. AND other.id != this.id
  761. AND other.company_id = this.company_id
  762. AND (
  763. other.code_prefix_start <= this.code_prefix_start AND this.code_prefix_start <= other.code_prefix_end
  764. OR
  765. other.code_prefix_start >= this.code_prefix_start AND this.code_prefix_end >= other.code_prefix_start
  766. )
  767. WHERE this.id IN %(ids)s
  768. """
  769. self.env.cr.execute(query, {'ids': tuple(self.ids)})
  770. res = self.env.cr.fetchall()
  771. if res:
  772. raise ValidationError(_('Account Groups with the same granularity can\'t overlap'))
  773. @api.model_create_multi
  774. def create(self, vals_list):
  775. for vals in vals_list:
  776. if 'code_prefix_start' in vals and not vals.get('code_prefix_end'):
  777. vals['code_prefix_end'] = vals['code_prefix_start']
  778. res_ids = super(AccountGroup, self).create(vals_list)
  779. res_ids._adapt_accounts_for_account_groups()
  780. res_ids._adapt_parent_account_group()
  781. return res_ids
  782. def write(self, vals):
  783. res = super(AccountGroup, self).write(vals)
  784. if 'code_prefix_start' in vals or 'code_prefix_end' in vals:
  785. self._adapt_accounts_for_account_groups()
  786. self._adapt_parent_account_group()
  787. return res
  788. def unlink(self):
  789. for record in self:
  790. account_ids = self.env['account.account'].search([('group_id', '=', record.id)])
  791. account_ids.write({'group_id': record.parent_id.id})
  792. children_ids = self.env['account.group'].search([('parent_id', '=', record.id)])
  793. children_ids.write({'parent_id': record.parent_id.id})
  794. super(AccountGroup, self).unlink()
  795. def _adapt_accounts_for_account_groups(self, account_ids=None):
  796. """Ensure consistency between accounts and account groups.
  797. Find and set the most specific group matching the code of the account.
  798. The most specific is the one with the longest prefixes and with the starting
  799. prefix being smaller than the account code and the ending prefix being greater.
  800. """
  801. company_ids = account_ids.company_id.ids if account_ids else self.company_id.ids
  802. account_ids = account_ids.ids if account_ids else []
  803. if not company_ids and not account_ids:
  804. return
  805. self.flush_model()
  806. self.env['account.account'].flush_model()
  807. account_where_clause = ''
  808. where_params = [tuple(company_ids)]
  809. if account_ids:
  810. account_where_clause = 'AND account.id IN %s'
  811. where_params.append(tuple(account_ids))
  812. self._cr.execute(f'''
  813. WITH candidates_account_groups AS (
  814. SELECT
  815. account.id AS account_id,
  816. ARRAY_AGG(agroup.id ORDER BY char_length(agroup.code_prefix_start) DESC, agroup.id) AS group_ids
  817. FROM account_account account
  818. LEFT JOIN account_group agroup
  819. ON agroup.code_prefix_start <= LEFT(account.code, char_length(agroup.code_prefix_start))
  820. AND agroup.code_prefix_end >= LEFT(account.code, char_length(agroup.code_prefix_end))
  821. AND agroup.company_id = account.company_id
  822. WHERE account.company_id IN %s {account_where_clause}
  823. GROUP BY account.id
  824. )
  825. UPDATE account_account
  826. SET group_id = rel.group_ids[1]
  827. FROM candidates_account_groups rel
  828. WHERE account_account.id = rel.account_id
  829. ''', where_params)
  830. self.env['account.account'].invalidate_model(['group_id'])
  831. def _adapt_parent_account_group(self):
  832. """Ensure consistency of the hierarchy of account groups.
  833. Find and set the most specific parent for each group.
  834. The most specific is the one with the longest prefixes and with the starting
  835. prefix being smaller than the child prefixes and the ending prefix being greater.
  836. """
  837. if not self:
  838. return
  839. self.flush_model()
  840. query = """
  841. WITH relation AS (
  842. SELECT DISTINCT FIRST_VALUE(parent.id) OVER (PARTITION BY child.id ORDER BY child.id, char_length(parent.code_prefix_start) DESC) AS parent_id,
  843. child.id AS child_id
  844. FROM account_group parent
  845. JOIN account_group child
  846. ON char_length(parent.code_prefix_start) < char_length(child.code_prefix_start)
  847. AND parent.code_prefix_start <= LEFT(child.code_prefix_start, char_length(parent.code_prefix_start))
  848. AND parent.code_prefix_end >= LEFT(child.code_prefix_end, char_length(parent.code_prefix_end))
  849. AND parent.id != child.id
  850. AND parent.company_id = child.company_id
  851. WHERE child.company_id IN %(company_ids)s
  852. )
  853. UPDATE account_group child
  854. SET parent_id = relation.parent_id
  855. FROM relation
  856. WHERE child.id = relation.child_id;
  857. """
  858. self.env.cr.execute(query, {'company_ids': tuple(self.company_id.ids)})
  859. self.invalidate_model(['parent_id'])
  860. self.search([('company_id', 'in', self.company_id.ids)])._parent_store_update()
  861. class AccountRoot(models.Model):
  862. _name = 'account.root'
  863. _description = 'Account codes first 2 digits'
  864. _auto = False
  865. name = fields.Char()
  866. parent_id = fields.Many2one('account.root')
  867. company_id = fields.Many2one('res.company')
  868. def init(self):
  869. tools.drop_view_if_exists(self.env.cr, self._table)
  870. self.env.cr.execute('''
  871. CREATE OR REPLACE VIEW %s AS (
  872. SELECT DISTINCT ASCII(code) * 1000 + ASCII(SUBSTRING(code,2,1)) AS id,
  873. LEFT(code,2) AS name,
  874. ASCII(code) AS parent_id,
  875. company_id
  876. FROM account_account WHERE code IS NOT NULL
  877. UNION ALL
  878. SELECT DISTINCT ASCII(code) AS id,
  879. LEFT(code,1) AS name,
  880. NULL::int AS parent_id,
  881. company_id
  882. FROM account_account WHERE code IS NOT NULL
  883. )''' % (self._table,)
  884. )