Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

fix(billing): start the first tracking run from the webhook too, once per purchase (#1772)

Cihan605494dfeac0
diff --git a/server/README.md b/server/README.md
index 2cc4028fb..a3749ad51 100644
--- a/server/README.md
+++ b/server/README.md
@@ -79,7 +79,7 @@ The server exposes a small public surface plus authenticated API routes:
| `/api/topics` | Topic grouping and topic-level prompt organization |
| `/api/internal/daily-tracking` | Internal daily tracking trigger protected by `CRON_SECRET` |
| `/api/internal/content/:id/brief` | Internal content brief trigger protected by `CRON_SECRET` |
-| `/api/internal/trigger-tracking` | Internal immediate tracking trigger protected by `CRON_SECRET` |
+| `/api/internal/trigger-tracking` | First tracking run after a payment (Stripe return page and webhook), one per purchase, with the brand's volume analysis; protected by `CRON_SECRET` |
| `POST /cloro/callback` | Public Cloro scraper webhook callback |
| `GET /t.js` | Public AI traffic tracking script |
| `POST /track/:trackingCode` | Public AI traffic pixel ingestion endpoint |
diff --git a/server/src/lib/first-run.js b/server/src/lib/first-run.js
new file mode 100644
index 000000000..75e4d2342
--- /dev/null
+++ b/server/src/lib/first-run.js
@@ -0,0 +1,113 @@
+/**
+ * The first tracking run after a payment (POST /api/internal/trigger-tracking).
+ *
+ * Two callers ask for it: the Stripe return page and Stripe's webhook (a
+ * completed checkout, or a subscription whose delayed payment went through).
+ * Either may come alone — the person can close the tab before the return page
+ * loads, and the webhook can be late — and both often come within the same
+ * second. So a run is started once per purchase: a call finds the run the
+ * other one started and hands back its id, which the return page carries to
+ * the dashboard's progress bar. The job is marked `afterPayment`.
+ *
+ * Calls for the same brand are taken one at a time in this process, so two
+ * calls cannot both find nothing and both start a run. The job queue already
+ * lives in this one process (job-runner.js).
+ */
+
+import supabaseAdmin from '../config/supabase.js';
+import { createJob } from './job-manager.js';
+
+/** How far back a run counts as this purchase's when the caller gives no time. */
+export const DEFAULT_SINCE_MS = 15 * 60_000;
+
+/**
+ * How far back a run still waiting or running is looked for. As the recovery
+ * sweep's limit (job-runner.js): an older waiting job is not restarted.
+ */
+export const LIVE_LOOKBACK_MS = 20 * 60 * 60_000;
+
+const LIVE = new Set(['waiting', 'active']);
+
+/** A run of every prompt, not a single-prompt or new-prompts run. */
+export function isFullRun(job) {
+ const data = job?.data ?? {};
+ return !data.promptId && !(Array.isArray(data.promptIds) && data.promptIds.length > 0);
+}
+
+/**
+ * The run that already covers this purchase, if any: a run of every prompt
+ * that is still waiting or running, or one started since `sinceIso` that did
+ * not fail or get cancelled. `jobs` are the brand's tracking jobs, newest
+ * first.
+ */
+export function pickStartedRun(jobs, sinceIso) {
+ const since = Date.parse(sinceIso);
+ return (
+ (jobs ?? []).find(
+ (job) =>
+ isFullRun(job) &&
+ (LIVE.has(job.status) ||
+ (job.status === 'completed' && Date.parse(job.created_at) >= since)),
+ ) ?? null
+ );
+}
+
+/**
+ * The brand's tracking jobs that could cover the purchase: back to whichever
+ * is earlier, the purchase or LIVE_LOOKBACK_MS ago. From the purchase, so a
+ * return page opened again a day later still finds the run that finished.
+ */
+async function brandTrackingJobs(brandId, sinceIso, now) {
+ const floor = Math.min(Date.parse(sinceIso), now - LIVE_LOOKBACK_MS);
+ const { data, error } = await supabaseAdmin
+ .from('jobs')
+ .select('id, status, data, created_at')
+ .eq('brand_id', brandId)
+ .eq('type', 'tracking')
+ .in('status', ['waiting', 'active', 'completed'])
+ .gte('created_at', new Date(floor).toISOString())
+ .order('created_at', { ascending: false })
+ .limit(50);
+ // A failed read must not start a second run: the caller logs it, and the
+ // nightly run tracks the brand.
+ if (error) throw new Error(`Failed to read tracking jobs: ${error.message}`);
+ return data ?? [];
+}
+
+async function startOnce(brandId, sinceIso) {
+ const now = Date.now();
+ const since = sinceIso ?? new Date(now - DEFAULT_SINCE_MS).toISOString();
+ const started = pickStartedRun(await brandTrackingJobs(brandId, since, now), since);
+ if (started) return { job: started, created: false };
+
+ const job = await createJob({
+ type: 'tracking',
+ brandId,
+ data: { brandId, immediate: true, afterPayment: true },
+ maxAttempts: 3,
+ });
+ return { job, created: true };
+}
+
+/** Calls in progress, per brand: each waits for the one before it. */
+const starting = new Map();
+
+/**
+ * Start a brand's first run after a purchase, unless one already covers it.
+ * `since` is when the purchase began (ISO); without it, the last
+ * DEFAULT_SINCE_MS count. Resolves to the job and whether this call created
+ * it — only a created job needs running.
+ *
+ * @param {{ brandId: string, since?: string }} opts
+ * @returns {Promise<{ job: { id: string }, created: boolean }>}
+ */
+export function startFirstRun({ brandId, since }) {
+ const previous = starting.get(brandId) ?? Promise.resolve();
+ const call = previous.catch(() => {}).then(() => startOnce(brandId, since));
+ starting.set(brandId, call);
+ const forget = () => {
+ if (starting.get(brandId) === call) starting.delete(brandId);
+ };
+ call.then(forget, forget);
+ return call;
+}
diff --git a/server/src/lib/first-run.test.js b/server/src/lib/first-run.test.js
new file mode 100644
index 000000000..c8f7d8740
--- /dev/null
+++ b/server/src/lib/first-run.test.js
@@ -0,0 +1,184 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The first run after a payment: the Stripe return page and the webhook both
+ * ask for it, and only one run starts.
+ */
+
+// The brand's tracking jobs, as the jobs table holds them (newest first).
+const table = vi.hoisted(() => ({ jobs: [], reads: [], readError: null }));
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: () => {
+ const read = { filters: [] };
+ const chain = {
+ select: () => chain,
+ eq: (column, value) => {
+ read.filters.push(['eq', column, value]);
+ return chain;
+ },
+ in: (column, values) => {
+ read.filters.push(['in', column, values]);
+ return chain;
+ },
+ gte: (column, value) => {
+ read.filters.push(['gte', column, value]);
+ return chain;
+ },
+ order: () => chain,
+ limit: () => chain,
+ then: (resolve, reject) => {
+ table.reads.push(read);
+ // The answer is the table as it is when the read lands, after any
+ // insert made meanwhile.
+ return Promise.resolve(
+ table.readError
+ ? { data: null, error: table.readError }
+ : { data: [...table.jobs], error: null },
+ ).then(resolve, reject);
+ },
+ };
+ return chain;
+ },
+ },
+}));
+
+const createJob = vi.hoisted(() => vi.fn());
+vi.mock('./job-manager.js', () => ({ createJob }));
+
+const { isFullRun, pickStartedRun, startFirstRun } = await import('./first-run.js');
+
+let ids = 0;
+beforeEach(() => {
+ table.jobs = [];
+ table.reads = [];
+ table.readError = null;
+ createJob.mockReset().mockImplementation(async ({ data }) => {
+ // Inserted a moment later, as a network call would be.
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ const job = {
+ id: `job-${++ids}`,
+ status: 'waiting',
+ data,
+ created_at: new Date().toISOString(),
+ };
+ table.jobs.unshift(job);
+ return job;
+ });
+});
+
+const CHECKOUT = '2026-10-29T10:00:00.000Z';
+const job = (status, createdAt, data = {}) => ({
+ id: `${status}-${createdAt}`,
+ status,
+ data: { brandId: 'b1', ...data },
+ created_at: createdAt,
+});
+
+describe('startFirstRun', () => {
+ it('starts one run when the return page and the webhook ask at the same moment', async () => {
+ const [page, webhook] = await Promise.all([
+ startFirstRun({ brandId: 'b1', since: CHECKOUT }),
+ startFirstRun({ brandId: 'b1', since: CHECKOUT }),
+ ]);
+
+ expect(createJob).toHaveBeenCalledTimes(1);
+ expect(createJob).toHaveBeenCalledWith({
+ type: 'tracking',
+ brandId: 'b1',
+ data: { brandId: 'b1', immediate: true, afterPayment: true },
+ maxAttempts: 3,
+ });
+ expect(page).toEqual({ job: expect.objectContaining({ id: 'job-1' }), created: true });
+ // The second gets the first's run back, for the progress bar.
+ expect(webhook.created).toBe(false);
+ expect(webhook.job.id).toBe(page.job.id);
+ });
+
+ it('starts a run when the webhook asks alone', async () => {
+ const { created } = await startFirstRun({ brandId: 'b1', since: CHECKOUT });
+
+ expect(created).toBe(true);
+ expect(createJob).toHaveBeenCalledTimes(1);
+ // Reads the brand's tracking jobs only.
+ expect(table.reads[0].filters).toEqual(
+ expect.arrayContaining([
+ ['eq', 'brand_id', 'b1'],
+ ['eq', 'type', 'tracking'],
+ ['in', 'status', ['waiting', 'active', 'completed']],
+ ]),
+ );
+ });
+
+ it('keeps brands apart: another brand still gets its run', async () => {
+ await Promise.all([
+ startFirstRun({ brandId: 'b1', since: CHECKOUT }),
+ startFirstRun({ brandId: 'b2', since: CHECKOUT }),
+ ]);
+ // Both reads saw an empty table at the time, one per brand.
+ expect(table.reads.map((read) => read.filters[0])).toEqual([
+ ['eq', 'brand_id', 'b1'],
+ ['eq', 'brand_id', 'b2'],
+ ]);
+ expect(createJob).toHaveBeenCalledTimes(2);
+ });
+
+ it('finds the finished run when the return page is opened again a day later', async () => {
+ const purchase = new Date(Date.now() - 30 * 60 * 60_000).toISOString();
+ const done = job('completed', new Date(Date.now() - 29 * 60 * 60_000).toISOString());
+ table.jobs = [done];
+
+ const { job: found, created } = await startFirstRun({ brandId: 'b1', since: purchase });
+
+ expect(created).toBe(false);
+ expect(found).toBe(done);
+ // Read back to the purchase, not only the last 20 hours.
+ expect(table.reads[0].filters).toContainEqual(['gte', 'created_at', purchase]);
+ });
+
+ it('reads back 20 hours for a run still waiting from before a recent purchase', async () => {
+ await startFirstRun({ brandId: 'b1', since: new Date().toISOString() });
+ const [, , floor] = table.reads[0].filters.find(([op]) => op === 'gte');
+ const hoursBack = (Date.now() - Date.parse(floor)) / 3_600_000;
+ expect(hoursBack).toBeGreaterThan(19.9);
+ expect(hoursBack).toBeLessThan(20.1);
+ });
+
+ it('starts nothing when the jobs cannot be read, and lets the next call try', async () => {
+ table.readError = { message: 'timeout' };
+ await expect(startFirstRun({ brandId: 'b1', since: CHECKOUT })).rejects.toThrow('timeout');
+ expect(createJob).not.toHaveBeenCalled();
+
+ table.readError = null;
+ expect((await startFirstRun({ brandId: 'b1', since: CHECKOUT })).created).toBe(true);
+ });
+});
+
+describe('pickStartedRun', () => {
+ it('finds a run of every prompt still waiting or running, however old', () => {
+ const live = job('active', '2026-10-29T08:00:00.000Z');
+ expect(pickStartedRun([live], CHECKOUT)).toBe(live);
+ });
+
+ it('finds a run finished since the checkout began', () => {
+ const done = job('completed', '2026-10-29T10:00:05.000Z');
+ expect(pickStartedRun([done], CHECKOUT)).toBe(done);
+ });
+
+ it('starts again after a run that finished before the checkout', () => {
+ expect(pickStartedRun([job('completed', '2026-10-29T09:00:00.000Z')], CHECKOUT)).toBeNull();
+ });
+
+ it('never counts a single-prompt or new-prompts run as the first run', () => {
+ const jobs = [
+ job('active', '2026-10-29T10:00:01.000Z', { promptId: 'p1' }),
+ job('waiting', '2026-10-29T10:00:02.000Z', { promptIds: ['p1', 'p2'] }),
+ ];
+ expect(pickStartedRun(jobs, CHECKOUT)).toBeNull();
+ });
+
+ it('counts a run with an empty new-prompts list as a full run', () => {
+ expect(isFullRun({ data: { brandId: 'b1', promptIds: [] } })).toBe(true);
+ expect(isFullRun({ data: { brandId: 'b1', promptId: null } })).toBe(true);
+ });
+});
diff --git a/server/src/routes/internal-trigger-tracking.js b/server/src/routes/internal-trigger-tracking.js
new file mode 100644
index 000000000..31fe49492
--- /dev/null
+++ b/server/src/routes/internal-trigger-tracking.js
@@ -0,0 +1,58 @@
+/**
+ * POST /api/internal/trigger-tracking — the first tracking run after a
+ * payment (CRON_SECRET auth).
+ *
+ * Asked for by both the Stripe return page and the Stripe webhook: one run per
+ * purchase (lib/first-run.js). `since` is when the purchase began; a call that
+ * finds the run already started gets its id back with `created: false`. The
+ * call that starts the run also starts the brand's volume analysis, here
+ * rather than from the web app, so a caller that gives up waiting for the
+ * answer still gets both.
+ *
+ * Mounted in server.js before the authenticated /api routes.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { startFirstRun } from '../lib/first-run.js';
+import { runTrackingJob } from '../lib/job-runner.js';
+import { analyzeBrandVolumes } from '../lib/volume-analysis.js';
+
+const router = Router();
+
+const body = z.object({
+ brandId: z.string().min(1),
+ since: z.iso.datetime({ offset: true }).optional(),
+});
+
+router.post('/', async (req, res) => {
+ const secret = req.headers.authorization?.replace('Bearer ', '');
+ if (!process.env.CRON_SECRET || secret !== process.env.CRON_SECRET) {
+ return res.status(401).json({ success: false, message: 'Unauthorized' });
+ }
+
+ const parsed = body.safeParse(req.body ?? {});
+ if (!parsed.success) {
+ return res
+ .status(400)
+ .json({ success: false, message: 'brandId is required; since must be an ISO time' });
+ }
+ const { brandId } = parsed.data;
+
+ try {
+ const { job, created } = await startFirstRun(parsed.data);
+ if (created) {
+ runTrackingJob(job.id, req.app.get('io'));
+ analyzeBrandVolumes(brandId, { onlyMissing: true }).catch((err) => {
+ req.log.error({ err, brandId }, 'first-run volume analysis error');
+ });
+ }
+
+ return res.json({ success: true, jobId: job.id, created });
+ } catch (err) {
+ req.log.error({ err, brandId }, 'internal trigger-tracking error');
+ return res.status(500).json({ success: false, message: err.message });
+ }
+});
+
+export default router;
diff --git a/server/src/routes/internal-trigger-tracking.test.js b/server/src/routes/internal-trigger-tracking.test.js
new file mode 100644
index 000000000..7178d144a
--- /dev/null
+++ b/server/src/routes/internal-trigger-tracking.test.js
@@ -0,0 +1,111 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * The first run after a payment, asked for by the Stripe return page and the
+ * webhook: the run that starts it also starts the volume analysis.
+ */
+
+const startFirstRun = vi.fn();
+const runTrackingJob = vi.fn();
+const analyzeBrandVolumes = vi.fn();
+vi.mock('../lib/first-run.js', () => ({ startFirstRun: (...args) => startFirstRun(...args) }));
+vi.mock('../lib/job-runner.js', () => ({ runTrackingJob: (...args) => runTrackingJob(...args) }));
+vi.mock('../lib/volume-analysis.js', () => ({
+ analyzeBrandVolumes: (...args) => analyzeBrandVolumes(...args),
+}));
+
+const { default: router } = await import('./internal-trigger-tracking.js');
+
+const io = { emit: vi.fn() };
+const log = { error: vi.fn() };
+let server;
+let url;
+
+beforeEach(async () => {
+ vi.stubEnv('CRON_SECRET', 'secret');
+ startFirstRun.mockReset().mockResolvedValue({ job: { id: 'job1' }, created: true });
+ runTrackingJob.mockReset();
+ analyzeBrandVolumes.mockReset().mockResolvedValue({});
+ log.error.mockReset();
+ const app = express();
+ app.set('io', io);
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.log = log;
+ next();
+ });
+ app.use('/api/internal/trigger-tracking', router);
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ url = `http://127.0.0.1:${server.address().port}/api/internal/trigger-tracking`;
+});
+
+afterEach(async () => {
+ vi.unstubAllEnvs();
+ await new Promise((resolve) => server.close(resolve));
+});
+
+const send = (body, secret = 'secret') =>
+ fetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${secret}` },
+ body: JSON.stringify(body),
+ });
+
+describe('POST /api/internal/trigger-tracking', () => {
+ it('starts the run it created, and the volume analysis with it', async () => {
+ const since = '2026-10-29T10:00:00.000Z';
+ const res = await send({ brandId: 'b1', since });
+
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ success: true, jobId: 'job1', created: true });
+ expect(startFirstRun).toHaveBeenCalledWith({ brandId: 'b1', since });
+ expect(runTrackingJob).toHaveBeenCalledWith('job1', io);
+ expect(analyzeBrandVolumes).toHaveBeenCalledWith('b1', { onlyMissing: true });
+ });
+
+ it('hands back the run already started, and starts nothing more', async () => {
+ startFirstRun.mockResolvedValue({ job: { id: 'job0' }, created: false });
+ const res = await send({ brandId: 'b1' });
+
+ expect(await res.json()).toEqual({ success: true, jobId: 'job0', created: false });
+ expect(runTrackingJob).not.toHaveBeenCalled();
+ expect(analyzeBrandVolumes).not.toHaveBeenCalled();
+ });
+
+ it('keeps the run when the volume analysis fails', async () => {
+ analyzeBrandVolumes.mockRejectedValue(new Error('volumes down'));
+ const res = await send({ brandId: 'b1' });
+
+ expect(res.status).toBe(200);
+ await vi.waitFor(() => expect(log.error).toHaveBeenCalled());
+ });
+
+ it.each([
+ ['no brand', {}],
+ ['an empty brand', { brandId: '' }],
+ ['a time that is not ISO', { brandId: 'b1', since: 'yesterday' }],
+ ])('refuses %s with 400, starting nothing', async (_name, body) => {
+ const res = await send(body);
+
+ expect(res.status).toBe(400);
+ expect(startFirstRun).not.toHaveBeenCalled();
+ });
+
+ it('refuses a caller without the secret', async () => {
+ const res = await send({ brandId: 'b1' }, 'wrong');
+
+ expect(res.status).toBe(401);
+ expect(startFirstRun).not.toHaveBeenCalled();
+ });
+
+ it('answers 500 when the jobs cannot be read', async () => {
+ startFirstRun.mockRejectedValue(new Error('Failed to read tracking jobs: timeout'));
+ const res = await send({ brandId: 'b1' });
+
+ expect(res.status).toBe(500);
+ expect(runTrackingJob).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/server.js b/server/src/server.js
index 411507077..42b4259a5 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -17,6 +17,7 @@ import routes from './routes/index.js';
import trafficRoutes from './routes/traffic.js';
import botIngestRoutes from './routes/bot-ingest.js';
import cloroCallbackRoutes from './routes/cloro-callback.js';
+import internalTriggerTrackingRoutes from './routes/internal-trigger-tracking.js';
import { pruneBotEvents } from './lib/bot-ingest.js';
import { pruneContentVersions } from './lib/content-history.js';
import {
@@ -48,7 +49,6 @@ import { PlanLimitError, getAiUsage, getSiteAuditQuotaStatus } from './lib/plan-
import { recountBrandCitations } from './lib/citation-recount.js';
import supabaseAdmin from './config/supabase.js';
import { getPlan, hasFeature, isCloud, isSubscriptionActive } from './config/plans.js';
-import { analyzeBrandVolumes } from './lib/volume-analysis.js';
import { runGscSync } from './lib/gsc-sync.js';
import { scheduleDemandCollect, sweepPromptDemand } from './lib/prompt-demand.js';
import { runGaSync } from './lib/ga-sync.js';
@@ -706,59 +706,9 @@ app.post('/api/internal/recount-citations', async (req, res) => {
}
});
-// --- Internal trigger-tracking endpoint (CRON_SECRET auth, called by Stripe success route) ---
-app.post('/api/internal/trigger-tracking', async (req, res) => {
- const secret = req.headers.authorization?.replace('Bearer ', '');
- if (!process.env.CRON_SECRET || secret !== process.env.CRON_SECRET) {
- return res.status(401).json({ success: false, message: 'Unauthorized' });
- }
-
- try {
- const { brandId } = req.body;
- if (!brandId) {
- return res.status(400).json({ success: false, message: 'brandId is required' });
- }
-
- const job = await createJob({
- type: 'tracking',
- brandId,
- data: { brandId, immediate: true },
- maxAttempts: 3,
- });
- runTrackingJob(job.id, io);
-
- return res.json({ success: true, jobId: job.id });
- } catch (err) {
- req.log.error({ err }, 'internal trigger-tracking error');
- return res.status(500).json({ success: false, message: err.message });
- }
-});
-
-// --- Internal analyze volumes endpoint (CRON_SECRET auth, called by Stripe success route) ---
-app.post('/api/internal/analyze-volumes', async (req, res) => {
- const secret = req.headers.authorization?.replace('Bearer ', '');
- if (!process.env.CRON_SECRET || secret !== process.env.CRON_SECRET) {
- return res.status(401).json({ success: false, message: 'Unauthorized' });
- }
-
- try {
- const { brandId } = req.body;
- if (!brandId) {
- return res.status(400).json({ success: false, message: 'brandId is required' });
- }
-
- analyzeBrandVolumes(brandId, {
- onlyMissing: true,
- }).catch((err) => {
- req.log.error({ err, brandId }, 'internal analyze-volumes error');
- });
-
- return res.status(202).json({ success: true, message: 'Volume analysis started' });
- } catch (err) {
- req.log.error({ err }, 'internal analyze volume error');
- return res.status(500).json({ success: false, message: err.message });
- }
-});
+// --- Internal trigger-tracking endpoint (routes/internal-trigger-tracking.js) ---
+// The first run after a payment, and the brand's volume analysis with it.
+app.use('/api/internal/trigger-tracking', internalTriggerTrackingRoutes);
// --- Cloro webhook callback (routes/cloro-callback.js) ---
// After the raw body parser mounted for this path at the top.
diff --git a/web/src/app/api/stripe/success/route.test.ts b/web/src/app/api/stripe/success/route.test.ts
index b6b586a63..fe2caf1d3 100644
--- a/web/src/app/api/stripe/success/route.test.ts
+++ b/web/src/app/api/stripe/success/route.test.ts
@@ -1,5 +1,5 @@
import type { NextRequest } from 'next/server';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* Back from Stripe Checkout: the organization gets its plan, status and
@@ -14,7 +14,11 @@ vi.mock('@/lib/stripe', () => ({
},
}));
-const db = vi.hoisted(() => ({ update: vi.fn(), eq: vi.fn() }));
+const db = vi.hoisted(() => ({
+ update: vi.fn(),
+ eq: vi.fn(),
+ brand: null as { id: string } | null,
+}));
vi.mock('@/lib/supabase/admin', () => ({
supabaseAdmin: {
from: () => ({
@@ -22,13 +26,14 @@ vi.mock('@/lib/supabase/admin', () => ({
db.update(values);
return { eq: db.eq };
},
- // No brand yet: nothing to start tracking for.
+ // The organization's first brand, for its first run: none unless a
+ // test says so.
select: () => {
const query = {
eq: () => query,
order: () => query,
limit: () => query,
- single: async () => ({ data: null }),
+ maybeSingle: async () => ({ data: db.brand }),
};
return query;
},
@@ -52,12 +57,25 @@ const subscription = (end?: number) => ({
items: { data: [end == null ? {} : { current_period_end: end }] },
});
+// The API the first run is asked of.
+const api = vi.fn();
+const apiPaths = () => api.mock.calls.map(([url]) => new URL(String(url)).pathname);
+
beforeEach(() => {
vi.clearAllMocks();
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'log').mockImplementation(() => {});
align.mockResolvedValue({ promptCount: 0, platforms: [], models: [] });
db.eq.mockResolvedValue({ error: null });
+ db.brand = null;
+ api.mockReset();
+ vi.stubGlobal('fetch', api);
+ vi.stubEnv('CRON_SECRET', 'secret');
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
});
describe('GET /api/stripe/success', () => {
@@ -100,3 +118,77 @@ describe('GET /api/stripe/success', () => {
expect(db.update.mock.calls[0][0]).not.toHaveProperty('subscription_ends_at');
});
});
+
+/**
+ * The first run: started here or by the webhook, whichever came first, and
+ * its id carried to the dashboard's progress bar either way.
+ */
+describe('GET /api/stripe/success, the first run', () => {
+ const paidCheckout = (status: string) => ({
+ payment_status: 'paid',
+ status: 'complete',
+ customer: 'cus1',
+ created: 1_800_000_000,
+ subscription: { ...subscription(), status },
+ });
+
+ beforeEach(() => {
+ db.brand = { id: 'brand1' };
+ });
+
+ it("carries the webhook's run to the dashboard, and starts no second one", async () => {
+ stripeApi.retrieveSession.mockResolvedValue(paidCheckout('active'));
+ api.mockResolvedValueOnce(Response.json({ success: true, jobId: 'job-w', created: false }));
+
+ const res = await back();
+
+ expect(apiPaths()).toEqual(['/api/internal/trigger-tracking']);
+ expect(JSON.parse(api.mock.calls[0][1].body)).toEqual({
+ brandId: 'brand1',
+ since: '2027-01-15T08:00:00.000Z',
+ });
+ expect(new URL(res.headers.get('location')!).searchParams.get('jobId')).toBe('job-w');
+ });
+
+ it('starts the run itself when it comes first', async () => {
+ stripeApi.retrieveSession.mockResolvedValue(paidCheckout('trialing'));
+ api.mockResolvedValueOnce(Response.json({ success: true, jobId: 'job-s', created: true }));
+
+ const res = await back();
+
+ // The API starts the volume analysis with the run.
+ expect(apiPaths()).toEqual(['/api/internal/trigger-tracking']);
+ expect(new URL(res.headers.get('location')!).searchParams.get('jobId')).toBe('job-s');
+ });
+
+ it('starts nothing for a subscription whose payment was not made', async () => {
+ stripeApi.retrieveSession.mockResolvedValue(paidCheckout('incomplete'));
+
+ const res = await back();
+
+ expect(api).not.toHaveBeenCalled();
+ expect(res.headers.get('location')).toMatch(/\/dashboard\/action-center\/actions$/);
+ });
+
+ it('starts nothing for a checkout that is not paid', async () => {
+ stripeApi.retrieveSession.mockResolvedValue({
+ ...paidCheckout('incomplete'),
+ payment_status: 'unpaid',
+ status: 'open',
+ });
+
+ await back();
+
+ expect(db.update).not.toHaveBeenCalled();
+ expect(api).not.toHaveBeenCalled();
+ });
+
+ it('opens the dashboard without a job when the API is down', async () => {
+ stripeApi.retrieveSession.mockResolvedValue(paidCheckout('active'));
+ api.mockRejectedValue(new Error('connect ECONNREFUSED'));
+
+ const res = await back();
+
+ expect(res.headers.get('location')).toMatch(/\/dashboard\/action-center\/actions$/);
+ });
+});
diff --git a/web/src/app/api/stripe/success/route.ts b/web/src/app/api/stripe/success/route.ts
index 27555a491..356f55b64 100644
--- a/web/src/app/api/stripe/success/route.ts
+++ b/web/src/app/api/stripe/success/route.ts
@@ -3,7 +3,7 @@ import { stripe } from '@/lib/stripe';
import { supabaseAdmin } from '@/lib/supabase/admin';
import { alignPromptsToPlanForOrg } from '@/lib/plan-engines';
import { periodEndIso } from '@/lib/billing/period-end';
-import { API_BASE_URL } from '@/config/api';
+import { startFirstTrackingRun } from '@/lib/billing/first-run';
import { DASHBOARD_HOME } from '@/config/home';
export async function GET(req: NextRequest) {
@@ -74,69 +74,14 @@ export async function GET(req: NextRequest) {
console.error('[stripe/success] Plan-engine alignment threw:', alignErr);
}
- // Find first brand and trigger tracking via aeo-server
- const { data: brand } = await supabaseAdmin
- .from('brands')
- .select('id')
- .eq('organization_id', orgId)
- .order('created_at', { ascending: true })
- .limit(1)
- .single();
-
- if (brand) {
- const serverUrl = API_BASE_URL;
- const cronSecret = process.env.CRON_SECRET;
-
- if (cronSecret) {
- try {
- const trackingRes = await fetch(`${serverUrl}/api/internal/trigger-tracking`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${cronSecret}`,
- },
- body: JSON.stringify({ brandId: brand.id }),
- });
-
- if (trackingRes.ok) {
- const result = await trackingRes.json();
- trackingJobId = result.jobId;
- console.log(
- '[stripe/success] Tracking triggered for brand:',
- brand.id,
- 'jobId:',
- trackingJobId,
- );
- } else {
- console.error('[stripe/success] Tracking trigger failed:', trackingRes.status);
- }
- } catch (fetchErr) {
- console.error('[stripe/success] Failed to call trigger-tracking:', fetchErr);
- }
-
- try {
- const volumesRes = await fetch(`${serverUrl}/api/internal/analyze-volumes`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${cronSecret}`,
- },
- body: JSON.stringify({ brandId: brand.id }),
- });
-
- if (volumesRes.ok) {
- console.log('[stripe/success] Volume analysis triggered for brand:', brand.id);
- } else {
- console.error(
- '[stripe/success] Volume analysis trigger failed:',
- volumesRes.status,
- );
- }
- } catch (fetchErr) {
- console.error('[stripe/success] Failed to call volume analysis:', fetchErr);
- }
- }
- }
+ // The first run, or the one the webhook already started for this
+ // checkout: its id goes to the dashboard either way.
+ trackingJobId = await startFirstTrackingRun({
+ orgId,
+ subscriptionStatus: subscription?.status,
+ purchaseStarted: session.created,
+ ctx: 'stripe/success',
+ });
}
}
}
diff --git a/web/src/app/api/stripe/webhook/route.test.ts b/web/src/app/api/stripe/webhook/route.test.ts
index 65f0d11c4..12c8cb4bb 100644
--- a/web/src/app/api/stripe/webhook/route.test.ts
+++ b/web/src/app/api/stripe/webhook/route.test.ts
@@ -1,5 +1,5 @@
import type { NextRequest } from 'next/server';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* The Stripe webhook keeps the organization's plan, status and period end in
@@ -17,16 +17,24 @@ vi.mock('@/lib/stripe', () => ({
const db = vi.hoisted(() => ({ update: vi.fn(), eq: vi.fn() }));
vi.mock('@/lib/supabase/admin', () => ({
supabaseAdmin: {
- from: () => ({
- update: (values: unknown) => {
- db.update(values);
- return { eq: db.eq };
- },
- // The plan before an update, to tell a plan change.
- select: () => ({
- eq: () => ({ maybeSingle: async () => ({ data: { id: 'org1', plan: 'starter' } }) }),
- }),
- }),
+ from: (table: string) => {
+ // The plan before an update, to tell a plan change; the organization's
+ // first brand, for its first run.
+ const row = table === 'brands' ? { id: 'brand1' } : { id: 'org1', plan: 'starter' };
+ const query = {
+ eq: () => query,
+ order: () => query,
+ limit: () => query,
+ maybeSingle: async () => ({ data: row }),
+ };
+ return {
+ update: (values: unknown) => {
+ db.update(values);
+ return { eq: db.eq };
+ },
+ select: () => query,
+ };
+ },
},
}));
@@ -35,8 +43,11 @@ vi.mock('@/lib/plan-engines', () => ({ alignPromptsToPlanForOrg: align }));
const { POST } = await import('./route');
-const deliver = (type: string, object: unknown) => {
- stripeApi.constructEvent.mockReturnValue({ type, data: { object } });
+const deliver = (type: string, object: unknown, previous?: Record<string, unknown>) => {
+ stripeApi.constructEvent.mockReturnValue({
+ type,
+ data: { object, ...(previous ? { previous_attributes: previous } : {}) },
+ });
return POST(
new Request('http://localhost/api/stripe/webhook', {
method: 'POST',
@@ -55,12 +66,24 @@ const subscription = (status: string, end?: number) => ({
items: { data: [end == null ? {} : { current_period_end: end }] },
});
+// The API the first run is asked of.
+const api = vi.fn();
+const apiPaths = () => api.mock.calls.map(([url]) => new URL(String(url)).pathname);
+
beforeEach(() => {
vi.clearAllMocks();
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(console, 'log').mockImplementation(() => {});
align.mockResolvedValue({ promptCount: 0, platforms: [], models: [] });
db.eq.mockResolvedValue({ error: null });
+ api.mockReset().mockImplementation(async () => Response.json({ jobId: 'job1', created: true }));
+ vi.stubGlobal('fetch', api);
+ vi.stubEnv('CRON_SECRET', 'secret');
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
});
describe('checkout.session.completed', () => {
@@ -91,6 +114,113 @@ describe('checkout.session.completed', () => {
});
});
+/**
+ * The first run starts from the webhook too, as the return page may never
+ * load; the API keeps it to one run per purchase.
+ */
+describe('checkout.session.completed, the first run', () => {
+ const checkout = { customer: 'cus1', subscription: 'sub1', created: 1_800_000_000 };
+
+ it('starts the first run on its own, after the alignment, with when the checkout began', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('trialing'));
+ const res = await deliver('checkout.session.completed', checkout);
+
+ expect(res.status).toBe(200);
+ expect(apiPaths()).toEqual(['/api/internal/trigger-tracking']);
+ expect(JSON.parse(api.mock.calls[0][1].body)).toEqual({
+ brandId: 'brand1',
+ since: '2027-01-15T08:00:00.000Z',
+ });
+ expect(align.mock.invocationCallOrder[0]).toBeLessThan(api.mock.invocationCallOrder[0]);
+ });
+
+ it('starts nothing for a subscription whose payment was not made', async () => {
+ for (const status of ['incomplete', 'incomplete_expired']) {
+ stripeApi.retrieve.mockResolvedValue(subscription(status));
+ const res = await deliver('checkout.session.completed', checkout);
+ expect(res.status).toBe(200);
+ }
+ expect(api).not.toHaveBeenCalled();
+ });
+
+ it('starts nothing when the organization could not be written', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('active'));
+ db.eq.mockResolvedValue({ error: { message: 'timeout' } });
+ await deliver('checkout.session.completed', checkout);
+ expect(api).not.toHaveBeenCalled();
+ });
+
+ it('still answers Stripe 200 when the API is down', async () => {
+ stripeApi.retrieve.mockResolvedValue(subscription('active'));
+ api.mockRejectedValue(new Error('connect ECONNREFUSED'));
+ const res = await deliver('checkout.session.completed', checkout);
+ expect(res.status).toBe(200);
+ expect(db.update).toHaveBeenCalledTimes(1);
+ });
+
+ it('starts nothing on a later update or a failed payment', async () => {
+ await deliver('customer.subscription.updated', subscription('active'));
+ await deliver('invoice.payment_failed', { customer: 'cus1' });
+ expect(api).not.toHaveBeenCalled();
+ });
+});
+
+/**
+ * A delayed payment (SEPA) leaves the checkout's subscription incomplete; the
+ * first run starts when Stripe says it went through.
+ */
+describe('customer.subscription.updated, the first run', () => {
+ const paidLater = (status: string) => ({ ...subscription(status), created: 1_800_000_000 });
+
+ it('starts the first run when an incomplete subscription becomes active', async () => {
+ const res = await deliver('customer.subscription.updated', paidLater('active'), {
+ status: 'incomplete',
+ });
+
+ expect(res.status).toBe(200);
+ expect(apiPaths()).toEqual(['/api/internal/trigger-tracking']);
+ // Since the subscription began: a run started since then covers it.
+ expect(JSON.parse(api.mock.calls[0][1].body)).toEqual({
+ brandId: 'brand1',
+ since: '2027-01-15T08:00:00.000Z',
+ });
+ // After the organization reads active, which the run checks.
+ expect(db.update.mock.invocationCallOrder[0]).toBeLessThan(api.mock.invocationCallOrder[0]);
+ });
+
+ it('aligns the prompts to the plan before the run, when it comes before the checkout', async () => {
+ // Same plan as the organization already has, so no plan change aligns.
+ const samePlan = { ...paidLater('active'), metadata: { plan_id: 'starter' } };
+ await deliver('customer.subscription.updated', samePlan, { status: 'incomplete' });
+
+ expect(align).toHaveBeenCalledTimes(1);
+ expect(align).toHaveBeenCalledWith('org1', 'starter');
+ expect(align.mock.invocationCallOrder[0]).toBeLessThan(api.mock.invocationCallOrder[0]);
+ });
+
+ it('aligns once when the plan changed too', async () => {
+ await deliver('customer.subscription.updated', paidLater('active'), { status: 'incomplete' });
+ expect(align).toHaveBeenCalledTimes(1);
+ expect(align).toHaveBeenCalledWith('org1', 'growth');
+ });
+
+ it('starts nothing on a renewal, or other changes of an active subscription', async () => {
+ await deliver('customer.subscription.updated', paidLater('active'), {
+ current_period_end: 1_700_000_000,
+ });
+ await deliver('customer.subscription.updated', paidLater('active'), { status: 'trialing' });
+ await deliver('customer.subscription.updated', paidLater('active'), { status: 'past_due' });
+ expect(api).not.toHaveBeenCalled();
+ });
+
+ it('starts nothing when the delayed payment fails', async () => {
+ await deliver('customer.subscription.updated', paidLater('incomplete_expired'), {
+ status: 'incomplete',
+ });
+ expect(api).not.toHaveBeenCalled();
+ });
+});
+
describe('customer.subscription.updated', () => {
it('still writes the new period end, and leaves it alone without one', async () => {
await deliver('customer.subscription.updated', subscription('active', 1_800_000_000));
diff --git a/web/src/app/api/stripe/webhook/route.ts b/web/src/app/api/stripe/webhook/route.ts
index 8fabc55ed..385ff603e 100644
--- a/web/src/app/api/stripe/webhook/route.ts
+++ b/web/src/app/api/stripe/webhook/route.ts
@@ -3,6 +3,8 @@ import { stripe } from '@/lib/stripe';
import { supabaseAdmin } from '@/lib/supabase/admin';
import { alignPromptsToPlanForOrg } from '@/lib/plan-engines';
import { periodEndIso } from '@/lib/billing/period-end';
+import { startFirstTrackingRun } from '@/lib/billing/first-run';
+import { isSubscriptionActive } from '@/config/plans';
import type Stripe from 'stripe';
/**
@@ -89,6 +91,15 @@ export async function POST(req: NextRequest) {
// ahead of the redirect (or that happen out-of-band entirely)
// still get prompts in sync. Idempotent.
await alignPromptsSafe(orgId, planId || 'starter', 'checkout');
+ // The first run too, after the alignment so it tracks the plan's
+ // engines: the return page may never load (a closed tab). One
+ // run per checkout, whichever of the two comes first.
+ await startFirstTrackingRun({
+ orgId,
+ subscriptionStatus: subscription.status,
+ purchaseStarted: session.created,
+ ctx: 'webhook:checkout',
+ });
}
}
} else {
@@ -137,12 +148,38 @@ export async function POST(req: NextRequest) {
.update(updates)
.eq('stripe_customer_id', customerId);
- if (orgBefore && newPlanId && newPlanId !== orgBefore.plan) {
+ const planChanged = Boolean(orgBefore && newPlanId && newPlanId !== orgBefore.plan);
+ if (orgBefore && planChanged) {
// Plan changed — re-align prompts. Handles both expansion
// (Starter → Growth: 2 → 8 engines) and contraction
// (Growth → Starter: 8 → 2 engines). Issue #79.
await alignPromptsSafe(orgBefore.id, newPlanId, 'subscription.updated');
}
+
+ // A delayed payment (SEPA, for one) that went through: the
+ // checkout left the subscription incomplete, so nothing started
+ // the first run then. Only on that change, never on a renewal.
+ const previous = event.data.previous_attributes as
+ | Partial<Stripe.Subscription>
+ | undefined;
+ if (orgBefore && previous?.status === 'incomplete') {
+ // Stripe doesn't order its events: this one can come before the
+ // checkout's, whose alignment then hasn't run. Align here too, so
+ // the run tracks only the plan's engines. Idempotent.
+ if (!planChanged && isSubscriptionActive(subscription.status)) {
+ await alignPromptsSafe(
+ orgBefore.id,
+ newPlanId || orgBefore.plan || 'starter',
+ 'subscription.updated',
+ );
+ }
+ await startFirstTrackingRun({
+ orgId: orgBefore.id,
+ subscriptionStatus: subscription.status,
+ purchaseStarted: subscription.created,
+ ctx: 'webhook:subscription.updated',
+ });
+ }
}
break;
}
diff --git a/web/src/lib/billing/first-run.test.ts b/web/src/lib/billing/first-run.test.ts
new file mode 100644
index 000000000..343f220f9
--- /dev/null
+++ b/web/src/lib/billing/first-run.test.ts
@@ -0,0 +1,120 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The first tracking run after a purchase, asked of the API by the Stripe
+ * return page and the webhook alike.
+ */
+
+const brands = vi.hoisted(() => ({
+ first: { id: 'brand1' } as { id: string } | null,
+ filters: [] as [string, unknown][],
+}));
+vi.mock('@/lib/supabase/admin', () => ({
+ supabaseAdmin: {
+ from: () => {
+ const query = {
+ select: () => query,
+ eq: (column: string, value: unknown) => {
+ brands.filters.push([column, value]);
+ return query;
+ },
+ order: () => query,
+ limit: () => query,
+ maybeSingle: async () => ({ data: brands.first }),
+ };
+ return query;
+ },
+ },
+}));
+
+const { startFirstTrackingRun } = await import('./first-run');
+
+const fetchMock = vi.fn();
+const answer = (status: number, body: unknown = {}) =>
+ new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+
+/** The API paths called, in order. */
+const calls = () => fetchMock.mock.calls.map(([url]) => new URL(String(url)).pathname);
+const bodyOf = (n: number) => JSON.parse(fetchMock.mock.calls[n][1].body as string);
+
+const start = (status: string | null | undefined = 'trialing') =>
+ startFirstTrackingRun({
+ orgId: 'org1',
+ subscriptionStatus: status,
+ purchaseStarted: 1_800_000_000,
+ ctx: 'test',
+ });
+
+beforeEach(() => {
+ brands.first = { id: 'brand1' };
+ brands.filters = [];
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubEnv('CRON_SECRET', 'secret');
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+});
+
+describe('startFirstTrackingRun', () => {
+ it('starts the run for the first active brand, with when the purchase began', async () => {
+ fetchMock.mockResolvedValueOnce(answer(200, { jobId: 'job1', created: true }));
+
+ expect(await start()).toBe('job1');
+ // One call: the API starts the volume analysis with the run.
+ expect(calls()).toEqual(['/api/internal/trigger-tracking']);
+ expect(bodyOf(0)).toEqual({ brandId: 'brand1', since: '2027-01-15T08:00:00.000Z' });
+ expect(fetchMock.mock.calls[0][1].headers).toMatchObject({ Authorization: 'Bearer secret' });
+ // A paused brand is never the one tracked.
+ expect(brands.filters).toEqual([
+ ['organization_id', 'org1'],
+ ['is_active', true],
+ ]);
+ });
+
+ it('hands back the run the other caller started', async () => {
+ fetchMock.mockResolvedValueOnce(answer(200, { jobId: 'job1', created: false }));
+
+ expect(await start('active')).toBe('job1');
+ expect(calls()).toEqual(['/api/internal/trigger-tracking']);
+ });
+
+ it.each(['incomplete', 'incomplete_expired', 'past_due', 'unpaid', null])(
+ 'starts nothing for a %s subscription',
+ async (status) => {
+ expect(await start(status)).toBeNull();
+ expect(fetchMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it('starts nothing for an organization without an active brand', async () => {
+ brands.first = null;
+ expect(await start()).toBeNull();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('starts nothing without the API secret', async () => {
+ vi.stubEnv('CRON_SECRET', '');
+ expect(await start()).toBeNull();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('never throws: a refused or unreachable API gives no run', async () => {
+ fetchMock.mockResolvedValueOnce(answer(500));
+ expect(await start()).toBeNull();
+ expect(calls()).toEqual(['/api/internal/trigger-tracking']);
+
+ fetchMock.mockReset().mockRejectedValueOnce(new Error('timeout'));
+ expect(await start()).toBeNull();
+ });
+
+ it('lets the API pick the window when the purchase time is unknown', async () => {
+ fetchMock.mockResolvedValueOnce(answer(200, { jobId: 'job1', created: false }));
+ await startFirstTrackingRun({ orgId: 'org1', subscriptionStatus: 'active', ctx: 'test' });
+ expect(bodyOf(0)).toEqual({ brandId: 'brand1' });
+ });
+});
diff --git a/web/src/lib/billing/first-run.ts b/web/src/lib/billing/first-run.ts
new file mode 100644
index 000000000..9e4bb67ca
--- /dev/null
+++ b/web/src/lib/billing/first-run.ts
@@ -0,0 +1,98 @@
+import { supabaseAdmin } from '@/lib/supabase/admin';
+import { API_BASE_URL } from '@/config/api';
+import { isSubscriptionActive } from '@/config/plans';
+
+/** Each call to the API gets this long, so a slow server never holds up a webhook. */
+const API_TIMEOUT_MS = 5_000;
+
+/**
+ * The organization's first brand that is not paused: the one onboarding
+ * created. Once the demo brand lands (00380, not on main yet), it is skipped
+ * too: `.eq('is_demo', false)`.
+ */
+async function firstBrandId(orgId: string): Promise<string | null> {
+ const { data: brand } = await supabaseAdmin
+ .from('brands')
+ .select('id')
+ .eq('organization_id', orgId)
+ .eq('is_active', true)
+ .order('created_at', { ascending: true })
+ .limit(1)
+ .maybeSingle();
+ return brand?.id ?? null;
+}
+
+async function callApi(path: string, body: Record<string, unknown>, cronSecret: string) {
+ return fetch(`${API_BASE_URL}${path}`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${cronSecret}`,
+ },
+ body: JSON.stringify(body),
+ cache: 'no-store',
+ signal: AbortSignal.timeout(API_TIMEOUT_MS),
+ });
+}
+
+/**
+ * Start an organization's first tracking run after a purchase, from the
+ * Stripe return page or the webhook, whichever comes first: the person may
+ * close the tab before the return page loads, and the prompts saved in
+ * onboarding would then wait for the nightly run. The webhook also starts it
+ * when a delayed payment (SEPA, for one) goes through later. The API starts
+ * one run per purchase (server/src/lib/first-run.js), so the second caller
+ * gets the first one's job back; the API also starts the volume analysis
+ * with the run it starts.
+ *
+ * Only for a subscription that is active or trialing: an incomplete one (a
+ * payment not made) gets nothing. Resolves to the run's job id, for the
+ * dashboard's progress bar, or null. Never throws: the payment is done
+ * whatever happens here, and the nightly run tracks the brand anyway.
+ */
+export async function startFirstTrackingRun({
+ orgId,
+ subscriptionStatus,
+ purchaseStarted,
+ ctx,
+}: {
+ orgId: string;
+ subscriptionStatus: string | null | undefined;
+ /**
+ * When the purchase began, in Stripe's Unix seconds: the Checkout
+ * Session's `created`, or the subscription's.
+ */
+ purchaseStarted?: number | null;
+ /** Who is asking, for the logs. */
+ ctx: string;
+}): Promise<string | null> {
+ if (!isSubscriptionActive(subscriptionStatus)) {
+ console.log(`[${ctx}] No first run: subscription is ${subscriptionStatus ?? 'missing'}`);
+ return null;
+ }
+ const cronSecret = process.env.CRON_SECRET;
+ if (!cronSecret) return null;
+
+ try {
+ const brandId = await firstBrandId(orgId);
+ if (!brandId) return null;
+
+ const since = purchaseStarted ? new Date(purchaseStarted * 1000).toISOString() : undefined;
+ const res = await callApi('/api/internal/trigger-tracking', { brandId, since }, cronSecret);
+ if (!res.ok) {
+ console.error(`[${ctx}] First run trigger failed:`, res.status);
+ return null;
+ }
+ const { jobId, created } = (await res.json()) as { jobId?: string; created?: boolean };
+ console.log(
+ `[${ctx}] First run ${created === false ? 'already started' : 'started'} for brand:`,
+ brandId,
+ 'jobId:',
+ jobId,
+ );
+ return jobId ?? null;
+ } catch (err) {
+ console.error(`[${ctx}] Failed to start the first run:`, err);
+ return null;
+ }
+}