Skip to content

feat(billing): show the add-on packs, the AI credit left and the purchases in Billing (W1-33) - #1846

Merged
gkhngyk merged 11 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w1-33-billing-packs
Oct 30, 2026
Merged

gkhngyk merged 11 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w1-33-billing-packs

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

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.

  • Tabs: AI credits ( / / / ,000) and Storage (+25 / +100 / +250 GB at / / a month), with Most picked on and +25 GB.
  • Each card says what it adds against the plan's monthly limit, e.g. "+1 monthly limit".
  • Buying: the Admin picks a pack, then Continue to payment. Storage asks first, since it charges at once.
  • Credit line: "AI credit: $X left · expires …", in the pack's own dollars; no model cost is shown.
  • Purchases list with invoice links, Admin only. Others see the packs and "Ask an admin".
  • Hidden with the flag off.
  • "Not on sale yet" shows until stripe_price_id is set.
  • Help: 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 feature

How 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

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • Web: lint, typecheck and the related tests pass (run one at a time on an 8 GB machine; build left to CI)
  • Tests added
  • Help article updated (help/chat/*, approved: false)

🤖 Generated with Claude Code

cihan-gyk and others added 7 commits October 30, 2026 01:12
…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]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

Pushed 96e285c: the add-ons card's picked tab now uses the same style as the plan tabs (#1806): bg-primary text-primary-foreground, black in light mode and white in dark. The test checks aria-pressed and the class. add-ons-card tests 11/11, lint clean.

🤖 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
gkhngyk previously approved these changes Oct 30, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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. getBillingAddOns returns purchases: null for anyone who isn't an Admin of the caller's own organization (role and organization from profiles, never from the client). That matches 00413's add_on_purchases: admin select policy. 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's organization_id before 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. creditLeftCents uses usd_total − usd_used per grant, on grants with expires_at > now. That matches leftMicros / creditRoomUsd in server/src/lib/ai-credits.js. The "expires" date is the soonest end among grants with credit left, which is the grant drawCredits takes from first. Converting to the pack's own dollars (price ÷ grant) rounds down. The monthly limit a pack is measured against follows applyPlanOverrides (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 same subscription_status checks as startAddOnPurchase, 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.ts reads 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 still bg-background, so the two differ for a while.
  • Client imports. add-ons-card.tsx imports the server actions and types only. plan-row.test.ts passes.
  • No migration, no new embed, no new write route. The new route is a GET, and subscription-guard-coverage.test.ts passes.

Follow-ups (not blocking)

  1. Billing's AI usage card vs the credit line. getAiUsage still 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: before CHAT_AGENTIC is turned on for customers, the usage read should know about credits left. It could return a creditLeft flag, so the card, banner and meter can say "running on AI credits" instead of "stopped".
  2. 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.
  3. 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.
  4. 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 BillingAddOns would let the card say so up front.
  5. Merge order with #1818. Both PRs add a card next to <AiUsageCard /> in billing-section.tsx and 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
gkhngyk previously approved these changes Oct 30, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@gkhngyk
gkhngyk merged commit 82766c1 into ansvisor:main Oct 30, 2026
4 of 5 checks passed
@github-actions github-actions Bot removed the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants