Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Refactoring import data from excel

support2fb25f171f45
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs
new file mode 100644
index 000000000..0ff504afa
--- /dev/null
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs
@@ -0,0 +1,149 @@
+using Grand.Business.Catalog.Services.ExportImport.Dto;
+using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Catalog.Brands;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Seo;
+using Grand.Business.Core.Interfaces.ExportImport;
+using Grand.Business.Core.Interfaces.Storage;
+using Grand.Domain.Catalog;
+using Grand.Domain.Media;
+using Grand.Domain.Seo;
+using Grand.Infrastructure.Mapper;
+using Microsoft.AspNetCore.StaticFiles;
+
+namespace Grand.Business.Catalog.Services.ExportImport
+{
+ public class BrandImportDataObject : IImportDataObject<BrandDto>
+ {
+ private readonly IBrandService _brandService;
+ private readonly IPictureService _pictureService;
+ private readonly IBrandLayoutService _brandLayoutService;
+ private readonly ISlugService _slugService;
+ private readonly ILanguageService _languageService;
+
+ private readonly SeoSettings _seoSetting;
+
+ public BrandImportDataObject(
+ IBrandService brandService,
+ IPictureService pictureService,
+ IBrandLayoutService brandLayoutService,
+ ISlugService slugService,
+ ILanguageService languageService,
+ SeoSettings seoSetting)
+ {
+ _brandService = brandService;
+ _pictureService = pictureService;
+ _brandLayoutService = brandLayoutService;
+ _slugService = slugService;
+ _languageService = languageService;
+
+ _seoSetting = seoSetting;
+ }
+
+ public async Task Execute(IEnumerable<BrandDto> data)
+ {
+ foreach (var item in data)
+ {
+ await Import(item);
+ }
+ }
+
+ protected async Task Import(BrandDto brandDto)
+ {
+ var brand = await _brandService.GetBrandById(brandDto.Id);
+ var isNew = brand == null;
+
+ if (brand == null) brand = brandDto.MapTo<BrandDto, Brand>();
+ else brandDto.MapTo(brand);
+
+ if (isNew) await _brandService.InsertBrand(brand);
+ else await _brandService.UpdateBrand(brand);
+
+ if (!ValidBrand(brand)) return;
+
+ await UpdateBrandData(brandDto, brand);
+
+ }
+
+ protected async Task<Brand> UpdateBrandData(BrandDto brandDto, Brand brand)
+ {
+ if (string.IsNullOrEmpty(brand.BrandLayoutId))
+ brand.BrandLayoutId = (await _brandLayoutService.GetAllBrandLayouts()).FirstOrDefault().Id;
+ else
+ {
+ var layout = await _brandLayoutService.GetBrandLayoutById(brand.BrandLayoutId);
+ if (layout == null)
+ brand.BrandLayoutId = (await _brandLayoutService.GetAllBrandLayouts()).FirstOrDefault().Id;
+ }
+
+ if (!string.IsNullOrEmpty(brandDto.Picture))
+ {
+ var _picture = await LoadPicture(brandDto.Picture, brand.Name, brand.PictureId);
+ if (_picture != null)
+ brand.PictureId = _picture.Id;
+ }
+
+ var sename = brand.SeName ?? brand.Name;
+ sename = await brand.ValidateSeName(sename, brand.Name, true, _seoSetting, _slugService, _languageService);
+ brand.SeName = sename;
+
+ await _brandService.UpdateBrand(brand);
+ await _slugService.SaveSlug(brand, sename, "");
+
+ return brand;
+ }
+
+ protected virtual bool ValidBrand(Brand brand)
+ {
+ if (string.IsNullOrEmpty(brand.Name))
+ return false;
+
+ return true;
+ }
+
+ /// <summary>
+ /// Creates or loads the image
+ /// </summary>
+ /// <param name="picturePath">The path to the image file</param>
+ /// <param name="name">The name of the object</param>
+ /// <param name="picId">Image identifier, may be null</param>
+ /// <returns>The image or null if the image has not changed</returns>
+ protected virtual async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")
+ {
+ if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
+ return null;
+
+ var mimeType = GetMimeTypeFromFilePath(picturePath);
+ var newPictureBinary = File.ReadAllBytes(picturePath);
+ var pictureAlreadyExists = false;
+ if (!string.IsNullOrEmpty(picId))
+ {
+ //compare with existing product pictures
+ var existingPicture = await _pictureService.GetPictureById(picId);
+
+ var existingBinary = await _pictureService.LoadPictureBinary(existingPicture);
+ //picture binary after validation (like in database)
+ var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
+ if (existingBinary.SequenceEqual(validatedPictureBinary) ||
+ existingBinary.SequenceEqual(newPictureBinary))
+ {
+ pictureAlreadyExists = true;
+ }
+ }
+
+ if (pictureAlreadyExists) return null;
+
+ var newPicture = await _pictureService.InsertPicture(newPictureBinary, mimeType,
+ _pictureService.GetPictureSeName(name));
+ return newPicture;
+ }
+ protected virtual string GetMimeTypeFromFilePath(string filePath)
+ {
+ new FileExtensionContentTypeProvider().TryGetContentType(filePath, out string mimeType);
+ //set to jpeg in case mime type cannot be found
+ if (mimeType == null)
+ mimeType = "image/jpeg";
+ return mimeType;
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs
new file mode 100644
index 000000000..23797453f
--- /dev/null
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs
@@ -0,0 +1,150 @@
+using Grand.Business.Catalog.Services.ExportImport.Dto;
+using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Catalog.Categories;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Seo;
+using Grand.Business.Core.Interfaces.ExportImport;
+using Grand.Business.Core.Interfaces.Storage;
+using Grand.Domain.Catalog;
+using Grand.Domain.Media;
+using Grand.Domain.Seo;
+using Grand.Infrastructure.Mapper;
+using Microsoft.AspNetCore.StaticFiles;
+
+namespace Grand.Business.Catalog.Services.ExportImport
+{
+ public class CategoryImportDataObject : IImportDataObject<CategoryDto>
+ {
+ private readonly ICategoryService _categoryService;
+ private readonly IPictureService _pictureService;
+ private readonly ICategoryLayoutService _categoryLayoutService;
+ private readonly ISlugService _slugService;
+ private readonly ILanguageService _languageService;
+
+ private readonly SeoSettings _seoSetting;
+
+ public CategoryImportDataObject(
+ ICategoryService categoryService,
+ IPictureService pictureService,
+ ICategoryLayoutService categoryLayoutService,
+ ISlugService slugService,
+ ILanguageService languageService,
+ SeoSettings seoSetting)
+ {
+ _categoryService = categoryService;
+ _pictureService = pictureService;
+ _categoryLayoutService = categoryLayoutService;
+ _slugService = slugService;
+ _languageService = languageService;
+
+ _seoSetting = seoSetting;
+ }
+
+ public async Task Execute(IEnumerable<CategoryDto> data)
+ {
+ foreach (var item in data)
+ {
+ await Import(item);
+ }
+ }
+
+ protected async Task Import(CategoryDto categoryDto)
+ {
+ var category = await _categoryService.GetCategoryById(categoryDto.Id);
+ var isNew = category == null;
+ if (category == null) category = categoryDto.MapTo<CategoryDto, Category>();
+ else categoryDto.MapTo(category);
+
+ if (isNew) await _categoryService.InsertCategory(category);
+ else await _categoryService.UpdateCategory(category);
+
+ if (!ValidCategory(category)) return;
+
+ await UpdateCategoryData(categoryDto, category);
+ }
+
+ protected async Task<Category> UpdateCategoryData(CategoryDto categoryDto, Category category)
+ {
+ if (string.IsNullOrEmpty(category.CategoryLayoutId))
+ category.CategoryLayoutId = (await _categoryLayoutService.GetAllCategoryLayouts()).FirstOrDefault().Id;
+ else
+ {
+ var layout = await _categoryLayoutService.GetCategoryLayoutById(category.CategoryLayoutId);
+ if (layout == null)
+ category.CategoryLayoutId = (await _categoryLayoutService.GetAllCategoryLayouts()).FirstOrDefault().Id;
+ }
+ if(!string.IsNullOrEmpty(category.ParentCategoryId))
+ {
+ var parentCategory = await _categoryService.GetCategoryById(category.ParentCategoryId);
+ if (parentCategory == null)
+ category.ParentCategoryId = string.Empty;
+ }
+ if (!string.IsNullOrEmpty(categoryDto.Picture))
+ {
+ var _picture = await LoadPicture(categoryDto.Picture, category.Name, category.PictureId);
+ if (_picture != null)
+ category.PictureId = _picture.Id;
+ }
+
+ var sename = category.SeName ?? category.Name;
+ sename = await category.ValidateSeName(sename, category.Name, true, _seoSetting, _slugService, _languageService);
+ category.SeName = sename;
+ await _categoryService.UpdateCategory(category);
+ await _slugService.SaveSlug(category, sename, "");
+ return category;
+ }
+
+ protected virtual bool ValidCategory(Category category)
+ {
+ if (string.IsNullOrEmpty(category.Name))
+ return false;
+
+ return true;
+ }
+
+ /// <summary>
+ /// Creates or loads the image
+ /// </summary>
+ /// <param name="picturePath">The path to the image file</param>
+ /// <param name="name">The name of the object</param>
+ /// <param name="picId">Image identifier, may be null</param>
+ /// <returns>The image or null if the image has not changed</returns>
+ protected virtual async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")
+ {
+ if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
+ return null;
+
+ var mimeType = GetMimeTypeFromFilePath(picturePath);
+ var newPictureBinary = File.ReadAllBytes(picturePath);
+ var pictureAlreadyExists = false;
+ if (!string.IsNullOrEmpty(picId))
+ {
+ //compare with existing product pictures
+ var existingPicture = await _pictureService.GetPictureById(picId);
+
+ var existingBinary = await _pictureService.LoadPictureBinary(existingPicture);
+ //picture binary after validation (like in database)
+ var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
+ if (existingBinary.SequenceEqual(validatedPictureBinary) ||
+ existingBinary.SequenceEqual(newPictureBinary))
+ {
+ pictureAlreadyExists = true;
+ }
+ }
+
+ if (pictureAlreadyExists) return null;
+
+ var newPicture = await _pictureService.InsertPicture(newPictureBinary, mimeType,
+ _pictureService.GetPictureSeName(name));
+ return newPicture;
+ }
+ protected virtual string GetMimeTypeFromFilePath(string filePath)
+ {
+ new FileExtensionContentTypeProvider().TryGetContentType(filePath, out string mimeType);
+ //set to jpeg in case mime type cannot be found
+ if (mimeType == null)
+ mimeType = "image/jpeg";
+ return mimeType;
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs
new file mode 100644
index 000000000..43d867e23
--- /dev/null
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs
@@ -0,0 +1,148 @@
+using Grand.Business.Catalog.Services.ExportImport.Dto;
+using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Catalog.Collections;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Seo;
+using Grand.Business.Core.Interfaces.ExportImport;
+using Grand.Business.Core.Interfaces.Storage;
+using Grand.Domain.Catalog;
+using Grand.Domain.Media;
+using Grand.Domain.Seo;
+using Grand.Infrastructure.Mapper;
+using Microsoft.AspNetCore.StaticFiles;
+
+namespace Grand.Business.Catalog.Services.ExportImport
+{
+ public class CollectionImportDataObject : IImportDataObject<CollectionDto>
+ {
+ private readonly ICollectionService _collectionService;
+ private readonly IPictureService _pictureService;
+ private readonly ICollectionLayoutService _collectionLayoutService;
+ private readonly ISlugService _slugService;
+ private readonly ILanguageService _languageService;
+
+ private readonly SeoSettings _seoSetting;
+
+ public CollectionImportDataObject(
+ ICollectionService collectionService,
+ IPictureService pictureService,
+ ICollectionLayoutService collectionLayoutService,
+ ISlugService slugService,
+ ILanguageService languageService,
+ SeoSettings seoSetting)
+ {
+ _collectionService = collectionService;
+ _pictureService = pictureService;
+ _collectionLayoutService = collectionLayoutService;
+ _slugService = slugService;
+ _languageService = languageService;
+
+ _seoSetting = seoSetting;
+ }
+
+ public async Task Execute(IEnumerable<CollectionDto> data)
+ {
+ foreach (var item in data)
+ {
+ await Import(item);
+ }
+ }
+
+ protected async Task Import(CollectionDto collectionDto)
+ {
+ var collection = await _collectionService.GetCollectionById(collectionDto.Id);
+ var isNew = collection == null;
+
+ if (collection == null) collection = collectionDto.MapTo<CollectionDto, Collection>();
+ else collectionDto.MapTo(collection);
+
+ if (isNew) await _collectionService.InsertCollection(collection);
+ else await _collectionService.UpdateCollection(collection);
+
+ if (!ValidCollection(collection)) return;
+
+ await UpdateCollectionData(collectionDto, collection);
+ }
+
+ protected async Task<Collection> UpdateCollectionData(CollectionDto collectionDto, Collection collection)
+ {
+ if (string.IsNullOrEmpty(collection.CollectionLayoutId))
+ collection.CollectionLayoutId = (await _collectionLayoutService.GetAllCollectionLayouts()).FirstOrDefault().Id;
+ else
+ {
+ var layout = await _collectionLayoutService.GetCollectionLayoutById(collection.CollectionLayoutId);
+ if (layout == null)
+ collection.CollectionLayoutId = (await _collectionLayoutService.GetAllCollectionLayouts()).FirstOrDefault().Id;
+ }
+
+ if (!string.IsNullOrEmpty(collectionDto.Picture))
+ {
+ var _picture = await LoadPicture(collectionDto.Picture, collection.Name, collection.PictureId);
+ if (_picture != null)
+ collection.PictureId = _picture.Id;
+ }
+
+ var sename = collection.SeName ?? collection.Name;
+ sename = await collection.ValidateSeName(sename, collection.Name, true, _seoSetting, _slugService, _languageService);
+ collection.SeName = sename;
+
+ await _collectionService.UpdateCollection(collection);
+ await _slugService.SaveSlug(collection, sename, "");
+
+ return collection;
+ }
+
+ protected virtual bool ValidCollection(Collection collection)
+ {
+ if (string.IsNullOrEmpty(collection.Name))
+ return false;
+
+ return true;
+ }
+
+ /// <summary>
+ /// Creates or loads the image
+ /// </summary>
+ /// <param name="picturePath">The path to the image file</param>
+ /// <param name="name">The name of the object</param>
+ /// <param name="picId">Image identifier, may be null</param>
+ /// <returns>The image or null if the image has not changed</returns>
+ protected virtual async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")
+ {
+ if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
+ return null;
+
+ var mimeType = GetMimeTypeFromFilePath(picturePath);
+ var newPictureBinary = File.ReadAllBytes(picturePath);
+ var pictureAlreadyExists = false;
+ if (!string.IsNullOrEmpty(picId))
+ {
+ //compare with existing product pictures
+ var existingPicture = await _pictureService.GetPictureById(picId);
+
+ var existingBinary = await _pictureService.LoadPictureBinary(existingPicture);
+ //picture binary after validation (like in database)
+ var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
+ if (existingBinary.SequenceEqual(validatedPictureBinary) ||
+ existingBinary.SequenceEqual(newPictureBinary))
+ {
+ pictureAlreadyExists = true;
+ }
+ }
+
+ if (pictureAlreadyExists) return null;
+
+ var newPicture = await _pictureService.InsertPicture(newPictureBinary, mimeType,
+ _pictureService.GetPictureSeName(name));
+ return newPicture;
+ }
+ protected virtual string GetMimeTypeFromFilePath(string filePath)
+ {
+ new FileExtensionContentTypeProvider().TryGetContentType(filePath, out string mimeType);
+ //set to jpeg in case mime type cannot be found
+ if (mimeType == null)
+ mimeType = "image/jpeg";
+ return mimeType;
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/BrandDto.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/BrandDto.cs
new file mode 100644
index 000000000..0876116e7
--- /dev/null
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/BrandDto.cs
@@ -0,0 +1,26 @@
+namespace Grand.Business.Catalog.Services.ExportImport.Dto
+{
+ public class BrandDto
+ {
+ public string Id { get; set; }
+ public string Name { get; set; }
+ public string SeName { get; set; }
+ public string Picture { get; set; }
+ public string Description { get; set; }
+ public string BottomDescription { get; set; }
+ public string BrandLayoutId { get; set; }
+ public string MetaKeywords { get; set; }
+ public string MetaDescription { get; set; }
+ public string MetaTitle { get; set; }
+ public int? PageSize { get; set; }
+ public bool? AllowCustomersToSelectPageSize { get; set; }
+ public string PageSizeOptions { get; set; }
+ public bool? ShowOnHomePage { get; set; }
+ public bool? IncludeInMenu { get; set; }
+ public string Icon { get; set; }
+ public int? DefaultSort { get; set; }
+ public string ExternalId { get; set; }
+ public bool? Published { get; set; }
+ public int? DisplayOrder { get; set; }
+ }
+}
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/CategoryDto.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/CategoryDto.cs
new file mode 100644
index 000000000..3b804988e
--- /dev/null
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/CategoryDto.cs
@@ -0,0 +1,34 @@
+namespace Grand.Business.Catalog.Services.ExportImport.Dto
+{
+ public class CategoryDto
+ {
+ public string Id { get; set; }
+ public string Name { get; set; }
+ public string CategoryLayoutId { get; set; }
+ public string Picture { get; set; }
+ public string SeName { get; set; }
+ public string Description { get; set; }
+ public string BottomDescription { get; set; }
+ public string MetaKeywords { get; set; }
+ public string MetaDescription { get; set; }
+ public string MetaTitle { get; set; }
+ public string ParentCategoryId { get; set; }
+ public int? PageSize { get; set; }
+ public bool? AllowCustomersToSelectPageSize { get; set; }
+ public string PageSizeOptions { get; set; }
+ public bool? ShowOnHomePage { get; set; }
+ public bool? FeaturedProductsOnHomePage { get; set; }
+ public bool? ShowOnSearchBox { get; set; }
+ public int? SearchBoxDisplayOrder { get; set; }
+ public bool? IncludeInMenu { get; set; }
+ public bool? Published { get; set; }
+ public int? DisplayOrder { get; set; }
+ public string ExternalId { get; set; }
+ public string Flag { get; set; }
+ public string FlagStyle { get; set; }
+ public string Icon { get; set; }
+ public int? DefaultSort { get; set; }
+ public bool? HideOnCatalog { get; set; }
+
+ }
+}
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/CollectionDto.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/CollectionDto.cs
new file mode 100644
index 000000000..711972ce7
--- /dev/null
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/CollectionDto.cs
@@ -0,0 +1,28 @@
+namespace Grand.Business.Catalog.Services.ExportImport.Dto
+{
+ public class CollectionDto
+ {
+ public string Id { get; set; }
+ public string Name { get; set; }
+ public string Picture { get; set; }
+ public string SeName { get; set; }
+ public string Description { get; set; }
+ public string BottomDescription { get; set; }
+ public string CollectionLayoutId { get; set; }
+ public string MetaKeywords { get; set; }
+ public string MetaDescription { get; set; }
+ public string MetaTitle { get; set; }
+ public int? PageSize { get; set; }
+ public bool? AllowCustomersToSelectPageSize { get; set; }
+ public string PageSizeOptions { get; set; }
+ public bool? ShowOnHomePage { get; set; }
+ public bool? FeaturedProductsOnHomePage { get; set; }
+ public bool? IncludeInMenu { get; set; }
+ public string Icon { get; set; }
+ public int? DefaultSort { get; set; } = -1;
+ public bool? Published { get; set; }
+ public int? DisplayOrder { get; set; }
+ public string ExternalId { get; set; }
+
+ }
+}
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/ProductDto.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/ProductDto.cs
new file mode 100644
index 000000000..58fa54722
--- /dev/null
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Dto/ProductDto.cs
@@ -0,0 +1,124 @@
+using Grand.Domain.Catalog;
+
+namespace Grand.Business.Catalog.Services.ExportImport.Dto
+{
+ public class ProductDto
+ {
+ public string Id { get; set; }
+ public ProductType? ProductTypeId { get; set; }
+ public string ParentGroupedProductId { get; set; }
+ public bool? VisibleIndividually { get; set; }
+ public string Name { get; set; }
+ public string SeName { get; set; }
+ public string ShortDescription { get; set; }
+ public string FullDescription { get; set; }
+ public string AdminComment { get; set; }
+ public string ProductLayoutId { get; set; }
+ public string BrandId { get; set; }
+ public string VendorId { get; set; }
+ public bool? ShowOnHomePage { get; set; }
+ public bool? BestSeller { get; set; }
+ public string MetaKeywords { get; set; }
+ public string MetaDescription { get; set; }
+ public string MetaTitle { get; set; }
+ public bool? AllowCustomerReviews { get; set; }
+ public int? ApprovedRatingSum { get; set; }
+ public int? NotApprovedRatingSum { get; set; }
+ public int? ApprovedTotalReviews { get; set; }
+ public int? NotApprovedTotalReviews { get; set; }
+ public string ExternalId { get; set; }
+ public string Sku { get; set; }
+ public string Mpn { get; set; }
+ public string Gtin { get; set; }
+ public bool? IsGiftVoucher { get; set; }
+ public GiftVoucherType? GiftVoucherTypeId { get; set; }
+ public double? OverGiftAmount { get; set; }
+ public bool? RequireOtherProducts { get; set; }
+ public string RequiredProductIds { get; set; }
+ public bool? AutoAddRequiredProducts { get; set; }
+ public bool? IsDownload { get; set; }
+ public string DownloadId { get; set; }
+ public bool? UnlimitedDownloads { get; set; }
+ public int? MaxNumberOfDownloads { get; set; }
+ public int? DownloadExpirationDays { get; set; }
+ public DownloadActivationType? DownloadActivationTypeId { get; set; }
+ public bool? HasSampleDownload { get; set; }
+ public string SampleDownloadId { get; set; }
+ public bool? HasUserAgreement { get; set; }
+ public string UserAgreementText { get; set; }
+ public bool? IsRecurring { get; set; }
+ public int? RecurringCycleLength { get; set; }
+ public RecurringCyclePeriod? RecurringCyclePeriodId { get; set; }
+ public int? RecurringTotalCycles { get; set; }
+ public bool? IncBothDate { get; set; }
+ public int? Interval { get; set; }
+ public IntervalUnit? IntervalUnitId { get; set; }
+ public bool? IsShipEnabled { get; set; }
+ public bool? IsFreeShipping { get; set; }
+ public bool? ShipSeparately { get; set; }
+ public double? AdditionalShippingCharge { get; set; }
+ public string DeliveryDateId { get; set; }
+ public bool? IsTaxExempt { get; set; }
+ public string TaxCategoryId { get; set; }
+ public bool? IsTele { get; set; }
+ public ManageInventoryMethod? ManageInventoryMethodId { get; set; }
+ public bool? UseMultipleWarehouses { get; set; }
+ public string WarehouseId { get; set; }
+ public int? StockQuantity { get; set; }
+ public int? ReservedQuantity { get; set; }
+ public bool? StockAvailability { get; set; }
+ public bool? DisplayStockQuantity { get; set; }
+ public int? MinStockQuantity { get; set; }
+ public bool? LowStock { get; set; }
+ public LowStockActivity? LowStockActivityId { get; set; }
+ public int? NotifyAdminForQuantityBelow { get; set; }
+ public BackorderMode? BackorderModeId { get; set; }
+ public bool? AllowOutOfStockSubscriptions { get; set; }
+ public int? OrderMinimumQuantity { get; set; }
+ public int? OrderMaximumQuantity { get; set; }
+ public string AllowedQuantities { get; set; }
+ public bool? NotReturnable { get; set; }
+ public bool? DisableBuyButton { get; set; }
+ public bool? DisableWishlistButton { get; set; }
+ public bool? AvailableForPreOrder { get; set; }
+ public DateTime? PreOrderDateTimeUtc { get; set; }
+ public bool? CallForPrice { get; set; }
+ public double? Price { get; set; }
+ public double? OldPrice { get; set; }
+ public double? CatalogPrice { get; set; }
+ public double? ProductCost { get; set; }
+ public bool? EnteredPrice { get; set; }
+ public double? MinEnteredPrice { get; set; }
+ public double? MaxEnteredPrice { get; set; }
+ public bool? BasepriceEnabled { get; set; }
+ public double? BasepriceAmount { get; set; }
+ public string BasepriceUnitId { get; set; }
+ public double? BasepriceBaseAmount { get; set; }
+ public string BasepriceBaseUnitId { get; set; }
+ public string UnitId { get; set; }
+ public string CourseId { get; set; }
+ public bool? MarkAsNew { get; set; }
+ public DateTime? MarkAsNewStartDateTimeUtc { get; set; }
+ public DateTime? MarkAsNewEndDateTimeUtc { get; set; }
+ public double? Weight { get; set; }
+ public double? Length { get; set; }
+ public double? Width { get; set; }
+ public double? Height { get; set; }
+ public DateTime? AvailableStartDateTimeUtc { get; set; }
+ public DateTime? AvailableEndDateTimeUtc { get; set; }
+ public int? DisplayOrder { get; set; }
+ public int? DisplayOrderCategory { get; set; }
+ public int? DisplayOrderBrand { get; set; }
+ public int? DisplayOrderCollection { get; set; }
+ public bool? Published { get; set; }
+ public int? Sold { get; set; }
+ public Int64? Viewed { get; set; }
+ public int? OnSale { get; set; }
+ public string Flag { get; set; }
+ public string CategoryIds { get; set; }
+ public string CollectionIds { get; set; }
+ public string Picture1 { get; set; }
+ public string Picture2 { get; set; }
+ public string Picture3 { get; set; }
+ }
+}
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/BrandProfile.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/BrandProfile.cs
new file mode 100644
index 000000000..5fdf4ba3c
--- /dev/null
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/BrandProfile.cs
@@ -0,0 +1,27 @@
+using AutoMapper;
+using Grand.Business.Catalog.Services.ExportImport.Dto;
+using Grand.Domain.Catalog;
+using Grand.Infrastructure.Mapper;
+
+namespace Grand.Business.Catalog.Services.ExportImport.Mapper
+{
+ public class BrandProfile : Profile, IAutoMapperProfile
+ {
+ public BrandProfile()
+ {
+ CreateMap<BrandDto, Brand>()
+ .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
+ .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
+ .ForMember(x => x.PageSize, opt => opt.Condition(z => z.PageSize.HasValue))
+ .ForMember(x => x.AllowCustomersToSelectPageSize, opt => opt.Condition(z => z.AllowCustomersToSelectPageSize.HasValue))
+ .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
+ .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
+ .ForMember(x => x.IncludeInMenu, opt => opt.Condition(z => z.IncludeInMenu.HasValue))
+ .ForMember(x => x.DefaultSort, opt => opt.Condition(z => z.DefaultSort.HasValue))
+ .ForMember(x => x.Published, opt => opt.Condition(z => z.Published.HasValue))
+ .ForMember(x => x.DisplayOrder, opt => opt.Condition(z => z.DisplayOrder.HasValue));
+ }
+
+ public int Order => 0;
+ }
+}
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CategoryProfile.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CategoryProfile.cs
new file mode 100644
index 000000000..12671c3a2
--- /dev/null
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CategoryProfile.cs
@@ -0,0 +1,30 @@
+using AutoMapper;
+using Grand.Business.Catalog.Services.ExportImport.Dto;
+using Grand.Domain.Catalog;
+using Grand.Infrastructure.Mapper;
+
+namespace Grand.Business.Catalog.Services.ExportImport.Mapper
+{
+ public class CategoryProfile : Profile, IAutoMapperProfile
+ {
+ public CategoryProfile()
+ {
+ CreateMap<CategoryDto, Category>()
+ .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
+ .ForMember(x => x.PageSize, opt => opt.Condition(z => z.PageSize.HasValue))
+ .ForMember(x => x.AllowCustomersToSelectPageSize, opt => opt.Condition(z => z.AllowCustomersToSelectPageSize.HasValue))
+ .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
+ .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
+ .ForMember(x => x.IncludeInMenu, opt => opt.Condition(z => z.IncludeInMenu.HasValue))
+ .ForMember(x => x.DefaultSort, opt => opt.Condition(z => z.DefaultSort.HasValue))
+ .ForMember(x => x.FeaturedProductsOnHomePage, opt => opt.Condition(z => z.FeaturedProductsOnHomePage.HasValue))
+ .ForMember(x => x.ShowOnSearchBox, opt => opt.Condition(z => z.ShowOnSearchBox.HasValue))
+ .ForMember(x => x.SearchBoxDisplayOrder, opt => opt.Condition(z => z.SearchBoxDisplayOrder.HasValue))
+ .ForMember(x => x.HideOnCatalog, opt => opt.Condition(z => z.HideOnCatalog.HasValue))
+ .ForMember(x => x.Published, opt => opt.Condition(z => z.Published.HasValue))
+ .ForMember(x => x.DisplayOrder, opt => opt.Condition(z => z.DisplayOrder.HasValue));
+ }
+
+ public int Order => 0;
+ }
+}
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CollectionProfile.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CollectionProfile.cs
new file mode 100644
index 000000000..f04a88bfa
--- /dev/null
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/CollectionProfile.cs
@@ -0,0 +1,26 @@
+using AutoMapper;
+using Grand.Business.Catalog.Services.ExportImport.Dto;
+using Grand.Domain.Catalog;
+using Grand.Infrastructure.Mapper;
+
+namespace Grand.Business.Catalog.Services.ExportImport.Mapper
+{
+ public class CollectionProfile : Profile, IAutoMapperProfile
+ {
+ public CollectionProfile()
+ {
+ CreateMap<CollectionDto, Collection>()
+ .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
+ .ForMember(x => x.PageSize, opt => opt.Condition(z => z.PageSize.HasValue))
+ .ForMember(x => x.AllowCustomersToSelectPageSize, opt => opt.Condition(z => z.AllowCustomersToSelectPageSize.HasValue))
+ .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
+ .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
+ .ForMember(x => x.IncludeInMenu, opt => opt.Condition(z => z.IncludeInMenu.HasValue))
+ .ForMember(x => x.DefaultSort, opt => opt.Condition(z => z.DefaultSort.HasValue))
+ .ForMember(x => x.Published, opt => opt.Condition(z => z.Published.HasValue))
+ .ForMember(x => x.DisplayOrder, opt => opt.Condition(z => z.DisplayOrder.HasValue));
+ }
+
+ public int Order => 0;
+ }
+}
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/ProductProfile.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/ProductProfile.cs
new file mode 100644
index 000000000..8ca59a251
--- /dev/null
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/Mapper/ProductProfile.cs
@@ -0,0 +1,99 @@
+using AutoMapper;
+using Grand.Business.Catalog.Services.ExportImport.Dto;
+using Grand.Domain.Catalog;
+using Grand.Infrastructure.Mapper;
+
+namespace Grand.Business.Catalog.Services.ExportImport.Mapper
+{
+ public class ProductProfile : Profile, IAutoMapperProfile
+ {
+ public ProductProfile()
+ {
+ CreateMap<ProductDto, Product>()
+ .ForMember(x => x.UpdatedOnUtc, opt => opt.MapFrom(o => DateTime.UtcNow))
+ .ForMember(x => x.ProductTypeId, opt => opt.Condition(z => z.ProductTypeId.HasValue))
+ .ForMember(x => x.VisibleIndividually, opt => opt.Condition(z => z.VisibleIndividually.HasValue))
+ .ForMember(x => x.ShowOnHomePage, opt => opt.Condition(z => z.ShowOnHomePage.HasValue))
+ .ForMember(x => x.BestSeller, opt => opt.Condition(z => z.BestSeller.HasValue))
+ .ForMember(x => x.AllowCustomerReviews, opt => opt.Condition(z => z.AllowCustomerReviews.HasValue))
+ .ForMember(x => x.ApprovedRatingSum, opt => opt.Condition(z => z.ApprovedRatingSum.HasValue))
+ .ForMember(x => x.NotApprovedRatingSum, opt => opt.Condition(z => z.NotApprovedRatingSum.HasValue))
+ .ForMember(x => x.ApprovedTotalReviews, opt => opt.Condition(z => z.ApprovedTotalReviews.HasValue))
+ .ForMember(x => x.NotApprovedTotalReviews, opt => opt.Condition(z => z.NotApprovedTotalReviews.HasValue))
+ .ForMember(x => x.IsGiftVoucher, opt => opt.Condition(z => z.IsGiftVoucher.HasValue))
+ .ForMember(x => x.GiftVoucherTypeId, opt => opt.Condition(z => z.GiftVoucherTypeId.HasValue))
+ .ForMember(x => x.OverGiftAmount, opt => opt.Condition(z => z.OverGiftAmount.HasValue))
+ .ForMember(x => x.RequireOtherProducts, opt => opt.Condition(z => z.RequireOtherProducts.HasValue))
+ .ForMember(x => x.AutoAddRequiredProducts, opt => opt.Condition(z => z.AutoAddRequiredProducts.HasValue))
+ .ForMember(x => x.IsDownload, opt => opt.Condition(z => z.IsDownload.HasValue))
+ .ForMember(x => x.UnlimitedDownloads, opt => opt.Condition(z => z.UnlimitedDownloads.HasValue))
+ .ForMember(x => x.MaxNumberOfDownloads, opt => opt.Condition(z => z.MaxNumberOfDownloads.HasValue))
+ .ForMember(x => x.DownloadExpirationDays, opt => opt.Condition(z => z.DownloadExpirationDays.HasValue))
+ .ForMember(x => x.DownloadActivationTypeId, opt => opt.Condition(z => z.DownloadActivationTypeId.HasValue))
+ .ForMember(x => x.HasSampleDownload, opt => opt.Condition(z => z.HasSampleDownload.HasValue))
+ .ForMember(x => x.HasUserAgreement, opt => opt.Condition(z => z.HasUserAgreement.HasValue))
+ .ForMember(x => x.IsRecurring, opt => opt.Condition(z => z.IsRecurring.HasValue))
+ .ForMember(x => x.RecurringCycleLength, opt => opt.Condition(z => z.RecurringCycleLength.HasValue))
+ .ForMember(x => x.RecurringCyclePeriodId, opt => opt.Condition(z => z.RecurringCyclePeriodId.HasValue))
+ .ForMember(x => x.RecurringTotalCycles, opt => opt.Condition(z => z.RecurringTotalCycles.HasValue))
+ .ForMember(x => x.IncBothDate, opt => opt.Condition(z => z.IncBothDate.HasValue))
+ .ForMember(x => x.Interval, opt => opt.Condition(z => z.Interval.HasValue))
+ .ForMember(x => x.IntervalUnitId, opt => opt.Condition(z => z.IntervalUnitId.HasValue))
+ .ForMember(x => x.IsFreeShipping, opt => opt.Condition(z => z.IsFreeShipping.HasValue))
+ .ForMember(x => x.ShipSeparately, opt => opt.Condition(z => z.ShipSeparately.HasValue))
+ .ForMember(x => x.AdditionalShippingCharge, opt => opt.Condition(z => z.AdditionalShippingCharge.HasValue))
+ .ForMember(x => x.IsTaxExempt, opt => opt.Condition(z => z.IsTaxExempt.HasValue))
+ .ForMember(x => x.IsTele, opt => opt.Condition(z => z.IsTele.HasValue))
+ .ForMember(x => x.ManageInventoryMethodId, opt => opt.Condition(z => z.ManageInventoryMethodId.HasValue))
+ .ForMember(x => x.UseMultipleWarehouses, opt => opt.Condition(z => z.UseMultipleWarehouses.HasValue))
+ .ForMember(x => x.StockQuantity, opt => opt.Condition(z => z.StockQuantity.HasValue))
+ .ForMember(x => x.ReservedQuantity, opt => opt.Condition(z => z.ReservedQuantity.HasValue))
+ .ForMember(x => x.StockAvailability, opt => opt.Condition(z => z.StockAvailability.HasValue))
+ .ForMember(x => x.DisplayStockQuantity, opt => opt.Condition(z => z.DisplayStockQuantity.HasValue))
+ .ForMember(x => x.MinStockQuantity, opt => opt.Condition(z => z.MinStockQuantity.HasValue))
+ .ForMember(x => x.LowStock, opt => opt.Condition(z => z.LowStock.HasValue))
+ .ForMember(x => x.LowStockActivityId, opt => opt.Condition(z => z.LowStockActivityId.HasValue))
+ .ForMember(x => x.NotifyAdminForQuantityBelow, opt => opt.Condition(z => z.NotifyAdminForQuantityBelow.HasValue))
+ .ForMember(x => x.BackorderModeId, opt => opt.Condition(z => z.BackorderModeId.HasValue))
+ .ForMember(x => x.AllowOutOfStockSubscriptions, opt => opt.Condition(z => z.AllowOutOfStockSubscriptions.HasValue))
+ .ForMember(x => x.OrderMinimumQuantity, opt => opt.Condition(z => z.OrderMinimumQuantity.HasValue))
+ .ForMember(x => x.OrderMaximumQuantity, opt => opt.Condition(z => z.OrderMaximumQuantity.HasValue))
+ .ForMember(x => x.NotReturnable, opt => opt.Condition(z => z.NotReturnable.HasValue))
+ .ForMember(x => x.DisableBuyButton, opt => opt.Condition(z => z.DisableBuyButton.HasValue))
+ .ForMember(x => x.DisableWishlistButton, opt => opt.Condition(z => z.DisableWishlistButton.HasValue))
+ .ForMember(x => x.AvailableForPreOrder, opt => opt.Condition(z => z.AvailableForPreOrder.HasValue))
+ .ForMember(x => x.PreOrderDateTimeUtc, opt => opt.Condition(z => z.PreOrderDateTimeUtc.HasValue))
+ .ForMember(x => x.CallForPrice, opt => opt.Condition(z => z.CallForPrice.HasValue))
+ .ForMember(x => x.Price, opt => opt.Condition(z => z.Price.HasValue))
+ .ForMember(x => x.OldPrice, opt => opt.Condition(z => z.OldPrice.HasValue))
+ .ForMember(x => x.CatalogPrice, opt => opt.Condition(z => z.CatalogPrice.HasValue))
+ .ForMember(x => x.ProductCost, opt => opt.Condition(z => z.ProductCost.HasValue))
+ .ForMember(x => x.EnteredPrice, opt => opt.Condition(z => z.EnteredPrice.HasValue))
+ .ForMember(x => x.MinEnteredPrice, opt => opt.Condition(z => z.MinEnteredPrice.HasValue))
+ .ForMember(x => x.MaxEnteredPrice, opt => opt.Condition(z => z.MaxEnteredPrice.HasValue))
+ .ForMember(x => x.BasepriceEnabled, opt => opt.Condition(z => z.BasepriceEnabled.HasValue))
+ .ForMember(x => x.BasepriceAmount, opt => opt.Condition(z => z.BasepriceAmount.HasValue))
+ .ForMember(x => x.BasepriceBaseAmount, opt => opt.Condition(z => z.BasepriceBaseAmount.HasValue))
+ .ForMember(x => x.MarkAsNew, opt => opt.Condition(z => z.MarkAsNew.HasValue))
+ .ForMember(x => x.MarkAsNewStartDateTimeUtc, opt => opt.Condition(z => z.MarkAsNewStartDateTimeUtc.HasValue))
+ .ForMember(x => x.MarkAsNewEndDateTimeUtc, opt => opt.Condition(z => z.MarkAsNewEndDateTimeUtc.HasValue))
+ .ForMember(x => x.Weight, opt => opt.Condition(z => z.Weight.HasValue))
+ .ForMember(x => x.Length, opt => opt.Condition(z => z.Length.HasValue))
+ .ForMember(x => x.Width, opt => opt.Condition(z => z.Width.HasValue))
+ .ForMember(x => x.Height, opt => opt.Condition(z => z.Height.HasValue))
+ .ForMember(x => x.AvailableStartDateTimeUtc, opt => opt.Condition(z => z.AvailableStartDateTimeUtc.HasValue))
+ .ForMember(x => x.AvailableEndDateTimeUtc, opt => opt.Condition(z => z.AvailableEndDateTimeUtc.HasValue))
+ .ForMember(x => x.DisplayOrder, opt => opt.Condition(z => z.DisplayOrder.HasValue))
+ .ForMember(x => x.DisplayOrderCategory, opt => opt.Condition(z => z.DisplayOrderCategory.HasValue))
+ .ForMember(x => x.DisplayOrderBrand, opt => opt.Condition(z => z.DisplayOrderBrand.HasValue))
+ .ForMember(x => x.DisplayOrderCollection, opt => opt.Condition(z => z.DisplayOrderCollection.HasValue))
+ .ForMember(x => x.Sold, opt => opt.Condition(z => z.Sold.HasValue))
+ .ForMember(x => x.Viewed, opt => opt.Condition(z => z.Viewed.HasValue))
+ .ForMember(x => x.OnSale, opt => opt.Condition(z => z.OnSale.HasValue))
+ .ForMember(x => x.Published, opt => opt.Condition(z => z.Published.HasValue));
+
+ }
+
+ public int Order => 0;
+ }
+}
diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs
new file mode 100644
index 000000000..ed564bcd2
--- /dev/null
+++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs
@@ -0,0 +1,361 @@
+using Grand.Business.Catalog.Services.ExportImport.Dto;
+using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Catalog.Brands;
+using Grand.Business.Core.Interfaces.Catalog.Categories;
+using Grand.Business.Core.Interfaces.Catalog.Collections;
+using Grand.Business.Core.Interfaces.Catalog.Directory;
+using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Business.Core.Interfaces.Catalog.Tax;
+using Grand.Business.Core.Interfaces.Checkout.Shipping;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Seo;
+using Grand.Business.Core.Interfaces.ExportImport;
+using Grand.Business.Core.Interfaces.Storage;
+using Grand.Business.Core.Utilities.System;
+using Grand.Domain.Catalog;
+using Grand.Domain.Media;
+using Grand.Domain.Seo;
+using Grand.Infrastructure.Mapper;
+using Microsoft.AspNetCore.StaticFiles;
+
+namespace Grand.Business.Catalog.Services.ExportImport
+{
+ public class ProductImportDataObject : IImportDataObject<ProductDto>
+ {
+ private readonly IProductService _productService;
+ private readonly IPictureService _pictureService;
+ private readonly IProductLayoutService _productLayoutService;
+ private readonly IDeliveryDateService _deliveryDateService;
+ private readonly ITaxCategoryService _taxService;
+ private readonly IWarehouseService _warehouseService;
+ private readonly IMeasureService _measureService;
+ private readonly ICategoryService _categoryService;
+ private readonly IProductCategoryService _productCategoryService;
+ private readonly IBrandService _brandService;
+ private readonly ICollectionService _collectionService;
+ private readonly IProductCollectionService _productCollectionService;
+ private readonly ISlugService _slugService;
+ private readonly ILanguageService _languageService;
+
+ private readonly SeoSettings _seoSetting;
+
+ public ProductImportDataObject(
+ IProductService productService,
+ IPictureService pictureService,
+ IProductLayoutService productLayoutService,
+ IDeliveryDateService deliveryDateService,
+ ITaxCategoryService taxService,
+ IWarehouseService warehouseService,
+ IMeasureService measureService,
+ ISlugService slugService,
+ ILanguageService languageService,
+ ICategoryService categoryService,
+ IProductCategoryService productCategoryService,
+ IBrandService brandService,
+ ICollectionService collectionService,
+ IProductCollectionService productCollectionService,
+ SeoSettings seoSetting)
+ {
+ _productService = productService;
+ _pictureService = pictureService;
+ _productLayoutService = productLayoutService;
+ _deliveryDateService = deliveryDateService;
+ _taxService = taxService;
+ _warehouseService = warehouseService;
+ _measureService = measureService;
+ _slugService = slugService;
+ _languageService = languageService;
+ _categoryService = categoryService;
+ _productCategoryService = productCategoryService;
+ _brandService = brandService;
+ _collectionService = collectionService;
+ _productCollectionService = productCollectionService;
+ _seoSetting = seoSetting;
+ }
+
+ public async Task Execute(IEnumerable<ProductDto> data)
+ {
+ foreach (var item in data)
+ {
+ await Import(item);
+ }
+ }
+
+ protected async Task Import(ProductDto productDto)
+ {
+ var product = await _productService.GetProductById(productDto.Id);
+ product ??= await _productService.GetProductBySku(productDto.Sku);
+
+ var isNew = product == null;
+
+ if (product == null) product = productDto.MapTo<ProductDto, Product>();
+ else productDto.MapTo(product);
+
+ if (isNew) await _productService.InsertProduct(product);
+ else await _productService.UpdateProduct(product);
+
+ if (!ValidProduct(product)) return;
+
+ await UpdateProductData(productDto, product, isNew);
+
+ }
+
+ protected async Task<Product> UpdateProductData(ProductDto productDto, Product product, bool isNew)
+ {
+ await UpdateProductDataLayout(product);
+ await UpdateProductDataDeliveryDate(product);
+ await UpdateProductDataTaxCategory(product);
+ await UpdateProductDataWarehouse(product);
+ await UpdateProductDataUnit(product);
+ await UpdateProductDataBrand(product);
+
+ //search engine name
+ var sename = product.SeName ?? product.Name;
+ sename = await product.ValidateSeName(sename, product.Name, true, _seoSetting, _slugService, _languageService);
+ await _slugService.SaveSlug(product, sename, "");
+ product.SeName = sename;
+ await _productService.UpdateProduct(product);
+
+ product.LowStock = product.MinStockQuantity > 0 && product.MinStockQuantity >= product.StockQuantity;
+
+ if (!string.IsNullOrEmpty(productDto.CategoryIds)) await PrepareProductCategories(product, productDto.CategoryIds);
+
+ if (!string.IsNullOrEmpty(productDto.CollectionIds)) await PrepareProductCollections(product, productDto.CollectionIds);
+
+ //pictures
+ await PrepareProductPictures(productDto, product, isNew);
+
+ return product;
+ }
+ protected async Task<Product> UpdateProductDataLayout(Product product)
+ {
+ if (string.IsNullOrEmpty(product.ProductLayoutId))
+ product.ProductLayoutId = (await _productLayoutService.GetAllProductLayouts()).FirstOrDefault().Id;
+ else
+ {
+ var layout = await _productLayoutService.GetProductLayoutById(product.ProductLayoutId);
+ if (layout == null)
+ product.ProductLayoutId = (await _productLayoutService.GetAllProductLayouts()).FirstOrDefault().Id;
+ }
+ return product;
+ }
+ protected async Task<Product> UpdateProductDataDeliveryDate(Product product)
+ {
+ if (string.IsNullOrEmpty(product.DeliveryDateId))
+ product.DeliveryDateId = (await _deliveryDateService.GetAllDeliveryDates()).FirstOrDefault().Id;
+ else
+ {
+ var deliveryDate = await _deliveryDateService.GetDeliveryDateById(product.DeliveryDateId);
+ if (deliveryDate == null)
+ product.DeliveryDateId = (await _deliveryDateService.GetAllDeliveryDates()).FirstOrDefault().Id;
+ }
+ return product;
+ }
+ protected async Task<Product> UpdateProductDataTaxCategory(Product product)
+ {
+ if (string.IsNullOrEmpty(product.TaxCategoryId))
+ product.TaxCategoryId = (await _taxService.GetAllTaxCategories()).FirstOrDefault().Id;
+ else
+ {
+ var taxCategory = await _taxService.GetTaxCategoryById(product.TaxCategoryId);
+ if (taxCategory == null)
+ product.TaxCategoryId = (await _taxService.GetAllTaxCategories()).FirstOrDefault().Id;
+ }
+ return product;
+ }
+ protected async Task<Product> UpdateProductDataWarehouse(Product product)
+ {
+ if (string.IsNullOrEmpty(product.WarehouseId))
+ product.WarehouseId = (await _warehouseService.GetAllWarehouses()).FirstOrDefault().Id;
+ else
+ {
+ var warehouse = await _warehouseService.GetWarehouseById(product.WarehouseId);
+ if (warehouse == null)
+ product.WarehouseId = (await _warehouseService.GetAllWarehouses()).FirstOrDefault().Id;
+ }
+ return product;
+ }
+ protected async Task<Product> UpdateProductDataUnit(Product product)
+ {
+ if (string.IsNullOrEmpty(product.UnitId))
+ product.UnitId = (await _measureService.GetAllMeasureUnits()).FirstOrDefault().Id;
+ else
+ {
+ var unit = await _measureService.GetMeasureUnitById(product.UnitId);
+ if (unit == null)
+ product.UnitId = (await _measureService.GetAllMeasureUnits()).FirstOrDefault().Id;
+ }
+ return product;
+ }
+ protected async Task<Product> UpdateProductDataBrand(Product product)
+ {
+ if (string.IsNullOrEmpty(product.BrandId))
+ product.BrandId = (await _brandService.GetAllBrands()).FirstOrDefault().Id;
+ else
+ {
+ var brand = await _brandService.GetBrandById(product.BrandId);
+ if (brand == null)
+ product.BrandId = (await _brandService.GetAllBrands()).FirstOrDefault().Id;
+ }
+ return product;
+ }
+ protected virtual async Task PrepareProductCategories(Product product, string categoryIds)
+ {
+ foreach (var id in categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()))
+ {
+ if (product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) == null)
+ {
+ //ensure that category exists
+ var category = await _categoryService.GetCategoryById(id);
+ if (category != null)
+ {
+ var productCategory = new ProductCategory {
+ CategoryId = category.Id,
+ IsFeaturedProduct = false,
+ DisplayOrder = 1
+ };
+ await _productCategoryService.InsertProductCategory(productCategory, product.Id);
+ }
+ }
+ }
+ }
+
+ protected virtual async Task PrepareProductCollections(Product product, string collectionIds)
+ {
+ foreach (var id in collectionIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()))
+ {
+ if (product.ProductCollections.FirstOrDefault(x => x.CollectionId == id) == null)
+ {
+ //ensure that collection exists
+ var collection = await _collectionService.GetCollectionById(id);
+ if (collection != null)
+ {
+ var productCollection = new ProductCollection {
+ CollectionId = collection.Id,
+ IsFeaturedProduct = false,
+ DisplayOrder = 1
+ };
+ await _productCollectionService.InsertProductCollection(productCollection, product.Id);
+ }
+ }
+ }
+ }
+
+ protected virtual async Task PrepareProductPictures(ProductDto productDto, Product product, bool isNew)
+ {
+ var picture1 = productDto.Picture1;
+ var picture2 = productDto.Picture2;
+ var picture3 = productDto.Picture3;
+
+ foreach (var picturePath in new[] { picture1, picture2, picture3 })
+ {
+ if (string.IsNullOrEmpty(picturePath))
+ continue;
+ if (!picturePath.ToLower().StartsWith(("http".ToLower())))
+ {
+ var mimeType = GetMimeTypeFromFilePath(picturePath);
+ var newPictureBinary = File.ReadAllBytes(picturePath);
+ var pictureAlreadyExists = false;
+ if (!isNew)
+ {
+ //compare with existing product pictures
+ var existingPictures = product.ProductPictures;
+ foreach (var existingPicture in existingPictures)
+ {
+ var pp = await _pictureService.GetPictureById(existingPicture.PictureId);
+ var existingBinary = await _pictureService.LoadPictureBinary(pp);
+ //picture binary after validation (like in database)
+ var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
+ if (existingBinary.SequenceEqual(validatedPictureBinary) || existingBinary.SequenceEqual(newPictureBinary))
+ {
+ //the same picture content
+ pictureAlreadyExists = true;
+ break;
+ }
+ }
+ }
+
+ if (!pictureAlreadyExists)
+ {
+ var picture = await _pictureService.InsertPicture(newPictureBinary, mimeType, _pictureService.GetPictureSeName(product.Name), "", "", false,
+ Domain.Common.Reference.Product, product.Id);
+ var productPicture = new ProductPicture {
+ PictureId = picture.Id,
+ DisplayOrder = 1,
+ };
+ await _productService.InsertProductPicture(productPicture, product.Id);
+ }
+ }
+ else
+ {
+ byte[] fileBinary = await DownloadUrl.DownloadFile(picturePath);
+ if (fileBinary != null)
+ {
+ var mimeType = GetMimeTypeFromFilePath(picturePath);
+ var picture = await _pictureService.InsertPicture(fileBinary, mimeType, _pictureService.GetPictureSeName(product.Name), "", "", false, Domain.Common.Reference.Product, product.Id);
+ var productPicture = new ProductPicture {
+ PictureId = picture.Id,
+ DisplayOrder = 1,
+ };
+ await _productService.InsertProductPicture(productPicture, product.Id);
+ }
+ }
+ }
+
+ }
+
+
+ protected virtual bool ValidProduct(Product product)
+ {
+ if (string.IsNullOrEmpty(product.Name))
+ return false;
+
+ return true;
+ }
+
+ /// <summary>
+ /// Creates or loads the image
+ /// </summary>
+ /// <param name="picturePath">The path to the image file</param>
+ /// <param name="name">The name of the object</param>
+ /// <param name="picId">Image identifier, may be null</param>
+ /// <returns>The image or null if the image has not changed</returns>
+ protected virtual async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")
+ {
+ if (string.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
+ return null;
+
+ var mimeType = GetMimeTypeFromFilePath(picturePath);
+ var newPictureBinary = File.ReadAllBytes(picturePath);
+ var pictureAlreadyExists = false;
+ if (!string.IsNullOrEmpty(picId))
+ {
+ //compare with existing product pictures
+ var existingPicture = await _pictureService.GetPictureById(picId);
+
+ var existingBinary = await _pictureService.LoadPictureBinary(existingPicture);
+ //picture binary after validation (like in database)
+ var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
+ if (existingBinary.SequenceEqual(validatedPictureBinary) ||
+ existingBinary.SequenceEqual(newPictureBinary))
+ {
+ pictureAlreadyExists = true;
+ }
+ }
+
+ if (pictureAlreadyExists) return null;
+
+ var newPicture = await _pictureService.InsertPicture(newPictureBinary, mimeType,
+ _pictureService.GetPictureSeName(name));
+ return newPicture;
+ }
+ protected virtual string GetMimeTypeFromFilePath(string filePath)
+ {
+ new FileExtensionContentTypeProvider().TryGetContentType(filePath, out string mimeType);
+ //set to jpeg in case mime type cannot be found
+ if (mimeType == null)
+ mimeType = "image/jpeg";
+ return mimeType;
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs b/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs
index 96f803545..9d95da1d3 100644
--- a/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs
+++ b/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs
@@ -22,6 +22,7 @@ using Grand.Business.Core.Interfaces.Catalog.Directory;
using Grand.Business.Core.Interfaces.ExportImport;
using Grand.Domain.Catalog;
using Grand.Business.Catalog.Services.ExportImport;
+using Grand.Business.Catalog.Services.ExportImport.Dto;
namespace Grand.Business.Catalog.Startup
{
@@ -95,6 +96,11 @@ namespace Grand.Business.Catalog.Startup
serviceCollection.AddScoped<ISchemaProperty<Category>, CategorySchemaProperty>();
serviceCollection.AddScoped<ISchemaProperty<Collection>, CollectionSchemaProperty>();
serviceCollection.AddScoped<ISchemaProperty<Product>, ProductSchemaProperty>();
+
+ serviceCollection.AddScoped<IImportDataObject<CategoryDto>, CategoryImportDataObject>();
+ serviceCollection.AddScoped<IImportDataObject<BrandDto>, BrandImportDataObject>();
+ serviceCollection.AddScoped<IImportDataObject<CollectionDto>, CollectionImportDataObject>();
+ serviceCollection.AddScoped<IImportDataObject<ProductDto>, ProductImportDataObject>();
}
}
diff --git a/src/Business/Grand.Business.Common/Grand.Business.Common.csproj b/src/Business/Grand.Business.Common/Grand.Business.Common.csproj
index e0b906b65..25c0fdad8 100644
--- a/src/Business/Grand.Business.Common/Grand.Business.Common.csproj
+++ b/src/Business/Grand.Business.Common/Grand.Business.Common.csproj
@@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\Build\Grand.Common.props" />
<ItemGroup>
+ <PackageReference Include="ExcelMapper" Version="5.2.429" />
<PackageReference Include="HtmlRendererCore.PdfSharp" Version="1.0.5" />
<PackageReference Include="NPOI" Version="2.5.6" />
</ItemGroup>
diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.cs b/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.cs
new file mode 100644
index 000000000..d127defb2
--- /dev/null
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.cs
@@ -0,0 +1,53 @@
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.ExportImport;
+using Grand.Domain.Directory;
+
+namespace Grand.Business.Common.Services.ExportImport
+{
+ public class CountryImportDataObject : IImportDataObject<CountryStates>
+ {
+ private readonly ICountryService _countryService;
+
+ public CountryImportDataObject(ICountryService countryService)
+ {
+ _countryService = countryService;
+ }
+
+ public async Task Execute(IEnumerable<CountryStates> data)
+ {
+ foreach (var item in data)
+ {
+ await Import(item);
+ }
+ }
+
+ protected async Task Import(CountryStates countryStatesDto)
+ {
+ var country = await _countryService.GetCountryByTwoLetterIsoCode(countryStatesDto.Country);
+ if (country == null)
+ return;
+
+ var state = country.StateProvinces.FirstOrDefault(x => x.Abbreviation.Equals(countryStatesDto.Abbreviation, StringComparison.OrdinalIgnoreCase));
+ if (state != null)
+ {
+ state.Name = countryStatesDto.StateProvinceName;
+ state.Abbreviation = countryStatesDto.Abbreviation;
+ state.Published = countryStatesDto.Published;
+ state.DisplayOrder = countryStatesDto.DisplayOrder;
+ await _countryService.UpdateStateProvince(state, country.Id);
+ }
+ else
+ {
+ state = new StateProvince {
+ Name = countryStatesDto.StateProvinceName,
+ Abbreviation = countryStatesDto.Abbreviation,
+ Published = countryStatesDto.Published,
+ DisplayOrder = countryStatesDto.DisplayOrder,
+ };
+ await _countryService.InsertStateProvince(state, country.Id);
+ }
+ }
+
+
+ }
+}
diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/CountrySchemaProperty.cs b/src/Business/Grand.Business.Common/Services/ExportImport/CountrySchemaProperty.cs
index dacba82de..510641b8e 100644
--- a/src/Business/Grand.Business.Common/Services/ExportImport/CountrySchemaProperty.cs
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/CountrySchemaProperty.cs
@@ -9,8 +9,8 @@ namespace Grand.Business.Common.Services.ExportImport
{
var properties = new[]
{
- new PropertyByName<CountryStates>("Country", p => p.TwoLetterIsoCode),
- new PropertyByName<CountryStates>("Name", p => p.StateProvinceName),
+ new PropertyByName<CountryStates>("Country", p => p.Country),
+ new PropertyByName<CountryStates>("StateProvinceName", p => p.StateProvinceName),
new PropertyByName<CountryStates>("Abbreviation", p => p.Abbreviation),
new PropertyByName<CountryStates>("DisplayOrder", p => p.DisplayOrder),
new PropertyByName<CountryStates>("Published", p => p.Published)
@@ -18,13 +18,4 @@ namespace Grand.Business.Common.Services.ExportImport
return properties;
}
}
-
- public class CountryStates
- {
- public string TwoLetterIsoCode { get; set; }
- public string StateProvinceName { get; set; }
- public string Abbreviation { get; set; }
- public int DisplayOrder { get; set; }
- public bool Published { get; set; }
- }
}
diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/CountryStates.cs b/src/Business/Grand.Business.Common/Services/ExportImport/CountryStates.cs
new file mode 100644
index 000000000..3bd02864f
--- /dev/null
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/CountryStates.cs
@@ -0,0 +1,11 @@
+namespace Grand.Business.Common.Services.ExportImport
+{
+ public class CountryStates
+ {
+ public string Country { get; set; }
+ public string StateProvinceName { get; set; }
+ public string Abbreviation { get; set; }
+ public int DisplayOrder { get; set; }
+ public bool Published { get; set; }
+ }
+}
diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs
index 38276d5ad..dde72f014 100644
--- a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs
@@ -13,6 +13,7 @@ namespace Grand.Business.Common.Services.ExportImport
{
IWorkbook xlPackage = new XSSFWorkbook();
ISheet worksheet = xlPackage.CreateSheet(typeof(T).Name);
+
var manager = new PropertyManager<T>(properties);
WriteCaption(worksheet, properties);
@@ -21,8 +22,7 @@ namespace Grand.Business.Common.Services.ExportImport
foreach (var items in itemsToExport)
{
- manager.CurrentObject = items;
- WriteToXlsx(manager, properties, worksheet, row++);
+ WriteToXlsx(properties, worksheet, items, row++);
}
xlPackage.Write(stream);
return stream.ToArray();
@@ -47,15 +47,12 @@ namespace Grand.Business.Common.Services.ExportImport
/// </summary>
/// <param name="worksheet">worksheet</param>
/// <param name="row">Row index</param>
- private void WriteToXlsx<T>(PropertyManager<T> manager, PropertyByName<T>[] properties, ISheet sheet, int row)
+ private void WriteToXlsx<T>(PropertyByName<T>[] properties, ISheet sheet, T items, int row)
{
- if (manager.CurrentObject == null)
- return;
-
IRow _row = sheet.CreateRow(row);
foreach (var prop in properties)
{
- var cellValue = (prop.GetProperty(manager.CurrentObject)?.ToString());
+ var cellValue = (prop.GetProperty(items)?.ToString());
if (cellValue != null && cellValue.Length >= 32767) // 32767 is the max char size of an excel cell
{
cellValue = cellValue.Substring(0, 32767); //Truncate the content to max size.
diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelImportProvider.cs b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelImportProvider.cs
new file mode 100644
index 000000000..dc2689318
--- /dev/null
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelImportProvider.cs
@@ -0,0 +1,13 @@
+using Ganss.Excel;
+using Grand.Business.Core.Interfaces.ExportImport;
+
+namespace Grand.Business.Common.Services.ExportImport
+{
+ public class ExcelImportProvider : IImportDataProvider
+ {
+ public IEnumerable<T> Convert<T>(Stream stream)
+ {
+ return new ExcelMapper(stream).Fetch<T>();
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/ImportManager.cs b/src/Business/Grand.Business.Common/Services/ExportImport/ImportManager.cs
new file mode 100644
index 000000000..0378676d8
--- /dev/null
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/ImportManager.cs
@@ -0,0 +1,22 @@
+using Grand.Business.Core.Interfaces.ExportImport;
+
+namespace Grand.Business.Common.Services.ExportImport
+{
+ public class ImportManager<T> : IImportManager<T> where T : class
+ {
+ private readonly IImportDataProvider _importDataProvider;
+ private readonly IImportDataObject<T> _importDataObject;
+
+ public ImportManager(IImportDataProvider importDataProvider, IImportDataObject<T> importDataObject)
+ {
+ _importDataProvider = importDataProvider;
+ _importDataObject = importDataObject;
+ }
+
+ public async Task Import(Stream stream)
+ {
+ var data = _importDataProvider.Convert<T>(stream);
+ await _importDataObject.Execute(data);
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Common/Startup/StartupApplication.cs b/src/Business/Grand.Business.Common/Startup/StartupApplication.cs
index 7ad3af52b..0e273aef0 100644
--- a/src/Business/Grand.Business.Common/Startup/StartupApplication.cs
+++ b/src/Business/Grand.Business.Common/Startup/StartupApplication.cs
@@ -18,7 +18,6 @@ using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Interfaces.Common.Seo;
using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Interfaces.ExportImport;
-using Grand.Domain.Directory;
using Grand.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
@@ -103,8 +102,14 @@ namespace Grand.Business.Common.Startup
private void RegisterExportImportService(IServiceCollection serviceCollection)
{
serviceCollection.AddScoped<ISchemaProperty<CountryStates>, CountrySchemaProperty>();
+
serviceCollection.AddScoped<IExportProvider, ExcelExportProvider>();
serviceCollection.AddScoped(typeof(IExportManager<>), typeof(ExportManager<>));
+
+ serviceCollection.AddScoped<IImportDataProvider, ExcelImportProvider>();
+ serviceCollection.AddScoped(typeof(IImportManager<>), typeof(ImportManager<>));
+
+ serviceCollection.AddScoped<IImportDataObject<CountryStates>, CountryImportDataObject>();
}
}
}
diff --git a/src/Business/Grand.Business.Core/Interfaces/ExportImport/IImportDataObject.cs b/src/Business/Grand.Business.Core/Interfaces/ExportImport/IImportDataObject.cs
new file mode 100644
index 000000000..483d23baf
--- /dev/null
+++ b/src/Business/Grand.Business.Core/Interfaces/ExportImport/IImportDataObject.cs
@@ -0,0 +1,7 @@
+namespace Grand.Business.Core.Interfaces.ExportImport
+{
+ public interface IImportDataObject<T>
+ {
+ Task Execute(IEnumerable<T> data);
+ }
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Core/Interfaces/ExportImport/IImportDataProvider.cs b/src/Business/Grand.Business.Core/Interfaces/ExportImport/IImportDataProvider.cs
new file mode 100644
index 000000000..fcdd63b96
--- /dev/null
+++ b/src/Business/Grand.Business.Core/Interfaces/ExportImport/IImportDataProvider.cs
@@ -0,0 +1,7 @@
+namespace Grand.Business.Core.Interfaces.ExportImport
+{
+ public interface IImportDataProvider
+ {
+ IEnumerable<T> Convert<T>(Stream stream);
+ }
+}
diff --git a/src/Business/Grand.Business.Core/Interfaces/ExportImport/IImportManager.cs b/src/Business/Grand.Business.Core/Interfaces/ExportImport/IImportManager.cs
new file mode 100644
index 000000000..c0dbf741a
--- /dev/null
+++ b/src/Business/Grand.Business.Core/Interfaces/ExportImport/IImportManager.cs
@@ -0,0 +1,7 @@
+namespace Grand.Business.Core.Interfaces.ExportImport
+{
+ public interface IImportManager<T>
+ {
+ Task Import(Stream stream);
+ }
+}
diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs
index 8c8a093c6..75bb55bd2 100644
--- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs
+++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs
@@ -78,5 +78,13 @@ namespace Grand.Business.Core.Interfaces.Marketing.Newsletters
/// <param name="subscriptions">Subscriptions</param>
/// <returns>Result in TXT (string) format</returns>
string ExportNewsletterSubscribersToTxt(IList<NewsLetterSubscription> subscriptions);
+
+ /// <summary>
+ /// Import newsletter subscribers from TXT file
+ /// </summary>
+ /// <param name="stream">Stream</param>
+ /// <param name="currentStoreId">Current store ident</param>
+ /// <returns>Number of imported subscribers</returns>
+ Task<int> ImportNewsletterSubscribersFromTxt(Stream stream, string currentStoreId);
}
}
diff --git a/src/Business/Grand.Business.Core/Interfaces/System/ExportImport/IExportManager.cs b/src/Business/Grand.Business.Core/Interfaces/System/ExportImport/IExportManager.cs
deleted file mode 100644
index 90fab551b..000000000
--- a/src/Business/Grand.Business.Core/Interfaces/System/ExportImport/IExportManager.cs
+++ /dev/null
@@ -1,79 +0,0 @@
-//using Grand.Domain.Catalog;
-//using Grand.Domain.Customers;
-//using Grand.Domain.Directory;
-//using Grand.Domain.Messages;
-//using Grand.Domain.Orders;
-
-//namespace Grand.Business.Core.Interfaces.System.ExportImport
-//{
-// /// <summary>
-// /// Export manager interface
-// /// </summary>
-// public partial interface IExportManager
-// {
-// /// <summary>
-// /// Export collections to XLSX
-// /// </summary>
-// /// <param name="collections">Brands</param>
-// byte[] ExportBrandsToXlsx(IEnumerable<Brand> brands);
-
-// /// <summary>
-// /// Export collections to XLSX
-// /// </summary>
-// /// <param name="collections">Collections</param>
-// byte[] ExportCollectionsToXlsx(IEnumerable<Collection> collections);
-
-
-// /// <summary>
-// /// Export category to XLSX
-// /// </summary>
-// /// <param name="categories">Categories</param>
-// byte[] ExportCategoriesToXlsx(IEnumerable<Category> categories);
-
-
-// /// <summary>
-// /// Export products to XLSX
-// /// </summary>
-// /// <param name="products">Products</param>
-// byte[] ExportProductsToXlsx(IEnumerable<Product> products);
-
-// /// <summary>
-// /// Export orders to XLSX
-// /// </summary>
-// /// <param name="orders">Orders</param>
-// byte[] ExportOrdersToXlsx(IList<Order> orders);
-
-// /// <summary>
-// /// Export customer list to XLSX
-// /// </summary>
-// /// <param name="customers">Customers</param>
-// byte[] ExportCustomersToXlsx(IList<Customer> customers);
-
-// /// <summary>
-// /// Export customer - personal info to XLSX
-// /// </summary>
-// /// <param name="customer">Customer</param>
-// Task<byte[]> ExportCustomerToXlsx(Customer customer, string storeId);
-
-// /// <summary>
-// /// Export states to XLSX
-// /// </summary>
-// /// <param name="countries">Countries</param>
-// byte[] ExportStatesToXlsx(IList<Country> countries);
-
-// /// <summary>
-// /// Export newsletter subscribers to TXT
-// /// </summary>
-// /// <param name="subscriptions">Subscriptions</param>
-// /// <returns>Result in TXT (string) format</returns>
-// string ExportNewsletterSubscribersToTxt(IList<NewsLetterSubscription> subscriptions);
-
-// /// <summary>
-// /// Export newsletter subscribers to TXT
-// /// </summary>
-// /// <param name="subscriptions">Subscriptions</param>
-// /// <returns>Result in TXT (string) format</returns>
-// string ExportNewsletterSubscribersToTxt(IList<string> subscriptions);
-
-// }
-//}
diff --git a/src/Business/Grand.Business.Core/Interfaces/System/ExportImport/IImportManager.cs b/src/Business/Grand.Business.Core/Interfaces/System/ExportImport/IImportManager.cs
deleted file mode 100644
index 0c452aa85..000000000
--- a/src/Business/Grand.Business.Core/Interfaces/System/ExportImport/IImportManager.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-namespace Grand.Business.Core.Interfaces.System.ExportImport
-{
- /// <summary>
- /// Import manager interface
- /// </summary>
- public partial interface IImportManager
- {
- /// <summary>
- /// Import products from XLSX file
- /// </summary>
- /// <param name="stream">Stream</param>
- Task ImportProductsFromXlsx(Stream stream);
-
- /// <summary>
- /// Import newsletter subscribers from TXT file
- /// </summary>
- /// <param name="stream">Stream</param>
- /// <param name="currentStoreId">Current store ident</param>
- /// <returns>Number of imported subscribers</returns>
- Task<int> ImportNewsletterSubscribersFromTxt(Stream stream, string currentStoreId);
-
- /// <summary>
- /// Import country states from XLSX file
- /// </summary>
- /// <param name="stream">Stream</param>
- Task ImportCountryStatesFromXlsx(Stream stream);
-
- /// <summary>
- /// Import brand from XLSX file
- /// </summary>
- /// <param name="stream">Stream</param>
- Task ImportBrandFromXlsx(Stream stream);
-
- /// <summary>
- /// Import collections from XLSX file
- /// </summary>
- /// <param name="stream">Stream</param>
- Task ImportCollectionFromXlsx(Stream stream);
-
- /// <summary>
- /// Import categories from XLSX file
- /// </summary>
- /// <param name="stream">Stream</param>
- Task ImportCategoryFromXlsx(Stream stream);
- }
-}
diff --git a/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyByName.cs b/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyByName.cs
index 8af7bb7fa..d91ace582 100644
--- a/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyByName.cs
+++ b/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyByName.cs
@@ -39,84 +39,5 @@
/// </summary>
public object PropertyValue { get; set; }
- /// <summary>
- /// Converted property value to Int32
- /// </summary>
- public int IntValue {
- get {
- if (PropertyValue == null || !int.TryParse(PropertyValue.ToString(), out var rez))
- return default;
- return rez;
- }
- }
-
- /// <summary>
- /// Converted property value to bool
- /// </summary>
- public bool BooleanValue {
- get {
- if (PropertyValue == null || !bool.TryParse(PropertyValue.ToString(), out var rez))
- return default;
- return rez;
- }
- }
-
- /// <summary>
- /// Converted property value to string
- /// </summary>
- public string StringValue {
- get { return PropertyValue == null ? string.Empty : Convert.ToString(PropertyValue); }
- }
-
- /// <summary>
- /// Converted property value to double
- /// </summary>
- public double DecimalValue {
- get {
- if (PropertyValue == null || !double.TryParse(PropertyValue.ToString(), out var rez))
- return default;
- return rez;
- }
- }
-
- /// <summary>
- /// Converted property value to double?
- /// </summary>
- public double? DecimalValueNullable {
- get {
- if (PropertyValue == null || !double.TryParse(PropertyValue.ToString(), out var rez))
- return null;
- return rez;
- }
- }
-
- /// <summary>
- /// Converted property value to double
- /// </summary>
- public double DoubleValue {
- get {
- if (PropertyValue == null || !double.TryParse(PropertyValue.ToString(), out var rez))
- return default;
- return rez;
- }
- }
-
- /// <summary>
- /// Converted property value to DateTime?
- /// </summary>
- public DateTime? DateTimeNullable {
- get {
- if (PropertyValue != null && DateTime.TryParse(PropertyValue.ToString(), out DateTime date))
- return (DateTime?)date;
-
- return default;
- }
-
- }
-
- public override string ToString()
- {
- return PropertyName;
- }
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyHelperList.cs b/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyHelperList.cs
deleted file mode 100644
index 901f1678d..000000000
--- a/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyHelperList.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-namespace Grand.Business.Core.Utilities.ExportImport
-{
- public class PropertyHelperList<T>
- {
- private static T obj;
-
- public PropertyHelperList(T obj1)
- {
- ObjectList = new List<PropertyHelperList<T>>();
- obj = obj1;
- }
- public List<PropertyHelperList<T>> ObjectList { get; set; }
-
- private string PropertyName { get; set; }
- private object PropertyValue { get; set; }
-
- public PropertyHelperList(string propertyName, Func<T, object> func = null)
- {
- PropertyName = propertyName;
- PropertyValue = func(obj);
- }
-
- public List<PropertyList> ToList()
- {
- List<PropertyList> list = new List<PropertyList>();
- foreach (var item in ObjectList)
- {
- list.Add(new PropertyList(item.PropertyName, item.PropertyValue?.ToString()));
- }
-
- return list;
- }
-
- public class PropertyList
- {
- public PropertyList(string field, string value)
- {
- Field = field;
- Value = value;
- }
- public string Field { get; set; }
- public string Value { get; set; }
- }
- }
-}
diff --git a/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyManager.cs b/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyManager.cs
index f54ab3c67..26cbb80f6 100644
--- a/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyManager.cs
+++ b/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyManager.cs
@@ -28,60 +28,5 @@
}
}
- /// <summary>
- /// Curent object to acsess
- /// </summary>
- public T CurrentObject { get; set; }
-
- /// <summary>
- /// Return properti index
- /// </summary>
- /// <param name="propertyName">Property name</param>
- /// <returns></returns>
- public int GetIndex(string propertyName)
- {
- if (!_properties.ContainsKey(propertyName))
- return -1;
-
- return _properties[propertyName].PropertyOrderPosition;
- }
-
- /// <summary>
- /// Access object by property name
- /// </summary>
- /// <param name="propertyName">Property name</param>
- /// <returns>Property value</returns>
- public object this[string propertyName] {
- get {
- return _properties.ContainsKey(propertyName) && CurrentObject != null
- ? _properties[propertyName].GetProperty(CurrentObject)
- : null;
- }
- }
-
- /// <summary>
- /// Count of properties
- /// </summary>
- public int Count {
- get { return _properties.Count; }
- }
-
- /// <summary>
- /// Get property by name
- /// </summary>
- /// <param name="propertyName"></param>
- /// <returns></returns>
- public PropertyByName<T> GetProperty(string propertyName)
- {
- return _properties.ContainsKey(propertyName) ? _properties[propertyName] : null;
- }
-
-
- /// <summary>
- /// Get property array
- /// </summary>
- public PropertyByName<T>[] GetProperties {
- get { return _properties.Values.ToArray(); }
- }
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs
index 08bc8af4b..3e4fb34fd 100644
--- a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs
+++ b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs
@@ -8,6 +8,7 @@ using Grand.Domain.Data;
using Grand.Domain.Messages;
using Grand.SharedKernel.Extensions;
using MediatR;
+using Grand.SharedKernel;
namespace Grand.Business.Marketing.Services.Newsteletters
{
@@ -273,6 +274,116 @@ namespace Grand.Business.Marketing.Services.Newsteletters
}
return sb.ToString();
}
+
+ /// <summary>
+ /// Import newsletter subscribers from TXT file
+ /// </summary>
+ /// <param name="stream">Stream</param>
+ /// <param name="currentStoreId">Current store ident</param>
+ /// <returns>Number of imported subscribers</returns>
+ public virtual async Task<int> ImportNewsletterSubscribersFromTxt(Stream stream, string currentStoreId)
+ {
+ int count = 0;
+ using (var reader = new StreamReader(stream))
+ {
+ while (!reader.EndOfStream)
+ {
+ string line = reader.ReadLine();
+ if (string.IsNullOrWhiteSpace(line))
+ continue;
+ string[] tmp = line.Split(',');
+
+ var email = "";
+ bool isActive = true;
+ var categories = new List<string>();
+ bool iscategories = false;
+ string storeId = currentStoreId;
+ //parse
+ if (tmp.Length == 1)
+ {
+ //"email" only
+ email = tmp[0].Trim();
+ }
+ else if (tmp.Length == 2)
+ {
+ //"email" and "active" fields specified
+ email = tmp[0].Trim();
+ isActive = Boolean.Parse(tmp[1].Trim());
+ }
+ else if (tmp.Length == 3)
+ {
+ //"email" and "active" and "storeId" fields specified
+ email = tmp[0].Trim();
+ isActive = Boolean.Parse(tmp[1].Trim());
+ storeId = tmp[2].Trim();
+ }
+ else if (tmp.Length == 4)
+ {
+ //"email" and "active" and "storeId" and categories fields specified
+ email = tmp[0].Trim();
+ isActive = Boolean.Parse(tmp[1].Trim());
+ storeId = tmp[2].Trim();
+ try
+ {
+ var items = tmp[3].Trim().Split(';').ToList();
+ foreach (var item in items)
+ {
+ if (!string.IsNullOrEmpty(item))
+ {
+ categories.Add(item);
+ }
+ }
+ iscategories = true;
+ }
+ catch { };
+ }
+ else
+ throw new GrandException("Wrong file format");
+
+ //import
+ await ImportSubscription(email, storeId, isActive, iscategories, categories);
+
+ count++;
+ }
+ }
+
+ return count;
+ }
+
+ protected virtual async Task ImportSubscription(string email, string storeId, bool isActive, bool iscategories, List<string> categories)
+ {
+ var subscription = await GetNewsLetterSubscriptionByEmailAndStoreId(email, storeId);
+ if (subscription != null)
+ {
+ subscription.Email = email;
+ subscription.Active = isActive;
+ if (iscategories)
+ {
+ subscription.Categories.Clear();
+ foreach (var item in categories)
+ {
+ subscription.Categories.Add(item);
+ }
+ }
+ await UpdateNewsLetterSubscription(subscription);
+ }
+ else
+ {
+ subscription = new NewsLetterSubscription {
+ Active = isActive,
+ CreatedOnUtc = DateTime.UtcNow,
+ Email = email,
+ StoreId = storeId,
+ NewsLetterSubscriptionGuid = Guid.NewGuid()
+ };
+ foreach (var item in categories)
+ {
+ subscription.Categories.Add(item);
+ }
+ await InsertNewsLetterSubscription(subscription);
+ }
+ }
+
#endregion
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.System/Grand.Business.System.csproj b/src/Business/Grand.Business.System/Grand.Business.System.csproj
index 242a2b27a..8666c3f46 100644
--- a/src/Business/Grand.Business.System/Grand.Business.System.csproj
+++ b/src/Business/Grand.Business.System/Grand.Business.System.csproj
@@ -6,7 +6,4 @@
<ProjectReference Include="..\..\Core\Grand.SharedKernel\Grand.SharedKernel.csproj" />
<ProjectReference Include="..\Grand.Business.Core\Grand.Business.Core.csproj" />
</ItemGroup>
- <ItemGroup>
- <PackageReference Include="NPOI" Version="2.5.6" />
- </ItemGroup>
</Project>
diff --git a/src/Business/Grand.Business.System/Services/ExportImport/ImportManager.cs b/src/Business/Grand.Business.System/Services/ExportImport/ImportManager.cs
deleted file mode 100644
index 4a2288820..000000000
--- a/src/Business/Grand.Business.System/Services/ExportImport/ImportManager.cs
+++ /dev/null
@@ -1,1321 +0,0 @@
-using Grand.Business.Core.Interfaces.Catalog.Brands;
-using Grand.Business.Core.Interfaces.Catalog.Categories;
-using Grand.Business.Core.Interfaces.Catalog.Collections;
-using Grand.Business.Core.Interfaces.Catalog.Directory;
-using Grand.Business.Core.Interfaces.Catalog.Products;
-using Grand.Business.Core.Interfaces.Catalog.Tax;
-using Grand.Business.Core.Interfaces.Checkout.Shipping;
-using Grand.Business.Core.Extensions;
-using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Seo;
-using Grand.Business.Core.Interfaces.Common.Stores;
-using Grand.Business.Core.Interfaces.Customers;
-using Grand.Business.Core.Interfaces.Marketing.Newsletters;
-using Grand.Business.Core.Interfaces.Storage;
-using Grand.Business.Core.Interfaces.System.ExportImport;
-using Grand.Business.Core.Utilities.System;
-using Grand.Domain.Catalog;
-using Grand.Domain.Directory;
-using Grand.Domain.Media;
-using Grand.Domain.Messages;
-using Grand.Domain.Seo;
-using Grand.Domain.Shipping;
-using Grand.Domain.Stores;
-using Grand.Domain.Tax;
-using Grand.SharedKernel;
-using Microsoft.AspNetCore.StaticFiles;
-using NPOI.XSSF.UserModel;
-using Grand.Business.System.Utilities.System;
-
-namespace Grand.Business.System.Services.ExportImport
-{
- /// <summary>
- /// Import manager
- /// </summary>
- public partial class ImportManager : IImportManager
- {
- #region Fields
-
- private readonly IProductService _productService;
- private readonly ICategoryService _categoryService;
- private readonly IProductCategoryService _productCategoryService;
- private readonly IBrandService _brandService;
- private readonly ICollectionService _collectionService;
- private readonly IProductCollectionService _productCollectionService;
- private readonly IPictureService _pictureService;
- private readonly ISlugService _slugService;
- private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
- private readonly INewsletterCategoryService _newsletterCategoryService;
- private readonly ICountryService _countryService;
- private readonly IVendorService _vendorService;
- private readonly ICategoryLayoutService _categoryLayoutService;
- private readonly ICollectionLayoutService _collectionLayoutService;
- private readonly IBrandLayoutService _brandLayoutService;
- private readonly IProductLayoutService _productLayoutService;
- private readonly IDownloadService _downloadService;
- private readonly IWarehouseService _warehouseService;
- private readonly IDeliveryDateService _deliveryDateService;
- private readonly ITaxCategoryService _taxService;
- private readonly IMeasureService _measureService;
- private readonly ILanguageService _languageService;
- private readonly IStoreService _storeService;
- private readonly SeoSettings _seoSetting;
-
- #endregion
-
- #region Ctor
-
- public ImportManager(IProductService productService,
- ICategoryService categoryService,
- IProductCategoryService productCategoryService,
- IBrandService brandService,
- ICollectionService collectionService,
- IProductCollectionService productCollectionService,
- IPictureService pictureService,
- ISlugService slugService,
- INewsLetterSubscriptionService newsLetterSubscriptionService,
- INewsletterCategoryService newsletterCategoryService,
- ICountryService countryService,
- IVendorService vendorService,
- ICategoryLayoutService categoryLayoutService,
- ICollectionLayoutService collectionLayoutService,
- IBrandLayoutService brandLayoutService,
- IProductLayoutService productLayoutService,
- IDownloadService downloadService,
- IWarehouseService warehouseService,
- IDeliveryDateService deliveryDateService,
- ITaxCategoryService taxService,
- IMeasureService measureService,
- ILanguageService languageService,
- IStoreService storeService,
- SeoSettings seoSetting)
- {
- _productService = productService;
- _categoryService = categoryService;
- _productCategoryService = productCategoryService;
- _brandService = brandService;
- _collectionService = collectionService;
- _productCollectionService = productCollectionService;
- _pictureService = pictureService;
- _slugService = slugService;
- _newsLetterSubscriptionService = newsLetterSubscriptionService;
- _newsletterCategoryService = newsletterCategoryService;
- _countryService = countryService;
- _vendorService = vendorService;
- _categoryLayoutService = categoryLayoutService;
- _collectionLayoutService = collectionLayoutService;
- _brandLayoutService = brandLayoutService;
- _productLayoutService = productLayoutService;
- _downloadService = downloadService;
- _warehouseService = warehouseService;
- _deliveryDateService = deliveryDateService;
- _taxService = taxService;
- _measureService = measureService;
- _languageService = languageService;
- _storeService = storeService;
- _seoSetting = seoSetting;
- }
-
- #endregion
-
- #region Utilities
-
- protected virtual PropertyManager<T> GetPropertyManager<T>(NPOI.SS.UserModel.ISheet worksheet)
- {
- var properties = new List<PropertyByName<T>>();
- var poz = 0;
- while (true)
- {
- try
- {
- var cell = worksheet.GetRow(0).Cells[poz];
-
- if (cell == null || string.IsNullOrEmpty(cell.StringCellValue))
- break;
-
- poz += 1;
- properties.Add(new PropertyByName<T>(cell.StringCellValue.ToLower()));
- }
- catch
- {
- break;
- }
- }
- return new PropertyManager<T>(properties.ToArray());
- }
-
- protected virtual void PrepareProductMapping(Product product, PropertyManager<Product> manager,
- IList<ProductLayout> layouts,
- IList<DeliveryDate> deliveryDates,
- IList<Warehouse> warehouses,
- IList<MeasureUnit> units,
- IList<TaxCategory> taxes,
- IList<Store> stores)
- {
-
- foreach (var property in manager.GetProperties)
- {
- switch (property.PropertyName.ToLower())
- {
- case "producttypeid":
- product.ProductTypeId = (ProductType)property.IntValue;
- break;
- case "parentgroupedproductid":
- var parentgroupedproductid = property.StringValue;
- if (_productService.GetProductById(parentgroupedproductid) != null)
- product.ParentGroupedProductId = property.StringValue;
- break;
- case "visibleindividually":
- product.VisibleIndividually = property.BooleanValue;
- break;
- case "name":
- product.Name = property.StringValue;
- break;
- case "shortdescription":
- product.ShortDescription = property.StringValue;
- break;
- case "fulldescription":
- product.FullDescription = property.StringValue;
- break;
- case "brandid":
- var brandid = property.StringValue;
- if (_brandService.GetBrandById(brandid) != null)
- product.BrandId = property.StringValue;
- break;
- case "vendorid":
- var vendorid = property.StringValue;
- if (_vendorService.GetVendorById(vendorid) != null)
- product.VendorId = property.StringValue;
- break;
- case "productlayoutid":
- var layoutid = property.StringValue;
- if (layouts.FirstOrDefault(x => x.Id == layoutid) != null)
- product.ProductLayoutId = property.StringValue;
- break;
- case "showonhomepage":
- product.ShowOnHomePage = property.BooleanValue;
- break;
- case "bestseller":
- product.BestSeller = property.BooleanValue;
- break;
- case "metakeywords":
- product.MetaKeywords = property.StringValue;
- break;
- case "metadescription":
- product.MetaDescription = property.StringValue;
- break;
- case "metatitle":
- product.MetaTitle = property.StringValue;
- break;
- case "allowcustomerreviews":
- product.AllowCustomerReviews = property.BooleanValue;
- break;
- case "published":
- product.Published = property.BooleanValue;
- break;
- case "sku":
- product.Sku = property.StringValue;
- break;
- case "mpn":
- product.Mpn = property.StringValue;
- break;
- case "gtin":
- product.Gtin = property.StringValue;
- break;
- case "isgiftvoucher":
- product.IsGiftVoucher = property.BooleanValue;
- break;
- case "giftvouchertypeid":
- product.GiftVoucherTypeId = (GiftVoucherType)property.IntValue;
- break;
- case "overriddengiftvoucheramount":
- product.OverGiftAmount = property.DecimalValue;
- break;
- case "requireotherproducts":
- product.RequireOtherProducts = property.BooleanValue;
- break;
- case "requiredproductids":
- product.RequiredProductIds = property.StringValue;
- break;
- case "automaticallyaddrequiredproducts":
- product.AutoAddRequiredProducts = property.BooleanValue;
- break;
- case "isdownload":
- product.IsDownload = property.BooleanValue;
- break;
- case "downloadid":
- var downloadid = property.StringValue;
- if (_downloadService.GetDownloadById(downloadid) != null)
- product.DownloadId = downloadid;
- break;
- case "unlimiteddownloads":
- product.UnlimitedDownloads = property.BooleanValue;
- break;
- case "maxnumberofdownloads":
- product.MaxNumberOfDownloads = property.IntValue;
- break;
- case "downloadactivationtypeid":
- product.DownloadActivationTypeId = (DownloadActivationType)property.IntValue;
- break;
- case "hassampledownload":
- product.HasSampleDownload = property.BooleanValue;
- break;
- case "sampledownloadid":
- var sampledownloadid = property.StringValue;
- if (_downloadService.GetDownloadById(sampledownloadid) != null)
- product.SampleDownloadId = property.StringValue;
- break;
- case "hasuseragreement":
- product.HasUserAgreement = property.BooleanValue;
- break;
- case "useragreementtext":
- product.UserAgreementText = property.StringValue;
- break;
- case "isrecurring":
- product.IsRecurring = property.BooleanValue;
- break;
- case "recurringcyclelength":
- product.RecurringCycleLength = property.IntValue;
- break;
- case "recurringcycleperiodid":
- product.RecurringCyclePeriodId = (RecurringCyclePeriod)property.IntValue;
- break;
- case "recurringtotalcycles":
- product.RecurringTotalCycles = property.IntValue;
- break;
- case "interval":
- product.Interval = property.IntValue;
- break;
- case "intervalunitId":
- product.IntervalUnitId = (IntervalUnit)property.IntValue;
- break;
- case "isshipenabled":
- product.IsShipEnabled = property.BooleanValue;
- break;
- case "isfreeshipping":
- product.IsFreeShipping = property.BooleanValue;
- break;
- case "shipseparately":
- product.ShipSeparately = property.BooleanValue;
- break;
- case "additionalshippingcharge":
- product.AdditionalShippingCharge = property.DecimalValue;
- break;
- case "deliverydateId":
- var deliverydateid = property.StringValue;
- if (deliveryDates.FirstOrDefault(x => x.Id == deliverydateid) != null)
- product.DeliveryDateId = deliverydateid;
- break;
- case "storeid":
- var storeid = property.StringValue;
- if (stores.FirstOrDefault(x => x.Id == storeid) != null)
- {
- if (!product.Stores.Contains(storeid))
- product.Stores.Add(storeid);
-
- product.LimitedToStores = product.Stores.Any();
- }
- break;
- case "istaxexempt":
- product.IsTaxExempt = property.BooleanValue;
- break;
- case "taxcategoryid":
- var taxcategoryid = property.StringValue;
- if (taxes.FirstOrDefault(x => x.Id == taxcategoryid) != null)
- product.TaxCategoryId = property.StringValue;
- break;
- case "istele":
- product.IsTele = property.BooleanValue;
- break;
- case "manageinventorymethodid":
- product.ManageInventoryMethodId = (ManageInventoryMethod)property.IntValue;
- break;
- case "usemultiplewarehouses":
- product.UseMultipleWarehouses = property.BooleanValue;
- break;
- case "warehouseid":
- var warehouseid = property.StringValue;
- if (warehouses.FirstOrDefault(x => x.Id == warehouseid) != null)
- product.WarehouseId = property.StringValue;
- break;
- case "stockquantity":
- product.StockQuantity = property.IntValue;
- break;
- case "reservedquantity":
- product.ReservedQuantity = property.IntValue;
- break;
- case "displaystockavailability":
- product.StockAvailability = property.BooleanValue;
- break;
- case "displaystockquantity":
- product.DisplayStockQuantity = property.BooleanValue;
- break;
- case "minstockquantity":
- product.MinStockQuantity = property.IntValue;
- break;
- case "lowstockactivityid":
- product.LowStockActivityId = (LowStockActivity)property.IntValue;
- break;
- case "notifyadminforquantitybelow":
- product.NotifyAdminForQuantityBelow = property.IntValue;
- break;
- case "admincomment":
- product.AdminComment = property.StringValue;
- break;
- case "flag":
- product.Flag = property.StringValue;
- break;
- case "backordermodeid":
- product.BackorderModeId = (BackorderMode)property.IntValue;
- break;
- case "allowoutofstocksubscriptions":
- product.AllowOutOfStockSubscriptions = property.BooleanValue;
- break;
- case "orderminimumquantity":
- product.OrderMinimumQuantity = property.IntValue;
- break;
- case "ordermaximumquantity":
- product.OrderMaximumQuantity = property.IntValue;
- break;
- case "allowedquantities":
- product.AllowedQuantities = property.StringValue;
- break;
- case "disablebuybutton":
- product.DisableBuyButton = property.BooleanValue;
- break;
- case "disablewishlistbutton":
- product.DisableWishlistButton = property.BooleanValue;
- break;
- case "availableforpreorder":
- product.AvailableForPreOrder = property.BooleanValue;
- break;
- case "preorderavailabilitystartdatetimeutc":
- product.PreOrderDateTimeUtc = property.DateTimeNullable;
- break;
- case "callforprice":
- product.CallForPrice = property.BooleanValue;
- break;
- case "price":
- product.Price = property.DecimalValue;
- break;
- case "oldprice":
- product.OldPrice = property.DecimalValue;
- break;
- case "catalogprice":
- product.CatalogPrice = property.DecimalValue;
- break;
- case "startprice":
- product.StartPrice = property.DecimalValue;
- break;
- case "productcost":
- product.ProductCost = property.DecimalValue;
- break;
- case "customerentersprice":
- product.EnteredPrice = property.BooleanValue;
- break;
- case "minimumcustomerenteredprice":
- product.MinEnteredPrice = property.DecimalValue;
- break;
- case "maximumcustomerenteredprice":
- product.MaxEnteredPrice = property.DecimalValue;
- break;
- case "basepriceenabled":
- product.BasepriceEnabled = property.BooleanValue;
- break;
- case "basepriceamount":
- product.BasepriceAmount = property.DecimalValue;
- break;
- case "basepriceunitid":
- product.BasepriceUnitId = property.StringValue;
- break;
- case "basepricebaseamount":
- product.BasepriceBaseAmount = property.DecimalValue;
- break;
- case "basepricebaseunitid":
- product.BasepriceBaseUnitId = property.StringValue;
- break;
- case "markasnew":
- product.MarkAsNew = property.BooleanValue;
- break;
- case "markasnewstartdatetimeutc":
- product.MarkAsNewStartDateTimeUtc = property.DateTimeNullable;
- break;
- case "markasnewenddatetimeutc":
- product.MarkAsNewEndDateTimeUtc = property.DateTimeNullable;
- break;
- case "unitid":
- var unitid = property.StringValue;
- if (units.FirstOrDefault(x => x.Id == unitid) != null)
- product.UnitId = property.StringValue;
- break;
- case "weight":
- product.Weight = property.DecimalValue;
- break;
- case "length":
- product.Length = property.DecimalValue;
- break;
- case "width":
- product.Width = property.DecimalValue;
- break;
- case "height":
- product.Height = property.DecimalValue;
- break;
- case "displayorder":
- product.DisplayOrder = property.IntValue;
- break;
- case "displayordercategory":
- product.DisplayOrderCategory = property.IntValue;
- break;
- case "displayorderbrand":
- product.DisplayOrderBrand = property.IntValue;
- break;
- case "displayordercollection":
- product.DisplayOrderCollection = property.IntValue;
- break;
- case "onsale":
- product.OnSale = property.IntValue;
- break;
- default:
- break;
- }
- }
- }
-
- protected virtual async Task PrepareProductCategories(Product product, string categoryIds)
- {
- foreach (var id in categoryIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()))
- {
- if (product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) == null)
- {
- //ensure that category exists
- var category = await _categoryService.GetCategoryById(id);
- if (category != null)
- {
- var productCategory = new ProductCategory {
- CategoryId = category.Id,
- IsFeaturedProduct = false,
- DisplayOrder = 1
- };
- await _productCategoryService.InsertProductCategory(productCategory, product.Id);
- }
- }
- }
- }
-
- protected virtual async Task PrepareProductCollections(Product product, string collectionIds)
- {
- foreach (var id in collectionIds.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()))
- {
- if (product.ProductCollections.FirstOrDefault(x => x.CollectionId == id) == null)
- {
- //ensure that collection exists
- var collection = await _collectionService.GetCollectionById(id);
- if (collection != null)
- {
- var productCollection = new ProductCollection {
- CollectionId = collection.Id,
- IsFeaturedProduct = false,
- DisplayOrder = 1
- };
- await _productCollectionService.InsertProductCollection(productCollection, product.Id);
- }
- }
- }
- }
-
- protected virtual async Task PrepareProductPictures(Product product, PropertyManager<Product> manager, bool isNew)
- {
- var picture1 = manager.GetProperty("picture1") != null ? manager.GetProperty("picture1").StringValue : string.Empty;
- var picture2 = manager.GetProperty("picture2") != null ? manager.GetProperty("picture2").StringValue : string.Empty;
- var picture3 = manager.GetProperty("picture3") != null ? manager.GetProperty("picture3").StringValue : string.Empty;
-
- foreach (var picturePath in new[] { picture1, picture2, picture3 })
- {
- if (String.IsNullOrEmpty(picturePath))
- continue;
- if (!picturePath.ToLower().StartsWith(("http".ToLower())))
- {
- var mimeType = GetMimeTypeFromFilePath(picturePath);
- var newPictureBinary = File.ReadAllBytes(picturePath);
- var pictureAlreadyExists = false;
- if (!isNew)
- {
- //compare with existing product pictures
- var existingPictures = product.ProductPictures;
- foreach (var existingPicture in existingPictures)
- {
- var pp = await _pictureService.GetPictureById(existingPicture.PictureId);
- var existingBinary = await _pictureService.LoadPictureBinary(pp);
- //picture binary after validation (like in database)
- var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
- if (existingBinary.SequenceEqual(validatedPictureBinary) || existingBinary.SequenceEqual(newPictureBinary))
- {
- //the same picture content
- pictureAlreadyExists = true;
- break;
- }
- }
- }
-
- if (!pictureAlreadyExists)
- {
- var picture = await _pictureService.InsertPicture(newPictureBinary, mimeType, _pictureService.GetPictureSeName(product.Name), "", "", false,
- Domain.Common.Reference.Product, product.Id);
- var productPicture = new ProductPicture {
- PictureId = picture.Id,
- DisplayOrder = 1,
- };
- await _productService.InsertProductPicture(productPicture, product.Id);
- }
- }
- else
- {
- byte[] fileBinary = await DownloadUrl.DownloadFile(picturePath);
- if (fileBinary != null)
- {
- var mimeType = GetMimeTypeFromFilePath(picturePath);
- var picture = await _pictureService.InsertPicture(fileBinary, mimeType, _pictureService.GetPictureSeName(product.Name), "", "", false, Domain.Common.Reference.Product, product.Id);
- var productPicture = new ProductPicture {
- PictureId = picture.Id,
- DisplayOrder = 1,
- };
- await _productService.InsertProductPicture(productPicture, product.Id);
- }
- }
- }
-
- }
-
- protected virtual void PrepareCategoryMapping(Category category, PropertyManager<Category> manager, IList<CategoryLayout> layouts)
- {
- foreach (var property in manager.GetProperties)
- {
- switch (property.PropertyName.ToLower())
- {
- case "name":
- category.Name = property.StringValue;
- break;
- case "description":
- category.Description = property.StringValue;
- break;
- case "CategoryLayoutId":
- var CategoryLayoutId = property.StringValue;
- if (layouts.FirstOrDefault(x => x.Id == CategoryLayoutId) != null)
- category.CategoryLayoutId = property.StringValue;
- break;
- case "metakeywords":
- category.MetaKeywords = property.StringValue;
- break;
- case "metadescription":
- category.MetaDescription = property.StringValue;
- break;
- case "metatitle":
- category.MetaTitle = property.StringValue;
- break;
- case "pagesize":
- category.PageSize = property.IntValue > 0 ? property.IntValue : 10;
- break;
- case "allowcustomerstoselectpageSize":
- category.AllowCustomersToSelectPageSize = property.BooleanValue;
- break;
- case "pagesizeoptions":
- category.PageSizeOptions = property.StringValue;
- break;
- case "published":
- category.Published = property.BooleanValue;
- break;
- case "displayorder":
- category.DisplayOrder = property.IntValue;
- break;
- case "showonhomepage":
- category.ShowOnHomePage = property.BooleanValue;
- break;
- case "includeinmenu":
- category.IncludeInMenu = property.BooleanValue;
- break;
- case "showonsearchbox":
- category.ShowOnSearchBox = property.BooleanValue;
- break;
- case "searchboxdisplayorder":
- category.SearchBoxDisplayOrder = property.IntValue;
- break;
- case "externalid":
- category.ExternalId = property.StringValue;
- break;
- case "flag":
- category.Flag = property.StringValue;
- break;
- case "flagstyle":
- category.FlagStyle = property.StringValue;
- break;
- case "icon":
- category.Icon = property.StringValue;
- break;
- case "parentcategoryid":
- if (!string.IsNullOrEmpty(property.StringValue) && property.StringValue != "0")
- category.ParentCategoryId = property.StringValue;
- break;
- default:
- break;
- }
- }
- }
-
- protected virtual void PrepareBrandMapping(Brand brand, PropertyManager<Brand> manager, IList<BrandLayout> layouts)
- {
- foreach (var property in manager.GetProperties)
- {
- switch (property.PropertyName.ToLower())
- {
- case "name":
- brand.Name = property.StringValue;
- break;
- case "description":
- brand.Description = property.StringValue;
- break;
- case "brandlayoutid":
- var brandLayoutId = property.StringValue;
- if (layouts.FirstOrDefault(x => x.Id == brandLayoutId) != null)
- brand.BrandLayoutId = property.StringValue;
- break;
- case "metakeywords":
- brand.MetaKeywords = property.StringValue;
- break;
- case "metadescription":
- brand.MetaDescription = property.StringValue;
- break;
- case "metatitle":
- brand.MetaTitle = property.StringValue;
- break;
- case "pagesize":
- brand.PageSize = property.IntValue > 0 ? property.IntValue : 10;
- break;
- case "allowcustomerstoselectpageSize":
- brand.AllowCustomersToSelectPageSize = property.BooleanValue;
- break;
- case "pagesizeoptions":
- brand.PageSizeOptions = property.StringValue;
- break;
- case "published":
- brand.Published = property.BooleanValue;
- break;
- case "showonhomepage":
- brand.ShowOnHomePage = property.BooleanValue;
- break;
- case "includeinmenu":
- brand.IncludeInMenu = property.BooleanValue;
- break;
- case "displayorder":
- brand.DisplayOrder = property.IntValue;
- break;
- case "externalid":
- brand.ExternalId = property.StringValue;
- break;
- default:
- break;
- }
- }
- }
-
- protected virtual void PrepareCollectionMapping(Collection collection, PropertyManager<Collection> manager, IList<CollectionLayout> layouts)
- {
- foreach (var property in manager.GetProperties)
- {
- switch (property.PropertyName.ToLower())
- {
- case "name":
- collection.Name = property.StringValue;
- break;
- case "description":
- collection.Description = property.StringValue;
- break;
- case "CollectionLayoutId":
- var collectionLayoutId = property.StringValue;
- if (layouts.FirstOrDefault(x => x.Id == collectionLayoutId) != null)
- collection.CollectionLayoutId = property.StringValue;
- break;
- case "metakeywords":
- collection.MetaKeywords = property.StringValue;
- break;
- case "metadescription":
- collection.MetaDescription = property.StringValue;
- break;
- case "metatitle":
- collection.MetaTitle = property.StringValue;
- break;
- case "pagesize":
- collection.PageSize = property.IntValue > 0 ? property.IntValue : 10;
- break;
- case "allowcustomerstoselectpageSize":
- collection.AllowCustomersToSelectPageSize = property.BooleanValue;
- break;
- case "pagesizeoptions":
- collection.PageSizeOptions = property.StringValue;
- break;
- case "published":
- collection.Published = property.BooleanValue;
- break;
- case "showonhomepage":
- collection.ShowOnHomePage = property.BooleanValue;
- break;
- case "includeinmenu":
- collection.IncludeInMenu = property.BooleanValue;
- break;
- case "displayorder":
- collection.DisplayOrder = property.IntValue;
- break;
- case "externalid":
- collection.ExternalId = property.StringValue;
- break;
- default:
- break;
- }
- }
- }
-
- protected virtual async Task ImportSubscription(string email, string storeId, bool isActive, bool iscategories, List<string> categories)
- {
- var subscription = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(email, storeId);
- if (subscription != null)
- {
- subscription.Email = email;
- subscription.Active = isActive;
- if (iscategories)
- {
- subscription.Categories.Clear();
- foreach (var item in categories)
- {
- subscription.Categories.Add(item);
- }
- }
- await _newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscription);
- }
- else
- {
- subscription = new NewsLetterSubscription {
- Active = isActive,
- CreatedOnUtc = DateTime.UtcNow,
- Email = email,
- StoreId = storeId,
- NewsLetterSubscriptionGuid = Guid.NewGuid()
- };
- foreach (var item in categories)
- {
- subscription.Categories.Add(item);
- }
- await _newsLetterSubscriptionService.InsertNewsLetterSubscription(subscription);
- }
- }
- protected virtual string GetMimeTypeFromFilePath(string filePath)
- {
- new FileExtensionContentTypeProvider().TryGetContentType(filePath, out string mimeType);
- //set to jpeg in case mime type cannot be found
- if (mimeType == null)
- mimeType = "image/jpeg";
- return mimeType;
- }
-
- /// <summary>
- /// Creates or loads the image
- /// </summary>
- /// <param name="picturePath">The path to the image file</param>
- /// <param name="name">The name of the object</param>
- /// <param name="picId">Image identifier, may be null</param>
- /// <returns>The image or null if the image has not changed</returns>
- protected virtual async Task<Picture> LoadPicture(string picturePath, string name, string picId = "")
- {
- if (String.IsNullOrEmpty(picturePath) || !File.Exists(picturePath))
- return null;
-
- var mimeType = GetMimeTypeFromFilePath(picturePath);
- var newPictureBinary = File.ReadAllBytes(picturePath);
- var pictureAlreadyExists = false;
- if (!String.IsNullOrEmpty(picId))
- {
- //compare with existing product pictures
- var existingPicture = await _pictureService.GetPictureById(picId);
-
- var existingBinary = await _pictureService.LoadPictureBinary(existingPicture);
- //picture binary after validation (like in database)
- var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
- if (existingBinary.SequenceEqual(validatedPictureBinary) ||
- existingBinary.SequenceEqual(newPictureBinary))
- {
- pictureAlreadyExists = true;
- }
- }
-
- if (pictureAlreadyExists) return null;
-
- var newPicture = await _pictureService.InsertPicture(newPictureBinary, mimeType,
- _pictureService.GetPictureSeName(name));
- return newPicture;
- }
-
- protected virtual bool ValidProduct(Product product)
- {
- if (string.IsNullOrEmpty(product.Name))
- return false;
-
- return true;
- }
- protected virtual bool ValidCategory(Category category)
- {
- if (string.IsNullOrEmpty(category.Name))
- return false;
-
- return true;
- }
-
- protected virtual bool ValidBrand(Brand brand)
- {
- if (string.IsNullOrEmpty(brand.Name))
- return false;
-
- return true;
- }
- protected virtual bool ValidCollection(Collection collection)
- {
- if (string.IsNullOrEmpty(collection.Name))
- return false;
-
- return true;
- }
-
-
- #endregion
-
- #region Methods
-
- /// <summary>
- /// Import products from XLSX file
- /// </summary>
- /// <param name="stream">Stream</param>
- public virtual async Task ImportProductsFromXlsx(Stream stream)
- {
- var workbook = new XSSFWorkbook(stream);
- var worksheet = workbook.GetSheetAt(0);
- if (worksheet == null)
- throw new GrandException("No worksheet found");
-
- var manager = GetPropertyManager<Product>(worksheet);
-
- var layouts = await _productLayoutService.GetAllProductLayouts();
- var deliveryDates = await _deliveryDateService.GetAllDeliveryDates();
- var taxes = await _taxService.GetAllTaxCategories();
- var warehouses = await _warehouseService.GetAllWarehouses();
- var units = await _measureService.GetAllMeasureUnits();
- var stores = await _storeService.GetAllStores();
- for (var iRow = 1; iRow < worksheet.PhysicalNumberOfRows; iRow++)
- {
-
- manager.ReadFromXlsx(worksheet, iRow);
- var sku = manager.GetProperty("sku") != null ? manager.GetProperty("sku").StringValue : string.Empty;
- var productid = manager.GetProperty("id") != null ? manager.GetProperty("id").StringValue : string.Empty;
-
- Product product = null;
-
- if (!string.IsNullOrEmpty(sku))
- product = await _productService.GetProductBySku(sku);
-
- if (!string.IsNullOrEmpty(productid))
- product = await _productService.GetProductById(productid);
-
- var isNew = product == null;
-
- product ??= new Product();
-
- if (isNew)
- {
- product.CreatedOnUtc = DateTime.UtcNow;
- product.ProductLayoutId = layouts.FirstOrDefault()?.Id;
- product.DeliveryDateId = deliveryDates.FirstOrDefault()?.Id;
- product.TaxCategoryId = taxes.FirstOrDefault()?.Id;
- product.WarehouseId = warehouses.FirstOrDefault()?.Id;
- product.UnitId = units.FirstOrDefault().Id;
- if (!string.IsNullOrEmpty(productid))
- product.Id = productid;
- }
-
- PrepareProductMapping(product, manager, layouts, deliveryDates, warehouses, units, taxes, stores);
-
- if (isNew && manager.GetProperties.All(p => p.PropertyName.ToLower() != "producttypeid"))
- product.ProductTypeId = ProductType.SimpleProduct;
-
- product.LowStock = product.MinStockQuantity > 0 && product.MinStockQuantity >= product.StockQuantity;
-
- product.UpdatedOnUtc = DateTime.UtcNow;
-
- if (!ValidProduct(product))
- continue;
-
- if (isNew)
- {
- await _productService.InsertProduct(product);
- }
- else
- {
- await _productService.UpdateProduct(product);
- }
-
- //search engine name
- var seName = manager.GetProperty("sename") != null ? manager.GetProperty("sename").StringValue : product.Name;
- await _slugService.SaveSlug(product, await product.ValidateSeName(seName, product.Name, true, _seoSetting, _slugService, _languageService), "");
- var _seName = await product.ValidateSeName(seName, product.Name, true, _seoSetting, _slugService, _languageService);
- //search engine name
- await _slugService.SaveSlug(product, _seName, "");
- product.SeName = _seName;
- await _productService.UpdateProduct(product);
-
- //category mappings
- var categoryIds = manager.GetProperty("categoryids") != null ? manager.GetProperty("categoryids").StringValue : string.Empty;
- if (!string.IsNullOrEmpty(categoryIds))
- {
- await PrepareProductCategories(product, categoryIds);
- }
-
- //collection mappings
- var collectionIds = manager.GetProperty("collectionids") != null ? manager.GetProperty("collectionids").StringValue : string.Empty;
- if (!string.IsNullOrEmpty(collectionIds))
- {
- await PrepareProductCollections(product, collectionIds);
- }
-
- //pictures
- await PrepareProductPictures(product, manager, isNew);
-
- }
-
- }
-
- /// <summary>
- /// Import newsletter subscribers from TXT file
- /// </summary>
- /// <param name="stream">Stream</param>
- /// <param name="currentStoreId">Current store ident</param>
- /// <returns>Number of imported subscribers</returns>
- public virtual async Task<int> ImportNewsletterSubscribersFromTxt(Stream stream, string currentStoreId)
- {
- int count = 0;
- using (var reader = new StreamReader(stream))
- {
- while (!reader.EndOfStream)
- {
- string line = reader.ReadLine();
- if (string.IsNullOrWhiteSpace(line))
- continue;
- string[] tmp = line.Split(',');
-
- var email = "";
- bool isActive = true;
- var categories = new List<string>();
- bool iscategories = false;
- string storeId = currentStoreId;
- //parse
- if (tmp.Length == 1)
- {
- //"email" only
- email = tmp[0].Trim();
- }
- else if (tmp.Length == 2)
- {
- //"email" and "active" fields specified
- email = tmp[0].Trim();
- isActive = Boolean.Parse(tmp[1].Trim());
- }
- else if (tmp.Length == 3)
- {
- //"email" and "active" and "storeId" fields specified
- email = tmp[0].Trim();
- isActive = Boolean.Parse(tmp[1].Trim());
- storeId = tmp[2].Trim();
- }
- else if (tmp.Length == 4)
- {
- //"email" and "active" and "storeId" and categories fields specified
- email = tmp[0].Trim();
- isActive = Boolean.Parse(tmp[1].Trim());
- storeId = tmp[2].Trim();
- try
- {
- var items = tmp[3].Trim().Split(';').ToList();
- foreach (var item in items)
- {
- if (!string.IsNullOrEmpty(item))
- {
- if (_newsletterCategoryService.GetNewsletterCategoryById(item) != null)
- categories.Add(item);
- }
- }
- iscategories = true;
- }
- catch { };
- }
- else
- throw new GrandException("Wrong file format");
-
- //import
- await ImportSubscription(email, storeId, isActive, iscategories, categories);
-
- count++;
- }
- }
-
- return count;
- }
-
- /// <summary>
- /// Import country states from XLSX file
- /// </summary>
- /// <param name="stream">Stream</param>
- public virtual async Task ImportCountryStatesFromXlsx(Stream stream)
- {
- var workbook = new XSSFWorkbook(stream);
- var worksheet = workbook.GetSheetAt(0);
- if (worksheet == null)
- throw new GrandException("No worksheet found");
-
- var manager = GetPropertyManager<(string Country, string Name, string Abbreviation, int DisplayOrder, bool Published)>(worksheet);
-
- for (var iRow = 1; iRow < worksheet.PhysicalNumberOfRows; iRow++)
- {
- manager.ReadFromXlsx(worksheet, iRow);
- var countryCode = manager.GetProperty("country") != null ? manager.GetProperty("country").StringValue : string.Empty;
- var country = string.IsNullOrEmpty(countryCode) ? null : await _countryService.GetCountryByTwoLetterIsoCode(countryCode);
-
- if (country == null)
- continue;
-
- //import
- var abbreviation = manager.GetProperty("abbreviation") != null ? manager.GetProperty("abbreviation").StringValue : string.Empty;
- if (string.IsNullOrEmpty(abbreviation))
- continue;
-
- var name = manager.GetProperty("name") != null ? manager.GetProperty("name").StringValue : string.Empty;
- if (string.IsNullOrEmpty(name))
- continue;
-
- var displayOrder = manager.GetProperty("displayorder") != null ? manager.GetProperty("displayorder").IntValue : 0;
- var published = manager.GetProperty("published") != null ? manager.GetProperty("published").BooleanValue : true;
-
- var states = country.StateProvinces.ToList();
- var state = states.FirstOrDefault(x => x.Abbreviation.Equals(abbreviation, StringComparison.OrdinalIgnoreCase));
-
- if (state != null)
- {
- state.Name = name;
- state.Abbreviation = abbreviation;
- state.Published = published;
- state.DisplayOrder = displayOrder;
- await _countryService.UpdateStateProvince(state, country.Id);
- }
- else
- {
- state = new StateProvince {
- Name = name,
- Abbreviation = abbreviation,
- Published = published,
- DisplayOrder = displayOrder,
- };
- await _countryService.InsertStateProvince(state, country.Id);
- }
-
- }
-
- }
-
- /// <summary>
- /// Import brands from XLSX file
- /// </summary>
- /// <param name="stream">Stream</param>
- public virtual async Task ImportBrandFromXlsx(Stream stream)
- {
- var workbook = new XSSFWorkbook(stream);
- var worksheet = workbook.GetSheetAt(0);
- if (worksheet == null)
- throw new GrandException("No worksheet found");
-
- var manager = GetPropertyManager<Brand>(worksheet);
-
- var layouts = await _brandLayoutService.GetAllBrandLayouts();
-
- for (var iRow = 1; iRow < worksheet.PhysicalNumberOfRows; iRow++)
- {
-
- manager.ReadFromXlsx(worksheet, iRow);
- var brandId = manager.GetProperty("id") != null ? manager.GetProperty("id").StringValue : string.Empty;
- var brand = string.IsNullOrEmpty(brandId) ? null : await _brandService.GetBrandById(brandId);
-
- var isNew = brand == null;
-
- brand ??= new Brand();
-
- if (isNew)
- {
- brand.CreatedOnUtc = DateTime.UtcNow;
- brand.BrandLayoutId = layouts.FirstOrDefault()?.Id;
- if (!string.IsNullOrEmpty(brandId))
- brand.Id = brandId;
- }
-
- PrepareBrandMapping(brand, manager, layouts);
-
- if (!ValidBrand(brand))
- continue;
-
- var picture = manager.GetProperty("picture") != null ? manager.GetProperty("sename").StringValue : "";
- if (!string.IsNullOrEmpty(picture))
- {
- var _picture = await LoadPicture(picture, brand.Name,
- isNew ? "" : brand.PictureId);
- if (_picture != null)
- brand.PictureId = _picture.Id;
- }
- brand.UpdatedOnUtc = DateTime.UtcNow;
-
- if (isNew)
- await _brandService.InsertBrand(brand);
- else
- await _brandService.UpdateBrand(brand);
-
- var sename = manager.GetProperty("sename") != null ? manager.GetProperty("sename").StringValue : brand.Name;
- sename = await brand.ValidateSeName(sename, brand.Name, true, _seoSetting, _slugService, _languageService);
- brand.SeName = sename;
- await _brandService.UpdateBrand(brand);
- await _slugService.SaveSlug(brand, brand.SeName, "");
-
- }
-
- }
- /// <summary>
- /// Import collections from XLSX file
- /// </summary>
- /// <param name="stream">Stream</param>
- public virtual async Task ImportCollectionFromXlsx(Stream stream)
- {
- var workbook = new XSSFWorkbook(stream);
- var worksheet = workbook.GetSheetAt(0);
- if (worksheet == null)
- throw new GrandException("No worksheet found");
-
- var manager = GetPropertyManager<Collection>(worksheet);
-
- var layouts = await _collectionLayoutService.GetAllCollectionLayouts();
-
- for (var iRow = 1; iRow < worksheet.PhysicalNumberOfRows; iRow++)
- {
-
- manager.ReadFromXlsx(worksheet, iRow);
- var collectionid = manager.GetProperty("id") != null ? manager.GetProperty("id").StringValue : string.Empty;
- var collection = string.IsNullOrEmpty(collectionid) ? null : await _collectionService.GetCollectionById(collectionid);
-
- var isNew = collection == null;
-
- collection ??= new Collection();
-
- if (isNew)
- {
- collection.CreatedOnUtc = DateTime.UtcNow;
- collection.CollectionLayoutId = layouts.FirstOrDefault()?.Id;
- if (!string.IsNullOrEmpty(collectionid))
- collection.Id = collectionid;
- }
-
- PrepareCollectionMapping(collection, manager, layouts);
-
-
- var picture = manager.GetProperty("picture") != null ? manager.GetProperty("sename").StringValue : "";
- if (!string.IsNullOrEmpty(picture))
- {
- var _picture = await LoadPicture(picture, collection.Name,
- isNew ? "" : collection.PictureId);
- if (_picture != null)
- collection.PictureId = _picture.Id;
- }
- collection.UpdatedOnUtc = DateTime.UtcNow;
-
- if (!ValidCollection(collection))
- continue;
-
- if (isNew)
- await _collectionService.InsertCollection(collection);
- else
- await _collectionService.UpdateCollection(collection);
-
- var sename = manager.GetProperty("sename") != null ? manager.GetProperty("sename").StringValue : collection.Name;
- sename = await collection.ValidateSeName(sename, collection.Name, true, _seoSetting, _slugService, _languageService);
- collection.SeName = sename;
- await _collectionService.UpdateCollection(collection);
- await _slugService.SaveSlug(collection, collection.SeName, "");
-
- }
-
- }
-
- /// <summary>
- /// Import categories from XLSX file
- /// </summary>
- /// <param name="stream">Stream</param>
- public virtual async Task ImportCategoryFromXlsx(Stream stream)
- {
- var workbook = new XSSFWorkbook(stream);
- var worksheet = workbook.GetSheetAt(0);
- if (worksheet == null)
- throw new GrandException("No worksheet found");
-
- var manager = GetPropertyManager<Category>(worksheet);
-
- var layouts = await _categoryLayoutService.GetAllCategoryLayouts();
-
- for (var iRow = 1; iRow < worksheet.PhysicalNumberOfRows; iRow++)
- {
- manager.ReadFromXlsx(worksheet, iRow);
-
- var categoryid = manager.GetProperty("id") != null ? manager.GetProperty("id").StringValue : string.Empty;
- var category = string.IsNullOrEmpty(categoryid) ? null : await _categoryService.GetCategoryById(categoryid);
-
- var isNew = category == null;
-
- category ??= new Category();
-
- if (isNew)
- {
- category.CreatedOnUtc = DateTime.UtcNow;
- category.CategoryLayoutId = layouts.FirstOrDefault()?.Id;
- if (!string.IsNullOrEmpty(categoryid))
- category.Id = categoryid;
- }
-
- PrepareCategoryMapping(category, manager, layouts);
- category.UpdatedOnUtc = DateTime.UtcNow;
-
- if (!ValidCategory(category))
- continue;
-
- if (isNew)
- await _categoryService.InsertCategory(category);
- else
- await _categoryService.UpdateCategory(category);
-
- var picture = manager.GetProperty("picture") != null ? manager.GetProperty("sename").StringValue : "";
- if (!string.IsNullOrEmpty(picture))
- {
- var _picture = await LoadPicture(picture, category.Name, isNew ? "" : category.PictureId);
- if (_picture != null)
- category.PictureId = _picture.Id;
- }
-
- var sename = manager.GetProperty("sename") != null ? manager.GetProperty("sename").StringValue : category.Name;
- sename = await category.ValidateSeName(sename, category.Name, true, _seoSetting, _slugService, _languageService);
- category.SeName = sename;
- await _categoryService.UpdateCategory(category);
- await _slugService.SaveSlug(category, sename, "");
-
- }
-
- }
-
- #endregion
- }
-}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.System/Startup/StartupApplication.cs b/src/Business/Grand.Business.System/Startup/StartupApplication.cs
index 862a8d862..2e3d6823e 100644
--- a/src/Business/Grand.Business.System/Startup/StartupApplication.cs
+++ b/src/Business/Grand.Business.System/Startup/StartupApplication.cs
@@ -1,12 +1,10 @@
using Grand.Business.Core.Interfaces.System.Admin;
-using Grand.Business.Core.Interfaces.System.ExportImport;
using Grand.Business.Core.Interfaces.System.Installation;
using Grand.Business.Core.Interfaces.System.MachineNameProvider;
using Grand.Business.Core.Interfaces.System.Reports;
using Grand.Business.Core.Interfaces.System.ScheduleTasks;
using Grand.Business.System.Services.Admin;
using Grand.Business.System.Services.BackgroundServices.ScheduleTasks;
-using Grand.Business.System.Services.ExportImport;
using Grand.Business.System.Services.Installation;
using Grand.Business.System.Services.MachineNameProvider;
using Grand.Business.System.Services.Migrations;
@@ -29,7 +27,6 @@ namespace Grand.Business.System.Startup
RegisterReports(services);
RegisterMachineNameProvider(services, configuration);
RegisterTask(services);
- RegisterExportImportService(services);
RegisterInstallService(services);
RegisterAdmin(services);
}
@@ -89,11 +86,6 @@ namespace Grand.Business.System.Startup
serviceCollection.AddScoped<IMigrationProcess, MigrationProcess>();
}
- private void RegisterExportImportService(IServiceCollection serviceCollection)
- {
- //serviceCollection.AddScoped<IExportManager, ExportManager>();
- serviceCollection.AddScoped<IImportManager, ImportManager>();
- }
private void RegisterAdmin(IServiceCollection serviceCollection)
{
serviceCollection.AddScoped<IAdminSiteMapService, AdminSiteMapService>();
diff --git a/src/Business/Grand.Business.System/Utilities/PropertyByName.cs b/src/Business/Grand.Business.System/Utilities/PropertyByName.cs
deleted file mode 100644
index 1cb58fb30..000000000
--- a/src/Business/Grand.Business.System/Utilities/PropertyByName.cs
+++ /dev/null
@@ -1,122 +0,0 @@
-namespace Grand.Business.System.Utilities.System
-{
- /// <summary>
- /// A helper class to access the property by name
- /// </summary>
- /// <typeparam name="T">Object type</typeparam>
- public class PropertyByName<T>
- {
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="propertyName">Property name</param>
- /// <param name="func">Feature property access</param>
- public PropertyByName(string propertyName, Func<T, object> func = null)
- {
- PropertyName = propertyName;
- GetProperty = func;
-
- PropertyOrderPosition = 0;
- }
-
- /// <summary>
- /// Property order position
- /// </summary>
- public int PropertyOrderPosition { get; set; }
-
- /// <summary>
- /// Feature property access
- /// </summary>
- public Func<T, object> GetProperty { get; private set; }
-
- /// <summary>
- /// Property name
- /// </summary>
- public string PropertyName { get; private set; }
-
- /// <summary>
- /// Property value
- /// </summary>
- public object PropertyValue { get; set; }
-
- /// <summary>
- /// Converted property value to Int32
- /// </summary>
- public int IntValue {
- get {
- if (PropertyValue == null || !int.TryParse(PropertyValue.ToString(), out var rez))
- return default;
- return rez;
- }
- }
-
- /// <summary>
- /// Converted property value to bool
- /// </summary>
- public bool BooleanValue {
- get {
- if (PropertyValue == null || !bool.TryParse(PropertyValue.ToString(), out var rez))
- return default;
- return rez;
- }
- }
-
- /// <summary>
- /// Converted property value to string
- /// </summary>
- public string StringValue {
- get { return PropertyValue == null ? string.Empty : Convert.ToString(PropertyValue); }
- }
-
- /// <summary>
- /// Converted property value to double
- /// </summary>
- public double DecimalValue {
- get {
- if (PropertyValue == null || !double.TryParse(PropertyValue.ToString(), out var rez))
- return default;
- return rez;
- }
- }
-
- /// <summary>
- /// Converted property value to double?
- /// </summary>
- public double? DecimalValueNullable {
- get {
- if (PropertyValue == null || !double.TryParse(PropertyValue.ToString(), out var rez))
- return null;
- return rez;
- }
- }
-
- /// <summary>
- /// Converted property value to double
- /// </summary>
- public double DoubleValue {
- get {
- if (PropertyValue == null || !double.TryParse(PropertyValue.ToString(), out var rez))
- return default;
- return rez;
- }
- }
-
- /// <summary>
- /// Converted property value to DateTime?
- /// </summary>
- public DateTime? DateTimeNullable {
- get {
- if (PropertyValue != null && DateTime.TryParse(PropertyValue.ToString(), out DateTime date))
- return (DateTime?)date;
-
- return default;
- }
-
- }
-
- public override string ToString()
- {
- return PropertyName;
- }
- }
-}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.System/Utilities/PropertyHelperList.cs b/src/Business/Grand.Business.System/Utilities/PropertyHelperList.cs
deleted file mode 100644
index ef77ad71c..000000000
--- a/src/Business/Grand.Business.System/Utilities/PropertyHelperList.cs
+++ /dev/null
@@ -1,59 +0,0 @@
-using NPOI.SS.UserModel;
-
-namespace Grand.Business.System.Utilities.System
-{
- public class PropertyHelperList<T>
- {
- private static T obj;
-
- public PropertyHelperList(T obj1)
- {
- ObjectList = new List<PropertyHelperList<T>>();
- obj = obj1;
- }
- public List<PropertyHelperList<T>> ObjectList { get; set; }
-
- private string PropertyName { get; set; }
- private object PropertyValue { get; set; }
-
- public PropertyHelperList(string propertyName, Func<T, object> func = null)
- {
- PropertyName = propertyName;
- PropertyValue = func(obj);
- }
-
- public List<PropertyList> ToList()
- {
- List<PropertyList> list = new List<PropertyList>();
- foreach (var item in ObjectList)
- {
- list.Add(new PropertyList(item.PropertyName, item.PropertyValue?.ToString()));
- }
-
- return list;
- }
-
- public class PropertyList
- {
- public PropertyList(string field, string value)
- {
- Field = field;
- Value = value;
- }
- public string Field { get; set; }
- public string Value { get; set; }
- }
-
- public void WriteToXlsx(ISheet sheet)
- {
- int row = 0;
- foreach (var prop in ToList())
- {
- IRow _row = sheet.CreateRow(row);
- _row.CreateCell(0).SetCellValue(prop.Field);
- _row.CreateCell(1).SetCellValue(prop.Value);
- row++;
- }
- }
- }
-}
diff --git a/src/Business/Grand.Business.System/Utilities/PropertyManager.cs b/src/Business/Grand.Business.System/Utilities/PropertyManager.cs
deleted file mode 100644
index bb2c2aae0..000000000
--- a/src/Business/Grand.Business.System/Utilities/PropertyManager.cs
+++ /dev/null
@@ -1,145 +0,0 @@
-using Grand.Business.Core.Utilities.ExportImport;
-using Grand.Business.Core.Utilities.System;
-using NPOI.SS.UserModel;
-
-namespace Grand.Business.System.Utilities.System
-{
- /// <summary>
- /// Class for working with PropertyByName object list
- /// </summary>
- /// <typeparam name="T">Object type</typeparam>
- public class PropertyManager<T>
- {
- /// <summary>
- /// All properties
- /// </summary>
- private readonly Dictionary<string, PropertyByName<T>> _properties;
-
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="properties">All acsess properties</param>
- public PropertyManager(PropertyByName<T>[] properties)
- {
- _properties = new Dictionary<string, PropertyByName<T>>();
-
- var poz = 0;
- foreach (var propertyByName in properties)
- {
- propertyByName.PropertyOrderPosition = poz;
- poz++;
- _properties.Add(propertyByName.PropertyName, propertyByName);
- }
- }
-
- /// <summary>
- /// Curent object to acsess
- /// </summary>
- public T CurrentObject { get; set; }
-
- /// <summary>
- /// Return properti index
- /// </summary>
- /// <param name="propertyName">Property name</param>
- /// <returns></returns>
- public int GetIndex(string propertyName)
- {
- if (!_properties.ContainsKey(propertyName))
- return -1;
-
- return _properties[propertyName].PropertyOrderPosition;
- }
-
- /// <summary>
- /// Access object by property name
- /// </summary>
- /// <param name="propertyName">Property name</param>
- /// <returns>Property value</returns>
- public object this[string propertyName] {
- get {
- return _properties.ContainsKey(propertyName) && CurrentObject != null
- ? _properties[propertyName].GetProperty(CurrentObject)
- : null;
- }
- }
-
- /// <summary>
- /// Write object data to XLSX worksheet
- /// </summary>
- /// <param name="worksheet">worksheet</param>
- /// <param name="row">Row index</param>
- public void WriteToXlsx(ISheet sheet, int row)
- {
- if (CurrentObject == null)
- return;
-
- IRow _row = sheet.CreateRow(row);
- foreach (var prop in _properties.Values)
- {
- var cellValue = (prop.GetProperty(CurrentObject)?.ToString());
- if(cellValue != null && cellValue.Length >= 32767) // 32767 is the max char size of an excel cell
- {
- cellValue = cellValue.Substring(0, 32767); //Truncate the content to max size.
- }
- _row.CreateCell(prop.PropertyOrderPosition).SetCellValue(cellValue);
- }
- }
-
- /// <summary>
- /// Read object data from XLSX worksheet
- /// </summary>
- /// <param name="ISheet">sheet</param>
- /// <param name="row">Row index</param>
- public void ReadFromXlsx(ISheet sheet, int row)
- {
- if (sheet == null)
- return;
-
-
- var _row = sheet.GetRow(row);
- foreach (var prop in _properties.Values)
- {
- var cell = _row.GetCell(prop.PropertyOrderPosition);
- prop.PropertyValue = cell?.ToString();
- }
- }
-
- /// <summary>
- /// Write caption (first row) to XLSX worksheet
- /// </summary>
- /// <param name="ISheet">sheet</param>
- public void WriteCaption(ISheet sheet)
- {
- IRow row = sheet.CreateRow(0);
- foreach (var caption in _properties.Values)
- {
- row.CreateCell(caption.PropertyOrderPosition).SetCellValue(caption.PropertyName);
- }
- }
-
- /// <summary>
- /// Count of properties
- /// </summary>
- public int Count {
- get { return _properties.Count; }
- }
-
- /// <summary>
- /// Get property by name
- /// </summary>
- /// <param name="propertyName"></param>
- /// <returns></returns>
- public PropertyByName<T> GetProperty(string propertyName)
- {
- return _properties.ContainsKey(propertyName) ? _properties[propertyName] : null;
- }
-
-
- /// <summary>
- /// Get property array
- /// </summary>
- public PropertyByName<T>[] GetProperties {
- get { return _properties.Values.ToArray(); }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Controllers/BrandController.cs b/src/Web/Grand.Web.Admin/Controllers/BrandController.cs
index 360f000a4..19707773d 100644
--- a/src/Web/Grand.Web.Admin/Controllers/BrandController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/BrandController.cs
@@ -1,10 +1,11 @@
-using Grand.Business.Core.Interfaces.Catalog.Brands;
+using Grand.Business.Catalog.Services.ExportImport.Dto;
using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Catalog.Brands;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Stores;
+using Grand.Business.Core.Interfaces.ExportImport;
using Grand.Business.Core.Utilities.Common.Security;
-using Grand.Business.Core.Interfaces.System.ExportImport;
using Grand.Domain.Catalog;
using Grand.Infrastructure;
using Grand.Web.Admin.Extensions;
@@ -17,7 +18,6 @@ using Grand.Web.Common.Security.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
-using Grand.Business.Core.Interfaces.ExportImport;
namespace Grand.Web.Admin.Controllers
{
@@ -33,7 +33,7 @@ namespace Grand.Web.Admin.Controllers
private readonly ITranslationService _translationService;
private readonly IGroupService _groupService;
private readonly IExportManager<Brand> _exportManager;
- private readonly IImportManager _importManager;
+ private readonly IImportManager<BrandDto> _importManager;
private readonly IPictureViewModelService _pictureViewModelService;
#endregion
@@ -48,7 +48,7 @@ namespace Grand.Web.Admin.Controllers
ITranslationService translationService,
IGroupService groupService,
IExportManager<Brand> exportManager,
- IImportManager importManager,
+ IImportManager<BrandDto> importManager,
IPictureViewModelService pictureViewModelService)
{
_brandViewModelService = brandViewModelService;
@@ -362,7 +362,7 @@ namespace Grand.Web.Admin.Controllers
{
if (importexcelfile != null && importexcelfile.Length > 0)
{
- await _importManager.ImportBrandFromXlsx(importexcelfile.OpenReadStream());
+ await _importManager.Import(importexcelfile.OpenReadStream());
}
else
{
diff --git a/src/Web/Grand.Web.Admin/Controllers/CategoryController.cs b/src/Web/Grand.Web.Admin/Controllers/CategoryController.cs
index 1bb300c10..abb32a034 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CategoryController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CategoryController.cs
@@ -1,11 +1,10 @@
-using Grand.Business.Core.Interfaces.Catalog.Categories;
+using Grand.Business.Catalog.Services.ExportImport.Dto;
using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Catalog.Categories;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Stores;
+using Grand.Business.Core.Interfaces.ExportImport;
using Grand.Business.Core.Utilities.Common.Security;
-using Grand.Business.Core.Interfaces.Customers;
-using Grand.Business.Core.Interfaces.System.ExportImport;
using Grand.Domain.Catalog;
using Grand.Infrastructure;
using Grand.Web.Admin.Extensions;
@@ -17,7 +16,6 @@ using Grand.Web.Common.Filters;
using Grand.Web.Common.Security.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Grand.Business.Core.Interfaces.ExportImport;
namespace Grand.Web.Admin.Controllers
{
@@ -28,14 +26,12 @@ namespace Grand.Web.Admin.Controllers
private readonly ICategoryService _categoryService;
private readonly ICategoryViewModelService _categoryViewModelService;
- private readonly ICustomerService _customerService;
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
- private readonly IStoreService _storeService;
private readonly IExportManager<Category> _exportManager;
+ private readonly IImportManager<CategoryDto> _importManager;
private readonly IWorkContext _workContext;
private readonly IGroupService _groupService;
- private readonly IImportManager _importManager;
private readonly IPictureViewModelService _pictureViewModelService;
#endregion
@@ -44,22 +40,18 @@ namespace Grand.Web.Admin.Controllers
public CategoryController(
ICategoryService categoryService,
ICategoryViewModelService categoryViewModelService,
- ICustomerService customerService,
ILanguageService languageService,
ITranslationService translationService,
- IStoreService storeService,
IExportManager<Category> exportManager,
+ IImportManager<CategoryDto> importManager,
IWorkContext workContext,
IGroupService groupService,
- IImportManager importManager,
IPictureViewModelService pictureViewModelService)
{
_categoryService = categoryService;
_categoryViewModelService = categoryViewModelService;
- _customerService = customerService;
_languageService = languageService;
_translationService = translationService;
- _storeService = storeService;
_exportManager = exportManager;
_workContext = workContext;
_groupService = groupService;
@@ -107,8 +99,7 @@ namespace Grand.Web.Admin.Controllers
}
var categories = await _categoryViewModelService.PrepareCategoryListModel(model, command.Page, command.PageSize);
- var gridModel = new DataSourceResult
- {
+ var gridModel = new DataSourceResult {
Data = categories.categoryListModel,
Total = categories.totalCount
};
@@ -332,7 +323,7 @@ namespace Grand.Web.Admin.Controllers
{
if (importexcelfile != null && importexcelfile.Length > 0)
{
- await _importManager.ImportCategoryFromXlsx(importexcelfile.OpenReadStream());
+ await _importManager.Import(importexcelfile.OpenReadStream());
}
else
{
@@ -362,8 +353,7 @@ namespace Grand.Web.Admin.Controllers
return ErrorForKendoGridJson(permission.message);
var productCategories = await _categoryViewModelService.PrepareCategoryProductModel(categoryId, command.Page, command.PageSize);
- var gridModel = new DataSourceResult
- {
+ var gridModel = new DataSourceResult {
Data = productCategories.categoryProductModels,
Total = productCategories.totalCount
};
@@ -436,7 +426,7 @@ namespace Grand.Web.Admin.Controllers
return View(model);
}
-
+
}
#endregion
@@ -454,8 +444,7 @@ namespace Grand.Web.Admin.Controllers
return ErrorForKendoGridJson(permission.message);
var activityLog = await _categoryViewModelService.PrepareActivityLogModel(categoryId, command.Page, command.PageSize);
- var gridModel = new DataSourceResult
- {
+ var gridModel = new DataSourceResult {
Data = activityLog.activityLogModel,
Total = activityLog.totalCount
};
diff --git a/src/Web/Grand.Web.Admin/Controllers/CollectionController.cs b/src/Web/Grand.Web.Admin/Controllers/CollectionController.cs
index b2aaa2008..8a81dd5e3 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CollectionController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CollectionController.cs
@@ -1,10 +1,11 @@
-using Grand.Business.Core.Interfaces.Catalog.Collections;
+using Grand.Business.Catalog.Services.ExportImport.Dto;
using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Catalog.Collections;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Stores;
+using Grand.Business.Core.Interfaces.ExportImport;
using Grand.Business.Core.Utilities.Common.Security;
-using Grand.Business.Core.Interfaces.System.ExportImport;
using Grand.Domain.Catalog;
using Grand.Infrastructure;
using Grand.Web.Admin.Extensions;
@@ -17,7 +18,6 @@ using Grand.Web.Common.Security.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
-using Grand.Business.Core.Interfaces.ExportImport;
namespace Grand.Web.Admin.Controllers
{
@@ -34,7 +34,7 @@ namespace Grand.Web.Admin.Controllers
private readonly ITranslationService _translationService;
private readonly IGroupService _groupService;
private readonly IExportManager<Collection> _exportManager;
- private readonly IImportManager _importManager;
+ private readonly IImportManager<CollectionDto> _importManager;
private readonly IPictureViewModelService _pictureViewModelService;
#endregion
@@ -50,7 +50,7 @@ namespace Grand.Web.Admin.Controllers
ITranslationService translationService,
IGroupService groupService,
IExportManager<Collection> exportManager,
- IImportManager importManager,
+ IImportManager<CollectionDto> importManager,
IPictureViewModelService pictureViewModelService)
{
_collectionViewModelService = collectionViewModelService;
@@ -110,8 +110,7 @@ namespace Grand.Web.Admin.Controllers
}
var collections = await _collectionService.GetAllCollections(model.SearchCollectionName,
model.SearchStoreId, command.Page - 1, command.PageSize, true);
- var gridModel = new DataSourceResult
- {
+ var gridModel = new DataSourceResult {
Data = collections.Select(x => x.ToModel()),
Total = collections.TotalCount
};
@@ -365,7 +364,7 @@ namespace Grand.Web.Admin.Controllers
{
if (importexcelfile != null && importexcelfile.Length > 0)
{
- await _importManager.ImportCollectionFromXlsx(importexcelfile.OpenReadStream());
+ await _importManager.Import(importexcelfile.OpenReadStream());
}
else
{
@@ -396,8 +395,7 @@ namespace Grand.Web.Admin.Controllers
var (collectionProductModels, totalCount) = await _collectionViewModelService.PrepareCollectionProductModel(collectionId, _workContext.CurrentStore.Id, command.Page, command.PageSize);
- var gridModel = new DataSourceResult
- {
+ var gridModel = new DataSourceResult {
Data = collectionProductModels.ToList(),
Total = totalCount
};
@@ -446,8 +444,7 @@ namespace Grand.Web.Admin.Controllers
model.SearchStoreId = _workContext.CurrentCustomer.StaffStoreId;
}
var products = await _collectionViewModelService.PrepareProductModel(model, command.Page, command.PageSize);
- var gridModel = new DataSourceResult
- {
+ var gridModel = new DataSourceResult {
Data = products.products.ToList(),
Total = products.totalCount
};
@@ -488,8 +485,7 @@ namespace Grand.Web.Admin.Controllers
return ErrorForKendoGridJson(permission.message);
var (activityLogModels, totalCount) = await _collectionViewModelService.PrepareActivityLogModel(collectionId, command.Page, command.PageSize);
- var gridModel = new DataSourceResult
- {
+ var gridModel = new DataSourceResult {
Data = activityLogModels.ToList(),
Total = totalCount
};
diff --git a/src/Web/Grand.Web.Admin/Controllers/CountryController.cs b/src/Web/Grand.Web.Admin/Controllers/CountryController.cs
index fd74606d3..1b422439c 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CountryController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CountryController.cs
@@ -3,7 +3,6 @@ using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.ExportImport;
-using Grand.Business.Core.Interfaces.System.ExportImport;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Interfaces;
@@ -27,7 +26,7 @@ namespace Grand.Web.Admin.Controllers
private readonly ITranslationService _translationService;
private readonly ILanguageService _languageService;
private readonly IExportManager<CountryStates> _exportManager;
- private readonly IImportManager _importManager;
+ private readonly IImportManager<CountryStates> _importManager;
#endregion
@@ -38,7 +37,7 @@ namespace Grand.Web.Admin.Controllers
ITranslationService translationService,
ILanguageService languageService,
IExportManager<CountryStates> exportManager,
- IImportManager importManager)
+ IImportManager<CountryStates> importManager)
{
_countryService = countryService;
_countryViewModelService = countryViewModelService;
@@ -344,7 +343,7 @@ namespace Grand.Web.Admin.Controllers
var query = from p in countries
from s in p.StateProvinces
select new CountryStates() {
- TwoLetterIsoCode = p.TwoLetterIsoCode,
+ Country = p.TwoLetterIsoCode,
StateProvinceName = s.Name,
Abbreviation = s.Abbreviation,
DisplayOrder = s.DisplayOrder,
@@ -363,7 +362,7 @@ namespace Grand.Web.Admin.Controllers
{
if (importexcelfile != null && importexcelfile.Length > 0)
{
- await _importManager.ImportCountryStatesFromXlsx(importexcelfile.OpenReadStream());
+ await _importManager.Import(importexcelfile.OpenReadStream());
Success(_translationService.GetResource("Admin.Configuration.Countries.ImportSuccess"));
return RedirectToAction("List");
diff --git a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs b/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
index 982698bcb..64d3fa05d 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
@@ -9,7 +9,6 @@ using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Utilities.Customers;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Interfaces.Storage;
-using Grand.Business.Core.Interfaces.System.ExportImport;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Customers;
diff --git a/src/Web/Grand.Web.Admin/Controllers/NewsLetterSubscriptionController.cs b/src/Web/Grand.Web.Admin/Controllers/NewsLetterSubscriptionController.cs
index 0d8311228..9d3f92a1a 100644
--- a/src/Web/Grand.Web.Admin/Controllers/NewsLetterSubscriptionController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/NewsLetterSubscriptionController.cs
@@ -2,7 +2,6 @@
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Interfaces.Marketing.Newsletters;
-using Grand.Business.Core.Interfaces.System.ExportImport;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Infrastructure;
using Grand.SharedKernel.Extensions;
@@ -26,7 +25,6 @@ namespace Grand.Web.Admin.Controllers
private readonly ITranslationService _translationService;
private readonly IStoreService _storeService;
private readonly IGroupService _groupService;
- private readonly IImportManager _importManager;
private readonly IWorkContext _workContext;
public NewsLetterSubscriptionController(INewsLetterSubscriptionService newsLetterSubscriptionService,
@@ -35,7 +33,6 @@ namespace Grand.Web.Admin.Controllers
ITranslationService translationService,
IStoreService storeService,
IGroupService groupService,
- IImportManager importManager,
IWorkContext workContext)
{
_newsLetterSubscriptionService = newsLetterSubscriptionService;
@@ -44,7 +41,6 @@ namespace Grand.Web.Admin.Controllers
_translationService = translationService;
_storeService = storeService;
_groupService = groupService;
- _importManager = importManager;
_workContext = workContext;
}
@@ -198,8 +194,8 @@ namespace Grand.Web.Admin.Controllers
{
if (importcsvfile != null && importcsvfile.Length > 0)
{
- int count = await _importManager.ImportNewsletterSubscribersFromTxt(importcsvfile.OpenReadStream(), _workContext.CurrentStore.Id);
- Success(String.Format(_translationService.GetResource("admin.marketing.NewsLetterSubscriptions.ImportEmailsSuccess"), count));
+ var count = await _newsLetterSubscriptionService.ImportNewsletterSubscribersFromTxt(importcsvfile.OpenReadStream(), _workContext.CurrentStore.Id);
+ Success(string.Format(_translationService.GetResource("admin.marketing.NewsLetterSubscriptions.ImportEmailsSuccess"), count));
return RedirectToAction("List");
}
Error(_translationService.GetResource("Admin.Common.UploadFile"));
diff --git a/src/Web/Grand.Web.Admin/Controllers/OrderController.cs b/src/Web/Grand.Web.Admin/Controllers/OrderController.cs
index a7e0cfc43..add527395 100644
--- a/src/Web/Grand.Web.Admin/Controllers/OrderController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/OrderController.cs
@@ -8,7 +8,6 @@ using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Logging;
using Grand.Business.Core.Interfaces.Common.Pdf;
using Grand.Business.Core.Utilities.Common.Security;
-using Grand.Business.Core.Interfaces.System.ExportImport;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Orders;
diff --git a/src/Web/Grand.Web.Admin/Controllers/ProductController.cs b/src/Web/Grand.Web.Admin/Controllers/ProductController.cs
index 84979af68..dcd4eff06 100644
--- a/src/Web/Grand.Web.Admin/Controllers/ProductController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/ProductController.cs
@@ -9,7 +9,6 @@ using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Utilities.Common.Security;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Storage;
-using Grand.Business.Core.Interfaces.System.ExportImport;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Media;
@@ -29,6 +28,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.StaticFiles;
using Grand.Business.Core.Interfaces.ExportImport;
+using Grand.Business.Catalog.Services.ExportImport.Dto;
namespace Grand.Web.Admin.Controllers
{
@@ -46,7 +46,7 @@ namespace Grand.Web.Admin.Controllers
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
private readonly IExportManager<Product> _exportManager;
- private readonly IImportManager _importManager;
+ private readonly IImportManager<ProductDto> _importManager;
private readonly IStoreService _storeService;
private readonly IProductReservationService _productReservationService;
private readonly IAuctionService _auctionService;
@@ -68,7 +68,7 @@ namespace Grand.Web.Admin.Controllers
ILanguageService languageService,
ITranslationService translationService,
IExportManager<Product> exportManager,
- IImportManager importManager,
+ IImportManager<ProductDto> importManager,
IStoreService storeService,
IProductReservationService productReservationService,
IAuctionService auctionService,
@@ -1620,7 +1620,7 @@ namespace Grand.Web.Admin.Controllers
{
if (importexcelfile != null && importexcelfile.Length > 0)
{
- await _importManager.ImportProductsFromXlsx(importexcelfile.OpenReadStream());
+ await _importManager.Import(importexcelfile.OpenReadStream());
}
else
{
diff --git a/src/Web/Grand.Web/Controllers/AccountController.cs b/src/Web/Grand.Web/Controllers/AccountController.cs
index f640aa64f..d6960cb3a 100644
--- a/src/Web/Grand.Web/Controllers/AccountController.cs
+++ b/src/Web/Grand.Web/Controllers/AccountController.cs
@@ -8,7 +8,6 @@ using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Queries.Customers;
using Grand.Business.Core.Utilities.Customers;
using Grand.Business.Core.Interfaces.Messages;
-using Grand.Business.Core.Interfaces.System.ExportImport;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Stores;