-
Notifications
You must be signed in to change notification settings - Fork 75
/
cartService.go
1200 lines (1005 loc) · 39.6 KB
/
cartService.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
package application
import (
"context"
"encoding/gob"
"fmt"
"flamingo.me/flamingo/v3/core/auth"
"github.com/pkg/errors"
"flamingo.me/flamingo/v3/framework/flamingo"
"flamingo.me/flamingo/v3/framework/web"
cartDomain "flamingo.me/flamingo-commerce/v3/cart/domain/cart"
"flamingo.me/flamingo-commerce/v3/cart/domain/decorator"
"flamingo.me/flamingo-commerce/v3/cart/domain/events"
"flamingo.me/flamingo-commerce/v3/cart/domain/placeorder"
"flamingo.me/flamingo-commerce/v3/cart/domain/validation"
productDomain "flamingo.me/flamingo-commerce/v3/product/domain"
)
// CartService application struct
type (
// CartService provides methods to modify the cart
CartService struct {
cartReceiverService *CartReceiverService
webIdentityService *auth.WebIdentityService
productService productDomain.ProductService
eventPublisher events.EventPublisher
eventRouter flamingo.EventRouter
deliveryInfoBuilder cartDomain.DeliveryInfoBuilder
logger flamingo.Logger
defaultDeliveryCode string
restrictionService *validation.RestrictionService
deleteEmptyDelivery bool
// optionals - these may be nil
cartValidator validation.Validator
itemValidator validation.ItemValidator
cartCache CartCache
placeOrderService placeorder.Service
}
// RestrictionError error enriched with result of restrictions
RestrictionError struct {
message string
CartItemID string
RestrictionResult validation.RestrictionResult
}
// QtyAdjustmentResult restriction result enriched with the respective item
QtyAdjustmentResult struct {
OriginalItem cartDomain.Item
DeliveryCode string
WasDeleted bool
RestrictionResult *validation.RestrictionResult
NewQty int
HasRemovedCouponCodes bool
}
// QtyAdjustmentResults slice of QtyAdjustmentResult
QtyAdjustmentResults []QtyAdjustmentResult
// PromotionFunction type takes ctx, cart, couponCode and applies the promotion
promotionFunc func(context.Context, *cartDomain.Cart, string) (*cartDomain.Cart, cartDomain.DeferEvents, error)
)
func init() {
gob.Register(RestrictionError{})
gob.Register(QtyAdjustmentResults{})
}
// Error fetch error message
func (e *RestrictionError) Error() string {
return e.message
}
// Inject dependencies
func (cs *CartService) Inject(
cartReceiverService *CartReceiverService,
productService productDomain.ProductService,
eventPublisher events.EventPublisher,
eventRouter flamingo.EventRouter,
deliveryInfoBuilder cartDomain.DeliveryInfoBuilder,
restrictionService *validation.RestrictionService,
webIdentityService *auth.WebIdentityService,
logger flamingo.Logger,
config *struct {
DefaultDeliveryCode string `inject:"config:commerce.cart.defaultDeliveryCode,optional"`
DeleteEmptyDelivery bool `inject:"config:commerce.cart.deleteEmptyDelivery,optional"`
},
optionals *struct {
CartValidator validation.Validator `inject:",optional"`
ItemValidator validation.ItemValidator `inject:",optional"`
CartCache CartCache `inject:",optional"`
PlaceOrderService placeorder.Service `inject:",optional"`
},
) {
cs.cartReceiverService = cartReceiverService
cs.productService = productService
cs.eventPublisher = eventPublisher
cs.eventRouter = eventRouter
cs.deliveryInfoBuilder = deliveryInfoBuilder
cs.restrictionService = restrictionService
cs.webIdentityService = webIdentityService
cs.logger = logger.WithField("module", "cart").WithField("category", "application.cartService")
if config != nil {
cs.defaultDeliveryCode = config.DefaultDeliveryCode
cs.deleteEmptyDelivery = config.DeleteEmptyDelivery
}
if optionals != nil {
cs.cartValidator = optionals.CartValidator
cs.itemValidator = optionals.ItemValidator
cs.cartCache = optionals.CartCache
cs.placeOrderService = optionals.PlaceOrderService
}
}
// GetCartReceiverService returns the injected cart receiver service
func (cs *CartService) GetCartReceiverService() *CartReceiverService {
return cs.cartReceiverService
}
// ValidateCart validates a carts content
func (cs *CartService) ValidateCart(ctx context.Context, session *web.Session, decoratedCart *decorator.DecoratedCart) validation.Result {
if cs.cartValidator != nil {
result := cs.cartValidator.Validate(ctx, session, decoratedCart)
return result
}
return validation.Result{}
}
// ValidateCurrentCart validates the current active cart
func (cs *CartService) ValidateCurrentCart(ctx context.Context, session *web.Session) (validation.Result, error) {
decoratedCart, err := cs.cartReceiverService.ViewDecoratedCart(ctx, session)
if err != nil {
return validation.Result{}, err
}
return cs.ValidateCart(ctx, session, decoratedCart), nil
}
// UpdatePaymentSelection updates the paymentselection in the cart
func (cs *CartService) UpdatePaymentSelection(ctx context.Context, session *web.Session, paymentSelection cartDomain.PaymentSelection) error {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return err
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.dispatchAllEvents(ctx, defers)
}()
cart, defers, err = behaviour.UpdatePaymentSelection(ctx, cart, paymentSelection)
if err != nil {
cs.handleCartNotFound(session, err)
cs.logger.WithContext(ctx).WithField("subCategory", "UpdatePaymentSelection").Error(err)
return err
}
return nil
}
// UpdateBillingAddress updates the billing address on the cart
func (cs *CartService) UpdateBillingAddress(ctx context.Context, session *web.Session, billingAddress *cartDomain.Address) error {
if billingAddress == nil {
return nil
}
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return err
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.dispatchAllEvents(ctx, defers)
}()
cart, defers, err = behaviour.UpdateBillingAddress(ctx, cart, *billingAddress)
if err != nil {
cs.handleCartNotFound(session, err)
cs.logger.WithContext(ctx).WithField("subCategory", "UpdateBillingAddress").Error(err)
return err
}
return nil
}
// UpdateDeliveryInfo updates the delivery info on the cart
func (cs *CartService) UpdateDeliveryInfo(ctx context.Context, session *web.Session, deliveryCode string, deliveryInfo cartDomain.DeliveryInfoUpdateCommand) error {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return err
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.dispatchAllEvents(ctx, defers)
}()
if deliveryCode == "" {
deliveryCode = cs.defaultDeliveryCode
}
cart, defers, err = behaviour.UpdateDeliveryInfo(ctx, cart, deliveryCode, deliveryInfo)
if err != nil {
cs.handleCartNotFound(session, err)
cs.logger.WithContext(ctx).WithField("subCategory", "UpdateDeliveryInfo").Error(err)
return err
}
return nil
}
// UpdatePurchaser updates the purchaser on the cart
func (cs *CartService) UpdatePurchaser(ctx context.Context, session *web.Session, purchaser *cartDomain.Person, additionalData *cartDomain.AdditionalData) error {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return err
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.dispatchAllEvents(ctx, defers)
}()
cart, defers, err = behaviour.UpdatePurchaser(ctx, cart, purchaser, additionalData)
if err != nil {
cs.handleCartNotFound(session, err)
cs.logger.WithContext(ctx).WithField("subCategory", "UpdatePurchaser").Error(err)
return err
}
return nil
}
// UpdateItemQty updates a single cart item qty
func (cs *CartService) UpdateItemQty(ctx context.Context, session *web.Session, itemID string, deliveryCode string, qty int) error {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return err
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.dispatchAllEvents(ctx, defers)
}()
if deliveryCode == "" {
deliveryCode = cs.defaultDeliveryCode
}
item, err := cart.GetByItemID(itemID)
if err != nil {
cs.logger.WithContext(ctx).WithField("subCategory", "UpdateItemQty").Error(err)
return err
}
qtyBefore := item.Qty
if qty < 1 {
return cs.DeleteItem(ctx, session, itemID, deliveryCode)
}
product, err := cs.productService.Get(ctx, item.MarketplaceCode)
if err != nil {
cs.logger.WithContext(ctx).WithField("subCategory", "UpdateItemQty").Error(err)
return err
}
product, err = cs.getProductWithActiveVariantIfProductIsConfigurable(ctx, product, item.VariantMarketPlaceCode)
if err != nil {
return err
}
err = cs.checkProductQtyRestrictions(ctx, session, product, cart, qty-qtyBefore, deliveryCode, itemID)
if err != nil {
cs.logger.WithContext(ctx).WithField("subCategory", "UpdateItemQty").Info(err)
return err
}
itemUpdate := cartDomain.ItemUpdateCommand{
Qty: &qty,
ItemID: itemID,
AdditionalData: nil,
}
cart, defers, err = behaviour.UpdateItem(ctx, cart, itemUpdate)
if err != nil {
cs.handleCartNotFound(session, err)
cs.logger.WithContext(ctx).WithField("subCategory", "UpdateItemQty").Error(err)
return err
}
// append deferred events of behaviour with changed qty event
updateEvent := &events.ChangedQtyInCartEvent{
Cart: cart,
CartID: cart.ID,
MarketplaceCode: item.MarketplaceCode,
VariantMarketplaceCode: item.VariantMarketPlaceCode,
ProductName: product.TeaserData().ShortTitle,
QtyBefore: qtyBefore,
QtyAfter: qty,
}
defers = append(defers, updateEvent)
return nil
}
// UpdateItemSourceID updates an item source id
func (cs *CartService) UpdateItemSourceID(ctx context.Context, session *web.Session, itemID string, sourceID string) error {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return err
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.dispatchAllEvents(ctx, defers)
}()
_, err = cart.GetByItemID(itemID)
if err != nil {
cs.logger.WithContext(ctx).WithField("subCategory", "UpdateItemSourceId").Error(err)
return err
}
itemUpdate := cartDomain.ItemUpdateCommand{
SourceID: &sourceID,
ItemID: itemID,
}
cart, defers, err = behaviour.UpdateItem(ctx, cart, itemUpdate)
if err != nil {
cs.handleCartNotFound(session, err)
cs.logger.WithContext(ctx).WithField("subCategory", "UpdateItemSourceId").Error(err)
return err
}
return nil
}
// UpdateItems updates multiple items
func (cs *CartService) UpdateItems(ctx context.Context, session *web.Session, updateCommands []cartDomain.ItemUpdateCommand) error {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return err
}
for _, command := range updateCommands {
_, err := cart.GetByItemID(command.ItemID)
if err != nil {
return err
}
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.dispatchAllEvents(ctx, defers)
}()
cart, defers, err = behaviour.UpdateItems(ctx, cart, updateCommands)
if err != nil {
cs.handleCartNotFound(session, err)
cs.logger.WithContext(ctx).WithField("subCategory", "UpdateItemSourceId").Error(err)
return err
}
return nil
}
// DeleteItem in current cart
func (cs *CartService) DeleteItem(ctx context.Context, session *web.Session, itemID string, deliveryCode string) error {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return err
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.handleEmptyDelivery(ctx, session, cart, deliveryCode)
cs.dispatchAllEvents(ctx, defers)
}()
if deliveryCode == "" {
deliveryCode = cs.defaultDeliveryCode
}
item, err := cart.GetByItemID(itemID)
if err != nil {
cs.logger.WithContext(ctx).WithField("subCategory", "DeleteItem").Error(err)
return err
}
qtyBefore := item.Qty
cart, defers, err = behaviour.DeleteItem(ctx, cart, itemID, deliveryCode)
if err != nil {
cs.handleCartNotFound(session, err)
cs.logger.WithContext(ctx).WithField("subCategory", "DeleteItem").Error(errors.Wrap(err, "Trying to delete SKU :"+item.MarketplaceCode))
return err
}
// append deferred events of behaviour with changed qty event
updateEvent := &events.ChangedQtyInCartEvent{
Cart: cart,
CartID: cart.ID,
MarketplaceCode: item.MarketplaceCode,
VariantMarketplaceCode: item.VariantMarketPlaceCode,
ProductName: item.ProductName,
QtyBefore: qtyBefore,
QtyAfter: 0,
}
defers = append(defers, updateEvent)
return nil
}
// DeleteAllItems in current cart
func (cs *CartService) DeleteAllItems(ctx context.Context, session *web.Session) error {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return err
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
var deleteItemEvents cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.dispatchAllEvents(ctx, defers)
}()
// we throw a qty changed event for every item in delivery
for _, delivery := range cart.Deliveries {
for _, item := range delivery.Cartitems {
updateEvent := &events.ChangedQtyInCartEvent{
Cart: cart,
CartID: cart.ID,
MarketplaceCode: item.MarketplaceCode,
VariantMarketplaceCode: item.VariantMarketPlaceCode,
ProductName: item.ProductName,
QtyBefore: item.Qty,
QtyAfter: 0,
}
deleteItemEvents = append(deleteItemEvents, updateEvent)
cart, defers, err = behaviour.DeleteItem(ctx, cart, item.ID, delivery.DeliveryInfo.Code)
if err != nil {
cs.handleCartNotFound(session, err)
cs.logger.WithContext(ctx).WithField("subCategory", "DeleteAllItems").Error(err)
return err
}
}
}
// append deferred events of behaviour with changed qty events
defers = append(defers, deleteItemEvents)
return nil
}
// CompleteCurrentCart and remove from cache
func (cs *CartService) CompleteCurrentCart(ctx context.Context) (*cartDomain.Cart, error) {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, web.SessionFromContext(ctx))
if err != nil {
return nil, err
}
// dispatch potential events
var defers cartDomain.DeferEvents
defer func() {
cs.dispatchAllEvents(ctx, defers)
}()
completeBehaviour, ok := behaviour.(cartDomain.CompleteBehaviour)
if !ok {
return nil, fmt.Errorf("not supported by used cart behaviour: %T", behaviour)
}
var completedCart *cartDomain.Cart
completedCart, defers, err = completeBehaviour.Complete(ctx, cart)
if err != nil {
cs.handleCartNotFound(web.SessionFromContext(ctx), err)
cs.logger.WithContext(ctx).WithField(flamingo.LogKeySubCategory, "CloseCurrentCart").Error(err)
return nil, err
}
cs.DeleteCartInCache(ctx, web.SessionFromContext(ctx), nil)
session := web.SessionFromContext(ctx)
if !cart.BelongsToAuthenticatedUser {
session.Delete(GuestCartSessionKey)
}
return completedCart, nil
}
// RestoreCart and cache
func (cs *CartService) RestoreCart(ctx context.Context, cart *cartDomain.Cart) (*cartDomain.Cart, error) {
session := web.SessionFromContext(ctx)
behaviour, err := cs.cartReceiverService.ModifyBehaviour(ctx)
if err != nil {
return nil, err
}
completeBehaviour, ok := behaviour.(cartDomain.CompleteBehaviour)
if !ok {
return nil, fmt.Errorf("not supported by used cart behaviour: %T", behaviour)
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
var restoredCart *cartDomain.Cart
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, restoredCart)
cs.dispatchAllEvents(ctx, defers)
}()
restoredCart, defers, err = completeBehaviour.Restore(ctx, cart)
if err != nil {
cs.handleCartNotFound(web.SessionFromContext(ctx), err)
cs.logger.WithContext(ctx).WithField(flamingo.LogKeySubCategory, "RestoreCart").Error(err)
return nil, err
}
if !restoredCart.BelongsToAuthenticatedUser {
session.Store(GuestCartSessionKey, restoredCart.ID)
}
return restoredCart, nil
}
// Clean current cart
func (cs *CartService) Clean(ctx context.Context, session *web.Session) error {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return err
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
var deleteItemEvents cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.dispatchAllEvents(ctx, defers)
}()
// we throw a qty changed event for every item of each delivery
for _, delivery := range cart.Deliveries {
for _, item := range delivery.Cartitems {
updateEvent := &events.ChangedQtyInCartEvent{
Cart: cart,
CartID: cart.ID,
MarketplaceCode: item.MarketplaceCode,
VariantMarketplaceCode: item.VariantMarketPlaceCode,
ProductName: item.ProductName,
QtyBefore: item.Qty,
QtyAfter: 0,
}
deleteItemEvents = append(deleteItemEvents, updateEvent)
}
}
cart, defers, err = behaviour.CleanCart(ctx, cart)
if err != nil {
cs.logger.WithContext(ctx).WithField("subCategory", "DeleteAllItems").Error(err)
return err
}
// append deferred events of behaviour with changed qty events for every deleted item
defers = append(defers, deleteItemEvents)
return nil
}
// DeleteDelivery in current cart
func (cs *CartService) DeleteDelivery(ctx context.Context, session *web.Session, deliveryCode string) (*cartDomain.Cart, error) {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return nil, err
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
var deleteItemEvents cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.dispatchAllEvents(ctx, defers)
}()
delivery, found := cart.GetDeliveryByCode(deliveryCode)
if !found {
return nil, errors.New("delivery not found: " + deliveryCode)
}
// we throw a qty changed event for every item in delivery// we throw a qty changed event for every item in delivery
for _, item := range delivery.Cartitems {
updateEvent := &events.ChangedQtyInCartEvent{
Cart: cart,
CartID: cart.ID,
MarketplaceCode: item.MarketplaceCode,
VariantMarketplaceCode: item.VariantMarketPlaceCode,
ProductName: item.ProductName,
QtyBefore: item.Qty,
QtyAfter: 0,
}
deleteItemEvents = append(deleteItemEvents, updateEvent)
}
cart, defers, err = behaviour.CleanDelivery(ctx, cart, deliveryCode)
if err != nil {
cs.logger.WithContext(ctx).WithField("subCategory", "DeleteAllItems").Error(err)
return nil, err
}
// append deferred events of behaviour with changed qty events for every deleted item
defers = append(defers, deleteItemEvents)
return cart, nil
}
// BuildAddRequest Helper to build
func (cs *CartService) BuildAddRequest(_ context.Context, marketplaceCode string, variantMarketplaceCode string, qty int, additionalData map[string]string) cartDomain.AddRequest {
if qty < 0 {
qty = 0
}
return cartDomain.AddRequest{
MarketplaceCode: marketplaceCode,
Qty: qty,
VariantMarketplaceCode: variantMarketplaceCode,
AdditionalData: additionalData,
}
}
// AddProduct adds a product to the cart
func (cs *CartService) AddProduct(ctx context.Context, session *web.Session, deliveryCode string, addRequest cartDomain.AddRequest) (productDomain.BasicProduct, error) {
if deliveryCode == "" {
deliveryCode = cs.defaultDeliveryCode
}
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
cs.logger.WithContext(ctx).WithField(flamingo.LogKeySubCategory, "AddProduct").Error(err)
return nil, err
}
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.handleEmptyDelivery(ctx, session, cart, deliveryCode)
cs.dispatchAllEvents(ctx, defers)
}()
addRequest, product, err := cs.checkProductForAddRequest(ctx, session, cart, deliveryCode, addRequest)
switch err.(type) {
case nil:
case *validation.AddToCartNotAllowed:
cs.logger.WithContext(ctx).WithField(flamingo.LogKeySubCategory, "AddProduct").Info(err)
return nil, err
default:
cs.logger.WithContext(ctx).WithField(flamingo.LogKeySubCategory, "AddProduct").Warn(err)
return nil, err
}
cs.logger.WithContext(ctx).WithField(flamingo.LogKeySubCategory, "AddProduct").Debug(fmt.Sprintf("AddRequest received %#v / %v", addRequest, deliveryCode))
cart, err = cs.CreateInitialDeliveryIfNotPresent(ctx, session, deliveryCode)
if err != nil {
cs.logger.WithContext(ctx).WithField(flamingo.LogKeySubCategory, "AddProduct").Error(err)
return nil, err
}
err = cs.checkProductQtyRestrictions(ctx, session, product, cart, addRequest.Qty, deliveryCode, "")
if err != nil {
cs.logger.WithContext(ctx).WithField(flamingo.LogKeySubCategory, "AddProduct").Info(err)
return nil, err
}
cart, defers, err = behaviour.AddToCart(ctx, cart, deliveryCode, addRequest)
if err != nil {
cs.handleCartNotFound(session, err)
cs.logger.WithContext(ctx).WithField("subCategory", "AddProduct").Error(err)
return nil, err
}
// append deferred events of behaviour with add to cart event
addToCart := &events.AddToCartEvent{
Cart: cart,
MarketplaceCode: addRequest.MarketplaceCode,
VariantMarketplaceCode: addRequest.VariantMarketplaceCode,
ProductName: product.TeaserData().ShortTitle,
Qty: addRequest.Qty,
}
defers = append(defers, addToCart)
return product, nil
}
// CreateInitialDeliveryIfNotPresent creates the initial delivery
func (cs *CartService) CreateInitialDeliveryIfNotPresent(ctx context.Context, session *web.Session, deliveryCode string) (*cartDomain.Cart, error) {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return nil, err
}
if cart.HasDeliveryForCode(deliveryCode) {
return cart, nil
}
delInfo, err := cs.deliveryInfoBuilder.BuildByDeliveryCode(deliveryCode)
if err != nil {
return nil, err
}
updateCommand := cartDomain.DeliveryInfoUpdateCommand{
DeliveryInfo: *delInfo,
}
updatedCart, defers, err := behaviour.UpdateDeliveryInfo(ctx, cart, deliveryCode, updateCommand)
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, updatedCart)
cs.dispatchAllEvents(ctx, defers)
}()
return updatedCart, err
}
// GetInitialDelivery - calls the registered deliveryInfoBuilder to get the initial values for a Delivery based on the given code
func (cs *CartService) GetInitialDelivery(deliveryCode string) (*cartDomain.DeliveryInfo, error) {
return cs.deliveryInfoBuilder.BuildByDeliveryCode(deliveryCode)
}
// ApplyVoucher applies a voucher to the cart
func (cs *CartService) ApplyVoucher(ctx context.Context, session *web.Session, couponCode string) (*cartDomain.Cart, error) {
cart, behaviour, err := cs.getCartAndBehaviour(ctx, session, "ApplyVoucher")
if err != nil {
return nil, err
}
return cs.executeVoucherBehaviour(ctx, session, cart, couponCode, behaviour.ApplyVoucher)
}
// ApplyAny applies a voucher or giftcard to the cart
func (cs *CartService) ApplyAny(ctx context.Context, session *web.Session, anyCode string) (*cartDomain.Cart, error) {
cart, behaviour, err := cs.getCartAndBehaviour(ctx, session, "ApplyAny")
if err != nil {
return nil, err
}
if giftCardAndVoucherBehaviour, ok := behaviour.(cartDomain.GiftCardAndVoucherBehaviour); ok {
return cs.executeVoucherBehaviour(ctx, session, cart, anyCode, giftCardAndVoucherBehaviour.ApplyAny)
}
return nil, errors.New("ApplyAny not supported")
}
// RemoveVoucher removes a voucher from the cart
func (cs *CartService) RemoveVoucher(ctx context.Context, session *web.Session, couponCode string) (*cartDomain.Cart, error) {
cart, behaviour, err := cs.getCartAndBehaviour(ctx, session, "RemoveVoucher")
if err != nil {
return nil, err
}
return cs.executeVoucherBehaviour(ctx, session, cart, couponCode, behaviour.RemoveVoucher)
}
// ApplyGiftCard adds a giftcard to the cart
func (cs *CartService) ApplyGiftCard(ctx context.Context, session *web.Session, couponCode string) (*cartDomain.Cart, error) {
cart, behaviour, err := cs.getCartAndBehaviour(ctx, session, "ApplyGiftCard")
if err != nil {
return nil, err
}
if giftCartBehaviour, ok := behaviour.(cartDomain.GiftCardBehaviour); ok {
return cs.executeVoucherBehaviour(ctx, session, cart, couponCode, giftCartBehaviour.ApplyGiftCard)
}
return nil, errors.New("ApplyGiftCard not supported")
}
// RemoveGiftCard removes a giftcard from the cart
func (cs *CartService) RemoveGiftCard(ctx context.Context, session *web.Session, couponCode string) (*cartDomain.Cart, error) {
cart, behaviour, err := cs.getCartAndBehaviour(ctx, session, "RemoveGiftCard")
if err != nil {
return nil, err
}
if giftCartBehaviour, ok := behaviour.(cartDomain.GiftCardBehaviour); ok {
return cs.executeVoucherBehaviour(ctx, session, cart, couponCode, giftCartBehaviour.RemoveGiftCard)
}
return nil, errors.New("RemoveGiftCard not supported")
}
// Get current cart from session and corresponding behaviour
func (cs *CartService) getCartAndBehaviour(ctx context.Context, session *web.Session, logKey string) (*cartDomain.Cart, cartDomain.ModifyBehaviour, error) {
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
cs.logger.WithContext(ctx).WithField(flamingo.LogKeySubCategory, logKey).Error(err)
return nil, nil, err
}
return cart, behaviour, nil
}
// Executes provided behaviour regarding vouchers, this function serves to reduce duplicated code
// for voucher / giftcard behaviour as their internal logic is basically the same
func (cs *CartService) executeVoucherBehaviour(ctx context.Context, session *web.Session, cart *cartDomain.Cart, couponCode string, fn promotionFunc) (*cartDomain.Cart, error) {
// cart cache must be updated - with the current value of cart
var defers cartDomain.DeferEvents
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.dispatchAllEvents(ctx, defers)
}()
cart, defers, err := fn(ctx, cart, couponCode)
return cart, err
}
func (cs *CartService) handleCartNotFound(session *web.Session, err error) {
if err == cartDomain.ErrCartNotFound {
_ = cs.DeleteSavedSessionGuestCartID(session)
}
}
// checkProductForAddRequest existence and validate with productService
func (cs *CartService) checkProductForAddRequest(ctx context.Context, session *web.Session, cart *cartDomain.Cart, deliveryCode string, addRequest cartDomain.AddRequest) (cartDomain.AddRequest, productDomain.BasicProduct, error) {
product, err := cs.productService.Get(ctx, addRequest.MarketplaceCode)
if err != nil {
return addRequest, nil, err
}
if product.Type() == productDomain.TypeConfigurable {
if addRequest.VariantMarketplaceCode == "" {
return addRequest, nil, errors.New("no variant given for configurable product")
}
configurableProduct := product.(productDomain.ConfigurableProduct)
if !configurableProduct.HasVariant(addRequest.VariantMarketplaceCode) {
return addRequest, nil, errors.New("product has not the given variant")
}
product, err = configurableProduct.GetConfigurableWithActiveVariant(addRequest.VariantMarketplaceCode)
if err != nil {
return addRequest, nil, err
}
}
// Now Validate the Item with the optional registered ItemValidator
if cs.itemValidator != nil {
decoratedCart, _ := cs.cartReceiverService.DecorateCart(ctx, cart)
return addRequest, product, cs.itemValidator.Validate(ctx, session, decoratedCart, deliveryCode, addRequest, product)
}
return addRequest, product, nil
}
func (cs *CartService) checkProductQtyRestrictions(ctx context.Context, sess *web.Session, product productDomain.BasicProduct, cart *cartDomain.Cart, qtyToCheck int, deliveryCode string, itemID string) error {
restrictionResult := cs.restrictionService.RestrictQty(ctx, sess, product, cart, deliveryCode)
if restrictionResult.IsRestricted {
if qtyToCheck > restrictionResult.RemainingDifference {
return &RestrictionError{
message: fmt.Sprintf("Can't update item quantity, product max quantity of %d would be exceeded. Restrictor: %v", restrictionResult.MaxAllowed, restrictionResult.RestrictorName),
CartItemID: itemID,
RestrictionResult: *restrictionResult,
}
}
}
return nil
}
func (cs *CartService) updateCartInCacheIfCacheIsEnabled(ctx context.Context, session *web.Session, cart *cartDomain.Cart) {
if cs.cartCache != nil && cart != nil {
id, err := cs.cartCache.BuildIdentifier(ctx, session)
if err != nil {
return
}
if cart.BelongsToAuthenticatedUser != id.IsCustomerCart {
cs.logger.WithContext(ctx).Error(fmt.Sprintf("Request to cache a cart with wrong idendifier. Cart BelongsToAuthenticatedUser: %v / CacheIdendifier: %v", cart.BelongsToAuthenticatedUser, id.IsCustomerCart))
return
}
err = cs.cartCache.CacheCart(ctx, session, id, cart)
if err != nil {
cs.logger.WithContext(ctx).Error("Error while caching cart: %v", err)
}
}
}
// DeleteCartInCache removes the cart from cache
func (cs *CartService) DeleteCartInCache(ctx context.Context, session *web.Session, _ *cartDomain.Cart) {
if cs.cartCache != nil {
id, err := cs.cartCache.BuildIdentifier(ctx, session)
if err != nil {
return
}
err = cs.cartCache.Delete(ctx, session, id)
if err == ErrNoCacheEntry {
cs.logger.WithContext(ctx).Info("Cart in cache not found: %v", err)
return
}
if err != nil {
cs.logger.WithContext(ctx).Error("Error while deleting cart in cache: %v", err)
}
}
}
// ReserveOrderIDAndSave reserves order id by using the PlaceOrder behaviour, sets and saves it on the cart.
// If the cart already holds a reserved order id no set/save is performed and the existing cart is returned.
// You may want to use this before proceeding with payment to ensure having a useful reference in the payment processing
func (cs *CartService) ReserveOrderIDAndSave(ctx context.Context, session *web.Session) (*cartDomain.Cart, error) {
return cs.reserveOrderIDAndSave(ctx, session, false)
}
// ForceReserveOrderIDAndSave reserves order id by using the PlaceOrder behaviour, sets and saves it on the cart.
// Each call of this method reserves a new order ID, even if it is already set on the cart.
// You may want to use this before proceeding with payment to ensure having a useful reference in the payment processing
func (cs *CartService) ForceReserveOrderIDAndSave(ctx context.Context, session *web.Session) (*cartDomain.Cart, error) {
return cs.reserveOrderIDAndSave(ctx, session, true)
}
func (cs *CartService) reserveOrderIDAndSave(ctx context.Context, session *web.Session, force bool) (*cartDomain.Cart, error) {
if cs.placeOrderService == nil {
return nil, errors.New("No placeOrderService registered")
}
cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return nil, err
}
// the cart already has a reserved order id - no need to generate and update data, if force parameter is true
// a new reserved order id will always be generated
if !force && cart.AdditionalData.ReservedOrderID != "" {
return cart, nil
}
reservedOrderID, err := cs.placeOrderService.ReserveOrderID(ctx, cart)
if err != nil {
cs.logger.WithContext(ctx).Debug("Reserve order id:", reservedOrderID)
return nil, err
}
additionalData := cart.AdditionalData
additionalData.ReservedOrderID = reservedOrderID
cart, defers, err := behaviour.UpdateAdditionalData(ctx, cart, &additionalData)
defer func() {
cs.updateCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.dispatchAllEvents(ctx, defers)
}()
return cart, err
}
// PlaceOrderWithCart converts the given cart with payments into orders by calling the Service
func (cs *CartService) PlaceOrderWithCart(ctx context.Context, session *web.Session, cart *cartDomain.Cart, payment *placeorder.Payment) (placeorder.PlacedOrderInfos, error) {
return cs.placeOrder(ctx, session, cart, payment)
}
// PlaceOrder converts the cart (possibly cached) with payments into orders by calling the Service
func (cs *CartService) PlaceOrder(ctx context.Context, session *web.Session, payment *placeorder.Payment) (placeorder.PlacedOrderInfos, error) {
cart, _, err := cs.cartReceiverService.GetCart(ctx, session)
if err != nil {
return nil, err
}
return cs.placeOrder(ctx, session, cart, payment)
}
func (cs *CartService) placeOrder(ctx context.Context, session *web.Session, cart *cartDomain.Cart, payment *placeorder.Payment) (placeorder.PlacedOrderInfos, error) {
if cs.placeOrderService == nil {
return nil, errors.New("No placeOrderService registered")
}
var placeOrderInfos placeorder.PlacedOrderInfos
var errPlaceOrder error
identity := cs.webIdentityService.Identify(ctx, web.RequestFromContext(ctx))
if identity != nil {
placeOrderInfos, errPlaceOrder = cs.placeOrderService.PlaceCustomerCart(ctx, identity, cart, payment)
} else {