-
Notifications
You must be signed in to change notification settings - Fork 4
/
account_move.go
2456 lines (2297 loc) · 97.3 KB
/
account_move.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 (
"fmt"
"math"
"strconv"
"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/i18n"
"github.com/hexya-erp/hexya/src/models"
"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/pool/h"
"github.com/hexya-erp/pool/m"
"github.com/hexya-erp/pool/q"
"github.com/jmoiron/sqlx"
)
func init() {
h.AccountMove().DeclareModel()
h.AccountMove().SetDefaultOrder("Date DESC", "ID DESC")
h.AccountMove().AddFields(map[string]models.FieldDefinition{
"Name": models.CharField{
String: "Number",
Required: true,
NoCopy: true,
Default: models.DefaultValue("/")},
"Ref": models.CharField{
String: "Reference",
NoCopy: true},
"Date": models.DateField{
String: "Date",
Required: true, /*[ states {'posted': [('readonly']*/ /*[ True)]}]*/
Index: true,
Default: models.DefaultValue(dates.Today())},
"Journal": models.Many2OneField{RelationModel: h.AccountJournal(),
Required: true, /*[ states {'posted': [('readonly']*/ /*[ True)]}]*/
Default: func(env models.Environment) interface{} {
if env.Context().HasKey("default_journal_type") {
return h.AccountJournal().Search(env,
q.AccountJournal().Type().Equals(env.Context().GetString("default_journal_type"))).Limit(1)
}
return h.AccountJournal().NewSet(env)
}},
"Currency": models.Many2OneField{
RelationModel: h.Currency(),
Compute: h.AccountMove().Methods().ComputeCurrency(),
Stored: true,
Depends: []string{"Company"}},
"State": models.SelectionField{
String: "Status",
Selection: types.Selection{
"draft": "Unposted",
"posted": "Posted"},
Required: true,
ReadOnly: true,
NoCopy: true,
Default: models.DefaultValue("draft"),
Help: `All manually created new journal entries are usually in the status 'Unposted' but you can set the option
to skip that status on the related journal. In that case they will behave as journal entries
automatically created by the system on document validation (invoices, bank statements...) and
will be created in 'Posted' status.'`},
"Lines": models.One2ManyField{
String: "Journal Items",
RelationModel: h.AccountMoveLine(),
ReverseFK: "Move",
JSON: "line_ids", /*[ states {'posted': [('readonly']*/ /*[ True)]}]*/
Copy: true},
"Partner": models.Many2OneField{
RelationModel: h.Partner(),
Compute: h.AccountMove().Methods().ComputePartner(),
Depends: []string{"Lines", "Lines.Partner"},
Stored: true},
"Amount": models.FloatField{
Compute: h.AccountMove().Methods().AmountCompute(),
Depends: []string{"Lines", "Lines.Debit", "Lines.Credit"},
Stored: true},
"Narration": models.TextField{
String: "Internal Note"},
"Company": models.Many2OneField{
RelationModel: h.Company(),
Related: "Journal.Company",
ReadOnly: true,
Default: func(env models.Environment) interface{} {
return h.User().NewSet(env).CurrentUser().Company()
}},
"MatchedPercentage": models.FloatField{
String: "Percentage Matched",
Compute: h.AccountMove().Methods().ComputeMatchedPercentage(),
Depends: []string{"Lines", "Lines.Debit", "Lines.Credit", "Lines.MatchedDebits",
"Lines.MatchedDebits.Amount", "Lines.MatchedCredits", "Lines.MatchedCredits.Amount",
"Lines.Account", "Lines.Account.UserType", "Lines.Account.UserType.Type"},
Stored: true,
Help: "Technical field used in cash basis method"},
"StatementLine": models.Many2OneField{
String: "Bank statement line reconciled with this entry",
RelationModel: h.AccountBankStatementLine(),
Index: true,
NoCopy: true,
ReadOnly: true},
"DummyAccount": models.Many2OneField{
String: "Account",
RelationModel: h.AccountAccount(),
Related: "Lines.Account"},
})
h.AccountMove().Methods().NameGet().Extend("",
func(rs m.AccountMoveSet) string {
if rs.State() == "draft" {
return fmt.Sprintf("* %d", rs.ID())
}
return rs.Name()
})
h.AccountMove().Methods().AmountCompute().DeclareMethod(
`AmountCompute`,
func(rs m.AccountMoveSet) m.AccountMoveData {
data := h.AccountMove().NewData()
total := 0.0
for _, line := range rs.Lines().Records() {
total += line.Debit()
}
data.SetAmount(total)
return data
})
h.AccountMove().Methods().ComputeMatchedPercentage().DeclareMethod(
`Compute the percentage to apply for cash basis method. This value is relevant only for moves that
involve journal items on receivable or payable accounts.`,
func(rs m.AccountMoveSet) m.AccountMoveData {
data := h.AccountMove().NewData()
var totalAmount float64
var totalReconciled float64
for _, line := range rs.Lines().Records() {
if !strutils.IsIn(line.Account().UserType().Type(), "receivable", "payable") {
continue
}
totalAmount += math.Abs(line.Debit() - line.Credit())
for _, partialLine := range line.MatchedDebits().Union(line.MatchedCredits()).Records() {
totalReconciled += partialLine.Amount()
}
}
precisionCurrency := h.Currency().Coalesce(rs.Currency(), rs.Company().Currency())
if precisionCurrency.IsZero(totalAmount) {
data.SetMatchedPercentage(1.0)
} else {
data.SetMatchedPercentage(totalReconciled / totalAmount)
}
return data
})
h.AccountMove().Methods().ComputeCurrency().DeclareMethod(
`ComputeCurrency`,
func(rs m.AccountMoveSet) m.AccountMoveData {
return h.AccountMove().NewData().SetCurrency(
h.Currency().Coalesce(
rs.Company().Currency(),
h.User().NewSet(rs.Env()).CurrentUser().Company().Currency()))
})
h.AccountMove().Methods().ComputePartner().DeclareMethod(
`ComputePartner`,
func(rs m.AccountMoveSet) m.AccountMoveData {
data := h.AccountMove().NewData()
partner := h.Partner().NewSet(rs.Env())
for _, line := range rs.Lines().Records() {
partner = partner.Union(line.Partner())
}
if partner.Len() == 1 {
data.SetPartner(partner)
}
return data
})
h.AccountMove().Methods().FieldsViewGet().Extend("",
func(rs m.AccountMoveSet, args webdata.FieldsViewGetParams) *webdata.FieldsViewData {
res := rs.Super().FieldsViewGet(args)
if rs.Env().Context().GetBool("vat_domain") {
res.Fields["line_ids"].Views["tree"].(*webdata.FieldsViewData).Fields["tax_line_id"].Domain = "[('tag_ids', 'in', [self.env.ref(self._context.get('vat_domain')).id])]"
//tovalid is this correct? from res['fields']['line_ids']['views']['tree']['fields']['tax_line_id']['domain'] = [('tag_ids', 'in', [self.env.ref(self._context.get('vat_domain')).id])]
}
return res
})
h.AccountMove().Methods().Create().Extend("",
func(rs m.AccountMoveSet, data m.AccountMoveData) m.AccountMoveSet {
move := rs.WithContext("check_move_validity", false).
WithContext("partner_id", data.Partner().ID()).
Super().Create(data)
move.AssertBalanced()
return move
})
h.AccountMove().Methods().Write().Extend("",
func(rs m.AccountMoveSet, data m.AccountMoveData) bool {
if data.Lines().IsEmpty() {
return rs.Super().Write(data)
}
res := rs.Super().WithContext("check_move_validity", false).Write(data)
rs.AssertBalanced()
return res
})
h.AccountMove().Methods().Post().DeclareMethod(
`Post`,
func(rs m.AccountMoveSet) bool {
invoice := h.AccountInvoice().BrowseOne(rs.Env(), rs.Env().Context().GetInteger("invoice_id"))
rs.PostValidate()
for _, move := range rs.Records() {
move.Lines().CreateAnalyticLines()
if move.Name() != "/" {
continue
}
var newName string
journal := move.Journal()
if val := invoice.MoveName(); val != "" && val != "/" {
newName = invoice.MoveName()
} else {
if sequence := journal.EntrySequence(); sequence.IsNotEmpty() {
// If invoice is actually refund and journal has a refund_sequence then use that one or use the regular one
if strutils.IsIn(invoice.Type(), "out_refund", "in_refund") && journal.RefundSequence() {
sequence = journal.RefundEntrySequence()
if sequence.IsEmpty() {
panic(rs.T(`Please define a sequence for the refunds`))
}
}
newName = sequence.WithContext("ir_sequence_date", move.Date()).NextByID()
} else {
panic(rs.T(`Please define a sequence on the journal.`))
}
}
if newName != "" {
move.SetName(newName)
}
}
return rs.Write(h.AccountMove().NewData().SetState("posted"))
})
h.AccountMove().Methods().ButtonCancel().DeclareMethod(
`ButtonCancel`,
func(rs m.AccountMoveSet) bool {
for _, move := range rs.Records() {
if !move.Journal().UpdatePosted() {
panic(rs.T(`You cannot modify a posted entry of this journal.\nFirst you should set the journal to allow cancelling entries.`))
}
}
if len(rs.Ids()) > 0 {
rs.CheckLockDate()
h.AccountMove().Search(rs.Env(), q.AccountMove().ID().In(rs.Ids())).Write(h.AccountMove().NewData().SetState("draft"))
rs.Collection().InvalidateCache()
}
rs.CheckLockDate()
return true
})
h.AccountMove().Methods().Unlink().Extend("",
func(rs m.AccountMoveSet) int64 {
for _, move := range rs.Records() {
// check the lock date + check if some entries are reconciled
move.Lines().UpdateCheck()
move.Lines().Unlink()
}
return rs.Super().Unlink()
})
h.AccountMove().Methods().PostValidate().DeclareMethod(
`PostValidate`,
func(rs m.AccountMoveSet) bool {
for _, move := range rs.Records() {
for _, x := range move.Lines().Records() {
if !x.Company().Equals(move.Company()) {
panic(rs.T(`Cannot create moves for different companies.`))
}
}
}
rs.AssertBalanced()
return rs.CheckLockDate()
})
h.AccountMove().Methods().CheckLockDate().DeclareMethod(
`CheckLockDate`,
func(rs m.AccountMoveSet) bool {
for _, move := range rs.Records() {
lockDate := move.Company().FiscalyearLockDate()
if val := move.Company().PeriodLockDate(); val.Greater(lockDate) {
lockDate = val
}
hasgroup := h.User().NewSet(rs.Env()).CurrentUser().HasGroup("account.group_account_manager")
if hasgroup {
lockDate = move.Company().FiscalyearLockDate()
}
if move.Date().LowerEqual(lockDate) {
if hasgroup {
panic(rs.T(`You cannot add/modify entries prior to and inclusive of the lock date %s`, lockDate))
} else {
panic(rs.T(`You cannot add/modify entries prior to and inclusive of the lock date %s. Check the company settings or ask someone with the 'Adviser' role`, lockDate))
}
}
}
return true
})
h.AccountMove().Methods().AssertBalanced().DeclareMethod(
`AssertBalanced`,
func(rs m.AccountMoveSet) bool {
if rs.IsEmpty() {
return true
}
prec := decimalPrecision.GetPrecision("Account").Precision
if prec < 5 {
prec = 5
}
var moves []int64
rs.Env().Cr().Select(&moves, `
SELECT move_id
FROM account_move_line
WHERE move_id in (?)
GROUP BY move_id
HAVING abs(sum(debit) - sum(credit)) > ?
`, rs.Ids(), math.Pow10(-int(prec)))
if len(moves) != 0 {
panic(rs.T(`Cannot create unbalanced journal entry.`))
}
return true
})
h.AccountMove().Methods().ReconcileReversedPair().DeclareMethod(
`ReconcileReversedPair reconciles the reversed move with its reverse`,
func(rs m.AccountMoveSet, move m.AccountMoveSet, reversedMove m.AccountMoveSet) {
amlToReconcile := move.Lines().Union(reversedMove.Lines()).Filtered(func(r m.AccountMoveLineSet) bool {
return !r.Reconciled()
})
for _, aml := range amlToReconcile.Records() {
if !aml.Account().Reconcile() && aml.Account().InternalType() != "liquidity" {
continue
}
amlsForAccount := amlToReconcile.Filtered(func(r m.AccountMoveLineSet) bool {
return r.Account().Equals(aml.Account())
})
amlsForAccount.Reconcile(h.AccountAccount().NewSet(rs.Env()), h.AccountJournal().NewSet(rs.Env()))
amlToReconcile = amlToReconcile.Subtract(amlsForAccount)
}
})
h.AccountMove().Methods().ReverseMove().DeclareMethod(
`ReverseMove`,
func(rs m.AccountMoveSet, date dates.Date, journal m.AccountJournalSet) m.AccountMoveSet {
rs.EnsureOne()
reversedMove := rs.Copy(h.AccountMove().NewData().
SetDate(date).
SetJournal(h.AccountJournal().Coalesce(journal, rs.Journal())).
SetRef(rs.T(`reversal of: %s`, rs.Name())))
for _, acmLine := range reversedMove.Lines().WithContext("check_move_validity", false).Records() {
acmLine.Write(h.AccountMoveLine().NewData().
SetDebit(acmLine.Credit()).
SetCredit(acmLine.Debit()).
SetAmountCurrency(-acmLine.AmountCurrency()))
}
rs.ReconcileReversedPair(rs, reversedMove)
return reversedMove
})
h.AccountMove().Methods().ReverseMoves().DeclareMethod(
`ReverseMoves`,
func(rs m.AccountMoveSet, date dates.Date, journal m.AccountJournalSet) m.AccountMoveSet {
if date.IsZero() {
date = dates.Today()
}
reversedMoves := h.AccountMove().NewSet(rs.Env())
for _, acMove := range rs.Records() {
// unreconcile all lines reversed
aml := acMove.Lines().Filtered(func(r m.AccountMoveLineSet) bool {
return r.Account().Reconcile() || r.Account().InternalType() == "liquidity"
})
aml.RemoveMoveReconcile()
reversedMove := acMove.ReverseMove(date, journal)
reversedMoves = reversedMoves.Union(reversedMove)
}
if reversedMoves.IsNotEmpty() {
reversedMoves.PostValidate()
reversedMoves.Post()
return reversedMoves
}
return h.AccountMove().NewSet(rs.Env())
})
h.AccountMove().Methods().OpenReconcileView().DeclareMethod(
`OpenReconcileView`,
func(rs m.AccountMoveSet) *actions.Action {
return rs.Lines().OpenReconcileView()
})
h.AccountMoveLine().DeclareModel()
h.AccountMoveLine().SetDefaultOrder("Date DESC", "ID DESC")
h.AccountMoveLine().AddFields(map[string]models.FieldDefinition{
"Name": models.CharField{
String: "Label",
Required: true},
"Quantity": models.FloatField{
Digits: decimalPrecision.GetPrecision("Product Unit of Measure"),
Help: `The optional quantity expressed by this line, eg: number of product sold.
The quantity is not a legal requirement but is very useful for some reports.`},
"ProductUom": models.Many2OneField{
String: "Unit of Measure",
RelationModel: h.ProductUom()},
"Product": models.Many2OneField{
String: "Product",
RelationModel: h.ProductProduct()},
"Debit": models.FloatField{
Default: models.DefaultValue(0.0)},
"Credit": models.FloatField{
Default: models.DefaultValue(0.0)},
"Balance": models.FloatField{
Compute: h.AccountMoveLine().Methods().ComputeBalance(),
Stored: true,
Depends: []string{"Debit", "Credit"},
Help: "Technical field holding the debit - credit in order to open meaningful graph views from reports"},
"DebitCashBasis": models.FloatField{
Compute: h.AccountMoveLine().Methods().ComputeCashBasis(),
Depends: []string{"Debit", "Credit", "Move.MatchedPercentage", "Move.Journal"},
Stored: true},
"CreditCashBasis": models.FloatField{
Compute: h.AccountMoveLine().Methods().ComputeCashBasis(),
Depends: []string{"Debit", "Credit", "Move.MatchedPercentage", "Move.Journal"},
Stored: true},
"BalanceCashBasis": models.FloatField{
Compute: h.AccountMoveLine().Methods().ComputeCashBasis(),
Depends: []string{"Debit", "Credit", "Move.MatchedPercentage", "Move.Journal"},
Stored: true,
Help: `Technical field holding the debit_cash_basis - credit_cash_basis in order to open meaningful graph
views from reports`},
"AmountCurrency": models.FloatField{
Default: models.DefaultValue(0.0),
Constraint: h.AccountMoveLine().Methods().CheckCurrencyAccountAmount(),
Help: "The amount expressed in an optional other currency if it is a multi-currency entry."},
"CompanyCurrency": models.Many2OneField{
RelationModel: h.Currency(),
Related: "Company.Currency",
ReadOnly: true,
Help: "Utility field to express amount currency"},
"Currency": models.Many2OneField{
RelationModel: h.Currency(),
Default: func(env models.Environment) interface{} {
if env.Context().HasKey("default_journal_id") {
return h.AccountJournal().Browse(env, []int64{env.Context().GetInteger("default_journal_id")}).Currency()
}
return h.Currency().NewSet(env)
},
Constraint: h.AccountMoveLine().Methods().CheckCurrencyAccountAmount(),
Help: "The optional other currency if it is a multi-currency entry."},
"AmountResidual": models.FloatField{
String: "Residual Amount",
Compute: h.AccountMoveLine().Methods().ComputeAmountResidual(),
Stored: true,
Depends: []string{"Debit", "Credit", "AmountCurrency", "Currency", "MatchedDebits", "MatchedCredits",
"MatchedDebits.Amount", "MatchedCredits.Amount", "Move.State"},
Help: "The residual amount on a journal item expressed in the company currency."},
"AmountResidualCurrency": models.FloatField{
String: "Residual Amount in Currency",
Compute: h.AccountMoveLine().Methods().ComputeAmountResidual(),
Stored: true,
Depends: []string{"Debit", "Credit", "AmountCurrency", "Currency", "MatchedDebits", "MatchedCredits",
"MatchedDebits.Amount", "MatchedCredits.Amount", "Move.State"},
Help: "The residual amount on a journal item expressed in its currency (possibly not the company currency)."},
"Account": models.Many2OneField{
RelationModel: h.AccountAccount(),
Required: true,
Index: true,
OnDelete: models.Cascade,
Filter: q.AccountAccount().Deprecated().Equals(false),
Default: func(env models.Environment) interface{} {
if env.Context().HasKey("account_id") {
return h.AccountAccount().Browse(env, []int64{env.Context().GetInteger("account_id")})
}
return h.AccountAccount().NewSet(env)
},
Constraint: h.AccountMoveLine().Methods().CheckCurrencyAccountAmount()},
"Move": models.Many2OneField{
String: "Journal Entry",
RelationModel: h.AccountMove(),
OnDelete: models.Cascade,
Help: "The move of this entry line.",
Index: true,
Required: true},
"Narration": models.TextField{
Related: "Move.Narration"},
"Ref": models.CharField{
String: "Reference",
NoCopy: true,
Index: true},
"Payment": models.Many2OneField{
String: "Originator Payment",
RelationModel: h.AccountPayment(),
Help: "Payment that created this entry"},
"Statement": models.Many2OneField{
RelationModel: h.AccountBankStatement(),
Help: "The bank statement used for bank reconciliation",
Index: true,
NoCopy: true},
"Reconciled": models.BooleanField{
Compute: h.AccountMoveLine().Methods().ComputeAmountResidual(),
Depends: []string{"Debit", "Credit", "AmountCurrency", "Currency", "MatchedDebits", "MatchedCredits",
"MatchedDebits.Amount", "MatchedCredits.Amount", "Move.State"},
Stored: true},
"FullReconcile": models.Many2OneField{
String: "Matching Number",
RelationModel: h.AccountFullReconcile(),
NoCopy: true},
"MatchedDebits": models.One2ManyField{
RelationModel: h.AccountPartialReconcile(),
ReverseFK: "CreditMove",
JSON: "matched_debit_ids",
Help: "Debit journal items that are matched with this journal item."},
"MatchedCredits": models.One2ManyField{
RelationModel: h.AccountPartialReconcile(),
ReverseFK: "DebitMove",
JSON: "matched_credit_ids",
Help: "Credit journal items that are matched with this journal item."},
"Journal": models.Many2OneField{
RelationModel: h.AccountJournal(),
Related: "Move.Journal",
Index: true,
NoCopy: true},
"Blocked": models.BooleanField{
String: "No Follow-up",
Default: models.DefaultValue(false),
Help: "You can check this box to mark this journal item as a litigation with the associated partner"},
"DateMaturity": models.DateField{
String: "Due date",
Index: true,
Required: true,
Help: `This field is used for payable and receivable journal entries.
You can put the limit date for the payment of this line.`},
"Date": models.DateField{
Related: "Move.Date",
Index: true,
NoCopy: true},
"AnalyticLines": models.One2ManyField{
RelationModel: h.AccountAnalyticLine(),
ReverseFK: "Move",
JSON: "analytic_line_ids"},
"Taxes": models.Many2ManyField{
RelationModel: h.AccountTax(),
JSON: "tax_ids"},
"TaxLine": models.Many2OneField{
String: "Originator tax",
RelationModel: h.AccountTax(),
OnDelete: models.Restrict},
"AnalyticAccount": models.Many2OneField{
String: "Analytic Account",
RelationModel: h.AccountAnalyticAccount()},
"AnalyticTags": models.Many2ManyField{
String: "Analytic tags",
RelationModel: h.AccountAnalyticTag(),
JSON: "analytic_tag_ids"},
"Company": models.Many2OneField{
RelationModel: h.Company(),
Related: "Account.Company"},
"Counterpart": models.CharField{
Compute: h.AccountMoveLine().Methods().ComputeCounterpart(),
Help: `Compute the counter part accounts of this journal item for this journal entry.
This can be needed in reports.`},
"Invoice": models.Many2OneField{
RelationModel: h.AccountInvoice()},
"Partner": models.Many2OneField{
RelationModel: h.Partner(),
OnDelete: models.Restrict},
"UserType": models.Many2OneField{
RelationModel: h.AccountAccountType(),
Related: "Account.UserType",
Index: true},
"TaxExigible": models.BooleanField{
String: "Appears in VAT report",
Default: models.DefaultValue(true),
Help: `Technical field used to mark a tax line as exigible in the vat report or not
(only exigible journal items are displayed). By default all new journal items are directly exigible,
but with the module account_tax_cash_basis, some will become exigible only when the payment is recorded`},
})
h.AccountMoveLine().AddSQLConstraint("credit_debit1", "CHECK (credit*debit=0)",
"Wrong credit or debit value in accounting entry (credit*debit!=0)!")
h.AccountMoveLine().AddSQLConstraint("credit_debit2", "CHECK (credit+debit>=0)",
"Wrong credit or debit value in accounting entry (credit+debit<0)!")
h.AccountMoveLine().Methods().Init().DeclareMethod(
`Init change index on partner_id to a multi-column index on (partner_id, ref), the new index will behave in the
same way when we search on partner_id, with the addition of being optimal when having a query that will
search on partner_id and ref at the same time (which is the case when we open the bank reconciliation widget)`,
func(rs m.AccountMoveLineSet) {
cr := rs.Env().Cr()
cr.Execute(`DROP INDEX IF EXISTS account_move_line_partner_id_index`)
var out []interface{}
cr.Select(&out, `SELECT indexname FROM pg_indexes WHERE indexname = 'account_move_line_partner_id_ref_idx'`)
if len(out) == 0 {
cr.Execute(`CREATE INDEX account_move_line_partner_id_ref_idx ON account_move_line (partner_id, ref)`)
}
})
h.AccountMoveLine().Methods().ComputeAmountResidual().DeclareMethod(
`ComputeAmountResidual Computes the residual amount of a move line from a reconciliable account in the company currency and the line's currency.
This amount will be 0 for fully reconciled lines or lines from a non-reconciliable account, the original line amount
for unreconciled lines, and something in-between for partially reconciled lines.`,
func(rs m.AccountMoveLineSet) m.AccountMoveLineData {
data := h.AccountMoveLine().NewData()
if !rs.Account().Reconcile() && rs.Account().InternalType() != "liquidity" {
data.SetReconciled(false).
SetAmountResidual(0).
SetAmountResidualCurrency(0)
return data
}
// amounts in the partial reconcile table aren't signed, so we need to use abs()
amount := math.Abs(rs.Debit() - rs.Credit())
amountResidualCurrency := math.Abs(rs.AmountCurrency())
sign := -1.0
if rs.Debit()-rs.Credit() > 0 {
sign = 1
}
if rs.Debit() == 0.0 && rs.Credit() == 0.0 && rs.AmountCurrency() != 0.0 && rs.Currency().IsNotEmpty() {
// residual for exchange rate entries
sign = -1
if rs.Currency().CompareAmounts(rs.AmountCurrency(), 0) == 1 {
sign = 1
}
}
for _, partialLine := range rs.MatchedCredits().Union(rs.MatchedDebits()).Records() {
// If line is a credit (sign = -1) we:
// - subtract matched_debit_ids (partial_line.credit_move_id == line)
// - add matched_credit_ids (partial_line.credit_move_id != line)
// If line is a debit (sign = 1), do the opposite.
signPartialLine := -sign
if partialLine.CreditMove().Equals(rs) {
signPartialLine = sign
}
amount += signPartialLine * partialLine.Amount()
// getting the date of the matched item to compute the amount_residual in currency
if rs.Currency().IsNotEmpty() {
if partialLine.Currency().IsNotEmpty() && partialLine.Currency().Equals(rs.Currency()) {
amountResidualCurrency += signPartialLine * partialLine.AmountCurrency()
} else {
var rate float64
if rs.Balance() != 0.0 && rs.AmountCurrency() != 0.0 {
rate = rs.AmountCurrency() / rs.Balance()
} else {
date := partialLine.DebitMove().Date()
if partialLine.DebitMove().Equals(rs) {
date = partialLine.CreditMove().Date()
}
rate = rs.Currency().WithContext("date", date).Rate()
}
amountResidualCurrency += signPartialLine * partialLine.Amount() * rate
}
}
}
// computing the `reconciled` field. As we book exchange rate difference on each partial matching,
// we can only check the amount in company currency
var reconciled bool
if rs.Company().Currency().IsZero(amount) {
if rs.Currency().IsNotEmpty() && rs.AmountCurrency() != 0.0 {
if rs.Currency().IsZero(amountResidualCurrency) {
reconciled = true
}
} else {
reconciled = true
}
}
data.SetReconciled(reconciled).
SetAmountResidual(rs.Company().Currency().Round(amount * sign)).
SetAmountResidualCurrency(rs.Currency().Round(amountResidualCurrency * sign))
return data
})
h.AccountMoveLine().Methods().ComputeBalance().DeclareMethod(
`ComputeBalance`,
func(rs m.AccountMoveLineSet) m.AccountMoveLineData {
return h.AccountMoveLine().NewData().SetBalance(rs.Debit() - rs.Credit())
})
h.AccountMoveLine().Methods().ComputeCashBasis().DeclareMethod(
`ComputeCashBasis`,
func(rs m.AccountMoveLineSet) m.AccountMoveLineData {
data := h.AccountMoveLine().NewData()
if strutils.IsIn(rs.Journal().Type(), "sale", "purchase") {
data.SetDebitCashBasis(rs.Debit() * rs.Move().MatchedPercentage())
data.SetCreditCashBasis(rs.Credit() * rs.Move().MatchedPercentage())
} else {
data.SetDebitCashBasis(rs.Debit())
data.SetCreditCashBasis(rs.Credit())
}
data.SetBalanceCashBasis(data.DebitCashBasis() - data.CreditCashBasis())
return data
})
h.AccountMoveLine().Methods().ComputeCounterpart().DeclareMethod(
`ComputeCounterpart`,
func(rs m.AccountMoveLineSet) m.AccountMoveLineData {
var counterpart []string
for _, line := range rs.Move().Lines().Records() {
if line.Account().Code() != rs.Account().Code() {
counterpart = append(counterpart, line.Account().Code())
}
}
if len(counterpart) > 2 {
counterpart = append(counterpart[:2], "...")
}
return h.AccountMoveLine().NewData().SetCounterpart(strings.Join(counterpart, ","))
})
h.AccountMoveLine().Methods().CheckCurrencyAccountAmount().DeclareMethod(
`CheckCurrency`,
func(rs m.AccountMoveLineSet) {
if rs.Account().Currency().IsNotEmpty() && (rs.Currency().IsEmpty() || !rs.Currency().Equals(rs.Account().Currency())) {
panic(rs.T(`The selected account of your Journal Entry forces to provide a secondary currency. You should remove the secondary currency on the account.`))
}
if rs.AmountCurrency() != 0.0 && rs.Currency().IsEmpty() {
panic(rs.T(`You cannot create journal items with a secondary currency without filling both 'currency' and 'amount currency' field.`))
}
if (rs.AmountCurrency() > 0.0 && rs.Credit() > 0.0) || (rs.AmountCurrency() < 0.0 && rs.Debit() > 0.0) {
panic(rs.T(`The amount expressed in the secondary currency must be positive when account is debited and negative when account is credited.`))
}
})
h.AccountMoveLine().Methods().GetDataForManualReconciliationWidget().DeclareMethod(
`GetDataForManualReconciliationWidget Returns the data required for the invoices & payments matching of partners/accounts.
If an argument is None, fetch all related reconciliations. Use [] to fetch nothing.`,
func(rs m.AccountMoveLineSet, partners m.PartnerSet, accounts m.AccountAccountSet) *accounttypes.DataForReconciliationWidget {
var out accounttypes.DataForReconciliationWidget
out.Customers = rs.GetDataForManualReconciliation("partner", partners.Ids(), "receivable")
out.Suppliers = rs.GetDataForManualReconciliation("partner", partners.Ids(), "payable")
out.Accounts = rs.GetDataForManualReconciliation("account", accounts.Ids(), "")
return &out
})
h.AccountMoveLine().Methods().GetDataForManualReconciliation().DeclareMethod(
`GetDataForManualReconciliation Returns the data required for the invoices & payments matching of partners/accounts (list of dicts).
If no res_ids is passed, returns data for all partners/accounts that can be reconciled.
:param res_type: either 'partner' or 'account'
:param res_ids: ids of the partners/accounts to reconcile, use None to fetch data indiscriminately
of the id, use [] to prevent from fetching any data at all.
:param account_type: if a partner is both customer and vendor, you can use 'payable' to reconcile
the vendor-related journal entries and 'receivable' for the customer-related entries.`,
func(rs m.AccountMoveLineSet, resType string, resIds []int64, accountType string) []map[string]interface{} {
// error handling
if resIds != nil && len(resIds) == 0 {
// Note : this short-circuiting is better for performances, but also required
// since postgresql doesn't implement empty list (so 'AND id in ()' is useless)
return []map[string]interface{}{}
}
if !strutils.IsIn(resType, "partner", "account") {
panic(rs.T(`GetDataForManualReconciliation: Parameter invalid: resType should be "%s" or "%s". (current: "%s")`, "partner", "account", resType))
}
if !strutils.IsIn(accountType, "payable", "receivable") {
panic(rs.T(`GetDataForManualReconciliation: Parameter invalid: accountType should be "%s", "%s" or empty. (current: "%s")`, "payable", "receivable", resType))
}
//inits
isPartner := resType == "partner"
resAlias := "a"
if isPartner {
resAlias = "p"
}
// big query of doom - parameters
BQODParams := []interface{}{ //set defaults
" ", //0
" ", //1
resAlias, //2
" ", //3
`AND at.type <> 'payable' AND at.type <> 'receivable'`, //4
" ", //5
" ", //6
strconv.Itoa(int(h.User().NewSet(rs.Env()).CurrentUser().Currency().ID())), //7
" ", //8
" ", //9
" ", //10
resAlias, //11
resAlias, //12
}
if isPartner {
BQODParams[0] = `partner_id, partner_name,`
BQODParams[1] = `p.id AS partner_id, p.name AS partner_name,`
BQODParams[3] = `RIGHT JOIN res_partner p ON (l.partner_id = p.id)`
BQODParams[4] = ` `
BQODParams[8] = `AND l.partner_id = p.id`
BQODParams[9] = `AND l.partner_id = p.id`
BQODParams[10] = `l.partner_id, p.id,`
}
if accountType != "" {
BQODParams[5] = `AND at.type = :accountType `
}
if len(resIds) > 0 {
BQODParams[6] = `AND ` + resAlias + `.id in :resIds "`
}
query := fmt.Sprintf(`
SELECT account_id, account_name, account_code, max_date, %s
to_char(last_time_entries_checked, 'YYYY-MM-DD') AS last_time_entries_checked
FROM (
SELECT %s
%s.last_time_entries_checked AS last_time_entries_checked,
a.id AS account_id,
a.name AS account_name,
a.code AS account_code,
MAX(l.write_date) AS max_date
FROM
account_move_line l
RIGHT JOIN account_account a ON (a.id = l.account_id)
RIGHT JOIN account_account_type at ON (at.id = a.user_type_id)
%s
WHERE
a.reconcile IS TRUE
AND l.full_reconcile_id is NULL
%s
%s
%s
AND l.company_id =%s
AND EXISTS (
SELECT NULL
FROM account_move_line l
WHERE l.account_id = a.id
%s
AND l.amount_residual > 0
)
AND EXISTS (
SELECT NULL
FROM account_move_line l
WHERE l.account_id = a.id
%s
AND l.amount_residual < 0
)
GROUP BY %s a.id, a.name, a.code, %s.last_time_entries_checked
ORDER BY %s.last_time_entries_checked
) as s
WHERE (last_time_entries_checked IS NULL OR max_date > last_time_entries_checked)
`, BQODParams...)
paramMap := map[string]interface{}{
"accountType": accountType,
"resIds": resIds,
}
type RowType struct {
accountId int64
accountName string
accountCode string
maxDate dates.Date
partnerId int64
partnerName string
}
var outputRows []RowType
// Compile and exec query
query, args, err := sqlx.Named(query, paramMap)
if err != nil {
panic(rs.T(`%s: Error, could not compile query, please refer to an administrator`, "GetDataForManualReconciliation"))
}
rs.Env().Cr().Get(&outputRows, query, args)
// Apply ir_rules by filtering out
var ids []int64
for _, outputRows := range outputRows {
ids = append(ids, outputRows.accountId)
}
allowedIds := h.AccountAccount().Browse(rs.Env(), ids).Ids() //tovalid is this needed that way? getting all ids after a browse of those ids?
var rows []RowType
for _, row := range outputRows {
for _, id := range allowedIds {
if row.accountId == id {
rows = append(rows, row)
break
}
}
}
if isPartner {
ids = []int64{}
for _, outputRows := range outputRows {
ids = append(ids, outputRows.partnerId)
}
allowedIds = h.Partner().Browse(rs.Env(), ids).Ids()
rows = []RowType{}
for _, row := range outputRows {
for _, id := range allowedIds {
if row.partnerId == id {
rows = append(rows, row)
break
}
}
}
}
// Fetch other data and store to map
var out []map[string]interface{}
for _, row := range rows {
o := make(map[string]interface{})
account := h.AccountAccount().BrowseOne(rs.Env(), row.accountId)
o["currency_id"] = h.Currency().Coalesce(account.Currency(), account.Company().Currency()).ID()
o["reconciliation_proposition"] = rs.GetReconciliationProposition(account, h.Partner().BrowseOne(rs.Env(), row.partnerId))
o["account_id"] = row.accountId
o["account_name"] = row.accountName
o["account_code"] = row.accountCode
o["max_date"] = row.maxDate
o["partner_id"] = row.partnerId
o["partner_name"] = row.partnerName
out = append(out, o)
}
return out
})
h.AccountMoveLine().Methods().GetReconciliationProposition().DeclareMethod(
`Returns two lines whose amount are opposite`,
func(rs m.AccountMoveLineSet, account m.AccountAccountSet, partner m.PartnerSet) []map[string]interface{} {
// Get pairs
params := map[string]interface{}{
"accountId": account.ID(),
}
partnerIDCondition := ""
if partner.IsNotEmpty() {
partnerIDCondition = `AND a.partner_id = :partnerID AND b.partner_id = :partnerID`
params["partnerID"] = partner.ID()
}
query, args, err := sqlx.Named(`
SELECT a.id, b.id
FROM account_move_line a, account_move_line b
WHERE a.amount_residual = -b.amount_residual
AND NOT a.reconciled AND NOT b.reconciled
AND a.account_id = :accountID AND b.account_id = :accountID
`+partnerIDCondition+`
ORDER BY a.date asc
LIMIT 10
`, params)
if err != nil {
panic(rs.T(`%s: Error, could not compile query, please refer to an administrator`, "GetReconciliationProposition"))
}
type pairType struct {
a int64
b int64
}
var pairsOut []pairType
rs.Env().Cr().Select(&pairsOut, query, args...)
// Apply ir_rules by filtering out
var allIds []int64
for _, pair := range pairsOut {
allIds = append(allIds, pair.a, pair.b)
}
allowed := h.AccountMoveLine().Browse(rs.Env(), allIds).Ids() //tovalid is this needed that way? getting all ids after a browse of those ids?
var pairs []pairType
for _, pair := range pairsOut {
aIsIn := false
bIsIn := false
for _, id := range allowed {
if pair.a == id {
aIsIn = true
}
if pair.b == id {
bIsIn = true
}
if aIsIn && bIsIn {
pairs = append(pairs, pair)
break
}
}
}
// Return lines formatted
if len(pairs) > 0 {
targetCurrency := rs.Company().Currency()
if rs.Currency().IsNotEmpty() && rs.AmountCurrency() != 0.0 {
targetCurrency = rs.Currency()
}
lines := rs.Browse([]int64{pairs[0].a, pairs[0].b})
return lines.PrepareMoveLinesForReconciliationWidget(targetCurrency, dates.Date{})
}
return []map[string]interface{}{}
})
h.AccountMoveLine().Methods().DomainMoveLinesForReconciliation().DeclareMethod(
`DomainMoveLinesForReconciliation Returns the domain which is common to both manual and bank statement reconciliation.
:param excluded_ids: list of ids of move lines that should not be fetched
:param str: search string`,
func(rs m.AccountMoveLineSet, excludedIds []int64, str string) q.AccountMoveLineCondition {
epsilon := 0.0001
var domain q.AccountMoveLineCondition
if len(excludedIds) > 1 {
domain = q.AccountMoveLine().ID().NotIn(excludedIds)