Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Auto-reload credits within a monthly budget (#982)
Ben Senescuc730ddfa9175
diff --git a/docs/maintainers/specs/0017-credit-auto-reload.md b/docs/maintainers/specs/0017-credit-auto-reload.mdnew file mode 100644index 00000000..f7700541--- /dev/null+++ b/docs/maintainers/specs/0017-credit-auto-reload.md@@ -0,0 +1,60 @@+# Credit auto-reload++## Status++Accepted.++## Context++Hosted organizations get monthly usage credits with their plan and can buy top-up credits that never expire (see [hosted metering](0002-hosted-dataforseo-metering-with-autumn.md)). Every purchase goes through Stripe Checkout. An organization that runs out mid-task stops: rank checks are refused, agents report insufficient credits, and someone with the billing role has to notice, open Billing and buy credits by hand.++Customers asked to buy credits automatically, with a cap on how much that can cost them in a month.++## Decision++Billing managers on a paid plan can turn on auto-reload on the Billing page, under the one-off purchase. It has two whole-dollar settings: the amount each reload buys, and a monthly budget, the most the organization spends on top-up credits in a billing cycle. The threshold that triggers a reload is fixed at $5 of top-up credits.++Autumn holds both settings as billing controls on the customer's `topup_credits` balance and enforces them itself. The reload is an `auto_topups` control: after every deduction from or refused check on the top-up balance, Autumn compares the remaining balance with the threshold and, when at or below it, charges the organization's saved card for the reload amount through the existing one-off `credit-top-up` price, adding the credits to the top-up balance. The budget is a `usage_limits` control: a hard cap on top-up credits spent per month, aligned to the billing cycle. Autumn refuses the hold that would take the cycle's spend past it, with credits still in the balance, and counts open holds against it. The budget counts every top-up credit spent, including credits bought by hand, and is in force only while auto-reload is on.++Autumn refuses the hold that would exceed the budget while credits remain, so the spend rarely lands on the limit itself; the app treats the budget as spent once less than the threshold, the largest single hold, is left of it. When the budget is spent, top-up credits are paused until the budget is raised or the cycle resets. The Billing page shows the cycle's spend against the budget and, once it is spent, a notice with a one-click raise; the banner, the insufficient-credits error, the chat agent and the MCP tools say the same and point at Billing. Raising the budget keeps the cycle's count, so the organization carries on from where it stopped. A one-off purchase does not lift the pause, so the page holds the purchase button while the budget is spent and says why.++Turning auto-reload on buys the first reload immediately, before the controls are written, when the organization has never bought a top-up, or when its top-up balance is already at or below the threshold and auto-reload is off or its last reload failed. The server decides this from the customer and the page reads the same decision, so the button says so before the click. A balance above the threshold never buys now, which also means a second click after a charge that landed cannot charge again. Changing the settings while auto-reload already runs leaves the next purchase to Autumn. Turning it off is one click, needs no paid plan, and lifts the budget with it. The cycle's spend is kept while it is off, so turning it back on under a budget that spend has reached is refused, and the page says what budget would do.++Monthly plan credits are still spent first and top-up credits after, so the threshold is in practice a floor on the total balance once the monthly credits are gone, and a spent budget only stops work once they are gone too.++A paid plan that ends turns auto-reload off: the billing webhook that records the plan change disables the controls for a customer who no longer holds the paid entitlement.++When a reload cannot be charged, Autumn reports why through a webhook. The reason is recorded on the Autumn customer so the Billing page, the out-of-credits banner and the insufficient-credits error can say what happened: a declined card points at the billing portal and a retry, anything else at support. Billing managers get an email for card problems. A successful reload, or a successful retry from the page, clears the notice. Autumn's own waits between attempts are not failures.++## Rationale++The budget caps what is spent rather than what is bought. That is the number customers have in mind and the way other prepaid products present it: a monthly spending cap next to the reload, with the card charged only as credits are spent. A cap on purchases makes the customer reason in reloads, and the window Autumn keeps for it is a rolling month from the first reload rather than the billing cycle; the budget resets with the cycle and reads as one number. It bounds the card as well: a cycle's reloads cannot exceed the budget by more than one reload, the one that can land as the budget is reached.++The budget counts credits bought by hand too. A budget on reloaded credits alone would need every deduction to tell the two apart, which Autumn's limit cannot do, and a customer at their budget who wants to spend more says so by raising it.++The first reload is bought by the app rather than left to Autumn because Autumn prices a reload from the organization's own top-up purchase, which an organization that never bought credits does not have, and because Autumn otherwise buys only when a deduction or a refused check crosses the threshold, so the first attempt after enabling would fail before the credits arrived. Buying first also leaves the balance above the threshold, so Autumn's own enable-time purchase does not double up. The same purchase is the retry after a failed reload: a successful charge is what lifts Autumn's pause on a card that kept declining.++The threshold is fixed and below the smallest amount. A user-set threshold is a question most customers cannot answer, and one at or above the amount would make every reload trigger the next. $5 covers the largest single hold a call takes; a larger one is refused and succeeds after smaller usage brings the balance down.++The budget is capped at $1,000 a month because reloads are charged off-session, without Stripe Checkout's confirmation; the budget is what bounds what a stolen card can cost. A purchase-count limit stays on the reload control as a backstop, at twice the reloads a cycle's budget can need plus one, which the budget keeps out of reach.++The failure notice lives in the Autumn customer's metadata because the billing page already reads that customer on every page load and Autumn is the source of truth for the controls it describes; a table of our own would add a second read and a migration for one flag.++## Alternatives considered++- **A cap on purchases.** A monthly limit on how many reloads Autumn may buy, which is what some API platforms offer. It bounds the card directly, but customers would have to think in reloads, the limit would be a multiple of the reload amount, its window is a rolling month, and credits bought by hand would fall outside it. Rejected for the budget on spend.+- **A budget on reloaded credits only.** Would let hand-bought credits spend freely under a spent budget. Autumn's limit counts all spend on the balance, and separating the two would put the budget back in the app on every deduction.+- **Post-paid overage.** Price top-up credits as overage on the plan's invoice with a spend limit, as some developer tools do. One number and no balance to watch, but it extends credit for real provider costs, so a declined card after a month of use is a loss, and it needs a new plan version. Rejected while the plan is $10 a month.+- **A user-set threshold.** Lets an agency keep a larger floor for big batches, but it is a question most customers cannot answer, and one at or above the reload amount would chain reloads.+- **Recurring top-up subscription.** Buys the same amount every month whether or not it is needed. Auto-reload buys only when the balance is low.+- **Reloading from inside the metered call path.** The app could buy credits when a hold is refused and retry. It would duplicate Autumn's purchase counting and put a card charge on the hot path of every DataForSEO call.++## Consequences++- Autumn's own trigger covers the reloads and its usage limit the budget; the app turns them on and off, primes the first purchase, reads the state back and handles the webhooks. No catalog change and no schema change.+- The budget resets with the billing cycle, so the page shows the monthly credits' refill date as the reset. Spend from before the budget was created does not count, and nothing counts while auto-reload is off.+- A hold refused by the budget comes back with the balance still showing credits. The metering code reads a positive balance that refuses as the budget, refuses the batch without retrying it smaller, and says so in the error; the chat gate refuses on it without the stale-balance confirmation it does for an empty balance.+- The first call refused after the monthly credits run out can still fail while Autumn's purchase is in flight; the next call succeeds. The threshold is what keeps that rare.+- A reload can land as the budget is reached, when the balance is at the threshold. Those credits wait for the next cycle or a raised budget; they never expire.+- Research priced after the fact (LLM usage) is admitted on the balance before it runs. If the budget is reached during such a run, the part of that run's top-up deduction past the budget is not deducted; Autumn stops deducting there. Bounded to one run.+- Repeated card declines make Autumn pause reloads until a payment method succeeds. The notice on the Billing page points at the billing portal and offers the retry.diff --git a/src/client/features/billing/AutoReloadNotice.tsx b/src/client/features/billing/AutoReloadNotice.tsxnew file mode 100644index 00000000..fe7dae58--- /dev/null+++ b/src/client/features/billing/AutoReloadNotice.tsx@@ -0,0 +1,152 @@+import { useState } from "react";+import { toast } from "sonner";+import { Alert, AlertDescription } from "@/client/components/ui/alert";+import { Button } from "@/client/components/ui/button";+import type { useCreditBalance } from "@/client/features/billing/useCreditBalance";+import { getStandardErrorMessage } from "@/client/lib/error-messages";+import { SUPPORT_EMAIL } from "@/client/lib/support";+import { createBillingPortalSession } from "@/serverFunctions/billing";+import {+ AUTO_RELOAD_CARD_FAILURE_REASONS,+ AUTO_RELOAD_MAX_MONTHLY_USD,+ BILLING_ROUTE,+} from "@/shared/billing";++type AutoReload = NonNullable<+ ReturnType<typeof useCreditBalance>["autoReload"]+>;+type AutoReloadState = ReturnType<typeof useCreditBalance>["autoReloadState"];++// What the one-click raise adds once the cycle's budget is spent.+const BUDGET_RAISE_STEP_USD = 50;++// Why a reload did not go through, in the customer's terms, for the reasons+// in AUTO_RELOAD_CARD_FAILURE_REASONS. Anything else is ours and gets support.+const CARD_FAILURES: Record<string, string> = {+ charge_failed: "your card was declined",+ suspended_after_failures: "your card kept declining",+ missing_payment_method: "there is no card on file",+ payment_method_not_supported:+ "your payment method can't be charged automatically",+ payment_method_delayed: "your payment method settles too slowly",+};++function formatDate(epochMs: number) {+ return new Date(epochMs).toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ });+}++/** The last failed reload, or the cycle's budget being spent. */+export function AutoReloadNotice({+ saved,+ state,+ canRetry,+ resetDate,+ onRaise,+ pending,+}: {+ saved: AutoReload;+ state: AutoReloadState;+ /** Whether saving below charges the card again, which is the retry. */+ canRetry: boolean;+ resetDate: string | null;+ /** Saves a higher budget at once; absent when saving would charge the card. */+ onRaise: ((monthlyLimitUsd: number) => void) | undefined;+ pending: boolean;+}) {+ // A failure is news while reloads are expected; off, it is history.+ if (saved.enabled && saved.failure) {+ const isCardFailure = AUTO_RELOAD_CARD_FAILURE_REASONS.has(+ saved.failure.reason,+ );+ return (+ <Alert variant="destructive">+ <AlertDescription className="space-y-2">+ <p>+ {isCardFailure ? (+ <>+ Auto-reload failed on {formatDate(saved.failure.at)}:{" "}+ {CARD_FAILURES[saved.failure.reason] ?? "the charge failed"}.{" "}+ {canRetry+ ? "Update your card, then retry below."+ : "Update your card so it works the next time you run low."}+ </>+ ) : (+ <>+ Auto-reload isn’t working right now. Buy credits above and+ email {SUPPORT_EMAIL}.+ </>+ )}+ </p>+ {isCardFailure ? <UpdateCardButton /> : null}+ </AlertDescription>+ </Alert>+ );+ }+ if (state === "budget_spent") {+ const raised = Math.min(+ saved.monthlyLimitUsd + BUDGET_RAISE_STEP_USD,+ AUTO_RELOAD_MAX_MONTHLY_USD,+ );+ // At the maximum there is nothing to raise; the reset is the way out.+ const canRaise = raised > saved.monthlyLimitUsd;+ return (+ <Alert variant="warning">+ <AlertDescription className="space-y-2">+ <p>+ You’ve hit your ${saved.monthlyLimitUsd} monthly budget, so+ top-up credits are paused{resetDate ? ` until ${resetDate}` : ""}.+ {canRaise ? " Raise it to keep going." : ""}+ </p>+ {onRaise && canRaise ? (+ <Button+ variant="outline"+ size="sm"+ pending={pending}+ disabled={pending}+ onClick={() => onRaise(raised)}+ >+ Raise budget to ${raised}+ </Button>+ ) : null}+ </AlertDescription>+ </Alert>+ );+ }+ return null;+}++/** Opens the Stripe billing portal, where the card on file is changed. */+export function UpdateCardButton() {+ const [isOpening, setIsOpening] = useState(false);++ async function openPortal() {+ setIsOpening(true);+ try {+ window.location.assign(+ await createBillingPortalSession({ data: { returnTo: BILLING_ROUTE } }),+ );+ } catch (error) {+ setIsOpening(false);+ toast.error(+ getStandardErrorMessage(+ error,+ "We couldn't open the billing portal. Please try again.",+ ),+ );+ }+ }++ return (+ <Button+ variant="outline"+ size="sm"+ pending={isOpening}+ onClick={() => void openPortal()}+ >+ {isOpening ? "Opening Stripe..." : "Update card"}+ </Button>+ );+}diff --git a/src/client/features/billing/AutoReloadSettings.tsx b/src/client/features/billing/AutoReloadSettings.tsxnew file mode 100644index 00000000..8f879509--- /dev/null+++ b/src/client/features/billing/AutoReloadSettings.tsx@@ -0,0 +1,322 @@+import { useMutation } from "@tanstack/react-query";+import { useState } from "react";+import { toast } from "sonner";+import { Button } from "@/client/components/ui/button";+import {+ Field,+ FieldDescription,+ FieldError,+ FieldLabel,+} from "@/client/components/ui/field";+import {+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+} from "@/client/components/ui/input-group";+import {+ AutoReloadNotice,+ UpdateCardButton,+} from "@/client/features/billing/AutoReloadNotice";+import { billingAccountQueryOptions } from "@/client/features/billing/billingAccountQuery";+import { parseUsdAmount } from "@/client/features/billing/HostedBillingContentUtils";+import { useCreditBalance } from "@/client/features/billing/useCreditBalance";+import {+ getErrorCode,+ getStandardErrorMessage,+} from "@/client/lib/error-messages";+import { queryClient } from "@/client/tanstack-db";+import { setAutoReload } from "@/serverFunctions/billing";+import {+ AUTO_RELOAD_DEFAULTS,+ AUTO_RELOAD_MAX_MONTHLY_USD,+ AUTO_RELOAD_THRESHOLD_USD,+ isAutoReloadBudgetSpent,+ TOP_UP_MAX_USD,+ TOP_UP_MIN_USD,+ type AutoReloadSettings as AutoReloadValues,+} from "@/shared/billing";++type AutoReload = NonNullable<+ ReturnType<typeof useCreditBalance>["autoReload"]+>;++/**+ * The auto-reload section of the Buy credits card. Off: the two amounts and+ * one button to turn it on. On: a status line, the amounts with Save, and+ * Turn off, which acts at once. Turning on can charge the first reload right+ * away (the server buys it before enabling); the button says so. A spent+ * budget shows a notice with a one-click raise. Owner-only at the call site,+ * as the server enforces.+ */+export function AutoReloadSettings() {+ const {+ topUpRemaining,+ refillDate,+ autoReload: saved,+ autoReloadState,+ autoReloadPrimesOnEnable: chargesNow,+ } = useCreditBalance();+ // The saved control while it is on; null when off or never set up.+ const on = saved?.enabled ? saved : null;++ const [fields, setFields] = useState<Record<keyof AutoReloadValues, string>>({+ amountUsd: String(saved?.amountUsd ?? AUTO_RELOAD_DEFAULTS.amountUsd),+ monthlyLimitUsd: String(+ saved?.monthlyLimitUsd ?? AUTO_RELOAD_DEFAULTS.monthlyLimitUsd,+ ),+ });++ const amount = parseUsdAmount(fields.amountUsd, {+ fallback: saved?.amountUsd ?? AUTO_RELOAD_DEFAULTS.amountUsd,+ });+ const budget = parseUsdAmount(fields.monthlyLimitUsd, {+ min: amount.parsed,+ max: AUTO_RELOAD_MAX_MONTHLY_USD,+ fallback: saved?.monthlyLimitUsd ?? AUTO_RELOAD_DEFAULTS.monthlyLimitUsd,+ });+ const values: AutoReloadValues = {+ amountUsd: amount.parsed,+ monthlyLimitUsd: budget.parsed,+ };+ const isValid = amount.isValid && budget.isValid;+ const isDirty =+ !on ||+ on.amountUsd !== values.amountUsd ||+ on.monthlyLimitUsd !== values.monthlyLimitUsd;+ // The server decides whether saving buys the first reload now (also the+ // retry after a failed one), and the page shows that same decision. A+ // retry is worth submitting with nothing changed.+ const budgetUnderSpend = isBudgetUnderSpend(saved, values.monthlyLimitUsd);+ const canSubmit = isValid && !budgetUnderSpend && (isDirty || chargesNow);+ const hint = hintCopy({+ saved,+ on,+ values,+ isValid,+ chargesNow,+ topUpRemaining,+ });++ const mutation = useMutation({+ mutationFn: (+ input: { enabled: false } | ({ enabled: true } & AutoReloadValues),+ ) => setAutoReload({ data: input }),+ // Errors show inline, with the portal when the card is the problem.+ meta: { errorToast: false },+ onSuccess: (_, input) => {+ void queryClient.invalidateQueries({+ queryKey: billingAccountQueryOptions().queryKey,+ });+ toast.success(input.enabled ? "Auto-reload is on" : "Auto-reload is off");+ },+ });+ const saving = mutation.isPending && Boolean(mutation.variables?.enabled);+ const turningOff = mutation.isPending && !saving;++ const save = (next: AutoReloadValues) => {+ setFields({+ amountUsd: String(next.amountUsd),+ monthlyLimitUsd: String(next.monthlyLimitUsd),+ });+ mutation.mutate({ enabled: true, ...next });+ };++ const saveLabel = chargesNow+ ? `${on ? "Retry" : "Turn on"} and buy $${values.amountUsd} now`+ : on+ ? "Save changes"+ : "Turn on auto-reload";++ return (+ <div className="space-y-3">+ <div>+ <p className="text-sm font-medium">Auto-reload</p>+ <p className="text-xs text-muted-foreground">+ When your top-up credits drop to ${AUTO_RELOAD_THRESHOLD_USD} or less,+ we charge your card for more, up to a monthly budget you set.+ </p>+ </div>++ {on ? (+ <p className="text-xs text-muted-foreground">+ <span className="font-medium text-foreground">On</span> · $+ {on.spentUsd.toFixed(2)} of ${on.monthlyLimitUsd} spent this month+ {refillDate ? `, resets ${refillDate}` : ""}+ </p>+ ) : null}++ {saved ? (+ <AutoReloadNotice+ saved={saved}+ state={autoReloadState}+ canRetry={chargesNow}+ resetDate={refillDate}+ // The raise is the plain save; when saving would charge the card,+ // the main button says so and is the way to do it.+ onRaise={+ on && !chargesNow+ ? (monthlyLimitUsd) =>+ save({ amountUsd: on.amountUsd, monthlyLimitUsd })+ : undefined+ }+ pending={mutation.isPending}+ />+ ) : null}++ <div className="grid gap-3 sm:grid-cols-2">+ <AmountField+ id="auto-reload-amount"+ label="Add each time"+ value={fields.amountUsd}+ error={+ amount.isValid+ ? undefined+ : `Enter between $${TOP_UP_MIN_USD}–$${TOP_UP_MAX_USD}.`+ }+ onChange={(value) =>+ setFields((prev) => ({ ...prev, amountUsd: value }))+ }+ />+ <AmountField+ id="auto-reload-budget"+ label="Monthly budget"+ value={fields.monthlyLimitUsd}+ error={+ budget.isValid+ ? undefined+ : `Enter between $${amount.parsed}–$${AUTO_RELOAD_MAX_MONTHLY_USD}.`+ }+ description="The most you spend on top-up credits a month, including ones you buy yourself."+ onChange={(value) =>+ setFields((prev) => ({ ...prev, monthlyLimitUsd: value }))+ }+ />+ </div>++ {hint ? <p className="text-xs text-amber-600">{hint}</p> : null}++ <div className="flex gap-2">+ <Button+ variant="secondary"+ className="flex-1"+ pending={saving}+ disabled={mutation.isPending || !canSubmit}+ onClick={() => save(values)}+ >+ {saveLabel}+ </Button>+ {on ? (+ <Button+ variant="ghost"+ pending={turningOff}+ disabled={mutation.isPending}+ onClick={() => mutation.mutate({ enabled: false })}+ >+ Turn off+ </Button>+ ) : null}+ </div>++ {mutation.isError ? (+ <div className="space-y-2">+ <p role="alert" className="text-sm text-destructive">+ {getStandardErrorMessage(+ mutation.error,+ "We couldn't save auto-reload. Please try again.",+ )}+ </p>+ {getErrorCode(mutation.error) === "PAYMENT_METHOD_REQUIRED" ? (+ <UpdateCardButton />+ ) : null}+ </div>+ ) : null}+ </div>+ );+}++// Autumn keeps the cycle's top-up spend while auto-reload is off, so a+// budget the spend already reaches pauses the credits at once, and a turn-on+// that buys now would buy credits that cannot be used. The server refuses+// it; the page says so first.+function isBudgetUnderSpend(saved: AutoReload | null, monthlyLimitUsd: number) {+ return (+ saved !== null &&+ saved.spentUsd > 0 &&+ isAutoReloadBudgetSpent(saved.spentUsd, monthlyLimitUsd)+ );+}++/** The amber line under the fields: a budget the spend has reached (unless+ * the notice above already says it), else what saving charges now. */+function hintCopy({+ saved,+ on,+ values,+ isValid,+ chargesNow,+ topUpRemaining,+}: {+ saved: AutoReload | null;+ on: AutoReload | null;+ values: AutoReloadValues;+ isValid: boolean;+ chargesNow: boolean;+ topUpRemaining: number;+}) {+ if (+ saved &&+ isBudgetUnderSpend(saved, values.monthlyLimitUsd) &&+ (!on || values.monthlyLimitUsd !== on.monthlyLimitUsd)+ ) {+ return `You've already spent $${saved.spentUsd.toFixed(2)} on top-up credits this month. Set a budget of at least $${Math.ceil(saved.spentUsd + AUTO_RELOAD_THRESHOLD_USD)} to keep going.`;+ }+ if (!chargesNow || !isValid) return null;+ if (on) {+ return `Retrying charges your card $${values.amountUsd} now.`;+ }+ if (topUpRemaining > 0) {+ return `Your top-up credits are already at $${topUpRemaining.toFixed(2)}, so turning this on buys $${values.amountUsd} now.`;+ }+ return `You have no top-up credits yet, so turning this on buys $${values.amountUsd} now. They're used after your monthly credits run out.`;+}++function AmountField({+ id,+ label,+ value,+ error,+ description,+ onChange,+}: {+ id: string;+ label: string;+ value: string;+ error: string | undefined;+ description?: string;+ onChange: (value: string) => void;+}) {+ return (+ <Field data-invalid={error !== undefined}>+ <FieldLabel htmlFor={id} className="text-xs">+ {label}+ </FieldLabel>+ <InputGroup>+ <InputGroupAddon>$</InputGroupAddon>+ <InputGroupInput+ id={id}+ type="number"+ step={1}+ inputMode="numeric"+ aria-invalid={error !== undefined}+ value={value}+ onChange={(event) => onChange(event.target.value)}+ />+ </InputGroup>+ {error ? (+ <FieldError>{error}</FieldError>+ ) : description ? (+ <FieldDescription className="text-xs">{description}</FieldDescription>+ ) : null}+ </Field>+ );+}diff --git a/src/client/features/billing/FreePlanBanner.tsx b/src/client/features/billing/FreePlanBanner.tsxindex beb05ae6..148f6024 100644--- a/src/client/features/billing/FreePlanBanner.tsx+++ b/src/client/features/billing/FreePlanBanner.tsx@@ -8,8 +8,16 @@ import { useCanManageBilling } from "@/client/features/team/organizationQueries"import { BILLING_ROUTE, SUBSCRIBE_ROUTE } from "@/shared/billing";export function FreePlanBanner() {- const { accountQuery, isFreePlan, isOutOfCredits, isLowCredits, refillDate } =- useCreditBalance();+ const {+ accountQuery,+ isFreePlan,+ isOutOfCredits,+ isLowCredits,+ refillDate,+ autoReload,+ autoReloadState,+ isPausedByBudget,+ } = useCreditBalance();const canManageBilling = useCanManageBilling();const showsOutOfCredits = Boolean(accountQuery.data) && isOutOfCredits;@@ -22,15 +30,57 @@ export function FreePlanBanner() {return null;}+ // Credits may be in the balance, but the budget holds them back; buying+ // more would not help, only raising it does.+ if (isPausedByBudget && autoReload) {+ const until = refillDate ? ` until ${refillDate}` : "";+ return (+ <AppBanner variant="warning">+ {canManageBilling ? (+ <>+ You’ve hit your ${autoReload.monthlyLimitUsd} monthly+ auto-reload budget, so credits are paused{until}.{" "}+ <Link+ to={BILLING_ROUTE}+ className="font-medium text-primary underline-offset-4 hover:underline"+ >+ Raise your budget+ </Link>{" "}+ to keep going.+ </>+ ) : (+ <>+ Your organization hit its monthly auto-reload budget, so credits are+ paused{until}. Ask the owner to raise it.+ </>+ )}+ </AppBanner>+ );+ }++ // Out of credits with auto-reload on and working means Autumn is charging+ // the card right now; a "buy more" notice would have them pay twice.+ if (!isFreePlan && isOutOfCredits && autoReloadState === "on" && autoReload) {+ return (+ <AppBanner variant="info">+ You’re out of credits. Auto-reload is adding $+ {autoReload.amountUsd} now.+ </AppBanner>+ );+ }+// Only the owner can change the plan or buy credits, so a link would lead// everyone else to a page where they can't act.if (!canManageBilling && (isOutOfCredits || isLowCredits)) {return (<AppBanner variant={isOutOfCredits ? "destructive" : "warning"}>{isOutOfCredits- ? "Your organization has used its credits."+ ? autoReloadState === "card_failed"+ ? "Your organization is out of credits and its card was declined."+ : "Your organization has used its credits.": "Your organization is running low on credits."}{" "}- Ask your organization owner to add more.+ Ask your organization owner to{" "}+ {autoReloadState === "card_failed" ? "update it" : "add more"}.</AppBanner>);}@@ -60,6 +110,23 @@ export function FreePlanBanner() {You’ve used your free credits. {creditsActionLink} to get ${BASE_PLAN_OFFER.monthlyCreditsUsd} of credits every month.</>+ ) : autoReloadState === "card_failed" ? (+ <>+ You’re out of credits and auto-reload couldn’t charge+ your card.{" "}+ <Link+ to={BILLING_ROUTE}+ className="font-medium text-primary underline-offset-4 hover:underline"+ >+ Update your card+ </Link>{" "}+ to keep going.+ </>+ ) : autoReloadState === "failed" ? (+ <>+ You’re out of credits and auto-reload couldn’t buy more.{" "}+ {creditsActionLink} to keep going.+ </>) : (<>You’ve used this month’s credits. {creditsActionLink} todiff --git a/src/client/features/billing/HostedBillingContentUtils.ts b/src/client/features/billing/HostedBillingContentUtils.tsindex 4fcaf2e5..acbbea84 100644--- a/src/client/features/billing/HostedBillingContentUtils.ts+++ b/src/client/features/billing/HostedBillingContentUtils.ts@@ -1,18 +1,31 @@-export function parseTopUpAmount(value: string) {+import { TOP_UP_MAX_USD, TOP_UP_MIN_USD } from "@/shared/billing";++/** A whole-dollar amount typed into a billing field, within [min, max].+ * `parsed` falls back to `fallback` while the field is invalid so a pending+ * checkout link always has a usable amount. */+export function parseUsdAmount(+ value: string,+ {+ min = TOP_UP_MIN_USD,+ max = TOP_UP_MAX_USD,+ fallback = 20,+ }: { min?: number; max?: number; fallback?: number } = {},+) {const trimmed = value.trim();if (!/^\d+$/.test(trimmed)) {- return {- isValid: false,- parsed: 20,- };+ return { isValid: false, parsed: fallback };}const parsed = Number(trimmed);- const isValid = Number.isInteger(parsed) && parsed >= 10 && parsed <= 99;+ const isValid = Number.isInteger(parsed) && parsed >= min && parsed <= max;return {isValid,- parsed: isValid ? parsed : 20,+ parsed: isValid ? parsed : fallback,};}++export function parseTopUpAmount(value: string) {+ return parseUsdAmount(value);+}diff --git a/src/client/features/billing/InsufficientCreditsError.tsx b/src/client/features/billing/InsufficientCreditsError.tsxindex 667676b8..73dec5f0 100644--- a/src/client/features/billing/InsufficientCreditsError.tsx+++ b/src/client/features/billing/InsufficientCreditsError.tsx@@ -3,9 +3,11 @@ import { Link } from "@tanstack/react-router";import { ErrorState } from "@/client/components/ErrorState";import { Button } from "@/client/components/ui/button";import { BASE_PLAN_OFFER } from "@/client/features/billing/plan-offers";+import { billingAccountQueryOptions } from "@/client/features/billing/billingAccountQuery";import { useCreditBalance } from "@/client/features/billing/useCreditBalance";import { getStandardErrorMessage } from "@/client/lib/error-messages";import { captureClientEvent } from "@/client/lib/posthog";+import { queryClient } from "@/client/tanstack-db";import { BILLING_ROUTE, SUBSCRIBE_ROUTE } from "@/shared/billing";/**@@ -41,12 +43,29 @@ export function GetCreditsButton() {}function useCreditsOffer(surface: "card" | "button") {- const { accountQuery, isFreePlan, refillDate } = useCreditBalance();+ const {+ accountQuery,+ isFreePlan,+ isOutOfCredits,+ refillDate,+ autoReload,+ autoReloadState,+ } = useCreditBalance();useEffect(() => {captureClientEvent("billing:out_of_credits_shown", { surface });}, [surface]);+ // The balance the page shows is up to a minute old; a fresh refusal means+ // it moved, and with auto-reload on it is about to move again. The button+ // alone sits on stored skip reasons, one per row, which say nothing new.+ useEffect(() => {+ if (surface !== "card") return;+ void queryClient.invalidateQueries({+ queryKey: billingAccountQueryOptions().queryKey,+ });+ }, [surface]);+let message: string;let action: ReactElement;if (!accountQuery.data) {@@ -62,10 +81,36 @@ function useCreditsOffer(surface: "card" | "button") {label="Upgrade plan"/>);+ } else if (autoReloadState === "on" && isOutOfCredits && autoReload) {+ // The refused call is what told Autumn to reload; the credits are coming.+ // A balance that is not out means this is an old refusal (a scheduled+ // run's stored skip reason), so it gets the general copy below.+ message = `You're out of credits. Auto-reload is adding $${autoReload.amountUsd} now, so try again in a moment.`;+ action = (+ <CreditsButton link={<Link to={BILLING_ROUTE} />} label="Go to Billing" />+ );+ } else if (autoReloadState === "card_failed") {+ message =+ "You're out of credits and auto-reload couldn't charge your card. Update your card to keep going.";+ action = (+ <CreditsButton link={<Link to={BILLING_ROUTE} />} label="Update card" />+ );+ } else if (autoReloadState === "failed") {+ message =+ "You're out of credits and auto-reload couldn't buy more. Buy credits to keep going.";+ action = (+ <CreditsButton link={<Link to={BILLING_ROUTE} />} label="Buy credits" />+ );+ } else if (autoReloadState === "budget_spent" && autoReload) {+ // Buying credits would not help: the budget counts those too.+ message = `You've hit your $${autoReload.monthlyLimitUsd} monthly auto-reload budget, so credits are paused${refillDate ? ` until ${refillDate}` : ""}. Raise it to keep going.`;+ action = (+ <CreditsButton link={<Link to={BILLING_ROUTE} />} label="Raise budget" />+ );} else {message = refillDate- ? `You don't have enough credits for this. Buy more credits to keep going, or wait for your monthly credits to refill on ${refillDate}.`- : "You don't have enough credits for this. Buy more credits to keep going.";+ ? `You don't have enough credits for this. Buy more, or wait for your monthly refill on ${refillDate}. Auto-reload can buy them for you next time.`+ : "You don't have enough credits for this. Buy more to keep going. Auto-reload can buy them for you next time.";action = (<CreditsButton link={<Link to={BILLING_ROUTE} />} label="Buy credits" />);diff --git a/src/client/features/billing/useCreditBalance.ts b/src/client/features/billing/useCreditBalance.tsindex 7a607600..7988bcc0 100644--- a/src/client/features/billing/useCreditBalance.ts+++ b/src/client/features/billing/useCreditBalance.ts@@ -1,6 +1,10 @@import { useQuery } from "@tanstack/react-query";import { billingAccountQueryOptions } from "@/client/features/billing/billingAccountQuery";-import { LOW_CREDITS_THRESHOLD_USD } from "@/shared/billing";+import {+ AUTO_RELOAD_CARD_FAILURE_REASONS,+ isAutoReloadBudgetSpent,+ LOW_CREDITS_THRESHOLD_USD,+} from "@/shared/billing";/** The signed-in organization's plan and remaining credits in USD. */export function useCreditBalance() {@@ -12,6 +16,30 @@ export function useCreditBalance() {const totalRemaining = monthlyRemaining + topUpRemaining;const isOutOfCredits = totalRemaining <= 0;+ // Whether auto-reload will bring credits: "on" means the next low balance+ // buys more, the others say why it will not. "card_failed" is the+ // customer's to fix; "failed" is ours; "budget_spent" pauses top-up+ // credits until the budget is raised or the cycle resets.+ const autoReload = account?.autoReload ?? null;+ const autoReloadState:+ | "off"+ | "on"+ | "card_failed"+ | "failed"+ | "budget_spent" = !autoReload?.enabled+ ? "off"+ : autoReload.failure+ ? AUTO_RELOAD_CARD_FAILURE_REASONS.has(autoReload.failure.reason)+ ? "card_failed"+ : "failed"+ : isAutoReloadBudgetSpent(autoReload.spentUsd, autoReload.monthlyLimitUsd)+ ? "budget_spent"+ : "on";+ // Top-up credits pay once the monthly credits are gone, so a spent budget+ // only stops work then.+ const isPausedByBudget =+ autoReloadState === "budget_spent" && monthlyRemaining <= 0;+return {accountQuery,isFreePlan: account?.planStatus !== "paid",@@ -19,7 +47,15 @@ export function useCreditBalance() {topUpRemaining,totalRemaining,isOutOfCredits,- isLowCredits: !isOutOfCredits && totalRemaining < LOW_CREDITS_THRESHOLD_USD,+ // Running low is expected while auto-reload is about to buy more.+ isLowCredits:+ !isOutOfCredits &&+ totalRemaining < LOW_CREDITS_THRESHOLD_USD &&+ autoReloadState !== "on",+ autoReload,+ autoReloadState,+ isPausedByBudget,+ autoReloadPrimesOnEnable: account?.autoReloadPrimesOnEnable ?? false,// When monthly credits refill, e.g. "Oct 12".refillDate: account?.monthlyRefillsAt? new Date(account.monthlyRefillsAt).toLocaleDateString(undefined, {diff --git a/src/client/lib/error-messages.ts b/src/client/lib/error-messages.tsindex 15408f48..6588a0b1 100644--- a/src/client/lib/error-messages.ts+++ b/src/client/lib/error-messages.ts@@ -18,6 +18,10 @@ const STANDARD_MESSAGES: Record<ErrorCode, string> = {"An active hosted subscription is required before you can use OpenSEO.",INSUFFICIENT_CREDITS:"You don't have enough credits for this. Upgrade your plan or buy more credits to keep going.",+ PAYMENT_METHOD_REQUIRED:+ "We couldn't charge a card on file. Add or update your card in the billing portal, then try again.",+ PAYMENT_ACTION_REQUIRED:+ "Your bank needs more time or a confirmation for this charge. Check your balance in a minute; if nothing arrived, buy your first top-up with the Buy credits button, then turn on auto-reload.",AUDIT_RENDERING_UNAVAILABLE:"JavaScript rendering is not configured on this deployment. Ask your administrator to enable a renderer.",FORBIDDEN: "You do not have access to this resource.",diff --git a/src/routes/_app/billing.tsx b/src/routes/_app/billing.tsxindex d4a86709..3e705d93 100644--- a/src/routes/_app/billing.tsx+++ b/src/routes/_app/billing.tsx@@ -28,6 +28,7 @@ import {openUpgradeCheckout,prefetchUpgradeCheckout,} from "@/client/features/billing/checkout";+import { AutoReloadSettings } from "@/client/features/billing/AutoReloadSettings";import { BillingTabs } from "@/client/features/billing/BillingTabs";import { parseTopUpAmount } from "@/client/features/billing/HostedBillingContentUtils";import { billingUsageQueryOptions } from "@/client/features/billing/useBillingUsage";@@ -41,7 +42,12 @@ import {createBillingPortalSession,createTopUpCheckout,} from "@/serverFunctions/billing";-import { BILLING_ROUTE, BILLING_TABS } from "@/shared/billing";+import {+ BILLING_ROUTE,+ BILLING_TABS,+ TOP_UP_MAX_USD,+ TOP_UP_MIN_USD,+} from "@/shared/billing";export const Route = createFileRoute("/_app/billing")({validateSearch: z.object({@@ -91,8 +97,12 @@ function BillingPage() {isOutOfCredits,isLowCredits,refillDate,+ autoReloadState,} = useCreditBalance();const account = accountQuery.data;+ // The budget counts bought credits too, so a purchase now would sit+ // unspent until it is raised; the notice below the button says so.+ const budgetSpent = autoReloadState === "budget_spent";// Subscription changes are owner-only; other members see balances but are// pointed at the owner instead of checkout (the server enforces this too).@@ -299,7 +309,16 @@ function BillingPage() {</CardContent></Card>- {/* Buy credits card — paid plan only, owner-only */}+ {/* Buy credits card — paid plan only, owner-only. The sync turns+ auto-reload off when a plan ends; until that lands, an owner+ who left the plan still sees it, so they can turn it off. */}+ {isFreePlan && canManageBilling && account.autoReload?.enabled ? (+ <Card>+ <CardContent>+ <AutoReloadSettings />+ </CardContent>+ </Card>+ ) : null}{!isFreePlan && canManageBilling ? (<Card><CardHeader>@@ -315,8 +334,8 @@ function BillingPage() {<InputGroupAddon>$</InputGroupAddon><InputGroupInputtype="number"- min={10}- max={99}+ min={TOP_UP_MIN_USD}+ max={TOP_UP_MAX_USD}step={1}inputMode="numeric"aria-label="Top-up amount in USD"@@ -326,7 +345,9 @@ function BillingPage() {/></InputGroup>{showTopUpError ? (- <FieldError>Enter between $10–$99.</FieldError>+ <FieldError>+ Enter between ${TOP_UP_MIN_USD}–${TOP_UP_MAX_USD}.+ </FieldError>) : null}</Field>@@ -334,7 +355,9 @@ function BillingPage() {variant="secondary"className="w-full"pending={pendingAction === "topUp"}- disabled={!isValidTopUp || pendingAction !== null}+ disabled={+ !isValidTopUp || pendingAction !== null || budgetSpent+ }onClick={() =>void runAction("topUp",@@ -347,7 +370,17 @@ function BillingPage() {? "Redirecting to Stripe...": "Buy credits"}</Button>+ {budgetSpent ? (+ <p className="text-xs text-muted-foreground">+ You’ve hit your monthly auto-reload budget. Raise it+ below to buy more.+ </p>+ ) : null}{actionError("topUp")}++ <div className="border-t border-border pt-4">+ <AutoReloadSettings />+ </div></CardContent></Card>) : null}diff --git a/src/server/billing/auto-reload-budget.test.ts b/src/server/billing/auto-reload-budget.test.tsnew file mode 100644index 00000000..63098f2e--- /dev/null+++ b/src/server/billing/auto-reload-budget.test.ts@@ -0,0 +1,93 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+} from "@/shared/billing";++const { checkMock } = vi.hoisted(() => ({+ checkMock: vi.fn<(arg: { featureId: string }) => Promise<unknown>>(),+}));++vi.mock("cloudflare:workers", () => ({+ env: { KV: { get: vi.fn(), put: vi.fn() } },+}));+vi.mock("@/server/billing/autumn", () => ({+ autumn: {+ check: checkMock,+ balances: { finalize: vi.fn() },+ customers: { getOrCreate: vi.fn() },+ },+ AUTUMN_TRACK_RETRY_OPTIONS: {},+}));+vi.mock("@/server/lib/posthog", () => ({ captureServerEvent: vi.fn() }));++import { captureServerEvent } from "@/server/lib/posthog";+import { getUsageCreditsRemaining, reserveUsageCredits } from "./subscription";++const customer = {+ organizationId: "org_1",+ userId: "user_1",+ userEmail: "[email protected]",+};++// The monthly auto-reload budget is Autumn's usage limit on the top-up+// balance: a check it refuses comes back with the balance still showing+// credits. What the metering seams make of that.+describe("auto-reload budget", () => {+ beforeEach(() => {+ // Monthly credits gone; $12 of top-up credits the budget holds back.+ checkMock.mockImplementation(async ({ featureId }) =>+ featureId === AUTUMN_SEO_DATA_BALANCE_FEATURE_ID+ ? { allowed: false, balance: { remaining: 0 } }+ : { allowed: false, balance: { remaining: 12000 } },+ );+ });++ it("reads a top-up balance that refuses with credits left as nothing to spend", async () => {+ await expect(getUsageCreditsRemaining("org_1")).resolves.toEqual({+ monthlyRemaining: 0,+ topupRemaining: 0,+ topupBudgetReached: true,+ });+ });++ it("refuses a hold as the budget, without retrying it smaller", async () => {+ const refused = reserveUsageCredits({+ customer,+ customerId: "org_1",+ callCredits: [100],+ });++ await expect(refused).rejects.toMatchObject({+ code: "INSUFFICIENT_CREDITS",+ });+ await expect(refused).rejects.toThrow(/budget/);+ const topupChecks = checkMock.mock.calls.filter(+ ([arg]) => arg.featureId === AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ );+ expect(topupChecks).toHaveLength(1);+ expect(vi.mocked(captureServerEvent).mock.calls[0][0]).toMatchObject({+ event: "usage:credits_gate_refused",+ properties: { reason: "monthly_budget_reached", topup_remaining: 12000 },+ });+ });++ it("reads a refused smaller hold as the budget too", async () => {+ // $16 asked of a $12 balance: the first refusal reads as a short+ // balance, the retry fits the balance, and the budget refuses that one.+ const refused = reserveUsageCredits({+ customer,+ customerId: "org_1",+ callCredits: [8000, 8000],+ });++ await expect(refused).rejects.toThrow(/budget/);+ const topupChecks = checkMock.mock.calls.filter(+ ([arg]) => arg.featureId === AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ );+ expect(topupChecks).toHaveLength(2);+ expect(vi.mocked(captureServerEvent).mock.calls[0][0]).toMatchObject({+ properties: { reason: "monthly_budget_reached" },+ });+ });+});diff --git a/src/server/billing/auto-reload-status.ts b/src/server/billing/auto-reload-status.tsnew file mode 100644index 00000000..d2f00038--- /dev/null+++ b/src/server/billing/auto-reload-status.ts@@ -0,0 +1,97 @@+import type { autumn } from "@/server/billing/autumn";+import { z } from "zod";+import {+ AUTO_RELOAD_DEFAULTS,+ AUTO_RELOAD_THRESHOLD_USD,+ AUTUMN_SEO_DATA_CREDITS_PER_USD,+ AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ autumnSeoDataCreditsToUsd,+ type AutoReloadSettings,+} from "@/shared/billing";++// Leaf module (no runtime imports beyond zod) so the billing account read,+// which every page makes, does not load the email and database modules the+// auto-reload service needs.++type AutumnCustomer = Awaited<ReturnType<typeof autumn.customers.get>>;++export type AutoReloadStatus = AutoReloadSettings & {+ enabled: boolean;+ /** The top-up balance at or below which Autumn reloads. Fixed by the app,+ * read back from Autumn. */+ thresholdUsd: number;+ /** Top-up credits spent so far this billing cycle, in USD, as Autumn+ * counts them against the budget. Open holds count; the cycle resets+ * with the monthly credits. */+ spentUsd: number;+ /** The last reload Autumn could not charge, until one succeeds or the+ * settings are saved again. */+ failure: { reason: string; at: number } | null;+};++// The failure webhook writes this to the Autumn customer's metadata and the+// success webhook (or the next save) clears it, so the billing page can say+// why credits stopped arriving without a table of our own. Metadata updates+// merge by key, and a null value deletes the key.+export const AUTO_RELOAD_FAILURE_METADATA_KEY = "autoReloadFailure";+const autoReloadFailureSchema = z.object({+ reason: z.string(),+ at: z.number(),+});++/** The customer's auto-reload control as the billing page shows it. Null+ * when it has never been set up. */+export function readAutoReload(+ customer: AutumnCustomer,+): AutoReloadStatus | null {+ const control = customer.billingControls?.autoTopups?.find(+ (entry) => entry.featureId === AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ );+ if (!control) return null;++ // The budget is Autumn's usage limit on the same balance, written together+ // with the control, so it is only missing on a customer set up before it.+ const budget = customer.billingControls?.usageLimits?.find(+ (entry) => entry.featureId === AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ );+ const failure = autoReloadFailureSchema.safeParse(+ customer.metadata?.[AUTO_RELOAD_FAILURE_METADATA_KEY],+ );++ return {+ enabled: control.enabled,+ thresholdUsd: autumnSeoDataCreditsToUsd(control.threshold),+ amountUsd: autumnSeoDataCreditsToUsd(control.quantity),+ monthlyLimitUsd: budget+ ? autumnSeoDataCreditsToUsd(budget.limit)+ : AUTO_RELOAD_DEFAULTS.monthlyLimitUsd,+ spentUsd: autumnSeoDataCreditsToUsd(budget?.usage ?? 0),+ failure: failure.success ? failure.data : null,+ };+}++/**+ * Whether turning auto-reload on buys the first reload right away, which the+ * page must say before the click. Autumn prices a reload from the+ * organization's own top-up purchase, so an organization without one gets+ * it now. Otherwise only when the top-up balance is already at or below the+ * threshold and Autumn would not buy on its own: it is off, or its last+ * reload failed (a successful charge is what lifts Autumn's pause on a+ * declining card). A balance above the threshold never buys now, so a retry+ * after a charge that landed cannot charge again.+ */+export function primesAutoReloadOnEnable(customer: AutumnCustomer) {+ const hasTopUpPurchase = customer.purchases.some(+ (purchase) => purchase.planId === AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,+ );+ if (!hasTopUpPurchase) return true;+ const current = readAutoReload(customer);+ const topUpRemaining =+ customer.balances[AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]?.remaining ?? 0;+ return (+ topUpRemaining <=+ AUTO_RELOAD_THRESHOLD_USD * AUTUMN_SEO_DATA_CREDITS_PER_USD &&+ (!current?.enabled || current.failure !== null)+ );+}diff --git a/src/server/billing/auto-reload.test.ts b/src/server/billing/auto-reload.test.tsnew file mode 100644index 00000000..452eff66--- /dev/null+++ b/src/server/billing/auto-reload.test.ts@@ -0,0 +1,379 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ AUTUMN_PAID_PLAN_FEATURE_ID,+ AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+} from "@/shared/billing";++const { attachMock, getMock, updateMock, sendLoopsEventMock, contactsMock } =+ vi.hoisted(() => ({+ attachMock: vi.fn(),+ getMock: vi.fn(),+ updateMock: vi.fn(),+ sendLoopsEventMock: vi.fn(),+ contactsMock: vi.fn(),+ }));++vi.mock("@/server/billing/autumn", () => ({+ autumn: {+ billing: { attach: attachMock },+ customers: { get: getMock, update: updateMock },+ },+ AUTUMN_TRACK_RETRY_OPTIONS: { retryCodes: ["429"] },+}));+vi.mock("@/server/lib/posthog", () => ({ captureServerEvent: vi.fn() }));+vi.mock("@/server/billing/loops-sync", () => ({+ getOrganizationContacts: contactsMock,+}));+vi.mock("@/server/email/loops-client", () => ({+ sendLoopsEvent: sendLoopsEventMock,+}));+vi.mock("@/server/lib/runtime-env", () => ({+ getOptionalEnvValue: vi.fn().mockResolvedValue("loops-key"),+}));++import {+ disableAutoReloadIfUnpaid,+ handleAutoReloadWebhook,+ setOrganizationAutoReload,+} from "./auto-reload";++const owner = { organizationId: "org_1", role: "owner", userId: "user_1" };+const settings = { amountUsd: 20, monthlyLimitUsd: 100 };++/** Saved before: $30 reloads within a $120 budget. */+const savedControls = (enabled: boolean) => ({+ autoTopups: [+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ enabled,+ threshold: 5000,+ quantity: 30000,+ purchaseLimit: { interval: "month", intervalCount: 1, limit: 9 },+ },+ ],+ usageLimits: [+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ enabled,+ limit: 120000,+ interval: "month",+ anchor: "billing_cycle",+ usage: 0,+ },+ ],+});++/** A paying customer with a card who bought a top-up before. */+const customer = (overrides: Record<string, unknown> = {}) => ({+ id: "org_1",+ flags: { [AUTUMN_PAID_PLAN_FEATURE_ID]: { planId: "base-plan" } },+ paymentMethod: { type: "card" },+ purchases: [{ planId: AUTUMN_SEO_DATA_TOP_UP_PLAN_ID }],+ balances: {+ [AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]: { remaining: 9000 },+ },+ billingControls: {},+ metadata: {},+ ...overrides,+});++/** What `settings` writes: the reload control with its backstop, and the+ * budget as a usage limit on the same balance. */+const expectedControls = (enabled: boolean) => ({+ autoTopups: [+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ enabled,+ threshold: 5000,+ quantity: 20000,+ purchaseLimit: { interval: "month", limit: 11 },+ },+ ],+ usageLimits: [+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ enabled,+ limit: 100000,+ interval: "month",+ anchor: "billing_cycle",+ },+ ],+});++beforeEach(() => {+ getMock.mockResolvedValue(customer());+ attachMock.mockResolvedValue({ paymentUrl: null });+ updateMock.mockResolvedValue({});+ contactsMock.mockResolvedValue([+ { userId: "user_1", email: "[email protected]", role: "owner" },+ { userId: "user_2", email: "[email protected]", role: "member" },+ ]);+ sendLoopsEventMock.mockResolvedValue({ duplicate: false });+});++describe("setOrganizationAutoReload", () => {+ it("turns auto-reload on with the fixed threshold and the budget as a usage limit", async () => {+ await setOrganizationAutoReload(owner, { enabled: true, ...settings });++ // Credits above the threshold and a purchase to price from: Autumn can+ // take it from here without a charge now.+ expect(attachMock).not.toHaveBeenCalled();+ expect(updateMock).toHaveBeenCalledWith({+ customerId: "org_1",+ billingControls: expectedControls(true),+ metadata: { autoReloadFailure: null },+ });+ });++ it.each([+ [+ "the balance is at the threshold",+ {+ balances: {+ [AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]: { remaining: 5000 },+ },+ },+ ],+ ["the organization never bought a top-up", { purchases: [] }],+ [+ "the last reload failed and the balance is still low",+ {+ balances: {+ [AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]: { remaining: 0 },+ },+ billingControls: savedControls(true),+ metadata: { autoReloadFailure: { reason: "charge_failed", at: 1 } },+ },+ ],+ ])(+ "buys the first reload with the saved card before turning on when %s",+ async (_, overrides) => {+ getMock.mockResolvedValue(customer(overrides));++ await setOrganizationAutoReload(owner, { enabled: true, ...settings });++ expect(attachMock).toHaveBeenCalledWith(+ {+ customerId: "org_1",+ planId: AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,+ featureQuantities: [+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ quantity: 20000,+ },+ ],+ redirectMode: "never",+ },+ // A replayed charge would be a second charge.+ { retryCodes: ["429"] },+ );+ // The purchase lands before the control, so Autumn's own enable-time+ // purchase sees a balance above the threshold and does not double up.+ expect(attachMock.mock.invocationCallOrder[0]).toBeLessThan(+ updateMock.mock.invocationCallOrder[0],+ );+ },+ );++ it("does not buy again when a retry's purchase already landed", async () => {+ // The failed-reload notice is still up (the control write failed after+ // the charge), but the credits are there.+ getMock.mockResolvedValue(+ customer({+ billingControls: savedControls(true),+ metadata: { autoReloadFailure: { reason: "charge_failed", at: 1 } },+ }),+ );++ await setOrganizationAutoReload(owner, { enabled: true, ...settings });++ expect(attachMock).not.toHaveBeenCalled();+ expect(updateMock).toHaveBeenCalledWith(+ expect.objectContaining({ metadata: { autoReloadFailure: null } }),+ );+ });++ it("sends a charge that got no answer to the balance, not to a retry", async () => {+ vi.spyOn(console, "error").mockImplementation(() => {});+ getMock.mockResolvedValue(customer({ purchases: [] }));+ const timeout = new Error("timed out");+ timeout.name = "RequestTimeoutError";+ attachMock.mockRejectedValueOnce(timeout);++ await expect(+ setOrganizationAutoReload(owner, { enabled: true, ...settings }),+ ).rejects.toMatchObject({ code: "PAYMENT_ACTION_REQUIRED" });+ expect(updateMock).not.toHaveBeenCalled();+ });++ it("tells the bank's confirmation apart from a card that cannot be charged", async () => {+ getMock.mockResolvedValue(customer({ purchases: [] }));+ attachMock.mockResolvedValueOnce({+ paymentUrl: null,+ requiredAction: { code: "3ds_required", reason: "SCA" },+ });+ await expect(+ setOrganizationAutoReload(owner, { enabled: true, ...settings }),+ ).rejects.toMatchObject({ code: "PAYMENT_ACTION_REQUIRED" });++ attachMock.mockResolvedValueOnce({+ paymentUrl: null,+ requiredAction: { code: "payment_failed", reason: "declined" },+ });+ await expect(+ setOrganizationAutoReload(owner, { enabled: true, ...settings }),+ ).rejects.toMatchObject({ code: "PAYMENT_METHOD_REQUIRED" });+ expect(updateMock).not.toHaveBeenCalled();+ });++ it("needs a paid plan and a card to turn on, but not to turn off", async () => {+ getMock.mockResolvedValueOnce(customer({ flags: {} }));+ await expect(+ setOrganizationAutoReload(owner, { enabled: true, ...settings }),+ ).rejects.toMatchObject({ code: "PAYMENT_REQUIRED" });++ getMock.mockResolvedValueOnce(customer({ paymentMethod: null }));+ await expect(+ setOrganizationAutoReload(owner, { enabled: true, ...settings }),+ ).rejects.toMatchObject({ code: "PAYMENT_METHOD_REQUIRED" });+ expect(attachMock).not.toHaveBeenCalled();+ expect(updateMock).not.toHaveBeenCalled();++ getMock.mockResolvedValueOnce(+ customer({ flags: {}, billingControls: savedControls(true) }),+ );+ await setOrganizationAutoReload(owner, { enabled: false });+ // The saved amounts stay for turning it back on; the failure notice too.+ // The budget goes off with it: nothing is budgeted while nothing is+ // bought automatically.+ const off = savedControls(false);+ expect(updateMock).toHaveBeenCalledWith({+ customerId: "org_1",+ billingControls: {+ autoTopups: [+ {+ ...off.autoTopups[0],+ purchaseLimit: { interval: "month", limit: 9 },+ },+ ],+ usageLimits: [{ ...off.usageLimits[0], usage: undefined }],+ },+ });+ });++ it("refuses a budget the cycle's spend has as good as reached, charging nothing", async () => {+ // $96.40 spent under the saved $120 budget, balance at the threshold:+ // turning on with a $100 budget would buy a reload that cannot be used.+ const controls = savedControls(false);+ controls.usageLimits[0].usage = 96400;+ getMock.mockResolvedValue(+ customer({+ billingControls: controls,+ balances: {+ [AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]: { remaining: 2000 },+ },+ }),+ );++ await expect(+ setOrganizationAutoReload(owner, { enabled: true, ...settings }),+ ).rejects.toMatchObject({ code: "VALIDATION_ERROR" });+ expect(attachMock).not.toHaveBeenCalled();+ expect(updateMock).not.toHaveBeenCalled();+ });++ it("only lets the owner change auto-reload", async () => {+ await expect(+ setOrganizationAutoReload(+ { ...owner, role: "member" },+ { enabled: true, ...settings },+ ),+ ).rejects.toMatchObject({ code: "FORBIDDEN" });+ expect(getMock).not.toHaveBeenCalled();+ });+});++describe("disableAutoReloadIfUnpaid", () => {+ it("turns auto-reload off when the paid plan is gone, and leaves a paying customer alone", async () => {+ getMock.mockResolvedValueOnce(+ customer({ flags: {}, billingControls: savedControls(true) }),+ );+ await disableAutoReloadIfUnpaid("org_1");+ expect(updateMock).toHaveBeenCalledWith(+ expect.objectContaining({+ billingControls: {+ autoTopups: [expect.objectContaining({ enabled: false })],+ usageLimits: [expect.objectContaining({ enabled: false })],+ },+ }),+ );++ getMock.mockResolvedValueOnce(+ customer({ billingControls: savedControls(true) }),+ );+ await disableAutoReloadIfUnpaid("org_1");+ expect(updateMock).toHaveBeenCalledTimes(1);+ });+});++describe("handleAutoReloadWebhook", () => {+ const failed = (reason: string) => ({+ type: "billing.auto_topup_failed",+ occurred_at: 1_700_000_000_000,+ data: {+ customer_id: "org_1",+ feature_id: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ reason,+ },+ });++ it("flags a declined card for the billing page and emails whoever can fix it", async () => {+ await handleAutoReloadWebhook(failed("charge_failed"));++ expect(updateMock).toHaveBeenCalledWith({+ customerId: "org_1",+ metadata: {+ autoReloadFailure: { reason: "charge_failed", at: 1_700_000_000_000 },+ },+ });+ expect(sendLoopsEventMock).toHaveBeenCalledTimes(1);+ expect(sendLoopsEventMock.mock.calls[0]?.[0]).toMatchObject({+ payload: {+ email: "[email protected]",+ eventName: "auto_reload_failed",+ eventProperties: { reason: "charge_failed" },+ },+ });+ });++ it("flags a failure on our side without blaming the card", async () => {+ vi.spyOn(console, "error").mockImplementation(() => {});+ await handleAutoReloadWebhook(failed("configuration_unavailable"));++ expect(updateMock).toHaveBeenCalledTimes(1);+ expect(sendLoopsEventMock).not.toHaveBeenCalled();+ });++ it("treats Autumn's own windows as waits and the purchase backstop as ours, not failures", async () => {+ vi.spyOn(console, "error").mockImplementation(() => {});+ await handleAutoReloadWebhook(failed("failed_attempt_limit_reached"));+ await handleAutoReloadWebhook(failed("purchase_limit_reached"));++ expect(updateMock).not.toHaveBeenCalled();+ expect(sendLoopsEventMock).not.toHaveBeenCalled();+ expect(console.error).toHaveBeenCalledTimes(1);+ });++ it("clears the flag once a reload goes through", async () => {+ await handleAutoReloadWebhook({+ type: "billing.auto_topup_succeeded",+ data: { customer_id: "org_1", quantity_granted: 20000 },+ });++ expect(updateMock).toHaveBeenCalledWith({+ customerId: "org_1",+ metadata: { autoReloadFailure: null },+ });+ });+});diff --git a/src/server/billing/auto-reload.ts b/src/server/billing/auto-reload.tsnew file mode 100644index 00000000..0bde9ac1--- /dev/null+++ b/src/server/billing/auto-reload.ts@@ -0,0 +1,383 @@+import { z } from "zod";+import type { EnsuredUserContext } from "@/middleware/ensure-user/types";+import { hasOrgPermission } from "@/lib/org-permissions";+import { requireOrgPermission } from "@/server/auth/org-gate";+import { autumn, AUTUMN_TRACK_RETRY_OPTIONS } from "@/server/billing/autumn";+import {+ AUTO_RELOAD_FAILURE_METADATA_KEY,+ primesAutoReloadOnEnable,+ readAutoReload,+} from "@/server/billing/auto-reload-status";+import { getOrganizationContacts } from "@/server/billing/loops-sync";+import { sendLoopsEvent } from "@/server/email/loops-client";+import { sha256Hex } from "@/server/lib/audit/ids";+import { AppError } from "@/server/lib/errors";+import { captureServerEvent } from "@/server/lib/posthog";+import { getOptionalEnvValue } from "@/server/lib/runtime-env";+import {+ AUTO_RELOAD_CARD_FAILURE_REASONS,+ AUTO_RELOAD_DEFAULTS,+ AUTO_RELOAD_THRESHOLD_USD,+ AUTUMN_PAID_PLAN_FEATURE_ID,+ AUTUMN_SEO_DATA_CREDITS_PER_USD,+ AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ isAutoReloadBudgetSpent,+ type AutoReloadSettings,+} from "@/shared/billing";++/**+ * Auto-reload: Autumn buys top-up credits with the organization's saved card+ * whenever the top-up balance is at or below the threshold, and the+ * organization's monthly budget caps what it spends on top-up credits per+ * billing cycle. Autumn holds both as customer billing controls on the same+ * balance (an auto top-up and a usage limit) and enforces them itself: it+ * buys after each deduction or refused check on the top-up balance, and+ * refuses the hold that would take the cycle's spend past the budget. This+ * module turns them on and off and records what Autumn reports back.+ */++type BillingCaller = Pick<+ EnsuredUserContext,+ "organizationId" | "role" | "userId"+>;+// Autumn waiting out one of its own windows (two attempts per ten minutes,+// one failed attempt per hour). Not a failure of its own: whatever failed+// before is already recorded.+const WAIT_REASONS = new Set([+ "attempt_limit_reached",+ "failed_attempt_limit_reached",+]);++// The SDK's own errors for a request that did not get an answer: the charge+// may still have gone through on Autumn's side. Matched by class name, as+// the SDK does not set `name` on them.+const NO_ANSWER_ERROR_NAMES = new Set([+ "RequestTimeoutError",+ "ConnectionError",+ "RequestAbortedError",+ "UnexpectedClientError",+]);+const isNoAnswerError = (error: unknown): error is Error =>+ error instanceof Error &&+ (NO_ANSWER_ERROR_NAMES.has(error.name) ||+ NO_ANSWER_ERROR_NAMES.has(error.constructor.name));++const usdToCredits = (usd: number) => usd * AUTUMN_SEO_DATA_CREDITS_PER_USD;++export async function setOrganizationAutoReload(+ caller: BillingCaller,+ input: { enabled: false } | ({ enabled: true } & AutoReloadSettings),+) {+ requireOrgPermission(caller, { billing: ["manage"] });+ const customerId = caller.organizationId;++ if (!input.enabled) {+ // Autumn keeps an amount on a disabled entry too; keeping the saved one+ // means turning it back on restores it. Turning off is never gated: an+ // organization that left the paid plan must still be able to.+ const current = readAutoReload(await autumn.customers.get({ customerId }));+ await writeAutoReloadControl(customerId, {+ ...(current ?? AUTO_RELOAD_DEFAULTS),+ enabled: false,+ });+ await captureSaved(caller, { enabled: false });+ return;+ }++ const customer = await autumn.customers.get({+ customerId,+ expand: ["payment_method"],+ });+ // Top-ups are for paid plans (the page offers them to no one else), and a+ // reload is a card charge without a checkout, so there has to be a card.+ // The organization that pays the subscription has one; a plan granted by+ // hand may not.+ if (!customer.flags[AUTUMN_PAID_PLAN_FEATURE_ID]) {+ throw new AppError("PAYMENT_REQUIRED", "Auto-reload needs a paid plan");+ }+ if (!customer.paymentMethod) {+ throw new AppError(+ "PAYMENT_METHOD_REQUIRED",+ `No payment method on file for ${customerId}`,+ );+ }+ // Autumn keeps the cycle's top-up spend while auto-reload is off, so a+ // budget the spend already reaches would pause the credits at once, and+ // the first reload below would buy credits that cannot be used. The page+ // says so before the click; this is the backstop.+ const current = readAutoReload(customer);+ if (+ current &&+ current.spentUsd > 0 &&+ isAutoReloadBudgetSpent(current.spentUsd, input.monthlyLimitUsd)+ ) {+ throw new AppError(+ "VALIDATION_ERROR",+ `This cycle's top-up spend is $${current.spentUsd}; the budget must leave room above it`,+ );+ }++ // Buying the first reload here (see primesAutoReloadOnEnable for when)+ // gives Autumn a purchase to price from, leaves the balance above the+ // threshold so Autumn's own enable-time purchase is skipped, and gives the+ // customer credits at once instead of after a failed call. The purchase+ // lands before the control is written.+ const primed = primesAutoReloadOnEnable(customer);+ if (primed) {+ await buyFirstReload(customerId, input.amountUsd);+ }++ await writeAutoReloadControl(customerId, { ...input, enabled: true });+ await captureSaved(caller, { ...input, primed });+}++async function buyFirstReload(customerId: string, amountUsd: number) {+ let requiredAction;+ try {+ ({ requiredAction } = await autumn.billing.attach(+ {+ customerId,+ planId: AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,+ featureQuantities: [+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ quantity: usdToCredits(amountUsd),+ },+ ],+ // Charge the saved card now; a checkout link is of no use here.+ redirectMode: "never",+ },+ // A charge has no idempotency key, so the SDK's default retry on a 5xx+ // or dropped connection after Autumn charged the card would charge it+ // again.+ AUTUMN_TRACK_RETRY_OPTIONS,+ ));+ } catch (error) {+ // No answer is not no charge: the generic "please try again" would invite+ // a second one, so the message sends them to the balance first. Logged+ // because the code it maps to is not reported on its own.+ if (isNoAnswerError(error)) {+ console.error("[billing] first auto-reload purchase got no answer", {+ customerId,+ error,+ });+ throw new AppError("PAYMENT_ACTION_REQUIRED", error.message);+ }+ throw error;+ }+ if (!requiredAction) return;+ // The bank wants a confirmation or more time: the card itself may be fine,+ // and the charge may still land, so the message must not ask for a retry.+ const bankNeedsTime =+ requiredAction.code === "3ds_required" ||+ requiredAction.code === "payment_processing";+ throw new AppError(+ bankNeedsTime ? "PAYMENT_ACTION_REQUIRED" : "PAYMENT_METHOD_REQUIRED",+ `First auto-reload purchase needs ${requiredAction.code}: ${requiredAction.reason}`,+ );+}++/** Turns auto-reload off for a customer who no longer holds a paid plan, so+ * a canceled subscription stops the card charges with it. Called from the+ * billing.updated sync. */+export async function disableAutoReloadIfUnpaid(customerId: string) {+ const customer = await autumn.customers.get({ customerId });+ const current = readAutoReload(customer);+ if (!current?.enabled || customer.flags[AUTUMN_PAID_PLAN_FEATURE_ID]) return;+ await writeAutoReloadControl(customerId, { ...current, enabled: false });+ await captureServerEvent({+ distinctId: customerId,+ event: "billing:auto_reload_disabled_on_downgrade",+ organizationId: customerId,+ });+}++async function writeAutoReloadControl(+ customerId: string,+ settings: AutoReloadSettings & { enabled: boolean },+) {+ await autumn.customers.update({+ customerId,+ billingControls: {+ autoTopups: [+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ enabled: settings.enabled,+ threshold: usdToCredits(AUTO_RELOAD_THRESHOLD_USD),+ quantity: usdToCredits(settings.amountUsd),+ // A backstop on the card only; the budget below is what bounds+ // reloads. Autumn's purchase window is a rolling month that can+ // span two billing cycles, so this is twice the reloads a cycle's+ // budget can need, plus the one that can land as it is reached.+ purchaseLimit: {+ interval: "month",+ limit:+ 2 * Math.ceil(settings.monthlyLimitUsd / settings.amountUsd) + 1,+ },+ },+ ],+ // The budget: Autumn's hard cap on top-up credits spent per billing+ // cycle. It refuses the hold that would exceed it, counts open holds,+ // keeps the cycle's count when the limit changes, and starts counting+ // when created. Off with auto-reload: credits bought by hand alone are+ // not budgeted.+ usageLimits: [+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ enabled: settings.enabled,+ limit: usdToCredits(settings.monthlyLimitUsd),+ interval: "month",+ anchor: "billing_cycle",+ },+ ],+ },+ // Turning on either found no failure or just charged the card again+ // successfully, so the notice is over. Turning off keeps it: the reason+ // reloads stopped is still worth knowing.+ ...(settings.enabled+ ? { metadata: { [AUTO_RELOAD_FAILURE_METADATA_KEY]: null } }+ : {}),+ });+}++function captureSaved(+ caller: BillingCaller,+ properties: Record<string, unknown>,+) {+ return captureServerEvent({+ distinctId: caller.userId,+ event: "billing:auto_reload_saved",+ organizationId: caller.organizationId,+ properties,+ });+}++// Autumn reports every reload it buys or fails to buy. Only what is read is+// required; the shape is the dashboard's, and only one feature has a control.+const autoReloadWebhookSchema = z+ .object({+ type: z.enum(["billing.auto_topup_succeeded", "billing.auto_topup_failed"]),+ occurred_at: z.number().optional(),+ data: z+ .object({+ customer_id: z.string(),+ reason: z.string().optional(),+ quantity_granted: z.number().optional(),+ error: z+ .object({+ code: z.string().nullish(),+ message: z.string().nullish(),+ decline_code: z.string().nullish(),+ })+ .passthrough()+ .nullish(),+ })+ .passthrough(),+ })+ .passthrough();++export const AUTO_RELOAD_WEBHOOK_TYPES = new Set<string>(+ autoReloadWebhookSchema.shape.type.options,+);++/** Records what Autumn's auto top-up webhooks say about an organization's+ * reloads: the notice the billing page shows, an email to the people who+ * can fix the card, and analytics. The Autumn customer id is the+ * organization id. */+export async function handleAutoReloadWebhook(payload: unknown) {+ const parsed = autoReloadWebhookSchema.safeParse(payload);+ if (!parsed.success) {+ // Reportable: a shape change here would hide every reload failure.+ console.error("[billing] unrecognized auto top-up webhook", {+ payload,+ issues: parsed.error.issues,+ });+ return;+ }+ const { type, data } = parsed.data;+ const organizationId = data.customer_id;+ const at = parsed.data.occurred_at ?? Date.now();++ if (type === "billing.auto_topup_succeeded") {+ // The card works again: a notice from before this reload is stale.+ await autumn.customers.update({+ customerId: organizationId,+ metadata: { [AUTO_RELOAD_FAILURE_METADATA_KEY]: null },+ });+ await captureServerEvent({+ distinctId: organizationId,+ event: "billing:auto_reload_succeeded",+ organizationId,+ properties: { credits: data.quantity_granted },+ });+ return;+ }++ const reason = data.reason ?? "unknown";+ await captureServerEvent({+ distinctId: organizationId,+ event: "billing:auto_reload_failed",+ organizationId,+ properties: { reason, decline_code: data.error?.decline_code },+ });+ if (WAIT_REASONS.has(reason)) return;+ if (reason === "purchase_limit_reached") {+ // The backstop on reload count, which the budget keeps out of reach.+ // Reportable, but nothing the customer can fix.+ console.error("[billing] auto-reload hit its purchase backstop", {+ organizationId,+ });+ return;+ }++ // Every other reason stops the credits, so every other reason is shown;+ // only card problems are the customer's to fix.+ await autumn.customers.update({+ customerId: organizationId,+ metadata: { [AUTO_RELOAD_FAILURE_METADATA_KEY]: { reason, at } },+ });+ if (!AUTO_RELOAD_CARD_FAILURE_REASONS.has(reason)) {+ console.error("[billing] auto-reload failed", {+ organizationId,+ reason,+ error: data.error,+ });+ return;+ }+ // Best effort after the notice is written: a retried webhook must not+ // write a stale notice over a success that landed in between.+ try {+ await emailAutoReloadFailed(organizationId, reason);+ } catch (error) {+ console.error("[billing] auto-reload failure email failed", {+ organizationId,+ error,+ });+ }+}++/** Loops event to the members who can change the card. One email per person+ * per day: Autumn retries a declining card until it pauses reloads, and+ * each attempt sends a webhook. */+async function emailAutoReloadFailed(organizationId: string, reason: string) {+ const apiKey = await getOptionalEnvValue("LOOPS_API_KEY");+ if (!apiKey) return;+ const day = new Date().toISOString().slice(0, 10);+ for (const contact of await getOrganizationContacts(organizationId)) {+ if (!hasOrgPermission(contact.role, { billing: ["manage"] })) continue;+ await sendLoopsEvent({+ apiKey,+ idempotencyKey: `auto_reload_failed:${await sha256Hex(+ `${organizationId}:${contact.userId}:${day}`,+ )}`,+ payload: {+ email: contact.email,+ userId: contact.userId,+ eventName: "auto_reload_failed",+ eventProperties: { reason },+ },+ logContext: { action: "auto-reload-failed", organizationId },+ });+ }+}diff --git a/src/server/billing/autumn-webhook.ts b/src/server/billing/autumn-webhook.tsindex dd8b09d0..eaa1e012 100644--- a/src/server/billing/autumn-webhook.ts+++ b/src/server/billing/autumn-webhook.ts@@ -2,6 +2,10 @@ import { z } from "zod";import { getRequiredEnvValue } from "@/server/lib/runtime-env";import { captureServerError } from "@/server/lib/posthog";import { trackDubSalesForOrganization } from "@/server/referrals/dub";+import {+ AUTO_RELOAD_WEBHOOK_TYPES,+ handleAutoReloadWebhook,+} from "./auto-reload";import { syncAutumnCustomerStatus } from "./customer-status-sync";import { verifySvixSignature } from "./svix";@@ -43,38 +47,46 @@ export async function handleAutumnWebhookRequest(request: Request) {return json({ error: "Invalid webhook payload" }, 400);}+ const isBillingUpdated = payload.type === "billing.updated";+ if (!isBillingUpdated && !AUTO_RELOAD_WEBHOOK_TYPES.has(payload.type)) {+ return json({ received: true });+ }+ const customerId = getCustomerId(payload);+ if (isBillingUpdated && !customerId) {+ return json({ error: "Missing customer_id" }, 400);+ }+// Re-syncing the customer's current state from Autumn is idempotent, so a// replayed or out-of-order webhook simply converges to the same row — no// dedup table needed. Svix retries on a non-2xx response.- if (payload.type === "billing.updated") {- const customerId = getCustomerId(payload);- if (!customerId) {- return json({ error: "Missing customer_id" }, 400);- }-- try {+ try {+ if (customerId && isBillingUpdated) {await syncAutumnCustomerStatus(customerId);- } catch (error) {- // Drizzle truncates its own message to "Failed query:"; the real driver- // detail (postgres.js code/constraint) lives on error.cause, so log that- // explicitly. Also forward to PostHog — this raw handler runs outside the- // server-function middleware, so nothing else captures it as a $exception.- console.error("Autumn billing.updated sync failed", customerId, error, {- cause: error instanceof Error ? error.cause : undefined,- });- // Webhooks carry no user; the Autumn customer id is the organization id,- // which at least makes "users affected" count organizations instead of events.- await captureServerError(- error,- {- source: "autumn_webhook",- customer_id: customerId,- },- customerId,- );- return json({ error: "Webhook processing failed" }, 500);+ } else {+ await handleAutoReloadWebhook(payload);}+ } catch (error) {+ // Drizzle truncates its own message to "Failed query:"; the real driver+ // detail (postgres.js code/constraint) lives on error.cause, so log that+ // explicitly. Also forward to PostHog — this raw handler runs outside the+ // server-function middleware, so nothing else captures it as a $exception.+ console.error(`Autumn ${payload.type} webhook failed`, customerId, error, {+ cause: error instanceof Error ? error.cause : undefined,+ });+ // Webhooks carry no user; the Autumn customer id is the organization id,+ // which at least makes "users affected" count organizations instead of events.+ await captureServerError(+ error,+ {+ source: "autumn_webhook",+ customer_id: customerId,+ },+ customerId ?? undefined,+ );+ return json({ error: "Webhook processing failed" }, 500);+ }+ if (customerId && isBillingUpdated) {// Referral revenue attribution; internally fire-and-forget and can never// fail the webhook response.await trackDubSalesForOrganization(customerId);diff --git a/src/server/billing/billing-account.test.ts b/src/server/billing/billing-account.test.tsindex 326297b4..94d7f7f6 100644--- a/src/server/billing/billing-account.test.ts+++ b/src/server/billing/billing-account.test.ts@@ -37,6 +37,7 @@ describe("getOrganizationBillingAccount", () => {[AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]: { remaining: 2500 },},subscriptions: [{ planId: "friends_and_family_2", pastDue: true }],+ purchases: [],sendEmailReceipts: true,});@@ -50,6 +51,9 @@ describe("getOrganizationBillingAccount", () => {isPastDue: true,monthlyRefillsAt: 1_790_000_000_000,invoiceEmailsEnabled: true,+ autoReload: null,+ // No top-up purchase to price a reload from, so turning it on buys one.+ autoReloadPrimesOnEnable: true,});// The organization is the billing identity.expect(getOrCreateMock).toHaveBeenCalledWith({@@ -62,6 +66,7 @@ describe("getOrganizationBillingAccount", () => {flags: { [AUTUMN_MANAGED_ACCESS_FEATURE_ID]: {} },balances: {},subscriptions: [{ pastDue: false }],+ purchases: [],});await expect(getOrganizationBillingAccount(context)).resolves.toMatchObject(@@ -79,6 +84,7 @@ describe("getOrganizationBillingAccount", () => {},},subscriptions: [{ planId: "base-plan", canceledAt: 1_789_000_000_000 }],+ purchases: [],});await expect(getOrganizationBillingAccount(context)).resolves.toMatchObject(@@ -86,6 +92,56 @@ describe("getOrganizationBillingAccount", () => {);});+ it("reads auto-reload in USD with the cycle's spend against the budget and the last failure", async () => {+ getOrCreateMock.mockResolvedValueOnce({+ id: "org_1",+ flags: {},+ balances: {+ [AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]: { remaining: 12000 },+ },+ subscriptions: [],+ purchases: [{ planId: "credit-top-up" }],+ billingControls: {+ autoTopups: [+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ enabled: true,+ threshold: 5000,+ quantity: 20000,+ purchaseLimit: { interval: "month", intervalCount: 1, limit: 11 },+ },+ ],+ usageLimits: [+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ enabled: true,+ limit: 100000,+ interval: "month",+ anchor: "billing_cycle",+ usage: 42500,+ },+ ],+ },+ metadata: { autoReloadFailure: { reason: "charge_failed", at: 1_000 } },+ });++ await expect(getOrganizationBillingAccount(context)).resolves.toMatchObject(+ {+ autoReload: {+ enabled: true,+ thresholdUsd: 5,+ amountUsd: 20,+ monthlyLimitUsd: 100,+ spentUsd: 42.5,+ failure: { reason: "charge_failed", at: 1_000 },+ },+ // Credits above the threshold: the failed reload is retried by+ // Autumn when they run low, not charged again now.+ autoReloadPrimesOnEnable: false,+ },+ );+ });+it("fails instead of showing the empty customer Autumn returns when it fails open", async () => {vi.spyOn(console, "warn").mockImplementation(() => {});getOrCreateMock.mockResolvedValueOnce({diff --git a/src/server/billing/billing-account.ts b/src/server/billing/billing-account.tsindex 8f08cc28..66964eae 100644--- a/src/server/billing/billing-account.ts+++ b/src/server/billing/billing-account.ts@@ -7,6 +7,11 @@ import {type PlanStatus,} from "@/shared/billing";import { autumn } from "@/server/billing/autumn";+import {+ primesAutoReloadOnEnable,+ readAutoReload,+ type AutoReloadStatus,+} from "@/server/billing/auto-reload-status";import type { BillingCustomerContext } from "@/server/billing/subscription";import { AppError } from "@/server/lib/errors";@@ -28,12 +33,18 @@ type BillingAccount = {monthlyRefillsAt: number | null;/** Stripe emails a receipt for each paid invoice. */invoiceEmailsEnabled: boolean;+ /** Automatic top-up purchases. Null when never set up. */+ autoReload: AutoReloadStatus | null;+ /** Whether turning auto-reload on charges the card for the first reload+ * at once; the page says so on the button. */+ autoReloadPrimesOnEnable: boolean;};export async function getOrganizationBillingAccount(context: BillingCustomerContext,): Promise<BillingAccount> {- // No expand: every field read below is on the bare customer.+ // No expand: every field read below, the auto-reload controls and the+ // budget's spend included, is on the bare customer.const customer = await autumn.customers.getOrCreate({customerId: context.organizationId,email: context.userEmail,@@ -73,5 +84,7 @@ export async function getOrganizationBillingAccount(? null: (monthly?.nextResetAt ?? null),invoiceEmailsEnabled: customer.sendEmailReceipts,+ autoReload: readAutoReload(customer),+ autoReloadPrimesOnEnable: primesAutoReloadOnEnable(customer),};}diff --git a/src/server/billing/customer-status-sync.ts b/src/server/billing/customer-status-sync.tsindex af0fcd32..049c6374 100644--- a/src/server/billing/customer-status-sync.ts+++ b/src/server/billing/customer-status-sync.ts@@ -2,6 +2,7 @@ import { eq, sql } from "drizzle-orm";import { db } from "@/db";import { billingCustomerStatus } from "@/db/schema";import { autumn } from "@/server/billing/autumn";+import { disableAutoReloadIfUnpaid } from "@/server/billing/auto-reload";import { captureMetaPurchase } from "@/server/referrals/meta";import { AUTUMN_PAID_PLAN_ID } from "@/shared/billing";import {@@ -16,6 +17,8 @@ export async function syncAutumnCustomerStatus(customerId: string) {// references an existing Autumn customer. The SDK returns the camelCase shape.const customer = await autumn.customers.getOrCreate({ customerId });const snapshot = deriveBillingCustomerStatusSnapshot(customer);+ // Auto-reload charges the saved card; a plan that ended must not keep it.+ await disableAutoReloadIfUnpaid(customerId);// Lifecycle emails are the diff between the last stored customer and this// one. Loops is called before the row is written: an outage fails thediff --git a/src/server/billing/loops-sync.ts b/src/server/billing/loops-sync.tsindex dac0de61..2ac2055e 100644--- a/src/server/billing/loops-sync.ts+++ b/src/server/billing/loops-sync.ts@@ -93,7 +93,8 @@ export async function syncBillingStatusToLoops({}}-async function getOrganizationContacts(organizationId: string) {+/** Every member with their role, for billing email. */+export async function getOrganizationContacts(organizationId: string) {return db.select({userId: user.id,diff --git a/src/server/billing/subscription.test.ts b/src/server/billing/subscription.test.tsindex 20a876b1..3e0faddf 100644--- a/src/server/billing/subscription.test.ts+++ b/src/server/billing/subscription.test.ts@@ -127,6 +127,7 @@ describe("subscription billing", () => {await expect(result).resolves.toEqual({depleted: false,monthlyRemaining: 250,+ budgetReached: false,});expect(monthlyChecks).toBe(2);});diff --git a/src/server/billing/subscription.ts b/src/server/billing/subscription.tsindex 393adff1..02814bb2 100644--- a/src/server/billing/subscription.ts+++ b/src/server/billing/subscription.ts@@ -91,9 +91,13 @@ export async function customerHasPaidPlan(// Remaining shared usage credits — the monthly `usage_credits` balance plus the// rolled-over `topup_credits` balance. Both DataForSEO and LLM spend draw from// these (the `seo_data_usage` and `llm_usage` features both map into them).+// `topupRemaining` is what can be spent now: 0 while the organization's+// monthly auto-reload budget (Autumn's usage limit on the top-up balance) is+// spent, which `topupBudgetReached` reports.export async function getUsageCreditsRemaining(customerId: string): Promise<{monthlyRemaining: number;topupRemaining: number;+ topupBudgetReached: boolean;}> {const [monthlyCheck, topupCheck] = await Promise.all([autumn.check({ customerId, featureId: AUTUMN_SEO_DATA_BALANCE_FEATURE_ID }),@@ -139,9 +143,16 @@ export async function getUsageCreditsRemaining(customerId: string): Promise<{);}+ // A positive balance that refuses one credit is the budget: the usage+ // limit is the only control on this balance that refuses with credits left.+ const topupBudgetReached =+ !topupCheck.allowed && (topupCheck.balance?.remaining ?? 0) > 0;return {monthlyRemaining: monthlyBalance.remaining,- topupRemaining: topupCheck.balance?.remaining ?? 0,+ topupRemaining: topupBudgetReached+ ? 0+ : (topupCheck.balance?.remaining ?? 0),+ topupBudgetReached,};}@@ -159,10 +170,36 @@ export async function getUsageCreditsRemaining(customerId: string): Promise<{*/export async function checkUsageCreditsDepleted(customer: BillingCustomerContext,-): Promise<{ depleted: boolean; monthlyRemaining: number }> {+): Promise<{+ depleted: boolean;+ monthlyRemaining: number;+ /** Depleted because the monthly auto-reload budget is spent, with top-up+ * credits still in the balance; the refusal copy says to raise it. */+ budgetReached: boolean;+}> {const check = await getUsageCreditsRemaining(customer.organizationId);- if (check.monthlyRemaining + check.topupRemaining > 0) {- return { depleted: false, monthlyRemaining: check.monthlyRemaining };+ const notDepleted = {+ depleted: false,+ monthlyRemaining: check.monthlyRemaining,+ budgetReached: false,+ };+ if (check.monthlyRemaining + check.topupRemaining > 0) return notDepleted;++ // The budget is a refusal Autumn made on purpose, not a stale balance, so+ // there is nothing to confirm against the customer object, which shows+ // the credits the budget holds back.+ if (check.topupBudgetReached) {+ await captureServerEvent({+ distinctId: customer.userId,+ event: "usage:credits_gate_refused",+ organizationId: customer.organizationId,+ properties: {+ project_id: customer.projectId,+ reason: "monthly_budget_reached",+ monthly_remaining: check.monthlyRemaining,+ },+ });+ return { ...notDepleted, depleted: true, budgetReached: true };}// No try/catch: if this second read fails while the first said depleted,@@ -189,7 +226,7 @@ export async function checkUsageCreditsDepleted(confirmed,},);- return { depleted: false, monthlyRemaining: confirmed.monthlyRemaining };+ return { ...notDepleted, monthlyRemaining: confirmed.monthlyRemaining };}await captureServerEvent({@@ -203,7 +240,7 @@ export async function checkUsageCreditsDepleted(},});await sendCreditsExhaustedEvent(customer);- return { depleted: true, monthlyRemaining: check.monthlyRemaining };+ return { ...notDepleted, depleted: true };}// A hold outlives the provider call it covers; an orphaned hold (isolate@@ -306,7 +343,10 @@ export async function holdCredits(args: {** Throws INSUFFICIENT_CREDITS when no call fits; `refusedCalls` lists the* ones that did not when some did. Either way the refusal event and the- * credits-exhausted email event are sent.+ * credits-exhausted email event are sent. A top-up balance that covers the+ * estimate and still refuses is the organization's monthly auto-reload+ * budget (Autumn's usage limit): the error says so, as nothing but raising+ * it or the next cycle helps.* The caller must settle every returned hold with `settleUsageCredits` once* its calls' real cost is known.*/@@ -352,6 +392,7 @@ export async function reserveUsageCredits(args: {const holds: UsageCreditHold[] = [];let monthlyRemaining = 0;let topupRemaining = 0;+ let budgetReached = false;let refusedCalls: number[] = [];try {const monthly = await holdFitting(@@ -377,11 +418,22 @@ export async function reserveUsageCredits(args: {);if (topup && !topup.allowed) {topupRemaining = topup.balance?.remaining ?? 0;- topup = await holdFitting(- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,- topupCalls,- topupRemaining,- );+ // The budget's headroom is not in the response, so the calls are+ // refused rather than retried smaller.+ budgetReached = topupRemaining >= creditsFor(topupCalls);+ if (!budgetReached) {+ topup = await holdFitting(+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ topupCalls,+ topupRemaining,+ );+ // The smaller hold fits the balance just read, so a refusal of it+ // is the budget too, unless the balance moved in between.+ if (topup && !topup.allowed) {+ budgetReached =+ (topup.balance?.remaining ?? 0) >= topup.hold.estimatedCredits;+ }+ }}if (topup?.allowed) holds.push(topup.hold);refusedCalls = allCalls.filter(@@ -403,7 +455,9 @@ export async function reserveUsageCredits(args: {organizationId: args.customer.organizationId,properties: {project_id: args.customer.projectId,- reason: "estimate_exceeds_balance",+ reason: budgetReached+ ? "monthly_budget_reached"+ : "estimate_exceeds_balance",source: "dataforseo",credit_feature: args.creditFeature,estimated_credits: creditsFor(refusedCalls),@@ -412,10 +466,18 @@ export async function reserveUsageCredits(args: {},});// Most users are refused while they still have a few credits left, so- // this, not the zero-balance gate, is where most of them run out.- await sendCreditsExhaustedEvent(args.customer);+ // this, not the zero-balance gate, is where most of them run out. A+ // spent budget is not that: the credits are there, only held back.+ if (!budgetReached) await sendCreditsExhaustedEvent(args.customer);+ }+ if (holds.length === 0) {+ throw new AppError(+ "INSUFFICIENT_CREDITS",+ budgetReached+ ? "The organization has hit its monthly auto-reload budget, so its top-up credits are paused until the owner raises it or the billing cycle resets."+ : undefined,+ );}- if (holds.length === 0) throw new AppError("INSUFFICIENT_CREDITS");return { holds, refusedCalls };}diff --git a/src/server/features/sam/SamChatAgent.ts b/src/server/features/sam/SamChatAgent.tsindex 438b50cf..f85dfbc9 100644--- a/src/server/features/sam/SamChatAgent.ts+++ b/src/server/features/sam/SamChatAgent.ts@@ -332,19 +332,20 @@ export class SamChatAgent extends Think {const { organizationId } = ctx.project;const hosted = await isHostedServerAuthMode();if (hosted) {- const { depleted, monthlyRemaining } = await checkUsageCreditsDepleted({+ const gate = await checkUsageCreditsDepleted({userId: ctx.row.userId,userEmail: ctx.userEmail,organizationId,projectId: ctx.project.id,});- if (depleted) {+ if (gate.depleted) {turn.refusal = "credits";+ // A spent budget holds credits back; buying more would not help.return this.refusalTurn(- "You're out of credits. Upgrade your plan or buy more credits on the Billing page to keep using SAM.",+ `${gate.budgetReached ? "You've hit your monthly auto-reload budget. Raise it" : "You're out of credits. Upgrade your plan or buy more credits"} on the Billing page to keep using SAM.`,);}- this.turnMonthlyRemaining = monthlyRemaining;+ this.turnMonthlyRemaining = gate.monthlyRemaining;}const baseUrl =diff --git a/src/server/mcp/tools/whoami.ts b/src/server/mcp/tools/whoami.tsindex 5d7d9e1f..121e5f06 100644--- a/src/server/mcp/tools/whoami.ts+++ b/src/server/mcp/tools/whoami.ts@@ -33,12 +33,14 @@ export const whoamiTool = {const auth = context.auth;const isHosted = await isHostedServerAuthMode();let creditsRemaining: number | null = null;+ let budgetReached = false;if (isHosted) {try {const customer = await getOrCreateOrganizationCustomer(auth);- const { monthlyRemaining, topupRemaining } =+ const { monthlyRemaining, topupRemaining, topupBudgetReached } =await getUsageCreditsRemaining(customer.id);creditsRemaining = monthlyRemaining + topupRemaining;+ budgetReached = topupBudgetReached;} catch {// Account identity is still available when billing is unavailable.}@@ -52,6 +54,11 @@ export const whoamiTool = {lines.push(`Credits remaining: ${creditsRemaining != null ? creditsRemaining.toLocaleString() : "unknown"}`,);+ if (budgetReached) {+ lines.push(+ "Top-up credits: paused until the owner raises the monthly auto-reload budget on the Billing page.",+ );+ }}return mcpResponse({text: lines.join("\n"),diff --git a/src/serverFunctions/billing.ts b/src/serverFunctions/billing.tsindex 745b7468..d7b472b1 100644--- a/src/serverFunctions/billing.ts+++ b/src/serverFunctions/billing.ts@@ -1,7 +1,13 @@import { createServerFn } from "@tanstack/react-start";import { getRequest } from "@tanstack/react-start/server";import { z } from "zod";-import { CHECKOUT_PLAN_IDS } from "@/shared/billing";+import {+ autoReloadSettingsSchema,+ CHECKOUT_PLAN_IDS,+ TOP_UP_MAX_USD,+ TOP_UP_MIN_USD,+} from "@/shared/billing";+import { setOrganizationAutoReload } from "@/server/billing/auto-reload";import { getOrganizationBillingAccount } from "@/server/billing/billing-account";import {createBillingPortalUrl,@@ -47,7 +53,11 @@ export const createPlanCheckout = createServerFn({ method: "POST" })export const createTopUpCheckout = createServerFn({ method: "POST" }).middleware(requireAuthenticatedContext)- .validator(z.object({ amountUsd: z.number().int().min(10).max(99) }))+ .validator(+ z.object({+ amountUsd: z.number().int().min(TOP_UP_MIN_USD).max(TOP_UP_MAX_USD),+ }),+ ).handler(({ data, context }) =>createTopUpCheckoutUrl(context, {...data,@@ -55,6 +65,20 @@ export const createTopUpCheckout = createServerFn({ method: "POST" })}),);+// Turning auto-reload on may charge the saved card for the first reload at+// once (see setOrganizationAutoReload); the page says so before the click.+// The threshold is fixed server-side, so the client chooses only the amount+// and the monthly limit.+export const setAutoReload = createServerFn({ method: "POST" })+ .middleware(requireAuthenticatedContext)+ .validator(+ z.union([+ z.object({ enabled: z.literal(false) }),+ z.object({ enabled: z.literal(true) }).and(autoReloadSettingsSchema),+ ]),+ )+ .handler(({ data, context }) => setOrganizationAutoReload(context, data));+export const createBillingPortalSession = createServerFn({ method: "POST" }).middleware(requireAuthenticatedContext).validator(z.object({ returnTo: z.string() }))diff --git a/src/shared/billing.ts b/src/shared/billing.tsindex ec949c6b..2d9bf498 100644--- a/src/shared/billing.ts+++ b/src/shared/billing.ts@@ -1,3 +1,5 @@+import { z } from "zod";+export const BILLING_ROUTE = "/billing";export const SUBSCRIBE_ROUTE = "/subscribe";@@ -34,6 +36,62 @@ export const AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID = "topup_credits";export const AUTUMN_SEO_DATA_CREDITS_PER_USD = 1000;const SEO_DATA_COST_MARKUP = 1.28;export const LOW_CREDITS_THRESHOLD_USD = 0.25;++// Auto-reload: Autumn buys top-up credits with the saved card whenever the+// top-up balance is at or below the threshold, and a monthly budget caps+// what the organization spends on top-up credits per billing cycle. The+// threshold is fixed: it only needs to cover the largest single hold, and a+// user-set one that reached the reload amount would make every reload+// trigger the next. The reload amount shares the one-off top-up bounds+// because both buy through the same Autumn plan.+export const TOP_UP_MIN_USD = 10;+export const TOP_UP_MAX_USD = 99;+export const AUTO_RELOAD_THRESHOLD_USD = 5;+// Reloads are charged off-session, without Stripe Checkout's confirmation,+// and only happen as top-up credits are spent, so the budget bounds what a+// card can be charged in a cycle; raise on request.+export const AUTO_RELOAD_MAX_MONTHLY_USD = 1000;+export const AUTO_RELOAD_DEFAULTS = {+ amountUsd: 20,+ monthlyLimitUsd: 100,+} as const;+// Autumn refuses the hold that would take the cycle's spend past the budget+// while the balance still shows credits, so the spend rarely lands on the+// limit itself: the budget is as good as spent once less than the largest+// single hold (the threshold) is left of it, and the pages say so then.+export function isAutoReloadBudgetSpent(+ spentUsd: number,+ monthlyLimitUsd: number,+) {+ return monthlyLimitUsd - spentUsd < AUTO_RELOAD_THRESHOLD_USD;+}+// Autumn's reasons a reload did not go through that the customer can act on:+// the card, not our setup. Everything else is ours to look at.+export const AUTO_RELOAD_CARD_FAILURE_REASONS: ReadonlySet<string> = new Set([+ "charge_failed",+ "suspended_after_failures",+ "missing_payment_method",+ "payment_method_not_supported",+ "payment_method_delayed",+]);++export const autoReloadSettingsSchema = z+ .object({+ amountUsd: z.number().int().min(TOP_UP_MIN_USD).max(TOP_UP_MAX_USD),+ /** The most the organization spends on top-up credits per billing+ * cycle, in USD. Every top-up credit counts, not only reloaded ones. */+ monthlyLimitUsd: z+ .number()+ .int()+ .min(TOP_UP_MIN_USD)+ .max(AUTO_RELOAD_MAX_MONTHLY_USD),+ })+ .refine((settings) => settings.monthlyLimitUsd >= settings.amountUsd, {+ message: "The monthly budget must be at least the reload amount.",+ path: ["monthlyLimitUsd"],+ });+export type AutoReloadSettings = z.infer<typeof autoReloadSettingsSchema>;+// DataForSEO's raw price for one Google Ads search_volume live call (up to// 1,000 keywords). Local keyword research adds one call to each search.export const LOCAL_VOLUME_COST_USD = 0.09;diff --git a/src/shared/error-codes.ts b/src/shared/error-codes.tsindex daf6c252..a82c3928 100644--- a/src/shared/error-codes.ts+++ b/src/shared/error-codes.ts@@ -4,6 +4,8 @@ const ERROR_CODES = ["UNAUTHENTICATED","AUTH_CONFIG_MISSING","PAYMENT_REQUIRED",+ "PAYMENT_METHOD_REQUIRED",+ "PAYMENT_ACTION_REQUIRED","INSUFFICIENT_CREDITS","FORBIDDEN","NOT_FOUND",@@ -35,6 +37,10 @@ const NON_REPORTABLE_ERROR_CODES = new Set<ErrorCode>(["RATE_LIMITED","NOT_FOUND","PAYMENT_REQUIRED",+ // The customer's own card declined, is missing, or needs their bank's+ // confirmation; the message tells them what to do.+ "PAYMENT_METHOD_REQUIRED",+ "PAYMENT_ACTION_REQUIRED","INSUFFICIENT_CREDITS","VALIDATION_ERROR","UNKNOWN_LOCATION",diff --git a/web/src/components/campaign-pages.tsx b/web/src/components/campaign-pages.tsxindex cd5dc04e..f86f873c 100644--- a/web/src/components/campaign-pages.tsx+++ b/web/src/components/campaign-pages.tsx@@ -187,7 +187,7 @@ const SELF_HOST_ANSWER = ();const BILLING_ANSWER =- "One plan at $10/mo includes $10 of usage every month. Buy extra usage when you need it; top-ups never expire. Cancel anytime from your billing portal.";+ "One plan at $10/mo includes $10 of usage every month. Buy extra usage when you need it, or let auto-reload buy it for you up to a monthly limit; top-ups never expire. Cancel anytime from your billing portal.";// ─── /agencies ───────────────────────────────────────────────────────diff --git a/web/src/routes/_marketing/pricing.tsx b/web/src/routes/_marketing/pricing.tsxindex 23083e70..c3780659 100644--- a/web/src/routes/_marketing/pricing.tsx+++ b/web/src/routes/_marketing/pricing.tsx@@ -223,7 +223,7 @@ function Pricing() {"Works inside Claude, Cursor, and ChatGPT","Google Search Console data is free and doesn't touch your $10","Includes $10 of usage every month",- "Buy extra usage anytime; it never expires",+ "Buy extra usage anytime, or reload it automatically; it never expires",].map((item) => (<li key={item} className="flex gap-2.5 text-sm text-neutral-700"><span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-brand-accent)]">@@ -441,7 +441,9 @@ function Pricing() {What if I use all my credits for the month?</dt><dd className="mt-1.5 text-sm leading-6 text-[var(--color-brand-muted)]">- Buy top-up credits at any time to keep using paid features.+ Buy top-up credits at any time, or turn on auto-reload so+ OpenSEO buys them for you when you run low, up to a monthly+ limit you set.</dd></div><div className="py-4 first:pt-0 last:pb-0">