using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using NCC.Extend.Entitys.Dto.LqEducationDepartmentDashboard; using NCC.Extend.Entitys.lq_kd_kdjlb; using NCC.Extend.Entitys.lq_kd_pxmx; using NCC.Extend.Entitys.lq_tkjlb; using NCC.Extend.Entitys.lq_xh_hyhk; using NCC.Extend.Helpers; using NCC.FriendlyException; using SqlSugar; namespace NCC.Extend { /// /// 教育部经营看板 - 拓客漏斗分析 /// public partial class LqEducationDepartmentDashboardService { private const string DealTypeGoddessLife = "生美-女神卡"; private const string DealTypeOtherLife = "生美-其他"; private const string DealTypeTech = "科美"; private const string DealTypeMedical = "医美"; private const string TechBeautyCategory = "科美"; private const string MedicalBeautyCategory = "医美"; private const int UpgradeWindowDays = 90; private static readonly string[] AllDealTypes = { DealTypeGoddessLife, DealTypeOtherLife, DealTypeTech, DealTypeMedical }; /// /// 获取拓客漏斗分析(①~⑦ + 结论) /// /// /// 按教育部/门店范围与日期区间,聚合线索→到店→成交分型→90天升单全链路指标,供战略决策中心漏斗区块展示。 /// /// 示例请求: /// ```json /// { /// "educationDepartmentId": "教育部组织ID", /// "startDate": "2026-01-01", /// "endDate": "2026-07-31" /// } /// ``` /// /// 参数说明: /// - educationDepartmentId: 教育部组织ID,与 storeIds 二选一 /// - storeIds: 门店ID列表,与 educationDepartmentId 二选一 /// - startDate: 统计开始日期(必填) /// - endDate: 统计结束日期(必填,须大于等于 startDate) /// /// 查询条件 /// 拓客漏斗全量分析结果 /// 成功返回拓客漏斗分析数据 /// 参数校验失败 /// 服务器内部错误 [HttpPost("GetAcquisitionFunnelAnalysis")] public async Task GetAcquisitionFunnelAnalysis( [FromBody] EducationDepartmentDashboardAcquisitionFunnelInput input) { var (startInclusive, endExclusive, storeIds) = await ResolveAcquisitionFunnelContextAsync(input); if (!storeIds.Any()) { return BuildEmptyAcquisitionFunnelOutput(); } var tkGiftItemIds = await ItemCategoryRuleHelper.GetTkGiftItemIdsAsync(_db); var tkGiftItemIdSet = new HashSet(tkGiftItemIds, StringComparer.Ordinal); // 1. 线索会员(去重) var leadMemberIds = await _db.Queryable() .Where(x => storeIds.Contains(x.StoreId)) .Where(x => x.ExpansionTime >= startInclusive && x.ExpansionTime < endExclusive) .Where(x => !SqlFunc.IsNullOrEmpty(x.MemberId)) .Select(x => x.MemberId) .Distinct() .ToListAsync(); if (!leadMemberIds.Any()) { return BuildEmptyAcquisitionFunnelOutput(); } var leadSet = new HashSet(leadMemberIds, StringComparer.Ordinal); // 2. 到店会员 var arrivalMemberIds = await _db.Queryable() .Where(x => leadMemberIds.Contains(x.Hy)) .Where(x => x.IsEffective == 1) .Where(x => x.Hksj >= startInclusive && x.Hksj < endExclusive) .Select(x => x.Hy) .Distinct() .ToListAsync(); var arrivalSet = new HashSet(arrivalMemberIds, StringComparer.Ordinal); // 3. 区间内有效开单(线索会员) var billingRows = await _db.Queryable() .Where(x => leadMemberIds.Contains(x.Kdhy)) .Where(x => x.IsEffective == 1) .Where(x => x.Sfyj > 0) .Where(x => x.Kdrq.HasValue) .Where(x => x.Kdrq.Value >= startInclusive && x.Kdrq.Value < endExclusive) .Select(x => new MemberBillRow { BillId = x.Id, MemberId = x.Kdhy, BillingDate = x.Kdrq.Value }) .ToListAsync(); var firstBillByMember = billingRows .GroupBy(x => x.MemberId) .ToDictionary( g => g.Key, g => g.OrderBy(x => x.BillingDate).ThenBy(x => x.BillId, StringComparer.Ordinal).First()); var dealMemberIds = firstBillByMember.Keys.ToList(); var dealSet = new HashSet(dealMemberIds, StringComparer.Ordinal); // 4. 首单明细 → 成交类型 var firstBillIds = firstBillByMember.Values.Select(x => x.BillId).Distinct().ToList(); var firstBillDetails = firstBillIds.Any() ? await _db.Queryable() .Where(x => firstBillIds.Contains(x.Glkdbh)) .Where(x => x.IsEffective == 1) .Select(x => new BillDetailRow { BillId = x.Glkdbh, MemberId = x.MemberId, ItemId = x.Px, ItemName = x.Pxmc, ItemCategory = x.ItemCategory, ActualPrice = x.ActualPrice }) .ToListAsync() : new List(); var detailsByBill = firstBillDetails .GroupBy(x => x.BillId) .ToDictionary(g => g.Key, g => g.ToList()); var memberDealType = new Dictionary(StringComparer.Ordinal); foreach (var pair in firstBillByMember) { detailsByBill.TryGetValue(pair.Value.BillId, out var details); memberDealType[pair.Key] = ClassifyDealType(details, tkGiftItemIdSet); } // 5. 升单:首单后 90 天内另一笔有效开单(可超出筛选结束日) var upgradeEndByMember = firstBillByMember.ToDictionary( x => x.Key, x => x.Value.BillingDate.AddDays(UpgradeWindowDays)); var maxUpgradeEnd = upgradeEndByMember.Values.DefaultIfEmpty(endExclusive).Max(); var upgradeCandidateBills = dealMemberIds.Any() ? await _db.Queryable() .Where(x => dealMemberIds.Contains(x.Kdhy)) .Where(x => x.IsEffective == 1) .Where(x => x.Sfyj > 0) .Where(x => x.Kdrq.HasValue) .Where(x => x.Kdrq.Value >= startInclusive && x.Kdrq.Value <= maxUpgradeEnd) .Select(x => new MemberBillRow { BillId = x.Id, MemberId = x.Kdhy, BillingDate = x.Kdrq.Value }) .ToListAsync() : new List(); var upgradeBillIds = new HashSet(StringComparer.Ordinal); var upgradedMembers = new HashSet(StringComparer.Ordinal); foreach (var memberId in dealMemberIds) { if (!firstBillByMember.TryGetValue(memberId, out var firstBill)) continue; var windowEnd = upgradeEndByMember[memberId]; var hasUpgrade = upgradeCandidateBills.Any(x => x.MemberId == memberId && !string.Equals(x.BillId, firstBill.BillId, StringComparison.Ordinal) && x.BillingDate >= firstBill.BillingDate && x.BillingDate <= windowEnd); if (!hasUpgrade) continue; upgradedMembers.Add(memberId); foreach (var bill in upgradeCandidateBills.Where(x => x.MemberId == memberId && !string.Equals(x.BillId, firstBill.BillId, StringComparison.Ordinal) && x.BillingDate >= firstBill.BillingDate && x.BillingDate <= windowEnd)) { upgradeBillIds.Add(bill.BillId); } } // 6. 升单明细 var upgradeDetails = upgradeBillIds.Any() ? await _db.Queryable() .Where(x => upgradeBillIds.Contains(x.Glkdbh)) .Where(x => x.IsEffective == 1) .Select(x => new BillDetailRow { BillId = x.Glkdbh, MemberId = x.MemberId, ItemId = x.Px, ItemName = x.Pxmc, ItemCategory = x.ItemCategory, ActualPrice = x.ActualPrice }) .ToListAsync() : new List(); var billMemberMap = upgradeCandidateBills .Where(x => !string.IsNullOrWhiteSpace(x.BillId) && !string.IsNullOrWhiteSpace(x.MemberId)) .GroupBy(x => x.BillId, StringComparer.Ordinal) .ToDictionary(g => g.Key, g => g.First().MemberId, StringComparer.Ordinal); foreach (var detail in upgradeDetails) { if (!string.IsNullOrWhiteSpace(detail.MemberId)) continue; if (!string.IsNullOrWhiteSpace(detail.BillId) && billMemberMap.TryGetValue(detail.BillId, out var memberId)) { detail.MemberId = memberId; } } return BuildAcquisitionFunnelOutput( leadSet, arrivalSet, dealSet, upgradedMembers, memberDealType, upgradeDetails, tkGiftItemIdSet); } private async Task<(DateTime startInclusive, DateTime endExclusive, List storeIds)> ResolveAcquisitionFunnelContextAsync(EducationDepartmentDashboardAcquisitionFunnelInput input) { if (input == null) throw NCCException.Oh("请求参数不能为空"); if (!input.StartDate.HasValue || !input.EndDate.HasValue) throw NCCException.Oh("开始日期与结束日期不能为空"); var start = input.StartDate.Value.Date; var end = input.EndDate.Value.Date; if (end < start) throw NCCException.Oh("结束日期不能早于开始日期"); if (string.IsNullOrWhiteSpace(input.EducationDepartmentId) && (input.StoreIds == null || !input.StoreIds.Any())) throw NCCException.Oh("教育部ID和门店ID列表不能同时为空,必须传入其中一个"); if (!string.IsNullOrWhiteSpace(input.EducationDepartmentId) && input.StoreIds != null && input.StoreIds.Any()) throw NCCException.Oh("教育部ID和门店ID列表不能同时传入,请只传入其中一个"); var storeIds = await GetStoreIdsUnionForDateRangeAsync( input.EducationDepartmentId, input.StoreIds, start, end); return (start, end.AddDays(1), storeIds); } private async Task> GetStoreIdsUnionForDateRangeAsync( string educationDepartmentId, List storeIds, DateTime startDate, DateTime endDate) { var months = BuildStatisticsMonthList(startDate, endDate); var union = new HashSet(StringComparer.Ordinal); foreach (var month in months) { var ids = await GetStoreIdsAsync(educationDepartmentId, storeIds, month); foreach (var id in ids.Where(x => !string.IsNullOrWhiteSpace(x))) { union.Add(id); } } return union.ToList(); } private static List BuildStatisticsMonthList(DateTime startDate, DateTime endDate) { var months = new List(); var cursor = new DateTime(startDate.Year, startDate.Month, 1); var endMonth = new DateTime(endDate.Year, endDate.Month, 1); while (cursor <= endMonth) { months.Add(cursor.ToString("yyyyMM")); cursor = cursor.AddMonths(1); } return months; } private static string ClassifyDealType(List details, HashSet tkGiftItemIdSet) { if (details == null || !details.Any()) { return DealTypeOtherLife; } if (details.Any(x => ItemCategoryRuleHelper.IsTkGiftItem(x.ItemId, tkGiftItemIdSet))) { return DealTypeGoddessLife; } var top = details .OrderByDescending(x => x.ActualPrice) .ThenBy(x => x.ItemId, StringComparer.Ordinal) .First(); var category = top.ItemCategory?.Trim(); if (string.Equals(category, LifeBeautyCategory, StringComparison.Ordinal)) return DealTypeOtherLife; if (string.Equals(category, TechBeautyCategory, StringComparison.Ordinal)) return DealTypeTech; if (string.Equals(category, MedicalBeautyCategory, StringComparison.Ordinal)) return DealTypeMedical; return DealTypeOtherLife; } private EducationDepartmentDashboardAcquisitionFunnelOutput BuildAcquisitionFunnelOutput( HashSet leadSet, HashSet arrivalSet, HashSet dealSet, HashSet upgradedMembers, Dictionary memberDealType, List upgradeDetails, HashSet tkGiftItemIdSet) { var leadCount = leadSet.Count; var arrivalCount = arrivalSet.Count; var dealCount = dealSet.Count; var upgradeCount = upgradedMembers.Count; var arrivalRate = SafePercent(arrivalCount, leadCount); var dealRate = SafePercent(dealCount, arrivalCount); var upgradeRate = SafePercent(upgradeCount, dealCount); var leadToDealRate = SafePercent(dealCount, leadCount); var output = new EducationDepartmentDashboardAcquisitionFunnelOutput { SummaryKpis = new AcquisitionFunnelSummaryKpis { LeadCount = leadCount, ArrivalCount = arrivalCount, ArrivalRate = arrivalRate, DealCount = dealCount, DealRate = dealRate, UpgradeCount = upgradeCount, UpgradeRate = upgradeRate, LeadToDealRate = leadToDealRate }, FunnelSteps = BuildFunnelSteps(leadCount, arrivalCount, dealCount, upgradeCount, arrivalRate, dealRate, upgradeRate), DropOffs = BuildDropOffs(leadCount, arrivalCount, dealCount, upgradeCount), DealTypeDistribution = BuildDealTypeDistribution(memberDealType, dealCount), LifeBeautySplit = BuildLifeBeautySplit(memberDealType, upgradedMembers, upgradeDetails, tkGiftItemIdSet), DealTypeUpgradeRates = BuildDealTypeUpgradeRates(memberDealType, upgradedMembers), MetricNote = BuildMetricNote(tkGiftItemIdSet) }; var goddessUpgraded = upgradedMembers .Where(m => memberDealType.TryGetValue(m, out var t) && t == DealTypeGoddessLife) .ToHashSet(StringComparer.Ordinal); var otherLifeUpgraded = upgradedMembers .Where(m => memberDealType.TryGetValue(m, out var t) && t == DealTypeOtherLife) .ToHashSet(StringComparer.Ordinal); output.GoddessUpgradeFlow = BuildGoddessUpgradeFlow(goddessUpgraded, upgradeDetails); output.GoddessUpgradeTopItems = BuildUpgradeTopItems( upgradeDetails.Where(x => goddessUpgraded.Contains(x.MemberId)).ToList(), 10); output.OtherLifeUpgradeFlow = BuildOtherLifeUpgradeFlow(otherLifeUpgraded, upgradeDetails); output.OtherLifeUpgradeTopItems = BuildUpgradeTopItems( upgradeDetails.Where(x => otherLifeUpgraded.Contains(x.MemberId)).ToList(), 10); output.TechMedicalSupplement = BuildTechMedicalSupplement( memberDealType, upgradedMembers, upgradeDetails); output.Conclusions = BuildConclusions(output); return output; } private static List BuildFunnelSteps( int leadCount, int arrivalCount, int dealCount, int upgradeCount, decimal arrivalRate, decimal dealRate, decimal upgradeRate) { return new List { new AcquisitionFunnelStepItem { Name = "线索", Count = leadCount, RateLabel = "基准 100%" }, new AcquisitionFunnelStepItem { Name = "到店", Count = arrivalCount, RateLabel = $"到店率 {arrivalRate:F2}%" }, new AcquisitionFunnelStepItem { Name = "成交", Count = dealCount, RateLabel = $"成交率 {dealRate:F2}%" }, new AcquisitionFunnelStepItem { Name = "升单", Count = upgradeCount, RateLabel = $"升单率 {upgradeRate:F2}%" } }; } private static AcquisitionFunnelDropOffs BuildDropOffs( int leadCount, int arrivalCount, int dealCount, int upgradeCount) { var noArrival = Math.Max(0, leadCount - arrivalCount); var arrivalNoDeal = Math.Max(0, arrivalCount - dealCount); var dealNoUpgrade = Math.Max(0, dealCount - upgradeCount); return new AcquisitionFunnelDropOffs { NoArrivalCount = noArrival, NoArrivalRate = SafePercent(noArrival, leadCount), ArrivalNoDealCount = arrivalNoDeal, ArrivalNoDealRate = SafePercent(arrivalNoDeal, arrivalCount), DealNoUpgradeCount = dealNoUpgrade, DealNoUpgradeRate = SafePercent(dealNoUpgrade, dealCount) }; } private static List BuildDealTypeDistribution( Dictionary memberDealType, int dealCount) { return AllDealTypes.Select(dealType => { var count = memberDealType.Values.Count(x => x == dealType); return new AcquisitionDealTypeDistributionItem { DealType = dealType, Count = count, Rate = SafePercent(count, dealCount) }; }).ToList(); } private static AcquisitionLifeBeautySplit BuildLifeBeautySplit( Dictionary memberDealType, HashSet upgradedMembers, List upgradeDetails, HashSet tkGiftItemIdSet) { var goddessDealMembers = memberDealType.Where(x => x.Value == DealTypeGoddessLife).Select(x => x.Key).ToList(); var otherLifeDealMembers = memberDealType.Where(x => x.Value == DealTypeOtherLife).Select(x => x.Key).ToList(); var goddessUpgraded = goddessDealMembers.Count(m => upgradedMembers.Contains(m)); var otherLifeUpgraded = otherLifeDealMembers.Count(m => upgradedMembers.Contains(m)); var goddessUpgradeLines = upgradeDetails.Where(x => goddessDealMembers.Contains(x.MemberId) && upgradedMembers.Contains(x.MemberId)).ToList(); var otherLifeUpgradeLines = upgradeDetails.Where(x => otherLifeDealMembers.Contains(x.MemberId) && upgradedMembers.Contains(x.MemberId)).ToList(); return new AcquisitionLifeBeautySplit { GoddessDealCount = goddessDealMembers.Count, GoddessUpgradeCount = goddessUpgraded, GoddessUpgradeRate = SafePercent(goddessUpgraded, goddessDealMembers.Count), GoddessUpgradeGoddessLineCount = CountLifeBeautyLines(goddessUpgradeLines, tkGiftItemIdSet, true), GoddessUpgradeOtherLifeLineCount = CountLifeBeautyLines(goddessUpgradeLines, tkGiftItemIdSet, false), OtherLifeDealCount = otherLifeDealMembers.Count, OtherLifeUpgradeCount = otherLifeUpgraded, OtherLifeUpgradeRate = SafePercent(otherLifeUpgraded, otherLifeDealMembers.Count), OtherLifeUpgradeGoddessLineCount = CountLifeBeautyLines(otherLifeUpgradeLines, tkGiftItemIdSet, true), OtherLifeUpgradeOtherLifeLineCount = CountLifeBeautyLines(otherLifeUpgradeLines, tkGiftItemIdSet, false) }; } private static int CountLifeBeautyLines( List lines, HashSet tkGiftItemIdSet, bool goddessLines) { return lines.Count(x => string.Equals(x.ItemCategory?.Trim(), LifeBeautyCategory, StringComparison.Ordinal) && ItemCategoryRuleHelper.IsTkGiftItem(x.ItemId, tkGiftItemIdSet) == goddessLines); } private static List BuildDealTypeUpgradeRates( Dictionary memberDealType, HashSet upgradedMembers) { return AllDealTypes.Select(dealType => { var dealMembers = memberDealType.Where(x => x.Value == dealType).Select(x => x.Key).ToList(); var upgradeCount = dealMembers.Count(m => upgradedMembers.Contains(m)); return new AcquisitionDealTypeUpgradeRateItem { DealType = dealType, DealCount = dealMembers.Count, UpgradeCount = upgradeCount, UpgradeRate = SafePercent(upgradeCount, dealMembers.Count) }; }).ToList(); } private static AcquisitionGoddessUpgradeFlow BuildGoddessUpgradeFlow( HashSet upgradedMembers, List upgradeDetails) { var lines = upgradeDetails.Where(x => upgradedMembers.Contains(x.MemberId)).ToList(); var lifeCount = CountDistinctMembersByCategory(lines, LifeBeautyCategory); var techCount = CountDistinctMembersByCategory(lines, TechBeautyCategory); var medicalCount = CountDistinctMembersByCategory(lines, MedicalBeautyCategory); return new AcquisitionGoddessUpgradeFlow { LifeBeautyCustomerCount = lifeCount, TechBeautyCustomerCount = techCount, MedicalBeautyCustomerCount = medicalCount, FlowSummary = BuildFlowSummary("女神卡首单", lifeCount, techCount, medicalCount) }; } private static AcquisitionOtherLifeUpgradeFlow BuildOtherLifeUpgradeFlow( HashSet upgradedMembers, List upgradeDetails) { var lines = upgradeDetails.Where(x => upgradedMembers.Contains(x.MemberId)).ToList(); var lifeCount = CountDistinctMembersByCategory(lines, LifeBeautyCategory); var techCount = CountDistinctMembersByCategory(lines, TechBeautyCategory); var medicalCount = CountDistinctMembersByCategory(lines, MedicalBeautyCategory); return new AcquisitionOtherLifeUpgradeFlow { LifeBeautyCustomerCount = lifeCount, TechBeautyCustomerCount = techCount, MedicalBeautyCustomerCount = medicalCount, FlowSummary = BuildFlowSummary("其他生美首单", lifeCount, techCount, medicalCount) }; } private static AcquisitionTechMedicalSupplement BuildTechMedicalSupplement( Dictionary memberDealType, HashSet upgradedMembers, List upgradeDetails) { var techDealMembers = memberDealType.Where(x => x.Value == DealTypeTech).Select(x => x.Key).ToList(); var medicalDealMembers = memberDealType.Where(x => x.Value == DealTypeMedical).Select(x => x.Key).ToList(); var techFirstUpgraded = techDealMembers.Where(upgradedMembers.Contains).ToHashSet(StringComparer.Ordinal); var medicalFirstUpgraded = medicalDealMembers.Where(upgradedMembers.Contains).ToHashSet(StringComparer.Ordinal); var destLines = upgradeDetails .Where(x => upgradedMembers.Contains(x.MemberId)) .ToList(); var techDestLines = destLines .Where(x => string.Equals(x.ItemCategory?.Trim(), TechBeautyCategory, StringComparison.Ordinal)) .ToList(); var medicalDestLines = destLines .Where(x => string.Equals(x.ItemCategory?.Trim(), MedicalBeautyCategory, StringComparison.Ordinal)) .ToList(); var techDestCount = techDestLines .Select(x => x.MemberId) .Where(x => !string.IsNullOrWhiteSpace(x)) .Distinct(StringComparer.Ordinal) .Count(); var medicalDestCount = medicalDestLines .Select(x => x.MemberId) .Where(x => !string.IsNullOrWhiteSpace(x)) .Distinct(StringComparer.Ordinal) .Count(); return new AcquisitionTechMedicalSupplement { TechDealCount = techDealMembers.Count, TechUpgradeCount = Math.Max(techFirstUpgraded.Count, techDestCount), TechUpgradeRate = SafePercent(techFirstUpgraded.Count, techDealMembers.Count), TechFlowSummary = techDestCount > 0 ? $"升单进入科美 {techDestCount} 人(首单为科美 {techDealMembers.Count} 人)" : BuildFlowSummary("科美首单", CountDistinctMembersByCategory(upgradeDetails.Where(x => techFirstUpgraded.Contains(x.MemberId)).ToList(), LifeBeautyCategory), CountDistinctMembersByCategory(upgradeDetails.Where(x => techFirstUpgraded.Contains(x.MemberId)).ToList(), TechBeautyCategory), CountDistinctMembersByCategory(upgradeDetails.Where(x => techFirstUpgraded.Contains(x.MemberId)).ToList(), MedicalBeautyCategory)), TechUpgradeTopItems = BuildUpgradeTopItems(techDestLines.Any() ? techDestLines : upgradeDetails.Where(x => techFirstUpgraded.Contains(x.MemberId)).ToList(), 10), MedicalDealCount = medicalDealMembers.Count, MedicalUpgradeCount = Math.Max(medicalFirstUpgraded.Count, medicalDestCount), MedicalUpgradeRate = SafePercent(medicalFirstUpgraded.Count, medicalDealMembers.Count), MedicalFlowSummary = medicalDestCount > 0 ? $"升单进入医美 {medicalDestCount} 人(首单为医美 {medicalDealMembers.Count} 人)" : BuildFlowSummary("医美首单", CountDistinctMembersByCategory(upgradeDetails.Where(x => medicalFirstUpgraded.Contains(x.MemberId)).ToList(), LifeBeautyCategory), CountDistinctMembersByCategory(upgradeDetails.Where(x => medicalFirstUpgraded.Contains(x.MemberId)).ToList(), TechBeautyCategory), CountDistinctMembersByCategory(upgradeDetails.Where(x => medicalFirstUpgraded.Contains(x.MemberId)).ToList(), MedicalBeautyCategory)), MedicalUpgradeTopItems = BuildUpgradeTopItems(medicalDestLines.Any() ? medicalDestLines : upgradeDetails.Where(x => medicalFirstUpgraded.Contains(x.MemberId)).ToList(), 10) }; } private static List BuildUpgradeTopItems(List lines, int topN) { return lines .GroupBy(x => new { ItemId = x.ItemId ?? string.Empty, ItemName = string.IsNullOrWhiteSpace(x.ItemName) ? "无" : x.ItemName.Trim(), ItemCategory = x.ItemCategory ?? string.Empty }) .Select(g => new AcquisitionUpgradeTopItem { ItemId = g.Key.ItemId, ItemName = g.Key.ItemName, ItemCategory = string.IsNullOrWhiteSpace(g.Key.ItemCategory) ? "无" : g.Key.ItemCategory, CustomerCount = g.Select(x => x.MemberId).Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().Count(), LineCount = g.Count() }) .OrderByDescending(x => x.LineCount) .ThenByDescending(x => x.CustomerCount) .Take(topN) .ToList(); } private static int CountDistinctMembersByCategory(List lines, string category) { return lines .Where(x => string.Equals(x.ItemCategory?.Trim(), category, StringComparison.Ordinal)) .Select(x => x.MemberId) .Where(x => !string.IsNullOrWhiteSpace(x)) .Distinct(StringComparer.Ordinal) .Count(); } private static string BuildFlowSummary(string prefix, int lifeCount, int techCount, int medicalCount) { return $"{prefix}升单客户流向:生美 {lifeCount} 人、科美 {techCount} 人、医美 {medicalCount} 人"; } private static List BuildConclusions(EducationDepartmentDashboardAcquisitionFunnelOutput output) { var kpis = output.SummaryKpis; var dropOffs = output.DropOffs; var goddessSplit = output.LifeBeautySplit; var conclusions = new List { $"统计期内共获取线索 {kpis.LeadCount} 人,到店率 {kpis.ArrivalRate:F2}%,线索→成交转化率 {kpis.LeadToDealRate:F2}%。", $"成交客户 {kpis.DealCount} 人,其中 90 天内升单 {kpis.UpgradeCount} 人,整体升单率 {kpis.UpgradeRate:F2}%。", $"未到店流失 {dropOffs.NoArrivalCount} 人(占线索 {dropOffs.NoArrivalRate:F2}%),到店未成交 {dropOffs.ArrivalNoDealCount} 人(占到店 {dropOffs.ArrivalNoDealRate:F2}%)。" }; if (goddessSplit.GoddessDealCount + goddessSplit.OtherLifeDealCount > 0) { conclusions.Add( $"生美成交中女神卡 {goddessSplit.GoddessDealCount} 人(升单率 {goddessSplit.GoddessUpgradeRate:F2}%),其他生美 {goddessSplit.OtherLifeDealCount} 人(升单率 {goddessSplit.OtherLifeUpgradeRate:F2}%)。"); } conclusions.Add( "升单按首单成交日后 90 天内再次开单统计,筛选区间末段成交客户的升单可能被观察窗截断。"); return conclusions.Take(5).ToList(); } private static string BuildMetricNote(HashSet tkGiftItemIdSet) { var ids = tkGiftItemIdSet.Any() ? string.Join(",", tkGiftItemIdSet) : ItemCategoryRuleHelper.DefaultTkGiftItemIds; return "线索=拓客管理按会员ID去重(不含调整明细);到店=线索会员在区间内有有效耗卡;成交=线索会员在区间内有有效开单(F_IsEffective=1且实付业绩>0);" + "成交类型按区间内最早一笔开单判定:含配置女神卡品项ID→生美-女神卡,否则按该单实付金额最大明细的品项分类;" + $"女神卡品项ID={ids};升单=首单后90天内不同开单编号再次成交(观察窗可超出筛选结束日)。"; } private static EducationDepartmentDashboardAcquisitionFunnelOutput BuildEmptyAcquisitionFunnelOutput() { var output = new EducationDepartmentDashboardAcquisitionFunnelOutput { SummaryKpis = new AcquisitionFunnelSummaryKpis(), FunnelSteps = BuildFunnelSteps(0, 0, 0, 0, 0m, 0m, 0m), DropOffs = BuildDropOffs(0, 0, 0, 0), DealTypeDistribution = BuildDealTypeDistribution(new Dictionary(), 0), LifeBeautySplit = new AcquisitionLifeBeautySplit(), DealTypeUpgradeRates = BuildDealTypeUpgradeRates(new Dictionary(), new HashSet()), GoddessUpgradeFlow = new AcquisitionGoddessUpgradeFlow { FlowSummary = "暂无数据" }, OtherLifeUpgradeFlow = new AcquisitionOtherLifeUpgradeFlow { FlowSummary = "暂无数据" }, TechMedicalSupplement = new AcquisitionTechMedicalSupplement { TechFlowSummary = "暂无数据", MedicalFlowSummary = "暂无数据" }, MetricNote = BuildMetricNote(new HashSet { ItemCategoryRuleHelper.DefaultTkGiftItemIds }) }; output.Conclusions = new List { "当前筛选条件下暂无拓客漏斗数据。" }; return output; } private static decimal SafePercent(int numerator, int denominator) { if (denominator <= 0) return 0m; return Math.Round((decimal)numerator / denominator * 100m, 2); } private class MemberBillRow { public string BillId { get; set; } public string MemberId { get; set; } public DateTime BillingDate { get; set; } } private class BillDetailRow { public string BillId { get; set; } public string MemberId { get; set; } public string ItemId { get; set; } public string ItemName { get; set; } public string ItemCategory { get; set; } public decimal ActualPrice { get; set; } } } }