All files / services/crm analytics.service.ts

100% Statements 61/61
100% Branches 35/35
100% Functions 18/18
100% Lines 56/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216                  30x     27x     27x               27x       27x   27x                   27x 3x           27x 27x 2x     27x 27x 3x       27x 29x                                           27x         27x   27x 4x 4x 4x 4x                         27x               27x       27x                       27x 27x 27x     27x             27x                       27x         27x             27x 54x     27x   1x 1x 1x 1x 1x     18x 18x     2x 2x 2x     2x 2x 2x     1x 1x                   2x 2x       1x 1x       25x      
// Analytics Service - Dashboard data aggregation
import type { Dal } from "../../dal";
 
type DateRange = {
	from: number; // epoch seconds
	to: number; // epoch seconds
};
 
export class CrmAnalyticsService {
	constructor(private dal: Dal) {}
 
	async getDashboard(proId: string, period: string) {
		const dateRange = this.parsePeriod(period);
 
		const [pipeline, sources, financial, followup, lossReasons] =
			await Promise.all([
				this.getPipelineOverview(proId, dateRange),
				this.getSourcePerformance(proId, dateRange),
				this.getFinancialSummary(proId, dateRange),
				this.getFollowupHealth(proId),
				this.getLossReasonBreakdown(proId, dateRange),
			]);
 
		return { pipeline, sources, financial, followup, lossReasons, period };
	}
 
	private async getPipelineOverview(proId: string, dateRange: DateRange) {
		const stages = await this.dal.pipelineStages.findByProId(proId);
 
		const [stageCountsRaw, wonLost, newLeadsCount] = await Promise.all([
			// #427: scope by dateRange so Active Leads / Pipeline Value /
			// Pipeline Overview bars react to the period filter. Pre-fix this
			// call had no dateRange, which is why those widgets stayed frozen
			// while only Source Performance reacted.
			this.dal.crmAnalytics.getStageCountsForPro(proId, dateRange),
			this.dal.crmAnalytics.getWonLostInPeriod(proId, dateRange),
			this.dal.crmAnalytics.getNewLeadsInPeriod(proId, dateRange),
		]);
 
		const countMap = new Map(
			stageCountsRaw.map((r) => [
				r.stageId,
				{ count: r.count, value: r.totalQuoteValue },
			]),
		);
 
		const wonData = wonLost.find((r) => r.stageType === "system_terminal_won");
		const lostData = wonLost.find(
			(r) => r.stageType === "system_terminal_lost",
		);
 
		const totalActive = stageCountsRaw.reduce((sum, r) => sum + r.count, 0);
		const totalPipelineValue = stageCountsRaw.reduce(
			(sum, r) => sum + r.totalQuoteValue,
			0,
		);
 
		return {
			stages: stages.map((stage) => ({
				id: stage.id,
				name: stage.name,
				stageType: stage.stageType,
				position: stage.position,
				leadCount: countMap.get(stage.id)?.count ?? 0,
				totalValue: countMap.get(stage.id)?.value ?? 0,
			})),
			totalActive,
			totalPipelineValue,
			newLeadsInPeriod: newLeadsCount,
			wonInPeriod: wonData?.count ?? 0,
			wonValueInPeriod: wonData?.totalOrderValue ?? 0,
			lostInPeriod: lostData?.count ?? 0,
			avgDealSize:
				wonData && wonData.count > 0
					? Math.round(wonData.totalOrderValue / wonData.count)
					: 0,
		};
	}
 
	private async getSourcePerformance(proId: string, dateRange: DateRange) {
		const [sources, sourceStats] = await Promise.all([
			this.dal.leadSources.findByProId(proId),
			this.dal.crmAnalytics.getSourceStatsInPeriod(proId, dateRange),
		]);
 
		const statsMap = new Map(sourceStats.map((r) => [r.sourceId, r]));
 
		return sources.map((source) => {
			const stats = statsMap.get(source.id);
			const total = stats?.total ?? 0;
			const wonCount = stats?.wonCount ?? 0;
			return {
				id: source.id,
				name: source.name,
				isSystem: source.isSystem,
				totalLeads: total,
				wonCount,
				conversionRate: total > 0 ? Math.round((wonCount / total) * 100) : 0,
				totalValue: stats?.totalValue ?? 0,
			};
		});
	}
 
	private async getFinancialSummary(proId: string, dateRange: DateRange) {
		const [won, pipelineValue] = await Promise.all([
			this.dal.crmAnalytics.getWonFinancialsInPeriod(proId, dateRange),
			// #427: same fix — Financial Summary's Active Pipeline tile must
			// reflect the period filter.
			this.dal.crmAnalytics.getActivePipelineValue(proId, dateRange),
		]);
 
		const quoteToOrderRatio =
			won.totalQuoteValue > 0
				? Math.round((won.totalOrderValue / won.totalQuoteValue) * 100)
				: 0;
 
		return {
			wonDealCount: won.count,
			wonTotalValue: won.totalOrderValue,
			avgDealSize:
				won.count > 0 ? Math.round(won.totalOrderValue / won.count) : 0,
			quoteToOrderRatio,
			activePipelineValue: pipelineValue.totalQuoteValue,
			activePipelineCount: pipelineValue.count,
		};
	}
 
	private async getFollowupHealth(proId: string) {
		const now = Math.floor(Date.now() / 1000);
		const sevenDaysAgo = now - 7 * 24 * 60 * 60;
		const fourteenDaysAgo = now - 14 * 24 * 60 * 60;
 
		const [staleLeads, stuckLeads, overdueReminders, noNotesLeads] =
			await Promise.all([
				this.dal.crmAnalytics.getStaleLeadsCount(proId, sevenDaysAgo),
				this.dal.crmAnalytics.getStuckLeadsCount(proId, fourteenDaysAgo),
				this.dal.leadReminders.countOverdueByProId(proId),
				this.dal.crmAnalytics.getNoNotesLeadsCount(proId),
			]);
 
		return {
			staleLeads,
			stuckLeads,
			overdueReminders,
			leadsWithNoNotes: noNotesLeads,
		};
	}
 
	private async getLossReasonBreakdown(
		proId: string,
		dateRange: DateRange,
	) {
		const results = await this.dal.crmAnalytics.getLossReasonBreakdown(
			proId,
			dateRange,
		);
 
		return results.map((r) => ({
			category: r.category ?? "unspecified",
			count: r.count,
		}));
	}
 
	private parsePeriod(period: string): DateRange {
		const now = new Date();
		const toEpoch = (d: Date) => Math.floor(d.getTime() / 1000);
		let from: Date;
 
		switch (period) {
			case "this_week": {
				const day = now.getDay();
				from = new Date(now);
				from.setDate(now.getDate() - day);
				from.setHours(0, 0, 0, 0);
				break;
			}
			case "this_month": {
				from = new Date(now.getFullYear(), now.getMonth(), 1);
				break;
			}
			case "last_month": {
				from = new Date(now.getFullYear(), now.getMonth() - 1, 1);
				const to = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59);
				return { from: toEpoch(from), to: toEpoch(to) };
			}
			case "this_quarter": {
				const quarter = Math.floor(now.getMonth() / 3);
				from = new Date(now.getFullYear(), quarter * 3, 1);
				break;
			}
			case "this_year": {
				from = new Date(now.getFullYear(), 0, 1);
				break;
			}
			case "all_time": {
				// Unix epoch — effectively unbounded. The previous floor at
				// 2020-01-01 silently excluded any pre-2020 leads from the
				// "All Time" view once #542 plumbed dateRange through to
				// getStageCountsForPro / getActivePipelineValue (resolving
				// issue #427). No current data predates 2020, but a back-
				// dated lead would have been invisible. Epoch is the obvious
				// unbounded sentinel.
				from = new Date(0);
				break;
			}
			default: {
				// Default to this month
				from = new Date(now.getFullYear(), now.getMonth(), 1);
				break;
			}
		}
 
		return { from: toEpoch(from), to: toEpoch(now) };
	}
}