-
Notifications
You must be signed in to change notification settings - Fork 0
/
tax.py
461 lines (397 loc) · 15.3 KB
/
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
from decimal import Decimal
from sql import Literal, Null
from sql.aggregate import Sum
from sql.conditionals import Case
from trytond import backend
from trytond.model import ModelSQL, ModelView, fields
from trytond.pool import Pool, PoolMeta
from trytond.pyson import Bool, Eval
from trytond.rpc import RPC
from trytond.tools import cursor_dict, is_full_text, lstrip_wildcard
from trytond.transaction import Transaction
PARITY = [
(None, ""),
('O', "Odd"),
('E', "Even"),
('B', "Both"),
]
class TaxAuthorityMixin:
__slots__ = ()
authority = fields.Many2One('country.subdivision', "Authority",
domain=[
('country.code', '=', 'US'),
('parent', '=', None),
],
states={
'invisible': Bool(Eval('parent')),
},
help="The tax authority that administers this entity")
authority_override = fields.Boolean('Override Definition',
help="Check to override tax authority definition",
states={
'invisible': ~Bool(Eval('authority', -1)),
})
@classmethod
def __setup__(cls):
super().__setup__()
for fname in dir(cls):
field = getattr(cls, fname)
if ((isinstance(field, fields.Field)
and fname == 'authority_override')
or not isinstance(field, fields.Field)
or isinstance(field, fields.Function)):
continue
field.states['readonly'] = (
Bool(Eval('authority', -1)) & ~Eval('authority_override',
False))
if hasattr(cls, 'parent') and hasattr(cls, 'childs'):
cls.parent.domain = [
('authority', '=', Eval('authority', -1)),
cls.parent.domain or []]
cls.parent.depends.update({'authority'})
cls.childs.domain = [
('authority', '=', Eval('authority', -1)),
cls.childs.domain or []]
cls.childs.depends.update({'authority'})
@classmethod
def default_authority_override(cls):
return False
@classmethod
def copy(cls, records, default=None):
if default is None:
default = {}
else:
default = default.copy()
default.setdefault('authority', None)
return super().copy(records, default=default)
class Tax(TaxAuthorityMixin, metaclass=PoolMeta):
__name__ = 'account.tax'
place = fields.Many2One(
'country.subdivision', "Related Place", domain=[
('code_fips', '=', Eval('code')),
], states={
'invisible': ~Eval('authority') | Bool(Eval('parent')),
})
code = fields.Char("Jurisdiction Code", size=5, states={
'required': Bool(Eval('authority')),
'invisible': ~Eval('authority') | Bool(Eval('parent')),
})
sourcing = fields.Selection([
(None, ""),
('intrastate', "In-state Destination"),
('interstate', "Out-of-state Destination"),
('origin', "Origin"),
], "Sourcing", sort=False, states={
'invisible': Bool(Eval('parent')),
})
product_class = fields.Selection([
(None, ""),
('general', "General Goods & Services"),
('food', "Food & Drugs"),
], "Product Class", sort=False, states={
'invisible': Bool(Eval('parent')),
})
def get_rec_name(self, name):
if not self.authority:
return self.name
parts = []
parts.append(self.authority.code)
parts.append(self.code)
if self.place:
parts.append(self.place.name)
elif self.group:
parts.append(self.group.name)
else:
parts.append("Special")
if self.product_class:
parts.append(self.product_class.capitalize())
if self.sourcing == 'interstate':
parts.append("Foreign")
else:
parts.append("Domestic")
parts.append(self.name)
return '—'.join(parts)
@classmethod
def __setup__(cls):
super().__setup__()
cls.parent.domain = [
('code', '=', Eval('code')),
('place', '=', Eval('place')),
('sourcing', '=', Eval('sourcing')),
('product_class', '=', Eval('product_class')),
cls.parent.domain or []]
@classmethod
def search_rec_name(cls, name, clause):
_, operator, operand, *extra = clause
if operator.startswith('!') or operator.startswith('not'):
bool_op = 'AND'
else:
bool_op = 'OR'
code_value = operand
if operator.endswith('like') and is_full_text(operand):
code_value = lstrip_wildcard(operand)
return [bool_op,
('code', operator, code_value, *extra),
(cls._rec_name, operator, operand, *extra),
]
@classmethod
def get_amount(cls, taxes, names):
pool = Pool()
Move = pool.get('account.move')
MoveLine = pool.get('account.move.line')
TaxLine = pool.get('account.tax.line')
Tax = pool.get('account.tax')
cursor = Transaction().connection.cursor()
move = Move.__table__()
move_line = MoveLine.__table__()
tax_line = TaxLine.__table__()
tax = Tax.__table__()
tax_ids = list(map(int, taxes))
result = {}
for name in names:
result[name] = dict.fromkeys(tax_ids, Decimal(0))
columns = []
amount = tax_line.amount
debit = move_line.debit
credit = move_line.credit
if backend.name == 'sqlite':
amount = TaxLine.amount.sql_cast(tax_line.amount)
debit = MoveLine.debit.sql_cast(debit)
credit = MoveLine.credit.sql_cast(credit)
is_invoice = (
((amount > 0) & ((debit > 0) | (credit > 0)))
| ((amount < 0) & ((debit < 0) | (credit < 0)))
)
is_credit = (
((amount < 0) & ((debit > 0) | (credit > 0)))
| ((amount > 0) & ((debit < 0) | (credit < 0)))
)
for name, clause in [
('invoice_base_amount',
is_invoice & (tax_line.type == 'base')),
('invoice_tax_amount',
is_invoice & (tax_line.type == 'tax')),
('credit_base_amount',
is_credit & (tax_line.type == 'base')),
('credit_tax_amount',
is_credit & (tax_line.type == 'tax')),
]:
if name not in names:
continue
if backend.name == 'postgresql': # FIXME
columns.append(Sum(amount, filter_=clause).as_(name))
else:
columns.append(Sum(Case([clause, amount])).as_(name))
where = cls._amount_where(tax_line, move_line, move)
where_tax = cls._amount_where_tax(tax_line, move_line, move, tax)
query = (tax_line
.join(move_line, condition=tax_line.move_line == move_line.id)
.join(move, condition=move_line.move == move.id)
.join(tax, condition=tax_line.tax == tax.id)
.select(tax_line.tax.as_('tax'),
*columns,
where=tax_line.tax.in_(tax_ids)
& (move_line.state != 'draft')
& where
& where_tax,
group_by=tax_line.tax)
)
cursor.execute(*query)
for row in cursor_dict(cursor):
for name in names:
value = row[name] or 0
if not isinstance(value, Decimal):
value = Decimal(str(value))
result[name][row['tax']] = value
return result
@classmethod
def _amount_where(cls, tax_line, move_line, move):
where = super()._amount_where(tax_line, move_line, move)
context = Transaction().context
code_id = context.get('code')
amount = context.get('amount')
if code_id and amount == 'tax':
TaxCode = Pool().get('account.tax.code')
code = TaxCode(code_id)
return where & ((tax_line.code == code.code)
| (tax_line.code == Null))
else:
return where
@classmethod
def _amount_where_tax(cls, tax_line, move_line, move, tax):
context = Transaction().context
sourcing = context.get('sourcing')
product_class = context.get('product_class')
where = Literal(True)
if sourcing:
where = where & (tax.sourcing == sourcing)
if product_class:
where = where & (tax.product_class == product_class)
return where
@classmethod
def copy(cls, records, default=None):
if default is None:
default = {}
else:
default = default.copy()
default.setdefault('code', None)
default.setdefault('place', None)
return super().copy(records, default=default)
class TaxCodeContext(metaclass=PoolMeta):
__name__ = 'account.tax.code.context'
sourcing = fields.Selection([
(None, ""),
('intrastate', "In-state Destination"),
('interstate', "Out-of-state Destination"),
('origin', "Origin"),
], "Sourcing", sort=False)
product_class = fields.Selection([
(None, ""),
('general', "General Goods & Services"),
('food', "Food & Drugs"),
], "Product Class", sort=False)
class TaxBoundary(TaxAuthorityMixin, ModelView, ModelSQL):
"Tax Boundary"
__name__ = 'account.tax.boundary'
type = fields.Selection([
('A', 'Address'),
('Z', 'ZIP Code'),
('4', 'ZIP+4 Code'),
], "Boundary Type", required=True)
start_date = fields.Date("Starting Date", required=True)
end_date = fields.Date("End Date")
address_low = fields.Char("Low Address Range", size=10, states={
'required': Eval('type') == 'A',
}, help="Low end of PO Box or street address numbers")
address_high = fields.Char("High Address Range", size=10, states={
'required': Eval('type') == 'A',
}, help="High end of PO Box or street address numbers")
address_parity = fields.Selection(PARITY, "Odd/Even Indicator",
help="Indicates whether the given range of address(es) is "
"odd or even. For PO Boxes this field should be blank.")
street_pre = fields.Char("Street Predirectional", size=2)
street = fields.Char("Street Name", size=20, states={
'required': Eval('type') == 'A',
})
street_suffix = fields.Char("Street Suffix Abbreviation", size=4,
help="Indicates the type of street")
street_post = fields.Char("Street Postdirectional", size=2)
secondary = fields.Char("Secondary Address Abbreviation", size=4)
secondary_low = fields.Char("Address Secondary Low", size=8)
secondary_high = fields.Char("Address Secondary High", size=8)
secondary_parity = fields.Selection(PARITY, "Odd/Even Indicator")
city = fields.Char("City Name", size=28, states={
'required': Eval('type') == 'A',
})
zipcode = fields.Char("Zip Code", size=5, states={
'required': Eval('type') == 'A',
})
zipext = fields.Char("ZIP+4", size=4, states={
'required': Eval('type') == 'A',
})
zipcode_low = fields.Char("ZIP Code Low", size=5, states={
'required': Eval('type').in_(['Z', '4']),
})
zipcode_high = fields.Char("ZIP Code High", size=5, states={
'required': Eval('type').in_(['Z', '4']),
})
zipext_low = fields.Char("ZIP+4 Code Low", size=4, states={
'required': Eval('type') == '4',
})
zipext_high = fields.Char("ZIP+4 Code High", size=4, states={
'required': Eval('type') == '4',
})
company = fields.Many2One('company.company', "Company", required=True)
tax_key = fields.Many2One('account.tax.boundary.tax_key', "Tax Key",
domain=[
('authority', '=', Eval('authority', -1)),
], required=True)
code = fields.Many2One('account.tax.code', "Tax Code", domain=[
('authority', '=', Eval('authority', -1)),
('company', '=', Eval('company', -1)),
],
ondelete='RESTRICT')
@classmethod
def __setup__(cls):
super().__setup__()
cls.authority.required = True
cls.__rpc__.update(
clean=RPC(
readonly=False, fresh_session=True))
@staticmethod
def default_company():
return Transaction().context.get('company')
@classmethod
def clean(cls, domain=None):
table = cls.__table__()
cursor = Transaction().connection.cursor()
if domain:
query = cls.search(domain, query=True)
where = table.id.in_(query)
else:
where = None
cursor.execute(*table.delete(where=where))
class TaxKey(TaxAuthorityMixin, ModelView, ModelSQL):
"Tax Key"
__name__ = 'account.tax.boundary.tax_key'
value = fields.Char("Tax Key Value", required=True,
help="A composite key made of all applicable tax codes")
class TaxCode(TaxAuthorityMixin, metaclass=PoolMeta):
__name__ = 'account.tax.code'
class TaxCodeLine(TaxAuthorityMixin, metaclass=PoolMeta):
__name__ = 'account.tax.code.line'
@classmethod
def __setup__(cls):
super().__setup__()
cls.tax.context['code'] = Eval('code')
cls.tax.depends.add('code')
cls.tax.context['amount'] = Eval('amount')
cls.tax.depends.add('amount')
cls.code.ondelete = 'CASCADE'
cls.code.domain = [
('authority', '=', Eval('authority', -1)),
cls.code.domain or []]
@property
def _line_domain(self):
domain = super()._line_domain
domain.append(['OR',
[('code', '=', self.code.code)],
[('code', '=', None)],
])
context = Transaction().context
sourcing = context.get('sourcing')
product_class = context.get('product_class')
if sourcing:
domain.append([('tax.sourcing', '=', sourcing)])
if product_class:
domain.append([('tax.product_class', '=', product_class)])
return domain
class TaxLine(metaclass=PoolMeta):
__name__ = 'account.tax.line'
code = fields.Char("Reporting Code")
class TaxRule(TaxAuthorityMixin, metaclass=PoolMeta):
__name__ = 'account.tax.rule'
def apply(self, tax, pattern):
pool = Pool()
TaxKey = pool.get('account.tax.boundary.tax_key')
pattern = pattern.copy()
tax_key = pattern.pop('tax_key', None)
if tax_key:
tax_key = TaxKey(tax_key)
pattern['tax_key'] = tax_key.value.split('-')
return super().apply(tax, pattern)
class TaxRuleLine(TaxAuthorityMixin, metaclass=PoolMeta):
__name__ = 'account.tax.rule.line'
@classmethod
def __setup__(cls):
super().__setup__()
cls.rule.domain = [
('authority', '=', Eval('authority', -1)),
cls.rule.domain or []]
def match(self, pattern):
pattern = pattern.copy()
tax_key = pattern.pop('tax_key', None)
if not tax_key or not self.tax or not self.tax.code or (
self.tax.code not in tax_key):
return False
return super().match(pattern)