forked from i-love-flamingo/flamingo-commerce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cartReceiver.go
380 lines (307 loc) · 12.4 KB
/
cartReceiver.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
package application
import (
"context"
"errors"
"flamingo.me/flamingo/v3/core/auth"
"flamingo.me/flamingo/v3/framework/web"
"flamingo.me/flamingo/v3/framework/flamingo"
"github.com/lunarforge/flamingo_commerce/cart/domain/cart"
cartDomain "github.com/lunarforge/flamingo_commerce/cart/domain/cart"
"github.com/lunarforge/flamingo_commerce/cart/domain/decorator"
"github.com/lunarforge/flamingo_commerce/customer/application"
)
type (
//CartReceiverService provides methods to get the correct cart
CartReceiverService struct {
guestCartService cartDomain.GuestCartService
customerCartService cartDomain.CustomerCartService
cartDecoratorFactory *decorator.DecoratedCartFactory
webIdentityService *auth.WebIdentityService
eventRouter flamingo.EventRouter
logger flamingo.Logger
// CartCache is optional
cartCache CartCache
}
)
var (
//ErrTemporaryCartService - should be returned if it is likely that the backend service will return a cart on a next try
ErrTemporaryCartService = errors.New("the cart could not be received currently - try again later")
)
const (
// GuestCartSessionKey is a prefix
GuestCartSessionKey = "cart.guestid"
)
// Inject the dependencies
func (cs *CartReceiverService) Inject(
guestCartService cartDomain.GuestCartService,
customerCartService cartDomain.CustomerCartService,
cartDecoratorFactory *decorator.DecoratedCartFactory,
webIdentityService *auth.WebIdentityService,
logger flamingo.Logger,
eventRouter flamingo.EventRouter,
optionals *struct {
CartCache CartCache `inject:",optional"`
},
) {
cs.guestCartService = guestCartService
cs.customerCartService = customerCartService
cs.cartDecoratorFactory = cartDecoratorFactory
cs.webIdentityService = webIdentityService
cs.logger = logger.WithField("module", "cart").WithField(flamingo.LogKeyCategory, "checkout.cartreceiver")
cs.eventRouter = eventRouter
if optionals != nil {
cs.cartCache = optionals.CartCache
}
}
// RestoreCart restores a previously used guest / customer cart
// deprecated: use CartService.RestoreCart(), ensure that your cart implements the CompleteBehaviour
func (cs *CartReceiverService) RestoreCart(ctx context.Context, session *web.Session, cartToRestore cart.Cart) (*cartDomain.Cart, error) {
identitiy := cs.webIdentityService.Identify(ctx, web.RequestFromContext(ctx))
if identitiy != nil {
restoredCart, err := cs.customerCartService.RestoreCart(ctx, identitiy, cartToRestore)
if err != nil {
return nil, err
}
cs.storeCartInCacheIfCacheIsEnabled(ctx, session, restoredCart)
return restoredCart, nil
}
restoredCart, err := cs.guestCartService.RestoreCart(ctx, cartToRestore)
if err != nil {
return nil, err
}
session.Store(GuestCartSessionKey, restoredCart.ID)
cs.storeCartInCacheIfCacheIsEnabled(ctx, session, restoredCart)
return restoredCart, nil
}
// ShouldHaveCart - checks if there should be a cart. Indicated if a call to GetCart should return a real cart
func (cs *CartReceiverService) ShouldHaveCart(ctx context.Context, session *web.Session) bool {
if cs.webIdentityService.Identify(ctx, web.RequestFromContext(ctx)) != nil {
return true
}
return cs.ShouldHaveGuestCart(session)
}
// ShouldHaveGuestCart - checks if there should be guest cart
func (cs *CartReceiverService) ShouldHaveGuestCart(session *web.Session) bool {
_, ok := session.Load(GuestCartSessionKey)
return ok
}
// ViewDecoratedCart return a Cart for view
func (cs *CartReceiverService) ViewDecoratedCart(ctx context.Context, session *web.Session) (*decorator.DecoratedCart, error) {
cart, err := cs.ViewCart(ctx, session)
if err != nil {
return nil, err
}
return cs.DecorateCart(ctx, cart)
}
// ViewDecoratedCartWithoutCache return a Cart for view
func (cs *CartReceiverService) ViewDecoratedCartWithoutCache(ctx context.Context, session *web.Session) (*decorator.DecoratedCart, error) {
cart, err := cs.GetCartWithoutCache(ctx, session)
if err != nil {
return nil, err
}
return cs.DecorateCart(ctx, cart)
}
// ViewCart return a Cart for view
func (cs *CartReceiverService) ViewCart(ctx context.Context, session *web.Session) (*cartDomain.Cart, error) {
if cs.ShouldHaveCart(ctx, session) {
cart, _, err := cs.GetCart(ctx, session)
if err != nil {
return cs.getEmptyCart(), err
}
return cart, nil
}
return cs.getEmptyCart(), nil
}
func (cs *CartReceiverService) storeCartInCacheIfCacheIsEnabled(ctx context.Context, session *web.Session, cart *cartDomain.Cart) error {
if cs.cartCache == nil {
return errors.New("no cache")
}
id, err := cs.cartCache.BuildIdentifier(ctx, session)
if err != nil {
return err
}
return cs.cartCache.CacheCart(ctx, session, id, cart)
}
// GetCart Get the correct Cart (either Guest or User)
func (cs *CartReceiverService) GetCart(ctx context.Context, session *web.Session) (*cartDomain.Cart, cartDomain.ModifyBehaviour, error) {
if cs.webIdentityService.Identify(ctx, web.RequestFromContext(ctx)) != nil {
return cs.getCustomerCart(ctx, session)
}
if cs.ShouldHaveGuestCart(session) {
return cs.getExistingGuestCart(ctx, session)
}
return cs.getNewGuestCart(ctx, session)
}
// ModifyBehaviour returns the correct behaviour to modify the cart for the current user (guest/customer)
func (cs *CartReceiverService) ModifyBehaviour(ctx context.Context) (cartDomain.ModifyBehaviour, error) {
identity := cs.webIdentityService.Identify(ctx, web.RequestFromContext(ctx))
if identity != nil {
return cs.customerCartService.GetModifyBehaviour(ctx, identity)
}
return cs.guestCartService.GetModifyBehaviour(ctx)
}
// getCustomerCart
func (cs *CartReceiverService) getCustomerCart(ctx context.Context, session *web.Session) (*cartDomain.Cart, cartDomain.ModifyBehaviour, error) {
cart, found, err := cs.getCartFromCacheIfCacheIsEnabled(ctx, session)
switch err {
case nil:
case ErrCacheIsInvalid, ErrNoCacheEntry:
cs.logger.WithContext(ctx).Info(err)
default:
cs.logger.WithContext(ctx).Error(err)
}
identitiy := cs.webIdentityService.Identify(ctx, web.RequestFromContext(ctx))
if identitiy == nil {
return nil, nil, application.ErrNoIdentity
}
if !found {
cart, err = cs.customerCartService.GetCart(ctx, identitiy, "me")
if err != nil {
return nil, nil, err
}
_ = cs.storeCartInCacheIfCacheIsEnabled(ctx, session, cart)
}
behaviour, err := cs.customerCartService.GetModifyBehaviour(ctx, identitiy)
if err != nil {
return nil, nil, err
}
return cart, behaviour, nil
}
func (cs *CartReceiverService) getCartFromCacheIfCacheIsEnabled(ctx context.Context, session *web.Session) (*cartDomain.Cart, bool, error) {
if cs.cartCache == nil {
return nil, false, nil
}
cacheID, err := cs.cartCache.BuildIdentifier(ctx, session)
if err != nil {
return nil, false, err
}
cs.logger.WithContext(ctx).Debug("query cart cache %#v", cacheID)
cart, cacheErr := cs.cartCache.GetCart(ctx, session, cacheID)
if cacheErr == ErrNoCacheEntry {
return nil, false, nil
}
if cacheErr != nil {
return nil, false, cacheErr
}
return cart, true, nil
}
// getExistingGuestCart
func (cs *CartReceiverService) getExistingGuestCart(ctx context.Context, session *web.Session) (*cartDomain.Cart, cartDomain.ModifyBehaviour, error) {
cart, found, err := cs.getCartFromCacheIfCacheIsEnabled(ctx, session)
if err != nil {
if err == ErrCacheIsInvalid {
cs.logger.WithContext(ctx).Info(err)
} else if err == ErrNoCacheEntry {
cs.logger.WithContext(ctx).Info(err)
} else {
cs.logger.WithContext(ctx).Error(err)
}
}
if err != nil || !found {
cart, err = cs.getSessionGuestCart(ctx, session)
if err != nil {
//TODO - decide on recoverable errors (where we should communicate "try again" / and not recoverable (where we should clean up guest cart in session and try to get a new one)
cs.logger.WithContext(ctx).Warn("cart.application.cartservice: GetCart - No cart in session return empty")
//delete(ctx.Session().Values, "cart.guestid")
return nil, nil, ErrTemporaryCartService
}
_ = cs.storeCartInCacheIfCacheIsEnabled(ctx, session, cart)
cs.logger.WithContext(ctx).Debug("guestcart not in cache - requested and passed to cache")
}
behaviour, err := cs.guestCartService.GetModifyBehaviour(ctx)
if err != nil {
return nil, nil, err
}
if cart == nil {
cs.logger.WithContext(ctx).Error("Something unexpected went wrong! No guestcart!")
return nil, nil, errors.New("something unexpected went wrong - no guestcart")
}
return cart, behaviour, nil
}
// getNewGuestCart
func (cs *CartReceiverService) getNewGuestCart(ctx context.Context, session *web.Session) (*cartDomain.Cart, cartDomain.ModifyBehaviour, error) {
guestCart, err := cs.guestCartService.GetNewCart(ctx)
if err != nil {
cs.logger.WithContext(ctx).Error("cart.application.cartservice: Cannot create a new guest cart. Error %s", err)
return nil, nil, err
}
cs.logger.WithContext(ctx).Info("cart.application.cartservice: Requested new Guestcart %v", guestCart)
session.Store(GuestCartSessionKey, guestCart.ID)
_ = cs.storeCartInCacheIfCacheIsEnabled(ctx, session, guestCart)
behaviour, err := cs.guestCartService.GetModifyBehaviour(ctx)
if err != nil {
return guestCart, nil, err
}
if guestCart == nil {
cs.logger.WithContext(ctx).Error("Something unexpected went wrong! No guestcart!")
return nil, nil, errors.New("something unexpected went wrong - no guestcart")
}
return guestCart, behaviour, nil
}
// GetCartWithoutCache - forces to get the cart without cache
func (cs *CartReceiverService) GetCartWithoutCache(ctx context.Context, session *web.Session) (*cartDomain.Cart, error) {
// Invalidate cart cache
if cs.eventRouter != nil {
cs.eventRouter.Dispatch(ctx, &cart.InvalidateCartEvent{Session: session})
}
identitiy := cs.webIdentityService.Identify(ctx, web.RequestFromContext(ctx))
if identitiy != nil {
return cs.customerCartService.GetCart(ctx, identitiy, "me")
}
if cs.ShouldHaveGuestCart(session) {
return cs.getSessionGuestCart(ctx, session)
}
return cs.guestCartService.GetNewCart(ctx)
}
// ViewGuestCart try to get the guest Cart - even if the user is logged in
func (cs *CartReceiverService) ViewGuestCart(ctx context.Context, session *web.Session) (*cartDomain.Cart, error) {
if cs.ShouldHaveGuestCart(session) {
guestCart, err := cs.getSessionGuestCart(ctx, session)
if err != nil {
//TODO - decide on recoverable errors (where we should communicate "try again" / and not recoverable (where we should clean up guest cart in session and try to get a new one)
cs.logger.WithContext(ctx).Warn("cart.application.cartservice: GetCart - No cart in session return empty")
return nil, ErrTemporaryCartService
}
return guestCart, nil
}
return cs.getEmptyCart(), nil
}
// DeleteSavedSessionGuestCartID deletes a guest cart Key from the Session Values
func (cs *CartService) DeleteSavedSessionGuestCartID(session *web.Session) error {
session.Delete(GuestCartSessionKey)
//TODO - trigger backend also to be able to delete the cart there ( cs.GuestCartService.DeleteCart())
return nil
}
// getSessionGuestCart
func (cs *CartReceiverService) getSessionGuestCart(ctx context.Context, session *web.Session) (*cartDomain.Cart, error) {
if guestcartid, ok := session.Load(GuestCartSessionKey); ok {
existingCart, err := cs.guestCartService.GetCart(ctx, guestcartid.(string))
if err != nil {
cs.logger.WithContext(ctx).Warn("cart.application.cartservice: Guestcart id in session cannot be retrieved. Id %s, Error: %s", guestcartid, err)
// we seem to have an erratic session cart - remove it
session.Delete(GuestCartSessionKey)
}
return existingCart, err
}
cs.logger.WithContext(ctx).Error("No cart in session yet - getSessionGuestCart should be called only if HasSssionGuestCart returns true")
return nil, errors.New("no cart in session yet")
}
// DecorateCart Get the correct Cart
func (cs *CartReceiverService) DecorateCart(ctx context.Context, cart *cartDomain.Cart) (*decorator.DecoratedCart, error) {
if cart == nil {
return nil, errors.New("no cart given")
}
cs.logger.WithContext(ctx).Debug("cart.application.cartservice: Get decorated cart ")
return cs.cartDecoratorFactory.Create(ctx, *cart), nil
}
// GetDecoratedCart Get the correct Cart
func (cs *CartReceiverService) GetDecoratedCart(ctx context.Context, session *web.Session) (*decorator.DecoratedCart, cartDomain.ModifyBehaviour, error) {
cart, behaviour, err := cs.GetCart(ctx, session)
if err != nil {
return nil, nil, err
}
return cs.cartDecoratorFactory.Create(ctx, *cart), behaviour, nil
}
func (cs *CartReceiverService) getEmptyCart() *cartDomain.Cart {
return &cartDomain.Cart{}
}