From 2b3694af824548eee8382d097e77f6b6c76fa50b Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Thu, 19 Nov 2026 17:41:13 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix:=20=E5=B7=9E=E7=9C=81=E5=9F=8E=E5=B8=82?= =?UTF-8?q?=E7=A7=8D=E5=AD=90=E5=BC=BA=E5=88=B6=20utf8mb4=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E4=BF=AE=E5=A4=8D=E7=A9=BA/=E4=B9=B1=E7=A0=81?= =?UTF-8?q?=E4=B8=AD=E6=96=87=E5=90=8D=E5=8F=AF=E9=87=8D=E8=B7=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- ...migrate_country_province_city_20261119.sql | 102 +++++++++++++++--- 1 file changed, 86 insertions(+), 16 deletions(-) diff --git a/sql/migrate_country_province_city_20261119.sql b/sql/migrate_country_province_city_20261119.sql index fb51f2c..2b7b207 100644 --- a/sql/migrate_country_province_city_20261119.sql +++ b/sql/migrate_country_province_city_20261119.sql @@ -2,7 +2,9 @@ -- migrate_country_province_city_20261119.sql -- 国家下州省 / 城市主数据(地址簿下拉 + 经营地图发件省归一) -- 审计字段对齐 t_outbound_record;禁止 UNIQUE KEY;可重复执行。 +-- 重要:请用 utf8mb4 客户端执行(Navicat/DBeaver/mysql 均需连接编码 utf8mb4)。 -- ============================================================================= +SET NAMES utf8mb4; SET @db := DATABASE(); -- ---------- t_country_province ---------- @@ -22,7 +24,7 @@ SET @sql := IF( `Lat` DECIMAL(10,6) NULL COMMENT ''中心纬度'', `SortOrder` INT NOT NULL DEFAULT 100 COMMENT ''排序,越小越前'', `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'', - `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'', + `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT '''' COMMENT ''并发戳'', `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'', `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'', `UpdateUserId` INT NULL COMMENT ''更新人'', @@ -30,7 +32,7 @@ SET @sql := IF( PRIMARY KEY (`Id`), KEY `ix_country_province_country` (`CountryId`), KEY `ix_country_province_cn_name` (`ChineseName`) - ) COMMENT=''国家州省主数据''', + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT=''国家州省主数据''', 'SELECT ''t_country_province already exists'' AS info' ); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; @@ -49,7 +51,7 @@ SET @sql := IF( `EnglishName` VARCHAR(128) NOT NULL DEFAULT '''' COMMENT ''英文名'', `SortOrder` INT NOT NULL DEFAULT 100 COMMENT ''排序,越小越前'', `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'', - `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'', + `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT '''' COMMENT ''并发戳'', `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'', `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'', `UpdateUserId` INT NULL COMMENT ''更新人'', @@ -57,12 +59,34 @@ SET @sql := IF( PRIMARY KEY (`Id`), KEY `ix_country_city_province` (`ProvinceId`), KEY `ix_country_city_cn_name` (`ChineseName`) - ) COMMENT=''国家城市主数据''', + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT=''国家城市主数据''', 'SELECT ''t_country_city already exists'' AS info' ); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; --- ---------- 种子:中国省/直辖市/自治区/特别行政区(仅当 CN 存在且尚无有效州省时) ---------- +-- 存量表若被建成 latin1,中文会落成 ?/空;强制转 utf8mb4(可重复) +SET @prov_exists := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_country_province' +); +SET @city_exists := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_country_city' +); +SET @sql := IF( + @prov_exists > 0, + 'ALTER TABLE `t_country_province` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci', + 'SELECT ''skip province charset'' AS info' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; +SET @sql := IF( + @city_exists > 0, + 'ALTER TABLE `t_country_city` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci', + 'SELECT ''skip city charset'' AS info' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ---------- 种子:中国省/直辖市/自治区/特别行政区(可重复;按英文名对齐并修复空/乱码中文名) ---------- SET @cn_id := ( SELECT Id FROM t_country WHERE IsDeleted = 0 AND UPPER(CountryCode) = 'CN' @@ -70,12 +94,6 @@ SET @cn_id := ( LIMIT 1 ); -SET @cn_province_count := ( - SELECT COUNT(1) FROM t_country_province - WHERE IsDeleted = 0 AND CountryId = IFNULL(@cn_id, 0) -); - --- 使用临时过程式插入:仅当有 CN 且无州省数据 DROP TEMPORARY TABLE IF EXISTS tmp_cn_province_seed; CREATE TEMPORARY TABLE tmp_cn_province_seed ( ChineseName VARCHAR(64) NOT NULL, @@ -84,7 +102,7 @@ CREATE TEMPORARY TABLE tmp_cn_province_seed ( Lng DECIMAL(10,6) NULL, Lat DECIMAL(10,6) NULL, SortOrder INT NOT NULL -); +) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; INSERT INTO tmp_cn_province_seed (ChineseName, EnglishName, ShortName, Lng, Lat, SortOrder) VALUES ('北京', 'Beijing', '京', 116.400000, 39.900000, 10), @@ -122,6 +140,7 @@ INSERT INTO tmp_cn_province_seed (ChineseName, EnglishName, ShortName, Lng, Lat, ('香港', 'Hong Kong', '港', 114.170000, 22.320000, 330), ('澳门', 'Macao', '澳', 113.540000, 22.190000, 340); +-- 缺省才插;已有行按 EnglishName 对齐 INSERT INTO t_country_province ( CountryId, ChineseName, EnglishName, ShortName, Lng, Lat, SortOrder, IsDeleted, CreateUserId, CreateTime @@ -131,7 +150,35 @@ SELECT 0, 0, CURRENT_TIMESTAMP FROM tmp_cn_province_seed s WHERE @cn_id IS NOT NULL - AND @cn_province_count = 0; + AND NOT EXISTS ( + SELECT 1 FROM t_country_province p + WHERE p.IsDeleted = 0 + AND p.CountryId = @cn_id + AND ( + p.EnglishName = s.EnglishName + OR p.ChineseName = s.ChineseName + ) + ); + +-- 修复:中文名为空、问号乱码、或纯单字节(无汉字)时,按英文名回写中文/简称/坐标 +UPDATE t_country_province p +INNER JOIN tmp_cn_province_seed s + ON p.EnglishName = s.EnglishName +SET + p.ChineseName = s.ChineseName, + p.ShortName = s.ShortName, + p.Lng = s.Lng, + p.Lat = s.Lat, + p.SortOrder = s.SortOrder, + p.UpdateTime = CURRENT_TIMESTAMP +WHERE @cn_id IS NOT NULL + AND p.IsDeleted = 0 + AND p.CountryId = @cn_id + AND ( + TRIM(p.ChineseName) = '' + OR p.ChineseName LIKE '%?%' + OR LENGTH(p.ChineseName) = CHAR_LENGTH(p.ChineseName) + ); DROP TEMPORARY TABLE IF EXISTS tmp_cn_city_seed; CREATE TEMPORARY TABLE tmp_cn_city_seed ( @@ -139,7 +186,7 @@ CREATE TEMPORARY TABLE tmp_cn_city_seed ( ChineseName VARCHAR(64) NOT NULL, EnglishName VARCHAR(128) NOT NULL, SortOrder INT NOT NULL -); +) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; -- 地级市 + 常见自治州/盟/地区 + 物流常用县级市(如义乌);直辖市记本级 INSERT INTO tmp_cn_city_seed (ProvinceName, ChineseName, EnglishName, SortOrder) VALUES @@ -544,7 +591,27 @@ INSERT INTO tmp_cn_city_seed (ProvinceName, ChineseName, EnglishName, SortOrder) ('香港', '香港', 'Hong Kong', 10), ('澳门', '澳门', 'Macao', 10); --- 按「省 + 城市中文名」缺啥补啥,已有库可重复执行 +-- 按「省中文名 + 城市」缺啥补啥;先修城市空/乱码中文名,再补插 +UPDATE t_country_city c +INNER JOIN t_country_province p + ON p.Id = c.ProvinceId + AND p.IsDeleted = 0 + AND p.CountryId = @cn_id +INNER JOIN tmp_cn_city_seed s + ON s.ProvinceName = p.ChineseName + AND s.EnglishName = c.EnglishName +SET + c.ChineseName = s.ChineseName, + c.SortOrder = s.SortOrder, + c.UpdateTime = CURRENT_TIMESTAMP +WHERE @cn_id IS NOT NULL + AND c.IsDeleted = 0 + AND ( + TRIM(c.ChineseName) = '' + OR c.ChineseName LIKE '%?%' + OR LENGTH(c.ChineseName) = CHAR_LENGTH(c.ChineseName) + ); + INSERT INTO t_country_city ( ProvinceId, ChineseName, EnglishName, SortOrder, IsDeleted, CreateUserId, CreateTime @@ -562,7 +629,10 @@ WHERE @cn_id IS NOT NULL SELECT 1 FROM t_country_city c WHERE c.IsDeleted = 0 AND c.ProvinceId = p.Id - AND c.ChineseName = s.ChineseName + AND ( + c.ChineseName = s.ChineseName + OR c.EnglishName = s.EnglishName + ) ); DROP TEMPORARY TABLE IF EXISTS tmp_cn_province_seed; -- 2.45.2 From 1d48613285e75e0a03ffce192121a43dfd19c11d Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Thu, 19 Nov 2026 17:56:23 +0800 Subject: [PATCH 2/2] =?UTF-8?q?feat:=20=E5=B7=9E=E7=9C=81=E5=9F=8E?= =?UTF-8?q?=E5=B8=82=20Excel=20=E5=AF=BC=E5=85=A5=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- .../Services/System/CountryRegionService.cs | 263 ++++++++++++++++++ .../Shared/CountryRegionImportHelper.cs | 263 ++++++++++++++++++ 2 files changed, 526 insertions(+) create mode 100644 src/Oms.Application/Shared/CountryRegionImportHelper.cs diff --git a/src/Oms.Application/Services/System/CountryRegionService.cs b/src/Oms.Application/Services/System/CountryRegionService.cs index 875a603..31b2f4d 100644 --- a/src/Oms.Application/Services/System/CountryRegionService.cs +++ b/src/Oms.Application/Services/System/CountryRegionService.cs @@ -2,6 +2,7 @@ using Fake.Application; using Microsoft.AspNetCore.Mvc; using Oms.Application.Dtos.Shared; using Oms.Application.Dtos.System; +using Oms.Application.Shared; using Oms.Domain.SystemAggregate.Entities; using Oms.Domain.SystemAggregate.Repositories; @@ -215,6 +216,268 @@ public class CountryRegionService : ApplicationService await CityRepository.DeleteAsync(entity); } + /// + /// 下载州省/城市导入模板。 + /// + /// xlsx 文件:国家二字码、州省中文/英文、城市中文/英文、简称、排序。 + [HttpGet("/system/country/region/import-template")] + public async Task DownloadRegionImportTemplateAsync() + { + var bytes = await CountryRegionImportHelper.BuildTemplateBytesAsync(); + return new FileContentResult(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") + { + FileDownloadName = CountryRegionImportHelper.TemplateFileName + }; + } + + /// + /// 导入州省/城市(Excel)。增量按国家+州省中文名、州省+城市中文名新增或更新; + /// 全量还会软删除「文件中出现过的国家」下未列出的州省,以及「文件中出现过城市的州省」下未列出的城市。 + /// 城市中文名为空时仅处理州省。 + /// + /// Excel 文件与导入模式。 + /// 成功、跳过、失败及全量删除条数。 + [HttpPost("/system/country/region/import")] + public async Task ImportRegionAsync([FromForm] CountryImportInput input) + { + if (input.File == null || input.File.Length == 0) + { + throw new BusinessException("请上传 Excel 文件"); + } + + var importMode = NormalizeImportMode(input.ImportMode); + await using var stream = input.File.OpenReadStream(); + var parsedRows = await CountryRegionImportHelper.ParseImportRowsAsync(stream); + if (parsedRows.Count == 0) + { + throw new BusinessException("Excel 中无有效数据行"); + } + + var output = new CountryImportOutput(); + var countryCache = new Dictionary(StringComparer.OrdinalIgnoreCase); + var provinceCache = new Dictionary(StringComparer.OrdinalIgnoreCase); + var seenKeys = new HashSet(StringComparer.OrdinalIgnoreCase); + var touchedCountryIds = new HashSet(); + var touchedProvinceNamesByCountry = new Dictionary>(); + var touchedCityNamesByProvince = new Dictionary>(); + + foreach (var (rowNumber, row) in parsedRows) + { + try + { + CountryRegionImportHelper.Normalize(row); + var rowKey = BuildRowKey(row); + if (!seenKeys.Add(rowKey)) + { + output.SkipCount++; + output.Failures.Add(new CountryImportFailRow + { + RowNumber = rowNumber, + Reason = "文件内州省/城市重复,已跳过" + }); + continue; + } + + var country = await ResolveCountryAsync(row.CountryCode, countryCache); + touchedCountryIds.Add(country.Id); + if (!touchedProvinceNamesByCountry.TryGetValue(country.Id, out var provinceNames)) + { + provinceNames = new HashSet(StringComparer.OrdinalIgnoreCase); + touchedProvinceNamesByCountry[country.Id] = provinceNames; + } + + provinceNames.Add(row.ProvinceChineseName); + + var province = await UpsertProvinceAsync(country.Id, row, provinceCache); + if (!string.IsNullOrWhiteSpace(row.CityChineseName)) + { + if (!touchedCityNamesByProvince.TryGetValue(province.Id, out var cityNames)) + { + cityNames = new HashSet(StringComparer.OrdinalIgnoreCase); + touchedCityNamesByProvince[province.Id] = cityNames; + } + + cityNames.Add(row.CityChineseName); + await UpsertCityAsync(province.Id, row); + } + + output.SuccessCount++; + } + catch (Exception ex) + { + output.FailCount++; + output.Failures.Add(new CountryImportFailRow + { + RowNumber = rowNumber, + Reason = ex.Message + }); + } + } + + if (importMode == CountryImportInput.ImportModes.Full && output.SuccessCount > 0) + { + output.DeletedCount += await SoftDeleteMissingRegionsAsync( + touchedCountryIds, + touchedProvinceNamesByCountry, + touchedCityNamesByProvince); + } + + return output; + } + + private async Task ResolveCountryAsync(string countryCode, IDictionary cache) + { + if (cache.TryGetValue(countryCode, out var cached)) + { + return cached; + } + + var country = await CountryRepository.GetByCountryCodeAsync(countryCode); + if (country == null) + { + throw new BusinessException($"国家二字码不存在:{countryCode},请先导入国家"); + } + + cache[countryCode] = country; + return country; + } + + private async Task UpsertProvinceAsync( + int countryId, + CountryRegionImportRow row, + IDictionary cache) + { + var cacheKey = $"{countryId}:{row.ProvinceChineseName}"; + if (cache.TryGetValue(cacheKey, out var cached)) + { + ApplyProvinceFields(cached, row); + await ProvinceRepository.UpdateAsync(cached); + return cached; + } + + var existing = await ProvinceRepository.FindByCountryAndChineseNameAsync(countryId, row.ProvinceChineseName); + if (existing != null) + { + ApplyProvinceFields(existing, row); + await ProvinceRepository.UpdateAsync(existing); + cache[cacheKey] = existing; + return existing; + } + + var entity = new CountryProvince + { + CountryId = countryId, + ChineseName = row.ProvinceChineseName, + EnglishName = row.ProvinceEnglishName, + ShortName = row.ShortName, + SortOrder = row.SortOrder + }; + await ProvinceRepository.InsertAsync(entity); + cache[cacheKey] = entity; + return entity; + } + + private async Task UpsertCityAsync(int provinceId, CountryRegionImportRow row) + { + var existing = await CityRepository.FindByProvinceAndChineseNameAsync(provinceId, row.CityChineseName); + if (existing != null) + { + existing.EnglishName = row.CityEnglishName; + existing.SortOrder = row.SortOrder; + await CityRepository.UpdateAsync(existing); + return; + } + + await CityRepository.InsertAsync(new CountryCity + { + ProvinceId = provinceId, + ChineseName = row.CityChineseName, + EnglishName = row.CityEnglishName, + SortOrder = row.SortOrder + }); + } + + private async Task SoftDeleteMissingRegionsAsync( + IReadOnlyCollection touchedCountryIds, + IReadOnlyDictionary> touchedProvinceNamesByCountry, + IReadOnlyDictionary> touchedCityNamesByProvince) + { + var deleted = 0; + foreach (var countryId in touchedCountryIds) + { + var keepProvinces = touchedProvinceNamesByCountry.GetValueOrDefault(countryId) + ?? new HashSet(StringComparer.OrdinalIgnoreCase); + var provinces = await ProvinceRepository.ListByCountryIdAsync(countryId); + foreach (var province in provinces) + { + if (!keepProvinces.Contains(province.ChineseName)) + { + var cities = await CityRepository.ListByProvinceIdAsync(province.Id); + foreach (var city in cities) + { + await CityRepository.DeleteAsync(city); + deleted++; + } + + await ProvinceRepository.DeleteAsync(province); + deleted++; + continue; + } + + if (!touchedCityNamesByProvince.TryGetValue(province.Id, out var keepCities)) + { + continue; + } + + var existingCities = await CityRepository.ListByProvinceIdAsync(province.Id); + foreach (var city in existingCities) + { + if (keepCities.Contains(city.ChineseName)) + { + continue; + } + + await CityRepository.DeleteAsync(city); + deleted++; + } + } + } + + return deleted; + } + + private static void ApplyProvinceFields(CountryProvince entity, CountryRegionImportRow row) + { + if (!string.IsNullOrWhiteSpace(row.ProvinceEnglishName)) + { + entity.EnglishName = row.ProvinceEnglishName; + } + + if (!string.IsNullOrWhiteSpace(row.ShortName)) + { + entity.ShortName = row.ShortName; + } + + entity.SortOrder = row.SortOrder; + } + + private static string BuildRowKey(CountryRegionImportRow row) => + string.IsNullOrWhiteSpace(row.CityChineseName) + ? $"{row.CountryCode}|{row.ProvinceChineseName}|*" + : $"{row.CountryCode}|{row.ProvinceChineseName}|{row.CityChineseName}"; + + private static string NormalizeImportMode(string? mode) + { + if (string.Equals(mode, CountryImportInput.ImportModes.Full, StringComparison.OrdinalIgnoreCase) + || string.Equals(mode, "全量", StringComparison.OrdinalIgnoreCase) + || string.Equals(mode, "replace", StringComparison.OrdinalIgnoreCase)) + { + return CountryImportInput.ImportModes.Full; + } + + return CountryImportInput.ImportModes.Incremental; + } + private async Task GetCountryOrThrowAsync(int id) { var entity = await CountryRepository.FirstOrDefaultAsync(x => x.Id == id); diff --git a/src/Oms.Application/Shared/CountryRegionImportHelper.cs b/src/Oms.Application/Shared/CountryRegionImportHelper.cs new file mode 100644 index 0000000..400c4ed --- /dev/null +++ b/src/Oms.Application/Shared/CountryRegionImportHelper.cs @@ -0,0 +1,263 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using MiniExcelLibs; + +namespace Oms.Application.Shared; + +/// +/// 州省/城市 Excel 模板与导入解析。 +/// +public static class CountryRegionImportHelper +{ + public const string TemplateSheetName = "导入模板"; + public const string TemplateFileName = "州省城市导入模板.xlsx"; + + private static readonly Regex CountryCodePattern = new("^[A-Za-z]{2}$", RegexOptions.Compiled); + + private static readonly Dictionary HeaderAliases = new(StringComparer.OrdinalIgnoreCase) + { + ["国家二字码"] = nameof(CountryRegionImportRow.CountryCode), + ["二字码"] = nameof(CountryRegionImportRow.CountryCode), + ["国家代码"] = nameof(CountryRegionImportRow.CountryCode), + ["CountryCode"] = nameof(CountryRegionImportRow.CountryCode), + ["countryCode"] = nameof(CountryRegionImportRow.CountryCode), + ["州省中文名"] = nameof(CountryRegionImportRow.ProvinceChineseName), + ["省中文名"] = nameof(CountryRegionImportRow.ProvinceChineseName), + ["州省"] = nameof(CountryRegionImportRow.ProvinceChineseName), + ["省/州"] = nameof(CountryRegionImportRow.ProvinceChineseName), + ["ProvinceChineseName"] = nameof(CountryRegionImportRow.ProvinceChineseName), + ["ProvinceName"] = nameof(CountryRegionImportRow.ProvinceChineseName), + ["州省英文名"] = nameof(CountryRegionImportRow.ProvinceEnglishName), + ["省英文名"] = nameof(CountryRegionImportRow.ProvinceEnglishName), + ["ProvinceEnglishName"] = nameof(CountryRegionImportRow.ProvinceEnglishName), + ["城市中文名"] = nameof(CountryRegionImportRow.CityChineseName), + ["市中文名"] = nameof(CountryRegionImportRow.CityChineseName), + ["城市"] = nameof(CountryRegionImportRow.CityChineseName), + ["CityChineseName"] = nameof(CountryRegionImportRow.CityChineseName), + ["CityName"] = nameof(CountryRegionImportRow.CityChineseName), + ["城市英文名"] = nameof(CountryRegionImportRow.CityEnglishName), + ["市英文名"] = nameof(CountryRegionImportRow.CityEnglishName), + ["CityEnglishName"] = nameof(CountryRegionImportRow.CityEnglishName), + ["简称"] = nameof(CountryRegionImportRow.ShortName), + ["州省简称"] = nameof(CountryRegionImportRow.ShortName), + ["ShortName"] = nameof(CountryRegionImportRow.ShortName), + ["排序"] = nameof(CountryRegionImportRow.SortOrderText), + ["SortOrder"] = nameof(CountryRegionImportRow.SortOrderText), + ["sortOrder"] = nameof(CountryRegionImportRow.SortOrderText), + }; + + public static async Task BuildTemplateBytesAsync() + { + var templateRows = new List> + { + new() + { + ["国家二字码"] = "CN", + ["州省中文名"] = "广东", + ["州省英文名"] = "Guangdong", + ["城市中文名"] = "深圳", + ["城市英文名"] = "Shenzhen", + ["简称"] = "粤", + ["排序"] = 190 + }, + new() + { + ["国家二字码"] = "CN", + ["州省中文名"] = "广东", + ["州省英文名"] = "Guangdong", + ["城市中文名"] = "广州", + ["城市英文名"] = "Guangzhou", + ["简称"] = "粤", + ["排序"] = 190 + }, + new() + { + ["国家二字码"] = "CN", + ["州省中文名"] = "北京", + ["州省英文名"] = "Beijing", + ["城市中文名"] = "", + ["城市英文名"] = "", + ["简称"] = "京", + ["排序"] = 10 + } + }; + + var sheets = new Dictionary + { + [TemplateSheetName] = templateRows + }; + + await using var stream = new MemoryStream(); + await MiniExcel.SaveAsAsync(stream, sheets); + return stream.ToArray(); + } + + public static async Task> ParseImportRowsAsync(Stream fileStream) + { + if (fileStream.CanSeek) + { + fileStream.Position = 0; + } + + var sheetNames = MiniExcel.GetSheetNames(fileStream); + var sheetName = sheetNames.FirstOrDefault(x => + string.Equals(x, TemplateSheetName, StringComparison.OrdinalIgnoreCase)) + ?? sheetNames.FirstOrDefault(); + + if (fileStream.CanSeek) + { + fileStream.Position = 0; + } + + var rows = await MiniExcel.QueryAsync(fileStream, useHeaderRow: true, sheetName: sheetName); + var result = new List<(int RowNumber, CountryRegionImportRow Row)>(); + var rowNumber = 1; + + foreach (var row in rows) + { + rowNumber++; + if (row is not IDictionary rowDict || IsEmptyRow(rowDict)) + { + continue; + } + + result.Add((rowNumber, ParseRow(rowDict))); + } + + return result; + } + + public static void Normalize(CountryRegionImportRow row) + { + row.CountryCode = row.CountryCode?.Trim().ToUpperInvariant() ?? string.Empty; + row.ProvinceChineseName = row.ProvinceChineseName?.Trim() ?? string.Empty; + row.ProvinceEnglishName = row.ProvinceEnglishName?.Trim() ?? string.Empty; + row.CityChineseName = row.CityChineseName?.Trim() ?? string.Empty; + row.CityEnglishName = row.CityEnglishName?.Trim() ?? string.Empty; + row.ShortName = string.IsNullOrWhiteSpace(row.ShortName) ? null : row.ShortName.Trim(); + row.SortOrder = ParseSortOrder(row.SortOrderText); + + if (string.IsNullOrWhiteSpace(row.CountryCode)) + { + throw new InvalidOperationException("国家二字码不能为空"); + } + + if (!CountryCodePattern.IsMatch(row.CountryCode)) + { + throw new InvalidOperationException("国家二字码须为 2 位字母,如 CN、US"); + } + + if (string.IsNullOrWhiteSpace(row.ProvinceChineseName)) + { + throw new InvalidOperationException("州省中文名不能为空"); + } + + if (row.ProvinceChineseName.Length > 64) + { + throw new InvalidOperationException("州省中文名不可超过 64 个字符"); + } + + if (row.ProvinceEnglishName.Length > 128) + { + throw new InvalidOperationException("州省英文名不可超过 128 个字符"); + } + + if (row.CityChineseName.Length > 64) + { + throw new InvalidOperationException("城市中文名不可超过 64 个字符"); + } + + if (row.CityEnglishName.Length > 128) + { + throw new InvalidOperationException("城市英文名不可超过 128 个字符"); + } + + if (row.ShortName is { Length: > 16 }) + { + throw new InvalidOperationException("简称不可超过 16 个字符"); + } + } + + private static int ParseSortOrder(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) + { + return 100; + } + + if (int.TryParse(raw.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var value)) + { + return value; + } + + if (decimal.TryParse(raw.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var decimalValue)) + { + return (int)Math.Round(decimalValue, MidpointRounding.AwayFromZero); + } + + throw new InvalidOperationException("排序须为整数"); + } + + private static CountryRegionImportRow ParseRow(IDictionary rowDict) + { + var mapped = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (header, value) in rowDict) + { + if (string.IsNullOrWhiteSpace(header) || !HeaderAliases.TryGetValue(header.Trim(), out var field)) + { + continue; + } + + mapped[field] = NormalizeCell(value); + } + + return new CountryRegionImportRow + { + CountryCode = mapped.GetValueOrDefault(nameof(CountryRegionImportRow.CountryCode)) ?? string.Empty, + ProvinceChineseName = + mapped.GetValueOrDefault(nameof(CountryRegionImportRow.ProvinceChineseName)) ?? string.Empty, + ProvinceEnglishName = + mapped.GetValueOrDefault(nameof(CountryRegionImportRow.ProvinceEnglishName)) ?? string.Empty, + CityChineseName = mapped.GetValueOrDefault(nameof(CountryRegionImportRow.CityChineseName)) ?? string.Empty, + CityEnglishName = mapped.GetValueOrDefault(nameof(CountryRegionImportRow.CityEnglishName)) ?? string.Empty, + ShortName = mapped.GetValueOrDefault(nameof(CountryRegionImportRow.ShortName)), + SortOrderText = mapped.GetValueOrDefault(nameof(CountryRegionImportRow.SortOrderText)) + }; + } + + private static string? NormalizeCell(object? value) + { + if (value is null) + { + return null; + } + + var text = Convert.ToString(value, CultureInfo.InvariantCulture)?.Trim(); + return string.IsNullOrWhiteSpace(text) ? null : text; + } + + private static bool IsEmptyRow(IDictionary rowDict) => + rowDict.Values.All(value => string.IsNullOrWhiteSpace(NormalizeCell(value))); +} + +/// +/// 州省/城市导入行。城市中文名为空时仅导入/更新州省。 +/// +public class CountryRegionImportRow +{ + public string CountryCode { get; set; } = string.Empty; + + public string ProvinceChineseName { get; set; } = string.Empty; + + public string ProvinceEnglishName { get; set; } = string.Empty; + + public string CityChineseName { get; set; } = string.Empty; + + public string CityEnglishName { get; set; } = string.Empty; + + public string? ShortName { get; set; } + + public string? SortOrderText { get; set; } + + public int SortOrder { get; set; } = 100; +} -- 2.45.2