Repository navigation
feat(billing): show the add-on packs, the AI credit left and the purchases in Billing (W1-33) - #1846
Conversation
…iles, Help and add-on packs Chat's Wave 1 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC: nothing reads or writes them while the flag is off. Tables, types and the demo's coverage only; the code that uses them comes in the Wave 1 PRs. - 00407: chat_conversations gets shared_at (Share with team: every member of the workspace reads it), last_read_at (unread results), deleted_at (Delete with Undo; deleted chats are hidden from every member) and a title search column; chat_messages gets context_json (what a person's message was scoped to) and a text search column. 'simple' text search, so a chat in any language is found. The author policy now leaves deleted chats out, and a shared policy reads shared ones. - 00408: chat_user_prefs gets the rest of Settings › General and the one-time notices: rail_open, panel_size, default_mode, answer_language, notify_via, show_thought, panel_on_pages, focus_prompted_at, usage_notice_period, legacy_imported_at. - 00409: chat_uploads and the private bucket chat-uploads: 10 MB a file, the composer's 11 types, 5 a message (a trigger backs the server's check), kept 90 days. - 00410: chat_tool_cache (a chat's read results by tool and scope, server only) and each step's and model call's measure: latency, cache hit, truncation, result tokens on chat_run_steps (never granted to members), prompt cache read/write tokens and latency on the ledger. - 00411: chat_files (filed deliverables and saved answers, the workspace's, kept a year, searchable by title, summary and tags), chat_file_task_links, chat_storage_usage kept by a trigger, and the private bucket chat-files. - 00412: help_answer_cache and help_gaps (server only, no workspace or person ids). - 00413: add_on_products seeded with the owner's packs (AI credits $10, $50, $250, $1,000 at half their price in budget, 12 months; storage +25/+100/+250 GB at $5/$15/$29 a month; $50 and +25 GB Most picked), add_on_purchases (Admins read), ai_credit_grants and storage_grants (server only), and prompt_improve_usage.grant_id. Members only ever read; every write is the server's. Tool names, tool results and dollars stay server only. web/src/types/supabase.ts carries the new tables and columns; schema.test.ts checks the policies, the server-only tables, the limits and the seeded packs from the SQL; steps.test.ts keeps the step measure out of the member columns. The demo coverage skips chat_files and chat_tool_cache (a person's own Chat work). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…Stripe webhook
CHAT-18 (W1-31), behind CHAT_AGENTIC, on 00413's tables. An Admin of a
workspace on a paid, active plan buys a pack; nothing is granted before
Stripe says it was paid.
- Buying (startAddOnPurchase, a server action that never throws): AI
credits open a Stripe Checkout in payment mode with an invoice; storage
is a monthly item on the plan's subscription, prorated and charged to
the card on file at once (a declined card fails the purchase with
Stripe's words). A pending add_on_purchases row is written first and
every Stripe object names it. Refused for non-Admins, the free trial, a
plan that isn't active, Chat off, and a pack without a Stripe price
("unavailable", no Stripe call); storage also on a plan billed yearly.
- Granting (the webhook, before the plan's handlers): checkout.session
.completed / async_payment_succeeded and the pack's invoice.paid write
one ai_credit_grants row (half the price in model cost, 12 months from
the payment); invoice.paid with a storage item writes storage_grants
until the period's end and moves it on at each renewal. A purchase is
paid once (only from pending) and a grant written once (unique
purchase_id), however often or early the event comes; an item not yet
written down is found by its pack's price. A full charge.refunded takes
back the unused credits or ends the storage, and a refunded pack isn't
renewed. A pack's invoice never changes the plan's status.
- Spending (server): with Chat on, a hold passes on the credits once the
included budget is spent (creditRoomUsd), and a charged call's cost past
the included budget is drawn from the grant ending soonest, its ledger
row split by grant_id (drawCredits), for Chat's steps and every other AI
feature. Credits outlive the monthly reset; own-key rows never touch
them.
- The plan's routes take the plan's subscription item, never a pack's.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e plan themselves startAddOnPurchase refuses a workspace without an active, paid plan itself (trial, no_plan), answering a reason rather than throwing, as prepareImageUpload and Chat's settings do: the read-only coverage test lists it with why. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hases in Billing
CHAT-18 (W1-33), on W1-31, behind CHAT_AGENTIC: Settings › Billing gets an
Add-ons card under the AI usage card; nothing renders while Chat is off.
- Packs: AI credits and Storage tabs; each card is the "Get more"
window's pack card (price, what it adds, validity, Most picked on $50
and +25 GB). What an AI pack adds is a share of the plan's own monthly
AI limit ("+20% of the monthly limit", "+5 monthly limits"), worked out
on the server; a pack without a Stripe price reads "Not on sale yet".
- Buying: Admins pick a pack and Continue to payment; AI credits go to
Stripe Checkout, storage asks first (it is charged at once) and says
so when the card is declined. Others see the packs and "Ask an admin";
the trial and a plan not active say why they can't buy.
- "AI credit: $X left · expires {date}": the credits still valid, in the
packs' own dollars (what was paid, never the model cost), ending with
the soonest. Dollars stay on Billing; Chat and the model get none.
- Purchases (Admins): date, pack, price, status, what's left and the
invoice, through GET /api/add-ons/invoice/{id} (Admins of the
purchase's workspace, sent on to the PDF).
- getBillingAddOns never throws; texts in settings.addOns; theme tokens
with dark: variants. Help: help/settings/add-ons.md (approved: false).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s it lib/stripe.ts makes its client when it is loaded and throws without STRIPE_SECRET_KEY (local development, self-hosted). The add-on actions imported it at the top, so on Settings, whose server actions are bundled together, every action beside them broke with it (Billing's AI usage card among them). loadStripe (lib/billing/add-ons.ts) imports it on demand and gives null without the key: a purchase then answers "unavailable", and the webhook's lookups load it only when they run. lib/stripe.ts and its routes are as they were. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ling-packs # Conflicts: # web/src/lib/actions/add-ons.ts
The add-on invoice route imported lib/stripe.ts at the top, which throws without STRIPE_SECRET_KEY: it now loads it through loadStripe when an Admin opens an invoice, and answers 404 without the key. The test without a key also reads Billing's packs and credit line: they never touch Stripe. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… dark, as the plan tabs AI credits / Storage in Settings › Billing › Add-ons marked the picked tab with bg-background in a muted track, which read as unpicked in the dark theme. It now uses bg-primary text-primary-foreground, as the plan tabs (ansvisor#1806) and the Get more window do; the test checks the picked tab by aria-pressed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Pushed 96e285c: the add-ons card's picked tab now uses the same style as the plan tabs (#1806): 🤖 Generated with Claude Code |
…heckouts, and let pages use purchased AI credits
- A full refund of a storage pack now takes its item off the plan's
subscription (no proration), so it isn't charged each month for storage
it no longer grants. An item already gone is fine; any other Stripe error
answers 500 so Stripe sends the event again.
- checkout.session.completed grants AI credits only when payment_status is
'paid' ('no_payment_required' never grants).
- getAiUsage says whether purchased credits are left (a boolean, no
dollars), and aiUsageTone stays a warning at 100% while they are, so the
Content Editor, the banners and Chat's composer don't say "used up" while
calls still run on the credits. The Improve tab's quota counts them too.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
gkhngyk
left a comment
There was a problem hiding this comment.
Reviewed #1846's own commits on top of #1845 (b14c910f3, the merge of #1845's Stripe fix, 2eb3b64ba, 96e285c9e). Approving. Notes below are follow-ups, none blocking.
What I checked
- Purchases are Admin only, on the server.
getBillingAddOnsreturnspurchases: nullfor anyone who isn't an Admin of the caller's own organization (role and organization fromprofiles, never from the client). That matches 00413'sadd_on_purchases: admin selectpolicy. Members see the packs and the credit line only, and the action test covers both sides. - Invoice links.
GET /api/add-ons/invoice/{purchaseId}checks the id shape, the signed-in user, Chat on for their organization, and the Admin role. It then looks the purchase up by id and the caller'sorganization_idbefore calling Stripe. Another workspace's purchase is a 404, and Stripe isn't called. The browser only gets a purchase id. The Stripe invoice id stays on the server, and the redirect goes to the URL Stripe returns for that invoice. The test covers the other workspace, a bad id, a non-Admin, flag off, and no Stripe key. - Credit left.
creditLeftCentsusesusd_total − usd_usedper grant, on grants withexpires_at > now. That matchesleftMicros/creditRoomUsdinserver/src/lib/ai-credits.js. The "expires" date is the soonest end among grants with credit left, which is the grantdrawCreditstakes from first. Converting to the pack's own dollars (price ÷ grant) rounds down. The monthly limit a pack is measured against followsapplyPlanOverrides(Enterprise's own budget only when it's a number ≥ $50), so "+N monthly limits" matches what the server holds. - Buy states.
buy(open/trial/no_plan) uses the samesubscription_statuschecks asstartAddOnPurchase, and the server refuses non-Admins and trials whatever the UI shows. - Stripe loaded lazily. The invoice route and the action file now reach Stripe only through
loadStripe().add-ons-without-stripe.test.tsreads Billing's packs and credit with no key. - Tabs. The picked tab is
bg-primary text-primary-foreground: near-black in light, light grey with dark text in dark. That matches #1806's period toggle. Until #1806 merges, main's plan toggle is stillbg-background, so the two differ for a while. - Client imports.
add-ons-card.tsximports the server actions and types only.plan-row.test.tspasses. - No migration, no new embed, no new write route. The new route is a GET, and
subscription-guard-coverage.test.tspasses.
Follow-ups (not blocking)
- Billing's AI usage card vs the credit line.
getAiUsagestill measures the plan's included budget only. A workspace that has used up its month but still has pack credit sees "Used up. AI features stop until …" on the AI usage card. Right below it, the Add-ons card says "AI credit: $X left", and the server lets calls through on the credit. This is the same point raised on #1840: beforeCHAT_AGENTICis turned on for customers, the usage read should know about credits left. It could return acreditLeftflag, so the card, banner and meter can say "running on AI credits" instead of "stopped". - Credit line and the 200-row read. Grants are matched to their pack through the newest 200 purchases, and abandoned Checkouts count toward those 200. A workspace with many abandoned Checkouts could drop an older grant from the credit line, while the server still counts it. Reading the grants' purchases by
purchase_id(.in('id', …)) would remove that dependency. - Trial line. "Trials can't buy packs. Choose a plan to buy them." could link to Start my plan now once #1818 is in. That button already exists for admins in a trial.
- Storage on a yearly plan. The card offers storage packs to an Admin on a yearly plan, and the server then answers "This pack can't be bought right now." The help article says storage needs a monthly plan. Passing the billing period in
BillingAddOnswould let the card say so up front. - Merge order with #1818. Both PRs add a card next to
<AiUsageCard />inbilling-section.tsxand its test. Whichever lands second resolves a small adjacent-lines conflict.
Tests
On the PR head (it already contains the latest main): web tsc clean; eslint and prettier clean on the changed files; the billing, add-on, Stripe route and guard tests pass (25 files / 203 tests), including plan-row.test.ts and subscription-guard-coverage.test.ts. Full web vitest: 661 of 664 files pass. The content editor's page.test.tsx fails the same way on main with our local dependencies, so the cause isn't this PR. Two timing tests pass when run alone.
gkhngyk
left a comment
There was a problem hiding this comment.
Still good with cca3635, a clean merge of #1845's fixes (a refunded storage pack now leaves the subscription, the usage API says whether bought credit is left, and credit is granted only on a paid Checkout). On this branch, tsc is clean and the settings, billing, Stripe route and plan-row tests pass (391).
gkhngyk
left a comment
There was a problem hiding this comment.
Merging in order with the other approved Chat PRs. This head merges current main; where they overlapped, both sides are kept. Its tree is what main will be after this squash, checked with the full server and web suites, tsc, lint, format and next build. Chat stays behind CHAT_AGENTIC.
Summary
Chat Wave 1, behind
CHAT_AGENTIC. Stacked on #1845 (W1-31). The diff against main includes the PRs below it until they merge. The product owner saw this in a local preview and approved it.W1-33: Billing › Add-ons.
stripe_price_idis set.help/settings/add-ons.md.Open product questions, not in this PR: which plans may buy packs, and own keys only on Custom, are being settled with the product owner.
No migration, no new dependency.
Related issue
Part of Chat (Wave 1, CHAT-18).
Type of change
feat— New featureHow to test
Billing on an active cloud plan: the Add-ons card, tabs, Most picked, "Not on sale yet" while prices are empty. Tests: 136 files / 1,113 tests at the tip.
Checklist
help/chat/*,approved: false)🤖 Generated with Claude Code