-
Notifications
You must be signed in to change notification settings - Fork 400
/
ShoppingCartValidator.cs
643 lines (546 loc) · 26 KB
/
ShoppingCartValidator.cs
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
using Smartstore.Core.Catalog.Attributes;
using Smartstore.Core.Catalog.Products;
using Smartstore.Core.Checkout.Attributes;
using Smartstore.Core.Checkout.GiftCards;
using Smartstore.Core.Common.Services;
using Smartstore.Core.Data;
using Smartstore.Core.Identity;
using Smartstore.Core.Localization;
using Smartstore.Core.Security;
using Smartstore.Core.Stores;
namespace Smartstore.Core.Checkout.Cart
{
/// <summary>
/// Shopping cart validation methods.
/// </summary>
public partial class ShoppingCartValidator : IShoppingCartValidator
{
private readonly SmartDbContext _db;
private readonly IAclService _aclService;
private readonly IWorkContext _workContext;
private readonly IStoreContext _storeContext;
private readonly ICurrencyService _currencyService;
private readonly ShoppingCartSettings _cartSettings;
private readonly IPermissionService _permissionService;
private readonly IStoreMappingService _storeMappingService;
private readonly ILocalizationService _localizationService;
private readonly IProductAttributeMaterializer _productAttributeMaterializer;
private readonly ICheckoutAttributeMaterializer _checkoutAttributeMaterializer;
public ShoppingCartValidator(
SmartDbContext db,
IAclService aclService,
IWorkContext workContext,
IStoreContext storeContext,
ICurrencyService currencyService,
ShoppingCartSettings cartSettings,
IPermissionService permissionService,
IStoreMappingService storeMappingService,
ILocalizationService localizationService,
IProductAttributeMaterializer productAttributeMaterializer,
ICheckoutAttributeMaterializer checkoutAttributeMaterializer)
{
_db = db;
_aclService = aclService;
_workContext = workContext;
_storeContext = storeContext;
_currencyService = currencyService;
_cartSettings = cartSettings;
_permissionService = permissionService;
_storeMappingService = storeMappingService;
_localizationService = localizationService;
_productAttributeMaterializer = productAttributeMaterializer;
_checkoutAttributeMaterializer = checkoutAttributeMaterializer;
}
public Localizer T { get; set; } = NullLocalizer.Instance;
public virtual async Task<bool> ValidateAccessPermissionsAsync(Customer customer, ShoppingCartType cartType, IList<string> warnings)
{
Guard.NotNull(customer);
Guard.NotNull(warnings);
var isValid = true;
// Validate access permissions
if (cartType == ShoppingCartType.ShoppingCart
&& !await _permissionService.AuthorizeAsync(Permissions.Cart.AccessShoppingCart, customer))
{
isValid = false;
warnings.Add(T("ShoppingCart.IsDisabled"));
}
else if (cartType == ShoppingCartType.Wishlist
&& !await _permissionService.AuthorizeAsync(Permissions.Cart.AccessWishlist, customer))
{
isValid = false;
warnings.Add(T("Wishlist.IsDisabled"));
}
return isValid;
}
public virtual bool ValidateBundleItem(ProductBundleItem bundleItem, IList<string> warnings)
{
Guard.NotNull(bundleItem);
Guard.NotNull(warnings);
var currentWarnings = new List<string>();
var name = bundleItem.GetLocalizedName();
if (!bundleItem.Published)
{
currentWarnings.Add(T("ShoppingCart.Bundle.BundleItemUnpublished", name));
}
if (bundleItem.ProductId == 0
|| bundleItem.Product == null
|| bundleItem.BundleProductId == 0
|| bundleItem.BundleProduct == null)
{
currentWarnings.Add(T("ShoppingCart.Bundle.MissingProduct", name));
}
if (bundleItem.Quantity <= 0)
{
currentWarnings.Add(T("ShoppingCart.Bundle.Quantity", name));
}
if (bundleItem.Product.IsDownload || bundleItem.Product.IsRecurring)
{
currentWarnings.Add(T("ShoppingCart.Bundle.ProductResrictions", name));
}
warnings.AddRange(currentWarnings);
return !currentWarnings.Any();
}
public virtual async Task<bool> ValidateCartAsync(ShoppingCart cart, IList<string> warnings, bool validateCheckoutAttributes = false)
{
Guard.NotNull(cart);
Guard.NotNull(warnings);
var currentWarnings = new List<string>();
var missingProduct = cart.Items.Where(x => x.Item.Product is null).FirstOrDefault();
if (missingProduct != null)
{
currentWarnings.Add(T("ShoppingCart.CannotLoadProduct", missingProduct.Item.ProductId));
}
var hasNonRecurringProducts = cart.IncludesMatchingItems(x => !x.IsRecurring);
var hasRecurringProducts = cart.IncludesMatchingItems(x => x.IsRecurring);
// Do not mix recurring and non-recurring products
if (hasNonRecurringProducts && hasRecurringProducts)
{
currentWarnings.Add(T("ShoppingCart.CannotMixStandardAndAutoshipProducts"));
}
// Validate recurring products
if (hasRecurringProducts)
{
var recurringCycleInfo = cart.GetRecurringCycleInfo(_localizationService);
if (recurringCycleInfo.ErrorMessage.HasValue())
{
currentWarnings.Add(recurringCycleInfo.ErrorMessage);
}
}
// Validate checkout attributes if defined.
if (validateCheckoutAttributes)
{
var checkoutAttributes = cart?.Customer?.GenericAttributes?.CheckoutAttributes;
if (checkoutAttributes != null)
{
var existingAttributesQuery = _db.CheckoutAttributes.ApplyStoreFilter(_storeContext.CurrentStore.Id);
if (!cart.IsShippingRequired())
{
// No shipping required. Filter attributes which require shippable products.
existingAttributesQuery = existingAttributesQuery.Where(x => !x.ShippableProductRequired);
}
var selectedAttributes = await _checkoutAttributeMaterializer.MaterializeCheckoutAttributesAsync(checkoutAttributes);
var notSelectedAttributes = await existingAttributesQuery
.Where(x => x.IsRequired && !selectedAttributes.Contains(x))
.ToListAsync();
// Check for not selected attributes.
foreach (var attribute in notSelectedAttributes)
{
if (attribute.IsActive)
{
var textPrompt = attribute.TextPrompt.IsEmpty() ? attribute.GetLocalized(x => x.Name) : attribute.GetLocalized(x => x.TextPrompt);
currentWarnings.Add(T("ShoppingCart.SelectAttribute", textPrompt));
}
}
}
}
warnings.AddRange(currentWarnings);
return !currentWarnings.Any();
}
public virtual async Task<bool> ValidateAddToCartItemAsync(AddToCartContext ctx, ShoppingCartItem cartItem, IEnumerable<OrganizedShoppingCartItem> cartItems)
{
Guard.NotNull(ctx);
Guard.NotNull(cartItem);
Guard.NotNull(cartItems);
var warnings = new List<string>();
await ValidateProductAsync(cartItem, cartItems, warnings, ctx.StoreId);
await this.ValidateProductAttributesAsync(cartItem, cartItems, warnings);
ValidateGiftCardInfo(cartItem.Product, cartItem.AttributeSelection, warnings);
// Bundle and bundle items (child items) warnings.
if (ctx.BundleItem != null || !ctx.ChildItems.IsNullOrEmpty())
{
var bundleItem = ctx.BundleItem ?? ctx.ChildItems.Select(x => x.BundleItem).FirstOrDefault();
if (bundleItem != null)
{
ValidateBundleItem(bundleItem, warnings);
}
}
ctx.Warnings.AddRange(warnings);
return !warnings.Any();
}
public virtual bool ValidateItemsMaximumCartQuantity(ShoppingCartType cartType, int cartItemsCount, IList<string> warnings)
{
Guard.NotNull(warnings);
var isValid = true;
if (cartType == ShoppingCartType.ShoppingCart && cartItemsCount >= _cartSettings.MaximumShoppingCartItems)
{
isValid = false;
warnings.Add(T("ShoppingCart.MaximumShoppingCartItems"));
}
else if (cartType == ShoppingCartType.Wishlist && cartItemsCount >= _cartSettings.MaximumWishlistItems)
{
isValid = false;
warnings.Add(T("ShoppingCart.MaximumWishlistItems"));
}
return isValid;
}
public virtual bool ValidateGiftCardInfo(Product product, ProductVariantAttributeSelection selection, IList<string> warnings)
{
Guard.NotNull(product);
Guard.NotNull(selection);
Guard.NotNull(warnings);
if (!product.IsGiftCard)
{
return true;
}
var currentWarnings = new List<string>();
var giftCardInfo = selection.GetGiftCardInfo();
var recipientName = giftCardInfo?.RecipientName;
var recipientEmail = giftCardInfo?.RecipientEmail;
var senderName = giftCardInfo?.SenderName;
var senderEmail = giftCardInfo?.SenderEmail;
if (recipientName.IsEmpty())
{
currentWarnings.Add(T("ShoppingCart.RecipientNameError"));
}
if (senderName.IsEmpty())
{
currentWarnings.Add(T("ShoppingCart.SenderNameError"));
}
if (product.GiftCardType == GiftCardType.Virtual)
{
if (!recipientEmail.IsEmail())
{
currentWarnings.Add(T("ShoppingCart.RecipientEmailError"));
}
if (!senderEmail.IsEmail())
{
currentWarnings.Add(T("ShoppingCart.SenderEmailError"));
}
}
warnings.AddRange(currentWarnings);
return !currentWarnings.Any();
}
public virtual async Task<bool> ValidateProductAsync(
ShoppingCartItem cartItem,
IEnumerable<OrganizedShoppingCartItem> cartItems,
IList<string> warnings,
int? storeId = null,
int? quantity = null)
{
Guard.NotNull(cartItem);
Guard.NotNull(warnings);
var p = cartItem.Product;
if (p == null)
{
warnings.Add(T("Products.NotFound", cartItem.ProductId));
return false;
}
if (p.Deleted)
{
warnings.Add(T("ShoppingCart.ProductDeleted"));
return false;
}
var currentWarnings = new List<string>();
// Grouped products are not available for order
if (p.ProductType == ProductType.GroupedProduct)
{
currentWarnings.Add(T("ShoppingCart.ProductNotAvailableForOrder"));
}
// Validate product bundle, no customer entered price allowed
if (p.ProductType == ProductType.BundledProduct
&& p.BundlePerItemPricing
&& cartItem.CustomerEnteredPrice != decimal.Zero)
{
currentWarnings.Add(T("ShoppingCart.Bundle.NoCustomerEnteredPrice"));
}
// Not published or no permissions for customer or store
if (!p.Published
|| !await _aclService.AuthorizeAsync(p, cartItem.Customer)
|| !await _storeMappingService.AuthorizeAsync(p, storeId ?? _storeContext.CurrentStore.Id))
{
currentWarnings.Add(T("ShoppingCart.ProductUnpublished"));
}
// Disabled buy button
if (cartItem.ShoppingCartType == ShoppingCartType.ShoppingCart && p.DisableBuyButton)
{
currentWarnings.Add(T("ShoppingCart.BuyingDisabled"));
}
// Disabled wishlist button
if (cartItem.ShoppingCartType == ShoppingCartType.Wishlist && p.DisableWishlistButton)
{
currentWarnings.Add(T("ShoppingCart.WishlistDisabled"));
}
// Call for price
if (cartItem.ShoppingCartType == ShoppingCartType.ShoppingCart && p.CallForPrice)
{
currentWarnings.Add(T("Products.CallForPrice"));
}
// Customer entered price
if (p.CustomerEntersPrice &&
(cartItem.CustomerEnteredPrice < p.MinimumCustomerEnteredPrice
|| cartItem.CustomerEnteredPrice > p.MaximumCustomerEnteredPrice))
{
var min = _currencyService.ConvertToWorkingCurrency(p.MinimumCustomerEnteredPrice);
var max = _currencyService.ConvertToWorkingCurrency(p.MaximumCustomerEnteredPrice);
currentWarnings.Add(T("ShoppingCart.CustomerEnteredPrice.RangeError", min, max));
}
// Quantity validation
var hasQuantityWarnings = false;
var quantityToValidate = quantity ?? cartItem.Quantity;
if (quantityToValidate <= 0)
{
currentWarnings.Add(T("ShoppingCart.QuantityShouldPositive"));
hasQuantityWarnings = true;
}
if (quantityToValidate < p.OrderMinimumQuantity)
{
currentWarnings.Add(T("ShoppingCart.MinimumQuantity", p.OrderMinimumQuantity));
hasQuantityWarnings = true;
}
if (quantityToValidate > p.OrderMaximumQuantity)
{
currentWarnings.Add(T("ShoppingCart.MaximumQuantity", p.OrderMaximumQuantity));
hasQuantityWarnings = true;
}
var allowedQuantities = p.ParseAllowedQuantities();
if (allowedQuantities.Length > 0 && !allowedQuantities.Contains(quantityToValidate))
{
currentWarnings.Add(T("ShoppingCart.AllowedQuantities", string.Join(", ", allowedQuantities)));
}
// Stock validation
var validateStock = cartItem.ShoppingCartType == ShoppingCartType.ShoppingCart || !_cartSettings.AllowOutOfStockItemsToBeAddedToWishlist;
if (validateStock && !hasQuantityWarnings)
{
if (p.ManageInventoryMethod == ManageInventoryMethod.ManageStock && p.BackorderMode == BackorderMode.NoBackorders)
{
// INFO: bundles with per-item-pricing are always added in single positions (see ShoppingCart.FindItemInCart).
if (cartItems != null
&& (_cartSettings.AddProductsToBasketInSinglePositions || (p.ProductType == ProductType.BundledProduct && p.BundlePerItemPricing)))
{
quantityToValidate += cartItems
.Select(x => x.Item)
.Where(x => x.ProductId == p.Id && x.ParentItemId == null)
.Sum(x => x.Quantity);
}
if (p.StockQuantity < quantityToValidate)
{
currentWarnings.Add(p.StockQuantity > 0
? T("ShoppingCart.QuantityExceedsStock", p.StockQuantity)
: T("ShoppingCart.OutOfStock"));
}
}
else if (p.ManageInventoryMethod == ManageInventoryMethod.ManageStockByAttributes)
{
var combination = await _productAttributeMaterializer.FindAttributeCombinationAsync(p.Id, cartItem.AttributeSelection);
if (combination != null && !combination.AllowOutOfStockOrders)
{
if (cartItems != null && _cartSettings.AddProductsToBasketInSinglePositions)
{
quantityToValidate += cartItems
.Select(x => x.Item)
.Where(x => x.ProductId == p.Id && x.ParentItemId == null && x.AttributeSelection.Equals(cartItem.AttributeSelection))
.Sum(x => x.Quantity);
}
if (combination.StockQuantity < quantityToValidate)
{
currentWarnings.Add(combination.StockQuantity > 0
? T("ShoppingCart.QuantityExceedsStock", combination.StockQuantity)
: T("ShoppingCart.OutOfStock"));
}
}
}
}
// Validate availability
var invalidStartDate = false;
if (p.AvailableStartDateTimeUtc.HasValue)
{
var availableStartDate = DateTime.SpecifyKind(p.AvailableStartDateTimeUtc.Value, DateTimeKind.Utc);
if (availableStartDate.CompareTo(DateTime.UtcNow) > 0)
{
currentWarnings.Add(T("ShoppingCart.NotAvailable"));
invalidStartDate = true;
}
}
if (p.AvailableEndDateTimeUtc.HasValue && !invalidStartDate)
{
var availableEndDate = DateTime.SpecifyKind(p.AvailableEndDateTimeUtc.Value, DateTimeKind.Utc);
if (availableEndDate.CompareTo(DateTime.UtcNow) < 0)
{
currentWarnings.Add(T("ShoppingCart.NotAvailable"));
}
}
warnings.AddRange(currentWarnings);
return !currentWarnings.Any();
}
public virtual async Task<bool> ValidateProductAttributesAsync(
Product product,
ProductVariantAttributeSelection selection,
int storeId,
IList<string> warnings,
int quantity = 1,
Customer customer = null,
ProductBundleItem bundleItem = null,
ShoppingCartType cartType = ShoppingCartType.ShoppingCart,
IEnumerable<OrganizedShoppingCartItem> cartItems = null)
{
customer ??= _workContext.CurrentCustomer;
cartItems ??= Enumerable.Empty<OrganizedShoppingCartItem>();
var currentWarnings = new List<string>();
// Check if the product is a bundle. Since bundles have no attributes, the customer has nothing to select.
if (product.ProductType == ProductType.BundledProduct ||
(bundleItem?.BundleProduct != null && !bundleItem.BundleProduct.BundlePerItemPricing))
{
if (selection.AttributesMap.Any())
{
warnings.Add(T("ShoppingCart.Bundle.NoAttributes"));
}
return true;
}
// Get selected product variant attributes and check for product errors.
var selectedAttributes = await _productAttributeMaterializer.MaterializeProductVariantAttributesAsync(selection);
foreach (var attribute in selectedAttributes)
{
if (attribute.Product == null || attribute.Product.Id != product.Id)
{
warnings.Add(T("ShoppingCart.AttributeError"));
return false;
}
}
await _db.LoadCollectionAsync(product, x => x.ProductVariantAttributes, false, q => q.Include(x => x.ProductAttribute));
// Get existing product variant attributes.
foreach (var existingAttribute in product.ProductVariantAttributes)
{
if (!existingAttribute.IsRequired)
{
continue;
}
var found = false;
foreach (var attribute in selectedAttributes)
{
if (attribute.Id == existingAttribute.Id)
{
var values = selection.GetAttributeValues(attribute.Id) ?? Enumerable.Empty<object>();
foreach (var value in values)
{
var strValue = value?.ToString().EmptyNull();
if (strValue.HasValue())
{
found = true;
break;
}
}
if (found)
{
break;
}
}
}
if (!found &&
(bundleItem?.FilterAttributes ?? false) &&
!bundleItem.AttributeFilters.Any(x => x.AttributeId == existingAttribute.ProductAttributeId))
{
// Attribute is filtered out by bundle item. It cannot be selected by the customer.
found = true;
}
if (!found)
{
var prompt = existingAttribute.TextPrompt.NullEmpty() ?? existingAttribute.ProductAttribute.GetLocalized(x => x.Name);
currentWarnings.Add(T("ShoppingCart.SelectAttribute", prompt));
}
}
if (currentWarnings.Any())
{
warnings.AddRange(currentWarnings);
return false;
}
// Checks whether there is an active selected attribute combination.
var combination = await _productAttributeMaterializer.FindAttributeCombinationAsync(product.Id, selection);
if (combination != null && !combination.IsActive)
{
currentWarnings.Add(T("ShoppingCart.NotAvailable"));
}
var attributeValues = await _productAttributeMaterializer.MaterializeProductVariantAttributeValuesAsync(selection);
var productLinkageValues = attributeValues
.Where(x => x.ValueType == ProductVariantAttributeValueType.ProductLinkage)
.ToArray();
var linkedProductIds = productLinkageValues
.Select(x => x.LinkedProductId)
.Where(x => x != 0)
.Distinct()
.ToArray();
var linkedProducts = linkedProductIds.Any()
? await _db.Products.AsNoTracking().Where(x => linkedProductIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id)
: new Dictionary<int, Product>();
// Validate each linked product, create shopping cart item from linked product and run validation.
foreach (var value in productLinkageValues)
{
if (linkedProducts.TryGetValue(value.LinkedProductId, out var linkedProduct))
{
var item = new ShoppingCartItem
{
ProductId = linkedProduct.Id,
Product = linkedProduct,
ShoppingCartType = cartType,
Customer = customer,
StoreId = storeId,
Quantity = quantity * value.Quantity
};
var ctx = new AddToCartContext
{
Product = linkedProduct,
Customer = customer,
CartType = cartType,
StoreId = storeId,
Quantity = quantity * value.Quantity
};
// Get product linkage warnings.
await ValidateAddToCartItemAsync(ctx, item, cartItems);
foreach (var linkageWarning in ctx.Warnings)
{
currentWarnings.Add(T("ShoppingCart.ProductLinkageAttributeWarning",
value.ProductVariantAttribute.ProductAttribute.GetLocalized(x => x.Name),
value.GetLocalized(x => x.Name),
linkageWarning));
}
}
else
{
currentWarnings.Add(T("ShoppingCart.ProductLinkageProductNotLoading", value.LinkedProductId));
}
}
warnings.AddRange(currentWarnings);
return !currentWarnings.Any();
}
public virtual async Task<bool> ValidateRequiredProductsAsync(Product product, IEnumerable<OrganizedShoppingCartItem> cartItems, IList<string> warnings)
{
Guard.NotNull(product);
if (!product.RequireOtherProducts)
return true;
var requiredProductIds = product.ParseRequiredProductIds();
if (!requiredProductIds.Any())
return true;
var cartProductIds = cartItems.Select(x => x.Item.Product.Id);
var missingRequiredProductIds = requiredProductIds.Except(cartProductIds);
if (!missingRequiredProductIds.Any())
return true;
var isValid = true;
var missingRequiredProducts = await _db.Products.GetManyAsync(missingRequiredProductIds);
foreach (var requiredProduct in missingRequiredProducts)
{
isValid = false;
warnings.Add(T("ShoppingCart.RequiredProductWarning", requiredProduct.GetLocalized(x => x.Name)));
}
return isValid;
}
}
}