account_tax.py 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. # -*- coding: utf-8 -*-
  2. from odoo import api, fields, models, _, Command
  3. from odoo.osv import expression
  4. from odoo.tools.float_utils import float_round
  5. from odoo.exceptions import UserError, ValidationError
  6. from odoo.tools.misc import formatLang
  7. from odoo.tools import frozendict
  8. from collections import defaultdict
  9. import math
  10. import re
  11. TYPE_TAX_USE = [
  12. ('sale', 'Sales'),
  13. ('purchase', 'Purchases'),
  14. ('none', 'None'),
  15. ]
  16. class AccountTaxGroup(models.Model):
  17. _name = 'account.tax.group'
  18. _description = 'Tax Group'
  19. _order = 'sequence asc'
  20. name = fields.Char(required=True, translate=True)
  21. sequence = fields.Integer(default=10)
  22. property_tax_payable_account_id = fields.Many2one(
  23. comodel_name='account.account',
  24. company_dependent=True,
  25. string='Tax Payable Account',
  26. help="Tax current account used as a counterpart to the Tax Closing Entry when in favor of the authorities.")
  27. property_tax_receivable_account_id = fields.Many2one(
  28. comodel_name='account.account',
  29. company_dependent=True,
  30. string='Tax Receivable Account',
  31. help="Tax current account used as a counterpart to the Tax Closing Entry when in favor of the company.")
  32. property_advance_tax_payment_account_id = fields.Many2one(
  33. comodel_name='account.account',
  34. company_dependent=True,
  35. string='Tax Advance Account',
  36. help="Downpayments posted on this account will be considered by the Tax Closing Entry.")
  37. country_id = fields.Many2one(string="Country", comodel_name='res.country', help="The country for which this tax group is applicable.")
  38. country_code = fields.Char(related="country_id.code")
  39. preceding_subtotal = fields.Char(
  40. string="Preceding Subtotal",
  41. help="If set, this value will be used on documents as the label of a subtotal excluding this tax group before displaying it. " \
  42. "If not set, the tax group will be displayed after the 'Untaxed amount' subtotal.",
  43. )
  44. @api.model
  45. def _check_misconfigured_tax_groups(self, company, countries):
  46. """ Searches the tax groups used on the taxes from company in countries that don't have
  47. at least a tax payable account, a tax receivable account or an advance tax payment account.
  48. :return: A boolean telling whether or not there are misconfigured groups for any
  49. of these countries, in this company
  50. """
  51. # This cannot be refactored to check for misconfigured groups instead
  52. # because of an ORM limitation with search on property fields:
  53. # searching on property = False also returns the properties using the default value,
  54. # even if it's non-empty.
  55. # (introduced here https://github.com/odoo/odoo/pull/6044)
  56. all_configured_groups_ids = self.with_company(company)._search([
  57. ('property_tax_payable_account_id', '!=', False),
  58. ('property_tax_receivable_account_id', '!=', False),
  59. ])
  60. return bool(self.env['account.tax'].search([
  61. ('company_id', '=', company.id),
  62. ('tax_group_id', 'not in', all_configured_groups_ids),
  63. ('country_id', 'in', countries.ids),
  64. ], limit=1))
  65. class AccountTax(models.Model):
  66. _name = 'account.tax'
  67. _description = 'Tax'
  68. _order = 'sequence,id'
  69. _check_company_auto = True
  70. _rec_names_search = ['name', 'description']
  71. @api.model
  72. def _default_tax_group(self):
  73. return self.env.ref('account.tax_group_taxes')
  74. name = fields.Char(string='Tax Name', required=True)
  75. name_searchable = fields.Char(store=False, search='_search_name',
  76. help="This dummy field lets us use another search method on the field 'name'."
  77. "This allows more freedom on how to search the 'name' compared to 'filter_domain'."
  78. "See '_search_name' and '_parse_name_search' for why this is not possible with 'filter_domain'.")
  79. type_tax_use = fields.Selection(TYPE_TAX_USE, string='Tax Type', required=True, default="sale",
  80. help="Determines where the tax is selectable. Note : 'None' means a tax can't be used by itself, however it can still be used in a group. 'adjustment' is used to perform tax adjustment.")
  81. tax_scope = fields.Selection([('service', 'Services'), ('consu', 'Goods')], string="Tax Scope", help="Restrict the use of taxes to a type of product.")
  82. amount_type = fields.Selection(default='percent', string="Tax Computation", required=True,
  83. selection=[('group', 'Group of Taxes'), ('fixed', 'Fixed'), ('percent', 'Percentage of Price'), ('division', 'Percentage of Price Tax Included')],
  84. help="""
  85. - Group of Taxes: The tax is a set of sub taxes.
  86. - Fixed: The tax amount stays the same whatever the price.
  87. - Percentage of Price: The tax amount is a % of the price:
  88. e.g 100 * (1 + 10%) = 110 (not price included)
  89. e.g 110 / (1 + 10%) = 100 (price included)
  90. - Percentage of Price Tax Included: The tax amount is a division of the price:
  91. e.g 180 / (1 - 10%) = 200 (not price included)
  92. e.g 200 * (1 - 10%) = 180 (price included)
  93. """)
  94. active = fields.Boolean(default=True, help="Set active to false to hide the tax without removing it.")
  95. company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.company)
  96. children_tax_ids = fields.Many2many('account.tax',
  97. 'account_tax_filiation_rel', 'parent_tax', 'child_tax',
  98. check_company=True,
  99. string='Children Taxes')
  100. sequence = fields.Integer(required=True, default=1,
  101. help="The sequence field is used to define order in which the tax lines are applied.")
  102. amount = fields.Float(required=True, digits=(16, 4), default=0.0)
  103. real_amount = fields.Float(string='Real amount to apply', compute='_compute_real_amount', store=True)
  104. description = fields.Char(string='Label on Invoices')
  105. price_include = fields.Boolean(string='Included in Price', default=False,
  106. help="Check this if the price you use on the product and invoices includes this tax.")
  107. include_base_amount = fields.Boolean(string='Affect Base of Subsequent Taxes', default=False,
  108. help="If set, taxes with a higher sequence than this one will be affected by it, provided they accept it.")
  109. is_base_affected = fields.Boolean(
  110. string="Base Affected by Previous Taxes",
  111. default=True,
  112. help="If set, taxes with a lower sequence might affect this one, provided they try to do it.")
  113. analytic = fields.Boolean(string="Include in Analytic Cost", help="If set, the amount computed by this tax will be assigned to the same analytic account as the invoice line (if any)")
  114. tax_group_id = fields.Many2one('account.tax.group', string="Tax Group", default=_default_tax_group, required=True,
  115. domain="[('country_id', 'in', (country_id, False))]")
  116. # Technical field to make the 'tax_exigibility' field invisible if the same named field is set to false in 'res.company' model
  117. hide_tax_exigibility = fields.Boolean(string='Hide Use Cash Basis Option', related='company_id.tax_exigibility', readonly=True)
  118. tax_exigibility = fields.Selection(
  119. [('on_invoice', 'Based on Invoice'),
  120. ('on_payment', 'Based on Payment'),
  121. ], string='Tax Exigibility', default='on_invoice',
  122. help="Based on Invoice: the tax is due as soon as the invoice is validated.\n"
  123. "Based on Payment: the tax is due as soon as the payment of the invoice is received.")
  124. cash_basis_transition_account_id = fields.Many2one(string="Cash Basis Transition Account",
  125. check_company=True,
  126. domain="[('deprecated', '=', False), ('company_id', '=', company_id)]",
  127. comodel_name='account.account',
  128. help="Account used to transition the tax amount for cash basis taxes. It will contain the tax amount as long as the original invoice has not been reconciled ; at reconciliation, this amount cancelled on this account and put on the regular tax account.")
  129. invoice_repartition_line_ids = fields.One2many(string="Distribution for Invoices", comodel_name="account.tax.repartition.line", inverse_name="invoice_tax_id", copy=True, help="Distribution when the tax is used on an invoice")
  130. refund_repartition_line_ids = fields.One2many(string="Distribution for Refund Invoices", comodel_name="account.tax.repartition.line", inverse_name="refund_tax_id", copy=True, help="Distribution when the tax is used on a refund")
  131. country_id = fields.Many2one(string="Country", comodel_name='res.country', required=True, help="The country for which this tax is applicable.")
  132. country_code = fields.Char(related='country_id.code', readonly=True)
  133. _sql_constraints = [
  134. ('name_company_uniq', 'unique(name, company_id, type_tax_use, tax_scope)', 'Tax names must be unique !'),
  135. ]
  136. @api.constrains('tax_group_id')
  137. def validate_tax_group_id(self):
  138. for record in self:
  139. if record.tax_group_id.country_id and record.tax_group_id.country_id != record.country_id:
  140. raise ValidationError(_("The tax group must have the same country_id as the tax using it."))
  141. @api.model
  142. def default_get(self, fields_list):
  143. # company_id is added so that we are sure to fetch a default value from it to use in repartition lines, below
  144. rslt = super(AccountTax, self).default_get(fields_list + ['company_id'])
  145. company_id = rslt.get('company_id')
  146. company = self.env['res.company'].browse(company_id)
  147. if 'country_id' in fields_list:
  148. rslt['country_id'] = company.account_fiscal_country_id.id
  149. if 'refund_repartition_line_ids' in fields_list:
  150. rslt['refund_repartition_line_ids'] = [
  151. (0, 0, {'repartition_type': 'base', 'tag_ids': [], 'company_id': company_id}),
  152. (0, 0, {'repartition_type': 'tax', 'tag_ids': [], 'company_id': company_id}),
  153. ]
  154. if 'invoice_repartition_line_ids' in fields_list:
  155. rslt['invoice_repartition_line_ids'] = [
  156. (0, 0, {'repartition_type': 'base', 'tag_ids': [], 'company_id': company_id}),
  157. (0, 0, {'repartition_type': 'tax', 'tag_ids': [], 'company_id': company_id}),
  158. ]
  159. return rslt
  160. @staticmethod
  161. def _parse_name_search(name):
  162. """
  163. Parse the name to search the taxes faster.
  164. Technical: 0EUM => 0%E%U%M
  165. 21M => 2%1%M% where the % represents 0, 1 or multiple characters in a SQL 'LIKE' search.
  166. 21" M" => 2%1% M%
  167. 21" M"co => 2%1% M%c%o%
  168. Examples: 0EUM => VAT 0% EU M.
  169. 21M => 21% M , 21% EU M, 21% M.Cocont and 21% EX M.
  170. 21" M" => 21% M and 21% M.Cocont.
  171. 21" M"co => 21% M.Cocont.
  172. """
  173. regex = r"(\"[^\"]*\")"
  174. list_name = re.split(regex, name)
  175. for i, name in enumerate(list_name.copy()):
  176. if not name:
  177. continue
  178. if re.search(regex, name):
  179. list_name[i] = "%" + name.replace("%", "_").replace("\"", "") + "%"
  180. else:
  181. list_name[i] = '%'.join(re.sub(r"\W+", "", name))
  182. return ''.join(list_name)
  183. @api.model
  184. def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None):
  185. if operator in ("ilike", "like"):
  186. name = AccountTax._parse_name_search(name)
  187. return super()._name_search(name, args, operator, limit, name_get_uid)
  188. def _search_name(self, operator, value):
  189. if operator not in ("ilike", "like") or not isinstance(value, str):
  190. return [('name', operator, value)]
  191. return [('name', operator, AccountTax._parse_name_search(value))]
  192. def _check_repartition_lines(self, lines):
  193. self.ensure_one()
  194. base_line = lines.filtered(lambda x: x.repartition_type == 'base')
  195. if len(base_line) != 1:
  196. raise ValidationError(_("Invoice and credit note distribution should each contain exactly one line for the base."))
  197. @api.constrains('invoice_repartition_line_ids', 'refund_repartition_line_ids')
  198. def _validate_repartition_lines(self):
  199. for record in self:
  200. # if the tax is an aggregation of its sub-taxes (group) it can have no repartition lines
  201. if record.amount_type == 'group' and \
  202. not record.invoice_repartition_line_ids and \
  203. not record.refund_repartition_line_ids:
  204. continue
  205. invoice_repartition_line_ids = record.invoice_repartition_line_ids.sorted()
  206. refund_repartition_line_ids = record.refund_repartition_line_ids.sorted()
  207. record._check_repartition_lines(invoice_repartition_line_ids)
  208. record._check_repartition_lines(refund_repartition_line_ids)
  209. if len(invoice_repartition_line_ids) != len(refund_repartition_line_ids):
  210. raise ValidationError(_("Invoice and credit note distribution should have the same number of lines."))
  211. if not invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') or \
  212. not refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax'):
  213. raise ValidationError(_("Invoice and credit note repartition should have at least one tax repartition line."))
  214. index = 0
  215. while index < len(invoice_repartition_line_ids):
  216. inv_rep_ln = invoice_repartition_line_ids[index]
  217. ref_rep_ln = refund_repartition_line_ids[index]
  218. if inv_rep_ln.repartition_type != ref_rep_ln.repartition_type or inv_rep_ln.factor_percent != ref_rep_ln.factor_percent:
  219. raise ValidationError(_("Invoice and credit note distribution should match (same percentages, in the same order)."))
  220. index += 1
  221. @api.constrains('children_tax_ids', 'type_tax_use')
  222. def _check_children_scope(self):
  223. for tax in self:
  224. if not tax._check_m2m_recursion('children_tax_ids'):
  225. raise ValidationError(_("Recursion found for tax '%s'.") % (tax.name,))
  226. if any(child.type_tax_use not in ('none', tax.type_tax_use) or child.tax_scope != tax.tax_scope for child in tax.children_tax_ids):
  227. raise ValidationError(_('The application scope of taxes in a group must be either the same as the group or left empty.'))
  228. @api.constrains('company_id')
  229. def _check_company_consistency(self):
  230. if not self:
  231. return
  232. self.env['account.move.line'].flush_model(['company_id', 'tax_line_id'])
  233. self.flush_recordset(['company_id'])
  234. self._cr.execute('''
  235. SELECT line.id
  236. FROM account_move_line line
  237. JOIN account_tax tax ON tax.id = line.tax_line_id
  238. WHERE line.tax_line_id IN %s
  239. AND line.company_id != tax.company_id
  240. UNION ALL
  241. SELECT line.id
  242. FROM account_move_line_account_tax_rel tax_rel
  243. JOIN account_tax tax ON tax.id = tax_rel.account_tax_id
  244. JOIN account_move_line line ON line.id = tax_rel.account_move_line_id
  245. WHERE tax_rel.account_tax_id IN %s
  246. AND line.company_id != tax.company_id
  247. ''', [tuple(self.ids)] * 2)
  248. if self._cr.fetchone():
  249. raise UserError(_("You can't change the company of your tax since there are some journal items linked to it."))
  250. @api.returns('self', lambda value: value.id)
  251. def copy(self, default=None):
  252. default = dict(default or {})
  253. if 'name' not in default:
  254. default['name'] = _("%s (Copy)") % self.name
  255. return super(AccountTax, self).copy(default=default)
  256. def name_get(self):
  257. name_list = []
  258. type_tax_use = dict(self._fields['type_tax_use']._description_selection(self.env))
  259. tax_scope = dict(self._fields['tax_scope']._description_selection(self.env))
  260. for record in self:
  261. name = record.name
  262. if self._context.get('append_type_to_tax_name'):
  263. name += ' (%s)' % type_tax_use.get(record.type_tax_use)
  264. if record.tax_scope:
  265. name += ' (%s)' % tax_scope.get(record.tax_scope)
  266. name_list += [(record.id, name)]
  267. return name_list
  268. @api.model
  269. def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
  270. context = self._context or {}
  271. if context.get('move_type'):
  272. if context.get('move_type') in ('out_invoice', 'out_refund'):
  273. args += [('type_tax_use', '=', 'sale')]
  274. elif context.get('move_type') in ('in_invoice', 'in_refund'):
  275. args += [('type_tax_use', '=', 'purchase')]
  276. if context.get('journal_id'):
  277. journal = self.env['account.journal'].browse(context.get('journal_id'))
  278. if journal.type in ('sale', 'purchase'):
  279. args += [('type_tax_use', '=', journal.type)]
  280. return super(AccountTax, self)._search(args, offset, limit, order, count=count, access_rights_uid=access_rights_uid)
  281. @api.onchange('amount')
  282. def onchange_amount(self):
  283. if self.amount_type in ('percent', 'division') and self.amount != 0.0 and not self.description:
  284. self.description = "{0:.4g}%".format(self.amount)
  285. @api.onchange('amount_type')
  286. def onchange_amount_type(self):
  287. if self.amount_type != 'group':
  288. self.children_tax_ids = [(5,)]
  289. if self.amount_type == 'group':
  290. self.description = None
  291. @api.onchange('price_include')
  292. def onchange_price_include(self):
  293. if self.price_include:
  294. self.include_base_amount = True
  295. @api.depends('invoice_repartition_line_ids', 'amount', 'invoice_repartition_line_ids.factor')
  296. def _compute_real_amount(self):
  297. for tax in self:
  298. tax_repartition_lines = tax.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax')
  299. total_factor = sum(tax_repartition_lines.mapped('factor'))
  300. tax.real_amount = tax.amount * total_factor
  301. def _compute_amount(self, base_amount, price_unit, quantity=1.0, product=None, partner=None, fixed_multiplicator=1):
  302. """ Returns the amount of a single tax. base_amount is the actual amount on which the tax is applied, which is
  303. price_unit * quantity eventually affected by previous taxes (if tax is include_base_amount XOR price_include)
  304. """
  305. self.ensure_one()
  306. if self.amount_type == 'fixed':
  307. # Use copysign to take into account the sign of the base amount which includes the sign
  308. # of the quantity and the sign of the price_unit
  309. # Amount is the fixed price for the tax, it can be negative
  310. # Base amount included the sign of the quantity and the sign of the unit price and when
  311. # a product is returned, it can be done either by changing the sign of quantity or by changing the
  312. # sign of the price unit.
  313. # When the price unit is equal to 0, the sign of the quantity is absorbed in base_amount then
  314. # a "else" case is needed.
  315. if base_amount:
  316. return math.copysign(quantity, base_amount) * self.amount * abs(fixed_multiplicator)
  317. else:
  318. return quantity * self.amount * abs(fixed_multiplicator)
  319. price_include = self._context.get('force_price_include', self.price_include)
  320. # base * (1 + tax_amount) = new_base
  321. if self.amount_type == 'percent' and not price_include:
  322. return base_amount * self.amount / 100
  323. # <=> new_base = base / (1 + tax_amount)
  324. if self.amount_type == 'percent' and price_include:
  325. return base_amount - (base_amount / (1 + self.amount / 100))
  326. # base / (1 - tax_amount) = new_base
  327. if self.amount_type == 'division' and not price_include:
  328. return base_amount / (1 - self.amount / 100) - base_amount if (1 - self.amount / 100) else 0.0
  329. # <=> new_base * (1 - tax_amount) = base
  330. if self.amount_type == 'division' and price_include:
  331. return base_amount - (base_amount * (self.amount / 100))
  332. # default value for custom amount_type
  333. return 0.0
  334. def json_friendly_compute_all(self, price_unit, currency_id=None, quantity=1.0, product_id=None, partner_id=None, is_refund=False, include_caba_tags=False):
  335. """ Called by the reconciliation to compute taxes on writeoff during bank reconciliation
  336. """
  337. if currency_id:
  338. currency_id = self.env['res.currency'].browse(currency_id)
  339. if product_id:
  340. product_id = self.env['product.product'].browse(product_id)
  341. if partner_id:
  342. partner_id = self.env['res.partner'].browse(partner_id)
  343. # We first need to find out whether this tax computation is made for a refund
  344. tax_type = self and self[0].type_tax_use
  345. is_refund = is_refund or (tax_type == 'sale' and price_unit > 0) or (tax_type == 'purchase' and price_unit < 0)
  346. rslt = self.with_context(caba_no_transition_account=True)\
  347. .compute_all(price_unit, currency=currency_id, quantity=quantity, product=product_id, partner=partner_id, is_refund=is_refund, include_caba_tags=include_caba_tags)
  348. return rslt
  349. def flatten_taxes_hierarchy(self, create_map=False):
  350. # Flattens the taxes contained in this recordset, returning all the
  351. # children at the bottom of the hierarchy, in a recordset, ordered by sequence.
  352. # Eg. considering letters as taxes and alphabetic order as sequence :
  353. # [G, B([A, D, F]), E, C] will be computed as [A, D, F, C, E, G]
  354. # If create_map is True, an additional value is returned, a dictionary
  355. # mapping each child tax to its parent group
  356. all_taxes = self.env['account.tax']
  357. groups_map = {}
  358. for tax in self.sorted(key=lambda r: r.sequence):
  359. if tax.amount_type == 'group':
  360. flattened_children = tax.children_tax_ids.flatten_taxes_hierarchy()
  361. all_taxes += flattened_children
  362. for flat_child in flattened_children:
  363. groups_map[flat_child] = tax
  364. else:
  365. all_taxes += tax
  366. if create_map:
  367. return all_taxes, groups_map
  368. return all_taxes
  369. def get_tax_tags(self, is_refund, repartition_type):
  370. rep_lines = self.mapped(is_refund and 'refund_repartition_line_ids' or 'invoice_repartition_line_ids')
  371. return rep_lines.filtered(lambda x: x.repartition_type == repartition_type).mapped('tag_ids')
  372. def compute_all(self, price_unit, currency=None, quantity=1.0, product=None, partner=None, is_refund=False, handle_price_include=True, include_caba_tags=False, fixed_multiplicator=1):
  373. """Compute all information required to apply taxes (in self + their children in case of a tax group).
  374. We consider the sequence of the parent for group of taxes.
  375. Eg. considering letters as taxes and alphabetic order as sequence :
  376. [G, B([A, D, F]), E, C] will be computed as [A, D, F, C, E, G]
  377. :param price_unit: The unit price of the line to compute taxes on.
  378. :param currency: The optional currency in which the price_unit is expressed.
  379. :param quantity: The optional quantity of the product to compute taxes on.
  380. :param product: The optional product to compute taxes on.
  381. Used to get the tags to apply on the lines.
  382. :param partner: The optional partner compute taxes on.
  383. Used to retrieve the lang to build strings and for potential extensions.
  384. :param is_refund: The optional boolean indicating if this is a refund.
  385. :param handle_price_include: Used when we need to ignore all tax included in price. If False, it means the
  386. amount passed to this method will be considered as the base of all computations.
  387. :param include_caba_tags: The optional boolean indicating if CABA tags need to be taken into account.
  388. :param fixed_multiplicator: The amount to multiply fixed amount taxes by.
  389. :return: {
  390. 'total_excluded': 0.0, # Total without taxes
  391. 'total_included': 0.0, # Total with taxes
  392. 'total_void' : 0.0, # Total with those taxes, that don't have an account set
  393. 'base_tags: : list<int>, # Tags to apply on the base line
  394. 'taxes': [{ # One dict for each tax in self and their children
  395. 'id': int,
  396. 'name': str,
  397. 'amount': float,
  398. 'base': float,
  399. 'sequence': int,
  400. 'account_id': int,
  401. 'refund_account_id': int,
  402. 'analytic': bool,
  403. 'price_include': bool,
  404. 'tax_exigibility': str,
  405. 'tax_repartition_line_id': int,
  406. 'group': recordset,
  407. 'tag_ids': list<int>,
  408. 'tax_ids': list<int>,
  409. }],
  410. } """
  411. if not self:
  412. company = self.env.company
  413. else:
  414. company = self[0].company_id
  415. # 1) Flatten the taxes.
  416. taxes, groups_map = self.flatten_taxes_hierarchy(create_map=True)
  417. # 2) Deal with the rounding methods
  418. if not currency:
  419. currency = company.currency_id
  420. # By default, for each tax, tax amount will first be computed
  421. # and rounded at the 'Account' decimal precision for each
  422. # PO/SO/invoice line and then these rounded amounts will be
  423. # summed, leading to the total amount for that tax. But, if the
  424. # company has tax_calculation_rounding_method = round_globally,
  425. # we still follow the same method, but we use a much larger
  426. # precision when we round the tax amount for each line (we use
  427. # the 'Account' decimal precision + 5), and that way it's like
  428. # rounding after the sum of the tax amounts of each line
  429. prec = currency.rounding
  430. # In some cases, it is necessary to force/prevent the rounding of the tax and the total
  431. # amounts. For example, in SO/PO line, we don't want to round the price unit at the
  432. # precision of the currency.
  433. # The context key 'round' allows to force the standard behavior.
  434. round_tax = False if company.tax_calculation_rounding_method == 'round_globally' else True
  435. if 'round' in self.env.context:
  436. round_tax = bool(self.env.context['round'])
  437. if not round_tax:
  438. prec *= 1e-5
  439. # 3) Iterate the taxes in the reversed sequence order to retrieve the initial base of the computation.
  440. # tax | base | amount |
  441. # /\ ----------------------------
  442. # || tax_1 | XXXX | | <- we are looking for that, it's the total_excluded
  443. # || tax_2 | .. | |
  444. # || tax_3 | .. | |
  445. # || ... | .. | .. |
  446. # ----------------------------
  447. def recompute_base(base_amount, fixed_amount, percent_amount, division_amount):
  448. # Recompute the new base amount based on included fixed/percent amounts and the current base amount.
  449. # Example:
  450. # tax | amount | type | price_include |
  451. # -----------------------------------------------
  452. # tax_1 | 10% | percent | t
  453. # tax_2 | 15 | fix | t
  454. # tax_3 | 20% | percent | t
  455. # tax_4 | 10% | division | t
  456. # -----------------------------------------------
  457. # if base_amount = 145, the new base is computed as:
  458. # (145 - 15) / (1.0 + 30%) * 90% = 130 / 1.3 * 90% = 90
  459. return (base_amount - fixed_amount) / (1.0 + percent_amount / 100.0) * (100 - division_amount) / 100
  460. # The first/last base must absolutely be rounded to work in round globally.
  461. # Indeed, the sum of all taxes ('taxes' key in the result dictionary) must be strictly equals to
  462. # 'price_included' - 'price_excluded' whatever the rounding method.
  463. #
  464. # Example using the global rounding without any decimals:
  465. # Suppose two invoice lines: 27000 and 10920, both having a 19% price included tax.
  466. #
  467. # Line 1 Line 2
  468. # -----------------------------------------------------------------------
  469. # total_included: 27000 10920
  470. # tax: 27000 / 1.19 = 4310.924 10920 / 1.19 = 1743.529
  471. # total_excluded: 22689.076 9176.471
  472. #
  473. # If the rounding of the total_excluded isn't made at the end, it could lead to some rounding issues
  474. # when summing the tax amounts, e.g. on invoices.
  475. # In that case:
  476. # - amount_untaxed will be 22689 + 9176 = 31865
  477. # - amount_tax will be 4310.924 + 1743.529 = 6054.453 ~ 6054
  478. # - amount_total will be 31865 + 6054 = 37919 != 37920 = 27000 + 10920
  479. #
  480. # By performing a rounding at the end to compute the price_excluded amount, the amount_tax will be strictly
  481. # equals to 'price_included' - 'price_excluded' after rounding and then:
  482. # Line 1: sum(taxes) = 27000 - 22689 = 4311
  483. # Line 2: sum(taxes) = 10920 - 2176 = 8744
  484. # amount_tax = 4311 + 8744 = 13055
  485. # amount_total = 31865 + 13055 = 37920
  486. base = currency.round(price_unit * quantity)
  487. # For the computation of move lines, we could have a negative base value.
  488. # In this case, compute all with positive values and negate them at the end.
  489. sign = 1
  490. if currency.is_zero(base):
  491. sign = -1 if fixed_multiplicator < 0 else 1
  492. elif base < 0:
  493. sign = -1
  494. base = -base
  495. # Store the totals to reach when using price_include taxes (only the last price included in row)
  496. total_included_checkpoints = {}
  497. i = len(taxes) - 1
  498. store_included_tax_total = True
  499. # Keep track of the accumulated included fixed/percent amount.
  500. incl_fixed_amount = incl_percent_amount = incl_division_amount = 0
  501. # Store the tax amounts we compute while searching for the total_excluded
  502. cached_tax_amounts = {}
  503. if handle_price_include:
  504. for tax in reversed(taxes):
  505. tax_repartition_lines = (
  506. is_refund
  507. and tax.refund_repartition_line_ids
  508. or tax.invoice_repartition_line_ids
  509. ).filtered(lambda x: x.repartition_type == "tax")
  510. sum_repartition_factor = sum(tax_repartition_lines.mapped("factor"))
  511. if tax.include_base_amount:
  512. base = recompute_base(base, incl_fixed_amount, incl_percent_amount, incl_division_amount)
  513. incl_fixed_amount = incl_percent_amount = incl_division_amount = 0
  514. store_included_tax_total = True
  515. if tax.price_include or self._context.get('force_price_include'):
  516. if tax.amount_type == 'percent':
  517. incl_percent_amount += tax.amount * sum_repartition_factor
  518. elif tax.amount_type == 'division':
  519. incl_division_amount += tax.amount * sum_repartition_factor
  520. elif tax.amount_type == 'fixed':
  521. incl_fixed_amount += abs(quantity) * tax.amount * sum_repartition_factor * abs(fixed_multiplicator)
  522. else:
  523. # tax.amount_type == other (python)
  524. tax_amount = tax._compute_amount(base, sign * price_unit, quantity, product, partner, fixed_multiplicator) * sum_repartition_factor
  525. incl_fixed_amount += tax_amount
  526. # Avoid unecessary re-computation
  527. cached_tax_amounts[i] = tax_amount
  528. # In case of a zero tax, do not store the base amount since the tax amount will
  529. # be zero anyway. Group and Python taxes have an amount of zero, so do not take
  530. # them into account.
  531. if store_included_tax_total and (
  532. tax.amount or tax.amount_type not in ("percent", "division", "fixed")
  533. ):
  534. total_included_checkpoints[i] = base
  535. store_included_tax_total = False
  536. i -= 1
  537. total_excluded = currency.round(recompute_base(base, incl_fixed_amount, incl_percent_amount, incl_division_amount))
  538. # 4) Iterate the taxes in the sequence order to compute missing tax amounts.
  539. # Start the computation of accumulated amounts at the total_excluded value.
  540. base = total_included = total_void = total_excluded
  541. # Flag indicating the checkpoint used in price_include to avoid rounding issue must be skipped since the base
  542. # amount has changed because we are currently mixing price-included and price-excluded include_base_amount
  543. # taxes.
  544. skip_checkpoint = False
  545. # Get product tags, account.account.tag objects that need to be injected in all
  546. # the tax_tag_ids of all the move lines created by the compute all for this product.
  547. product_tag_ids = product.account_tag_ids.ids if product else []
  548. taxes_vals = []
  549. i = 0
  550. cumulated_tax_included_amount = 0
  551. for tax in taxes:
  552. price_include = self._context.get('force_price_include', tax.price_include)
  553. if price_include or tax.is_base_affected:
  554. tax_base_amount = base
  555. else:
  556. tax_base_amount = total_excluded
  557. tax_repartition_lines = (is_refund and tax.refund_repartition_line_ids or tax.invoice_repartition_line_ids).filtered(lambda x: x.repartition_type == 'tax')
  558. sum_repartition_factor = sum(tax_repartition_lines.mapped('factor'))
  559. #compute the tax_amount
  560. if not skip_checkpoint and price_include and total_included_checkpoints.get(i) is not None and sum_repartition_factor != 0:
  561. # We know the total to reach for that tax, so we make a substraction to avoid any rounding issues
  562. tax_amount = total_included_checkpoints[i] - (base + cumulated_tax_included_amount)
  563. cumulated_tax_included_amount = 0
  564. else:
  565. tax_amount = tax.with_context(force_price_include=False)._compute_amount(
  566. tax_base_amount, sign * price_unit, quantity, product, partner, fixed_multiplicator)
  567. # Round the tax_amount multiplied by the computed repartition lines factor.
  568. tax_amount = float_round(tax_amount, precision_rounding=prec)
  569. factorized_tax_amount = float_round(tax_amount * sum_repartition_factor, precision_rounding=prec)
  570. if price_include and total_included_checkpoints.get(i) is None:
  571. cumulated_tax_included_amount += factorized_tax_amount
  572. # If the tax affects the base of subsequent taxes, its tax move lines must
  573. # receive the base tags and tag_ids of these taxes, so that the tax report computes
  574. # the right total
  575. subsequent_taxes = self.env['account.tax']
  576. subsequent_tags = self.env['account.account.tag']
  577. if tax.include_base_amount:
  578. subsequent_taxes = taxes[i+1:].filtered('is_base_affected')
  579. taxes_for_subsequent_tags = subsequent_taxes
  580. if not include_caba_tags:
  581. taxes_for_subsequent_tags = subsequent_taxes.filtered(lambda x: x.tax_exigibility != 'on_payment')
  582. subsequent_tags = taxes_for_subsequent_tags.get_tax_tags(is_refund, 'base')
  583. # Compute the tax line amounts by multiplying each factor with the tax amount.
  584. # Then, spread the tax rounding to ensure the consistency of each line independently with the factorized
  585. # amount. E.g:
  586. #
  587. # Suppose a tax having 4 x 50% repartition line applied on a tax amount of 0.03 with 2 decimal places.
  588. # The factorized_tax_amount will be 0.06 (200% x 0.03). However, each line taken independently will compute
  589. # 50% * 0.03 = 0.01 with rounding. It means there is 0.06 - 0.04 = 0.02 as total_rounding_error to dispatch
  590. # in lines as 2 x 0.01.
  591. repartition_line_amounts = [float_round(tax_amount * line.factor, precision_rounding=prec) for line in tax_repartition_lines]
  592. total_rounding_error = float_round(factorized_tax_amount - sum(repartition_line_amounts), precision_rounding=prec)
  593. nber_rounding_steps = int(abs(total_rounding_error / currency.rounding))
  594. rounding_error = float_round(nber_rounding_steps and total_rounding_error / nber_rounding_steps or 0.0, precision_rounding=prec)
  595. for repartition_line, line_amount in zip(tax_repartition_lines, repartition_line_amounts):
  596. if nber_rounding_steps:
  597. line_amount += rounding_error
  598. nber_rounding_steps -= 1
  599. if not include_caba_tags and tax.tax_exigibility == 'on_payment':
  600. repartition_line_tags = self.env['account.account.tag']
  601. else:
  602. repartition_line_tags = repartition_line.tag_ids
  603. taxes_vals.append({
  604. 'id': tax.id,
  605. 'name': partner and tax.with_context(lang=partner.lang).name or tax.name,
  606. 'amount': sign * line_amount,
  607. 'base': float_round(sign * tax_base_amount, precision_rounding=prec),
  608. 'sequence': tax.sequence,
  609. 'account_id': repartition_line._get_aml_target_tax_account(force_caba_exigibility=include_caba_tags).id,
  610. 'analytic': tax.analytic,
  611. 'use_in_tax_closing': repartition_line.use_in_tax_closing,
  612. 'price_include': price_include,
  613. 'tax_exigibility': tax.tax_exigibility,
  614. 'tax_repartition_line_id': repartition_line.id,
  615. 'group': groups_map.get(tax),
  616. 'tag_ids': (repartition_line_tags + subsequent_tags).ids + product_tag_ids,
  617. 'tax_ids': subsequent_taxes.ids,
  618. })
  619. if not repartition_line.account_id:
  620. total_void += line_amount
  621. # Affect subsequent taxes
  622. if tax.include_base_amount:
  623. base += factorized_tax_amount
  624. if not price_include:
  625. skip_checkpoint = True
  626. total_included += factorized_tax_amount
  627. i += 1
  628. base_taxes_for_tags = taxes
  629. if not include_caba_tags:
  630. base_taxes_for_tags = base_taxes_for_tags.filtered(lambda x: x.tax_exigibility != 'on_payment')
  631. base_rep_lines = base_taxes_for_tags.mapped(is_refund and 'refund_repartition_line_ids' or 'invoice_repartition_line_ids').filtered(lambda x: x.repartition_type == 'base')
  632. return {
  633. 'base_tags': base_rep_lines.tag_ids.ids + product_tag_ids,
  634. 'taxes': taxes_vals,
  635. 'total_excluded': sign * total_excluded,
  636. 'total_included': sign * currency.round(total_included),
  637. 'total_void': sign * total_void,
  638. }
  639. @api.model
  640. def _convert_to_tax_base_line_dict(
  641. self, base_line,
  642. partner=None, currency=None, product=None, taxes=None, price_unit=None, quantity=None,
  643. discount=None, account=None, analytic_distribution=None, price_subtotal=None,
  644. is_refund=False, rate=None,
  645. handle_price_include=True,
  646. extra_context=None,
  647. ):
  648. return {
  649. 'record': base_line,
  650. 'partner': partner or self.env['res.partner'],
  651. 'currency': currency or self.env['res.currency'],
  652. 'product': product or self.env['product.product'],
  653. 'taxes': taxes or self.env['account.tax'],
  654. 'price_unit': price_unit or 0.0,
  655. 'quantity': quantity or 0.0,
  656. 'discount': discount or 0.0,
  657. 'account': account or self.env['account.account'],
  658. 'analytic_distribution': analytic_distribution,
  659. 'price_subtotal': price_subtotal or 0.0,
  660. 'is_refund': is_refund,
  661. 'rate': rate or 1.0,
  662. 'handle_price_include': handle_price_include,
  663. 'extra_context': extra_context or {},
  664. }
  665. @api.model
  666. def _convert_to_tax_line_dict(
  667. self, tax_line,
  668. partner=None, currency=None, taxes=None, tax_tags=None, tax_repartition_line=None,
  669. group_tax=None, account=None, analytic_distribution=None, tax_amount=None,
  670. ):
  671. return {
  672. 'record': tax_line,
  673. 'partner': partner or self.env['res.partner'],
  674. 'currency': currency or self.env['res.currency'],
  675. 'taxes': taxes or self.env['account.tax'],
  676. 'tax_tags': tax_tags or self.env['account.account.tag'],
  677. 'tax_repartition_line': tax_repartition_line or self.env['account.tax.repartition.line'],
  678. 'group_tax': group_tax or self.env['account.tax'],
  679. 'account': account or self.env['account.account'],
  680. 'analytic_distribution': analytic_distribution,
  681. 'tax_amount': tax_amount or 0.0,
  682. }
  683. @api.model
  684. def _get_generation_dict_from_base_line(self, line_vals, tax_vals, force_caba_exigibility=False):
  685. """ Take a tax results returned by the taxes computation method and return a dictionary representing the way
  686. the tax amounts will be grouped together. To do so, the dictionary will be converted into a string key.
  687. Then, the existing tax lines sharing the same key will be updated and the missing ones will be created.
  688. :param line_vals: A python dict returned by '_convert_to_tax_base_line_dict'.
  689. :param tax_vals: A python dict returned by 'compute_all' under the 'taxes' key.
  690. :return: A python dict.
  691. """
  692. tax_repartition_line = tax_vals['tax_repartition_line']
  693. tax_account = tax_repartition_line._get_aml_target_tax_account(force_caba_exigibility=force_caba_exigibility) or line_vals['account']
  694. return {
  695. 'account_id': tax_account.id,
  696. 'currency_id': line_vals['currency'].id,
  697. 'partner_id': line_vals['partner'].id,
  698. 'tax_repartition_line_id': tax_repartition_line.id,
  699. 'tax_ids': [Command.set(tax_vals['tax_ids'])],
  700. 'tax_tag_ids': [Command.set(tax_vals['tag_ids'])],
  701. 'tax_id': tax_vals['group'].id if tax_vals['group'] else tax_vals['id'],
  702. 'analytic_distribution': line_vals['analytic_distribution'] if tax_vals['analytic'] else {},
  703. }
  704. @api.model
  705. def _get_generation_dict_from_tax_line(self, line_vals):
  706. """ Turn the values corresponding to a tax line and convert it into a dictionary. The dictionary will be
  707. converted into a string key. This allows updating the existing tax lines instead of creating new ones
  708. everytime.
  709. :param line_vals: A python dict returned by '_convert_to_tax_line_dict'.
  710. :return: A python dict representing the grouping key used to update an existing tax line.
  711. """
  712. tax = line_vals['tax_repartition_line'].tax_id
  713. return {
  714. 'account_id': line_vals['account'].id,
  715. 'currency_id': line_vals['currency'].id,
  716. 'partner_id': line_vals['partner'].id,
  717. 'tax_repartition_line_id': line_vals['tax_repartition_line'].id,
  718. 'tax_ids': [Command.set(line_vals['taxes'].ids)],
  719. 'tax_tag_ids': [Command.set(line_vals['tax_tags'].ids)],
  720. 'tax_id': (line_vals['group_tax'] or tax).id,
  721. 'analytic_distribution': line_vals['analytic_distribution'] if tax.analytic else {},
  722. }
  723. @api.model
  724. def _compute_taxes_for_single_line(self, base_line, handle_price_include=True, include_caba_tags=False, early_pay_discount_computation=None, early_pay_discount_percentage=None):
  725. orig_price_unit_after_discount = base_line['price_unit'] * (1 - (base_line['discount'] / 100.0))
  726. price_unit_after_discount = orig_price_unit_after_discount
  727. taxes = base_line['taxes']._origin
  728. currency = base_line['currency'] or self.env.company.currency_id
  729. rate = base_line['rate']
  730. if early_pay_discount_computation in ('included', 'excluded'):
  731. remaining_part_to_consider = (100 - early_pay_discount_percentage) / 100.0
  732. price_unit_after_discount = remaining_part_to_consider * price_unit_after_discount
  733. if taxes:
  734. taxes_res = taxes.with_context(**base_line['extra_context']).compute_all(
  735. price_unit_after_discount,
  736. currency=currency,
  737. quantity=base_line['quantity'],
  738. product=base_line['product'],
  739. partner=base_line['partner'],
  740. is_refund=base_line['is_refund'],
  741. handle_price_include=base_line['handle_price_include'],
  742. include_caba_tags=include_caba_tags,
  743. )
  744. to_update_vals = {
  745. 'tax_tag_ids': [Command.set(taxes_res['base_tags'])],
  746. 'price_subtotal': taxes_res['total_excluded'],
  747. 'price_total': taxes_res['total_included'],
  748. }
  749. if early_pay_discount_computation == 'excluded':
  750. new_taxes_res = taxes.with_context(**base_line['extra_context']).compute_all(
  751. orig_price_unit_after_discount,
  752. currency=currency,
  753. quantity=base_line['quantity'],
  754. product=base_line['product'],
  755. partner=base_line['partner'],
  756. is_refund=base_line['is_refund'],
  757. handle_price_include=base_line['handle_price_include'],
  758. include_caba_tags=include_caba_tags,
  759. )
  760. for tax_res, new_taxes_res in zip(taxes_res['taxes'], new_taxes_res['taxes']):
  761. delta_tax = new_taxes_res['amount'] - tax_res['amount']
  762. tax_res['amount'] += delta_tax
  763. to_update_vals['price_total'] += delta_tax
  764. tax_values_list = []
  765. for tax_res in taxes_res['taxes']:
  766. tax_amount = tax_res['amount'] / rate
  767. if self.company_id.tax_calculation_rounding_method == 'round_per_line':
  768. tax_amount = currency.round(tax_amount)
  769. tax_rep = self.env['account.tax.repartition.line'].browse(tax_res['tax_repartition_line_id'])
  770. tax_values_list.append({
  771. **tax_res,
  772. 'tax_repartition_line': tax_rep,
  773. 'base_amount_currency': tax_res['base'],
  774. 'base_amount': currency.round(tax_res['base'] / rate),
  775. 'tax_amount_currency': tax_res['amount'],
  776. 'tax_amount': tax_amount,
  777. })
  778. else:
  779. price_subtotal = currency.round(price_unit_after_discount * base_line['quantity'])
  780. to_update_vals = {
  781. 'tax_tag_ids': [Command.clear()],
  782. 'price_subtotal': price_subtotal,
  783. 'price_total': price_subtotal,
  784. }
  785. tax_values_list = []
  786. return to_update_vals, tax_values_list
  787. @api.model
  788. def _aggregate_taxes(self, to_process, filter_tax_values_to_apply=None, grouping_key_generator=None):
  789. def default_grouping_key_generator(base_line, tax_values):
  790. return {'tax': tax_values['tax_repartition_line'].tax_id}
  791. global_tax_details = {
  792. 'base_amount_currency': 0.0,
  793. 'base_amount': 0.0,
  794. 'tax_amount_currency': 0.0,
  795. 'tax_amount': 0.0,
  796. 'tax_details': defaultdict(lambda: {
  797. 'base_amount_currency': 0.0,
  798. 'base_amount': 0.0,
  799. 'tax_amount_currency': 0.0,
  800. 'tax_amount': 0.0,
  801. 'group_tax_details': [],
  802. 'records': set(),
  803. }),
  804. 'tax_details_per_record': defaultdict(lambda: {
  805. 'base_amount_currency': 0.0,
  806. 'base_amount': 0.0,
  807. 'tax_amount_currency': 0.0,
  808. 'tax_amount': 0.0,
  809. 'tax_details': defaultdict(lambda: {
  810. 'base_amount_currency': 0.0,
  811. 'base_amount': 0.0,
  812. 'tax_amount_currency': 0.0,
  813. 'tax_amount': 0.0,
  814. 'group_tax_details': [],
  815. 'records': set(),
  816. }),
  817. }),
  818. }
  819. def add_tax_values(record, results, grouping_key, serialized_grouping_key, tax_values):
  820. # Add to global results.
  821. results['tax_amount_currency'] += tax_values['tax_amount_currency']
  822. results['tax_amount'] += tax_values['tax_amount']
  823. # Add to tax details.
  824. if serialized_grouping_key not in results['tax_details']:
  825. tax_details = results['tax_details'][serialized_grouping_key]
  826. tax_details.update(grouping_key)
  827. tax_details['base_amount_currency'] = tax_values['base_amount_currency']
  828. tax_details['base_amount'] = tax_values['base_amount']
  829. tax_details['records'].add(record)
  830. else:
  831. tax_details = results['tax_details'][serialized_grouping_key]
  832. if record not in tax_details['records']:
  833. tax_details['base_amount_currency'] += tax_values['base_amount_currency']
  834. tax_details['base_amount'] += tax_values['base_amount']
  835. tax_details['records'].add(record)
  836. tax_details['tax_amount_currency'] += tax_values['tax_amount_currency']
  837. tax_details['tax_amount'] += tax_values['tax_amount']
  838. tax_details['group_tax_details'].append(tax_values)
  839. if self.env.company.tax_calculation_rounding_method == 'round_globally':
  840. amount_per_tax_repartition_line_id = defaultdict(lambda: {
  841. 'delta_tax_amount': 0.0,
  842. 'delta_tax_amount_currency': 0.0,
  843. })
  844. for base_line, to_update_vals, tax_values_list in to_process:
  845. currency = base_line['currency'] or self.env.company.currency_id
  846. comp_currency = self.env.company.currency_id
  847. for tax_values in tax_values_list:
  848. grouping_key = frozendict(self._get_generation_dict_from_base_line(base_line, tax_values))
  849. total_amounts = amount_per_tax_repartition_line_id[grouping_key]
  850. tax_amount_currency_with_delta = tax_values['tax_amount_currency'] \
  851. + total_amounts['delta_tax_amount_currency']
  852. tax_amount_currency = currency.round(tax_amount_currency_with_delta)
  853. tax_amount_with_delta = tax_values['tax_amount'] \
  854. + total_amounts['delta_tax_amount']
  855. tax_amount = comp_currency.round(tax_amount_with_delta)
  856. tax_values['tax_amount_currency'] = tax_amount_currency
  857. tax_values['tax_amount'] = tax_amount
  858. total_amounts['delta_tax_amount_currency'] = tax_amount_currency_with_delta - tax_amount_currency
  859. total_amounts['delta_tax_amount'] = tax_amount_with_delta - tax_amount
  860. grouping_key_generator = grouping_key_generator or default_grouping_key_generator
  861. for base_line, to_update_vals, tax_values_list in to_process:
  862. record = base_line['record']
  863. # Add to global tax amounts.
  864. global_tax_details['base_amount_currency'] += to_update_vals['price_subtotal']
  865. currency = base_line['currency'] or self.env.company.currency_id
  866. base_amount = currency.round(to_update_vals['price_subtotal'] / base_line['rate'])
  867. global_tax_details['base_amount'] += base_amount
  868. for tax_values in tax_values_list:
  869. if filter_tax_values_to_apply and not filter_tax_values_to_apply(base_line, tax_values):
  870. continue
  871. grouping_key = grouping_key_generator(base_line, tax_values)
  872. serialized_grouping_key = frozendict(grouping_key)
  873. # Add to invoice line global tax amounts.
  874. if serialized_grouping_key not in global_tax_details['tax_details_per_record'][record]:
  875. record_global_tax_details = global_tax_details['tax_details_per_record'][record]
  876. record_global_tax_details['base_amount_currency'] = to_update_vals['price_subtotal']
  877. record_global_tax_details['base_amount'] = base_amount
  878. else:
  879. record_global_tax_details = global_tax_details['tax_details_per_record'][record]
  880. add_tax_values(record, global_tax_details, grouping_key, serialized_grouping_key, tax_values)
  881. add_tax_values(record, record_global_tax_details, grouping_key, serialized_grouping_key, tax_values)
  882. return global_tax_details
  883. @api.model
  884. def _compute_taxes(self, base_lines, tax_lines=None, handle_price_include=True, include_caba_tags=False):
  885. """ Generic method to compute the taxes for different business models.
  886. :param base_lines: A list of python dictionaries created using the '_convert_to_tax_base_line_dict' method.
  887. :param tax_lines: A list of python dictionaries created using the '_convert_to_tax_line_dict' method.
  888. :param handle_price_include: Manage the price-included taxes. If None, use the 'handle_price_include' key
  889. set on base lines.
  890. :param include_caba_tags: Manage tags for taxes being exigible on_payment.
  891. :return: A python dictionary containing:
  892. The complete diff on tax lines if 'tax_lines' is passed as parameter:
  893. * tax_lines_to_add: To create new tax lines.
  894. * tax_lines_to_delete: To track the tax lines that are no longer used.
  895. * tax_lines_to_update: The values to update the existing tax lines.
  896. * base_lines_to_update: The values to update the existing base lines:
  897. * tax_tag_ids: The tags related to taxes.
  898. * price_subtotal: The amount without tax.
  899. * price_total: The amount with taxes.
  900. * totals: A mapping for each involved currency to:
  901. * amount_untaxed: The base amount without tax.
  902. * amount_tax: The total tax amount.
  903. """
  904. res = {
  905. 'tax_lines_to_add': [],
  906. 'tax_lines_to_delete': [],
  907. 'tax_lines_to_update': [],
  908. 'base_lines_to_update': [],
  909. 'totals': defaultdict(lambda: {
  910. 'amount_untaxed': 0.0,
  911. 'amount_tax': 0.0,
  912. }),
  913. }
  914. # =========================================================================================
  915. # BASE LINES
  916. # For each base line, populate 'base_lines_to_update'.
  917. # Compute 'tax_base_amount'/'tax_amount' for each pair <base line, tax repartition line>
  918. # using the grouping key generated by the '_get_generation_dict_from_base_line' method.
  919. # =========================================================================================
  920. to_process = []
  921. for base_line in base_lines:
  922. to_update_vals, tax_values_list = self._compute_taxes_for_single_line(
  923. base_line,
  924. include_caba_tags=include_caba_tags,
  925. )
  926. to_process.append((base_line, to_update_vals, tax_values_list))
  927. res['base_lines_to_update'].append((base_line, to_update_vals))
  928. currency = base_line['currency'] or self.env.company.currency_id
  929. res['totals'][currency]['amount_untaxed'] += to_update_vals['price_subtotal']
  930. # =========================================================================================
  931. # TAX LINES
  932. # Map each existing tax lines using the grouping key generated by the
  933. # '_get_generation_dict_from_tax_line' method.
  934. # Since everything is indexed using the grouping key, we are now able to decide if
  935. # (1) we can reuse an existing tax line and update its amounts
  936. # (2) some tax lines are no longer used and can be dropped
  937. # (3) we need to create new tax lines
  938. # =========================================================================================
  939. # Track the existing tax lines using the grouping key.
  940. existing_tax_line_map = {}
  941. for line_vals in tax_lines or []:
  942. grouping_key = frozendict(self._get_generation_dict_from_tax_line(line_vals))
  943. # After a modification (e.g. changing the analytic account of the tax line), if two tax lines are sharing
  944. # the same key, keep only one.
  945. if grouping_key in existing_tax_line_map:
  946. res['tax_lines_to_delete'].append(line_vals)
  947. else:
  948. existing_tax_line_map[grouping_key] = line_vals
  949. def grouping_key_generator(base_line, tax_values):
  950. return self._get_generation_dict_from_base_line(base_line, tax_values, force_caba_exigibility=include_caba_tags)
  951. # Update/create the tax lines.
  952. global_tax_details = self._aggregate_taxes(to_process, grouping_key_generator=grouping_key_generator)
  953. for grouping_key, tax_values in global_tax_details['tax_details'].items():
  954. if tax_values['currency_id']:
  955. currency = self.env['res.currency'].browse(tax_values['currency_id'])
  956. tax_amount = currency.round(tax_values['tax_amount'])
  957. res['totals'][currency]['amount_tax'] += tax_amount
  958. if grouping_key in existing_tax_line_map:
  959. # Update an existing tax line.
  960. line_vals = existing_tax_line_map.pop(grouping_key)
  961. res['tax_lines_to_update'].append((line_vals, tax_values))
  962. else:
  963. # Create a new tax line.
  964. res['tax_lines_to_add'].append(tax_values)
  965. for line_vals in existing_tax_line_map.values():
  966. res['tax_lines_to_delete'].append(line_vals)
  967. return res
  968. @api.model
  969. def _prepare_tax_totals(self, base_lines, currency, tax_lines=None):
  970. """ Compute the tax totals details for the business documents.
  971. :param base_lines: A list of python dictionaries created using the '_convert_to_tax_base_line_dict' method.
  972. :param currency: The currency set on the business document.
  973. :param tax_lines: Optional list of python dictionaries created using the '_convert_to_tax_line_dict' method.
  974. If specified, the taxes will be recomputed using them instead of recomputing the taxes on
  975. the provided base lines.
  976. :return: A dictionary in the following form:
  977. {
  978. 'amount_total': The total amount to be displayed on the document, including every total
  979. types.
  980. 'amount_untaxed': The untaxed amount to be displayed on the document.
  981. 'formatted_amount_total': Same as amount_total, but as a string formatted accordingly with
  982. partner's locale.
  983. 'formatted_amount_untaxed': Same as amount_untaxed, but as a string formatted accordingly with
  984. partner's locale.
  985. 'groups_by_subtotals': A dictionary formed liked {'subtotal': groups_data}
  986. Where total_type is a subtotal name defined on a tax group, or the
  987. default one: 'Untaxed Amount'.
  988. And groups_data is a list of dict in the following form:
  989. {
  990. 'tax_group_name': The name of the tax groups this total is made for.
  991. 'tax_group_amount': The total tax amount in this tax group.
  992. 'tax_group_base_amount': The base amount for this tax group.
  993. 'formatted_tax_group_amount': Same as tax_group_amount, but as a string formatted accordingly
  994. with partner's locale.
  995. 'formatted_tax_group_base_amount': Same as tax_group_base_amount, but as a string formatted
  996. accordingly with partner's locale.
  997. 'tax_group_id': The id of the tax group corresponding to this dict.
  998. }
  999. 'subtotals': A list of dictionaries in the following form, one for each subtotal in
  1000. 'groups_by_subtotals' keys.
  1001. {
  1002. 'name': The name of the subtotal
  1003. 'amount': The total amount for this subtotal, summing all the tax groups
  1004. belonging to preceding subtotals and the base amount
  1005. 'formatted_amount': Same as amount, but as a string formatted accordingly with
  1006. partner's locale.
  1007. }
  1008. 'subtotals_order': A list of keys of `groups_by_subtotals` defining the order in which it needs
  1009. to be displayed
  1010. }
  1011. """
  1012. # ==== Compute the taxes ====
  1013. to_process = []
  1014. for base_line in base_lines:
  1015. to_update_vals, tax_values_list = self._compute_taxes_for_single_line(base_line)
  1016. to_process.append((base_line, to_update_vals, tax_values_list))
  1017. def grouping_key_generator(base_line, tax_values):
  1018. source_tax = tax_values['tax_repartition_line'].tax_id
  1019. return {'tax_group': source_tax.tax_group_id}
  1020. global_tax_details = self._aggregate_taxes(to_process, grouping_key_generator=grouping_key_generator)
  1021. tax_group_vals_list = []
  1022. for tax_detail in global_tax_details['tax_details'].values():
  1023. tax_group_vals = {
  1024. 'tax_group': tax_detail['tax_group'],
  1025. 'base_amount': tax_detail['base_amount_currency'],
  1026. 'tax_amount': tax_detail['tax_amount_currency'],
  1027. }
  1028. # Handle a manual edition of tax lines.
  1029. if tax_lines is not None:
  1030. matched_tax_lines = [
  1031. x
  1032. for x in tax_lines
  1033. if x['tax_repartition_line'].tax_id.tax_group_id == tax_detail['tax_group']
  1034. ]
  1035. if matched_tax_lines:
  1036. tax_group_vals['tax_amount'] = sum(x['tax_amount'] for x in matched_tax_lines)
  1037. tax_group_vals_list.append(tax_group_vals)
  1038. tax_group_vals_list = sorted(tax_group_vals_list, key=lambda x: (x['tax_group'].sequence, x['tax_group'].id))
  1039. # ==== Partition the tax group values by subtotals ====
  1040. amount_untaxed = global_tax_details['base_amount_currency']
  1041. amount_tax = 0.0
  1042. subtotal_order = {}
  1043. groups_by_subtotal = defaultdict(list)
  1044. for tax_group_vals in tax_group_vals_list:
  1045. tax_group = tax_group_vals['tax_group']
  1046. subtotal_title = tax_group.preceding_subtotal or _("Untaxed Amount")
  1047. sequence = tax_group.sequence
  1048. subtotal_order[subtotal_title] = min(subtotal_order.get(subtotal_title, float('inf')), sequence)
  1049. groups_by_subtotal[subtotal_title].append({
  1050. 'group_key': tax_group.id,
  1051. 'tax_group_id': tax_group.id,
  1052. 'tax_group_name': tax_group.name,
  1053. 'tax_group_amount': tax_group_vals['tax_amount'],
  1054. 'tax_group_base_amount': tax_group_vals['base_amount'],
  1055. 'formatted_tax_group_amount': formatLang(self.env, tax_group_vals['tax_amount'], currency_obj=currency),
  1056. 'formatted_tax_group_base_amount': formatLang(self.env, tax_group_vals['base_amount'], currency_obj=currency),
  1057. })
  1058. # ==== Build the final result ====
  1059. subtotals = []
  1060. for subtotal_title in sorted(subtotal_order.keys(), key=lambda k: subtotal_order[k]):
  1061. amount_total = amount_untaxed + amount_tax
  1062. subtotals.append({
  1063. 'name': subtotal_title,
  1064. 'amount': amount_total,
  1065. 'formatted_amount': formatLang(self.env, amount_total, currency_obj=currency),
  1066. })
  1067. amount_tax += sum(x['tax_group_amount'] for x in groups_by_subtotal[subtotal_title])
  1068. amount_total = amount_untaxed + amount_tax
  1069. display_tax_base = (len(global_tax_details['tax_details']) == 1 and currency.compare_amounts(tax_group_vals_list[0]['base_amount'], amount_untaxed) != 0)\
  1070. or len(global_tax_details['tax_details']) > 1
  1071. return {
  1072. 'amount_untaxed': currency.round(amount_untaxed) if currency else amount_untaxed,
  1073. 'amount_total': currency.round(amount_total) if currency else amount_total,
  1074. 'formatted_amount_total': formatLang(self.env, amount_total, currency_obj=currency),
  1075. 'formatted_amount_untaxed': formatLang(self.env, amount_untaxed, currency_obj=currency),
  1076. 'groups_by_subtotal': groups_by_subtotal,
  1077. 'subtotals': subtotals,
  1078. 'subtotals_order': sorted(subtotal_order.keys(), key=lambda k: subtotal_order[k]),
  1079. 'display_tax_base': display_tax_base
  1080. }
  1081. @api.model
  1082. def _fix_tax_included_price(self, price, prod_taxes, line_taxes):
  1083. """Subtract tax amount from price when corresponding "price included" taxes do not apply"""
  1084. # FIXME get currency in param?
  1085. prod_taxes = prod_taxes._origin
  1086. line_taxes = line_taxes._origin
  1087. incl_tax = prod_taxes.filtered(lambda tax: tax not in line_taxes and tax.price_include)
  1088. if incl_tax:
  1089. return incl_tax.compute_all(price)['total_excluded']
  1090. return price
  1091. @api.model
  1092. def _fix_tax_included_price_company(self, price, prod_taxes, line_taxes, company_id):
  1093. if company_id:
  1094. #To keep the same behavior as in _compute_tax_id
  1095. prod_taxes = prod_taxes.filtered(lambda tax: tax.company_id == company_id)
  1096. line_taxes = line_taxes.filtered(lambda tax: tax.company_id == company_id)
  1097. return self._fix_tax_included_price(price, prod_taxes, line_taxes)
  1098. class AccountTaxRepartitionLine(models.Model):
  1099. _name = "account.tax.repartition.line"
  1100. _description = "Tax Repartition Line"
  1101. _order = 'sequence, repartition_type, id'
  1102. _check_company_auto = True
  1103. factor_percent = fields.Float(
  1104. string="%",
  1105. default=100,
  1106. required=True,
  1107. help="Factor to apply on the account move lines generated from this distribution line, in percents",
  1108. )
  1109. factor = fields.Float(string="Factor Ratio", compute="_compute_factor", help="Factor to apply on the account move lines generated from this distribution line")
  1110. repartition_type = fields.Selection(string="Based On", selection=[('base', 'Base'), ('tax', 'of tax')], required=True, default='tax', help="Base on which the factor will be applied.")
  1111. account_id = fields.Many2one(string="Account",
  1112. comodel_name='account.account',
  1113. domain="[('deprecated', '=', False), ('company_id', '=', company_id), ('account_type', 'not in', ('asset_receivable', 'liability_payable', 'off_balance'))]",
  1114. check_company=True,
  1115. help="Account on which to post the tax amount")
  1116. tag_ids = fields.Many2many(string="Tax Grids", comodel_name='account.account.tag', domain=[('applicability', '=', 'taxes')], copy=True, ondelete='restrict')
  1117. invoice_tax_id = fields.Many2one(comodel_name='account.tax',
  1118. ondelete='cascade',
  1119. check_company=True,
  1120. help="The tax set to apply this distribution on invoices. Mutually exclusive with refund_tax_id")
  1121. refund_tax_id = fields.Many2one(comodel_name='account.tax',
  1122. ondelete='cascade',
  1123. check_company=True,
  1124. help="The tax set to apply this distribution on refund invoices. Mutually exclusive with invoice_tax_id")
  1125. tax_id = fields.Many2one(comodel_name='account.tax', compute='_compute_tax_id')
  1126. document_type = fields.Selection(
  1127. selection=[
  1128. ('invoice', 'Invoice'),
  1129. ('refund', 'Refund'),
  1130. ],
  1131. compute='_compute_document_type',
  1132. help="The type of documnet on which the repartition line should be applied",
  1133. )
  1134. company_id = fields.Many2one(string="Company", comodel_name='res.company', compute="_compute_company", store=True, help="The company this distribution line belongs to.")
  1135. sequence = fields.Integer(string="Sequence", default=1,
  1136. help="The order in which distribution lines are displayed and matched. For refunds to work properly, invoice distribution lines should be arranged in the same order as the credit note distribution lines they correspond to.")
  1137. use_in_tax_closing = fields.Boolean(string="Tax Closing Entry", default=True)
  1138. tag_ids_domain = fields.Binary(string="tag domain", help="Dynamic domain used for the tag that can be set on tax", compute="_compute_tag_ids_domain")
  1139. @api.depends('company_id.multi_vat_foreign_country_ids', 'company_id.account_fiscal_country_id')
  1140. def _compute_tag_ids_domain(self):
  1141. for rep_line in self:
  1142. allowed_country_ids = (False, rep_line.company_id.account_fiscal_country_id.id, *rep_line.company_id.multi_vat_foreign_country_ids.ids,)
  1143. rep_line.tag_ids_domain = [('applicability', '=', 'taxes'), ('country_id', 'in', allowed_country_ids)]
  1144. @api.onchange('account_id', 'repartition_type')
  1145. def _on_change_account_id(self):
  1146. if not self.account_id or self.repartition_type == 'base':
  1147. self.use_in_tax_closing = False
  1148. else:
  1149. self.use_in_tax_closing = self.account_id.internal_group not in ('income', 'expense')
  1150. @api.constrains('invoice_tax_id', 'refund_tax_id')
  1151. def validate_tax_template_link(self):
  1152. for record in self:
  1153. if record.invoice_tax_id and record.refund_tax_id:
  1154. raise ValidationError(_("Tax distribution lines should apply to either invoices or refunds, not both at the same time. invoice_tax_id and refund_tax_id should not be set together."))
  1155. @api.depends('factor_percent')
  1156. def _compute_factor(self):
  1157. for record in self:
  1158. record.factor = record.factor_percent / 100.0
  1159. @api.depends('invoice_tax_id.company_id', 'refund_tax_id.company_id')
  1160. def _compute_company(self):
  1161. for record in self:
  1162. record.company_id = record.invoice_tax_id and record.invoice_tax_id.company_id.id or record.refund_tax_id.company_id.id
  1163. @api.depends('invoice_tax_id', 'refund_tax_id')
  1164. def _compute_tax_id(self):
  1165. for record in self:
  1166. record.tax_id = record.invoice_tax_id or record.refund_tax_id
  1167. @api.depends('invoice_tax_id', 'refund_tax_id')
  1168. def _compute_document_type(self):
  1169. for record in self:
  1170. record.document_type = 'invoice' if record.invoice_tax_id else 'refund'
  1171. @api.onchange('repartition_type')
  1172. def _onchange_repartition_type(self):
  1173. if self.repartition_type == 'base':
  1174. self.account_id = None
  1175. def _get_aml_target_tax_account(self, force_caba_exigibility=False):
  1176. """ Get the default tax account to set on a business line.
  1177. :return: An account.account record or an empty recordset.
  1178. """
  1179. self.ensure_one()
  1180. if not force_caba_exigibility and self.tax_id.tax_exigibility == 'on_payment' and not self._context.get('caba_no_transition_account'):
  1181. return self.tax_id.cash_basis_transition_account_id
  1182. else:
  1183. return self.account_id