From 72a1a3590e2a3e8f08a9cfd43b966ab99fd9325d Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Thu, 19 Nov 2026 11:24:06 +0800 Subject: [PATCH 1/6] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E7=BB=8F?= =?UTF-8?q?=E8=90=A5=E5=9C=B0=E5=9B=BE=E5=B7=A5=E4=BD=9C=E5=8F=B0=E7=BB=9F?= =?UTF-8?q?=E8=AE=A1=E6=8E=A5=E5=8F=A3=EF=BC=88=E4=BA=A7=E5=93=81/?= =?UTF-8?q?=E5=9B=BD=E5=AE=B6=E7=BA=BF=E8=B7=AF=E4=B8=8E=E7=83=AD=E5=8A=9B?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- .../Dtos/Orders/BizOpsOverviewOutput.cs | 160 +++++ .../Services/Orders/OrderService.BizOps.cs | 560 ++++++++++++++++++ .../BizOpsOrderProjectionRow.cs | 43 ++ .../Repositories/IOrderRepository.cs | 16 + .../Orders/OrderRepository.cs | 130 ++++ 5 files changed, 909 insertions(+) create mode 100644 src/Oms.Application/Dtos/Orders/BizOpsOverviewOutput.cs create mode 100644 src/Oms.Application/Services/Orders/OrderService.BizOps.cs create mode 100644 src/Oms.Domain/OrdersAggregate/BizOpsOrderProjectionRow.cs diff --git a/src/Oms.Application/Dtos/Orders/BizOpsOverviewOutput.cs b/src/Oms.Application/Dtos/Orders/BizOpsOverviewOutput.cs new file mode 100644 index 0000000..070d943 --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/BizOpsOverviewOutput.cs @@ -0,0 +1,160 @@ +namespace Oms.Application.Dtos.Orders; + +/// +/// 经营地图工作台总览。 +/// +public class BizOpsOverviewOutput +{ + /// 统计天数:7 / 30 / 90。 + public int RangeDays { get; set; } + + /// 线路维度:product=销售产品,country=目的国。 + public string LaneDim { get; set; } = "product"; + + /// 本期起(含)。 + public DateTime PeriodStart { get; set; } + + /// 本期止(不含)。 + public DateTime PeriodEndExclusive { get; set; } + + /// 失败时效告警阈值(天)。 + public decimal FailDaysThreshold { get; set; } + + /// 毛利率偏低阈值(0-1)。 + public decimal MarginRateThreshold { get; set; } + + /// 客户汇总。 + public BizOpsCustomerSummaryOutput CustomerSummary { get; set; } = new(); + + /// 收件侧订单状态角标(当前快照)。 + public BizOpsOrderStatusSnapshotOutput OrderStatusSnapshot { get; set; } = new(); + + /// 中国发件省热力。 + public List Provinces { get; set; } = []; + + /// 发件城市热点。 + public List Cities { get; set; } = []; + + /// 目的国热力。 + public List Countries { get; set; } = []; + + /// 重点线路(按维度)。 + public List Lanes { get; set; } = []; + + /// 线路合计(本期)。 + public BizOpsLaneTotalsOutput Totals { get; set; } = new(); + + /// 线路合计(上期,用于环比)。 + public BizOpsLaneTotalsOutput PreviousTotals { get; set; } = new(); +} + +/// 客户汇总。 +public class BizOpsCustomerSummaryOutput +{ + public int Total { get; set; } + public int Neu { get; set; } + public int Online { get; set; } + public int Idle7 { get; set; } + public decimal? NeuGrowthPercent { get; set; } +} + +/// 订单状态快照(收件图角标)。 +public class BizOpsOrderStatusSnapshotOutput +{ + public int Total { get; set; } + public int Predeclared { get; set; } + public int PendingPayment { get; set; } + public int PendingShip { get; set; } +} + +/// 省域统计。 +public class BizOpsProvinceStatOutput +{ + public string Name { get; set; } = string.Empty; + public string Short { get; set; } = string.Empty; + public double[] Center { get; set; } = []; + public int OrderCount { get; set; } + public int CustomerTotal { get; set; } + public int CustomerNew { get; set; } + public int CustomerOnline { get; set; } + public int CustomerIdle7 { get; set; } +} + +/// 城市热点。 +public class BizOpsCityHotspotOutput +{ + public string Name { get; set; } = string.Empty; + public string Province { get; set; } = string.Empty; + public double[] Value { get; set; } = []; +} + +/// 目的国统计。 +public class BizOpsCountryStatOutput +{ + /// geoJSON 英文名(前端着色用)。 + public string Name { get; set; } = string.Empty; + public string NameZh { get; set; } = string.Empty; + public string Code { get; set; } = string.Empty; + public double[] Center { get; set; } = []; + public int OrderCount { get; set; } + public decimal AvgDays { get; set; } + public decimal SuccessRate { get; set; } +} + +/// 线路统计。 +public class BizOpsLaneStatOutput +{ + public string Id { get; set; } = string.Empty; + + /// product | country。 + public string Dim { get; set; } = "product"; + + /// 销售产品编码(产品维度)。 + public string? ProductCode { get; set; } + + /// 销售产品名称或国家展示名。 + public string Label { get; set; } = string.Empty; + + /// 短标签(表行左侧)。 + public string ShortLabel { get; set; } = string.Empty; + + public string? FromProvince { get; set; } + public string? FromShort { get; set; } + public double[]? FromCenter { get; set; } + + public string? ToCountryCode { get; set; } + public string? ToCountryName { get; set; } + public string? ToCountryNameZh { get; set; } + public double[]? ToCenter { get; set; } + + public decimal AvgSuccessDays { get; set; } + public decimal AvgFailDays { get; set; } + public int OrderCount { get; set; } + public decimal SuccessRate { get; set; } + public decimal Revenue { get; set; } + public decimal Cost { get; set; } + public decimal GrossProfit { get; set; } + public decimal MarginRate { get; set; } + + /// 近 30 日均时效(天)。 + public List DailyAvg { get; set; } = []; + + /// 近 30 日毛利。 + public List DailyProfit { get; set; } = []; + + public decimal? OrderCountGrowthPercent { get; set; } + public decimal? RevenueGrowthPercent { get; set; } + public decimal? GrossProfitGrowthPercent { get; set; } +} + +/// 线路合计。 +public class BizOpsLaneTotalsOutput +{ + public int OrderCount { get; set; } + public decimal Revenue { get; set; } + public decimal Cost { get; set; } + public decimal GrossProfit { get; set; } + public decimal? RevenueGrowthPercent { get; set; } + public decimal? GrossProfitGrowthPercent { get; set; } + public decimal? OrderCountGrowthPercent { get; set; } +} diff --git a/src/Oms.Application/Services/Orders/OrderService.BizOps.cs b/src/Oms.Application/Services/Orders/OrderService.BizOps.cs new file mode 100644 index 0000000..d72f69b --- /dev/null +++ b/src/Oms.Application/Services/Orders/OrderService.BizOps.cs @@ -0,0 +1,560 @@ +using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Orders; +using Oms.Domain.CustomersAggregate.Enums; +using Oms.Domain.OrdersAggregate; +using Oms.Domain.OrdersAggregate.Consts; + +namespace Oms.Application.Services.Orders; + +public partial class OrderService +{ + private static readonly Dictionary ProvinceMeta = + new(StringComparer.OrdinalIgnoreCase) + { + ["广东"] = ("粤", 113.26, 23.13), + ["浙江"] = ("浙", 120.15, 30.28), + ["江苏"] = ("苏", 118.78, 32.06), + ["上海"] = ("沪", 121.47, 31.23), + ["福建"] = ("闽", 119.3, 26.08), + ["山东"] = ("鲁", 117.0, 36.65), + ["北京"] = ("京", 116.4, 39.9), + ["四川"] = ("川", 104.06, 30.67), + ["湖北"] = ("鄂", 114.3, 30.59), + ["湖南"] = ("湘", 112.98, 28.19), + ["河南"] = ("豫", 113.65, 34.76), + ["安徽"] = ("皖", 117.28, 31.86), + ["江西"] = ("赣", 115.89, 28.68), + ["河北"] = ("冀", 114.48, 38.03), + ["辽宁"] = ("辽", 123.43, 41.8), + ["陕西"] = ("陕", 108.93, 34.27), + ["云南"] = ("滇", 102.71, 25.04), + ["广西"] = ("桂", 108.32, 22.82), + ["重庆"] = ("渝", 106.55, 29.56), + ["天津"] = ("津", 117.2, 39.13), + ["山西"] = ("晋", 112.55, 37.87), + ["黑龙江"] = ("黑", 126.63, 45.75), + ["吉林"] = ("吉", 125.32, 43.88), + ["内蒙古"] = ("蒙", 111.65, 40.82), + ["贵州"] = ("黔", 106.71, 26.57), + ["甘肃"] = ("甘", 103.82, 36.06), + ["青海"] = ("青", 101.78, 36.62), + ["宁夏"] = ("宁", 106.27, 38.47), + ["新疆"] = ("新", 87.62, 43.82), + ["西藏"] = ("藏", 91.11, 29.97), + ["海南"] = ("琼", 110.35, 20.02), + ["台湾"] = ("台", 121.5, 25.03), + ["香港"] = ("港", 114.17, 22.32), + ["澳门"] = ("澳", 113.54, 22.19), + }; + + private static readonly Dictionary CountryMeta = + new(StringComparer.OrdinalIgnoreCase) + { + ["US"] = ("United States", "美国", -95.7, 37.1), + ["GB"] = ("United Kingdom", "英国", -1.17, 52.35), + ["UK"] = ("United Kingdom", "英国", -1.17, 52.35), + ["DE"] = ("Germany", "德国", 10.45, 51.16), + ["FR"] = ("France", "法国", 2.21, 46.22), + ["JP"] = ("Japan", "日本", 138.25, 36.2), + ["AU"] = ("Australia", "澳大利亚", 133.77, -25.27), + ["CA"] = ("Canada", "加拿大", -106.3, 56.1), + ["SG"] = ("Singapore", "新加坡", 103.82, 1.35), + ["MY"] = ("Malaysia", "马来西亚", 101.98, 4.21), + ["TH"] = ("Thailand", "泰国", 100.99, 15.87), + ["KR"] = ("Korea", "韩国", 127.76, 35.9), + ["IT"] = ("Italy", "意大利", 12.56, 41.87), + ["ES"] = ("Spain", "西班牙", -3.74, 40.46), + ["NL"] = ("Netherlands", "荷兰", 5.29, 52.13), + ["BR"] = ("Brazil", "巴西", -51.92, -14.23), + ["MX"] = ("Mexico", "墨西哥", -102.55, 23.63), + ["AE"] = ("United Arab Emirates", "阿联酋", 53.84, 23.42), + ["IN"] = ("India", "印度", 78.96, 20.59), + ["NZ"] = ("New Zealand", "新西兰", 174.89, -40.9), + ["RU"] = ("Russia", "俄罗斯", 105.32, 61.52), + ["PH"] = ("Philippines", "菲律宾", 121.77, 12.88), + ["ID"] = ("Indonesia", "印度尼西亚", 113.92, -0.79), + ["VN"] = ("Vietnam", "越南", 108.28, 14.06), + }; + + /// + /// 经营地图工作台总览:发件省/目的国热力、销售产品或国家线路时效与营收毛利。 + /// + /// 统计天数:7 / 30 / 90,默认 30。 + /// 线路维度:product=销售产品,country=目的国。 + /// 失败时效告警阈值(天),默认 18。 + /// 毛利率偏低阈值(0-1),默认 0.18。 + [HttpGet("/order/biz-ops-overview")] + public async Task GetBizOpsOverviewAsync( + [FromQuery] int rangeDays = 30, + [FromQuery] string? laneDim = "product", + [FromQuery] decimal failDaysThreshold = 18m, + [FromQuery] decimal marginRateThreshold = 0.18m) + { + rangeDays = rangeDays switch + { + 7 or 30 or 90 => rangeDays, + _ => 30, + }; + var dim = string.Equals(laneDim, "country", StringComparison.OrdinalIgnoreCase) + ? "country" + : "product"; + failDaysThreshold = Math.Clamp(failDaysThreshold, 1m, 90m); + marginRateThreshold = Math.Clamp(marginRateThreshold, 0.01m, 0.9m); + + var (filter, _) = await BuildScopedListFilterAsync(); + var today = DateTime.Today; + var endExclusive = today.AddDays(1); + var periodStart = today.AddDays(1 - rangeDays); + var previousStart = periodStart.AddDays(-rangeDays); + var previousEnd = periodStart; + + var currentRows = await OrderRepository.ListBizOpsProjectionsByCreateTimeRangeAsync( + filter, periodStart, endExclusive); + var previousRows = await OrderRepository.ListBizOpsProjectionsByCreateTimeRangeAsync( + filter, previousStart, previousEnd); + + var currentFees = await OrderRepository.SumFeesByOrderIdsAsync(currentRows.Select(x => x.Id)); + var previousFees = await OrderRepository.SumFeesByOrderIdsAsync(previousRows.Select(x => x.Id)); + var feeMap = currentFees.ToDictionary(x => x.OrderId); + var prevFeeMap = previousFees.ToDictionary(x => x.OrderId); + + var productNames = await LoadProductNameMapAsync(currentRows); + + var statusRows = await OrderRepository.GetStatusCountsByFilterAsync(filter); + var statusCounts = statusRows + .Where(x => !string.Equals(x.Status, OrderStatusCodes.Deleted, StringComparison.OrdinalIgnoreCase)) + .ToDictionary(x => x.Status, x => x.Count, StringComparer.OrdinalIgnoreCase); + int StatusCount(string code) => + statusCounts.TryGetValue(code, out var n) ? n : 0; + + var customerSummary = await BuildBizOpsCustomerSummaryAsync(periodStart, endExclusive, previousStart, previousEnd); + + var provinces = BuildProvinceStats(currentRows); + var cities = BuildCityHotspots(currentRows); + var countries = BuildCountryStats(currentRows); + + var currentLanes = BuildLanes(currentRows, feeMap, productNames, dim, periodStart); + var previousLaneMap = BuildLanes(previousRows, prevFeeMap, productNames, dim, previousStart) + .ToDictionary(x => x.Id, StringComparer.OrdinalIgnoreCase); + + foreach (var lane in currentLanes) + { + if (!previousLaneMap.TryGetValue(lane.Id, out var prev)) + { + continue; + } + + lane.OrderCountGrowthPercent = CalcGrowthPercent(lane.OrderCount, prev.OrderCount); + lane.RevenueGrowthPercent = CalcGrowthPercentDecimal(lane.Revenue, prev.Revenue); + lane.GrossProfitGrowthPercent = CalcGrowthPercentDecimal(lane.GrossProfit, prev.GrossProfit); + } + + var totals = SumLaneTotals(currentLanes); + var previousTotals = SumLaneTotals(previousLaneMap.Values); + totals.OrderCountGrowthPercent = CalcGrowthPercent(totals.OrderCount, previousTotals.OrderCount); + totals.RevenueGrowthPercent = CalcGrowthPercentDecimal(totals.Revenue, previousTotals.Revenue); + totals.GrossProfitGrowthPercent = CalcGrowthPercentDecimal(totals.GrossProfit, previousTotals.GrossProfit); + + return new BizOpsOverviewOutput + { + RangeDays = rangeDays, + LaneDim = dim, + PeriodStart = periodStart, + PeriodEndExclusive = endExclusive, + FailDaysThreshold = failDaysThreshold, + MarginRateThreshold = marginRateThreshold, + CustomerSummary = customerSummary, + OrderStatusSnapshot = new BizOpsOrderStatusSnapshotOutput + { + Total = statusCounts.Values.Sum(), + Predeclared = StatusCount(OrderStatusCodes.Predeclared), + PendingPayment = StatusCount(OrderStatusCodes.PendingPayment), + PendingShip = StatusCount(OrderStatusCodes.PendingShip), + }, + Provinces = provinces, + Cities = cities, + Countries = countries, + Lanes = currentLanes, + Totals = totals, + PreviousTotals = previousTotals, + }; + } + + private async Task> LoadProductNameMapAsync( + List rows) + { + var codes = rows + .Select(x => x.ProductCode?.Trim()) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + if (codes.Count == 0) + { + return new Dictionary(StringComparer.OrdinalIgnoreCase); + } + + var products = await SalesProductRepository.GetListAsync(x => codes.Contains(x.ProductCode)); + return products + .GroupBy(x => x.ProductCode, StringComparer.OrdinalIgnoreCase) + .ToDictionary( + g => g.Key, + g => string.IsNullOrWhiteSpace(g.First().ProductName) ? g.Key : g.First().ProductName, + StringComparer.OrdinalIgnoreCase); + } + + private async Task BuildBizOpsCustomerSummaryAsync( + DateTime periodStart, + DateTime endExclusive, + DateTime previousStart, + DateTime previousEnd) + { + var total = await CustomerRepository.CountAsync(x => x.Status == CustomerStatus.Normal); + var neu = await CustomerRepository.CountAsync( + x => x.Status == CustomerStatus.Normal + && x.CreateTime >= periodStart + && x.CreateTime < endExclusive); + var prevNeu = await CustomerRepository.CountAsync( + x => x.Status == CustomerStatus.Normal + && x.CreateTime >= previousStart + && x.CreateTime < previousEnd); + var online = await CustomerRepository.CountAsync( + x => x.Status == CustomerStatus.Normal + && x.LastLoginTime != null + && x.LastLoginTime >= DateTime.Now.AddMinutes(-30)); + var idle7 = await CustomerRepository.CountAsync( + x => x.Status == CustomerStatus.Normal + && (x.LastLoginTime == null || x.LastLoginTime < DateTime.Today.AddDays(-7))); + + return new BizOpsCustomerSummaryOutput + { + Total = total, + Neu = neu, + Online = online, + Idle7 = idle7, + NeuGrowthPercent = CalcGrowthPercent(neu, prevNeu), + }; + } + + private static List BuildProvinceStats(List rows) + { + return rows + .Select(x => NormalizeProvince(x.SenderProvince)) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .GroupBy(x => x!, StringComparer.OrdinalIgnoreCase) + .Select(g => + { + var name = g.Key; + ProvinceMeta.TryGetValue(name, out var meta); + return new BizOpsProvinceStatOutput + { + Name = name, + Short = string.IsNullOrWhiteSpace(meta.Short) ? name[..Math.Min(1, name.Length)] : meta.Short, + Center = meta.Lng == 0 && meta.Lat == 0 ? [] : [meta.Lng, meta.Lat], + OrderCount = g.Count(), + CustomerTotal = 0, + CustomerNew = 0, + CustomerOnline = 0, + CustomerIdle7 = 0, + }; + }) + .OrderByDescending(x => x.OrderCount) + .ToList(); + } + + private static List BuildCityHotspots(List rows) + { + return rows + .Where(x => !string.IsNullOrWhiteSpace(x.SenderCity)) + .GroupBy(x => new + { + City = x.SenderCity!.Trim(), + Province = NormalizeProvince(x.SenderProvince) ?? string.Empty, + }) + .Select(g => + { + ProvinceMeta.TryGetValue(g.Key.Province, out var meta); + var lng = meta.Lng; + var lat = meta.Lat; + // 无精确城市坐标时落在省心附近抖动,仅作热点展示 + var jitter = (g.Key.City.GetHashCode() % 100) / 500.0; + return new BizOpsCityHotspotOutput + { + Name = g.Key.City, + Province = g.Key.Province, + Value = [lng + jitter, lat + jitter / 2, g.Count()], + }; + }) + .OrderByDescending(x => x.Value.Length > 2 ? x.Value[2] : 0) + .Take(12) + .ToList(); + } + + private static List BuildCountryStats(List rows) + { + return rows + .Where(x => !string.IsNullOrWhiteSpace(x.ConsigneeCountry)) + .GroupBy(x => x.ConsigneeCountry!.Trim().ToUpperInvariant()) + .Select(g => + { + var code = g.Key; + CountryMeta.TryGetValue(code, out var meta); + var nameZh = string.IsNullOrWhiteSpace(meta.NameZh) + ? (g.First().ConsigneeCountryName ?? code) + : meta.NameZh; + var geoName = string.IsNullOrWhiteSpace(meta.Name) ? nameZh : meta.Name; + var success = g.Count(x => + string.Equals(x.OrderStatus, OrderStatusCodes.DeliverySuccess, StringComparison.OrdinalIgnoreCase)); + var withLatency = g + .Where(x => x.ReceiveTime != null && x.SignTime != null + && string.Equals(x.OrderStatus, OrderStatusCodes.DeliverySuccess, StringComparison.OrdinalIgnoreCase)) + .Select(x => (decimal)(x.SignTime!.Value - x.ReceiveTime!.Value).TotalDays) + .ToList(); + return new BizOpsCountryStatOutput + { + Name = geoName, + NameZh = nameZh, + Code = code, + Center = meta.Lng == 0 && meta.Lat == 0 ? [] : [meta.Lng, meta.Lat], + OrderCount = g.Count(), + AvgDays = withLatency.Count == 0 ? 0 : Math.Round(withLatency.Average(), 1), + SuccessRate = g.Count() == 0 ? 0 : Math.Round((decimal)success / g.Count(), 3), + }; + }) + .OrderByDescending(x => x.OrderCount) + .ToList(); + } + + private static List BuildLanes( + List rows, + Dictionary feeMap, + Dictionary productNames, + string dim, + DateTime periodStart) + { + if (dim == "country") + { + return rows + .Where(x => !string.IsNullOrWhiteSpace(x.ConsigneeCountry)) + .GroupBy(x => x.ConsigneeCountry!.Trim().ToUpperInvariant()) + .Select(g => BuildOneLane( + id: $"country-{g.Key}", + dim: dim, + productCode: null, + label: ResolveCountryLabel(g.Key, g.First().ConsigneeCountryName), + shortLabel: g.Key, + toCountryCode: g.Key, + toCountryNameZh: ResolveCountryLabel(g.Key, g.First().ConsigneeCountryName), + groupRows: g.ToList(), + feeMap: feeMap, + periodStart: periodStart)) + .OrderByDescending(x => x.OrderCount) + .ToList(); + } + + return rows + .Where(x => !string.IsNullOrWhiteSpace(x.ProductCode)) + .GroupBy(x => x.ProductCode!.Trim(), StringComparer.OrdinalIgnoreCase) + .Select(g => + { + var code = g.Key; + var name = productNames.TryGetValue(code, out var n) ? n : code; + var topCountry = g + .Where(x => !string.IsNullOrWhiteSpace(x.ConsigneeCountry)) + .GroupBy(x => x.ConsigneeCountry!.Trim().ToUpperInvariant()) + .OrderByDescending(x => x.Count()) + .Select(x => x.Key) + .FirstOrDefault(); + return BuildOneLane( + id: $"product-{code}", + dim: dim, + productCode: code, + label: name, + shortLabel: name.Length > 10 ? name[..10] : name, + toCountryCode: topCountry, + toCountryNameZh: topCountry == null + ? null + : ResolveCountryLabel(topCountry, null), + groupRows: g.ToList(), + feeMap: feeMap, + periodStart: periodStart); + }) + .OrderByDescending(x => x.OrderCount) + .ToList(); + } + + private static BizOpsLaneStatOutput BuildOneLane( + string id, + string dim, + string? productCode, + string label, + string shortLabel, + string? toCountryCode, + string? toCountryNameZh, + List groupRows, + Dictionary feeMap, + DateTime periodStart) + { + var successDays = groupRows + .Where(x => x.ReceiveTime != null && x.SignTime != null + && string.Equals(x.OrderStatus, OrderStatusCodes.DeliverySuccess, StringComparison.OrdinalIgnoreCase)) + .Select(x => (decimal)(x.SignTime!.Value - x.ReceiveTime!.Value).TotalDays) + .Where(x => x >= 0 && x < 120) + .ToList(); + var failDays = groupRows + .Where(x => x.ReceiveTime != null + && string.Equals(x.OrderStatus, OrderStatusCodes.DeliveryFailed, StringComparison.OrdinalIgnoreCase)) + .Select(x => (decimal)((x.UpdateTime ?? x.ReceiveTime!.Value) - x.ReceiveTime!.Value).TotalDays) + .Where(x => x >= 0 && x < 180) + .ToList(); + + var successCount = groupRows.Count(x => + string.Equals(x.OrderStatus, OrderStatusCodes.DeliverySuccess, StringComparison.OrdinalIgnoreCase)); + var deliveredCount = groupRows.Count(x => + string.Equals(x.OrderStatus, OrderStatusCodes.DeliverySuccess, StringComparison.OrdinalIgnoreCase) + || string.Equals(x.OrderStatus, OrderStatusCodes.DeliveryFailed, StringComparison.OrdinalIgnoreCase)); + + decimal revenue = 0, cost = 0; + foreach (var row in groupRows) + { + if (!feeMap.TryGetValue(row.Id, out var fee)) + { + continue; + } + + revenue += fee.Receivable; + cost += fee.Payable; + } + + var gross = revenue - cost; + var margin = revenue <= 0 ? 0 : Math.Round(gross / revenue, 3); + + CountryMeta.TryGetValue(toCountryCode ?? string.Empty, out var countryMeta); + var topProvince = groupRows + .Select(x => NormalizeProvince(x.SenderProvince)) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .GroupBy(x => x!, StringComparer.OrdinalIgnoreCase) + .OrderByDescending(x => x.Count()) + .Select(x => x.Key) + .FirstOrDefault(); + ProvinceMeta.TryGetValue(topProvince ?? string.Empty, out var provinceMeta); + + var dailyAvg = new List(30); + var dailyProfit = new List(30); + for (var i = 29; i >= 0; i--) + { + var day = DateTime.Today.AddDays(-i); + var next = day.AddDays(1); + var dayRows = groupRows.Where(x => x.CreateTime >= day && x.CreateTime < next).ToList(); + var dayLatency = dayRows + .Where(x => x.ReceiveTime != null && x.SignTime != null + && string.Equals(x.OrderStatus, OrderStatusCodes.DeliverySuccess, StringComparison.OrdinalIgnoreCase)) + .Select(x => (decimal)(x.SignTime!.Value - x.ReceiveTime!.Value).TotalDays) + .Where(x => x >= 0 && x < 120) + .ToList(); + dailyAvg.Add(dayLatency.Count == 0 ? 0 : Math.Round(dayLatency.Average(), 1)); + + decimal dayProfit = 0; + foreach (var row in dayRows) + { + if (!feeMap.TryGetValue(row.Id, out var fee)) + { + continue; + } + + dayProfit += fee.Receivable - fee.Payable; + } + + dailyProfit.Add(Math.Round(dayProfit, 2)); + } + + return new BizOpsLaneStatOutput + { + Id = id, + Dim = dim, + ProductCode = productCode, + Label = label, + ShortLabel = shortLabel, + FromProvince = topProvince, + FromShort = string.IsNullOrWhiteSpace(provinceMeta.Short) ? topProvince : provinceMeta.Short, + FromCenter = provinceMeta.Lng == 0 && provinceMeta.Lat == 0 ? null : [provinceMeta.Lng, provinceMeta.Lat], + ToCountryCode = toCountryCode, + ToCountryName = string.IsNullOrWhiteSpace(countryMeta.Name) ? toCountryCode : countryMeta.Name, + ToCountryNameZh = toCountryNameZh, + ToCenter = countryMeta.Lng == 0 && countryMeta.Lat == 0 ? null : [countryMeta.Lng, countryMeta.Lat], + AvgSuccessDays = successDays.Count == 0 ? 0 : Math.Round(successDays.Average(), 1), + AvgFailDays = failDays.Count == 0 ? 0 : Math.Round(failDays.Average(), 1), + OrderCount = groupRows.Count, + SuccessRate = deliveredCount == 0 ? 0 : Math.Round((decimal)successCount / deliveredCount, 3), + Revenue = Math.Round(revenue, 2), + Cost = Math.Round(cost, 2), + GrossProfit = Math.Round(gross, 2), + MarginRate = margin, + DailyAvg = dailyAvg, + DailyProfit = dailyProfit, + }; + } + + private static BizOpsLaneTotalsOutput SumLaneTotals(IEnumerable lanes) + { + var list = lanes.ToList(); + return new BizOpsLaneTotalsOutput + { + OrderCount = list.Sum(x => x.OrderCount), + Revenue = Math.Round(list.Sum(x => x.Revenue), 2), + Cost = Math.Round(list.Sum(x => x.Cost), 2), + GrossProfit = Math.Round(list.Sum(x => x.GrossProfit), 2), + }; + } + + private static string ResolveCountryLabel(string code, string? nameZh) + { + if (CountryMeta.TryGetValue(code, out var meta) && !string.IsNullOrWhiteSpace(meta.NameZh)) + { + return meta.NameZh; + } + + return string.IsNullOrWhiteSpace(nameZh) ? code : nameZh.Trim(); + } + + private static string? NormalizeProvince(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) + { + return null; + } + + var s = raw.Trim() + .Replace("省", string.Empty, StringComparison.Ordinal) + .Replace("市", string.Empty, StringComparison.Ordinal) + .Replace("壮族自治区", string.Empty, StringComparison.Ordinal) + .Replace("回族自治区", string.Empty, StringComparison.Ordinal) + .Replace("维吾尔自治区", string.Empty, StringComparison.Ordinal) + .Replace("自治区", string.Empty, StringComparison.Ordinal) + .Replace("特别行政区", string.Empty, StringComparison.Ordinal); + + if (s.StartsWith("内蒙古", StringComparison.Ordinal)) + { + return "内蒙古"; + } + + if (s.StartsWith("黑龙江", StringComparison.Ordinal)) + { + return "黑龙江"; + } + + if (ProvinceMeta.ContainsKey(s)) + { + return s; + } + + foreach (var key in ProvinceMeta.Keys) + { + if (s.StartsWith(key, StringComparison.Ordinal) || key.StartsWith(s, StringComparison.Ordinal)) + { + return key; + } + } + + return s.Length >= 2 ? s[..2] : s; + } +} diff --git a/src/Oms.Domain/OrdersAggregate/BizOpsOrderProjectionRow.cs b/src/Oms.Domain/OrdersAggregate/BizOpsOrderProjectionRow.cs new file mode 100644 index 0000000..66594fd --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/BizOpsOrderProjectionRow.cs @@ -0,0 +1,43 @@ +namespace Oms.Domain.OrdersAggregate; + +/// +/// 经营地图投影行(轻量字段,避免拉全量 Order)。 +/// +public class BizOpsOrderProjectionRow +{ + public int Id { get; set; } + + public int CustomerId { get; set; } + + public string? ProductCode { get; set; } + + public string? ConsigneeCountry { get; set; } + + public string? ConsigneeCountryName { get; set; } + + public string OrderStatus { get; set; } = string.Empty; + + public DateTime CreateTime { get; set; } + + public DateTime? ReceiveTime { get; set; } + + public DateTime? SignTime { get; set; } + + public DateTime? UpdateTime { get; set; } + + public string? SenderProvince { get; set; } + + public string? SenderCity { get; set; } +} + +/// +/// 订单费用按单汇总。 +/// +public class BizOpsOrderFeeSumRow +{ + public int OrderId { get; set; } + + public decimal Receivable { get; set; } + + public decimal Payable { get; set; } +} diff --git a/src/Oms.Domain/OrdersAggregate/Repositories/IOrderRepository.cs b/src/Oms.Domain/OrdersAggregate/Repositories/IOrderRepository.cs index 4fa5fb3..d5f17f9 100644 --- a/src/Oms.Domain/OrdersAggregate/Repositories/IOrderRepository.cs +++ b/src/Oms.Domain/OrdersAggregate/Repositories/IOrderRepository.cs @@ -162,4 +162,20 @@ public interface IOrderRepository : IRepository DateTime endExclusive, bool usePayTime, CancellationToken cancellationToken = default); + + /// + /// 经营地图:按创建时间拉取轻量投影(含发件省/市)。 + /// + Task> ListBizOpsProjectionsByCreateTimeRangeAsync( + OrderListFilter filter, + DateTime startInclusive, + DateTime endExclusive, + CancellationToken cancellationToken = default); + + /// + /// 经营地图:按订单汇总应收/应付费用。 + /// + Task> SumFeesByOrderIdsAsync( + IEnumerable orderIds, + CancellationToken cancellationToken = default); } diff --git a/src/Oms.SqlSugarCore/Orders/OrderRepository.cs b/src/Oms.SqlSugarCore/Orders/OrderRepository.cs index 929073f..21d11b0 100644 --- a/src/Oms.SqlSugarCore/Orders/OrderRepository.cs +++ b/src/Oms.SqlSugarCore/Orders/OrderRepository.cs @@ -438,6 +438,17 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I q => q.Where(x => x.ProductCode == null || x.ProductCode == string.Empty), q => q.Where(x => x.ProductCode != null && x.ProductCode != string.Empty)); } + else if (string.Equals(field, "consigneeCountry", StringComparison.OrdinalIgnoreCase)) + { + query = ApplyStringField(query, op, value, values, + (q, v) => q.Where(x => (x.ConsigneeCountry ?? string.Empty).Contains(v)), + (q, v) => q.Where(x => x.ConsigneeCountry == v), + (q, v) => q.Where(x => x.ConsigneeCountry != v), + (q, list) => q.Where(x => x.ConsigneeCountry != null && list.Contains(x.ConsigneeCountry)), + (q, list) => q.Where(x => x.ConsigneeCountry == null || !list.Contains(x.ConsigneeCountry)), + q => q.Where(x => x.ConsigneeCountry == null || x.ConsigneeCountry == string.Empty), + q => q.Where(x => x.ConsigneeCountry != null && x.ConsigneeCountry != string.Empty)); + } else if (string.Equals(field, "channelCode", StringComparison.OrdinalIgnoreCase)) { query = ApplyStringField(query, op, value, values, @@ -1793,4 +1804,123 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I }) .ToListAsync(cancellationToken); } + + public async Task> ListBizOpsProjectionsByCreateTimeRangeAsync( + OrderListFilter filter, + DateTime startInclusive, + DateTime endExclusive, + CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + var orderRows = await ApplyListFilter(db.Queryable(), filter) + .Where(x => x.CreateTime >= startInclusive && x.CreateTime < endExclusive) + .Where(x => x.OrderStatus != OrderStatusCodes.Deleted) + .Select(x => new + { + x.Id, + x.CustomerId, + x.ProductCode, + x.ConsigneeCountry, + x.ConsigneeCountryName, + x.OrderStatus, + x.CreateTime, + x.ReceiveTime, + x.SignTime, + x.UpdateTime, + }) + .ToListAsync(cancellationToken); + + var rows = orderRows.Select(x => new BizOpsOrderProjectionRow + { + Id = x.Id, + CustomerId = x.CustomerId ?? 0, + ProductCode = x.ProductCode, + ConsigneeCountry = x.ConsigneeCountry, + ConsigneeCountryName = x.ConsigneeCountryName, + OrderStatus = x.OrderStatus, + CreateTime = x.CreateTime, + ReceiveTime = x.ReceiveTime, + SignTime = x.SignTime, + UpdateTime = x.UpdateTime, + }).ToList(); + + if (rows.Count == 0) + { + return rows; + } + + const int batchSize = 800; + var senderMap = new Dictionary(); + for (var i = 0; i < rows.Count; i += batchSize) + { + var batchIds = rows.Skip(i).Take(batchSize).Select(x => x.Id).ToArray(); + var senders = await db.Queryable() + .Where(x => batchIds.Contains(x.OrderId) && !x.IsDeleted) + .Select(x => new { x.OrderId, x.Province, x.City, x.Id }) + .ToListAsync(cancellationToken); + foreach (var group in senders.GroupBy(x => x.OrderId)) + { + var first = group.OrderBy(x => x.Id).First(); + senderMap[group.Key] = (first.Province, first.City); + } + } + + foreach (var row in rows) + { + if (senderMap.TryGetValue(row.Id, out var sender)) + { + row.SenderProvince = sender.Province; + row.SenderCity = sender.City; + } + } + + return rows; + } + + public async Task> SumFeesByOrderIdsAsync( + IEnumerable orderIds, + CancellationToken cancellationToken = default) + { + var ids = orderIds.Distinct().ToArray(); + if (ids.Length == 0) + { + return []; + } + + var db = await GetDbContextAsync(cancellationToken); + const int batchSize = 800; + var map = new Dictionary(); + + async Task AccumulateAsync(string feeType, Action apply) + { + for (var i = 0; i < ids.Length; i += batchSize) + { + var batch = ids.Skip(i).Take(batchSize).ToArray(); + var rows = await db.Queryable() + .Where(x => batch.Contains(x.OrderId) && !x.IsDeleted && x.Type == feeType) + .GroupBy(x => x.OrderId) + .Select(x => new + { + OrderId = x.OrderId, + Amount = SqlFunc.AggregateSum(x.Amount), + }) + .ToListAsync(cancellationToken); + + foreach (var row in rows) + { + if (!map.TryGetValue(row.OrderId, out var item)) + { + item = new BizOpsOrderFeeSumRow { OrderId = row.OrderId }; + map[row.OrderId] = item; + } + + apply(item, row.Amount); + } + } + } + + await AccumulateAsync(OrderFeeTypeCodes.Receivable, (item, amount) => item.Receivable = amount); + await AccumulateAsync(OrderFeeTypeCodes.Payable, (item, amount) => item.Payable = amount); + return map.Values.ToList(); + } } -- 2.45.2 From 748afbf45bdf43ad8f570b8692f36d6f0fe9fb0f Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Thu, 19 Nov 2026 12:32:06 +0800 Subject: [PATCH 2/6] =?UTF-8?q?feat:=20=E5=9B=BD=E5=AE=B6=E5=B7=9E?= =?UTF-8?q?=E7=9C=81=E5=9F=8E=E5=B8=82=E4=B8=BB=E6=95=B0=E6=8D=AE=E4=B8=8E?= =?UTF-8?q?=E5=9C=B0=E5=9D=80=E7=B0=BF=E5=BF=85=E5=A1=AB=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 支撑地址簿级联下拉与经营地图发件省归一;附 CN 种子迁移脚本。 Co-authored-by: Cursor --- ...migrate_country_province_city_20261119.sql | 211 +++++++++++ .../Dtos/Orders/CustomerSenderAddressDtos.cs | 18 +- .../Dtos/System/CountryRegionDtos.cs | 164 +++++++++ .../Orders/OrderService.SenderAddress.cs | 76 +++- .../Services/System/CountryRegionService.cs | 336 ++++++++++++++++++ .../SystemAggregate/Entities/CountryCity.cs | 31 ++ .../Entities/CountryProvince.cs | 49 +++ .../Repositories/ICountryCityRepository.cs | 14 + .../ICountryProvinceRepository.cs | 14 + .../System/CountryCityRepository.cs | 31 ++ .../System/CountryProvinceRepository.cs | 31 ++ 11 files changed, 960 insertions(+), 15 deletions(-) create mode 100644 sql/migrate_country_province_city_20261119.sql create mode 100644 src/Oms.Application/Dtos/System/CountryRegionDtos.cs create mode 100644 src/Oms.Application/Services/System/CountryRegionService.cs create mode 100644 src/Oms.Domain/SystemAggregate/Entities/CountryCity.cs create mode 100644 src/Oms.Domain/SystemAggregate/Entities/CountryProvince.cs create mode 100644 src/Oms.Domain/SystemAggregate/Repositories/ICountryCityRepository.cs create mode 100644 src/Oms.Domain/SystemAggregate/Repositories/ICountryProvinceRepository.cs create mode 100644 src/Oms.SqlSugarCore/System/CountryCityRepository.cs create mode 100644 src/Oms.SqlSugarCore/System/CountryProvinceRepository.cs diff --git a/sql/migrate_country_province_city_20261119.sql b/sql/migrate_country_province_city_20261119.sql new file mode 100644 index 0000000..2cbc56d --- /dev/null +++ b/sql/migrate_country_province_city_20261119.sql @@ -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; diff --git a/src/Oms.Application/Dtos/Orders/CustomerSenderAddressDtos.cs b/src/Oms.Application/Dtos/Orders/CustomerSenderAddressDtos.cs index 1ba0dc4..5c9f041 100644 --- a/src/Oms.Application/Dtos/Orders/CustomerSenderAddressDtos.cs +++ b/src/Oms.Application/Dtos/Orders/CustomerSenderAddressDtos.cs @@ -62,14 +62,26 @@ public class CreateCustomerSenderAddressInput [StringLength(255)] public string? Company { get; set; } + /// + /// 国家二字码(必填,取自国家主数据)。 + /// + [Required] [StringLength(8)] - public string? CountryCode { get; set; } + public string CountryCode { get; set; } = string.Empty; + /// + /// 省/州中文名(必填,取自国家州省主数据)。 + /// + [Required] [StringLength(50)] - public string? Province { get; set; } + public string Province { get; set; } = string.Empty; + /// + /// 城市中文名(必填,取自国家城市主数据)。 + /// + [Required] [StringLength(50)] - public string? City { get; set; } + public string City { get; set; } = string.Empty; [StringLength(50)] public string? ZipCode { get; set; } diff --git a/src/Oms.Application/Dtos/System/CountryRegionDtos.cs b/src/Oms.Application/Dtos/System/CountryRegionDtos.cs new file mode 100644 index 0000000..c5dd4bf --- /dev/null +++ b/src/Oms.Application/Dtos/System/CountryRegionDtos.cs @@ -0,0 +1,164 @@ +using System.ComponentModel.DataAnnotations; + +namespace Oms.Application.Dtos.System; + +/// +/// 州省列表项。 +/// +public class CountryProvinceOutput +{ + /// 主键。 + public int Id { get; set; } + + /// 所属国家 Id。 + public int CountryId { get; set; } + + /// 国家二字码。 + public string CountryCode { get; set; } = string.Empty; + + /// 中文名。 + public string ChineseName { get; set; } = string.Empty; + + /// 英文名。 + public string EnglishName { get; set; } = string.Empty; + + /// 简称。 + public string? ShortName { get; set; } + + /// 中心经度。 + public decimal? Lng { get; set; } + + /// 中心纬度。 + public decimal? Lat { get; set; } + + /// 排序。 + public int SortOrder { get; set; } + + /// 下属城市数量。 + public int CityCount { get; set; } +} + +/// +/// 城市列表项。 +/// +public class CountryCityOutput +{ + /// 主键。 + public int Id { get; set; } + + /// 所属州省 Id。 + public int ProvinceId { get; set; } + + /// 中文名。 + public string ChineseName { get; set; } = string.Empty; + + /// 英文名。 + public string EnglishName { get; set; } = string.Empty; + + /// 排序。 + public int SortOrder { get; set; } +} + +/// +/// 地址下拉:州省选项。 +/// +public class CountryProvinceOptionOutput +{ + /// 州省 Id。 + public int Id { get; set; } + + /// 展示名(优先中文)。 + public string Label { get; set; } = string.Empty; + + /// 写入地址快照的中文名。 + public string Value { get; set; } = string.Empty; +} + +/// +/// 地址下拉:城市选项。 +/// +public class CountryCityOptionOutput +{ + /// 城市 Id。 + public int Id { get; set; } + + /// 展示名。 + public string Label { get; set; } = string.Empty; + + /// 写入地址快照的中文名。 + public string Value { get; set; } = string.Empty; +} + +/// +/// 新增州省。 +/// +public class CreateCountryProvinceInput +{ + /// 所属国家 Id。 + [Required] + public int CountryId { get; set; } + + /// 中文名。 + [Required] + [StringLength(64)] + public string ChineseName { get; set; } = string.Empty; + + /// 英文名。 + [StringLength(128)] + public string EnglishName { get; set; } = string.Empty; + + /// 简称。 + [StringLength(16)] + public string? ShortName { get; set; } + + /// 中心经度。 + public decimal? Lng { get; set; } + + /// 中心纬度。 + public decimal? Lat { get; set; } + + /// 排序。 + public int SortOrder { get; set; } = 100; +} + +/// +/// 更新州省。 +/// +public class UpdateCountryProvinceInput : CreateCountryProvinceInput +{ + /// 主键。 + [Required] + public int Id { get; set; } +} + +/// +/// 新增城市。 +/// +public class CreateCountryCityInput +{ + /// 所属州省 Id。 + [Required] + public int ProvinceId { get; set; } + + /// 中文名。 + [Required] + [StringLength(64)] + public string ChineseName { get; set; } = string.Empty; + + /// 英文名。 + [StringLength(128)] + public string EnglishName { get; set; } = string.Empty; + + /// 排序。 + public int SortOrder { get; set; } = 100; +} + +/// +/// 更新城市。 +/// +public class UpdateCountryCityInput : CreateCountryCityInput +{ + /// 主键。 + [Required] + public int Id { get; set; } +} diff --git a/src/Oms.Application/Services/Orders/OrderService.SenderAddress.cs b/src/Oms.Application/Services/Orders/OrderService.SenderAddress.cs index 51287ce..7baca80 100644 --- a/src/Oms.Application/Services/Orders/OrderService.SenderAddress.cs +++ b/src/Oms.Application/Services/Orders/OrderService.SenderAddress.cs @@ -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 ResolveSenderCountryIdAsync(string? countryCode) + /// + /// 校验联系人/街道,并把国家、州省、城市归一到主数据中文名(必填下拉)。 + /// + 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(); + var cityRepo = LazyServiceProvider.GetRequiredService(); + + 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> BuildSenderAddressPredicate( diff --git a/src/Oms.Application/Services/System/CountryRegionService.cs b/src/Oms.Application/Services/System/CountryRegionService.cs new file mode 100644 index 0000000..875a603 --- /dev/null +++ b/src/Oms.Application/Services/System/CountryRegionService.cs @@ -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; + +/// +/// 国家州省/城市主数据 API(地址下拉与经营地图发件省归一)。 +/// +[ApiExplorerSettings(GroupName = "OMS-System")] +public class CountryRegionService : ApplicationService +{ + private ICountryRepository CountryRepository => LazyServiceProvider.GetRequiredService(); + private ICountryProvinceRepository ProvinceRepository => LazyServiceProvider.GetRequiredService(); + private ICountryCityRepository CityRepository => LazyServiceProvider.GetRequiredService(); + + /// + /// 按国家查询州省列表(维护页)。 + /// + /// 国家主键。 + /// 州省列表,含下属城市数。 + [HttpGet("/system/country/province/list")] + public async Task> 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(); + } + + /// + /// 地址下拉:按国家二字码返回州省选项(value=中文名)。 + /// + /// ISO 二字码,如 CN。 + /// 州省选项;国家不存在时返回空列表。 + [HttpGet("/system/country/province/options")] + public async Task> 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(); + } + + /// + /// 新增州省。同一国家下中文名业务唯一。 + /// + [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 + }); + } + + /// + /// 更新州省。 + /// + [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); + } + + /// + /// 删除州省(软删除);同时软删除其下城市。 + /// + [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); + } + + /// + /// 按州省查询城市列表(维护页)。 + /// + [HttpGet("/system/country/city/list")] + public async Task> GetCityListAsync([FromQuery] int provinceId) + { + if (provinceId <= 0) + { + throw new BusinessException("请指定州省"); + } + + await GetProvinceOrThrowAsync(provinceId); + var cities = await CityRepository.ListByProvinceIdAsync(provinceId); + return cities.Select(ToCityOutput).ToList(); + } + + /// + /// 地址下拉:按州省 Id 返回城市选项(value=中文名)。 + /// + [HttpGet("/system/country/city/options")] + public async Task> 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(); + } + + /// + /// 新增城市。同一州省下中文名业务唯一。 + /// + [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 + }); + } + + /// + /// 更新城市。 + /// + [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); + } + + /// + /// 删除城市(软删除)。 + /// + [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 GetCountryOrThrowAsync(int id) + { + var entity = await CountryRepository.FirstOrDefaultAsync(x => x.Id == id); + if (entity == null) + { + throw new BusinessException("国家不存在"); + } + + return entity; + } + + private async Task GetProvinceOrThrowAsync(int id) + { + var entity = await ProvinceRepository.FirstOrDefaultAsync(x => x.Id == id); + if (entity == null) + { + throw new BusinessException("州省不存在"); + } + + return entity; + } + + private async Task 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> LoadCityCountMapAsync(IEnumerable provinceIds) + { + var ids = provinceIds.Distinct().ToArray(); + if (ids.Length == 0) + { + return new Dictionary(); + } + + 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 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}"; + } +} diff --git a/src/Oms.Domain/SystemAggregate/Entities/CountryCity.cs b/src/Oms.Domain/SystemAggregate/Entities/CountryCity.cs new file mode 100644 index 0000000..8aefa88 --- /dev/null +++ b/src/Oms.Domain/SystemAggregate/Entities/CountryCity.cs @@ -0,0 +1,31 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.SystemAggregate.Entities; + +/// +/// 州省下城市主数据。 +/// +[SugarTable("t_country_city")] +public class CountryCity : OmsAuditedAggregateRoot +{ + /// + /// 所属州省 Id。 + /// + public int ProvinceId { get; set; } + + /// + /// 中文名。 + /// + public string ChineseName { get; set; } = string.Empty; + + /// + /// 英文名。 + /// + public string EnglishName { get; set; } = string.Empty; + + /// + /// 排序,越小越前。 + /// + public int SortOrder { get; set; } = 100; +} diff --git a/src/Oms.Domain/SystemAggregate/Entities/CountryProvince.cs b/src/Oms.Domain/SystemAggregate/Entities/CountryProvince.cs new file mode 100644 index 0000000..9111945 --- /dev/null +++ b/src/Oms.Domain/SystemAggregate/Entities/CountryProvince.cs @@ -0,0 +1,49 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.SystemAggregate.Entities; + +/// +/// 国家下州省主数据。 +/// +[SugarTable("t_country_province")] +public class CountryProvince : OmsAuditedAggregateRoot +{ + /// + /// 所属国家 Id。 + /// + public int CountryId { get; set; } + + /// + /// 中文名(地址快照与地图归一用,如「广东」)。 + /// + public string ChineseName { get; set; } = string.Empty; + + /// + /// 英文名。 + /// + public string EnglishName { get; set; } = string.Empty; + + /// + /// 简称,如「粤」。 + /// + [SugarColumn(IsNullable = true, Length = 16)] + public string? ShortName { get; set; } + + /// + /// 中心经度。 + /// + [SugarColumn(IsNullable = true, DecimalDigits = 6, Length = 10)] + public decimal? Lng { get; set; } + + /// + /// 中心纬度。 + /// + [SugarColumn(IsNullable = true, DecimalDigits = 6, Length = 10)] + public decimal? Lat { get; set; } + + /// + /// 排序,越小越前。 + /// + public int SortOrder { get; set; } = 100; +} diff --git a/src/Oms.Domain/SystemAggregate/Repositories/ICountryCityRepository.cs b/src/Oms.Domain/SystemAggregate/Repositories/ICountryCityRepository.cs new file mode 100644 index 0000000..44b10c4 --- /dev/null +++ b/src/Oms.Domain/SystemAggregate/Repositories/ICountryCityRepository.cs @@ -0,0 +1,14 @@ +using Fake.Domain.Repositories; +using Oms.Domain.SystemAggregate.Entities; + +namespace Oms.Domain.SystemAggregate.Repositories; + +public interface ICountryCityRepository : IRepository +{ + Task> ListByProvinceIdAsync(int provinceId, CancellationToken cancellationToken = default); + + Task FindByProvinceAndChineseNameAsync( + int provinceId, + string chineseName, + CancellationToken cancellationToken = default); +} diff --git a/src/Oms.Domain/SystemAggregate/Repositories/ICountryProvinceRepository.cs b/src/Oms.Domain/SystemAggregate/Repositories/ICountryProvinceRepository.cs new file mode 100644 index 0000000..2395fba --- /dev/null +++ b/src/Oms.Domain/SystemAggregate/Repositories/ICountryProvinceRepository.cs @@ -0,0 +1,14 @@ +using Fake.Domain.Repositories; +using Oms.Domain.SystemAggregate.Entities; + +namespace Oms.Domain.SystemAggregate.Repositories; + +public interface ICountryProvinceRepository : IRepository +{ + Task> ListByCountryIdAsync(int countryId, CancellationToken cancellationToken = default); + + Task FindByCountryAndChineseNameAsync( + int countryId, + string chineseName, + CancellationToken cancellationToken = default); +} diff --git a/src/Oms.SqlSugarCore/System/CountryCityRepository.cs b/src/Oms.SqlSugarCore/System/CountryCityRepository.cs new file mode 100644 index 0000000..c28fdac --- /dev/null +++ b/src/Oms.SqlSugarCore/System/CountryCityRepository.cs @@ -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, ICountryCityRepository, IScopedDependency +{ + public async Task> 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 FindByProvinceAndChineseNameAsync( + int provinceId, + string chineseName, + CancellationToken cancellationToken = default) + { + var name = chineseName?.Trim() ?? string.Empty; + return FirstOrDefaultAsync( + x => x.ProvinceId == provinceId && x.ChineseName == name, + cancellationToken); + } +} diff --git a/src/Oms.SqlSugarCore/System/CountryProvinceRepository.cs b/src/Oms.SqlSugarCore/System/CountryProvinceRepository.cs new file mode 100644 index 0000000..3d2a11a --- /dev/null +++ b/src/Oms.SqlSugarCore/System/CountryProvinceRepository.cs @@ -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, ICountryProvinceRepository, IScopedDependency +{ + public async Task> 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 FindByCountryAndChineseNameAsync( + int countryId, + string chineseName, + CancellationToken cancellationToken = default) + { + var name = chineseName?.Trim() ?? string.Empty; + return FirstOrDefaultAsync( + x => x.CountryId == countryId && x.ChineseName == name, + cancellationToken); + } +} -- 2.45.2 From 884276d2931422efe356a25c4304ec04f1c0dbd4 Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Thu, 19 Nov 2026 14:10:50 +0800 Subject: [PATCH 3/6] =?UTF-8?q?feat:=20=E6=89=A9=E5=85=85=E5=9B=BD?= =?UTF-8?q?=E5=AE=B6=E5=9F=8E=E5=B8=82=E7=A7=8D=E5=AD=90=EF=BC=8C=E8=A1=A5?= =?UTF-8?q?=E9=BD=90=E5=9C=B0=E7=BA=A7=E5=B8=82=E8=A6=86=E7=9B=96?= 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 | 378 +++++++++++++++++- 1 file changed, 368 insertions(+), 10 deletions(-) diff --git a/sql/migrate_country_province_city_20261119.sql b/sql/migrate_country_province_city_20261119.sql index 2cbc56d..fb51f2c 100644 --- a/sql/migrate_country_province_city_20261119.sql +++ b/sql/migrate_country_province_city_20261119.sql @@ -141,54 +141,410 @@ CREATE TEMPORARY TABLE tmp_cn_city_seed ( SortOrder INT NOT NULL ); +-- 地级市 + 常见自治州/盟/地区 + 物流常用县级市(如义乌);直辖市记本级 INSERT INTO tmp_cn_city_seed (ProvinceName, ChineseName, EnglishName, SortOrder) VALUES +-- 直辖市 ('北京', '北京', 'Beijing', 10), ('天津', '天津', 'Tianjin', 10), +('上海', '上海', 'Shanghai', 10), +('重庆', '重庆', 'Chongqing', 10), +-- 河北 ('河北', '石家庄', 'Shijiazhuang', 10), ('河北', '唐山', 'Tangshan', 20), +('河北', '秦皇岛', 'Qinhuangdao', 30), +('河北', '邯郸', 'Handan', 40), +('河北', '邢台', 'Xingtai', 50), +('河北', '保定', 'Baoding', 60), +('河北', '张家口', 'Zhangjiakou', 70), +('河北', '承德', 'Chengde', 80), +('河北', '沧州', 'Cangzhou', 90), +('河北', '廊坊', 'Langfang', 100), +('河北', '衡水', 'Hengshui', 110), +-- 山西 ('山西', '太原', 'Taiyuan', 10), +('山西', '大同', 'Datong', 20), +('山西', '阳泉', 'Yangquan', 30), +('山西', '长治', 'Changzhi', 40), +('山西', '晋城', 'Jincheng', 50), +('山西', '朔州', 'Shuozhou', 60), +('山西', '晋中', 'Jinzhong', 70), +('山西', '运城', 'Yuncheng', 80), +('山西', '忻州', 'Xinzhou', 90), +('山西', '临汾', 'Linfen', 100), +('山西', '吕梁', 'Lvliang', 110), +-- 内蒙古(地级市 + 盟) ('内蒙古', '呼和浩特', 'Hohhot', 10), +('内蒙古', '包头', 'Baotou', 20), +('内蒙古', '乌海', 'Wuhai', 30), +('内蒙古', '赤峰', 'Chifeng', 40), +('内蒙古', '通辽', 'Tongliao', 50), +('内蒙古', '鄂尔多斯', 'Ordos', 60), +('内蒙古', '呼伦贝尔', 'Hulunbuir', 70), +('内蒙古', '巴彦淖尔', 'Bayannur', 80), +('内蒙古', '乌兰察布', 'Ulanqab', 90), +('内蒙古', '兴安盟', 'Hinggan League', 100), +('内蒙古', '锡林郭勒盟', 'Xilin Gol League', 110), +('内蒙古', '阿拉善盟', 'Alxa League', 120), +-- 辽宁 ('辽宁', '沈阳', 'Shenyang', 10), ('辽宁', '大连', 'Dalian', 20), +('辽宁', '鞍山', 'Anshan', 30), +('辽宁', '抚顺', 'Fushun', 40), +('辽宁', '本溪', 'Benxi', 50), +('辽宁', '丹东', 'Dandong', 60), +('辽宁', '锦州', 'Jinzhou', 70), +('辽宁', '营口', 'Yingkou', 80), +('辽宁', '阜新', 'Fuxin', 90), +('辽宁', '辽阳', 'Liaoyang', 100), +('辽宁', '盘锦', 'Panjin', 110), +('辽宁', '铁岭', 'Tieling', 120), +('辽宁', '朝阳', 'Chaoyang', 130), +('辽宁', '葫芦岛', 'Huludao', 140), +-- 吉林(+ 延边) ('吉林', '长春', 'Changchun', 10), +('吉林', '吉林', 'Jilin', 20), +('吉林', '四平', 'Siping', 30), +('吉林', '辽源', 'Liaoyuan', 40), +('吉林', '通化', 'Tonghua', 50), +('吉林', '白山', 'Baishan', 60), +('吉林', '松原', 'Songyuan', 70), +('吉林', '白城', 'Baicheng', 80), +('吉林', '延边', 'Yanbian', 90), +-- 黑龙江(+ 大兴安岭) ('黑龙江', '哈尔滨', 'Harbin', 10), -('上海', '上海', 'Shanghai', 10), +('黑龙江', '齐齐哈尔', 'Qiqihar', 20), +('黑龙江', '鸡西', 'Jixi', 30), +('黑龙江', '鹤岗', 'Hegang', 40), +('黑龙江', '双鸭山', 'Shuangyashan', 50), +('黑龙江', '大庆', 'Daqing', 60), +('黑龙江', '伊春', 'Yichun', 70), +('黑龙江', '佳木斯', 'Jiamusi', 80), +('黑龙江', '七台河', 'Qitaihe', 90), +('黑龙江', '牡丹江', 'Mudanjiang', 100), +('黑龙江', '黑河', 'Heihe', 110), +('黑龙江', '绥化', 'Suihua', 120), +('黑龙江', '大兴安岭', 'Daxinganling', 130), +-- 江苏 ('江苏', '南京', 'Nanjing', 10), -('江苏', '苏州', 'Suzhou', 20), -('江苏', '无锡', 'Wuxi', 30), +('江苏', '无锡', 'Wuxi', 20), +('江苏', '徐州', 'Xuzhou', 30), +('江苏', '常州', 'Changzhou', 40), +('江苏', '苏州', 'Suzhou', 50), +('江苏', '南通', 'Nantong', 60), +('江苏', '连云港', 'Lianyungang', 70), +('江苏', '淮安', 'Huaian', 80), +('江苏', '盐城', 'Yancheng', 90), +('江苏', '扬州', 'Yangzhou', 100), +('江苏', '镇江', 'Zhenjiang', 110), +('江苏', '泰州', 'Taizhou', 120), +('江苏', '宿迁', 'Suqian', 130), +-- 浙江(+ 义乌) ('浙江', '杭州', 'Hangzhou', 10), ('浙江', '宁波', 'Ningbo', 20), -('浙江', '义乌', 'Yiwu', 30), +('浙江', '温州', 'Wenzhou', 30), +('浙江', '嘉兴', 'Jiaxing', 40), +('浙江', '湖州', 'Huzhou', 50), +('浙江', '绍兴', 'Shaoxing', 60), +('浙江', '金华', 'Jinhua', 70), +('浙江', '衢州', 'Quzhou', 80), +('浙江', '舟山', 'Zhoushan', 90), +('浙江', '台州', 'Taizhou', 100), +('浙江', '丽水', 'Lishui', 110), +('浙江', '义乌', 'Yiwu', 120), +-- 安徽 ('安徽', '合肥', 'Hefei', 10), +('安徽', '芜湖', 'Wuhu', 20), +('安徽', '蚌埠', 'Bengbu', 30), +('安徽', '淮南', 'Huainan', 40), +('安徽', '马鞍山', 'Maanshan', 50), +('安徽', '淮北', 'Huaibei', 60), +('安徽', '铜陵', 'Tongling', 70), +('安徽', '安庆', 'Anqing', 80), +('安徽', '黄山', 'Huangshan', 90), +('安徽', '滁州', 'Chuzhou', 100), +('安徽', '阜阳', 'Fuyang', 110), +('安徽', '宿州', 'Suzhou', 120), +('安徽', '六安', 'Luan', 130), +('安徽', '亳州', 'Bozhou', 140), +('安徽', '池州', 'Chizhou', 150), +('安徽', '宣城', 'Xuancheng', 160), +-- 福建 ('福建', '福州', 'Fuzhou', 10), ('福建', '厦门', 'Xiamen', 20), +('福建', '莆田', 'Putian', 30), +('福建', '三明', 'Sanming', 40), +('福建', '泉州', 'Quanzhou', 50), +('福建', '漳州', 'Zhangzhou', 60), +('福建', '南平', 'Nanping', 70), +('福建', '龙岩', 'Longyan', 80), +('福建', '宁德', 'Ningde', 90), +-- 江西 ('江西', '南昌', 'Nanchang', 10), +('江西', '景德镇', 'Jingdezhen', 20), +('江西', '萍乡', 'Pingxiang', 30), +('江西', '九江', 'Jiujiang', 40), +('江西', '新余', 'Xinyu', 50), +('江西', '鹰潭', 'Yingtan', 60), +('江西', '赣州', 'Ganzhou', 70), +('江西', '吉安', 'Jian', 80), +('江西', '宜春', 'Yichun', 90), +('江西', '抚州', 'Fuzhou', 100), +('江西', '上饶', 'Shangrao', 110), +-- 山东 ('山东', '济南', 'Jinan', 10), ('山东', '青岛', 'Qingdao', 20), +('山东', '淄博', 'Zibo', 30), +('山东', '枣庄', 'Zaozhuang', 40), +('山东', '东营', 'Dongying', 50), +('山东', '烟台', 'Yantai', 60), +('山东', '潍坊', 'Weifang', 70), +('山东', '济宁', 'Jining', 80), +('山东', '泰安', 'Taian', 90), +('山东', '威海', 'Weihai', 100), +('山东', '日照', 'Rizhao', 110), +('山东', '临沂', 'Linyi', 120), +('山东', '德州', 'Dezhou', 130), +('山东', '聊城', 'Liaocheng', 140), +('山东', '滨州', 'Binzhou', 150), +('山东', '菏泽', 'Heze', 160), +-- 河南(+ 济源) ('河南', '郑州', 'Zhengzhou', 10), +('河南', '开封', 'Kaifeng', 20), +('河南', '洛阳', 'Luoyang', 30), +('河南', '平顶山', 'Pingdingshan', 40), +('河南', '安阳', 'Anyang', 50), +('河南', '鹤壁', 'Hebi', 60), +('河南', '新乡', 'Xinxiang', 70), +('河南', '焦作', 'Jiaozuo', 80), +('河南', '濮阳', 'Puyang', 90), +('河南', '许昌', 'Xuchang', 100), +('河南', '漯河', 'Luohe', 110), +('河南', '三门峡', 'Sanmenxia', 120), +('河南', '南阳', 'Nanyang', 130), +('河南', '商丘', 'Shangqiu', 140), +('河南', '信阳', 'Xinyang', 150), +('河南', '周口', 'Zhoukou', 160), +('河南', '驻马店', 'Zhumadian', 170), +('河南', '济源', 'Jiyuan', 180), +-- 湖北(+ 恩施 + 省直辖) ('湖北', '武汉', 'Wuhan', 10), +('湖北', '黄石', 'Huangshi', 20), +('湖北', '十堰', 'Shiyan', 30), +('湖北', '宜昌', 'Yichang', 40), +('湖北', '襄阳', 'Xiangyang', 50), +('湖北', '鄂州', 'Ezhou', 60), +('湖北', '荆门', 'Jingmen', 70), +('湖北', '孝感', 'Xiaogan', 80), +('湖北', '荆州', 'Jingzhou', 90), +('湖北', '黄冈', 'Huanggang', 100), +('湖北', '咸宁', 'Xianning', 110), +('湖北', '随州', 'Suizhou', 120), +('湖北', '恩施', 'Enshi', 130), +('湖北', '仙桃', 'Xiantao', 140), +('湖北', '潜江', 'Qianjiang', 150), +('湖北', '天门', 'Tianmen', 160), +('湖北', '神农架', 'Shennongjia', 170), +-- 湖南(+ 湘西) ('湖南', '长沙', 'Changsha', 10), +('湖南', '株洲', 'Zhuzhou', 20), +('湖南', '湘潭', 'Xiangtan', 30), +('湖南', '衡阳', 'Hengyang', 40), +('湖南', '邵阳', 'Shaoyang', 50), +('湖南', '岳阳', 'Yueyang', 60), +('湖南', '常德', 'Changde', 70), +('湖南', '张家界', 'Zhangjiajie', 80), +('湖南', '益阳', 'Yiyang', 90), +('湖南', '郴州', 'Chenzhou', 100), +('湖南', '永州', 'Yongzhou', 110), +('湖南', '怀化', 'Huaihua', 120), +('湖南', '娄底', 'Loudi', 130), +('湖南', '湘西', 'Xiangxi', 140), +-- 广东 ('广东', '广州', 'Guangzhou', 10), -('广东', '深圳', 'Shenzhen', 20), -('广东', '东莞', 'Dongguan', 30), -('广东', '佛山', 'Foshan', 40), +('广东', '韶关', 'Shaoguan', 20), +('广东', '深圳', 'Shenzhen', 30), +('广东', '珠海', 'Zhuhai', 40), +('广东', '汕头', 'Shantou', 50), +('广东', '佛山', 'Foshan', 60), +('广东', '江门', 'Jiangmen', 70), +('广东', '湛江', 'Zhanjiang', 80), +('广东', '茂名', 'Maoming', 90), +('广东', '肇庆', 'Zhaoqing', 100), +('广东', '惠州', 'Huizhou', 110), +('广东', '梅州', 'Meizhou', 120), +('广东', '汕尾', 'Shanwei', 130), +('广东', '河源', 'Heyuan', 140), +('广东', '阳江', 'Yangjiang', 150), +('广东', '清远', 'Qingyuan', 160), +('广东', '东莞', 'Dongguan', 170), +('广东', '中山', 'Zhongshan', 180), +('广东', '潮州', 'Chaozhou', 190), +('广东', '揭阳', 'Jieyang', 200), +('广东', '云浮', 'Yunfu', 210), +-- 广西 ('广西', '南宁', 'Nanning', 10), +('广西', '柳州', 'Liuzhou', 20), +('广西', '桂林', 'Guilin', 30), +('广西', '梧州', 'Wuzhou', 40), +('广西', '北海', 'Beihai', 50), +('广西', '防城港', 'Fangchenggang', 60), +('广西', '钦州', 'Qinzhou', 70), +('广西', '贵港', 'Guigang', 80), +('广西', '玉林', 'Yulin', 90), +('广西', '百色', 'Baise', 100), +('广西', '贺州', 'Hezhou', 110), +('广西', '河池', 'Hechi', 120), +('广西', '来宾', 'Laibin', 130), +('广西', '崇左', 'Chongzuo', 140), +-- 海南(地级 + 常用县级市) ('海南', '海口', 'Haikou', 10), -('重庆', '重庆', 'Chongqing', 10), +('海南', '三亚', 'Sanya', 20), +('海南', '三沙', 'Sansha', 30), +('海南', '儋州', 'Danzhou', 40), +('海南', '五指山', 'Wuzhishan', 50), +('海南', '琼海', 'Qionghai', 60), +('海南', '文昌', 'Wenchang', 70), +('海南', '万宁', 'Wanning', 80), +('海南', '东方', 'Dongfang', 90), +-- 四川(地级 + 自治州) ('四川', '成都', 'Chengdu', 10), +('四川', '自贡', 'Zigong', 20), +('四川', '攀枝花', 'Panzhihua', 30), +('四川', '泸州', 'Luzhou', 40), +('四川', '德阳', 'Deyang', 50), +('四川', '绵阳', 'Mianyang', 60), +('四川', '广元', 'Guangyuan', 70), +('四川', '遂宁', 'Suining', 80), +('四川', '内江', 'Neijiang', 90), +('四川', '乐山', 'Leshan', 100), +('四川', '南充', 'Nanchong', 110), +('四川', '眉山', 'Meishan', 120), +('四川', '宜宾', 'Yibin', 130), +('四川', '广安', 'Guangan', 140), +('四川', '达州', 'Dazhou', 150), +('四川', '雅安', 'Yaan', 160), +('四川', '巴中', 'Bazhong', 170), +('四川', '资阳', 'Ziyang', 180), +('四川', '阿坝', 'Aba', 190), +('四川', '甘孜', 'Garze', 200), +('四川', '凉山', 'Liangshan', 210), +-- 贵州(地级 + 自治州) ('贵州', '贵阳', 'Guiyang', 10), +('贵州', '六盘水', 'Liupanshui', 20), +('贵州', '遵义', 'Zunyi', 30), +('贵州', '安顺', 'Anshun', 40), +('贵州', '毕节', 'Bijie', 50), +('贵州', '铜仁', 'Tongren', 60), +('贵州', '黔西南', 'Qianxinan', 70), +('贵州', '黔东南', 'Qiandongnan', 80), +('贵州', '黔南', 'Qiannan', 90), +-- 云南(地级 + 自治州) ('云南', '昆明', 'Kunming', 10), +('云南', '曲靖', 'Qujing', 20), +('云南', '玉溪', 'Yuxi', 30), +('云南', '保山', 'Baoshan', 40), +('云南', '昭通', 'Zhaotong', 50), +('云南', '丽江', 'Lijiang', 60), +('云南', '普洱', 'Puer', 70), +('云南', '临沧', 'Lincang', 80), +('云南', '楚雄', 'Chuxiong', 90), +('云南', '红河', 'Honghe', 100), +('云南', '文山', 'Wenshan', 110), +('云南', '西双版纳', 'Xishuangbanna', 120), +('云南', '大理', 'Dali', 130), +('云南', '德宏', 'Dehong', 140), +('云南', '怒江', 'Nujiang', 150), +('云南', '迪庆', 'Diqing', 160), +-- 西藏(地级 + 阿里) ('西藏', '拉萨', 'Lhasa', 10), +('西藏', '日喀则', 'Xigaze', 20), +('西藏', '昌都', 'Qamdo', 30), +('西藏', '林芝', 'Nyingchi', 40), +('西藏', '山南', 'Shannan', 50), +('西藏', '那曲', 'Nagqu', 60), +('西藏', '阿里', 'Ngari', 70), +-- 陕西 ('陕西', '西安', 'Xian', 10), +('陕西', '铜川', 'Tongchuan', 20), +('陕西', '宝鸡', 'Baoji', 30), +('陕西', '咸阳', 'Xianyang', 40), +('陕西', '渭南', 'Weinan', 50), +('陕西', '延安', 'Yanan', 60), +('陕西', '汉中', 'Hanzhong', 70), +('陕西', '榆林', 'Yulin', 80), +('陕西', '安康', 'Ankang', 90), +('陕西', '商洛', 'Shangluo', 100), +-- 甘肃(地级 + 自治州) ('甘肃', '兰州', 'Lanzhou', 10), +('甘肃', '嘉峪关', 'Jiayuguan', 20), +('甘肃', '金昌', 'Jinchang', 30), +('甘肃', '白银', 'Baiyin', 40), +('甘肃', '天水', 'Tianshui', 50), +('甘肃', '武威', 'Wuwei', 60), +('甘肃', '张掖', 'Zhangye', 70), +('甘肃', '平凉', 'Pingliang', 80), +('甘肃', '酒泉', 'Jiuquan', 90), +('甘肃', '庆阳', 'Qingyang', 100), +('甘肃', '定西', 'Dingxi', 110), +('甘肃', '陇南', 'Longnan', 120), +('甘肃', '临夏', 'Linxia', 130), +('甘肃', '甘南', 'Gannan', 140), +-- 青海(地级 + 自治州) ('青海', '西宁', 'Xining', 10), +('青海', '海东', 'Haidong', 20), +('青海', '海北', 'Haibei', 30), +('青海', '黄南', 'Huangnan', 40), +('青海', '海南', 'Hainan', 50), +('青海', '果洛', 'Golog', 60), +('青海', '玉树', 'Yushu', 70), +('青海', '海西', 'Haixi', 80), +-- 宁夏 ('宁夏', '银川', 'Yinchuan', 10), +('宁夏', '石嘴山', 'Shizuishan', 20), +('宁夏', '吴忠', 'Wuzhong', 30), +('宁夏', '固原', 'Guyuan', 40), +('宁夏', '中卫', 'Zhongwei', 50), +-- 新疆(地级 + 州/地区 + 常用直辖县级市) ('新疆', '乌鲁木齐', 'Urumqi', 10), +('新疆', '克拉玛依', 'Karamay', 20), +('新疆', '吐鲁番', 'Turpan', 30), +('新疆', '哈密', 'Hami', 40), +('新疆', '昌吉', 'Changji', 50), +('新疆', '博尔塔拉', 'Bortala', 60), +('新疆', '巴音郭楞', 'Bayingolin', 70), +('新疆', '阿克苏', 'Aksu', 80), +('新疆', '克孜勒苏', 'Kizilsu', 90), +('新疆', '喀什', 'Kashgar', 100), +('新疆', '和田', 'Hotan', 110), +('新疆', '伊犁', 'Ili', 120), +('新疆', '塔城', 'Tacheng', 130), +('新疆', '阿勒泰', 'Altay', 140), +('新疆', '石河子', 'Shihezi', 150), +('新疆', '阿拉尔', 'Aral', 160), +('新疆', '图木舒克', 'Tumxuk', 170), +('新疆', '五家渠', 'Wujiaqu', 180), +('新疆', '北屯', 'Beitun', 190), +('新疆', '铁门关', 'Tiemenguan', 200), +('新疆', '双河', 'Shuanghe', 210), +('新疆', '可克达拉', 'Kokdala', 220), +('新疆', '昆玉', 'Kunyu', 230), +('新疆', '胡杨河', 'Huyanghe', 240), +('新疆', '新星', 'Xinxing', 250), +-- 台湾(主要城市) ('台湾', '台北', 'Taipei', 10), +('台湾', '新北', 'New Taipei', 20), +('台湾', '桃园', 'Taoyuan', 30), +('台湾', '台中', 'Taichung', 40), +('台湾', '台南', 'Tainan', 50), +('台湾', '高雄', 'Kaohsiung', 60), +('台湾', '基隆', 'Keelung', 70), +('台湾', '新竹', 'Hsinchu', 80), +('台湾', '嘉义', 'Chiayi', 90), +-- 港澳 ('香港', '香港', 'Hong Kong', 10), ('澳门', '澳门', 'Macao', 10); --- 仅当刚种子了州省(或 CN 下仍无城市)时补城市:以「该省尚无有效城市」为条件逐省插入 +-- 按「省 + 城市中文名」缺啥补啥,已有库可重复执行 INSERT INTO t_country_city ( ProvinceId, ChineseName, EnglishName, SortOrder, IsDeleted, CreateUserId, CreateTime @@ -204,7 +560,9 @@ INNER JOIN t_country_province p 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 + WHERE c.IsDeleted = 0 + AND c.ProvinceId = p.Id + AND c.ChineseName = s.ChineseName ); DROP TEMPORARY TABLE IF EXISTS tmp_cn_province_seed; -- 2.45.2 From 2ced23e56416cc804cab6598c45376f614081878 Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Thu, 19 Nov 2026 15:27:27 +0800 Subject: [PATCH 4/6] =?UTF-8?q?feat:=20=E5=85=A5=E5=BA=93=E9=A2=84?= =?UTF-8?q?=E6=8A=A5=E6=8C=89=E6=89=AB=E7=A0=81=E5=AE=9A=E4=BD=8D=E5=BE=85?= =?UTF-8?q?=E4=B8=8A=E6=9E=B6=E8=AF=A6=E6=83=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 lookup-by-scan,支持预报单号/箱唛/NoticeNo-Seq,供 H5 上架扫描使用。 Co-authored-by: Cursor --- .../Dtos/Warehouse/WarehouseDtos.cs | 22 +++ .../Warehouse/WarehouseService.Inbound.cs | 156 +++++++++++++++--- 2 files changed, 155 insertions(+), 23 deletions(-) diff --git a/src/Oms.Application/Dtos/Warehouse/WarehouseDtos.cs b/src/Oms.Application/Dtos/Warehouse/WarehouseDtos.cs index 630cb9a..08888a6 100644 --- a/src/Oms.Application/Dtos/Warehouse/WarehouseDtos.cs +++ b/src/Oms.Application/Dtos/Warehouse/WarehouseDtos.cs @@ -367,6 +367,28 @@ public class WarehouseInboundConfirmReceiveInput public List Boxes { get; set; } = []; } +/// +/// H5 上架扫描:按扫码内容定位待收货入库预报。 +/// +public class WarehouseInboundLookupByScanInput +{ + /// + /// 扫码内容:预报单号 / 箱唛 MarkBoxNo / {NoticeNo}-{BoxSeqNo}。 + /// + [Required] + public string Code { get; set; } = string.Empty; + + /// + /// 当前操作仓(可选;传入则校验预报归属仓)。 + /// + public int? WarehouseId { get; set; } + + /// + /// 客户 ID(可选;管理端可空表示不限客户)。 + /// + public int? CustomerId { get; set; } +} + public class WarehouseInboundSummaryOutput { public int Forecasted { get; set; } diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.Inbound.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.Inbound.cs index e3761e9..78709e2 100644 --- a/src/Oms.Application/Services/Warehouse/WarehouseService.Inbound.cs +++ b/src/Oms.Application/Services/Warehouse/WarehouseService.Inbound.cs @@ -127,31 +127,109 @@ public partial class WarehouseService { var resolvedCustomerId = await ResolveListCustomerIdAsync(customerId); var notice = await GetInboundNoticeOrThrowAsync(resolvedCustomerId, id); - var boxes = await InboundBoxRepository.GetListAsync(x => x.InboundNoticeId == notice.Id); - boxes = OrderInboundBoxes(boxes); - var boxIds = boxes.Select(x => x.Id).ToArray(); - var lines = boxIds.Length == 0 - ? [] - : await InboundBoxLineRepository.GetListAsync(x => boxIds.Contains(x.InboundBoxId)); + return await BuildInboundDetailAsync(notice); + } - var output = MapInboundOutput(notice, boxes, lines); - return new WarehouseInboundDetailOutput + /// + /// H5 上架扫描:按预报单号 / 箱唛 / {NoticeNo}-{BoxSeqNo} 定位未完成收货的入库预报详情。 + /// + /// 扫码内容与可选仓库、客户过滤。 + /// 入库预报详情(含箱与明细)。 + [HttpPost("/warehouse/inbound/lookup-by-scan")] + public async Task LookupInboundByScanAsync( + WarehouseInboundLookupByScanInput input) + { + var code = input.Code?.Trim() ?? string.Empty; + if (string.IsNullOrWhiteSpace(code)) { - Id = output.Id, - CustomerId = output.CustomerId, - WarehouseId = output.WarehouseId, - NoticeNo = output.NoticeNo, - MarkReference = output.MarkReference, - InboundType = output.InboundType, - ReceiptStatus = output.ReceiptStatus, - ExpectedArrivalTime = output.ExpectedArrivalTime, - ActualArrivalTime = output.ActualArrivalTime, - Remark = output.Remark, - BoxCount = output.BoxCount, - PlannedQty = output.PlannedQty, - CreateTime = output.CreateTime, - Boxes = boxes.Select(box => MapInboundBox(box, lines.Where(l => l.InboundBoxId == box.Id))).ToList() - }; + throw new BusinessException("请扫描或输入预报单号 / 箱唛"); + } + + var customerId = await ResolveListCustomerIdAsync(input.CustomerId); + var (hasCustomerFilter, customerIdValue) = CustomerFilter(customerId); + var hasWarehouseFilter = input.WarehouseId is > 0; + var warehouseIdValue = input.WarehouseId.GetValueOrDefault(); + + CInboundNotice? notice = null; + + // 1) 精确预报单号 + var exactNotices = await InboundNoticeRepository.GetListAsync(x => + x.NoticeNo == code + && x.ReceiptStatus != WarehouseReceiptStatusCodes.Completed + && (!hasCustomerFilter || x.CustomerId == customerIdValue) + && (!hasWarehouseFilter || x.WarehouseId == warehouseIdValue)); + notice = exactNotices.OrderByDescending(x => x.UpdateTime).ThenByDescending(x => x.Id).FirstOrDefault(); + + // 2) 精确箱唛 MarkBoxNo + if (notice == null) + { + var boxes = await InboundBoxRepository.GetListAsync(x => x.MarkBoxNo == code); + if (boxes.Count > 0) + { + var noticeIds = boxes.Select(x => x.InboundNoticeId).Distinct().ToArray(); + var byBox = await InboundNoticeRepository.GetListAsync(x => + noticeIds.Contains(x.Id) + && x.ReceiptStatus != WarehouseReceiptStatusCodes.Completed + && (!hasCustomerFilter || x.CustomerId == customerIdValue) + && (!hasWarehouseFilter || x.WarehouseId == warehouseIdValue)); + notice = byBox.OrderByDescending(x => x.UpdateTime).ThenByDescending(x => x.Id).FirstOrDefault(); + } + } + + // 3) {NoticeNo}-{BoxSeqNo}(与箱唛条码 ResolveBarcode 一致) + if (notice == null) + { + var dash = code.LastIndexOf('-'); + if (dash > 0 && dash < code.Length - 1) + { + var noticeNoPart = code[..dash].Trim(); + var seqPart = code[(dash + 1)..].Trim(); + if (!string.IsNullOrWhiteSpace(noticeNoPart) && !string.IsNullOrWhiteSpace(seqPart)) + { + var byBarcode = await InboundNoticeRepository.GetListAsync(x => + x.NoticeNo == noticeNoPart + && x.ReceiptStatus != WarehouseReceiptStatusCodes.Completed + && (!hasCustomerFilter || x.CustomerId == customerIdValue) + && (!hasWarehouseFilter || x.WarehouseId == warehouseIdValue)); + var candidate = byBarcode + .OrderByDescending(x => x.UpdateTime) + .ThenByDescending(x => x.Id) + .FirstOrDefault(); + if (candidate != null) + { + var seqBoxes = await InboundBoxRepository.GetListAsync(x => + x.InboundNoticeId == candidate.Id && x.BoxSeqNo == seqPart); + if (seqBoxes.Count > 0) + { + notice = candidate; + } + } + } + } + } + + // 4) 预报单号模糊包含(兜底) + if (notice == null) + { + var fuzzy = await InboundNoticeRepository.GetListAsync(x => + x.NoticeNo.Contains(code) + && x.ReceiptStatus != WarehouseReceiptStatusCodes.Completed + && (!hasCustomerFilter || x.CustomerId == customerIdValue) + && (!hasWarehouseFilter || x.WarehouseId == warehouseIdValue)); + notice = fuzzy.OrderByDescending(x => x.UpdateTime).ThenByDescending(x => x.Id).FirstOrDefault(); + } + + if (notice == null) + { + throw new BusinessException("未找到待上架的入库预报"); + } + + if (hasWarehouseFilter && notice.WarehouseId != warehouseIdValue) + { + throw new BusinessException("该预报不属于当前仓库"); + } + + return await BuildInboundDetailAsync(notice); } /// @@ -475,6 +553,38 @@ public partial class WarehouseService return entity; } + private async Task BuildInboundDetailAsync(CInboundNotice notice) + { + var boxes = await InboundBoxRepository.GetListAsync(x => x.InboundNoticeId == notice.Id); + boxes = OrderInboundBoxes(boxes); + var boxIds = boxes.Select(x => x.Id).ToArray(); + var lines = boxIds.Length == 0 + ? [] + : await InboundBoxLineRepository.GetListAsync(x => boxIds.Contains(x.InboundBoxId)); + + var output = MapInboundOutput(notice, boxes, lines); + var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == notice.CustomerId); + return new WarehouseInboundDetailOutput + { + Id = output.Id, + CustomerId = output.CustomerId, + CustomerName = customer?.CustomerName, + CustomerCode = customer?.CustomerCode, + WarehouseId = output.WarehouseId, + NoticeNo = output.NoticeNo, + MarkReference = output.MarkReference, + InboundType = output.InboundType, + ReceiptStatus = output.ReceiptStatus, + ExpectedArrivalTime = output.ExpectedArrivalTime, + ActualArrivalTime = output.ActualArrivalTime, + Remark = output.Remark, + BoxCount = output.BoxCount, + PlannedQty = output.PlannedQty, + CreateTime = output.CreateTime, + Boxes = boxes.Select(box => MapInboundBox(box, lines.Where(l => l.InboundBoxId == box.Id))).ToList() + }; + } + private async Task SaveInboundLabelPdfAsync(string noticeNo, byte[] pdfBytes) { var safeNo = string.IsNullOrWhiteSpace(noticeNo) ? "inbound" : noticeNo.Trim(); -- 2.45.2 From 8c1b7c0140abca675e7707770ddf53dd2de9d628 Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Thu, 19 Nov 2026 16:03:34 +0800 Subject: [PATCH 5/6] =?UTF-8?q?feat:=20=E5=93=81=E7=89=8C=20Logo=20?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E4=B8=8E=E5=8C=BF=E5=90=8D=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 brand_logo 配置及 portal/site 渠道上传,供系统顶栏与官网展示。 Co-authored-by: Cursor --- .../Dtos/System/BrandLogoOutput.cs | 17 ++++ .../Dtos/System/BrandLogoUploadInput.cs | 19 +++++ .../System/SystemOtherConfigService.cs | 83 +++++++++++++++++++ .../Shared/OmsFileUploadHelper.cs | 3 + .../Consts/SystemOtherConfigCodes.cs | 5 ++ 5 files changed, 127 insertions(+) create mode 100644 src/Oms.Application/Dtos/System/BrandLogoOutput.cs create mode 100644 src/Oms.Application/Dtos/System/BrandLogoUploadInput.cs diff --git a/src/Oms.Application/Dtos/System/BrandLogoOutput.cs b/src/Oms.Application/Dtos/System/BrandLogoOutput.cs new file mode 100644 index 0000000..a2478fa --- /dev/null +++ b/src/Oms.Application/Dtos/System/BrandLogoOutput.cs @@ -0,0 +1,17 @@ +namespace Oms.Application.Dtos.System; + +/// +/// 品牌 Logo 展示输出。 +/// +public class BrandLogoOutput +{ + /// + /// 系统顶栏 Logo 可访问 URL;未配置时为空。 + /// + public string PortalUrl { get; set; } = string.Empty; + + /// + /// 官网 Logo 可访问 URL;未配置时为空。 + /// + public string SiteUrl { get; set; } = string.Empty; +} diff --git a/src/Oms.Application/Dtos/System/BrandLogoUploadInput.cs b/src/Oms.Application/Dtos/System/BrandLogoUploadInput.cs new file mode 100644 index 0000000..ba54106 --- /dev/null +++ b/src/Oms.Application/Dtos/System/BrandLogoUploadInput.cs @@ -0,0 +1,19 @@ +using Microsoft.AspNetCore.Http; + +namespace Oms.Application.Dtos.System; + +/// +/// 上传品牌 Logo 入参(multipart/form-data:channel + file)。 +/// +public class BrandLogoUploadInput +{ + /// + /// 渠道:portal(系统顶栏)/ site(官网)。 + /// + public string Channel { get; set; } = string.Empty; + + /// + /// Logo 图片。 + /// + public IFormFile File { get; set; } = null!; +} diff --git a/src/Oms.Application/Services/System/SystemOtherConfigService.cs b/src/Oms.Application/Services/System/SystemOtherConfigService.cs index e8654b9..c24633a 100644 --- a/src/Oms.Application/Services/System/SystemOtherConfigService.cs +++ b/src/Oms.Application/Services/System/SystemOtherConfigService.cs @@ -1,6 +1,7 @@ using System.Linq.Expressions; using Fake.Application; using Fake.ObjectStorage; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Oms.Application.Dtos.Shared; using Oms.Application.Dtos.System; @@ -21,6 +22,8 @@ public class SystemOtherConfigService : ApplicationService private const string SecretMask = "******"; private const string PaymentQrChannelAlipay = "alipay"; private const string PaymentQrChannelWechat = "wechat"; + private const string BrandLogoChannelPortal = "portal"; + private const string BrandLogoChannelSite = "site"; private ISystemOtherConfigRepository SystemOtherConfigRepository => LazyServiceProvider.GetRequiredService(); @@ -193,6 +196,54 @@ public class SystemOtherConfigService : ApplicationService }; } + /// + /// 获取品牌 Logo(系统顶栏 / 官网)。未配置时对应 URL 为空(前端回退本地默认图)。匿名可读,供官网使用。 + /// + [AllowAnonymous] + [HttpGet("/system/other-config/brand-logo")] + public async Task GetBrandLogoAsync() + { + var entity = await SystemOtherConfigRepository.GetByConfigCodeAsync(SystemOtherConfigCodes.BrandLogo); + return new BrandLogoOutput + { + PortalUrl = FileStorage.GetPublicUrl(entity?.AppKey), + SiteUrl = FileStorage.GetPublicUrl(entity?.Remark) + }; + } + + /// + /// 上传并替换品牌 Logo。Channel=portal|site;返回最新可访问 URL。 + /// + /// 入参:渠道 + 图片文件。 + [HttpPost("/system/other-config/brand-logo/upload")] + [Consumes("multipart/form-data")] + public async Task UploadBrandLogoAsync([FromForm] BrandLogoUploadInput input) + { + var channel = (input.Channel ?? string.Empty).Trim().ToLowerInvariant(); + if (channel is not (BrandLogoChannelPortal or BrandLogoChannelSite)) + { + throw new BusinessException("渠道仅支持 portal 或 site"); + } + + var key = await OmsFileUploadHelper.SaveBrandLogoAsync(input.File, FileStorage); + var entity = await EnsureBrandLogoConfigAsync(); + if (channel == BrandLogoChannelPortal) + { + entity.AppKey = key; + } + else + { + entity.Remark = key; + } + + await SystemOtherConfigRepository.UpdateAsync(entity); + return new BrandLogoOutput + { + PortalUrl = FileStorage.GetPublicUrl(entity.AppKey), + SiteUrl = FileStorage.GetPublicUrl(entity.Remark) + }; + } + private async Task EnsurePaymentReceiveQrConfigAsync() { var entity = await SystemOtherConfigRepository.GetByConfigCodeAsync(SystemOtherConfigCodes.PaymentReceiveQr); @@ -224,11 +275,43 @@ public class SystemOtherConfigService : ApplicationService }); } + private async Task EnsureBrandLogoConfigAsync() + { + var entity = await SystemOtherConfigRepository.GetByConfigCodeAsync(SystemOtherConfigCodes.BrandLogo); + if (entity != null) + { + return entity; + } + + var deleted = await SystemOtherConfigRepository.GetByConfigCodeIncludingDeletedAsync( + SystemOtherConfigCodes.BrandLogo); + if (deleted != null) + { + deleted.IsDeleted = false; + deleted.ConfigName = "品牌 Logo"; + deleted.Enabled = true; + deleted.TimeoutSeconds = 30; + deleted.BaseUrl = null; + deleted.AppSecret = null; + await SystemOtherConfigRepository.UpdateAsync(deleted); + return deleted; + } + + return await SystemOtherConfigRepository.InsertAsync(new SystemOtherConfig + { + ConfigCode = SystemOtherConfigCodes.BrandLogo, + ConfigName = "品牌 Logo", + Enabled = true, + TimeoutSeconds = 30 + }); + } + private static Expression> BuildListPredicate(SystemOtherConfigListInput input) { var keyword = input.Keyword?.Trim(); return x => x.ConfigCode != SystemOtherConfigCodes.PaymentReceiveQr + && x.ConfigCode != SystemOtherConfigCodes.BrandLogo && (string.IsNullOrWhiteSpace(keyword) || x.ConfigCode.Contains(keyword) || x.ConfigName.Contains(keyword)); diff --git a/src/Oms.Application/Shared/OmsFileUploadHelper.cs b/src/Oms.Application/Shared/OmsFileUploadHelper.cs index 4889596..f7a169d 100644 --- a/src/Oms.Application/Shared/OmsFileUploadHelper.cs +++ b/src/Oms.Application/Shared/OmsFileUploadHelper.cs @@ -29,6 +29,9 @@ public static class OmsFileUploadHelper public static Task SavePaymentReceiveQrAsync(IFormFile file, IObjectStorage storage) => SaveImageAsync(file, storage, "payment-qr", "收款码图片"); + public static Task SaveBrandLogoAsync(IFormFile file, IObjectStorage storage) => + SaveImageAsync(file, storage, "brand-logo", "品牌 Logo"); + private static async Task SaveImageAsync( IFormFile? file, IObjectStorage storage, diff --git a/src/Oms.Domain/SystemAggregate/Consts/SystemOtherConfigCodes.cs b/src/Oms.Domain/SystemAggregate/Consts/SystemOtherConfigCodes.cs index 7bc9f93..8116eae 100644 --- a/src/Oms.Domain/SystemAggregate/Consts/SystemOtherConfigCodes.cs +++ b/src/Oms.Domain/SystemAggregate/Consts/SystemOtherConfigCodes.cs @@ -64,4 +64,9 @@ public static class SystemOtherConfigCodes /// 客户充值收款码(AppKey=支付宝收款码 object key,Remark=微信收款码 object key)。 /// public const string PaymentReceiveQr = "payment_receive_qr"; + + /// + /// 品牌 Logo(AppKey=系统顶栏 Logo object key,Remark=官网 Logo object key)。 + /// + public const string BrandLogo = "brand_logo"; } -- 2.45.2 From af9532f5dfee3f07559883b54e84ce5f995b120c Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Thu, 19 Nov 2026 16:22:05 +0800 Subject: [PATCH 6/6] =?UTF-8?q?feat:=20=E5=93=81=E7=89=8C=20Logo=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20mascot=20=E6=B8=A0=E9=81=93=EF=BC=88?= =?UTF-8?q?=E5=90=AF=E5=8A=A8=E9=A1=B5=E5=90=89=E7=A5=A5=E7=89=A9=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- .../Dtos/System/BrandLogoOutput.cs | 10 ++++ .../Dtos/System/BrandLogoUploadInput.cs | 2 +- .../System/SystemOtherConfigService.cs | 50 ++++++++++++------- .../Consts/SystemOtherConfigCodes.cs | 2 +- 4 files changed, 45 insertions(+), 19 deletions(-) diff --git a/src/Oms.Application/Dtos/System/BrandLogoOutput.cs b/src/Oms.Application/Dtos/System/BrandLogoOutput.cs index a2478fa..6026054 100644 --- a/src/Oms.Application/Dtos/System/BrandLogoOutput.cs +++ b/src/Oms.Application/Dtos/System/BrandLogoOutput.cs @@ -14,4 +14,14 @@ public class BrandLogoOutput /// 官网 Logo 可访问 URL;未配置时为空。 /// public string SiteUrl { get; set; } = string.Empty; + + /// + /// 网站标签(favicon)可访问 URL;未配置时为空。 + /// + public string FaviconUrl { get; set; } = string.Empty; + + /// + /// 启动页 / 空态吉祥物可访问 URL;未配置时为空。 + /// + public string MascotUrl { get; set; } = string.Empty; } diff --git a/src/Oms.Application/Dtos/System/BrandLogoUploadInput.cs b/src/Oms.Application/Dtos/System/BrandLogoUploadInput.cs index ba54106..534076a 100644 --- a/src/Oms.Application/Dtos/System/BrandLogoUploadInput.cs +++ b/src/Oms.Application/Dtos/System/BrandLogoUploadInput.cs @@ -8,7 +8,7 @@ namespace Oms.Application.Dtos.System; public class BrandLogoUploadInput { /// - /// 渠道:portal(系统顶栏)/ site(官网)。 + /// 渠道:portal(系统顶栏)/ site(官网)/ favicon(网站标签)/ mascot(启动页吉祥物)。 /// public string Channel { get; set; } = string.Empty; diff --git a/src/Oms.Application/Services/System/SystemOtherConfigService.cs b/src/Oms.Application/Services/System/SystemOtherConfigService.cs index c24633a..d091e30 100644 --- a/src/Oms.Application/Services/System/SystemOtherConfigService.cs +++ b/src/Oms.Application/Services/System/SystemOtherConfigService.cs @@ -24,6 +24,8 @@ public class SystemOtherConfigService : ApplicationService private const string PaymentQrChannelWechat = "wechat"; private const string BrandLogoChannelPortal = "portal"; private const string BrandLogoChannelSite = "site"; + private const string BrandLogoChannelFavicon = "favicon"; + private const string BrandLogoChannelMascot = "mascot"; private ISystemOtherConfigRepository SystemOtherConfigRepository => LazyServiceProvider.GetRequiredService(); @@ -197,22 +199,18 @@ public class SystemOtherConfigService : ApplicationService } /// - /// 获取品牌 Logo(系统顶栏 / 官网)。未配置时对应 URL 为空(前端回退本地默认图)。匿名可读,供官网使用。 + /// 获取品牌 Logo(系统顶栏 / 官网 / 网站标签 / 启动页吉祥物)。未配置时对应 URL 为空(前端回退本地默认图)。匿名可读。 /// [AllowAnonymous] [HttpGet("/system/other-config/brand-logo")] public async Task GetBrandLogoAsync() { var entity = await SystemOtherConfigRepository.GetByConfigCodeAsync(SystemOtherConfigCodes.BrandLogo); - return new BrandLogoOutput - { - PortalUrl = FileStorage.GetPublicUrl(entity?.AppKey), - SiteUrl = FileStorage.GetPublicUrl(entity?.Remark) - }; + return MapBrandLogoOutput(entity); } /// - /// 上传并替换品牌 Logo。Channel=portal|site;返回最新可访问 URL。 + /// 上传并替换品牌 Logo。Channel=portal|site|favicon|mascot;返回最新可访问 URL。 /// /// 入参:渠道 + 图片文件。 [HttpPost("/system/other-config/brand-logo/upload")] @@ -220,9 +218,13 @@ public class SystemOtherConfigService : ApplicationService public async Task UploadBrandLogoAsync([FromForm] BrandLogoUploadInput input) { var channel = (input.Channel ?? string.Empty).Trim().ToLowerInvariant(); - if (channel is not (BrandLogoChannelPortal or BrandLogoChannelSite)) + if (channel is not ( + BrandLogoChannelPortal + or BrandLogoChannelSite + or BrandLogoChannelFavicon + or BrandLogoChannelMascot)) { - throw new BusinessException("渠道仅支持 portal 或 site"); + throw new BusinessException("渠道仅支持 portal、site、favicon 或 mascot"); } var key = await OmsFileUploadHelper.SaveBrandLogoAsync(input.File, FileStorage); @@ -231,19 +233,34 @@ public class SystemOtherConfigService : ApplicationService { entity.AppKey = key; } - else + else if (channel == BrandLogoChannelSite) { entity.Remark = key; } + else if (channel == BrandLogoChannelFavicon) + { + // BaseUrl 复用为 favicon object key(非网关地址) + entity.BaseUrl = key; + } + else + { + // AppSecret 复用为启动页吉祥物 object key(非密钥) + entity.AppSecret = key; + } await SystemOtherConfigRepository.UpdateAsync(entity); - return new BrandLogoOutput - { - PortalUrl = FileStorage.GetPublicUrl(entity.AppKey), - SiteUrl = FileStorage.GetPublicUrl(entity.Remark) - }; + return MapBrandLogoOutput(entity); } + private BrandLogoOutput MapBrandLogoOutput(SystemOtherConfig? entity) => + new() + { + PortalUrl = FileStorage.GetPublicUrl(entity?.AppKey), + SiteUrl = FileStorage.GetPublicUrl(entity?.Remark), + FaviconUrl = FileStorage.GetPublicUrl(entity?.BaseUrl), + MascotUrl = FileStorage.GetPublicUrl(entity?.AppSecret) + }; + private async Task EnsurePaymentReceiveQrConfigAsync() { var entity = await SystemOtherConfigRepository.GetByConfigCodeAsync(SystemOtherConfigCodes.PaymentReceiveQr); @@ -291,8 +308,7 @@ public class SystemOtherConfigService : ApplicationService deleted.ConfigName = "品牌 Logo"; deleted.Enabled = true; deleted.TimeoutSeconds = 30; - deleted.BaseUrl = null; - deleted.AppSecret = null; + // 保留 AppKey/Remark/BaseUrl/AppSecret 中的 Logo object key,避免恢复时丢图 await SystemOtherConfigRepository.UpdateAsync(deleted); return deleted; } diff --git a/src/Oms.Domain/SystemAggregate/Consts/SystemOtherConfigCodes.cs b/src/Oms.Domain/SystemAggregate/Consts/SystemOtherConfigCodes.cs index 8116eae..46fc49f 100644 --- a/src/Oms.Domain/SystemAggregate/Consts/SystemOtherConfigCodes.cs +++ b/src/Oms.Domain/SystemAggregate/Consts/SystemOtherConfigCodes.cs @@ -66,7 +66,7 @@ public static class SystemOtherConfigCodes public const string PaymentReceiveQr = "payment_receive_qr"; /// - /// 品牌 Logo(AppKey=系统顶栏 Logo object key,Remark=官网 Logo object key)。 + /// 品牌 Logo(AppKey=系统顶栏,Remark=官网,BaseUrl=favicon,AppSecret=启动页吉祥物;均为 object key)。 /// public const string BrandLogo = "brand_logo"; } -- 2.45.2