feat: 新增经营地图工作台统计接口(产品/国家线路与热力)
All checks were successful
Build and Deploy / deploy (push) Successful in 1m19s
All checks were successful
Build and Deploy / deploy (push) Successful in 1m19s
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
cbe22652c0
commit
72a1a3590e
160
src/Oms.Application/Dtos/Orders/BizOpsOverviewOutput.cs
Normal file
160
src/Oms.Application/Dtos/Orders/BizOpsOverviewOutput.cs
Normal file
@ -0,0 +1,160 @@
|
||||
namespace Oms.Application.Dtos.Orders;
|
||||
|
||||
/// <summary>
|
||||
/// 经营地图工作台总览。
|
||||
/// </summary>
|
||||
public class BizOpsOverviewOutput
|
||||
{
|
||||
/// <summary>统计天数:7 / 30 / 90。</summary>
|
||||
public int RangeDays { get; set; }
|
||||
|
||||
/// <summary>线路维度:product=销售产品,country=目的国。</summary>
|
||||
public string LaneDim { get; set; } = "product";
|
||||
|
||||
/// <summary>本期起(含)。</summary>
|
||||
public DateTime PeriodStart { get; set; }
|
||||
|
||||
/// <summary>本期止(不含)。</summary>
|
||||
public DateTime PeriodEndExclusive { get; set; }
|
||||
|
||||
/// <summary>失败时效告警阈值(天)。</summary>
|
||||
public decimal FailDaysThreshold { get; set; }
|
||||
|
||||
/// <summary>毛利率偏低阈值(0-1)。</summary>
|
||||
public decimal MarginRateThreshold { get; set; }
|
||||
|
||||
/// <summary>客户汇总。</summary>
|
||||
public BizOpsCustomerSummaryOutput CustomerSummary { get; set; } = new();
|
||||
|
||||
/// <summary>收件侧订单状态角标(当前快照)。</summary>
|
||||
public BizOpsOrderStatusSnapshotOutput OrderStatusSnapshot { get; set; } = new();
|
||||
|
||||
/// <summary>中国发件省热力。</summary>
|
||||
public List<BizOpsProvinceStatOutput> Provinces { get; set; } = [];
|
||||
|
||||
/// <summary>发件城市热点。</summary>
|
||||
public List<BizOpsCityHotspotOutput> Cities { get; set; } = [];
|
||||
|
||||
/// <summary>目的国热力。</summary>
|
||||
public List<BizOpsCountryStatOutput> Countries { get; set; } = [];
|
||||
|
||||
/// <summary>重点线路(按维度)。</summary>
|
||||
public List<BizOpsLaneStatOutput> Lanes { get; set; } = [];
|
||||
|
||||
/// <summary>线路合计(本期)。</summary>
|
||||
public BizOpsLaneTotalsOutput Totals { get; set; } = new();
|
||||
|
||||
/// <summary>线路合计(上期,用于环比)。</summary>
|
||||
public BizOpsLaneTotalsOutput PreviousTotals { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>客户汇总。</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>订单状态快照(收件图角标)。</summary>
|
||||
public class BizOpsOrderStatusSnapshotOutput
|
||||
{
|
||||
public int Total { get; set; }
|
||||
public int Predeclared { get; set; }
|
||||
public int PendingPayment { get; set; }
|
||||
public int PendingShip { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>省域统计。</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>城市热点。</summary>
|
||||
public class BizOpsCityHotspotOutput
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Province { get; set; } = string.Empty;
|
||||
public double[] Value { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>目的国统计。</summary>
|
||||
public class BizOpsCountryStatOutput
|
||||
{
|
||||
/// <summary>geoJSON 英文名(前端着色用)。</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>线路统计。</summary>
|
||||
public class BizOpsLaneStatOutput
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>product | country。</summary>
|
||||
public string Dim { get; set; } = "product";
|
||||
|
||||
/// <summary>销售产品编码(产品维度)。</summary>
|
||||
public string? ProductCode { get; set; }
|
||||
|
||||
/// <summary>销售产品名称或国家展示名。</summary>
|
||||
public string Label { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>短标签(表行左侧)。</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>近 30 日均时效(天)。</summary>
|
||||
public List<decimal> DailyAvg { get; set; } = [];
|
||||
|
||||
/// <summary>近 30 日毛利。</summary>
|
||||
public List<decimal> DailyProfit { get; set; } = [];
|
||||
|
||||
public decimal? OrderCountGrowthPercent { get; set; }
|
||||
public decimal? RevenueGrowthPercent { get; set; }
|
||||
public decimal? GrossProfitGrowthPercent { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>线路合计。</summary>
|
||||
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; }
|
||||
}
|
||||
560
src/Oms.Application/Services/Orders/OrderService.BizOps.cs
Normal file
560
src/Oms.Application/Services/Orders/OrderService.BizOps.cs
Normal file
@ -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<string, (string Short, double Lng, double Lat)> 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<string, (string Name, string NameZh, double Lng, double Lat)> 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),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 经营地图工作台总览:发件省/目的国热力、销售产品或国家线路时效与营收毛利。
|
||||
/// </summary>
|
||||
/// <param name="rangeDays">统计天数:7 / 30 / 90,默认 30。</param>
|
||||
/// <param name="laneDim">线路维度:product=销售产品,country=目的国。</param>
|
||||
/// <param name="failDaysThreshold">失败时效告警阈值(天),默认 18。</param>
|
||||
/// <param name="marginRateThreshold">毛利率偏低阈值(0-1),默认 0.18。</param>
|
||||
[HttpGet("/order/biz-ops-overview")]
|
||||
public async Task<BizOpsOverviewOutput> 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<Dictionary<string, string>> LoadProductNameMapAsync(
|
||||
List<BizOpsOrderProjectionRow> 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<string, string>(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<BizOpsCustomerSummaryOutput> 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<BizOpsProvinceStatOutput> BuildProvinceStats(List<BizOpsOrderProjectionRow> 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<BizOpsCityHotspotOutput> BuildCityHotspots(List<BizOpsOrderProjectionRow> 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<BizOpsCountryStatOutput> BuildCountryStats(List<BizOpsOrderProjectionRow> 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<BizOpsLaneStatOutput> BuildLanes(
|
||||
List<BizOpsOrderProjectionRow> rows,
|
||||
Dictionary<int, BizOpsOrderFeeSumRow> feeMap,
|
||||
Dictionary<string, string> 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<BizOpsOrderProjectionRow> groupRows,
|
||||
Dictionary<int, BizOpsOrderFeeSumRow> 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<decimal>(30);
|
||||
var dailyProfit = new List<decimal>(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<BizOpsLaneStatOutput> 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;
|
||||
}
|
||||
}
|
||||
43
src/Oms.Domain/OrdersAggregate/BizOpsOrderProjectionRow.cs
Normal file
43
src/Oms.Domain/OrdersAggregate/BizOpsOrderProjectionRow.cs
Normal file
@ -0,0 +1,43 @@
|
||||
namespace Oms.Domain.OrdersAggregate;
|
||||
|
||||
/// <summary>
|
||||
/// 经营地图投影行(轻量字段,避免拉全量 Order)。
|
||||
/// </summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 订单费用按单汇总。
|
||||
/// </summary>
|
||||
public class BizOpsOrderFeeSumRow
|
||||
{
|
||||
public int OrderId { get; set; }
|
||||
|
||||
public decimal Receivable { get; set; }
|
||||
|
||||
public decimal Payable { get; set; }
|
||||
}
|
||||
@ -162,4 +162,20 @@ public interface IOrderRepository : IRepository<Order>
|
||||
DateTime endExclusive,
|
||||
bool usePayTime,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 经营地图:按创建时间拉取轻量投影(含发件省/市)。
|
||||
/// </summary>
|
||||
Task<List<BizOpsOrderProjectionRow>> ListBizOpsProjectionsByCreateTimeRangeAsync(
|
||||
OrderListFilter filter,
|
||||
DateTime startInclusive,
|
||||
DateTime endExclusive,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 经营地图:按订单汇总应收/应付费用。
|
||||
/// </summary>
|
||||
Task<List<BizOpsOrderFeeSumRow>> SumFeesByOrderIdsAsync(
|
||||
IEnumerable<int> orderIds,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@ -438,6 +438,17 @@ public class OrderRepository : OmsSqlSugarRepository<Order>, 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<Order>, IOrderRepository, I
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<List<BizOpsOrderProjectionRow>> ListBizOpsProjectionsByCreateTimeRangeAsync(
|
||||
OrderListFilter filter,
|
||||
DateTime startInclusive,
|
||||
DateTime endExclusive,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var db = await GetDbContextAsync(cancellationToken);
|
||||
var orderRows = await ApplyListFilter(db.Queryable<Order>(), 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<int, (string? Province, string? City)>();
|
||||
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<OrderSender>()
|
||||
.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<List<BizOpsOrderFeeSumRow>> SumFeesByOrderIdsAsync(
|
||||
IEnumerable<int> 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<int, BizOpsOrderFeeSumRow>();
|
||||
|
||||
async Task AccumulateAsync(string feeType, Action<BizOpsOrderFeeSumRow, decimal> apply)
|
||||
{
|
||||
for (var i = 0; i < ids.Length; i += batchSize)
|
||||
{
|
||||
var batch = ids.Skip(i).Take(batchSize).ToArray();
|
||||
var rows = await db.Queryable<OrderFee>()
|
||||
.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();
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user