All checks were successful
Build and Deploy / deploy (push) Successful in 1m23s
补齐访问审计与订单/财务侧数据权限接入,并增加公告批量确认已读接口。 Co-authored-by: Cursor <cursoragent@cursor.com>
412 lines
18 KiB
C#
412 lines
18 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
||
using Oms.Application.Dtos.Monitor;
|
||
using Oms.Application.Monitor;
|
||
using Oms.Domain.CustomersAggregate.Enums;
|
||
using Oms.Domain.OrdersAggregate;
|
||
using Oms.Domain.OrdersAggregate.Consts;
|
||
|
||
namespace Oms.Application.Services.Orders;
|
||
|
||
public partial class OrderService
|
||
{
|
||
/// <summary>
|
||
/// 实时监控页概览(订单/客户统计与趋势)。
|
||
/// </summary>
|
||
/// <param name="dimension">经营指标维度:day / week / month,默认 day。</param>
|
||
[HttpGet("/monitor/overview")]
|
||
public async Task<MonitorOverviewOutput> GetMonitorOverviewAsync(
|
||
[FromQuery] string? dimension = "day")
|
||
{
|
||
var dim = NormalizeMonitorDimension(dimension);
|
||
var (filter, _) = await BuildScopedListFilterAsync();
|
||
var today = DateTime.Today;
|
||
var tomorrow = today.AddDays(1);
|
||
var yesterday = today.AddDays(-1);
|
||
|
||
var rows = await OrderRepository.GetStatusCountsByFilterAsync(filter);
|
||
var counts = rows
|
||
.Where(x => !string.Equals(x.Status, OrderStatusCodes.Deleted, StringComparison.OrdinalIgnoreCase))
|
||
.ToDictionary(x => x.Status, x => x.Count, StringComparer.OrdinalIgnoreCase);
|
||
|
||
int GetCount(string status) =>
|
||
counts.TryGetValue(status, out var value) ? value : 0;
|
||
|
||
var pendingPayment = GetCount(OrderStatusCodes.PendingPayment);
|
||
var pendingOnline = GetCount(OrderStatusCodes.PendingOnline);
|
||
var pendingSign = GetCount(OrderStatusCodes.Shipping);
|
||
var problematic = GetCount(OrderStatusCodes.Problematic);
|
||
|
||
var (currentStart, currentEndExclusive, previousStart, previousEndExclusive) =
|
||
ResolveOpsPeriodRanges(dim, today, tomorrow);
|
||
|
||
var orderCount = await OrderRepository.CountByFilterAndCreateTimeRangeAsync(
|
||
filter, currentStart, currentEndExclusive);
|
||
var previousOrderCount = await OrderRepository.CountByFilterAndCreateTimeRangeAsync(
|
||
filter, previousStart, previousEndExclusive);
|
||
|
||
var revenue = await OrderRepository.SumFeeAmountByPayTimeRangeAsync(
|
||
filter, OrderFeeTypeCodes.Receivable, currentStart, currentEndExclusive);
|
||
var previousRevenue = await OrderRepository.SumFeeAmountByPayTimeRangeAsync(
|
||
filter, OrderFeeTypeCodes.Receivable, previousStart, previousEndExclusive);
|
||
|
||
var payable = await OrderRepository.SumFeeAmountByPayTimeRangeAsync(
|
||
filter, OrderFeeTypeCodes.Payable, currentStart, currentEndExclusive);
|
||
var previousPayable = await OrderRepository.SumFeeAmountByPayTimeRangeAsync(
|
||
filter, OrderFeeTypeCodes.Payable, previousStart, previousEndExclusive);
|
||
var grossProfit = revenue - payable;
|
||
var previousGrossProfit = previousRevenue - previousPayable;
|
||
|
||
// 兼容旧字段:始终提供「今日」口径
|
||
var todayCreated = dim == "day"
|
||
? orderCount
|
||
: await OrderRepository.CountByFilterAndCreateTimeRangeAsync(filter, today, tomorrow);
|
||
var yesterdayCreated = dim == "day"
|
||
? previousOrderCount
|
||
: await OrderRepository.CountByFilterAndCreateTimeRangeAsync(filter, yesterday, today);
|
||
var todayRevenue = dim == "day"
|
||
? revenue
|
||
: await OrderRepository.SumFeeAmountByPayTimeRangeAsync(
|
||
filter, OrderFeeTypeCodes.Receivable, today, tomorrow);
|
||
var yesterdayRevenue = dim == "day"
|
||
? previousRevenue
|
||
: await OrderRepository.SumFeeAmountByPayTimeRangeAsync(
|
||
filter, OrderFeeTypeCodes.Receivable, yesterday, today);
|
||
|
||
var monthStart = new DateTime(today.Year, today.Month, 1);
|
||
var lastMonthStart = monthStart.AddMonths(-1);
|
||
var thisMonthCreated = await OrderRepository.CountByFilterAndCreateTimeRangeAsync(filter, monthStart, tomorrow);
|
||
var lastMonthCreated = await OrderRepository.CountByFilterAndCreateTimeRangeAsync(filter, lastMonthStart, monthStart);
|
||
|
||
var trendCount = dim switch
|
||
{
|
||
"week" => 8,
|
||
"month" => 6,
|
||
_ => 7,
|
||
};
|
||
var orderTrend = await BuildMonitorOrderTrendAsync(filter, dim, trendCount);
|
||
var revenueTrend = await BuildMonitorRevenueTrendAsync(filter, dim, trendCount);
|
||
|
||
var recentFilter = CloneFilterWithCreateTimeStart(filter, today.AddDays(-90));
|
||
var recentOrders = await OrderRepository.GetFilteredListAsync(recentFilter);
|
||
var regionSignRates = BuildRegionSignRates(recentOrders);
|
||
var trackRates = BuildTrackRates(recentOrders);
|
||
|
||
var (weekOrderLabels, weekOrderSeries) = await BuildRegionOrderTrendAsync(filter, "week", 8);
|
||
var (monthOrderLabels, monthOrderSeries) = await BuildRegionOrderTrendAsync(filter, "month", 6);
|
||
var (weekRecvLabels, weekRecvSeries) = await BuildRegionReceivableTrendAsync(filter, "week", 8);
|
||
var (monthRecvLabels, monthRecvSeries) = await BuildRegionReceivableTrendAsync(filter, "month", 6);
|
||
|
||
var totalCustomers = await CustomerRepository.CountAsync(x => x.Status == CustomerStatus.Normal);
|
||
var newCustomersToday = await CustomerRepository.CountAsync(
|
||
x => x.Status == CustomerStatus.Normal && x.CreateTime >= today && x.CreateTime < tomorrow);
|
||
var newCustomersYesterday = await CustomerRepository.CountAsync(
|
||
x => x.Status == CustomerStatus.Normal && x.CreateTime >= yesterday && x.CreateTime < today);
|
||
var customersThisMonth = await CustomerRepository.CountAsync(
|
||
x => x.Status == CustomerStatus.Normal && x.CreateTime >= monthStart && x.CreateTime < tomorrow);
|
||
var customersLastMonth = await CustomerRepository.CountAsync(
|
||
x => x.Status == CustomerStatus.Normal && x.CreateTime >= lastMonthStart && x.CreateTime < monthStart);
|
||
var inactive7dThreshold = today.AddDays(-7);
|
||
var inactiveLogin7d = await CustomerRepository.CountAsync(
|
||
x => x.Status == CustomerStatus.Normal
|
||
&& (x.LastLoginTime == null || x.LastLoginTime < inactive7dThreshold));
|
||
var inactiveLogin14d = await CustomerRepository.CountAsync(
|
||
x => x.Status == CustomerStatus.Normal
|
||
&& (x.LastLoginTime == null || x.LastLoginTime < today.AddDays(-14)));
|
||
var onlineCustomers = await CustomerRepository.CountAsync(
|
||
x => x.Status == CustomerStatus.Normal
|
||
&& x.LastLoginTime != null
|
||
&& x.LastLoginTime >= DateTime.Now.AddMinutes(-30));
|
||
|
||
return new MonitorOverviewOutput
|
||
{
|
||
Order = new MonitorOrderStatsOutput
|
||
{
|
||
TodayCreated = todayCreated,
|
||
TodayCreatedGrowthPercent = CalcGrowthPercent(todayCreated, yesterdayCreated),
|
||
Total = counts.Values.Sum(),
|
||
TotalMonthGrowthPercent = CalcGrowthPercent(thisMonthCreated, lastMonthCreated),
|
||
PendingPayment = pendingPayment,
|
||
PendingOnline = pendingOnline,
|
||
PendingSign = pendingSign,
|
||
Problematic = problematic,
|
||
TodayRevenue = todayRevenue,
|
||
TodayRevenueGrowthPercent = CalcGrowthPercentDecimal(todayRevenue, yesterdayRevenue),
|
||
},
|
||
Ops = new MonitorOpsStatsOutput
|
||
{
|
||
Dimension = dim,
|
||
OrderCount = orderCount,
|
||
OrderCountGrowthPercent = CalcGrowthPercent(orderCount, previousOrderCount),
|
||
Revenue = revenue,
|
||
RevenueGrowthPercent = CalcGrowthPercentDecimal(revenue, previousRevenue),
|
||
GrossProfit = grossProfit,
|
||
GrossProfitGrowthPercent = CalcGrowthPercentDecimal(grossProfit, previousGrossProfit),
|
||
},
|
||
Queue = new MonitorQueueStatsOutput
|
||
{
|
||
PendingPayment = pendingPayment,
|
||
PendingOnline = pendingOnline,
|
||
PendingSign = pendingSign,
|
||
Problematic = problematic,
|
||
},
|
||
Customer = new MonitorCustomerStatsOutput
|
||
{
|
||
TotalCustomers = totalCustomers,
|
||
TotalCustomersMonthGrowthPercent = CalcGrowthPercent(customersThisMonth, customersLastMonth),
|
||
NewCustomersToday = newCustomersToday,
|
||
NewCustomersGrowthPercent = CalcGrowthPercent(newCustomersToday, newCustomersYesterday),
|
||
OnlineCustomers = onlineCustomers,
|
||
InactiveLogin7d = inactiveLogin7d,
|
||
InactiveLogin7dDelta = inactiveLogin7d - inactiveLogin14d,
|
||
},
|
||
OrderTrend = orderTrend,
|
||
OrderTrend7d = dim == "day" ? orderTrend : await BuildMonitorOrderTrendAsync(filter, "day", 7),
|
||
RevenueTrend = revenueTrend,
|
||
RevenueTrend7d = dim == "day" ? revenueTrend : await BuildMonitorRevenueTrendAsync(filter, "day", 7),
|
||
RegionOrderTrend = new MonitorRegionTrendBundleOutput
|
||
{
|
||
Week = new MonitorRegionTrendPeriodOutput { Labels = weekOrderLabels, Series = weekOrderSeries },
|
||
Month = new MonitorRegionTrendPeriodOutput { Labels = monthOrderLabels, Series = monthOrderSeries },
|
||
},
|
||
RegionReceivableTrend = new MonitorRegionTrendBundleOutput
|
||
{
|
||
Week = new MonitorRegionTrendPeriodOutput { Labels = weekRecvLabels, Series = weekRecvSeries },
|
||
Month = new MonitorRegionTrendPeriodOutput { Labels = monthRecvLabels, Series = monthRecvSeries },
|
||
},
|
||
RegionSignRates = regionSignRates,
|
||
TrackRates = trackRates,
|
||
};
|
||
}
|
||
|
||
private static string NormalizeMonitorDimension(string? dimension)
|
||
{
|
||
var dim = (dimension ?? "day").Trim().ToLowerInvariant();
|
||
return dim is "day" or "week" or "month" ? dim : "day";
|
||
}
|
||
|
||
/// <summary>
|
||
/// 当前周期(统计到今天结束)与上一完整同尺度周期。
|
||
/// </summary>
|
||
private static (DateTime CurrentStart, DateTime CurrentEndExclusive, DateTime PreviousStart, DateTime PreviousEndExclusive)
|
||
ResolveOpsPeriodRanges(string dimension, DateTime today, DateTime tomorrow)
|
||
{
|
||
if (dimension == "week")
|
||
{
|
||
var weekStart = GetWeekStart(today);
|
||
var previousWeekStart = weekStart.AddDays(-7);
|
||
return (weekStart, tomorrow, previousWeekStart, weekStart);
|
||
}
|
||
|
||
if (dimension == "month")
|
||
{
|
||
var monthStart = new DateTime(today.Year, today.Month, 1);
|
||
var previousMonthStart = monthStart.AddMonths(-1);
|
||
return (monthStart, tomorrow, previousMonthStart, monthStart);
|
||
}
|
||
|
||
var yesterday = today.AddDays(-1);
|
||
return (today, tomorrow, yesterday, today);
|
||
}
|
||
|
||
private async Task<List<MonitorTrendPointOutput>> BuildMonitorOrderTrendAsync(
|
||
OrderListFilter filter,
|
||
string dimension,
|
||
int count)
|
||
{
|
||
var buckets = BuildTrendBuckets(dimension, count);
|
||
var points = new List<MonitorTrendPointOutput>(buckets.Count);
|
||
foreach (var bucket in buckets)
|
||
{
|
||
var value = await OrderRepository.CountByFilterAndCreateTimeRangeAsync(
|
||
filter, bucket.Start, bucket.EndExclusive);
|
||
points.Add(new MonitorTrendPointOutput { Label = bucket.Label, Count = value });
|
||
}
|
||
|
||
return points;
|
||
}
|
||
|
||
private async Task<List<MonitorRevenueTrendPointOutput>> BuildMonitorRevenueTrendAsync(
|
||
OrderListFilter filter,
|
||
string dimension,
|
||
int count)
|
||
{
|
||
var buckets = BuildTrendBuckets(dimension, count);
|
||
var points = new List<MonitorRevenueTrendPointOutput>(buckets.Count);
|
||
foreach (var bucket in buckets)
|
||
{
|
||
var revenue = await OrderRepository.SumFeeAmountByPayTimeRangeAsync(
|
||
filter, OrderFeeTypeCodes.Receivable, bucket.Start, bucket.EndExclusive);
|
||
var payable = await OrderRepository.SumFeeAmountByPayTimeRangeAsync(
|
||
filter, OrderFeeTypeCodes.Payable, bucket.Start, bucket.EndExclusive);
|
||
points.Add(new MonitorRevenueTrendPointOutput
|
||
{
|
||
Label = bucket.Label,
|
||
Revenue = revenue,
|
||
GrossProfit = revenue - payable,
|
||
});
|
||
}
|
||
|
||
return points;
|
||
}
|
||
|
||
private async Task<(List<string> Labels, List<MonitorRegionSeriesOutput> Series)> BuildRegionOrderTrendAsync(
|
||
OrderListFilter filter,
|
||
string dimension,
|
||
int bucketCount)
|
||
{
|
||
var buckets = BuildTrendBuckets(dimension, bucketCount);
|
||
var labels = buckets.Select(x => x.Label).ToList();
|
||
var regionValues = MonitorRegionMapper.RegionKeys.ToDictionary(
|
||
key => key,
|
||
_ => new int[bucketCount],
|
||
StringComparer.OrdinalIgnoreCase);
|
||
|
||
for (var i = 0; i < buckets.Count; i++)
|
||
{
|
||
var orders = await OrderRepository.GetOrdersByFilterAndCreateTimeRangeAsync(
|
||
filter, buckets[i].Start, buckets[i].EndExclusive);
|
||
foreach (var group in orders.GroupBy(x => MonitorRegionMapper.MapCountryToRegion(x.ConsigneeCountry)))
|
||
{
|
||
if (!regionValues.ContainsKey(group.Key))
|
||
{
|
||
continue;
|
||
}
|
||
|
||
regionValues[group.Key][i] = group.Count();
|
||
}
|
||
}
|
||
|
||
var series = MonitorRegionMapper.RegionKeys
|
||
.Select(key => new MonitorRegionSeriesOutput
|
||
{
|
||
Region = key,
|
||
Values = regionValues[key].ToList(),
|
||
})
|
||
.ToList();
|
||
|
||
return (labels, series);
|
||
}
|
||
|
||
private async Task<(List<string> Labels, List<MonitorRegionSeriesOutput> Series)> BuildRegionReceivableTrendAsync(
|
||
OrderListFilter filter,
|
||
string dimension,
|
||
int bucketCount)
|
||
{
|
||
var buckets = BuildTrendBuckets(dimension, bucketCount);
|
||
var labels = buckets.Select(x => x.Label).ToList();
|
||
var regionValues = MonitorRegionMapper.RegionKeys.ToDictionary(
|
||
key => key,
|
||
_ => new int[bucketCount],
|
||
StringComparer.OrdinalIgnoreCase);
|
||
|
||
for (var i = 0; i < buckets.Count; i++)
|
||
{
|
||
var orders = await OrderRepository.GetOrdersByFilterAndCreateTimeRangeAsync(
|
||
filter, buckets[i].Start, buckets[i].EndExclusive);
|
||
foreach (var group in orders.GroupBy(x => MonitorRegionMapper.MapCountryToRegion(x.ConsigneeCountry)))
|
||
{
|
||
if (!regionValues.ContainsKey(group.Key))
|
||
{
|
||
continue;
|
||
}
|
||
|
||
// 以订单数 * 100 作为应收趋势相对值(避免逐单查 fee 过慢)
|
||
regionValues[group.Key][i] = group.Count() * 100;
|
||
}
|
||
}
|
||
|
||
var series = MonitorRegionMapper.RegionKeys
|
||
.Select(key => new MonitorRegionSeriesOutput
|
||
{
|
||
Region = key,
|
||
Values = regionValues[key].ToList(),
|
||
})
|
||
.ToList();
|
||
|
||
return (labels, series);
|
||
}
|
||
|
||
private static List<MonitorRegionRateOutput> BuildRegionSignRates(IReadOnlyCollection<Domain.OrdersAggregate.Entities.Order> orders)
|
||
{
|
||
return MonitorRegionMapper.RegionKeys
|
||
.Select(region =>
|
||
{
|
||
var regionOrders = orders
|
||
.Where(x => MonitorRegionMapper.MapCountryToRegion(x.ConsigneeCountry) == region)
|
||
.ToList();
|
||
var success = regionOrders.Count(x => MonitorRegionMapper.IsDeliveredStatus(x.OrderStatus));
|
||
var failed = regionOrders.Count(x => MonitorRegionMapper.IsDeliveryFailedStatus(x.OrderStatus));
|
||
var total = success + failed;
|
||
var rate = total == 0 ? 0m : Math.Round(success * 100m / total, 1);
|
||
return new MonitorRegionRateOutput { Region = region, Rate = rate };
|
||
})
|
||
.ToList();
|
||
}
|
||
|
||
private static MonitorTrackRatesOutput BuildTrackRates(IReadOnlyCollection<Domain.OrdersAggregate.Entities.Order> orders)
|
||
{
|
||
var active = orders.Where(x => !string.Equals(x.OrderStatus, OrderStatusCodes.Deleted, StringComparison.OrdinalIgnoreCase)).ToList();
|
||
var delivered = active.Count(x => MonitorRegionMapper.IsDeliveredStatus(x.OrderStatus));
|
||
var failed = active.Count(x => MonitorRegionMapper.IsDeliveryFailedStatus(x.OrderStatus));
|
||
var inTransit = active.Count(x => MonitorRegionMapper.IsInTransitStatus(x.OrderStatus));
|
||
var finished = delivered + failed;
|
||
var completeBase = finished + inTransit;
|
||
|
||
var completeRate = completeBase == 0 ? 0m : Math.Round((delivered + inTransit) * 100m / completeBase, 1);
|
||
var timelyRate = finished == 0 ? 0m : Math.Round(delivered * 100m / finished, 1);
|
||
var otdRate = finished == 0 ? 0m : Math.Round(delivered * 100m / finished, 1);
|
||
|
||
return new MonitorTrackRatesOutput
|
||
{
|
||
TrackCompleteRate = completeRate,
|
||
TrackTimelyRate = timelyRate,
|
||
OtdRate = otdRate,
|
||
};
|
||
}
|
||
|
||
private static OrderListFilter CloneFilterWithCreateTimeStart(OrderListFilter filter, DateTime start)
|
||
{
|
||
return new OrderListFilter
|
||
{
|
||
Status = filter.Status,
|
||
HandleStatus = filter.HandleStatus,
|
||
OrderSource = filter.OrderSource,
|
||
Keyword = filter.Keyword,
|
||
CreateTimeStart = start,
|
||
CreateTimeEnd = filter.CreateTimeEnd,
|
||
CustomerId = filter.CustomerId,
|
||
FieldFilters = filter.FieldFilters,
|
||
SortField = filter.SortField,
|
||
SortOrder = filter.SortOrder,
|
||
ScopeOrganizationIds = filter.ScopeOrganizationIds,
|
||
ScopeSecretLevels = filter.ScopeSecretLevels,
|
||
ScopeDataScope = filter.ScopeDataScope,
|
||
ScopePersonalOwnerMapId = filter.ScopePersonalOwnerMapId,
|
||
ScopePersonalOwnerAccount = filter.ScopePersonalOwnerAccount,
|
||
ScopeOwnerMapIds = filter.ScopeOwnerMapIds,
|
||
ScopeBizFilters = filter.ScopeBizFilters,
|
||
ScopeCustomFilters = filter.ScopeCustomFilters,
|
||
};
|
||
}
|
||
|
||
private static decimal? CalcGrowthPercent(int current, int previous)
|
||
{
|
||
if (previous > 0)
|
||
{
|
||
return Math.Round((current - previous) * 100m / previous, 1);
|
||
}
|
||
|
||
return current > 0 ? 100m : null;
|
||
}
|
||
|
||
private static decimal? CalcGrowthPercentDecimal(decimal current, decimal previous)
|
||
{
|
||
if (previous > 0)
|
||
{
|
||
return Math.Round((current - previous) * 100m / previous, 1);
|
||
}
|
||
|
||
return current > 0 ? 100m : null;
|
||
}
|
||
}
|