-
Notifications
You must be signed in to change notification settings - Fork 3
/
sale.go
1362 lines (1282 loc) · 56.4 KB
/
sale.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 sale
import (
"fmt"
"math"
"sort"
"strconv"
"strings"
"github.com/hexya-addons/account/accounttypes"
"github.com/hexya-addons/decimalPrecision"
"github.com/hexya-erp/hexya/src/actions"
"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/hexya/src/views"
"github.com/hexya-erp/pool/h"
"github.com/hexya-erp/pool/m"
"github.com/hexya-erp/pool/q"
)
func init() {
h.SaleOrder().DeclareModel()
h.SaleOrder().SetDefaultOrder("DateOrder DESC", "ID DESC")
h.SaleOrder().AddFields(map[string]models.FieldDefinition{
"Name": models.CharField{String: "Order Reference", Required: true, NoCopy: true, Index: true,
ReadOnlyFunc: func(env models.Environment) (bool, models.Conditioner) {
return false, q.SaleOrder().State().NotEquals("draft")
},
Default: func(env models.Environment) interface{} {
return h.SaleOrder().NewSet(env).T("New")
}},
"Origin": models.CharField{String: "Source Document",
Help: "Reference of the document that generated this sales order request."},
"ClientOrderRef": models.CharField{String: "Customer Reference", NoCopy: true},
"State": models.SelectionField{String: "Status", Selection: types.Selection{
"draft": "Quotation",
"sent": "Quotation Sent",
"sale": "Sales Order",
"done": "Locked",
"cancel": "Cancelled",
}, ReadOnly: true, NoCopy: true, Index: true, /*[ track_visibility 'onchange']*/
Default: models.DefaultValue("draft")},
"DateOrder": models.DateTimeField{String: "Order Date", Required: true, Index: true, /*[ readonly True]*/
/*[ states {'draft': [('readonly']*/ /*[ False)]]*/
/*[ 'sent': [('readonly'] [ False)]}]*/
NoCopy: true, Default: func(env models.Environment) interface{} {
return dates.Now()
}},
"ValidityDate": models.DateField{String: "Expiration Date" /*[ readonly True]*/, NoCopy: true,
/*[ states {'draft': [('readonly']*/ /*[ False)]]*/
/*[ 'sent': [('readonly'] [ False)]}]*/
Help: `Manually set the expiration date of your quotation (offer), or it will set the date automatically
based on the template if online quotation is installed.`},
"ConfirmationDate": models.DateTimeField{Index: true, ReadOnly: true,
Help: "Date on which the sale order is confirmed."},
"User": models.Many2OneField{String: "Salesperson", RelationModel: h.User(), Index: true, /*[ track_visibility 'onchange']*/
Default: func(env models.Environment) interface{} {
return h.User().NewSet(env).CurrentUser()
}},
"Partner": models.Many2OneField{String: "Customer", RelationModel: h.Partner(), /* readonly=true */
/*[ states {'draft': [('readonly'] [ False)]]*/
/*[ 'sent': [('readonly'] [ False)]}]*/
OnChange: h.SaleOrder().Methods().OnchangePartner(),
Required: true, Index: true /*[ track_visibility 'always']*/},
"PartnerInvoice": models.Many2OneField{String: "Invoice Address", RelationModel: h.Partner(), /* readonly=true */
Required: true,
/*[ states {'draft': [('readonly']*/ /*[ False)]]*/
/*[ 'sent': [('readonly'] [ False)]}]*/
Help: "Invoice address for current sales order."},
"PartnerShipping": models.Many2OneField{String: "Delivery Address", RelationModel: h.Partner(), /* readonly=true */
Required: true,
/*[ states {'draft': [('readonly']*/ /*[ False)]]*/
/*[ 'sent': [('readonly'] [ False)]}]*/
OnChange: h.SaleOrder().Methods().OnchangePartnerShipping(),
Help: "Delivery address for current sales order."},
"Pricelist": models.Many2OneField{RelationModel: h.ProductPricelist(), Required: true, /* readonly=true */
/*[ states {'draft': [('readonly']*/ /*[ False)]]*/
/*[ 'sent': [('readonly'] [ False)]}]*/
Help: "Pricelist for current sales order."},
"Currency": models.Many2OneField{RelationModel: h.Currency(),
Related: "Pricelist.Currency", ReadOnly: true, Required: true},
"Project": models.Many2OneField{String: "Analytic Account", RelationModel: h.AccountAnalyticAccount(),
/* readonly=true */
/*[ states {'draft': [('readonly'] [ False)]]*/
/*[ 'sent': [('readonly'] [ False)]}]*/
Help: "The analytic account related to a sales order.", NoCopy: true},
"RelatedProject": models.Many2OneField{String: "Analytic Account", RelationModel: h.AccountAnalyticAccount(),
Related: "Project", Help: "The analytic account related to a sales order."},
"OrderLine": models.One2ManyField{String: "Order Lines", RelationModel: h.SaleOrderLine(),
ReverseFK: "Order",
/*[ states {'cancel': [('readonly'] [ True)]]*/
/*[ 'done': [('readonly'] [ True)]}]*/
Copy: true},
"InvoiceCount": models.IntegerField{String: "# of Invoices",
Compute: h.SaleOrder().Methods().GetInvoiced(),
Depends: []string{"State", "OrderLine.InvoiceStatus"}, GoType: new(int)},
"Invoices": models.Many2ManyField{String: "Invoices", RelationModel: h.AccountInvoice(),
JSON: "invoice_ids", Compute: h.SaleOrder().Methods().GetInvoiced(),
Depends: []string{"State", "OrderLine.InvoiceStatus"}, NoCopy: true},
"InvoiceStatus": models.SelectionField{Selection: types.Selection{
"upselling": "Upselling Opportunity",
"invoiced": "Fully Invoiced",
"to invoice": "To Invoice",
"no": "Nothing to Invoice",
}, Compute: h.SaleOrder().Methods().GetInvoiced(),
Depends: []string{"State", "OrderLine.InvoiceStatus"}, Stored: true},
"Note": models.TextField{String: "Terms and conditions",
Default: func(env models.Environment) interface{} {
return h.User().NewSet(env).CurrentUser().Company().SaleNote()
}},
"AmountUntaxed": models.FloatField{String: "Untaxed Amount", Stored: true,
Compute: h.SaleOrder().Methods().AmountAll(), /*[ track_visibility 'always']*/
Depends: []string{"OrderLine.PriceTotal"}},
"AmountTax": models.FloatField{String: "Taxes", Stored: true,
Compute: h.SaleOrder().Methods().AmountAll(), /*[ track_visibility 'always']*/
Depends: []string{"OrderLine.PriceTotal"}},
"AmountTotal": models.FloatField{String: "Total", Stored: true,
Compute: h.SaleOrder().Methods().AmountAll(), /*[ track_visibility 'always']*/
Depends: []string{"OrderLine.PriceTotal"}},
"PaymentTerm": models.Many2OneField{String: "Payment Terms", RelationModel: h.AccountPaymentTerm()},
"FiscalPosition": models.Many2OneField{RelationModel: h.AccountFiscalPosition(),
OnChange: h.SaleOrder().Methods().ComputeTax()},
"Company": models.Many2OneField{RelationModel: h.Company(),
Default: func(env models.Environment) interface{} {
return h.Company().NewSet(env).CompanyDefaultGet()
}},
"Team": models.Many2OneField{String: "Sales Team", RelationModel: h.CRMTeam(),
Default: func(env models.Environment) interface{} {
return h.CRMTeam().NewSet(env).GetDefaultTeam(h.User().NewSet(env))
}},
"ProcurementGroup": models.Many2OneField{RelationModel: h.ProcurementGroup(), NoCopy: true},
"Product": models.Many2OneField{RelationModel: h.ProductProduct(), Related: "OrderLine.Product"},
})
h.SaleOrder().Methods().AmountAll().DeclareMethod(
`AmountAll computes all the amounts of this sale order by summing its sale order lines.`,
func(rs m.SaleOrderSet) m.SaleOrderData {
var amountUntaxed, amountTaxed float64
for _, line := range rs.OrderLine().Records() {
amountUntaxed += line.PriceSubtotal()
if rs.Company().TaxCalculationRoundingMethod() == "round_globally" {
price := line.PriceUnit() * (1 - line.Discount()/100)
_, _, _, taxes := line.Tax().ComputeAll(price, line.Order().Currency(), line.ProductUomQty(),
line.Product(), rs.PartnerShipping())
for _, t := range taxes {
amountTaxed += t.Amount
}
} else {
amountTaxed += line.PriceTax()
}
}
return h.SaleOrder().NewData().
SetAmountUntaxed(rs.Pricelist().Currency().Round(amountUntaxed)).
SetAmountTax(rs.Pricelist().Currency().Round(amountTaxed)).
SetAmountTotal(amountTaxed + amountUntaxed)
})
h.SaleOrder().Methods().GetInvoiced().DeclareMethod(
`GetInvoiced computes the invoice status of a SO. Possible statuses:
- no: if the SO is not in status 'sale' or 'done', we consider that there is nothing to
invoice. This is also hte default value if the conditions of no other status is met.
- to invoice: if any SO line is 'to invoice', the whole SO is 'to invoice'
- invoiced: if all SO lines are invoiced, the SO is invoiced.
- upselling: if all SO lines are invoiced or upselling, the status is upselling.
The invoice_ids are obtained thanks to the invoice lines of the SO lines, and we also search
for possible refunds created directly from existing invoices. This is necessary since such a
refund is not directly linked to the SO.`,
func(rs m.SaleOrderSet) m.SaleOrderData {
invoices := h.AccountInvoice().NewSet(rs.Env())
for _, line := range rs.OrderLine().Records() {
for _, invLine := range line.InvoiceLines().Records() {
if invLine.Invoice().Type() == "out_invoice" || invLine.Invoice().Type() == "out_refund" {
invoices = invoices.Union(invLine.Invoice())
}
}
}
// Search for invoices which have been 'cancelled' (filter_refund = 'modify' in
// 'account.invoice.refund')
// use like as origin may contains multiple references (e.g. 'SO01, SO02')
origins := strings.Split(rs.Origin(), ",")
for i, o := range origins {
origins[i] = strings.TrimSpace(o)
}
invoices = invoices.Union(h.AccountInvoice().Search(rs.Env(),
q.AccountInvoice().Origin().Like(rs.Name()).
And().Name().In(origins).
And().Type().In([]string{"out_invoice", "out_refund"})))
refunds := h.AccountInvoice().NewSet(rs.Env())
for _, inv := range invoices.Records() {
refunds = refunds.Union(h.AccountInvoice().Search(rs.Env(),
q.AccountInvoice().Type().Equals("out_refund").
And().Origin().Equals(inv.Number()).
And().Origin().IsNotNull().
And().Journal().Equals(inv.Journal())))
}
// Ignore the status of the deposit product
depositProduct := h.SaleAdvancePaymentInv().NewSet(rs.Env()).DefaultProduct()
lineInvoiceStatus := make(map[string]bool)
for _, l := range rs.OrderLine().Records() {
if l.Product().Equals(depositProduct) {
continue
}
lineInvoiceStatus[l.InvoiceStatus()] = true
}
var invoiceStatus string
switch {
case !strutils.IsIn(rs.State(), "sale", "done"):
invoiceStatus = "no"
case lineInvoiceStatus["to invoice"]:
invoiceStatus = "to invoice"
case len(lineInvoiceStatus) == 1 && lineInvoiceStatus["invoiced"]:
invoiceStatus = "invoiced"
case len(lineInvoiceStatus) == 2 && lineInvoiceStatus["invoiced"] && lineInvoiceStatus["upselling"]:
invoiceStatus = "upselling"
default:
invoiceStatus = "no"
}
return h.SaleOrder().NewData().
SetInvoiceCount(invoices.Union(refunds).Len()).
SetInvoices(invoices.Union(refunds)).
SetInvoiceStatus(invoiceStatus)
})
h.SaleOrder().Methods().ComputeTax().DeclareMethod(
`ComputeTax triggers the recompute of the taxes if the fiscal position is changed on the SO.`,
func(rs m.SaleOrderSet) m.SaleOrderData {
//@api.onchange('fiscal_position_id')
/*def _compute_tax_id(self):
"""
Trigger the recompute of the taxes if the fiscal position is changed on the SO.
"""
for order in self:
order.order_line._compute_tax_id()
*/
// TODO : need to implement onchange on relation fields first
return h.SaleOrder().NewData()
})
h.SaleOrder().Methods().GetCustomerLead().DeclareMethod(
`GetCustomerLead returns the delay to deliver the given product template`,
func(rs m.SaleOrderSet, productTmpl m.ProductTemplateSet) int {
return 0
})
h.SaleOrder().Methods().ButtonDummy().DeclareMethod(
`ButtonDummy is a dummy function to force reload of the form on client side.`,
func(rs m.SaleOrderSet) bool {
return true
})
h.SaleOrder().Methods().Unlink().Extend("",
func(rs m.SaleOrderSet) int64 {
for _, order := range rs.Records() {
if !strutils.IsIn(order.State(), "draft", "cancel") {
panic(rs.T("You can not delete a sent quotation or a sales order! Try to cancel it before."))
}
}
return rs.Super().Unlink()
})
//h.SaleOrder().Methods().TrackSubtype().DeclareMethod(
// `TrackSubtype`,
// func(rs m.SaleOrderSet, initvalues interface{}) {
// //@api.multi
// /*def _track_subtype(self, init_values):
// self.ensure_one()
// if 'state' in init_values and self.state == 'sale':
// return 'sale.mt_order_confirmed'
// elif 'state' in init_values and self.state == 'sent':
// return 'sale.mt_order_sent'
// return super(SaleOrder, self)._track_subtype(init_values)
//
// */
// })
h.SaleOrder().Methods().OnchangePartnerShipping().DeclareMethod(
`OnchangePartnerShipping triggers the change of fiscal position when the shipping address is modified.`,
func(rs m.SaleOrderSet) m.SaleOrderData {
return h.SaleOrder().NewData().SetFiscalPosition(
h.AccountFiscalPosition().NewSet(rs.Env()).GetFiscalPosition(rs.Partner(), rs.PartnerShipping()))
})
h.SaleOrder().Methods().OnchangePartner().DeclareMethod(
`OnchangePartner updates the following fields when the partner is changed:
- Pricelist
- Payment term
- Invoice address
- Delivery address
`,
func(rs m.SaleOrderSet) m.SaleOrderData {
if rs.Partner().IsEmpty() {
return h.SaleOrder().NewData().
SetPartnerInvoice(h.Partner().NewSet(rs.Env())).
SetPartnerShipping(h.Partner().NewSet(rs.Env())).
SetPaymentTerm(h.AccountPaymentTerm().NewSet(rs.Env())).
SetFiscalPosition(h.AccountFiscalPosition().NewSet(rs.Env()))
}
addr := rs.Partner().AddressGet([]string{"delivery", "invoice"})
values := h.SaleOrder().NewData().
SetPricelist(rs.Partner().PropertyProductPricelist()).
SetPaymentTerm(rs.Partner().PropertyPaymentTerm()).
SetPartnerInvoice(addr["invoice"]).
SetPartnerShipping(addr["delivery"])
if h.User().NewSet(rs.Env()).CurrentUser().Company().SaleNote() != "" {
values.SetNote(h.User().NewSet(rs.Env()).WithContext("lang", rs.Partner().Lang()).
CurrentUser().Company().SaleNote())
}
if !rs.Partner().User().IsEmpty() {
values.SetUser(rs.Partner().User())
}
if !rs.Partner().Team().IsEmpty() {
values.SetTeam(rs.Partner().Team())
}
return values
})
//h.SaleOrder().Methods().OnchangePartnerWarning().DeclareMethod(
// `OnchangePartnerWarning`,
// func(rs m.SaleOrderSet) {
// //@api.onchange('partner_id')
// /*def onchange_partner_id_warning(self):
// if not self.partner_id:
// return
// warning = {}
// title = False
// message = False
// partner = self.partner_id
//
// # If partner has no warning, check its company
// if partner.sale_warn == 'no-message' and partner.parent_id:
// partner = partner.parent_id
//
// if partner.sale_warn != 'no-message':
// # Block if partner only has warning but parent company is blocked
// if partner.sale_warn != 'block' and partner.parent_id and partner.parent_id.sale_warn == 'block':
// partner = partner.parent_id
// title = ("Warning for %s") % partner.name
// message = partner.sale_warn_msg
// warning = {
// 'title': title,
// 'message': message,
// }
// if partner.sale_warn == 'block':
// self.update({'partner_id': False, 'partner_invoice_id': False, 'partner_shipping_id': False, 'pricelist_id': False})
// return {'warning': warning}
//
// if warning:
// return {'warning': warning}
//
// */
// TODO : need to implement onchange warnings first
// })
h.SaleOrder().Methods().Create().Extend("",
func(rs m.SaleOrderSet, data m.SaleOrderData) m.SaleOrderSet {
if data.Name() == "" || data.Name() == rs.T("New") {
seq := h.Sequence().NewSet(rs.Env())
if data.Company().IsNotEmpty() {
seq = seq.WithContext("force_company", data.Company().ID())
}
data.SetName(rs.T("New"))
seqValue := seq.NextByCode("sale.order")
if seqValue != "" {
data.SetName(seqValue)
}
}
// Makes sure PartnerInvoice, PartnerShipping and Pricelist are defined
addr := data.Partner().AddressGet([]string{"delivery", "invoice"})
if data.PartnerInvoice().IsEmpty() {
data.SetPartnerInvoice(addr["invoice"])
}
if data.PartnerShipping().IsEmpty() {
data.SetPartnerShipping(addr["delivery"])
}
if data.Pricelist().IsEmpty() {
data.SetPricelist(data.Partner().PropertyProductPricelist())
}
return rs.Super().Create(data)
})
h.SaleOrder().Methods().PrepareInvoice().DeclareMethod(
`PrepareInvoice prepares the data to create the new invoice for a sales order. This method may be
overridden to implement custom invoice generation (making sure to call super() to establish
a clean extension chain).`,
func(rs m.SaleOrderSet) m.AccountInvoiceData {
rs.EnsureOne()
journal := h.AccountInvoice().NewSet(rs.Env()).DefaultJournal()
if journal.IsEmpty() {
panic(rs.T("Please define an accounting sale journal for this company."))
}
fPos := rs.PartnerInvoice().PropertyAccountPosition()
if !rs.FiscalPosition().IsEmpty() {
fPos = rs.FiscalPosition()
}
invoiceVals := h.AccountInvoice().NewData().
SetName(rs.ClientOrderRef()).
SetOrigin(rs.Name()).
SetType("out_invoice").
SetAccount(rs.PartnerInvoice().PropertyAccountReceivable()).
SetPartner(rs.PartnerInvoice()).
SetPartnerShipping(rs.PartnerShipping()).
SetJournal(journal).
SetCurrency(rs.Pricelist().Currency()).
SetComment(rs.Note()).
SetPaymentTerm(rs.PaymentTerm()).
SetFiscalPosition(fPos).
SetCompany(rs.Company()).
SetUser(rs.User()).
SetTeam(rs.Team())
return invoiceVals
})
h.SaleOrder().Methods().PrintQuotation().DeclareMethod(
`PrintQuotation returns the action to print the quotation report`,
func(rs m.SaleOrderSet) *actions.Action {
//@api.multi
/*def print_quotation(self):
self.filtered(lambda s: s.state == 'draft').write({'state': 'sent'})
return self.env['report'].get_action(self, 'sale.report_saleorder')
*/
// TODO Implement reports first
rs.Search(q.SaleOrder().State().Equals("draft")).SetState("sent")
return &actions.Action{
Type: actions.ActionCloseWindow,
}
})
h.SaleOrder().Methods().ActionViewInvoice().DeclareMethod(
`ActionViewInvoice returns an action to view the invoice(s) related to this order.
If there is a single invoice, then it will be opened in a form view, otherwise in list view.`,
func(rs m.SaleOrderSet) *actions.Action {
invoices := h.AccountInvoice().NewSet(rs.Env())
for _, order := range rs.Records() {
invoices = invoices.Union(order.Invoices())
}
action := actions.Registry.MustGetById("account_account_invoice_tree1")
switch {
case invoices.Len() > 1:
idsStr := make([]string, invoices.Len())
for i, inv := range invoices.Records() {
idsStr[i] = strconv.FormatInt(inv.ID(), 10)
}
action.Domain = fmt.Sprintf("[('id', 'in', (%s))]", strings.Join(idsStr, ","))
case invoices.Len() == 1:
action.Views = []views.ViewTuple{{
ID: "account_invoice_form",
Type: views.ViewTypeForm,
}}
action.ResID = invoices.ID()
default:
action = &actions.Action{Type: actions.ActionCloseWindow}
}
return action
})
h.SaleOrder().Methods().ActionInvoiceCreate().DeclareMethod(
`ActionInvoiceCreate creates the invoice associated to the SO.
- If grouped is true, invoices are grouped by sale orders.
If False, invoices are grouped by (partner_invoice_id, currency)
- If final is true, refunds will be generated if necessary.`,
func(rs m.SaleOrderSet, grouped, final bool) m.AccountInvoiceSet {
type keyStruct struct {
OrderID int64
PartnerID int64
CurrencyID int64
}
precision := decimalPrecision.GetPrecision("Product Unit of Measure").ToPrecision()
invoices := make(map[keyStruct]m.AccountInvoiceSet)
references := make(map[int64]m.SaleOrderSet)
for _, order := range rs.Records() {
groupKey := keyStruct{PartnerID: order.PartnerInvoice().ID(), CurrencyID: order.Currency().ID()}
if grouped {
groupKey = keyStruct{OrderID: order.ID()}
}
lines := order.OrderLine().SortedByField(h.SaleOrderLine().Fields().QtyToInvoice(), false)
for _, line := range lines.Records() {
if nbutils.IsZero(line.QtyToInvoice(), precision) {
continue
}
if _, exists := invoices[groupKey]; !exists {
invData := order.PrepareInvoice()
invoice := h.AccountInvoice().Create(rs.Env(), invData)
references[invoice.ID()] = order
invoices[groupKey] = invoice
} else {
vals := h.AccountInvoice().NewData()
origins := strings.Split(invoices[groupKey].Origin(), ", ")
var inOrigins bool
for _, o := range origins {
if o == order.Name() {
inOrigins = true
break
}
}
if !inOrigins {
vals.SetOrigin(invoices[groupKey].Origin() + ", " + order.Name())
}
names := strings.Split(invoices[groupKey].Name(), ", ")
var inNames bool
for _, n := range names {
if n == order.ClientOrderRef() {
inNames = true
break
}
}
if !inNames && order.ClientOrderRef() != "" {
vals.SetName(invoices[groupKey].Name() + ", " + order.ClientOrderRef())
}
}
if line.QtyToInvoice() > 0 || (line.QtyToInvoice() < 0 && final) {
line.InvoiceLineCreate(invoices[groupKey], line.QtyToInvoice())
}
}
if ref, exists := references[invoices[groupKey].ID()]; exists {
if order.Intersect(ref).IsEmpty() {
references[invoices[groupKey].ID()] = ref.Union(order)
}
}
}
if len(invoices) == 0 {
panic(rs.T("There is no invoicable line"))
}
res := h.AccountInvoice().NewSet(rs.Env())
for _, invoice := range invoices {
if invoice.InvoiceLines().IsEmpty() {
panic(rs.T("There is no invoicable line."))
}
// If invoice is negative, do a refund invoice instead
if invoice.AmountUntaxed() < 0 {
invoice.SetType("out_refund")
for _, line := range invoice.InvoiceLines().Records() {
line.SetQuantity(-line.Quantity())
}
}
// Use additional field helper function (for account extensions)
for _, line := range invoice.InvoiceLines().Records() {
line.DefineAdditionalFields(invoice)
}
// Necessary to force computation of taxes. In account_invoice, they are triggered
// by onchanges, which are not triggered when doing a create.
invoice.ComputeTaxes()
//invoice.message_post_with_view('mail.message_origin_link',
// values={'self': invoice, 'origin': references[invoice]},
// subtype_id=self.env.ref('mail.mt_note').id)
res = res.Union(invoice)
}
return res
})
h.SaleOrder().Methods().ActionDraft().DeclareMethod(
`ActionDraft sets this sale order back to the draft state.`,
func(rs m.SaleOrderSet) bool {
orders := h.SaleOrder().NewSet(rs.Env())
for _, order := range rs.Records() {
if order.State() != "cancel" && order.State() != "sent" {
continue
}
orders = orders.Union(order)
}
orders.Write(h.SaleOrder().NewData().
SetState("draft").
SetProcurementGroup(h.ProcurementGroup().NewSet(rs.Env())))
for _, order := range orders.Records() {
for _, line := range order.OrderLine().Records() {
for _, proc := range line.Procurements().Records() {
proc.SetSaleLine(h.SaleOrderLine().NewSet(rs.Env()))
}
}
}
return true
})
h.SaleOrder().Methods().ActionCancel().DeclareMethod(
`ActionCancel cancels this sale order.`,
func(rs m.SaleOrderSet) bool {
rs.SetState("cancel")
return true
})
h.SaleOrder().Methods().ActionQuotationSend().DeclareMethod(
`ActionQuotationSend opens a window to compose an email,
with the edi sale template message loaded by default`,
func(rs m.SaleOrderSet) *actions.Action {
rs.EnsureOne()
// //@api.multi
// /*def action_quotation_send(self):
// '''
// This function opens a window to compose an email, with the edi sale template message loaded by default
// '''
// self.ensure_one()
// ir_model_data = self.env['ir.model.data']
// try:
// template_id = ir_model_data.get_object_reference('sale', 'email_template_edi_sale')[1]
// except ValueError:
// template_id = False
// try:
// compose_form_id = ir_model_data.get_object_reference('mail', 'email_compose_message_wizard_form')[1]
// except ValueError:
// compose_form_id = False
// ctx = dict()
// ctx.update({
// 'default_model': 'sale.order',
// 'default_res_id': self.ids[0],
// 'default_use_template': bool(template_id),
// 'default_template_id': template_id,
// 'default_composition_mode': 'comment',
// 'mark_so_as_sent': True,
// 'custom_layout': "sale.mail_template_data_notification_email_sale_order"
// })
// return {
// '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,
// }
//
// */
// FIXME: Next line for demo only
rs.Search(q.SaleOrder().State().Equals("draft")).SetState("sent")
return &actions.Action{
Type: actions.ActionCloseWindow,
}
})
h.SaleOrder().Methods().ForceQuotationSend().DeclareMethod(
`ForceQuotationSend`,
func(rs m.SaleOrderSet) bool {
//@api.multi
/*def force_quotation_send(self):
for order in self:
email_act = order.action_quotation_send()
if email_act and email_act.get('context'):
email_ctx = email_act['context']
email_ctx.update(default_email_from=order.company_id.email)
order.with_context(email_ctx).message_post_with_template(email_ctx.get('default_template_id'))
return True
*/
rs.ActionQuotationSend()
return true
})
h.SaleOrder().Methods().ActionDone().DeclareMethod(
`ActionDone sets the state of this sale order to done`,
func(rs m.SaleOrderSet) bool {
rs.SetState("done")
return true
})
h.SaleOrder().Methods().PrepareProcurementGroup().DeclareMethod(
`PrepareProcurementGroup returns the data that will be used to create the
procurement group of this sale order`,
func(rs m.SaleOrderSet) m.ProcurementGroupData {
return h.ProcurementGroup().NewData().SetName(rs.Name())
})
h.SaleOrder().Methods().ActionConfirm().DeclareMethod(
`ActionConfirm confirms this quotation into a sale order`,
func(rs m.SaleOrderSet) bool {
for _, order := range rs.Records() {
order.Write(h.SaleOrder().NewData().
SetState("sale").
SetConfirmationDate(dates.Now()))
if rs.Env().Context().HasKey("send_email") {
rs.ForceQuotationSend()
}
order.OrderLine().ActionProcurementCreate()
}
autoDone := h.ConfigParameter().Search(rs.Env(), q.ConfigParameter().Key().Equals("sale.auto_done_setting"))
if autoDone.Value() != "" {
rs.ActionDone()
}
return true
})
h.SaleOrder().Methods().CreateAnalyticAccount().DeclareMethod(
`CreateAnalyticAccount creates the analytic account (project) for this sale order.`,
func(rs m.SaleOrderSet, prefix string) {
for _, order := range rs.Records() {
name := order.Name()
if prefix != "" {
name = fmt.Sprintf("%s: %s", prefix, order.Name())
}
analyticAccount := h.AccountAnalyticAccount().Create(rs.Env(), h.AccountAnalyticAccount().NewData().
SetName(name).
SetCode(order.ClientOrderRef()).
SetCompany(order.Company()).
SetPartner(order.Partner()))
order.SetProject(analyticAccount)
}
})
h.SaleOrder().Methods().OrderLinesLayouted().DeclareMethod(
`OrderLinesLayouted returns this order lines classified by sale_layout_category and separated in
pages according to the category pagebreaks. Used to render the report.`,
func(rs m.SaleOrderSet) {
/*
@api.multi
def order_lines_layouted(self):
self.ensure_one()
report_pages = [[]]
for category, lines in groupby(self.order_line, lambda l: l.layout_category_id):
# If last added category induced a pagebreak, this one will be on a new page
if report_pages[-1] and report_pages[-1][-1]['pagebreak']:
report_pages.append([])
# Append category to current report page
report_pages[-1].append({
'name': category and category.name or 'Uncategorized',
'subtotal': category and category.subtotal,
'pagebreak': category and category.pagebreak,
'lines': list(lines)
})
return report_pages
*/
})
h.SaleOrder().Methods().GetTaxAmountByGroup().DeclareMethod(
`GetTaxAmountByGroup`,
func(rs m.SaleOrderSet) []accounttypes.TaxGroup {
rs.EnsureOne()
currency := rs.Company().Currency()
if !rs.Currency().IsEmpty() {
currency = rs.Currency()
}
groups := make(map[int64]float64)
for _, line := range rs.OrderLine().Records() {
var baseTax float64
for _, tax := range line.Tax().Records() {
priceReduce := line.PriceUnit() * (1 - line.Discount()/100)
_, _, _, taxes := tax.ComputeAll(priceReduce+baseTax, currency, line.ProductUomQty(), line.Product(), rs.PartnerShipping())
for _, t := range taxes {
groups[tax.TaxGroup().ID()] += t.Amount
}
if tax.IncludeBaseAmount() {
_, _, _, taxesIncl := tax.ComputeAll(priceReduce+baseTax, currency, 1, line.Product(), rs.PartnerShipping())
baseTax += taxesIncl[0].Amount
}
}
}
res := make([]accounttypes.TaxGroup, len(groups))
var i int
for id, amount := range groups {
taxGroup := h.AccountTaxGroup().Browse(rs.Env(), []int64{id})
res[i] = accounttypes.TaxGroup{GroupName: taxGroup.Name(), TaxAmount: amount}
i++
}
sort.Slice(res, func(i, j int) bool {
return res[i].Sequence < res[j].Sequence
})
return res
})
h.SaleOrderLine().DeclareModel()
h.SaleOrderLine().SetDefaultOrder("Order", "LayoutCategory", "Sequence", "ID")
h.SaleOrderLine().AddFields(map[string]models.FieldDefinition{
"Order": models.Many2OneField{String: "Order Reference", RelationModel: h.SaleOrder(),
Required: true, OnDelete: models.Cascade, Index: true, NoCopy: true},
"Name": models.TextField{String: "Description", Required: true},
"Sequence": models.IntegerField{String: "Sequence", Default: models.DefaultValue(10)},
"InvoiceLines": models.Many2ManyField{String: "Invoice Lines", JSON: "invoice_lines",
RelationModel: h.AccountInvoiceLine(), NoCopy: true},
"InvoiceStatus": models.SelectionField{Selection: types.Selection{
"upselling": "Upselling Opportunity",
"invoiced": "Fully Invoiced",
"to invoice": "To Invoice",
"no": "Nothing to Invoice",
},
Compute: h.SaleOrderLine().Methods().ComputeInvoiceStatus(), Stored: true,
Depends: []string{"State", "ProductUom", "QtyDelivered", "QtyToInvoice", "QtyInvoiced"},
Default: models.DefaultValue("no"),
},
"PriceUnit": models.FloatField{String: "Unit Price", Required: true,
Digits: decimalPrecision.GetPrecision("Product Price"),
OnChange: h.SaleOrderLine().Methods().OnchangeDiscount()},
"PriceSubtotal": models.FloatField{String: "Subtotal",
Compute: h.SaleOrderLine().Methods().ComputeAmount(), Stored: true,
Depends: []string{"ProductUomQty", "Discount", "PriceUnit", "Tax"}},
"PriceTax": models.FloatField{String: "Taxes",
Compute: h.SaleOrderLine().Methods().ComputeAmount(), Stored: true,
Depends: []string{"ProductUomQty", "Discount", "PriceUnit", "Tax"}},
"PriceTotal": models.FloatField{String: "Total",
Compute: h.SaleOrderLine().Methods().ComputeAmount(), Stored: true,
Depends: []string{"ProductUomQty", "Discount", "PriceUnit", "Tax"}},
"PriceReduce": models.FloatField{String: "Price Reduce",
Compute: h.SaleOrderLine().Methods().GetPriceReduce(), Stored: true,
Depends: []string{"PriceUnit", "Discount"}},
"Tax": models.Many2ManyField{String: "Taxes",
RelationModel: h.AccountTax(), JSON: "tax_id",
OnChange: h.SaleOrderLine().Methods().OnchangeDiscount(),
Filter: q.AccountTax().Active().Equals(true).Or().Active().Equals(false)},
"PriceReduceTaxInc": models.FloatField{Compute: h.SaleOrderLine().Methods().GetPriceReduceTax(),
Stored: true, Depends: []string{"PriceTotal", "ProductUomQty"}},
"PriceReduceTaxExcl": models.FloatField{Compute: h.SaleOrderLine().Methods().GetPriceReduceNotax(),
Stored: true, Depends: []string{"PriceSubtotal", "ProductUomQty"}},
"Discount": models.FloatField{String: "Discount (%)",
Digits: decimalPrecision.GetPrecision("Discount")},
"Product": models.Many2OneField{String: "Product", RelationModel: h.ProductProduct(),
OnChange: h.SaleOrderLine().Methods().ProductChange(),
Filter: q.ProductProduct().SaleOk().Equals(true), OnDelete: models.Restrict, Required: true},
"ProductUomQty": models.FloatField{String: "Quantity",
Digits: decimalPrecision.GetPrecision("Product Unit of Measure"), Required: true,
OnChange: h.SaleOrderLine().Methods().ProductUomChange(),
Default: models.DefaultValue(1.0)},
"ProductUom": models.Many2OneField{String: "Unit of Measure", RelationModel: h.ProductUom(),
OnChange: h.SaleOrderLine().Methods().ProductUomChange(),
Required: true},
"QtyDeliveredUpdateable": models.BooleanField{String: "Can Edit Delivered",
Compute: h.SaleOrderLine().Methods().ComputeQtyDeliveredUpdateable(),
Depends: []string{"Product.InvoicePolicy", "Order.State"},
Default: models.DefaultValue(true)},
"QtyDelivered": models.FloatField{String: "Delivered", NoCopy: true,
Digits: decimalPrecision.GetPrecision("Product Unit of Measure")},
"QtyToInvoice": models.FloatField{String: "To Invoice",
Compute: h.SaleOrderLine().Methods().GetToInvoiceQty(), Stored: true,
Depends: []string{"QtyInvoiced", "QtyDelivered", "ProductUomQty", "Order.State"},
Digits: decimalPrecision.GetPrecision("Product Unit of Measure")},
"QtyInvoiced": models.FloatField{String: "Invoiced", Compute: h.SaleOrderLine().Methods().GetInvoiceQty(),
Depends: []string{"InvoiceLines.Invoice.State", "InvoiceLines.Quantity"},
Stored: true, Digits: decimalPrecision.GetPrecision("Product Unit of Measure")},
"Salesman": models.Many2OneField{String: "Salesperson", RelationModel: h.User(), Related: "Order.User",
ReadOnly: true},
"Currency": models.Many2OneField{String: "Currency", RelationModel: h.Currency(),
Related: "Order.Currency", ReadOnly: true},
"Company": models.Many2OneField{String: "Company", RelationModel: h.Company(), Related: "Order.Company",
ReadOnly: true},
"OrderPartner": models.Many2OneField{String: "Customer", RelationModel: h.Partner(),
Related: "Order.Partner"},
"AnalyticTags": models.Many2ManyField{String: "Analytic Tags", RelationModel: h.AccountAnalyticTag(),
JSON: "analytic_tag_ids"},
"State": models.SelectionField{String: "Order Status", Selection: types.Selection{
"draft": "Quotation",
"sent": "Quotation Sent",
"sale": "Sale Order",
"done": "Done",
"cancel": "Cancelled",
},
Related: "Order.State", ReadOnly: true, NoCopy: true, Default: models.DefaultValue("draft")},
"CustomerLead": models.IntegerField{String: "Delivery Lead Time", Required: true, GoType: new(int),
Default: models.DefaultValue(0.0),
Help: "Number of days between the order confirmation and the shipping of the products to the customer"},
"Procurements": models.One2ManyField{String: "ProcurementIds", RelationModel: h.ProcurementOrder(),
ReverseFK: "SaleLine", JSON: "procurement_ids"},
"LayoutCategory": models.Many2OneField{String: "Section", RelationModel: h.SaleLayoutCategory()},
"LayoutCategorySequence": models.IntegerField{String: "Layout Sequence"},
})
h.SaleOrderLine().Methods().ComputeInvoiceStatus().DeclareMethod(
`ComputeInvoiceStatus compute the invoice status of a SO line. Possible statuses:
- no: if the SO is not in status 'sale' or 'done', we consider that there is nothing to
invoice. This is also hte default value if the conditions of no other status is met.
- to invoice: we refer to the quantity to invoice of the line. Refer to method
'GetToInvoiceQty()' for more information on how this quantity is calculated.
- upselling: this is possible only for a product invoiced on ordered quantities for which
we delivered more than expected. The could arise if, for example, a project took more
time than expected but we decided not to invoice the extra cost to the client. This
occurs only in state 'sale', so that when a SO is set to done, the upselling opportunity
is removed from the list.
- invoiced: the quantity invoiced is larger or equal to the quantity ordered.`,
func(rs m.SaleOrderLineSet) m.SaleOrderLineData {
precision := decimalPrecision.GetPrecision("Product Unit of Measure").ToPrecision()
invoiceStatus := "no"
switch {
case rs.State() != "sale" && rs.State() != "done":
invoiceStatus = "no"
case !nbutils.IsZero(rs.QtyToInvoice(), precision):
invoiceStatus = "to invoice"
case rs.State() == "sale" && rs.Product().InvoicePolicy() == "order" &&
nbutils.Compare(rs.QtyDelivered(), rs.ProductUomQty(), precision) > 0:
invoiceStatus = "upselling"
case nbutils.Compare(rs.QtyInvoiced(), rs.ProductUomQty(), precision) >= 0:
invoiceStatus = "invoiced"
default:
invoiceStatus = "no"
}
return h.SaleOrderLine().NewData().SetInvoiceStatus(invoiceStatus)
})
h.SaleOrderLine().Methods().ComputeAmount().DeclareMethod(
`ComputeAmount computes the amounts of the SO line.`,
func(rs m.SaleOrderLineSet) m.SaleOrderLineData {
price := rs.PriceUnit() * (1 - rs.Discount()/100)
_, totalExcluded, totalIncluded, _ := rs.Tax().ComputeAll(price, rs.Order().Currency(), rs.ProductUomQty(), rs.Product(), rs.Order().PartnerShipping())
return h.SaleOrderLine().NewData().
SetPriceTax(totalIncluded - totalExcluded).
SetPriceTotal(totalIncluded).
SetPriceSubtotal(totalExcluded)
})
h.SaleOrderLine().Methods().ComputeQtyDeliveredUpdateable().DeclareMethod(
`ComputeQtyDeliveredUpdateable checks if the delivered quantity can be updated`,
func(rs m.SaleOrderLineSet) m.SaleOrderLineData {
qtyDeliveredUpdateable := rs.Order().State() == "sale" && rs.Product().TrackService() == "manual" && rs.Product().ExpensePolicy() == "no"
return h.SaleOrderLine().NewData().SetQtyDeliveredUpdateable(qtyDeliveredUpdateable)
})
h.SaleOrderLine().Methods().GetToInvoiceQty().DeclareMethod(
`GetToInvoiceQty compute the quantity to invoice. If the invoice policy is order,
the quantity to invoice is calculated from the ordered quantity. Otherwise, the quantity
delivered is used.`,
func(rs m.SaleOrderLineSet) m.SaleOrderLineData {
if rs.Order().State() != "sale" && rs.Order().State() != "done" {
return h.SaleOrderLine().NewData().SetQtyToInvoice(0)
}
qtyToInvoice := rs.QtyDelivered() - rs.QtyInvoiced()
if rs.Product().InvoicePolicy() == "order" {
qtyToInvoice = rs.ProductUomQty() - rs.QtyInvoiced()
}
return h.SaleOrderLine().NewData().
SetQtyToInvoice(qtyToInvoice)
})
h.SaleOrderLine().Methods().GetInvoiceQty().DeclareMethod(
`GetInvoiceQty computes the quantity invoiced. If case of a refund, the quantity invoiced is decreased.
Note that this is the case only if the refund is generated from the SO and that is intentional: if
a refund made would automatically decrease the invoiced quantity, then there is a risk of reinvoicing
it automatically, which may not be wanted at all. That's why the refund has to be created from the SO`,
func(rs m.SaleOrderLineSet) m.SaleOrderLineData {
var qtyInvoiced float64
for _, invoiceLine := range rs.InvoiceLines().Records() {
if invoiceLine.Invoice().State() == "cancel" {
continue
}
switch invoiceLine.Invoice().Type() {
case "out_invoice":
qtyInvoiced += invoiceLine.Uom().ComputeQuantity(invoiceLine.Quantity(), rs.ProductUom(), true)
case "out_refund":
qtyInvoiced -= invoiceLine.Uom().ComputeQuantity(invoiceLine.Quantity(), rs.ProductUom(), true)
}
}
return h.SaleOrderLine().NewData().SetQtyInvoiced(qtyInvoiced)
})
h.SaleOrderLine().Methods().GetPriceReduce().DeclareMethod(
`GetPriceReduce computes the unit price with discount.`,
func(rs m.SaleOrderLineSet) m.SaleOrderLineData {
return h.SaleOrderLine().NewData().SetPriceReduce(rs.PriceUnit() * (1 - rs.Discount()/100))
})
h.SaleOrderLine().Methods().GetPriceReduceTax().DeclareMethod(
`GetPriceReduceTax computes the total price with tax and discount.`,
func(rs m.SaleOrderLineSet) m.SaleOrderLineData {
var price float64
if rs.ProductUomQty() != 0 {
price = rs.PriceTotal() / rs.ProductUomQty()
}
return h.SaleOrderLine().NewData().SetPriceReduceTaxInc(price)
})
h.SaleOrderLine().Methods().GetPriceReduceNotax().DeclareMethod(
`GetPriceReduceNotax computes the total price with discount but without taxes.`,
func(rs m.SaleOrderLineSet) m.SaleOrderLineData {
var price float64
if rs.ProductUomQty() != 0 {
price = rs.PriceSubtotal() / rs.ProductUomQty()
}
return h.SaleOrderLine().NewData().SetPriceReduceTaxExcl(price)
})
h.SaleOrderLine().Methods().ComputeTax().DeclareMethod(
`ComputeTax computes the taxes applicable for this sale order line.`,
func(rs m.SaleOrderLineSet) m.SaleOrderLineData {
rs.EnsureOne()
fPos := rs.Order().Partner().PropertyAccountPosition()
if !rs.Order().FiscalPosition().IsEmpty() {
fPos = rs.Order().FiscalPosition()
}
taxes := rs.Product().Taxes()
if !rs.Company().IsEmpty() {
taxes = taxes.Search(q.AccountTax().Company().Equals(rs.Company()))
}
if !fPos.IsEmpty() {
taxes = fPos.MapTax(taxes, rs.Product(), rs.Order().PartnerShipping())
}
return h.SaleOrderLine().NewData().SetTax(taxes)