forked from tryton/account_invoice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinvoice.py
2783 lines (2518 loc) · 103 KB
/
invoice.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
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from decimal import Decimal
from collections import defaultdict, namedtuple
from itertools import combinations
from sql import Null
from sql.aggregate import Sum
from sql.conditionals import Coalesce, Case
from sql.functions import Round
from trytond.model import Workflow, ModelView, ModelSQL, fields, Check, \
sequence_ordered, Unique, DeactivableMixin
from trytond.report import Report
from trytond.wizard import Wizard, StateView, StateTransition, StateAction, \
Button
from trytond import backend
from trytond.pyson import If, Eval, Bool
from trytond.tools import reduce_ids, grouped_slice
from trytond.transaction import Transaction
from trytond.pool import Pool
from trytond.rpc import RPC
from trytond.config import config
from trytond.modules.account.tax import TaxableMixin
from trytond.modules.product import price_digits
__all__ = ['Invoice', 'InvoicePaymentLine', 'InvoiceLine',
'InvoiceLineTax', 'InvoiceTax', 'PaymentMethod',
'InvoiceReport',
'PayInvoiceStart', 'PayInvoiceAsk', 'PayInvoice',
'CreditInvoiceStart', 'CreditInvoice']
_STATES = {
'readonly': Eval('state') != 'draft',
}
_DEPENDS = ['state']
_TYPE = [
('out', 'Customer'),
('in', 'Supplier'),
]
_TYPE2JOURNAL = {
'out': 'revenue',
'in': 'expense',
}
_ZERO = Decimal('0.0')
STATES = [
('draft', 'Draft'),
('validated', 'Validated'),
('posted', 'Posted'),
('paid', 'Paid'),
('cancel', 'Cancelled'),
]
if config.getboolean('account_invoice', 'filestore', default=False):
file_id = 'invoice_report_cache_id'
store_prefix = config.get('account_invoice', 'store_prefix', default=None)
else:
file_id = None
store_prefix = None
class Invoice(Workflow, ModelSQL, ModelView, TaxableMixin):
'Invoice'
__name__ = 'account.invoice'
_order_name = 'number'
company = fields.Many2One('company.company', 'Company', required=True,
states=_STATES, select=True, domain=[
('id', If(Eval('context', {}).contains('company'), '=', '!='),
Eval('context', {}).get('company', -1)),
],
depends=_DEPENDS)
company_party = fields.Function(
fields.Many2One('party.party', "Company Party"),
'on_change_with_company_party')
tax_identifier = fields.Many2One(
'party.identifier', "Tax Identifier",
states=_STATES, depends=_DEPENDS)
type = fields.Selection(_TYPE, 'Type', select=True,
required=True, states={
'readonly': ((Eval('state') != 'draft')
| Eval('context', {}).get('type')
| (Eval('lines', [0]) & Eval('type'))),
}, depends=['state'])
type_name = fields.Function(fields.Char('Type'), 'get_type_name')
number = fields.Char('Number', size=None, readonly=True, select=True)
reference = fields.Char('Reference', size=None, states=_STATES,
depends=_DEPENDS)
description = fields.Char('Description', size=None, states=_STATES,
depends=_DEPENDS)
state = fields.Selection(STATES, 'State', readonly=True)
invoice_date = fields.Date('Invoice Date',
states={
'readonly': Eval('state').in_(['posted', 'paid', 'cancel']),
'required': Eval('state').in_(
If(Eval('type') == 'in',
['validated', 'posted', 'paid'],
['posted', 'paid'])),
},
depends=['state'])
accounting_date = fields.Date('Accounting Date', states=_STATES,
depends=_DEPENDS)
party = fields.Many2One('party.party', 'Party',
required=True, states=_STATES, depends=_DEPENDS)
party_tax_identifier = fields.Many2One(
'party.identifier', "Party Tax Identifier",
states=_STATES,
domain=[
('party', '=', Eval('party', -1)),
],
depends=_DEPENDS + ['party'])
party_lang = fields.Function(fields.Char('Party Language'),
'on_change_with_party_lang')
invoice_address = fields.Many2One('party.address', 'Invoice Address',
required=True, states=_STATES, depends=['state', 'party'],
domain=[('party', '=', Eval('party'))])
currency = fields.Many2One('currency.currency', 'Currency', required=True,
states=_STATES, depends=_DEPENDS)
currency_digits = fields.Function(fields.Integer('Currency Digits'),
'on_change_with_currency_digits')
currency_date = fields.Function(fields.Date('Currency Date'),
'on_change_with_currency_date')
journal = fields.Many2One('account.journal', 'Journal', required=True,
states=_STATES, depends=_DEPENDS)
move = fields.Many2One('account.move', 'Move', readonly=True,
domain=[
('company', '=', Eval('company', -1)),
],
depends=['company'])
cancel_move = fields.Many2One('account.move', 'Cancel Move', readonly=True,
domain=[
('company', '=', Eval('company', -1)),
],
states={
'invisible': ~Eval('cancel_move'),
},
depends=['company'])
account = fields.Many2One('account.account', 'Account', required=True,
states=_STATES, depends=_DEPENDS + ['type', 'company'],
domain=[
('company', '=', Eval('company', -1)),
If(Eval('type') == 'out',
('kind', '=', 'receivable'),
('kind', '=', 'payable')),
])
payment_term = fields.Many2One('account.invoice.payment_term',
'Payment Term', states=_STATES, depends=_DEPENDS)
lines = fields.One2Many('account.invoice.line', 'invoice', 'Lines',
domain=[
('company', '=', Eval('company', -1)),
],
states={
'readonly': (Eval('state') != 'draft') | ~Eval('company'),
},
depends=['state', 'company'])
taxes = fields.One2Many('account.invoice.tax', 'invoice', 'Tax Lines',
states=_STATES, depends=_DEPENDS)
comment = fields.Text('Comment', states=_STATES, depends=_DEPENDS)
origins = fields.Function(fields.Char('Origins'), 'get_origins')
untaxed_amount = fields.Function(fields.Numeric('Untaxed',
digits=(16, Eval('currency_digits', 2)),
depends=['currency_digits']),
'get_amount', searcher='search_untaxed_amount')
tax_amount = fields.Function(fields.Numeric('Tax', digits=(16,
Eval('currency_digits', 2)), depends=['currency_digits']),
'get_amount', searcher='search_tax_amount')
total_amount = fields.Function(fields.Numeric('Total', digits=(16,
Eval('currency_digits', 2)), depends=['currency_digits']),
'get_amount', searcher='search_total_amount')
reconciled = fields.Function(fields.Date('Reconciled',
states={
'invisible': ~Eval('reconciled'),
}),
'get_reconciled')
lines_to_pay = fields.Function(fields.One2Many('account.move.line', None,
'Lines to Pay'), 'get_lines_to_pay')
payment_lines = fields.Many2Many('account.invoice-account.move.line',
'invoice', 'line', string='Payment Lines',
domain=[
('account', '=', Eval('account', -1)),
('party', 'in', [None, Eval('party', -1)]),
['OR',
('invoice_payment', '=', None),
('invoice_payment', '=', Eval('id', -1)),
],
If(Eval('type') == 'out',
If(Eval('total_amount', 0) >= 0,
('debit', '=', 0),
('credit', '=', 0)),
If(Eval('total_amount', 0) >= 0,
('credit', '=', 0),
('debit', '=', 0))),
],
states={
'invisible': Eval('state') == 'paid',
'readonly': Eval('state') != 'posted',
},
depends=['state', 'account', 'party', 'id', 'type', 'total_amount'])
amount_to_pay_today = fields.Function(fields.Numeric('Amount to Pay Today',
digits=(16, Eval('currency_digits', 2)),
depends=['currency_digits']), 'get_amount_to_pay')
amount_to_pay = fields.Function(fields.Numeric('Amount to Pay',
digits=(16, Eval('currency_digits', 2)),
depends=['currency_digits']), 'get_amount_to_pay')
invoice_report_cache = fields.Binary('Invoice Report', readonly=True,
file_id=file_id, store_prefix=store_prefix)
invoice_report_cache_id = fields.Char('Invoice Report ID', readonly=True)
invoice_report_format = fields.Char('Invoice Report Format', readonly=True)
@classmethod
def __setup__(cls):
super(Invoice, cls).__setup__()
cls._check_modify_exclude = ['state', 'payment_lines', 'cancel_move',
'invoice_report_cache', 'invoice_report_format']
cls._order = [
('number', 'DESC'),
('id', 'DESC'),
]
cls.tax_identifier.domain = [
('party', '=', Eval('company_party', -1)),
('type', 'in', cls._tax_identifier_types()),
]
cls.tax_identifier.depends += ['company_party']
cls._error_messages.update({
'missing_tax_line': ('Invoice "%s" has taxes defined but not '
'on invoice lines.\nRe-compute the invoice.'),
'diff_tax_line': ('Invoice "%s" tax bases are different from '
'invoice lines.\nRe-compute the invoice.'),
'missing_tax_line2': (
'Invoice "%s" has taxes on invoice lines '
'that are not in the invoice.\nRe-compute the invoice.'),
'no_invoice_sequence': ('Missing invoice sequence for '
'invoice "%(invoice)s" on fiscalyear "%(fiscalyear)s".'),
'modify_invoice': ('You can not modify invoice "%s" because '
'it is posted, paid or cancelled.'),
'same_account_on_line': ('Invoice "%(invoice)s" uses the same '
'account "%(account)s" for the invoice and in line '
'"%(line)s".'),
'delete_cancel': ('Invoice "%s" must be cancelled before '
'deletion.'),
'delete_numbered': ('The numbered invoice "%s" can not be '
'deleted.'),
'customer_invoice_cancel_move': (
'Customer invoice/credit note '
'"%s" can not be cancelled once posted.'),
'payment_lines_greater_amount': (
'The payment lines on invoice "%(invoice)s" can not be '
'greater than the invoice amount.'),
'modify_payment_lines_invoice_paid': (
'Payment lines can not be modified '
'on a paid invoice "%(invoice)s"'),
'credit_refund_non_posted': (
'Invoice "%(invoice)s" can not be refund '
'because it is not posted.'),
})
cls._transitions |= set((
('draft', 'validated'),
('validated', 'posted'),
('draft', 'posted'),
('posted', 'paid'),
('validated', 'draft'),
('paid', 'posted'),
('draft', 'cancel'),
('validated', 'cancel'),
('posted', 'cancel'),
('cancel', 'draft'),
))
cls._buttons.update({
'cancel': {
'invisible': (~Eval('state').in_(['draft', 'validated'])
& ~((Eval('state') == 'posted')
& (Eval('type') == 'in'))),
'help': 'Cancel the invoice',
'depends': ['state', 'type'],
},
'draft': {
'invisible': (~Eval('state').in_(['cancel', 'validated'])
| ((Eval('state') == 'cancel')
& Eval('cancel_move', -1))),
'icon': If(Eval('state') == 'cancel', 'tryton-undo',
'tryton-back'),
'depends': ['state'],
},
'validate_invoice': {
'pre_validate':
['OR',
('invoice_date', '!=', None),
('type', '!=', 'in'),
],
'invisible': Eval('state') != 'draft',
'depends': ['state'],
},
'post': {
'pre_validate':
['OR',
('invoice_date', '!=', None),
('type', '!=', 'in'),
],
'invisible': ~Eval('state').in_(['draft', 'validated']),
'depends': ['state'],
},
'pay': {
'invisible': Eval('state') != 'posted',
'depends': ['state'],
},
})
cls.__rpc__.update({
'post': RPC(
readonly=False, instantiate=0, fresh_session=True),
})
@classmethod
def __register__(cls, module_name):
pool = Pool()
Line = pool.get('account.invoice.line')
Tax = pool.get('account.invoice.tax')
sql_table = cls.__table__()
line = Line.__table__()
tax = Tax.__table__()
super(Invoice, cls).__register__(module_name)
transaction = Transaction()
cursor = transaction.connection.cursor()
table = cls.__table_handler__(module_name)
# Migration from 3.8: remove invoice/credit note type
cursor.execute(*sql_table.select(sql_table.id,
where=sql_table.type.like('%_invoice')
| sql_table.type.like('%_credit_note'),
limit=1))
if cursor.fetchone():
for type_ in ['out', 'in']:
cursor.execute(*sql_table.update(
columns=[sql_table.type],
values=[type_],
where=sql_table.type == '%s_invoice' % type_))
cursor.execute(*line.update(
columns=[line.invoice_type],
values=[type_],
where=line.invoice_type == '%s_invoice' % type_))
cursor.execute(*line.update(
columns=[line.quantity, line.invoice_type],
values=[-line.quantity, type_],
where=(line.invoice_type == '%s_credit_note' % type_)
& (line.invoice == Null)
))
# Don't use UPDATE FROM because SQLite nor MySQL support it
cursor.execute(*line.update(
columns=[line.quantity, line.invoice_type],
values=[-line.quantity, type_],
where=line.invoice.in_(sql_table.select(sql_table.id,
where=(
sql_table.type == '%s_credit_note' % type_)
))))
cursor.execute(*tax.update(
columns=[tax.base, tax.amount, tax.base_sign],
values=[-tax.base, -tax.amount, -tax.base_sign],
where=tax.invoice.in_(sql_table.select(sql_table.id,
where=(
sql_table.type == '%s_credit_note' % type_)
))))
cursor.execute(*sql_table.update(
columns=[sql_table.type],
values=[type_],
where=sql_table.type == '%s_credit_note' % type_))
# Migration from 4.0: Drop not null on payment_term
table.not_null_action('payment_term', 'remove')
# Add index on create_date
table.index_action('create_date', action='add')
@staticmethod
def default_type():
return Transaction().context.get('type', 'out')
@staticmethod
def default_state():
return 'draft'
@staticmethod
def default_currency():
Company = Pool().get('company.company')
if Transaction().context.get('company'):
company = Company(Transaction().context['company'])
return company.currency.id
@staticmethod
def default_currency_digits():
Company = Pool().get('company.company')
if Transaction().context.get('company'):
company = Company(Transaction().context['company'])
return company.currency.digits
return 2
@staticmethod
def default_company():
return Transaction().context.get('company')
@fields.depends('company')
def on_change_with_company_party(self, name=None):
if self.company:
return self.company.party.id
@classmethod
def default_payment_term(cls):
PaymentTerm = Pool().get('account.invoice.payment_term')
payment_terms = PaymentTerm.search(cls.payment_term.domain)
if len(payment_terms) == 1:
return payment_terms[0].id
@fields.depends('party', 'type', 'accounting_date', 'invoice_date')
def _get_account_payment_term(self):
'''
Return default account and payment term
'''
self.account = None
if self.party:
with Transaction().set_context(
date=self.accounting_date or self.invoice_date):
if self.type == 'out':
self.account = self.party.account_receivable_used
if self.party.customer_payment_term:
self.payment_term = self.party.customer_payment_term
elif self.type == 'in':
self.account = self.party.account_payable_used
if self.party.supplier_payment_term:
self.payment_term = self.party.supplier_payment_term
@fields.depends('type', methods=['_get_account_payment_term'])
def on_change_type(self):
Journal = Pool().get('account.journal')
journals = Journal.search([
('type', '=', _TYPE2JOURNAL.get(self.type or 'out',
'revenue')),
], limit=1)
if journals:
self.journal, = journals
self._get_account_payment_term()
@fields.depends('party', methods=['_get_account_payment_term'])
def on_change_party(self):
self.invoice_address = None
self._get_account_payment_term()
if self.party:
self.invoice_address = self.party.address_get(type='invoice')
self.party_tax_identifier = self.party.tax_identifier
@fields.depends('currency')
def on_change_with_currency_digits(self, name=None):
if self.currency:
return self.currency.digits
return 2
@fields.depends('invoice_date')
def on_change_with_currency_date(self, name=None):
Date = Pool().get('ir.date')
return self.invoice_date or Date.today()
@fields.depends('party')
def on_change_with_party_lang(self, name=None):
Config = Pool().get('ir.configuration')
if self.party:
if self.party.lang:
return self.party.lang.code
return Config.get_language()
@classmethod
def get_type_name(cls, invoices, name):
type_names = {}
type2name = {}
for type, name in cls.fields_get(fields_names=['type']
)['type']['selection']:
type2name[type] = name
for invoice in invoices:
type_names[invoice.id] = type2name[invoice.type]
return type_names
@fields.depends('lines', 'taxes', 'currency', 'party', 'type',
'accounting_date', 'invoice_date')
def on_change_lines(self):
self._on_change_lines_taxes()
@fields.depends('lines', 'taxes', 'currency', 'party', 'type',
'accounting_date', 'invoice_date')
def on_change_taxes(self):
self._on_change_lines_taxes()
def _on_change_lines_taxes(self):
pool = Pool()
InvoiceTax = pool.get('account.invoice.tax')
self.untaxed_amount = Decimal('0.0')
self.tax_amount = Decimal('0.0')
self.total_amount = Decimal('0.0')
computed_taxes = {}
if self.lines:
for line in self.lines:
self.untaxed_amount += getattr(line, 'amount', None) or 0
computed_taxes = self._get_taxes()
def is_zero(amount):
if self.currency:
return self.currency.is_zero(amount)
else:
return amount != Decimal('0.0')
tax_keys = []
taxes = list(self.taxes or [])
for tax in (self.taxes or []):
if tax.manual:
self.tax_amount += tax.amount or Decimal('0.0')
continue
tax_id = tax.tax.id if tax.tax else None
key = (tax.account.id, tax_id)
if (key not in computed_taxes) or (key in tax_keys):
taxes.remove(tax)
continue
tax_keys.append(key)
if not is_zero(computed_taxes[key]['base']
- (tax.base or Decimal('0.0'))):
self.tax_amount += computed_taxes[key]['amount']
tax.amount = computed_taxes[key]['amount']
tax.base = computed_taxes[key]['base']
else:
self.tax_amount += tax.amount or Decimal('0.0')
for key in computed_taxes:
if key not in tax_keys:
self.tax_amount += computed_taxes[key]['amount']
value = InvoiceTax.default_get(list(InvoiceTax._fields.keys()))
value.update(computed_taxes[key])
invoice_tax = InvoiceTax(**value)
if invoice_tax.tax:
invoice_tax.sequence = invoice_tax.tax.sequence
taxes.append(invoice_tax)
self.taxes = taxes
if self.currency:
self.untaxed_amount = self.currency.round(self.untaxed_amount)
self.tax_amount = self.currency.round(self.tax_amount)
self.total_amount = self.untaxed_amount + self.tax_amount
if self.currency:
self.total_amount = self.currency.round(self.total_amount)
@classmethod
def get_amount(cls, invoices, names):
pool = Pool()
InvoiceTax = pool.get('account.invoice.tax')
Move = pool.get('account.move')
MoveLine = pool.get('account.move.line')
cursor = Transaction().connection.cursor()
untaxed_amount = dict((i.id, _ZERO) for i in invoices)
tax_amount = dict((i.id, _ZERO) for i in invoices)
total_amount = dict((i.id, _ZERO) for i in invoices)
type_name = cls.tax_amount._field.sql_type().base
tax = InvoiceTax.__table__()
to_round = False
for sub_ids in grouped_slice(invoices):
red_sql = reduce_ids(tax.invoice, sub_ids)
cursor.execute(*tax.select(tax.invoice,
Coalesce(Sum(tax.amount), 0).as_(type_name),
where=red_sql,
group_by=tax.invoice))
for invoice_id, sum_ in cursor.fetchall():
# SQLite uses float for SUM
if not isinstance(sum_, Decimal):
sum_ = Decimal(str(sum_))
to_round = True
tax_amount[invoice_id] = sum_
# Float amount must be rounded to get the right precision
if to_round:
for invoice in invoices:
tax_amount[invoice.id] = invoice.currency.round(
tax_amount[invoice.id])
invoices_move = set()
invoices_no_move = set()
for invoice in invoices:
if invoice.move:
invoices_move.add(invoice.id)
else:
invoices_no_move.add(invoice.id)
invoices_move = cls.browse(invoices_move)
invoices_no_move = cls.browse(invoices_no_move)
type_name = cls.total_amount._field.sql_type().base
invoice = cls.__table__()
move = Move.__table__()
line = MoveLine.__table__()
to_round = False
for sub_ids in grouped_slice(invoices_move):
red_sql = reduce_ids(invoice.id, sub_ids)
cursor.execute(*invoice.join(move,
condition=invoice.move == move.id
).join(line, condition=move.id == line.move
).select(invoice.id,
Coalesce(Sum(
Case((line.second_currency == invoice.currency,
line.amount_second_currency),
else_=line.debit - line.credit)),
0).cast(type_name),
where=(invoice.account == line.account) & red_sql,
group_by=invoice.id))
for invoice_id, sum_ in cursor.fetchall():
# SQLite uses float for SUM
if not isinstance(sum_, Decimal):
sum_ = Decimal(str(sum_))
to_round = True
total_amount[invoice_id] = sum_
for invoice in invoices_move:
if invoice.type == 'in':
total_amount[invoice.id] *= -1
# Float amount must be rounded to get the right precision
if to_round:
total_amount[invoice.id] = invoice.currency.round(
total_amount[invoice.id])
untaxed_amount[invoice.id] = (
total_amount[invoice.id] - tax_amount[invoice.id])
for invoice in invoices_no_move:
untaxed_amount[invoice.id] = sum(
(line.amount for line in invoice.lines
if line.type == 'line'), _ZERO)
total_amount[invoice.id] = (
untaxed_amount[invoice.id] + tax_amount[invoice.id])
result = {
'untaxed_amount': untaxed_amount,
'tax_amount': tax_amount,
'total_amount': total_amount,
}
for key in list(result.keys()):
if key not in names:
del result[key]
return result
def get_reconciled(self, name):
reconciliations = [l.reconciliation for l in self.lines_to_pay]
if not reconciliations:
return None
elif not all(reconciliations):
return None
else:
return max(r.date for r in reconciliations)
@classmethod
def get_lines_to_pay(cls, invoices, name):
pool = Pool()
MoveLine = pool.get('account.move.line')
line = MoveLine.__table__()
invoice = cls.__table__()
cursor = Transaction().connection.cursor()
lines = defaultdict(list)
for sub_ids in grouped_slice(invoices):
red_sql = reduce_ids(invoice.id, sub_ids)
cursor.execute(*invoice.join(line,
condition=((invoice.move == line.move)
& (invoice.account == line.account))).select(
invoice.id, line.id,
where=(line.maturity_date != Null) & red_sql,
order_by=(invoice.id, line.maturity_date)))
for invoice_id, line_id in cursor.fetchall():
lines[invoice_id].append(line_id)
return lines
@classmethod
def get_amount_to_pay(cls, invoices, name):
pool = Pool()
Currency = pool.get('currency.currency')
Date = pool.get('ir.date')
today = Date.today()
res = dict((x.id, _ZERO) for x in invoices)
for invoice in invoices:
if invoice.state != 'posted':
continue
amount = _ZERO
amount_currency = _ZERO
for line in invoice.lines_to_pay:
if line.reconciliation:
continue
if (name == 'amount_to_pay_today'
and line.maturity_date > today):
continue
if (line.second_currency
and line.second_currency == invoice.currency):
amount_currency += line.amount_second_currency
else:
amount += line.debit - line.credit
for line in invoice.payment_lines:
if line.reconciliation:
continue
if (line.second_currency
and line.second_currency == invoice.currency):
amount_currency += line.amount_second_currency
else:
amount += line.debit - line.credit
if amount != _ZERO:
with Transaction().set_context(date=invoice.currency_date):
amount_currency += Currency.compute(
invoice.company.currency, amount, invoice.currency)
if invoice.type == 'in' and amount_currency:
amount_currency *= -1
res[invoice.id] = amount_currency
return res
@classmethod
def search_total_amount(cls, name, clause):
pool = Pool()
Rule = pool.get('ir.rule')
Line = pool.get('account.invoice.line')
Tax = pool.get('account.invoice.tax')
Invoice = pool.get('account.invoice')
Currency = pool.get('currency.currency')
type_name = cls.total_amount._field.sql_type().base
line = Line.__table__()
invoice = Invoice.__table__()
currency = Currency.__table__()
tax = Tax.__table__()
_, operator, value = clause
invoice_query = Rule.query_get('account.invoice')
Operator = fields.SQL_OPERATORS[operator]
# SQLite uses float for sum
if backend.name() == 'sqlite':
value = float(value)
union = (line.join(invoice, condition=(invoice.id == line.invoice)
).join(currency, condition=(currency.id == invoice.currency)
).select(line.invoice.as_('invoice'),
Coalesce(Sum(Round((line.quantity * line.unit_price).cast(
type_name),
currency.digits)), 0).as_('total_amount'),
where=line.invoice.in_(invoice_query),
group_by=line.invoice)
| tax.select(tax.invoice.as_('invoice'),
Coalesce(Sum(tax.amount), 0).as_('total_amount'),
where=tax.invoice.in_(invoice_query),
group_by=tax.invoice))
query = union.select(union.invoice, group_by=union.invoice,
having=Operator(Sum(union.total_amount).cast(type_name),
value))
return [('id', 'in', query)]
@classmethod
def search_untaxed_amount(cls, name, clause):
pool = Pool()
Rule = pool.get('ir.rule')
Line = pool.get('account.invoice.line')
Invoice = pool.get('account.invoice')
Currency = pool.get('currency.currency')
type_name = cls.untaxed_amount._field.sql_type().base
line = Line.__table__()
invoice = Invoice.__table__()
currency = Currency.__table__()
_, operator, value = clause
invoice_query = Rule.query_get('account.invoice')
Operator = fields.SQL_OPERATORS[operator]
# SQLite uses float for sum
if backend.name() == 'sqlite':
value = float(value)
query = line.join(invoice,
condition=(invoice.id == line.invoice)
).join(currency,
condition=(currency.id == invoice.currency)
).select(line.invoice,
where=line.invoice.in_(invoice_query),
group_by=line.invoice,
having=Operator(Coalesce(Sum(
Round((line.quantity * line.unit_price).cast(
type_name),
currency.digits)), 0).cast(type_name),
value))
return [('id', 'in', query)]
@classmethod
def search_tax_amount(cls, name, clause):
pool = Pool()
Rule = pool.get('ir.rule')
Tax = pool.get('account.invoice.tax')
type_name = cls.tax_amount._field.sql_type().base
tax = Tax.__table__()
_, operator, value = clause
invoice_query = Rule.query_get('account.invoice')
Operator = fields.SQL_OPERATORS[operator]
# SQLite uses float for sum
if backend.name() == 'sqlite':
value = float(value)
query = tax.select(tax.invoice,
where=tax.invoice.in_(invoice_query),
group_by=tax.invoice,
having=Operator(Coalesce(Sum(tax.amount), 0).cast(type_name),
value))
return [('id', 'in', query)]
@property
def taxable_lines(self):
taxable_lines = []
# In case we're called from an on_change we have to use some sensible
# defaults
for line in self.lines:
if getattr(line, 'type', None) != 'line':
continue
taxable_lines.append(tuple())
for attribute, default_value in [
('taxes', []),
('unit_price', Decimal(0)),
('quantity', 0.),
]:
value = getattr(line, attribute, None)
taxable_lines[-1] += (
value if value is not None else default_value,)
return taxable_lines
@property
def tax_date(self):
return self.accounting_date or self.invoice_date
def _get_tax_context(self):
context = {}
if self.party and self.party.lang:
context['language'] = self.party.lang.code
return context
def _compute_taxes(self):
taxes = self._get_taxes()
for tax in taxes.values():
tax['invoice'] = self.id
return taxes
@classmethod
def update_taxes(cls, invoices, exception=False):
Tax = Pool().get('account.invoice.tax')
to_create = []
to_delete = []
to_write = []
for invoice in invoices:
if invoice.state in ('posted', 'paid', 'cancel'):
continue
computed_taxes = invoice._compute_taxes()
if not invoice.taxes:
to_create.extend(computed_taxes.values())
else:
tax_keys = []
for tax in invoice.taxes:
if tax.manual:
continue
tax_id = tax.tax.id if tax.tax else None
key = (tax.account.id, tax_id)
if (key not in computed_taxes) or (key in tax_keys):
if exception:
cls.raise_user_error('missing_tax_line',
(invoice.rec_name,))
to_delete.append(tax)
continue
tax_keys.append(key)
if not invoice.currency.is_zero(
computed_taxes[key]['base'] - tax.base):
if exception:
cls.raise_user_error('diff_tax_line',
(invoice.rec_name,))
to_write.extend(([tax], computed_taxes[key]))
for key in computed_taxes:
if key not in tax_keys:
if exception:
cls.raise_user_error('missing_tax_line2',
(invoice.rec_name,))
to_create.append(computed_taxes[key])
if to_create:
Tax.create(to_create)
if to_delete:
Tax.delete(to_delete)
if to_write:
Tax.write(*to_write)
def _get_move_line(self, date, amount):
'''
Return move line
'''
pool = Pool()
Currency = pool.get('currency.currency')
MoveLine = pool.get('account.move.line')
line = MoveLine()
if self.currency != self.company.currency:
with Transaction().set_context(date=self.currency_date):
line.amount_second_currency = Currency.compute(
self.company.currency, amount, self.currency)
line.second_currency = self.currency
else:
line.amount_second_currency = None
line.second_currency = None
if amount <= 0:
line.debit, line.credit = -amount, 0
else:
line.debit, line.credit = 0, amount
if line.amount_second_currency:
line.amount_second_currency = (
line.amount_second_currency.copy_sign(
line.debit - line.credit))
line.account = self.account
if self.account.party_required:
line.party = self.party
line.maturity_date = date
line.description = self.description
return line
def get_move(self):
'''
Compute account move for the invoice and return the created move
'''
pool = Pool()
Move = pool.get('account.move')
Period = pool.get('account.period')
Date = pool.get('ir.date')
if self.move:
return self.move
self.update_taxes([self], exception=True)
move_lines = []
for line in self.lines:
move_lines += line.get_move_lines()
for tax in self.taxes:
move_lines += tax.get_move_lines()
total = Decimal('0.0')
total_currency = Decimal('0.0')
for line in move_lines:
total += line.debit - line.credit
if line.amount_second_currency:
total_currency += line.amount_second_currency
term_lines = [(Date.today(), total)]
if self.payment_term:
term_lines = self.payment_term.compute(
total, self.company.currency, self.invoice_date)
remainder_total_currency = total_currency
for date, amount in term_lines:
line = self._get_move_line(date, amount)
if line.amount_second_currency:
remainder_total_currency += line.amount_second_currency
move_lines.append(line)
if not self.currency.is_zero(remainder_total_currency):
move_lines[-1].amount_second_currency -= \
remainder_total_currency
accounting_date = self.accounting_date or self.invoice_date
period_id = Period.find(self.company.id, date=accounting_date)
move = Move()
move.journal = self.journal
move.period = period_id
move.date = accounting_date
move.origin = self
move.company = self.company
move.lines = move_lines
return move
@classmethod
def set_number(cls, invoices):
'''
Set number to the invoice
'''
pool = Pool()
Date = pool.get('ir.date')
for invoice in invoices:
# Posted and paid invoices are tested by check_modify so we can
# not modify tax_identifier nor number
if invoice.state in {'posted', 'paid'}:
continue
if not invoice.tax_identifier:
invoice.tax_identifier = invoice.get_tax_identifier()
# Generated invoice may not fill the party tax identifier
if not invoice.party_tax_identifier:
invoice.party_tax_identifier = invoice.party.tax_identifier
if invoice.number:
continue
if not invoice.invoice_date and invoice.type == 'out':
invoice.invoice_date = Date.today()
invoice.number = invoice.get_next_number()
cls.save(invoices)
def get_next_number(self, pattern=None):
pool = Pool()
Sequence = pool.get('ir.sequence.strict')