Skip to content

feat(billing): sell AI credit and storage packs, granted only by the Stripe webhook (W1-31) - #1845

Merged
gkhngyk merged 6 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w1-31-add-ons
Oct 30, 2026
Merged

gkhngyk merged 6 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-w1-31-add-ons

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Chat Wave 1, behind CHAT_AGENTIC. Stacked on #1812 (W1-DB). 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-31: AI credit and storage packs, granted only by the Stripe webhook (CHAT-18).

  • Purchase: startAddOnPurchase, Admin only; it never throws.
    • AI credit: a one-time Checkout (payment mode, invoiced).
    • Storage: a monthly item on the plan's subscription, prorated and charged to the saved card at once.
    • Refused: in a trial, on an inactive plan, with the flag off, for non-admins, and for a pack without stripe_price_id (unavailable, Stripe never called).
  • Grants come only from the webhook (checkout.session.completed, invoice.paid, charge.refunded).
    • Credit: budget = price ÷ 2, valid 12 months.
    • Storage: until the paid period's end, extended on each renewal.
    • Idempotent: the same event twice gives one grant.
    • Full refund: takes back unused credit or ends storage.
  • Spending (server): the month's included budget first, then the soonest-expiring credit. The ledger row is split with grant_id where the limit is crossed. Own-key usage never touches credit.
  • Plan changes apply to the plan's own item, not the storage item.
  • Stripe is loaded lazily (loadStripe()), so Settings works without STRIPE_SECRET_KEY, as on self-hosted installs. A test proves the module loads and a purchase returns unavailable without the key.

No migration, no new dependency.

Related issue

Part of Chat (Wave 1, CHAT-18).

Type of change

  • feat — New feature

How to test

Tests: webhook grants, idempotency, refunds, the spending order, a pack without a price, and the module without a Stripe key. Server 4,503 tests.

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 4 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]>
…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]>
…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.

Looks good with a77230f (one fix commit on this branch, described below).

I reviewed only what this PR adds on top of #1812 (af43140df..894cebd9c). #1812's head hasn't moved since. I covered the purchase action, the webhook's pack handling, the plan route's planItemOf, and the credit draw on the AI budget. The fixes are on take-1845 in one commit, each with a test that fails without it.

What the fix commit changes

  1. A refunded storage pack keeps getting charged. On a full refund, refund() ends the storage grant and marks the purchase refunded. The pack's item stays on the plan's subscription, though, so every renewal invoice charges for it. grantStorage then skips the refunded purchase, which means the workspace pays each month and gets no storage. Your test "no renewal brings it back" checks the grant side, but nothing removes the item.
    Fix: on a full refund of a storage pack, removeStorageItem deletes its subscription item with proration_behavior: 'none', since the refund already settled the money. If Stripe answers resource_missing, the item is already gone and that's fine. Any other error throws, so the webhook answers 500 and Stripe sends the event again; the purchase stays paid until then.

  2. The pages say "used up" while credits are left. The server's hold counts the credits (creditRoomUsd), but getAiUsage still reports the plan's share alone. At 100%, aiUsageTone returns exhausted, and then:

    • the Content Editor's agent buttons switch off (aiUsedUp)
    • the banners say the allowance is used up
    • with #1840, Chat's composer turns off (chatAtCap reads aiUsageTone)
    • the Improve tab's quota (getImproveQuotaStatus) gives remainingUsd 0 and exhausted: true

    So a workspace that just bought credits can't use them from the UI.
    Fix:

    • creditsLeftUsd(orgId) in ai-credits.js returns 0 with Chat off.
    • getAiUsage returns creditsLeft (a boolean, no dollars), and aiUsageTone stays warning at 100% while credits are left.
    • getImproveQuotaStatus counts the credits the same way reserveAiBudget does: budget + creditRoomUsd − spent, with percentLeft capped at 100.
    • The meter still shows 100% of the plan's share. #1846's "AI credit left" line can explain the rest.
  3. Grant on payment_status === 'paid' only. checkout.session.completed granted on anything but unpaid, so no_payment_required also granted. No current path gives a pack Checkout that status, because Checkout gets no discounts or promotion codes, but the grant should depend on being paid.

Suggested commit: fix(billing): stop billing a refunded storage pack, grant only paid Checkouts, and let pages use purchased AI credits.

Checked and fine

  • Who can buy: the check runs on the server, in this order: signed in, Chat on for the workspace, role = 'admin' read from profiles with the service client, cloud, subscription_status = 'active'. A trial gets trial and anything else gets no_plan. The workspace is always the caller's own, from profiles. The browser sends only a product id, checked by regex. The Stripe price comes from add_on_products, and a pack without stripe_price_id or not active is never sold. No amount or price id from the client reaches Stripe. The action is listed in OPEN_ACTIONS with a reason, and subscription-guard-coverage passes.
  • Webhook: the signature is checked before handleAddOnEvent. Grants come only from checkout.session.completed / async_payment_succeeded when paid, or from invoice.paid. A return from Checkout grants nothing.
  • Replays: grants are upsert … onConflict purchase_id, ignoreDuplicates, so purchase_id is unique. markPaid only moves a purchase from pending. stripe_checkout_session_id and stripe_subscription_item_id are unique. The dry run below confirms each on the real schema.
  • Organization: every grant takes organization_id from the purchase row (purchase.organization_id), never from Stripe metadata or the customer. claimByPrice only looks at pending purchases of the workspace that owns the invoice's customer. So the mismatch #1812's review raised can't come from this code. The composite FK stays a nice-to-have for the schema.
  • Plan handlers: pack Checkouts and pack-only invoices return true and skip the plan's handlers. A declined storage invoice doesn't set past_due, and an AI invoice doesn't set active. Plan changes use planItemOf, so a storage item is never swapped for the plan's price.
  • Credit draw: the included budget is used first, then the grant that ends soonest. A row that crosses the line is split by grant_id, own-key rows are never drawn, and nothing is read with Chat off. ai_usage_by_feature sums the split rows (dry run), so the meter's total is still the true spend.
  • Storage cap: nothing in this PR reads storage_grants yet. #1856 does (readChatStorage, active_until > now), so the cap goes up once both land.
  • Embeds: none. Migrations: none of its own (00413 is #1812's).
  • Client bundle: plan-row.test.ts passes on the merge with main. add-ons.ts loads Stripe lazily, and its no-key test passes.

Follow-ups (not blocking)

  1. Disputes aren't handled. After a chargeback, the unused credits or the storage stay. Handling charge.dispute.funds_withdrawn the same way as a full refund would cover it. Until then staff handle it in Stripe, which emails every dispute. Partial refunds are also left to staff, as the PR says.
  2. Buying the same storage pack twice fails. Stripe won't take two items with the same price on one subscription. The second purchase gets a generic failed and its row stays pending. Raising the existing item's quantity, or refusing up front, would read better.
  3. Storage and yearly plans don't mix. With a storage item on, switching the plan to yearly fails in Stripe, because the items' intervals must match. The plan route returns an error. The page could say why, or the pack could move with the plan.
  4. A plan cancelled to its period end (#1823) can still buy credits. Those credits stop counting once the plan ends, since there's no active plan. Consider refusing a purchase when cancel_at_period_end is set.
  5. The draw isn't atomic. If splitRow fails after takeFromGrants, the credit is used while the row stays on the included budget, so that cost is counted twice. It's logged. A single RPC would close this.
  6. Credits count only with Chat on. If Chat is turned off for a workspace that bought credits, the budget goes back to the plan's own. That matches the flag, but keep it in mind for any rollback.
  7. cancelled is never set. Nothing marks a storage purchase as cancelled when its item or the plan's subscription ends. The grant still lapses at active_until, but the history keeps showing paid.
  8. Subscription coupons apply to the storage item. A coupon on the plan's subscription also discounts the storage item, and a 100% one makes it free. Decide whether that's intended.

Merge status

  • Base: #1812 at af43140df (unchanged).
  • On main: take-1845 merges cleanly into origin/main (a8121a6c8).
  • Other PRs: no textual conflicts with #1804, #1806, #1818, #1823, #1840 or #1846. #1846 changes add-on-webhook.ts only through the merge of this branch, so it needs this fix merged in. #1840's chatAtCap picks up the creditsLeft change through aiUsageTone with no change of its own.

Tests (on take-1845)

  • Server: the full suite passes, except 8 regex/parse timing tests that fail under load. All of them pass when run on their own, and this PR doesn't touch them. chat-budget.test has the new credit test, and demo coverage passes.
  • Web: vitest for lib/billing, lib/chat, the add-on actions, the Stripe routes, ai-usage components, subscription-guard-coverage and plan-row: 47 files, 622 tests. tsc --noEmit is clean, and eslint and prettier are clean on the touched files.

gkhngyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 30, 2026
gkhngyk added a commit to cihan-gyk/ansvisor that referenced this pull request 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.

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 a3becb2 into ansvisor:main Oct 30, 2026
7 of 9 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