forked from i-love-flamingo/flamingo-commerce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
item.go
509 lines (436 loc) · 15.6 KB
/
item.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
package cart
import (
"errors"
"fmt"
"math/big"
priceDomain "github.com/lunarforge/flamingo_commerce/price/domain"
"github.com/lunarforge/flamingo_commerce/product/domain"
)
type (
// Item for Cart
Item struct {
// ID of the item - needs to be unique over the whole cart
ID string
// ExternalReference can be used by cart service implementations to separate the representation in an external
// cart service from the unique item ID
ExternalReference string
MarketplaceCode string
// VariantMarketPlaceCode is used for Configurable products
VariantMarketPlaceCode string
ProductName string
// Source Id of where the items should be initial picked - This is set by the SourcingLogic
SourceID string
Qty int
AdditionalData map[string]string
// SinglePriceGross gross price (incl. taxes) for a single product
SinglePriceGross priceDomain.Price
// SinglePriceNet net price (excl. taxes) for a single product
SinglePriceNet priceDomain.Price
// RowPriceGross
RowPriceGross priceDomain.Price
// RowPriceNet
RowPriceNet priceDomain.Price
// RowPriceGross
RowTaxes Taxes
// AppliedDiscounts contains the details about the discounts applied to this item - they can be "itemrelated" or not
AppliedDiscounts AppliedDiscounts
}
// ItemBuilder can be used to construct an item with a fluent interface
ItemBuilder struct {
itemCurrency *string
invariantError error
itemInBuilding *Item
configUseGrossPrice bool
}
// ItemBuilderProvider should be used to create an item
ItemBuilderProvider func() *ItemBuilder
// ItemSplitter used to split an item
ItemSplitter struct {
itemBuilderProvider ItemBuilderProvider
configUseGrossPrice bool
}
)
// TotalTaxAmount returns total tax amount as price
func (i Item) TotalTaxAmount() priceDomain.Price {
return i.RowTaxes.TotalAmount()
}
// TotalDiscountAmount gets the savings by item
func (i Item) TotalDiscountAmount() priceDomain.Price {
result, _ := i.NonItemRelatedDiscountAmount().Add(i.ItemRelatedDiscountAmount())
return result
}
// ItemRelatedDiscountAmount is the sum of AppliedDiscounts where IsItemRelated = true
func (i Item) ItemRelatedDiscountAmount() priceDomain.Price {
prices := make([]priceDomain.Price, 0, len(i.AppliedDiscounts))
for _, discount := range i.AppliedDiscounts {
if !discount.IsItemRelated {
continue
}
prices = append(prices, discount.Applied)
}
result, _ := priceDomain.SumAll(prices...)
return result.GetPayable()
}
// NonItemRelatedDiscountAmount is the sum of AppliedDiscounts where IsItemRelated = false
func (i Item) NonItemRelatedDiscountAmount() priceDomain.Price {
prices := make([]priceDomain.Price, 0, len(i.AppliedDiscounts))
for _, discount := range i.AppliedDiscounts {
if discount.IsItemRelated {
continue
}
prices = append(prices, discount.Applied)
}
result, _ := priceDomain.SumAll(prices...)
return result.GetPayable()
}
// RowPriceGrossWithDiscount = RowPriceGross-TotalDiscountAmount()
func (i Item) RowPriceGrossWithDiscount() priceDomain.Price {
result, _ := i.RowPriceGross.Add(i.TotalDiscountAmount())
return result
}
// RowPriceNetWithDiscount = RowPriceNet-TotalDiscountAmount()
func (i Item) RowPriceNetWithDiscount() priceDomain.Price {
result, _ := i.RowPriceNet.Add(i.TotalDiscountAmount())
return result
}
// RowPriceGrossWithItemRelatedDiscount = RowPriceGross-ItemRelatedDiscountAmount()
func (i Item) RowPriceGrossWithItemRelatedDiscount() priceDomain.Price {
result, _ := i.RowPriceGross.Add(i.ItemRelatedDiscountAmount())
return result
}
// RowPriceNetWithItemRelatedDiscount =RowTotal-ItemRelatedDiscountAmount
func (i Item) RowPriceNetWithItemRelatedDiscount() priceDomain.Price {
result, _ := i.RowPriceNet.Add(i.ItemRelatedDiscountAmount())
return result
}
// AdditionalDataKeys lists all available keys
func (i Item) AdditionalDataKeys() []string {
additionalData := i.AdditionalData
res := make([]string, len(additionalData))
n := 0
for k := range additionalData {
res[n] = k
n++
}
return res
}
// AdditionalDataValues lists all values
func (i Item) AdditionalDataValues() []string {
res := make([]string, len(i.AdditionalData))
n := 0
for _, v := range i.AdditionalData {
res[n] = v
n++
}
return res
}
// HasAdditionalDataKey checks if an attribute is available
func (i Item) HasAdditionalDataKey(key string) bool {
_, exist := i.AdditionalData[key]
return exist
}
// GetAdditionalData returns a specified attribute
func (i Item) GetAdditionalData(key string) string {
attribute := i.AdditionalData[key]
return attribute
}
// Inject dependencies
func (f *ItemBuilder) Inject(config *struct {
UseGrosPrice bool `inject:"config:commerce.product.priceIsGross,optional"`
}) {
if config != nil {
f.configUseGrossPrice = config.UseGrosPrice
}
}
// SetID sets the id
func (f *ItemBuilder) SetID(id string) *ItemBuilder {
f.init()
f.itemInBuilding.ID = id
return f
}
// SetExternalReference sets the ExternalReference
func (f *ItemBuilder) SetExternalReference(ref string) *ItemBuilder {
f.init()
f.itemInBuilding.ExternalReference = ref
return f
}
// SetFromItem sets the data in builder from existing item - useful to get a updated item based from existing. Its not setting Taxes (use Calculate)
func (f *ItemBuilder) SetFromItem(item Item) *ItemBuilder {
f.init()
f.SetProductData(item.MarketplaceCode, item.VariantMarketPlaceCode, item.ProductName)
f.SetExternalReference(item.ExternalReference)
f.SetID(item.ID)
f.SetQty(item.Qty)
f.AddDiscounts(item.AppliedDiscounts...)
f.SetSinglePriceGross(item.SinglePriceGross)
f.SetSinglePriceNet(item.SinglePriceNet)
return f
}
// SetVariantMarketPlaceCode sets VariantMarketPlaceCode (only for configurable_with_variant relevant)
func (f *ItemBuilder) SetVariantMarketPlaceCode(id string) *ItemBuilder {
f.init()
f.itemInBuilding.VariantMarketPlaceCode = id
return f
}
// SetSourceID sets optional source ID
func (f *ItemBuilder) SetSourceID(id string) *ItemBuilder {
f.init()
f.itemInBuilding.SourceID = id
return f
}
// SetAdditionalData sets optional additional data
func (f *ItemBuilder) SetAdditionalData(d map[string]string) *ItemBuilder {
f.init()
f.itemInBuilding.AdditionalData = d
return f
}
// SetQty sets the qty (defaults to 1)
func (f *ItemBuilder) SetQty(q int) *ItemBuilder {
f.init()
f.itemInBuilding.Qty = q
return f
}
// SetSinglePriceGross set by gross price
func (f *ItemBuilder) SetSinglePriceGross(grossPrice priceDomain.Price) *ItemBuilder {
f.init()
if !grossPrice.IsPayable() {
f.invariantError = errors.New("SetSinglePriceGross need to get payable price")
}
f.itemInBuilding.SinglePriceGross = grossPrice
f.checkCurrency(&grossPrice)
return f
}
// SetSinglePriceNet set by net price
func (f *ItemBuilder) SetSinglePriceNet(price priceDomain.Price) *ItemBuilder {
f.init()
if !price.IsPayable() {
f.invariantError = errors.New("SetSinglePriceNet need to get payable price")
}
f.itemInBuilding.SinglePriceNet = price
f.checkCurrency(&price)
return f
}
// AddTaxInfo add a tax info - at least taxRate OR taxAmount need to be given. the tax amount can be calculated
func (f *ItemBuilder) AddTaxInfo(taxType string, taxRate *big.Float, taxAmount *priceDomain.Price) *ItemBuilder {
f.init()
if taxRate == nil && taxAmount == nil {
f.invariantError = errors.New("at least taxRate or taxAmount need to be given")
}
tax := Tax{
Type: taxType,
Rate: taxRate,
}
if taxAmount != nil {
if !taxAmount.IsPayable() {
f.invariantError = errors.New("taxAmount need to be payable price")
}
f.checkCurrency(taxAmount)
tax.Amount = *taxAmount
}
f.itemInBuilding.RowTaxes = append(f.itemInBuilding.RowTaxes, tax)
return f
}
// AddDiscount adds a discount
func (f *ItemBuilder) AddDiscount(discount AppliedDiscount) *ItemBuilder {
f.init()
if !discount.Applied.IsPayable() {
f.invariantError = errors.New("AddDiscount need to have payable price")
}
if !discount.Applied.IsNegative() {
f.invariantError = fmt.Errorf("AddDiscount need to have negative price - given %f", discount.Applied.FloatAmount())
}
f.checkCurrency(&discount.Applied)
f.itemInBuilding.AppliedDiscounts = append(f.itemInBuilding.AppliedDiscounts, discount)
return f
}
// AddDiscounts adds a list of discounts
func (f *ItemBuilder) AddDiscounts(discounts ...AppliedDiscount) *ItemBuilder {
for _, discount := range discounts {
f.AddDiscount(discount)
}
return f
}
// CalculatePricesAndTaxAmountsFromSinglePriceNet handles the vertical tax calculation - based from current SinglePriceNet, Qty and the RowTax Infos given
// Sets RowPriceNet, missing tax.Amount and RowPriceGross
func (f *ItemBuilder) CalculatePricesAndTaxAmountsFromSinglePriceNet() *ItemBuilder {
priceNet := f.itemInBuilding.SinglePriceNet
f.itemInBuilding.RowPriceNet = priceNet.Multiply(f.itemInBuilding.Qty)
for k, tax := range f.itemInBuilding.RowTaxes {
// Calculate tax amount from rate if required
if tax.Amount.IsZero() && tax.Rate != nil {
// set tax amount and round it
tax.Amount = f.itemInBuilding.RowPriceNetWithDiscount().TaxFromNet(*tax.Rate).GetPayable()
f.itemInBuilding.RowTaxes[k] = tax
}
}
totalTaxAmount := f.itemInBuilding.TotalTaxAmount()
f.itemInBuilding.RowPriceGross, _ = priceDomain.SumAll(f.itemInBuilding.RowPriceNet, totalTaxAmount)
if f.itemInBuilding.Qty == 0 {
f.invariantError = errors.New("Quantity is Zero")
return f
}
f.itemInBuilding.SinglePriceGross, _ = priceNet.Add(totalTaxAmount.Divided(f.itemInBuilding.Qty))
return f
}
// CalculatePricesAndTax reads the config flag and recalculates Total and Tax
func (f *ItemBuilder) CalculatePricesAndTax() *ItemBuilder {
if f.configUseGrossPrice {
return f.CalculatePricesAndTaxAmountsFromSinglePriceGross()
}
return f.CalculatePricesAndTaxAmountsFromSinglePriceNet()
}
// CalculatePricesAndTaxAmountsFromSinglePriceGross handles the vertical tax calculation - based from current SinglePriceNet, Qty and the RowTax Infos given
// Sets RowPriceNet, missing tax.Amount and RowPriceGross
func (f *ItemBuilder) CalculatePricesAndTaxAmountsFromSinglePriceGross() *ItemBuilder {
priceGross := f.itemInBuilding.SinglePriceGross
f.itemInBuilding.RowPriceGross = priceGross.Multiply(f.itemInBuilding.Qty)
for k, tax := range f.itemInBuilding.RowTaxes {
// Calculate tax amount from rate if required
if tax.Amount.IsZero() && tax.Rate != nil {
tax.Amount = f.itemInBuilding.RowPriceGrossWithDiscount().TaxFromGross(*tax.Rate).GetPayable()
f.itemInBuilding.RowTaxes[k] = tax
}
}
totalTaxAmount := f.itemInBuilding.TotalTaxAmount()
f.itemInBuilding.RowPriceNet, _ = f.itemInBuilding.RowPriceGross.Sub(totalTaxAmount)
f.itemInBuilding.SinglePriceNet, _ = priceGross.Sub(totalTaxAmount.Divided(f.itemInBuilding.Qty))
return f
}
// SetProductData set product data: MarketplaceCode, VariantMarketPlaceCode, ProductName
func (f *ItemBuilder) SetProductData(marketplace string, vc string, name string) *ItemBuilder {
f.init()
f.itemInBuilding.MarketplaceCode = marketplace
f.itemInBuilding.VariantMarketPlaceCode = vc
f.itemInBuilding.ProductName = name
return f
}
// SetByProduct gets a product and calculates also prices
func (f *ItemBuilder) SetByProduct(product domain.BasicProduct) *ItemBuilder {
if !product.IsSaleable() {
f.invariantError = errors.New("Product is not saleable")
}
f.init()
f.itemInBuilding.MarketplaceCode = product.BaseData().MarketPlaceCode
f.itemInBuilding.ProductName = product.BaseData().Title
if configurable, ok := product.(domain.ConfigurableProductWithActiveVariant); ok {
f.itemInBuilding.MarketplaceCode = configurable.ConfigurableBaseData().MarketPlaceCode
f.itemInBuilding.VariantMarketPlaceCode = configurable.ActiveVariant.MarketPlaceCode
}
if f.configUseGrossPrice {
f.SetSinglePriceGross(product.SaleableData().ActivePrice.GetFinalPrice())
f.CalculatePricesAndTaxAmountsFromSinglePriceGross()
} else {
f.SetSinglePriceNet(product.SaleableData().ActivePrice.GetFinalPrice())
f.CalculatePricesAndTaxAmountsFromSinglePriceNet()
}
return f
}
func (f *ItemBuilder) checkCurrency(price *priceDomain.Price) {
if price == nil {
return
}
currency := price.Currency()
if f.itemCurrency == nil {
f.itemCurrency = ¤cy
return
}
if *f.itemCurrency != currency {
f.invariantError = fmt.Errorf("There is a currency mismatch inside the item %v and %v", currency, *f.itemCurrency)
}
}
// Build returns build item or error if invariants do not match. Any call will also REST the ItemBuilder
func (f *ItemBuilder) Build() (*Item, error) {
if f.itemInBuilding == nil {
return f.reset(errors.New("Nothing in building"))
}
if f.invariantError != nil {
return f.reset(f.invariantError)
}
if f.itemInBuilding.ID == "" {
return f.reset(errors.New("Id Required"))
}
checkPrice, _ := f.itemInBuilding.RowPriceNet.Add(f.itemInBuilding.TotalTaxAmount())
if !checkPrice.LikelyEqual(f.itemInBuilding.RowPriceGross) {
return f.reset(fmt.Errorf("RowPriceGross (%f) need to match likely TotalTaxAmount + RowPriceNet. (%f) for item %v ", f.itemInBuilding.RowPriceGross.FloatAmount(), checkPrice.FloatAmount(), f.itemInBuilding.ID))
}
return f.reset(nil)
}
func (f *ItemBuilder) init() {
if f.itemInBuilding == nil {
f.itemInBuilding = &Item{
Qty: 1,
}
}
}
func (f *ItemBuilder) reset(err error) (*Item, error) {
item := f.itemInBuilding
f.itemInBuilding = nil
f.invariantError = nil
f.itemCurrency = nil
return item, err
}
// Inject dependencies
func (s *ItemSplitter) Inject(itemBuilderProvider ItemBuilderProvider, config *struct {
UseGrossPrice bool `inject:"config:commerce.product.priceIsGross,optional"`
}) {
s.itemBuilderProvider = itemBuilderProvider
if config != nil {
s.configUseGrossPrice = config.UseGrossPrice
}
}
// SplitInSingleQtyItems the given item into multiple items with Qty 1 and make sure the sum of the items prices matches by using SplitInPayables
func (s *ItemSplitter) SplitInSingleQtyItems(givenItem Item) ([]Item, error) {
var items []Item
// configUseGrossPrice true then:
// Given: SinglePriceGross / all AppliedDiscounts / All Taxes
// Calculated: SinglePriceNet / RowPriceGross / RowPriceNet / SinglePriceNet
// configUseGrossPrice false then:
// Given: SinglePriceNez / all AppliedDiscounts / All Taxes
// Calculated: SinglePriceGross / RowPriceGross / RowPriceNet / SinglePriceGross
for x := 0; x < givenItem.Qty; x++ {
itemBuilder := s.itemBuilderProvider()
itemBuilder.SetProductData(givenItem.MarketplaceCode, givenItem.VariantMarketPlaceCode, givenItem.ProductName)
itemBuilder.SetExternalReference(givenItem.ExternalReference)
itemBuilder.SetID(givenItem.ID)
itemBuilder.SetQty(1)
for _, ap := range givenItem.AppliedDiscounts {
apSplitted, err := ap.Applied.SplitInPayables(givenItem.Qty)
if err != nil {
return nil, err
}
newDiscount := AppliedDiscount{
CampaignCode: ap.CampaignCode,
CouponCode: ap.CouponCode,
Label: ap.Label,
Applied: apSplitted[x],
Type: ap.Type,
IsItemRelated: ap.IsItemRelated,
SortOrder: ap.SortOrder,
}
itemBuilder.AddDiscount(newDiscount)
}
for _, rt := range givenItem.RowTaxes {
if rt.Amount.IsZero() {
continue
}
rtSplitted, err := rt.Amount.SplitInPayables(givenItem.Qty)
if err != nil {
return nil, err
}
itemBuilder.AddTaxInfo(rt.Type, rt.Rate, &rtSplitted[x])
}
if s.configUseGrossPrice {
itemBuilder.SetSinglePriceGross(givenItem.SinglePriceGross.GetPayable())
itemBuilder.CalculatePricesAndTaxAmountsFromSinglePriceGross()
} else {
itemBuilder.SetSinglePriceNet(givenItem.SinglePriceNet.GetPayable())
itemBuilder.CalculatePricesAndTaxAmountsFromSinglePriceNet()
}
item, err := itemBuilder.Build()
if err != nil {
return nil, err
}
items = append(items, *item)
}
return items, nil
}