|
| 1 | +import { NextRequest, NextResponse } from 'next/server'; |
| 2 | +import { requireApiUser } from '@/lib/api-auth'; |
| 3 | +import { getDb } from '@/lib/db'; |
| 4 | +import { clampDays } from '@/lib/analytics'; |
| 5 | +import { summarizeCycleTimes, percentImprovement } from '@/lib/benchmarks'; |
| 6 | +import { maybeSeedExclude } from '@/lib/seed-filter'; |
| 7 | + |
| 8 | +export const dynamic = 'force-dynamic'; |
| 9 | + |
| 10 | +type CycleTimeRow = { |
| 11 | + cycle_hours: number; |
| 12 | +}; |
| 13 | + |
| 14 | +function parseLaunchDate(raw: string | null | undefined): Date | null { |
| 15 | + if (!raw) return null; |
| 16 | + const d = new Date(raw); |
| 17 | + return Number.isNaN(d.getTime()) ? null : d; |
| 18 | +} |
| 19 | + |
| 20 | +function toIsoOrNull(date: Date | null): string | null { |
| 21 | + return date ? date.toISOString() : null; |
| 22 | +} |
| 23 | + |
| 24 | +function queryCycleTimes( |
| 25 | + request: Request, |
| 26 | + startIso: string, |
| 27 | + endIso: string, |
| 28 | +): number[] { |
| 29 | + const db = getDb(); |
| 30 | + const leadSeedFilter = maybeSeedExclude(request, 'leads', 'l.id'); |
| 31 | + const seqSeedFilter = maybeSeedExclude(request, 'sequences', 's.id'); |
| 32 | + const rows = db.prepare( |
| 33 | + ` |
| 34 | + SELECT ((julianday(MIN(s.created_at)) - julianday(l.created_at)) * 24.0) AS cycle_hours |
| 35 | + FROM leads l |
| 36 | + JOIN sequences s ON s.lead_id = l.id |
| 37 | + WHERE s.status IN ('approved', 'queued') |
| 38 | + AND julianday(l.created_at) >= julianday(?) |
| 39 | + AND julianday(l.created_at) < julianday(?) |
| 40 | + ${leadSeedFilter} |
| 41 | + ${seqSeedFilter} |
| 42 | + GROUP BY l.id, l.created_at |
| 43 | + `, |
| 44 | + ).all(startIso, endIso) as CycleTimeRow[]; |
| 45 | + |
| 46 | + return rows |
| 47 | + .map((r) => Number(r.cycle_hours)) |
| 48 | + .filter((h) => Number.isFinite(h) && h >= 0); |
| 49 | +} |
| 50 | + |
| 51 | +export async function GET(req: NextRequest) { |
| 52 | + const auth = requireApiUser(req as Request); |
| 53 | + if (auth) return auth; |
| 54 | + |
| 55 | + const days = clampDays(req.nextUrl.searchParams.get('days'), 30); |
| 56 | + const now = new Date(); |
| 57 | + const launchAt = parseLaunchDate( |
| 58 | + req.nextUrl.searchParams.get('launch_at') || process.env.HERMES_BENCHMARK_HERMES_LAUNCH_AT, |
| 59 | + ); |
| 60 | + |
| 61 | + let beforeStart: Date; |
| 62 | + let beforeEnd: Date; |
| 63 | + let afterStart: Date; |
| 64 | + let afterEnd: Date; |
| 65 | + let baselineMode: 'rolling_window' | 'launch_anchored'; |
| 66 | + |
| 67 | + if (launchAt) { |
| 68 | + baselineMode = 'launch_anchored'; |
| 69 | + const dMs = days * 24 * 60 * 60 * 1000; |
| 70 | + beforeEnd = new Date(launchAt.getTime()); |
| 71 | + beforeStart = new Date(launchAt.getTime() - dMs); |
| 72 | + afterStart = new Date(launchAt.getTime()); |
| 73 | + const launchPlusWindow = new Date(launchAt.getTime() + dMs); |
| 74 | + afterEnd = launchPlusWindow.getTime() < now.getTime() ? launchPlusWindow : now; |
| 75 | + } else { |
| 76 | + baselineMode = 'rolling_window'; |
| 77 | + const dMs = days * 24 * 60 * 60 * 1000; |
| 78 | + afterEnd = new Date(now.getTime()); |
| 79 | + afterStart = new Date(now.getTime() - dMs); |
| 80 | + beforeEnd = new Date(afterStart.getTime()); |
| 81 | + beforeStart = new Date(afterStart.getTime() - dMs); |
| 82 | + } |
| 83 | + |
| 84 | + const beforeValues = queryCycleTimes(req as Request, beforeStart.toISOString(), beforeEnd.toISOString()); |
| 85 | + const afterValues = queryCycleTimes(req as Request, afterStart.toISOString(), afterEnd.toISOString()); |
| 86 | + |
| 87 | + const beforeStats = summarizeCycleTimes(beforeValues.map((cycleHours) => ({ cycleHours }))); |
| 88 | + const afterStats = summarizeCycleTimes(afterValues.map((cycleHours) => ({ cycleHours }))); |
| 89 | + |
| 90 | + const medianDeltaPct = percentImprovement(beforeStats.medianHours, afterStats.medianHours); |
| 91 | + const p90DeltaPct = percentImprovement(beforeStats.p90Hours, afterStats.p90Hours); |
| 92 | + |
| 93 | + return NextResponse.json({ |
| 94 | + metric: 'lead_to_approved_campaign_cycle_time_hours', |
| 95 | + days, |
| 96 | + baseline_mode: baselineMode, |
| 97 | + window: { |
| 98 | + before: { start: beforeStart.toISOString(), end: beforeEnd.toISOString() }, |
| 99 | + after: { start: afterStart.toISOString(), end: afterEnd.toISOString() }, |
| 100 | + now: now.toISOString(), |
| 101 | + launch_at: toIsoOrNull(launchAt), |
| 102 | + }, |
| 103 | + before: beforeStats, |
| 104 | + after: afterStats, |
| 105 | + delta: { |
| 106 | + median_pct: medianDeltaPct, |
| 107 | + p90_pct: p90DeltaPct, |
| 108 | + }, |
| 109 | + inclusion_rules: [ |
| 110 | + 'Lead cohort is based on lead.created_at within each window.', |
| 111 | + "Cycle time is MIN(sequence.created_at where sequence.status in ['approved','queued']) - lead.created_at.", |
| 112 | + 'Only non-negative cycle times are counted.', |
| 113 | + 'real=true excludes seeded records.', |
| 114 | + ], |
| 115 | + }); |
| 116 | +} |
0 commit comments