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