/
ProductService.cs
2513 lines (2162 loc) · 112 KB
/
ProductService.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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Discounts;
using Nop.Core.Domain.Localization;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Shipping;
using Nop.Core.Infrastructure;
using Nop.Data;
using Nop.Services.Customers;
using Nop.Services.Localization;
using Nop.Services.Messages;
using Nop.Services.Security;
using Nop.Services.Shipping.Date;
using Nop.Services.Stores;
namespace Nop.Services.Catalog
{
/// <summary>
/// Product service
/// </summary>
public partial class ProductService : IProductService
{
#region Fields
protected readonly CatalogSettings _catalogSettings;
protected readonly CommonSettings _commonSettings;
protected readonly IAclService _aclService;
protected readonly ICustomerService _customerService;
protected readonly IDateRangeService _dateRangeService;
protected readonly ILanguageService _languageService;
protected readonly ILocalizationService _localizationService;
protected readonly IProductAttributeParser _productAttributeParser;
protected readonly IProductAttributeService _productAttributeService;
protected readonly IRepository<CrossSellProduct> _crossSellProductRepository;
protected readonly IRepository<DiscountProductMapping> _discountProductMappingRepository;
protected readonly IRepository<LocalizedProperty> _localizedPropertyRepository;
protected readonly IRepository<Product> _productRepository;
protected readonly IRepository<ProductAttributeCombination> _productAttributeCombinationRepository;
protected readonly IRepository<ProductAttributeMapping> _productAttributeMappingRepository;
protected readonly IRepository<ProductCategory> _productCategoryRepository;
protected readonly IRepository<ProductManufacturer> _productManufacturerRepository;
protected readonly IRepository<ProductPicture> _productPictureRepository;
protected readonly IRepository<ProductProductTagMapping> _productTagMappingRepository;
protected readonly IRepository<ProductReview> _productReviewRepository;
protected readonly IRepository<ProductReviewHelpfulness> _productReviewHelpfulnessRepository;
protected readonly IRepository<ProductSpecificationAttribute> _productSpecificationAttributeRepository;
protected readonly IRepository<ProductTag> _productTagRepository;
protected readonly IRepository<ProductWarehouseInventory> _productWarehouseInventoryRepository;
protected readonly IRepository<RelatedProduct> _relatedProductRepository;
protected readonly IRepository<Shipment> _shipmentRepository;
protected readonly IRepository<StockQuantityHistory> _stockQuantityHistoryRepository;
protected readonly IRepository<TierPrice> _tierPriceRepository;
protected readonly IRepository<Warehouse> _warehouseRepository;
protected readonly IStaticCacheManager _staticCacheManager;
protected readonly IStoreMappingService _storeMappingService;
protected readonly IStoreService _storeService;
protected readonly IWorkContext _workContext;
protected readonly LocalizationSettings _localizationSettings;
#endregion
#region Ctor
public ProductService(CatalogSettings catalogSettings,
CommonSettings commonSettings,
IAclService aclService,
ICustomerService customerService,
IDateRangeService dateRangeService,
ILanguageService languageService,
ILocalizationService localizationService,
IProductAttributeParser productAttributeParser,
IProductAttributeService productAttributeService,
IRepository<CrossSellProduct> crossSellProductRepository,
IRepository<DiscountProductMapping> discountProductMappingRepository,
IRepository<LocalizedProperty> localizedPropertyRepository,
IRepository<Product> productRepository,
IRepository<ProductAttributeCombination> productAttributeCombinationRepository,
IRepository<ProductAttributeMapping> productAttributeMappingRepository,
IRepository<ProductCategory> productCategoryRepository,
IRepository<ProductManufacturer> productManufacturerRepository,
IRepository<ProductPicture> productPictureRepository,
IRepository<ProductProductTagMapping> productTagMappingRepository,
IRepository<ProductReview> productReviewRepository,
IRepository<ProductReviewHelpfulness> productReviewHelpfulnessRepository,
IRepository<ProductSpecificationAttribute> productSpecificationAttributeRepository,
IRepository<ProductTag> productTagRepository,
IRepository<ProductWarehouseInventory> productWarehouseInventoryRepository,
IRepository<RelatedProduct> relatedProductRepository,
IRepository<Shipment> shipmentRepository,
IRepository<StockQuantityHistory> stockQuantityHistoryRepository,
IRepository<TierPrice> tierPriceRepository,
IRepository<Warehouse> warehouseRepository,
IStaticCacheManager staticCacheManager,
IStoreService storeService,
IStoreMappingService storeMappingService,
IWorkContext workContext,
LocalizationSettings localizationSettings)
{
_catalogSettings = catalogSettings;
_commonSettings = commonSettings;
_aclService = aclService;
_customerService = customerService;
_dateRangeService = dateRangeService;
_languageService = languageService;
_localizationService = localizationService;
_productAttributeParser = productAttributeParser;
_productAttributeService = productAttributeService;
_crossSellProductRepository = crossSellProductRepository;
_discountProductMappingRepository = discountProductMappingRepository;
_localizedPropertyRepository = localizedPropertyRepository;
_productRepository = productRepository;
_productAttributeCombinationRepository = productAttributeCombinationRepository;
_productAttributeMappingRepository = productAttributeMappingRepository;
_productCategoryRepository = productCategoryRepository;
_productManufacturerRepository = productManufacturerRepository;
_productPictureRepository = productPictureRepository;
_productTagMappingRepository = productTagMappingRepository;
_productReviewRepository = productReviewRepository;
_productReviewHelpfulnessRepository = productReviewHelpfulnessRepository;
_productSpecificationAttributeRepository = productSpecificationAttributeRepository;
_productTagRepository = productTagRepository;
_productWarehouseInventoryRepository = productWarehouseInventoryRepository;
_relatedProductRepository = relatedProductRepository;
_shipmentRepository = shipmentRepository;
_stockQuantityHistoryRepository = stockQuantityHistoryRepository;
_tierPriceRepository = tierPriceRepository;
_warehouseRepository = warehouseRepository;
_staticCacheManager = staticCacheManager;
_storeMappingService = storeMappingService;
_storeService = storeService;
_workContext = workContext;
_localizationSettings = localizationSettings;
}
#endregion
#region Utilities
/// <summary>
/// Applies the low stock activity to specified product by the total stock quantity
/// </summary>
/// <param name="product">Product</param>
/// <param name="totalStock">Total stock</param>
protected virtual async Task ApplyLowStockActivityAsync(Product product, int totalStock)
{
var stockDec = product.MinStockQuantity >= totalStock;
var stockInc = _catalogSettings.PublishBackProductWhenCancellingOrders && product.MinStockQuantity < totalStock;
switch (product.LowStockActivity)
{
case LowStockActivity.DisableBuyButton:
product.DisableBuyButton = stockDec && !stockInc;
product.DisableWishlistButton = stockDec && !stockInc;
await UpdateProductAsync(product);
break;
case LowStockActivity.Unpublish:
product.Published = !stockDec && stockInc;
await UpdateProductAsync(product);
break;
default:
break;
}
}
/// <summary>
/// Gets SKU, Manufacturer part number and GTIN
/// </summary>
/// <param name="product">Product</param>
/// <param name="attributesXml">Attributes in XML format</param>
/// <returns>SKU, Manufacturer part number, GTIN</returns>
protected virtual async Task<(string sku, string manufacturerPartNumber, string gtin)> GetSkuMpnGtinAsync(Product product, string attributesXml)
{
if (product == null)
throw new ArgumentNullException(nameof(product));
string sku = null;
string manufacturerPartNumber = null;
string gtin = null;
if (!string.IsNullOrEmpty(attributesXml) &&
product.ManageInventoryMethod == ManageInventoryMethod.ManageStockByAttributes)
{
//manage stock by attribute combinations
//let's find appropriate record
var combination = await _productAttributeParser.FindProductAttributeCombinationAsync(product, attributesXml);
if (combination != null)
{
sku = combination.Sku;
manufacturerPartNumber = combination.ManufacturerPartNumber;
gtin = combination.Gtin;
}
}
if (string.IsNullOrEmpty(sku))
sku = product.Sku;
if (string.IsNullOrEmpty(manufacturerPartNumber))
manufacturerPartNumber = product.ManufacturerPartNumber;
if (string.IsNullOrEmpty(gtin))
gtin = product.Gtin;
return (sku, manufacturerPartNumber, gtin);
}
/// <summary>
/// Get stock message
/// </summary>
/// <param name="product">Product</param>
/// <param name="attributesXml">Attributes in XML format</param>
/// <returns>Message</returns>
protected virtual async Task<string> GeStockMessageAsync(Product product, string attributesXml)
{
if (!product.DisplayStockAvailability)
return string.Empty;
string stockMessage;
var combination = await _productAttributeParser.FindProductAttributeCombinationAsync(product, attributesXml);
if (combination != null)
{
//combination exists
var stockQuantity = combination.StockQuantity;
if (stockQuantity > 0)
{
stockMessage = product.DisplayStockQuantity
?
//display "in stock" with stock quantity
string.Format(await _localizationService.GetResourceAsync("Products.Availability.InStockWithQuantity"), stockQuantity)
:
//display "in stock" without stock quantity
await _localizationService.GetResourceAsync("Products.Availability.InStock");
}
else if (combination.AllowOutOfStockOrders)
{
stockMessage = await _localizationService.GetResourceAsync("Products.Availability.InStock");
}
else
{
var productAvailabilityRange = await
_dateRangeService.GetProductAvailabilityRangeByIdAsync(product.ProductAvailabilityRangeId);
stockMessage = productAvailabilityRange == null
? await _localizationService.GetResourceAsync("Products.Availability.OutOfStock")
: string.Format(await _localizationService.GetResourceAsync("Products.Availability.AvailabilityRange"),
await _localizationService.GetLocalizedAsync(productAvailabilityRange, range => range.Name));
}
}
else
{
//no combination configured
if (product.AllowAddingOnlyExistingAttributeCombinations)
{
var productAvailabilityRange = await
_dateRangeService.GetProductAvailabilityRangeByIdAsync(product.ProductAvailabilityRangeId);
stockMessage = productAvailabilityRange == null
? await _localizationService.GetResourceAsync("Products.Availability.OutOfStock")
: string.Format(await _localizationService.GetResourceAsync("Products.Availability.AvailabilityRange"),
await _localizationService.GetLocalizedAsync(productAvailabilityRange, range => range.Name));
}
else
{
stockMessage = !(await _productAttributeService.GetProductAttributeMappingsByProductIdAsync(product.Id))
.Any(pam => pam.IsRequired) ? await _localizationService.GetResourceAsync("Products.Availability.InStock") : await _localizationService.GetResourceAsync("Products.Availability.SelectRequiredAttributes");
}
}
return stockMessage;
}
/// <summary>
/// Get stock message
/// </summary>
/// <param name="product">Product</param>
/// <param name="stockMessage">Message</param>
/// <returns>Message</returns>
protected virtual async Task<string> GetStockMessageAsync(Product product, string stockMessage)
{
if (!product.DisplayStockAvailability)
return string.Empty;
var stockQuantity = await GetTotalStockQuantityAsync(product);
if (stockQuantity > 0)
{
stockMessage = product.DisplayStockQuantity
?
//display "in stock" with stock quantity
string.Format(await _localizationService.GetResourceAsync("Products.Availability.InStockWithQuantity"), stockQuantity)
:
//display "in stock" without stock quantity
await _localizationService.GetResourceAsync("Products.Availability.InStock");
}
else
{
//out of stock
var productAvailabilityRange = await _dateRangeService.GetProductAvailabilityRangeByIdAsync(product.ProductAvailabilityRangeId);
switch (product.BackorderMode)
{
case BackorderMode.NoBackorders:
stockMessage = productAvailabilityRange == null
? await _localizationService.GetResourceAsync("Products.Availability.OutOfStock")
: string.Format(await _localizationService.GetResourceAsync("Products.Availability.AvailabilityRange"),
await _localizationService.GetLocalizedAsync(productAvailabilityRange, range => range.Name));
break;
case BackorderMode.AllowQtyBelow0:
stockMessage = await _localizationService.GetResourceAsync("Products.Availability.InStock");
break;
case BackorderMode.AllowQtyBelow0AndNotifyCustomer:
stockMessage = productAvailabilityRange == null
? await _localizationService.GetResourceAsync("Products.Availability.Backordering")
: string.Format(await _localizationService.GetResourceAsync("Products.Availability.BackorderingWithDate"),
await _localizationService.GetLocalizedAsync(productAvailabilityRange, range => range.Name));
break;
}
}
return stockMessage;
}
/// <summary>
/// Filter hidden entries according to constraints if any
/// </summary>
/// <param name="query">Query to filter</param>
/// <param name="storeId">A store identifier</param>
/// <param name="customerRolesIds">Identifiers of customer's roles</param>
/// <returns>Filtered query</returns>
protected virtual async Task<IQueryable<TEntity>> FilterHiddenEntriesAsync<TEntity>(IQueryable<TEntity> query,
int storeId, int[] customerRolesIds)
where TEntity : Product
{
//filter unpublished entries
query = query.Where(entry => entry.Published);
//apply store mapping constraints
if (!_catalogSettings.IgnoreStoreLimitations && await _storeMappingService.IsEntityMappingExistsAsync<TEntity>(storeId))
query = query.Where(_storeMappingService.ApplyStoreMapping<TEntity>(storeId));
//apply ACL constraints
if (!_catalogSettings.IgnoreAcl && await _aclService.IsEntityAclMappingExistAsync<TEntity>(customerRolesIds))
query = query.Where(_aclService.ApplyAcl<TEntity>(customerRolesIds));
return query;
}
/// <summary>
/// Reserve the given quantity in the warehouses.
/// </summary>
/// <param name="product">Product</param>
/// <param name="quantity">Quantity, must be negative</param>
protected virtual async Task ReserveInventoryAsync(Product product, int quantity)
{
if (product == null)
throw new ArgumentNullException(nameof(product));
if (quantity >= 0)
throw new ArgumentException("Value must be negative.", nameof(quantity));
var qty = -quantity;
var productInventory = _productWarehouseInventoryRepository.Table.Where(pwi => pwi.ProductId == product.Id)
.OrderByDescending(pwi => pwi.StockQuantity - pwi.ReservedQuantity)
.ToList();
if (productInventory.Count <= 0)
return;
// 1st pass: Applying reserved
foreach (var item in productInventory)
{
var selectQty = Math.Min(Math.Max(0, item.StockQuantity - item.ReservedQuantity), qty);
item.ReservedQuantity += selectQty;
qty -= selectQty;
if (qty <= 0)
break;
}
if (qty > 0)
{
// 2rd pass: Booking negative stock!
var pwi = productInventory[0];
pwi.ReservedQuantity += qty;
}
await UpdateProductWarehouseInventoryAsync(productInventory);
}
/// <summary>
/// Unblocks the given quantity reserved items in the warehouses
/// </summary>
/// <param name="product">Product</param>
/// <param name="quantity">Quantity, must be positive</param>
protected virtual async Task UnblockReservedInventoryAsync(Product product, int quantity)
{
if (product == null)
throw new ArgumentNullException(nameof(product));
if (quantity < 0)
throw new ArgumentException("Value must be positive.", nameof(quantity));
var productInventory = await _productWarehouseInventoryRepository.Table.Where(pwi => pwi.ProductId == product.Id)
.OrderByDescending(pwi => pwi.ReservedQuantity)
.ThenByDescending(pwi => pwi.StockQuantity)
.ToListAsync();
if (!productInventory.Any())
return;
var qty = quantity;
foreach (var item in productInventory)
{
var selectQty = Math.Min(item.ReservedQuantity, qty);
item.ReservedQuantity -= selectQty;
qty -= selectQty;
if (qty <= 0)
break;
}
if (qty > 0)
{
var pwi = productInventory[0];
pwi.StockQuantity += qty;
}
await UpdateProductWarehouseInventoryAsync(productInventory);
}
/// <summary>
/// Gets cross-sell products by product identifier
/// </summary>
/// <param name="productIds">The first product identifiers</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Cross-sell products</returns>
protected virtual async Task<IList<CrossSellProduct>> GetCrossSellProductsByProductIdsAsync(int[] productIds, bool showHidden = false)
{
if (productIds == null || productIds.Length == 0)
return new List<CrossSellProduct>();
var query = from csp in _crossSellProductRepository.Table
join p in _productRepository.Table on csp.ProductId2 equals p.Id
where productIds.Contains(csp.ProductId1) &&
!p.Deleted &&
(showHidden || p.Published)
orderby csp.Id
select csp;
var crossSellProducts = await query.ToListAsync();
return crossSellProducts;
}
/// <summary>
/// Gets ratio of useful and not useful product reviews
/// </summary>
/// <param name="productReview">Product review</param>
/// <returns>Result</returns>
protected virtual async Task<(int usefulCount, int notUsefulCount)> GetHelpfulnessCountsAsync(ProductReview productReview)
{
if (productReview is null)
throw new ArgumentNullException(nameof(productReview));
var productReviewHelpfulness = _productReviewHelpfulnessRepository.Table.Where(prh => prh.ProductReviewId == productReview.Id);
return (await productReviewHelpfulness.CountAsync(prh => prh.WasHelpful),
await productReviewHelpfulness.CountAsync(prh => !prh.WasHelpful));
}
/// <summary>
/// Inserts a product review helpfulness record
/// </summary>
/// <param name="productReviewHelpfulness">Product review helpfulness record</param>
protected virtual async Task InsertProductReviewHelpfulnessAsync(ProductReviewHelpfulness productReviewHelpfulness)
{
await _productReviewHelpfulnessRepository.InsertAsync(productReviewHelpfulness);
}
#endregion
#region Methods
#region Products
/// <summary>
/// Delete a product
/// </summary>
/// <param name="product">Product</param>
public virtual async Task DeleteProductAsync(Product product)
{
await _productRepository.DeleteAsync(product);
}
/// <summary>
/// Delete products
/// </summary>
/// <param name="products">Products</param>
public virtual async Task DeleteProductsAsync(IList<Product> products)
{
await _productRepository.DeleteAsync(products);
}
/// <summary>
/// Gets all products displayed on the home page
/// </summary>
/// <returns>Products</returns>
public virtual async Task<IList<Product>> GetAllProductsDisplayedOnHomepageAsync()
{
var products = await _productRepository.GetAllAsync(query =>
{
return from p in query
orderby p.DisplayOrder, p.Id
where p.Published &&
!p.Deleted &&
p.ShowOnHomepage
select p;
}, cache => cache.PrepareKeyForDefaultCache(NopCatalogDefaults.ProductsHomepageCacheKey));
return products;
}
/// <summary>
/// Gets product
/// </summary>
/// <param name="productId">Product identifier</param>
/// <returns>Product</returns>
public virtual async Task<Product> GetProductByIdAsync(int productId)
{
return await _productRepository.GetByIdAsync(productId, cache => default);
}
/// <summary>
/// Get products by identifiers
/// </summary>
/// <param name="productIds">Product identifiers</param>
/// <returns>Products</returns>
public virtual async Task<IList<Product>> GetProductsByIdsAsync(int[] productIds)
{
return await _productRepository.GetByIdsAsync(productIds, cache => default);
}
/// <summary>
/// Inserts a product
/// </summary>
/// <param name="product">Product</param>
public virtual async Task InsertProductAsync(Product product)
{
await _productRepository.InsertAsync(product);
}
/// <summary>
/// Updates the product
/// </summary>
/// <param name="product">Product</param>
public virtual async Task UpdateProductAsync(Product product)
{
await _productRepository.UpdateAsync(product);
}
/// <summary>
/// Gets featured products by a category identifier
/// </summary>
/// <param name="categoryId">Category identifier</param>
/// <param name="storeId">Store identifier; 0 if you want to get all records</param>
/// <returns>List of featured products</returns>
public virtual async Task<IList<Product>> GetCategoryFeaturedProductsAsync(int categoryId, int storeId = 0)
{
IList<Product> featuredProducts = new List<Product>();
if (categoryId == 0)
return featuredProducts;
var customer = await _workContext.GetCurrentCustomerAsync();
var customerRolesIds = await _customerService.GetCustomerRoleIdsAsync(customer);
var cacheKey = _staticCacheManager.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoryFeaturedProductsIdsKey, categoryId, customerRolesIds, storeId);
var featuredProductIds = await _staticCacheManager.GetAsync(cacheKey, async () =>
{
var query = from p in _productRepository.Table
join pc in _productCategoryRepository.Table on p.Id equals pc.ProductId
where !p.Deleted && p.VisibleIndividually &&
pc.IsFeaturedProduct && categoryId == pc.CategoryId
select p;
query = await FilterHiddenEntriesAsync(query, storeId, customerRolesIds);
featuredProducts = query.ToList();
return featuredProducts.Select(p => p.Id).ToList();
});
if (featuredProducts.Count == 0 && featuredProductIds.Count > 0)
featuredProducts = await _productRepository.GetByIdsAsync(featuredProductIds, cache => default);
return featuredProducts;
}
/// <summary>
/// Gets featured products by manufacturer identifier
/// </summary>
/// <param name="manufacturerId">Manufacturer identifier</param>
/// <param name="storeId">Store identifier; 0 if you want to get all records</param>
/// <returns>List of featured products</returns>
public virtual async Task<IList<Product>> GetManufacturerFeaturedProductsAsync(int manufacturerId, int storeId = 0)
{
IList<Product> featuredProducts = new List<Product>();
if (manufacturerId == 0)
return featuredProducts;
var customer = await _workContext.GetCurrentCustomerAsync();
var customerRolesIds = await _customerService.GetCustomerRoleIdsAsync(customer);
var cacheKey = _staticCacheManager.PrepareKeyForDefaultCache(NopCatalogDefaults.ManufacturerFeaturedProductIdsKey, manufacturerId, customerRolesIds, storeId);
var featuredProductIds = await _staticCacheManager.GetAsync(cacheKey, async () =>
{
var query = from p in _productRepository.Table
join pm in _productManufacturerRepository.Table on p.Id equals pm.ProductId
where !p.Deleted && p.VisibleIndividually &&
pm.IsFeaturedProduct && manufacturerId == pm.ManufacturerId
select p;
query = await FilterHiddenEntriesAsync(query, storeId, customerRolesIds);
featuredProducts = query.ToList();
return featuredProducts.Select(p => p.Id).ToList();
});
if (featuredProducts.Count == 0 && featuredProductIds.Count > 0)
featuredProducts = await _productRepository.GetByIdsAsync(featuredProductIds, cache => default);
return featuredProducts;
}
/// <summary>
/// Gets products which marked as new
/// </summary>
/// <param name="storeId">Store identifier; 0 if you want to get all records</param>
/// <returns>List of new products</returns>
public virtual async Task<IList<Product>> GetProductsMarkedAsNewAsync(int storeId = 0)
{
return await _productRepository.GetAllAsync(async query =>
{
var customer = await _workContext.GetCurrentCustomerAsync();
var customerRolesIds = await _customerService.GetCustomerRoleIdsAsync(customer);
query = await FilterHiddenEntriesAsync(query, storeId, customerRolesIds);
query = from p in query
where p.VisibleIndividually && p.MarkAsNew && !p.Deleted &&
LinqToDB.Sql.Between(DateTime.UtcNow, p.MarkAsNewStartDateTimeUtc ?? DateTime.MinValue, p.MarkAsNewEndDateTimeUtc ?? DateTime.MaxValue)
select p;
return query.Take(_catalogSettings.NewProductsNumber)
.OrderBy(ProductSortingEnum.CreatedOn);
});
}
/// <summary>
/// Get number of product (published and visible) in certain category
/// </summary>
/// <param name="categoryIds">Category identifiers</param>
/// <param name="storeId">Store identifier; 0 to load all records</param>
/// <returns>Number of products</returns>
public virtual async Task<int> GetNumberOfProductsInCategoryAsync(IList<int> categoryIds = null, int storeId = 0)
{
//validate "categoryIds" parameter
if (categoryIds != null && categoryIds.Contains(0))
categoryIds.Remove(0);
var customer = await _workContext.GetCurrentCustomerAsync();
var customerRolesIds = await _customerService.GetCustomerRoleIdsAsync(customer);
var query = _productRepository.Table;
query = await FilterHiddenEntriesAsync(query, storeId, customerRolesIds);
query = query.Where(p => !p.Deleted && p.VisibleIndividually);
//category filtering
if (categoryIds != null && categoryIds.Any())
{
query = from p in query
join pc in _productCategoryRepository.Table on p.Id equals pc.ProductId
where categoryIds.Contains(pc.CategoryId)
select p;
}
var cacheKey = _staticCacheManager
.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoryProductsNumberCacheKey, customerRolesIds, storeId, categoryIds);
//only distinct products
return await _staticCacheManager.GetAsync(cacheKey, () => query.Select(p => p.Id).Count());
}
/// <summary>
/// Search products
/// </summary>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="categoryIds">Category identifiers</param>
/// <param name="manufacturerId">Manufacturer identifier; 0 to load all records</param>
/// <param name="storeId">Store identifier; 0 to load all records</param>
/// <param name="vendorId">Vendor identifier; 0 to load all records</param>
/// <param name="warehouseId">Warehouse identifier; 0 to load all records</param>
/// <param name="productType">Product type; 0 to load all records</param>
/// <param name="visibleIndividuallyOnly">A values indicating whether to load only products marked as "visible individually"; "false" to load all records; "true" to load "visible individually" only</param>
/// <param name="excludeFeaturedProducts">A value indicating whether loaded products are marked as featured (relates only to categories and manufacturers); "false" (by default) to load all records; "true" to exclude featured products from results</param>
/// <param name="priceMin">Minimum price; null to load all records</param>
/// <param name="priceMax">Maximum price; null to load all records</param>
/// <param name="productTagId">Product tag identifier; 0 to load all records</param>
/// <param name="keywords">Keywords</param>
/// <param name="searchDescriptions">A value indicating whether to search by a specified "keyword" in product descriptions</param>
/// <param name="searchManufacturerPartNumber">A value indicating whether to search by a specified "keyword" in manufacturer part number</param>
/// <param name="searchSku">A value indicating whether to search by a specified "keyword" in product SKU</param>
/// <param name="searchProductTags">A value indicating whether to search by a specified "keyword" in product tags</param>
/// <param name="languageId">Language identifier (search for text searching)</param>
/// <param name="filteredSpecs">Filtered product specification identifiers</param>
/// <param name="orderBy">Order by</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <param name="overridePublished">
/// null - process "Published" property according to "showHidden" parameter
/// true - load only "Published" products
/// false - load only "Unpublished" products
/// </param>
/// <returns>Products</returns>
public virtual async Task<IPagedList<Product>> SearchProductsAsync(
int pageIndex = 0,
int pageSize = int.MaxValue,
IList<int> categoryIds = null,
int manufacturerId = 0,
int storeId = 0,
int vendorId = 0,
int warehouseId = 0,
ProductType? productType = null,
bool visibleIndividuallyOnly = false,
bool excludeFeaturedProducts = false,
decimal? priceMin = null,
decimal? priceMax = null,
int productTagId = 0,
string keywords = null,
bool searchDescriptions = false,
bool searchManufacturerPartNumber = true,
bool searchSku = true,
bool searchProductTags = false,
int languageId = 0,
IList<int> filteredSpecs = null,
ProductSortingEnum orderBy = ProductSortingEnum.Position,
bool showHidden = false,
bool? overridePublished = null)
{
var (products, _) = await SearchProductsAsync(false,
pageIndex, pageSize, categoryIds, manufacturerId,
storeId, vendorId, warehouseId,
productType, visibleIndividuallyOnly, excludeFeaturedProducts,
priceMin, priceMax, productTagId, keywords, searchDescriptions, searchManufacturerPartNumber, searchSku,
searchProductTags, languageId, filteredSpecs,
orderBy, showHidden, overridePublished);
return products;
}
/// <summary>
/// Search products
/// </summary>
/// <param name="loadFilterableSpecificationAttributeOptionIds">A value indicating whether we should load the specification attribute option identifiers applied to loaded products (all pages)</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="categoryIds">Category identifiers</param>
/// <param name="manufacturerId">Manufacturer identifier; 0 to load all records</param>
/// <param name="storeId">Store identifier; 0 to load all records</param>
/// <param name="vendorId">Vendor identifier; 0 to load all records</param>
/// <param name="warehouseId">Warehouse identifier; 0 to load all records</param>
/// <param name="productType">Product type; 0 to load all records</param>
/// <param name="visibleIndividuallyOnly">A values indicating whether to load only products marked as "visible individually"; "false" to load all records; "true" to load "visible individually" only</param>
/// <param name="excludeFeaturedProducts">A value indicating whether loaded products are marked as featured (relates only to categories and manufacturers); "false" (by default) to load all records; "true" to exclude featured products from results</param>
/// <param name="priceMin">Minimum price; null to load all records</param>
/// <param name="priceMax">Maximum price; null to load all records</param>
/// <param name="productTagId">Product tag identifier; 0 to load all records</param>
/// <param name="keywords">Keywords</param>
/// <param name="searchDescriptions">A value indicating whether to search by a specified "keyword" in product descriptions</param>
/// <param name="searchManufacturerPartNumber">A value indicating whether to search by a specified "keyword" in manufacturer part number</param>
/// <param name="searchSku">A value indicating whether to search by a specified "keyword" in product SKU</param>
/// <param name="searchProductTags">A value indicating whether to search by a specified "keyword" in product tags</param>
/// <param name="languageId">Language identifier (search for text searching)</param>
/// <param name="filteredSpecs">Filtered product specification identifiers</param>
/// <param name="orderBy">Order by</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <param name="overridePublished">
/// null - process "Published" property according to "showHidden" parameter
/// true - load only "Published" products
/// false - load only "Unpublished" products
/// </param>
/// <returns>Products; specification attribute option ids</returns>
public virtual async Task<(IPagedList<Product> Products, IList<int> SpecificationAttributeOptionIds)> SearchProductsAsync(
bool loadFilterableSpecificationAttributeOptionIds = false,
int pageIndex = 0,
int pageSize = int.MaxValue,
IList<int> categoryIds = null,
int manufacturerId = 0,
int storeId = 0,
int vendorId = 0,
int warehouseId = 0,
ProductType? productType = null,
bool visibleIndividuallyOnly = false,
bool excludeFeaturedProducts = false,
decimal? priceMin = null,
decimal? priceMax = null,
int productTagId = 0,
string keywords = null,
bool searchDescriptions = false,
bool searchManufacturerPartNumber = true,
bool searchSku = true,
bool searchProductTags = false,
int languageId = 0,
IList<int> filteredSpecs = null,
ProductSortingEnum orderBy = ProductSortingEnum.Position,
bool showHidden = false,
bool? overridePublished = null)
{
//search by keyword
var searchLocalizedValue = false;
if (languageId > 0)
{
if (showHidden)
{
searchLocalizedValue = true;
}
else
{
//ensure that we have at least two published languages
var totalPublishedLanguages = (await _languageService.GetAllLanguagesAsync()).Count;
searchLocalizedValue = totalPublishedLanguages >= 2;
}
}
//validate "categoryIds" parameter
if (categoryIds != null && categoryIds.Contains(0))
categoryIds.Remove(0);
//pass specification identifiers as comma-delimited string
var commaSeparatedSpecIds = string.Empty;
if (filteredSpecs != null)
{
((List<int>)filteredSpecs).Sort();
commaSeparatedSpecIds = string.Join(",", filteredSpecs);
}
//some databases don't support int.MaxValue
if (pageSize == int.MaxValue)
pageSize = int.MaxValue - 1;
var productsQuery = _productRepository.Table;
if (!showHidden)
{
var customer = await _workContext.GetCurrentCustomerAsync();
var customerRolesIds = await _customerService.GetCustomerRoleIdsAsync(customer);
productsQuery = await FilterHiddenEntriesAsync(productsQuery, storeId, customerRolesIds);
}
else if (overridePublished.HasValue)
productsQuery = productsQuery.Where(p => p.Published == overridePublished.Value);
productsQuery =
from p in productsQuery
where !p.Deleted &&
(vendorId == 0 || p.VendorId == vendorId) &&
(
warehouseId == 0 ||
(
!p.UseMultipleWarehouses ? p.WarehouseId == warehouseId :
_productWarehouseInventoryRepository.Table.Any(pwi => pwi.Id == warehouseId && pwi.ProductId == p.Id)
)
) &&
(productType == null || p.ProductTypeId == (int)productType) &&
(showHidden == false || LinqToDB.Sql.Between(DateTime.UtcNow, p.AvailableStartDateTimeUtc ?? DateTime.MinValue, p.AvailableEndDateTimeUtc ?? DateTime.MaxValue)) &&
(priceMin == null || p.Price >= priceMin) &&
(priceMax == null || p.Price <= priceMax)
select p;
if (!string.IsNullOrEmpty(keywords))
{
IQueryable<int> productsByKeywords;
productsByKeywords =
from p in _productRepository.Table
where p.Name.Contains(keywords) ||
(searchDescriptions &&
(p.ShortDescription.Contains(keywords) || p.FullDescription.Contains(keywords))) ||
(searchManufacturerPartNumber && p.ManufacturerPartNumber == keywords) ||
(searchSku && p.Sku == keywords)
select p.Id;
if (searchProductTags)
{
productsByKeywords = productsByKeywords.Union(
from pptm in _productTagMappingRepository.Table
join pt in _productTagRepository.Table on pptm.ProductTagId equals pt.Id
where pt.Name == keywords
select pptm.ProductId
);
productsByKeywords = productsByKeywords.Union(
from pptm in _productTagMappingRepository.Table
join lp in _localizedPropertyRepository.Table on pptm.ProductTagId equals lp.EntityId
where lp.LocaleKeyGroup == nameof(ProductTag) &&
lp.LocaleKey == nameof(ProductTag.Name) &&
lp.LocaleValue.Contains(keywords)
select lp.EntityId
);
}
productsByKeywords = productsByKeywords.Union(
from lp in _localizedPropertyRepository.Table
let checkName = lp.LocaleKey == nameof(Product.Name) &&
lp.LocaleValue.Contains(keywords)
let checkShortDesc = searchDescriptions &&
lp.LocaleKey == nameof(Product.ShortDescription) &&
lp.LocaleValue.Contains(keywords)
let checkProductTags = searchProductTags &&
lp.LocaleKeyGroup == nameof(ProductTag) &&
lp.LocaleKey == nameof(ProductTag.Name) &&
lp.LocaleValue.Contains(keywords)
where
(lp.LocaleKeyGroup == nameof(Product) && lp.LanguageId == languageId) && (checkName || checkShortDesc) ||
checkProductTags
select lp.EntityId
);
productsQuery =
from p in productsQuery
from pbk in LinqToDB.LinqExtensions.InnerJoin(productsByKeywords, pbk => pbk == p.Id)
select p;
}
if (categoryIds?.Count > 0)
{
productsQuery =
from p in productsQuery
join pc in _productCategoryRepository.Table on p.Id equals pc.ProductId
where categoryIds.Contains(pc.CategoryId) &&
(!excludeFeaturedProducts || !pc.IsFeaturedProduct)
select p;
}
if (manufacturerId > 0)
{
productsQuery =
from p in productsQuery
join pmm in _productManufacturerRepository.Table on p.Id equals pmm.ProductId
where pmm.ManufacturerId == manufacturerId &&
(!excludeFeaturedProducts || !pmm.IsFeaturedProduct)
select p;
}
if (productTagId > 0)
{
productsQuery =
from p in productsQuery
join ptm in _productTagMappingRepository.Table on p.Id equals ptm.ProductId
where ptm.ProductTagId == productTagId
select p;
}
if (filteredSpecs?.Count > 0)
{
productsQuery =
from p in productsQuery
join psm in _productSpecificationAttributeRepository.Table.Where(psa => filteredSpecs.Contains(psa.SpecificationAttributeOptionId)) on p.Id equals psm.ProductId
group p by p into groupedProduct
where groupedProduct.Count() == filteredSpecs.Count
select groupedProduct.Key;
}
var filterableSpecificationAttributeOptionIds = new List<int>();
if (loadFilterableSpecificationAttributeOptionIds)
{
filterableSpecificationAttributeOptionIds =
(from psam in _productSpecificationAttributeRepository.Table
where psam.AllowFiltering && productsQuery.Any(p => p.Id == psam.ProductId)
select psam.SpecificationAttributeOptionId).Distinct().ToList();
}
var products = await productsQuery.OrderBy(orderBy).ToPagedListAsync(pageIndex, pageSize);
return (products, filterableSpecificationAttributeOptionIds);
}
/// <summary>
/// Gets products by product attribute
/// </summary>
/// <param name="productAttributeId">Product attribute identifier</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <returns>Products</returns>
public virtual async Task<IPagedList<Product>> GetProductsByProductAtributeIdAsync(int productAttributeId,