/
OrderModelFactory.cs
1927 lines (1653 loc) · 95.2 KB
/
OrderModelFactory.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.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Domain.Shipping;
using Nop.Core.Domain.Tax;
using Nop.Services.Affiliates;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Discounts;
using Nop.Services.Helpers;
using Nop.Services.Localization;
using Nop.Services.Media;
using Nop.Services.Orders;
using Nop.Services.Payments;
using Nop.Services.Security;
using Nop.Services.Seo;
using Nop.Services.Shipping;
using Nop.Services.Stores;
using Nop.Services.Tax;
using Nop.Services.Vendors;
using Nop.Web.Areas.Admin.Infrastructure.Mapper.Extensions;
using Nop.Web.Areas.Admin.Models.Catalog;
using Nop.Web.Areas.Admin.Models.Common;
using Nop.Web.Areas.Admin.Models.Orders;
using Nop.Web.Areas.Admin.Models.Reports;
using Nop.Web.Framework.Extensions;
using Nop.Web.Framework.Models.Extensions;
namespace Nop.Web.Areas.Admin.Factories
{
/// <summary>
/// Represents the order model factory implementation
/// </summary>
public partial class OrderModelFactory : IOrderModelFactory
{
#region Fields
private readonly AddressSettings _addressSettings;
private readonly CatalogSettings _catalogSettings;
private readonly CurrencySettings _currencySettings;
private readonly IActionContextAccessor _actionContextAccessor;
private readonly IAddressModelFactory _addressModelFactory;
private readonly IAddressService _addressService;
private readonly IAffiliateService _affiliateService;
private readonly IBaseAdminModelFactory _baseAdminModelFactory;
private readonly ICountryService _countryService;
private readonly ICurrencyService _currencyService;
private readonly ICustomerService _customerService;
private readonly IDateTimeHelper _dateTimeHelper;
private readonly IDiscountService _discountService;
private readonly IDownloadService _downloadService;
private readonly IEncryptionService _encryptionService;
private readonly IGiftCardService _giftCardService;
private readonly ILocalizationService _localizationService;
private readonly IMeasureService _measureService;
private readonly IOrderProcessingService _orderProcessingService;
private readonly IOrderReportService _orderReportService;
private readonly IOrderService _orderService;
private readonly IPaymentPluginManager _paymentPluginManager;
private readonly IPaymentService _paymentService;
private readonly IPictureService _pictureService;
private readonly IPriceCalculationService _priceCalculationService;
private readonly IPriceFormatter _priceFormatter;
private readonly IProductAttributeService _productAttributeService;
private readonly IProductService _productService;
private readonly IReturnRequestService _returnRequestService;
private readonly IRewardPointService _rewardPointService;
private readonly IShipmentService _shipmentService;
private readonly IShippingService _shippingService;
private readonly IStateProvinceService _stateProvinceService;
private readonly IStoreService _storeService;
private readonly ITaxService _taxService;
private readonly IUrlHelperFactory _urlHelperFactory;
private readonly IVendorService _vendorService;
private readonly IWorkContext _workContext;
private readonly MeasureSettings _measureSettings;
private readonly OrderSettings _orderSettings;
private readonly ShippingSettings _shippingSettings;
private readonly IUrlRecordService _urlRecordService;
private readonly TaxSettings _taxSettings;
#endregion
#region Ctor
public OrderModelFactory(AddressSettings addressSettings,
CatalogSettings catalogSettings,
CurrencySettings currencySettings,
IActionContextAccessor actionContextAccessor,
IAddressModelFactory addressModelFactory,
IAddressService addressService,
IAffiliateService affiliateService,
IBaseAdminModelFactory baseAdminModelFactory,
ICountryService countryService,
ICurrencyService currencyService,
ICustomerService customerService,
IDateTimeHelper dateTimeHelper,
IDiscountService discountService,
IDownloadService downloadService,
IEncryptionService encryptionService,
IGiftCardService giftCardService,
ILocalizationService localizationService,
IMeasureService measureService,
IOrderProcessingService orderProcessingService,
IOrderReportService orderReportService,
IOrderService orderService,
IPaymentPluginManager paymentPluginManager,
IPaymentService paymentService,
IPictureService pictureService,
IPriceCalculationService priceCalculationService,
IPriceFormatter priceFormatter,
IProductAttributeService productAttributeService,
IProductService productService,
IReturnRequestService returnRequestService,
IRewardPointService rewardPointService,
IShipmentService shipmentService,
IShippingService shippingService,
IStateProvinceService stateProvinceService,
IStoreService storeService,
ITaxService taxService,
IUrlHelperFactory urlHelperFactory,
IVendorService vendorService,
IWorkContext workContext,
MeasureSettings measureSettings,
OrderSettings orderSettings,
ShippingSettings shippingSettings,
IUrlRecordService urlRecordService,
TaxSettings taxSettings)
{
_addressSettings = addressSettings;
_catalogSettings = catalogSettings;
_currencySettings = currencySettings;
_actionContextAccessor = actionContextAccessor;
_addressModelFactory = addressModelFactory;
_addressService = addressService;
_affiliateService = affiliateService;
_baseAdminModelFactory = baseAdminModelFactory;
_countryService = countryService;
_currencyService = currencyService;
_customerService = customerService;
_dateTimeHelper = dateTimeHelper;
_discountService = discountService;
_downloadService = downloadService;
_encryptionService = encryptionService;
_giftCardService = giftCardService;
_localizationService = localizationService;
_measureService = measureService;
_orderProcessingService = orderProcessingService;
_orderReportService = orderReportService;
_orderService = orderService;
_paymentPluginManager = paymentPluginManager;
_paymentService = paymentService;
_pictureService = pictureService;
_priceCalculationService = priceCalculationService;
_priceFormatter = priceFormatter;
_productAttributeService = productAttributeService;
_productService = productService;
_returnRequestService = returnRequestService;
_rewardPointService = rewardPointService;
_shipmentService = shipmentService;
_shippingService = shippingService;
_stateProvinceService = stateProvinceService;
_storeService = storeService;
_taxService = taxService;
_urlHelperFactory = urlHelperFactory;
_vendorService = vendorService;
_workContext = workContext;
_measureSettings = measureSettings;
_orderSettings = orderSettings;
_shippingSettings = shippingSettings;
_urlRecordService = urlRecordService;
_taxSettings = taxSettings;
}
#endregion
#region Utilities
/// <summary>
/// Set some address fields as required
/// </summary>
/// <param name="model">Address model</param>
protected virtual void SetAddressFieldsAsRequired(AddressModel model)
{
model.FirstNameRequired = true;
model.LastNameRequired = true;
model.EmailRequired = true;
model.CompanyRequired = _addressSettings.CompanyRequired;
model.CountyRequired = _addressSettings.CountyRequired;
model.CityRequired = _addressSettings.CityRequired;
model.StreetAddressRequired = _addressSettings.StreetAddressRequired;
model.StreetAddress2Required = _addressSettings.StreetAddress2Required;
model.ZipPostalCodeRequired = _addressSettings.ZipPostalCodeRequired;
model.PhoneRequired = _addressSettings.PhoneRequired;
model.FaxRequired = _addressSettings.FaxRequired;
}
/// <summary>
/// Prepare order item models
/// </summary>
/// <param name="models">List of order item models</param>
/// <param name="order">Order</param>
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task PrepareOrderItemModelsAsync(IList<OrderItemModel> models, Order order)
{
if (models == null)
throw new ArgumentNullException(nameof(models));
if (order == null)
throw new ArgumentNullException(nameof(order));
var primaryStoreCurrency = await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId);
//get order items
var orderItems = await _orderService.GetOrderItemsAsync(order.Id, vendorId: (await _workContext.GetCurrentVendorAsync())?.Id ?? 0);
foreach (var orderItem in orderItems)
{
var product = await _productService.GetProductByIdAsync(orderItem.ProductId);
//fill in model values from the entity
var orderItemModel = new OrderItemModel
{
Id = orderItem.Id,
ProductId = orderItem.ProductId,
ProductName = product.Name,
Quantity = orderItem.Quantity,
IsDownload = product.IsDownload,
DownloadCount = orderItem.DownloadCount,
DownloadActivationType = product.DownloadActivationType,
IsDownloadActivated = orderItem.IsDownloadActivated,
UnitPriceInclTaxValue = orderItem.UnitPriceInclTax,
UnitPriceExclTaxValue = orderItem.UnitPriceExclTax,
DiscountInclTaxValue = orderItem.DiscountAmountInclTax,
DiscountExclTaxValue = orderItem.DiscountAmountExclTax,
SubTotalInclTaxValue = orderItem.PriceInclTax,
SubTotalExclTaxValue = orderItem.PriceExclTax,
AttributeInfo = orderItem.AttributeDescription
};
//fill in additional values (not existing in the entity)
orderItemModel.Sku = await _productService.FormatSkuAsync(product, orderItem.AttributesXml);
orderItemModel.VendorName = (await _vendorService.GetVendorByIdAsync(product.VendorId))?.Name;
//picture
var orderItemPicture = await _pictureService.GetProductPictureAsync(product, orderItem.AttributesXml);
(orderItemModel.PictureThumbnailUrl, _) = await _pictureService.GetPictureUrlAsync(orderItemPicture, 75);
//license file
if (orderItem.LicenseDownloadId.HasValue)
{
orderItemModel.LicenseDownloadGuid = (await _downloadService
.GetDownloadByIdAsync(orderItem.LicenseDownloadId.Value))?.DownloadGuid ?? Guid.Empty;
}
var languageId = (await _workContext.GetWorkingLanguageAsync()).Id;
//unit price
orderItemModel.UnitPriceInclTax = await _priceFormatter
.FormatOrderPriceAsync(orderItem.UnitPriceInclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, true, true);
orderItemModel.UnitPriceExclTax = await _priceFormatter
.FormatOrderPriceAsync(orderItem.UnitPriceExclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, false, true);
//discounts
orderItemModel.DiscountInclTax = await _priceFormatter
.FormatOrderPriceAsync(orderItem.DiscountAmountInclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, true, true);
orderItemModel.DiscountExclTax = await _priceFormatter
.FormatOrderPriceAsync(orderItem.DiscountAmountExclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, false, true);
//subtotal
orderItemModel.SubTotalInclTax = await _priceFormatter
.FormatOrderPriceAsync(orderItem.PriceInclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, true, true);
orderItemModel.SubTotalExclTax = await _priceFormatter
.FormatOrderPriceAsync(orderItem.PriceExclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, false, true);
//recurring info
if (product.IsRecurring)
{
orderItemModel.RecurringInfo = string.Format(await _localizationService.GetResourceAsync("Admin.Orders.Products.RecurringPeriod"),
product.RecurringCycleLength, await _localizationService.GetLocalizedEnumAsync(product.RecurringCyclePeriod));
}
//rental info
if (product.IsRental)
{
var rentalStartDate = orderItem.RentalStartDateUtc.HasValue
? _productService.FormatRentalDate(product, orderItem.RentalStartDateUtc.Value) : string.Empty;
var rentalEndDate = orderItem.RentalEndDateUtc.HasValue
? _productService.FormatRentalDate(product, orderItem.RentalEndDateUtc.Value) : string.Empty;
orderItemModel.RentalInfo = string.Format(await _localizationService.GetResourceAsync("Order.Rental.FormattedDate"),
rentalStartDate, rentalEndDate);
}
//prepare return request models
await PrepareReturnRequestBriefModelsAsync(orderItemModel.ReturnRequests, orderItem);
//gift card identifiers
orderItemModel.PurchasedGiftCardIds = (await _giftCardService
.GetGiftCardsByPurchasedWithOrderItemIdAsync(orderItem.Id)).Select(card => card.Id).ToList();
models.Add(orderItemModel);
}
}
/// <summary>
/// Prepare return request brief models
/// </summary>
/// <param name="models">List of return request brief models</param>
/// <param name="orderItem">Order item</param>
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task PrepareReturnRequestBriefModelsAsync(IList<OrderItemModel.ReturnRequestBriefModel> models, OrderItem orderItem)
{
if (models == null)
throw new ArgumentNullException(nameof(models));
if (orderItem == null)
throw new ArgumentNullException(nameof(orderItem));
var returnRequests = await _returnRequestService.SearchReturnRequestsAsync(orderItemId: orderItem.Id);
foreach (var returnRequest in returnRequests)
{
models.Add(new OrderItemModel.ReturnRequestBriefModel
{
CustomNumber = returnRequest.CustomNumber,
Id = returnRequest.Id
});
}
}
/// <summary>
/// Prepare order model totals
/// </summary>
/// <param name="model">Order model</param>
/// <param name="order">Order</param>
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task PrepareOrderModelTotalsAsync(OrderModel model, Order order)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
if (order == null)
throw new ArgumentNullException(nameof(order));
var primaryStoreCurrency = await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId);
var languageId = (await _workContext.GetWorkingLanguageAsync()).Id;
//subtotal
model.OrderSubtotalInclTax = await _priceFormatter
.FormatOrderPriceAsync(order.OrderSubtotalInclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, true);
model.OrderSubtotalExclTax = await _priceFormatter
.FormatOrderPriceAsync(order.OrderSubtotalExclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, false);
model.OrderSubtotalInclTaxValue = order.OrderSubtotalInclTax;
model.OrderSubtotalExclTaxValue = order.OrderSubtotalExclTax;
//discount (applied to order subtotal)
var orderSubtotalDiscountInclTaxStr = await _priceFormatter
.FormatOrderPriceAsync(order.OrderSubTotalDiscountInclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, true);
var orderSubtotalDiscountExclTaxStr = await _priceFormatter
.FormatOrderPriceAsync(order.OrderSubTotalDiscountExclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, false);
if (order.OrderSubTotalDiscountInclTax > decimal.Zero)
model.OrderSubTotalDiscountInclTax = orderSubtotalDiscountInclTaxStr;
if (order.OrderSubTotalDiscountExclTax > decimal.Zero)
model.OrderSubTotalDiscountExclTax = orderSubtotalDiscountExclTaxStr;
model.OrderSubTotalDiscountInclTaxValue = order.OrderSubTotalDiscountInclTax;
model.OrderSubTotalDiscountExclTaxValue = order.OrderSubTotalDiscountExclTax;
//shipping
model.OrderShippingInclTax = await _priceFormatter
.FormatOrderPriceAsync(order.OrderShippingInclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, true,
_taxSettings.ShippingIsTaxable && _taxSettings.DisplayTaxSuffix);
model.OrderShippingExclTax = await _priceFormatter
.FormatOrderPriceAsync(order.OrderShippingExclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, false,
_taxSettings.ShippingIsTaxable && _taxSettings.DisplayTaxSuffix);
model.OrderShippingInclTaxValue = order.OrderShippingInclTax;
model.OrderShippingExclTaxValue = order.OrderShippingExclTax;
//payment method additional fee
if (order.PaymentMethodAdditionalFeeInclTax > decimal.Zero)
{
model.PaymentMethodAdditionalFeeInclTax = await _priceFormatter
.FormatOrderPriceAsync(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, true,
_taxSettings.PaymentMethodAdditionalFeeIsTaxable && _taxSettings.DisplayTaxSuffix);
model.PaymentMethodAdditionalFeeExclTax = await _priceFormatter
.FormatOrderPriceAsync(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, false,
_taxSettings.PaymentMethodAdditionalFeeIsTaxable && _taxSettings.DisplayTaxSuffix);
}
model.PaymentMethodAdditionalFeeInclTaxValue = order.PaymentMethodAdditionalFeeInclTax;
model.PaymentMethodAdditionalFeeExclTaxValue = order.PaymentMethodAdditionalFeeExclTax;
//tax
model.Tax = await _priceFormatter
.FormatOrderPriceAsync(order.OrderTax, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, null, false);
var taxRates = _orderService.ParseTaxRates(order, order.TaxRates);
var displayTaxRates = _taxSettings.DisplayTaxRates && taxRates.Any();
var displayTax = !displayTaxRates;
foreach (var tr in taxRates)
{
model.TaxRates.Add(new OrderModel.TaxRate
{
Rate = _priceFormatter.FormatTaxRate(tr.Key),
Value = await _priceFormatter
.FormatOrderPriceAsync(tr.Value, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, null, false)
});
}
model.DisplayTaxRates = displayTaxRates;
model.DisplayTax = displayTax;
model.TaxValue = order.OrderTax;
model.TaxRatesValue = order.TaxRates;
//discount
if (order.OrderDiscount > 0)
{
model.OrderTotalDiscount = await _priceFormatter
.FormatOrderPriceAsync(-order.OrderDiscount, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, null, false);
}
model.OrderTotalDiscountValue = order.OrderDiscount;
//gift cards
foreach (var gcuh in await _giftCardService.GetGiftCardUsageHistoryAsync(order))
{
model.GiftCards.Add(new OrderModel.GiftCard
{
CouponCode = (await _giftCardService.GetGiftCardByIdAsync(gcuh.GiftCardId)).GiftCardCouponCode,
Amount = await _priceFormatter.FormatPriceAsync(-gcuh.UsedValue, true, false)
});
}
//reward points
if (order.RedeemedRewardPointsEntryId.HasValue && await _rewardPointService.GetRewardPointsHistoryEntryByIdAsync(order.RedeemedRewardPointsEntryId.Value) is RewardPointsHistory redeemedRewardPointsEntry)
{
model.RedeemedRewardPoints = -redeemedRewardPointsEntry.Points;
model.RedeemedRewardPointsAmount =
await _priceFormatter.FormatPriceAsync(-redeemedRewardPointsEntry.UsedAmount, true, false);
}
//total
model.OrderTotal = await _priceFormatter
.FormatOrderPriceAsync(order.OrderTotal, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, null, false);
model.OrderTotalValue = order.OrderTotal;
//refunded amount
if (order.RefundedAmount > decimal.Zero)
model.RefundedAmount = await _priceFormatter.FormatPriceAsync(order.RefundedAmount, true, false);
//used discounts
var duh = await _discountService.GetAllDiscountUsageHistoryAsync(orderId: order.Id);
foreach (var d in duh)
{
var discount = await _discountService.GetDiscountByIdAsync(d.DiscountId);
model.UsedDiscounts.Add(new OrderModel.UsedDiscountModel
{
DiscountId = d.DiscountId,
DiscountName = discount.Name
});
}
//profit (hide for vendors)
if (await _workContext.GetCurrentVendorAsync() != null)
return;
var profit = await _orderReportService.ProfitReportAsync(orderId: order.Id);
model.Profit = await _priceFormatter
.FormatOrderPriceAsync(profit, order.CurrencyRate, order.CustomerCurrencyCode,
_orderSettings.DisplayCustomerCurrencyOnOrders, primaryStoreCurrency, languageId, null, false);
}
/// <summary>
/// Prepare order model payment info
/// </summary>
/// <param name="model">Order model</param>
/// <param name="order">Order</param>
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task PrepareOrderModelPaymentInfoAsync(OrderModel model, Order order)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
if (order == null)
throw new ArgumentNullException(nameof(order));
var billingAddress = await _addressService.GetAddressByIdAsync(order.BillingAddressId);
//prepare billing address
model.BillingAddress = billingAddress.ToModel(model.BillingAddress);
model.BillingAddress.CountryName = (await _countryService.GetCountryByAddressAsync(billingAddress))?.Name;
model.BillingAddress.StateProvinceName = (await _stateProvinceService.GetStateProvinceByAddressAsync(billingAddress))?.Name;
await _addressModelFactory.PrepareAddressModelAsync(model.BillingAddress, billingAddress);
SetAddressFieldsAsRequired(model.BillingAddress);
if (order.AllowStoringCreditCardNumber)
{
//card type
model.CardType = _encryptionService.DecryptText(order.CardType);
//cardholder name
model.CardName = _encryptionService.DecryptText(order.CardName);
//card number
model.CardNumber = _encryptionService.DecryptText(order.CardNumber);
//cvv
model.CardCvv2 = _encryptionService.DecryptText(order.CardCvv2);
//expiry date
var cardExpirationMonthDecrypted = _encryptionService.DecryptText(order.CardExpirationMonth);
if (!string.IsNullOrEmpty(cardExpirationMonthDecrypted) && cardExpirationMonthDecrypted != "0")
model.CardExpirationMonth = cardExpirationMonthDecrypted;
var cardExpirationYearDecrypted = _encryptionService.DecryptText(order.CardExpirationYear);
if (!string.IsNullOrEmpty(cardExpirationYearDecrypted) && cardExpirationYearDecrypted != "0")
model.CardExpirationYear = cardExpirationYearDecrypted;
model.AllowStoringCreditCardNumber = true;
}
else
{
var maskedCreditCardNumberDecrypted = _encryptionService.DecryptText(order.MaskedCreditCardNumber);
if (!string.IsNullOrEmpty(maskedCreditCardNumberDecrypted))
model.CardNumber = maskedCreditCardNumberDecrypted;
}
//payment transaction info
model.AuthorizationTransactionId = order.AuthorizationTransactionId;
model.CaptureTransactionId = order.CaptureTransactionId;
model.SubscriptionTransactionId = order.SubscriptionTransactionId;
//payment method info
var pm = await _paymentPluginManager.LoadPluginBySystemNameAsync(order.PaymentMethodSystemName);
model.PaymentMethod = pm != null ? pm.PluginDescriptor.FriendlyName : order.PaymentMethodSystemName;
model.PaymentStatus = await _localizationService.GetLocalizedEnumAsync(order.PaymentStatus);
//payment method buttons
model.CanCancelOrder = _orderProcessingService.CanCancelOrder(order);
model.CanCapture = await _orderProcessingService.CanCaptureAsync(order);
model.CanMarkOrderAsPaid = _orderProcessingService.CanMarkOrderAsPaid(order);
model.CanRefund = await _orderProcessingService.CanRefundAsync(order);
model.CanRefundOffline = _orderProcessingService.CanRefundOffline(order);
model.CanPartiallyRefund = await _orderProcessingService.CanPartiallyRefundAsync(order, decimal.Zero);
model.CanPartiallyRefundOffline = _orderProcessingService.CanPartiallyRefundOffline(order, decimal.Zero);
model.CanVoid = await _orderProcessingService.CanVoidAsync(order);
model.CanVoidOffline = _orderProcessingService.CanVoidOffline(order);
model.PrimaryStoreCurrencyCode = (await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId))?.CurrencyCode;
model.MaxAmountToRefund = order.OrderTotal - order.RefundedAmount;
//recurring payment record
model.RecurringPaymentId = (await _orderService.SearchRecurringPaymentsAsync(initialOrderId: order.Id, showHidden: true)).FirstOrDefault()?.Id ?? 0;
}
/// <summary>
/// Prepare order model shipping info
/// </summary>
/// <param name="model">Order model</param>
/// <param name="order">Order</param>
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task PrepareOrderModelShippingInfoAsync(OrderModel model, Order order)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
if (order == null)
throw new ArgumentNullException(nameof(order));
model.ShippingStatus = await _localizationService.GetLocalizedEnumAsync(order.ShippingStatus);
if (order.ShippingStatus == ShippingStatus.ShippingNotRequired)
return;
model.IsShippable = true;
model.ShippingMethod = order.ShippingMethod;
model.CanAddNewShipments = await _orderService.HasItemsToAddToShipmentAsync(order);
model.PickupInStore = order.PickupInStore;
if (!order.PickupInStore)
{
var shippingAddress = await _addressService.GetAddressByIdAsync(order.ShippingAddressId.Value);
var shippingCountry = await _countryService.GetCountryByAddressAsync(shippingAddress);
model.ShippingAddress = shippingAddress.ToModel(model.ShippingAddress);
model.ShippingAddress.CountryName = shippingCountry?.Name;
model.ShippingAddress.StateProvinceName = (await _stateProvinceService.GetStateProvinceByAddressAsync(shippingAddress))?.Name;
await _addressModelFactory.PrepareAddressModelAsync(model.ShippingAddress, shippingAddress);
SetAddressFieldsAsRequired(model.ShippingAddress);
model.ShippingAddressGoogleMapsUrl = "https://maps.google.com/maps?f=q&hl=en&ie=UTF8&oe=UTF8&geocode=&q=" +
$"{WebUtility.UrlEncode(shippingAddress.Address1 + " " + shippingAddress.ZipPostalCode + " " + shippingAddress.City + " " + (shippingCountry?.Name ?? string.Empty))}";
}
else
{
if (order.PickupAddressId is null)
return;
var pickupAddress = await _addressService.GetAddressByIdAsync(order.PickupAddressId.Value);
var pickupCountry = await _countryService.GetCountryByAddressAsync(pickupAddress);
model.PickupAddress = pickupAddress.ToModel(model.PickupAddress);
model.PickupAddressGoogleMapsUrl = $"https://maps.google.com/maps?f=q&hl=en&ie=UTF8&oe=UTF8&geocode=&q=" +
$"{WebUtility.UrlEncode($"{pickupAddress.Address1} {pickupAddress.ZipPostalCode} {pickupAddress.City} {(pickupCountry?.Name ?? string.Empty)}")}";
}
}
/// <summary>
/// Prepare product attribute models
/// </summary>
/// <param name="models">List of product attribute models</param>
/// <param name="order">Order</param>
/// <param name="product">Product</param>
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task PrepareProductAttributeModelsAsync(IList<AddProductToOrderModel.ProductAttributeModel> models, Order order, Product product)
{
if (models == null)
throw new ArgumentNullException(nameof(models));
if (order == null)
throw new ArgumentNullException(nameof(order));
if (product == null)
throw new ArgumentNullException(nameof(product));
var attributes = await _productAttributeService.GetProductAttributeMappingsByProductIdAsync(product.Id);
foreach (var attribute in attributes)
{
var attributeModel = new AddProductToOrderModel.ProductAttributeModel
{
Id = attribute.Id,
ProductAttributeId = attribute.ProductAttributeId,
Name = (await _productAttributeService.GetProductAttributeByIdAsync(attribute.ProductAttributeId)).Name,
TextPrompt = attribute.TextPrompt,
IsRequired = attribute.IsRequired,
AttributeControlType = attribute.AttributeControlType,
HasCondition = !string.IsNullOrEmpty(attribute.ConditionAttributeXml)
};
if (!string.IsNullOrEmpty(attribute.ValidationFileAllowedExtensions))
{
attributeModel.AllowedFileExtensions = attribute.ValidationFileAllowedExtensions
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
}
if (attribute.ShouldHaveValues())
{
var customer = await _customerService.GetCustomerByIdAsync(order.CustomerId);
//values
var attributeValues = await _productAttributeService.GetProductAttributeValuesAsync(attribute.Id);
foreach (var attributeValue in attributeValues)
{
//price adjustment
var (priceAdjustment, _) = await _taxService.GetProductPriceAsync(product,
await _priceCalculationService.GetProductAttributeValuePriceAdjustmentAsync(product, attributeValue, customer));
var priceAdjustmentStr = string.Empty;
if (priceAdjustment != 0)
{
if (attributeValue.PriceAdjustmentUsePercentage)
{
priceAdjustmentStr = attributeValue.PriceAdjustment.ToString("G29");
priceAdjustmentStr = priceAdjustment > 0 ? $"+{priceAdjustmentStr}%" : $"{priceAdjustmentStr}%";
}
else
{
priceAdjustmentStr = priceAdjustment > 0 ? $"+{await _priceFormatter.FormatPriceAsync(priceAdjustment, false, false)}" : $"-{await _priceFormatter.FormatPriceAsync(-priceAdjustment, false, false)}";
}
}
attributeModel.Values.Add(new AddProductToOrderModel.ProductAttributeValueModel
{
Id = attributeValue.Id,
Name = attributeValue.Name,
IsPreSelected = attributeValue.IsPreSelected,
CustomerEntersQty = attributeValue.CustomerEntersQty,
Quantity = attributeValue.Quantity,
PriceAdjustment = priceAdjustmentStr,
PriceAdjustmentValue = priceAdjustment
});
}
}
models.Add(attributeModel);
}
}
/// <summary>
/// Prepare shipment item model
/// </summary>
/// <param name="model">Shipment item model</param>
/// <param name="orderItem">Order item</param>
/// <param name="product">Product item</param>
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task PrepareShipmentItemModelAsync(ShipmentItemModel model, OrderItem orderItem, Product product)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
if (orderItem is null)
throw new ArgumentNullException(nameof(orderItem));
if (product is null)
throw new ArgumentNullException(nameof(product));
if (orderItem.ProductId != product.Id)
throw new ArgumentException($"{nameof(orderItem.ProductId)} != {nameof(product.Id)}");
//fill in additional values (not existing in the entity)
model.OrderItemId = orderItem.Id;
model.ProductId = orderItem.ProductId;
model.ProductName = product.Name;
model.Sku = await _productService.FormatSkuAsync(product, orderItem.AttributesXml);
model.AttributeInfo = orderItem.AttributeDescription;
model.ShipSeparately = product.ShipSeparately;
model.QuantityOrdered = orderItem.Quantity;
model.QuantityInAllShipments = await _orderService.GetTotalNumberOfItemsInAllShipmentAsync(orderItem);
model.QuantityToAdd = await _orderService.GetTotalNumberOfItemsCanBeAddedToShipmentAsync(orderItem);
var baseWeight = (await _measureService.GetMeasureWeightByIdAsync(_measureSettings.BaseWeightId))?.Name;
var baseDimension = (await _measureService.GetMeasureDimensionByIdAsync(_measureSettings.BaseDimensionId))?.Name;
if (orderItem.ItemWeight.HasValue)
model.ItemWeight = $"{orderItem.ItemWeight:F2} [{baseWeight}]";
model.ItemDimensions =
$"{product.Length:F2} x {product.Width:F2} x {product.Height:F2} [{baseDimension}]";
if (!product.IsRental)
return;
var rentalStartDate = orderItem.RentalStartDateUtc.HasValue
? _productService.FormatRentalDate(product, orderItem.RentalStartDateUtc.Value) : string.Empty;
var rentalEndDate = orderItem.RentalEndDateUtc.HasValue
? _productService.FormatRentalDate(product, orderItem.RentalEndDateUtc.Value) : string.Empty;
model.RentalInfo = string.Format(await _localizationService.GetResourceAsync("Order.Rental.FormattedDate"), rentalStartDate, rentalEndDate);
}
/// <summary>
/// Prepare shipment status event models
/// </summary>
/// <param name="models">List of shipment status event models</param>
/// <param name="shipment">Shipment</param>
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task PrepareShipmentStatusEventModelsAsync(IList<ShipmentStatusEventModel> models, Shipment shipment)
{
if (models == null)
throw new ArgumentNullException(nameof(models));
var shipmentTracker = await _shipmentService.GetShipmentTrackerAsync(shipment);
var shipmentEvents = await shipmentTracker.GetShipmentEventsAsync(shipment.TrackingNumber);
if (shipmentEvents == null)
return;
foreach (var shipmentEvent in shipmentEvents)
{
var shipmentStatusEventModel = new ShipmentStatusEventModel
{
Date = shipmentEvent.Date,
EventName = shipmentEvent.EventName,
Location = shipmentEvent.Location
};
var shipmentEventCountry = await _countryService.GetCountryByTwoLetterIsoCodeAsync(shipmentEvent.CountryCode);
shipmentStatusEventModel.Country = shipmentEventCountry != null
? await _localizationService.GetLocalizedAsync(shipmentEventCountry, x => x.Name) : shipmentEvent.CountryCode;
models.Add(shipmentStatusEventModel);
}
}
/// <summary>
/// Prepare order shipment search model
/// </summary>
/// <param name="searchModel">Order shipment search model</param>
/// <param name="order">Order</param>
/// <returns>Order shipment search model</returns>
protected virtual OrderShipmentSearchModel PrepareOrderShipmentSearchModel(OrderShipmentSearchModel searchModel, Order order)
{
if (searchModel == null)
throw new ArgumentNullException(nameof(searchModel));
if (order == null)
throw new ArgumentNullException(nameof(order));
searchModel.OrderId = order.Id;
//prepare nested search model
PrepareShipmentItemSearchModel(searchModel.ShipmentItemSearchModel);
//prepare page parameters
searchModel.SetGridPageSize();
return searchModel;
}
/// <summary>
/// Prepare shipment item search model
/// </summary>
/// <param name="searchModel">Shipment item search model</param>
/// <returns>Shipment item search model</returns>
protected virtual ShipmentItemSearchModel PrepareShipmentItemSearchModel(ShipmentItemSearchModel searchModel)
{
if (searchModel == null)
throw new ArgumentNullException(nameof(searchModel));
//prepare page parameters
searchModel.SetGridPageSize();
return searchModel;
}
/// <summary>
/// Prepare order note search model
/// </summary>
/// <param name="searchModel">Order note search model</param>
/// <param name="order">Order</param>
/// <returns>Order note search model</returns>
protected virtual OrderNoteSearchModel PrepareOrderNoteSearchModel(OrderNoteSearchModel searchModel, Order order)
{
if (searchModel == null)
throw new ArgumentNullException(nameof(searchModel));
if (order == null)
throw new ArgumentNullException(nameof(order));
searchModel.OrderId = order.Id;
//prepare page parameters
searchModel.SetGridPageSize();
return searchModel;
}
#endregion
#region Methods
/// <summary>
/// Prepare order search model
/// </summary>
/// <param name="searchModel">Order search model</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the order search model
/// </returns>
public virtual async Task<OrderSearchModel> PrepareOrderSearchModelAsync(OrderSearchModel searchModel)
{
if (searchModel == null)
throw new ArgumentNullException(nameof(searchModel));
searchModel.IsLoggedInAsVendor = await _workContext.GetCurrentVendorAsync() != null;
searchModel.BillingPhoneEnabled = _addressSettings.PhoneEnabled;
//prepare available order, payment and shipping statuses
await _baseAdminModelFactory.PrepareOrderStatusesAsync(searchModel.AvailableOrderStatuses);
if (searchModel.AvailableOrderStatuses.Any())
{
if (searchModel.OrderStatusIds?.Any() ?? false)
{
var ids = searchModel.OrderStatusIds.Select(id => id.ToString());
searchModel.AvailableOrderStatuses.Where(statusItem => ids.Contains(statusItem.Value)).ToList()
.ForEach(statusItem => statusItem.Selected = true);
}
else
searchModel.AvailableOrderStatuses.FirstOrDefault().Selected = true;
}
await _baseAdminModelFactory.PreparePaymentStatusesAsync(searchModel.AvailablePaymentStatuses);
if (searchModel.AvailablePaymentStatuses.Any())
{
if (searchModel.PaymentStatusIds?.Any() ?? false)
{
var ids = searchModel.PaymentStatusIds.Select(id => id.ToString());
searchModel.AvailablePaymentStatuses.Where(statusItem => ids.Contains(statusItem.Value)).ToList()
.ForEach(statusItem => statusItem.Selected = true);
}
else
searchModel.AvailablePaymentStatuses.FirstOrDefault().Selected = true;
}
await _baseAdminModelFactory.PrepareShippingStatusesAsync(searchModel.AvailableShippingStatuses);
if (searchModel.AvailableShippingStatuses.Any())
{
if (searchModel.ShippingStatusIds?.Any() ?? false)
{
var ids = searchModel.ShippingStatusIds.Select(id => id.ToString());
searchModel.AvailableShippingStatuses.Where(statusItem => ids.Contains(statusItem.Value)).ToList()
.ForEach(statusItem => statusItem.Selected = true);
}
else
searchModel.AvailableShippingStatuses.FirstOrDefault().Selected = true;
}
//prepare available stores
await _baseAdminModelFactory.PrepareStoresAsync(searchModel.AvailableStores);
//prepare available vendors
await _baseAdminModelFactory.PrepareVendorsAsync(searchModel.AvailableVendors);
//prepare available warehouses
await _baseAdminModelFactory.PrepareWarehousesAsync(searchModel.AvailableWarehouses);
//prepare available payment methods
searchModel.AvailablePaymentMethods = (await _paymentPluginManager.LoadAllPluginsAsync()).Select(method =>
new SelectListItem { Text = method.PluginDescriptor.FriendlyName, Value = method.PluginDescriptor.SystemName }).ToList();
searchModel.AvailablePaymentMethods.Insert(0, new SelectListItem { Text = await _localizationService.GetResourceAsync("Admin.Common.All"), Value = string.Empty });
//prepare available billing countries
searchModel.AvailableCountries = (await _countryService.GetAllCountriesForBillingAsync(showHidden: true))
.Select(country => new SelectListItem { Text = country.Name, Value = country.Id.ToString() }).ToList();
searchModel.AvailableCountries.Insert(0, new SelectListItem { Text = await _localizationService.GetResourceAsync("Admin.Common.All"), Value = "0" });
//prepare grid
searchModel.SetGridPageSize();
searchModel.HideStoresList = _catalogSettings.IgnoreStoreLimitations || searchModel.AvailableStores.SelectionIsNotPossible();
return searchModel;
}
/// <summary>
/// Prepare paged order list model
/// </summary>
/// <param name="searchModel">Order search model</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the order list model
/// </returns>
public virtual async Task<OrderListModel> PrepareOrderListModelAsync(OrderSearchModel searchModel)
{
if (searchModel == null)
throw new ArgumentNullException(nameof(searchModel));
//get parameters to filter orders
var orderStatusIds = (searchModel.OrderStatusIds?.Contains(0) ?? true) ? null : searchModel.OrderStatusIds.ToList();
var paymentStatusIds = (searchModel.PaymentStatusIds?.Contains(0) ?? true) ? null : searchModel.PaymentStatusIds.ToList();
var shippingStatusIds = (searchModel.ShippingStatusIds?.Contains(0) ?? true) ? null : searchModel.ShippingStatusIds.ToList();
if (await _workContext.GetCurrentVendorAsync() != null)
searchModel.VendorId = (await _workContext.GetCurrentVendorAsync()).Id;
var startDateValue = !searchModel.StartDate.HasValue ? null
: (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.StartDate.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync());
var endDateValue = !searchModel.EndDate.HasValue ? null
: (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.EndDate.Value, await _dateTimeHelper.GetCurrentTimeZoneAsync()).AddDays(1);
var product = await _productService.GetProductByIdAsync(searchModel.ProductId);
var filterByProductId = product != null && (await _workContext.GetCurrentVendorAsync() == null || product.VendorId == (await _workContext.GetCurrentVendorAsync()).Id)
? searchModel.ProductId : 0;
//get orders
var orders = await _orderService.SearchOrdersAsync(storeId: searchModel.StoreId,
vendorId: searchModel.VendorId,
productId: filterByProductId,
warehouseId: searchModel.WarehouseId,
paymentMethodSystemName: searchModel.PaymentMethodSystemName,
createdFromUtc: startDateValue,
createdToUtc: endDateValue,
osIds: orderStatusIds,
psIds: paymentStatusIds,
ssIds: shippingStatusIds,
billingPhone: searchModel.BillingPhone,
billingEmail: searchModel.BillingEmail,
billingLastName: searchModel.BillingLastName,
billingCountryId: searchModel.BillingCountryId,
orderNotes: searchModel.OrderNotes,
pageIndex: searchModel.Page - 1, pageSize: searchModel.PageSize);
//prepare list model
var model = await new OrderListModel().PrepareToGridAsync(searchModel, orders, () =>
{
//fill in model values from the entity
return orders.SelectAwait(async order =>
{
var billingAddress = await _addressService.GetAddressByIdAsync(order.BillingAddressId);
//fill in model values from the entity
var orderModel = new OrderModel
{
Id = order.Id,