admin/src/Oms.Application/Services/System/CountryRegionService.cs
zzh 748afbf45b
All checks were successful
Build and Deploy / deploy (push) Successful in 1m19s
feat: 国家州省城市主数据与地址簿必填校验
支撑地址簿级联下拉与经营地图发件省归一;附 CN 种子迁移脚本。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 12:32:06 +08:00

337 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Fake.Application;
using Microsoft.AspNetCore.Mvc;
using Oms.Application.Dtos.Shared;
using Oms.Application.Dtos.System;
using Oms.Domain.SystemAggregate.Entities;
using Oms.Domain.SystemAggregate.Repositories;
namespace Oms.Application.Services.System;
/// <summary>
/// 国家州省/城市主数据 API(地址下拉与经营地图发件省归一)。
/// </summary>
[ApiExplorerSettings(GroupName = "OMS-System")]
public class CountryRegionService : ApplicationService
{
private ICountryRepository CountryRepository => LazyServiceProvider.GetRequiredService<ICountryRepository>();
private ICountryProvinceRepository ProvinceRepository => LazyServiceProvider.GetRequiredService<ICountryProvinceRepository>();
private ICountryCityRepository CityRepository => LazyServiceProvider.GetRequiredService<ICountryCityRepository>();
/// <summary>
/// 按国家查询州省列表(维护页)。
/// </summary>
/// <param name="countryId">国家主键。</param>
/// <returns>州省列表,含下属城市数。</returns>
[HttpGet("/system/country/province/list")]
public async Task<List<CountryProvinceOutput>> GetProvinceListAsync([FromQuery] int countryId)
{
if (countryId <= 0)
{
throw new BusinessException("请指定国家");
}
var country = await GetCountryOrThrowAsync(countryId);
var provinces = await ProvinceRepository.ListByCountryIdAsync(countryId);
var cityCounts = await LoadCityCountMapAsync(provinces.Select(x => x.Id));
return provinces.Select(x => ToProvinceOutput(x, country.CountryCode, cityCounts)).ToList();
}
/// <summary>
/// 地址下拉:按国家二字码返回州省选项(value=中文名)。
/// </summary>
/// <param name="countryCode">ISO 二字码,如 CN。</param>
/// <returns>州省选项;国家不存在时返回空列表。</returns>
[HttpGet("/system/country/province/options")]
public async Task<List<CountryProvinceOptionOutput>> GetProvinceOptionsAsync([FromQuery] string countryCode)
{
var code = (countryCode ?? string.Empty).Trim().ToUpperInvariant();
if (string.IsNullOrWhiteSpace(code))
{
return [];
}
var country = await CountryRepository.GetByCountryCodeAsync(code);
if (country == null)
{
return [];
}
var provinces = await ProvinceRepository.ListByCountryIdAsync(country.Id);
return provinces.Select(x => new CountryProvinceOptionOutput
{
Id = x.Id,
Label = BuildLabel(x.ChineseName, x.EnglishName),
Value = x.ChineseName
}).ToList();
}
/// <summary>
/// 新增州省。同一国家下中文名业务唯一。
/// </summary>
[HttpPost("/system/country/province/create")]
public async Task CreateProvinceAsync([FromBody] CreateCountryProvinceInput input)
{
await GetCountryOrThrowAsync(input.CountryId);
var name = NormalizeRequiredName(input.ChineseName, "州省中文名不能为空");
await EnsureProvinceNameUniqueAsync(input.CountryId, name, excludeId: null);
await ProvinceRepository.InsertAsync(new CountryProvince
{
CountryId = input.CountryId,
ChineseName = name,
EnglishName = (input.EnglishName ?? string.Empty).Trim(),
ShortName = NullIfWhiteSpace(input.ShortName),
Lng = input.Lng,
Lat = input.Lat,
SortOrder = input.SortOrder
});
}
/// <summary>
/// 更新州省。
/// </summary>
[HttpPost("/system/country/province/update")]
public async Task UpdateProvinceAsync([FromBody] UpdateCountryProvinceInput input)
{
var entity = await GetProvinceOrThrowAsync(input.Id);
if (input.CountryId != entity.CountryId)
{
await GetCountryOrThrowAsync(input.CountryId);
entity.CountryId = input.CountryId;
}
var name = NormalizeRequiredName(input.ChineseName, "州省中文名不能为空");
await EnsureProvinceNameUniqueAsync(entity.CountryId, name, excludeId: entity.Id);
entity.ChineseName = name;
entity.EnglishName = (input.EnglishName ?? string.Empty).Trim();
entity.ShortName = NullIfWhiteSpace(input.ShortName);
entity.Lng = input.Lng;
entity.Lat = input.Lat;
entity.SortOrder = input.SortOrder;
await ProvinceRepository.UpdateAsync(entity);
}
/// <summary>
/// 删除州省(软删除);同时软删除其下城市。
/// </summary>
[HttpPost("/system/country/province/delete")]
public async Task DeleteProvinceAsync([FromBody] IdInput input)
{
var entity = await GetProvinceOrThrowAsync(input.Id);
var cities = await CityRepository.ListByProvinceIdAsync(entity.Id);
foreach (var city in cities)
{
await CityRepository.DeleteAsync(city);
}
await ProvinceRepository.DeleteAsync(entity);
}
/// <summary>
/// 按州省查询城市列表(维护页)。
/// </summary>
[HttpGet("/system/country/city/list")]
public async Task<List<CountryCityOutput>> GetCityListAsync([FromQuery] int provinceId)
{
if (provinceId <= 0)
{
throw new BusinessException("请指定州省");
}
await GetProvinceOrThrowAsync(provinceId);
var cities = await CityRepository.ListByProvinceIdAsync(provinceId);
return cities.Select(ToCityOutput).ToList();
}
/// <summary>
/// 地址下拉:按州省 Id 返回城市选项(value=中文名)。
/// </summary>
[HttpGet("/system/country/city/options")]
public async Task<List<CountryCityOptionOutput>> GetCityOptionsAsync([FromQuery] int provinceId)
{
if (provinceId <= 0)
{
return [];
}
var cities = await CityRepository.ListByProvinceIdAsync(provinceId);
return cities.Select(x => new CountryCityOptionOutput
{
Id = x.Id,
Label = BuildLabel(x.ChineseName, x.EnglishName),
Value = x.ChineseName
}).ToList();
}
/// <summary>
/// 新增城市。同一州省下中文名业务唯一。
/// </summary>
[HttpPost("/system/country/city/create")]
public async Task CreateCityAsync([FromBody] CreateCountryCityInput input)
{
await GetProvinceOrThrowAsync(input.ProvinceId);
var name = NormalizeRequiredName(input.ChineseName, "城市中文名不能为空");
await EnsureCityNameUniqueAsync(input.ProvinceId, name, excludeId: null);
await CityRepository.InsertAsync(new CountryCity
{
ProvinceId = input.ProvinceId,
ChineseName = name,
EnglishName = (input.EnglishName ?? string.Empty).Trim(),
SortOrder = input.SortOrder
});
}
/// <summary>
/// 更新城市。
/// </summary>
[HttpPost("/system/country/city/update")]
public async Task UpdateCityAsync([FromBody] UpdateCountryCityInput input)
{
var entity = await GetCityOrThrowAsync(input.Id);
if (input.ProvinceId != entity.ProvinceId)
{
await GetProvinceOrThrowAsync(input.ProvinceId);
entity.ProvinceId = input.ProvinceId;
}
var name = NormalizeRequiredName(input.ChineseName, "城市中文名不能为空");
await EnsureCityNameUniqueAsync(entity.ProvinceId, name, excludeId: entity.Id);
entity.ChineseName = name;
entity.EnglishName = (input.EnglishName ?? string.Empty).Trim();
entity.SortOrder = input.SortOrder;
await CityRepository.UpdateAsync(entity);
}
/// <summary>
/// 删除城市(软删除)。
/// </summary>
[HttpPost("/system/country/city/delete")]
public async Task DeleteCityAsync([FromBody] IdInput input)
{
var entity = await GetCityOrThrowAsync(input.Id);
await CityRepository.DeleteAsync(entity);
}
private async Task<Country> GetCountryOrThrowAsync(int id)
{
var entity = await CountryRepository.FirstOrDefaultAsync(x => x.Id == id);
if (entity == null)
{
throw new BusinessException("国家不存在");
}
return entity;
}
private async Task<CountryProvince> GetProvinceOrThrowAsync(int id)
{
var entity = await ProvinceRepository.FirstOrDefaultAsync(x => x.Id == id);
if (entity == null)
{
throw new BusinessException("州省不存在");
}
return entity;
}
private async Task<CountryCity> GetCityOrThrowAsync(int id)
{
var entity = await CityRepository.FirstOrDefaultAsync(x => x.Id == id);
if (entity == null)
{
throw new BusinessException("城市不存在");
}
return entity;
}
private async Task EnsureProvinceNameUniqueAsync(int countryId, string chineseName, int? excludeId)
{
var hit = await ProvinceRepository.FindByCountryAndChineseNameAsync(countryId, chineseName);
if (hit != null && hit.Id != excludeId)
{
throw new BusinessException("该国家下州省中文名已存在");
}
}
private async Task EnsureCityNameUniqueAsync(int provinceId, string chineseName, int? excludeId)
{
var hit = await CityRepository.FindByProvinceAndChineseNameAsync(provinceId, chineseName);
if (hit != null && hit.Id != excludeId)
{
throw new BusinessException("该州省下城市中文名已存在");
}
}
private async Task<Dictionary<int, int>> LoadCityCountMapAsync(IEnumerable<int> provinceIds)
{
var ids = provinceIds.Distinct().ToArray();
if (ids.Length == 0)
{
return new Dictionary<int, int>();
}
var cities = await CityRepository.GetListAsync(x => ids.Contains(x.ProvinceId));
return cities
.GroupBy(x => x.ProvinceId)
.ToDictionary(g => g.Key, g => g.Count());
}
private static CountryProvinceOutput ToProvinceOutput(
CountryProvince x,
string countryCode,
IReadOnlyDictionary<int, int> cityCounts) =>
new()
{
Id = x.Id,
CountryId = x.CountryId,
CountryCode = countryCode,
ChineseName = x.ChineseName,
EnglishName = x.EnglishName,
ShortName = x.ShortName,
Lng = x.Lng,
Lat = x.Lat,
SortOrder = x.SortOrder,
CityCount = cityCounts.TryGetValue(x.Id, out var count) ? count : 0
};
private static CountryCityOutput ToCityOutput(CountryCity x) => new()
{
Id = x.Id,
ProvinceId = x.ProvinceId,
ChineseName = x.ChineseName,
EnglishName = x.EnglishName,
SortOrder = x.SortOrder
};
private static string NormalizeRequiredName(string? value, string emptyMessage)
{
var name = (value ?? string.Empty).Trim();
if (string.IsNullOrWhiteSpace(name))
{
throw new BusinessException(emptyMessage);
}
return name;
}
private static string? NullIfWhiteSpace(string? value)
{
var trimmed = value?.Trim();
return string.IsNullOrWhiteSpace(trimmed) ? null : trimmed;
}
private static string BuildLabel(string chineseName, string englishName)
{
if (string.IsNullOrWhiteSpace(englishName) || string.Equals(chineseName, englishName, StringComparison.OrdinalIgnoreCase))
{
return chineseName;
}
return $"{chineseName} / {englishName}";
}
}