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.

Allow to export/import country states to the Excel - fix #71

KrzysztofPajakb23c732f02ca
diff --git a/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs b/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs
index 690c73f1c..72045ae8d 100644
--- a/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs
+++ b/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs
@@ -290,9 +290,15 @@ namespace Grand.Business.Common.Services.Directory
if (country == null)
throw new ArgumentNullException(nameof(country));
- var state = country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id);
- state = stateProvince;
-
+ if (country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id) != null)
+ {
+ var state = country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id);
+ state.Name = stateProvince.Name;
+ state.Locales = stateProvince.Locales;
+ state.Published = stateProvince.Published;
+ state.Abbreviation = stateProvince.Abbreviation;
+ state.DisplayOrder = stateProvince.DisplayOrder;
+ }
await UpdateCountry(country);
}
/// <summary>
diff --git a/src/Business/Grand.Business.System/Interfaces/ExportImport/IExportManager.cs b/src/Business/Grand.Business.System/Interfaces/ExportImport/IExportManager.cs
index 614823fce..1eee9785c 100644
--- a/src/Business/Grand.Business.System/Interfaces/ExportImport/IExportManager.cs
+++ b/src/Business/Grand.Business.System/Interfaces/ExportImport/IExportManager.cs
@@ -57,6 +57,12 @@ namespace Grand.Business.System.Interfaces.ExportImport
/// <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>
diff --git a/src/Business/Grand.Business.System/Interfaces/ExportImport/IImportManager.cs b/src/Business/Grand.Business.System/Interfaces/ExportImport/IImportManager.cs
index 40f557f0f..6d2c90518 100644
--- a/src/Business/Grand.Business.System/Interfaces/ExportImport/IImportManager.cs
+++ b/src/Business/Grand.Business.System/Interfaces/ExportImport/IImportManager.cs
@@ -22,14 +22,13 @@ namespace Grand.Business.System.Interfaces.ExportImport
Task<int> ImportNewsletterSubscribersFromTxt(Stream stream);
/// <summary>
- /// Import states from TXT file
+ /// Import country states from XLSX file
/// </summary>
/// <param name="stream">Stream</param>
- /// <returns>Number of imported states</returns>
- Task<int> ImportStatesFromCsv(Stream stream);
+ Task ImportCountryStatesFromXlsx(Stream stream);
/// <summary>
- /// Import collections from XLSX file
+ /// Import brand from XLSX file
/// </summary>
/// <param name="stream">Stream</param>
Task ImportBrandFromXlsx(Stream stream);
diff --git a/src/Business/Grand.Business.System/Services/ExportImport/ExportManager.cs b/src/Business/Grand.Business.System/Services/ExportImport/ExportManager.cs
index 4e7e7c196..af0abf882 100644
--- a/src/Business/Grand.Business.System/Services/ExportImport/ExportManager.cs
+++ b/src/Business/Grand.Business.System/Services/ExportImport/ExportManager.cs
@@ -384,6 +384,19 @@ namespace Grand.Business.System.Services.ExportImport
}
+ /// <summary>
+ /// Export states to XLSX
+ /// </summary>
+ /// <param name="countries">Countries</param>
+ public virtual byte[] ExportStatesToXlsx(IList<Country> countries)
+ {
+ var query = from p in countries
+ from s in p.StateProvinces
+ select (p, s);
+
+ return ExportToXlsx(PropertyByCountryState(), query);
+ }
+
/// <summary>
/// Export newsletter subscribers to TXT
/// </summary>
@@ -612,6 +625,19 @@ namespace Grand.Business.System.Services.ExportImport
return properties;
}
+ private PropertyByName<(Country, StateProvince)>[] PropertyByCountryState()
+ {
+ var properties = new[]
+ {
+ new PropertyByName<(Country c, StateProvince s)>("Country", p => p.c.TwoLetterIsoCode),
+ new PropertyByName<(Country c, StateProvince s)>("Name", p => p.s.Name),
+ new PropertyByName<(Country c, StateProvince s)>("Abbreviation", p => p.s.Abbreviation),
+ new PropertyByName<(Country c, StateProvince s)>("DisplayOrder", p => p.s.DisplayOrder),
+ new PropertyByName<(Country c, StateProvince s)>("Published", p => p.s.Published)
+ };
+ return properties;
+ }
+
private PropertyByName<ActivityLog>[] PropertyByActivityLog()
{
var properties = new[]
diff --git a/src/Business/Grand.Business.System/Services/ExportImport/ImportManager.cs b/src/Business/Grand.Business.System/Services/ExportImport/ImportManager.cs
index c336fc791..2fc551875 100644
--- a/src/Business/Grand.Business.System/Services/ExportImport/ImportManager.cs
+++ b/src/Business/Grand.Business.System/Services/ExportImport/ImportManager.cs
@@ -1048,67 +1048,65 @@ namespace Grand.Business.System.Services.ExportImport
}
/// <summary>
- /// Import states from TXT file
+ /// Import country states from XLSX file
/// </summary>
/// <param name="stream">Stream</param>
- /// <returns>Number of imported states</returns>
- public virtual async Task<int> ImportStatesFromCsv(Stream stream)
+ public virtual async Task ImportCountryStatesFromXlsx(Stream stream)
{
- int count = 0;
- using (var reader = new StreamReader(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++)
{
- while (!reader.EndOfStream)
- {
- string line = reader.ReadLine();
- if (String.IsNullOrWhiteSpace(line))
- continue;
- string[] tmp = line.Split(',');
+ 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 (tmp.Length != 5)
- throw new GrandException("Wrong file format");
+ if (country == null)
+ continue;
- //parse
- var countryTwoLetterIsoCode = tmp[0].Trim();
- var name = tmp[1].Trim();
- var abbreviation = tmp[2].Trim();
- bool published = Boolean.Parse(tmp[3].Trim());
- int displayOrder = Int32.Parse(tmp[4].Trim());
-
- var country = await _countryService.GetCountryByTwoLetterIsoCode(countryTwoLetterIsoCode);
- if (country == null)
- {
- //country cannot be loaded. skip
- continue;
- }
+ //import
+ var abbreviation = manager.GetProperty("abbreviation") != null ? manager.GetProperty("abbreviation").StringValue : string.Empty;
+ if (string.IsNullOrEmpty(abbreviation))
+ continue;
- //import
- var states = country.StateProvinces.ToList();
- var state = states.FirstOrDefault(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
+ var name = manager.GetProperty("name") != null ? manager.GetProperty("name").StringValue : string.Empty;
+ if (string.IsNullOrEmpty(name))
+ continue;
- if (state != null)
- {
- 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);
- }
- count++;
+ 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);
}
+
}
- return count;
}
+
/// <summary>
/// Import brands from XLSX file
/// </summary>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Country/List.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Country/List.cshtml
index 79556dc5d..fef54966e 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Country/List.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Country/List.cshtml
@@ -16,8 +16,8 @@
<a href="@Url.Action("Create", new { area = Constants.AreaAdmin })" class="btn green"><i class="fa fa-plus"></i><span class="d-none d-sm-inline"> @Loc["Admin.Common.AddNew"] </span></a>
<input type="button" id="publish-selected" class="btn default" value="@Loc["Admin.Configuration.Countries.PublishSelected"]" />
<input type="button" id="unpublish-selected" class="btn default" value="@Loc["Admin.Configuration.Countries.UnpublishSelected"]" />
- <a href="@Url.Action("ExportCsv", new { area = Constants.AreaAdmin })" class="btn blue">@Loc["Admin.Configuration.Countries.ExportToCsv"]</a>
- <input type="submit" id="importcsv" name="importcsv" class="btn yellow" value="@Loc["Admin.Configuration.Countries.ImportFromCsv"]" />
+ <a href="@Url.Action("ExportExcel", new { area = Constants.AreaAdmin })" class="btn blue">@Loc["Admin.Configuration.Countries.ExportStatesToExcel"]</a>
+ <input type="submit" id="importexcel" name="importexcel" class="btn yellow" value="@Loc["Admin.Configuration.Countries.ImportStatesFromExcel"]" />
<vc:admin-widget widget-zone="country_list_buttons" additional-data="null" />
</div>
</div>
@@ -249,21 +249,21 @@
}
</script>
-<div id="importcsv-window" style="display:none;">
- <form asp-area="@Constants.AreaAdmin" asp-controller="Country" asp-action="ImportCsv" method="post" enctype="multipart/form-data">
+<div id="importexcel-window" style="display:none;">
+ <form asp-area="@Constants.AreaAdmin" asp-controller="Country" asp-action="ImportExcel" method="post" enctype="multipart/form-data">
<table style="text-align:left;">
<tr>
<td>
- @Loc["Admin.Common.CsvFile"]:
+ @Loc["Admin.Common.ExcelFile"]:
</td>
<td>
- <input type="file" id="importcsvfile" name="importcsvfile" />
+ <input type="file" id="importexcelfile" name="importexcelfile" />
</td>
</tr>
<tr>
<td colspan="2">
- <input type="submit" class="k-button" value="@Loc["Admin.Common.ImportFromCsv"]" />
+ <input type="submit" class="k-button" value="@Loc["Admin.Common.ImportFromExcel"]" />
</td>
</tr>
</table>
@@ -271,14 +271,14 @@
</div>
<script>
$(document).ready(function () {
- $("#importcsv").click(function (e) {
+ $("#importexcel").click(function (e) {
e.preventDefault();
- var window = $("#importcsv-window");
+ var window = $("#importexcel-window");
if (!window.data("kendoWindow")) {
window.kendoWindow({
modal: true,
width: "400px",
- title: "@Loc["Admin.Common.ImportFromCsv"]",
+ title: "@Loc["Admin.Common.ImportFromExcel"]",
actions: ["Close"]
});
}
diff --git a/src/Web/Grand.Web.Admin/Controllers/CountryController.cs b/src/Web/Grand.Web.Admin/Controllers/CountryController.cs
index 12531b3d0..22f3fef6a 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CountryController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CountryController.cs
@@ -18,6 +18,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
+using Grand.SharedKernel.Extensions;
namespace Grand.Web.Admin.Controllers
{
@@ -348,16 +349,27 @@ namespace Grand.Web.Admin.Controllers
#region Export / import
+ [PermissionAuthorizeAction(PermissionActionName.Export)]
+ public async Task<IActionResult> ExportExcel()
+ {
+ var countries = await _countryService.GetAllCountries();
+ var bytes = _exportManager.ExportStatesToXlsx(countries);
+
+ return File(bytes, "text/xls", "states.xlsx");
+
+ }
+
[PermissionAuthorizeAction(PermissionActionName.Import)]
[HttpPost]
- public async Task<IActionResult> ImportCsv(IFormFile importcsvfile)
+ public async Task<IActionResult> ImportExcel(IFormFile importexcelfile)
{
try
{
- if (importcsvfile != null && importcsvfile.Length > 0)
+ if (importexcelfile != null && importexcelfile.Length > 0)
{
- int count = await _importManager.ImportStatesFromCsv(importcsvfile.OpenReadStream());
- Success(String.Format(_translationService.GetResource("Admin.Configuration.Countries.ImportSuccess"), count));
+ await _importManager.ImportCountryStatesFromXlsx(importexcelfile.OpenReadStream());
+
+ Success(_translationService.GetResource("Admin.Configuration.Countries.ImportSuccess"));
return RedirectToAction("List");
}
Error(_translationService.GetResource("Admin.Common.UploadFile"));
diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml
index a6286b36e..48053a9ed 100644
--- a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml
+++ b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml
@@ -4053,8 +4053,8 @@
<Resource Name="Admin.Configuration.Countries.EditCountryDetails">
<Value>Edit country details</Value>
</Resource>
- <Resource Name="Admin.Configuration.Countries.ExportToCsv">
- <Value>Export states to CSV</Value>
+ <Resource Name="Admin.Configuration.Countries.ExportStatesToExcel">
+ <Value>Export states to Excel</Value>
</Resource>
<Resource Name="Admin.Configuration.Countries.Fields.AllowsBilling">
<Value>Allows billing</Value>
@@ -4104,11 +4104,11 @@
<Resource Name="Admin.Configuration.Countries.Fields.TwoLetterIsoCode.Required">
<Value>Two letter ISO code is required.</Value>
</Resource>
- <Resource Name="Admin.Configuration.Countries.ImportFromCsv">
- <Value>Import states from CSV</Value>
+ <Resource Name="Admin.Configuration.Countries.ImportStatesFromExcel">
+ <Value>Import states from Excel</Value>
</Resource>
<Resource Name="Admin.Configuration.Countries.ImportSuccess">
- <Value>{0} states have been successfully imported</Value>
+ <Value>The states have been successfully imported</Value>
</Resource>
<Resource Name="Admin.Configuration.Countries.Info">
<Value>Country info</Value>