/
account_invoice.py
1635 lines (1462 loc) · 81.1 KB
/
account_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
# -*- coding: utf-8 -*-
import json
import re
from lxml import etree
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.tools import float_is_zero, float_compare, pycompat
from odoo.exceptions import UserError, RedirectWarning, ValidationError, Warning
from odoo.addons import decimal_precision as dp
import logging
_logger = logging.getLogger(__name__)
# mapping invoice type to journal type
TYPE2JOURNAL = {
'out_invoice': 'sale',
'in_invoice': 'purchase',
'out_refund': 'sale',
'in_refund': 'purchase',
}
# mapping invoice type to refund type
TYPE2REFUND = {
'out_invoice': 'out_refund', # Customer Invoice
'in_invoice': 'in_refund', # Vendor Bill
'out_refund': 'out_invoice', # Customer Credit Note
'in_refund': 'in_invoice', # Vendor Credit Note
}
MAGIC_COLUMNS = ('id', 'create_uid', 'create_date', 'write_uid', 'write_date')
class AccountInvoice(models.Model):
_name = "account.invoice"
_inherit = ['mail.thread', 'mail.activity.mixin']
_description = "Invoice"
_order = "date_invoice desc, number desc, id desc"
@api.one
@api.depends('invoice_line_ids.price_subtotal', 'tax_line_ids.amount', 'currency_id', 'company_id', 'date_invoice', 'type')
def _compute_amount(self):
self.amount_untaxed = sum(line.price_subtotal for line in self.invoice_line_ids)
self.amount_tax = sum(line.amount for line in self.tax_line_ids)
self.amount_total = self.amount_untaxed + self.amount_tax
amount_total_company_signed = self.amount_total
amount_untaxed_signed = self.amount_untaxed
if self.currency_id and self.company_id and self.currency_id != self.company_id.currency_id:
currency_id = self.currency_id.with_context(date=self.date_invoice)
amount_total_company_signed = currency_id.compute(self.amount_total, self.company_id.currency_id)
amount_untaxed_signed = currency_id.compute(self.amount_untaxed, self.company_id.currency_id)
sign = self.type in ['in_refund', 'out_refund'] and -1 or 1
self.amount_total_company_signed = amount_total_company_signed * sign
self.amount_total_signed = self.amount_total * sign
self.amount_untaxed_signed = amount_untaxed_signed * sign
@api.onchange('amount_total')
def _onchange_amount_total(self):
for inv in self:
if inv.amount_total < 0:
raise Warning(_('You cannot validate an invoice with a negative total amount. You should create a credit note instead.'))
@api.model
def _default_journal(self):
if self._context.get('default_journal_id', False):
return self.env['account.journal'].browse(self._context.get('default_journal_id'))
inv_type = self._context.get('type', 'out_invoice')
inv_types = inv_type if isinstance(inv_type, list) else [inv_type]
company_id = self._context.get('company_id', self.env.user.company_id.id)
domain = [
('type', 'in', [TYPE2JOURNAL[ty] for ty in inv_types if ty in TYPE2JOURNAL]),
('company_id', '=', company_id),
]
return self.env['account.journal'].search(domain, limit=1)
@api.model
def _default_currency(self):
journal = self._default_journal()
return journal.currency_id or journal.company_id.currency_id or self.env.user.company_id.currency_id
@api.model
def _get_reference_type(self):
return [('none', _('Free Reference'))]
@api.one
@api.depends(
'state', 'currency_id', 'invoice_line_ids.price_subtotal',
'move_id.line_ids.amount_residual',
'move_id.line_ids.currency_id')
def _compute_residual(self):
residual = 0.0
residual_company_signed = 0.0
sign = self.type in ['in_refund', 'out_refund'] and -1 or 1
for line in self.sudo().move_id.line_ids:
if line.account_id == self.account_id:
residual_company_signed += line.amount_residual
if line.currency_id == self.currency_id:
residual += line.amount_residual_currency if line.currency_id else line.amount_residual
else:
from_currency = (line.currency_id and line.currency_id.with_context(date=line.date)) or line.company_id.currency_id.with_context(date=line.date)
residual += from_currency.compute(line.amount_residual, self.currency_id)
self.residual_company_signed = abs(residual_company_signed) * sign
self.residual_signed = abs(residual) * sign
self.residual = abs(residual)
digits_rounding_precision = self.currency_id.rounding
if float_is_zero(self.residual, precision_rounding=digits_rounding_precision):
self.reconciled = True
else:
self.reconciled = False
@api.one
def _get_outstanding_info_JSON(self):
self.outstanding_credits_debits_widget = json.dumps(False)
if self.state == 'open':
domain = [('account_id', '=', self.account_id.id), ('partner_id', '=', self.env['res.partner']._find_accounting_partner(self.partner_id).id), ('reconciled', '=', False), ('amount_residual', '!=', 0.0)]
if self.type in ('out_invoice', 'in_refund'):
domain.extend([('credit', '>', 0), ('debit', '=', 0)])
type_payment = _('Outstanding credits')
else:
domain.extend([('credit', '=', 0), ('debit', '>', 0)])
type_payment = _('Outstanding debits')
info = {'title': '', 'outstanding': True, 'content': [], 'invoice_id': self.id}
lines = self.env['account.move.line'].search(domain)
currency_id = self.currency_id
if len(lines) != 0:
for line in lines:
# get the outstanding residual value in invoice currency
if line.currency_id and line.currency_id == self.currency_id:
amount_to_show = abs(line.amount_residual_currency)
else:
amount_to_show = line.company_id.currency_id.with_context(date=line.date).compute(abs(line.amount_residual), self.currency_id)
if float_is_zero(amount_to_show, precision_rounding=self.currency_id.rounding):
continue
info['content'].append({
'journal_name': line.ref or line.move_id.name,
'amount': amount_to_show,
'currency': currency_id.symbol,
'id': line.id,
'position': currency_id.position,
'digits': [69, self.currency_id.decimal_places],
})
info['title'] = type_payment
self.outstanding_credits_debits_widget = json.dumps(info)
self.has_outstanding = True
@api.model
def _get_payments_vals(self):
if not self.payment_move_line_ids:
return []
payment_vals = []
currency_id = self.currency_id
for payment in self.payment_move_line_ids:
payment_currency_id = False
if self.type in ('out_invoice', 'in_refund'):
amount = sum([p.amount for p in payment.matched_debit_ids if p.debit_move_id in self.move_id.line_ids])
amount_currency = sum(
[p.amount_currency for p in payment.matched_debit_ids if p.debit_move_id in self.move_id.line_ids])
if payment.matched_debit_ids:
payment_currency_id = all([p.currency_id == payment.matched_debit_ids[0].currency_id for p in
payment.matched_debit_ids]) and payment.matched_debit_ids[
0].currency_id or False
elif self.type in ('in_invoice', 'out_refund'):
amount = sum(
[p.amount for p in payment.matched_credit_ids if p.credit_move_id in self.move_id.line_ids])
amount_currency = sum([p.amount_currency for p in payment.matched_credit_ids if
p.credit_move_id in self.move_id.line_ids])
if payment.matched_credit_ids:
payment_currency_id = all([p.currency_id == payment.matched_credit_ids[0].currency_id for p in
payment.matched_credit_ids]) and payment.matched_credit_ids[
0].currency_id or False
# get the payment value in invoice currency
if payment_currency_id and payment_currency_id == self.currency_id:
amount_to_show = amount_currency
else:
amount_to_show = payment.company_id.currency_id.with_context(date=payment.date).compute(amount,
self.currency_id)
if float_is_zero(amount_to_show, precision_rounding=self.currency_id.rounding):
continue
payment_ref = payment.move_id.name
if payment.move_id.ref:
payment_ref += ' (' + payment.move_id.ref + ')'
payment_vals.append({
'name': payment.name,
'journal_name': payment.journal_id.name,
'amount': amount_to_show,
'currency': currency_id.symbol,
'digits': [69, currency_id.decimal_places],
'position': currency_id.position,
'date': payment.date,
'payment_id': payment.id,
'move_id': payment.move_id.id,
'ref': payment_ref,
})
return payment_vals
@api.one
@api.depends('payment_move_line_ids.amount_residual')
def _get_payment_info_JSON(self):
self.payments_widget = json.dumps(False)
if self.payment_move_line_ids:
info = {'title': _('Less Payment'), 'outstanding': False, 'content': self._get_payments_vals()}
self.payments_widget = json.dumps(info)
@api.one
@api.depends('move_id.line_ids.amount_residual')
def _compute_payments(self):
payment_lines = set()
for line in self.move_id.line_ids:
payment_lines.update(line.mapped('matched_credit_ids.credit_move_id.id'))
payment_lines.update(line.mapped('matched_debit_ids.debit_move_id.id'))
self.payment_move_line_ids = self.env['account.move.line'].browse(list(payment_lines))
name = fields.Char(string='Reference/Description', index=True,
readonly=True, states={'draft': [('readonly', False)]}, copy=False, help='The name that will be used on account move lines')
origin = fields.Char(string='Source Document',
help="Reference of the document that produced this invoice.",
readonly=True, states={'draft': [('readonly', False)]})
type = fields.Selection([
('out_invoice','Customer Invoice'),
('in_invoice','Vendor Bill'),
('out_refund','Customer Credit Note'),
('in_refund','Vendor Credit Note'),
], readonly=True, index=True, change_default=True,
default=lambda self: self._context.get('type', 'out_invoice'),
track_visibility='always')
refund_invoice_id = fields.Many2one('account.invoice', string="Invoice for which this invoice is the credit note")
number = fields.Char(related='move_id.name', store=True, readonly=True, copy=False)
move_name = fields.Char(string='Journal Entry Name', readonly=False,
default=False, copy=False,
help="Technical field holding the number given to the invoice, automatically set when the invoice is validated then stored to set the same number again if the invoice is cancelled, set to draft and re-validated.")
reference = fields.Char(string='Vendor Reference',
help="The partner reference of this invoice.", readonly=True, states={'draft': [('readonly', False)]})
reference_type = fields.Selection('_get_reference_type', string='Payment Reference',
required=True, readonly=True, states={'draft': [('readonly', False)]},
default='none')
comment = fields.Text('Additional Information', readonly=True, states={'draft': [('readonly', False)]})
state = fields.Selection([
('draft','Draft'),
('open', 'Open'),
('paid', 'Paid'),
('cancel', 'Cancelled'),
], string='Status', index=True, readonly=True, default='draft',
track_visibility='onchange', copy=False,
help=" * The 'Draft' status is used when a user is encoding a new and unconfirmed Invoice.\n"
" * The 'Pro-forma' status is used when the invoice does not have an invoice number.\n"
" * The 'Open' status is used when user creates invoice, an invoice number is generated. It stays in the open status till the user pays the invoice.\n"
" * The 'Paid' status is set automatically when the invoice is paid. Its related journal entries may or may not be reconciled.\n"
" * The 'Cancelled' status is used when user cancel invoice.")
sent = fields.Boolean(readonly=True, default=False, copy=False,
help="It indicates that the invoice has been sent.")
date_invoice = fields.Date(string='Invoice Date',
readonly=True, states={'draft': [('readonly', False)]}, index=True,
help="Keep empty to use the current date", copy=False)
date_due = fields.Date(string='Due Date',
readonly=True, states={'draft': [('readonly', False)]}, index=True, copy=False,
help="If you use payment terms, the due date will be computed automatically at the generation "
"of accounting entries. The Payment terms may compute several due dates, for example 50% "
"now and 50% in one month, but if you want to force a due date, make sure that the payment "
"term is not set on the invoice. If you keep the Payment terms and the due date empty, it "
"means direct payment.")
partner_id = fields.Many2one('res.partner', string='Partner', change_default=True,
required=True, readonly=True, states={'draft': [('readonly', False)]},
track_visibility='always')
payment_term_id = fields.Many2one('account.payment.term', string='Payment Terms', oldname='payment_term',
readonly=True, states={'draft': [('readonly', False)]},
help="If you use payment terms, the due date will be computed automatically at the generation "
"of accounting entries. If you keep the payment terms and the due date empty, it means direct payment. "
"The payment terms may compute several due dates, for example 50% now, 50% in one month.")
date = fields.Date(string='Accounting Date',
copy=False,
help="Keep empty to use the invoice date.",
readonly=True, states={'draft': [('readonly', False)]})
account_id = fields.Many2one('account.account', string='Account',
required=True, readonly=True, states={'draft': [('readonly', False)]},
domain=[('deprecated', '=', False)], help="The partner account used for this invoice.")
invoice_line_ids = fields.One2many('account.invoice.line', 'invoice_id', string='Invoice Lines', oldname='invoice_line',
readonly=True, states={'draft': [('readonly', False)]}, copy=True)
tax_line_ids = fields.One2many('account.invoice.tax', 'invoice_id', string='Tax Lines', oldname='tax_line',
readonly=True, states={'draft': [('readonly', False)]}, copy=True)
move_id = fields.Many2one('account.move', string='Journal Entry',
readonly=True, index=True, ondelete='restrict', copy=False,
help="Link to the automatically generated Journal Items.")
amount_untaxed = fields.Monetary(string='Untaxed Amount',
store=True, readonly=True, compute='_compute_amount', track_visibility='always')
amount_untaxed_signed = fields.Monetary(string='Untaxed Amount in Company Currency', currency_field='company_currency_id',
store=True, readonly=True, compute='_compute_amount')
amount_tax = fields.Monetary(string='Tax',
store=True, readonly=True, compute='_compute_amount')
amount_total = fields.Monetary(string='Total',
store=True, readonly=True, compute='_compute_amount')
amount_total_signed = fields.Monetary(string='Total in Invoice Currency', currency_field='currency_id',
store=True, readonly=True, compute='_compute_amount',
help="Total amount in the currency of the invoice, negative for credit notes.")
amount_total_company_signed = fields.Monetary(string='Total in Company Currency', currency_field='company_currency_id',
store=True, readonly=True, compute='_compute_amount',
help="Total amount in the currency of the company, negative for credit notes.")
currency_id = fields.Many2one('res.currency', string='Currency',
required=True, readonly=True, states={'draft': [('readonly', False)]},
default=_default_currency, track_visibility='always')
company_currency_id = fields.Many2one('res.currency', related='company_id.currency_id', string="Company Currency", readonly=True)
journal_id = fields.Many2one('account.journal', string='Journal',
required=True, readonly=True, states={'draft': [('readonly', False)]},
default=_default_journal,
domain="[('type', 'in', {'out_invoice': ['sale'], 'out_refund': ['sale'], 'in_refund': ['purchase'], 'in_invoice': ['purchase']}.get(type, [])), ('company_id', '=', company_id)]")
company_id = fields.Many2one('res.company', string='Company', change_default=True,
required=True, readonly=True, states={'draft': [('readonly', False)]},
default=lambda self: self.env['res.company']._company_default_get('account.invoice'))
reconciled = fields.Boolean(string='Paid/Reconciled', store=True, readonly=True, compute='_compute_residual',
help="It indicates that the invoice has been paid and the journal entry of the invoice has been reconciled with one or several journal entries of payment.")
partner_bank_id = fields.Many2one('res.partner.bank', string='Bank Account',
help='Bank Account Number to which the invoice will be paid. A Company bank account if this is a Customer Invoice or Vendor Credit Note, otherwise a Partner bank account number.',
readonly=True, states={'draft': [('readonly', False)]}) #Default value computed in default_get for out_invoices
residual = fields.Monetary(string='Amount Due',
compute='_compute_residual', store=True, help="Remaining amount due.")
residual_signed = fields.Monetary(string='Amount Due in Invoice Currency', currency_field='currency_id',
compute='_compute_residual', store=True, help="Remaining amount due in the currency of the invoice.")
residual_company_signed = fields.Monetary(string='Amount Due in Company Currency', currency_field='company_currency_id',
compute='_compute_residual', store=True, help="Remaining amount due in the currency of the company.")
payment_ids = fields.Many2many('account.payment', 'account_invoice_payment_rel', 'invoice_id', 'payment_id', string="Payments", copy=False, readonly=True)
payment_move_line_ids = fields.Many2many('account.move.line', string='Payment Move Lines', compute='_compute_payments', store=True)
user_id = fields.Many2one('res.users', string='Salesperson', track_visibility='onchange',
readonly=True, states={'draft': [('readonly', False)]},
default=lambda self: self.env.user)
fiscal_position_id = fields.Many2one('account.fiscal.position', string='Fiscal Position', oldname='fiscal_position',
readonly=True, states={'draft': [('readonly', False)]})
commercial_partner_id = fields.Many2one('res.partner', string='Commercial Entity', compute_sudo=True,
related='partner_id.commercial_partner_id', store=True, readonly=True,
help="The commercial entity that will be used on Journal Entries for this invoice")
outstanding_credits_debits_widget = fields.Text(compute='_get_outstanding_info_JSON')
payments_widget = fields.Text(compute='_get_payment_info_JSON')
has_outstanding = fields.Boolean(compute='_get_outstanding_info_JSON')
#fields use to set the sequence, on the first invoice of the journal
sequence_number_next = fields.Char(string='Next Number', compute="_get_sequence_prefix", inverse="_set_sequence_next")
sequence_number_next_prefix = fields.Char(string='Next Number', compute="_get_sequence_prefix")
_sql_constraints = [
('number_uniq', 'unique(number, company_id, journal_id, type)', 'Invoice Number must be unique per Company!'),
]
@api.depends('state', 'journal_id', 'date_invoice')
def _get_sequence_prefix(self):
""" computes the number that will be assigned to the first invoice/bill/refund of a journal, in order to
let the user manually change it.
"""
for invoice in self:
journal_sequence = invoice.journal_id.sequence_id
if invoice.journal_id.refund_sequence:
domain = [('type', '=', invoice.type)]
journal_sequence = invoice.type in ['in_refund', 'out_refund'] and invoice.journal_id.refund_sequence_id or invoice.journal_id.sequence_id
elif invoice.type in ['in_invoice', 'in_refund']:
domain = [('type', 'in', ['in_invoice', 'in_refund'])]
else:
domain = [('type', 'in', ['out_invoice', 'out_refund'])]
if invoice.id:
domain += [('id', '<>', invoice.id)]
domain += [('journal_id', '=', invoice.journal_id.id), ('state', 'not in', ['draft', 'cancel'])]
if (invoice.state == 'draft') and not self.search(domain, limit=1):
prefix, dummy = journal_sequence.with_context(ir_sequence_date=invoice.date_invoice)._get_prefix_suffix()
invoice.sequence_number_next_prefix = prefix
number_next = journal_sequence._get_current_sequence().number_next_actual
invoice.sequence_number_next = '%%0%sd' % journal_sequence.padding % number_next
else:
invoice.sequence_number_next_prefix = False
invoice.sequence_number_next = 'no'
@api.multi
def _set_sequence_next(self):
''' Set the number_next on the sequence related to the invoice/bill/refund'''
for invoice in self:
nxt = re.sub("[^0-9]", '', invoice.sequence_number_next or '1')
result = re.match("(0*)([0-9]+)", nxt)
journal_sequence = invoice.journal_id.refund_sequence and invoice.journal_id.refund_sequence_id or invoice.journal_id.sequence_id
if result and journal_sequence:
#use _get_current_sequence to manage the date range sequences
sequence = journal_sequence._get_current_sequence()
sequence.number_next = int(result.group(2))
@api.model
def create(self, vals):
onchanges = {
'_onchange_partner_id': ['account_id', 'payment_term_id', 'fiscal_position_id', 'partner_bank_id'],
'_onchange_journal_id': ['currency_id'],
}
for onchange_method, changed_fields in pycompat.items(onchanges):
if any(f not in vals for f in changed_fields):
invoice = self.new(vals)
getattr(invoice, onchange_method)()
for field in changed_fields:
if field not in vals and invoice[field]:
vals[field] = invoice._fields[field].convert_to_write(invoice[field], invoice)
if not vals.get('account_id',False):
raise UserError(_('Configuration error!\nCould not find any account to create the invoice, are you sure you have a chart of account installed?'))
invoice = super(AccountInvoice, self.with_context(mail_create_nolog=True)).create(vals)
if any(line.invoice_line_tax_ids for line in invoice.invoice_line_ids) and not invoice.tax_line_ids:
invoice.compute_taxes()
return invoice
@api.multi
def _write(self, vals):
pre_not_reconciled = self.filtered(lambda invoice: not invoice.reconciled)
pre_reconciled = self - pre_not_reconciled
res = super(AccountInvoice, self)._write(vals)
reconciled = self.filtered(lambda invoice: invoice.reconciled)
not_reconciled = self - reconciled
(reconciled & pre_reconciled).filtered(lambda invoice: invoice.state == 'open').action_invoice_paid()
(not_reconciled & pre_not_reconciled).filtered(lambda invoice: invoice.state == 'paid').action_invoice_re_open()
return res
@api.model
def default_get(self,default_fields):
""" Compute default partner_bank_id field for 'out_invoice' type,
using the default values computed for the other fields.
"""
res = super(AccountInvoice, self).default_get(default_fields)
if not res.get('type', False) == 'out_invoice' or not 'company_id' in res:
return res
company = self.env['res.company'].browse(res['company_id'])
if company.partner_id:
partner_bank_result = self.env['res.partner.bank'].search([('partner_id', '=', company.partner_id.id)], limit=1)
if partner_bank_result:
res['partner_bank_id'] = partner_bank_result.id
return res
@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
def get_view_id(xid, name):
try:
return self.env.ref('account.' + xid)
except ValueError:
view = self.env['ir.ui.view'].search([('name', '=', name)], limit=1)
if not view:
return False
return view.id
context = self._context
if context.get('active_model') == 'res.partner' and context.get('active_ids'):
partner = self.env['res.partner'].browse(context['active_ids'])[0]
if not view_type:
view_id = get_view_id('invoice_tree', 'account.invoice.tree')
view_type = 'tree'
elif view_type == 'form':
if partner.supplier and not partner.customer:
view_id = get_view_id('invoice_supplier_form', 'account.invoice.supplier.form').id
elif partner.customer and not partner.supplier:
view_id = get_view_id('invoice_form', 'account.invoice.form').id
return super(AccountInvoice, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
@api.multi
def invoice_print(self):
""" Print the invoice and mark it as sent, so that we can see more
easily the next step of the workflow
"""
self.ensure_one()
self.sent = True
return self.env.ref('account.account_invoices').report_action(self)
@api.multi
def action_invoice_sent(self):
""" Open a window to compose an email, with the edi invoice template
message loaded by default
"""
self.ensure_one()
template = self.env.ref('account.email_template_edi_invoice', False)
compose_form = self.env.ref('mail.email_compose_message_wizard_form', False)
ctx = dict(
default_model='account.invoice',
default_res_id=self.id,
default_use_template=bool(template),
default_template_id=template and template.id or False,
default_composition_mode='comment',
mark_invoice_as_sent=True,
custom_layout="account.mail_template_data_notification_email_account_invoice"
)
return {
'name': _('Compose Email'),
'type': 'ir.actions.act_window',
'view_type': 'form',
'view_mode': 'form',
'res_model': 'mail.compose.message',
'views': [(compose_form.id, 'form')],
'view_id': compose_form.id,
'target': 'new',
'context': ctx,
}
@api.multi
def compute_taxes(self):
"""Function used in other module to compute the taxes on a fresh invoice created (onchanges did not applied)"""
account_invoice_tax = self.env['account.invoice.tax']
ctx = dict(self._context)
for invoice in self:
# Delete non-manual tax lines
self._cr.execute("DELETE FROM account_invoice_tax WHERE invoice_id=%s AND manual is False", (invoice.id,))
self.invalidate_cache()
# Generate one tax line per tax, however many invoice lines it's applied to
tax_grouped = invoice.get_taxes_values()
# Create new tax lines
for tax in pycompat.values(tax_grouped):
account_invoice_tax.create(tax)
# dummy write on self to trigger recomputations
return self.with_context(ctx).write({'invoice_line_ids': []})
@api.multi
def unlink(self):
for invoice in self:
if invoice.state not in ('draft', 'cancel'):
raise UserError(_('You cannot delete an invoice which is not draft or cancelled. You should create a credit note instead.'))
elif invoice.move_name:
raise UserError(_('You cannot delete an invoice after it has been validated (and received a number). You can set it back to "Draft" state and modify its content, then re-confirm it.'))
return super(AccountInvoice, self).unlink()
@api.onchange('invoice_line_ids')
def _onchange_invoice_line_ids(self):
taxes_grouped = self.get_taxes_values()
tax_lines = self.tax_line_ids.filtered('manual')
for tax in pycompat.values(taxes_grouped):
tax_lines += tax_lines.new(tax)
self.tax_line_ids = tax_lines
return
@api.onchange('partner_id', 'company_id')
def _onchange_partner_id(self):
account_id = False
payment_term_id = False
fiscal_position = False
bank_id = False
warning = {}
domain = {}
company_id = self.company_id.id
p = self.partner_id if not company_id else self.partner_id.with_context(force_company=company_id)
type = self.type
if p:
rec_account = p.property_account_receivable_id
pay_account = p.property_account_payable_id
if not rec_account and not pay_account:
action = self.env.ref('account.action_account_config')
msg = _('Cannot find a chart of accounts for this company, You should configure it. \nPlease go to Account Configuration.')
raise RedirectWarning(msg, action.id, _('Go to the configuration panel'))
if type in ('out_invoice', 'out_refund'):
account_id = rec_account.id
payment_term_id = p.property_payment_term_id.id
else:
account_id = pay_account.id
payment_term_id = p.property_supplier_payment_term_id.id
delivery_partner_id = self.get_delivery_partner_id()
fiscal_position = self.env['account.fiscal.position'].get_fiscal_position(self.partner_id.id, delivery_id=delivery_partner_id)
# If partner has no warning, check its company
if p.invoice_warn == 'no-message' and p.parent_id:
p = p.parent_id
if p.invoice_warn != 'no-message':
# Block if partner only has warning but parent company is blocked
if p.invoice_warn != 'block' and p.parent_id and p.parent_id.invoice_warn == 'block':
p = p.parent_id
warning = {
'title': _("Warning for %s") % p.name,
'message': p.invoice_warn_msg
}
if p.invoice_warn == 'block':
self.partner_id = False
self.account_id = account_id
self.payment_term_id = payment_term_id
self.fiscal_position_id = fiscal_position
if type in ('in_invoice', 'out_refund'):
bank_ids = p.commercial_partner_id.bank_ids
bank_id = bank_ids[0].id if bank_ids else False
self.partner_bank_id = bank_id
domain = {'partner_bank_id': [('id', 'in', bank_ids.ids)]}
res = {}
if warning:
res['warning'] = warning
if domain:
res['domain'] = domain
return res
@api.multi
def get_delivery_partner_id(self):
self.ensure_one()
return self.partner_id.address_get(['delivery'])['delivery']
@api.onchange('journal_id')
def _onchange_journal_id(self):
if self.journal_id:
self.currency_id = self.journal_id.currency_id.id or self.journal_id.company_id.currency_id.id
@api.onchange('payment_term_id', 'date_invoice')
def _onchange_payment_term_date_invoice(self):
date_invoice = self.date_invoice
if not date_invoice:
date_invoice = fields.Date.context_today(self)
if self.payment_term_id:
pterm = self.payment_term_id
pterm_list = pterm.with_context(currency_id=self.company_id.currency_id.id).compute(value=1, date_ref=date_invoice)[0]
self.date_due = max(line[0] for line in pterm_list)
elif self.date_due and (date_invoice > self.date_due):
self.date_due = date_invoice
@api.multi
def action_invoice_draft(self):
if self.filtered(lambda inv: inv.state != 'cancel'):
raise UserError(_("Invoice must be cancelled in order to reset it to draft."))
# go from canceled state to draft state
self.write({'state': 'draft', 'date': False})
# Delete former printed invoice
try:
report_invoice = self.env['ir.actions.report']._get_report_from_name('account.report_invoice')
except IndexError:
report_invoice = False
if report_invoice and report_invoice.attachment:
for invoice in self:
with invoice.env.do_in_draft():
invoice.number, invoice.state = invoice.move_name, 'open'
attachment = self.env.ref('account.account_invoices').retrieve_attachment(invoice)
if attachment:
attachment.unlink()
return True
@api.multi
def action_invoice_open(self):
# lots of duplicate calls to action_invoice_open, so we remove those already open
to_open_invoices = self.filtered(lambda inv: inv.state != 'open')
if to_open_invoices.filtered(lambda inv: inv.state != 'draft'):
raise UserError(_("Invoice must be in draft state in order to validate it."))
if to_open_invoices.filtered(lambda inv: inv.amount_total < 0):
raise UserError(_("You cannot validate an invoice with a negative total amount. You should create a credit note instead."))
to_open_invoices.action_date_assign()
to_open_invoices.action_move_create()
return to_open_invoices.invoice_validate()
@api.multi
def action_invoice_paid(self):
# lots of duplicate calls to action_invoice_paid, so we remove those already paid
to_pay_invoices = self.filtered(lambda inv: inv.state != 'paid')
if to_pay_invoices.filtered(lambda inv: inv.state != 'open'):
raise UserError(_('Invoice must be validated in order to set it to register payment.'))
if to_pay_invoices.filtered(lambda inv: not inv.reconciled):
raise UserError(_('You cannot pay an invoice which is partially paid. You need to reconcile payment entries first.'))
return to_pay_invoices.write({'state': 'paid'})
@api.multi
def action_invoice_re_open(self):
if self.filtered(lambda inv: inv.state != 'paid'):
raise UserError(_('Invoice must be paid in order to set it to register payment.'))
return self.write({'state': 'open'})
@api.multi
def action_invoice_cancel(self):
if self.filtered(lambda inv: inv.state not in ['draft', 'open']):
raise UserError(_("Invoice must be in draft or open state in order to be cancelled."))
return self.action_cancel()
@api.multi
def get_formview_id(self, access_uid=None):
""" Update form view id of action to open the invoice """
if self.type in ('in_invoice', 'in_refund'):
return self.env.ref('account.invoice_supplier_form').id
else:
return self.env.ref('account.invoice_form').id
def _prepare_tax_line_vals(self, line, tax):
""" Prepare values to create an account.invoice.tax line
The line parameter is an account.invoice.line, and the
tax parameter is the output of account.tax.compute_all().
"""
vals = {
'invoice_id': self.id,
'name': tax['name'],
'tax_id': tax['id'],
'amount': tax['amount'],
'base': tax['base'],
'manual': False,
'sequence': tax['sequence'],
'account_analytic_id': tax['analytic'] and line.account_analytic_id.id or False,
'account_id': self.type in ('out_invoice', 'in_invoice') and (tax['account_id'] or line.account_id.id) or (tax['refund_account_id'] or line.account_id.id),
}
# If the taxes generate moves on the same financial account as the invoice line,
# propagate the analytic account from the invoice line to the tax line.
# This is necessary in situations were (part of) the taxes cannot be reclaimed,
# to ensure the tax move is allocated to the proper analytic account.
if not vals.get('account_analytic_id') and line.account_analytic_id and vals['account_id'] == line.account_id.id:
vals['account_analytic_id'] = line.account_analytic_id.id
return vals
@api.multi
def get_taxes_values(self):
tax_grouped = {}
for line in self.invoice_line_ids:
price_unit = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
taxes = line.invoice_line_tax_ids.compute_all(price_unit, self.currency_id, line.quantity, line.product_id, self.partner_id)['taxes']
for tax in taxes:
val = self._prepare_tax_line_vals(line, tax)
key = self.env['account.tax'].browse(tax['id']).get_grouping_key(val)
if key not in tax_grouped:
tax_grouped[key] = val
else:
tax_grouped[key]['amount'] += val['amount']
tax_grouped[key]['base'] += val['base']
return tax_grouped
@api.multi
def register_payment(self, payment_line, writeoff_acc_id=False, writeoff_journal_id=False):
""" Reconcile payable/receivable lines from the invoice with payment_line """
line_to_reconcile = self.env['account.move.line']
for inv in self:
line_to_reconcile += inv.move_id.line_ids.filtered(lambda r: not r.reconciled and r.account_id.internal_type in ('payable', 'receivable'))
return (line_to_reconcile + payment_line).reconcile(writeoff_acc_id, writeoff_journal_id)
@api.multi
def assign_outstanding_credit(self, credit_aml_id):
self.ensure_one()
credit_aml = self.env['account.move.line'].browse(credit_aml_id)
if not credit_aml.currency_id and self.currency_id != self.company_id.currency_id:
credit_aml.with_context(allow_amount_currency=True).write({
'amount_currency': self.company_id.currency_id.with_context(date=credit_aml.date).compute(credit_aml.balance, self.currency_id),
'currency_id': self.currency_id.id})
if credit_aml.payment_id:
credit_aml.payment_id.write({'invoice_ids': [(4, self.id, None)]})
return self.register_payment(credit_aml)
@api.multi
def action_date_assign(self):
for inv in self:
# Here the onchange will automatically write to the database
inv._onchange_payment_term_date_invoice()
return True
@api.multi
def finalize_invoice_move_lines(self, move_lines):
""" finalize_invoice_move_lines(move_lines) -> move_lines
Hook method to be overridden in additional modules to verify and
possibly alter the move lines to be created by an invoice, for
special cases.
:param move_lines: list of dictionaries with the account.move.lines (as for create())
:return: the (possibly updated) final move_lines to create for this invoice
"""
return move_lines
@api.multi
def compute_invoice_totals(self, company_currency, invoice_move_lines):
total = 0
total_currency = 0
for line in invoice_move_lines:
if self.currency_id != company_currency:
currency = self.currency_id.with_context(date=self.date or self.date_invoice or fields.Date.context_today(self))
if not (line.get('currency_id') and line.get('amount_currency')):
line['currency_id'] = currency.id
line['amount_currency'] = currency.round(line['price'])
line['price'] = currency.compute(line['price'], company_currency)
else:
line['currency_id'] = False
line['amount_currency'] = False
line['price'] = self.currency_id.round(line['price'])
if self.type in ('out_invoice', 'in_refund'):
total += line['price']
total_currency += line['amount_currency'] or line['price']
line['price'] = - line['price']
else:
total -= line['price']
total_currency -= line['amount_currency'] or line['price']
return total, total_currency, invoice_move_lines
@api.model
def invoice_line_move_line_get(self):
res = []
for line in self.invoice_line_ids:
if line.quantity==0:
continue
tax_ids = []
for tax in line.invoice_line_tax_ids:
tax_ids.append((4, tax.id, None))
for child in tax.children_tax_ids:
if child.type_tax_use != 'none':
tax_ids.append((4, child.id, None))
analytic_tag_ids = [(4, analytic_tag.id, None) for analytic_tag in line.analytic_tag_ids]
move_line_dict = {
'invl_id': line.id,
'type': 'src',
'name': line.name.split('\n')[0][:64],
'price_unit': line.price_unit,
'quantity': line.quantity,
'price': line.price_subtotal,
'account_id': line.account_id.id,
'product_id': line.product_id.id,
'uom_id': line.uom_id.id,
'account_analytic_id': line.account_analytic_id.id,
'tax_ids': tax_ids,
'invoice_id': self.id,
'analytic_tag_ids': analytic_tag_ids
}
if line['account_analytic_id']:
move_line_dict['analytic_line_ids'] = [(0, 0, line._get_analytic_line())]
res.append(move_line_dict)
return res
@api.model
def tax_line_move_line_get(self):
res = []
# keep track of taxes already processed
done_taxes = []
# loop the invoice.tax.line in reversal sequence
for tax_line in sorted(self.tax_line_ids, key=lambda x: -x.sequence):
if tax_line.amount:
tax = tax_line.tax_id
if tax.amount_type == "group":
for child_tax in tax.children_tax_ids:
done_taxes.append(child_tax.id)
done_taxes.append(tax.id)
res.append({
'invoice_tax_line_id': tax_line.id,
'tax_line_id': tax_line.tax_id.id,
'type': 'tax',
'name': tax_line.name,
'price_unit': tax_line.amount,
'quantity': 1,
'price': tax_line.amount,
'account_id': tax_line.account_id.id,
'account_analytic_id': tax_line.account_analytic_id.id,
'invoice_id': self.id,
'tax_ids': [(6, 0, done_taxes)] if tax_line.tax_id.include_base_amount else []
})
return res
def inv_line_characteristic_hashcode(self, invoice_line):
"""Overridable hashcode generation for invoice lines. Lines having the same hashcode
will be grouped together if the journal has the 'group line' option. Of course a module
can add fields to invoice lines that would need to be tested too before merging lines
or not."""
return "%s-%s-%s-%s-%s-%s-%s" % (
invoice_line['account_id'],
invoice_line.get('tax_ids', 'False'),
invoice_line.get('tax_line_id', 'False'),
invoice_line.get('product_id', 'False'),
invoice_line.get('analytic_account_id', 'False'),
invoice_line.get('date_maturity', 'False'),
invoice_line.get('analytic_tag_ids', 'False'),
)
def group_lines(self, iml, line):
"""Merge account move lines (and hence analytic lines) if invoice line hashcodes are equals"""
if self.journal_id.group_invoice_lines:
line2 = {}
for x, y, l in line:
tmp = self.inv_line_characteristic_hashcode(l)
if tmp in line2:
am = line2[tmp]['debit'] - line2[tmp]['credit'] + (l['debit'] - l['credit'])
line2[tmp]['debit'] = (am > 0) and am or 0.0
line2[tmp]['credit'] = (am < 0) and -am or 0.0
line2[tmp]['amount_currency'] += l['amount_currency']
line2[tmp]['analytic_line_ids'] += l['analytic_line_ids']
qty = l.get('quantity')
if qty:
line2[tmp]['quantity'] = line2[tmp].get('quantity', 0.0) + qty
else:
line2[tmp] = l
line = []
for key, val in pycompat.items(line2):
line.append((0, 0, val))
return line
@api.multi
def action_move_create(self):
""" Creates invoice related analytics and financial move lines """
account_move = self.env['account.move']
for inv in self:
if not inv.journal_id.sequence_id:
raise UserError(_('Please define sequence on the journal related to this invoice.'))
if not inv.invoice_line_ids:
raise UserError(_('Please create some invoice lines.'))
if inv.move_id:
continue
ctx = dict(self._context, lang=inv.partner_id.lang)
if not inv.date_invoice:
inv.with_context(ctx).write({'date_invoice': fields.Date.context_today(self)})
company_currency = inv.company_id.currency_id
# create move lines (one per invoice line + eventual taxes and analytic lines)
iml = inv.invoice_line_move_line_get()
iml += inv.tax_line_move_line_get()
diff_currency = inv.currency_id != company_currency
# create one move line for the total and possibly adjust the other lines amount
total, total_currency, iml = inv.with_context(ctx).compute_invoice_totals(company_currency, iml)
name = inv.name or '/'
if inv.payment_term_id:
totlines = inv.with_context(ctx).payment_term_id.with_context(currency_id=company_currency.id).compute(total, inv.date_invoice)[0]
res_amount_currency = total_currency
ctx['date'] = inv.date or inv.date_invoice
for i, t in enumerate(totlines):
if inv.currency_id != company_currency:
amount_currency = company_currency.with_context(ctx).compute(t[1], inv.currency_id)
else:
amount_currency = False
# last line: add the diff
res_amount_currency -= amount_currency or 0
if i + 1 == len(totlines):
amount_currency += res_amount_currency
iml.append({
'type': 'dest',
'name': name,
'price': t[1],
'account_id': inv.account_id.id,
'date_maturity': t[0],
'amount_currency': diff_currency and amount_currency,
'currency_id': diff_currency and inv.currency_id.id,
'invoice_id': inv.id
})
else:
iml.append({
'type': 'dest',
'name': name,
'price': total,
'account_id': inv.account_id.id,
'date_maturity': inv.date_due,
'amount_currency': diff_currency and total_currency,
'currency_id': diff_currency and inv.currency_id.id,
'invoice_id': inv.id
})
part = self.env['res.partner']._find_accounting_partner(inv.partner_id)
line = [(0, 0, self.line_get_convert(l, part.id)) for l in iml]
line = inv.group_lines(iml, line)
journal = inv.journal_id.with_context(ctx)
line = inv.finalize_invoice_move_lines(line)
date = inv.date or inv.date_invoice
move_vals = {
'ref': inv.reference,
'line_ids': line,
'journal_id': journal.id,
'date': date,
'narration': inv.comment,
}
ctx['company_id'] = inv.company_id.id
ctx['invoice'] = inv
ctx_nolang = ctx.copy()
ctx_nolang.pop('lang', None)
move = account_move.with_context(ctx_nolang).create(move_vals)
# Pass invoice in context in method post: used if you want to get the same
# account move reference when creating the same invoice after a cancelled one:
move.post()
# make the invoice point to that move
vals = {
'move_id': move.id,
'date': date,
'move_name': move.name,
}
inv.with_context(ctx).write(vals)
return True
@api.multi
def _check_duplicate_supplier_reference(self):
for invoice in self:
# refuse to validate a vendor bill/credit note if there already exists one with the same reference for the same partner,
# because it's probably a double encoding of the same bill/credit note
if invoice.type in ('in_invoice', 'in_refund') and invoice.reference:
if self.search([('type', '=', invoice.type), ('reference', '=', invoice.reference), ('company_id', '=', invoice.company_id.id), ('commercial_partner_id', '=', invoice.commercial_partner_id.id), ('id', '!=', invoice.id)]):
raise UserError(_("Duplicated vendor reference detected. You probably encoded twice the same vendor bill/credit note."))
@api.multi
def invoice_validate(self):
for invoice in self.filtered(lambda invoice: invoice.partner_id not in invoice.message_partner_ids):