2026111901 #27

Merged
zzh merged 2 commits from test into master 2026-11-19 18:06:09 +08:00
2 changed files with 526 additions and 0 deletions
Showing only changes of commit 1d48613285 - Show all commits

View File

@ -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);
}
/// <summary>
/// 下载州省/城市导入模板。
/// </summary>
/// <returns>xlsx 文件:国家二字码、州省中文/英文、城市中文/英文、简称、排序。</returns>
[HttpGet("/system/country/region/import-template")]
public async Task<FileContentResult> DownloadRegionImportTemplateAsync()
{
var bytes = await CountryRegionImportHelper.BuildTemplateBytesAsync();
return new FileContentResult(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = CountryRegionImportHelper.TemplateFileName
};
}
/// <summary>
/// 导入州省/城市(Excel)。增量按国家+州省中文名、州省+城市中文名新增或更新;
/// 全量还会软删除「文件中出现过的国家」下未列出的州省,以及「文件中出现过城市的州省」下未列出的城市。
/// 城市中文名为空时仅处理州省。
/// </summary>
/// <param name="input">Excel 文件与导入模式。</param>
/// <returns>成功、跳过、失败及全量删除条数。</returns>
[HttpPost("/system/country/region/import")]
public async Task<CountryImportOutput> 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<string, Country>(StringComparer.OrdinalIgnoreCase);
var provinceCache = new Dictionary<string, CountryProvince>(StringComparer.OrdinalIgnoreCase);
var seenKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var touchedCountryIds = new HashSet<int>();
var touchedProvinceNamesByCountry = new Dictionary<int, HashSet<string>>();
var touchedCityNamesByProvince = new Dictionary<int, HashSet<string>>();
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<string>(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<string>(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<Country> ResolveCountryAsync(string countryCode, IDictionary<string, Country> 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<CountryProvince> UpsertProvinceAsync(
int countryId,
CountryRegionImportRow row,
IDictionary<string, CountryProvince> 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<int> SoftDeleteMissingRegionsAsync(
IReadOnlyCollection<int> touchedCountryIds,
IReadOnlyDictionary<int, HashSet<string>> touchedProvinceNamesByCountry,
IReadOnlyDictionary<int, HashSet<string>> touchedCityNamesByProvince)
{
var deleted = 0;
foreach (var countryId in touchedCountryIds)
{
var keepProvinces = touchedProvinceNamesByCountry.GetValueOrDefault(countryId)
?? new HashSet<string>(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<Country> GetCountryOrThrowAsync(int id)
{
var entity = await CountryRepository.FirstOrDefaultAsync(x => x.Id == id);

View File

@ -0,0 +1,263 @@
using System.Globalization;
using System.Text.RegularExpressions;
using MiniExcelLibs;
namespace Oms.Application.Shared;
/// <summary>
/// 州省/城市 Excel 模板与导入解析。
/// </summary>
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<string, string> 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<byte[]> BuildTemplateBytesAsync()
{
var templateRows = new List<Dictionary<string, object?>>
{
new()
{
["国家二字码"] = "CN",
["州省中文名"] = "广东",
["州省英文名"] = "Guangdong",
["城市中文名"] = "深圳",
["城市英文名"] = "Shenzhen",
["简称"] = "粤",
["排序"] = 190
},
new()
{
["国家二字码"] = "CN",
["州省中文名"] = "广东",
["州省英文名"] = "Guangdong",
["城市中文名"] = "广州",
["城市英文名"] = "Guangzhou",
["简称"] = "粤",
["排序"] = 190
},
new()
{
["国家二字码"] = "CN",
["州省中文名"] = "北京",
["州省英文名"] = "Beijing",
["城市中文名"] = "",
["城市英文名"] = "",
["简称"] = "京",
["排序"] = 10
}
};
var sheets = new Dictionary<string, object>
{
[TemplateSheetName] = templateRows
};
await using var stream = new MemoryStream();
await MiniExcel.SaveAsAsync(stream, sheets);
return stream.ToArray();
}
public static async Task<List<(int RowNumber, CountryRegionImportRow Row)>> 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<string, object> 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<string, object> rowDict)
{
var mapped = new Dictionary<string, string?>(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<string, object> rowDict) =>
rowDict.Values.All(value => string.IsNullOrWhiteSpace(NormalizeCell(value)));
}
/// <summary>
/// 州省/城市导入行。城市中文名为空时仅导入/更新州省。
/// </summary>
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;
}