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; } }