-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathExportManager.cs
2557 lines (2249 loc) · 169 KB
/
ExportManager.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.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Xml;
using ClosedXML.Excel;
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.Forums;
using Nop.Core.Domain.Gdpr;
using Nop.Core.Domain.Localization;
using Nop.Core.Domain.Messages;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Domain.Security;
using Nop.Core.Domain.Seo;
using Nop.Core.Domain.Shipping;
using Nop.Core.Domain.Stores;
using Nop.Core.Domain.Tax;
using Nop.Core.Domain.Vendors;
using Nop.Services.Attributes;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Discounts;
using Nop.Services.ExportImport.Help;
using Nop.Services.Forums;
using Nop.Services.Gdpr;
using Nop.Services.Helpers;
using Nop.Services.Localization;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.Messages;
using Nop.Services.Orders;
using Nop.Services.Seo;
using Nop.Services.Shipping;
using Nop.Services.Shipping.Date;
using Nop.Services.Stores;
using Nop.Services.Tax;
using Nop.Services.Vendors;
namespace Nop.Services.ExportImport;
/// <summary>
/// Export manager
/// </summary>
public partial class ExportManager : IExportManager
{
#region Fields
protected readonly AddressSettings _addressSettings;
protected readonly CatalogSettings _catalogSettings;
protected readonly SecuritySettings _securitySettings;
protected readonly ICustomerActivityService _customerActivityService;
protected readonly CustomerSettings _customerSettings;
protected readonly DateTimeSettings _dateTimeSettings;
protected readonly ForumSettings _forumSettings;
protected readonly IAddressService _addressService;
protected readonly ICategoryService _categoryService;
protected readonly ICountryService _countryService;
protected readonly ICurrencyService _currencyService;
protected readonly IAttributeFormatter<CustomerAttribute, CustomerAttributeValue> _customerAttributeFormatter;
protected readonly ICustomerService _customerService;
protected readonly IDateRangeService _dateRangeService;
protected readonly IDateTimeHelper _dateTimeHelper;
protected readonly IDiscountService _discountService;
protected readonly IForumService _forumService;
protected readonly IGdprService _gdprService;
protected readonly IGenericAttributeService _genericAttributeService;
protected readonly ILanguageService _languageService;
protected readonly ILocalizationService _localizationService;
protected readonly ILocalizedEntityService _localizedEntityService;
protected readonly IManufacturerService _manufacturerService;
protected readonly IMeasureService _measureService;
protected readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
protected readonly IOrderService _orderService;
protected readonly IPictureService _pictureService;
protected readonly IPriceFormatter _priceFormatter;
protected readonly IProductAttributeService _productAttributeService;
protected readonly IProductService _productService;
protected readonly IProductTagService _productTagService;
protected readonly IProductTemplateService _productTemplateService;
protected readonly IShipmentService _shipmentService;
protected readonly ISpecificationAttributeService _specificationAttributeService;
protected readonly IStateProvinceService _stateProvinceService;
protected readonly IStoreMappingService _storeMappingService;
protected readonly IStoreService _storeService;
protected readonly ITaxCategoryService _taxCategoryService;
protected readonly IUrlRecordService _urlRecordService;
protected readonly IVendorService _vendorService;
protected readonly IWorkContext _workContext;
protected readonly OrderSettings _orderSettings;
protected readonly ProductEditorSettings _productEditorSettings;
#endregion
#region Ctor
public ExportManager(AddressSettings addressSettings,
CatalogSettings catalogSettings,
SecuritySettings securitySettings,
CustomerSettings customerSettings,
DateTimeSettings dateTimeSettings,
ForumSettings forumSettings,
IAddressService addressService,
IAttributeFormatter<CustomerAttribute, CustomerAttributeValue> customerAttributeFormatter,
ICategoryService categoryService,
ICountryService countryService,
ICurrencyService currencyService,
ICustomerActivityService customerActivityService,
ICustomerService customerService,
IDateRangeService dateRangeService,
IDateTimeHelper dateTimeHelper,
IDiscountService discountService,
IForumService forumService,
IGdprService gdprService,
IGenericAttributeService genericAttributeService,
ILanguageService languageService,
ILocalizationService localizationService,
ILocalizedEntityService localizedEntityService,
IManufacturerService manufacturerService,
IMeasureService measureService,
INewsLetterSubscriptionService newsLetterSubscriptionService,
IOrderService orderService,
IPictureService pictureService,
IPriceFormatter priceFormatter,
IProductAttributeService productAttributeService,
IProductService productService,
IProductTagService productTagService,
IProductTemplateService productTemplateService,
IShipmentService shipmentService,
ISpecificationAttributeService specificationAttributeService,
IStateProvinceService stateProvinceService,
IStoreMappingService storeMappingService,
IStoreService storeService,
ITaxCategoryService taxCategoryService,
IUrlRecordService urlRecordService,
IVendorService vendorService,
IWorkContext workContext,
OrderSettings orderSettings,
ProductEditorSettings productEditorSettings)
{
_addressSettings = addressSettings;
_catalogSettings = catalogSettings;
_securitySettings = securitySettings;
_customerSettings = customerSettings;
_dateTimeSettings = dateTimeSettings;
_addressService = addressService;
_customerAttributeFormatter = customerAttributeFormatter;
_forumSettings = forumSettings;
_categoryService = categoryService;
_countryService = countryService;
_currencyService = currencyService;
_customerActivityService = customerActivityService;
_customerService = customerService;
_dateRangeService = dateRangeService;
_dateTimeHelper = dateTimeHelper;
_discountService = discountService;
_forumService = forumService;
_gdprService = gdprService;
_genericAttributeService = genericAttributeService;
_languageService = languageService;
_localizationService = localizationService;
_localizedEntityService = localizedEntityService;
_manufacturerService = manufacturerService;
_measureService = measureService;
_newsLetterSubscriptionService = newsLetterSubscriptionService;
_orderService = orderService;
_pictureService = pictureService;
_priceFormatter = priceFormatter;
_productAttributeService = productAttributeService;
_productService = productService;
_productTagService = productTagService;
_productTemplateService = productTemplateService;
_shipmentService = shipmentService;
_specificationAttributeService = specificationAttributeService;
_stateProvinceService = stateProvinceService;
_storeMappingService = storeMappingService;
_storeService = storeService;
_taxCategoryService = taxCategoryService;
_urlRecordService = urlRecordService;
_vendorService = vendorService;
_workContext = workContext;
_orderSettings = orderSettings;
_productEditorSettings = productEditorSettings;
}
#endregion
#region Utilities
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<int> WriteCategoriesAsync(XmlWriter xmlWriter, int parentCategoryId, int totalCategories)
{
var categories = await _categoryService.GetAllCategoriesByParentCategoryIdAsync(parentCategoryId, true);
if (categories == null || !categories.Any())
return totalCategories;
totalCategories += categories.Count;
var languages = await _languageService.GetAllLanguagesAsync(showHidden: true);
foreach (var category in categories)
{
await xmlWriter.WriteStartElementAsync("Category");
await xmlWriter.WriteStringAsync("Id", category.Id);
await WriteLocalizedPropertyXmlAsync(category, c => c.Name, xmlWriter, languages);
await WriteLocalizedPropertyXmlAsync(category, c => c.Description, xmlWriter, languages);
await xmlWriter.WriteStringAsync("CategoryTemplateId", category.CategoryTemplateId);
await WriteLocalizedPropertyXmlAsync(category, c => c.MetaKeywords, xmlWriter, languages, await IgnoreExportCategoryPropertyAsync());
await WriteLocalizedPropertyXmlAsync(category, c => c.MetaDescription, xmlWriter, languages, await IgnoreExportCategoryPropertyAsync());
await WriteLocalizedPropertyXmlAsync(category, c => c.MetaTitle, xmlWriter, languages, await IgnoreExportCategoryPropertyAsync());
await WriteLocalizedSeNameXmlAsync(category, xmlWriter, languages, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStringAsync("ParentCategoryId", category.ParentCategoryId);
await xmlWriter.WriteStringAsync("PictureId", category.PictureId);
await xmlWriter.WriteStringAsync("PageSize", category.PageSize, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStringAsync("AllowCustomersToSelectPageSize", category.AllowCustomersToSelectPageSize, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStringAsync("PageSizeOptions", category.PageSizeOptions, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStringAsync("PriceRangeFiltering", category.PriceRangeFiltering, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStringAsync("PriceFrom", category.PriceFrom, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStringAsync("PriceTo", category.PriceTo, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStringAsync("ManuallyPriceRange", category.ManuallyPriceRange, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStringAsync("ShowOnHomepage", category.ShowOnHomepage, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStringAsync("IncludeInTopMenu", category.IncludeInTopMenu, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStringAsync("Published", category.Published, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStringAsync("Deleted", category.Deleted, true);
await xmlWriter.WriteStringAsync("DisplayOrder", category.DisplayOrder);
await xmlWriter.WriteStringAsync("CreatedOnUtc", category.CreatedOnUtc, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStringAsync("UpdatedOnUtc", category.UpdatedOnUtc, await IgnoreExportCategoryPropertyAsync());
await xmlWriter.WriteStartElementAsync("Products");
var productCategories = await _categoryService.GetProductCategoriesByCategoryIdAsync(category.Id, showHidden: true);
foreach (var productCategory in productCategories)
{
var product = await _productService.GetProductByIdAsync(productCategory.ProductId);
if (product == null || product.Deleted)
continue;
await xmlWriter.WriteStartElementAsync("ProductCategory");
await xmlWriter.WriteStringAsync("ProductCategoryId", productCategory.Id);
await xmlWriter.WriteStringAsync("ProductId", productCategory.ProductId);
await WriteLocalizedPropertyXmlAsync(product, p => p.Name, xmlWriter, languages, overriddenNodeName: "ProductName");
await xmlWriter.WriteStringAsync("IsFeaturedProduct", productCategory.IsFeaturedProduct);
await xmlWriter.WriteStringAsync("DisplayOrder", productCategory.DisplayOrder);
await xmlWriter.WriteEndElementAsync();
}
await xmlWriter.WriteEndElementAsync();
await xmlWriter.WriteStartElementAsync("SubCategories");
totalCategories = await WriteCategoriesAsync(xmlWriter, category.Id, totalCategories);
await xmlWriter.WriteEndElementAsync();
await xmlWriter.WriteEndElementAsync();
}
return totalCategories;
}
/// <summary>
/// Returns the path to the image file by ID
/// </summary>
/// <param name="pictureId">Picture ID</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the path to the image file
/// </returns>
protected virtual async Task<string> GetPicturesAsync(int pictureId)
{
var picture = await _pictureService.GetPictureByIdAsync(pictureId);
return await _pictureService.GetThumbLocalPathAsync(picture);
}
/// <summary>
/// Returns the list of categories for a product separated by a ";"
/// </summary>
/// <param name="product">Product</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the list of categories
/// </returns>
protected virtual async Task<object> GetCategoriesAsync(Product product)
{
string categoryNames = null;
foreach (var pc in await _categoryService.GetProductCategoriesByProductIdAsync(product.Id, true))
{
if (_catalogSettings.ExportImportRelatedEntitiesByName)
{
var category = await _categoryService.GetCategoryByIdAsync(pc.CategoryId);
categoryNames += _catalogSettings.ExportImportProductCategoryBreadcrumb
? await _categoryService.GetFormattedBreadCrumbAsync(category)
: category.Name;
}
else
{
categoryNames += pc.CategoryId.ToString();
}
categoryNames += ";";
}
return categoryNames;
}
/// <summary>
/// Returns the list of manufacturer for a product separated by a ";"
/// </summary>
/// <param name="product">Product</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the list of manufacturer
/// </returns>
protected virtual async Task<object> GetManufacturersAsync(Product product)
{
string manufacturerNames = null;
foreach (var pm in await _manufacturerService.GetProductManufacturersByProductIdAsync(product.Id, true))
{
if (_catalogSettings.ExportImportRelatedEntitiesByName)
{
var manufacturer = await _manufacturerService.GetManufacturerByIdAsync(pm.ManufacturerId);
manufacturerNames += manufacturer.Name;
}
else
{
manufacturerNames += pm.ManufacturerId.ToString();
}
manufacturerNames += ";";
}
return manufacturerNames;
}
/// <summary>
/// Returns the list of limited to stores for a product separated by a ";"
/// </summary>
/// <param name="product">Product</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the list of store
/// </returns>
protected virtual async Task<object> GetLimitedToStoresAsync(Product product)
{
string limitedToStores = null;
foreach (var storeMapping in await _storeMappingService.GetStoreMappingsAsync(product))
{
var store = await _storeService.GetStoreByIdAsync(storeMapping.StoreId);
if (store == null)
continue;
limitedToStores += _catalogSettings.ExportImportRelatedEntitiesByName ? store.Name : store.Id.ToString();
limitedToStores += ";";
}
return limitedToStores;
}
/// <summary>
/// Returns the list of product tag for a product separated by a ";"
/// </summary>
/// <param name="product">Product</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the list of product tag
/// </returns>
protected virtual async Task<object> GetProductTagsAsync(Product product)
{
string productTagNames = null;
var productTags = await _productTagService.GetAllProductTagsByProductIdAsync(product.Id);
if (!productTags?.Any() ?? true)
return null;
foreach (var productTag in productTags)
{
productTagNames += _catalogSettings.ExportImportRelatedEntitiesByName
? productTag.Name
: productTag.Id.ToString();
productTagNames += ";";
}
return productTagNames;
}
/// <summary>
/// Returns the image at specified index associated with the product
/// </summary>
/// <param name="product">Product</param>
/// <param name="pictureIndex">Picture index to get</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the image thumb local path
/// </returns>
protected virtual async Task<string> GetPictureAsync(Product product, short pictureIndex)
{
// we need only the picture at a specific index, no need to get more pictures than that
var recordsToReturn = pictureIndex + 1;
var pictures = await _pictureService.GetPicturesByProductIdAsync(product.Id, recordsToReturn);
return pictures.Count > pictureIndex ? await _pictureService.GetThumbLocalPathAsync(pictures[pictureIndex]) : null;
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<bool> IgnoreExportProductPropertyAsync(Func<ProductEditorSettings, bool> func)
{
var productAdvancedMode = true;
try
{
productAdvancedMode = await _genericAttributeService.GetAttributeAsync<bool>(await _workContext.GetCurrentCustomerAsync(), "product-advanced-mode");
}
catch (ArgumentNullException)
{
}
return !productAdvancedMode && !func(_productEditorSettings);
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<bool> IgnoreExportCategoryPropertyAsync()
{
try
{
return !await _genericAttributeService.GetAttributeAsync<bool>(await _workContext.GetCurrentCustomerAsync(), "category-advanced-mode");
}
catch (ArgumentNullException)
{
return false;
}
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<bool> IgnoreExportManufacturerPropertyAsync()
{
try
{
return !await _genericAttributeService.GetAttributeAsync<bool>(await _workContext.GetCurrentCustomerAsync(), "manufacturer-advanced-mode");
}
catch (ArgumentNullException)
{
return false;
}
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<bool> IgnoreExportLimitedToStoreAsync()
{
return _catalogSettings.IgnoreStoreLimitations ||
!_catalogSettings.ExportImportProductUseLimitedToStores ||
(await _storeService.GetAllStoresAsync()).Count == 1;
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<TProperty> GetLocalizedAsync<TEntity, TProperty>(TEntity entity, Expression<Func<TEntity, TProperty>> keySelector,
Language language) where TEntity : BaseEntity, ILocalizedEntity
{
if (entity == null)
return default;
return await _localizationService.GetLocalizedAsync(entity, keySelector, language.Id, false);
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<PropertyManager<ExportProductAttribute, Language>> GetProductAttributeManagerAsync(IList<Language> languages)
{
var attributeProperties = new[]
{
new PropertyByName<ExportProductAttribute, Language>("AttributeId", (p, l) => p.AttributeId),
new PropertyByName<ExportProductAttribute, Language>("AttributeName", (p, l) => p.AttributeName),
new PropertyByName<ExportProductAttribute, Language>("DefaultValue", (p, l) => p.DefaultValue),
new PropertyByName<ExportProductAttribute, Language>("ValidationMinLength", (p, l) => p.ValidationMinLength),
new PropertyByName<ExportProductAttribute, Language>("ValidationMaxLength", (p, l) => p.ValidationMaxLength),
new PropertyByName<ExportProductAttribute, Language>("ValidationFileAllowedExtensions", (p, l) => p.ValidationFileAllowedExtensions),
new PropertyByName<ExportProductAttribute, Language>("ValidationFileMaximumSize", (p, l) => p.ValidationFileMaximumSize),
new PropertyByName<ExportProductAttribute, Language>("AttributeTextPrompt", (p, l) => p.AttributeTextPrompt),
new PropertyByName<ExportProductAttribute, Language>("AttributeIsRequired", (p, l) => p.AttributeIsRequired),
new PropertyByName<ExportProductAttribute, Language>("AttributeControlType", (p, l) => p.AttributeControlTypeId)
{
DropDownElements = await AttributeControlType.TextBox.ToSelectListAsync(useLocalization: false)
},
new PropertyByName<ExportProductAttribute, Language>("AttributeDisplayOrder", (p, l) => p.AttributeDisplayOrder),
new PropertyByName<ExportProductAttribute, Language>("ProductAttributeValueId", (p, l) => p.Id),
new PropertyByName<ExportProductAttribute, Language>("ValueName", (p, l) => p.Name),
new PropertyByName<ExportProductAttribute, Language>("AttributeValueType", (p, l) => p.AttributeValueTypeId)
{
DropDownElements = await AttributeValueType.Simple.ToSelectListAsync(useLocalization: false)
},
new PropertyByName<ExportProductAttribute, Language>("AssociatedProductId", (p, l) => p.AssociatedProductId),
new PropertyByName<ExportProductAttribute, Language>("ColorSquaresRgb", (p, l) => p.ColorSquaresRgb),
new PropertyByName<ExportProductAttribute, Language>("ImageSquaresPictureId", (p, l) => p.ImageSquaresPictureId),
new PropertyByName<ExportProductAttribute, Language>("PriceAdjustment", (p, l) => p.PriceAdjustment),
new PropertyByName<ExportProductAttribute, Language>("PriceAdjustmentUsePercentage", (p, l) => p.PriceAdjustmentUsePercentage),
new PropertyByName<ExportProductAttribute, Language>("WeightAdjustment", (p, l) => p.WeightAdjustment),
new PropertyByName<ExportProductAttribute, Language>("Cost", (p, l) => p.Cost),
new PropertyByName<ExportProductAttribute, Language>("CustomerEntersQty", (p, l) => p.CustomerEntersQty),
new PropertyByName<ExportProductAttribute, Language>("Quantity", (p, l) => p.Quantity),
new PropertyByName<ExportProductAttribute, Language>("IsPreSelected", (p, l) => p.IsPreSelected),
new PropertyByName<ExportProductAttribute, Language>("DisplayOrder", (p, l) => p.DisplayOrder),
new PropertyByName<ExportProductAttribute, Language>("PictureIds", async (p, l) => string.Join(",",
(await _productAttributeService.GetProductAttributeValuePicturesAsync(p.Id)).Select(vp => vp.PictureId)))
};
var localizedProperties = new[]
{
new PropertyByName<ExportProductAttribute, Language>("DefaultValue", async (p, l) =>
await GetLocalizedAsync(await _productAttributeService.GetProductAttributeMappingByIdAsync(p.AttributeMappingId), x => x.DefaultValue, l)),
new PropertyByName<ExportProductAttribute, Language>("AttributeTextPrompt", async (p, l) =>
await GetLocalizedAsync(await _productAttributeService.GetProductAttributeMappingByIdAsync(p.AttributeMappingId), x => x.TextPrompt, l)),
new PropertyByName<ExportProductAttribute, Language>("ValueName", async (p, l) =>
await GetLocalizedAsync(await _productAttributeService.GetProductAttributeValueByIdAsync(p.Id), x => x.Name, l)),
};
return new PropertyManager<ExportProductAttribute, Language>(attributeProperties, _catalogSettings, localizedProperties, languages);
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<PropertyManager<ExportSpecificationAttribute, Language>> GetSpecificationAttributeManagerAsync(IList<Language> languages)
{
var attributeProperties = new[]
{
new PropertyByName<ExportSpecificationAttribute, Language>("AttributeType", (p, l) => p.AttributeTypeId)
{
DropDownElements = await SpecificationAttributeType.Option.ToSelectListAsync(useLocalization: false)
},
new PropertyByName<ExportSpecificationAttribute, Language>("SpecificationAttribute", (p, l) => p.SpecificationAttributeId)
{
DropDownElements = (await _specificationAttributeService.GetSpecificationAttributesAsync()).Select(sa => sa as BaseEntity).ToSelectList(p => (p as SpecificationAttribute)?.Name ?? string.Empty)
},
new PropertyByName<ExportSpecificationAttribute, Language>("CustomValue", (p, l) => p.CustomValue),
new PropertyByName<ExportSpecificationAttribute, Language>("SpecificationAttributeOptionId", (p, l) => p.SpecificationAttributeOptionId),
new PropertyByName<ExportSpecificationAttribute, Language>("AllowFiltering", (p, l) => p.AllowFiltering),
new PropertyByName<ExportSpecificationAttribute, Language>("ShowOnProductPage", (p, l) => p.ShowOnProductPage),
new PropertyByName<ExportSpecificationAttribute, Language>("DisplayOrder", (p, l) => p.DisplayOrder)
};
var localizedProperties = new[]
{
new PropertyByName<ExportSpecificationAttribute, Language>("CustomValue", async (p, l) =>
await GetLocalizedAsync(await _specificationAttributeService.GetProductSpecificationAttributeByIdAsync(p.Id), x => x.CustomValue, l)),
};
return new PropertyManager<ExportSpecificationAttribute, Language>(attributeProperties, _catalogSettings, localizedProperties, languages);
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<PropertyManager<ExportTierPrice, Language>> GetTierPriceManagerAsync(IList<Language> languages)
{
var tierPriceProperties = new[]
{
new PropertyByName<ExportTierPrice, Language>("TierPriceId", (p, _) => p.Id),
new PropertyByName<ExportTierPrice, Language>("Store", (p, _) => p.StoreId)
{
DropDownElements = (await _storeService.GetAllStoresAsync()).ToSelectList(p=>(p as Store)?.Name ?? string.Empty)
},
new PropertyByName<ExportTierPrice, Language>("CustomerRole", (p, _) => p.CustomerRoleId ?? 0)
{
DropDownElements = (await _customerService.GetAllCustomerRolesAsync()).ToSelectList(p=>(p as CustomerRole)?.Name ?? string.Empty)
},
new PropertyByName<ExportTierPrice, Language>("Quantity", (p, _) => p.Quantity),
new PropertyByName<ExportTierPrice, Language>("Price", (p, _) => p.Price),
new PropertyByName<ExportTierPrice, Language>("StartDateTimeUtc", (p, _) => p.StartDateTimeUtc),
new PropertyByName<ExportTierPrice, Language>("EndDateTimeUtc", (p, _) => p.EndDateTimeUtc)
};
return new PropertyManager<ExportTierPrice, Language>(tierPriceProperties, _catalogSettings, languages: languages);
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<byte[]> ExportProductsToXlsxWithAdditionalInfoAsync(PropertyByName<Product, Language>[] properties, PropertyByName<Product, Language>[] localizedProperties, IEnumerable<Product> itemsToExport, IList<Language> languages)
{
var productAttributeManager = await GetProductAttributeManagerAsync(languages);
var specificationAttributeManager = await GetSpecificationAttributeManagerAsync(languages);
var tierPriceManager = await GetTierPriceManagerAsync(languages);
await using var stream = new MemoryStream();
// ok, we can run the real code of the sample now
using (var workbook = new XLWorkbook())
{
// uncomment this line if you want the XML written out to the outputDir
//xlPackage.DebugMode = true;
// get handles to the worksheets
// Worksheet names cannot be more than 31 characters
var worksheet = workbook.Worksheets.Add(nameof(Product));
var fpWorksheet = workbook.Worksheets.Add("ProductsFilters");
fpWorksheet.Visibility = XLWorksheetVisibility.VeryHidden;
var fbaWorksheet = workbook.Worksheets.Add("ProductAttributesFilters");
fbaWorksheet.Visibility = XLWorksheetVisibility.VeryHidden;
var fsaWorksheet = workbook.Worksheets.Add("SpecificationAttributesFilters");
fsaWorksheet.Visibility = XLWorksheetVisibility.VeryHidden;
//create Headers and format them
var manager = new PropertyManager<Product, Language>(properties, _catalogSettings, localizedProperties, languages);
manager.WriteDefaultCaption(worksheet);
var localizedWorksheets = new List<(Language Language, IXLWorksheet Worksheet)>();
if (languages.Count >= 2)
{
foreach (var language in languages)
{
var lws = workbook.Worksheets.Add(language.UniqueSeoCode);
localizedWorksheets.Add(new(language, lws));
manager.WriteLocalizedCaption(lws);
}
}
var row = 2;
foreach (var item in itemsToExport)
{
manager.CurrentObject = item;
await manager.WriteDefaultToXlsxAsync(worksheet, row, fWorksheet: fpWorksheet);
foreach (var lws in localizedWorksheets)
{
manager.CurrentLanguage = lws.Language;
await manager.WriteLocalizedToXlsxAsync(lws.Worksheet, row, fWorksheet: fpWorksheet);
}
row++;
if (_catalogSettings.ExportImportProductAttributes)
row = await ExportProductAttributesAsync(item, productAttributeManager, worksheet, localizedWorksheets, row, fbaWorksheet);
if (_catalogSettings.ExportImportProductSpecificationAttributes)
row = await ExportSpecificationAttributesAsync(item, specificationAttributeManager, worksheet, localizedWorksheets, row, fsaWorksheet);
if (_catalogSettings.ExportImportTierPrices)
row = await ExportTierPricesAsync(item, tierPriceManager, worksheet, localizedWorksheets, row, fsaWorksheet);
}
workbook.SaveAs(stream);
}
return stream.ToArray();
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<int> ExportProductAttributesAsync(Product item, PropertyManager<ExportProductAttribute, Language> attributeManager,
IXLWorksheet worksheet, IList<(Language Language, IXLWorksheet Worksheet)> localizedWorksheets, int row, IXLWorksheet faWorksheet)
{
var attributes = await (await _productAttributeService.GetProductAttributeMappingsByProductIdAsync(item.Id))
.SelectManyAwait(async pam =>
{
var productAttribute = await _productAttributeService.GetProductAttributeByIdAsync(pam.ProductAttributeId);
var values = await _productAttributeService.GetProductAttributeValuesAsync(pam.Id);
if (values?.Any() ?? false)
{
IEnumerable<ExportProductAttribute> productAttributes = await values.SelectAwait(async pav =>
new ExportProductAttribute
{
AttributeId = productAttribute.Id,
AttributeName = productAttribute.Name,
AttributeTextPrompt = pam.TextPrompt,
AttributeIsRequired = pam.IsRequired,
AttributeControlTypeId = pam.AttributeControlTypeId,
AttributeMappingId = pav.ProductAttributeMappingId,
AssociatedProductId = pav.AssociatedProductId,
AttributeDisplayOrder = pam.DisplayOrder,
Id = pav.Id,
Name = pav.Name,
AttributeValueTypeId = pav.AttributeValueTypeId,
ColorSquaresRgb = pav.ColorSquaresRgb,
ImageSquaresPictureId = pav.ImageSquaresPictureId,
PriceAdjustment = pav.PriceAdjustment,
PriceAdjustmentUsePercentage = pav.PriceAdjustmentUsePercentage,
WeightAdjustment = pav.WeightAdjustment,
Cost = pav.Cost,
CustomerEntersQty = pav.CustomerEntersQty,
Quantity = pav.Quantity,
IsPreSelected = pav.IsPreSelected,
DisplayOrder = pav.DisplayOrder,
PictureIds = string.Join(";",
(await _productAttributeService.GetProductAttributeValuePicturesAsync(pav.Id)).Select(vp => vp.PictureId))
}).ToListAsync();
return productAttributes;
}
var attribute = new ExportProductAttribute
{
AttributeId = productAttribute.Id,
AttributeName = productAttribute.Name,
AttributeTextPrompt = pam.TextPrompt,
AttributeIsRequired = pam.IsRequired,
AttributeControlTypeId = pam.AttributeControlTypeId,
};
//validation rules
if (!pam.ValidationRulesAllowed())
return new List<ExportProductAttribute> { attribute };
attribute.ValidationMinLength = pam.ValidationMinLength;
attribute.ValidationMaxLength = pam.ValidationMaxLength;
attribute.ValidationFileAllowedExtensions = pam.ValidationFileAllowedExtensions;
attribute.ValidationFileMaximumSize = pam.ValidationFileMaximumSize;
attribute.DefaultValue = pam.DefaultValue;
return new List<ExportProductAttribute>
{
attribute
};
}).ToListAsync();
if (!attributes.Any())
return row;
attributeManager.WriteDefaultCaption(worksheet, row, ExportImportDefaults.ProductAdditionalInfoCellOffset);
worksheet.Row(row).OutlineLevel = 1;
worksheet.Row(row).Collapse();
foreach (var lws in localizedWorksheets)
{
attributeManager.WriteLocalizedCaption(lws.Worksheet, row, ExportImportDefaults.ProductAdditionalInfoCellOffset);
lws.Worksheet.Row(row).OutlineLevel = 1;
lws.Worksheet.Row(row).Collapse();
}
foreach (var exportProductAttribute in attributes)
{
row++;
attributeManager.CurrentObject = exportProductAttribute;
await attributeManager.WriteDefaultToXlsxAsync(worksheet, row, ExportImportDefaults.ProductAdditionalInfoCellOffset, faWorksheet);
worksheet.Row(row).OutlineLevel = 1;
worksheet.Row(row).Collapse();
foreach (var lws in localizedWorksheets)
{
attributeManager.CurrentLanguage = lws.Language;
await attributeManager.WriteLocalizedToXlsxAsync(lws.Worksheet, row, ExportImportDefaults.ProductAdditionalInfoCellOffset, faWorksheet);
lws.Worksheet.Row(row).OutlineLevel = 1;
lws.Worksheet.Row(row).Collapse();
}
}
return row + 1;
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<int> ExportSpecificationAttributesAsync(Product item, PropertyManager<ExportSpecificationAttribute, Language> attributeManager,
IXLWorksheet worksheet, IList<(Language Language, IXLWorksheet Worksheet)> localizedWorksheets, int row, IXLWorksheet faWorksheet)
{
var attributes = await (await _specificationAttributeService
.GetProductSpecificationAttributesAsync(item.Id)).SelectAwait(
async psa => await ExportSpecificationAttribute.CreateAsync(psa, _specificationAttributeService)).ToListAsync();
if (!attributes.Any())
return row;
attributeManager.WriteDefaultCaption(worksheet, row, ExportImportDefaults.ProductAdditionalInfoCellOffset);
worksheet.Row(row).OutlineLevel = 1;
worksheet.Row(row).Collapse();
foreach (var lws in localizedWorksheets)
{
attributeManager.WriteLocalizedCaption(lws.Worksheet, row, ExportImportDefaults.ProductAdditionalInfoCellOffset);
lws.Worksheet.Row(row).OutlineLevel = 1;
lws.Worksheet.Row(row).Collapse();
}
foreach (var exportProductAttribute in attributes)
{
row++;
attributeManager.CurrentObject = exportProductAttribute;
await attributeManager.WriteDefaultToXlsxAsync(worksheet, row, ExportImportDefaults.ProductAdditionalInfoCellOffset, faWorksheet);
worksheet.Row(row).OutlineLevel = 1;
worksheet.Row(row).Collapse();
foreach (var lws in localizedWorksheets)
{
attributeManager.CurrentLanguage = lws.Language;
await attributeManager.WriteLocalizedToXlsxAsync(lws.Worksheet, row, ExportImportDefaults.ProductAdditionalInfoCellOffset, faWorksheet);
lws.Worksheet.Row(row).OutlineLevel = 1;
lws.Worksheet.Row(row).Collapse();
}
}
return row + 1;
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<int> ExportTierPricesAsync(Product item, PropertyManager<ExportTierPrice, Language> tierPriceManager,
IXLWorksheet worksheet, IList<(Language Language, IXLWorksheet Worksheet)> localizedWorksheets, int row, IXLWorksheet faWorksheet)
{
var tierPrices = (await _productService.GetTierPricesByProductAsync(item.Id)).Select(p=>new ExportTierPrice
{
Id = p.Id,
CustomerRoleId = p.CustomerRoleId,
Quantity = p.Quantity,
Price = p.Price,
StartDateTimeUtc = p.StartDateTimeUtc,
EndDateTimeUtc = p.EndDateTimeUtc,
StoreId = p.StoreId
}).ToList();
if (!tierPrices.Any())
return row;
tierPriceManager.WriteDefaultCaption(worksheet, row, ExportImportDefaults.ProductAdditionalInfoCellOffset);
worksheet.Row(row).OutlineLevel = 1;
worksheet.Row(row).Collapse();
foreach (var tierPrice in tierPrices)
{
row++;
tierPriceManager.CurrentObject = tierPrice;
await tierPriceManager.WriteDefaultToXlsxAsync(worksheet, row, ExportImportDefaults.ProductAdditionalInfoCellOffset, faWorksheet);
worksheet.Row(row).OutlineLevel = 1;
worksheet.Row(row).Collapse();
}
return row + 1;
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<byte[]> ExportOrderToXlsxWithProductsAsync(PropertyByName<Order, Language>[] properties, IEnumerable<Order> itemsToExport)
{
var orderItemProperties = new[]
{
new PropertyByName<OrderItem, Language>("OrderItemGuid", (oi, l) => oi.OrderItemGuid),
new PropertyByName<OrderItem, Language>("Name", async (oi, l) => (await _productService.GetProductByIdAsync(oi.ProductId)).Name),
new PropertyByName<OrderItem, Language>("Sku", async (oi, l) => await _productService.FormatSkuAsync(await _productService.GetProductByIdAsync(oi.ProductId), oi.AttributesXml)),
new PropertyByName<OrderItem, Language>("PriceExclTax", (oi, l) => oi.UnitPriceExclTax),
new PropertyByName<OrderItem, Language>("PriceInclTax", (oi, l) => oi.UnitPriceInclTax),
new PropertyByName<OrderItem, Language>("Quantity", (oi, l) => oi.Quantity),
new PropertyByName<OrderItem, Language>("DiscountExclTax", (oi, l) => oi.DiscountAmountExclTax),
new PropertyByName<OrderItem, Language>("DiscountInclTax", (oi, l) => oi.DiscountAmountInclTax),
new PropertyByName<OrderItem, Language>("TotalExclTax", (oi, l) => oi.PriceExclTax),
new PropertyByName<OrderItem, Language>("TotalInclTax", (oi, l) => oi.PriceInclTax)
};
var orderItemsManager = new PropertyManager<OrderItem, Language>(orderItemProperties, _catalogSettings);
await using var stream = new MemoryStream();
// ok, we can run the real code of the sample now
using (var workbook = new XLWorkbook())
{
// uncomment this line if you want the XML written out to the outputDir
//xlPackage.DebugMode = true;
// get handles to the worksheets
// Worksheet names cannot be more than 31 characters
var worksheet = workbook.Worksheets.Add(typeof(Order).Name);
var fpWorksheet = workbook.Worksheets.Add("DataForProductsFilters");
fpWorksheet.Visibility = XLWorksheetVisibility.VeryHidden;
//create Headers and format them
var manager = new PropertyManager<Order, Language>(properties, _catalogSettings);
manager.WriteDefaultCaption(worksheet);
var row = 2;
foreach (var order in itemsToExport)
{
manager.CurrentObject = order;
await manager.WriteDefaultToXlsxAsync(worksheet, row++);
//a vendor should have access only to his products
var vendor = await _workContext.GetCurrentVendorAsync();
var orderItems = await _orderService.GetOrderItemsAsync(order.Id, vendorId: vendor?.Id ?? 0);
if (!orderItems.Any())
continue;
orderItemsManager.WriteDefaultCaption(worksheet, row, 2);
worksheet.Row(row).OutlineLevel = 1;
worksheet.Row(row).Collapse();
foreach (var orderItem in orderItems)
{
row++;
orderItemsManager.CurrentObject = orderItem;
await orderItemsManager.WriteDefaultToXlsxAsync(worksheet, row, 2, fpWorksheet);
worksheet.Row(row).OutlineLevel = 1;
worksheet.Row(row).Collapse();
}
row++;
}
workbook.SaveAs(stream);
}
return stream.ToArray();
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task<object> GetCustomCustomerAttributesAsync(Customer customer)
{
return await _customerAttributeFormatter.FormatAttributesAsync(customer.CustomCustomerAttributesXML, ";");
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task WriteLocalizedPropertyXmlAsync<TEntity, TPropType>(TEntity entity, Expression<Func<TEntity, TPropType>> keySelector,
XmlWriter xmlWriter, IList<Language> languages, bool ignore = false, string overriddenNodeName = null)
where TEntity : BaseEntity, ILocalizedEntity
{
if (ignore)
return;
ArgumentNullException.ThrowIfNull(entity);
if (keySelector.Body is not MemberExpression member)
throw new ArgumentException($"Expression '{keySelector}' refers to a method, not a property.");
if (member.Member is not PropertyInfo propInfo)
throw new ArgumentException($"Expression '{keySelector}' refers to a field, not a property.");
var localeKeyGroup = entity.GetType().Name;
var localeKey = propInfo.Name;
var nodeName = localeKey;
if (!string.IsNullOrWhiteSpace(overriddenNodeName))
nodeName = overriddenNodeName;
await xmlWriter.WriteStartElementAsync(nodeName);
await xmlWriter.WriteStringAsync("Standard", propInfo.GetValue(entity));
if (languages.Count >= 2)
{
await xmlWriter.WriteStartElementAsync("Locales");
var properties = await _localizedEntityService.GetEntityLocalizedPropertiesAsync(entity.Id, localeKeyGroup, localeKey);
foreach (var language in languages)
if (properties.FirstOrDefault(lp => lp.LanguageId == language.Id) is LocalizedProperty localizedProperty)
await xmlWriter.WriteStringAsync(language.UniqueSeoCode, localizedProperty.LocaleValue);
await xmlWriter.WriteEndElementAsync();
}
await xmlWriter.WriteEndElementAsync();
}
/// <returns>A task that represents the asynchronous operation</returns>
protected virtual async Task WriteLocalizedSeNameXmlAsync<TEntity>(TEntity entity, XmlWriter xmlWriter, IList<Language> languages,
bool ignore = false, string overriddenNodeName = null)
where TEntity : BaseEntity, ISlugSupported
{
if (ignore)
return;
ArgumentNullException.ThrowIfNull(entity);
var nodeName = "SEName";
if (!string.IsNullOrWhiteSpace(overriddenNodeName))
nodeName = overriddenNodeName;
await xmlWriter.WriteStartElementAsync(nodeName);
await xmlWriter.WriteStringAsync("Standard", await _urlRecordService.GetSeNameAsync(entity, 0));
if (languages.Count >= 2)
{
await xmlWriter.WriteStartElementAsync("Locales");
foreach (var language in languages)
if (await _urlRecordService.GetSeNameAsync(entity, language.Id, returnDefaultValue: false) is string seName && !string.IsNullOrWhiteSpace(seName))
await xmlWriter.WriteStringAsync(language.UniqueSeoCode, seName);
await xmlWriter.WriteEndElementAsync();
}
await xmlWriter.WriteEndElementAsync();
}
#endregion
#region Methods
/// <summary>
/// Export manufacturer list to XML
/// </summary>
/// <param name="manufacturers">Manufacturers</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the result in XML format
/// </returns>
public virtual async Task<string> ExportManufacturersToXmlAsync(IList<Manufacturer> manufacturers)
{
var settings = new XmlWriterSettings
{
Async = true,
ConformanceLevel = ConformanceLevel.Auto
};
await using var stringWriter = new StringWriter();
await using var xmlWriter = XmlWriter.Create(stringWriter, settings);
await xmlWriter.WriteStartDocumentAsync();
await xmlWriter.WriteStartElementAsync("Manufacturers");
await xmlWriter.WriteAttributeStringAsync("Version", NopVersion.CURRENT_VERSION);