Skip to content

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

Merged
gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:fix/first-run-after-payment
Oct 29, 2026
Merged

gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:fix/first-run-after-payment

Conversation

@cihan-gyk

@cihan-gyk cihan-gyk commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

The first tracking run after a purchase now starts even when the person never reaches the Stripe return page. It starts exactly once.

Before:

  • /api/stripe/success started the first run, but the webhook (checkout.session.completed) didn't. If the person closed the tab before the return page loaded, the subscription and the plan's engines were saved, but the prompts set up during onboarding waited for the nightly run, up to 24 h.
  • A payment confirmed later (e.g. SEPA: incomplete → active) never started it.

Now

  • web/src/lib/billing/first-run.ts is shared by the success route and the webhook. It:
    • starts the organization's first run only when the subscription is active or trialing, after the prompts are aligned to the plan's engines;
    • picks the oldest active brand (a paused brand is skipped);
    • logs errors and returns null, so Stripe always gets its 200.
  • Webhook:
    • checkout.session.completed starts it.
    • customer.subscription.updated starts it when the previous status was incomplete and the new one is active.
    • Renewals, trial → active, past_due and incomplete_expired don't.
  • Server: server/src/lib/first-run.js, behind /api/internal/trigger-tracking (moved to routes/internal-trigger-tracking.js):
    • Calls are serialized per brand.
    • If a full run is pending or running, or one was opened since the payment, it returns that run's id with created: false instead of opening another. The lower bound is min(since, now − 20 h), so reopening the return page a day later doesn't open a second run.
    • The success route carries that id to the dashboard.
  • Keyword volumes are started by the server when it opens the run (analyzeBrandVolumes(…, { onlyMissing: true })), so a slow response can't lose them. The web no longer calls /api/internal/analyze-volumes, which had no other caller and is removed.

Deploy: the API before the web. The old API opens a run per call, so in between, the webhook and the success route would start two runs.

Merge note (demo brand chain #1734–#1740):

  • firstBrandId in web/src/lib/billing/first-run.ts must add .eq('is_demo', false) once brands.is_demo exists.
  • In the success route, keep both this helper's call and hideDemoBrandAfterPurchase.

Related issue

None.

Type of change

  • fix — Bug fix

How to test

  1. cd server && npx vitest run src/lib/first-run.test.js src/routes/internal-trigger-tracking.test.js.
  2. cd web && yarn vitest run src/lib/billing/ src/app/api/stripe/. These cover:
    • the webhook alone starts the run;
    • success and webhook together give one run;
    • an incomplete → active update starts it;
    • an incomplete subscription or unpaid session doesn't;
    • Stripe gets 200 with the API down.

For the maintainer (Stripe test mode): try a checkout and close the tab on Stripe's success redirect. The first run should still start, once.

Checklist

🤖 Generated with Claude Code

cihan-gyk and others added 2 commits October 29, 2026 14:24
The first run after a payment only started when the Stripe return page
loaded. A person who closed the tab before it did had the prompts saved in
onboarding wait for the nightly run, up to a day.

The return page and the checkout.session.completed webhook now share one
helper (web/src/lib/billing/first-run.ts) that starts the first run for
the organization's first brand, after the plan alignment, and only for an
active or trialing subscription. The API keeps it to one run per checkout
(server/src/lib/first-run.js): calls for a brand are taken one at a time,
and one that finds a full run already waiting or running, or one started
since the checkout began, gets that run's id back with created: false.
The return page carries that id to the dashboard as before, and only the
caller that started the run also starts the volume analysis. A failure in
the webhook is logged and Stripe still gets its 200.

Deploy the API before the web app: an older API starts a run for every
call, so the two callers would start two.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ne run per purchase

Review follow-ups to the first run after a payment:

- A delayed payment (SEPA, for one) leaves the checkout's subscription
  incomplete, so nothing started the first run. The webhook now starts it
  on customer.subscription.updated when the status was incomplete, since
  the subscription's creation; never on renewals or other changes.
- The volume analysis starts in the API, with the run it creates
  (routes/internal-trigger-tracking.js, moved out of server.js and
  tested), not from the web app, so a caller that gives up waiting still
  gets it. The analyze-volumes endpoint had no other caller and is gone.
- The jobs read for an existing run go back to the purchase when it is
  older than 20 hours, so a return page opened again a day later finds the
  finished run instead of starting a second one.
- The first brand is the first active one: a paused brand is skipped.
- The job's flag is afterPayment, not firstRun.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Stripe doesn't order its events, so the subscription's incomplete to
active update can come before the checkout's, whose alignment then hasn't
run. Align here too before the first run starts, so it tracks only the
plan's engines.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good with 5f0a273 (branch take-1772, on this PR's head ce7cf99).

What I changed

  • customer.subscription.updated (incomplete → active) now aligns the prompts to the plan before it starts the first run, unless the plan-change branch just did. Stripe doesn't order its events: this update can arrive before checkout.session.completed, whose alignment then hasn't run, and the worker takes each prompt's platforms as stored (only models are filtered by plan at run time). Idempotent, like the other alignments.
  • Two webhook tests: same-plan update aligns before the API call; a plan-change update aligns once. The first fails without the fix.

Checked

  • One run per purchase: both callers pick the same brand (oldest active). The API takes calls for a brand one at a time, finds a live full run or one completed since the purchase, and hands its id back with created: false. Only the creating call starts the job and the volume analysis, so no second Cloro batch. This relies on the API being one process, which the in-memory job queue already assumes.
  • Stripe signature path: unchanged. constructEvent on the raw body, 400 on a missing or bad signature. The new calls never throw, have a 5 s timeout and return 200.
  • Plan limits: the run is started only for active/trialing, and only after the organization row has the new status and plan (the run's skipUnpaid reads it). With this fix, every caller aligns the prompts first.
  • Embeds: none added (jobs, brands read flat columns).
  • Read-only gate: no new web write route or action; the internal route keeps CRON_SECRET.
  • Migrations: none.

Follow-ups (not blocking)

  • A failed or cancelled first run gets restarted by reopening the return page. That's fine, and it's the same as before.
  • As before, any checkout (a re-subscribe too) starts a run when none ran since the session began.

Deploy: API before web, as the PR says.

Tests: on the stack tip merged with main 3b7611c: web stripe + billing (with the new tests), subscription-guard coverage and embed-hints pass; tsc is clean. Server first-run + internal-trigger-tracking pass. Full server suite: 290/298 files pass. The 8 that fail are the missing framer-api package in the local install (5 files) and the known timing tests (content-agent, content-people, traffic-events). eslint/prettier are clean on the touched files.

@gkhngyk
gkhngyk merged commit 605494d into ansvisor:main Oct 29, 2026
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants