-
Notifications
You must be signed in to change notification settings - Fork 4
/
account_invoice.go
2245 lines (2128 loc) · 86.1 KB
/
account_invoice.go
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
// Copyright 2017 NDP Systèmes. All Rights Reserved.
// See LICENSE file for full licensing details.
package account
import (
"encoding/json"
"fmt"
"math"
"strings"
"github.com/hexya-addons/account/accounttypes"
"github.com/hexya-addons/decimalPrecision"
"github.com/hexya-addons/web/webdata"
"github.com/hexya-erp/hexya/src/actions"
"github.com/hexya-erp/hexya/src/models"
"github.com/hexya-erp/hexya/src/models/operator"
"github.com/hexya-erp/hexya/src/models/types"
"github.com/hexya-erp/hexya/src/models/types/dates"
"github.com/hexya-erp/hexya/src/tools/nbutils"
"github.com/hexya-erp/hexya/src/tools/strutils"
"github.com/hexya-erp/hexya/src/views"
"github.com/hexya-erp/pool/h"
"github.com/hexya-erp/pool/m"
"github.com/hexya-erp/pool/q"
)
// ReferenceType for a move
var ReferenceType = types.Selection{
"none": "Free Reference",
}
// Type2Journal is mapping from invoice type to journal type
var Type2Journal = map[string]string{
"out_invoice": "sale",
"in_invoice": "purchase",
"out_refund": "sale",
"in_refund": "purchase",
}
// Type2Refund is a mapping from invoice type to refund type
var Type2Refund = map[string]string{
`out_invoice`: `out_refund`, // Customer Invoice
`in_invoice`: `in_refund`, // Vendor Bill
`out_refund`: `out_invoice`, // Customer Refund
`in_refund`: `in_invoice`, // Vendor Refund
}
// Type2PartnerType is a mapping from invoice type to partner type
var Type2PartnerType = map[string]string{
`out_invoice`: `customer`,
`out_refund`: `customer`,
`in_invoice`: `supplier`,
`in_refund`: `supplier`,
}
// Type2PaymentType is a mapping from invoice type to 1 or -1.
// Since invoice amounts are unsigned, this is how we know if money comes in or goes out
var Type2PaymentType = map[string]float64{
`out_invoice`: 1.0,
`in_refund`: 1.0,
`in_invoice`: -1.0,
`out_refund`: -1.0,
}
func init() {
h.AccountInvoice().DeclareModel()
h.AccountInvoice().SetDefaultOrder("DateInvoice DESC", "Number DESC", "ID DESC")
h.AccountInvoice().AddFields(map[string]models.FieldDefinition{
"Name": models.CharField{
String: "Reference/Description",
Index: true, /*[ readonly True]*/ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/
NoCopy: true,
Help: "The name that will be used on account move lines"},
"Origin": models.CharField{
String: "Source Document",
Help: "Reference of the document that produced this invoice." /*[ readonly True]*/ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/},
"Type": models.SelectionField{
Selection: types.Selection{
"out_invoice": "Customer Invoice",
"in_invoice": "Vendor Bill",
"out_refund": "Customer Refund",
"in_refund": "Vendor Refund"},
ReadOnly: true,
Index: true,
Default: func(env models.Environment) interface{} {
if env.Context().HasKey("type") {
return env.Context().GetString("type")
}
return "out_invoice"
} /*[ track_visibility 'always']*/},
"RefundInvoice": models.Many2OneField{
String: "Invoice for which this invoice is the refund",
RelationModel: h.AccountInvoice()},
"Number": models.CharField{
Related: "Move.Name",
ReadOnly: true,
NoCopy: true},
"MoveName": models.CharField{
String: "Journal Entry Name",
NoCopy: true,
Default: models.DefaultValue(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": models.CharField{
String: "Vendor Reference",
Help: "The partner reference of this invoice." /*[ readonly True]*/ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/},
"ReferenceType": models.SelectionField{
Selection: ReferenceType,
String: "Payment Reference", /* states draft:"readonly": "False" */
Default: models.DefaultValue("none"),
Required: true},
"Comment": models.TextField{
String: "Additional Information" /*[ readonly True]*/ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/},
"State": models.SelectionField{
String: "Status",
Selection: types.Selection{
"draft": "Draft",
"proforma": "Pro-forma",
"proforma2": "Pro-forma",
"open": "Open",
"paid": "Paid",
"cancel": "Cancelled"},
Index: true,
ReadOnly: true,
Default: models.DefaultValue("draft"), /*[ track_visibility 'onchange']*/
NoCopy: true,
Help: ` * The 'Draft' status is used when a user is encoding a new and unconfirmed Invoice.
* The 'Pro-forma' status is used when the invoice does not have an invoice number.
* 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.
* The 'Paid' status is set automatically when the invoice is paid. Its related journal
entries may or may not be reconciled.
* The 'Cancelled' status is used when user cancel invoice.`},
"Sent": models.BooleanField{
ReadOnly: true,
Default: models.DefaultValue(false),
NoCopy: true,
Help: "It indicates that the invoice has been sent."},
"DateInvoice": models.DateField{String: "Invoice Date", /*[ readonly True]*/ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/
Index: true, Help: "Keep empty to use the current date", NoCopy: true,
Constraint: h.AccountInvoice().Methods().OnchangePaymentTermDateInvoice()},
"DateDue": models.DateField{String: "Due Date", /*[ readonly True]*/ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/
Index: true, NoCopy: true,
Help: `If you use payment terms, the due date will be computed automatically at the generation
of accounting entries. The payment term 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 term and the due date empty, it
means direct payment.`},
"Partner": models.Many2OneField{
RelationModel: h.Partner(),
Required: true, /* readonly=true */ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/ /*[ track_visibility 'always']*/
OnChange: h.AccountInvoice().Methods().OnchangePartner()},
"PaymentTerm": models.Many2OneField{
String: "Payment Terms",
RelationModel: h.AccountPaymentTerm(), /* readonly=true */ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/
Constraint: h.AccountInvoice().Methods().OnchangePaymentTermDateInvoice(),
Help: `If you use payment terms, the due date will be computed automatically at the generation
of accounting entries. If you keep the payment term and the due date empty, it means direct payment.
The payment term may compute several due dates, for example 50% now, 50% in one month.`},
"Date": models.DateField{
String: "Accounting Date",
NoCopy: true,
Help: "Keep empty to use the invoice date." /*[ readonly True]*/ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/},
"Account": models.Many2OneField{
String: "Account",
RelationModel: h.AccountAccount(),
Required: true, /* readonly=true */ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/
Filter: q.AccountAccount().Deprecated().Equals(false),
Help: "The partner account used for this invoice."},
"InvoiceLines": models.One2ManyField{
String: "Invoice Lines",
RelationModel: h.AccountInvoiceLine(),
ReverseFK: "Invoice",
JSON: "invoice_line_ids", /* readonly */ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/
OnChange: h.AccountInvoice().Methods().OnchangeInvoiceLines(),
Copy: true},
"TaxLines": models.One2ManyField{
RelationModel: h.AccountInvoiceTax(),
ReverseFK: "Invoice",
JSON: "tax_line_ids", /* readonly */ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/
Copy: true},
"Move": models.Many2OneField{
String: "Journal Entry",
RelationModel: h.AccountMove(),
ReadOnly: true,
Index: true,
OnDelete: models.Restrict,
NoCopy: true,
Help: "Link to the automatically generated Journal Items."},
"AmountUntaxed": models.FloatField{
String: "Untaxed Amount",
Stored: true,
Compute: h.AccountInvoice().Methods().ComputeAmount(), /*[ track_visibility 'always']*/
Depends: []string{"InvoiceLines.PriceSubtotal", "TaxLines.Amount", "Currency", "Company", "DateInvoice", "Type"}},
"AmountUntaxedSigned": models.FloatField{
String: "Untaxed Amount in Company Currency",
Stored: true,
Compute: h.AccountInvoice().Methods().ComputeAmount(),
Depends: []string{"InvoiceLines.PriceSubtotal", "TaxLines.Amount", "Currency", "Company", "DateInvoice", "Type"}},
"AmountTax": models.FloatField{
String: "Tax",
Stored: true,
Compute: h.AccountInvoice().Methods().ComputeAmount(),
Depends: []string{"InvoiceLines.PriceSubtotal", "TaxLines.Amount", "Currency", "Company", "DateInvoice", "Type"}},
"AmountTotal": models.FloatField{
String: "Total",
Stored: true,
Compute: h.AccountInvoice().Methods().ComputeAmount(),
Depends: []string{"InvoiceLines.PriceSubtotal", "TaxLines.Amount", "Currency", "Company", "DateInvoice", "Type"}},
"AmountTotalSigned": models.FloatField{
String: "Total in Invoice Currency",
Stored: true,
Compute: h.AccountInvoice().Methods().ComputeAmount(),
Depends: []string{"InvoiceLines.PriceSubtotal", "TaxLines.Amount", "Currency", "Company", "DateInvoice", "Type"},
Help: "Total amount in the currency of the invoice, negative for credit notes."},
"AmountTotalCompanySigned": models.FloatField{
String: "Total in Company Currency",
Stored: true,
Compute: h.AccountInvoice().Methods().ComputeAmount(),
Depends: []string{"InvoiceLines.PriceSubtotal", "TaxLines.Amount", "Currency", "Company", "DateInvoice", "Type"},
Help: "Total amount in the currency of the company, negative for credit notes."},
"Currency": models.Many2OneField{
RelationModel: h.Currency(),
Required: true, /* readonly=true */ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/
Default: func(env models.Environment) interface{} {
journal := h.AccountInvoice().NewSet(env).DefaultJournal()
return h.Currency().Coalesce(journal.Currency(), journal.Company().Currency(), h.User().NewSet(env).CurrentUser().Company().Currency())
} /*[ track_visibility 'always']*/},
"CompanyCurrency": models.Many2OneField{
RelationModel: h.Currency(),
Related: "Company.Currency",
ReadOnly: true},
"Journal": models.Many2OneField{
RelationModel: h.AccountJournal(),
Required: true, /* readonly=true */ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/
OnChange: h.AccountInvoice().Methods().OnchangeJournal(),
Default: func(env models.Environment) interface{} {
return h.AccountInvoice().NewSet(env).DefaultJournal()
} /*Filter: "[('type'*/ /*[ 'in']*/ /*[ {'out_invoice': ['sale']]*/ /*[ 'out_refund': ['sale']]*/ /*[ 'in_refund': ['purchase']] [ 'in_invoice': ['purchase']}.get(type, ('company_id']*/ /*[ ' ']*/ /*[ company_id)]"]*/},
"Company": models.Many2OneField{
RelationModel: h.Company(),
Required: true, /* readonly=true */ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/
Default: func(env models.Environment) interface{} {
return h.Company().NewSet(env).CompanyDefaultGet()
},
OnChange: h.AccountInvoice().Methods().OnchangePartner()},
"Reconciled": models.BooleanField{
String: "Paid/Reconciled",
Stored: true,
Compute: h.AccountInvoice().Methods().ComputeResidual(),
Depends: []string{"State", "Currency", "InvoiceLines.PriceSubtotal", "Move.Lines.AmountResidual", "Move.Lines.Currency"},
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.`},
"PartnerBank": models.Many2OneField{
String: "Bank Account",
RelationModel: h.BankAccount(),
Help: `Bank Account Number to which the invoice will be paid.
A Company bank account if this is a Customer Invoice or Vendor Refund, otherwise a Partner bank account number.`, /* readonly=True */ /* states={'draft': [('readonly', False)]}" */
},
"Residual": models.FloatField{
String: "Amount Due",
Compute: h.AccountInvoice().Methods().ComputeResidual(),
Stored: true,
Help: "Remaining amount due.",
Depends: []string{"State", "Currency", "InvoiceLines.PriceSubtotal", "Move.Lines.AmountResidual", "Move.Lines.Currency"}},
"ResidualSigned": models.FloatField{
String: "Amount Due in Invoice Currency",
Compute: h.AccountInvoice().Methods().ComputeResidual(),
Stored: true,
Depends: []string{"State", "Currency", "InvoiceLines.PriceSubtotal", "Move.Lines.AmountResidual", "Move.Lines.Currency"},
Help: "Remaining amount due in the currency of the invoice."},
"ResidualCompanySigned": models.FloatField{
String: "Amount Due in Company Currency",
Compute: h.AccountInvoice().Methods().ComputeResidual(),
Stored: true,
Depends: []string{"State", "Currency", "InvoiceLines.PriceSubtotal", "Move.Lines.AmountResidual", "Move.Lines.Currency"},
Help: "Remaining amount due in the currency of the company."},
"Payments": models.Many2ManyField{
RelationModel: h.AccountPayment(),
JSON: "payment_ids",
NoCopy: true,
ReadOnly: true},
"PaymentMoveLines": models.Many2ManyField{
String: "Payment Move Lines",
RelationModel: h.AccountMoveLine(),
JSON: "payment_move_line_ids",
Compute: h.AccountInvoice().Methods().ComputePayments(),
Stored: true,
Depends: []string{"Move.Lines.AmountResidual"}},
"User": models.Many2OneField{
String: "Salesperson",
RelationModel: h.User(), /*[ track_visibility 'onchange']*/
/* readonly=true */ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/
Default: func(env models.Environment) interface{} {
return h.User().NewSet(env).CurrentUser()
}},
"FiscalPosition": models.Many2OneField{
RelationModel: h.AccountFiscalPosition() /* readonly=true */ /*[ states {'draft': [('readonly']*/ /*[ False)]}]*/},
"CommercialPartner": models.Many2OneField{
String: "Commercial Entity",
RelationModel: h.Partner(),
Related: "Partner.CommercialPartner",
ReadOnly: true,
Help: "The commercial entity that will be used on Journal Entries for this invoice"},
"OutstandingCreditsDebitsWidget": models.TextField{
Compute: h.AccountInvoice().Methods().GetOutstandingInfoJSON()},
"PaymentsWidget": models.TextField{
Compute: h.AccountInvoice().Methods().GetPaymentInfoJSON(),
Depends: []string{"PaymentMoveLines.AmountResidual"}},
"HasOutstanding": models.BooleanField{
Compute: h.AccountInvoice().Methods().GetOutstandingInfoJSON()},
})
// TODO implement as constraint
//h.AccountInvoice().AddSQLConstraint("number_uniq", "unique(number, company_id, journal_id, type)",
// "Invoice Number must be unique per Company!")
h.AccountInvoice().Methods().ComputeAmount().DeclareMethod(
`ComputeAmount`,
func(rs m.AccountInvoiceSet) m.AccountInvoiceData {
data := h.AccountInvoice().NewData()
valueUntaxed := 0.0
for _, line := range rs.InvoiceLines().Records() {
valueUntaxed += line.PriceSubtotal()
}
data.SetAmountUntaxed(valueUntaxed)
valueTax := 0.0
for _, line := range rs.TaxLines().Records() {
valueTax += line.Amount()
}
data.SetAmountTax(valueTax)
valueTotal := valueUntaxed + valueTax
data.SetAmountTotal(valueTotal)
if rs.Currency().IsNotEmpty() && rs.Company().IsNotEmpty() && !rs.Currency().Equals(rs.Company().Currency()) {
currency := rs.Currency().WithContext("date", rs.DateInvoice())
valueTotal = currency.Compute(valueTotal, rs.Company().Currency(), true)
valueUntaxed = currency.Compute(valueUntaxed, rs.Company().Currency(), true)
}
sign := 1.0
if strutils.IsIn(rs.Type(), "in_refund", "out_refund") {
sign = -1.0
}
data.SetAmountTotalCompanySigned(valueTotal * sign)
data.SetAmountTotalSigned(data.AmountTotal() * sign)
data.SetAmountUntaxedSigned(valueUntaxed * sign)
return data
})
h.AccountInvoice().Methods().DefaultJournal().DeclareMethod(
`DefaultJournal`,
func(rs m.AccountInvoiceSet) m.AccountJournalSet {
if rs.Env().Context().HasKey("default_journal_id") {
return h.AccountJournal().Browse(rs.Env(),
[]int64{rs.Env().Context().GetInteger("default_journal_id")})
}
invType := "out_invoice"
if rs.Env().Context().HasKey("type") {
invType = rs.Env().Context().GetString("type")
}
company := h.User().NewSet(rs.Env()).CurrentUser().Company()
if rs.Env().Context().HasKey("company_id") {
company = h.Company().Browse(rs.Env(), []int64{rs.Env().Context().GetInteger("company_id")})
}
jType := Type2Journal[invType]
cond := q.AccountJournal().Type().Equals(jType).And().Company().Equals(company)
return h.AccountJournal().Search(rs.Env(), cond)
})
h.AccountInvoice().Methods().ComputeResidual().DeclareMethod(
`ComputeResidual`,
func(rs m.AccountInvoiceSet) m.AccountInvoiceData {
residual := 0.0
residualCompanySigned := 0.0
sign := 1.0
if strutils.IsIn(rs.Type(), "in_refund", "out_refund") {
sign = -1.0
}
for _, line := range rs.Sudo().Move().Lines().Records() {
if !strutils.IsIn(line.Account().InternalType(), "receivable", "payable") {
continue
}
residualCompanySigned += line.AmountResidual()
if line.Currency().Equals(rs.Currency()) {
if line.Currency().IsNotEmpty() {
residual += line.AmountResidualCurrency()
} else {
residual += line.AmountResidual()
}
} else {
fromCurrency := line.Company().Currency().WithContext("date", line.Date())
if line.Currency().IsNotEmpty() {
fromCurrency = line.Currency().WithContext("date", line.Date())
}
residual += fromCurrency.Compute(line.AmountResidual(), rs.Currency(), true)
}
}
data := h.AccountInvoice().NewData()
data.SetResidualCompanySigned(math.Abs(residualCompanySigned) * sign)
data.SetResidualSigned(math.Abs(residual) * sign)
data.SetResidual(math.Abs(residual))
data.SetReconciled(false)
if rs.Currency().IsZero(data.Residual()) {
data.SetReconciled(true)
}
return data
})
h.AccountInvoice().Methods().GetOutstandingInfoJSON().DeclareMethod(
`GetOutstandingInfoJSON`,
func(rs m.AccountInvoiceSet) m.AccountInvoiceData {
data := h.AccountInvoice().NewData()
data.SetOutstandingCreditsDebitsWidget("false")
if rs.State() != "open" {
return data
}
domain := q.AccountMoveLine().Account().Equals(rs.Account()).
And().Partner().Equals(h.Partner().NewSet(rs.Env()).FindAccountingPartner(rs.Partner())).
And().Reconciled().Equals(false).
And().AmountResidual().NotEquals(0.0)
var typePayment string
if strutils.IsIn(rs.Type(), "out_invoice", "in_refund") {
domain = domain.And().Credit().Greater(0.0).And().Debit().Equals(0.0)
typePayment = rs.T(`Outstanding credits`)
} else {
domain = domain.And().Credit().Equals(0.0).And().Debit().Greater(0.0)
typePayment = rs.T(`Outstanding debits`)
}
lines := h.AccountMoveLine().Search(rs.Env(), domain)
if lines.IsEmpty() {
return data
}
var infoContent []map[string]interface{}
for _, line := range lines.Records() {
// get the outstanding residual value in invoice currency
var amtToShow float64
if line.Currency().IsNotEmpty() && line.Currency().Equals(rs.Currency()) {
amtToShow = math.Abs(line.AmountResidualCurrency())
} else {
amtToShow = line.Company().Currency().WithContext("date", line.Date()).Compute(math.Abs(line.AmountResidual()), rs.Currency(), true)
}
if rs.Currency().IsZero(amtToShow) {
continue
}
curInfoContent := make(map[string]interface{})
curInfoContent["journal_name"] = line.Move().Name()
if line.Ref() != "" {
curInfoContent["journal_name"] = line.Ref()
}
curInfoContent["amount"] = amtToShow
curInfoContent["currency"] = rs.Currency().Symbol()
curInfoContent["id"] = line.ID()
curInfoContent["position"] = rs.Currency().Position()
curInfoContent["digits"] = []int{69, rs.Currency().DecimalPlaces()}
infoContent = append(infoContent, curInfoContent)
}
info := make(map[string]interface{})
info["title"] = typePayment
info["outstanding"] = true
info["invoice_id"] = rs.ID()
info["content"] = infoContent
str, err := json.Marshal(info)
if err != nil {
panic(rs.T(err.Error()))
}
data.SetOutstandingCreditsDebitsWidget(string(str))
data.SetHasOutstanding(true)
return data
})
h.AccountInvoice().Methods().GetPaymentInfoJSON().DeclareMethod(
`GetPaymentInfoJSON`,
func(rs m.AccountInvoiceSet) m.AccountInvoiceData {
data := h.AccountInvoice().NewData()
data.SetPaymentsWidget("false")
if rs.PaymentMoveLines().IsEmpty() {
return data
}
info := map[string]interface{}{
`title`: rs.T(`Less Payment`),
`outstanding`: false,
`content`: []map[string]interface{}{}}
for _, payment := range rs.PaymentMoveLines().Records() {
paymentCurrency := h.Currency().NewSet(rs.Env())
var (
amount float64
amountCurrency float64
)
if strutils.IsIn(rs.Type(), "out_invoice", "in_refund") {
targetCurrency := payment.MatchedDebits().Currency()
for _, p := range payment.MatchedDebits().Records() {
if p.DebitMove().Subtract(rs.Move().Lines()).IsEmpty() {
amount += p.Amount()
amountCurrency += p.AmountCurrency()
}
if !p.Currency().Equals(targetCurrency) {
targetCurrency = h.Currency().NewSet(rs.Env())
}
}
paymentCurrency = targetCurrency
} else if strutils.IsIn(rs.Type(), "in_invoice", "out_refund") {
targetCurrency := payment.MatchedCredits().Currency()
for _, p := range payment.MatchedCredits().Records() {
if p.CreditMove().Subtract(rs.Move().Lines()).IsEmpty() {
amount += p.Amount()
amountCurrency += p.AmountCurrency()
}
if !p.Currency().Equals(targetCurrency) {
targetCurrency = h.Currency().NewSet(rs.Env())
}
}
paymentCurrency = targetCurrency
}
// get the payment value in invoice currency
var amtToShow float64
if paymentCurrency.IsNotEmpty() && paymentCurrency.Equals(rs.Currency()) {
amtToShow = amountCurrency
} else {
amtToShow = payment.Company().Currency().WithContext("date", payment.Date()).Compute(amount, rs.Currency(), true)
}
if rs.Currency().IsZero(amtToShow) {
continue
}
paymentRef := payment.Move().Name()
if payment.Move().Ref() != "" {
paymentRef += fmt.Sprintf(" (%s)", payment.Move().Ref())
}
info[`content`] = append(info[`content`].([]map[string]interface{}), map[string]interface{}{
`name`: payment.Name(),
`journal_name`: payment.Journal().Name(),
`amount`: amtToShow,
`currency`: rs.Currency().Symbol(),
`digits`: []int{69, rs.Currency().DecimalPlaces()},
`position`: rs.Currency().Position(),
`date`: payment.Date(),
`payment_id`: payment.ID(),
`move_id`: payment.Move().ID(),
`ref`: paymentRef,
})
}
str, err := json.Marshal(info)
if err != nil {
panic(rs.T(err.Error()))
}
data.SetPaymentsWidget(string(str))
return data
})
h.AccountInvoice().Methods().ComputePayments().DeclareMethod(
`ComputePayments`,
func(rs m.AccountInvoiceSet) m.AccountInvoiceData {
paymentLines := h.AccountMoveLine().NewSet(rs.Env())
for _, line := range rs.Move().Lines().Records() {
if !line.Account().Equals(rs.Account()) {
continue
}
for _, rp := range line.MatchedCredits().Records() {
if rp.CreditMove().IsNotEmpty() {
paymentLines = paymentLines.Union(rp.CreditMove())
}
}
for _, rp := range line.MatchedDebits().Records() {
if rp.DebitMove().IsNotEmpty() {
paymentLines = paymentLines.Union(rp.DebitMove())
}
}
}
data := h.AccountInvoice().NewData().
SetPaymentMoveLines(paymentLines)
return data
})
h.AccountInvoice().Methods().Create().Extend("",
func(rs m.AccountInvoiceSet, data m.AccountInvoiceData) m.AccountInvoiceSet {
data = rs.UpdateDataForPartner(data.Partner(), data)
data = rs.UpdateDataForJournal(data.Journal(), data)
if data.Account().IsEmpty() {
panic(rs.T(`Configuration error!\nCould not find any account to create the invoice, are you sure you have a chart of account installed?`))
}
invoice := rs.WithContext("mail_create_nolog", true).Super().Create(data)
if invoice.TaxLines().IsEmpty() {
hasLines := false
for _, line := range invoice.InvoiceLines().Records() {
if line.InvoiceLineTaxes().IsNotEmpty() {
hasLines = true
break
}
}
if hasLines {
invoice.ComputeTaxes()
}
}
return invoice
})
h.AccountInvoice().Methods().Write().Extend("",
func(rs m.AccountInvoiceSet, vals m.AccountInvoiceData) bool {
res := rs.Super().Write(vals)
reconciled := rs.Filtered(func(r m.AccountInvoiceSet) bool { return r.Reconciled() })
notReconciled := rs.Subtract(reconciled)
reconciled.Filtered(func(r m.AccountInvoiceSet) bool { return r.State() == "open" }).ActionInvoicePaid()
notReconciled.Filtered(func(r m.AccountInvoiceSet) bool { return r.State() == "paid" }).ActionInvoiceReOpen()
return res
})
h.AccountInvoice().Methods().FieldsViewGet().Extend("",
func(rs m.AccountInvoiceSet, params webdata.FieldsViewGetParams) *webdata.FieldsViewData {
if !(rs.Env().Context().GetString("active_model") == "res.partner" && rs.Env().Context().Get("acive_ids") != nil) {
return rs.Super().FieldsViewGet(params)
}
partner := h.Partner().BrowseOne(rs.Env(), rs.Env().Context().GetIntegerSlice("active_ids")[0])
switch params.ViewType {
case "":
params.ViewID = "account_invoice_tree"
params.ViewType = "tree"
case "form":
if partner.Supplier() && !partner.Customer() {
params.ViewID = "account_invoice_supplier_form"
} else if !partner.Supplier() && partner.Customer() {
params.ViewID = "account_invoice_form"
}
}
return rs.Super().FieldsViewGet(params)
})
h.AccountInvoice().Methods().InvoicePrint().DeclareMethod(
`Print the invoice and mark it as sent, so that we can see more
easily the next step of the workflow`,
func(rs m.AccountInvoiceSet) *actions.Action {
rs.EnsureOne()
rs.SetSent(true)
// return self.env['report'].get_action(self, 'account.report_invoice') //tovalid
return &actions.Action{
Type: actions.ActionCloseWindow,
}
})
h.AccountInvoice().Methods().ActionInvoiceSent().DeclareMethod(
`Open a window to compose an email, with the edi invoice template
message loaded by default`,
func(rs m.AccountInvoiceSet) *actions.Action {
rs.EnsureOne()
template := views.MakeViewRef("account.email_template_edi_invoice")
composeForm := views.MakeViewRef("mail.email_compose_message_wizard_form")
ctx := types.NewContext().
WithKey("default_model", "account.invoice").
WithKey("default_res_id", rs.ID()).
WithKey("default_use_template", !template.IsNull()).
WithKey("default_composition_mode", "comment").
WithKey("mark_invoice_as_sent", true).
WithKey("custom_layout", "account.mail_template_data_notification_email_account_invoice")
if !template.IsNull() {
ctx = ctx.WithKey("default_template_id", template.ID())
}
return &actions.Action{
Name: rs.T("Compose Email"),
Type: actions.ActionActWindow,
ViewMode: "form",
Model: "mail.compose.message",
Views: []views.ViewTuple{{composeForm.ID(), "form"}},
View: composeForm,
Target: "new",
Context: ctx,
}
})
h.AccountInvoice().Methods().ComputeTaxes().DeclareMethod(
`Function used in other module to compute the taxes on a fresh invoice created (onchanges did not applied)`,
func(rs m.AccountInvoiceSet) bool {
accountInvoiceTaxes := h.AccountInvoiceTax().NewSet(rs.Env())
for _, invoice := range rs.Records() {
// Delete non-manual tax lines
h.AccountInvoiceTax().Search(rs.Env(),
q.AccountInvoiceTax().Invoice().Equals(invoice).
And().Manual().Equals(false)).Unlink()
// Generate one tax line per tax, however many invoice lines it's applied to
taxGrouped := invoice.GetTaxesValues()
// Create new tax lines
for _, tax := range taxGrouped {
tax.UnsetBase()
accountInvoiceTaxes.Create(tax)
}
}
return true
})
h.AccountInvoice().Methods().Unlink().Extend("",
func(rs m.AccountInvoiceSet) int64 {
for _, invoice := range rs.Records() {
if strutils.IsIn(invoice.State(), "draft", "cancel") {
panic(rs.T(`You cannot delete an invoice which is not draft or cancelled. You should refund it instead.`))
} else if invoice.MoveName() != "" {
panic(rs.T(`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 rs.Super().Unlink()
})
h.AccountInvoice().Methods().OnchangeInvoiceLines().DeclareMethod(
`OnchangeInvoiceLines`,
func(rs m.AccountInvoiceSet) m.AccountInvoiceData {
taxesGrouped := rs.GetTaxesValues()
taxLines := rs.TaxLines().Filtered(func(r m.AccountInvoiceTaxSet) bool { return r.Manual() })
for _, tax := range taxesGrouped {
taxLines.Union(h.AccountInvoiceTax().Create(rs.Env(), tax))
}
data := h.AccountInvoice().NewData()
data.SetTaxLines(taxLines)
return data
})
h.AccountInvoice().Methods().OnchangePartner().DeclareMethod(
`OnchangePartner`,
func(rs m.AccountInvoiceSet) m.AccountInvoiceData {
p := rs.Partner()
if rs.Company().IsNotEmpty() {
p = rs.Partner().WithContext("force_company", rs.Company().ID())
}
data := h.AccountInvoice().NewData()
data = rs.UpdateDataForPartner(p, data)
return data
})
h.AccountInvoice().Methods().UpdateDataForPartner().DeclareMethod(
`UpdateDataForPartner updates the missing fields in the given data considering the given Partner.`,
func(rs m.AccountInvoiceSet, p m.PartnerSet, data m.AccountInvoiceData) m.AccountInvoiceData {
if p.IsNotEmpty() {
recAccount := p.PropertyAccountReceivable()
payAccount := p.PropertyAccountPayable()
if recAccount.IsEmpty() && payAccount.IsEmpty() {
panic("Cannot find a chart of accounts for this company, " +
"You should configure it. \nPlease go to Account Configuration.")
}
account := payAccount
payTerms := p.PropertySupplierPaymentTerm()
if strutils.IsIn(data.Type(), "out_invoice", "out_refund") {
account = recAccount
payTerms = p.PropertyPaymentTerm()
}
if !data.HasAccount() {
data.SetAccount(account)
}
if !data.HasPaymentTerm() {
data.SetPaymentTerm(payTerms)
}
deliveryPartner := rs.GetDeliveryPartner(p)
if !data.HasFiscalPosition() {
data.SetFiscalPosition(h.AccountFiscalPosition().NewSet(rs.Env()).GetFiscalPosition(p, deliveryPartner))
}
// If partner has no warning, check its company
if p.InvoiceWarn() == "no-message" && p.Parent().IsNotEmpty() {
p = p.Parent()
}
// Block if partner only has warning but parent company is blocked
if p.InvoiceWarn() != "no-message" {
if p.InvoiceWarn() != "block" && p.Parent().IsNotEmpty() && p.Parent().InvoiceWarn() == "block" {
p = p.Parent()
}
/*
// tovalid hot to format
warning = {
'title': _("Warning for %s") % p.name,
'message': p.invoice_warn_msg
}
*/
if p.InvoiceWarn() == "block" {
data.SetPartner(h.Partner().NewSet(rs.Env()))
}
}
}
data.SetDateDue(dates.Date{})
if strutils.IsIn(data.Type(), "in_invoice", "out_refund") {
banks := p.CommercialPartner().Banks()
if banks.IsNotEmpty() && !data.HasPartnerBank() {
data.SetPartnerBank(banks.Records()[0])
}
// domain = {'partner_bank_id': [('id', 'in', bank_ids.ids)]} // tovalid how to format? (see below)
}
/*
res = {} // tovalid what do of this?
if warning:
res['warning'] = warning
if domain:
res['domain'] = domain
return res
*/
return data
})
h.AccountInvoice().Methods().GetDeliveryPartner().DeclareMethod(
`GetDeliveryPartner`,
func(rs m.AccountInvoiceSet, p m.PartnerSet) m.PartnerSet {
return p.AddressGet([]string{"delivery"})["delivery"]
})
h.AccountInvoice().Methods().OnchangeJournal().DeclareMethod(
`OnchangeJournal`,
func(rs m.AccountInvoiceSet) m.AccountInvoiceData {
data := h.AccountInvoice().NewData()
data = rs.UpdateDataForJournal(data.Journal(), data)
return data
})
h.AccountInvoice().Methods().UpdateDataForJournal().DeclareMethod(
`UpdateDataForJournal updates the missing fields in the given data considering the given journal`,
func(rs m.AccountInvoiceSet, j m.AccountJournalSet, data m.AccountInvoiceData) m.AccountInvoiceData {
if j.IsNotEmpty() {
data.SetCurrency(h.Currency().Coalesce(j.Currency(), j.Company().Currency()))
}
return data
})
h.AccountInvoice().Methods().OnchangePaymentTermDateInvoice().DeclareMethod(
`OnchangePaymentTermDateInvoice`,
func(rs m.AccountInvoiceSet) m.AccountInvoiceData {
data := h.AccountInvoice().NewData()
dateInvoice := rs.DateInvoice()
if dateInvoice.IsZero() {
dateInvoice = dates.Now().ToDate()
}
if rs.PaymentTerm().IsEmpty() {
// When no payment term defined
data.SetDateDue(rs.DateInvoice())
if dateDue := rs.DateDue(); !dateDue.IsZero() {
data.SetDateDue(dateDue)
}
} else {
pTerm := rs.PaymentTerm()
pTermList := pTerm.WithContext("currency_id", rs.Company().Currency().ID()).Compute(1, dateInvoice)
max := pTermList[0].Date
for _, line := range pTermList {
if max.Lower(line.Date) {
max = line.Date
}
}
data.SetDateDue(max)
}
return data
})
h.AccountInvoice().Methods().ActionInvoiceDraft().DeclareMethod(
`ActionInvoiceDraft`,
func(rs m.AccountInvoiceSet) bool {
if rs.Filtered(func(r m.AccountInvoiceSet) bool { return r.State() != "cancel" }).IsNotEmpty() {
panic(rs.T(`Invoice must be cancelled in order to reset it to draft.`))
}
// go from canceled state to draft state
rs.Write(h.AccountInvoice().NewData().SetState("draft").UnsetDate())
// Delete former printed invoice
/*
try: // tovalid self.env["report"]
report_invoice = self.env['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['report']._attachment_stored(invoice, report_invoice)[invoice.id]
if attachment:
attachment.unlink()
*/
return true
})
h.AccountInvoice().Methods().ActionInvoiceProforma2().DeclareMethod(
`ActionInvoiceProforma2`,
func(rs m.AccountInvoiceSet) bool {
if rs.Filtered(func(r m.AccountInvoiceSet) bool { return r.State() != "draft" }).IsNotEmpty() {
panic(rs.T(`Invoice must be a draft in order to set it to Pro-forma.`))
}
return rs.Write(h.AccountInvoice().NewData().SetState("proforma2"))
})
h.AccountInvoice().Methods().ActionInvoiceOpen().DeclareMethod(
`ActionInvoiceOpen`,
func(rs m.AccountInvoiceSet) bool {
// lots of duplicate calls to action_invoice_open, so we remove those already open
toOpenInvoices := rs.Filtered(func(r m.AccountInvoiceSet) bool { return r.State() != "open" })
if toOpenInvoices.Filtered(func(r m.AccountInvoiceSet) bool { return !strutils.IsIn(r.State(), "proforma2", "draft") }).IsNotEmpty() {
panic(rs.T(`Invoice must be in draft or Pro-forma state in order to validate it.`))
}
toOpenInvoices.ActionDateAssign()
toOpenInvoices.ActionMoveCreate()
return toOpenInvoices.InvoiceValidate()
})
h.AccountInvoice().Methods().ActionInvoicePaid().DeclareMethod(
`ActionInvoicePaid`,
func(rs m.AccountInvoiceSet) bool {
// lots of duplicate calls to action_invoice_paid, so we remove those already paid
toPayInvoices := rs.Filtered(func(r m.AccountInvoiceSet) bool { return r.State() != "paid" })
if toPayInvoices.Filtered(func(r m.AccountInvoiceSet) bool { return r.State() != "open" }).IsNotEmpty() {
panic(rs.T(`Invoice must be validated in order to set it to register payment.`))
}
if toPayInvoices.Filtered(func(r m.AccountInvoiceSet) bool { return !r.Reconciled() }).IsNotEmpty() {
panic(rs.T(`You cannot pay an invoice which is partially paid. You need to reconcile payment entries first.`))
}
if toPayInvoices.IsNotEmpty() {
toPayInvoices.SetState("paid")
}
return true
})
h.AccountInvoice().Methods().ActionInvoiceReOpen().DeclareMethod(
`ActionInvoiceReOpen`,
func(rs m.AccountInvoiceSet) bool {
if rs.Filtered(func(r m.AccountInvoiceSet) bool { return r.State() != "paid" }).IsNotEmpty() {
panic(rs.T(`Invoice must be paid in order to set it to register payment.`))
}
if rs.IsNotEmpty() {
rs.SetState("open")
}
return true
})
h.AccountInvoice().Methods().ActionInvoiceCancel().DeclareMethod(
`ActionInvoiceCancel`,
func(rs m.AccountInvoiceSet) bool {
if rs.Filtered(func(r m.AccountInvoiceSet) bool { return !strutils.IsIn(r.State(), "proforma2", "draft", "open") }).IsNotEmpty() {
panic(rs.T(`Invoice must be in draft, Pro-forma or open state in order to be cancelled.`))
}
return rs.ActionCancel()
})
h.AccountInvoice().Methods().GetFormviewId().Extend(
"Update form view id of action to open the invoice",
func(rs m.AccountInvoiceSet) string {
if strutils.IsIn(rs.Type(), "in_invoice", "in_refund") {
return views.MakeViewRef("account.invoice_supplier_form").ID()
}
return views.MakeViewRef(`account.invoice_form`).ID()
})
h.AccountInvoice().Methods().PrepareTaxLineVals().DeclareMethod(
`PrepareTaxLineVals 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().
`,
func(rs m.AccountInvoiceSet, line m.AccountInvoiceLineSet, tax accounttypes.AppliedTaxData) m.AccountInvoiceTaxData {
vals := h.AccountInvoiceTax().NewData().
SetInvoice(rs).
SetName(tax.Name).
SetTax(h.AccountTax().BrowseOne(rs.Env(), tax.ID)).
SetAmount(tax.Amount).
SetBase(tax.Base).
SetManual(false).
SetSequence(int64(tax.Sequence))
if tax.Analytic {
vals.SetAccountAnalytic(line.AccountAnalytic())
}
if strutils.IsIn(rs.Type(), "out_invoice", "in_invoice") {
vals.SetAccount(h.AccountAccount().Coalesce(h.AccountAccount().BrowseOne(rs.Env(), tax.AccountID), line.Account()))
} else {
vals.SetAccount(h.AccountAccount().Coalesce(h.AccountAccount().BrowseOne(rs.Env(), tax.RefundAccountID), line.Account()))
}
// 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 vals.AccountAnalytic().IsEmpty() && line.AccountAnalytic().IsNotEmpty() && vals.Account().Equals(line.Account()) {
vals.SetAccountAnalytic(line.AccountAnalytic())
}
h.AccountInvoiceTax().NewData()
return vals
})
h.AccountInvoice().Methods().GetTaxesValues().DeclareMethod(
`GetTaxesValues`,
func(rs m.AccountInvoiceSet) map[string]m.AccountInvoiceTaxData {
taxGrouped := make(map[string]m.AccountInvoiceTaxData)
roundCurr := rs.Currency().Round
for _, line := range rs.InvoiceLines().Records() {
priceUnit := line.PriceUnit() * (1 - line.Discount()/100)
_, _, _, taxes := line.InvoiceLineTaxes().ComputeAll(priceUnit, rs.Currency(), line.Quantity(), line.Product(), rs.Partner())
for _, t := range taxes {
val := rs.PrepareTaxLineVals(line, t)
key := h.AccountTax().BrowseOne(rs.Env(), t.ID).GetGroupingKey(val)
if data, ok := taxGrouped[key]; !ok {
taxGrouped[key] = val
taxGrouped[key].SetBase(roundCurr(val.Base()))
} else {
taxGrouped[key].SetAmount(data.Amount() + val.Amount())
taxGrouped[key].SetBase(data.Base() + roundCurr(val.Base()))
}
}
}
return taxGrouped
})
h.AccountInvoice().Methods().RegisterPayment().DeclareMethod(
`RegisterPayment Reconcile payable/receivable lines from the invoice with payment_line`,
func(rs m.AccountInvoiceSet, paymentLine m.AccountMoveLineSet, writeOffAccount m.AccountAccountSet,
writeOffJournal m.AccountJournalSet) m.AccountMoveLineSet {
lineToReconcile := h.AccountMoveLine().NewSet(rs.Env())
for _, inv := range rs.Records() {