-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
ProductModelFactory.cs
1995 lines (1746 loc) · 102 KB
/
ProductModelFactory.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.Globalization;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Media;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Security;
using Nop.Core.Domain.Seo;
using Nop.Core.Domain.Shipping;
using Nop.Core.Domain.Vendors;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Helpers;
using Nop.Services.Localization;
using Nop.Services.Media;
using Nop.Services.Orders;
using Nop.Services.Security;
using Nop.Services.Seo;
using Nop.Services.Shipping.Date;
using Nop.Services.Tax;
using Nop.Services.Vendors;
using Nop.Web.Infrastructure.Cache;
using Nop.Web.Models.Catalog;
using Nop.Web.Models.Common;
using Nop.Web.Models.Media;
namespace Nop.Web.Factories
{
/// <summary>
/// Represents the product model factory
/// </summary>
public partial class ProductModelFactory : IProductModelFactory
{
#region Fields
private readonly CaptchaSettings _captchaSettings;
private readonly CatalogSettings _catalogSettings;
private readonly CustomerSettings _customerSettings;
private readonly ICategoryService _categoryService;
private readonly ICurrencyService _currencyService;
private readonly ICustomerService _customerService;
private readonly IDateRangeService _dateRangeService;
private readonly IDateTimeHelper _dateTimeHelper;
private readonly IDownloadService _downloadService;
private readonly IGenericAttributeService _genericAttributeService;
private readonly ILocalizationService _localizationService;
private readonly IManufacturerService _manufacturerService;
private readonly IPermissionService _permissionService;
private readonly IPictureService _pictureService;
private readonly IPriceCalculationService _priceCalculationService;
private readonly IPriceFormatter _priceFormatter;
private readonly IProductAttributeParser _productAttributeParser;
private readonly IProductAttributeService _productAttributeService;
private readonly IProductService _productService;
private readonly IProductTagService _productTagService;
private readonly IProductTemplateService _productTemplateService;
private readonly IReviewTypeService _reviewTypeService;
private readonly IShoppingCartService _shoppingCartService;
private readonly ISpecificationAttributeService _specificationAttributeService;
private readonly IStaticCacheManager _staticCacheManager;
private readonly IStoreContext _storeContext;
private readonly IShoppingCartModelFactory _shoppingCartModelFactory;
private readonly ITaxService _taxService;
private readonly IUrlRecordService _urlRecordService;
private readonly IVendorService _vendorService;
private readonly IVideoService _videoService;
private readonly IWebHelper _webHelper;
private readonly IWorkContext _workContext;
private readonly MediaSettings _mediaSettings;
private readonly OrderSettings _orderSettings;
private readonly SeoSettings _seoSettings;
private readonly ShippingSettings _shippingSettings;
private readonly VendorSettings _vendorSettings;
#endregion
#region Ctor
public ProductModelFactory(CaptchaSettings captchaSettings,
CatalogSettings catalogSettings,
CustomerSettings customerSettings,
ICategoryService categoryService,
ICurrencyService currencyService,
ICustomerService customerService,
IDateRangeService dateRangeService,
IDateTimeHelper dateTimeHelper,
IDownloadService downloadService,
IGenericAttributeService genericAttributeService,
ILocalizationService localizationService,
IManufacturerService manufacturerService,
IPermissionService permissionService,
IPictureService pictureService,
IPriceCalculationService priceCalculationService,
IPriceFormatter priceFormatter,
IProductAttributeParser productAttributeParser,
IProductAttributeService productAttributeService,
IProductService productService,
IProductTagService productTagService,
IProductTemplateService productTemplateService,
IReviewTypeService reviewTypeService,
IShoppingCartService shoppingCartService,
ISpecificationAttributeService specificationAttributeService,
IStaticCacheManager staticCacheManager,
IStoreContext storeContext,
IShoppingCartModelFactory shoppingCartModelFactory,
ITaxService taxService,
IUrlRecordService urlRecordService,
IVendorService vendorService,
IVideoService videoService,
IWebHelper webHelper,
IWorkContext workContext,
MediaSettings mediaSettings,
OrderSettings orderSettings,
SeoSettings seoSettings,
ShippingSettings shippingSettings,
VendorSettings vendorSettings)
{
_captchaSettings = captchaSettings;
_catalogSettings = catalogSettings;
_customerSettings = customerSettings;
_categoryService = categoryService;
_currencyService = currencyService;
_customerService = customerService;
_dateRangeService = dateRangeService;
_dateTimeHelper = dateTimeHelper;
_downloadService = downloadService;
_genericAttributeService = genericAttributeService;
_localizationService = localizationService;
_manufacturerService = manufacturerService;
_permissionService = permissionService;
_pictureService = pictureService;
_priceCalculationService = priceCalculationService;
_priceFormatter = priceFormatter;
_productAttributeParser = productAttributeParser;
_productAttributeService = productAttributeService;
_productService = productService;
_productTagService = productTagService;
_productTemplateService = productTemplateService;
_reviewTypeService = reviewTypeService;
_shoppingCartService = shoppingCartService;
_specificationAttributeService = specificationAttributeService;
_staticCacheManager = staticCacheManager;
_storeContext = storeContext;
_shoppingCartModelFactory = shoppingCartModelFactory;
_taxService = taxService;
_urlRecordService = urlRecordService;
_vendorService = vendorService;
_webHelper = webHelper;
_workContext = workContext;
_mediaSettings = mediaSettings;
_orderSettings = orderSettings;
_seoSettings = seoSettings;
_shippingSettings = shippingSettings;
_vendorSettings = vendorSettings;
_videoService = videoService;
}
#endregion
#region Utilities
/// <summary>
/// Prepare the product specification models
/// </summary>
/// <param name="product">Product</param>
/// <param name="group">Specification attribute group</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the list of product specification model
/// </returns>
protected virtual async Task<IList<ProductSpecificationAttributeModel>> PrepareProductSpecificationAttributeModelAsync(Product product, SpecificationAttributeGroup group)
{
if (product == null)
throw new ArgumentNullException(nameof(product));
var productSpecificationAttributes = await _specificationAttributeService.GetProductSpecificationAttributesAsync(
product.Id, specificationAttributeGroupId: group?.Id, showOnProductPage: true);
var result = new List<ProductSpecificationAttributeModel>();
foreach (var psa in productSpecificationAttributes)
{
var option = await _specificationAttributeService.GetSpecificationAttributeOptionByIdAsync(psa.SpecificationAttributeOptionId);
var model = result.FirstOrDefault(model => model.Id == option.SpecificationAttributeId);
if (model == null)
{
var attribute = await _specificationAttributeService.GetSpecificationAttributeByIdAsync(option.SpecificationAttributeId);
model = new ProductSpecificationAttributeModel
{
Id = attribute.Id,
Name = await _localizationService.GetLocalizedAsync(attribute, x => x.Name)
};
result.Add(model);
}
var value = new ProductSpecificationAttributeValueModel
{
AttributeTypeId = psa.AttributeTypeId,
ColorSquaresRgb = option.ColorSquaresRgb,
ValueRaw = psa.AttributeType switch
{
SpecificationAttributeType.Option => WebUtility.HtmlEncode(await _localizationService.GetLocalizedAsync(option, x => x.Name)),
SpecificationAttributeType.CustomText => WebUtility.HtmlEncode(await _localizationService.GetLocalizedAsync(psa, x => x.CustomValue)),
SpecificationAttributeType.CustomHtmlText => await _localizationService.GetLocalizedAsync(psa, x => x.CustomValue),
SpecificationAttributeType.Hyperlink => $"<a href='{psa.CustomValue}' target='_blank'>{psa.CustomValue}</a>",
_ => null
}
};
model.Values.Add(value);
}
return result;
}
/// <summary>
/// Prepare the product review overview model
/// </summary>
/// <param name="product">Product</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the product review overview model
/// </returns>
protected virtual async Task<ProductReviewOverviewModel> PrepareProductReviewOverviewModelAsync(Product product)
{
ProductReviewOverviewModel productReview;
var currentStore = await _storeContext.GetCurrentStoreAsync();
if (_catalogSettings.ShowProductReviewsPerStore)
{
var cacheKey = _staticCacheManager.PrepareKeyForDefaultCache(NopModelCacheDefaults.ProductReviewsModelKey, product, currentStore);
productReview = await _staticCacheManager.GetAsync(cacheKey, async () =>
{
var productReviews = await _productService.GetAllProductReviewsAsync(productId: product.Id, approved: true, storeId: currentStore.Id);
return new ProductReviewOverviewModel
{
RatingSum = productReviews.Sum(pr => pr.Rating),
TotalReviews = productReviews.Count
};
});
}
else
{
productReview = new ProductReviewOverviewModel
{
RatingSum = product.ApprovedRatingSum,
TotalReviews = product.ApprovedTotalReviews
};
}
if (productReview != null)
{
productReview.ProductId = product.Id;
productReview.AllowCustomerReviews = product.AllowCustomerReviews;
productReview.CanAddNewReview = await _productService.CanAddReviewAsync(product.Id, _catalogSettings.ShowProductReviewsPerStore ? currentStore.Id : 0);
}
return productReview;
}
/// <summary>
/// Prepare the product overview price model
/// </summary>
/// <param name="product">Product</param>
/// <param name="forceRedirectionAfterAddingToCart">Whether to force redirection after adding to cart</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the product overview price model
/// </returns>
protected virtual async Task<ProductOverviewModel.ProductPriceModel> PrepareProductOverviewPriceModelAsync(Product product, bool forceRedirectionAfterAddingToCart = false)
{
if (product == null)
throw new ArgumentNullException(nameof(product));
var priceModel = new ProductOverviewModel.ProductPriceModel
{
ForceRedirectionAfterAddingToCart = forceRedirectionAfterAddingToCart
};
switch (product.ProductType)
{
case ProductType.GroupedProduct:
//grouped product
await PrepareGroupedProductOverviewPriceModelAsync(product, priceModel);
break;
case ProductType.SimpleProduct:
default:
//simple product
await PrepareSimpleProductOverviewPriceModelAsync(product, priceModel);
break;
}
return priceModel;
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task PrepareSimpleProductOverviewPriceModelAsync(Product product, ProductOverviewModel.ProductPriceModel priceModel)
{
//add to cart button
priceModel.DisableBuyButton = product.DisableBuyButton ||
!await _permissionService.AuthorizeAsync(StandardPermissionProvider.EnableShoppingCart) ||
!await _permissionService.AuthorizeAsync(StandardPermissionProvider.DisplayPrices);
//add to wishlist button
priceModel.DisableWishlistButton = product.DisableWishlistButton ||
!await _permissionService.AuthorizeAsync(StandardPermissionProvider.EnableWishlist) ||
!await _permissionService.AuthorizeAsync(StandardPermissionProvider.DisplayPrices);
//compare products
priceModel.DisableAddToCompareListButton = !_catalogSettings.CompareProductsEnabled;
//rental
priceModel.IsRental = product.IsRental;
//pre-order
if (product.AvailableForPreOrder)
{
priceModel.AvailableForPreOrder = !product.PreOrderAvailabilityStartDateTimeUtc.HasValue ||
product.PreOrderAvailabilityStartDateTimeUtc.Value >=
DateTime.UtcNow;
priceModel.PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc;
}
//prices
if (await _permissionService.AuthorizeAsync(StandardPermissionProvider.DisplayPrices))
{
if (product.CustomerEntersPrice)
return;
if (product.CallForPrice &&
//also check whether the current user is impersonated
(!_orderSettings.AllowAdminsToBuyCallForPriceProducts ||
_workContext.OriginalCustomerIfImpersonated == null))
{
//call for price
priceModel.OldPrice = null;
priceModel.OldPriceValue = null;
priceModel.Price = await _localizationService.GetResourceAsync("Products.CallForPrice");
priceModel.PriceValue = null;
}
else
{
var store = await _storeContext.GetCurrentStoreAsync();
var customer = await _workContext.GetCurrentCustomerAsync();
//prices
var (minPossiblePriceWithoutDiscount, minPossiblePriceWithDiscount) = (decimal.Zero, decimal.Zero);
var hasMultiplePrices = false;
if (_catalogSettings.DisplayFromPrices)
{
var customerRoleIds = await _customerService.GetCustomerRoleIdsAsync(customer);
var cacheKey = _staticCacheManager
.PrepareKeyForDefaultCache(NopCatalogDefaults.ProductMultiplePriceCacheKey, product, customerRoleIds, store);
if (!_catalogSettings.CacheProductPrices || product.IsRental)
cacheKey.CacheTime = 0;
var cachedPrice = await _staticCacheManager.GetAsync(cacheKey, async () =>
{
var prices = new List<(decimal PriceWithoutDiscount, decimal PriceWithDiscount)>();
// price when there are no required attributes
var attributesMappings = await _productAttributeService.GetProductAttributeMappingsByProductIdAsync(product.Id);
if (!attributesMappings.Any(am => !am.IsNonCombinable() && am.IsRequired))
{
(var priceWithoutDiscount, var priceWithDiscount, _, _) = await _priceCalculationService
.GetFinalPriceAsync(product, customer);
prices.Add((priceWithoutDiscount, priceWithDiscount));
}
var allAttributesXml = await _productAttributeParser.GenerateAllCombinationsAsync(product, true);
foreach (var attributesXml in allAttributesXml)
{
var warnings = new List<string>();
warnings.AddRange(await _shoppingCartService.GetShoppingCartItemAttributeWarningsAsync(customer,
ShoppingCartType.ShoppingCart, product, 1, attributesXml, true, true, true));
if (warnings.Count != 0)
continue;
//get price with additional charge
var additionalCharge = decimal.Zero;
var combination = await _productAttributeParser.FindProductAttributeCombinationAsync(product, attributesXml);
if (combination?.OverriddenPrice.HasValue ?? false)
additionalCharge = combination.OverriddenPrice.Value;
else
{
var attributeValues = await _productAttributeParser.ParseProductAttributeValuesAsync(attributesXml);
foreach (var attributeValue in attributeValues)
{
additionalCharge += await _priceCalculationService.
GetProductAttributeValuePriceAdjustmentAsync(product, attributeValue, customer);
}
}
if (additionalCharge != decimal.Zero)
{
(var priceWithoutDiscount, var priceWithDiscount, _, _) = await _priceCalculationService
.GetFinalPriceAsync(product, customer, additionalCharge);
prices.Add((priceWithoutDiscount, priceWithDiscount));
}
}
if (prices.Distinct().Count() > 1)
{
(minPossiblePriceWithoutDiscount, minPossiblePriceWithDiscount) = prices.OrderBy(p => p.PriceWithDiscount).First();
return new
{
PriceWithoutDiscount = minPossiblePriceWithoutDiscount,
PriceWithDiscount = minPossiblePriceWithDiscount
};
}
// show default price when required attributes available but no values added
(minPossiblePriceWithoutDiscount, minPossiblePriceWithDiscount, _, _) = await _priceCalculationService.GetFinalPriceAsync(product, customer);
//don't cache (return null) if there are no multiple prices
return null;
});
if (cachedPrice is not null)
{
hasMultiplePrices = true;
(minPossiblePriceWithoutDiscount, minPossiblePriceWithDiscount) = (cachedPrice.PriceWithoutDiscount, cachedPrice.PriceWithDiscount);
}
}
else
(minPossiblePriceWithoutDiscount, minPossiblePriceWithDiscount, _, _) = await _priceCalculationService.GetFinalPriceAsync(product, customer);
if (product.HasTierPrices)
{
var (tierPriceMinPossiblePriceWithoutDiscount, tierPriceMinPossiblePriceWithDiscount, _, _) = await _priceCalculationService.GetFinalPriceAsync(product, customer, quantity: int.MaxValue);
//calculate price for the maximum quantity if we have tier prices, and choose minimal
minPossiblePriceWithoutDiscount = Math.Min(minPossiblePriceWithoutDiscount, tierPriceMinPossiblePriceWithoutDiscount);
minPossiblePriceWithDiscount = Math.Min(minPossiblePriceWithDiscount, tierPriceMinPossiblePriceWithDiscount);
}
var (oldPriceBase, _) = await _taxService.GetProductPriceAsync(product, product.OldPrice);
var (finalPriceWithoutDiscountBase, _) = await _taxService.GetProductPriceAsync(product, minPossiblePriceWithoutDiscount);
var (finalPriceWithDiscountBase, _) = await _taxService.GetProductPriceAsync(product, minPossiblePriceWithDiscount);
var currentCurrency = await _workContext.GetWorkingCurrencyAsync();
var oldPrice = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(oldPriceBase, currentCurrency);
var finalPriceWithoutDiscount = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(finalPriceWithoutDiscountBase, currentCurrency);
var finalPriceWithDiscount = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(finalPriceWithDiscountBase, currentCurrency);
var strikeThroughPrice = decimal.Zero;
if (finalPriceWithoutDiscountBase != oldPriceBase && oldPriceBase > decimal.Zero)
strikeThroughPrice = oldPrice;
if (finalPriceWithoutDiscountBase != finalPriceWithDiscountBase)
strikeThroughPrice = finalPriceWithoutDiscount;
if (strikeThroughPrice > decimal.Zero)
{
priceModel.OldPrice = await _priceFormatter.FormatPriceAsync(strikeThroughPrice);
}
else
{
priceModel.OldPrice = null;
priceModel.OldPriceValue = null;
}
//do we have tier prices configured?
var tierPrices = product.HasTierPrices
? await _productService.GetTierPricesAsync(product, customer, store.Id)
: new List<TierPrice>();
//When there is just one tier price (with qty 1), there are no actual savings in the list.
var hasTierPrices = tierPrices.Any() && !(tierPrices.Count == 1 && tierPrices[0].Quantity <= 1);
var price = await _priceFormatter.FormatPriceAsync(finalPriceWithDiscount);
priceModel.Price = hasTierPrices || hasMultiplePrices
? string.Format(await _localizationService.GetResourceAsync("Products.PriceRangeFrom"), price)
: price;
priceModel.PriceValue = finalPriceWithDiscount;
if (product.IsRental)
{
//rental product
priceModel.OldPrice = await _priceFormatter.FormatRentalProductPeriodAsync(product, priceModel.OldPrice);
priceModel.OldPriceValue = priceModel.OldPriceValue;
priceModel.Price = await _priceFormatter.FormatRentalProductPeriodAsync(product, priceModel.Price);
priceModel.PriceValue = priceModel.PriceValue;
}
//property for German market
//we display tax/shipping info only with "shipping enabled" for this product
//we also ensure this it's not free shipping
priceModel.DisplayTaxShippingInfo = _catalogSettings.DisplayTaxShippingInfoProductBoxes && product.IsShipEnabled && !product.IsFreeShipping;
//PAngV default baseprice (used in Germany)
priceModel.BasePricePAngV = await _priceFormatter.FormatBasePriceAsync(product, finalPriceWithDiscount);
priceModel.BasePricePAngVValue = finalPriceWithDiscount;
}
}
else
{
//hide prices
priceModel.OldPrice = null;
priceModel.OldPriceValue = null;
priceModel.Price = null;
priceModel.PriceValue = null;
}
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task PrepareGroupedProductOverviewPriceModelAsync(Product product, ProductOverviewModel.ProductPriceModel priceModel)
{
var store = await _storeContext.GetCurrentStoreAsync();
var associatedProducts = await _productService.GetAssociatedProductsAsync(product.Id,
store.Id);
//add to cart button (ignore "DisableBuyButton" property for grouped products)
priceModel.DisableBuyButton =
!await _permissionService.AuthorizeAsync(StandardPermissionProvider.EnableShoppingCart) ||
!await _permissionService.AuthorizeAsync(StandardPermissionProvider.DisplayPrices);
//add to wishlist button (ignore "DisableWishlistButton" property for grouped products)
priceModel.DisableWishlistButton =
!await _permissionService.AuthorizeAsync(StandardPermissionProvider.EnableWishlist) ||
!await _permissionService.AuthorizeAsync(StandardPermissionProvider.DisplayPrices);
//compare products
priceModel.DisableAddToCompareListButton = !_catalogSettings.CompareProductsEnabled;
if (!associatedProducts.Any())
return;
//we have at least one associated product
if (await _permissionService.AuthorizeAsync(StandardPermissionProvider.DisplayPrices))
{
//find a minimum possible price
decimal? minPossiblePrice = null;
Product minPriceProduct = null;
var customer = await _workContext.GetCurrentCustomerAsync();
foreach (var associatedProduct in associatedProducts)
{
var (_, tmpMinPossiblePrice, _, _) = await _priceCalculationService.GetFinalPriceAsync(associatedProduct, customer);
if (associatedProduct.HasTierPrices)
{
//calculate price for the maximum quantity if we have tier prices, and choose minimal
tmpMinPossiblePrice = Math.Min(tmpMinPossiblePrice,
(await _priceCalculationService.GetFinalPriceAsync(associatedProduct, customer, quantity: int.MaxValue)).finalPrice);
}
if (minPossiblePrice.HasValue && tmpMinPossiblePrice >= minPossiblePrice.Value)
continue;
minPriceProduct = associatedProduct;
minPossiblePrice = tmpMinPossiblePrice;
}
if (minPriceProduct == null || minPriceProduct.CustomerEntersPrice)
return;
if (minPriceProduct.CallForPrice &&
//also check whether the current user is impersonated
(!_orderSettings.AllowAdminsToBuyCallForPriceProducts ||
_workContext.OriginalCustomerIfImpersonated == null))
{
priceModel.OldPrice = null;
priceModel.OldPriceValue = null;
priceModel.Price = await _localizationService.GetResourceAsync("Products.CallForPrice");
priceModel.PriceValue = null;
}
else
{
//calculate prices
var (finalPriceBase, _) = await _taxService.GetProductPriceAsync(minPriceProduct, minPossiblePrice.Value);
var finalPrice = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(finalPriceBase, await _workContext.GetWorkingCurrencyAsync());
priceModel.OldPrice = null;
priceModel.OldPriceValue = null;
priceModel.Price = string.Format(await _localizationService.GetResourceAsync("Products.PriceRangeFrom"), await _priceFormatter.FormatPriceAsync(finalPrice));
priceModel.PriceValue = finalPrice;
//PAngV default baseprice (used in Germany)
priceModel.BasePricePAngV = await _priceFormatter.FormatBasePriceAsync(product, finalPriceBase);
priceModel.BasePricePAngVValue = finalPriceBase;
}
}
else
{
//hide prices
priceModel.OldPrice = null;
priceModel.OldPriceValue = null;
priceModel.Price = null;
priceModel.PriceValue = null;
}
}
/// <summary>
/// Prepare the product overview picture model
/// </summary>
/// <param name="product">Product</param>
/// <param name="productThumbPictureSize">Product thumb picture size (longest side); pass null to use the default value of media settings</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains picture models
/// </returns>
protected virtual async Task<IList<PictureModel>> PrepareProductOverviewPicturesModelAsync(Product product, int? productThumbPictureSize = null)
{
if (product == null)
throw new ArgumentNullException(nameof(product));
var productName = await _localizationService.GetLocalizedAsync(product, x => x.Name);
//If a size has been set in the view, we use it in priority
var pictureSize = productThumbPictureSize ?? _mediaSettings.ProductThumbPictureSize;
//prepare picture model
var cacheKey = _staticCacheManager.PrepareKeyForDefaultCache(NopModelCacheDefaults.ProductOverviewPicturesModelKey,
product, pictureSize, true, _catalogSettings.DisplayAllPicturesOnCatalogPages, await _workContext.GetWorkingLanguageAsync(),
_webHelper.IsCurrentConnectionSecured(), await _storeContext.GetCurrentStoreAsync());
var cachedPictures = await _staticCacheManager.GetAsync(cacheKey, async () =>
{
async Task<PictureModel> preparePictureModelAsync(Picture picture)
{
var (imageUrl, _) = await _pictureService.GetPictureUrlAsync(picture, pictureSize);
var (fullSizeImageUrl, _) = await _pictureService.GetPictureUrlAsync(picture);
return new PictureModel
{
ImageUrl = imageUrl,
FullSizeImageUrl = fullSizeImageUrl,
//"title" attribute
Title = (picture != null && !string.IsNullOrEmpty(picture.TitleAttribute))
? picture.TitleAttribute
: string.Format(await _localizationService.GetResourceAsync("Media.Product.ImageLinkTitleFormat"),
productName),
//"alt" attribute
AlternateText = (picture != null && !string.IsNullOrEmpty(picture.AltAttribute))
? picture.AltAttribute
: string.Format(await _localizationService.GetResourceAsync("Media.Product.ImageAlternateTextFormat"),
productName)
};
}
//all pictures
var pictures = (await _pictureService
.GetPicturesByProductIdAsync(product.Id, _catalogSettings.DisplayAllPicturesOnCatalogPages ? 0 : 1))
.DefaultIfEmpty(null);
var pictureModels = await pictures
.SelectAwait(async picture => await preparePictureModelAsync(picture))
.ToListAsync();
return pictureModels;
});
return cachedPictures;
}
/// <summary>
/// Prepare the product breadcrumb model
/// </summary>
/// <param name="product">Product</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the product breadcrumb model
/// </returns>
protected virtual async Task<ProductDetailsModel.ProductBreadcrumbModel> PrepareProductBreadcrumbModelAsync(Product product)
{
if (product == null)
throw new ArgumentNullException(nameof(product));
var breadcrumbModel = new ProductDetailsModel.ProductBreadcrumbModel
{
Enabled = _catalogSettings.CategoryBreadcrumbEnabled,
ProductId = product.Id,
ProductName = await _localizationService.GetLocalizedAsync(product, x => x.Name),
ProductSeName = await _urlRecordService.GetSeNameAsync(product)
};
var productCategories = await _categoryService.GetProductCategoriesByProductIdAsync(product.Id);
if (!productCategories.Any())
return breadcrumbModel;
var category = await _categoryService.GetCategoryByIdAsync(productCategories[0].CategoryId);
if (category == null)
return breadcrumbModel;
foreach (var catBr in await _categoryService.GetCategoryBreadCrumbAsync(category))
{
breadcrumbModel.CategoryBreadcrumb.Add(new CategorySimpleModel
{
Id = catBr.Id,
Name = await _localizationService.GetLocalizedAsync(catBr, x => x.Name),
SeName = await _urlRecordService.GetSeNameAsync(catBr),
IncludeInTopMenu = catBr.IncludeInTopMenu
});
}
return breadcrumbModel;
}
/// <summary>
/// Prepare the product tag models
/// </summary>
/// <param name="product">Product</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the list of product tag model
/// </returns>
protected virtual async Task<IList<ProductTagModel>> PrepareProductTagModelsAsync(Product product)
{
if (product == null)
throw new ArgumentNullException(nameof(product));
var store = await _storeContext.GetCurrentStoreAsync();
var productsTags = await _productTagService.GetAllProductTagsByProductIdAsync(product.Id);
var model = await productsTags
//filter by store
.WhereAwait(async x => await _productTagService.GetProductCountByProductTagIdAsync(x.Id, store.Id) > 0)
.SelectAwait(async x => new ProductTagModel
{
Id = x.Id,
Name = await _localizationService.GetLocalizedAsync(x, y => y.Name),
SeName = await _urlRecordService.GetSeNameAsync(x),
ProductCount = await _productTagService.GetProductCountByProductTagIdAsync(x.Id, store.Id)
}).ToListAsync();
return model;
}
/// <summary>
/// Prepare the product price model
/// </summary>
/// <param name="product">Product</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the product price model
/// </returns>
protected virtual async Task<ProductDetailsModel.ProductPriceModel> PrepareProductPriceModelAsync(Product product)
{
if (product == null)
throw new ArgumentNullException(nameof(product));
var model = new ProductDetailsModel.ProductPriceModel
{
ProductId = product.Id
};
if (await _permissionService.AuthorizeAsync(StandardPermissionProvider.DisplayPrices))
{
model.HidePrices = false;
if (product.CustomerEntersPrice)
{
model.CustomerEntersPrice = true;
}
else
{
if (product.CallForPrice &&
//also check whether the current user is impersonated
(!_orderSettings.AllowAdminsToBuyCallForPriceProducts || _workContext.OriginalCustomerIfImpersonated == null))
{
model.CallForPrice = true;
}
else
{
var customer = await _workContext.GetCurrentCustomerAsync();
var (oldPriceBase, _) = await _taxService.GetProductPriceAsync(product, product.OldPrice);
var (finalPriceWithoutDiscountBase, _) = await _taxService.GetProductPriceAsync(product, (await _priceCalculationService.GetFinalPriceAsync(product, customer, includeDiscounts: false)).finalPrice);
var (finalPriceWithDiscountBase, _) = await _taxService.GetProductPriceAsync(product, (await _priceCalculationService.GetFinalPriceAsync(product, customer)).finalPrice);
var currentCurrency = await _workContext.GetWorkingCurrencyAsync();
var oldPrice = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(oldPriceBase, currentCurrency);
var finalPriceWithoutDiscount = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(finalPriceWithoutDiscountBase, currentCurrency);
var finalPriceWithDiscount = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(finalPriceWithDiscountBase, currentCurrency);
if (finalPriceWithoutDiscountBase != oldPriceBase && oldPriceBase > decimal.Zero)
{
model.OldPrice = await _priceFormatter.FormatPriceAsync(oldPrice);
model.OldPriceValue = oldPrice;
}
model.Price = await _priceFormatter.FormatPriceAsync(finalPriceWithoutDiscount);
if (finalPriceWithoutDiscountBase != finalPriceWithDiscountBase)
{
model.PriceWithDiscount = await _priceFormatter.FormatPriceAsync(finalPriceWithDiscount);
model.PriceWithDiscountValue = finalPriceWithDiscount;
}
model.PriceValue = finalPriceWithDiscount;
//property for German market
//we display tax/shipping info only with "shipping enabled" for this product
//we also ensure this it's not free shipping
model.DisplayTaxShippingInfo = _catalogSettings.DisplayTaxShippingInfoProductDetailsPage
&& product.IsShipEnabled &&
!product.IsFreeShipping;
//PAngV baseprice (used in Germany)
model.BasePricePAngV = await _priceFormatter.FormatBasePriceAsync(product, finalPriceWithDiscountBase);
model.BasePricePAngVValue = finalPriceWithDiscountBase;
//currency code
model.CurrencyCode = (await _workContext.GetWorkingCurrencyAsync()).CurrencyCode;
//rental
if (product.IsRental)
{
model.IsRental = true;
var priceStr = await _priceFormatter.FormatPriceAsync(finalPriceWithDiscount);
model.RentalPrice = await _priceFormatter.FormatRentalProductPeriodAsync(product, priceStr);
model.RentalPriceValue = finalPriceWithDiscount;
}
}
}
}
else
{
model.HidePrices = true;
model.OldPrice = null;
model.OldPriceValue = null;
model.Price = null;
}
return model;
}
/// <summary>
/// Prepare the product add to cart model
/// </summary>
/// <param name="product">Product</param>
/// <param name="updatecartitem">Updated shopping cart item</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the product add to cart model
/// </returns>
protected virtual async Task<ProductDetailsModel.AddToCartModel> PrepareProductAddToCartModelAsync(Product product, ShoppingCartItem updatecartitem)
{
if (product == null)
throw new ArgumentNullException(nameof(product));
var model = new ProductDetailsModel.AddToCartModel
{
ProductId = product.Id
};
if (updatecartitem != null)
{
model.UpdatedShoppingCartItemId = updatecartitem.Id;
model.UpdateShoppingCartItemType = updatecartitem.ShoppingCartType;
}
//quantity
model.EnteredQuantity = updatecartitem != null ? updatecartitem.Quantity : product.OrderMinimumQuantity;
//allowed quantities
var allowedQuantities = _productService.ParseAllowedQuantities(product);
foreach (var qty in allowedQuantities)
{
model.AllowedQuantities.Add(new SelectListItem
{
Text = qty.ToString(),
Value = qty.ToString(),
Selected = updatecartitem != null && updatecartitem.Quantity == qty
});
}
//minimum quantity notification
if (product.OrderMinimumQuantity > 1)
{
model.MinimumQuantityNotification = string.Format(await _localizationService.GetResourceAsync("Products.MinimumQuantityNotification"), product.OrderMinimumQuantity);
}
//'add to cart', 'add to wishlist' buttons
model.DisableBuyButton = product.DisableBuyButton || !await _permissionService.AuthorizeAsync(StandardPermissionProvider.EnableShoppingCart);
model.DisableWishlistButton = product.DisableWishlistButton || !await _permissionService.AuthorizeAsync(StandardPermissionProvider.EnableWishlist);
if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.DisplayPrices))
{
model.DisableBuyButton = true;
model.DisableWishlistButton = true;
}
//pre-order
if (product.AvailableForPreOrder)
{
model.AvailableForPreOrder = !product.PreOrderAvailabilityStartDateTimeUtc.HasValue ||
product.PreOrderAvailabilityStartDateTimeUtc.Value >= DateTime.UtcNow;
model.PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc;
if (model.AvailableForPreOrder &&
model.PreOrderAvailabilityStartDateTimeUtc.HasValue &&
_catalogSettings.DisplayDatePreOrderAvailability)
{
model.PreOrderAvailabilityStartDateTimeUserTime =
(await _dateTimeHelper.ConvertToUserTimeAsync(model.PreOrderAvailabilityStartDateTimeUtc.Value)).ToString("D");
}
}
//rental
model.IsRental = product.IsRental;
//customer entered price
model.CustomerEntersPrice = product.CustomerEntersPrice;
if (!model.CustomerEntersPrice)
return model;
var currentCurrency = await _workContext.GetWorkingCurrencyAsync();
var minimumCustomerEnteredPrice = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(product.MinimumCustomerEnteredPrice, currentCurrency);
var maximumCustomerEnteredPrice = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(product.MaximumCustomerEnteredPrice, currentCurrency);
model.CustomerEnteredPrice = updatecartitem != null ? updatecartitem.CustomerEnteredPrice : minimumCustomerEnteredPrice;
model.CustomerEnteredPriceRange = string.Format(await _localizationService.GetResourceAsync("Products.EnterProductPrice.Range"),
await _priceFormatter.FormatPriceAsync(minimumCustomerEnteredPrice, false, false),
await _priceFormatter.FormatPriceAsync(maximumCustomerEnteredPrice, false, false));
return model;
}
/// <summary>
/// Prepare the product attribute models
/// </summary>
/// <param name="product">Product</param>
/// <param name="updatecartitem">Updated shopping cart item</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the list of product attribute model
/// </returns>
protected virtual async Task<IList<ProductDetailsModel.ProductAttributeModel>> PrepareProductAttributeModelsAsync(Product product, ShoppingCartItem updatecartitem)
{
if (product == null)
throw new ArgumentNullException(nameof(product));
var model = new List<ProductDetailsModel.ProductAttributeModel>();
var productAttributeMapping = await _productAttributeService.GetProductAttributeMappingsByProductIdAsync(product.Id);
foreach (var attribute in productAttributeMapping)
{
var productAttrubute = await _productAttributeService.GetProductAttributeByIdAsync(attribute.ProductAttributeId);
var attributeModel = new ProductDetailsModel.ProductAttributeModel
{
Id = attribute.Id,
ProductId = product.Id,
ProductAttributeId = attribute.ProductAttributeId,
Name = await _localizationService.GetLocalizedAsync(productAttrubute, x => x.Name),
Description = await _localizationService.GetLocalizedAsync(productAttrubute, x => x.Description),
TextPrompt = await _localizationService.GetLocalizedAsync(attribute, x => x.TextPrompt),
IsRequired = attribute.IsRequired,
AttributeControlType = attribute.AttributeControlType,
DefaultValue = updatecartitem != null ? null : await _localizationService.GetLocalizedAsync(attribute, x => x.DefaultValue),
HasCondition = !string.IsNullOrEmpty(attribute.ConditionAttributeXml)
};
if (!string.IsNullOrEmpty(attribute.ValidationFileAllowedExtensions))
{
attributeModel.AllowedFileExtensions = attribute.ValidationFileAllowedExtensions
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
}
if (attribute.ShouldHaveValues())
{
//values
var attributeValues = await _productAttributeService.GetProductAttributeValuesAsync(attribute.Id);
foreach (var attributeValue in attributeValues)
{
var valueModel = new ProductDetailsModel.ProductAttributeValueModel
{
Id = attributeValue.Id,
Name = await _localizationService.GetLocalizedAsync(attributeValue, x => x.Name),
ColorSquaresRgb = attributeValue.ColorSquaresRgb, //used with "Color squares" attribute type
IsPreSelected = attributeValue.IsPreSelected,
CustomerEntersQty = attributeValue.CustomerEntersQty,
Quantity = attributeValue.Quantity
};
attributeModel.Values.Add(valueModel);
//display price if allowed
if (await _permissionService.AuthorizeAsync(StandardPermissionProvider.DisplayPrices))
{
var customer = updatecartitem?.CustomerId is null ? await _workContext.GetCurrentCustomerAsync() : await _customerService.GetCustomerByIdAsync(updatecartitem.CustomerId);
var attributeValuePriceAdjustment = await _priceCalculationService.GetProductAttributeValuePriceAdjustmentAsync(product, attributeValue, customer);
var (priceAdjustmentBase, _) = await _taxService.GetProductPriceAsync(product, attributeValuePriceAdjustment);
var priceAdjustment = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(priceAdjustmentBase, await _workContext.GetWorkingCurrencyAsync());
if (attributeValue.PriceAdjustmentUsePercentage)
{
var priceAdjustmentStr = attributeValue.PriceAdjustment.ToString("G29");
if (attributeValue.PriceAdjustment > decimal.Zero)
valueModel.PriceAdjustment = "+";
valueModel.PriceAdjustment += priceAdjustmentStr + "%";
}
else
{
if (priceAdjustmentBase > decimal.Zero)
valueModel.PriceAdjustment = "+" + await _priceFormatter.FormatPriceAsync(priceAdjustment, false, false);
else if (priceAdjustmentBase < decimal.Zero)
valueModel.PriceAdjustment = "-" + await _priceFormatter.FormatPriceAsync(-priceAdjustment, false, false);
}