From 6b00451914764a11a4c2768254d4088908eaf506 Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Tue, 10 Nov 2026 18:32:39 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=90=A5=E9=94=80/=E4=BB=A3=E7=90=86?= =?UTF-8?q?=E5=88=86=E6=9E=90=E6=B1=87=E6=80=BB=20API=EF=BC=8C=E5=B9=B6?= =?UTF-8?q?=E8=A1=A5=E5=BA=94=E6=94=B6=E5=BA=94=E4=BB=98=E4=BB=A3=E7=90=86?= =?UTF-8?q?=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为老板看板提供服务端区间汇总(总览、排行/漏斗与导出),应收应付列表带上 AgentId 供财务分析代理维使用。 Co-authored-by: Cursor --- .../Dtos/Agents/AgentAnalysisDtos.cs | 154 +++++++ .../ReceivablePayablePaginatedInput.cs | 15 + .../ReceivablePayablePaginatedOutput.cs | 9 + .../Dtos/Marketing/MarketingAnalysisDtos.cs | 205 +++++++++ .../Services/Agents/AgentAnalysisService.cs | 377 +++++++++++++++++ .../Services/Finance/FinanceService.cs | 30 ++ .../Marketing/MarketingAnalysisService.cs | 392 ++++++++++++++++++ .../Repositories/IMarketingRepositories.cs | 29 ++ .../OrdersAggregate/AgentAnalysisOrderRow.cs | 20 + .../MarketingOrderSnapshotRow.cs | 22 + .../OrderReceivablePayableFilter.cs | 10 + .../Repositories/IOrderRepository.cs | 18 + .../Marketing/MarketingRepositories.cs | 41 ++ .../Orders/OrderRepository.cs | 99 +++++ 14 files changed, 1421 insertions(+) create mode 100644 src/Oms.Application/Dtos/Agents/AgentAnalysisDtos.cs create mode 100644 src/Oms.Application/Dtos/Marketing/MarketingAnalysisDtos.cs create mode 100644 src/Oms.Application/Services/Agents/AgentAnalysisService.cs create mode 100644 src/Oms.Application/Services/Marketing/MarketingAnalysisService.cs create mode 100644 src/Oms.Domain/OrdersAggregate/AgentAnalysisOrderRow.cs create mode 100644 src/Oms.Domain/OrdersAggregate/MarketingOrderSnapshotRow.cs diff --git a/src/Oms.Application/Dtos/Agents/AgentAnalysisDtos.cs b/src/Oms.Application/Dtos/Agents/AgentAnalysisDtos.cs new file mode 100644 index 0000000..e286da8 --- /dev/null +++ b/src/Oms.Application/Dtos/Agents/AgentAnalysisDtos.cs @@ -0,0 +1,154 @@ +namespace Oms.Application.Dtos.Agents; + +/// +/// 代理分析查询入参。 +/// +public class AgentAnalysisQueryInput +{ + /// 区间开始(含)。 + public DateTime? StartTime { get; set; } + + /// 区间结束(含)。 + public DateTime? EndTime { get; set; } + + /// 时间字段:payTime(默认)/ createTime。 + public string? TimeField { get; set; } + + /// 排行条数,默认 20。 + public int TopN { get; set; } = 20; +} + +/// +/// 代理分析总览。 +/// +public class AgentAnalysisOverviewOutput +{ + /// 当前区间 KPI。 + public AgentAnalysisKpiOutput Kpis { get; set; } = new(); + + /// 上一同等天数 KPI。 + public AgentAnalysisKpiOutput PreviousKpis { get; set; } = new(); + + /// 环比:金额/数量为百分数;比率类为百分点差。 + public AgentAnalysisGrowthOutput Growth { get; set; } = new(); + + /// 日趋势。 + public List Trend { get; set; } = []; +} + +/// +/// 代理分析 KPI。 +/// +public class AgentAnalysisKpiOutput +{ + /// 代理归因订单数(Order.AgentId)。 + public int OrderCount { get; set; } + + /// 折前 GMV。 + public decimal GmvPreDiscount { get; set; } + + /// 客户实收。 + public decimal CustomerPaid { get; set; } + + /// 区间计提返佣(CreateTime,排除 void)。 + public decimal CommissionAccrued { get; set; } + + /// 预计返佣(estimated)。 + public decimal CommissionEstimated { get; set; } + + /// 待结算返佣(pending)。 + public decimal CommissionPending { get; set; } + + /// 区间已打款(PaidTime 落入区间)。 + public decimal CommissionPaid { get; set; } + + /// 返佣率 = 计提返佣 / 折前 GMV;无 GMV 时为 null。 + public decimal? CommissionRate { get; set; } + + /// 区间新绑客户数(主客户)。 + public int NewBindCount { get; set; } + + /// 新绑且区间内有归因单的客户数。 + public int ConvertedBindCount { get; set; } + + /// 转化率 = Converted / NewBind;无新绑时为 null。 + public decimal? ConversionRate { get; set; } +} + +/// +/// KPI 环比。 +/// +public class AgentAnalysisGrowthOutput +{ + public decimal? OrderCount { get; set; } + + public decimal? GmvPreDiscount { get; set; } + + public decimal? CustomerPaid { get; set; } + + public decimal? CommissionAccrued { get; set; } + + public decimal? CommissionPending { get; set; } + + public decimal? CommissionPaid { get; set; } + + /// 返佣率百分点差。 + public decimal? CommissionRate { get; set; } + + public decimal? NewBindCount { get; set; } + + /// 转化率百分点差。 + public decimal? ConversionRate { get; set; } +} + +/// +/// 日趋势点。 +/// +public class AgentAnalysisTrendPointOutput +{ + /// 日期 yyyy-MM-dd。 + public string Date { get; set; } = string.Empty; + + public int OrderCount { get; set; } + + public decimal CommissionAccrued { get; set; } + + public int NewBindCount { get; set; } +} + +/// +/// 代理排行。 +/// +public class AgentAnalysisRankingOutput +{ + public List Agents { get; set; } = []; +} + +/// +/// 代理排行行。 +/// +public class AgentAnalysisRankItemOutput +{ + public int AgentId { get; set; } + + public string AgentCode { get; set; } = string.Empty; + + public string AgentName { get; set; } = string.Empty; + + public int OrderCount { get; set; } + + public decimal GmvPreDiscount { get; set; } + + public decimal CommissionAccrued { get; set; } + + /// 返佣率。 + public decimal? CommissionRate { get; set; } + + public int NewBindCount { get; set; } + + /// 转化率。 + public decimal? ConversionRate { get; set; } + + /// 待结算返佣(区间计提口径下的 pending)。 + public decimal CommissionPending { get; set; } +} diff --git a/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedInput.cs b/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedInput.cs index ce68e6b..1005738 100644 --- a/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedInput.cs +++ b/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedInput.cs @@ -36,6 +36,21 @@ public class ReceivablePayablePaginatedInput /// public string? CustomerCode { get; set; } + /// + /// 产品编码(精确匹配,财务分析下钻)。 + /// + public string? ProductCode { get; set; } + + /// + /// 渠道编码(精确匹配,财务分析下钻)。 + /// + public string? ChannelCode { get; set; } + + /// + /// 代理快照 Id(Order.AgentId,财务分析下钻)。 + /// + public int? AgentId { get; set; } + /// /// 仅保留各运单费用项的当前生效阶段。 /// diff --git a/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedOutput.cs b/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedOutput.cs index b39a291..7d4b303 100644 --- a/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedOutput.cs +++ b/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedOutput.cs @@ -15,6 +15,12 @@ public class ReceivablePayablePaginatedOutput public string? CustomerCode { get; set; } + /// 下单时代理快照(Order.AgentId)。 + public int? AgentId { get; set; } + + /// 代理名称(由 AgentId 解析)。 + public string? AgentName { get; set; } + public string OrderStatus { get; set; } = string.Empty; public string? OrderStatusName { get; set; } @@ -27,6 +33,9 @@ public class ReceivablePayablePaginatedOutput public DateTime? ShipTime { get; set; } + /// 订单创建时间(趋势分桶用)。 + public DateTime? CreateTime { get; set; } + public string? ProductCode { get; set; } public string? ChannelCode { get; set; } diff --git a/src/Oms.Application/Dtos/Marketing/MarketingAnalysisDtos.cs b/src/Oms.Application/Dtos/Marketing/MarketingAnalysisDtos.cs new file mode 100644 index 0000000..9033c63 --- /dev/null +++ b/src/Oms.Application/Dtos/Marketing/MarketingAnalysisDtos.cs @@ -0,0 +1,205 @@ +namespace Oms.Application.Dtos.Marketing; + +/// +/// 营销分析查询入参。 +/// +public class MarketingAnalysisQueryInput +{ + /// 区间开始(含)。 + public DateTime? StartTime { get; set; } + + /// 区间结束(含)。 + public DateTime? EndTime { get; set; } + + /// 时间字段:payTime(默认)/ createTime。 + public string? TimeField { get; set; } + + /// 优惠券模板排行条数,默认 20。 + public int TopN { get; set; } = 20; +} + +/// +/// 营销分析总览。 +/// +public class MarketingAnalysisOverviewOutput +{ + /// 当前区间 KPI。 + public MarketingAnalysisKpiOutput Kpis { get; set; } = new(); + + /// 上一同等天数 KPI(用于环比)。 + public MarketingAnalysisKpiOutput PreviousKpis { get; set; } = new(); + + /// 环比:金额/数量为百分数(12.3=+12.3%);比率类为百分点差。 + public MarketingAnalysisGrowthOutput Growth { get; set; } = new(); + + /// 日趋势。 + public List Trend { get; set; } = []; + + /// 折扣构成(券 vs 会员)。 + public MarketingAnalysisDiscountMixOutput DiscountMix { get; set; } = new(); +} + +/// +/// 营销分析 KPI。 +/// +public class MarketingAnalysisKpiOutput +{ + /// 折前 GMV(ReceivableSubtotal 合计)。 + public decimal GmvPreDiscount { get; set; } + + /// 优惠券折扣合计。 + public decimal CouponDiscount { get; set; } + + /// 会员折扣合计。 + public decimal LevelDiscount { get; set; } + + /// 营销成本 = 券折扣 + 会员折扣。 + public decimal MarketingCost { get; set; } + + /// 折扣率 = 营销成本 / 折前 GMV;无 GMV 时为 null。 + public decimal? DiscountRate { get; set; } + + /// 客户实收(PayableAmount 合计)。 + public decimal CustomerPaid { get; set; } + + /// 订单数。 + public int OrderCount { get; set; } + + /// 用券订单数。 + public int CouponOrderCount { get; set; } + + /// 用券订单占比;无订单时为 null。 + public decimal? CouponOrderRate { get; set; } +} + +/// +/// KPI 环比(相对上一同等天数)。金额/数量为增长率;折扣率/用券占比为百分点差。 +/// +public class MarketingAnalysisGrowthOutput +{ + /// 折前 GMV 环比增长率。 + public decimal? GmvPreDiscount { get; set; } + + /// 营销成本环比增长率。 + public decimal? MarketingCost { get; set; } + + /// 折扣率环比百分点差。 + public decimal? DiscountRate { get; set; } + + /// 客户实收环比增长率。 + public decimal? CustomerPaid { get; set; } + + /// 订单数环比增长率。 + public decimal? OrderCount { get; set; } + + /// 用券订单数环比增长率。 + public decimal? CouponOrderCount { get; set; } + + /// 用券占比环比百分点差。 + public decimal? CouponOrderRate { get; set; } +} + +/// +/// 总览日趋势点。 +/// +public class MarketingAnalysisTrendPointOutput +{ + /// 日期 yyyy-MM-dd。 + public string Date { get; set; } = string.Empty; + + /// 折前 GMV。 + public decimal GmvPreDiscount { get; set; } + + /// 营销成本。 + public decimal MarketingCost { get; set; } + + /// 客户实收。 + public decimal CustomerPaid { get; set; } +} + +/// +/// 折扣构成。 +/// +public class MarketingAnalysisDiscountMixOutput +{ + /// 券折扣。 + public decimal CouponDiscount { get; set; } + + /// 会员折扣。 + public decimal LevelDiscount { get; set; } +} + +/// +/// 优惠券分析。 +/// +public class MarketingAnalysisCouponsOutput +{ + /// 区间漏斗。 + public MarketingCouponFunnelOutput Funnel { get; set; } = new(); + + /// 当前可用券张数(时点负债,不参与环比)。 + public int AvailableLiability { get; set; } + + /// 模板排行。 + public List Templates { get; set; } = []; +} + +/// +/// 优惠券漏斗。 +/// +public class MarketingCouponFunnelOutput +{ + /// 发出张数(ReceiveTime 落入区间)。 + public int Issued { get; set; } + + /// 核销张数(UseTime 落入且已用)。 + public int Used { get; set; } + + /// 过期张数(Expired 且 ValidEndTime 落入区间)。 + public int Expired { get; set; } + + /// 核销率 = Used/Issued;发出为 0 时为 null。 + public decimal? RedemptionRate { get; set; } +} + +/// +/// 优惠券模板排行行。 +/// +public class MarketingCouponTemplateRankOutput +{ + /// 模板 Id。 + public int TemplateId { get; set; } + + /// 模板编码。 + public string TemplateCode { get; set; } = string.Empty; + + /// 模板名称。 + public string TemplateName { get; set; } = string.Empty; + + /// 发放渠道。 + public string GrantChannel { get; set; } = string.Empty; + + /// 发出。 + public int Issued { get; set; } + + /// 核销。 + public int Used { get; set; } + + /// 过期。 + public int Expired { get; set; } + + /// 核销率。 + public decimal? RedemptionRate { get; set; } + + /// 拉动单量(区间内用券订单数)。 + public int OrderCount { get; set; } + + /// 折扣额。 + public decimal DiscountAmount { get; set; } + + /// 用券单折前 GMV。 + public decimal GmvPreDiscount { get; set; } + + /// 折扣占 GMV;无 GMV 时为 null。 + public decimal? DiscountToGmvRate { get; set; } +} diff --git a/src/Oms.Application/Services/Agents/AgentAnalysisService.cs b/src/Oms.Application/Services/Agents/AgentAnalysisService.cs new file mode 100644 index 0000000..b2bfe89 --- /dev/null +++ b/src/Oms.Application/Services/Agents/AgentAnalysisService.cs @@ -0,0 +1,377 @@ +using Fake.Application; +using Fake.Domain.Exceptions; +using Microsoft.AspNetCore.Mvc; +using MiniExcelLibs; +using Oms.Application.Dtos.Agents; +using Oms.Domain.AgentsAggregate.Consts; +using Oms.Domain.AgentsAggregate.Repositories; +using Oms.Domain.CustomersAggregate.Repositories; +using Oms.Domain.OrdersAggregate; +using Oms.Domain.OrdersAggregate.Repositories; + +namespace Oms.Application.Services.Agents; + +/// +/// 代理分析 API(管理端总览 + 排行;与财务分析代理 Tab 错开:偏返佣/获客/转化)。 +/// +[ApiExplorerSettings(GroupName = "OMS-Agent")] +public class AgentAnalysisService : ApplicationService +{ + private IOrderRepository OrderRepository => + LazyServiceProvider.GetRequiredService(); + + private IAgentRepository AgentRepository => + LazyServiceProvider.GetRequiredService(); + + private IAgentCommissionDetailRepository DetailRepository => + LazyServiceProvider.GetRequiredService(); + + private ICustomerRepository CustomerRepository => + LazyServiceProvider.GetRequiredService(); + + /// + /// 代理分析总览:归因票量/GMV/实收、返佣三态、新绑与转化、日趋势与环比。 + /// + [HttpGet("/agent/admin/analysis/overview")] + public async Task GetOverviewAsync( + [FromQuery] AgentAnalysisQueryInput input) + { + var (start, endExclusive, usePayTime) = NormalizeRange(input); + var (prevStart, prevEndExclusive) = PreviousRange(start, endExclusive); + + var current = await LoadPeriodAsync(start, endExclusive, usePayTime); + var previous = await LoadPeriodAsync(prevStart, prevEndExclusive, usePayTime); + + var kpis = BuildKpis(current); + var previousKpis = BuildKpis(previous); + + return new AgentAnalysisOverviewOutput + { + Kpis = kpis, + PreviousKpis = previousKpis, + Growth = BuildGrowth(kpis, previousKpis), + Trend = BuildTrend(current, start, endExclusive) + }; + } + + /// + /// 代理排行:票量、GMV、计提返佣、返佣率、新绑、转化、待结算。 + /// + [HttpGet("/agent/admin/analysis/ranking")] + public async Task GetRankingAsync( + [FromQuery] AgentAnalysisQueryInput input) + { + return await BuildRankingAsync(input); + } + + /// + /// 导出代理排行 Excel。 + /// + [HttpGet("/agent/admin/analysis/ranking/export")] + public async Task ExportRankingAsync( + [FromQuery] AgentAnalysisQueryInput input) + { + var data = await BuildRankingAsync(input); + var exportRows = data.Agents.Select(item => new + { + 代理编码 = item.AgentCode, + 代理名称 = item.AgentName, + 订单数 = item.OrderCount, + 折前GMV = item.GmvPreDiscount, + 计提返佣 = item.CommissionAccrued, + 返佣率 = item.CommissionRate, + 新绑客户 = item.NewBindCount, + 转化率 = item.ConversionRate, + 待结算返佣 = item.CommissionPending + }).ToList(); + + await using var stream = new MemoryStream(); + await MiniExcel.SaveAsAsync(stream, exportRows); + stream.Position = 0; + return new FileContentResult( + stream.ToArray(), + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") + { + FileDownloadName = $"agent-analysis-{DateTime.Now:yyyyMMddHHmmss}.xlsx" + }; + } + + private async Task BuildRankingAsync(AgentAnalysisQueryInput input) + { + var (start, endExclusive, usePayTime) = NormalizeRange(input); + var topN = input.TopN <= 0 ? 20 : Math.Min(input.TopN, 100); + var period = await LoadPeriodAsync(start, endExclusive, usePayTime); + + var agentIds = period.Orders.Select(x => x.AgentId) + .Concat(period.Commissions.Select(x => x.AgentId)) + .Concat(period.NewBinds.Select(x => x.AgentId!.Value)) + .Distinct() + .ToArray(); + + var agents = agentIds.Length == 0 + ? [] + : await AgentRepository.GetListAsync(x => agentIds.Contains(x.Id)); + var agentMap = agents.ToDictionary(x => x.Id); + + var orderByAgent = period.Orders + .GroupBy(x => x.AgentId) + .ToDictionary( + g => g.Key, + g => ( + OrderCount: g.Count(), + Gmv: g.Sum(x => x.ReceivableSubtotal ?? 0m), + Customers: g.Where(x => x.CustomerId.HasValue) + .Select(x => x.CustomerId!.Value) + .ToHashSet())); + + var commissionByAgent = period.Commissions + .GroupBy(x => x.AgentId) + .ToDictionary( + g => g.Key, + g => ( + Accrued: g.Where(x => !IsVoid(x.Status)).Sum(x => x.CommissionAmount), + Pending: g.Where(x => IsPending(x.Status)).Sum(x => x.CommissionAmount))); + + var bindsByAgent = period.NewBinds + .GroupBy(x => x.AgentId!.Value) + .ToDictionary(g => g.Key, g => g.ToList()); + + var ranks = agentIds + .Select(agentId => + { + agentMap.TryGetValue(agentId, out var agent); + orderByAgent.TryGetValue(agentId, out var oa); + commissionByAgent.TryGetValue(agentId, out var ca); + bindsByAgent.TryGetValue(agentId, out var binds); + var newBindCount = binds?.Count ?? 0; + var converted = 0; + if (binds != null && oa.Customers != null) + { + converted = binds.Count(b => oa.Customers.Contains(b.Id)); + } + + var gmv = oa.Gmv; + var accrued = ca.Accrued; + return new AgentAnalysisRankItemOutput + { + AgentId = agentId, + AgentCode = agent?.AgentCode ?? string.Empty, + AgentName = agent?.AgentName ?? $"#{agentId}", + OrderCount = oa.OrderCount, + GmvPreDiscount = gmv, + CommissionAccrued = accrued, + CommissionRate = gmv > 0 ? Math.Round(accrued / gmv, 4) : null, + NewBindCount = newBindCount, + ConversionRate = newBindCount > 0 + ? Math.Round((decimal)converted / newBindCount, 4) + : null, + CommissionPending = ca.Pending + }; + }) + .OrderByDescending(x => x.CommissionAccrued) + .ThenByDescending(x => x.OrderCount) + .ThenByDescending(x => x.GmvPreDiscount) + .Take(topN) + .ToList(); + + return new AgentAnalysisRankingOutput { Agents = ranks }; + } + + private async Task LoadPeriodAsync( + DateTime start, + DateTime endExclusive, + bool usePayTime) + { + var ordersTask = OrderRepository.ListAgentAnalysisOrdersByTimeRangeAsync( + start, endExclusive, usePayTime); + var commissionsTask = DetailRepository.GetListAsync(x => + x.CreateTime >= start && x.CreateTime < endExclusive); + var paidTask = DetailRepository.GetListAsync(x => + x.Status == AgentCommissionStatusCodes.Paid + && x.PaidTime != null + && x.PaidTime >= start + && x.PaidTime < endExclusive); + var bindsTask = CustomerRepository.GetListAsync(x => + x.ParentCustomerId == null + && x.AgentId != null + && x.AgentId > 0 + && x.AgentBindTime != null + && x.AgentBindTime >= start + && x.AgentBindTime < endExclusive); + + await Task.WhenAll(ordersTask, commissionsTask, paidTask, bindsTask); + + return new PeriodBundle + { + Orders = await ordersTask, + Commissions = await commissionsTask, + PaidInPeriod = await paidTask, + NewBinds = await bindsTask + }; + } + + private static AgentAnalysisKpiOutput BuildKpis(PeriodBundle period) + { + var orderCount = period.Orders.Count; + var gmv = period.Orders.Sum(x => x.ReceivableSubtotal ?? 0m); + var paid = period.Orders.Sum(x => x.PayableAmount ?? 0m); + + var estimated = period.Commissions + .Where(x => IsEstimated(x.Status)) + .Sum(x => x.CommissionAmount); + var pending = period.Commissions + .Where(x => IsPending(x.Status)) + .Sum(x => x.CommissionAmount); + var accrued = period.Commissions + .Where(x => !IsVoid(x.Status)) + .Sum(x => x.CommissionAmount); + var paidAmount = period.PaidInPeriod.Sum(x => x.CommissionAmount); + + var newBindCount = period.NewBinds.Count; + var orderCustomers = period.Orders + .Where(x => x.CustomerId.HasValue) + .Select(x => (x.AgentId, x.CustomerId!.Value)) + .ToHashSet(); + var converted = period.NewBinds.Count(b => + b.AgentId.HasValue && orderCustomers.Contains((b.AgentId.Value, b.Id))); + + return new AgentAnalysisKpiOutput + { + OrderCount = orderCount, + GmvPreDiscount = gmv, + CustomerPaid = paid, + CommissionAccrued = accrued, + CommissionEstimated = estimated, + CommissionPending = pending, + CommissionPaid = paidAmount, + CommissionRate = gmv > 0 ? Math.Round(accrued / gmv, 4) : null, + NewBindCount = newBindCount, + ConvertedBindCount = converted, + ConversionRate = newBindCount > 0 + ? Math.Round((decimal)converted / newBindCount, 4) + : null + }; + } + + private static AgentAnalysisGrowthOutput BuildGrowth( + AgentAnalysisKpiOutput current, + AgentAnalysisKpiOutput previous) + { + return new AgentAnalysisGrowthOutput + { + OrderCount = RateGrowth(current.OrderCount, previous.OrderCount), + GmvPreDiscount = RateGrowth(current.GmvPreDiscount, previous.GmvPreDiscount), + CustomerPaid = RateGrowth(current.CustomerPaid, previous.CustomerPaid), + CommissionAccrued = RateGrowth(current.CommissionAccrued, previous.CommissionAccrued), + CommissionPending = RateGrowth(current.CommissionPending, previous.CommissionPending), + CommissionPaid = RateGrowth(current.CommissionPaid, previous.CommissionPaid), + CommissionRate = PointDiff(current.CommissionRate, previous.CommissionRate), + NewBindCount = RateGrowth(current.NewBindCount, previous.NewBindCount), + ConversionRate = PointDiff(current.ConversionRate, previous.ConversionRate) + }; + } + + private static List BuildTrend( + PeriodBundle period, + DateTime start, + DateTime endExclusive) + { + var orderMap = period.Orders + .GroupBy(x => x.BucketTime.Date) + .ToDictionary(g => g.Key, g => g.Count()); + var commissionMap = period.Commissions + .Where(x => !IsVoid(x.Status)) + .GroupBy(x => x.CreateTime.Date) + .ToDictionary(g => g.Key, g => g.Sum(x => x.CommissionAmount)); + var bindMap = period.NewBinds + .GroupBy(x => x.AgentBindTime!.Value.Date) + .ToDictionary(g => g.Key, g => g.Count()); + + var points = new List(); + for (var day = start.Date; day < endExclusive; day = day.AddDays(1)) + { + orderMap.TryGetValue(day, out var orders); + commissionMap.TryGetValue(day, out var commission); + bindMap.TryGetValue(day, out var binds); + points.Add(new AgentAnalysisTrendPointOutput + { + Date = day.ToString("yyyy-MM-dd"), + OrderCount = orders, + CommissionAccrued = commission, + NewBindCount = binds + }); + if (points.Count > 400) break; + } + + return points; + } + + private static (DateTime Start, DateTime EndExclusive, bool UsePayTime) NormalizeRange( + AgentAnalysisQueryInput input) + { + if (!input.StartTime.HasValue || !input.EndTime.HasValue) + { + throw new BusinessException("请选择分析时间区间"); + } + + var start = input.StartTime.Value; + var end = input.EndTime.Value; + if (end < start) + { + throw new BusinessException("结束时间不能早于开始时间"); + } + + var endExclusive = end.TimeOfDay == TimeSpan.Zero && end == end.Date + ? end.Date.AddDays(1) + : end.AddMilliseconds(1); + + var usePayTime = !string.Equals(input.TimeField, "createTime", StringComparison.OrdinalIgnoreCase); + return (start, endExclusive, usePayTime); + } + + private static (DateTime PrevStart, DateTime PrevEndExclusive) PreviousRange( + DateTime start, + DateTime endExclusive) + { + var duration = endExclusive - start; + if (duration <= TimeSpan.Zero) duration = TimeSpan.FromDays(1); + var prevEndExclusive = start; + var prevStart = prevEndExclusive - duration; + return (prevStart, prevEndExclusive); + } + + private static decimal? RateGrowth(decimal current, decimal previous) + { + if (previous == 0) return current == 0 ? 0 : null; + return Math.Round((current - previous) / previous * 100m, 1); + } + + private static decimal? RateGrowth(int current, int previous) + => RateGrowth((decimal)current, previous); + + private static decimal? PointDiff(decimal? current, decimal? previous) + { + if (current == null || previous == null) return null; + return Math.Round((current.Value - previous.Value) * 100m, 1); + } + + private static bool IsEstimated(string? status) => + string.Equals(status, AgentCommissionStatusCodes.Estimated, StringComparison.OrdinalIgnoreCase); + + private static bool IsPending(string? status) => + string.Equals(status, AgentCommissionStatusCodes.Pending, StringComparison.OrdinalIgnoreCase); + + private static bool IsVoid(string? status) => + string.Equals(status, AgentCommissionStatusCodes.Void, StringComparison.OrdinalIgnoreCase); + + private sealed class PeriodBundle + { + public List Orders { get; init; } = []; + + public List Commissions { get; init; } = []; + + public List PaidInPeriod { get; init; } = []; + + public List NewBinds { get; init; } = []; + } +} diff --git a/src/Oms.Application/Services/Finance/FinanceService.cs b/src/Oms.Application/Services/Finance/FinanceService.cs index 6a3021d..04142c2 100644 --- a/src/Oms.Application/Services/Finance/FinanceService.cs +++ b/src/Oms.Application/Services/Finance/FinanceService.cs @@ -7,6 +7,7 @@ using Oms.Application.Dtos.Finance; using Oms.Application.Dtos.Shared; using Oms.Application.Services.Orders; using Oms.Application.Shared; +using Oms.Domain.AgentsAggregate.Repositories; using Oms.Domain.CustomersAggregate.Repositories; using Oms.Domain.OrdersAggregate; using Oms.Domain.OrdersAggregate.Consts; @@ -30,6 +31,9 @@ public class FinanceService : ApplicationService private ICustomerRepository CustomerRepository => LazyServiceProvider.GetRequiredService(); + private IAgentRepository AgentRepository => + LazyServiceProvider.GetRequiredService(); + private IDictRepository DictRepository => LazyServiceProvider.GetRequiredService(); @@ -104,6 +108,7 @@ public class FinanceService : ApplicationService 客户单号 = item.ClientNo, 跟踪号 = item.TrackNo, 客户编码 = item.CustomerCode, + 代理 = item.AgentName ?? (item.AgentId.HasValue ? $"代理#{item.AgentId}" : ""), 费用类型 = item.FeeTypeName, 费用项 = item.CostItemName ?? item.CostItem, 金额 = item.Amount, @@ -157,6 +162,18 @@ public class FinanceService : ApplicationService ? [] : await CustomerRepository.GetListAsync(x => customerIds.Contains(x.Id)); var customerMap = customers.ToDictionary(x => x.Id); + + var agentIds = rows + .Select(x => x.Order.AgentId) + .Where(x => x.HasValue) + .Select(x => x!.Value) + .Distinct() + .ToArray(); + var agents = agentIds.Length == 0 + ? [] + : await AgentRepository.GetListAsync(x => agentIds.Contains(x.Id)); + var agentNameMap = agents.ToDictionary(x => x.Id, x => x.AgentName); + var feeItemNameMap = await BuildFeeItemNameMapAsync(); return rows.Select(row => @@ -168,6 +185,13 @@ public class FinanceService : ApplicationService customerCode = customer.CustomerCode; } + string? agentName = null; + if (row.Order.AgentId.HasValue + && agentNameMap.TryGetValue(row.Order.AgentId.Value, out var name)) + { + agentName = name; + } + var costItem = row.Fee.CostItem; feeItemNameMap.TryGetValue(costItem, out var costItemName); @@ -178,12 +202,15 @@ public class FinanceService : ApplicationService ClientNo = row.Order.ClientNo, TrackNo = row.Order.TrackNo, CustomerCode = customerCode, + AgentId = row.Order.AgentId, + AgentName = agentName, OrderStatus = row.Order.OrderStatus, OrderStatusName = OmsDocHelper.GetOrderStatusName(row.Order.OrderStatus), IsPaid = row.Order.IsPaid, PayTime = row.Order.PayTime, ReceiveTime = row.Order.ReceiveTime, ShipTime = row.Order.ShipTime, + CreateTime = row.Order.CreateTime, ProductCode = row.Order.ProductCode, ChannelCode = row.Order.ChannelCode, ConsigneeCountryName = row.Order.ConsigneeCountryName, @@ -225,6 +252,9 @@ public class FinanceService : ApplicationService Keyword = input.Keyword, CustomerId = customerId, CustomerCode = input.CustomerCode, + ProductCode = string.IsNullOrWhiteSpace(input.ProductCode) ? null : input.ProductCode.Trim(), + ChannelCode = string.IsNullOrWhiteSpace(input.ChannelCode) ? null : input.ChannelCode.Trim(), + AgentId = input.AgentId is > 0 ? input.AgentId : null, CreateTimeStart = useCreateTime ? input.StartTime : null, CreateTimeEnd = useCreateTime ? input.EndTime : null, TimeField = timeField, diff --git a/src/Oms.Application/Services/Marketing/MarketingAnalysisService.cs b/src/Oms.Application/Services/Marketing/MarketingAnalysisService.cs new file mode 100644 index 0000000..d5309b4 --- /dev/null +++ b/src/Oms.Application/Services/Marketing/MarketingAnalysisService.cs @@ -0,0 +1,392 @@ +using Fake.Application; +using Fake.Domain.Exceptions; +using Microsoft.AspNetCore.Mvc; +using MiniExcelLibs; +using Oms.Application.Dtos.Marketing; +using Oms.Domain.MarketingAggregate.Repositories; +using Oms.Domain.OrdersAggregate; +using Oms.Domain.OrdersAggregate.Repositories; + +namespace Oms.Application.Services.Marketing; + +/// +/// 营销分析 API(管理端总览 + 优惠券)。 +/// +[ApiExplorerSettings(GroupName = "OMS-Marketing")] +public class MarketingAnalysisService : ApplicationService +{ + private IOrderRepository OrderRepository => + LazyServiceProvider.GetRequiredService(); + + private ICouponInstanceRepository InstanceRepository => + LazyServiceProvider.GetRequiredService(); + + private ICouponTemplateRepository TemplateRepository => + LazyServiceProvider.GetRequiredService(); + + /// + /// 营销分析总览:折前 GMV、营销成本、折扣率、客户实收、用券占比、日趋势与折扣构成;含上一同等天数环比。 + /// + [HttpGet("/marketing/analysis/overview")] + public async Task GetOverviewAsync( + [FromQuery] MarketingAnalysisQueryInput input) + { + var (start, endExclusive, usePayTime) = NormalizeRange(input); + var (prevStart, prevEndExclusive) = PreviousRange(start, endExclusive); + + var currentRows = await OrderRepository.ListMarketingSnapshotsByTimeRangeAsync( + start, endExclusive, usePayTime); + var previousRows = await OrderRepository.ListMarketingSnapshotsByTimeRangeAsync( + prevStart, prevEndExclusive, usePayTime); + + var kpis = BuildKpis(currentRows); + var previousKpis = BuildKpis(previousRows); + + return new MarketingAnalysisOverviewOutput + { + Kpis = kpis, + PreviousKpis = previousKpis, + Growth = BuildGrowth(kpis, previousKpis), + Trend = BuildTrend(currentRows, start, endExclusive), + DiscountMix = new MarketingAnalysisDiscountMixOutput + { + CouponDiscount = kpis.CouponDiscount, + LevelDiscount = kpis.LevelDiscount + } + }; + } + + /// + /// 优惠券分析:区间漏斗、可用券负债、模板排行(折扣额按订单快照归集)。 + /// + [HttpGet("/marketing/analysis/coupons")] + public async Task GetCouponsAsync( + [FromQuery] MarketingAnalysisQueryInput input) + { + return await BuildCouponsAsync(input); + } + + /// + /// 导出优惠券模板排行 Excel。 + /// + [HttpGet("/marketing/analysis/coupons/export")] + public async Task ExportCouponsAsync( + [FromQuery] MarketingAnalysisQueryInput input) + { + var data = await BuildCouponsAsync(input); + var exportRows = data.Templates.Select(item => new + { + 模板编码 = item.TemplateCode, + 模板名称 = item.TemplateName, + 发放渠道 = item.GrantChannel, + 发出 = item.Issued, + 核销 = item.Used, + 过期 = item.Expired, + 核销率 = item.RedemptionRate, + 拉动单量 = item.OrderCount, + 折扣额 = item.DiscountAmount, + 折前GMV = item.GmvPreDiscount, + 折扣占GMV = item.DiscountToGmvRate + }).ToList(); + + await using var stream = new MemoryStream(); + await MiniExcel.SaveAsAsync(stream, exportRows); + stream.Position = 0; + return new FileContentResult( + stream.ToArray(), + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") + { + FileDownloadName = $"marketing-coupons-{DateTime.Now:yyyyMMddHHmmss}.xlsx" + }; + } + + private async Task BuildCouponsAsync(MarketingAnalysisQueryInput input) + { + var (start, endExclusive, usePayTime) = NormalizeRange(input); + var topN = input.TopN <= 0 ? 20 : Math.Min(input.TopN, 100); + + var issuedTask = InstanceRepository.ListReceivedInRangeAsync(start, endExclusive); + var usedTask = InstanceRepository.ListUsedInRangeAsync(start, endExclusive); + var expiredTask = InstanceRepository.ListExpiredInRangeAsync(start, endExclusive); + var availableTask = InstanceRepository.CountAvailableAsync(); + var ordersTask = OrderRepository.ListMarketingSnapshotsByTimeRangeAsync( + start, endExclusive, usePayTime); + + await Task.WhenAll(issuedTask, usedTask, expiredTask, availableTask, ordersTask); + + var issued = await issuedTask; + var used = await usedTask; + var expired = await expiredTask; + var available = await availableTask; + var orders = await ordersTask; + + var issuedCount = issued.Count; + var usedCount = used.Count; + var expiredCount = expired.Count; + + var templateIds = issued.Select(x => x.TemplateId) + .Concat(used.Select(x => x.TemplateId)) + .Concat(expired.Select(x => x.TemplateId)) + .Distinct() + .ToArray(); + + var instanceIdToTemplate = issued + .Concat(used) + .Concat(expired) + .GroupBy(x => x.Id) + .ToDictionary(g => g.Key, g => g.First().TemplateId); + + // 用券订单上的实例可能早于区间领取,补拉 TemplateId + var orderInstanceIds = orders + .Where(x => x.CouponInstanceId.HasValue && x.CouponDiscountAmount > 0) + .Select(x => x.CouponInstanceId!.Value) + .Distinct() + .Where(id => !instanceIdToTemplate.ContainsKey(id)) + .ToArray(); + if (orderInstanceIds.Length > 0) + { + var extraInstances = await InstanceRepository.GetListAsync(x => orderInstanceIds.Contains(x.Id)); + foreach (var inst in extraInstances) + { + instanceIdToTemplate[inst.Id] = inst.TemplateId; + if (!templateIds.Contains(inst.TemplateId)) + { + templateIds = templateIds.Append(inst.TemplateId).ToArray(); + } + } + } + + var templates = templateIds.Length == 0 + ? [] + : await TemplateRepository.GetListAsync(x => templateIds.Contains(x.Id)); + var templateMap = templates.ToDictionary(x => x.Id); + + var issuedByTemplate = issued.GroupBy(x => x.TemplateId).ToDictionary(g => g.Key, g => g.Count()); + var usedByTemplate = used.GroupBy(x => x.TemplateId).ToDictionary(g => g.Key, g => g.Count()); + var expiredByTemplate = expired.GroupBy(x => x.TemplateId).ToDictionary(g => g.Key, g => g.Count()); + + var orderAgg = new Dictionary(); + foreach (var order in orders) + { + if (!order.CouponInstanceId.HasValue || order.CouponDiscountAmount <= 0) + { + continue; + } + + if (!instanceIdToTemplate.TryGetValue(order.CouponInstanceId.Value, out var templateId)) + { + continue; + } + + orderAgg.TryGetValue(templateId, out var agg); + orderAgg[templateId] = ( + agg.OrderCount + 1, + agg.Discount + order.CouponDiscountAmount, + agg.Gmv + (order.ReceivableSubtotal ?? 0m)); + } + + var allTemplateIds = issuedByTemplate.Keys + .Concat(usedByTemplate.Keys) + .Concat(expiredByTemplate.Keys) + .Concat(orderAgg.Keys) + .Distinct(); + + var ranks = allTemplateIds + .Select(templateId => + { + templateMap.TryGetValue(templateId, out var template); + issuedByTemplate.TryGetValue(templateId, out var issuedQty); + usedByTemplate.TryGetValue(templateId, out var usedQty); + expiredByTemplate.TryGetValue(templateId, out var expiredQty); + orderAgg.TryGetValue(templateId, out var oa); + var gmv = oa.Gmv; + return new MarketingCouponTemplateRankOutput + { + TemplateId = templateId, + TemplateCode = template?.TemplateCode ?? string.Empty, + TemplateName = template?.TemplateName ?? $"#{templateId}", + GrantChannel = template?.GrantChannel ?? string.Empty, + Issued = issuedQty, + Used = usedQty, + Expired = expiredQty, + RedemptionRate = issuedQty > 0 ? Math.Round((decimal)usedQty / issuedQty, 4) : null, + OrderCount = oa.OrderCount, + DiscountAmount = oa.Discount, + GmvPreDiscount = gmv, + DiscountToGmvRate = gmv > 0 ? Math.Round(oa.Discount / gmv, 4) : null + }; + }) + .OrderByDescending(x => x.DiscountAmount) + .ThenByDescending(x => x.Used) + .ThenByDescending(x => x.Issued) + .Take(topN) + .ToList(); + + return new MarketingAnalysisCouponsOutput + { + Funnel = new MarketingCouponFunnelOutput + { + Issued = issuedCount, + Used = usedCount, + Expired = expiredCount, + RedemptionRate = issuedCount > 0 + ? Math.Round((decimal)usedCount / issuedCount, 4) + : null + }, + AvailableLiability = available, + Templates = ranks + }; + } + + private static (DateTime Start, DateTime EndExclusive, bool UsePayTime) NormalizeRange( + MarketingAnalysisQueryInput input) + { + if (!input.StartTime.HasValue || !input.EndTime.HasValue) + { + throw new BusinessException("请选择分析时间区间"); + } + + var start = input.StartTime.Value; + var end = input.EndTime.Value; + if (end < start) + { + throw new BusinessException("结束时间不能早于开始时间"); + } + + // 结束时间按「含当日/含时分」处理:统一转为开区间上界 + var endExclusive = end.TimeOfDay == TimeSpan.Zero && end == end.Date + ? end.Date.AddDays(1) + : end.AddMilliseconds(1); + + var usePayTime = !string.Equals(input.TimeField, "createTime", StringComparison.OrdinalIgnoreCase); + return (start, endExclusive, usePayTime); + } + + private static (DateTime PrevStart, DateTime PrevEndExclusive) PreviousRange( + DateTime start, + DateTime endExclusive) + { + var duration = endExclusive - start; + if (duration <= TimeSpan.Zero) + { + duration = TimeSpan.FromDays(1); + } + + var prevEndExclusive = start; + var prevStart = prevEndExclusive - duration; + return (prevStart, prevEndExclusive); + } + + private static MarketingAnalysisKpiOutput BuildKpis(List rows) + { + var gmv = rows.Sum(x => x.ReceivableSubtotal ?? 0m); + var coupon = rows.Sum(x => x.CouponDiscountAmount); + var level = rows.Sum(x => x.LevelDiscountAmount); + var cost = coupon + level; + var paid = rows.Sum(x => x.PayableAmount ?? 0m); + var orderCount = rows.Count; + var couponOrderCount = rows.Count(x => x.CouponDiscountAmount > 0); + + return new MarketingAnalysisKpiOutput + { + GmvPreDiscount = gmv, + CouponDiscount = coupon, + LevelDiscount = level, + MarketingCost = cost, + DiscountRate = gmv > 0 ? Math.Round(cost / gmv, 4) : null, + CustomerPaid = paid, + OrderCount = orderCount, + CouponOrderCount = couponOrderCount, + CouponOrderRate = orderCount > 0 + ? Math.Round((decimal)couponOrderCount / orderCount, 4) + : null + }; + } + + private static MarketingAnalysisGrowthOutput BuildGrowth( + MarketingAnalysisKpiOutput current, + MarketingAnalysisKpiOutput previous) + { + return new MarketingAnalysisGrowthOutput + { + GmvPreDiscount = RateGrowth(current.GmvPreDiscount, previous.GmvPreDiscount), + MarketingCost = RateGrowth(current.MarketingCost, previous.MarketingCost), + DiscountRate = PointDiff(current.DiscountRate, previous.DiscountRate), + CustomerPaid = RateGrowth(current.CustomerPaid, previous.CustomerPaid), + OrderCount = RateGrowth(current.OrderCount, previous.OrderCount), + CouponOrderCount = RateGrowth(current.CouponOrderCount, previous.CouponOrderCount), + CouponOrderRate = PointDiff(current.CouponOrderRate, previous.CouponOrderRate) + }; + } + + private static decimal? RateGrowth(decimal current, decimal previous) + { + if (previous == 0) + { + return current == 0 ? 0 : null; + } + + // 与财务分析一致:返回百分数(12.3 表示 +12.3%) + return Math.Round((current - previous) / previous * 100m, 1); + } + + private static decimal? RateGrowth(int current, int previous) + => RateGrowth((decimal)current, previous); + + private static decimal? PointDiff(decimal? current, decimal? previous) + { + if (current == null || previous == null) + { + return null; + } + + // 返回百分点(已是比率差 * 100) + return Math.Round((current.Value - previous.Value) * 100m, 1); + } + + private static List BuildTrend( + List rows, + DateTime start, + DateTime endExclusive) + { + var map = rows + .GroupBy(x => x.BucketTime.Date) + .ToDictionary( + g => g.Key, + g => new MarketingAnalysisTrendPointOutput + { + Date = g.Key.ToString("yyyy-MM-dd"), + GmvPreDiscount = g.Sum(x => x.ReceivableSubtotal ?? 0m), + MarketingCost = g.Sum(x => x.CouponDiscountAmount + x.LevelDiscountAmount), + CustomerPaid = g.Sum(x => x.PayableAmount ?? 0m) + }); + + var points = new List(); + for (var day = start.Date; day < endExclusive.Date || (day == endExclusive.Date && endExclusive.TimeOfDay > TimeSpan.Zero); day = day.AddDays(1)) + { + if (day >= endExclusive) + { + break; + } + + if (map.TryGetValue(day, out var point)) + { + points.Add(point); + } + else + { + points.Add(new MarketingAnalysisTrendPointOutput + { + Date = day.ToString("yyyy-MM-dd") + }); + } + + if (points.Count > 400) + { + break; + } + } + + return points; + } +} diff --git a/src/Oms.Domain/MarketingAggregate/Repositories/IMarketingRepositories.cs b/src/Oms.Domain/MarketingAggregate/Repositories/IMarketingRepositories.cs index d0da7b6..ca5fc5c 100644 --- a/src/Oms.Domain/MarketingAggregate/Repositories/IMarketingRepositories.cs +++ b/src/Oms.Domain/MarketingAggregate/Repositories/IMarketingRepositories.cs @@ -52,6 +52,35 @@ public interface ICouponInstanceRepository : IRepository Task> GetExpiredAvailableAsync(DateTime now, int take, CancellationToken cancellationToken = default); Task> GetExpiringAvailableAsync(DateTime from, DateTime to, int take, CancellationToken cancellationToken = default); + + /// + /// 当前可用券张数(时点负债)。 + /// + Task CountAvailableAsync(CancellationToken cancellationToken = default); + + /// + /// 区间内发出的券(ReceiveTime)。 + /// + Task> ListReceivedInRangeAsync( + DateTime startInclusive, + DateTime endExclusive, + CancellationToken cancellationToken = default); + + /// + /// 区间内核销的券(UseTime + Used)。 + /// + Task> ListUsedInRangeAsync( + DateTime startInclusive, + DateTime endExclusive, + CancellationToken cancellationToken = default); + + /// + /// 区间内过期的券(Expired + ValidEndTime)。 + /// + Task> ListExpiredInRangeAsync( + DateTime startInclusive, + DateTime endExclusive, + CancellationToken cancellationToken = default); } public interface IReferralCommissionRuleRepository : IRepository diff --git a/src/Oms.Domain/OrdersAggregate/AgentAnalysisOrderRow.cs b/src/Oms.Domain/OrdersAggregate/AgentAnalysisOrderRow.cs new file mode 100644 index 0000000..e5f9f34 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/AgentAnalysisOrderRow.cs @@ -0,0 +1,20 @@ +namespace Oms.Domain.OrdersAggregate; + +/// +/// 代理分析用订单投影(仅 Agent 归因订单)。 +/// +public class AgentAnalysisOrderRow +{ + public int Id { get; set; } + + public int AgentId { get; set; } + + public int? CustomerId { get; set; } + + /// 趋势分桶时间(支付或创建)。 + public DateTime BucketTime { get; set; } + + public decimal? ReceivableSubtotal { get; set; } + + public decimal? PayableAmount { get; set; } +} diff --git a/src/Oms.Domain/OrdersAggregate/MarketingOrderSnapshotRow.cs b/src/Oms.Domain/OrdersAggregate/MarketingOrderSnapshotRow.cs new file mode 100644 index 0000000..46834ea --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/MarketingOrderSnapshotRow.cs @@ -0,0 +1,22 @@ +namespace Oms.Domain.OrdersAggregate; + +/// +/// 营销分析用订单快照投影(仅必要字段)。 +/// +public class MarketingOrderSnapshotRow +{ + public int Id { get; set; } + + /// 趋势分桶时间(支付或创建)。 + public DateTime BucketTime { get; set; } + + public decimal? ReceivableSubtotal { get; set; } + + public decimal CouponDiscountAmount { get; set; } + + public decimal LevelDiscountAmount { get; set; } + + public decimal? PayableAmount { get; set; } + + public int? CouponInstanceId { get; set; } +} diff --git a/src/Oms.Domain/OrdersAggregate/OrderReceivablePayableFilter.cs b/src/Oms.Domain/OrdersAggregate/OrderReceivablePayableFilter.cs index 41c494e..9e8913b 100644 --- a/src/Oms.Domain/OrdersAggregate/OrderReceivablePayableFilter.cs +++ b/src/Oms.Domain/OrdersAggregate/OrderReceivablePayableFilter.cs @@ -25,6 +25,16 @@ public class OrderReceivablePayableFilter : OrderListFilter /// public string? CustomerCode { get; set; } + /// + /// 产品编码(精确匹配,财务分析下钻)。 + /// + public string? ProductCode { get; set; } + + /// + /// 渠道编码(精确匹配,财务分析下钻)。 + /// + public string? ChannelCode { get; set; } + /// /// 仅保留各运单费用项的当前生效阶段(出库 > 入库 > 预报)。 /// diff --git a/src/Oms.Domain/OrdersAggregate/Repositories/IOrderRepository.cs b/src/Oms.Domain/OrdersAggregate/Repositories/IOrderRepository.cs index 1e1397d..4fa5fb3 100644 --- a/src/Oms.Domain/OrdersAggregate/Repositories/IOrderRepository.cs +++ b/src/Oms.Domain/OrdersAggregate/Repositories/IOrderRepository.cs @@ -144,4 +144,22 @@ public interface IOrderRepository : IRepository /// 只更新标签模板 Id,避免面单生成覆盖预报计费正在写入的订单字段。 /// Task UpdateLabelTemplateIdAsync(int orderId, int labelTemplateId, CancellationToken cancellationToken = default); + + /// + /// 营销分析:按支付/创建时间拉取订单营销快照投影。 + /// + Task> ListMarketingSnapshotsByTimeRangeAsync( + DateTime startInclusive, + DateTime endExclusive, + bool usePayTime, + CancellationToken cancellationToken = default); + + /// + /// 代理分析:按支付/创建时间拉取带 AgentId 的订单投影。 + /// + Task> ListAgentAnalysisOrdersByTimeRangeAsync( + DateTime startInclusive, + DateTime endExclusive, + bool usePayTime, + CancellationToken cancellationToken = default); } diff --git a/src/Oms.SqlSugarCore/Marketing/MarketingRepositories.cs b/src/Oms.SqlSugarCore/Marketing/MarketingRepositories.cs index f42c74d..a1ac488 100644 --- a/src/Oms.SqlSugarCore/Marketing/MarketingRepositories.cs +++ b/src/Oms.SqlSugarCore/Marketing/MarketingRepositories.cs @@ -157,6 +157,47 @@ public class CouponInstanceRepository : OmsSqlSugarRepository, I .Take(take) .ToListAsync(cancellationToken); } + + public Task CountAvailableAsync(CancellationToken cancellationToken = default) + => CountAsync(x => x.Status == CouponInstanceStatus.Available, cancellationToken); + + public async Task> ListReceivedInRangeAsync( + DateTime startInclusive, + DateTime endExclusive, + CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + return await db.Queryable() + .Where(x => x.ReceiveTime >= startInclusive && x.ReceiveTime < endExclusive) + .ToListAsync(cancellationToken); + } + + public async Task> ListUsedInRangeAsync( + DateTime startInclusive, + DateTime endExclusive, + CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + return await db.Queryable() + .Where(x => x.Status == CouponInstanceStatus.Used + && x.UseTime != null + && x.UseTime >= startInclusive + && x.UseTime < endExclusive) + .ToListAsync(cancellationToken); + } + + public async Task> ListExpiredInRangeAsync( + DateTime startInclusive, + DateTime endExclusive, + CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + return await db.Queryable() + .Where(x => x.Status == CouponInstanceStatus.Expired + && x.ValidEndTime >= startInclusive + && x.ValidEndTime < endExclusive) + .ToListAsync(cancellationToken); + } } public class ReferralCommissionRuleRepository : OmsSqlSugarRepository, IReferralCommissionRuleRepository, IScopedDependency diff --git a/src/Oms.SqlSugarCore/Orders/OrderRepository.cs b/src/Oms.SqlSugarCore/Orders/OrderRepository.cs index 8a46cbf..daf4ba9 100644 --- a/src/Oms.SqlSugarCore/Orders/OrderRepository.cs +++ b/src/Oms.SqlSugarCore/Orders/OrderRepository.cs @@ -1353,6 +1353,18 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I .Any()); } + var productCode = filter.ProductCode?.Trim(); + if (!string.IsNullOrWhiteSpace(productCode)) + { + orderQuery = orderQuery.Where(o => o.ProductCode == productCode); + } + + var channelCode = filter.ChannelCode?.Trim(); + if (!string.IsNullOrWhiteSpace(channelCode)) + { + orderQuery = orderQuery.Where(o => o.ChannelCode == channelCode); + } + orderQuery = ApplyReceivablePayableTimeFilter(orderQuery, filter); if (filter.IsPaid is 0 or 1) @@ -1694,4 +1706,91 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I .Where(x => x.OrderStatus != OrderStatusCodes.Deleted) .ToListAsync(cancellationToken); } + + public async Task> ListMarketingSnapshotsByTimeRangeAsync( + DateTime startInclusive, + DateTime endExclusive, + bool usePayTime, + CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + var query = db.Queryable() + .Where(x => !x.IsDeleted) + .Where(x => x.OrderStatus != OrderStatusCodes.Deleted); + + if (usePayTime) + { + query = query.Where(x => + x.PayTime != null && x.PayTime >= startInclusive && x.PayTime < endExclusive); + return await query + .Select(x => new MarketingOrderSnapshotRow + { + Id = x.Id, + BucketTime = x.PayTime!.Value, + ReceivableSubtotal = x.ReceivableSubtotal, + CouponDiscountAmount = x.CouponDiscountAmount, + LevelDiscountAmount = x.LevelDiscountAmount, + PayableAmount = x.PayableAmount, + CouponInstanceId = x.CouponInstanceId + }) + .ToListAsync(cancellationToken); + } + + query = query.Where(x => x.CreateTime >= startInclusive && x.CreateTime < endExclusive); + return await query + .Select(x => new MarketingOrderSnapshotRow + { + Id = x.Id, + BucketTime = x.CreateTime, + ReceivableSubtotal = x.ReceivableSubtotal, + CouponDiscountAmount = x.CouponDiscountAmount, + LevelDiscountAmount = x.LevelDiscountAmount, + PayableAmount = x.PayableAmount, + CouponInstanceId = x.CouponInstanceId + }) + .ToListAsync(cancellationToken); + } + + public async Task> ListAgentAnalysisOrdersByTimeRangeAsync( + DateTime startInclusive, + DateTime endExclusive, + bool usePayTime, + CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + var query = db.Queryable() + .Where(x => !x.IsDeleted) + .Where(x => x.OrderStatus != OrderStatusCodes.Deleted) + .Where(x => x.AgentId != null && x.AgentId > 0); + + if (usePayTime) + { + query = query.Where(x => + x.PayTime != null && x.PayTime >= startInclusive && x.PayTime < endExclusive); + return await query + .Select(x => new AgentAnalysisOrderRow + { + Id = x.Id, + AgentId = x.AgentId!.Value, + CustomerId = x.CustomerId, + BucketTime = x.PayTime!.Value, + ReceivableSubtotal = x.ReceivableSubtotal, + PayableAmount = x.PayableAmount + }) + .ToListAsync(cancellationToken); + } + + query = query.Where(x => x.CreateTime >= startInclusive && x.CreateTime < endExclusive); + return await query + .Select(x => new AgentAnalysisOrderRow + { + Id = x.Id, + AgentId = x.AgentId!.Value, + CustomerId = x.CustomerId, + BucketTime = x.CreateTime, + ReceivableSubtotal = x.ReceivableSubtotal, + PayableAmount = x.PayableAmount + }) + .ToListAsync(cancellationToken); + } }