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..093c92f
--- /dev/null
+++ b/src/Oms.Application/Dtos/Marketing/MarketingAnalysisDtos.cs
@@ -0,0 +1,305 @@
+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; }
+}
+
+///
+/// 积分健康度分析(定级引擎,非营销成本 ROI)。
+///
+public class MarketingAnalysisPointsOutput
+{
+ /// 当前区间 KPI。
+ public MarketingPointsKpiOutput Kpis { get; set; } = new();
+
+ /// 上一同等天数 KPI。
+ public MarketingPointsKpiOutput PreviousKpis { get; set; } = new();
+
+ /// 环比。
+ public MarketingPointsGrowthOutput Growth { get; set; } = new();
+
+ /// 日趋势(发放/扣回/调账)。
+ public List Trend { get; set; } = [];
+
+ /// 时点账户沉淀(不参与环比)。
+ public MarketingPointsLiabilityOutput Liability { get; set; } = new();
+}
+
+///
+/// 积分区间 KPI。
+///
+public class MarketingPointsKpiOutput
+{
+ /// 发放积分合计(Earn)。
+ public int EarnPoints { get; set; }
+
+ /// 发放笔数。
+ public int EarnCount { get; set; }
+
+ /// 退款/删单扣回积分合计(绝对值)。
+ public int ClawbackPoints { get; set; }
+
+ /// 扣回笔数。
+ public int ClawbackCount { get; set; }
+
+ /// 人工调账净额(可正可负)。
+ public int AdjustPoints { get; set; }
+
+ /// 人工调账笔数。
+ public int AdjustCount { get; set; }
+
+ /// 大额调账笔数(|积分|≥阈值)。
+ public int LargeAdjustCount { get; set; }
+
+ /// 消耗积分合计(Consume,绝对值)。
+ public int ConsumePoints { get; set; }
+}
+
+///
+/// 积分 KPI 环比(百分数)。
+///
+public class MarketingPointsGrowthOutput
+{
+ public decimal? EarnPoints { get; set; }
+
+ public decimal? ClawbackPoints { get; set; }
+
+ public decimal? AdjustPoints { get; set; }
+
+ public decimal? AdjustCount { get; set; }
+
+ public decimal? LargeAdjustCount { get; set; }
+}
+
+///
+/// 积分日趋势。
+///
+public class MarketingPointsTrendPointOutput
+{
+ /// 日期 yyyy-MM-dd。
+ public string Date { get; set; } = string.Empty;
+
+ public int EarnPoints { get; set; }
+
+ public int ClawbackPoints { get; set; }
+
+ public int AdjustPoints { get; set; }
+}
+
+///
+/// 积分账户时点沉淀。
+///
+public class MarketingPointsLiabilityOutput
+{
+ /// 有积分账户数(AvailablePoints>0)。
+ public int AccountWithPoints { get; set; }
+
+ /// 可用积分合计。
+ public int AvailablePointsTotal { get; set; }
+
+ /// 累计积分合计。
+ public int TotalPointsSum { get; set; }
+
+ /// 人均可用积分;无账户时为 null。
+ public decimal? AvgAvailablePoints { get; set; }
+}
diff --git a/src/Oms.Application/Dtos/Mcp/McpDtos.cs b/src/Oms.Application/Dtos/Mcp/McpDtos.cs
index a59d983..51c99e1 100644
--- a/src/Oms.Application/Dtos/Mcp/McpDtos.cs
+++ b/src/Oms.Application/Dtos/Mcp/McpDtos.cs
@@ -58,10 +58,15 @@ public class AiAgentChatInput
[Required]
public List Messages { get; set; } = [];
- /// 为空则使用全部已启用工具
+ /// 为空则使用全部已启用工具;Audience=ops 时强制不挂工具
public List? ToolKeys { get; set; }
public int MaxToolRounds { get; set; } = 3;
+
+ ///
+ /// 对话受众:customer=客户侧查价/轨迹/对客说明(默认);ops=运营排障(不挂客户 MCP 三工具)。
+ ///
+ public string? Audience { get; set; }
}
public class AiAgentChatMessageInput
diff --git a/src/Oms.Application/Services/Agents/AgentAnalysisService.cs b/src/Oms.Application/Services/Agents/AgentAnalysisService.cs
new file mode 100644
index 0000000..a2a339b
--- /dev/null
+++ b/src/Oms.Application/Services/Agents/AgentAnalysisService.cs
@@ -0,0 +1,376 @@
+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)
+ {
+ // SqlSugar/MySQL 同一作用域连接不可并发复用,查询必须串行
+ var orders = await OrderRepository.ListAgentAnalysisOrdersByTimeRangeAsync(
+ start, endExclusive, usePayTime);
+ var commissions = await DetailRepository.GetListAsync(x =>
+ x.CreateTime >= start && x.CreateTime < endExclusive);
+ var paidInPeriod = await DetailRepository.GetListAsync(x =>
+ x.Status == AgentCommissionStatusCodes.Paid
+ && x.PaidTime != null
+ && x.PaidTime >= start
+ && x.PaidTime < endExclusive);
+ var newBinds = await CustomerRepository.GetListAsync(x =>
+ x.ParentCustomerId == null
+ && x.AgentId != null
+ && x.AgentId > 0
+ && x.AgentBindTime != null
+ && x.AgentBindTime >= start
+ && x.AgentBindTime < endExclusive);
+
+ return new PeriodBundle
+ {
+ Orders = orders,
+ Commissions = commissions,
+ PaidInPeriod = paidInPeriod,
+ NewBinds = newBinds
+ };
+ }
+
+ 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/Channels/SalesProductService.Helpers.cs b/src/Oms.Application/Services/Channels/SalesProductService.Helpers.cs
index 5cf2a96..6c68753 100644
--- a/src/Oms.Application/Services/Channels/SalesProductService.Helpers.cs
+++ b/src/Oms.Application/Services/Channels/SalesProductService.Helpers.cs
@@ -405,9 +405,11 @@ public partial class SalesProductService
object snapshot;
if (operatorType == PriceOperatorType)
{
+ var product = await GetProductOrThrowAsync(salesProductId);
var priceSnapshot = await BuildPricePublishSnapshotAsync(salesProductId);
ValidateBillingPriceItemRules(
- priceSnapshot.Prices.Select(p => MapPriceSaveInput(p, salesProductId)).ToList());
+ priceSnapshot.Prices.Select(p => MapPriceSaveInput(p, salesProductId)).ToList(),
+ product.AdditionalServices);
snapshot = priceSnapshot;
}
else
@@ -440,7 +442,8 @@ public partial class SalesProductService
var product = await GetProductOrThrowAsync(salesProductId);
var priceSnapshot = await BuildPricePublishSnapshotAsync(salesProductId);
ValidateBillingPriceItemRules(
- priceSnapshot.Prices.Select(p => MapPriceSaveInput(p, salesProductId)).ToList());
+ priceSnapshot.Prices.Select(p => MapPriceSaveInput(p, salesProductId)).ToList(),
+ product.AdditionalServices);
var content = OmsDocHelper.CanonicalizeSalesProductPriceSnapshotJson(priceSnapshot);
var contentHash = ComputeContentHash(content);
var publishUser = ResolvePublishUserName();
@@ -652,21 +655,56 @@ public partial class SalesProductService
};
///
- /// 保险/偏远费等附加费用项的计费条件校验;同一提交批次内费用项不可重复。
+ /// 费用项 → 产品必须已勾选的附加服务 code(与字典约定一致)。
///
- private static void ValidateBillingPriceItemRules(IReadOnlyList prices)
+ private static readonly IReadOnlyDictionary CostItemRequiredAdditionalService =
+ new Dictionary(StringComparer.OrdinalIgnoreCase)
+ {
+ ["insurance"] = "insurance",
+ ["proxyPacking"] = "proxyPacking",
+ };
+
+ ///
+ /// 保险/代打包/偏远费等费用项规则:计费条件 + 产品附加服务依赖;同一提交批次内费用项不可重复。
+ ///
+ /// 待校验价格项。
+ /// 产品 AdditionalServices JSON(如 ["insurance"])。
+ private static void ValidateBillingPriceItemRules(
+ IReadOnlyList prices,
+ string? productAdditionalServicesJson = null)
{
EnsureUniqueCostItemsInBatch(prices.Select(x => x.CostItem));
+ var allowedServices = ParseAdditionalServiceCodes(productAdditionalServicesJson);
foreach (var price in prices)
{
var costItem = price.CostItem?.Trim() ?? string.Empty;
var condition = price.ChargingCondition?.Trim() ?? string.Empty;
- if (costItem.Equals("insurance", StringComparison.OrdinalIgnoreCase))
+
+ if (CostItemRequiredAdditionalService.TryGetValue(costItem, out var requiredService))
{
+ if (!allowedServices.Contains(requiredService, StringComparer.OrdinalIgnoreCase))
+ {
+ var serviceLabel = requiredService switch
+ {
+ "insurance" => "保险",
+ "proxyPacking" => "代打包",
+ _ => requiredService,
+ };
+ throw new Fake.Application.BusinessException(
+ $"请先在产品配置勾选附加服务「{serviceLabel}」,再配置此费用项");
+ }
+
if (string.IsNullOrWhiteSpace(condition)
|| string.Equals(condition, "无", StringComparison.OrdinalIgnoreCase))
{
- throw new Fake.Application.BusinessException("保险费用项必须配置非空计费条件(不能为「无」)");
+ throw new Fake.Application.BusinessException(
+ $"费用项「{costItem}」必须配置非空计费条件(不能为「无」)");
+ }
+
+ if (!condition.Contains("附加服务包含", StringComparison.Ordinal))
+ {
+ throw new Fake.Application.BusinessException(
+ $"费用项「{costItem}」的计费条件必须包含「附加服务包含」");
}
}
@@ -682,6 +720,29 @@ public partial class SalesProductService
}
}
+ ///
+ /// 解析产品附加服务 JSON 为 code 列表。
+ ///
+ private static List ParseAdditionalServiceCodes(string? raw)
+ {
+ if (string.IsNullOrWhiteSpace(raw))
+ {
+ return [];
+ }
+
+ var codes = OmsDocHelper.DeserializeJson>(raw.Trim());
+ if (codes == null)
+ {
+ return [];
+ }
+
+ return codes
+ .Where(x => !string.IsNullOrWhiteSpace(x))
+ .Select(x => x.Trim())
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .ToList();
+ }
+
///
/// 同一销售产品下每种费用项只能有一条卖价配置。
///
diff --git a/src/Oms.Application/Services/Channels/SalesProductService.cs b/src/Oms.Application/Services/Channels/SalesProductService.cs
index f923a0d..fccb185 100644
--- a/src/Oms.Application/Services/Channels/SalesProductService.cs
+++ b/src/Oms.Application/Services/Channels/SalesProductService.cs
@@ -213,8 +213,8 @@ public partial class SalesProductService : ApplicationService
[HttpPost("/channel/sales-product/price/create")]
public async Task CreatePriceAsync(SalesProductPriceSaveInput input)
{
- await GetProductOrThrowAsync(input.SalesProductId);
- ValidateBillingPriceItemRules([input]);
+ var product = await GetProductOrThrowAsync(input.SalesProductId);
+ ValidateBillingPriceItemRules([input], product.AdditionalServices);
await EnsureCostItemUniqueAsync(input.SalesProductId, input.CostItem, excludePriceId: null);
await SalesProductRepository.InsertPriceAsync(
new SalesProductPrice
@@ -246,7 +246,8 @@ public partial class SalesProductService : ApplicationService
throw new BusinessException("价格项归属不匹配");
}
- ValidateBillingPriceItemRules([input]);
+ var product = await GetProductOrThrowAsync(input.SalesProductId);
+ ValidateBillingPriceItemRules([input], product.AdditionalServices);
await EnsureCostItemUniqueAsync(input.SalesProductId, input.CostItem, excludePriceId: price.Id);
price.SerialNumber = input.SerialNumber;
price.Status = input.Status;
@@ -293,8 +294,8 @@ public partial class SalesProductService : ApplicationService
[HttpPost("/channel/sales-product/price/save")]
public async Task SavePriceAsync(SalesProductPriceSaveAllInput input)
{
- await GetProductOrThrowAsync(input.SalesProductId);
- ValidateBillingPriceItemRules(input.Prices);
+ var product = await GetProductOrThrowAsync(input.SalesProductId);
+ ValidateBillingPriceItemRules(input.Prices, product.AdditionalServices);
var prices = new List();
var factors = new List();
var details = new List();
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..c940c60
--- /dev/null
+++ b/src/Oms.Application/Services/Marketing/MarketingAnalysisService.cs
@@ -0,0 +1,508 @@
+using Fake.Application;
+using Fake.Domain.Exceptions;
+using Microsoft.AspNetCore.Mvc;
+using MiniExcelLibs;
+using Oms.Application.Dtos.Marketing;
+using Oms.Domain.MarketingAggregate.Entities;
+using Oms.Domain.MarketingAggregate.Enums;
+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 const int LargeAdjustThreshold = 500;
+
+ private IOrderRepository OrderRepository =>
+ LazyServiceProvider.GetRequiredService();
+
+ private ICouponInstanceRepository InstanceRepository =>
+ LazyServiceProvider.GetRequiredService();
+
+ private ICouponTemplateRepository TemplateRepository =>
+ LazyServiceProvider.GetRequiredService();
+
+ private ICustomerPointsFlowRepository PointsFlowRepository =>
+ LazyServiceProvider.GetRequiredService();
+
+ private ICustomerPointsAccountRepository PointsAccountRepository =>
+ 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"
+ };
+ }
+
+ ///
+ /// 积分健康度:区间发放/扣回/调账与环比、日趋势;账户可用积分时点沉淀。按流水 CreateTime,与支付字段无关。
+ ///
+ [HttpGet("/marketing/analysis/points")]
+ public async Task GetPointsAsync(
+ [FromQuery] MarketingAnalysisQueryInput input)
+ {
+ var (start, endExclusive, _) = NormalizeRange(input);
+ var (prevStart, prevEndExclusive) = PreviousRange(start, endExclusive);
+
+ // 串行查询,避免同一 SqlSugar 连接并发复用
+ var currentFlows = await PointsFlowRepository.GetListAsync(x =>
+ x.CreateTime >= start && x.CreateTime < endExclusive);
+ var previousFlows = await PointsFlowRepository.GetListAsync(x =>
+ x.CreateTime >= prevStart && x.CreateTime < prevEndExclusive);
+ var accounts = await PointsAccountRepository.GetListAsync(x => x.AvailablePoints > 0 || x.TotalPoints > 0);
+
+ var kpis = BuildPointsKpis(currentFlows);
+ var previousKpis = BuildPointsKpis(previousFlows);
+ var withAvailable = accounts.Where(x => x.AvailablePoints > 0).ToList();
+
+ return new MarketingAnalysisPointsOutput
+ {
+ Kpis = kpis,
+ PreviousKpis = previousKpis,
+ Growth = BuildPointsGrowth(kpis, previousKpis),
+ Trend = BuildPointsTrend(currentFlows, start, endExclusive),
+ Liability = new MarketingPointsLiabilityOutput
+ {
+ AccountWithPoints = withAvailable.Count,
+ AvailablePointsTotal = withAvailable.Sum(x => x.AvailablePoints),
+ TotalPointsSum = accounts.Sum(x => x.TotalPoints),
+ AvgAvailablePoints = withAvailable.Count > 0
+ ? Math.Round((decimal)withAvailable.Sum(x => x.AvailablePoints) / withAvailable.Count, 1)
+ : null
+ }
+ };
+ }
+
+ private async Task BuildCouponsAsync(MarketingAnalysisQueryInput input)
+ {
+ var (start, endExclusive, usePayTime) = NormalizeRange(input);
+ var topN = input.TopN <= 0 ? 20 : Math.Min(input.TopN, 100);
+
+ // SqlSugar/MySQL 同一作用域连接不可并发复用,查询必须串行
+ var issued = await InstanceRepository.ListReceivedInRangeAsync(start, endExclusive);
+ var used = await InstanceRepository.ListUsedInRangeAsync(start, endExclusive);
+ var expired = await InstanceRepository.ListExpiredInRangeAsync(start, endExclusive);
+ var available = await InstanceRepository.CountAvailableAsync();
+ var orders = await OrderRepository.ListMarketingSnapshotsByTimeRangeAsync(
+ start, endExclusive, usePayTime);
+
+ 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;
+ }
+
+ private static MarketingPointsKpiOutput BuildPointsKpis(List flows)
+ {
+ var earn = flows.Where(x => x.ChangeType == PointsChangeType.Earn).ToList();
+ var clawback = flows.Where(x => x.ChangeType == PointsChangeType.RefundClawback).ToList();
+ var adjust = flows.Where(x => x.ChangeType == PointsChangeType.Adjust).ToList();
+ var consume = flows.Where(x => x.ChangeType == PointsChangeType.Consume).ToList();
+
+ return new MarketingPointsKpiOutput
+ {
+ EarnPoints = earn.Sum(x => x.Points),
+ EarnCount = earn.Count,
+ ClawbackPoints = clawback.Sum(x => Math.Abs(x.Points)),
+ ClawbackCount = clawback.Count,
+ AdjustPoints = adjust.Sum(x => x.Points),
+ AdjustCount = adjust.Count,
+ LargeAdjustCount = adjust.Count(x => Math.Abs(x.Points) >= LargeAdjustThreshold),
+ ConsumePoints = consume.Sum(x => Math.Abs(x.Points))
+ };
+ }
+
+ private static MarketingPointsGrowthOutput BuildPointsGrowth(
+ MarketingPointsKpiOutput current,
+ MarketingPointsKpiOutput previous)
+ {
+ return new MarketingPointsGrowthOutput
+ {
+ EarnPoints = RateGrowth(current.EarnPoints, previous.EarnPoints),
+ ClawbackPoints = RateGrowth(current.ClawbackPoints, previous.ClawbackPoints),
+ AdjustPoints = RateGrowth(current.AdjustPoints, previous.AdjustPoints),
+ AdjustCount = RateGrowth(current.AdjustCount, previous.AdjustCount),
+ LargeAdjustCount = RateGrowth(current.LargeAdjustCount, previous.LargeAdjustCount)
+ };
+ }
+
+ private static List BuildPointsTrend(
+ List flows,
+ DateTime start,
+ DateTime endExclusive)
+ {
+ var map = flows
+ .GroupBy(x => x.CreateTime.Date)
+ .ToDictionary(
+ g => g.Key,
+ g => new MarketingPointsTrendPointOutput
+ {
+ Date = g.Key.ToString("yyyy-MM-dd"),
+ EarnPoints = g.Where(x => x.ChangeType == PointsChangeType.Earn).Sum(x => x.Points),
+ ClawbackPoints = g.Where(x => x.ChangeType == PointsChangeType.RefundClawback)
+ .Sum(x => Math.Abs(x.Points)),
+ AdjustPoints = g.Where(x => x.ChangeType == PointsChangeType.Adjust).Sum(x => x.Points)
+ });
+
+ var points = new List();
+ for (var day = start.Date; day < endExclusive; day = day.AddDays(1))
+ {
+ if (map.TryGetValue(day, out var point))
+ {
+ points.Add(point);
+ }
+ else
+ {
+ points.Add(new MarketingPointsTrendPointOutput
+ {
+ Date = day.ToString("yyyy-MM-dd")
+ });
+ }
+
+ if (points.Count > 400) break;
+ }
+
+ return points;
+ }
+}
diff --git a/src/Oms.Application/Services/Mcp/McpToolService.cs b/src/Oms.Application/Services/Mcp/McpToolService.cs
index c8fab9a..3013974 100644
--- a/src/Oms.Application/Services/Mcp/McpToolService.cs
+++ b/src/Oms.Application/Services/Mcp/McpToolService.cs
@@ -115,7 +115,11 @@ public class McpToolService : ApplicationService
var provider = await ResolveProviderAsync(customerId, input.ProviderKey.Trim());
- var enabledTools = await ResolveEnabledToolsAsync(input.ToolKeys);
+ var isOpsAudience = string.Equals(input.Audience?.Trim(), "ops", StringComparison.OrdinalIgnoreCase);
+ // 运营排障:强制不挂客户 MCP 三工具(即使前端误传 toolKeys)
+ var enabledTools = isOpsAudience
+ ? []
+ : await ResolveEnabledToolsAsync(input.ToolKeys);
var llmTools = enabledTools.Select(t =>
{
JsonNode parameters;
@@ -141,21 +145,7 @@ public class McpToolService : ApplicationService
new()
{
Role = "system",
- Content =
- "你是 OMS 客户侧物流助手。可用工具:" +
- "oms.price_check(查价格)、oms.channel_guide(查对客说明/品名可否承运)、oms.track_query(查轨迹)。" +
- "\n【强制规则】" +
- "\n1) 查价:必填仅「目的国家 + 实重kg」。邮编/尺寸/货物属性/运输方式为选填。" +
- "不要索要起运地、发货城市、仓库(用户提到深圳等可忽略或作备注)。" +
- "国家可用中文,调工具时转二字码(美国→US、英国→GB)。" +
- "用户已给目的国+重量时,必须立刻调用 oms.price_check,用一两句中文总结结果。" +
- "\n2) 对客说明/可承运/走什么渠道:用户问某品名能不能寄、能不能走、走什么渠道时,必须立刻调用 oms.channel_guide。" +
- "参数示例:{\"productCode\":\"\",\"productName\":\"\",\"cargoName\":\"lipstick\"}。" +
- "cargoName 必填(从用户话里提取品名);productCode/productName 仅在客户已点名渠道时填写,否则留空由工具按品名检索。" +
- "有结果后用一两句中文说明可走/不可走的渠道;未命中时如实说,不要编造。" +
- "\n3) 查轨迹:消息里已有运单号/跟踪号/客户单号(如 IDE 开头)时,立刻调用 oms.track_query,禁止再向用户要单号。" +
- "\n4) 禁止空回复;信息不足时用一两句中文追问缺项;不要复述 JSON 或大段工具原文。" +
- "\n【省 token】回复尽量短;一次只调必需工具。"
+ Content = isOpsAudience ? BuildOpsSystemPrompt() : BuildCustomerSystemPrompt()
}
};
@@ -189,7 +179,9 @@ public class McpToolService : ApplicationService
var text = result.Content?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(text))
{
- text = "我这边没有生成有效回复。请换个说法再试,或直接发:目的国+重量查价,或运单号查轨迹。";
+ text = isOpsAudience
+ ? "我这边没有生成有效回复。请粘贴完整报错原文,或说明卡在哪个菜单/状态,我按指引帮你拆步骤。"
+ : "我这边没有生成有效回复。请换个说法再试,或直接发:目的国+重量查价,或运单号查轨迹。";
}
return new AiAgentChatOutput
@@ -298,6 +290,36 @@ public class McpToolService : ApplicationService
}
}
+ /// 客户侧系统提示:查价 / 对客说明 / 轨迹三工具。
+ private static string BuildCustomerSystemPrompt() =>
+ "你是 OMS 客户侧物流助手。可用工具:" +
+ "oms.price_check(查价格)、oms.channel_guide(查对客说明/品名可否承运)、oms.track_query(查轨迹)。" +
+ "\n【强制规则】" +
+ "\n1) 查价:必填仅「目的国家 + 实重kg」。邮编/尺寸/货物属性/运输方式为选填。" +
+ "不要索要起运地、发货城市、仓库(用户提到深圳等可忽略或作备注)。" +
+ "国家可用中文,调工具时转二字码(美国→US、英国→GB)。" +
+ "用户已给目的国+重量时,必须立刻调用 oms.price_check,用一两句中文总结结果。" +
+ "\n2) 对客说明/可承运/走什么渠道:用户问某品名能不能寄、能不能走、走什么渠道时,必须立刻调用 oms.channel_guide。" +
+ "参数示例:{\"productCode\":\"\",\"productName\":\"\",\"cargoName\":\"lipstick\"}。" +
+ "cargoName 必填(从用户话里提取品名);productCode/productName 仅在客户已点名渠道时填写,否则留空由工具按品名检索。" +
+ "有结果后用一两句中文说明可走/不可走的渠道;未命中时如实说,不要编造。" +
+ "\n3) 查轨迹:消息里已有运单号/跟踪号/客户单号(如 IDE 开头)时,立刻调用 oms.track_query,禁止再向用户要单号。" +
+ "\n4) 禁止空回复;信息不足时用一两句中文追问缺项;不要复述 JSON 或大段工具原文。" +
+ "\n【省 token】回复尽量短;一次只调必需工具。";
+
+ /// 运营排障系统提示:不挂客户 MCP 工具,依据消息中的指引摘录作答。
+ private static string BuildOpsSystemPrompt() =>
+ "你是 OMS 运营端排障助手「Edi / 艾迪」。" +
+ "\n【能力边界】" +
+ "\n- 不提供客户侧查价/对客品名检索/轨迹工具;不要调用 oms.price_check、oms.channel_guide、oms.track_query。" +
+ "\n- 优先依据对话中 system 提供的「模块指引摘录」回答;摘录未覆盖时明确说「指引未写到」,给通用排查清单,禁止编造不存在的菜单或按钮。" +
+ "\n【回答格式】" +
+ "\n1) 先用一两句定位:可能模块(渠道/订单等)+ 可能原因。" +
+ "\n2) 再给可执行步骤(编号),指向具体配置页,例如 /channel/salesProducts、/channel/serviceChannels、/order/waybillManage、/channel/guide、/order/guide。" +
+ "\n3) 若用户报错含「排货规则未匹配到有效渠道买价」「待排货」等:优先检查排货列表、渠道启用、买价矩阵是否发布、重量段/分区是否匹配、客户白名单。" +
+ "\n4) 信息不足时追问:完整报错原文、运单号、销售产品代码、服务渠道代码。" +
+ "\n【语气】简洁、友善、像帮同事排障;不要客服推销口吻。";
+
private async Task> ResolveEnabledToolsAsync(List? toolKeys)
{
var all = (await ListAsync()).Items;
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);
+ }
}