20261119 #26

Merged
zzh merged 6 commits from test into master 2026-11-19 17:20:06 +08:00
11 changed files with 960 additions and 15 deletions
Showing only changes of commit 748afbf45b - Show all commits

View File

@ -0,0 +1,211 @@
-- =============================================================================
-- migrate_country_province_city_20261119.sql
-- 国家下州省 / 城市主数据(地址簿下拉 + 经营地图发件省归一)
-- 审计字段对齐 t_outbound_record;禁止 UNIQUE KEY;可重复执行。
-- =============================================================================
SET @db := DATABASE();
-- ---------- t_country_province ----------
SET @tbl := (
SELECT COUNT(1) FROM information_schema.TABLES
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_country_province'
);
SET @sql := IF(
@tbl = 0,
'CREATE TABLE `t_country_province` (
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
`CountryId` INT NOT NULL COMMENT ''所属国家 t_country.Id'',
`ChineseName` VARCHAR(64) NOT NULL COMMENT ''中文名(地图归一用,如 广东)'',
`EnglishName` VARCHAR(128) NOT NULL DEFAULT '''' COMMENT ''英文名'',
`ShortName` VARCHAR(16) NULL COMMENT ''简称,如 粤'',
`Lng` DECIMAL(10,6) NULL COMMENT ''中心经度'',
`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 ''并发戳'',
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
`UpdateUserId` INT NULL COMMENT ''更新人'',
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
PRIMARY KEY (`Id`),
KEY `ix_country_province_country` (`CountryId`),
KEY `ix_country_province_cn_name` (`ChineseName`)
) COMMENT=''国家州省主数据''',
'SELECT ''t_country_province already exists'' AS info'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
-- ---------- t_country_city ----------
SET @tbl := (
SELECT COUNT(1) FROM information_schema.TABLES
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_country_city'
);
SET @sql := IF(
@tbl = 0,
'CREATE TABLE `t_country_city` (
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
`ProvinceId` INT NOT NULL COMMENT ''所属州省 t_country_province.Id'',
`ChineseName` VARCHAR(64) NOT NULL COMMENT ''中文名'',
`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 ''并发戳'',
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
`UpdateUserId` INT NULL COMMENT ''更新人'',
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
PRIMARY KEY (`Id`),
KEY `ix_country_city_province` (`ProvinceId`),
KEY `ix_country_city_cn_name` (`ChineseName`)
) COMMENT=''国家城市主数据''',
'SELECT ''t_country_city already exists'' AS info'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
-- ---------- 种子:中国省/直辖市/自治区/特别行政区(仅当 CN 存在且尚无有效州省时) ----------
SET @cn_id := (
SELECT Id FROM t_country
WHERE IsDeleted = 0 AND UPPER(CountryCode) = 'CN'
ORDER BY 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,
EnglishName VARCHAR(128) NOT NULL,
ShortName VARCHAR(16) NULL,
Lng DECIMAL(10,6) NULL,
Lat DECIMAL(10,6) NULL,
SortOrder INT NOT NULL
);
INSERT INTO tmp_cn_province_seed (ChineseName, EnglishName, ShortName, Lng, Lat, SortOrder) VALUES
('北京', 'Beijing', '京', 116.400000, 39.900000, 10),
('天津', 'Tianjin', '津', 117.200000, 39.130000, 20),
('河北', 'Hebei', '冀', 114.480000, 38.030000, 30),
('山西', 'Shanxi', '晋', 112.550000, 37.870000, 40),
('内蒙古', 'Inner Mongolia', '蒙', 111.650000, 40.820000, 50),
('辽宁', 'Liaoning', '辽', 123.430000, 41.800000, 60),
('吉林', 'Jilin', '吉', 125.320000, 43.880000, 70),
('黑龙江', 'Heilongjiang', '黑', 126.630000, 45.750000, 80),
('上海', 'Shanghai', '沪', 121.470000, 31.230000, 90),
('江苏', 'Jiangsu', '苏', 118.780000, 32.060000, 100),
('浙江', 'Zhejiang', '浙', 120.150000, 30.280000, 110),
('安徽', 'Anhui', '皖', 117.280000, 31.860000, 120),
('福建', 'Fujian', '闽', 119.300000, 26.080000, 130),
('江西', 'Jiangxi', '赣', 115.890000, 28.680000, 140),
('山东', 'Shandong', '鲁', 117.000000, 36.650000, 150),
('河南', 'Henan', '豫', 113.650000, 34.760000, 160),
('湖北', 'Hubei', '鄂', 114.300000, 30.590000, 170),
('湖南', 'Hunan', '湘', 112.980000, 28.190000, 180),
('广东', 'Guangdong', '粤', 113.260000, 23.130000, 190),
('广西', 'Guangxi', '桂', 108.320000, 22.820000, 200),
('海南', 'Hainan', '琼', 110.350000, 20.020000, 210),
('重庆', 'Chongqing', '渝', 106.550000, 29.560000, 220),
('四川', 'Sichuan', '川', 104.060000, 30.670000, 230),
('贵州', 'Guizhou', '黔', 106.710000, 26.570000, 240),
('云南', 'Yunnan', '滇', 102.710000, 25.040000, 250),
('西藏', 'Tibet', '藏', 91.110000, 29.970000, 260),
('陕西', 'Shaanxi', '陕', 108.930000, 34.270000, 270),
('甘肃', 'Gansu', '甘', 103.820000, 36.060000, 280),
('青海', 'Qinghai', '青', 101.780000, 36.620000, 290),
('宁夏', 'Ningxia', '宁', 106.270000, 38.470000, 300),
('新疆', 'Xinjiang', '新', 87.620000, 43.820000, 310),
('台湾', 'Taiwan', '台', 121.500000, 25.030000, 320),
('香港', 'Hong Kong', '港', 114.170000, 22.320000, 330),
('澳门', 'Macao', '澳', 113.540000, 22.190000, 340);
INSERT INTO t_country_province (
CountryId, ChineseName, EnglishName, ShortName, Lng, Lat, SortOrder,
IsDeleted, CreateUserId, CreateTime
)
SELECT
@cn_id, s.ChineseName, s.EnglishName, s.ShortName, s.Lng, s.Lat, s.SortOrder,
0, 0, CURRENT_TIMESTAMP
FROM tmp_cn_province_seed s
WHERE @cn_id IS NOT NULL
AND @cn_province_count = 0;
DROP TEMPORARY TABLE IF EXISTS tmp_cn_city_seed;
CREATE TEMPORARY TABLE tmp_cn_city_seed (
ProvinceName VARCHAR(64) NOT NULL,
ChineseName VARCHAR(64) NOT NULL,
EnglishName VARCHAR(128) NOT NULL,
SortOrder INT NOT NULL
);
INSERT INTO tmp_cn_city_seed (ProvinceName, ChineseName, EnglishName, SortOrder) VALUES
('北京', '北京', 'Beijing', 10),
('天津', '天津', 'Tianjin', 10),
('河北', '石家庄', 'Shijiazhuang', 10),
('河北', '唐山', 'Tangshan', 20),
('山西', '太原', 'Taiyuan', 10),
('内蒙古', '呼和浩特', 'Hohhot', 10),
('辽宁', '沈阳', 'Shenyang', 10),
('辽宁', '大连', 'Dalian', 20),
('吉林', '长春', 'Changchun', 10),
('黑龙江', '哈尔滨', 'Harbin', 10),
('上海', '上海', 'Shanghai', 10),
('江苏', '南京', 'Nanjing', 10),
('江苏', '苏州', 'Suzhou', 20),
('江苏', '无锡', 'Wuxi', 30),
('浙江', '杭州', 'Hangzhou', 10),
('浙江', '宁波', 'Ningbo', 20),
('浙江', '义乌', 'Yiwu', 30),
('安徽', '合肥', 'Hefei', 10),
('福建', '福州', 'Fuzhou', 10),
('福建', '厦门', 'Xiamen', 20),
('江西', '南昌', 'Nanchang', 10),
('山东', '济南', 'Jinan', 10),
('山东', '青岛', 'Qingdao', 20),
('河南', '郑州', 'Zhengzhou', 10),
('湖北', '武汉', 'Wuhan', 10),
('湖南', '长沙', 'Changsha', 10),
('广东', '广州', 'Guangzhou', 10),
('广东', '深圳', 'Shenzhen', 20),
('广东', '东莞', 'Dongguan', 30),
('广东', '佛山', 'Foshan', 40),
('广西', '南宁', 'Nanning', 10),
('海南', '海口', 'Haikou', 10),
('重庆', '重庆', 'Chongqing', 10),
('四川', '成都', 'Chengdu', 10),
('贵州', '贵阳', 'Guiyang', 10),
('云南', '昆明', 'Kunming', 10),
('西藏', '拉萨', 'Lhasa', 10),
('陕西', '西安', 'Xian', 10),
('甘肃', '兰州', 'Lanzhou', 10),
('青海', '西宁', 'Xining', 10),
('宁夏', '银川', 'Yinchuan', 10),
('新疆', '乌鲁木齐', 'Urumqi', 10),
('台湾', '台北', 'Taipei', 10),
('香港', '香港', 'Hong Kong', 10),
('澳门', '澳门', 'Macao', 10);
-- 仅当刚种子了州省(或 CN 下仍无城市)时补城市:以「该省尚无有效城市」为条件逐省插入
INSERT INTO t_country_city (
ProvinceId, ChineseName, EnglishName, SortOrder,
IsDeleted, CreateUserId, CreateTime
)
SELECT
p.Id, s.ChineseName, s.EnglishName, s.SortOrder,
0, 0, CURRENT_TIMESTAMP
FROM tmp_cn_city_seed s
INNER JOIN t_country_province p
ON p.IsDeleted = 0
AND p.CountryId = @cn_id
AND p.ChineseName = s.ProvinceName
WHERE @cn_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM t_country_city c
WHERE c.IsDeleted = 0 AND c.ProvinceId = p.Id
);
DROP TEMPORARY TABLE IF EXISTS tmp_cn_province_seed;
DROP TEMPORARY TABLE IF EXISTS tmp_cn_city_seed;

View File

@ -62,14 +62,26 @@ public class CreateCustomerSenderAddressInput
[StringLength(255)]
public string? Company { get; set; }
/// <summary>
/// 国家二字码(必填,取自国家主数据)。
/// </summary>
[Required]
[StringLength(8)]
public string? CountryCode { get; set; }
public string CountryCode { get; set; } = string.Empty;
/// <summary>
/// 省/州中文名(必填,取自国家州省主数据)。
/// </summary>
[Required]
[StringLength(50)]
public string? Province { get; set; }
public string Province { get; set; } = string.Empty;
/// <summary>
/// 城市中文名(必填,取自国家城市主数据)。
/// </summary>
[Required]
[StringLength(50)]
public string? City { get; set; }
public string City { get; set; } = string.Empty;
[StringLength(50)]
public string? ZipCode { get; set; }

View File

@ -0,0 +1,164 @@
using System.ComponentModel.DataAnnotations;
namespace Oms.Application.Dtos.System;
/// <summary>
/// 州省列表项。
/// </summary>
public class CountryProvinceOutput
{
/// <summary>主键。</summary>
public int Id { get; set; }
/// <summary>所属国家 Id。</summary>
public int CountryId { get; set; }
/// <summary>国家二字码。</summary>
public string CountryCode { get; set; } = string.Empty;
/// <summary>中文名。</summary>
public string ChineseName { get; set; } = string.Empty;
/// <summary>英文名。</summary>
public string EnglishName { get; set; } = string.Empty;
/// <summary>简称。</summary>
public string? ShortName { get; set; }
/// <summary>中心经度。</summary>
public decimal? Lng { get; set; }
/// <summary>中心纬度。</summary>
public decimal? Lat { get; set; }
/// <summary>排序。</summary>
public int SortOrder { get; set; }
/// <summary>下属城市数量。</summary>
public int CityCount { get; set; }
}
/// <summary>
/// 城市列表项。
/// </summary>
public class CountryCityOutput
{
/// <summary>主键。</summary>
public int Id { get; set; }
/// <summary>所属州省 Id。</summary>
public int ProvinceId { get; set; }
/// <summary>中文名。</summary>
public string ChineseName { get; set; } = string.Empty;
/// <summary>英文名。</summary>
public string EnglishName { get; set; } = string.Empty;
/// <summary>排序。</summary>
public int SortOrder { get; set; }
}
/// <summary>
/// 地址下拉:州省选项。
/// </summary>
public class CountryProvinceOptionOutput
{
/// <summary>州省 Id。</summary>
public int Id { get; set; }
/// <summary>展示名(优先中文)。</summary>
public string Label { get; set; } = string.Empty;
/// <summary>写入地址快照的中文名。</summary>
public string Value { get; set; } = string.Empty;
}
/// <summary>
/// 地址下拉:城市选项。
/// </summary>
public class CountryCityOptionOutput
{
/// <summary>城市 Id。</summary>
public int Id { get; set; }
/// <summary>展示名。</summary>
public string Label { get; set; } = string.Empty;
/// <summary>写入地址快照的中文名。</summary>
public string Value { get; set; } = string.Empty;
}
/// <summary>
/// 新增州省。
/// </summary>
public class CreateCountryProvinceInput
{
/// <summary>所属国家 Id。</summary>
[Required]
public int CountryId { get; set; }
/// <summary>中文名。</summary>
[Required]
[StringLength(64)]
public string ChineseName { get; set; } = string.Empty;
/// <summary>英文名。</summary>
[StringLength(128)]
public string EnglishName { get; set; } = string.Empty;
/// <summary>简称。</summary>
[StringLength(16)]
public string? ShortName { get; set; }
/// <summary>中心经度。</summary>
public decimal? Lng { get; set; }
/// <summary>中心纬度。</summary>
public decimal? Lat { get; set; }
/// <summary>排序。</summary>
public int SortOrder { get; set; } = 100;
}
/// <summary>
/// 更新州省。
/// </summary>
public class UpdateCountryProvinceInput : CreateCountryProvinceInput
{
/// <summary>主键。</summary>
[Required]
public int Id { get; set; }
}
/// <summary>
/// 新增城市。
/// </summary>
public class CreateCountryCityInput
{
/// <summary>所属州省 Id。</summary>
[Required]
public int ProvinceId { get; set; }
/// <summary>中文名。</summary>
[Required]
[StringLength(64)]
public string ChineseName { get; set; } = string.Empty;
/// <summary>英文名。</summary>
[StringLength(128)]
public string EnglishName { get; set; } = string.Empty;
/// <summary>排序。</summary>
public int SortOrder { get; set; } = 100;
}
/// <summary>
/// 更新城市。
/// </summary>
public class UpdateCountryCityInput : CreateCountryCityInput
{
/// <summary>主键。</summary>
[Required]
public int Id { get; set; }
}

View File

@ -7,6 +7,7 @@ using Oms.Application.Shared;
using Oms.Domain.OrdersAggregate.Consts;
using Oms.Domain.OrdersAggregate.Entities;
using Oms.Domain.OrdersAggregate.Repositories;
using Oms.Domain.SystemAggregate.Repositories;
namespace Oms.Application.Services.Orders;
@ -71,8 +72,7 @@ public partial class OrderService
CurrentUser,
input.CustomerId);
var addressType = NormalizeAddressTypeOrThrow(input.AddressType);
ValidateSenderAddressInput(input);
var countryId = await ResolveSenderCountryIdAsync(input.CountryCode);
var (countryId, provinceName, cityName) = await ValidateAndNormalizeSenderAddressRegionAsync(input);
if (input.IsDefault)
{
@ -87,8 +87,8 @@ public partial class OrderService
SenderName = input.SenderName.Trim(),
Company = TrimOrNull(input.Company),
Country = countryId,
Province = TrimOrNull(input.Province),
City = TrimOrNull(input.City),
Province = provinceName,
City = cityName,
ZipCode = TrimOrNull(input.ZipCode),
StreetAddress1 = input.StreetAddress1.Trim(),
StreetAddress2 = TrimOrNull(input.StreetAddress2),
@ -112,8 +112,7 @@ public partial class OrderService
{
var entity = await GetOwnedSenderAddressOrThrowAsync(input.Id, input.CustomerId);
var addressType = NormalizeAddressTypeOrThrow(input.AddressType);
ValidateSenderAddressInput(input);
var countryId = await ResolveSenderCountryIdAsync(input.CountryCode);
var (countryId, provinceName, cityName) = await ValidateAndNormalizeSenderAddressRegionAsync(input);
if (input.IsDefault)
{
@ -125,8 +124,8 @@ public partial class OrderService
entity.SenderName = input.SenderName.Trim();
entity.Company = TrimOrNull(input.Company);
entity.Country = countryId;
entity.Province = TrimOrNull(input.Province);
entity.City = TrimOrNull(input.City);
entity.Province = provinceName;
entity.City = cityName;
entity.ZipCode = TrimOrNull(input.ZipCode);
entity.StreetAddress1 = input.StreetAddress1.Trim();
entity.StreetAddress2 = TrimOrNull(input.StreetAddress2);
@ -209,11 +208,64 @@ public partial class OrderService
}
}
private async Task<int?> ResolveSenderCountryIdAsync(string? countryCode)
/// <summary>
/// 校验联系人/街道,并把国家、州省、城市归一到主数据中文名(必填下拉)。
/// </summary>
private async Task<(int CountryId, string Province, string City)> ValidateAndNormalizeSenderAddressRegionAsync(
CreateCustomerSenderAddressInput input)
{
var code = string.IsNullOrWhiteSpace(countryCode) ? "CN" : countryCode.Trim();
var country = await GetCountryOrThrowAsync(code, "国家不存在");
return country.Id;
ValidateSenderAddressInput(input);
if (string.IsNullOrWhiteSpace(input.CountryCode))
{
throw new BusinessException("国家二字码不能为空");
}
if (string.IsNullOrWhiteSpace(input.Province))
{
throw new BusinessException("省/州不能为空");
}
if (string.IsNullOrWhiteSpace(input.City))
{
throw new BusinessException("城市不能为空");
}
var country = await GetCountryOrThrowAsync(input.CountryCode.Trim(), "国家不存在");
var provinceRepo = LazyServiceProvider.GetRequiredService<ICountryProvinceRepository>();
var cityRepo = LazyServiceProvider.GetRequiredService<ICountryCityRepository>();
var provinces = await provinceRepo.ListByCountryIdAsync(country.Id);
if (provinces.Count == 0)
{
throw new BusinessException("该国家尚未维护州省,请先在「国家地区」中配置");
}
var provinceName = input.Province.Trim();
var province = provinces.FirstOrDefault(x =>
string.Equals(x.ChineseName, provinceName, StringComparison.OrdinalIgnoreCase)
|| string.Equals(x.EnglishName, provinceName, StringComparison.OrdinalIgnoreCase));
if (province == null)
{
throw new BusinessException("省/州不在主数据中,请从下拉选择");
}
var cities = await cityRepo.ListByProvinceIdAsync(province.Id);
if (cities.Count == 0)
{
throw new BusinessException("该州省尚未维护城市,请先在「国家地区」中配置");
}
var cityName = input.City.Trim();
var city = cities.FirstOrDefault(x =>
string.Equals(x.ChineseName, cityName, StringComparison.OrdinalIgnoreCase)
|| string.Equals(x.EnglishName, cityName, StringComparison.OrdinalIgnoreCase));
if (city == null)
{
throw new BusinessException("城市不在主数据中,请从下拉选择");
}
return (country.Id, province.ChineseName, city.ChineseName);
}
private static Expression<Func<CustomerSenderAddress, bool>> BuildSenderAddressPredicate(

View File

@ -0,0 +1,336 @@
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}";
}
}

View File

@ -0,0 +1,31 @@
using Oms.Domain.Shared;
using SqlSugar;
namespace Oms.Domain.SystemAggregate.Entities;
/// <summary>
/// 州省下城市主数据。
/// </summary>
[SugarTable("t_country_city")]
public class CountryCity : OmsAuditedAggregateRoot
{
/// <summary>
/// 所属州省 Id。
/// </summary>
public int ProvinceId { get; set; }
/// <summary>
/// 中文名。
/// </summary>
public string ChineseName { get; set; } = string.Empty;
/// <summary>
/// 英文名。
/// </summary>
public string EnglishName { get; set; } = string.Empty;
/// <summary>
/// 排序,越小越前。
/// </summary>
public int SortOrder { get; set; } = 100;
}

View File

@ -0,0 +1,49 @@
using Oms.Domain.Shared;
using SqlSugar;
namespace Oms.Domain.SystemAggregate.Entities;
/// <summary>
/// 国家下州省主数据。
/// </summary>
[SugarTable("t_country_province")]
public class CountryProvince : OmsAuditedAggregateRoot
{
/// <summary>
/// 所属国家 Id。
/// </summary>
public int CountryId { get; set; }
/// <summary>
/// 中文名(地址快照与地图归一用,如「广东」)。
/// </summary>
public string ChineseName { get; set; } = string.Empty;
/// <summary>
/// 英文名。
/// </summary>
public string EnglishName { get; set; } = string.Empty;
/// <summary>
/// 简称,如「粤」。
/// </summary>
[SugarColumn(IsNullable = true, Length = 16)]
public string? ShortName { get; set; }
/// <summary>
/// 中心经度。
/// </summary>
[SugarColumn(IsNullable = true, DecimalDigits = 6, Length = 10)]
public decimal? Lng { get; set; }
/// <summary>
/// 中心纬度。
/// </summary>
[SugarColumn(IsNullable = true, DecimalDigits = 6, Length = 10)]
public decimal? Lat { get; set; }
/// <summary>
/// 排序,越小越前。
/// </summary>
public int SortOrder { get; set; } = 100;
}

View File

@ -0,0 +1,14 @@
using Fake.Domain.Repositories;
using Oms.Domain.SystemAggregate.Entities;
namespace Oms.Domain.SystemAggregate.Repositories;
public interface ICountryCityRepository : IRepository<CountryCity>
{
Task<List<CountryCity>> ListByProvinceIdAsync(int provinceId, CancellationToken cancellationToken = default);
Task<CountryCity?> FindByProvinceAndChineseNameAsync(
int provinceId,
string chineseName,
CancellationToken cancellationToken = default);
}

View File

@ -0,0 +1,14 @@
using Fake.Domain.Repositories;
using Oms.Domain.SystemAggregate.Entities;
namespace Oms.Domain.SystemAggregate.Repositories;
public interface ICountryProvinceRepository : IRepository<CountryProvince>
{
Task<List<CountryProvince>> ListByCountryIdAsync(int countryId, CancellationToken cancellationToken = default);
Task<CountryProvince?> FindByCountryAndChineseNameAsync(
int countryId,
string chineseName,
CancellationToken cancellationToken = default);
}

View File

@ -0,0 +1,31 @@
using Fake.DependencyInjection;
using Oms.Domain.SystemAggregate.Entities;
using Oms.Domain.SystemAggregate.Repositories;
using Oms.SqlSugarCore.Repositories;
namespace Oms.SqlSugarCore.System;
public class CountryCityRepository : OmsSqlSugarRepository<CountryCity>, ICountryCityRepository, IScopedDependency
{
public async Task<List<CountryCity>> ListByProvinceIdAsync(
int provinceId,
CancellationToken cancellationToken = default)
{
var list = await GetListAsync(x => x.ProvinceId == provinceId, cancellationToken: cancellationToken);
return list
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.ChineseName)
.ToList();
}
public Task<CountryCity?> FindByProvinceAndChineseNameAsync(
int provinceId,
string chineseName,
CancellationToken cancellationToken = default)
{
var name = chineseName?.Trim() ?? string.Empty;
return FirstOrDefaultAsync(
x => x.ProvinceId == provinceId && x.ChineseName == name,
cancellationToken);
}
}

View File

@ -0,0 +1,31 @@
using Fake.DependencyInjection;
using Oms.Domain.SystemAggregate.Entities;
using Oms.Domain.SystemAggregate.Repositories;
using Oms.SqlSugarCore.Repositories;
namespace Oms.SqlSugarCore.System;
public class CountryProvinceRepository : OmsSqlSugarRepository<CountryProvince>, ICountryProvinceRepository, IScopedDependency
{
public async Task<List<CountryProvince>> ListByCountryIdAsync(
int countryId,
CancellationToken cancellationToken = default)
{
var list = await GetListAsync(x => x.CountryId == countryId, cancellationToken: cancellationToken);
return list
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.ChineseName)
.ToList();
}
public Task<CountryProvince?> FindByCountryAndChineseNameAsync(
int countryId,
string chineseName,
CancellationToken cancellationToken = default)
{
var name = chineseName?.Trim() ?? string.Empty;
return FirstOrDefaultAsync(
x => x.CountryId == countryId && x.ChineseName == name,
cancellationToken);
}
}