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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 12x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 6x 6x 6x 6x 12x 12x 6x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 3x 3x 5x 5x 5x 5x 5x 5x 5x 5x 15x 15x 15x 15x 15x 15x 15x 2x 2x 15x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 5x 5x 5x 5x 5x | /**
* Cohort Analysis Service
*
* Provides customer cohort analysis including:
* - Retention by signup month
* - Revenue by cohort
* - Customer lifetime value by cohort
*/
import { prisma } from "@/lib/prisma";
import { logger } from "@/lib/logging";
import { startOfMonth, subMonths, format, endOfMonth } from "date-fns";
export interface CohortData {
cohort: string; // Format: "YYYY-MM" (signup month)
size: number; // Number of users in cohort
retention: number[]; // Percentage retained in each subsequent month
revenue: number[]; // Revenue in each subsequent month
orders: number[]; // Order count in each subsequent month
averageOrderValue: number;
customerLifetimeValue: number;
}
export interface CohortAnalysisResult {
cohorts: CohortData[];
totalUsers: number;
averageRetention: number[];
averageCLV: number;
}
/**
* Get cohort analysis data
*
* @param months - Number of months to analyze (default: 6)
* @returns Cohort analysis with retention and revenue data
*/
export async function getCohortAnalysis(months: number = 6): Promise<CohortAnalysisResult> {
logger.info(`Running cohort analysis for ${months} months`, { category: "ANALYTICS", months });
const now = new Date();
const cohorts: CohortData[] = [];
// Process each cohort month
for (let i = months - 1; i >= 0; i--) {
const cohortMonth = subMonths(now, i);
const cohortStart = startOfMonth(cohortMonth);
const cohortEnd = endOfMonth(cohortMonth);
// Get users who signed up in this cohort month
const cohortUsers = await prisma.user.findMany({
where: {
createdAt: {
gte: cohortStart,
lte: cohortEnd,
},
},
select: { id: true },
});
const userIds = cohortUsers.map((u) => u.id);
const cohortSize = userIds.length;
if (cohortSize === 0) {
cohorts.push({
cohort: format(cohortStart, "yyyy-MM"),
size: 0,
retention: [],
revenue: [],
orders: [],
averageOrderValue: 0,
customerLifetimeValue: 0,
});
continue;
}
// Calculate retention, revenue, and orders for each subsequent month
const retention: number[] = [];
const revenue: number[] = [];
const orders: number[] = [];
// Track from cohort month to current month
for (let j = 0; j <= i; j++) {
const periodMonth = subMonths(now, i - j);
const periodStart = startOfMonth(periodMonth);
const periodEnd = endOfMonth(periodMonth);
// Count users who placed orders in this period
const activeUserOrders = await prisma.order.findMany({
where: {
userId: { in: userIds },
createdAt: {
gte: periodStart,
lte: periodEnd,
},
status: { not: "CANCELLED" },
},
select: {
userId: true,
total: true,
},
});
// Get unique active users
const activeUserIds = new Set(activeUserOrders.map((o) => o.userId));
const activeCount = activeUserIds.size;
// Calculate period revenue
const periodRevenue = activeUserOrders.reduce(
(sum, order) => sum + Number(order.total),
0
);
retention.push(Math.round((activeCount / cohortSize) * 100 * 10) / 10);
revenue.push(Math.round(periodRevenue * 100) / 100);
orders.push(activeUserOrders.length);
}
// Calculate total revenue and CLV
const totalRevenue = revenue.reduce((sum, r) => sum + r, 0);
const totalOrders = orders.reduce((sum, o) => sum + o, 0);
const aov = totalOrders > 0 ? totalRevenue / totalOrders : 0;
const clv = cohortSize > 0 ? totalRevenue / cohortSize : 0;
cohorts.push({
cohort: format(cohortStart, "yyyy-MM"),
size: cohortSize,
retention,
revenue,
orders,
averageOrderValue: Math.round(aov * 100) / 100,
customerLifetimeValue: Math.round(clv * 100) / 100,
});
}
// Calculate averages across all cohorts
const totalUsers = cohorts.reduce((sum, c) => sum + c.size, 0);
const averageCLV = cohorts.length > 0
? cohorts.reduce((sum, c) => sum + c.customerLifetimeValue * c.size, 0) / Math.max(totalUsers, 1)
: 0;
// Calculate average retention for each period
const maxPeriods = Math.max(...cohorts.map((c) => c.retention.length), 0);
const averageRetention: number[] = [];
for (let p = 0; p < maxPeriods; p++) {
const values = cohorts
.filter((c) => c.retention[p] !== undefined && c.size > 0)
.map((c) => c.retention[p]);
if (values.length > 0) {
averageRetention.push(
Math.round((values.reduce((sum, v) => sum + v, 0) / values.length) * 10) / 10
);
}
}
logger.info(`Cohort analysis complete: ${cohorts.length} cohorts, ${totalUsers} total users`, { category: "ANALYTICS", cohortCount: cohorts.length, totalUsers });
return {
cohorts,
totalUsers,
averageRetention,
averageCLV: Math.round(averageCLV * 100) / 100,
};
}
/**
* Get retention matrix for visualization
*
* Returns data suitable for a cohort heatmap
*/
export async function getRetentionMatrix(months: number = 6): Promise<{
labels: string[];
data: (number | null)[][];
}> {
const analysis = await getCohortAnalysis(months);
const labels = analysis.cohorts.map((c) => c.cohort);
const data = analysis.cohorts.map((c) => {
// Pad retention array to have consistent length
const maxLength = months;
const padded: (number | null)[] = [...c.retention];
while (padded.length < maxLength) {
padded.push(null); // Future periods not yet reached
}
return padded;
});
return { labels, data };
}
/**
* Get customer segments by value
*
* Segments customers into High/Medium/Low value based on total spend
*/
export async function getCustomerSegments(): Promise<{
high: { count: number; revenue: number; avgOrderValue: number };
medium: { count: number; revenue: number; avgOrderValue: number };
low: { count: number; revenue: number; avgOrderValue: number };
dormant: { count: number; lastOrderDaysAgo: number };
}> {
// Get all customers with their order totals
const customers = await prisma.user.findMany({
where: {
orders: { some: {} },
},
select: {
id: true,
orders: {
where: { status: { not: "CANCELLED" } },
select: {
total: true,
createdAt: true,
},
},
},
});
const now = new Date();
const dormantThreshold = 90; // Days since last order to be considered dormant
// Calculate metrics for each customer
const customerMetrics = customers.map((customer) => {
const totalSpend = customer.orders.reduce(
(sum, order) => sum + Number(order.total),
0
);
const orderCount = customer.orders.length;
const lastOrderDate = customer.orders.length > 0
? Math.max(...customer.orders.map((o) => o.createdAt.getTime()))
: 0;
const daysSinceLastOrder = lastOrderDate
? Math.floor((now.getTime() - lastOrderDate) / (1000 * 60 * 60 * 24))
: Infinity;
return {
id: customer.id,
totalSpend,
orderCount,
avgOrderValue: orderCount > 0 ? totalSpend / orderCount : 0,
daysSinceLastOrder,
};
});
// Define thresholds (can be made configurable)
const highValueThreshold = 500; // Customers who spent > $500
const mediumValueThreshold = 100; // Customers who spent $100-$500
// Segment customers
const segments = {
high: customerMetrics.filter(
(c) => c.totalSpend > highValueThreshold && c.daysSinceLastOrder < dormantThreshold
),
medium: customerMetrics.filter(
(c) =>
c.totalSpend > mediumValueThreshold &&
c.totalSpend <= highValueThreshold &&
c.daysSinceLastOrder < dormantThreshold
),
low: customerMetrics.filter(
(c) => c.totalSpend <= mediumValueThreshold && c.daysSinceLastOrder < dormantThreshold
),
dormant: customerMetrics.filter((c) => c.daysSinceLastOrder >= dormantThreshold),
};
const calculateSegmentStats = (
segment: typeof customerMetrics
): { count: number; revenue: number; avgOrderValue: number } => ({
count: segment.length,
revenue: Math.round(segment.reduce((sum, c) => sum + c.totalSpend, 0) * 100) / 100,
avgOrderValue:
segment.length > 0
? Math.round(
(segment.reduce((sum, c) => sum + c.avgOrderValue, 0) / segment.length) * 100
) / 100
: 0,
});
return {
high: calculateSegmentStats(segments.high),
medium: calculateSegmentStats(segments.medium),
low: calculateSegmentStats(segments.low),
dormant: {
count: segments.dormant.length,
lastOrderDaysAgo:
segments.dormant.length > 0
? Math.round(
segments.dormant.reduce((sum, c) => sum + c.daysSinceLastOrder, 0) /
segments.dormant.length
)
: 0,
},
};
}
|