|
| 1 | +/** |
| 2 | + * User credits and subscription plans — the Studio product's billing layer. |
| 3 | + * |
| 4 | + * The ledger stores grants only. Spend is never written here: every provider |
| 5 | + * call already lands in `nodetool_predictions` with its USD cost, so |
| 6 | + * |
| 7 | + * balance = sum(ledger.delta) - ceil(prediction spend / USD_PER_CREDIT) |
| 8 | + * |
| 9 | + * Plans accrue lazily: the first balance read in a month inserts that month's |
| 10 | + * grant, keyed `plan:<userId>:<periodKey>` so the primary key makes double |
| 11 | + * accrual impossible. No cron, no payment state — a payment provider webhook |
| 12 | + * would write `topup` rows and flip `plan_id`; until then plan switches are |
| 13 | + * instant and top-ups are stubbed. |
| 14 | + */ |
| 15 | +import { eq, sql } from "drizzle-orm"; |
| 16 | + |
| 17 | +import { getDb } from "./db.js"; |
| 18 | +import { creditLedger, userSubscriptions } from "./schema/credits.js"; |
| 19 | +import { predictions } from "./schema/predictions.js"; |
| 20 | +import { createTimeOrderedUuid } from "./base-model.js"; |
| 21 | + |
| 22 | +/** One credit is one US cent of provider spend. */ |
| 23 | +export const USD_PER_CREDIT = 0.01; |
| 24 | + |
| 25 | +export interface CreditPlan { |
| 26 | + id: string; |
| 27 | + name: string; |
| 28 | + /** Credits granted at the start of each calendar month (UTC). */ |
| 29 | + monthlyCredits: number; |
| 30 | + /** Display price; billing itself is not implemented. */ |
| 31 | + priceUsdPerMonth: number; |
| 32 | + blurb: string; |
| 33 | +} |
| 34 | + |
| 35 | +export const CREDIT_PLANS: readonly CreditPlan[] = [ |
| 36 | + { |
| 37 | + id: "free", |
| 38 | + name: "Free", |
| 39 | + monthlyCredits: 300, |
| 40 | + priceUsdPerMonth: 0, |
| 41 | + blurb: "Try both creation paths with a monthly starter allowance." |
| 42 | + }, |
| 43 | + { |
| 44 | + id: "creator", |
| 45 | + name: "Creator", |
| 46 | + monthlyCredits: 3_000, |
| 47 | + priceUsdPerMonth: 12, |
| 48 | + blurb: "Enough for regular short-form work: stills, clips, and voice." |
| 49 | + }, |
| 50 | + { |
| 51 | + id: "pro", |
| 52 | + name: "Pro", |
| 53 | + monthlyCredits: 10_000, |
| 54 | + priceUsdPerMonth: 40, |
| 55 | + blurb: "Headroom for daily production and longer cuts." |
| 56 | + } |
| 57 | +] as const; |
| 58 | + |
| 59 | +export const DEFAULT_PLAN_ID = "free"; |
| 60 | + |
| 61 | +export const planById = (planId: string): CreditPlan | null => |
| 62 | + CREDIT_PLANS.find((p) => p.id === planId) ?? null; |
| 63 | + |
| 64 | +/** Calendar-month key, UTC — "2026-08". */ |
| 65 | +export const periodKeyFor = (now: Date): string => |
| 66 | + `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}`; |
| 67 | + |
| 68 | +export interface UserSubscription { |
| 69 | + userId: string; |
| 70 | + planId: string; |
| 71 | + status: string; |
| 72 | + updatedAt: string; |
| 73 | +} |
| 74 | + |
| 75 | +export interface CreditStatus { |
| 76 | + userId: string; |
| 77 | + plan: CreditPlan; |
| 78 | + periodKey: string; |
| 79 | + /** All grants ever recorded, in credits. */ |
| 80 | + grantedCredits: number; |
| 81 | + /** All prediction spend ever recorded, rounded up, in credits. */ |
| 82 | + spentCredits: number; |
| 83 | + /** grantedCredits - spentCredits, floored at 0 for display. */ |
| 84 | + balanceCredits: number; |
| 85 | + spentUsd: number; |
| 86 | +} |
| 87 | + |
| 88 | +export type CreditDecision = |
| 89 | + | { allowed: true; status: CreditStatus } |
| 90 | + | { allowed: false; reason: string; status: CreditStatus }; |
| 91 | + |
| 92 | +const toSubscription = (row: Record<string, unknown>): UserSubscription => ({ |
| 93 | + userId: String(row.user_id), |
| 94 | + planId: String(row.plan_id ?? DEFAULT_PLAN_ID), |
| 95 | + status: String(row.status ?? "active"), |
| 96 | + updatedAt: String(row.updated_at ?? "") |
| 97 | +}); |
| 98 | + |
| 99 | +/** The user's subscription, creating the default (free) row on first read. */ |
| 100 | +export async function getSubscription( |
| 101 | + userId: string |
| 102 | +): Promise<UserSubscription> { |
| 103 | + const db = getDb(); |
| 104 | + const rows = await db |
| 105 | + .select() |
| 106 | + .from(userSubscriptions) |
| 107 | + .where(eq(userSubscriptions.user_id, userId)) |
| 108 | + .limit(1); |
| 109 | + if (rows[0]) return toSubscription(rows[0] as Record<string, unknown>); |
| 110 | + |
| 111 | + const now = new Date().toISOString(); |
| 112 | + try { |
| 113 | + await db.insert(userSubscriptions).values({ |
| 114 | + user_id: userId, |
| 115 | + plan_id: DEFAULT_PLAN_ID, |
| 116 | + status: "active", |
| 117 | + created_at: now, |
| 118 | + updated_at: now |
| 119 | + }); |
| 120 | + } catch { |
| 121 | + // Concurrent first read created it; fall through to the re-read. |
| 122 | + } |
| 123 | + const created = await db |
| 124 | + .select() |
| 125 | + .from(userSubscriptions) |
| 126 | + .where(eq(userSubscriptions.user_id, userId)) |
| 127 | + .limit(1); |
| 128 | + return toSubscription(created[0] as Record<string, unknown>); |
| 129 | +} |
| 130 | + |
| 131 | +export async function setSubscriptionPlan( |
| 132 | + userId: string, |
| 133 | + planId: string |
| 134 | +): Promise<UserSubscription> { |
| 135 | + const plan = planById(planId); |
| 136 | + if (!plan) throw new Error(`Unknown plan "${planId}".`); |
| 137 | + await getSubscription(userId); |
| 138 | + const db = getDb(); |
| 139 | + await db |
| 140 | + .update(userSubscriptions) |
| 141 | + .set({ plan_id: plan.id, updated_at: new Date().toISOString() }) |
| 142 | + .where(eq(userSubscriptions.user_id, userId)); |
| 143 | + // Accrue the new plan's grant for the current month right away, so an |
| 144 | + // upgrade is usable the moment it happens (the id keys on plan too, so an |
| 145 | + // upgraded month carries both grants — acceptable, and simpler than |
| 146 | + // proration). |
| 147 | + await ensureMonthlyGrant(userId, new Date()); |
| 148 | + return getSubscription(userId); |
| 149 | +} |
| 150 | + |
| 151 | +/** |
| 152 | + * Insert this month's plan grant if it isn't there yet. Idempotent via the |
| 153 | + * primary key `plan:<userId>:<planId>:<periodKey>`. |
| 154 | + */ |
| 155 | +export async function ensureMonthlyGrant( |
| 156 | + userId: string, |
| 157 | + now: Date |
| 158 | +): Promise<void> { |
| 159 | + const subscription = await getSubscription(userId); |
| 160 | + const plan = planById(subscription.planId) ?? planById(DEFAULT_PLAN_ID)!; |
| 161 | + if (subscription.status !== "active" || plan.monthlyCredits <= 0) return; |
| 162 | + |
| 163 | + const periodKey = periodKeyFor(now); |
| 164 | + const id = `plan:${userId}:${plan.id}:${periodKey}`; |
| 165 | + const db = getDb(); |
| 166 | + const existing = await db |
| 167 | + .select({ id: creditLedger.id }) |
| 168 | + .from(creditLedger) |
| 169 | + .where(eq(creditLedger.id, id)) |
| 170 | + .limit(1); |
| 171 | + if (existing[0]) return; |
| 172 | + try { |
| 173 | + await db.insert(creditLedger).values({ |
| 174 | + id, |
| 175 | + user_id: userId, |
| 176 | + delta: plan.monthlyCredits, |
| 177 | + kind: "plan_grant", |
| 178 | + description: `${plan.name} plan — ${periodKey}`, |
| 179 | + period_key: periodKey, |
| 180 | + created_at: now.toISOString() |
| 181 | + }); |
| 182 | + } catch { |
| 183 | + // Lost a race with a concurrent accrual of the same id — already granted. |
| 184 | + } |
| 185 | +} |
| 186 | + |
| 187 | +/** Record a top-up or manual adjustment. */ |
| 188 | +export async function grantCredits( |
| 189 | + userId: string, |
| 190 | + delta: number, |
| 191 | + kind: "topup" | "adjustment", |
| 192 | + description?: string |
| 193 | +): Promise<void> { |
| 194 | + if (!Number.isFinite(delta) || delta === 0) { |
| 195 | + throw new Error("Credit delta must be a non-zero number."); |
| 196 | + } |
| 197 | + const db = getDb(); |
| 198 | + await db.insert(creditLedger).values({ |
| 199 | + id: createTimeOrderedUuid(), |
| 200 | + user_id: userId, |
| 201 | + delta: Math.trunc(delta), |
| 202 | + kind, |
| 203 | + description: description ?? null, |
| 204 | + period_key: null, |
| 205 | + created_at: new Date().toISOString() |
| 206 | + }); |
| 207 | +} |
| 208 | + |
| 209 | +/** Balance, plan, and totals — accrues the current month's grant first. */ |
| 210 | +export async function creditStatus(userId: string): Promise<CreditStatus> { |
| 211 | + const now = new Date(); |
| 212 | + await ensureMonthlyGrant(userId, now); |
| 213 | + const subscription = await getSubscription(userId); |
| 214 | + const plan = planById(subscription.planId) ?? planById(DEFAULT_PLAN_ID)!; |
| 215 | + |
| 216 | + const db = getDb(); |
| 217 | + const grantRows = await db |
| 218 | + .select({ |
| 219 | + total: sql<number>`COALESCE(SUM(${creditLedger.delta}), 0)` |
| 220 | + }) |
| 221 | + .from(creditLedger) |
| 222 | + .where(eq(creditLedger.user_id, userId)); |
| 223 | + const grantedCredits = Number(grantRows[0]?.total ?? 0); |
| 224 | + |
| 225 | + const spendRows = await db |
| 226 | + .select({ total: sql<number>`COALESCE(SUM(${predictions.cost}), 0)` }) |
| 227 | + .from(predictions) |
| 228 | + .where(eq(predictions.user_id, userId)); |
| 229 | + const spentUsd = Number(spendRows[0]?.total ?? 0); |
| 230 | + const spentCredits = Math.ceil(spentUsd / USD_PER_CREDIT); |
| 231 | + |
| 232 | + return { |
| 233 | + userId, |
| 234 | + plan, |
| 235 | + periodKey: periodKeyFor(now), |
| 236 | + grantedCredits, |
| 237 | + spentCredits, |
| 238 | + balanceCredits: Math.max(0, grantedCredits - spentCredits), |
| 239 | + spentUsd |
| 240 | + }; |
| 241 | +} |
| 242 | + |
| 243 | +/** |
| 244 | + * The pre-spend gate. `estimatedUsd` is a floor (unpriceable nodes estimate |
| 245 | + * 0), so the check is: the balance must cover the estimate, and must be |
| 246 | + * positive at all. Callers decide whether the gate is on at all |
| 247 | + * (NODETOOL_CREDITS_ENFORCED). |
| 248 | + */ |
| 249 | +export async function checkCredits( |
| 250 | + userId: string, |
| 251 | + estimatedUsd: number |
| 252 | +): Promise<CreditDecision> { |
| 253 | + const status = await creditStatus(userId); |
| 254 | + const estimatedCredits = Math.ceil( |
| 255 | + Math.max(0, estimatedUsd) / USD_PER_CREDIT |
| 256 | + ); |
| 257 | + if (status.balanceCredits <= 0) { |
| 258 | + return { |
| 259 | + allowed: false, |
| 260 | + reason: `Out of credits on the ${status.plan.name} plan. Upgrade or top up to continue.`, |
| 261 | + status |
| 262 | + }; |
| 263 | + } |
| 264 | + if (estimatedCredits > status.balanceCredits) { |
| 265 | + return { |
| 266 | + allowed: false, |
| 267 | + reason: `This run needs about ${estimatedCredits} credits but ${status.balanceCredits} remain.`, |
| 268 | + status |
| 269 | + }; |
| 270 | + } |
| 271 | + return { allowed: true, status }; |
| 272 | +} |
0 commit comments