All checks were successful
Build and Deploy / deploy (push) Successful in 1m20s
同一作用域 SqlSugar 连接不能 Task.WhenAll 并发查询。 Co-authored-by: Cursor <cursoragent@cursor.com>
386 lines
15 KiB
C#
386 lines
15 KiB
C#
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;
|
||
|
||
/// <summary>
|
||
/// 营销分析 API(管理端总览 + 优惠券)。
|
||
/// </summary>
|
||
[ApiExplorerSettings(GroupName = "OMS-Marketing")]
|
||
public class MarketingAnalysisService : ApplicationService
|
||
{
|
||
private IOrderRepository OrderRepository =>
|
||
LazyServiceProvider.GetRequiredService<IOrderRepository>();
|
||
|
||
private ICouponInstanceRepository InstanceRepository =>
|
||
LazyServiceProvider.GetRequiredService<ICouponInstanceRepository>();
|
||
|
||
private ICouponTemplateRepository TemplateRepository =>
|
||
LazyServiceProvider.GetRequiredService<ICouponTemplateRepository>();
|
||
|
||
/// <summary>
|
||
/// 营销分析总览:折前 GMV、营销成本、折扣率、客户实收、用券占比、日趋势与折扣构成;含上一同等天数环比。
|
||
/// </summary>
|
||
[HttpGet("/marketing/analysis/overview")]
|
||
public async Task<MarketingAnalysisOverviewOutput> 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
|
||
}
|
||
};
|
||
}
|
||
|
||
/// <summary>
|
||
/// 优惠券分析:区间漏斗、可用券负债、模板排行(折扣额按订单快照归集)。
|
||
/// </summary>
|
||
[HttpGet("/marketing/analysis/coupons")]
|
||
public async Task<MarketingAnalysisCouponsOutput> GetCouponsAsync(
|
||
[FromQuery] MarketingAnalysisQueryInput input)
|
||
{
|
||
return await BuildCouponsAsync(input);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 导出优惠券模板排行 Excel。
|
||
/// </summary>
|
||
[HttpGet("/marketing/analysis/coupons/export")]
|
||
public async Task<FileContentResult> 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<MarketingAnalysisCouponsOutput> 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<int, (int OrderCount, decimal Discount, decimal Gmv)>();
|
||
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<MarketingOrderSnapshotRow> 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<MarketingAnalysisTrendPointOutput> BuildTrend(
|
||
List<MarketingOrderSnapshotRow> 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<MarketingAnalysisTrendPointOutput>();
|
||
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;
|
||
}
|
||
}
|