Skip to content

The platform for continuously improving AI agents.

Make credits the only billing model (#357)

Freyam Mehta2caefa878cde
diff --git a/.agents/skills/backend-architecture/references/auth-and-billing.md b/.agents/skills/backend-architecture/references/auth-and-billing.md
index 7ac8dabb..52bf5aca 100644
--- a/.agents/skills/backend-architecture/references/auth-and-billing.md
+++ b/.agents/skills/backend-architecture/references/auth-and-billing.md
@@ -15,7 +15,8 @@ Tenancy is project-scoped (`User` ↔ `Project` through `ProjectMembership`), wi
## Billing
-- Ledger charges always run. Remaining-credit 402s, the Free seat limit and Stripe Checkout apply only when `STRIPE_SECRET_KEY` is set (`services/billing_provider.py`); otherwise spend is recorded and shown, and gates and grants are no-ops.
+- Billing is credits only. Ledger charges always run. Remaining-credit 402s, the $50 signup `grant` and Stripe Checkout apply only when `STRIPE_SECRET_KEY` is set (`services/billing_provider.py`); otherwise spend is recorded and shown, and gates and grants are no-ops.
+- Money in is a `grant` (free: signup, promotions, `manage.py grant_credits`) or a `purchase` (a paid live Checkout session). A purchase is keyed `topup:<session id>` and lands from whichever comes first: `POST /api/billing/topup/confirm/` when the buyer returns from Checkout, or the webhook for payment methods that settle later (`services/credit_purchases.py`). The webhook endpoint's events live in `WEBHOOK_EVENTS`; `manage.py sync_stripe_webhook --url <endpoint>` applies them to Stripe.
- Native-agent model choice and funding belong to the coding-agent environment. Training, evaluation and serving keep their own billing.
- Compute estimates use live provider rates with fetch timestamps (`services/provider_pricing.py`: Modal workspace rates, cached 300 s when current and 30 s when unavailable, no static fallback; `compute_costs.py` and the forecasts call it). They never create ledger charges. One quote uses one rate snapshot. Chat-training cost estimates are the exception: they use the fixed `_MODAL_H100_USD_PER_SECOND` in `finetuning_pricing.py`.
- Modal training charges use deduplicated worker usage receipts and recorded hardware, never the delay before the collector notices completion. Missing usage stays unmeasured; historical ledger entries are not rewritten.
diff --git a/.agents/skills/seed-demo-data/SKILL.md b/.agents/skills/seed-demo-data/SKILL.md
index 37769b20..f80bf2e4 100644
--- a/.agents/skills/seed-demo-data/SKILL.md
+++ b/.agents/skills/seed-demo-data/SKILL.md
@@ -24,7 +24,7 @@ docker compose exec api python manage.py seed_demo [--owner EMAIL]
groups, timestamps anchored to NOW) and idempotent: the reset deletes the
project by slug (plus the retired Undermind demo slugs), the `@ledgerline.dev`
team users, demo-project ledger rows and the exact seeded top-up before it seeds.
-Unrelated account charges, top-ups and free credits are retained. The
+Unrelated account charges, purchases and grants are retained. The
project belongs to `--owner` (default `[email protected]`); the
account is created with password `password` when it does not exist. Plaintext
API keys print at the end. Activity and onboarding examples are terminal receipts
diff --git a/.env.example b/.env.example
index b1965ab5..d0e01a4b 100644
--- a/.env.example
+++ b/.env.example
@@ -70,10 +70,9 @@ OVERWATCH_SERVICE_TOKEN=
# Secret key from https://dashboard.stripe.com/apikeys
STRIPE_SECRET_KEY=
# Webhook signing secret from Stripe Dashboard → Developers → Webhooks.
-# Endpoint: POST /api/billing/webhook/ (listen for invoice.paid).
+# Endpoint: POST /api/billing/webhook/. `manage.py sync_stripe_webhook --url <endpoint>`
+# sets the events it listens for.
STRIPE_WEBHOOK_SECRET=
-# Pro plan recurring price id (defaults to the live Pro price if unset).
-STRIPE_PRO_PRICE_ID=price_1TvfC1CgXbweROl8gtGzCSV6
# One Overmind Credit at $0.01, one-time. Top-up checkout quantity = credits bought.
# Sandbox value below (product prod_Uxk0NXK4DO91Sz); prod uses
# price_1TxoTvCgXbweROl8s9G4WsfI (product prod_UxjxGrapXS061n).
diff --git a/frontend/src/client.ts b/frontend/src/client.ts
index e2180d82..dc0c1429 100644
--- a/frontend/src/client.ts
+++ b/frontend/src/client.ts
@@ -17,7 +17,6 @@ import {
GUEST_UPGRADE_CODE,
GuestUpgradeError,
} from "./lib/guest";
-import { emitPlanLimitToast, PlanLimitError, planLimitFromBody } from "./lib/plan-limits";
import { dismissSessionRecovery, requireSessionRecovery } from "./lib/session-recovery";
import { localStore } from "./lib/storage";
import type { ModelSwapPrompt } from "./openapi";
@@ -253,8 +252,7 @@ async function authenticatedFetch(input: RequestInfo | URL, init?: RequestInit):
/**
* Raising the dialog here rather than at call sites means a caller that only
- * logs errors still gets the right UI. Plan-limit 403s get a one-shot upgrade
- * toast instead of the credits dialog.
+ * logs errors still gets the right UI.
*/
const paymentRequiredMiddleware: Middleware = {
async post(context) {
@@ -270,11 +268,6 @@ const paymentRequiredMiddleware: Middleware = {
emitGuestUpgrade();
throw new GuestUpgradeError();
}
- const plan = planLimitFromBody(body);
- if (plan) {
- emitPlanLimitToast(plan.message);
- throw new PlanLimitError(plan.message, plan.code);
- }
}
},
};
@@ -410,11 +403,6 @@ export async function request<T>(path: string, init?: RequestInit): Promise<T> {
emitGuestUpgrade();
throw new GuestUpgradeError();
}
- const plan = planLimitFromBody(body);
- if (plan) {
- emitPlanLimitToast(plan.message);
- throw new PlanLimitError(plan.message, plan.code);
- }
}
const detail = extractErrorDetail(body);
throw new ApiError(
diff --git a/frontend/src/components/app-sidebar.tsx b/frontend/src/components/app-sidebar.tsx
index c2fc29f5..3f1b1d76 100644
--- a/frontend/src/components/app-sidebar.tsx
+++ b/frontend/src/components/app-sidebar.tsx
@@ -27,10 +27,8 @@ import { useAuthContext } from "@/contexts/auth-context";
import { useAllEvalRunsQuery } from "@/hooks/use-evaluations";
import { useFinetuningJobsQuery } from "@/hooks/use-finetuning";
import { useGuestGate } from "@/hooks/use-guest-gate";
-import { useOnboardingStatus } from "@/hooks/use-query";
import { useUnseenSignalCountQuery } from "@/hooks/use-signals";
import { featureFlags } from "@/lib/feature-flags";
-import { PUBLIC_PRICING_URL } from "@/lib/marketing";
import { isMac } from "@/lib/platform";
import { buildRunningJobs, type RunningJobKind } from "@/lib/running-jobs";
import {
@@ -199,9 +197,6 @@ export function AppSidebar({ collapsible = "icon", onSearchOpen }: AppSidebarPro
const iconOnly = state === "collapsed" && !isMobile;
const { isSignedIn, isGuest, requestUpgrade, user } = useAuthContext();
const navJobBadges = useNavJobBadges();
- const { data: me } = useOnboardingStatus(isSignedIn);
- const planLabel = me?.plan === "pro" ? "Pro" : "Free";
- const showPlan = me?.billingEnabled === true;
const [feedbackOpen, setFeedbackOpen] = useState(false);
const clerkUserId = user?.id ?? "";
const userEmail = user?.email ?? "";
@@ -322,17 +317,6 @@ export function AppSidebar({ collapsible = "icon", onSearchOpen }: AppSidebarPro
pane's bottom-bar band. */}
<div className="flex items-center gap-1 rounded-md transition-colors hover:bg-sidebar-accent focus-within:bg-sidebar-accent">
<AccountMenu />
- {showPlan ? (
- <a
- className="chip-label mr-1 shrink-0 rounded-sm border border-border px-1.5 py-0.5 text-xs text-muted-foreground transition-colors hover:border-sidebar-accent-foreground/30 hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:hidden"
- href={PUBLIC_PRICING_URL}
- rel="noreferrer"
- target="_blank"
- title="View plans"
- >
- {planLabel}
- </a>
- ) : null}
</div>
</SidebarMenuItem>
) : (
diff --git a/frontend/src/components/billing/account-band.tsx b/frontend/src/components/billing/account-band.tsx
index fd3e8f21..7c080669 100644
--- a/frontend/src/components/billing/account-band.tsx
+++ b/frontend/src/components/billing/account-band.tsx
@@ -1,32 +1,9 @@
-import { useEffect, useRef } from "react";
-
-import { format } from "date-fns";
-import { toast } from "sonner";
-
import { ResponseError } from "@/client";
import { TopUpDialog } from "@/components/billing/top-up-dialog";
-import { Badge } from "@/components/ui/badge";
-import { Button } from "@/components/ui/button";
-import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { CreditsAmount } from "@/components/ui/credits";
-import { Icon } from "@/components/ui/icons";
import { Skeleton } from "@/components/ui/skeleton";
-import {
- useBuyPlan,
- useCancelSubscription,
- useCommercialBilling,
- useRenewSubscription,
- useSubscriptionQuery,
-} from "@/hooks/use-subscription";
-import { PUBLIC_PRICING_URL } from "@/lib/marketing";
-import { notify } from "@/lib/notify";
+import { useBillingAccount, useCommercialBilling } from "@/hooks/use-billing-account";
import { cn } from "@/lib/utils";
-import { PlanEnum, type Subscription } from "@/openapi";
-
-function formatDate(value: Date | null | undefined): string | null {
- if (!value) return null;
- return format(value, "d MMM yyyy");
-}
function errorMessage(err: unknown, fallback: string): string {
if (err instanceof ResponseError) return err.message;
@@ -34,124 +11,6 @@ function errorMessage(err: unknown, fallback: string): string {
return fallback;
}
-function planBadge(sub: Subscription) {
- if (sub.plan === PlanEnum.pro && sub.canManageRenewal && sub.cancelAtPeriodEnd) {
- return <Badge variant="warning">Cancels soon</Badge>;
- }
- if (sub.plan === PlanEnum.pro) {
- return <Badge variant="success">Pro</Badge>;
- }
- if (sub.status === "past_due") {
- return <Badge variant="warning">Past due</Badge>;
- }
- return <Badge variant="neutral">Free</Badge>;
-}
-
-function SharedActions() {
- return (
- <>
- <TopUpDialog />
- <Button asChild size="sm" variant="secondary">
- <a href={PUBLIC_PRICING_URL} rel="noreferrer" target="_blank">
- <Icon.forward />
- View plans
- </a>
- </Button>
- </>
- );
-}
-
-function PlanActions({ sub }: { sub: Subscription }) {
- const buy = useBuyPlan();
- const cancel = useCancelSubscription();
- const renew = useRenewSubscription();
-
- async function startCheckout() {
- try {
- const res = await buy.mutateAsync();
- window.location.href = res.checkoutUrl;
- } catch (err) {
- notify.error(err, "Checkout failed");
- }
- }
-
- async function onCancel() {
- try {
- await cancel.mutateAsync();
- toast.success("Pro will cancel at the end of the billing period.");
- } catch (err) {
- notify.error(err, "Could not cancel plan");
- }
- }
-
- async function onRenew() {
- try {
- await renew.mutateAsync();
- toast.success("Auto-renewal resumed.");
- } catch (err) {
- notify.error(err, "Could not renew plan");
- }
- }
-
- if (sub.plan === PlanEnum.pro && !sub.canManageRenewal) {
- return <SharedActions />;
- }
-
- if (sub.plan === PlanEnum.pro && sub.cancelAtPeriodEnd) {
- return (
- <>
- <Button disabled={renew.isPending} onClick={() => void onRenew()} size="sm">
- {renew.isPending ? "Resuming…" : "Renew plan"}
- </Button>
- <SharedActions />
- </>
- );
- }
-
- if (sub.plan === PlanEnum.pro) {
- return (
- <>
- <ConfirmDialog
- confirmLabel="Cancel plan"
- description={
- <>
- <p>
- {sub.endDate
- ? `You'll keep Pro access and remaining credits until ${formatDate(sub.endDate)}. Auto-renewal stops after that.`
- : "You'll keep Pro access until the end of the current billing period."}
- </p>
- <p className="mt-2">
- When Pro ends, projects you created revert to a single seat (you alone). Teammates
- will lose access to those projects.
- </p>
- </>
- }
- destructive
- isPending={cancel.isPending}
- onConfirm={onCancel}
- title="Cancel Pro?"
- trigger={
- <Button disabled={cancel.isPending} size="sm" variant="secondary">
- <Icon.close />
- Cancel plan
- </Button>
- }
- />
- <SharedActions />
- </>
- );
- }
-
- return (
- <>
- <Button disabled={buy.isPending} onClick={() => void startCheckout()} size="sm">
- {buy.isPending ? "Redirecting…" : "Buy Pro"}
- </Button>
- <SharedActions />
- </>
- );
-}
-
function Fact({
label,
children,
@@ -169,159 +28,63 @@ function Fact({
);
}
-function QuotaStat({ label, value }: { label: string; value: string }) {
+function Amount({ usd, raw }: { usd: number; raw: string }) {
return (
- <div className="flex flex-col gap-1.5">
- <span className="pixel-label text-xs text-muted-foreground">{label}</span>
- <span className="text-sm font-medium leading-none tabular-nums text-foreground">{value}</span>
- </div>
+ <span className="flex h-6 items-center text-sm font-medium tabular-nums text-foreground">
+ {Number.isFinite(usd) ? <CreditsAmount usd={usd} /> : raw}
+ </span>
);
}
-export function AccountBand({
- autoCheckout = false,
- className,
- onAutoCheckoutStarted,
-}: {
- /** Marketing "Get Pro" lands on `/settings?billing=checkout`; start Stripe Checkout once. */
- autoCheckout?: boolean;
- className?: string;
- onAutoCheckoutStarted?: () => void;
-}) {
- const query = useSubscriptionQuery();
+export function AccountBand({ className }: { className?: string }) {
+ const query = useBillingAccount();
const { enabled: commercial, ready } = useCommercialBilling();
- const buy = useBuyPlan();
- const autoCheckoutStarted = useRef(false);
-
- useEffect(() => {
- if (!commercial) return;
- if (!autoCheckout || autoCheckoutStarted.current || query.isLoading || !query.data) return;
- if (query.data.plan === PlanEnum.pro && !query.data.cancelAtPeriodEnd) {
- autoCheckoutStarted.current = true;
- onAutoCheckoutStarted?.();
- toast.message("You already have an active Pro subscription.");
- return;
- }
- if (query.data.plan === PlanEnum.pro && query.data.cancelAtPeriodEnd) {
- // Cancelling Pro resumes via Renew — do not open a second Checkout Session.
- autoCheckoutStarted.current = true;
- onAutoCheckoutStarted?.();
- return;
- }
+ const account = query.data;
- autoCheckoutStarted.current = true;
- onAutoCheckoutStarted?.();
- void (async () => {
- try {
- const res = await buy.mutateAsync();
- window.location.href = res.checkoutUrl;
- } catch (err) {
- notify.error(err, "Checkout failed");
- }
- })();
- }, [autoCheckout, buy, commercial, onAutoCheckoutStarted, query.data, query.isLoading]);
-
- const sub = query.data;
-
- if (query.isLoading || buy.isPending || !ready) {
+ if (query.isLoading || !ready) {
return (
<div className={cn("rounded-md border border-border bg-card px-4 py-3", className)}>
- {buy.isPending ? (
- <p className="text-sm text-muted-foreground" role="status">
- Redirecting to Stripe…
- </p>
- ) : (
- <div
- aria-busy="true"
- aria-label={commercial ? "Loading plan" : "Loading usage"}
- role="status"
- >
- <span className="sr-only">{commercial ? "Loading plan" : "Loading usage"}</span>
- <div aria-hidden="true" className="flex items-center justify-between gap-4">
- <div className="flex-1 space-y-2">
- <Skeleton className="h-4 w-24" />
- <Skeleton className="h-3 w-1/2" />
- </div>
- <Skeleton className="h-8 w-24" />
+ <div aria-busy="true" aria-label="Loading credits" role="status">
+ <span className="sr-only">Loading credits</span>
+ <div aria-hidden="true" className="flex items-center justify-between gap-4">
+ <div className="flex-1 space-y-2">
+ <Skeleton className="h-4 w-24" />
+ <Skeleton className="h-3 w-1/2" />
</div>
+ <Skeleton className="h-8 w-24" />
</div>
- )}
+ </div>
</div>
);
}
- if (query.error || !sub) {
+ if (query.error || !account) {
return (
<div className={cn("rounded-md border border-border bg-card px-4 py-3", className)}>
<p className="text-sm text-muted-foreground">
- {errorMessage(query.error, "Failed to load subscription")}
+ {errorMessage(query.error, "Failed to load credits")}
</p>
</div>
);
}
- const end = formatDate(sub.endDate);
- const start = formatDate(sub.startDate);
- const creditsN = Number(sub.creditsUsd);
- const spentN = Number(sub.creditsSpentUsd);
- const usage = sub.usage;
-
- if (!commercial) {
- return (
- <div className={cn("rounded-md border border-border bg-card", className)}>
- <div className="flex flex-col divide-y divide-border/70 sm:flex-row sm:items-stretch sm:divide-x sm:divide-y-0">
- <Fact label="Spent">
- <span className="flex h-6 items-center text-sm font-medium tabular-nums text-foreground">
- {Number.isFinite(spentN) ? <CreditsAmount usd={spentN} /> : sub.creditsSpentUsd}
- </span>
- </Fact>
- </div>
- </div>
- );
- }
+ const spent = <Amount raw={account.creditsSpentUsd} usd={Number(account.creditsSpentUsd)} />;
return (
<div className={cn("rounded-md border border-border bg-card", className)}>
<div className="flex flex-col divide-y divide-border/70 sm:flex-row sm:items-stretch sm:divide-x sm:divide-y-0">
- <Fact label="Plan">
- <span className="flex min-h-6 flex-wrap items-center gap-x-2 gap-y-1 text-sm">
- {planBadge(sub)}
- {end ? (
- <span className="text-muted-foreground">
- {sub.canManageRenewal && !sub.cancelAtPeriodEnd ? `renews ${end}` : `until ${end}`}
- </span>
- ) : null}
- </span>
- </Fact>
- {start ? (
- <Fact label="Started">
- <span className="flex h-6 items-center text-sm text-foreground">{start}</span>
+ {commercial ? (
+ <Fact label="Credits">
+ <Amount raw={account.creditsUsd} usd={Number(account.creditsUsd)} />
</Fact>
) : null}
- <Fact label="Credits">
- <span className="flex h-6 items-center text-sm font-medium tabular-nums text-foreground">
- {Number.isFinite(creditsN) ? <CreditsAmount usd={creditsN} /> : sub.creditsUsd}
- </span>
- </Fact>
- <div className="flex flex-wrap items-center gap-2 px-4 py-3 sm:ml-auto">
- <PlanActions sub={sub} />
- </div>
+ <Fact label="Spent">{spent}</Fact>
+ {commercial ? (
+ <div className="flex flex-wrap items-center gap-2 px-4 py-3 sm:ml-auto">
+ <TopUpDialog />
+ </div>
+ ) : null}
</div>
-
- {sub.plan === PlanEnum.pro && sub.canManageRenewal && sub.cancelAtPeriodEnd ? (
- <p className="border-t border-border/70 px-4 py-2 text-sm text-warning">
- Cancellation scheduled{end ? ` — access ends ${end}` : ""}. Renew to keep Pro.
- </p>
- ) : null}
-
- {usage ? (
- <div className="flex flex-wrap items-start gap-x-10 gap-y-4 border-t border-border/70 px-4 py-3">
- <QuotaStat
- label="Seats / project"
- value={usage.seats.limit == null ? "Unlimited" : String(usage.seats.limit)}
- />
- </div>
- ) : null}
</div>
);
}
diff --git a/frontend/src/components/billing/billing-ledger-table.tsx b/frontend/src/components/billing/billing-ledger-table.tsx
index bccf5671..541fbea3 100644
--- a/frontend/src/components/billing/billing-ledger-table.tsx
+++ b/frontend/src/components/billing/billing-ledger-table.tsx
@@ -7,7 +7,7 @@ import { DataTable } from "@/components/ui/data-table";
import { DateTime } from "@/components/ui/datetime";
import { EmptyState } from "@/components/ui/empty-state";
import { Icon } from "@/components/ui/icons";
-import { useBillingLedgerQuery, useCommercialBilling } from "@/hooks/use-subscription";
+import { useBillingLedgerQuery, useCommercialBilling } from "@/hooks/use-billing-account";
import { PROSE, TITLE } from "@/lib/typography";
import { cn } from "@/lib/utils";
import type { BillingTelemetry } from "@/openapi";
diff --git a/frontend/src/components/billing/credits-required.tsx b/frontend/src/components/billing/credits-required.tsx
index 5955a254..a7e86b23 100644
--- a/frontend/src/components/billing/credits-required.tsx
+++ b/frontend/src/components/billing/credits-required.tsx
@@ -1,12 +1,11 @@
import { useEffect } from "react";
+import { TopUpDialog } from "@/components/billing/top-up-dialog";
import { Alert } from "@/components/ui/alert";
-import { Button } from "@/components/ui/button";
import { CreditsAmount } from "@/components/ui/credits";
import { Icon } from "@/components/ui/icons";
-import { useCredits } from "@/hooks/use-subscription";
+import { useCredits } from "@/hooks/use-billing-account";
import { claimCreditsSurface } from "@/lib/credits";
-import { PUBLIC_PRICING_URL } from "@/lib/marketing";
import { cn } from "@/lib/utils";
/** While one of these is on screen, the global dialog stays quiet. */
@@ -14,17 +13,6 @@ function useCreditsSurfaceClaim(active: boolean) {
useEffect(() => (active ? claimCreditsSurface() : undefined), [active]);
}
-function ViewPlansButton({ size = "sm" }: { size?: "sm" | "default" }) {
- return (
- <Button asChild className="shrink-0" size={size} variant="secondary">
- <a href={PUBLIC_PRICING_URL} rel="noreferrer" target="_blank">
- <Icon.zap />
- View plans
- </a>
- </Button>
- );
-}
-
export function CreditsRequiredAlert({
action,
className,
@@ -54,7 +42,7 @@ export function CreditsRequiredAlert({
You need credits to {action}. Your balance is{" "}
<CreditsAmount className="text-foreground" usd={balanceUsd ?? 0} />.
</p>
- <ViewPlansButton />
+ <TopUpDialog />
</Alert>
);
}
diff --git a/frontend/src/components/billing/out-of-credits-dialog.tsx b/frontend/src/components/billing/out-of-credits-dialog.tsx
index e439894c..9f4a7e6e 100644
--- a/frontend/src/components/billing/out-of-credits-dialog.tsx
+++ b/frontend/src/components/billing/out-of-credits-dialog.tsx
@@ -6,7 +6,7 @@ import { TopUpDialog } from "@/components/billing/top-up-dialog";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { CreditsAmount } from "@/components/ui/credits";
import { useAuthContext } from "@/contexts/auth-context";
-import { subscriptionQueryKey, useSubscriptionQuery } from "@/hooks/use-subscription";
+import { billingAccountQueryKey, useBillingAccount } from "@/hooks/use-billing-account";
import { hasCreditsSurface, onPaymentRequired, type PaymentRequiredContext } from "@/lib/credits";
/**
@@ -17,7 +17,7 @@ export function OutOfCreditsDialog() {
const [context, setContext] = useState<PaymentRequiredContext | null>(null);
const [topUpOpen, setTopUpOpen] = useState(false);
const { isSignedIn } = useAuthContext();
- const { data: sub } = useSubscriptionQuery({ enabled: isSignedIn });
+ const { data: sub } = useBillingAccount({ enabled: isSignedIn });
const queryClient = useQueryClient();
useEffect(
@@ -29,7 +29,7 @@ export function OutOfCreditsDialog() {
// so the copy doesn't swap under the user mid-read.
setContext((current) => current ?? next);
// The cached balance predates the spend that just failed.
- queryClient.invalidateQueries({ queryKey: subscriptionQueryKey });
+ queryClient.invalidateQueries({ queryKey: billingAccountQueryKey });
}),
[queryClient]
);
diff --git a/frontend/src/components/billing/top-up-dialog.tsx b/frontend/src/components/billing/top-up-dialog.tsx
index a3d409e4..a758c5ea 100644
--- a/frontend/src/components/billing/top-up-dialog.tsx
+++ b/frontend/src/components/billing/top-up-dialog.tsx
@@ -16,7 +16,7 @@ import { Icon } from "@/components/ui/icons";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Slider } from "@/components/ui/slider";
-import { useTopUpCredits } from "@/hooks/use-subscription";
+import { useTopUpCredits } from "@/hooks/use-billing-account";
import { notify } from "@/lib/notify";
import { TITLE } from "@/lib/typography";
import { cn } from "@/lib/utils";
diff --git a/frontend/src/components/command-palette.tsx b/frontend/src/components/command-palette.tsx
index eb6a4965..17099b85 100644
--- a/frontend/src/components/command-palette.tsx
+++ b/frontend/src/components/command-palette.tsx
@@ -111,15 +111,10 @@ const NAV_KEYWORDS: Record<string, string[]> = {
"/settings": [
"settings",
"billing",
- "plan",
"credits",
- "upgrade",
"top up",
"ledger",
"spend",
- "subscription",
- "cancel plan",
- "renew",
"buy credits",
"invoice",
"usage",
@@ -490,15 +485,10 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
<CommandItem
keywords={[
"billing",
- "plan",
"credits",
- "subscription",
"top up",
"topup",
"ledger",
- "upgrade",
- "cancel plan",
- "renew",
"buy credits",
"spend",
"invoice",
@@ -507,7 +497,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
value="resource:billing"
>
<Icon.credits className="size-[15px] shrink-0 text-muted-foreground" />
- <span className="flex-1">Plan & billing</span>
+ <span className="flex-1">Credits & usage</span>
</CommandItem>
)}
{resources.map((r) => {
diff --git a/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx b/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx
index 295f746d..d4e8d8b2 100644
--- a/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx
+++ b/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx
@@ -59,7 +59,6 @@ vi.mock("@tanstack/react-query", () => ({
}));
vi.mock("@/components/finetuning/train/model-picker", () => ({ findCatalogModel: () => null }));
vi.mock("@/hooks/use-capability-eval-preload", () => ({ useCapabilityEvalPreload: () => ({}) }));
-vi.mock("@/hooks/use-subscription", () => ({ useCredits: () => ({ hasCredits: true }) }));
vi.mock("@/hooks/use-evaluations", () => ({
useEvalSetsQuery: () => ({ data: mocks.sets }),
useModelCatalogQuery: () => ({
diff --git a/frontend/src/components/finetuning/train/use-train-wizard.ts b/frontend/src/components/finetuning/train/use-train-wizard.ts
index 091a840f..abe2bf7c 100644
--- a/frontend/src/components/finetuning/train/use-train-wizard.ts
+++ b/frontend/src/components/finetuning/train/use-train-wizard.ts
@@ -15,6 +15,7 @@ import {
TIER_ORDER,
} from "@/components/finetuning/train/model-config";
import { findCatalogModel } from "@/components/finetuning/train/model-picker";
+import { useCredits } from "@/hooks/use-billing-account";
import { useCapabilityEvalPreload } from "@/hooks/use-capability-eval-preload";
import {
useEvalSetsQuery,
@@ -34,7 +35,6 @@ import {
useTrainingBenchmarksQuery,
useValidateDatasetMutation,
} from "@/hooks/use-finetuning";
-import { useCredits } from "@/hooks/use-subscription";
import { isPaymentRequired } from "@/lib/credits";
import { errorMessage } from "@/lib/notify";
import type {
diff --git a/frontend/src/components/header-credits.tsx b/frontend/src/components/header-credits.tsx
index 0f26c63f..db126fc5 100644
--- a/frontend/src/components/header-credits.tsx
+++ b/frontend/src/components/header-credits.tsx
@@ -2,10 +2,9 @@ import { useEffect, useState } from "react";
import { CreditsAmount } from "@/components/ui/credits";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
-import { useCommercialBilling, useSubscriptionQuery } from "@/hooks/use-subscription";
+import { useBillingAccount, useCommercialBilling } from "@/hooks/use-billing-account";
import { onCreditsDelta } from "@/lib/credits-delta";
import { cn } from "@/lib/utils";
-import { PlanEnum } from "@/openapi";
const LOW_BALANCE_USD = 5;
/* Must match the credits-delta-bubble animation duration in styles.css. */
@@ -14,7 +13,7 @@ const DELTA_MS = 2500;
export function HeaderCredits() {
const { enabled: commercial, ready } = useCommercialBilling();
// Always mounted, so focus-refetch alone goes stale.
- const { data } = useSubscriptionQuery({ refetchInterval: 60_000 });
+ const { data } = useBillingAccount({ refetchInterval: 60_000 });
// seq keys the bubble so a reward landing mid-animation restarts it.
const [delta, setDelta] = useState<{ credits: number; seq: number } | null>(null);
@@ -56,17 +55,14 @@ export function HeaderCredits() {
}
const balance = Math.max(0, Number(data.creditsUsd) || 0);
- const pastDue = data.status === "past_due";
const out = balance <= 0;
const low = !out && balance < LOW_BALANCE_USD;
const detail = out
? "You're out of credits. Add credits in Settings."
- : pastDue
- ? "Payment past due. Check your plan in Settings."
- : low
- ? "Credits are low. Add credits in Settings."
- : `${data.plan === PlanEnum.pro ? "Pro" : "Free"} plan. Credits pay for training, inference and analysis.`;
+ : low
+ ? "Credits are low. Add credits in Settings."
+ : "Credits pay for training, inference and analysis.";
return (
<TooltipProvider delayDuration={150}>
@@ -79,7 +75,7 @@ export function HeaderCredits() {
className={cn(
"relative inline-flex h-8 cursor-help select-none items-center px-1 text-sm leading-none",
"[&_svg]:text-muted-foreground",
- out ? "text-destructive" : low || pastDue ? "text-warning" : "text-foreground"
+ out ? "text-destructive" : low ? "text-warning" : "text-foreground"
)}
role="status"
>
diff --git a/frontend/src/components/inference/dedicated-deployment.test.tsx b/frontend/src/components/inference/dedicated-deployment.test.tsx
index 76f3b9bc..4329b157 100644
--- a/frontend/src/components/inference/dedicated-deployment.test.tsx
+++ b/frontend/src/components/inference/dedicated-deployment.test.tsx
@@ -6,7 +6,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";
const api = vi.hoisted(() => ({
auth: { authMeRetrieve: vi.fn() },
- billing: { billingSubscriptionRetrieve: vi.fn() },
+ billing: { billingAccountRetrieve: vi.fn() },
deployedModels: {
deployedModelsDedicatedCreate: vi.fn(),
deployedModelsDedicatedGpusList: vi.fn(),
@@ -41,7 +41,7 @@ const LIVE = {
beforeEach(() => {
api.auth.authMeRetrieve.mockResolvedValue({ billingEnabled: false });
- api.billing.billingSubscriptionRetrieve.mockResolvedValue({ creditsUsd: "1000" });
+ api.billing.billingAccountRetrieve.mockResolvedValue({ creditsUsd: "1000" });
api.deployedModels.deployedModelsDedicatedGpusList.mockResolvedValue([
{ creditsPerGpuHour: "100", gpuType: "L4" },
]);
diff --git a/frontend/src/components/inference/dedicated-deployment.tsx b/frontend/src/components/inference/dedicated-deployment.tsx
index 9b6e4466..a8e4aba1 100644
--- a/frontend/src/components/inference/dedicated-deployment.tsx
+++ b/frontend/src/components/inference/dedicated-deployment.tsx
@@ -29,6 +29,7 @@ import {
} from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+import { useCommercialBilling, useCredits } from "@/hooks/use-billing-account";
import {
useDedicatedDeploymentQuery,
useDedicatedGpusQuery,
@@ -36,7 +37,6 @@ import {
useStopDedicatedMutation,
useUpdateDedicatedMutation,
} from "@/hooks/use-inference";
-import { useCommercialBilling, useCredits } from "@/hooks/use-subscription";
import { notify } from "@/lib/notify";
import { usdToOvermindCredits } from "@/lib/utils";
import type { DedicatedDeployment, DedicatedGpu, DeployedModel } from "@/openapi";
diff --git a/frontend/src/components/settings-menu.tsx b/frontend/src/components/settings-menu.tsx
index d67dddb6..89d09c01 100644
--- a/frontend/src/components/settings-menu.tsx
+++ b/frontend/src/components/settings-menu.tsx
@@ -26,7 +26,7 @@ export function SettingsMenuButton() {
},
{
icon: Icon.credits,
- label: "Plan & billing",
+ label: "Credits & usage",
onSelect: () => void navigate({ search: (prev) => prev, to: "/settings" }),
},
];
diff --git a/frontend/src/hooks/use-billing-account.test.tsx b/frontend/src/hooks/use-billing-account.test.tsx
new file mode 100644
index 00000000..017b4fa1
--- /dev/null
+++ b/frontend/src/hooks/use-billing-account.test.tsx
@@ -0,0 +1,48 @@
+// @vitest-environment jsdom
+// covers: console-logic
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+
+const billing = vi.hoisted(() => ({ account: vi.fn(), confirm: vi.fn() }));
+vi.mock("@/client", () => ({
+ default: {
+ billing: {
+ billingAccountRetrieve: billing.account,
+ billingTopupConfirmCreate: billing.confirm,
+ },
+ },
+}));
+
+import { billingAccountQueryKey, useBillingAccount, useConfirmTopUp } from "./use-billing-account";
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+it("keeps the confirmed balance when an older account read lands after it", async () => {
+ let landStale: (value: unknown) => void = () => {};
+ billing.account.mockReturnValueOnce(
+ new Promise((resolve) => {
+ landStale = resolve;
+ })
+ );
+ const confirmed = { creditsUsd: "75.0000" };
+ billing.confirm.mockResolvedValue({ account: confirmed, paid: true });
+ const client = new QueryClient();
+ const { result } = renderHook(
+ () => ({ account: useBillingAccount(), confirm: useConfirmTopUp() }),
+ {
+ wrapper: ({ children }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ }
+ );
+ await waitFor(() => expect(billing.account).toHaveBeenCalledOnce());
+
+ await act(() => result.current.confirm.mutateAsync("cs_test_paid"));
+ await act(async () => landStale({ creditsUsd: "50.0000" }));
+
+ expect(client.getQueryData(billingAccountQueryKey)).toEqual(confirmed);
+});
diff --git a/frontend/src/hooks/use-subscription.ts b/frontend/src/hooks/use-billing-account.ts
similarity index 63%
rename from frontend/src/hooks/use-subscription.ts
rename to frontend/src/hooks/use-billing-account.ts
index b7713a19..d91953a2 100644
--- a/frontend/src/hooks/use-subscription.ts
+++ b/frontend/src/hooks/use-billing-account.ts
@@ -2,16 +2,15 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import api from "@/client";
import { useOnboardingStatus } from "@/hooks/use-query";
-import type { Subscription } from "@/openapi";
-export const subscriptionQueryKey = ["billing-subscription"] as const;
+export const billingAccountQueryKey = ["billing-account"] as const;
export const billingLedgerQueryKey = ["billing-ledger"] as const;
-export function useSubscriptionQuery(options?: { enabled?: boolean; refetchInterval?: number }) {
+export function useBillingAccount(options?: { enabled?: boolean; refetchInterval?: number }) {
return useQuery({
enabled: options?.enabled ?? true,
- queryFn: () => api.billing.billingSubscriptionRetrieve(),
- queryKey: subscriptionQueryKey,
+ queryFn: () => api.billing.billingAccountRetrieve(),
+ queryKey: billingAccountQueryKey,
refetchInterval: options?.refetchInterval,
});
}
@@ -29,26 +28,6 @@ export function useBillingLedgerQuery(page = 1, pageSize = 25, ordering?: string
});
}
-export function useCancelSubscription() {
- const queryClient = useQueryClient();
- return useMutation({
- mutationFn: () => api.billing.billingCancelCreate(),
- onSuccess: (data: Subscription) => {
- queryClient.setQueryData(subscriptionQueryKey, data);
- },
- });
-}
-
-export function useRenewSubscription() {
- const queryClient = useQueryClient();
- return useMutation({
- mutationFn: () => api.billing.billingRenewCreate(),
- onSuccess: (data: Subscription) => {
- queryClient.setQueryData(subscriptionQueryKey, data);
- },
- });
-}
-
/**
* `hasCredits` mirrors the server gate exactly: `ensure_credits` rejects only a
* non-positive balance, it does not price the job. An unresolved balance counts
@@ -56,7 +35,7 @@ export function useRenewSubscription() {
*/
export function useCredits() {
const { enabled } = useCommercialBilling();
- const { data, isLoading } = useSubscriptionQuery();
+ const { data, isLoading } = useBillingAccount();
const balanceUsd = data ? Math.max(0, Number(data.creditsUsd) || 0) : undefined;
return {
balanceUsd,
@@ -65,12 +44,6 @@ export function useCredits() {
};
}
-export function useBuyPlan() {
- return useMutation({
- mutationFn: () => api.billing.billingCheckoutCreate(),
- });
-}
-
/** Resolves to a Stripe Checkout URL to redirect to. */
export function useTopUpCredits() {
return useMutation({
@@ -78,3 +51,20 @@ export function useTopUpCredits() {
api.billing.billingTopupCreate({ creditTopUpRequestRequest: { amountUsd } }),
});
}
+
+/** Grants a paid Checkout session on return, so the balance does not wait for the webhook. */
+export function useConfirmTopUp() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (sessionId: string) =>
+ api.billing.billingTopupConfirmCreate({
+ creditTopUpConfirmRequestRequest: { sessionId },
+ }),
+ onSuccess: async (data) => {
+ // A mount-time account fetch can still be in flight with the pre-purchase balance.
+ await queryClient.cancelQueries({ queryKey: billingAccountQueryKey });
+ queryClient.setQueryData(billingAccountQueryKey, data.account);
+ void queryClient.invalidateQueries({ queryKey: billingLedgerQueryKey });
+ },
+ });
+}
diff --git a/frontend/src/lib/api-error.test.ts b/frontend/src/lib/api-error.test.ts
index 34f3ae50..f8d55f92 100644
--- a/frontend/src/lib/api-error.test.ts
+++ b/frontend/src/lib/api-error.test.ts
@@ -4,7 +4,6 @@ import { expect, it } from "vitest";
import { ApiError, isPermanentApiRefusal } from "./api-error";
import { PaymentRequiredError } from "./credits";
import { GuestUpgradeError } from "./guest";
-import { PlanLimitError } from "./plan-limits";
it.each([0, 408, 429, 500, 503])("keeps retryable HTTP %s failures recoverable", (status) => {
expect(isPermanentApiRefusal(new ApiError(status, "failure", true))).toBe(false);
@@ -15,7 +14,6 @@ it.each([400, 401, 403, 404, 409, 413, 422])("recognizes permanent HTTP %s refus
it.each([
new PaymentRequiredError(),
new GuestUpgradeError(),
- new PlanLimitError("Seat limit"),
])("recognizes the client's specialised refusal %s", (error) => {
expect(isPermanentApiRefusal(error)).toBe(true);
});
diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.ts
index 340f8050..aa60bb61 100644
--- a/frontend/src/lib/api-error.ts
+++ b/frontend/src/lib/api-error.ts
@@ -1,6 +1,5 @@
import { PaymentRequiredError } from "@/lib/credits";
import { GuestUpgradeError } from "@/lib/guest";
-import { PlanLimitError } from "@/lib/plan-limits";
/**
* Thrown by the `client.ts` middleware for non-2xx responses, in place of the
@@ -23,12 +22,7 @@ export class ApiError extends Error {
export function isPermanentApiRefusal(error: unknown): boolean {
// The client raises these for 402 and 403 bodies before the generic ApiError.
- if (
- error instanceof PaymentRequiredError ||
- error instanceof GuestUpgradeError ||
- error instanceof PlanLimitError
- )
- return true;
+ if (error instanceof PaymentRequiredError || error instanceof GuestUpgradeError) return true;
return (
error instanceof ApiError &&
error.status >= 400 &&
diff --git a/frontend/src/lib/notify.ts b/frontend/src/lib/notify.ts
index 7fbf4e6c..99fedab8 100644
--- a/frontend/src/lib/notify.ts
+++ b/frontend/src/lib/notify.ts
@@ -4,7 +4,6 @@ import * as z from "zod";
import { ApiError, NETWORK_ERROR_MESSAGE } from "@/lib/api-error";
import { isChunkLoadError } from "@/lib/chunk-error";
import { isPaymentRequired } from "@/lib/credits";
-import { isPlanLimitError } from "@/lib/plan-limits";
const DEFAULT_FALLBACK = "Something went wrong";
@@ -41,12 +40,10 @@ export function errorMessage(err: unknown, fallback = DEFAULT_FALLBACK): string
export const notify = {
/**
- * Silent for 402s (the out-of-credits dialog owns that moment) and for
- * plan-limit 403s (the API middleware already toasts them once).
+ * Silent for 402s: the out-of-credits dialog owns that moment.
*/
error(err: unknown, fallback = "Something went wrong") {
if (isPaymentRequired(err)) return;
- if (isPlanLimitError(err)) return;
const message = errorMessage(err, fallback);
// Keyed by message so a retry storm or batch loop stacks one toast, not N.
toast.error(message, { id: `err:${message}` });
diff --git a/frontend/src/lib/plan-limits.ts b/frontend/src/lib/plan-limits.ts
deleted file mode 100644
index 632f7c92..00000000
--- a/frontend/src/lib/plan-limits.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * Seat refusals: 403 with ``code: seat_limit_exceeded``. Unlike a credits 402,
- * these toast a pricing link.
- */
-
-import { toast } from "sonner";
-
-import { PUBLIC_PRICING_URL } from "@/lib/marketing";
-
-export class PlanLimitError extends Error {
- override name = "PlanLimitError";
- readonly status = 403;
- readonly code: string;
-
- constructor(message: string, code = "seat_limit_exceeded") {
- super(message);
- this.code = code;
- }
-}
-
-export function isPlanLimitError(err: unknown): boolean {
- return err instanceof PlanLimitError;
-}
-
-/** Parse DRF body ``{"detail":"…","code":"seat_limit_exceeded"}`` (or nested detail). */
-export function planLimitFromBody(body: string): { message: string; code: string } | null {
- try {
- const parsed = JSON.parse(body) as {
- detail?: unknown;
- code?: unknown;
- };
- let message: string | undefined;
- let code: string | undefined;
- if (typeof parsed.code === "string") code = parsed.code;
- if (typeof parsed.detail === "string") {
- message = parsed.detail;
- } else if (parsed.detail && typeof parsed.detail === "object") {
- const d = parsed.detail as { detail?: unknown; code?: unknown };
- if (typeof d.detail === "string") message = d.detail;
- if (typeof d.code === "string") code = d.code;
- }
- if (code === "seat_limit_exceeded") {
- return {
- code,
- message: message || "Free plan is limited to one seat. Upgrade to Pro to invite teammates.",
- };
- }
- } catch {
- // non-JSON
- }
- return null;
-}
-
-export function emitPlanLimitToast(message: string) {
- // Fixed id: query retries fire this twice per refused request — keep one toast.
- toast.error(message, {
- action: {
- label: "Upgrade",
- onClick: () => {
- window.open(PUBLIC_PRICING_URL, "_blank", "noopener,noreferrer");
- },
- },
- id: "plan-limit",
- });
-}
diff --git a/frontend/src/openapi/.openapi-generator/FILES b/frontend/src/openapi/.openapi-generator/FILES
index 068adaff..f95448a6 100644
--- a/frontend/src/openapi/.openapi-generator/FILES
+++ b/frontend/src/openapi/.openapi-generator/FILES
@@ -62,6 +62,7 @@ models/AssistantThreadStateEnum.ts
models/AuthTokensResponse.ts
models/BackendEnum.ts
models/BeginUploadRequest.ts
+models/BillingAccount.ts
models/BillingTelemetry.ts
models/Binding.ts
models/BindingStateRequest.ts
@@ -126,6 +127,8 @@ models/ConnectorVerifyResponse.ts
models/ConsentDecisionRequest.ts
models/ConsentDetails.ts
models/ConsentRedirect.ts
+models/CreditTopUpConfirmRequestRequest.ts
+models/CreditTopUpConfirmation.ts
models/CreditTopUpRequestRequest.ts
models/Dataset.ts
models/DatasetAnalytics.ts
@@ -341,9 +344,6 @@ models/PermissionEnum.ts
models/PhaseEnum.ts
models/Pipeline.ts
models/PipelineRun.ts
-models/PlanEnum.ts
-models/PlanUsage.ts
-models/PlanUsageUnit.ts
models/PositionEnum.ts
models/PreparationEdge.ts
models/PreparationEdgeKindEnum.ts
@@ -400,7 +400,6 @@ models/SplitPositionEnum.ts
models/Status1b7Enum.ts
models/StrataPage.ts
models/Stratum.ts
-models/Subscription.ts
models/SyncSnapshot.ts
models/SyncSnapshotRequest.ts
models/SyncStatusEnum.ts
diff --git a/frontend/src/openapi/apis/BillingApi.ts b/frontend/src/openapi/apis/BillingApi.ts
index 7c075d64..9fd7c2bb 100644
--- a/frontend/src/openapi/apis/BillingApi.ts
+++ b/frontend/src/openapi/apis/BillingApi.ts
@@ -15,20 +15,26 @@
import * as runtime from '../runtime';
import type {
+ BillingAccount,
CheckoutSessionResponse,
+ CreditTopUpConfirmRequestRequest,
+ CreditTopUpConfirmation,
CreditTopUpRequestRequest,
PaginatedBillingTelemetryList,
- Subscription,
} from '../models/index';
import {
+ BillingAccountFromJSON,
+ BillingAccountToJSON,
CheckoutSessionResponseFromJSON,
CheckoutSessionResponseToJSON,
+ CreditTopUpConfirmRequestRequestFromJSON,
+ CreditTopUpConfirmRequestRequestToJSON,
+ CreditTopUpConfirmationFromJSON,
+ CreditTopUpConfirmationToJSON,
CreditTopUpRequestRequestFromJSON,
CreditTopUpRequestRequestToJSON,
PaginatedBillingTelemetryListFromJSON,
PaginatedBillingTelemetryListToJSON,
- SubscriptionFromJSON,
- SubscriptionToJSON,
} from '../models/index';
export interface BillingLedgerListRequest {
@@ -37,6 +43,10 @@ export interface BillingLedgerListRequest {
pageSize?: number;
}
+export interface BillingTopupConfirmCreateRequest {
+ creditTopUpConfirmRequestRequest: CreditTopUpConfirmRequestRequest;
+}
+
export interface BillingTopupCreateRequest {
creditTopUpRequestRequest: CreditTopUpRequestRequest;
}
@@ -47,9 +57,9 @@ export interface BillingTopupCreateRequest {
export class BillingApi extends runtime.BaseAPI {
/**
- * Cancel subscription at period end
+ * Get the credits account
*/
- async billingCancelCreateRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<Subscription>> {
+ async billingAccountRetrieveRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<BillingAccount>> {
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
@@ -75,72 +85,23 @@ export class BillingApi extends runtime.BaseAPI {
}
}
- let urlPath = `/api/billing/cancel/`;
+ let urlPath = `/api/billing/account/`;
const response = await this.request({
path: urlPath,
- method: 'POST',
- headers: headerParameters,
- query: queryParameters,
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => SubscriptionFromJSON(jsonValue));
- }
-
- /**
- * Cancel subscription at period end
- */
- async billingCancelCreate(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Subscription> {
- const response = await this.billingCancelCreateRaw(initOverrides);
- return await response.value();
- }
-
- /**
- * Create Stripe Checkout Session
- */
- async billingCheckoutCreateRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<CheckoutSessionResponse>> {
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
-
- let urlPath = `/api/billing/checkout/`;
-
- const response = await this.request({
- path: urlPath,
- method: 'POST',
+ method: 'GET',
headers: headerParameters,
query: queryParameters,
}, initOverrides);
- return new runtime.JSONApiResponse(response, (jsonValue) => CheckoutSessionResponseFromJSON(jsonValue));
+ return new runtime.JSONApiResponse(response, (jsonValue) => BillingAccountFromJSON(jsonValue));
}
/**
- * Create Stripe Checkout Session
+ * Get the credits account
*/
- async billingCheckoutCreate(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<CheckoutSessionResponse> {
- const response = await this.billingCheckoutCreateRaw(initOverrides);
+ async billingAccountRetrieve(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<BillingAccount> {
+ const response = await this.billingAccountRetrieveRaw(initOverrides);
return await response.value();
}
@@ -206,62 +167,22 @@ export class BillingApi extends runtime.BaseAPI {
}
/**
- * Resume subscription auto-renewal
+ * Confirm a credit purchase after Stripe Checkout
*/
- async billingRenewCreateRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<Subscription>> {
- const queryParameters: any = {};
-
- const headerParameters: runtime.HTTPHeaders = {};
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("ClerkBearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
- }
- if (this.configuration && this.configuration.apiKey) {
- headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication
- }
-
- if (this.configuration && this.configuration.accessToken) {
- const token = this.configuration.accessToken;
- const tokenString = await token("BearerAuth", []);
-
- if (tokenString) {
- headerParameters["Authorization"] = `Bearer ${tokenString}`;
- }
+ async billingTopupConfirmCreateRaw(requestParameters: BillingTopupConfirmCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<CreditTopUpConfirmation>> {
+ if (requestParameters['creditTopUpConfirmRequestRequest'] == null) {
+ throw new runtime.RequiredError(
+ 'creditTopUpConfirmRequestRequest',
+ 'Required parameter "creditTopUpConfirmRequestRequest" was null or undefined when calling billingTopupConfirmCreate().'
+ );
}
- let urlPath = `/api/billing/renew/`;
-
- const response = await this.request({
- path: urlPath,
- method: 'POST',
- headers: headerParameters,
- query: queryParameters,
- }, initOverrides);
-
- return new runtime.JSONApiResponse(response, (jsonValue) => SubscriptionFromJSON(jsonValue));
- }
-
- /**
- * Resume subscription auto-renewal
- */
- async billingRenewCreate(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Subscription> {
- const response = await this.billingRenewCreateRaw(initOverrides);
- return await response.value();
- }
-
- /**
- * Get subscription
- */
- async billingSubscriptionRetrieveRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<Subscription>> {
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
+ headerParameters['Content-Type'] = 'application/json';
+
if (this.configuration && this.configuration.accessToken) {
const token = this.configuration.accessToken;
const tokenString = await token("ClerkBearerAuth", []);
@@ -283,28 +204,28 @@ export class BillingApi extends runtime.BaseAPI {
}
}
- let urlPath = `/api/billing/subscription/`;
+ let urlPath = `/api/billing/topup/confirm/`;
const response = await this.request({
path: urlPath,
- method: 'GET',
+ method: 'POST',
headers: headerParameters,
query: queryParameters,
+ body: CreditTopUpConfirmRequestRequestToJSON(requestParameters['creditTopUpConfirmRequestRequest']),
}, initOverrides);
- return new runtime.JSONApiResponse(response, (jsonValue) => SubscriptionFromJSON(jsonValue));
+ return new runtime.JSONApiResponse(response, (jsonValue) => CreditTopUpConfirmationFromJSON(jsonValue));
}
/**
- * Get subscription
+ * Confirm a credit purchase after Stripe Checkout
*/
- async billingSubscriptionRetrieve(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Subscription> {
- const response = await this.billingSubscriptionRetrieveRaw(initOverrides);
+ async billingTopupConfirmCreate(requestParameters: BillingTopupConfirmCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<CreditTopUpConfirmation> {
+ const response = await this.billingTopupConfirmCreateRaw(requestParameters, initOverrides);
return await response.value();
}
/**
- * Open on every plan, unlike the Pro checkout — running out of credits is orthogonal to which plan you are on.
* Buy credits (one-time Stripe Checkout)
*/
async billingTopupCreateRaw(requestParameters: BillingTopupCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<CheckoutSessionResponse>> {
@@ -356,7 +277,6 @@ export class BillingApi extends runtime.BaseAPI {
}
/**
- * Open on every plan, unlike the Pro checkout — running out of credits is orthogonal to which plan you are on.
* Buy credits (one-time Stripe Checkout)
*/
async billingTopupCreate(requestParameters: BillingTopupCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<CheckoutSessionResponse> {
diff --git a/frontend/src/openapi/models/BillingAccount.ts b/frontend/src/openapi/models/BillingAccount.ts
new file mode 100644
index 00000000..9fe6f1af
--- /dev/null
+++ b/frontend/src/openapi/models/BillingAccount.ts
@@ -0,0 +1,92 @@
+/* tslint:disable */
+/* eslint-disable */
+/**
+ * Overbae API
+ * Backend API for the Overclaw / Overmind platform.
+ *
+ * The version of the OpenAPI document: 2.0.0
+ *
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+import { mapValues } from '../runtime';
+/**
+ * Credits balance for the authenticated user.
+ * @export
+ * @interface BillingAccount
+ */
+export interface BillingAccount {
+ /**
+ *
+ * @type {boolean}
+ * @memberof BillingAccount
+ */
+ billingEnabled: boolean;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingAccount
+ */
+ creditsUsd: string;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingAccount
+ */
+ creditsGrantedUsd: string;
+ /**
+ *
+ * @type {string}
+ * @memberof BillingAccount
+ */
+ creditsSpentUsd: string;
+}
+
+/**
+ * Check if a given object implements the BillingAccount interface.
+ */
+export function instanceOfBillingAccount(value: object): value is BillingAccount {
+ if (!('billingEnabled' in value) || value['billingEnabled'] === undefined) return false;
+ if (!('creditsUsd' in value) || value['creditsUsd'] === undefined) return false;
+ if (!('creditsGrantedUsd' in value) || value['creditsGrantedUsd'] === undefined) return false;
+ if (!('creditsSpentUsd' in value) || value['creditsSpentUsd'] === undefined) return false;
+ return true;
+}
+
+export function BillingAccountFromJSON(json: any): BillingAccount {
+ return BillingAccountFromJSONTyped(json, false);
+}
+
+export function BillingAccountFromJSONTyped(json: any, ignoreDiscriminator: boolean): BillingAccount {
+ if (json == null) {
+ return json;
+ }
+ return {
+
+ 'billingEnabled': json['billing_enabled'],
+ 'creditsUsd': json['credits_usd'],
+ 'creditsGrantedUsd': json['credits_granted_usd'],
+ 'creditsSpentUsd': json['credits_spent_usd'],
+ };
+}
+
+export function BillingAccountToJSON(json: any): BillingAccount {
+ return BillingAccountToJSONTyped(json, false);
+}
+
+export function BillingAccountToJSONTyped(value?: BillingAccount | null, ignoreDiscriminator: boolean = false): any {
+ if (value == null) {
+ return value;
+ }
+
+ return {
+
+ 'billing_enabled': value['billingEnabled'],
+ 'credits_usd': value['creditsUsd'],
+ 'credits_granted_usd': value['creditsGrantedUsd'],
+ 'credits_spent_usd': value['creditsSpentUsd'],
+ };
+}
diff --git a/frontend/src/openapi/models/CreditTopUpConfirmRequestRequest.ts b/frontend/src/openapi/models/CreditTopUpConfirmRequestRequest.ts
new file mode 100644
index 00000000..80be9974
--- /dev/null
+++ b/frontend/src/openapi/models/CreditTopUpConfirmRequestRequest.ts
@@ -0,0 +1,65 @@
+/* tslint:disable */
+/* eslint-disable */
+/**
+ * Overbae API
+ * Backend API for the Overclaw / Overmind platform.
+ *
+ * The version of the OpenAPI document: 2.0.0
+ *
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+import { mapValues } from '../runtime';
+/**
+ *
+ * @export
+ * @interface CreditTopUpConfirmRequestRequest
+ */
+export interface CreditTopUpConfirmRequestRequest {
+ /**
+ *
+ * @type {string}
+ * @memberof CreditTopUpConfirmRequestRequest
+ */
+ sessionId: string;
+}
+
+/**
+ * Check if a given object implements the CreditTopUpConfirmRequestRequest interface.
+ */
+export function instanceOfCreditTopUpConfirmRequestRequest(value: object): value is CreditTopUpConfirmRequestRequest {
+ if (!('sessionId' in value) || value['sessionId'] === undefined) return false;
+ return true;
+}
+
+export function CreditTopUpConfirmRequestRequestFromJSON(json: any): CreditTopUpConfirmRequestRequest {
+ return CreditTopUpConfirmRequestRequestFromJSONTyped(json, false);
+}
+
+export function CreditTopUpConfirmRequestRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): CreditTopUpConfirmRequestRequest {
+ if (json == null) {
+ return json;
+ }
+ return {
+
+ 'sessionId': json['session_id'],
+ };
+}
+
+export function CreditTopUpConfirmRequestRequestToJSON(json: any): CreditTopUpConfirmRequestRequest {
+ return CreditTopUpConfirmRequestRequestToJSONTyped(json, false);
+}
+
+export function CreditTopUpConfirmRequestRequestToJSONTyped(value?: CreditTopUpConfirmRequestRequest | null, ignoreDiscriminator: boolean = false): any {
+ if (value == null) {
+ return value;
+ }
+
+ return {
+
+ 'session_id': value['sessionId'],
+ };
+}
diff --git a/frontend/src/openapi/models/CreditTopUpConfirmation.ts b/frontend/src/openapi/models/CreditTopUpConfirmation.ts
new file mode 100644
index 00000000..4fa98c21
--- /dev/null
+++ b/frontend/src/openapi/models/CreditTopUpConfirmation.ts
@@ -0,0 +1,82 @@
+/* tslint:disable */
+/* eslint-disable */
+/**
+ * Overbae API
+ * Backend API for the Overclaw / Overmind platform.
+ *
+ * The version of the OpenAPI document: 2.0.0
+ *
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+import { mapValues } from '../runtime';
+import type { BillingAccount } from './BillingAccount';
+import {
+ BillingAccountFromJSON,
+ BillingAccountFromJSONTyped,
+ BillingAccountToJSON,
+ BillingAccountToJSONTyped,
+} from './BillingAccount';
+
+/**
+ *
+ * @export
+ * @interface CreditTopUpConfirmation
+ */
+export interface CreditTopUpConfirmation {
+ /**
+ *
+ * @type {boolean}
+ * @memberof CreditTopUpConfirmation
+ */
+ paid: boolean;
+ /**
+ *
+ * @type {BillingAccount}
+ * @memberof CreditTopUpConfirmation
+ */
+ account: BillingAccount;
+}
+
+/**
+ * Check if a given object implements the CreditTopUpConfirmation interface.
+ */
+export function instanceOfCreditTopUpConfirmation(value: object): value is CreditTopUpConfirmation {
+ if (!('paid' in value) || value['paid'] === undefined) return false;
+ if (!('account' in value) || value['account'] === undefined) return false;
+ return true;
+}
+
+export function CreditTopUpConfirmationFromJSON(json: any): CreditTopUpConfirmation {
+ return CreditTopUpConfirmationFromJSONTyped(json, false);
+}
+
+export function CreditTopUpConfirmationFromJSONTyped(json: any, ignoreDiscriminator: boolean): CreditTopUpConfirmation {
+ if (json == null) {
+ return json;
+ }
+ return {
+
+ 'paid': json['paid'],
+ 'account': BillingAccountFromJSON(json['account']),
+ };
+}
+
+export function CreditTopUpConfirmationToJSON(json: any): CreditTopUpConfirmation {
+ return CreditTopUpConfirmationToJSONTyped(json, false);
+}
+
+export function CreditTopUpConfirmationToJSONTyped(value?: CreditTopUpConfirmation | null, ignoreDiscriminator: boolean = false): any {
+ if (value == null) {
+ return value;
+ }
+
+ return {
+
+ 'paid': value['paid'],
+ 'account': BillingAccountToJSON(value['account']),
+ };
+}
diff --git a/frontend/src/openapi/models/PlanEnum.ts b/frontend/src/openapi/models/PlanEnum.ts
deleted file mode 100644
index 538ba815..00000000
--- a/frontend/src/openapi/models/PlanEnum.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-
-/**
- * * `free` - free
- * * `pro` - pro
- * @export
- */
-export const PlanEnum = {
- free: 'free',
- pro: 'pro'
-} as const;
-export type PlanEnum = typeof PlanEnum[keyof typeof PlanEnum];
-
-
-export function instanceOfPlanEnum(value: any): boolean {
- for (const key in PlanEnum) {
- if (Object.prototype.hasOwnProperty.call(PlanEnum, key)) {
- if (PlanEnum[key as keyof typeof PlanEnum] === value) {
- return true;
- }
- }
- }
- return false;
-}
-
-export function PlanEnumFromJSON(json: any): PlanEnum {
- return PlanEnumFromJSONTyped(json, false);
-}
-
-export function PlanEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): PlanEnum {
- return json as PlanEnum;
-}
-
-export function PlanEnumToJSON(value?: PlanEnum | null): any {
- return value as any;
-}
-
-export function PlanEnumToJSONTyped(value: any, ignoreDiscriminator: boolean): PlanEnum {
- return value as PlanEnum;
-}
diff --git a/frontend/src/openapi/models/PlanUsage.ts b/frontend/src/openapi/models/PlanUsage.ts
deleted file mode 100644
index 6ed5c1ea..00000000
--- a/frontend/src/openapi/models/PlanUsage.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { PlanUsageUnit } from './PlanUsageUnit';
-import {
- PlanUsageUnitFromJSON,
- PlanUsageUnitFromJSONTyped,
- PlanUsageUnitToJSON,
- PlanUsageUnitToJSONTyped,
-} from './PlanUsageUnit';
-
-/**
- *
- * @export
- * @interface PlanUsage
- */
-export interface PlanUsage {
- /**
- *
- * @type {PlanUsageUnit}
- * @memberof PlanUsage
- */
- seats: PlanUsageUnit;
-}
-
-/**
- * Check if a given object implements the PlanUsage interface.
- */
-export function instanceOfPlanUsage(value: object): value is PlanUsage {
- if (!('seats' in value) || value['seats'] === undefined) return false;
- return true;
-}
-
-export function PlanUsageFromJSON(json: any): PlanUsage {
- return PlanUsageFromJSONTyped(json, false);
-}
-
-export function PlanUsageFromJSONTyped(json: any, ignoreDiscriminator: boolean): PlanUsage {
- if (json == null) {
- return json;
- }
- return {
-
- 'seats': PlanUsageUnitFromJSON(json['seats']),
- };
-}
-
-export function PlanUsageToJSON(json: any): PlanUsage {
- return PlanUsageToJSONTyped(json, false);
-}
-
-export function PlanUsageToJSONTyped(value?: PlanUsage | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'seats': PlanUsageUnitToJSON(value['seats']),
- };
-}
diff --git a/frontend/src/openapi/models/PlanUsageUnit.ts b/frontend/src/openapi/models/PlanUsageUnit.ts
deleted file mode 100644
index 6c12d902..00000000
--- a/frontend/src/openapi/models/PlanUsageUnit.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-/**
- *
- * @export
- * @interface PlanUsageUnit
- */
-export interface PlanUsageUnit {
- /**
- *
- * @type {number}
- * @memberof PlanUsageUnit
- */
- limit: number | null;
-}
-
-/**
- * Check if a given object implements the PlanUsageUnit interface.
- */
-export function instanceOfPlanUsageUnit(value: object): value is PlanUsageUnit {
- if (!('limit' in value) || value['limit'] === undefined) return false;
- return true;
-}
-
-export function PlanUsageUnitFromJSON(json: any): PlanUsageUnit {
- return PlanUsageUnitFromJSONTyped(json, false);
-}
-
-export function PlanUsageUnitFromJSONTyped(json: any, ignoreDiscriminator: boolean): PlanUsageUnit {
- if (json == null) {
- return json;
- }
- return {
-
- 'limit': json['limit'],
- };
-}
-
-export function PlanUsageUnitToJSON(json: any): PlanUsageUnit {
- return PlanUsageUnitToJSONTyped(json, false);
-}
-
-export function PlanUsageUnitToJSONTyped(value?: PlanUsageUnit | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'limit': value['limit'],
- };
-}
diff --git a/frontend/src/openapi/models/Subscription.ts b/frontend/src/openapi/models/Subscription.ts
deleted file mode 100644
index 40982b4d..00000000
--- a/frontend/src/openapi/models/Subscription.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-/* tslint:disable */
-/* eslint-disable */
-/**
- * Overbae API
- * Backend API for the Overclaw / Overmind platform.
- *
- * The version of the OpenAPI document: 2.0.0
- *
- *
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
- * https://openapi-generator.tech
- * Do not edit the class manually.
- */
-
-import { mapValues } from '../runtime';
-import type { PlanEnum } from './PlanEnum';
-import {
- PlanEnumFromJSON,
- PlanEnumFromJSONTyped,
- PlanEnumToJSON,
- PlanEnumToJSONTyped,
-} from './PlanEnum';
-import type { PlanUsage } from './PlanUsage';
-import {
- PlanUsageFromJSON,
- PlanUsageFromJSONTyped,
- PlanUsageToJSON,
- PlanUsageToJSONTyped,
-} from './PlanUsage';
-
-/**
- * Current plan / subscription state for the authenticated user.
- * @export
- * @interface Subscription
- */
-export interface Subscription {
- /**
- *
- * @type {boolean}
- * @memberof Subscription
- */
- billingEnabled: boolean;
- /**
- *
- * @type {PlanEnum}
- * @memberof Subscription
- */
- plan: PlanEnum;
- /**
- *
- * @type {string}
- * @memberof Subscription
- */
- status: string | null;
- /**
- *
- * @type {string}
- * @memberof Subscription
- */
- creditsUsd: string;
- /**
- *
- * @type {string}
- * @memberof Subscription
- */
- creditsGrantedUsd: string;
- /**
- *
- * @type {string}
- * @memberof Subscription
- */
- creditsSpentUsd: string;
- /**
- *
- * @type {Date}
- * @memberof Subscription
- */
- startDate: Date | null;
- /**
- *
- * @type {Date}
- * @memberof Subscription
- */
- endDate: Date | null;
- /**
- *
- * @type {boolean}
- * @memberof Subscription
- */
- cancelAtPeriodEnd: boolean;
- /**
- *
- * @type {boolean}
- * @memberof Subscription
- */
- canManageRenewal: boolean;
- /**
- *
- * @type {PlanUsage}
- * @memberof Subscription
- */
- usage: PlanUsage;
-}
-
-
-
-/**
- * Check if a given object implements the Subscription interface.
- */
-export function instanceOfSubscription(value: object): value is Subscription {
- if (!('billingEnabled' in value) || value['billingEnabled'] === undefined) return false;
- if (!('plan' in value) || value['plan'] === undefined) return false;
- if (!('status' in value) || value['status'] === undefined) return false;
- if (!('creditsUsd' in value) || value['creditsUsd'] === undefined) return false;
- if (!('creditsGrantedUsd' in value) || value['creditsGrantedUsd'] === undefined) return false;
- if (!('creditsSpentUsd' in value) || value['creditsSpentUsd'] === undefined) return false;
- if (!('startDate' in value) || value['startDate'] === undefined) return false;
- if (!('endDate' in value) || value['endDate'] === undefined) return false;
- if (!('cancelAtPeriodEnd' in value) || value['cancelAtPeriodEnd'] === undefined) return false;
- if (!('canManageRenewal' in value) || value['canManageRenewal'] === undefined) return false;
- if (!('usage' in value) || value['usage'] === undefined) return false;
- return true;
-}
-
-export function SubscriptionFromJSON(json: any): Subscription {
- return SubscriptionFromJSONTyped(json, false);
-}
-
-export function SubscriptionFromJSONTyped(json: any, ignoreDiscriminator: boolean): Subscription {
- if (json == null) {
- return json;
- }
- return {
-
- 'billingEnabled': json['billing_enabled'],
- 'plan': PlanEnumFromJSON(json['plan']),
- 'status': json['status'],
- 'creditsUsd': json['credits_usd'],
- 'creditsGrantedUsd': json['credits_granted_usd'],
- 'creditsSpentUsd': json['credits_spent_usd'],
- 'startDate': (json['start_date'] == null ? null : new Date(json['start_date'])),
- 'endDate': (json['end_date'] == null ? null : new Date(json['end_date'])),
- 'cancelAtPeriodEnd': json['cancel_at_period_end'],
- 'canManageRenewal': json['can_manage_renewal'],
- 'usage': PlanUsageFromJSON(json['usage']),
- };
-}
-
-export function SubscriptionToJSON(json: any): Subscription {
- return SubscriptionToJSONTyped(json, false);
-}
-
-export function SubscriptionToJSONTyped(value?: Subscription | null, ignoreDiscriminator: boolean = false): any {
- if (value == null) {
- return value;
- }
-
- return {
-
- 'billing_enabled': value['billingEnabled'],
- 'plan': PlanEnumToJSON(value['plan']),
- 'status': value['status'],
- 'credits_usd': value['creditsUsd'],
- 'credits_granted_usd': value['creditsGrantedUsd'],
- 'credits_spent_usd': value['creditsSpentUsd'],
- 'start_date': value['startDate'] == null ? value['startDate'] : value['startDate'].toISOString(),
- 'end_date': value['endDate'] == null ? value['endDate'] : value['endDate'].toISOString(),
- 'cancel_at_period_end': value['cancelAtPeriodEnd'],
- 'can_manage_renewal': value['canManageRenewal'],
- 'usage': PlanUsageToJSON(value['usage']),
- };
-}
diff --git a/frontend/src/openapi/models/UserMe.ts b/frontend/src/openapi/models/UserMe.ts
index 607efb24..ebc77b2c 100644
--- a/frontend/src/openapi/models/UserMe.ts
+++ b/frontend/src/openapi/models/UserMe.ts
@@ -61,24 +61,12 @@ export interface UserMe {
* @memberof UserMe
*/
readonly billingEnabled: boolean;
- /**
- *
- * @type {string}
- * @memberof UserMe
- */
- readonly plan: string;
/**
*
* @type {string}
* @memberof UserMe
*/
readonly creditsUsd: string;
- /**
- *
- * @type {Date}
- * @memberof UserMe
- */
- readonly subscriptionEnd: Date | null;
/**
*
* @type {boolean}
@@ -97,9 +85,7 @@ export function instanceOfUserMe(value: object): value is UserMe {
if (!('hasCompletedOnboarding' in value) || value['hasCompletedOnboarding'] === undefined) return false;
if (!('isGuest' in value) || value['isGuest'] === undefined) return false;
if (!('billingEnabled' in value) || value['billingEnabled'] === undefined) return false;
- if (!('plan' in value) || value['plan'] === undefined) return false;
if (!('creditsUsd' in value) || value['creditsUsd'] === undefined) return false;
- if (!('subscriptionEnd' in value) || value['subscriptionEnd'] === undefined) return false;
if (!('agentFeedback' in value) || value['agentFeedback'] === undefined) return false;
return true;
}
@@ -121,9 +107,7 @@ export function UserMeFromJSONTyped(json: any, ignoreDiscriminator: boolean): Us
'hasCompletedOnboarding': json['has_completed_onboarding'],
'isGuest': json['is_guest'],
'billingEnabled': json['billing_enabled'],
- 'plan': json['plan'],
'creditsUsd': json['credits_usd'],
- 'subscriptionEnd': (json['subscription_end'] == null ? null : new Date(json['subscription_end'])),
'agentFeedback': json['agent_feedback'],
};
}
@@ -132,7 +116,7 @@ export function UserMeToJSON(json: any): UserMe {
return UserMeToJSONTyped(json, false);
}
-export function UserMeToJSONTyped(value?: Omit<UserMe, 'id'|'clerk_user_id'|'has_completed_onboarding'|'is_guest'|'billing_enabled'|'plan'|'credits_usd'|'subscription_end'|'agent_feedback'> | null, ignoreDiscriminator: boolean = false): any {
+export function UserMeToJSONTyped(value?: Omit<UserMe, 'id'|'clerk_user_id'|'has_completed_onboarding'|'is_guest'|'billing_enabled'|'credits_usd'|'agent_feedback'> | null, ignoreDiscriminator: boolean = false): any {
if (value == null) {
return value;
}
diff --git a/frontend/src/openapi/models/index.ts b/frontend/src/openapi/models/index.ts
index d4b31e9b..07079de4 100644
--- a/frontend/src/openapi/models/index.ts
+++ b/frontend/src/openapi/models/index.ts
@@ -21,6 +21,7 @@ export * from './AssistantThreadStateEnum';
export * from './AuthTokensResponse';
export * from './BackendEnum';
export * from './BeginUploadRequest';
+export * from './BillingAccount';
export * from './BillingTelemetry';
export * from './Binding';
export * from './BindingStateRequest';
@@ -85,6 +86,8 @@ export * from './ConnectorVerifyResponse';
export * from './ConsentDecisionRequest';
export * from './ConsentDetails';
export * from './ConsentRedirect';
+export * from './CreditTopUpConfirmRequestRequest';
+export * from './CreditTopUpConfirmation';
export * from './CreditTopUpRequestRequest';
export * from './Dataset';
export * from './DatasetAnalytics';
@@ -300,9 +303,6 @@ export * from './PermissionEnum';
export * from './PhaseEnum';
export * from './Pipeline';
export * from './PipelineRun';
-export * from './PlanEnum';
-export * from './PlanUsage';
-export * from './PlanUsageUnit';
export * from './PositionEnum';
export * from './PreparationEdge';
export * from './PreparationEdgeKindEnum';
@@ -359,7 +359,6 @@ export * from './SplitPositionEnum';
export * from './Status1b7Enum';
export * from './StrataPage';
export * from './Stratum';
-export * from './Subscription';
export * from './SyncSnapshot';
export * from './SyncSnapshotRequest';
export * from './SyncStatusEnum';
diff --git a/frontend/src/routes/_auth/projects.$projectId.index.tsx b/frontend/src/routes/_auth/projects.$projectId.index.tsx
index 687ae7eb..ed0ccfb2 100644
--- a/frontend/src/routes/_auth/projects.$projectId.index.tsx
+++ b/frontend/src/routes/_auth/projects.$projectId.index.tsx
@@ -30,17 +30,14 @@ import {
TableRow,
} from "@/components/ui/table";
import { useOnboardingStatus, useProjectQuery } from "@/hooks/use-query";
-import { useSubscriptionQuery } from "@/hooks/use-subscription";
import { useTableSort } from "@/hooks/use-table-sort";
import { useDeleteToken, useTokensList } from "@/hooks/use-tokens";
import { ApiError } from "@/lib/api-error";
import { featureFlags } from "@/lib/feature-flags";
-import { PUBLIC_PRICING_URL } from "@/lib/marketing";
import { notify } from "@/lib/notify";
import { localStore } from "@/lib/storage";
import { PROSE, TITLE } from "@/lib/typography";
import { cn } from "@/lib/utils";
-import { PlanEnum } from "@/openapi";
export const Route = createFileRoute("/_auth/projects/$projectId/")({
component: ProjectDetailPage,
@@ -516,10 +513,8 @@ function ProjectMembersCard({ projectId }: { projectId: string }) {
const [emailInput, setEmailInput] = useState("");
const [sentTo, setSentTo] = useState<string | null>(null);
const isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailInput.trim());
- const subscriptionQuery = useSubscriptionQuery();
const meQuery = useOnboardingStatus();
const myUserId = meQuery.data?.id;
- const isPro = subscriptionQuery.data?.plan === PlanEnum.pro;
const {
data: membersData,
@@ -611,45 +606,36 @@ function ProjectMembersCard({ projectId }: { projectId: string }) {
Members
</h2>
<p className={cn(PROSE, "mt-1 text-sm text-muted-foreground")}>
- {isPro
- ? "Add members by email. Emails without an account get a sign-up invitation. Every member can access everything in this project."
- : "Free plan is one seat. Upgrade to Pro to invite teammates."}
+ Add members by email. Emails without an account get a sign-up invitation. Every member can
+ access everything in this project.
</p>
</div>
<div className="space-y-4">
- {isPro ? (
- <div className="flex flex-col gap-2 sm:flex-row sm:items-end">
- <div className="flex-1 space-y-1.5">
- <Label htmlFor="add-user-email">Add by email</Label>
- <Input
- id="add-user-email"
- inputMode="email"
- onChange={(e) => {
- setEmailInput(e.target.value);
- setSentTo(null);
- if (inviteMember.isError) inviteMember.reset();
- }}
- placeholder="[email protected]"
- type="email"
- value={emailInput}
- />
- </div>
- <Button
- className="gap-2"
- disabled={!isValidEmail || inviteMember.isPending}
- onClick={() => inviteMember.mutate(emailInput.trim())}
- >
- <Icon.addUser />
- Add member
- </Button>
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-end">
+ <div className="flex-1 space-y-1.5">
+ <Label htmlFor="add-user-email">Add by email</Label>
+ <Input
+ id="add-user-email"
+ inputMode="email"
+ onChange={(e) => {
+ setEmailInput(e.target.value);
+ setSentTo(null);
+ if (inviteMember.isError) inviteMember.reset();
+ }}
+ placeholder="[email protected]"
+ type="email"
+ value={emailInput}
+ />
</div>
- ) : (
- <Button asChild className="gap-2" variant="outline">
- <a href={PUBLIC_PRICING_URL} rel="noreferrer" target="_blank">
- Upgrade to Pro
- </a>
+ <Button
+ className="gap-2"
+ disabled={!isValidEmail || inviteMember.isPending}
+ onClick={() => inviteMember.mutate(emailInput.trim())}
+ >
+ <Icon.addUser />
+ Add member
</Button>
- )}
+ </div>
{inviteError?.code === "user_not_found" ? (
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-3 rounded-md border border-border bg-wash-raised px-4 py-3">
diff --git a/frontend/src/routes/_auth/settings.tsx b/frontend/src/routes/_auth/settings.tsx
index 3af79cf1..0b844d88 100644
--- a/frontend/src/routes/_auth/settings.tsx
+++ b/frontend/src/routes/_auth/settings.tsx
@@ -1,6 +1,5 @@
-import { useCallback, useEffect } from "react";
+import { useCallback, useEffect, useRef } from "react";
-import { useQueryClient } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
import { toast } from "sonner";
import * as z from "zod";
@@ -11,16 +10,14 @@ import { BillingLedgerTable } from "@/components/billing/billing-ledger-table";
import { Icon } from "@/components/ui/icons";
import { PageHeader } from "@/components/ui/page-header";
import { PageShell } from "@/components/ui/page-shell";
-import {
- billingLedgerQueryKey,
- subscriptionQueryKey,
- useCommercialBilling,
-} from "@/hooks/use-subscription";
+import { useCommercialBilling, useConfirmTopUp } from "@/hooks/use-billing-account";
+import { errorMessage } from "@/lib/notify";
import { PROSE, TITLE } from "@/lib/typography";
const settingsSearchSchema = z.object({
billing: z.string().optional(),
projectId: z.string().optional(),
+ session_id: z.string().optional(),
});
export const Route = createFileRoute("/_auth/settings")({
@@ -31,43 +28,47 @@ export const Route = createFileRoute("/_auth/settings")({
function SettingsPage() {
const settingsSearch = Route.useSearch();
const navigate = Route.useNavigate();
- const queryClient = useQueryClient();
const { enabled: commercial } = useCommercialBilling();
+ const { mutate: confirmTopUp } = useConfirmTopUp();
+ const confirmed = useRef<string | null>(null);
- const autoCheckout = settingsSearch.billing === "checkout";
-
- const handleAutoCheckoutStarted = useCallback(() => {
- navigate({
- replace: true,
- search: (prev) => ({ ...prev, billing: undefined }),
- });
- }, [navigate]);
+ // The webhook grants a payment whose return confirmation failed, so a retry is
+ // offered rather than required.
+ const confirmReturn = useCallback(
+ (sessionId: string) =>
+ confirmTopUp(sessionId, {
+ onError: (err) =>
+ toast.error(errorMessage(err, "Could not confirm the payment"), {
+ action: { label: "Retry", onClick: () => confirmReturn(sessionId) },
+ id: "topup-confirm",
+ }),
+ onSuccess: ({ paid }) => {
+ toast.success(
+ paid ? "Credits added." : "Payment pending. Credits follow when it clears.",
+ { id: "topup-confirm" }
+ );
+ },
+ }),
+ [confirmTopUp]
+ );
useEffect(() => {
- // Stripe returns `success` from plan checkout and `topup` from a credit
- // purchase. The webhook, not this redirect, writes the balance and plan.
- const billing = settingsSearch.billing;
- if (billing !== "success" && billing !== "topup") return;
- toast.success(
- billing === "topup"
- ? "Payment received. Your credits will appear shortly."
- : "Payment received. Your plan will update shortly."
- );
- void queryClient.invalidateQueries({ queryKey: subscriptionQueryKey });
- void queryClient.invalidateQueries({ queryKey: billingLedgerQueryKey });
+ const { billing, session_id: sessionId } = settingsSearch;
+ if (!billing) return;
navigate({
replace: true,
- search: (prev) => ({ ...prev, billing: undefined }),
+ search: (prev) => ({ ...prev, billing: undefined, session_id: undefined }),
});
- }, [settingsSearch.billing, navigate, queryClient]);
+ if (billing !== "topup" || !sessionId || confirmed.current === sessionId) return;
+ confirmed.current = sessionId;
+ confirmReturn(sessionId);
+ }, [settingsSearch, navigate, confirmReturn]);
return (
<PageShell
header={
<PageHeader
- description={
- commercial ? "Manage your plan, credits and usage." : "Usage across all projects."
- }
+ description={commercial ? "Credits and usage." : "Usage across all projects."}
icon={<Icon.settings aria-hidden className="size-6 shrink-0" />}
title="Settings"
/>
@@ -82,14 +83,11 @@ function SettingsPage() {
</h2>
<p className={`${PROSE} mt-1 text-sm text-muted-foreground`}>
{commercial
- ? "Plan, credits and usage. Shared across all projects."
+ ? "Credits and usage. Shared across all projects."
: "Shared across all projects."}
</p>
</div>
- <AccountBand
- autoCheckout={autoCheckout}
- onAutoCheckoutStarted={handleAutoCheckoutStarted}
- />
+ <AccountBand />
</div>
<BillingLedgerTable />
</section>
diff --git a/overbae/admin.py b/overbae/admin.py
index 7ed6ebfd..f4a3fcf3 100644
--- a/overbae/admin.py
+++ b/overbae/admin.py
@@ -18,7 +18,6 @@ from overbae.models import (
SignalEvent,
SignalSubscription,
Span,
- Subscription,
User,
UserOnboarding,
)
@@ -85,29 +84,6 @@ class APITokenAdmin(admin.ModelAdmin):
readonly_fields = ["id", "prefix", "token_hash", "created_at"]
[email protected](Subscription)
-class SubscriptionAdmin(admin.ModelAdmin):
- list_display = [
- "user",
- "status",
- "cancel_at_period_end",
- "start_date",
- "end_date",
- "stripe_subscription_id",
- "updated_at",
- ]
- list_filter = ["status", "cancel_at_period_end"]
- search_fields = [
- "user__email",
- "user__stripe_customer_id",
- "stripe_subscription_id",
- "stripe_price_id",
- "last_stripe_invoice_id",
- ]
- readonly_fields = ["id", "created_at", "updated_at"]
- raw_id_fields = ["user"]
-
-
@admin.register(BillingTelemetry)
class BillingTelemetryAdmin(admin.ModelAdmin):
list_display = ["user", "service", "amount", "project", "timestamp", "idempotency_key"]
diff --git a/overbae/api/auth_registration.py b/overbae/api/auth_registration.py
index 117c13ad..0a78b72c 100644
--- a/overbae/api/auth_registration.py
+++ b/overbae/api/auth_registration.py
@@ -11,7 +11,7 @@ from rest_framework_simplejwt.tokens import RefreshToken
from overbae.api.serializers import UserOnboardingSerializer
from overbae.auth import clerk_enabled
-from overbae.models import SignOnMethod, Subscription, User, UserOnboarding
+from overbae.models import SignOnMethod, User, UserOnboarding
from overbae.services.feedback import set_agent_feedback
@@ -38,9 +38,7 @@ class LocalSessionSerializer(serializers.Serializer):
class UserMeSerializer(serializers.ModelSerializer):
has_completed_onboarding = serializers.SerializerMethodField()
billing_enabled = serializers.SerializerMethodField()
- plan = serializers.SerializerMethodField()
credits_usd = serializers.SerializerMethodField()
- subscription_end = serializers.SerializerMethodField()
class Meta:
model = User
@@ -52,9 +50,7 @@ class UserMeSerializer(serializers.ModelSerializer):
"has_completed_onboarding",
"is_guest",
"billing_enabled",
- "plan",
"credits_usd",
- "subscription_end",
"agent_feedback",
]
extra_kwargs = {
@@ -82,24 +78,12 @@ class UserMeSerializer(serializers.ModelSerializer):
return get_billing().enabled
- def get_plan(self, user: User) -> str:
- from overbae.services.plan_limits import is_pro
-
- return "pro" if is_pro(user) else "free"
-
@extend_schema_field(serializers.DecimalField(max_digits=12, decimal_places=4))
def get_credits_usd(self, user: User):
from overbae.services.billing_ledger import balance_usd
return balance_usd(user)
- @extend_schema_field(serializers.DateTimeField(allow_null=True))
- def get_subscription_end(self, user: User):
- try:
- return user.subscription.end_date
- except Subscription.DoesNotExist:
- return None
-
class AuthTokensResponseSerializer(serializers.Serializer):
access = serializers.CharField()
diff --git a/overbae/api/billing.py b/overbae/api/billing.py
index 357ebba1..47b63b73 100644
--- a/overbae/api/billing.py
+++ b/overbae/api/billing.py
@@ -1,13 +1,9 @@
from __future__ import annotations
import logging
-from datetime import UTC, datetime
-from decimal import Decimal
-from typing import Any
import stripe
from django.conf import settings
-from django.db import transaction
from django.db.models import Case, F, Value, When
from django.db.models.functions import Concat, Replace, Substr, Upper
from drf_spectacular.utils import extend_schema
@@ -19,423 +15,41 @@ from rest_framework.views import APIView
from overbae.api.config import PageNumberPagination
from overbae.api.ordering import TableOrderingFilter
from overbae.api.serializers import (
+ BillingAccountSerializer,
BillingTelemetrySerializer,
CheckoutSessionResponseSerializer,
+ CreditTopUpConfirmationSerializer,
+ CreditTopUpConfirmRequestSerializer,
CreditTopUpRequestSerializer,
- SubscriptionSerializer,
)
-from overbae.models import BillingService, BillingTelemetry, Subscription, SubscriptionStatus, User
-from overbae.services.billing_ledger import (
- CREDITS_PER_USD,
- balance_usd,
- grant_credit_purchase,
- grant_stripe_topup,
- granted_usd,
- spent_usd,
+from overbae.models import BillingService, BillingTelemetry
+from overbae.services.billing_ledger import account_payload
+from overbae.services.credit_purchases import (
+ WEBHOOK_EVENTS,
+ PurchaseUnavailable,
+ SessionNotFound,
+ configure_stripe,
+ confirm_session,
+ create_topup_session,
+ grant_from_session,
)
-from overbae.services.seat_downgrade import enforce_free_seats_after_downgrade
logger = logging.getLogger(__name__)
-def _configure_stripe() -> bool:
- key = (getattr(settings, "STRIPE_SECRET_KEY", "") or "").strip()
- if not key:
- return False
- stripe.api_key = key
- # The SDK's default 80s read timeout parks a web worker per request during a
- # Stripe brownout.
- stripe.max_network_retries = 1
- if getattr(stripe.default_http_client, "_overmind_timeout", None) != 20:
- client = stripe.new_default_http_client(timeout=20)
- client._overmind_timeout = 20
- stripe.default_http_client = client
- return True
-
-
-def _as_dict(obj: Any) -> dict[str, Any]:
- """Stripe SDK objects have no ``.get``; every handler here works on dicts."""
- if obj is None:
- return {}
- if isinstance(obj, dict):
- return obj
- to_dict = getattr(obj, "to_dict", None)
- if callable(to_dict):
- return to_dict()
- try:
- return dict(obj)
- except (TypeError, ValueError):
- return {}
-
-
-def _stripe_id(value: Any) -> str:
- """Normalize a Stripe id that may be a string or expanded object."""
- if not value:
- return ""
- if isinstance(value, str):
- return value
- data = _as_dict(value)
- if data:
- return data.get("id") or ""
- return getattr(value, "id", None) or ""
-
-
-def _invoice_subscription_id(invoice: dict[str, Any]) -> str:
- """Subscription id from invoice (classic field or newer parent.subscription_details)."""
- sub_id = _stripe_id(invoice.get("subscription"))
- if sub_id:
- return sub_id
- parent = _as_dict(invoice.get("parent"))
- details = _as_dict(parent.get("subscription_details"))
- return _stripe_id(details.get("subscription"))
-
-
-def _get_or_create_customer(user: User) -> str:
- if user.stripe_customer_id:
- return user.stripe_customer_id
-
- customer = stripe.Customer.create(
- email=user.email,
- metadata={"user_id": str(user.pk)},
- )
- user.stripe_customer_id = customer.id
- user.save(update_fields=["stripe_customer_id"])
- return customer.id
-
-
-def _set_user_stripe_customer(user: User, customer_id: str) -> None:
- if not customer_id or user.stripe_customer_id == customer_id:
- return
- user.stripe_customer_id = customer_id
- user.save(update_fields=["stripe_customer_id"])
-
-
-def _period_timestamp_from_invoice(invoice: dict[str, Any], key: str) -> datetime | None:
- """Stripe reports the invoice line's period in unix seconds."""
- lines = _as_dict(invoice.get("lines")).get("data") or []
- for line in lines:
- period = _as_dict(_as_dict(line).get("period"))
- value = period.get(key)
- if value:
- return datetime.fromtimestamp(int(value), tz=UTC)
- value = invoice.get(f"period_{key}")
- if value:
- return datetime.fromtimestamp(int(value), tz=UTC)
- return None
-
-
-def _period_end_from_invoice(invoice: dict[str, Any]) -> datetime | None:
- return _period_timestamp_from_invoice(invoice, "end")
-
-
-def _period_start_from_invoice(invoice: dict[str, Any]) -> datetime | None:
- return _period_timestamp_from_invoice(invoice, "start")
-
-
-def _cents_to_usd(raw: Any) -> Decimal:
- """Stripe money fields are integer cents; convert to USD."""
- if raw is None:
- return Decimal("0")
- return (Decimal(int(raw)) / Decimal("100")).quantize(Decimal("0.0001"))
-
-
-def _amount_paid_usd(invoice: dict[str, Any]) -> Decimal:
- return _cents_to_usd(invoice.get("amount_paid"))
-
-
-def _metadata_user_id(obj: Any) -> str:
- metadata = _as_dict(_as_dict(obj).get("metadata"))
- return str(metadata.get("user_id") or "")
-
-
-def _resolve_user_for_invoice(invoice: dict[str, Any]) -> User | None:
- customer_id = _stripe_id(invoice.get("customer"))
- subscription_id = _invoice_subscription_id(invoice)
-
- if subscription_id:
- sub = (
- Subscription.objects.filter(stripe_subscription_id=subscription_id)
- .select_related("user")
- .first()
- )
- if sub:
- return sub.user
-
- if customer_id:
- user = User.objects.filter(stripe_customer_id=customer_id).first()
- if user:
- return user
-
- # First invoice may arrive before we stored stripe_subscription_id — read metadata.
- if subscription_id:
- try:
- stripe_sub = stripe.Subscription.retrieve(subscription_id)
- user_id = _metadata_user_id(stripe_sub)
- if user_id:
- return User.objects.filter(pk=user_id).first()
- except stripe.StripeError:
- logger.exception("Failed to retrieve Stripe subscription %s", subscription_id)
-
- if customer_id:
- try:
- customer = stripe.Customer.retrieve(customer_id)
- user_id = _metadata_user_id(customer)
- if user_id:
- return User.objects.filter(pk=user_id).first()
- except stripe.StripeError:
- logger.exception("Failed to retrieve Stripe customer %s", customer_id)
-
- return None
-
-
-def renew_plan_from_invoice(invoice: Any) -> None:
- """Activates or extends Pro, and grants the invoiced amount as credits."""
- invoice = _as_dict(invoice)
- customer_id = _stripe_id(invoice.get("customer"))
- subscription_id = _invoice_subscription_id(invoice)
- invoice_id = _stripe_id(invoice.get("id"))
-
- # Credit top-ups also produce a paid invoice. Without this guard the
- # customer-id fallback below grants them Pro and double-grants the credits
- # the session handler already granted.
- if not subscription_id:
- logger.info(
- "invoice.paid: no subscription on invoice_id=%s customer=%s — not a plan renewal",
- invoice_id,
- customer_id,
- )
- return
-
- user = _resolve_user_for_invoice(invoice)
-
- if user is None:
- logger.error(
- "invoice.paid: could not resolve user (customer=%s subscription=%s)",
- customer_id,
- subscription_id,
- )
- return
-
- price_id = ""
- lines = _as_dict(invoice.get("lines")).get("data") or []
- if lines:
- price_id = _stripe_id(_as_dict(lines[0]).get("price"))
-
- sub, _ = Subscription.objects.select_for_update().get_or_create(user=user)
-
- if invoice_id and sub.last_stripe_invoice_id == invoice_id:
- logger.info(
- "invoice.paid: already processed invoice_id=%s user_id=%s",
- invoice_id,
- user.pk,
- )
- return
-
- update_fields = ["status", "updated_at"]
-
- sub.status = SubscriptionStatus.ACTIVE
- _set_user_stripe_customer(user, customer_id)
- if subscription_id and sub.stripe_subscription_id != subscription_id:
- sub.stripe_subscription_id = subscription_id
- update_fields.append("stripe_subscription_id")
- if price_id and sub.stripe_price_id != price_id:
- sub.stripe_price_id = price_id
- update_fields.append("stripe_price_id")
-
- period_end = _period_end_from_invoice(invoice)
- if period_end is not None:
- sub.end_date = period_end
- update_fields.append("end_date")
-
- if sub.start_date is None:
- period_start = _period_start_from_invoice(invoice)
- if period_start is not None:
- sub.start_date = period_start
- update_fields.append("start_date")
-
- grant = _amount_paid_usd(invoice)
- if grant and invoice_id:
- grant_stripe_topup(user, grant, invoice_id)
-
- if invoice_id:
- sub.last_stripe_invoice_id = invoice_id
- update_fields.append("last_stripe_invoice_id")
-
- if sub.cancel_at_period_end:
- sub.cancel_at_period_end = False
- update_fields.append("cancel_at_period_end")
-
- # Thin payload — only what period checks read.
- period_start_unix = None
- period_end_unix = None
- if lines:
- period = _as_dict(_as_dict(lines[0]).get("period"))
- period_start_unix = period.get("start")
- period_end_unix = period.get("end")
- sub.payload = {
- "id": subscription_id,
- "customer": customer_id,
- "status": "active",
- "current_period_start": period_start_unix,
- "current_period_end": period_end_unix,
- "last_invoice_id": invoice_id,
- }
- update_fields.append("payload")
-
- sub.save(update_fields=update_fields)
-
- logger.info(
- "Renewed Pro for user_id=%s subscription=%s end_date=%s grant=%s balance=%s",
- user.pk,
- subscription_id,
- period_end,
- grant,
- balance_usd(user),
+def _stripe_failure() -> Response:
+ # Stripe's error text names request ids and account settings; it stays in the log.
+ return Response(
+ {"detail": "Stripe did not answer. Try again."}, status=status.HTTP_502_BAD_GATEWAY
)
-def _subscription_payload(user: User) -> dict:
- from overbae.services.billing_provider import get_billing
- from overbae.services.plan_limits import is_pro, plan_usage_payload
-
- billing = get_billing()
- credits = balance_usd(user)
- granted = granted_usd(user)
- usage = plan_usage_payload(user)
- pro = is_pro(user)
- try:
- sub = user.subscription
- except Subscription.DoesNotExist:
- return {
- "billing_enabled": billing.enabled,
- "plan": "pro" if pro else "free",
- "status": None,
- "credits_usd": credits,
- "credits_granted_usd": granted,
- "credits_spent_usd": spent_usd(user),
- "start_date": None,
- "end_date": None,
- "cancel_at_period_end": False,
- "can_manage_renewal": False,
- "usage": usage,
- }
-
- return {
- "billing_enabled": billing.enabled,
- "plan": "pro" if pro else "free",
- "status": sub.status,
- "credits_usd": credits,
- "credits_granted_usd": granted,
- "credits_spent_usd": spent_usd(user),
- "start_date": sub.start_date,
- "end_date": sub.end_date,
- "cancel_at_period_end": sub.cancel_at_period_end,
- "can_manage_renewal": (
- billing.enabled
- and sub.status == SubscriptionStatus.ACTIVE
- and bool(sub.stripe_subscription_id)
- ),
- "usage": usage,
- }
-
-
-def _stripe_status_to_local(stripe_status: str) -> str | None:
- mapping = {
- "active": SubscriptionStatus.ACTIVE,
- "trialing": SubscriptionStatus.ACTIVE,
- "past_due": SubscriptionStatus.PAST_DUE,
- "canceled": SubscriptionStatus.CANCELED,
- "unpaid": SubscriptionStatus.UNPAID,
- "incomplete": SubscriptionStatus.INCOMPLETE,
- "incomplete_expired": SubscriptionStatus.CANCELED,
- "paused": SubscriptionStatus.CANCELED,
- }
- return mapping.get(stripe_status)
-
-
-def sync_subscription_from_stripe(stripe_sub: Any) -> None:
- stripe_sub = _as_dict(stripe_sub)
- subscription_id = _stripe_id(stripe_sub.get("id"))
- customer_id = _stripe_id(stripe_sub.get("customer"))
- if not subscription_id:
- return
-
- sub = (
- Subscription.objects.select_for_update()
- .filter(stripe_subscription_id=subscription_id)
- .select_related("user")
- .first()
- )
- if sub is None and customer_id:
- user = User.objects.filter(stripe_customer_id=customer_id).first()
- if user is not None:
- sub = (
- Subscription.objects.select_for_update()
- .filter(user=user)
- .select_related("user")
- .first()
- )
- if sub is None:
- logger.warning(
- "Stripe subscription sync: no local row (subscription=%s customer=%s)",
- subscription_id,
- customer_id,
- )
- return
-
- update_fields = ["updated_at"]
- if subscription_id and sub.stripe_subscription_id != subscription_id:
- sub.stripe_subscription_id = subscription_id
- update_fields.append("stripe_subscription_id")
- _set_user_stripe_customer(sub.user, customer_id)
-
- local_status = _stripe_status_to_local(stripe_sub.get("status") or "")
- if local_status and sub.status != local_status:
- sub.status = local_status
- update_fields.append("status")
-
- cancel_at_period_end = bool(stripe_sub.get("cancel_at_period_end"))
- if sub.cancel_at_period_end != cancel_at_period_end:
- sub.cancel_at_period_end = cancel_at_period_end
- update_fields.append("cancel_at_period_end")
-
- period_end = stripe_sub.get("current_period_end")
- if period_end:
- end_date = datetime.fromtimestamp(int(period_end), tz=UTC)
- if sub.end_date != end_date:
- sub.end_date = end_date
- update_fields.append("end_date")
-
- # Thin, JSON-safe copy — the full Stripe object is not serialisable.
- sub.payload = {
- "id": subscription_id,
- "customer": customer_id,
- "status": stripe_sub.get("status"),
- "cancel_at_period_end": cancel_at_period_end,
- "current_period_end": period_end,
- "current_period_start": stripe_sub.get("current_period_start"),
- }
- update_fields.append("payload")
-
- sub.save(update_fields=update_fields)
-
- user = sub.user
- if sub.status == SubscriptionStatus.CANCELED:
- enforce_free_seats_after_downgrade(user)
-
-
-class SubscriptionView(APIView):
+class BillingAccountView(APIView):
permission_classes = [IsAuthenticated]
- @extend_schema(
- summary="Get subscription",
- responses={200: SubscriptionSerializer},
- )
+ @extend_schema(summary="Get the credits account", responses={200: BillingAccountSerializer})
def get(self, request):
- data = SubscriptionSerializer(_subscription_payload(request.user)).data
- return Response(data)
+ return Response(BillingAccountSerializer(account_payload(request.user)).data)
class BillingLedgerView(generics.ListAPIView):
@@ -474,308 +88,54 @@ class BillingLedgerView(generics.ListAPIView):
)
-class CancelSubscriptionView(APIView):
- permission_classes = [IsAuthenticated]
-
- @extend_schema(
- summary="Cancel subscription at period end",
- request=None,
- responses={200: SubscriptionSerializer},
- )
- def post(self, request):
- if not _configure_stripe():
- return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
-
- try:
- sub = request.user.subscription
- except Subscription.DoesNotExist:
- return Response(
- {"detail": "No subscription found."},
- status=status.HTTP_404_NOT_FOUND,
- )
-
- if sub.status != SubscriptionStatus.ACTIVE:
- return Response(
- {"detail": "Only an active subscription can be cancelled."},
- status=status.HTTP_400_BAD_REQUEST,
- )
- if not sub.stripe_subscription_id:
- return Response(
- {"detail": "Subscription is not linked to Stripe."},
- status=status.HTTP_400_BAD_REQUEST,
- )
- if sub.cancel_at_period_end:
- data = SubscriptionSerializer(_subscription_payload(request.user)).data
- return Response(data)
-
- try:
- stripe.Subscription.modify(sub.stripe_subscription_id, cancel_at_period_end=True)
- except stripe.StripeError as exc:
- logger.exception("Stripe cancel failed for user_id=%s", request.user.pk)
- message = getattr(exc, "user_message", None) or str(exc) or "Stripe error."
- return Response({"detail": message}, status=status.HTTP_502_BAD_GATEWAY)
-
- sub.cancel_at_period_end = True
- sub.save(update_fields=["cancel_at_period_end", "updated_at"])
- data = SubscriptionSerializer(_subscription_payload(request.user)).data
- return Response(data)
-
-
-class RenewSubscriptionView(APIView):
- permission_classes = [IsAuthenticated]
-
- @extend_schema(
- summary="Resume subscription auto-renewal",
- request=None,
- responses={200: SubscriptionSerializer},
- )
- def post(self, request):
- if not _configure_stripe():
- return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
-
- try:
- sub = request.user.subscription
- except Subscription.DoesNotExist:
- return Response(
- {"detail": "No subscription found."},
- status=status.HTTP_404_NOT_FOUND,
- )
-
- if sub.status != SubscriptionStatus.ACTIVE:
- return Response(
- {
- "detail": (
- "Only an active subscription can be renewed. Buy Pro again to resubscribe."
- )
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
- if not sub.stripe_subscription_id:
- return Response(
- {"detail": "Subscription is not linked to Stripe."},
- status=status.HTTP_400_BAD_REQUEST,
- )
- if not sub.cancel_at_period_end:
- data = SubscriptionSerializer(_subscription_payload(request.user)).data
- return Response(data)
-
- try:
- stripe.Subscription.modify(sub.stripe_subscription_id, cancel_at_period_end=False)
- except stripe.StripeError as exc:
- logger.exception("Stripe renew failed for user_id=%s", request.user.pk)
- message = getattr(exc, "user_message", None) or str(exc) or "Stripe error."
- return Response({"detail": message}, status=status.HTTP_502_BAD_GATEWAY)
-
- sub.cancel_at_period_end = False
- sub.save(update_fields=["cancel_at_period_end", "updated_at"])
- data = SubscriptionSerializer(_subscription_payload(request.user)).data
- return Response(data)
-
-
-class CheckoutSessionView(APIView):
+class CreditTopUpView(APIView):
permission_classes = [IsAuthenticated]
@extend_schema(
- summary="Create Stripe Checkout Session",
- request=None,
+ summary="Buy credits (one-time Stripe Checkout)",
+ request=CreditTopUpRequestSerializer,
responses={200: CheckoutSessionResponseSerializer},
)
def post(self, request):
- if not _configure_stripe():
+ if not configure_stripe():
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
-
- price_id = (getattr(settings, "STRIPE_PRO_PRICE_ID", "") or "").strip()
- if not price_id:
- return Response(
- {"detail": "Stripe price is not configured."},
- status=status.HTTP_503_SERVICE_UNAVAILABLE,
- )
-
- try:
- existing = request.user.subscription
- except Subscription.DoesNotExist:
- existing = None
- if existing and existing.status == SubscriptionStatus.ACTIVE:
- if existing.cancel_at_period_end:
- return Response(
- {
- "detail": (
- "Your plan is set to cancel at period end. Resume auto-renewal instead."
- )
- },
- status=status.HTTP_400_BAD_REQUEST,
- )
- return Response(
- {"detail": "You already have an active Pro subscription."},
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- frontend = (getattr(settings, "FRONTEND_URL", "") or "http://localhost:5173").rstrip("/")
- user = request.user
-
+ payload = CreditTopUpRequestSerializer(data=request.data)
+ payload.is_valid(raise_exception=True)
try:
- customer_id = _get_or_create_customer(user)
- session = stripe.checkout.Session.create(
- mode="subscription",
- customer=customer_id,
- line_items=[{"price": price_id, "quantity": 1}],
- success_url=f"{frontend}/settings?billing=success",
- cancel_url=f"{frontend}/settings?billing=cancel",
- client_reference_id=str(user.pk),
- metadata={"user_id": str(user.pk)},
- subscription_data={"metadata": {"user_id": str(user.pk)}},
- )
- except stripe.StripeError as exc:
- logger.exception("Stripe checkout session create failed for user_id=%s", user.pk)
- message = getattr(exc, "user_message", None) or str(exc) or "Stripe error."
- return Response({"detail": message}, status=status.HTTP_502_BAD_GATEWAY)
-
- if not session.url:
+ url = create_topup_session(request.user, payload.validated_data["amount_usd"])
+ except PurchaseUnavailable:
return Response(
- {"detail": "Stripe did not return a checkout URL."},
- status=status.HTTP_502_BAD_GATEWAY,
+ {"detail": "Credit purchases are not configured."},
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
)
+ except stripe.StripeError:
+ logger.exception("Stripe top-up session create failed for user_id=%s", request.user.pk)
+ return _stripe_failure()
+ return Response(CheckoutSessionResponseSerializer({"checkout_url": url}).data)
- data = CheckoutSessionResponseSerializer({"checkout_url": session.url}).data
- return Response(data)
-
-
-CREDIT_TOPUP_PURPOSE = "credit-topup"
-
-
-class CreditTopUpView(APIView):
- """Open on every plan, unlike the Pro checkout — running out of credits is
- orthogonal to which plan you are on."""
+class CreditTopUpConfirmView(APIView):
permission_classes = [IsAuthenticated]
@extend_schema(
- summary="Buy credits (one-time Stripe Checkout)",
- request=CreditTopUpRequestSerializer,
- responses={200: CheckoutSessionResponseSerializer},
+ summary="Confirm a credit purchase after Stripe Checkout",
+ request=CreditTopUpConfirmRequestSerializer,
+ responses={200: CreditTopUpConfirmationSerializer},
)
def post(self, request):
- if not _configure_stripe():
+ if not configure_stripe():
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
-
- price_id = (getattr(settings, "STRIPE_CREDIT_PRICE_ID", "") or "").strip()
- if not price_id:
- return Response(
- {"detail": "Credit price is not configured."},
- status=status.HTTP_503_SERVICE_UNAVAILABLE,
- )
-
- payload = CreditTopUpRequestSerializer(data=request.data)
+ payload = CreditTopUpConfirmRequestSerializer(data=request.data)
payload.is_valid(raise_exception=True)
- amount_usd = payload.validated_data["amount_usd"]
- # The Stripe price is one credit at $0.01, so quantity is the credit count.
- credit_quantity = amount_usd * CREDITS_PER_USD
-
- frontend = (getattr(settings, "FRONTEND_URL", "") or "http://localhost:5173").rstrip("/")
- user = request.user
- metadata = {
- "user_id": str(user.pk),
- "purpose": CREDIT_TOPUP_PURPOSE,
- "amount_usd": str(amount_usd),
- "credits": str(credit_quantity),
- }
-
try:
- customer_id = _get_or_create_customer(user)
- session = stripe.checkout.Session.create(
- mode="payment",
- customer=customer_id,
- line_items=[{"price": price_id, "quantity": credit_quantity}],
- success_url=f"{frontend}/settings?billing=topup",
- cancel_url=f"{frontend}/settings?billing=cancel",
- client_reference_id=str(user.pk),
- metadata=metadata,
- payment_intent_data={"metadata": metadata},
- )
- except stripe.StripeError as exc:
- logger.exception("Stripe top-up session create failed for user_id=%s", user.pk)
- message = getattr(exc, "user_message", None) or str(exc) or "Stripe error."
- return Response({"detail": message}, status=status.HTTP_502_BAD_GATEWAY)
-
- if not session.url:
- return Response(
- {"detail": "Stripe did not return a checkout URL."},
- status=status.HTTP_502_BAD_GATEWAY,
- )
-
- data = CheckoutSessionResponseSerializer({"checkout_url": session.url}).data
- return Response(data)
-
-
-def _user_by_pk(raw_id: Any) -> User | None:
- """Tolerant pk lookup: a malformed id must not 500 (Stripe would retry forever)."""
- try:
- return User.objects.filter(pk=raw_id).first()
- except (TypeError, ValueError):
- logger.warning("Ignoring malformed user id from Stripe payload: %r", raw_id)
- return None
-
-
-def _resolve_user_for_session(session: dict[str, Any]) -> User | None:
- """Precedence: client_reference_id, then metadata, then the customer id."""
- for raw_id in (session.get("client_reference_id"), _metadata_user_id(session)):
- if raw_id:
- user = _user_by_pk(raw_id)
- if user:
- return user
-
- customer_id = _stripe_id(session.get("customer"))
- if customer_id:
- return User.objects.filter(stripe_customer_id=customer_id).first()
- return None
-
-
-def grant_credits_from_checkout_session(session: Any) -> None:
- session = _as_dict(session)
- session_id = _stripe_id(session.get("id"))
-
- if _as_dict(session.get("metadata")).get("purpose") != CREDIT_TOPUP_PURPOSE:
- logger.debug("checkout.session.completed: not a credit top-up (session=%s)", session_id)
- return
-
- # Async payment methods complete the session before the money lands.
- payment_status = session.get("payment_status")
- if payment_status != "paid":
- logger.info(
- "checkout.session.completed: session=%s not paid yet (payment_status=%s)",
- session_id,
- payment_status,
- )
- return
-
- user = _resolve_user_for_session(session)
- if user is None:
- logger.error(
- "checkout.session.completed: could not resolve user (session=%s customer=%s)",
- session_id,
- _stripe_id(session.get("customer")),
- )
- return
-
- # Trust amount_total over request metadata: it is what Stripe actually charged.
- amount = _cents_to_usd(session.get("amount_total"))
- if amount <= 0:
- logger.error("checkout.session.completed: session=%s has no amount_total", session_id)
- return
-
- _set_user_stripe_customer(user, _stripe_id(session.get("customer")))
- entry = grant_credit_purchase(user, amount, session_id)
- if entry is None:
- logger.info("checkout.session.completed: session=%s already granted", session_id)
- return
-
- logger.info(
- "Credit top-up granted user_id=%s session=%s amount=%s balance=%s",
- user.pk,
- session_id,
- amount,
- balance_usd(user),
- )
+ paid = confirm_session(request.user, payload.validated_data["session_id"])
+ except SessionNotFound:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ except stripe.StripeError:
+ logger.exception("Stripe session confirm failed for user_id=%s", request.user.pk)
+ return _stripe_failure()
+ data = {"paid": paid, "account": account_payload(request.user)}
+ return Response(CreditTopUpConfirmationSerializer(data).data)
class StripeWebhookView(APIView):
@@ -784,7 +144,7 @@ class StripeWebhookView(APIView):
@extend_schema(exclude=True)
def post(self, request):
- if not _configure_stripe():
+ if not configure_stripe():
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
webhook_secret = (getattr(settings, "STRIPE_WEBHOOK_SECRET", "") or "").strip()
@@ -795,42 +155,22 @@ class StripeWebhookView(APIView):
status=status.HTTP_503_SERVICE_UNAVAILABLE,
)
- payload = request.body
sig_header = request.headers.get("Stripe-Signature", "")
-
try:
- event = stripe.Webhook.construct_event(payload, sig_header, webhook_secret)
+ event = stripe.Webhook.construct_event(request.body, sig_header, webhook_secret)
except ValueError:
return Response({"detail": "Invalid payload."}, status=status.HTTP_400_BAD_REQUEST)
except stripe.SignatureVerificationError:
return Response({"detail": "Invalid signature."}, status=status.HTTP_401_UNAUTHORIZED)
- event_type = event["type"]
- data_object = _as_dict(event["data"]["object"])
-
+ if event["type"] not in WEBHOOK_EVENTS:
+ return Response(status=status.HTTP_204_NO_CONTENT)
try:
- if event_type == "invoice.paid":
- renew_plan_from_invoice(data_object)
- elif event_type in (
- "checkout.session.completed",
- # Delayed methods leave the completed session unpaid, so this is
- # where the money actually arrives. Granting is keyed on the
- # session id, so handling both can only ever credit once.
- "checkout.session.async_payment_succeeded",
- ):
- grant_credits_from_checkout_session(data_object)
- elif event_type in (
- "customer.subscription.updated",
- "customer.subscription.deleted",
- ):
- sync_subscription_from_stripe(data_object)
- else:
- logger.debug("Stripe webhook ignored event: %s", event_type)
+ grant_from_session(event["data"]["object"])
except Exception:
- logger.exception("%s handler failed", event_type)
+ logger.exception("%s handler failed", event["type"])
return Response(
{"detail": "Webhook handling error."},
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
-
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/overbae/api/exception_handler.py b/overbae/api/exception_handler.py
index 675abe16..6e54aa23 100644
--- a/overbae/api/exception_handler.py
+++ b/overbae/api/exception_handler.py
@@ -25,7 +25,7 @@ def api_exception_handler(exc, context):
flat = " ".join(str(item) for item in response.data if item)
response.data = {"detail": flat or "Invalid request."}
elif isinstance(response.data, dict) and "code" not in response.data:
- # The client distinguishes e.g. seat_limit_exceeded from
+ # The client distinguishes e.g. guest_upgrade_required from
# permission_denied by this code, not by the shared 403.
code = getattr(response.data.get("detail"), "code", None)
if code:
diff --git a/overbae/api/overwatch_dashboard.py b/overbae/api/overwatch_dashboard.py
index fcb6d9d3..e1b8702f 100644
--- a/overbae/api/overwatch_dashboard.py
+++ b/overbae/api/overwatch_dashboard.py
@@ -70,12 +70,9 @@ class OverviewSerializer(serializers.Serializer):
top_base_models = BaseModelUsageSerializer(many=True)
live_deployments = serializers.IntegerField()
inference_calls = DailyCountSerializer(many=True)
- subscriptions = serializers.DictField(child=serializers.IntegerField())
paying_users = serializers.IntegerField()
- cancelling_users = serializers.IntegerField()
- free_users = serializers.IntegerField()
low_balance_users = serializers.IntegerField()
- topups_usd = DailyUsdSerializer(many=True)
+ purchases_usd = DailyUsdSerializer(many=True)
spend_usd = DailyUsdSerializer(many=True)
spend_by_service = serializers.DictField(
child=serializers.DecimalField(max_digits=14, decimal_places=7)
@@ -113,15 +110,14 @@ class UserSerializer(serializers.Serializer):
date_joined = serializers.DateTimeField()
sign_on_method = serializers.CharField()
projects = serializers.IntegerField()
- seats = serializers.IntegerField()
+ members = serializers.IntegerField()
last_span_at = serializers.DateTimeField(allow_null=True)
spans = serializers.IntegerField()
training_jobs = serializers.IntegerField()
live_deployments = serializers.IntegerField()
stage = serializers.SerializerMethodField()
- subscription_status = serializers.CharField(allow_null=True)
spend_usd = serializers.DecimalField(max_digits=14, decimal_places=7)
- topups_usd = serializers.DecimalField(max_digits=14, decimal_places=7)
+ purchases_usd = serializers.DecimalField(max_digits=14, decimal_places=7)
balance_usd = serializers.DecimalField(max_digits=14, decimal_places=7)
def get_stage(self, account) -> str:
@@ -181,12 +177,11 @@ class WorkflowActivitySerializer(serializers.Serializer):
class BillingActivitySerializer(serializers.Serializer):
- subscription_status = serializers.CharField(allow_null=True)
spend_usd = serializers.DecimalField(max_digits=14, decimal_places=7)
- topups_usd = serializers.DecimalField(max_digits=14, decimal_places=7)
+ purchases_usd = serializers.DecimalField(max_digits=14, decimal_places=7)
balance_usd = serializers.DecimalField(max_digits=14, decimal_places=7)
spend_daily = DailyUsdSerializer(many=True)
- topups_daily = DailyUsdSerializer(many=True)
+ purchases_daily = DailyUsdSerializer(many=True)
class UserActivitySerializer(serializers.Serializer):
@@ -211,7 +206,7 @@ def _cached(request, compute, *, database: bool = True) -> Response:
fingerprint = hashlib.sha256(
f"{request.path}?{urlencode(sorted(request.query_params.items()))}".encode()
).hexdigest()
- key = f"overwatch:v2:{fingerprint}"
+ key = f"overwatch:v3:{fingerprint}"
payload = cache.get(key)
if payload is None:
computed_at = timezone.now()
@@ -291,14 +286,13 @@ class UsersView(OverwatchView, generics.ListAPIView):
"date_joined",
"email",
"projects",
- "seats",
+ "members",
"last_span_at",
"spans",
"training_jobs",
"live_deployments",
- "subscription_status",
"spend_usd",
- "topups_usd",
+ "purchases_usd",
"balance_usd",
]
ordering = ["-date_joined"]
diff --git a/overbae/api/serializers.py b/overbae/api/serializers.py
index c3d51a95..12825003 100644
--- a/overbae/api/serializers.py
+++ b/overbae/api/serializers.py
@@ -2585,34 +2585,28 @@ class CheckoutSessionResponseSerializer(serializers.Serializer):
checkout_url = serializers.URLField()
-class PlanUsageUnitSerializer(serializers.Serializer):
- limit = serializers.IntegerField(allow_null=True)
-
-
-class PlanUsageSerializer(serializers.Serializer):
- seats = PlanUsageUnitSerializer()
-
-
class CreditTopUpRequestSerializer(serializers.Serializer):
"""One-time credit purchase in whole dollars. 1 USD = 100 credits."""
amount_usd = serializers.IntegerField(min_value=MIN_TOPUP_USD, max_value=MAX_TOPUP_USD)
-class SubscriptionSerializer(serializers.Serializer):
- """Current plan / subscription state for the authenticated user."""
+class CreditTopUpConfirmRequestSerializer(serializers.Serializer):
+ session_id = serializers.RegexField(r"^cs_(live|test)_[A-Za-z0-9]{1,240}$")
+
+
+class BillingAccountSerializer(serializers.Serializer):
+ """Credits balance for the authenticated user."""
billing_enabled = serializers.BooleanField()
- plan = serializers.ChoiceField(choices=["free", "pro"])
- status = serializers.CharField(allow_null=True)
credits_usd = serializers.DecimalField(max_digits=12, decimal_places=4)
credits_granted_usd = serializers.DecimalField(max_digits=12, decimal_places=4)
credits_spent_usd = serializers.DecimalField(max_digits=12, decimal_places=4)
- start_date = serializers.DateTimeField(allow_null=True)
- end_date = serializers.DateTimeField(allow_null=True)
- cancel_at_period_end = serializers.BooleanField()
- can_manage_renewal = serializers.BooleanField()
- usage = PlanUsageSerializer()
+
+
+class CreditTopUpConfirmationSerializer(serializers.Serializer):
+ paid = serializers.BooleanField()
+ account = BillingAccountSerializer()
class BillingTelemetrySerializer(serializers.ModelSerializer):
diff --git a/overbae/api/views.py b/overbae/api/views.py
index 07f46517..00fd4278 100644
--- a/overbae/api/views.py
+++ b/overbae/api/views.py
@@ -254,10 +254,6 @@ class ProjectMembershipViewSet(
serializer = ProjectMembershipCreateSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.get_user()
- if not ProjectMembership.objects.filter(project=project, user=user).exists():
- from overbae.services.plan_limits import require_seat_for_invite
-
- require_seat_for_invite(request.user, project)
membership, _ = ProjectMembership.objects.get_or_create(project=project, user=user)
return Response(
ProjectMemberSerializer(membership).data,
@@ -319,7 +315,6 @@ class ProjectInviteViewSet(
def create(self, request, *args, **kwargs):
from overbae.auth import clerk_enabled
- from overbae.services.plan_limits import require_seat_for_invite
from overbae.services.project_invites import create_clerk_invitation
project = self._project()
@@ -339,7 +334,6 @@ class ProjectInviteViewSet(
if existing:
return Response(ProjectInviteSerializer(existing).data, status=status.HTTP_201_CREATED)
- require_seat_for_invite(request.user, project)
clerk_invitation_id = ""
if clerk_enabled():
try:
diff --git a/overbae/management/commands/grant_credits.py b/overbae/management/commands/grant_credits.py
index 4a9f416e..55fb5b68 100644
--- a/overbae/management/commands/grant_credits.py
+++ b/overbae/management/commands/grant_credits.py
@@ -55,7 +55,7 @@ class Command(BaseCommand):
entry = append_entry(
user=user,
amount=amount_usd,
- service=BillingService.STRIPE_TOPUP,
+ service=BillingService.GRANT,
idempotency_key=options["key"],
metadata={"granted_by": "grant_credits", "reason": options["reason"]},
)
diff --git a/overbae/management/commands/seed_demo.py b/overbae/management/commands/seed_demo.py
index 6a29abfa..744eacb9 100644
--- a/overbae/management/commands/seed_demo.py
+++ b/overbae/management/commands/seed_demo.py
@@ -676,7 +676,7 @@ class Command(BaseCommand):
clerk_user_id=f"user_{hashlib.sha256(email.encode()).hexdigest()[:24]}",
)
User.objects.filter(pk=u.pk).update(date_joined=days_ago(joined_days_ago))
- BillingTelemetry.objects.filter(user=u, service=BillingService.FREE_CREDITS).update(
+ BillingTelemetry.objects.filter(user=u, service=BillingService.GRANT).update(
timestamp=days_ago(joined_days_ago)
)
return u
@@ -3948,7 +3948,7 @@ class Command(BaseCommand):
row = BillingTelemetry.objects.create(
user=owner,
amount=Decimal("50.0000000"),
- service=BillingService.STRIPE_TOPUP,
+ service=BillingService.PURCHASE,
idempotency_key="topup:cs_live_seed_a1B2c3",
metadata={"checkout_session_id": "cs_live_seed_a1B2c3"},
)
diff --git a/overbae/management/commands/sync_stripe_webhook.py b/overbae/management/commands/sync_stripe_webhook.py
new file mode 100644
index 00000000..90079172
--- /dev/null
+++ b/overbae/management/commands/sync_stripe_webhook.py
@@ -0,0 +1,27 @@
+"""Set the Stripe webhook endpoint's events to the ones credit purchases need.
+
+Run it once per environment after a deploy that changes ``WEBHOOK_EVENTS``:
+``manage.py sync_stripe_webhook --url https://<api host>/api/billing/webhook/``.
+"""
+
+from __future__ import annotations
+
+from django.core.management.base import BaseCommand, CommandError
+
+from overbae.services.credit_purchases import configure_stripe, sync_webhook_endpoint
+
+
+class Command(BaseCommand):
+ help = "Set the Stripe webhook endpoint's events to the credit purchase events."
+
+ def add_arguments(self, parser):
+ parser.add_argument("--url", required=True, help="The endpoint URL registered in Stripe.")
+
+ def handle(self, *args, **options):
+ if not configure_stripe():
+ raise CommandError("STRIPE_SECRET_KEY is not set.")
+ try:
+ events = sync_webhook_endpoint(options["url"])
+ except LookupError as exc:
+ raise CommandError(str(exc)) from exc
+ self.stdout.write(f"{options['url']}: {', '.join(events)}")
diff --git a/overbae/migrations/0068_credits_only.py b/overbae/migrations/0068_credits_only.py
new file mode 100644
index 00000000..5ce81291
--- /dev/null
+++ b/overbae/migrations/0068_credits_only.py
@@ -0,0 +1,51 @@
+from django.db import migrations, models
+from django.db.models import F, Value
+from django.db.models.functions import Concat, Substr
+
+# Only live-mode Checkout sessions carried real money. Every other credit row,
+# including test-mode sessions and subscription invoices, was handed out for free.
+LIVE_PURCHASE_PREFIX = "topup:cs_live_"
+SIGNUP_PREFIX = "free-credits:"
+
+
+def label_credit_rows(apps, schema_editor):
+ BillingTelemetry = apps.get_model("overbae", "BillingTelemetry")
+ rows = BillingTelemetry.objects.using(schema_editor.connection.alias)
+ rows.filter(service="stripe-topup", idempotency_key__startswith=LIVE_PURCHASE_PREFIX).update(
+ service="purchase"
+ )
+ rows.filter(service="stripe-topup").update(service="grant")
+ rows.filter(service="free-credits", idempotency_key__startswith=SIGNUP_PREFIX).update(
+ idempotency_key=Concat(
+ Value("signup:"),
+ Substr(F("idempotency_key"), len(SIGNUP_PREFIX) + 1),
+ output_field=models.CharField(),
+ )
+ )
+ rows.filter(service="free-credits").update(service="grant")
+
+
+class Migration(migrations.Migration):
+ dependencies = [("overbae", "0067_delete_retired_beat_tasks")]
+
+ operations = [
+ migrations.AlterField(
+ model_name="billingtelemetry",
+ name="service",
+ field=models.CharField(
+ choices=[
+ ("grant", "Grant"),
+ ("purchase", "Purchase"),
+ ("finetuning-job", "Finetuning job"),
+ ("inference", "Inference"),
+ ("inference-ft-model", "Fine-tuned inference"),
+ ("dedicated-inference", "Dedicated inference"),
+ ("data-workshop", "Data workshop"),
+ ("evaluation", "Evaluation"),
+ ],
+ max_length=32,
+ ),
+ ),
+ migrations.RunPython(label_credit_rows, migrations.RunPython.noop),
+ migrations.DeleteModel(name="Subscription"),
+ ]
diff --git a/overbae/models/__init__.py b/overbae/models/__init__.py
index 4911b9f3..395587df 100644
--- a/overbae/models/__init__.py
+++ b/overbae/models/__init__.py
@@ -4,7 +4,7 @@ from .assistant import (
AssistantInput,
AssistantThread,
)
-from .billing import BillingService, BillingTelemetry, Subscription, SubscriptionStatus
+from .billing import BillingService, BillingTelemetry
from .capabilities import Capability, IdentityAlias, Prompt
from .connectors import ConnectorCredential, ConnectorSyncConfig, ConnectorSyncRun
from .dataset_admission import DatasetLandingWork
@@ -112,8 +112,6 @@ __all__ = [
"IdentityAlias",
"BillingService",
"BillingTelemetry",
- "Subscription",
- "SubscriptionStatus",
"ConnectorCredential",
"ConnectorSyncConfig",
"ConnectorSyncRun",
diff --git a/overbae/models/billing.py b/overbae/models/billing.py
index 27a7aed6..302e4ed1 100644
--- a/overbae/models/billing.py
+++ b/overbae/models/billing.py
@@ -7,8 +7,8 @@ from django.db import models
class BillingService(models.TextChoices):
- FREE_CREDITS = "free-credits", "Free credits"
- STRIPE_TOPUP = "stripe-topup", "Stripe top-up"
+ GRANT = "grant", "Grant"
+ PURCHASE = "purchase", "Purchase"
FINETUNING_JOB = "finetuning-job", "Finetuning job"
INFERENCE = "inference", "Inference"
INFERENCE_FT_MODEL = "inference-ft-model", "Fine-tuned inference"
@@ -47,44 +47,3 @@ class BillingTelemetry(models.Model):
def __str__(self) -> str:
return f"BillingTelemetry({self.user_id}, {self.service}, {self.amount})"
-
-
-class SubscriptionStatus(models.TextChoices):
- INCOMPLETE = "incomplete", "Incomplete"
- ACTIVE = "active", "Active"
- PAST_DUE = "past_due", "Past due"
- CANCELED = "canceled", "Canceled"
- UNPAID = "unpaid", "Unpaid"
-
-
-class Subscription(models.Model):
- id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
- user = models.OneToOneField(
- settings.AUTH_USER_MODEL,
- on_delete=models.CASCADE,
- related_name="subscription",
- )
- stripe_subscription_id = models.CharField(max_length=255, blank=True, default="", db_index=True)
- stripe_price_id = models.CharField(max_length=255, blank=True, default="")
- status = models.CharField(
- max_length=32,
- choices=SubscriptionStatus.choices,
- default=SubscriptionStatus.INCOMPLETE,
- )
- start_date = models.DateTimeField(null=True, blank=True)
- end_date = models.DateTimeField(null=True, blank=True)
- payload = models.JSONField(default=dict, blank=True)
- last_stripe_invoice_id = models.CharField(max_length=255, blank=True, default="")
- cancel_at_period_end = models.BooleanField(default=False)
- created_at = models.DateTimeField(auto_now_add=True)
- updated_at = models.DateTimeField(auto_now=True)
-
- class Meta:
- ordering = ["-created_at"]
-
- @property
- def started_at(self):
- return self.start_date
-
- def __str__(self) -> str:
- return f"Subscription({self.user_id}, {self.status})"
diff --git a/overbae/models/iam.py b/overbae/models/iam.py
index 34370806..cab94bc8 100644
--- a/overbae/models/iam.py
+++ b/overbae/models/iam.py
@@ -21,10 +21,10 @@ class UserManager(BaseUserManager):
user.set_password(password)
user.save(using=self._db)
# Lazy import: billing_ledger imports User.
- from overbae.services.billing_ledger import grant_free_credits
+ from overbae.services.billing_ledger import grant_signup_credits
if not user.is_guest:
- grant_free_credits(user)
+ grant_signup_credits(user)
return user
def create_user(self, email, password=None, **extra_fields):
diff --git a/overbae/services/billing_ledger.py b/overbae/services/billing_ledger.py
index 36e8d8bf..4426b6dd 100644
--- a/overbae/services/billing_ledger.py
+++ b/overbae/services/billing_ledger.py
@@ -15,10 +15,11 @@ from django.utils import timezone
from overbae.models import BillingService, BillingTelemetry, FinetuningJob, User
from overbae.services import model_catalog
+from overbae.services.billing_provider import get_billing
logger = logging.getLogger(__name__)
-FREE_CREDITS_USD = Decimal("50")
+SIGNUP_CREDITS_USD = Decimal("50")
# Display/purchase denomination: the ledger stores USD, users buy and see credits.
CREDITS_PER_USD = 100
@@ -116,38 +117,32 @@ def append_entry(
return None
-def grant_free_credits(user: User) -> BillingTelemetry | None:
- from overbae.services.billing_provider import get_billing
-
- return get_billing().grant_free_credits(user)
-
-
-def grant_stripe_topup(user: User, amount: Decimal, invoice_id: str) -> BillingTelemetry | None:
- if amount <= 0:
- return None
- return append_entry(
- user=user,
- amount=amount,
- service=BillingService.STRIPE_TOPUP,
- idempotency_key=invoice_id,
- )
+def grant_signup_credits(user: User) -> BillingTelemetry | None:
+ return get_billing().grant_signup_credits(user)
def grant_credit_purchase(user: User, amount: Decimal, session_id: str) -> BillingTelemetry | None:
- """One-time credit purchase. The ``topup:`` key namespace is distinct from
- ``grant_stripe_topup``'s bare invoice id so the two Stripe paths cannot collide.
- """
+ """Keyed on the Checkout Session, so the return confirmation and the webhook grant once."""
if amount <= 0:
return None
return append_entry(
user=user,
amount=amount,
- service=BillingService.STRIPE_TOPUP,
+ service=BillingService.PURCHASE,
idempotency_key=f"topup:{session_id}",
metadata={"checkout_session_id": session_id},
)
+def account_payload(user: User) -> dict[str, Any]:
+ return {
+ "billing_enabled": get_billing().enabled,
+ "credits_usd": balance_usd(user),
+ "credits_granted_usd": granted_usd(user),
+ "credits_spent_usd": spent_usd(user),
+ }
+
+
def charge_credits(
user: User,
amount: Decimal,
@@ -171,8 +166,6 @@ def charge_credits(
def ensure_credits(user: User) -> None:
- from overbae.services.billing_provider import get_billing
-
get_billing().ensure_credits(user)
diff --git a/overbae/services/billing_provider.py b/overbae/services/billing_provider.py
index 6282e00e..9d29bde9 100644
--- a/overbae/services/billing_provider.py
+++ b/overbae/services/billing_provider.py
@@ -1,7 +1,7 @@
"""Commercial billing vs uncapped metering.
-Ledger charges always run. Remaining-credit gates, signup grants, Stripe and
-the Free seat limit exist only when ``STRIPE_SECRET_KEY`` is set.
+Ledger charges always run. Remaining-credit gates, signup grants and Stripe
+Checkout exist only when ``STRIPE_SECRET_KEY`` is set.
"""
from __future__ import annotations
@@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, Protocol, runtime_checkable
from django.conf import settings
if TYPE_CHECKING:
- from overbae.models import BillingTelemetry, Project, User
+ from overbae.models import BillingTelemetry, User
__all__ = ["Billing", "commercial_billing_enabled", "get_billing"]
@@ -25,10 +25,7 @@ class Billing(Protocol):
enabled: bool
def ensure_credits(self, user: User) -> None: ...
- def grant_free_credits(self, user: User) -> BillingTelemetry | None: ...
- def is_pro(self, user: User) -> bool: ...
- def require_seat_for_invite(self, actor: User, project: Project) -> None: ...
- def plan_usage_payload(self, user: User) -> dict: ...
+ def grant_signup_credits(self, user: User) -> BillingTelemetry | None: ...
class UncappedBilling:
@@ -37,56 +34,33 @@ class UncappedBilling:
def ensure_credits(self, user: User) -> None:
return
- def grant_free_credits(self, user: User) -> BillingTelemetry | None:
+ def grant_signup_credits(self, user: User) -> BillingTelemetry | None:
return None
- def is_pro(self, user: User) -> bool:
- return False
-
- def require_seat_for_invite(self, actor: User, project: Project) -> None:
- return
-
- def plan_usage_payload(self, user: User) -> dict:
- from overbae.services.plan_limits import usage_payload
-
- return usage_payload(user, unlimited=True)
-
class StripeBilling:
enabled = True
def ensure_credits(self, user: User) -> None:
+ # Lazy import: billing_ledger imports this module.
from overbae.services.billing_ledger import InsufficientCredits, balance_usd
if balance_usd(user) <= 0:
raise InsufficientCredits("Insufficient credits.")
- def grant_free_credits(self, user: User) -> BillingTelemetry | None:
+ def grant_signup_credits(self, user: User) -> BillingTelemetry | None:
+ # Lazy import: billing_ledger imports this module.
from overbae.models import BillingService
- from overbae.services.billing_ledger import FREE_CREDITS_USD, append_entry
+ from overbae.services.billing_ledger import SIGNUP_CREDITS_USD, append_entry
return append_entry(
user=user,
- amount=FREE_CREDITS_USD,
- service=BillingService.FREE_CREDITS,
- idempotency_key=f"free-credits:{user.pk}",
+ amount=SIGNUP_CREDITS_USD,
+ service=BillingService.GRANT,
+ idempotency_key=f"signup:{user.pk}",
+ metadata={"reason": "signup"},
)
- def is_pro(self, user: User) -> bool:
- from overbae.services.plan_limits import subscription_is_pro
-
- return subscription_is_pro(user)
-
- def require_seat_for_invite(self, actor: User, project: Project) -> None:
- from overbae.services.plan_limits import enforce_seat_for_invite
-
- enforce_seat_for_invite(actor, project)
-
- def plan_usage_payload(self, user: User) -> dict:
- from overbae.services.plan_limits import usage_payload
-
- return usage_payload(user, unlimited=False)
-
_STRIPE = StripeBilling()
_UNCAPPED = UncappedBilling()
diff --git a/overbae/services/credit_purchases.py b/overbae/services/credit_purchases.py
new file mode 100644
index 00000000..e6c79b3d
--- /dev/null
+++ b/overbae/services/credit_purchases.py
@@ -0,0 +1,249 @@
+"""Credit purchases through one-time Stripe Checkout.
+
+A paid session grants its amount once, keyed on the session id. The Console
+confirms the session when the buyer returns, and the webhook covers payment
+methods that settle later; whichever arrives first grants.
+"""
+
+from __future__ import annotations
+
+import logging
+from decimal import Decimal
+from typing import Any
+
+import stripe
+from django.conf import settings
+
+from overbae.models import BillingTelemetry, User
+from overbae.services.billing_ledger import CREDITS_PER_USD, balance_usd, grant_credit_purchase
+
+logger = logging.getLogger(__name__)
+
+__all__ = [
+ "CREDIT_TOPUP_PURPOSE",
+ "WEBHOOK_EVENTS",
+ "PurchaseUnavailable",
+ "SessionNotFound",
+ "configure_stripe",
+ "confirm_session",
+ "create_topup_session",
+ "grant_from_session",
+ "sync_webhook_endpoint",
+]
+
+CREDIT_TOPUP_PURPOSE = "credit-topup"
+WEBHOOK_EVENTS = ("checkout.session.completed", "checkout.session.async_payment_succeeded")
+
+
+class PurchaseUnavailable(Exception): # noqa: N818
+ """Checkout cannot start: the credit price is not configured."""
+
+
+class SessionNotFound(Exception): # noqa: N818
+ """The session is not a credit top-up that belongs to the caller."""
+
+
+def configure_stripe() -> bool:
+ key = (getattr(settings, "STRIPE_SECRET_KEY", "") or "").strip()
+ if not key:
+ return False
+ stripe.api_key = key
+ # The SDK's default 80s read timeout parks a web worker per request during a
+ # Stripe brownout.
+ stripe.max_network_retries = 1
+ if getattr(stripe.default_http_client, "_overmind_timeout", None) != 20:
+ client = stripe.new_default_http_client(timeout=20)
+ client._overmind_timeout = 20
+ stripe.default_http_client = client
+ return True
+
+
+def _as_dict(obj: Any) -> dict[str, Any]:
+ """Stripe SDK objects have no ``.get``; every handler here works on dicts."""
+ if obj is None:
+ return {}
+ if isinstance(obj, dict):
+ return obj
+ to_dict = getattr(obj, "to_dict", None)
+ if callable(to_dict):
+ return to_dict()
+ try:
+ return dict(obj)
+ except (TypeError, ValueError):
+ return {}
+
+
+def _stripe_id(value: Any) -> str:
+ if not value:
+ return ""
+ if isinstance(value, str):
+ return value
+ data = _as_dict(value)
+ if data:
+ return data.get("id") or ""
+ return getattr(value, "id", None) or ""
+
+
+def _cents_to_usd(raw: Any) -> Decimal:
+ if raw is None:
+ return Decimal("0")
+ return (Decimal(int(raw)) / Decimal("100")).quantize(Decimal("0.0001"))
+
+
+def _customer_for(user: User) -> str:
+ if user.stripe_customer_id:
+ return user.stripe_customer_id
+ customer = stripe.Customer.create(email=user.email, metadata={"user_id": str(user.pk)})
+ user.stripe_customer_id = customer.id
+ user.save(update_fields=["stripe_customer_id"])
+ return customer.id
+
+
+def _remember_customer(user: User, customer_id: str) -> None:
+ if not customer_id or user.stripe_customer_id == customer_id:
+ return
+ user.stripe_customer_id = customer_id
+ user.save(update_fields=["stripe_customer_id"])
+
+
+def _user_by_pk(raw_id: Any) -> User | None:
+ """A malformed id must not 500: Stripe would retry the event forever."""
+ try:
+ return User.objects.filter(pk=raw_id).first()
+ except (TypeError, ValueError):
+ logger.warning("Ignoring malformed user id from Stripe payload: %r", raw_id)
+ return None
+
+
+def _buyer(session: dict[str, Any]) -> User | None:
+ """Precedence: client_reference_id, then metadata, then the customer id."""
+ metadata = _as_dict(session.get("metadata"))
+ for raw_id in (session.get("client_reference_id"), metadata.get("user_id")):
+ if raw_id:
+ user = _user_by_pk(raw_id)
+ if user:
+ return user
+ customer_id = _stripe_id(session.get("customer"))
+ if customer_id:
+ return User.objects.filter(stripe_customer_id=customer_id).first()
+ return None
+
+
+def _is_topup(session: dict[str, Any]) -> bool:
+ return _as_dict(session.get("metadata")).get("purpose") == CREDIT_TOPUP_PURPOSE
+
+
+def _usd_cents(session: dict[str, Any]) -> Any:
+ """What Stripe charged, in US cents, or None when the session settled in another currency.
+
+ With Adaptive Pricing the buyer pays in a local currency: ``amount_total`` is
+ then in that currency and the USD amount is under ``currency_conversion``.
+ """
+ if session.get("currency") == "usd":
+ return session.get("amount_total")
+ conversion = _as_dict(session.get("currency_conversion"))
+ if conversion.get("source_currency") == "usd":
+ return conversion.get("amount_total")
+ return None
+
+
+def _grant(user: User, session: dict[str, Any]) -> BillingTelemetry | None:
+ session_id = _stripe_id(session.get("id"))
+ # Async payment methods complete the session before the money lands.
+ if session.get("payment_status") != "paid":
+ return None
+ # The charged amount, not request metadata: metadata is only what we asked for.
+ amount = _cents_to_usd(_usd_cents(session))
+ if amount <= 0:
+ logger.error(
+ "Checkout session=%s has no USD total (currency=%s)",
+ session_id,
+ session.get("currency"),
+ )
+ return None
+ _remember_customer(user, _stripe_id(session.get("customer")))
+ entry = grant_credit_purchase(user, amount, session_id)
+ if entry is not None:
+ logger.info(
+ "Credit purchase granted user_id=%s session=%s amount=%s balance=%s",
+ user.pk,
+ session_id,
+ amount,
+ balance_usd(user),
+ )
+ return entry
+
+
+def create_topup_session(user: User, amount_usd: int) -> str:
+ """Returns the Checkout URL. Raises ``stripe.StripeError`` when Stripe fails."""
+ price_id = (getattr(settings, "STRIPE_CREDIT_PRICE_ID", "") or "").strip()
+ if not price_id:
+ raise PurchaseUnavailable("Credit price is not configured.")
+ # The Stripe price is one credit at $0.01, so quantity is the credit count.
+ credit_quantity = amount_usd * CREDITS_PER_USD
+ frontend = (getattr(settings, "FRONTEND_URL", "") or "http://localhost:5173").rstrip("/")
+ metadata = {
+ "user_id": str(user.pk),
+ "purpose": CREDIT_TOPUP_PURPOSE,
+ "amount_usd": str(amount_usd),
+ "credits": str(credit_quantity),
+ }
+ session = stripe.checkout.Session.create(
+ mode="payment",
+ customer=_customer_for(user),
+ line_items=[{"price": price_id, "quantity": credit_quantity}],
+ # Stripe substitutes the literal {CHECKOUT_SESSION_ID} on redirect.
+ success_url=f"{frontend}/settings?billing=topup&session_id={{CHECKOUT_SESSION_ID}}",
+ cancel_url=f"{frontend}/settings?billing=cancel",
+ client_reference_id=str(user.pk),
+ metadata=metadata,
+ payment_intent_data={"metadata": metadata},
+ )
+ if not session.url:
+ raise stripe.APIError("Stripe did not return a checkout URL.")
+ return session.url
+
+
+def grant_from_session(session: Any) -> BillingTelemetry | None:
+ """Webhook path: the buyer is resolved from the session itself."""
+ session = _as_dict(session)
+ session_id = _stripe_id(session.get("id"))
+ if not _is_topup(session):
+ return None
+ user = _buyer(session)
+ if user is None:
+ logger.error(
+ "Checkout session=%s: no user for customer=%s",
+ session_id,
+ _stripe_id(session.get("customer")),
+ )
+ return None
+ return _grant(user, session)
+
+
+def confirm_session(user: User, session_id: str) -> bool:
+ """Return path: grants a paid session the caller bought. Returns whether it is paid.
+
+ Raises ``SessionNotFound`` for another user's session or one that is not a
+ top-up, and ``stripe.StripeError`` when Stripe fails.
+ """
+ try:
+ session = _as_dict(stripe.checkout.Session.retrieve(session_id))
+ except stripe.InvalidRequestError as exc:
+ raise SessionNotFound(session_id) from exc
+ buyer = _buyer(session)
+ if not _is_topup(session) or buyer is None or buyer.pk != user.pk:
+ raise SessionNotFound(session_id)
+ _grant(user, session)
+ return session.get("payment_status") == "paid"
+
+
+def sync_webhook_endpoint(url: str) -> list[str]:
+ """Sets the endpoint's events to exactly ``WEBHOOK_EVENTS``. Raises ``LookupError``."""
+ for endpoint in stripe.WebhookEndpoint.list(limit=100).auto_paging_iter():
+ if endpoint.url == url:
+ updated = stripe.WebhookEndpoint.modify(
+ endpoint.id, enabled_events=list(WEBHOOK_EVENTS)
+ )
+ return list(updated.enabled_events)
+ raise LookupError(f"No Stripe webhook endpoint for {url}")
diff --git a/overbae/services/overwatch_tools.py b/overbae/services/overwatch_tools.py
index 37e96914..28f37364 100644
--- a/overbae/services/overwatch_tools.py
+++ b/overbae/services/overwatch_tools.py
@@ -39,12 +39,9 @@ def _billing_summary(args: dict[str, Any]) -> dict[str, Any]:
)
return {
"window_days": days,
- "subscription_statuses": overview["subscriptions"],
"paying_users": overview["paying_users"],
- "cancelling_users": overview["cancelling_users"],
- "free_users": overview["free_users"],
"low_balance_users": overview["low_balance_users"],
- "topups_usd": sum((point["value"] for point in overview["topups_usd"]), Decimal("0")),
+ "purchases_usd": sum((point["value"] for point in overview["purchases_usd"]), Decimal("0")),
"spend_usd": sum((point["value"] for point in overview["spend_usd"]), Decimal("0")),
"spend_by_service_usd": overview["spend_by_service"],
}
diff --git a/overbae/services/overwatch_usage.py b/overbae/services/overwatch_usage.py
index 0ac444df..605f1c73 100644
--- a/overbae/services/overwatch_usage.py
+++ b/overbae/services/overwatch_usage.py
@@ -15,7 +15,6 @@ from overbae.models import (
InferenceCall,
ProjectMembership,
Span,
- Subscription,
User,
)
from overbae.services.user_insights import window_start
@@ -185,19 +184,16 @@ def model_usage(arguments, user=None):
ledger = BillingTelemetry.objects.filter(user=user, timestamp__lte=now).aggregate(
balance=Sum("amount", default=0),
lifetime_spend=Sum(-F("amount"), filter=Q(amount__lt=0), default=0),
- lifetime_topups=Sum(
- "amount", filter=Q(amount__gt=0, service=BillingService.STRIPE_TOPUP), default=0
+ lifetime_purchases=Sum(
+ "amount", filter=Q(amount__gt=0, service=BillingService.PURCHASE), default=0
),
spend=Sum(-F("amount"), filter=Q(amount__lt=0, timestamp__gte=since), default=0),
)
- subscription = (
- Subscription.objects.filter(user=user).values_list("status", flat=True).first()
- )
lines.extend(
[
f"In this window: {traces:,} root traces, {jobs} training jobs started, {evaluations} evaluations started. Ready deployments now: {ready}.",
f"User billing: ${ledger['spend']:.2f} spent in window; ${ledger['balance']:.2f} current balance.",
- f"${ledger['lifetime_spend']:.2f} lifetime spend; ${ledger['lifetime_topups']:.2f} lifetime top-ups. Subscription: {subscription or 'none'}.",
+ f"${ledger['lifetime_spend']:.2f} lifetime spend; ${ledger['lifetime_purchases']:.2f} lifetime purchases.",
]
)
lines.extend(
diff --git a/overbae/services/plan_limits.py b/overbae/services/plan_limits.py
deleted file mode 100644
index 94dce8e0..00000000
--- a/overbae/services/plan_limits.py
+++ /dev/null
@@ -1,91 +0,0 @@
-"""Free/Pro seat entitlement.
-
-Free projects hold one seat; Pro (``Subscription.status == ACTIVE``) is unlimited.
-``past_due`` / canceled / missing sub → Free. Check-then-create can slightly
-overshoot under concurrency — no advisory lock.
-"""
-
-from __future__ import annotations
-
-from typing import TYPE_CHECKING
-
-from rest_framework.exceptions import APIException
-
-if TYPE_CHECKING:
- from overbae.models import Project, User
-
-FREE_LIMITS: dict[str, int] = {"seats": 1}
-
-__all__ = [
- "FREE_LIMITS",
- "SeatLimitExceeded",
- "enforce_seat_for_invite",
- "is_pro",
- "plan_usage_payload",
- "require_seat_for_invite",
- "subscription_is_pro",
- "usage_payload",
-]
-
-
-class SeatLimitExceeded(APIException):
- status_code = 403
- default_detail = "Free plan is limited to one seat. Upgrade to Pro to invite teammates."
- default_code = "seat_limit_exceeded"
-
- def __init__(self, detail: str | None = None):
- msg = detail or str(self.default_detail)
- super().__init__(detail={"detail": msg, "code": self.default_code}, code=self.default_code)
-
-
-def subscription_is_pro(user: User) -> bool:
- from overbae.models import Subscription, SubscriptionStatus
-
- try:
- sub = user.subscription
- except Subscription.DoesNotExist:
- return False
- return sub.status == SubscriptionStatus.ACTIVE
-
-
-def is_pro(user: User) -> bool:
- from overbae.services.billing_provider import get_billing
-
- return get_billing().is_pro(user)
-
-
-def enforce_seat_for_invite(actor: User, project: Project) -> None:
- """Free actors cannot add members once the project already has a seat filled.
-
- Pending invites count as filled seats — they become memberships without a
- further plan check when the invitee signs up.
- """
- if subscription_is_pro(actor):
- return
- from overbae.models import ProjectInvite, ProjectMembership
-
- seats = FREE_LIMITS["seats"]
- n = (
- ProjectMembership.objects.filter(project=project).count()
- + ProjectInvite.objects.filter(project=project).count()
- )
- if n >= seats:
- raise SeatLimitExceeded()
-
-
-def require_seat_for_invite(actor: User, project: Project) -> None:
- from overbae.services.billing_provider import get_billing
-
- get_billing().require_seat_for_invite(actor, project)
-
-
-def usage_payload(user: User, *, unlimited: bool) -> dict:
- """Limits for the subscription API (null limit = unlimited)."""
- uncapped = unlimited or subscription_is_pro(user)
- return {"seats": {"limit": None if uncapped else FREE_LIMITS["seats"]}}
-
-
-def plan_usage_payload(user: User) -> dict:
- from overbae.services.billing_provider import get_billing
-
- return get_billing().plan_usage_payload(user)
diff --git a/overbae/services/seat_downgrade.py b/overbae/services/seat_downgrade.py
deleted file mode 100644
index 2a5b8b1c..00000000
--- a/overbae/services/seat_downgrade.py
+++ /dev/null
@@ -1,54 +0,0 @@
-"""Enforce Free seat limits after a Pro → Free downgrade.
-
-Call only once the subscription actually becomes Free (Stripe
-``customer.subscription.deleted`` → status ``canceled``), never on
-``cancel_at_period_end`` — those users stay Pro until the period ends.
-"""
-
-from __future__ import annotations
-
-from typing import TYPE_CHECKING
-
-from django.db import transaction
-
-if TYPE_CHECKING:
- from overbae.models import User
-
-__all__ = ["enforce_free_seats_after_downgrade"]
-
-
-def enforce_free_seats_after_downgrade(user: User) -> dict:
- """Strip multi-member projects created by ``user`` down to the creator.
-
- Creator = earliest ``ProjectMembership`` (``created_at``, then ``id``);
- projects where ``user`` is only an invitee are left alone. Idempotent.
- """
- from overbae.models import ProjectMembership
-
- project_ids = list(
- ProjectMembership.objects.filter(user=user).values_list("project_id", flat=True)
- )
- projects_touched = 0
- memberships_removed = 0
-
- for project_id in project_ids:
- members = list(
- ProjectMembership.objects.filter(project_id=project_id).order_by("created_at", "id")
- )
- if len(members) <= 1:
- continue
- creator = members[0]
- if creator.user_id != user.pk:
- continue
- deleted, _ = (
- ProjectMembership.objects.filter(project_id=project_id).exclude(pk=creator.pk).delete()
- )
- # delete() returns (total_objs, {model_label: count}); memberships are one model.
- memberships_removed += deleted
- projects_touched += 1
-
- return {
- "projects_touched": projects_touched,
- "memberships_removed": memberships_removed,
- }
diff --git a/overbae/services/user_insights.py b/overbae/services/user_insights.py
index a3a327b6..e452d91a 100644
--- a/overbae/services/user_insights.py
+++ b/overbae/services/user_insights.py
@@ -41,8 +41,6 @@ from overbae.models import (
Project,
ProjectMembership,
Span,
- Subscription,
- SubscriptionStatus,
User,
)
@@ -236,10 +234,9 @@ def overview(since: datetime, active_since: datetime) -> dict[str, Any]:
project_ids = _user_project_ids()
spans = Span.objects.filter(project_id__in=project_ids, received_at__gte=since)
jobs = FinetuningJob.objects.filter(project_id__in=project_ids, created_at__gte=since)
- subscriptions = Subscription.objects.filter(user__is_guest=False)
ledger = BillingTelemetry.objects.filter(user__is_guest=False)
window_ledger = ledger.filter(timestamp__gte=since)
- subscription_counts = _counts(subscriptions, "status")
+ purchases = ledger.filter(service=BillingService.PURCHASE, amount__gt=0)
ledger_balances = (
ledger.order_by()
.values("user")
@@ -273,20 +270,12 @@ def overview(since: datetime, active_since: datetime) -> dict[str, Any]:
InferenceCall.objects.filter(project_id__in=project_ids, created_at__gte=since),
"created_at",
),
- "subscriptions": subscription_counts,
- "paying_users": subscription_counts.get(SubscriptionStatus.ACTIVE, 0),
- "cancelling_users": subscriptions.filter(
- status=SubscriptionStatus.ACTIVE, cancel_at_period_end=True
- ).count(),
- "free_users": users.filter(project_memberships__isnull=False)
- .exclude(pk__in=subscriptions.filter(status=SubscriptionStatus.ACTIVE).values("user_id"))
- .distinct()
- .count(),
+ "paying_users": purchases.order_by().values("user").distinct().count(),
"low_balance_users": ledger_balances.filter(
balance__lt=LOW_BALANCE_USD, spent__isnull=False
).count(),
- "topups_usd": _daily(
- window_ledger.filter(service=BillingService.STRIPE_TOPUP, amount__gt=0),
+ "purchases_usd": _daily(
+ purchases.filter(timestamp__gte=since),
"timestamp",
Sum("amount"),
),
@@ -389,7 +378,7 @@ def users(since: datetime) -> QuerySet[User]:
return _users().annotate(
**_reached(),
projects=Coalesce(_scalar(ProjectMembership.objects.filter(user=member), Count("pk")), 0),
- seats=Coalesce(
+ members=Coalesce(
_scalar(
ProjectMembership.objects.filter(
project__memberships__user=member, user__is_guest=False
@@ -413,7 +402,6 @@ def users(since: datetime) -> QuerySet[User]:
),
0,
),
- subscription_status=F("subscription__status"),
spend_usd=Coalesce(
_scalar(
ledger.filter(amount__lt=0, timestamp__gte=since),
@@ -421,9 +409,9 @@ def users(since: datetime) -> QuerySet[User]:
),
zero_usd,
),
- topups_usd=Coalesce(
+ purchases_usd=Coalesce(
_scalar(
- ledger.filter(service=BillingService.STRIPE_TOPUP, amount__gt=0),
+ ledger.filter(service=BillingService.PURCHASE, amount__gt=0),
Sum("amount"),
),
zero_usd,
@@ -446,29 +434,20 @@ def user_activity(user: User, since: datetime) -> dict[str, Any]:
datasets = Dataset.objects.filter(project_id__in=project_ids)
ledger = BillingTelemetry.objects.filter(user=user)
spend = Sum(-F("amount"), output_field=USD)
- topups = Sum("amount")
+ purchased = Sum("amount")
+ purchases = ledger.filter(service=BillingService.PURCHASE, amount__gt=0)
return {
"user": user,
"billing": {
- "subscription_status": getattr(user, "subscription_status", None),
"spend_usd": ledger.filter(amount__lt=0).aggregate(value=spend)["value"]
or Decimal("0"),
- "topups_usd": ledger.filter(
- service=BillingService.STRIPE_TOPUP, amount__gt=0
- ).aggregate(value=topups)["value"]
- or Decimal("0"),
+ "purchases_usd": purchases.aggregate(value=purchased)["value"] or Decimal("0"),
"balance_usd": ledger.aggregate(value=Sum("amount"))["value"] or Decimal("0"),
"spend_daily": _daily(
ledger.filter(amount__lt=0, timestamp__gte=since), "timestamp", spend
),
- "topups_daily": _daily(
- ledger.filter(
- service=BillingService.STRIPE_TOPUP,
- amount__gt=0,
- timestamp__gte=since,
- ),
- "timestamp",
- topups,
+ "purchases_daily": _daily(
+ purchases.filter(timestamp__gte=since), "timestamp", purchased
),
},
"training": {
diff --git a/overbae/settings.py b/overbae/settings.py
index d5e48b98..b46bffc5 100644
--- a/overbae/settings.py
+++ b/overbae/settings.py
@@ -293,7 +293,6 @@ TRACE_SETTLE_SECONDS = int(os.environ.get("TRACE_SETTLE_SECONDS", "600"))
STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY")
STRIPE_WEBHOOK_SECRET = os.environ.get("STRIPE_WEBHOOK_SECRET")
-STRIPE_PRO_PRICE_ID = os.environ.get("STRIPE_PRO_PRICE_ID")
# One-time price of a single Overmind Credit ($0.01); top-up quantity = credits bought.
STRIPE_CREDIT_PRICE_ID = os.environ.get("STRIPE_CREDIT_PRICE_ID")
diff --git a/overbae/urls.py b/overbae/urls.py
index ee40e13f..bd8e56b6 100644
--- a/overbae/urls.py
+++ b/overbae/urls.py
@@ -16,13 +16,11 @@ from overbae.api.auth_keys import APITokenCurrentView, APITokenDestroyView, APIT
from overbae.api.auth_registration import LocalSessionView, OnboardingView, UserMeView
from overbae.api.auth_token_views import PublicTokenObtainPairView, PublicTokenRefreshView
from overbae.api.billing import (
+ BillingAccountView,
BillingLedgerView,
- CancelSubscriptionView,
- CheckoutSessionView,
+ CreditTopUpConfirmView,
CreditTopUpView,
- RenewSubscriptionView,
StripeWebhookView,
- SubscriptionView,
)
from overbae.api.capabilities import AgentGraphView, CapabilityViewSet
from overbae.api.completions import chat_completions, model_detail, models_list
@@ -256,12 +254,14 @@ urlpatterns += [
path("api/auth/onboarding/", OnboardingView.as_view(), name="user-onboarding"),
path("api/auth/token/", PublicTokenObtainPairView.as_view(), name="token_obtain_pair"),
path("api/auth/token/refresh/", PublicTokenRefreshView.as_view(), name="token_refresh"),
- path("api/billing/subscription/", SubscriptionView.as_view(), name="billing-subscription"),
+ path("api/billing/account/", BillingAccountView.as_view(), name="billing-account"),
path("api/billing/ledger/", BillingLedgerView.as_view(), name="billing-ledger"),
- path("api/billing/checkout/", CheckoutSessionView.as_view(), name="billing-checkout"),
path("api/billing/topup/", CreditTopUpView.as_view(), name="billing-topup"),
- path("api/billing/cancel/", CancelSubscriptionView.as_view(), name="billing-cancel"),
- path("api/billing/renew/", RenewSubscriptionView.as_view(), name="billing-renew"),
+ path(
+ "api/billing/topup/confirm/",
+ CreditTopUpConfirmView.as_view(),
+ name="billing-topup-confirm",
+ ),
path("api/billing/webhook/", StripeWebhookView.as_view(), name="billing-webhook"),
path("api/schema/", SpectacularAPIView.as_view(permission_classes=[AllowAny]), name="schema"),
path(
diff --git a/sales-dashboard/src/lib/api.ts b/sales-dashboard/src/lib/api.ts
index 4af6b39e..5329bf02 100644
--- a/sales-dashboard/src/lib/api.ts
+++ b/sales-dashboard/src/lib/api.ts
@@ -49,12 +49,9 @@ export type Overview = Cached & {
top_base_models: { base_model: string; jobs: number }[];
live_deployments: number;
inference_calls: Daily[];
- subscriptions: Record<string, number>;
paying_users: number;
- cancelling_users: number;
- free_users: number;
low_balance_users: number;
- topups_usd: DailyUsd[];
+ purchases_usd: DailyUsd[];
spend_usd: DailyUsd[];
spend_by_service: Record<string, string>;
};
@@ -96,15 +93,14 @@ export type User = {
date_joined: string;
sign_on_method: string;
projects: number;
- seats: number;
+ members: number;
last_span_at: string | null;
spans: number;
training_jobs: number;
live_deployments: number;
stage: string;
- subscription_status: string | null;
spend_usd: string;
- topups_usd: string;
+ purchases_usd: string;
balance_usd: string;
};
@@ -120,12 +116,11 @@ export type TrainingOutcome = "completed" | "failed" | "cancelled" | "in_progres
export type UserActivity = Cached & {
user: User;
billing: {
- subscription_status: string | null;
spend_usd: string;
- topups_usd: string;
+ purchases_usd: string;
balance_usd: string;
spend_daily: DailyUsd[];
- topups_daily: DailyUsd[];
+ purchases_daily: DailyUsd[];
};
training: {
totals: Record<"started" | TrainingOutcome, number>;
diff --git a/sales-dashboard/src/routes/_app/accounts.tsx b/sales-dashboard/src/routes/_app/accounts.tsx
index 828c5761..d7f69d91 100644
--- a/sales-dashboard/src/routes/_app/accounts.tsx
+++ b/sales-dashboard/src/routes/_app/accounts.tsx
@@ -9,7 +9,6 @@ import {
formatDate,
formatInt,
formatUsd,
- humanize,
milestoneLabel,
} from "~/lib/format";
@@ -31,13 +30,13 @@ import { TablePagination } from "@/components/ui/table-pagination";
const COLUMNS = [
{ key: "date_joined", label: "Joined" },
{ key: "projects", label: "Projects" },
- { key: "seats", label: "Seats" },
+ { key: "members", label: "Members" },
{ key: "last_span_at", label: "Last activity" },
{ key: "spans", label: "Spans" },
{ key: "training_jobs", label: "Training runs" },
{ key: "live_deployments", label: "Live" },
{ key: "spend_usd", label: "Spend" },
- { key: "topups_usd", label: "Top-ups" },
+ { key: "purchases_usd", label: "Purchases" },
{ key: "balance_usd", label: "Balance" },
] as const;
@@ -100,7 +99,6 @@ function AccountsPage() {
<TableRow>
<SortableHeader label="User" onSort={onSort} sort={sort} sortKey="email" />
<TableHead>Milestone reached</TableHead>
- <TableHead>Subscription</TableHead>
{COLUMNS.map((column) => (
<SortableHeader
key={column.key}
@@ -153,31 +151,15 @@ function UserRow({ user, days }: { user: User; days: number }) {
{milestoneLabel(user.stage)}
</Badge>
</TableCell>
- <TableCell>
- <Badge
- size="chip"
- variant={
- user.subscription_status === "active"
- ? "success"
- : user.subscription_status === "past_due" || user.subscription_status === "unpaid"
- ? "error"
- : user.subscription_status === "incomplete"
- ? "warning"
- : "neutral"
- }
- >
- {user.subscription_status ? humanize(user.subscription_status) : "Free"}
- </Badge>
- </TableCell>
<TableCell className="whitespace-nowrap">{formatDate(user.date_joined)}</TableCell>
<TableCell className={number}>{formatInt(user.projects)}</TableCell>
- <TableCell className={number}>{formatInt(user.seats)}</TableCell>
+ <TableCell className={number}>{formatInt(user.members)}</TableCell>
<TableCell className="whitespace-nowrap">{formatAgo(user.last_span_at)}</TableCell>
<TableCell className={number}>{formatInt(user.spans)}</TableCell>
<TableCell className={number}>{formatInt(user.training_jobs)}</TableCell>
<TableCell className={number}>{formatInt(user.live_deployments)}</TableCell>
<TableCell className={number}>{formatUsd(user.spend_usd)}</TableCell>
- <TableCell className={number}>{formatUsd(user.topups_usd)}</TableCell>
+ <TableCell className={number}>{formatUsd(user.purchases_usd)}</TableCell>
<TableCell className={`${number} ${Number(user.balance_usd) < 5 ? "text-warning" : ""}`}>
{formatUsd(user.balance_usd)}
</TableCell>
diff --git a/sales-dashboard/src/routes/_app/accounts_.$accountId.tsx b/sales-dashboard/src/routes/_app/accounts_.$accountId.tsx
index 84645cc6..af53eba5 100644
--- a/sales-dashboard/src/routes/_app/accounts_.$accountId.tsx
+++ b/sales-dashboard/src/routes/_app/accounts_.$accountId.tsx
@@ -92,11 +92,7 @@ function AccountBody({ data, days }: { data: UserActivity; days: number }) {
return (
<>
<div className="grid grid-cols-2 gap-3 md:grid-cols-4 xl:grid-cols-7">
- <Stat
- label="Subscription"
- value={billing.subscription_status ? humanize(billing.subscription_status) : "Free"}
- />
- <Stat label="Stripe top-ups" value={formatUsd(billing.topups_usd)} />
+ <Stat label="Credit purchases" value={formatUsd(billing.purchases_usd)} />
<Stat label="Product spend" value={formatUsd(billing.spend_usd)} />
<Stat label="Credit balance" value={formatUsd(billing.balance_usd)} />
<Stat
@@ -124,11 +120,11 @@ function AccountBody({ data, days }: { data: UserActivity; days: number }) {
total={formatUsd(sum(billing.spend_daily))}
/>
<DailyChart
- data={fillDays(billing.topups_daily, days, data.computed_at)}
+ data={fillDays(billing.purchases_daily, days, data.computed_at)}
format={formatUsd}
- series={[{ color: "var(--chart-2)", key: "value", label: "Stripe top-ups" }]}
- title="Payments and top-ups"
- total={formatUsd(sum(billing.topups_daily))}
+ series={[{ color: "var(--chart-2)", key: "value", label: "Purchases" }]}
+ title="Credit purchases"
+ total={formatUsd(sum(billing.purchases_daily))}
/>
<DailyChart
data={trainingDaily}
diff --git a/sales-dashboard/src/routes/_app/index.tsx b/sales-dashboard/src/routes/_app/index.tsx
index f477ee1d..73d0eb9b 100644
--- a/sales-dashboard/src/routes/_app/index.tsx
+++ b/sales-dashboard/src/routes/_app/index.tsx
@@ -103,14 +103,14 @@ function OverviewBody({
(total, count) => total + count,
0
);
- const dailyTopups = fillDays(data.topups_usd, days, data.computed_at);
+ const dailyPurchases = fillDays(data.purchases_usd, days, data.computed_at);
const dailySpend = new Map(
fillDays(data.spend_usd, days, data.computed_at).map(({ day, value }) => [day, value])
);
- const financial = dailyTopups.map(({ day, value }) => ({
+ const financial = dailyPurchases.map(({ day, value }) => ({
day,
spend: dailySpend.get(day) ?? 0,
- topups: value,
+ purchases: value,
}));
const totalSpend = Object.values(data.spend_by_service).reduce(
(total, amount) => total + Number(amount),
@@ -151,23 +151,17 @@ function OverviewBody({
<section aria-label="Spend and payments" className="space-y-4">
<h2 className="text-sm font-medium text-muted-foreground">Spend and payments</h2>
- <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-6">
+ <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
<Stat
- detail="Active subscriptions"
+ detail="Bought credits at least once"
label="Paying users"
value={formatInt(data.paying_users)}
/>
- <Stat
- detail="Cancel at period end"
- label="Cancelling"
- value={formatInt(data.cancelling_users)}
- />
- <Stat label="Free users" value={formatInt(data.free_users)} />
<Stat detail={`Last ${days} days`} label="Product spend" value={formatUsd(totalSpend)} />
<Stat
detail={`Last ${days} days`}
- label="Stripe top-ups"
- value={formatUsd(sum(data.topups_usd))}
+ label="Credit purchases"
+ value={formatUsd(sum(data.purchases_usd))}
/>
<Stat
detail="Current balance below $5 after spend"
@@ -241,18 +235,17 @@ function OverviewBody({
data={financial}
format={formatUsd}
series={[
- { color: "var(--chart-2)", key: "topups", label: "Stripe top-ups" },
+ { color: "var(--chart-2)", key: "purchases", label: "Credit purchases" },
{ color: "var(--chart-4)", key: "spend", label: "Product spend" },
]}
title="Spend and payments"
- total={`${formatUsd(sum(data.topups_usd))} topped up`}
+ total={`${formatUsd(sum(data.purchases_usd))} purchased`}
/>
</section>
<section aria-label="Product breakdowns" className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<Breakdown format={formatInt} title="Training jobs" values={data.training_jobs} />
<Breakdown format={formatUsd} title="Spend by service" values={data.spend_by_service} />
- <Breakdown format={formatInt} title="Subscription status" values={data.subscriptions} />
<Breakdown format={formatInt} title="Sign-in method" values={data.sign_on_methods} />
{usage?.available ? (
<SectionCard contentClassName="p-0" title="Most used CLI commands">
diff --git a/tests/coverage_map.py b/tests/coverage_map.py
index 07dcbc19..0ac9b854 100644
--- a/tests/coverage_map.py
+++ b/tests/coverage_map.py
@@ -60,7 +60,7 @@ COVERAGE_MAP: dict[str, Entry] = {
S1,
INVARIANT,
"Each surface admits only its own credentials, with their permissions: API key "
- "scopes, MCP OAuth, sessions, the guest gate, invites and seats, Overwatch tokens.",
+ "scopes, MCP OAuth, sessions, the guest gate, invites, Overwatch tokens.",
),
"privacy": Entry(
S1,
@@ -72,7 +72,7 @@ COVERAGE_MAP: dict[str, Entry] = {
S1,
INVARIANT,
"Each charge is metered once from measured usage at the current price; the hosted "
- "cap stops spend at zero; a top-up, renewal or webhook applies once.",
+ "cap stops spend at zero; a purchase applies once, from the return or the webhook.",
),
"work-once": Entry(
S1,
diff --git a/tests/fakes/stripe.py b/tests/fakes/stripe.py
index 26c81966..351d834e 100644
--- a/tests/fakes/stripe.py
+++ b/tests/fakes/stripe.py
@@ -43,19 +43,22 @@ class StripeAPI:
webhook_secret: str = "whsec_fake"
sessions: list[dict[str, Any]] = field(default_factory=list)
customers: dict[str, dict[str, Any]] = field(default_factory=dict)
- subscriptions: dict[str, dict[str, Any]] = field(default_factory=dict)
+ webhook_endpoints: list[dict[str, Any]] = field(default_factory=list)
down: bool = False
- def subscription(self, **fields: Any) -> dict[str, Any]:
- sub = {
- "id": f"sub_fake{next(_ids)}",
- "object": "subscription",
- "status": "active",
- "cancel_at_period_end": False,
- **fields,
+ def pay(self, session: dict[str, Any], amount_total: int) -> dict[str, Any]:
+ session.update(payment_status="paid", amount_total=amount_total, currency="usd")
+ return session
+
+ def webhook_endpoint(self, url: str, events: list[str]) -> dict[str, Any]:
+ endpoint = {
+ "id": f"we_fake{next(_ids)}",
+ "object": "webhook_endpoint",
+ "url": url,
+ "enabled_events": events,
}
- self.subscriptions[sub["id"]] = sub
- return sub
+ self.webhook_endpoints.append(endpoint)
+ return endpoint
def signed(self, event: dict[str, Any]) -> tuple[str, str]:
payload = json.dumps({"object": "event", **event})
@@ -81,22 +84,36 @@ class StripeAPI:
customer = self.customers.get(path.rsplit("/", 1)[-1])
return _json(customer) if customer else _json({"error": {}}, 404)
if method == "POST" and path == "/v1/checkout/sessions":
- session_id = f"cs_fake{next(_ids)}"
+ session_id = f"cs_test_fake{next(_ids)}"
session = {
"id": session_id,
"object": "checkout.session",
"url": f"https://checkout.stripe.test/{session_id}",
+ "payment_status": "unpaid",
**form,
}
self.sessions.append(session)
return _json(session)
- if path.startswith("/v1/subscriptions/"):
- sub = self.subscriptions.get(path.rsplit("/", 1)[-1])
- if sub is None:
- return _json({"error": {"message": "No such subscription"}}, 404)
- if method == "POST":
- sub.update(
- {k: v == "true" if v in ("true", "false") else v for k, v in form.items()}
- )
- return _json(sub)
+ if method == "GET" and path.startswith("/v1/checkout/sessions/"):
+ wanted = path.rsplit("/", 1)[-1]
+ found = next((s for s in self.sessions if s["id"] == wanted), None)
+ if found is None:
+ return _json({"error": {"message": "No such checkout.session"}}, 404)
+ return _json(found)
+ if method == "GET" and path == "/v1/webhook_endpoints":
+ return _json(
+ {
+ "object": "list",
+ "url": path,
+ "has_more": False,
+ "data": self.webhook_endpoints,
+ }
+ )
+ if method == "POST" and path.startswith("/v1/webhook_endpoints/"):
+ wanted = path.rsplit("/", 1)[-1]
+ found = next((e for e in self.webhook_endpoints if e["id"] == wanted), None)
+ if found is None:
+ return _json({"error": {"message": "No such webhook endpoint"}}, 404)
+ found.update(form)
+ return _json(found)
return _json({"error": {"message": f"not found: {path}"}}, 404)
diff --git a/tests/journeys/test_ledger.py b/tests/journeys/test_ledger.py
index a54cc5a5..65945732 100644
--- a/tests/journeys/test_ledger.py
+++ b/tests/journeys/test_ledger.py
@@ -48,6 +48,7 @@ def top_up(live_api, user, usd) -> int:
"metadata": {"purpose": "credit-topup", "user_id": str(user.pk)},
"payment_status": "paid",
"amount_total": usd * 100,
+ "currency": "usd",
"customer": "cus_journey",
}
},
diff --git a/tests/load/README.md b/tests/load/README.md
index 618f713c..0604f199 100644
--- a/tests/load/README.md
+++ b/tests/load/README.md
@@ -95,6 +95,5 @@ windows. It requires a shared instant with training, imports, pipelines, trace
scoring, inference and quiet reads all active. Reports retain individual pipeline
queue and execution times. GPU execution is the external Modal fake; preparation, dispatch, progress
collection and training completion are real platform services. Serving startup
-is excluded. Its synthetic training user has an active Pro subscription so the
-soak measures concurrency rather than the Free plan monthly training quota.
+is excluded.
Training reconcilers run at the production 15-second cadence.
diff --git a/tests/load/mixed.py b/tests/load/mixed.py
index edcf1600..03f7dbc3 100644
--- a/tests/load/mixed.py
+++ b/tests/load/mixed.py
@@ -32,7 +32,6 @@ from overbae.models import (
FinetuningJob,
InferenceRequest,
Span,
- Subscription,
TrainingPreparation,
)
from overbae.services.datasets import pipeline_runner
@@ -103,8 +102,6 @@ def test_mixed_large_payload_soak(live_api, settings, fake_llm, fake_modal, sft)
capabilities = []
for index in range(9):
user = make_user()
- if index == 0:
- Subscription.objects.create(user=user, status="active")
project = make_project(name=f"mixed-{index}", member=user)
key, _ = APIToken.create_for_user(user, project=project)
identities.append((project, user, key))
diff --git a/tests/test_audit_data_boundaries.py b/tests/test_audit_data_boundaries.py
index 15884fb9..e122ba86 100644
--- a/tests/test_audit_data_boundaries.py
+++ b/tests/test_audit_data_boundaries.py
@@ -26,13 +26,13 @@ def test_demo_reset_preserves_real_owner_ledger():
).pk
for project, service, amount in [
(real, "evaluation", -2),
- (None, "stripe-topup", 100),
- (None, "free-credits", 10),
+ (None, "purchase", 100),
+ (None, "grant", 10),
]
]
BillingTelemetry.objects.create(user=owner, project=demo, service="evaluation", amount=-5)
BillingTelemetry.objects.create(
- user=owner, service="stripe-topup", amount=50, idempotency_key="topup:cs_live_seed_a1B2c3"
+ user=owner, service="purchase", amount=50, idempotency_key="topup:cs_live_seed_a1B2c3"
)
reset_demo_billing(owner.email)
assert set(BillingTelemetry.objects.values_list("pk", flat=True)) == set(keep) | initial
diff --git a/tests/test_billing_provider.py b/tests/test_billing_provider.py
index a6afff5c..bd957f4b 100644
--- a/tests/test_billing_provider.py
+++ b/tests/test_billing_provider.py
@@ -8,7 +8,7 @@ from django.urls import reverse
from factories import auth_client
from overbae.models import BillingService, BillingTelemetry
-from overbae.services.billing_ledger import charge_credits, grant_free_credits
+from overbae.services.billing_ledger import charge_credits, grant_signup_credits
from overbae.services.billing_provider import get_billing
pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]
@@ -33,15 +33,10 @@ def uncapped(_commercial_billing, settings):
def test_uncapped_skips_signup_grant(uncapped):
user = _make_user("uncapped-grant")
assert not get_billing().enabled
- assert grant_free_credits(user) is None
+ assert grant_signup_credits(user) is None
assert not BillingTelemetry.objects.filter(user=user).exists()
-def test_uncapped_seats_are_unlimited(uncapped):
- user = _make_user("uncapped-seats")
- assert get_billing().plan_usage_payload(user) == {"seats": {"limit": None}}
-
-
def test_uncapped_me_and_spend_routes(uncapped):
user = _make_user("uncapped-api")
charge_credits(
@@ -56,22 +51,21 @@ def test_uncapped_me_and_spend_routes(uncapped):
assert me.status_code == 200
assert me.data["billing_enabled"] is False
- sub = client.get(reverse("billing-subscription"))
- assert sub.status_code == 200
- assert sub.data["billing_enabled"] is False
- assert sub.data["credits_spent_usd"] == "2.0000"
- assert sub.data["usage"] == {"seats": {"limit": None}}
+ account = client.get(reverse("billing-account"))
+ assert account.status_code == 200
+ assert account.data["billing_enabled"] is False
+ assert account.data["credits_spent_usd"] == "2.0000"
ledger = client.get(reverse("billing-ledger"))
assert ledger.status_code == 200
assert ledger.data["count"] == 1
- checkout = client.post(reverse("billing-checkout"))
- assert checkout.status_code == 404
-
topup = client.post(reverse("billing-topup"), {"amount_usd": 10}, format="json")
assert topup.status_code == 404
+ confirm = client.post(reverse("billing-topup-confirm"), {"session_id": "cs_any"})
+ assert confirm.status_code == 404
+
def test_commercial_me_enables_billing():
user = _make_user("capped-api")
diff --git a/tests/test_billing_renewal.py b/tests/test_billing_renewal.py
deleted file mode 100644
index 720a2681..00000000
--- a/tests/test_billing_renewal.py
+++ /dev/null
@@ -1,471 +0,0 @@
-from __future__ import annotations
-
-from datetime import UTC, datetime
-from decimal import Decimal
-
-import pytest
-from django.contrib.auth import get_user_model
-from django.urls import reverse
-from factories import auth_client, make_project, make_user
-from rest_framework.test import APIClient
-
-from overbae.models import BillingService, BillingTelemetry, Subscription, SubscriptionStatus
-from overbae.services.billing_ledger import (
- FREE_CREDITS_USD,
- InsufficientCredits,
- balance_usd,
- charge_credits,
- ensure_credits,
- grant_free_credits,
- granted_usd,
-)
-
-pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]
-
-User = get_user_model()
-
-
-def _deliver(stripe, event_type: str, obj: dict) -> None:
- payload, signature = stripe.signed(
- {"id": f"evt_{obj['id']}", "type": event_type, "data": {"object": obj}}
- )
- response = APIClient().post(
- reverse("billing-webhook"),
- data=payload,
- content_type="application/json",
- HTTP_STRIPE_SIGNATURE=signature,
- )
- assert response.status_code < 300, response.data
-
-
-def _invoice(
- *,
- invoice_id: str,
- amount_paid: int,
- period_start: int,
- period_end: int,
- customer: str = "cus_test",
- subscription: str = "sub_test",
- price_id: str = "price_1TvfC1CgXbweROl8gtGzCSV6",
-) -> dict:
- return {
- "id": invoice_id,
- "object": "invoice",
- "customer": customer,
- "subscription": subscription,
- "amount_paid": amount_paid,
- "lines": {
- "data": [
- {
- "price": {"id": price_id},
- "period": {"start": period_start, "end": period_end},
- }
- ]
- },
- }
-
-
-def test_signup_grants_exactly_50_free_credits_once():
- user = User.objects.create_user(
- password="x",
- clerk_user_id="clerk_free_signup",
- )
- rows = BillingTelemetry.objects.filter(user=user, service=BillingService.FREE_CREDITS)
- assert rows.count() == 1
- assert rows.get().amount == FREE_CREDITS_USD
- assert balance_usd(user) == FREE_CREDITS_USD
-
- grant_free_credits(user)
- assert rows.count() == 1
- assert balance_usd(user) == FREE_CREDITS_USD
-
-
-def test_renew_plan_from_invoice_activates_pro_and_grants_credits(stripe_api):
- user = User.objects.create_user(
- password="x",
- clerk_user_id="clerk_pro_renew",
- stripe_customer_id="cus_test",
- )
- Subscription.objects.create(user=user, status=SubscriptionStatus.INCOMPLETE)
-
- _deliver(
- stripe_api,
- "invoice.paid",
- _invoice(
- invoice_id="in_first",
- amount_paid=12000,
- period_start=1861920000,
- period_end=1893456000,
- ),
- )
-
- user.refresh_from_db()
- sub = user.subscription
- assert sub.status == SubscriptionStatus.ACTIVE
- assert sub.stripe_subscription_id == "sub_test"
- assert sub.stripe_price_id == "price_1TvfC1CgXbweROl8gtGzCSV6"
- assert sub.start_date == datetime(2029, 1, 1, tzinfo=UTC)
- assert sub.end_date == datetime(2030, 1, 1, tzinfo=UTC)
- assert sub.last_stripe_invoice_id == "in_first"
- assert (
- BillingTelemetry.objects.filter(
- user=user, service=BillingService.STRIPE_TOPUP, idempotency_key="in_first"
- ).count()
- == 1
- )
- # $50 free + $120 invoice
- assert balance_usd(user) == Decimal("170")
-
-
-def test_renew_plan_extends_end_date_and_adds_credits_without_changing_start(stripe_api):
- user = User.objects.create_user(
- password="x",
- clerk_user_id="clerk_pro_renew2",
- stripe_customer_id="cus_test2",
- )
- Subscription.objects.create(user=user, status=SubscriptionStatus.INCOMPLETE)
-
- _deliver(
- stripe_api,
- "invoice.paid",
- _invoice(
- invoice_id="in_a",
- amount_paid=12000,
- period_start=1861920000,
- period_end=1893456000,
- customer="cus_test2",
- subscription="sub_test2",
- ),
- )
- sub = user.subscription
- sub.refresh_from_db()
- start = sub.start_date
- assert start == datetime(2029, 1, 1, tzinfo=UTC)
-
- _deliver(
- stripe_api,
- "invoice.paid",
- _invoice(
- invoice_id="in_b",
- amount_paid=12000,
- period_start=1893456000,
- period_end=1924992000,
- customer="cus_test2",
- subscription="sub_test2",
- ),
- )
-
- sub.refresh_from_db()
- assert sub.start_date == start
- assert sub.end_date == datetime(2031, 1, 1, tzinfo=UTC)
- assert sub.last_stripe_invoice_id == "in_b"
- # $50 free + $120 + $120
- assert balance_usd(user) == Decimal("290")
-
-
-def test_renew_plan_idempotent_on_same_invoice_id(stripe_api):
- user = User.objects.create_user(
- password="x",
- clerk_user_id="clerk_pro_idem",
- stripe_customer_id="cus_idem",
- )
- Subscription.objects.create(user=user, status=SubscriptionStatus.INCOMPLETE)
- payload = _invoice(
- invoice_id="in_same",
- amount_paid=12000,
- period_start=1861920000,
- period_end=1893456000,
- customer="cus_idem",
- subscription="sub_idem",
- )
-
- _deliver(stripe_api, "invoice.paid", payload)
- _deliver(stripe_api, "invoice.paid", payload)
-
- assert (
- BillingTelemetry.objects.filter(
- user=user, service=BillingService.STRIPE_TOPUP, idempotency_key="in_same"
- ).count()
- == 1
- )
- assert balance_usd(user) == Decimal("170")
- sub = user.subscription
- sub.refresh_from_db()
- assert sub.end_date == datetime(2030, 1, 1, tzinfo=UTC)
-
-
-def test_charge_credits_reduces_balance_and_entry_gate():
- user = User.objects.create_user(
- password="x",
- clerk_user_id="clerk_pro_deduct",
- )
- assert balance_usd(user) == FREE_CREDITS_USD
-
- charge_credits(
- user,
- Decimal("3.5"),
- BillingService.INFERENCE,
- idempotency_key="inf-1",
- )
- assert balance_usd(user) == Decimal("46.5")
-
- charge_credits(
- user,
- Decimal("46.5"),
- BillingService.INFERENCE,
- idempotency_key="inf-2",
- )
- assert balance_usd(user) == Decimal("0")
-
- with pytest.raises(InsufficientCredits):
- ensure_credits(user)
-
- # Post-hoc debit still records full amount (ledger truth).
- charge_credits(
- user,
- Decimal("1"),
- BillingService.INFERENCE,
- idempotency_key="inf-3",
- )
- assert balance_usd(user) == Decimal("-1")
- # Usage never shrinks the granted total (progress-bar denominator).
- assert granted_usd(user) == FREE_CREDITS_USD
-
-
-def test_subscription_get_free_user():
- user = User.objects.create_user(
- password="x",
- clerk_user_id="clerk_free",
- )
- r = auth_client(user).get(reverse("billing-subscription"))
- assert r.status_code == 200
- assert r.data["plan"] == "free"
- assert r.data["status"] is None
- assert r.data["credits_usd"] == "50.0000"
- assert r.data["credits_granted_usd"] == "50.0000"
- assert r.data["cancel_at_period_end"] is False
-
-
-def test_subscription_get_pro_user():
- user = User.objects.create_user(
- password="x",
- clerk_user_id="clerk_pro_get",
- )
- Subscription.objects.create(
- user=user,
- status=SubscriptionStatus.ACTIVE,
- end_date=datetime(2030, 1, 1, tzinfo=UTC),
- cancel_at_period_end=False,
- )
- r = auth_client(user).get(reverse("billing-subscription"))
- assert r.status_code == 200
- assert r.data["plan"] == "pro"
- assert r.data["status"] == "active"
- assert r.data["credits_usd"] == "50.0000"
-
-
- ("endpoint", "before", "after"),
- [("billing-cancel", False, True), ("billing-renew", True, False)],
-)
-def test_cancelling_and_resuming_change_the_stripe_subscription(
- stripe_api, endpoint, before, after
-):
- user = User.objects.create_user(
- email=f"{endpoint}@example.com", password="x", clerk_user_id=f"clerk_{endpoint}"
- )
- remote = stripe_api.subscription(cancel_at_period_end=before)
- Subscription.objects.create(
- user=user,
- status=SubscriptionStatus.ACTIVE,
- stripe_subscription_id=remote["id"],
- cancel_at_period_end=before,
- end_date=datetime(2030, 1, 1, tzinfo=UTC),
- )
-
- r = auth_client(user).post(reverse(endpoint))
-
- assert r.status_code == 200
- assert r.data["cancel_at_period_end"] is after
- assert r.data["plan"] == "pro"
- assert remote["cancel_at_period_end"] is after
- user.subscription.refresh_from_db()
- assert user.subscription.cancel_at_period_end is after
-
-
-def test_a_stripe_outage_leaves_the_subscription_unchanged(stripe_api):
- user = User.objects.create_user(
- email="[email protected]", password="x", clerk_user_id="clerk_cancel_outage"
- )
- remote = stripe_api.subscription()
- Subscription.objects.create(
- user=user, status=SubscriptionStatus.ACTIVE, stripe_subscription_id=remote["id"]
- )
- stripe_api.down = True
-
- r = auth_client(user).post(reverse("billing-cancel"))
-
- assert r.status_code >= 500
- user.subscription.refresh_from_db()
- assert user.subscription.cancel_at_period_end is False
-
-
- ("event_type", "remote", "status", "cancel_at_period_end"),
- [
- ("customer.subscription.deleted", "canceled", SubscriptionStatus.CANCELED, False),
- ("customer.subscription.updated", "active", SubscriptionStatus.ACTIVE, True),
- ],
-)
-def test_subscription_events_sync_the_plan(
- stripe_api, event_type, remote, status, cancel_at_period_end
-):
- user = User.objects.create_user(
- email=f"sync-{remote}@example.com",
- password="x",
- clerk_user_id=f"clerk_sync_{remote}",
- )
- Subscription.objects.create(
- user=user,
- status=SubscriptionStatus.ACTIVE,
- stripe_subscription_id="sub_sync",
- cancel_at_period_end=not cancel_at_period_end,
- )
-
- _deliver(
- stripe_api,
- event_type,
- {
- "id": "sub_sync",
- "object": "subscription",
- "customer": "cus_sync",
- "status": remote,
- "cancel_at_period_end": cancel_at_period_end,
- "current_period_end": 1893456000,
- },
- )
-
- user.refresh_from_db()
- sub = user.subscription
- sub.refresh_from_db()
- assert sub.status == status
- assert sub.cancel_at_period_end is cancel_at_period_end
- assert sub.end_date == datetime(2030, 1, 1, tzinfo=UTC)
-
-
-def test_a_newer_invoice_names_its_subscription_under_parent_details(stripe_api):
- user = User.objects.create_user(
- password="x",
- clerk_user_id="clerk_pro_parent",
- stripe_customer_id="cus_parent",
- )
- Subscription.objects.create(user=user, status=SubscriptionStatus.INCOMPLETE)
-
- _deliver(
- stripe_api,
- "invoice.paid",
- {
- "id": "in_parent",
- "object": "invoice",
- "customer": "cus_parent",
- "subscription": None,
- "amount_paid": 5000,
- "parent": {"subscription_details": {"subscription": "sub_parent"}},
- "lines": {
- "data": [
- {
- "price": {"id": "price_parent"},
- "period": {"start": 1861920000, "end": 1893456000},
- }
- ]
- },
- },
- )
-
- sub = user.subscription
- sub.refresh_from_db()
- assert sub.stripe_subscription_id == "sub_parent"
- assert balance_usd(user) == Decimal("100")
-
-
-def test_webhook_bad_signature_no_ledger_write(settings):
- settings.STRIPE_WEBHOOK_SECRET = "whsec_test"
- settings.STRIPE_SECRET_KEY = "sk_test"
- user = User.objects.create_user(
- password="x",
- clerk_user_id="clerk_wh",
- stripe_customer_id="cus_wh",
- )
- before = BillingTelemetry.objects.filter(user=user).count()
-
- client = APIClient()
- r = client.post(
- reverse("billing-webhook"),
- data=b'{"id":"evt_x"}',
- content_type="application/json",
- HTTP_STRIPE_SIGNATURE="t=1,v1=bad",
- )
- assert r.status_code == 401
- assert BillingTelemetry.objects.filter(user=user).count() == before
-
-
-def test_ledger_lists_own_entries_newest_first():
- user = User.objects.create_user(
- password="x",
- clerk_user_id="clerk_ledger",
- )
- other = User.objects.create_user(
- password="x",
- clerk_user_id="clerk_ledger_other",
- )
- charge_credits(
- user,
- Decimal("1.25"),
- BillingService.INFERENCE,
- idempotency_key="ledger-inf-1",
- )
- # Other user's row must not appear.
- charge_credits(
- other,
- Decimal("9"),
- BillingService.INFERENCE,
- idempotency_key="ledger-inf-other",
- )
-
- r = auth_client(user).get(reverse("billing-ledger"))
- assert r.status_code == 200
- results = r.data["results"]
- assert r.data["count"] == 2 # free-credits + inference debit
- assert results[0]["service"] == BillingService.INFERENCE
- assert results[0]["service_label"] == "Inference"
- assert results[0]["amount"] == "-1.2500000"
- assert results[1]["service"] == BillingService.FREE_CREDITS
- assert results[1]["amount"] == "50.0000000"
-
-
[email protected]("ordering", ["service", "-service", "project__name", "-project__name"])
-def test_ledger_sorts_visible_labels_and_keeps_missing_projects_last(ordering):
- user = make_user()
- BillingTelemetry.objects.filter(user=user).delete()
- project = make_project(name="Alpha")
- first = BillingTelemetry.objects.create(
- user=user, project=project, amount=-1, service=BillingService.INFERENCE_FT_MODEL
- )
- second = BillingTelemetry.objects.create(user=user, amount=-2, service=BillingService.INFERENCE)
- response = auth_client(user).get(
- reverse("billing-ledger"), {"ordering": ordering, "page_size": 1}
- )
- assert response.status_code == 200, response.content
- expected = second if ordering == "-service" else first
- assert response.data["results"][0]["id"] == str(expected.id)
diff --git a/tests/test_credit_grants.py b/tests/test_credit_grants.py
new file mode 100644
index 00000000..e14bcdd2
--- /dev/null
+++ b/tests/test_credit_grants.py
@@ -0,0 +1,131 @@
+from __future__ import annotations
+
+from decimal import Decimal
+
+import pytest
+from django.contrib.auth import get_user_model
+from django.urls import reverse
+from factories import auth_client, make_project, make_user
+
+from overbae.models import BillingService, BillingTelemetry
+from overbae.services.billing_ledger import (
+ SIGNUP_CREDITS_USD,
+ InsufficientCredits,
+ balance_usd,
+ charge_credits,
+ ensure_credits,
+ grant_signup_credits,
+ granted_usd,
+)
+
+pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]
+
+User = get_user_model()
+
+
+def test_signup_grants_exactly_50_credits_once():
+ user = User.objects.create_user(
+ password="x",
+ clerk_user_id="clerk_signup_grant",
+ )
+ rows = BillingTelemetry.objects.filter(user=user, service=BillingService.GRANT)
+ assert rows.count() == 1
+ assert rows.get().amount == SIGNUP_CREDITS_USD
+ assert balance_usd(user) == SIGNUP_CREDITS_USD
+
+ grant_signup_credits(user)
+ assert rows.count() == 1
+ assert balance_usd(user) == SIGNUP_CREDITS_USD
+
+
+def test_charge_credits_reduces_balance_and_entry_gate():
+ user = User.objects.create_user(
+ password="x",
+ clerk_user_id="clerk_deduct",
+ )
+ assert balance_usd(user) == SIGNUP_CREDITS_USD
+
+ charge_credits(
+ user,
+ Decimal("3.5"),
+ BillingService.INFERENCE,
+ idempotency_key="inf-1",
+ )
+ assert balance_usd(user) == Decimal("46.5")
+
+ charge_credits(
+ user,
+ Decimal("46.5"),
+ BillingService.INFERENCE,
+ idempotency_key="inf-2",
+ )
+ assert balance_usd(user) == Decimal("0")
+
+ with pytest.raises(InsufficientCredits):
+ ensure_credits(user)
+
+ # Post-hoc debit still records full amount (ledger truth).
+ charge_credits(
+ user,
+ Decimal("1"),
+ BillingService.INFERENCE,
+ idempotency_key="inf-3",
+ )
+ assert balance_usd(user) == Decimal("-1")
+ # Usage never shrinks the granted total (progress-bar denominator).
+ assert granted_usd(user) == SIGNUP_CREDITS_USD
+
+
+def test_ledger_lists_own_entries_newest_first():
+ user = User.objects.create_user(
+ password="x",
+ clerk_user_id="clerk_ledger",
+ )
+ other = User.objects.create_user(
+ password="x",
+ clerk_user_id="clerk_ledger_other",
+ )
+ charge_credits(
+ user,
+ Decimal("1.25"),
+ BillingService.INFERENCE,
+ idempotency_key="ledger-inf-1",
+ )
+ # Other user's row must not appear.
+ charge_credits(
+ other,
+ Decimal("9"),
+ BillingService.INFERENCE,
+ idempotency_key="ledger-inf-other",
+ )
+
+ r = auth_client(user).get(reverse("billing-ledger"))
+ assert r.status_code == 200
+ results = r.data["results"]
+ assert r.data["count"] == 2 # signup grant + inference debit
+ assert results[0]["service"] == BillingService.INFERENCE
+ assert results[0]["service_label"] == "Inference"
+ assert results[0]["amount"] == "-1.2500000"
+ assert results[1]["service"] == BillingService.GRANT
+ assert results[1]["amount"] == "50.0000000"
+
+
[email protected]("ordering", ["service", "-service", "project__name", "-project__name"])
+def test_ledger_sorts_visible_labels_and_keeps_missing_projects_last(ordering):
+ user = make_user()
+ BillingTelemetry.objects.filter(user=user).delete()
+ project = make_project(name="Alpha")
+ first = BillingTelemetry.objects.create(
+ user=user, project=project, amount=-1, service=BillingService.INFERENCE_FT_MODEL
+ )
+ second = BillingTelemetry.objects.create(user=user, amount=-2, service=BillingService.INFERENCE)
+ response = auth_client(user).get(
+ reverse("billing-ledger"), {"ordering": ordering, "page_size": 1}
+ )
+ assert response.status_code == 200, response.content
+ expected = second if ordering == "-service" else first
+ assert response.data["results"][0]["id"] == str(expected.id)
diff --git a/tests/test_credit_labels_migration.py b/tests/test_credit_labels_migration.py
new file mode 100644
index 00000000..0c102f29
--- /dev/null
+++ b/tests/test_credit_labels_migration.py
@@ -0,0 +1,37 @@
+from decimal import Decimal
+
+import pytest
+from django.db.migrations.executor import MigrationExecutor
+from django.db.models import Sum
+from migration_replay import scratch_database
+
+pytestmark = pytest.mark.covers("migrations")
+
+
+def test_only_live_checkout_rows_become_purchases_and_balances_hold(django_db_blocker):
+ before = [("overbae", "0067_delete_retired_beat_tasks")]
+ after = [("overbae", "0068_credits_only")]
+ rows = [
+ ("free-credits", "50", "free-credits:7", "grant", "signup:7"),
+ ("stripe-topup", "25", "topup:cs_live_a1", "purchase", "topup:cs_live_a1"),
+ ("stripe-topup", "1000", "topup:cs_test_a1", "grant", "topup:cs_test_a1"),
+ ("stripe-topup", "120", "in_1Pro", "grant", "in_1Pro"),
+ ("stripe-topup", "200", "signup-promo:7", "grant", "signup-promo:7"),
+ ("stripe-topup", "-490", "signup-promo-reset:7", "grant", "signup-promo-reset:7"),
+ ("inference", "-3", "inf-1", "inference", "inf-1"),
+ ]
+ with scratch_database(django_db_blocker) as database:
+ executor = MigrationExecutor(database)
+ executor.migrate(before)
+ state = executor.loader.project_state(before).apps
+ user = state.get_model("overbae", "User").objects.create(email="[email protected]")
+ old = state.get_model("overbae", "BillingTelemetry")
+ for service, amount, key, _, _ in rows:
+ old.objects.create(user=user, service=service, amount=amount, idempotency_key=key)
+ executor = MigrationExecutor(database)
+ executor.migrate(after)
+ new = executor.loader.project_state(after).apps.get_model("overbae", "BillingTelemetry")
+
+ labelled = sorted(new.objects.values_list("service", "idempotency_key"))
+ assert labelled == sorted((service, key) for _, _, _, service, key in rows)
+ assert new.objects.aggregate(total=Sum("amount"))["total"] == Decimal("902")
diff --git a/tests/test_credit_topup.py b/tests/test_credit_topup.py
index 8bf4d47e..640811dc 100644
--- a/tests/test_credit_topup.py
+++ b/tests/test_credit_topup.py
@@ -4,13 +4,14 @@ from decimal import Decimal
import pytest
from django.contrib.auth import get_user_model
+from django.core.management import call_command
from django.urls import reverse
from factories import auth_client
from rest_framework.test import APIClient
-from overbae.api.billing import CREDIT_TOPUP_PURPOSE
-from overbae.models import BillingService, BillingTelemetry, Subscription, SubscriptionStatus
-from overbae.services.billing_ledger import FREE_CREDITS_USD, balance_usd
+from overbae.models import BillingService, BillingTelemetry
+from overbae.services.billing_ledger import SIGNUP_CREDITS_USD, balance_usd
+from overbae.services.credit_purchases import CREDIT_TOPUP_PURPOSE, WEBHOOK_EVENTS
pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]
@@ -55,6 +56,7 @@ def _session(
purpose: str | None = CREDIT_TOPUP_PURPOSE,
payment_status: str = "paid",
customer: str = "cus_test",
+ **extra,
) -> dict:
metadata = {k: v for k, v in (("purpose", purpose), ("user_id", user_id)) if v is not None}
return {
@@ -65,10 +67,13 @@ def _session(
"payment_status": payment_status,
"client_reference_id": user_id,
"metadata": metadata,
+ "currency": "usd",
+ **extra,
}
-def test_topup_checkout_charges_a_fixed_credit_quantity(stripe):
+def test_topup_checkout_charges_a_fixed_credit_quantity(stripe, settings):
+ settings.FRONTEND_URL = "https://console.example"
user = _make_user("topup-quantity")
r = auth_client(user).post(reverse("billing-topup"), {"amount_usd": 25}, format="json")
@@ -82,6 +87,9 @@ def test_topup_checkout_charges_a_fixed_credit_quantity(stripe):
assert session["metadata"]["purpose"] == CREDIT_TOPUP_PURPOSE
assert session["metadata"]["user_id"] == str(user.pk)
assert session["payment_intent_data"]["metadata"]["credits"] == "2500"
+ assert session["success_url"] == (
+ "https://console.example/settings?billing=topup&session_id={CHECKOUT_SESSION_ID}"
+ )
user.refresh_from_db()
assert user.stripe_customer_id in stripe.customers
@@ -94,13 +102,6 @@ def test_topup_rejects_out_of_range_amount(stripe, amount):
assert stripe.sessions == []
-def test_topup_available_on_free_plan(stripe):
- user = _make_user("topup-free")
- r = auth_client(user).post(reverse("billing-topup"), {"amount_usd": 1}, format="json")
- assert r.status_code == 200
- assert stripe.sessions[0]["line_items"][0]["quantity"] == "100"
-
-
def test_topup_requires_configured_price(stripe, settings):
settings.STRIPE_CREDIT_PRICE_ID = ""
user = _make_user("topup-unconfigured")
@@ -123,16 +124,38 @@ def test_a_paid_topup_grants_its_amount_once(stripe):
assert _deliver(stripe, "checkout.session.completed", session) < 300
rows = BillingTelemetry.objects.filter(
- user=user, service=BillingService.STRIPE_TOPUP, idempotency_key="topup:cs_grant"
+ user=user, service=BillingService.PURCHASE, idempotency_key="topup:cs_grant"
)
assert rows.get().amount == Decimal("25")
- assert balance_usd(user) == FREE_CREDITS_USD + Decimal("25")
+ assert balance_usd(user) == SIGNUP_CREDITS_USD + Decimal("25")
+
+
+ ("currency", "conversion", "granted"),
+ [
+ ("inr", {"source_currency": "usd", "amount_total": 1000}, Decimal("10")),
+ ("eur", None, Decimal("0")),
+ ],
+ ids=["adaptive pricing", "no usd total"],
+)
+def test_a_local_currency_payment_grants_its_usd_amount(stripe, currency, conversion, granted):
+ user = _make_user(f"topup-{currency}", stripe_customer_id="cus_test")
+ session = _session(
+ session_id=f"cs_{currency}",
+ amount_total=85000,
+ user_id=str(user.pk),
+ currency=currency,
+ currency_conversion=conversion,
+ )
+
+ assert _deliver(stripe, "checkout.session.completed", session) < 300
+ assert balance_usd(user) == SIGNUP_CREDITS_USD + granted
@pytest.mark.parametrize(
"overrides",
[{"purpose": None}, {"payment_status": "unpaid"}],
- ids=["subscription checkout", "unpaid"],
+ ids=["another checkout", "unpaid"],
)
def test_a_session_that_is_not_a_paid_topup_grants_nothing(stripe, overrides):
user = _make_user("topup-ignored", stripe_customer_id="cus_test")
@@ -141,8 +164,8 @@ def test_a_session_that_is_not_a_paid_topup_grants_nothing(stripe, overrides):
"checkout.session.completed",
_session(session_id="cs_other", user_id=str(user.pk), **overrides),
)
- assert not BillingTelemetry.objects.filter(service=BillingService.STRIPE_TOPUP).exists()
- assert balance_usd(user) == FREE_CREDITS_USD
+ assert not BillingTelemetry.objects.filter(service=BillingService.PURCHASE).exists()
+ assert balance_usd(user) == SIGNUP_CREDITS_USD
@pytest.mark.parametrize("reference", ["not-a-user-id", None], ids=["malformed", "absent"])
@@ -154,44 +177,103 @@ def test_a_topup_without_a_usable_user_reference_finds_the_customer(stripe, refe
_session(session_id="cs_cust", amount_total=500, user_id=reference, customer="cus_lonely"),
)
assert status < 300
- assert balance_usd(user) == FREE_CREDITS_USD + Decimal("5")
+ assert balance_usd(user) == SIGNUP_CREDITS_USD + Decimal("5")
-def test_an_invoice_without_a_subscription_does_not_activate_pro(stripe):
- user = _make_user("topup-invoice-guard", stripe_customer_id="cus_test")
- Subscription.objects.create(user=user, status=SubscriptionStatus.INCOMPLETE)
+def test_returning_from_a_paid_checkout_grants_once_without_a_webhook(stripe):
+ user = _make_user("topup-return")
+ client = auth_client(user)
+ client.post(reverse("billing-topup"), {"amount_usd": 25}, format="json")
+ [session] = stripe.sessions
+ stripe.pay(session, amount_total=2500)
- _deliver(
- stripe,
- "invoice.paid",
- {
- "id": "in_topup",
- "object": "invoice",
- "customer": "cus_test",
- "amount_paid": 2500,
- "lines": {"data": [{"period": {"start": 1861920000, "end": 1893456000}}]},
- },
- )
+ first = client.post(reverse("billing-topup-confirm"), {"session_id": session["id"]})
+ again = client.post(reverse("billing-topup-confirm"), {"session_id": session["id"]})
+ late_webhook = _deliver(stripe, "checkout.session.completed", session)
- user.refresh_from_db()
- assert user.subscription.status == SubscriptionStatus.INCOMPLETE
- assert balance_usd(user) == FREE_CREDITS_USD
+ assert first.status_code == 200
+ assert first.data["paid"] is True
+ assert first.data["account"]["credits_usd"] == "75.0000"
+ assert again.data["account"]["credits_usd"] == "75.0000"
+ assert late_webhook < 300
+ assert balance_usd(user) == SIGNUP_CREDITS_USD + Decimal("25")
+ assert BillingTelemetry.objects.filter(user=user, service=BillingService.PURCHASE).count() == 1
-def test_plan_checkout_opens_one_subscription_and_refuses_an_active_plan(stripe, settings):
- settings.STRIPE_PRO_PRICE_ID = "price_pro"
- settings.FRONTEND_URL = "https://console.example"
- user = _make_user("plan-checkout")
+def test_returning_before_payment_settles_grants_nothing(stripe):
+ user = _make_user("topup-pending")
+ client = auth_client(user)
+ client.post(reverse("billing-topup"), {"amount_usd": 25}, format="json")
+ [session] = stripe.sessions
- r = auth_client(user).post(reverse("billing-checkout"))
+ r = client.post(reverse("billing-topup-confirm"), {"session_id": session["id"]})
assert r.status_code == 200
+ assert r.data["paid"] is False
+ assert balance_usd(user) == SIGNUP_CREDITS_USD
+
+
[email protected]("session_id", ["theirs", "cs_test_missing"])
+def test_confirming_a_session_the_caller_did_not_buy_is_not_found(stripe, session_id):
+ buyer = _make_user("topup-buyer")
+ other = _make_user("topup-other")
+ auth_client(buyer).post(reverse("billing-topup"), {"amount_usd": 25}, format="json")
[session] = stripe.sessions
- assert r.data["checkout_url"] == session["url"]
- assert session["mode"] == "subscription"
- assert session["line_items"] == [{"price": "price_pro", "quantity": "1"}]
- assert session["cancel_url"] == "https://console.example/settings?billing=cancel"
- assert session["subscription_data"]["metadata"]["user_id"] == str(user.pk)
- Subscription.objects.create(user=user, status=SubscriptionStatus.ACTIVE)
- assert auth_client(user).post(reverse("billing-checkout")).status_code == 400
- assert len(stripe.sessions) == 1
+ stripe.pay(session, amount_total=2500)
+ target = session["id"] if session_id == "theirs" else session_id
+
+ r = auth_client(other).post(reverse("billing-topup-confirm"), {"session_id": target})
+
+ assert r.status_code == 404
+ assert not BillingTelemetry.objects.filter(service=BillingService.PURCHASE).exists()
+
+
[email protected]("session_id", ["cs_test_a/../../v1/customers", "pi_123", ""])
+def test_confirming_a_malformed_session_id_never_reaches_stripe(stripe, session_id):
+ stripe.down = True
+ user = _make_user("topup-malformed")
+
+ r = auth_client(user).post(reverse("billing-topup-confirm"), {"session_id": session_id})
+
+ assert r.status_code == 400
+
+
+def test_a_stripe_failure_on_return_does_not_echo_stripe_text(stripe):
+ user = _make_user("topup-confirm-outage")
+ stripe.down = True
+
+ r = auth_client(user).post(reverse("billing-topup-confirm"), {"session_id": "cs_test_down"})
+
+ assert r.status_code == 502
+ assert "unavailable" not in r.data["detail"]
+
+
+def test_the_webhook_acknowledges_events_it_does_not_handle(stripe):
+ user = _make_user("topup-unhandled", stripe_customer_id="cus_test")
+ invoice = {"id": "in_other", "object": "invoice", "customer": "cus_test", "amount_paid": 2500}
+
+ assert _deliver(stripe, "invoice.paid", invoice) == 204
+ assert balance_usd(user) == SIGNUP_CREDITS_USD
+
+
+def test_a_badly_signed_webhook_writes_nothing(stripe):
+ user = _make_user("topup-bad-signature", stripe_customer_id="cus_test")
+ r = APIClient().post(
+ reverse("billing-webhook"),
+ data=b'{"id":"evt_x"}',
+ content_type="application/json",
+ HTTP_STRIPE_SIGNATURE="t=1,v1=bad",
+ )
+ assert r.status_code == 401
+ assert balance_usd(user) == SIGNUP_CREDITS_USD
+
+
+def test_syncing_the_webhook_sets_exactly_the_purchase_events(stripe):
+ url = "https://api.example/api/billing/webhook/"
+ endpoint = stripe.webhook_endpoint(url, ["invoice.paid", "customer.subscription.updated"])
+ stripe.webhook_endpoint("https://elsewhere.example/hook/", ["invoice.paid"])
+
+ call_command("sync_stripe_webhook", url=url)
+
+ assert endpoint["enabled_events"] == list(WEBHOOK_EVENTS)
+ assert stripe.webhook_endpoints[1]["enabled_events"] == ["invoice.paid"]
diff --git a/tests/test_local_auth.py b/tests/test_local_auth.py
index 7813674a..c67f4b84 100644
--- a/tests/test_local_auth.py
+++ b/tests/test_local_auth.py
@@ -13,8 +13,6 @@ from overbae.models import (
Project,
ProjectInvite,
ProjectMembership,
- Subscription,
- SubscriptionStatus,
User,
)
@@ -44,13 +42,6 @@ def _owner() -> tuple[User, Project]:
password="test-pass-123",
clerk_user_id=f"local_{uuid.uuid4().hex}",
)
- Subscription.objects.update_or_create(
- user=user,
- defaults={
- "status": SubscriptionStatus.ACTIVE,
- "stripe_subscription_id": f"sub_{uuid.uuid4().hex[:8]}",
- },
- )
project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
ProjectMembership.objects.create(user=user, project=project)
return user, project
diff --git a/tests/test_mcp_billing.py b/tests/test_mcp_billing.py
index 82942a62..c48683dd 100644
--- a/tests/test_mcp_billing.py
+++ b/tests/test_mcp_billing.py
@@ -32,7 +32,7 @@ def test_credit_report_scopes_balance_usage_and_window(settings):
other, _, _ = account()
since = timezone.now() - timedelta(hours=1)
for owner, project, amount, service in [
- (user, None, "10", BillingService.STRIPE_TOPUP),
+ (user, None, "10", BillingService.PURCHASE),
(user, projects[0], "-0.1234567", BillingService.EVALUATION),
(user, projects[1], "-2", BillingService.FINETUNING_JOB),
(other, projects[0], "-99", BillingService.EVALUATION),
diff --git a/tests/test_overwatch_customer_usage.py b/tests/test_overwatch_customer_usage.py
index e45b2807..e42ea5ac 100644
--- a/tests/test_overwatch_customer_usage.py
+++ b/tests/test_overwatch_customer_usage.py
@@ -12,7 +12,6 @@ from overbae.models import (
DeployedModel,
InferenceCall,
ProjectMembership,
- Subscription,
)
pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("measured-facts")]
@@ -167,13 +166,10 @@ def test_customer_billing_remains_user_attributed_and_keeps_lifetime_totals(sett
other = make_user()
project = make_project(member=user)
ProjectMembership.objects.create(project=project, user=other)
- Subscription.objects.create(user=user, status="active")
BillingTelemetry.objects.create(
user=user, project=project, amount="-2.50", service="inference-ft-model"
)
- BillingTelemetry.objects.create(
- user=user, project=project, amount="20.00", service="stripe-topup"
- )
+ BillingTelemetry.objects.create(user=user, project=project, amount="20.00", service="purchase")
old = BillingTelemetry.objects.create(
user=user, project=project, amount="-5.00", service="inference-ft-model"
)
@@ -186,9 +182,8 @@ def test_customer_billing_remains_user_attributed_and_keeps_lifetime_totals(sett
text = response.data["content"]
assert "$2.50 spent in window" in text
assert "$7.50 lifetime spend" in text
- assert "$20.00 lifetime top-ups" in text
+ assert "$20.00 lifetime purchases" in text
assert "$12.50 current balance" in text
- assert "Subscription: active" in text
assert "$99" not in text
diff --git a/tests/test_overwatch_dashboard.py b/tests/test_overwatch_dashboard.py
index 47cb7559..2511cd27 100644
--- a/tests/test_overwatch_dashboard.py
+++ b/tests/test_overwatch_dashboard.py
@@ -17,6 +17,8 @@ from factories import (
from rest_framework.test import APIClient
from overbae.models import (
+ BillingService,
+ BillingTelemetry,
Dataset,
DeployedModel,
EvalRun,
@@ -92,6 +94,21 @@ def test_rejects_anything_but_the_configured_token(settings, path):
assert overwatch_client("").get(url).status_code == 403
+def test_paying_users_and_purchases_count_only_bought_credits(accounts):
+ for user, service, amount in [
+ (accounts["paying"], BillingService.PURCHASE, 25),
+ (accounts["paying"], BillingService.PURCHASE, 10),
+ (accounts["active"], BillingService.GRANT, 200),
+ ]:
+ BillingTelemetry.objects.create(user=user, service=service, amount=amount)
+
+ data = overwatch_client().get("/api/internal/overwatch/overview/").data
+
+ assert data["paying_users"] == 1
+ assert sum(float(point["value"]) for point in data["purchases_usd"]) == 35
+
+
def test_unicode_bearer_token_is_rejected_safely():
assert overwatch_client("☃").get("/api/internal/overwatch/overview/").status_code == 403
diff --git a/tests/test_plan_limits.py b/tests/test_plan_limits.py
deleted file mode 100644
index d43872b8..00000000
--- a/tests/test_plan_limits.py
+++ /dev/null
@@ -1,110 +0,0 @@
-from __future__ import annotations
-
-import uuid
-
-import pytest
-from django.urls import reverse
-from rest_framework.test import APIClient
-from rest_framework_simplejwt.tokens import RefreshToken
-
-from overbae.models import Project, ProjectMembership, Subscription, SubscriptionStatus, User
-from overbae.services.plan_limits import (
- FREE_LIMITS,
- SeatLimitExceeded,
- is_pro,
- require_seat_for_invite,
-)
-
-pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]
-
-
-def _user(email: str | None = None, **extra) -> User:
- return User.objects.create_user(
- email=email or f"u-{uuid.uuid4().hex[:8]}@example.com",
- password="test-pass-123",
- clerk_user_id=f"clerk_{uuid.uuid4().hex}",
- **extra,
- )
-
-
-def _auth_client(user: User) -> APIClient:
- client = APIClient()
- token = RefreshToken.for_user(user)
- client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.access_token}")
- return client
-
-
-def _project(user: User) -> Project:
- project = Project.objects.create(
- name=f"P-{uuid.uuid4().hex[:6]}",
- slug=f"p-{uuid.uuid4().hex[:8]}",
- )
- ProjectMembership.objects.create(user=user, project=project)
- return project
-
-
-def _make_pro(user: User) -> None:
- Subscription.objects.update_or_create(
- user=user,
- defaults={
- "status": SubscriptionStatus.ACTIVE,
- "stripe_subscription_id": f"sub_{uuid.uuid4().hex[:10]}",
- },
- )
-
-
-def test_past_due_is_not_pro():
- u = _user()
- Subscription.objects.create(
- user=u,
- status=SubscriptionStatus.PAST_DUE,
- stripe_subscription_id="sub_past_due",
- )
- assert not is_pro(u)
-
-
-def test_active_subscription_is_pro():
- u = _user()
- _make_pro(u)
- assert is_pro(u)
-
-
-def test_free_cannot_invite_second_member():
- owner = _user("[email protected]")
- project = _project(owner)
- invitee = _user("[email protected]")
-
- with pytest.raises(SeatLimitExceeded):
- require_seat_for_invite(owner, project)
-
- r = _auth_client(owner).post(
- reverse("project-membership-list", kwargs={"project_id": project.id}),
- {"email": invitee.email},
- format="json",
- )
- assert r.status_code == 403
- assert r.data.get("code") == "seat_limit_exceeded"
- assert not ProjectMembership.objects.filter(project=project, user=invitee).exists()
-
-
-def test_pro_can_invite_members():
- owner = _user("[email protected]")
- _make_pro(owner)
- project = _project(owner)
- invitee = _user("[email protected]")
-
- require_seat_for_invite(owner, project)
- r = _auth_client(owner).post(
- reverse("project-membership-list", kwargs={"project_id": project.id}),
- {"email": invitee.email},
- format="json",
- )
- assert r.status_code == 201
- assert ProjectMembership.objects.filter(project=project, user=invitee).exists()
-
-
-def test_subscription_payload_reports_only_the_seat_limit():
- user = _user()
- r = _auth_client(user).get(reverse("billing-subscription"))
- assert r.status_code == 200
- assert r.data["usage"] == {"seats": {"limit": FREE_LIMITS["seats"]}}
diff --git a/tests/test_project_invites.py b/tests/test_project_invites.py
index 9e8df2c4..282e1153 100644
--- a/tests/test_project_invites.py
+++ b/tests/test_project_invites.py
@@ -14,8 +14,6 @@ from overbae.models import (
Project,
ProjectInvite,
ProjectMembership,
- Subscription,
- SubscriptionStatus,
User,
)
from overbae.services.project_invites import claim_pending_invites
@@ -28,17 +26,6 @@ def _clerk_on(clerk):
return clerk
-def _pro(user: User) -> User:
- Subscription.objects.update_or_create(
- user=user,
- defaults={
- "status": SubscriptionStatus.ACTIVE,
- "stripe_subscription_id": f"sub_{uuid.uuid4().hex[:8]}",
- },
- )
- return user
-
-
def _project_with(owner: User) -> Project:
project = Project.objects.create(name="Inv", slug=f"inv-{uuid.uuid4().hex[:6]}")
ProjectMembership.objects.create(user=owner, project=project)
@@ -50,7 +37,7 @@ def _invites_url(project: Project) -> str:
def test_invite_unknown_email_creates_row_and_clerk_invitation(clerk):
- owner = _pro(make_user("[email protected]"))
+ owner = make_user("[email protected]")
project = _project_with(owner)
r = auth_client(owner).post(_invites_url(project), {"email": "[email protected]"}, format="json")
@@ -67,7 +54,7 @@ def test_invite_unknown_email_creates_row_and_clerk_invitation(clerk):
def test_invite_existing_user_email_is_rejected(clerk):
- owner = _pro(make_user("[email protected]"))
+ owner = make_user("[email protected]")
make_user("[email protected]")
project = _project_with(owner)
@@ -82,7 +69,7 @@ def test_invite_existing_user_email_is_rejected(clerk):
def test_repeat_invite_is_idempotent(clerk):
- owner = _pro(make_user("[email protected]"))
+ owner = make_user("[email protected]")
project = _project_with(owner)
client = auth_client(owner)
@@ -97,7 +84,7 @@ def test_repeat_invite_is_idempotent(clerk):
def test_invite_list_requires_membership():
- owner = _pro(make_user("[email protected]"))
+ owner = make_user("[email protected]")
outsider = make_user("[email protected]")
project = _project_with(owner)
ProjectInvite.objects.create(project=project, email="[email protected]", invited_by=owner)
@@ -111,7 +98,7 @@ def test_invite_list_requires_membership():
def test_revoke_invite_deletes_row_and_revokes_clerk(clerk):
- owner = _pro(make_user("[email protected]"))
+ owner = make_user("[email protected]")
project = _project_with(owner)
sent = clerk.invite("[email protected]")
invite = ProjectInvite.objects.create(
@@ -127,33 +114,27 @@ def test_revoke_invite_deletes_row_and_revokes_clerk(clerk):
assert not ProjectInvite.objects.exists()
-def test_free_actor_cannot_invite_past_seat_limit(clerk):
- owner = make_user("[email protected]")
- project = _project_with(owner)
-
- r = auth_client(owner).post(_invites_url(project), {"email": "[email protected]"}, format="json")
-
- assert r.status_code == 403
- assert clerk.invitations == {}
- assert not ProjectInvite.objects.exists()
-
-
-def test_pending_invite_fills_a_free_seat():
- owner = make_user("[email protected]")
+def test_a_project_takes_any_number_of_members_and_invites(clerk):
+ owner = make_user("[email protected]")
project = _project_with(owner)
ProjectInvite.objects.create(project=project, email="[email protected]", invited_by=owner)
- known = make_user("[email protected]")
+ client = auth_client(owner)
- r = auth_client(owner).post(
+ added = client.post(
reverse("project-membership-list", kwargs={"project_id": project.id}),
- {"email": known.email},
+ {"email": make_user("[email protected]").email},
format="json",
)
- assert r.status_code == 403
+ invited = client.post(_invites_url(project), {"email": "[email protected]"}, format="json")
+
+ assert added.status_code == 201
+ assert invited.status_code == 201
+ assert ProjectMembership.objects.filter(project=project).count() == 2
+ assert ProjectInvite.objects.filter(project=project).count() == 2
def test_claim_converts_invites_to_memberships():
- owner = _pro(make_user("[email protected]"))
+ owner = make_user("[email protected]")
p1 = _project_with(owner)
p2 = _project_with(owner)
ProjectInvite.objects.create(project=p1, email="[email protected]", invited_by=owner)
diff --git a/tests/test_seat_downgrade.py b/tests/test_seat_downgrade.py
deleted file mode 100644
index 057f43ad..00000000
--- a/tests/test_seat_downgrade.py
+++ /dev/null
@@ -1,69 +0,0 @@
-from __future__ import annotations
-
-import pytest
-from factories import make_project, make_user
-
-from overbae.models import ProjectMembership
-from overbae.services.seat_downgrade import enforce_free_seats_after_downgrade
-
-pytestmark = [pytest.mark.django_db, pytest.mark.covers("authentication")]
-
-
-def test_strips_invitees_keeps_creator():
- creator = make_user("[email protected]")
- a = make_user("[email protected]")
- b = make_user("[email protected]")
- project = make_project()
- ProjectMembership.objects.create(user=creator, project=project)
- ProjectMembership.objects.create(user=a, project=project)
- ProjectMembership.objects.create(user=b, project=project)
-
- result = enforce_free_seats_after_downgrade(creator)
-
- assert result["projects_touched"] == 1
- assert result["memberships_removed"] == 2
- remaining = list(
- ProjectMembership.objects.filter(project=project).values_list("user_id", flat=True)
- )
- assert remaining == [creator.pk]
-
-
-def test_invitee_downgrade_does_not_strip_others_project():
- owner = make_user("[email protected]")
- invitee = make_user("[email protected]")
- project = make_project()
- ProjectMembership.objects.create(user=owner, project=project)
- ProjectMembership.objects.create(user=invitee, project=project)
-
- result = enforce_free_seats_after_downgrade(invitee)
-
- assert result["projects_touched"] == 0
- assert result["memberships_removed"] == 0
- assert ProjectMembership.objects.filter(project=project).count() == 2
-
-
-def test_idempotent_second_call():
- creator = make_user("[email protected]")
- peer = make_user("[email protected]")
- project = make_project()
- ProjectMembership.objects.create(user=creator, project=project)
- ProjectMembership.objects.create(user=peer, project=project)
-
- first = enforce_free_seats_after_downgrade(creator)
- second = enforce_free_seats_after_downgrade(creator)
-
- assert first["memberships_removed"] == 1
- assert second["projects_touched"] == 0
- assert second["memberships_removed"] == 0
- assert ProjectMembership.objects.filter(project=project).count() == 1
-
-
-def test_creator_only_project_unchanged():
- creator = make_user("[email protected]")
- project = make_project()
- ProjectMembership.objects.create(user=creator, project=project)
-
- result = enforce_free_seats_after_downgrade(creator)
-
- assert result == {"projects_touched": 0, "memberships_removed": 0}
- assert ProjectMembership.objects.filter(project=project, user=creator).exists()