# Stripe payments — take real money into the owner's own Stripe account

> Taking real money, one-time, through Stripe: pay a bill, check or invoice, tip, donate, sell tickets or products, deposit, dues, checkout, Apple Pay, Venmo, Cash App, Zelle, Chime; not Square (square), recurring (stripe-subscriptions) or orders only recorded

Source: https://good.vibes.diy/docs/reference/stripe

**The moment this is for: someone pays, and the money is in the owner's own account.** The regulars settle the tab from their table, a neighbor chips in for the block-party band, a fan who followed a link buys the last print, a caller pays for the reading they just had. The built-in way there: the payer arrives as a guest, pays on Stripe's own page, and the order turns paid when Stripe says so. This recipe is one payment made at the press of Pay, so a running tab, a balance kept in the app or by-the-minute charging lands on that shape too, as a pack bought up front or one payment when the thing is done.

When someone asks to **take money** — pay the bill at a table, split the check,
take tips or donations, charge for a booking, collect dues, sell tickets, take
a deposit, sell a download, have a client pay an invoice — build it on **Stripe
Checkout** from `backend.js`, through `ctx.stripe` — the owner connects their
Stripe account once with **Connect Stripe**, and the platform holds the
credential. This is a `backend.js` feature (see the backend docs for the
general handler contract); this page is the recipe that keeps every Stripe call
on the server, keeps "paid" a fact only Stripe can establish, and keeps every
order honest about where it is.

**This skill comes in only when the person asks for payment.** A storefront that
records orders, a plans page that records requests, a booking page that holds a
slot — each of those takes no money and says so in its own words, and they stay
that way until the person asks to charge for them. What you may do unasked is
**offer** it: on an app that sells, books, collects dues or sells tickets, the
closing row's capability option is `▸ [pay] Take card payments with Stripe`,
gold when nothing else fits better, and a tap on it is the ask. Words that are
the ask: "charge", "pay", "paid", "payment", "pay the bill", "split the check",
"tip", "donate", "deposit", "dues", "tickets", "sell", "buy now", "purchase online",
"checkout", "pay an invoice", "pay the invoice online", "bill a client", "Stripe",
and a named payment app — "Apple Pay", "Cash App", "Zelle", "Venmo", "Chime".
Words that are not: "orders",
"price", "plans", "cart" — those describe records, not money moving. "Invoice"
on its own is not the ask either: an invoice maker where the owner writes
invoices and marks them paid by hand is bookkeeping, and stays that way until
the person asks for the client to pay through the app.

**A shop's bag is line records from the first Add, for every visitor.** Each
Add is one `database.put` of that product's `line` record (`bagId`,
`productId`, `qty`): a signed-in buyer's lines name their `bag` record, and a
visitor's lines name `bag-<guestKey>` and stay on their device until sign-in.
The bag on screen is `useLiveQuery("bagId", { key })` read back, so it is there
after a reload, and Pay sends those lines. § _A shop with a bag_ has the page.

**Named payment apps are the ask too.** A person who names how buyers should
pay — Apple Pay, Google Pay, Cash App, Zelle, Venmo, Chime — is asking to take
money, and this skill answers it. Card, Apple Pay, Google Pay and Cash App Pay
all ride one Checkout Session and mark the order paid on their own, so Checkout
is the primary button and the reply says so in one line: "Card, Apple Pay and
Cash App Pay go through Stripe, which marks the pass paid by itself." Zelle,
Venmo and Chime have no checkout; when the person keeps one, it is a manual
lane beside Checkout, never in place of it: the owner types their own handle
on the Setup screen into an empty field with no sparkle and no example handle
(an invented handle sends a real buyer's money to a stranger), the buyer taps
**I sent it**, and the order waits for the owner's Approve.

**One-time charges only.** This recipe takes a payment and records that it
happened. It does not mirror a Stripe subscription — cancellation, a failed
renewal, an expiry — so a "subscription" or "paid tier" built on a permanently
`paid` order would keep unlocking after billing stopped. Build recurring money
as a one-time charge per period the app can see (annual dues, a season pass),
say so plainly, and leave
`mode=subscription` out of this recipe. A real subscription — a paid newsletter,
a monthly club — is the `stripe-subscriptions` skill, which mirrors Stripe's
subscription state into the app and takes the person's cancellations and failed
renewals into account.

**The money is the owner's, and so is the account.** Every payer pays the same
Stripe account, the one the owner connected; the app is a merchant's page. An
app where *each visitor* collects money into *their own* Stripe account is a
marketplace, a bigger thing than this recipe — say so plainly and build the
one-merchant half.

**The price list is the owner's, and it lives in the app.**

The price list is the owner's: each thing for sale is a product record in the app's own database that only the owner writes, from the app's own screen, and backend.js charges the price it reads from that record — never an amount the browser sends, never a constant in backend.js.

The owner lists what they sell, sets each price, changes it next week and takes
a thing off sale, all from the app's own **Products** screen with no new build
— and asking the builder to "add a $12 bag of the Ethiopian" writes the same
record the screen does. `access.js` takes a `product` record from the owner
alone and checks its price is whole cents. The live catalog starts empty: the
app's code writes no product, so the owner's first view is the form for their
first product, and a buyer sees *Nothing for sale yet* until there is one. A
`seed.json` may carry a few believable products for the screenshot; they reach
the live app only when the owner asks for the examples, and the owner prices
them there like any other. A price change applies to the next purchase; an
order keeps the price it was made at.

The owner's Setup and Orders each get their own page, reached from owner-only buttons in the app's header, so the shop page stays the page buyers shop on.

Products is a page of its own too, beside them: the owner opens **Setup** to finish connecting Stripe, **Orders**
to see every order and subscriber, and **Products** to change the list, each
from one press in the header. A buyer sees none of those buttons.

**Who pays: anyone, signed in or not, unless the owner asks for sign-in.**

Anyone can pay: checkout takes a guest by default, so a visitor with no Vibes DIY account fills the bag and presses Pay, and sign-in is asked for only when the owner's own request asks for it.

Stripe's own page asks every buyer for their email and sends the receipt, and
security rests on Stripe, not on a sign-in: the backend reads every session
back from Stripe before anything counts as paid. So a shop, a bag, tickets, a
class, a print, a preorder — every one-time sale — opens to whoever arrives.
The order records the buyer's handle when they happen to be signed in, and a
guest's order is just as real: the owner sees it on **Orders** with Stripe's
receipt behind it, and the guest's return page thanks them for it.
*Complete backend.js* below is that recipe, and *A shop with a bag* builds on
it.

A payment to a venue is guest checkout: the payer needs no Vibes DIY account, the payment record is keyed to the thing being paid and its Checkout Session, and backend.js writes it on the guest's behalf.

A restaurant check, a split-the-check page, a tip jar, a donation page, a
pay-at-the-counter page, a client paying an invoice — the payer is a guest at
the owner's place, and the record belongs to the thing being paid rather than
to a buyer. *Guest checkout at a venue* at the end of this page is that recipe,
with a table's check as the worked example, and *Invoices* after it is the same
recipe for a client paying a bill.

Sign-in is the owner's choice to make. When the request asks for it — members
only, a dues roster that lists who paid, a "my orders" or "my tickets" page
people come back to on any device — `/checkout` adds its one sign-in line (shown
in the recipe) and the page offers sign-in beside Pay. Every subscription signs
in too, because the subscriber manages it later (the `stripe-subscriptions`
skill). Sections 1 to 6 hold for every shape.

## 1. The setup item: Connect Stripe

The owner connects Stripe, once. The Setup surface it lands on — the
owner-only entry in the app's navigation, the verdict from `/setup`, the
re-read on focus that unlocks the Pay buttons in place — is the use-vibe
docs' *Some apps need setup before they work*; this recipe contributes one
item to it. The Stripe item is Connect Stripe: the backend reads ctx.stripe.status(), the item is done when the mode the app charges in reads ready, and its steps link this vibe's Settings tab, where the owner presses Connect Stripe under Payments.
The steps are written for someone who has never opened Stripe, so each one is
a link to the exact page and uses the words that page uses:

1. Open this vibe's **Settings** tab on vibes.diy:
   `https://vibes.diy/vibes/mine/<ownerHandle>/<appSlug>/settings` (that is
   **My Vibes** → this vibe → **Settings**), and press **Connect Stripe** under
   **Payments**. Stripe opens its own setup pages: sign in with a Stripe login
   or create one there, and answer Stripe's questions about the business. The
   Stripe account belongs to the owner's Vibes DIY account and serves every
   app they make, so it is connected once; an app that takes money for a
   friend lives on the friend's own account, where they connect their Stripe.
2. Come back to the app. The Pay buttons work in test mode the moment Stripe
   says the account is ready, with no redeploy; the card
   `4242 4242 4242 4242` with any future date pays.
3. Go live, one app at a time. Once a test payment goes through, press **Go live with Stripe** under
   **Payments** on the Settings tab and finish Stripe's live setup (once, for
   every app). Then press **Take live payments in this app** on this app's
   Setup screen. This step stays on the Setup screen after the item is done,
   with a badge that reads *Test mode* until this app takes live payments.

Those steps are the item's copy on the Setup surface, with the vibe's real
handle and slug filled in from the `ownerHandle` and `appSlug` the `/setup`
route hands over: `https://vibes.diy/vibes/mine/<ownerHandle>/<appSlug>/settings`
for where the button is, and **Connect Stripe** and **Payments** in so many
words. "The Settings page" is a direction to search for, and a person who has
never seen it has to go looking. In the consumer flow, a Pay button whose item
is not done reads *Checkout is not open yet*; the owner's Setup entry is where
the steps are. A Stripe account that reads `disconnected` is the paused state,
and its page is a finished one (§ 5).

The owner pastes nothing: the platform holds the credential and attaches it
to every call, and the backend names only which of the owner's two accounts —
test or live — a call is for.
An app made before Connect Stripe, whose `backend.js` already reads
`ctx.secrets.STRIPE_SECRET_KEY`, keeps that helper as it is: an edit to it
changes what was asked and leaves its payments where they are, and it moves to
`ctx.stripe` only when the owner asks to switch to Connect Stripe. Every new
payment app is built on `ctx.stripe`.

### Test mode first, live one app at a time

`ctx.stripe.status()` answers `{ test: { available, state }, live: { available,
state } }`. `available` says whether vibes.diy takes payments in that mode on
this deployment; `state` is the owner's account in that mode: `absent` (not
connected yet), `onboarding` (Stripe is still collecting the owner's details —
the Settings button reads **Finish Stripe setup**), `ready` (card payments on)
or `disconnected` (the button reads **Connect Stripe again**).

When the owner asks to disconnect Stripe or remove vibes.diy's access, the reply
names the route: **Disconnect** under **Payments** on the app's **Settings**
tab pauses payments in every app they make, leaves their Stripe account and its
payments as they are, and **Connect Stripe again** brings the same account
back. Anything else about their account goes to `help@vibes.diy`.

The Stripe account is the owner's and serves every app they make, so the live
account turning `ready` says the owner can take real money, not that **this**
app is done rehearsing. Going live is the owner's choice per app:

An app charges in live only after its owner chooses live for this app, and from then on live is its only account: a live account that is not ready closes checkout until the owner reconnects.

The Pay request carries the mode the buyer was shown, and the backend opens Checkout only when it matches the mode the app charges in now.

- The choice is a `setup:live` document the backend writes when the owner
  presses **Take live payments in this app** on the Setup screen, offered once
  `live.state` reads `ready`. Without it the app charges in **test**; with it,
  in **live**. The mode comes from that document alone, so a slow or failed
  status read never moves an app between accounts.
- A live app stays live. A live account that reads `onboarding` or
  `disconnected` closes checkout, and the Setup item names the button that
  brings it back; the test account keeps its rehearsal role.
- `/setup` hands the `mode` to everyone, and the Pay request carries the mode
  the buyer was shown. The backend compares it with the mode it charges in
  now, and a page that still shows the other mode is asked to refresh before
  any Checkout opens.
- While the mode is test, the Pay button sits beside a *Test mode* badge. The
  owner sees the test card `4242 4242 4242 4242` to rehearse with; buyers read
  that test purchases end when the app goes live.
- Every order keeps the mode it was made in and settles in that mode, and the
  app counts only orders made in its current mode: after going live, a paid
  test order reads as a rehearsal and unlocks nothing.
- The Go-live step reads `live.available`, which `/setup` hands the owner as
  `liveOpen`. While it is true, the step names the **Go live with Stripe**
  button; until then, the step says test mode runs the whole flow end to end
  and that the Go live button appears on the same Settings tab when vibes.diy
  opens live payments. A live app whose `liveOpen` turns false tells its owner
  that vibes.diy has paused live payments, in its own words.

## 2. Stripe stays on the server, and so does Stripe.js

Every Stripe request is made in backend.js with ctx.stripe.fetch(path, { method, body, headers, mode }); App.jsx never calls api.stripe.com and never loads Stripe.js.

The client talks to the app's own `/_api/...` routes, and the backend holds no
Stripe credential at all: `ctx.stripe.fetch` sends the call to the platform,
which attaches the key and the owner's account and hands back Stripe's own
`Response`. `path` is the Stripe API path from `/v1` (`/v1/checkout/sessions`),
`body` is the form as a `URLSearchParams`, `headers` carries the
`Idempotency-Key`, and `mode` is `"test"` or `"live"`. The calls this recipe
makes — create a Checkout Session and read it back — are calls `ctx.stripe`
carries, along with expiring an open session.

Stripe.js is not needed either: **Stripe Checkout is a page Stripe hosts.** The
backend creates a Checkout Session and gets back a URL; the browser opens that
URL; Stripe renders the card form, handles 3-D Secure, Apple Pay, Google Pay and
every regional method the owner has turned on; and the buyer lands back on the
app. Nothing about the card ever touches the app's code or its documents, which
is also why the app has no PCI question to answer.

Checkout opens in a new tab with window.open, because the app runs inside a frame that cannot navigate the page around it.

`window.location = url` would navigate only the app's own frame, leaving Stripe's
page boxed inside the app's chrome, and the frame is not allowed to redirect the
page around it. `window.open(url, "_blank")` is allowed, so the pay button calls
the backend, then opens the returned URL in a new tab from inside the click
handler (a tab opened later, after an `await`, is a popup the browser blocks).
Say in the button's own copy that Stripe opens in a new tab. `window.open` can
still answer `null` when a browser blocks it; check that before asking the
backend for anything, so a blocked tab costs no order. And a Pay button is
disabled from the click until the tab is on its way, so a double tap does not
start two purchases.

## 3. One order, then one Checkout Session

The order exists before the money moves. The `/checkout` route runs as
whoever pressed Pay (the page calls it with `apiFetch`, so `ctx.userInfo` is
set when they are signed in), writes an `order` document in `pending` with the
buyer's handle when there is one, the title, the amount and the mode it is made
in, and only then asks Stripe for a session for exactly that order. A guest's
order carries `buyerHandle: null` and a `guestKey`, the random id their page
keeps for them, so their second press finds the same attempt. A guest's payment
goes the same way once it has reserved its share of the check (*Guest
checkout at a venue*).

Every order records the mode it was made in, and every ctx.stripe.fetch call for that order passes the order's own mode.

- The order's `mode` is the app's current mode — test until the owner takes
  this app live, live after — and the session, the read-back and the sweep
  all use the order's own `mode`. A test order is a test-mode session on the
  owner's test account and stays one, so after the app goes live a pending
  test order still settles (or expires) where it was made. (This `mode` is the option
  `ctx.stripe.fetch` takes; the form's own `mode=payment` is Stripe's Checkout
  field, and both are always there.)
- The whole payment lands in the owner's own Stripe account: the session carries the line items, the order's ids and the return URLs, and Stripe pays the merchant directly.
- `mode=payment`, always: one charge, one order (see *One-time charges only*).
- The price is inline `price_data` — currency, `unit_amount`, a product name —
  so the owner never has to create products in the dashboard first.
- `branding_settings[display_name]` is the app's own name, the one its header shows, so Checkout opens with "Pay <app name>" rather than the name on the owner's Stripe account, which serves every app they connect. The backend holds it as a `SHOP_NAME` constant.
- `client_reference_id` and `metadata[orderId]` both carry the order's `_id`, so
  the session names the order from Stripe's side too.
- `success_url` and `cancel_url` are the app's public address with the order in
  the fragment: `https://vibes.diy/vibe/<owner>/<slug>#paid=<orderId>&total=<amount>&currency=<currency>`
  and `#cancelled=<orderId>`. The fragment never reaches the server, so the return
  page is the fast cached one, and the amount in it lets that page thank the
  buyer at once (see *The return*).
- `Idempotency-Key` is the order's `_id`, so a retried request mints one session,
  not two. And a second press for the same thing reuses the open attempt: the
  route looks for this buyer's pending order of the same bag at the prices it
  has now, with a session still inside its day, and hands back that session's
  URL rather than minting another order — one purchase attempt, however many
  times the button or the network retried it. A bag that changed, or a price
  the owner changed since, is a fresh order.

The routes read the `orders` database, which `access.js` binds, so `backend.js`
declares `config.fetch.unfilteredReads` for it — the obligation that comes
with it is yours: every route checks a signed-in buyer's
`order.buyerHandle` against the caller before it returns or settles anything,
a guest's order answers only its own status to the order id the return page
names, a venue page's routes answer only about the check and the payment the
request names, and no route lists orders for anyone.
The owner's view of every order is the page's own live query, which the
access function's `orders` channel already scopes to the owner role.

Amounts are integers in the currency's smallest unit: $12.50 is unit_amount 1250, never 12.5.

Keep the amount an integer in the document as well (`amount: 1250`), read it
once on the server from the product records the buyer names, and never trust an
amount the browser sends — the route takes *which products, and how many of
each*, and looks every price up in the owner's catalog.

A bag is paid in one Checkout Session: backend.js prices every line of the bag, each product and its quantity, from the owner's catalog, the order keeps those lines, and the session carries one line item per bag line.

A lone Pay button is a bag of one (`[{ productId, qty: 1 }]`) that the page
sends to `/checkout`; a shop's bag is a record the buyer fills, paid by the
`/pay` link (*A shop with a bag*). Both price through the same `priceBag`. The order's `lines` hold
each line's title, unit amount and quantity as they were at checkout, its
`amount` is their total, and the read-back matches Stripe's `amount_total` to
that total. A bag is one currency; the route caps it at a sensible number of
lines and a quantity per line.

`/checkout` answers what it charged: `amount`, `currency` and the order's `lines`, each line's title, unit amount and quantity, beside `orderId` and `url`, from a reused attempt as from a new order, so the page and anyone helping the buyer quote the total Stripe shows.

`POST /quote` prices a bag without buying it: it takes the same `lines` as `/checkout`, runs them through the same `priceBag`, and answers `{ ok, amount, currency, lines }`, writing no order and opening no Checkout Session, so the page shows a running total beside the bag before anyone presses Pay.

The price still comes only from the owner's product records, so the quote is
the total `/checkout` charges for that bag a moment later, and a bag
`/checkout` would refuse answers `unknown-item` here too. The page asks again
whenever the bag changes, and anyone helping the buyer shop asks the same
route before handing them the Pay link.

The API is form-encoded, not JSON: build the body with `URLSearchParams`, and
write nested fields in bracket form exactly as shown. Stripe answers JSON; the
fields this recipe reads are `id` and `url` when it creates a session, and
`payment_status`, `status`, `client_reference_id`, `amount_total` and
`currency` when it reads one back.

## 4. "Paid" is a fact the backend reads back from Stripe

An order is marked paid only after the backend has read the Checkout Session back from Stripe, seen payment_status equal to paid, and matched the session's client_reference_id, amount_total and currency to the order; a browser write can never set it.

The match is what binds a payment to *this* order: a session is proof that
somebody paid *something*, and the order's own `_id`, amount and currency in the
session are what say it was this. A `sessionId` is a field in a document, and a
document field is only as trustworthy as the rules that guard it — so the
read-back checks Stripe's copy, never the order's.

Two things settle an order, and both are the backend reading
`GET /v1/checkout/sessions/<id>` through `ctx.stripe`, in the order's own mode:

- **The return.** When the app opens with `#paid=<orderId>` in its address, the
  page calls `/confirm` for that order; the route reads the session back, and if
  `payment_status` is `"paid"` it moves the order to `paid` and stamps `paidAt`.
  A session whose `status` is `"expired"` moves the order to `expired`. Anything
  else leaves it pending.

The return page thanks the buyer from its address before it asks the backend: the success_url carries the amount, the page shows "Payment received" with it on its first render, and `/confirm` runs behind it, changing the line to "still confirming" only if the order comes back unpaid.

That line is display, so taking it from the address is safe: someone who types
`#paid=` into their own address bar only fools themselves, and the order's paid
state still comes from the read-back, never from the URL. Waiting on `/confirm`
before saying anything leaves a buyer who just paid looking at an unchanged shop
for the length of a Stripe round trip.

A scheduled sweep settles every order still pending by reading its session back from Stripe, so a buyer who closes the tab is still marked paid.

Settling is idempotent: the backend reads the order first, and an order that is no longer pending comes back as it is, with ok.

The return can arrive more than once for one payment, sometimes at the same
moment: the page runs its check on mount and again on `hashchange`, a reload
repeats it, and the sweep may get there first. So `/confirm` answers from the
order it reads, and already paid is a success. When two calls settle at once,
the second write meets `conflict` (or `access-denied`, when the access rule
lets only a pending order change); the route reads the order again, and an
order now settled from this same session is the answer it gives.

- **The sweep.** A buyer who pays and closes the tab never triggers `/confirm`.
  Every few minutes `scheduled` queries orders by `status = "pending"`, reads
  each one's session back, and settles it the same way. A Checkout Session
  expires on its own after 24 hours, so the sweep's work is bounded by orders
  made in the last day, and an order older than that with no session is marked
  `expired` rather than read forever. One whose session can no longer be read
  because the owner's Stripe account went away (`account_disconnected`) is
  never written from that refusal, since the buyer may have paid before it
  went: it stays `pending`, the owner's Orders list shows it *not completed*
  once its day is out, and the first sweep after the owner reconnects settles
  it to what Stripe says. A paid order never moves.

Why not a Stripe webhook: a webhook arrives with no identity, and a write with
no identity has to be opened to every anonymous visitor to be accepted — the
wrong door for the one record that means money changed hands. Reading the
session back through `ctx.stripe` is the same proof, from the
same source, on a route that can only move an order to the state Stripe
reports. `access.js` makes that structural: an existing order changes only on
a write from the app's own `backend.js` (`ctx.requireBackend()` on every
update, not only on the status), so a buyer cannot swap a cheaper session's id
onto a dearer order, and the two handlers that write orders do so only after
reading Stripe. A buyer never edits an order; they make a new one.

## 5. What the buyer and the owner each see

- A signed-in buyer sees their own orders and each one's state — *pending*
  with a "Finish paying" link that reuses the session URL while it is open,
  *paid* with the date, *expired* with a fresh "Pay" button that makes a new
  order. A guest sees a thank-you the moment they come back from Stripe and
  gets Stripe's receipt by email; at a venue they also see the thing they paid
  toward: the table's check moving to *Paid in full*, the tip jar's total rising.
- The owner hears about every sale the moment it settles.

When an order settles as paid, backend.js tells the owner with ctx.notify — toHandle ctx.appInfo.ownerHandle, a body that says what sold and for how much, and a dedupeKey built from the order's id — so each sale reaches the owner once, however many times it settles.

  The notice goes out from `settle`, the one place a payment becomes paid,
  after the write that marks it, so the return and the sweep send it alike
  and a buyer who closed the tab still makes the owner's phone buzz. A test
  payment says *Test* first, so the owner can tell a rehearsal from real
  money. A notice that cannot be delivered is logged and never undoes the
  sale. Every recipe on this page does it: an order, a guest's payment on a
  check or an invoice, a tip.
- The owner sees every order: who, what, how much, when, and a total of what
  has been paid. This is the app's own ledger; it is also in the Stripe
  dashboard, and the two agree because the app only ever copies Stripe's
  answer.
- Payments pause when the owner's Stripe account disconnects, and the page
  stays a finished page.

When ctx.stripe.status() reads disconnected for the mode the app charges in, the page shows no Pay button and one friendly line in the owner's voice, such as "Payments are paused right now. Check back soon.", while everything else in the app keeps working.

  `/setup` hands everyone `paused: true` with that state, so the page knows
  on its first render, before anyone presses anything. Paid orders, receipts,
  history and the rest of the app read from the app's own records and carry
  on as they are; the owner's Setup item names **Connect Stripe again**, and
  Pay comes back on its own once the account reads `ready`. A press that
  meets `account_disconnected` (the account went between the page loading and
  the press) shows the same paused line and re-reads `/setup`.
- A paid order unlocks whatever it was for in the app's own terms — the member
  shows as *dues paid* on the roster, the booking shows as *deposit received*,
  the ticket shows as *going* — read off the order's `status`, never off the
  return URL.

## 6. Errors keep their reason

Stripe's own answers arrive as a `Response`: a card decline or a bad parameter
is JSON with `error.message`; keep that sentence and return it as
`{ ok: false, reason: "stripe", message }` so the page can show *why*. A
platform answer is thrown as an `Error` with `e.reason`, and each reason names
the owner's next step: `not_connected` and `not_ready` are the Setup item
(connect, or let Stripe finish its checks), `account_disconnected` is
**Connect Stripe** again from the same Settings tab, and `not_available` means
payments in that mode are paused on vibes.diy for now. Log it with `ctx.log`
and hand the reason to the page, which reads it as *Checkout is not open yet*.

## Complete backend.js

The default recipe: anyone pays, signed in or not. The worked example is a
club's dues, open to whoever pays them: a signed-in member's order carries
their handle, a guest's order lands on the owner's **Orders** all the same, and
Stripe emails every payer their receipt. An owner who asks for members only
gets the one sign-in line the `/checkout` route shows in a comment.

### `backend.js`
```js app=stripe-dues
// Stripe Checkout for one merchant: the owner's connected Stripe account, hosted Checkout,
// orders settled by reading each session back. Nothing in this file touches a card or a key.
export const config = {
  scheduled: { interval: "5m" },
  // The routes read a buyer's own order back; access.js binds the database, so the fetch lane
  // needs this declaration, and the routes owe the buyerHandle check it waives.
  fetch: { unfilteredReads: { dbs: ["orders"], why: "the /quote and /checkout routes read the products the buyer names from the owner's catalog; /checkout and /confirm read the buyer's own order, a signed-in buyer's checked by buyerHandle and a guest's answering only its status to the order id their return page names" } },
};

const DB = "orders";
const SHOP_NAME = "Pottery Corner"; // the app's own name, as its header shows it
const SESSION_TTL_MS = 24 * 60 * 60 * 1000; // a Checkout Session expires on its own after a day

// What is for sale is the owner's catalog: `product` records in this database, written by the owner
// alone from the app's Products screen (access.js), each priced in the currency's smallest unit.
// The browser names a product, never an amount.
async function productFor(ctx, productId) {
  if (typeof productId !== "string" || !productId.startsWith("product-")) return null;
  const product = await ctx.db.get(productId, { db: DB });
  if (product?.type !== "product" || product.onSale !== true) return null;
  if (!Number.isInteger(product.amount) || product.amount <= 0) return null;
  return product;
}

// The buyer's bag, priced now: one line per product, each read from the owner's catalog, with the
// quantity the buyer asked for. One product and one quantity is a bag too, so a lone Pay button
// and a shop's whole bag take the same route. One currency per order.
const MAX_LINES = 20;
const MAX_QTY = 99;
async function priceBag(ctx, bag) {
  if (!Array.isArray(bag) || bag.length === 0 || bag.length > MAX_LINES) return null;
  // The shape first: whole quantities in range, each product once.
  if (!bag.every((item) => Number.isInteger(item?.qty) && item.qty >= 1 && item.qty <= MAX_QTY)) return null;
  if (new Set(bag.map((item) => item.productId)).size !== bag.length) return null;
  // Then every line's product, read at once.
  const products = await Promise.all(bag.map((item) => productFor(ctx, item.productId)));
  if (products.some((p) => !p || p.currency !== products[0].currency)) return null;
  const lines = products.map((p, i) => ({ productId: p._id, title: p.title, unitAmount: p.amount, currency: p.currency, qty: bag[i].qty }));
  const amount = lines.reduce((n, l) => n + l.unitAmount * l.qty, 0);
  // The bag's identity at these prices: the same bag at the same prices reuses its open session.
  const key = lines.map((l) => `${l.productId}:${l.qty}:${l.unitAmount}`).sort().join(",");
  return { lines, amount, currency: lines[0].currency, key };
}

function json(body, status = 200) {
  return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
}

// What /checkout charged, read back from the order priceBag priced: the page and anyone helping the
// buyer quote this total, the one Stripe shows.
function checkoutAnswer(order, url) {
  const lines = order.lines.map(({ title, unitAmount, qty }) => ({ title, unitAmount, qty }));
  return json({ ok: true, orderId: order._id, url, amount: order.amount, currency: order.currency, lines });
}

function appUrl(ctx, hash) {
  return `https://vibes.diy/vibe/${ctx.appInfo.ownerHandle}/${ctx.appInfo.appSlug}${hash}`;
}

// The owner's choice to take THIS app live. The Stripe account is the owner's and serves all of
// their apps, so its live account turning ready never moves an app by itself.
const LIVE_CHOICE = "setup:live";

// Which of the owner's two Stripe accounts this app charges in, decided by the owner's choice
// alone; then whether that account takes card payments right now. A live app whose live account
// is not ready stays live with checkout closed until the owner reconnects.
async function checkoutMode(ctx) {
  const mode = (await ctx.db.get(LIVE_CHOICE, { db: DB })) ? "live" : "test";
  let st;
  try {
    st = await ctx.stripe.status();
  } catch (e) {
    ctx.log("warn", "stripe status unavailable", { message: e.message });
    return { mode, open: false, state: "unavailable", liveOpen: false, liveReady: false };
  }
  return { mode, open: st[mode].state === "ready", state: st[mode].state, liveOpen: st.live.available, liveReady: st.live.state === "ready" };
}

// One call to Stripe on the owner's account, in the order's own mode. Form-encoded in, Stripe's
// JSON out, the refusal's own sentence kept.
async function stripe(ctx, mode, method, path, form, headers = {}) {
  let res;
  try {
    res = await ctx.stripe.fetch(`/v1${path}`, { method, body: form, headers, mode });
  } catch (e) {
    // The platform's answer, not Stripe's: a Setup step for the owner, or payments paused.
    ctx.log("warn", "stripe call refused", { reason: e.reason });
    return { ok: false, reason: e.reason ?? "not_available" };
  }
  const body = await res.json().catch(() => null);
  if (!res.ok) return { ok: false, reason: "stripe", message: body?.error?.message ?? `HTTP ${res.status}` };
  return { ok: true, body };
}

// The owner hears about each sale once: the dedupeKey is the order, so a second settle sends nothing.
async function tellOwner(ctx, { id, mode, amount, currency, what, path }) {
  const fmt = new Intl.NumberFormat("en-US", { style: "currency", currency });
  const price = fmt.format(amount / 10 ** fmt.resolvedOptions().maximumFractionDigits); // minor units: JPY has none
  try {
    await ctx.notify({
      toHandle: ctx.appInfo.ownerHandle,
      body: `${mode === "test" ? "Test sale" : "Sale"}: ${what}, ${price}`.slice(0, 500),
      dedupeKey: `sale-${id}`,
      ...(path ? { path } : {}), // a "#…" fragment, or nothing: a malformed path fails the call
    });
  } catch (err) {
    ctx.log("warn", "sale notice not delivered", { id, reason: err.message }); // the sale stands either way
  }
}

// Move one pending order to what Stripe says about its session. Returns the order as settled.
async function settle(ctx, order) {
  if (order.status !== "pending") return order;
  if (!order.sessionId) {
    if (Date.now() - order.createdAt > SESSION_TTL_MS) {
      const expired = { ...order, status: "expired" };
      await ctx.db.put(expired, { db: DB, id: order._id, ifRev: order._rev });
      return expired;
    }
    return order;
  }
  const session = await stripe(ctx, order.mode, "GET", `/checkout/sessions/${order.sessionId}`);
  // A refusal settles nothing, an unreadable account included: the buyer may have paid before it
  // went away, so the order stays pending and the first read after the owner reconnects settles it.
  if (!session.ok) return order;
  const s = session.body;
  // The session must be THIS order's: Stripe's copy of the order id, amount and currency,
  // never the document's own claim about which session it holds.
  const matches = s.client_reference_id === order._id && s.amount_total === order.amount && s.currency === order.currency;
  if (!matches) {
    ctx.log("warn", "stripe session does not match its order", { orderId: order._id });
    return order;
  }
  let next = order;
  if (s.payment_status === "paid") {
    next = { ...order, status: "paid", paidAt: Date.now(), amountPaid: s.amount_total };
  } else if (s.status === "expired") {
    next = { ...order, status: "expired" };
  }
  if (next === order) return order;
  try {
    await ctx.db.put(next, { db: DB, id: order._id, ifRev: order._rev });
  } catch (err) {
    if (err.code !== "conflict" && err.code !== "access-denied") throw err;
    // Another call settled it first: that is this payment's answer when it holds the same session.
    const stored = await ctx.db.get(order._id, { db: DB });
    if (stored && stored.status !== "pending" && stored.sessionId === order.sessionId) return stored;
    throw err;
  }
  if (next.status === "paid") {
    const buyer = next.buyerHandle ? `@${next.buyerHandle}` : "a guest";
    await tellOwner(ctx, { id: next._id, mode: next.mode, amount: next.amountPaid, currency: next.currency, what: `${next.title} to ${buyer}` });
  }
  return next;
}

export async function fetch(request, ctx) {
  const url = new URL(request.url);

  // The setup verdict: ready for everyone, the items (and the handle + slug the Setup screen
  // links with) for the owner alone.
  if (url.pathname === "/setup" && request.method === "GET") {
    const owner = ctx.userInfo?.userHandle === ctx.appInfo.ownerHandle;
    const { mode, open, state, liveOpen, liveReady } = await checkoutMode(ctx);
    const item = { id: "stripe-connect", label: "Connect Stripe", done: open, state };
    if (mode === "live" && !liveOpen) item.problem = "Vibes DIY has paused live payments for now; checkout reopens here by itself when they return.";
    const items = [item];
    const ready = items.every((i) => i.done);
    // `mode` is everyone's: the Pay button wears a Test mode badge while the app takes test payments.
    // `paused` is everyone's too: a disconnected account shows a calm paused line, never a Pay button.
    const paused = state === "disconnected";
    if (!owner) return json({ ok: true, ready, owner, mode, paused });
    // The Go-live step: `liveOpen` (vibes.diy takes live payments) and `liveReady` (the owner's live
    // Stripe account is ready, so this app can be taken live).
    return json({ ok: true, ready, owner, mode, paused, liveOpen, liveReady, items, ownerHandle: ctx.appInfo.ownerHandle, appSlug: ctx.appInfo.appSlug });
  }

  // The owner takes this app live: one document, written for the owner alone, once their live
  // Stripe account is ready. From here on the app charges in live only.
  if (url.pathname === "/go-live" && request.method === "POST") {
    if (ctx.userInfo?.userHandle !== ctx.appInfo.ownerHandle) return json({ ok: false, reason: "owner-only" }, 403);
    const { liveReady } = await checkoutMode(ctx);
    if (!liveReady) return json({ ok: false, reason: "not_ready" }, 409);
    const chosen = await ctx.db.get(LIVE_CHOICE, { db: DB });
    if (!chosen) await ctx.db.put({ _id: LIVE_CHOICE, type: "setup", mode: "live", chosenAt: Date.now() }, { db: DB, id: LIVE_CHOICE });
    return json({ ok: true, mode: "live" });
  }

  // The running total beside the bag: the same lines through the same priceBag, answered before
  // anyone presses Pay. Pricing only: no order, no Checkout Session, no call to Stripe.
  if (url.pathname === "/quote" && request.method === "POST") {
    const { lines: bag } = await request.json();
    const priced = await priceBag(ctx, bag);
    if (!priced) return json({ ok: false, reason: "unknown-item" }, 400);
    const lines = priced.lines.map(({ title, unitAmount, qty }) => ({ title, unitAmount, qty }));
    return json({ ok: true, amount: priced.amount, currency: priced.currency, lines });
  }

  // Start a purchase: the order first, then a Checkout Session for exactly that order. Anyone pays:
  // a signed-in buyer's order carries their handle, a guest's carries the key their page keeps.
  // (An owner who asked for members only adds: if (!me) return json({ ok: false, reason: "sign-in" }, 401);)
  if (url.pathname === "/checkout" && request.method === "POST") {
    const me = ctx.userInfo?.userHandle ?? null;
    const { mode, open, state } = await checkoutMode(ctx);
    const { lines: bag, mode: shown, guestKey } = await request.json();
    if (!me && !(typeof guestKey === "string" && /^guest-[\w-]{8,64}$/.test(guestKey))) return json({ ok: false, reason: "bad-request" }, 400);
    // The buyer pays in the mode their page showed them, or not at all: a page that still shows
    // the other mode refreshes first.
    if (shown !== mode) return json({ ok: false, reason: "mode-changed", mode }, 409);
    if (!open) return json({ ok: false, reason: state === "disconnected" ? "account_disconnected" : "not_ready" }, 503);
    // Every price is the one on the owner's product record, read now: a line that is off sale, gone
    // or out of bounds, and nothing is charged.
    const priced = await priceBag(ctx, bag);
    if (!priced) return json({ ok: false, reason: "unknown-item" }, 400);

    // One attempt per buyer per bag at these prices: a second press, a retry after a lost answer,
    // a reload, all land on the session already open rather than minting another order. A bag
    // that changed, or a price the owner changed since, is a new attempt.
    const pending = await ctx.db.query({ db: DB, field: "status", key: "pending", limit: 100 });
    const same = (o) => (me ? o.buyerHandle === me : o.guestKey === guestKey);
    const attempt = pending.find((o) => same(o) && o.bagKey === priced.key && o.currency === priced.currency && o.mode === mode && o.sessionUrl && Date.now() - o.createdAt < SESSION_TTL_MS);
    if (attempt) return checkoutAnswer(attempt, attempt.sessionUrl);

    const id = "order-" + crypto.randomUUID();
    const order = {
      _id: id,
      type: "order",
      // The order keeps what was bought at the prices it was bought at, whatever the catalog says later.
      lines: priced.lines.map(({ productId, title, unitAmount, qty }) => ({ productId, title, unitAmount, qty })),
      bagKey: priced.key,
      title: priced.lines.length === 1 ? priced.lines[0].title : `${priced.lines[0].title} and ${priced.lines.length - 1} more`,
      amount: priced.amount,
      currency: priced.currency,
      buyerHandle: me, // null for a guest; Stripe's page collects their email and sends the receipt
      ...(me ? {} : { guestKey }),
      mode, // the account this order is made in; every later call for it passes the same mode
      status: "pending",
      createdAt: Date.now(),
    };
    await ctx.db.put(order, { db: DB, id });

    const form = new URLSearchParams({
      mode: "payment",
      client_reference_id: id,
      "metadata[orderId]": id,
      // Checkout opens with "Pay <this app>", not the name on the owner's Stripe account.
      "branding_settings[display_name]": SHOP_NAME,
      // The amount rides in the fragment so the return page can thank the buyer before /confirm answers.
      success_url: appUrl(ctx, `#paid=${id}&total=${order.amount}&currency=${order.currency}`),
      cancel_url: appUrl(ctx, `#cancelled=${id}`),
    });
    // One Stripe line per bag line, so the buyer's receipt lists what they bought.
    order.lines.forEach((l, i) => {
      form.set(`line_items[${i}][quantity]`, String(l.qty));
      form.set(`line_items[${i}][price_data][currency]`, order.currency);
      form.set(`line_items[${i}][price_data][unit_amount]`, String(l.unitAmount));
      form.set(`line_items[${i}][price_data][product_data][name]`, l.title);
    });
    const session = await stripe(ctx, mode, "POST", "/checkout/sessions", form, { "idempotency-key": id });
    if (!session.ok) return json(session, session.reason === "stripe" ? 502 : 503);

    await ctx.db.put({ ...order, sessionId: session.body.id, sessionUrl: session.body.url }, { db: DB, id });
    return checkoutAnswer(order, session.body.url);
  }

  // The buyer is back: read the session, move the order to what Stripe says. A signed-in buyer's
  // order answers to them alone; a guest's answers its status to the order id their return page holds.
  if (url.pathname === "/confirm" && request.method === "POST") {
    const me = ctx.userInfo?.userHandle ?? null;
    const { orderId } = await request.json();
    const order = typeof orderId === "string" && orderId.startsWith("order-") ? await ctx.db.get(orderId, { db: DB }) : null;
    if (order?.type !== "order" || (order.buyerHandle && order.buyerHandle !== me)) return json({ ok: false, reason: "not-found" }, 404);
    const settled = await settle(ctx, order);
    return json({ ok: true, status: settled.status });
  }

  return json({ ok: false, reason: "not-found" }, 404);
}

// The sweep: anyone who paid and closed the tab is still marked paid within a few minutes.
export async function scheduled(event, ctx) {
  let after;
  let settled = 0;
  do {
    const page = await ctx.db.query({ db: DB, field: "status", key: "pending", limit: 100, after });
    for (const order of page) {
      const next = await settle(ctx, order);
      if (next !== order) settled += 1;
    }
    after = page.next;
  } while (after);
  ctx.log("info", "stripe sweep", { settled, at: event.scheduledTime });
}
```

## access.js — the status moves only on the backend's word

### `access.js`
```js app=stripe-dues
export function orders(doc, oldDoc, user, ctx) {
  // Orders come from backend.js for whoever paid, guests included; everything else needs a sign-in.
  if (!user?.userHandle && doc.type !== "order") throw { forbidden: "sign in" };
  // The catalog: the owner lists each product and sets its price from the app's own screen, and
  // anyone reads it. backend.js charges the price on this record, so the owner alone writes one.
  if (doc.type === "product") {
    ctx.requireRole("owner");
    const named = doc._id?.startsWith("product-") && typeof doc.title === "string" && doc.title.trim() !== "";
    if (!named || !Number.isInteger(doc.amount) || doc.amount <= 0 || !/^[a-z]{3}$/.test(doc.currency ?? "") || typeof doc.onSale !== "boolean") {
      throw { forbidden: "a product has a name, a whole-cent price and a currency" };
    }
    return { channels: ["catalog"], grant: { public: ["catalog"] } };
  }
  // The app's go-live choice: written by backend.js on the owner's /go-live call alone, read on
  // the owner's channel.
  if (doc.type === "setup") {
    ctx.requireBackend("fetch");
    return { channels: ["orders"] };
  }
  if (doc.type !== "order") throw { forbidden: "unknown document type" };
  if (oldDoc) {
    // Only backend.js changes an existing order — the /checkout route adding the session, the
    // /confirm route and the sweep settling it — so no field (sessionId included) is a buyer's to edit.
    ctx.requireBackend();
    if (doc.buyerHandle !== oldDoc.buyerHandle || doc.amount !== oldDoc.amount || doc.currency !== oldDoc.currency || doc.bagKey !== oldDoc.bagKey || doc.mode !== oldDoc.mode) {
      throw { forbidden: "an order keeps its buyer, its price and its mode" };
    }
  } else {
    // A signed-in buyer's order names them; a guest's names nobody.
    if (doc.buyerHandle !== (user?.userHandle ?? null)) throw { forbidden: "an order belongs to its buyer" };
    if (doc.status !== "pending") throw { forbidden: "an order starts pending" };
    ctx.requireBackend("fetch"); // the /checkout route writes it, so the amount is the server's
  }
  // allowAnonymous: backend.js writes a guest's order while serving a buyer who has no account.
  if (!doc.buyerHandle) return { channels: ["orders"], grant: { roles: { owner: ["orders"] } }, allowAnonymous: true };
  const mine = `user:${doc.buyerHandle}`;
  return { channels: [mine, "orders"], grant: { users: { [doc.buyerHandle]: [mine] }, roles: { owner: ["orders"] } }, allowAnonymous: true };
}
```

## App.jsx sketch

### `App.jsx`
```jsx app=stripe-dues
import React, { useEffect, useRef, useState } from "react";
import { useFireproof } from "use-fireproof";
import { apiFetch, useVibe } from "use-vibes";
import { Badge, Button, Field, Heading, Input, Row, Stack, Text } from "@vibes.diy/ui";
import { Checkbox } from "@vibes.diy/ui/interactive";

// Amounts are in the currency's smallest unit, the one Stripe charges in: cents for usd, whole yen
// for jpy. Show, edit and read them through that unit, never a fixed 100.
const digits = (currency) => new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits;
const money = (amount, currency) => new Intl.NumberFormat(undefined, { style: "currency", currency }).format(amount / 10 ** digits(currency));
const toMinor = (text, currency) => Math.round(Number(text) * 10 ** digits(currency));
const shown = (amount, currency) => (amount / 10 ** digits(currency)).toFixed(digits(currency));
const CURRENCY = "usd"; // the currency new products are priced in
// A Checkout Session lasts a day. A pending order older than that is one Stripe could not be asked
// about (the owner's account went away): it reads not completed until a sweep can settle it.
const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
const notCompleted = (o) => o.status === "expired" || (o.status === "pending" && Date.now() - o.createdAt > SESSION_TTL_MS);

// The setup verdict, read on mount and again whenever the app comes back into view: the owner
// connects Stripe in another tab and returns, and the Pay buttons unlock without a reload.
function useSetup() {
  const [setup, setSetup] = useState(null); // { ready, owner, mode, paused, liveOpen?, items?, ownerHandle?, appSlug? }
  const latest = useRef(0);
  useEffect(() => {
    // Mount, focus and visibility reads overlap; only the latest one may land, or a slow stale
    // answer overwrites a fresh one.
    const load = () => {
      const n = ++latest.current;
      apiFetch("/setup").then((r) => r.json()).catch(() => ({ ready: false, owner: false })).then((s) => { if (n === latest.current) setSetup(s); });
    };
    load();
    const onVisible = () => { if (document.visibilityState === "visible") load(); };
    document.addEventListener("visibilitychange", onVisible);
    window.addEventListener("focus", load);
    window.addEventListener("setup-changed", load); // the Setup screen's own Take live button
    return () => { document.removeEventListener("visibilitychange", onVisible); window.removeEventListener("focus", load); window.removeEventListener("setup-changed", load); };
  }, []);
  return setup;
}

// The paused line, in the owner's voice: a disconnected Stripe account shows this where Pay was.
const PAUSED = "Payments are paused right now. Check back soon.";

// The button the Settings tab shows for each state of the owner's Stripe account, in its own words.
const STRIPE_BUTTON = { absent: "Connect Stripe", onboarding: "Finish Stripe setup", disconnected: "Connect Stripe again" };

// The Setup surface, the owner's alone: one item, every step a link to the exact page in that
// page's own words, with this vibe's real handle and slug filled in.
function SetupScreen({ setup }) {
  const vibe = `${setup.ownerHandle}/${setup.appSlug}`;
  const settingsUrl = `https://vibes.diy/vibes/mine/${vibe}/settings`;
  const item = setup.items.find((i) => i.id === "stripe-connect");
  const live = setup.mode === "live";
  const takeLive = () => apiFetch("/go-live", { method: "POST" }).then(() => window.dispatchEvent(new Event("setup-changed")));
  return (
    <Stack>
      <Heading>Setup</Heading>
      <Row gap={2}>
        <Text>{item.label}</Text>
        <Badge tone={item.done ? "up" : "info"}>{item.done ? "Done" : item.state === "onboarding" ? "Stripe is finishing up" : "To do"}</Badge>
      </Row>
      {item.problem && <Text muted>{item.problem}</Text>}
      <ol>
        <li>
          Open <a href={settingsUrl} target="_blank" rel="noreferrer">this vibe's Settings tab</a> (My Vibes → this vibe → Settings)
          and press <b>{STRIPE_BUTTON[item.state] ?? "Connect Stripe"}</b> under <b>Payments</b>.
          Stripe opens its own setup pages: use your Stripe account, or create one there. Your Stripe account serves every app you make.
        </li>
        <li>
          Come back here: the Pay buttons work as soon as Stripe says your account is ready. In test mode the card 4242 4242 4242 4242 with any future date pays.
        </li>
        <li>
          {/* The Go-live step stays here once the item is done; its badge says which account this app charges in. */}
          <Badge tone={live ? "up" : "info"}>{live ? "Live" : "Test mode"}</Badge>{" "}
          {live ? (
            <>This app takes real payments into your Stripe account; refunds and payouts are in your Stripe Dashboard.</>
          ) : setup.liveReady ? (
            <>
              Your live Stripe account is ready. Each app goes live on its own, so this one rehearses until you press{" "}
              <Button onClick={takeLive}>Take live payments in this app</Button>. Buyers start fresh in live; test purchases stay rehearsals.
            </>
          ) : setup.liveOpen ? (
            <>When a test payment goes through, press <b>Go live with Stripe</b> under <b>Payments</b> on <a href={settingsUrl} target="_blank" rel="noreferrer">the same Settings tab</a> and finish Stripe's live setup, once for all your apps; then come back here to take this app live.</>
          ) : (
            <>Test mode runs the whole flow end to end. The <b>Go live with Stripe</b> button appears under <b>Payments</b> on the same Settings tab when vibes.diy opens live payments.</>
          )}
        </li>
      </ol>
    </Stack>
  );
}

// One product on the owner's list: its price edits in place, and On sale puts it in front of buyers
// or takes it away. A refused write puts the shown price back.
function ProductRow({ product, save }) {
  const [price, setPrice] = useState(shown(product.amount, product.currency));
  useEffect(() => setPrice(shown(product.amount, product.currency)), [product.amount]);
  const commit = () => {
    const amount = toMinor(price, product.currency);
    if (Number.isInteger(amount) && amount > 0 && amount !== product.amount) save({ ...product, amount }, () => setPrice(shown(product.amount, product.currency)));
    else setPrice(shown(product.amount, product.currency));
  };
  return (
    <Row gap={2}>
      <Text>{product.title}</Text>
      <Field label="Price">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={price} onChange={setPrice} onBlur={commit} onKeyDown={(e) => e.key === "Enter" && commit()} inputMode="decimal" />}</Field>
      <Checkbox label="On sale" checked={product.onSale} onChange={(on) => save({ ...product, onSale: on === true })} />
    </Row>
  );
}

// The owner's catalog: what is for sale and what it costs. Each save is a `product` record that
// access.js takes from the owner alone, and the price on it is the price /checkout charges. Empty,
// the form for the first product leads; from then on the list leads with a compact add on top.
function Products({ products, onAdd }) {
  const { database } = useFireproof("orders");
  const [title, setTitle] = useState("");
  const [price, setPrice] = useState("");
  const [error, setError] = useState(null);
  // A put lands on this device at once; the server's verdict arrives on its receipt. A refused save
  // converges back to what the server holds, and the owner gets their draft and the reason back.
  const save = async (product, undo) => {
    setError(null);
    const { synced } = await database.put(product);
    synced.on((s) => {
      if (s.status !== "refused") return;
      undo?.();
      setError(s.message ?? "That did not save: a product needs a name and a price like 12.50.");
    });
  };
  const add = () => {
    const amount = toMinor(price, CURRENCY);
    if (!title.trim() || !Number.isInteger(amount) || amount <= 0) return setError("Give it a name and a price like 12.50.");
    const product = { _id: "product-" + crypto.randomUUID(), type: "product", title: title.trim(), amount, currency: CURRENCY, onSale: true, createdAt: Date.now() };
    // The form empties as the owner presses Add; the draft comes back only if the write is refused.
    // The owner stays here: the first entry would otherwise flip the default screen to the shop.
    onAdd?.();
    setTitle("");
    setPrice("");
    save(product, () => { setTitle(product.title); setPrice(shown(product.amount, product.currency)); });
  };
  return (
    <Stack>
      <Heading>{products.length === 0 ? "Add the first thing you sell" : "Products"}</Heading>
      <Row gap={2}>
        <Field label="Name">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={title} onChange={setTitle} placeholder="Annual dues" />}</Field>
        <Field label="Price">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={price} onChange={setPrice} placeholder="40.00" inputMode="decimal" />}</Field>
        <Button onClick={add}>Add</Button>
      </Row>
      {error && <Text>{error}</Text>}
      {products.map((p) => <ProductRow key={p._id} product={p} save={save} />)}
    </Stack>
  );
}

export default function App() {
  const { me } = useVibe("orders");
  const { useLiveQuery } = useFireproof("orders");
  const { docs: orders } = useLiveQuery("type", { key: "order" });
  const { docs: products } = useLiveQuery("type", { key: "product" });
  const setup = useSetup();
  const [picked, setPicked] = useState(null);
  const [error, setError] = useState(null);
  // The order the buyer just came back from, and the line that thanks them for it.
  const [back, setBack] = useState(null);

  // Back from Stripe: thank the buyer from the address at once, then ask the backend to read the
  // session and settle the order. The wrapper hands the app its fragment just after first render and
  // fires hashchange, so read the hash now AND on every change — a mount-only read can miss it.
  useEffect(() => {
    const confirm = () => {
      const params = new URLSearchParams(location.hash.slice(1));
      const orderId = params.get("paid");
      if (!orderId) return;
      history.replaceState(null, "", location.pathname);
      const total = Number(params.get("total") ?? "x"); // NaN when the address carries no amount
      const currency = params.get("currency") ?? "usd";
      // Display only: the order's paid state comes from /confirm's read-back, never from this URL.
      const thanks = Number.isInteger(total) ? `Payment received: ${money(total, currency)}. Thank you!` : "Payment received. Thank you!";
      setBack({ orderId, thanks, confirming: false });
      apiFetch("/confirm", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ orderId }) })
        .then((r) => r.json())
        .then((d) => {
          // A guest reads no orders, so /confirm's answer is the status their line shows.
          setBack({ orderId, thanks, confirming: d.status !== "paid", status: d.status });
        })
        .catch(() => setBack({ orderId, thanks, confirming: true }));
    };
    confirm();
    window.addEventListener("hashchange", confirm);
    return () => window.removeEventListener("hashchange", confirm);
  }, []);

  const [busy, setBusy] = useState(false);
  // Anyone pays. A guest's page keeps one random key, so a second press finds the checkout already open.
  const [guestKey] = useState(() => {
    try {
      const kept = localStorage.getItem("guestKey") ?? "guest-" + crypto.randomUUID();
      localStorage.setItem("guestKey", kept);
      return kept;
    } catch {
      return "guest-" + crypto.randomUUID();
    }
  });
  // `lines` is a bag: [{ productId, qty }]. A lone Pay button sends a bag of one.
  const pay = async (lines) => {
    setError(null);
    const tab = window.open("", "_blank"); // opened inside the click, before any await, so it is not a popup
    if (!tab) {
      setError("Your browser blocked the Stripe tab. Allow pop-ups for this page and press Pay again.");
      return; // nothing was ordered
    }
    setBusy(true);
    try {
      // The page names the products and how many, never a price; the mode it shows rides along, so
      // the buyer pays in the mode they saw.
      const res = await apiFetch("/checkout", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ lines, mode: setup.mode, guestKey }) });
      const data = await res.json();
      if (!data.ok) {
        tab.close();
        setError(
          data.reason === "stripe" ? data.message
          : data.reason === "mode-changed" ? `Payments here just moved to ${data.mode} mode. Refresh the page and press Pay again.`
          : data.reason === "unknown-item" ? "Something in your order is no longer for sale. Refresh and try again."
          : data.reason === "account_disconnected" ? PAUSED
          : "Checkout is not open yet."
        );
        if (data.reason === "account_disconnected") window.dispatchEvent(new Event("setup-changed")); // re-read: Pay steps aside
        return;
      }
      tab.location.href = data.url;
    } finally {
      setBusy(false);
    }
  };

  const ready = setup?.ready === true;
  const forSale = products.filter((p) => p.onSale);
  // Only orders made in the app's current mode count: after going live, test orders are rehearsals.
  const mine = me ? orders.filter((o) => o.buyerHandle === me.userHandle && o.mode === setup?.mode) : [];
  // The owner with nothing listed starts on Products, the form for their first product in front.
  const screen = picked ?? (setup?.owner && products.length === 0 ? "products" : "shop");
  return (
    <Stack>
      <Row gap={2}>
        <Button variant="quiet" onClick={() => setPicked("shop")}>Shop</Button>
        {/* The owner's own pages: the catalog, every order, and Setup highlighted while an item is still to do. */}
        {setup?.owner && <Button variant="quiet" onClick={() => setPicked("products")}>Products</Button>}
        {setup?.owner && <Button variant="quiet" onClick={() => setPicked("orders")}>Orders</Button>}
        {setup?.owner && (
          <Button variant={ready ? "quiet" : "solid"} onClick={() => setPicked("setup")}>
            Setup{ready ? "" : " · to do"}
          </Button>
        )}
      </Row>
      {screen === "setup" && setup?.owner ? (
        <SetupScreen setup={setup} />
      ) : screen === "products" && setup?.owner ? (
        <Products products={products} onAdd={() => setPicked("products")} />
      ) : screen === "orders" && setup?.owner ? (
        <Stack>
          <Heading>Orders</Heading>
          {orders.length === 0 ? (
            <Text muted>No orders yet. Each one shows here the moment someone pays.</Text>
          ) : (
            <ul>
              {orders.map((o) => (
                <li key={o._id}>{o.buyerHandle ? `@${o.buyerHandle}` : "Guest"} · {o.title} · {money(o.amount, o.currency)} · {notCompleted(o) ? "not completed" : o.status}{o.mode === setup.mode ? "" : ` · ${o.mode} rehearsal`}</li>
              ))}
            </ul>
          )}
        </Stack>
      ) : (
        <Stack>
          <Heading>Shop</Heading>
          {/* The live order settles the line: once the sweep marks it paid, "still confirming" goes away. */}
          {back && (
            <Text>
              {(() => {
                const status = orders.find((o) => o._id === back.orderId)?.status ?? back.status;
                if (status === "expired") return "That checkout closed before it was paid. Press Pay to start a fresh one.";
                if (back.confirming && status !== "paid") return "Your payment is still confirming. It shows here as paid in a moment.";
                return back.thanks;
              })()}
            </Text>
          )}
          {forSale.length === 0 ? (
            <Text muted>{setup?.owner ? "Nothing is for sale yet. Add what you sell under Products." : "Nothing for sale yet."}</Text>
          ) : ready ? (
            <Stack>
              {/* Test mode is a rehearsal: the owner gets the test card, buyers learn it ends at go-live. */}
              {setup.mode === "test" && (
                <Row gap={2}>
                  <Badge tone="info">Test mode</Badge>
                  <Text muted>{setup.owner ? "Pay with the test card 4242 4242 4242 4242 and any future date." : "This is a rehearsal: test purchases end when the app goes live."}</Text>
                </Row>
              )}
              {forSale.map((p) => (
                <Row key={p._id} gap={2}>
                  <Text>{p.title}</Text>
                  <Button onClick={() => pay([{ productId: p._id, qty: 1 }])} disabled={busy} loading={busy}>
                    Pay {money(p.amount, p.currency)} — Stripe opens in a new tab
                  </Button>
                </Row>
              ))}
            </Stack>
          ) : (
            <Text muted>{setup?.paused ? PAUSED : "Checkout is not open yet."}</Text>
          )}
          {error && <Text>{error}</Text>}
          {mine.length > 0 && (
            <ul>
              {mine.map((o) => (
                <li key={o._id}>{o.title} · {money(o.amount, o.currency)} · {o.status === "pending" && o.sessionUrl ? <a href={o.sessionUrl} target="_blank" rel="noreferrer">Finish paying</a> : o.status}</li>
              ))}
            </ul>
          )}
        </Stack>
      )}
    </Stack>
  );
}
```

The catalog is records, so a page with one thing for sale and a page with
forty are the same code: the owner adds each one on **Products**, and the Shop
lists what is on sale with one `pay([{ productId, qty: 1 }])` per button. A club's dues are a
product called *Annual dues*; next year's dues are next year's purchase of it,
at whatever price the owner has set by then. Something that recurs on its own,
where Stripe renews and retries, is the `stripe-subscriptions` skill.

### A shop with a bag

A shop where people fill a bag (the `ui-storefront` block's shape) keeps that
block's page and swaps its **Place order** for this recipe's checkout. The
products are this recipe's `product` records (the storefront adds a photo to
each as `_files.photo`), and the order the bag becomes is this recipe's
`order`, written by backend.js, so the storefront's own browser-written order
goes away. Checkout charges the lines, so the storefront's shipping row goes
too, unless backend.js prices shipping as a line of its own.

A shop's bag is a record in the `orders` database that the buyer writes as they shop, and its Pay is one link, `/_api/pay?bag=<_id>&rev=<rev>`, that prices that exact version of the bag in backend.js and sends the buyer to Stripe Checkout.

A record rather than page state, because a signed-in buyer's bag is theirs, not the
tab's: it is there on their phone after they filled it on their laptop, and
anyone helping them shop (their own agent filling the bag in a conversation,
say) writes the same record the page does and hands them the same link. The
page never sends a price and never a list of lines; the link names a bag and
the version the buyer saw, and the shop's own `priceBag` reads every line
from the owner's catalog, options and all.

**The bag record.** One open bag per buyer: `type: "bag"`, an `_id` of
`bag-` and a fresh id, `buyerHandle` (access.js holds it to the writer),
and `rev`, a fresh random string on every write, which is the version the
Pay link names. Its lines take one of two shapes, and a shop picks the one
that fits:

- **A record per line.** Each line is its own `type: "line"` record with
  `bagId`, `productId`, `qty` and whatever options it carries (size, milk,
  engraving), and every line write also puts the bag with a new `rev` and
  `touchedAt`. Right for most shops: each line can be read, counted and
  changed on its own, the shop can tally a product across bags, and anyone
  helping the buyer adds a line without rewriting the rest. The line carries
  the `touchedAt` of the bag write that went with it, so a line newer than
  the bag was written after the link and is not in it.
- **Lines on the bag.** `lines: [{ productId, qty }]` on the bag itself, and
  every change is one put of the whole bag with a new `rev`. Right only for a
  bag of one or two fixed things that nobody reads line by line.

A line's options are the shop's to price: `priceBag` reads them off the line
and adds what the owner's product record says they cost, so a modifier is
priced in exactly one place, the same place as the product.

A guest's bag is the same `line` records, written from their first Add while they are signed out: a signed-out write is kept on their device until sign-in, so a reload keeps every line, and the page reads them back with the same query under the bag id `bag-<guestKey>`.

Their Pay sends those lines to `/checkout` with the page's `guestKey`, so a
visitor who never signs in fills the bag and pays: their lines stay on their
device and never reach `/pay`, and `/checkout` prices them through the same
`priceBag`. Same lines, same order, same Stripe page for everyone.

### `access.js`
```js partial
// Added before the `order` rule: the buyer's own bag, and its lines when they are records. A record
// keeps its type, so an order can never be rewritten as a line to slip past the order rule.
if (oldDoc && oldDoc.type !== doc.type) throw { forbidden: "a record keeps its type" };
if (doc.type === "bag" || doc.type === "line") {
  if (doc.buyerHandle !== user.userHandle || (oldDoc && oldDoc.buyerHandle !== doc.buyerHandle)) {
    throw { forbidden: "a bag is its buyer's own" };
  }
  if (doc.type === "bag" && (!doc._id?.startsWith("bag-") || typeof doc.rev !== "string")) {
    throw { forbidden: "a bag has a bag- id and a rev" };
  }
  if (doc.type === "line" && !doc.bagId?.startsWith("bag-")) throw { forbidden: "a line names its bag" };
  const mine = `user:${doc.buyerHandle}`;
  return { channels: [mine], grant: { users: { [doc.buyerHandle]: [mine] } } };
}
```

The `order` rule takes one change: a Pay link arrives as a plain link, so
`/pay` writes the order while nobody is signed in, naming the bag's buyer. The
new order's buyer is the signed-in writer when there is one and otherwise the
bag's `buyerHandle`, `ctx.requireBackend("fetch")` still gates its creation,
and the rule already returns `allowAnonymous: true` for the guest orders
`/checkout` writes. That is all a write from the app's own backend needs: the
app's anonymous-write setting gates browsers, not backend.js, so the owner has
no step to take.

### `backend.js`
```js partial
// Pay a bag by link. The page's Pay button and anyone helping the buyer open the same address, so
// the price is the one this route computes, from the owner's catalog, for the bag version named.
// A link is opened signed out: the buyer is the bag's buyerHandle, which only they could write.
if (url.pathname === "/pay" && request.method === "GET") {
  const back = (reason) => Response.redirect(appUrl(ctx, `#bag-problem=${reason}`), 303);
  const bagId = url.searchParams.get("bag") ?? "";
  const bag = bagId.startsWith("bag-") ? await ctx.db.get(bagId, { db: DB }) : null;
  if (bag?.type !== "bag") return back("not-found");
  // The version the buyer was shown, or nothing: a bag that moved since sends them back to look again.
  if (bag.rev !== url.searchParams.get("rev")) return back("bag-changed");
  const { mode, open } = await checkoutMode(ctx);
  const shown = url.searchParams.get("mode"); // the page adds the mode it showed; a link from elsewhere has none
  if (shown && shown !== mode) return back("mode-changed");
  if (!open) return back("not-open");
  let lines = bag.lines;
  if (!Array.isArray(lines)) {
    // A record per line: the bag's buyer's own lines naming this bag (anyone can name a bag id, so a
    // line someone else wrote is not in it), and none written after the bag's own write.
    // Every page: the query filters after its limit, and orders name the bag by bagId too.
    lines = [];
    let after;
    do {
      const page = await ctx.db.query({ db: DB, field: "bagId", key: bag._id, limit: 100, after });
      lines.push(...page.filter((l) => l.type === "line" && l.buyerHandle === bag.buyerHandle));
      after = page.next;
    } while (after && lines.length <= MAX_LINES);
    if (lines.some((l) => l.touchedAt > bag.touchedAt)) return back("bag-changed");
  }
  // Whole lines, options and all: priceBag prices each option from the owner's product record.
  const priced = await priceBag(ctx, lines);
  if (!priced) return back("unknown-item");
  const buyer = bag.buyerHandle;
  // One attempt per bag version: a second press of the same link lands on the session already open.
  const pending = await ctx.db.query({ db: DB, field: "status", key: "pending", limit: 100 });
  const attempt = pending.find((o) => o.bagId === bag._id && o.bagKey === priced.key && o.currency === priced.currency && o.mode === mode && o.sessionUrl && Date.now() - o.createdAt < SESSION_TTL_MS);
  if (attempt) return Response.redirect(attempt.sessionUrl, 303);
  // From here it is /checkout's order and session, with the bag's buyer and `bagId: bag._id` on the
  // order: the same order fields, the same form, the same line items, the same idempotency key.
  const { id, sessionUrl, failed } = await openSession(ctx, { priced, buyer, mode, bagId: bag._id });
  if (failed) return back(failed);
  return Response.redirect(sessionUrl, 303);
}
```

`openSession` is `/checkout`'s second half lifted into a function, so both
routes write the same order and the same session: the order (now with
`bagId` when a bag paid it), the session form, the second put with
`sessionId` and `sessionUrl`. `config.fetch.unfilteredReads` already covers
the `orders` database; its `why` names the bag too, since `/pay` reads a
bag and its lines with nobody signed in.

**The page.** It reads the buyer's open bag with a live query, writes it on
every Add, and its Pay is a link. The page runs in a frame, so the link is the
app's full address: `/setup` adds `pay: appUrl(ctx, "/_api/pay")` to everyone's
answer, and the page puts the bag on it.

### `App.jsx`
```jsx partial
// The buyer's open bag: theirs alone (access.js routes it to their own channel), and the newest one
// no paid order names. Its lines are records naming it by bagId; every Add puts one line and the
// bag with a fresh rev.
const { docs: bags } = useLiveQuery("type", { key: "bag" });
const bag = me && bags.filter((b) => b.buyerHandle === me.userHandle && !orders.some((o) => o.bagId === b._id && o.status === "paid")).sort((a, b) => b.touchedAt - a.touchedAt)[0];
// A visitor's bag is records too, under the page's guestKey (from the sketch above): their lines stay
// on this device until sign-in, and the same query reads them back after a reload.
const guestBagId = `bag-${guestKey}`;
const { docs: bagLines } = useLiveQuery("bagId", { key: me ? (bag?._id ?? "") : guestBagId });
const savedLines = bagLines.filter((l) => l.type === "line" && (me ? l.buyerHandle === me.userHandle : l.guestKey === guestKey));
// A bag this page started that the live query has not returned yet: two quick Adds share it.
const startedBag = useRef(null);
useEffect(() => {
  if (bag) startedBag.current = null; // the query has it now, and a paid bag must not be reused
}, [bag?._id]);
// The return page's /confirm answered paid: the guest's bag is bought, so its lines go, once per paid
// order and after the live query has read them, so a fresh Add after paying starts a new bag.
const clearedFor = useRef(null);
useEffect(() => {
  if (me || back?.status !== "paid" || savedLines.length === 0 || clearedFor.current === back.orderId) return;
  clearedFor.current = back.orderId;
  savedLines.forEach((l) => database.del(l._id));
}, [me, back?.status, back?.orderId, savedLines.length]);
const lines = savedLines.filter((l) => forSale.some((p) => p._id === l.productId));
const add = async (productId) => {
  const line = savedLines.find((l) => l.productId === productId);
  if (!me) {
    // A visitor's Add is one put of that product's line, held on this device until sign-in.
    return database.put({ ...(line ?? { _id: `${guestBagId}:${productId}`, type: "line", bagId: guestBagId, guestKey, productId }), qty: (line?.qty ?? 0) + 1 });
  }
  // One line per product, its id derived from the bag and the product, so a second Add is a new
  // quantity on the same line, options and all. The bag takes its new rev FIRST, so a Pay link to
  // the old version is refused before its line changes; the line shares the bag's touchedAt, so
  // /pay counts it in this version.
  const bagId = bag?._id ?? (startedBag.current ??= "bag-" + crypto.randomUUID());
  const touchedAt = Date.now();
  await database.put({ ...(bag ?? { _id: bagId, type: "bag", buyerHandle: me.userHandle }), rev: crypto.randomUUID(), touchedAt });
  await database.put({ ...(line ?? { _id: `${bagId}:${productId}`, type: "line", bagId, buyerHandle: me.userHandle, productId }), qty: (line?.qty ?? 0) + 1, touchedAt });
};
// The running total: /quote prices these lines on the server, from the owner's catalog, the way Pay
// will, and asks again whenever the bag changes. (A shop that prices options sends them on each line.)
const [quote, setQuote] = useState(null);
const quoted = JSON.stringify(lines.map(({ productId, qty }) => ({ productId, qty })));
useEffect(() => {
  if (lines.length === 0) return setQuote(null);
  let current = true;
  apiFetch("/quote", { method: "POST", headers: { "content-type": "application/json" }, body: quoted })
    .then((res) => res.json())
    .then((data) => current && setQuote(data.ok ? data : null))
    .catch(() => current && setQuote(null));
  return () => {
    current = false;
  };
}, [quoted]);
// The same address anyone helping the buyer would hand them; /pay charges the total /quote showed.
const payUrl = bag && setup?.pay && `${setup.pay}?bag=${encodeURIComponent(bag._id)}&rev=${encodeURIComponent(bag.rev)}&mode=${setup.mode}`;

// Pay waits for the server to hold this version: a put lands on this device first, and a link to a
// rev the server has not accepted yet would come back as "bag changed".
const saving = bag?._synced && bag._synced.status !== "accepted";
// A guest pays the same lines through /checkout: `pay` from the sketch above, with the page's guestKey.
<Button onClick={() => (me ? window.open(payUrl, "_blank") : pay(lines.map(({ productId, qty }) => ({ productId, qty }))))} disabled={(me && !payUrl) || lines.length === 0 || saving || busy}>
  Pay {quote ? money(quote.amount, quote.currency) : ""} — Stripe opens in a new tab
</Button>
```

`window.open` goes straight to the link inside the click, so there is no
blank tab to fill and no popup warning. The link lands back on the shop
with `#bag-problem=` when the bag moved, something went off sale or checkout
is closed, and the page says so in the shop's words (*Your bag changed: check
it and press Pay again*). The bag stays the buyer's until an order naming it
comes back paid; a buyer who closes Stripe's tab still has their bag, and a
paid bag drops out of the live query, so the next Add starts a fresh one. A
guest's lines go when their return page's `/confirm` answers paid.

A product listed with a period renews, so it sells on the `stripe-subscriptions` recipe: a line like *Monthly coffee bag, $22* or *Bread club, $30 a month* checks out in subscription mode with `price_data[recurring][interval]`, never as a one-time line in a payment-mode bag.

The bag pays the one-time products, and each renewing product is a plan with a
**Subscribe** button of its own (that recipe's *A page that sells both*), so the
starting catalog puts *Monthly coffee bag* on **Plans** and *Single bag* on
**Products**. The owner's **Orders** lists each subscription beside the one-time
orders, with Stripe's status and the next charge date read from its mirror. A
shop whose page says *monthly* while its checkout charges once has broken its
word to the buyer.

A shop with a bag shows the bag in the app's header: a link that carries the bag's live item count and jumps down to the bag or opens it as its own tab, so every Add to bag shows it landed.

The header link reads like *Bag (3)*, its count is the sum of the quantities,
and it sits in the `Navbar` beside the owner's **Products** button, on every
screen where people shop.

## Guest checkout at a venue: a table's check

A restaurant check is the fullest venue page; a tip jar, a donation page or a
pay-at-the-counter page is the same recipe with one line and no splitting.
Staff open a check with its lines, its link goes on the table as a QR code,
and anyone at the table opens it and pays, with no account.

A check may carry an optional pay-by date (`payBy`, a `YYYY-MM-DD` string the
owner picks, with the owner's time zone as `tz`). The page shows it under the
total, and a check past that date in the owner's time zone, with money still
left, reads *Overdue* on the owner's list and the payer's page alike.
A table's check rarely needs one; an invoice always has one.

A check is paid by one payer by default: one primary button pays the whole remaining balance plus the tip, and splitting is a second choice the table opens.

Below the primary *Pay $X*, a quiet *Split the check* opens the other two
ways: the lines I had, or an even share of what is left. The page sends
*what* is paid (`pay: "rest"`, `"lines"` with ids, or `"share"` with how many
ways) and a tip percentage from its own list; the backend prices it from the
check.

Every record is written by `backend.js`, guest or not: `access.js` takes a
payment's creation only from `ctx.requireBackend("fetch")` and its settling
only from the backend, keeps each type at its own ids, and takes the go-live
record only from the owner. A page writes nothing but the owner's own checks.

A guest's write through the route is a signed-out write: `user` is null,
`ctx.requireBackend("fetch")` passes, and the record returns
`allowAnonymous: true`. That opt-in is the whole of it: a write from the app's
own backend.js is not gated by the app's anonymous-write setting (that setting
is for writes straight from a browser), so guests pay with no Setup step for
it. A write the access function refuses answers `guests-closed`, and the page
reads *Checkout is not open yet*.

Before a Checkout Session is created, the payment reserves its share of the check with one revision-checked write.

- **One ledger per check per mode** (`ledger:<mode>:<checkId>`) holds what is
  paid, which lines are paid, and what each open payment holds. `/checkout`
  reads it, prices the request against what is free, adds a hold and writes
  it back with `ifRev`; a second payer who moved in the same instant meets
  `conflict`, reads again, and finds the balance held — the answer is
  *someone at the table is paying right now*. So no balance and no line is
  ever in two open sessions.
- **The payer pays what they were shown.** The page sends the subtotal it
  displayed as `quote`; when the check moved in between, the route reserves
  nothing and answers `quote-changed` with the new amount for the page to
  show.
- **An even split is fixed once chosen.** The first share writes the split
  onto the ledger: N shares of what was free, the rounding cents on the last
  share. Every later share pays the next open one, so two ways on $100 is $50
  and $50 however the first one ends.
- **Settling moves the hold.** `/confirm` reads the session back from Stripe;
  paid adds the hold to the ledger's paid total and lines, expired gives it
  back, and the ledger's `settled` map makes a repeat a no-op. A failed
  session create, a payer back from Stripe without paying (`/release` expires
  their session) and a second press of Pay (which replaces the payer's own
  attempt) all give the hold back the same way. A read-back Stripe cannot
  answer right now changes nothing: the hold stays, and a payer replacing
  their own attempt hears *try again in a moment*.
- **The sweep is the safety net**: every minute it settles payments whose
  payer closed the tab, and anything still pending a day after its
  `createdAt` is expired whatever its session says, since sessions close
  after 30 minutes (`expires_at`).
- The page reads the ledger for its mode with a live query: paid and left
  move on every phone at once, and *Paid in full* shows at zero.

Stripe's page asks the payer for their email and sends the receipt (the owner
turns receipts on under customer emails in their Stripe Dashboard); the app
keeps no email and no name. `submit_type: "pay"` makes Stripe's button read
*Pay*; a donation page passes `"donate"`.

### `backend.js`
```js app=table-check
// A table's check, paid by guests through Stripe Checkout into the owner's connected account.
// Anyone with the table's link pays; every record is written here, never by a page.
export const config = {
  scheduled: { interval: "1m" },
  // Guests have no account, so the routes read unfiltered; each answers only about the check or
  // the payment the request names.
  fetch: { unfilteredReads: { dbs: ["checks"], why: "guests pay a table's check without an account; /checkout, /confirm and /release read only the check, its ledger and the payment the request names" } },
};

const DB = "checks";
const SHOP_NAME = "Corner Bistro"; // the app's own name, as its header shows it
const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
const HOLD_SECONDS = 30 * 60; // a Checkout Session closes after 30 minutes
const TIPS = [0, 15, 18, 20, 25]; // percent of the subtotal
const LIVE_CHOICE = "setup:live";

function json(body, status = 200) {
  return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
}

function appUrl(ctx, hash) {
  return `https://vibes.diy/vibe/${ctx.appInfo.ownerHandle}/${ctx.appInfo.appSlug}${hash}`;
}

async function checkoutMode(ctx) {
  const choice = await ctx.db.get(LIVE_CHOICE, { db: DB });
  const mode = choice?.type === "setup" && choice.mode === "live" ? "live" : "test";
  let st;
  try {
    st = await ctx.stripe.status();
  } catch (e) {
    ctx.log("warn", "stripe status unavailable", { message: e.message });
    return { mode, open: false, state: "unavailable", liveOpen: false, liveReady: false };
  }
  return { mode, open: st[mode].state === "ready", state: st[mode].state, liveOpen: st.live.available, liveReady: st.live.state === "ready" };
}

async function stripe(ctx, mode, method, path, form, headers = {}) {
  let res;
  try {
    res = await ctx.stripe.fetch(`/v1${path}`, { method, body: form, headers, mode });
  } catch (e) {
    ctx.log("warn", "stripe call refused", { reason: e.reason });
    return { ok: false, reason: e.reason ?? "not_available" };
  }
  const body = await res.json().catch(() => null);
  if (!res.ok) return { ok: false, reason: "stripe", message: body?.error?.message ?? `HTTP ${res.status}` };
  return { ok: true, body };
}

// One ledger per check per mode holds the money: what is paid, which lines are paid, and what
// each open payment has reserved. Every change is revision-checked, so two payers can never
// reserve the same balance or the same line.
const ledgerId = (checkId, mode) => `ledger:${mode}:${checkId}`;

async function changeLedger(ctx, checkId, mode, change) {
  const id = ledgerId(checkId, mode);
  for (let attempt = 0; attempt < 5; attempt += 1) {
    const stored = await ctx.db.get(id, { db: DB });
    const ledger = stored ?? { _id: id, type: "ledger", checkId, mode, paid: 0, linesPaid: {}, holds: {}, settled: {} };
    const next = change(structuredClone(ledger));
    if (!next) return ledger; // nothing to change, or the change was refused
    try {
      await ctx.db.put(next, { db: DB, id, ifRev: stored ? stored._rev : null });
      return next;
    } catch (err) {
      if (err.code !== "conflict") throw err; // another payer moved first: read again and retry
    }
  }
  throw new Error("the check is busy");
}

// The sum a ledger has free to reserve, and the lines nobody has paid or reserved.
function freeOf(check, ledger) {
  const total = check.lines.reduce((n, l) => n + l.price, 0);
  const held = Object.values(ledger.holds);
  const taken = new Set([...Object.keys(ledger.linesPaid), ...held.flatMap((h) => h.lines)]);
  return { left: Math.max(0, total - ledger.paid), free: Math.max(0, total - ledger.paid - held.reduce((n, h) => n + h.subtotal, 0)), taken };
}

// An even split is fixed the first time someone picks it: N shares of what was free, the
// rounding cents on the last share, so a 2-way split of $100 stays $50 and $50.
function splitShares(free, ways) {
  const each = Math.floor(free / ways);
  return Array.from({ length: ways }, (_, i) => ({ amount: i === ways - 1 ? free - each * (ways - 1) : each, by: null }));
}

// Settle one pending payment by what Stripe says: paid moves its hold into the ledger's paid
// total, expired gives the hold back. /confirm, /release and the sweep all come here. A read-back
// Stripe could not answer keeps the hold until Stripe can, or until the day is out; `giveUp` is a
// payment whose session Stripe never opened.
async function settle(ctx, p, giveUp = false) {
  if (p.status !== "pending") return p;
  let outcome = null;
  if (p.sessionId) {
    const session = await stripe(ctx, p.mode, "GET", `/checkout/sessions/${p.sessionId}`);
    const s = session.ok ? session.body : null;
    const matches = s && s.client_reference_id === p._id && s.amount_total === p.amount && s.currency === p.currency;
    if (s && !matches) ctx.log("warn", "stripe session does not match its payment", { paymentId: p._id });
    if (matches && s.payment_status === "paid") outcome = "paid";
    else if (matches && s.status === "expired") outcome = "expired";
  }
  // Sessions close after 30 minutes, so a payment still pending a day later is over, whatever it holds.
  if (outcome === null && (giveUp || Date.now() - p.createdAt > SESSION_TTL_MS)) outcome = "expired";
  if (outcome === null) return p;
  await changeLedger(ctx, p.checkId, p.mode, (ledger) => {
    if (ledger.settled[p._id]) return null; // this payment already counted
    delete ledger.holds[p.holdId];
    ledger.settled[p._id] = outcome;
    const share = ledger.split?.shares[p.share];
    if (share) share.by = outcome === "paid" ? p._id : null;
    if (outcome === "paid") {
      ledger.paid += p.subtotal;
      for (const id of p.lines) ledger.linesPaid[id] = p._id;
    }
    return ledger;
  });
  const next = outcome === "paid" ? { ...p, status: "paid", paidAt: Date.now() } : { ...p, status: "expired" };
  try {
    await ctx.db.put(next, { db: DB, id: p._id, ifRev: p._rev });
  } catch (err) {
    if (err.code !== "conflict") throw err;
    const stored = await ctx.db.get(p._id, { db: DB }); // another call settled it first
    if (stored && stored.status !== "pending") return stored;
    throw err;
  }
  if (outcome === "paid") {
    const check = await ctx.db.get(p.checkId, { db: DB }).catch(() => null); // the payment is settled; a failed lookup only shortens the notice
    await tellOwner(ctx, { id: p._id, mode: p.mode, amount: p.amount, currency: p.currency, what: `${check?.table ?? "a check"} paid`, path: `#check=${p.checkId}` });
  }
  return next;
}

// The owner hears about each payment once: the dedupeKey is the payment, so a second settle sends nothing.
async function tellOwner(ctx, { id, mode, amount, currency, what, path }) {
  const fmt = new Intl.NumberFormat("en-US", { style: "currency", currency });
  const price = fmt.format(amount / 10 ** fmt.resolvedOptions().maximumFractionDigits); // minor units: JPY has none
  try {
    await ctx.notify({ toHandle: ctx.appInfo.ownerHandle, body: `${mode === "test" ? "Test payment" : "Payment"}: ${what}, ${price}`.slice(0, 500), dedupeKey: `sale-${id}`, ...(path ? { path } : {}) });
  } catch (err) {
    ctx.log("warn", "payment notice not delivered", { id, reason: err.message }); // the payment stands either way
  }
}

// A payer who came back without paying lets go of what they reserved, straight away.
async function release(ctx, paymentId) {
  const p = typeof paymentId === "string" ? await ctx.db.get(paymentId, { db: DB }) : null;
  if (p?.type !== "payment" || p.status !== "pending") return null;
  if (p.sessionId) await stripe(ctx, p.mode, "POST", `/checkout/sessions/${p.sessionId}/expire`);
  return settle(ctx, p);
}

export async function fetch(request, ctx) {
  const url = new URL(request.url);

  if (url.pathname === "/setup" && request.method === "GET") {
    const owner = ctx.userInfo?.userHandle === ctx.appInfo.ownerHandle;
    const { mode, open, state, liveOpen, liveReady } = await checkoutMode(ctx);
    const item = { id: "stripe-connect", label: "Connect Stripe", done: open, state };
    if (mode === "live" && !liveOpen) item.problem = "Vibes DIY has paused live payments for now; checkout reopens here by itself when they return.";
    const items = [item];
    const ready = items.every((i) => i.done);
    // `paused` is everyone's too: a disconnected account shows a calm paused line, never a Pay button.
    const paused = state === "disconnected";
    if (!owner) return json({ ok: true, ready, owner, mode, paused });
    return json({ ok: true, ready, owner, mode, paused, liveOpen, liveReady, items, ownerHandle: ctx.appInfo.ownerHandle, appSlug: ctx.appInfo.appSlug });
  }

  // The owner, and only the owner, takes this app live.
  if (url.pathname === "/go-live" && request.method === "POST") {
    if (ctx.userInfo?.userHandle !== ctx.appInfo.ownerHandle) return json({ ok: false, reason: "owner-only" }, 403);
    const { liveReady } = await checkoutMode(ctx);
    if (!liveReady) return json({ ok: false, reason: "not_ready" }, 409);
    const chosen = await ctx.db.get(LIVE_CHOICE, { db: DB });
    if (!chosen) await ctx.db.put({ _id: LIVE_CHOICE, type: "setup", mode: "live", chosenAt: Date.now() }, { db: DB, id: LIVE_CHOICE });
    return json({ ok: true, mode: "live" });
  }

  // Pay toward a check. Nobody signs in: the payment is keyed to the check and its session.
  if (url.pathname === "/checkout" && request.method === "POST") {
    const { mode, open, state } = await checkoutMode(ctx);
    const { checkId, pay, lineIds, ways, quote, tipPercent, replaces, mode: shown } = await request.json().catch(() => ({}));
    if (shown !== mode) return json({ ok: false, reason: "mode-changed", mode }, 409);
    if (!open) return json({ ok: false, reason: state === "disconnected" ? "account_disconnected" : "not_ready" }, 503);
    const check = typeof checkId === "string" ? await ctx.db.get(checkId, { db: DB }) : null;
    if (check?.type !== "check") return json({ ok: false, reason: "not-found" }, 404);
    // The payer's own earlier attempt lets go first; while Stripe cannot say how it ended, it keeps its hold.
    const earlier = await release(ctx, replaces);
    if (earlier?.status === "pending") return json({ ok: false, reason: "try-again" }, 503);

    // Reserve before Stripe hears of it: one revision-checked ledger write, priced from the check,
    // at exactly the amount the payer was shown.
    const id = "pay-" + crypto.randomUUID();
    const holdId = crypto.randomUUID();
    let hold = null;
    let refusal = { reason: "being-paid" };
    const refused = await changeLedger(ctx, check._id, mode, (ledger) => {
      const { left, free, taken } = freeOf(check, ledger);
      let lines = [];
      let share;
      let subtotal = free; // the default: everything still free on the check
      if (pay === "lines") {
        lines = [...new Set(Array.isArray(lineIds) ? lineIds : [])].map((lid) => check.lines.find((l) => l.id === lid));
        if (lines.length === 0 || lines.some((l) => !l || taken.has(l.id))) {
          refusal = { reason: "taken" };
          return null;
        }
        subtotal = lines.reduce((n, l) => n + l.price, 0);
      } else if (pay === "share") {
        if (!ledger.split) {
          const n = Math.min(20, Math.max(2, Math.round(Number(ways) || 2)));
          ledger.split = { ways: n, shares: splitShares(free, n) };
        }
        share = ledger.split.shares.findIndex((s) => s.by === null);
        subtotal = share < 0 ? 0 : ledger.split.shares[share].amount;
      }
      if (left === 0) refusal = { reason: "paid-in-full" };
      if (subtotal <= 0 || subtotal > free) return null;
      if (subtotal !== quote) {
        refusal = { reason: "quote-changed", quote: subtotal }; // the check moved since the page drew it
        return null;
      }
      hold = { subtotal, lines: lines.map((l) => l.id), share: share ?? null };
      ledger.holds[holdId] = hold;
      if (share !== undefined) ledger.split.shares[share].by = holdId;
      return ledger;
    }).then(
      () => null,
      (err) => err
    );
    if (refused) {
      // access.js refused the record; its reason is in the log.
      ctx.log("warn", "check reservation refused", { code: refused.code, message: refused.message });
      return json({ ok: false, reason: "guests-closed" }, 503);
    }
    if (!hold) return json({ ok: false, ...refusal }, 409);

    const tip = TIPS.includes(tipPercent) ? tipPercent : 0;
    const tipAmount = Math.round((hold.subtotal * tip) / 100);
    const payment = {
      _id: id,
      type: "payment",
      checkId: check._id,
      holdId,
      lines: hold.lines,
      share: hold.share,
      subtotal: hold.subtotal,
      tip: tipAmount,
      amount: hold.subtotal + tipAmount,
      currency: check.currency,
      mode,
      status: "pending",
      createdAt: Date.now(),
    };
    await ctx.db.put(payment, { db: DB, id, ifRev: null });

    const what = pay === "lines" ? check.lines.filter((l) => hold.lines.includes(l.id)).map((l) => l.name).join(", ").slice(0, 200) : pay === "share" ? "A share of the check" : "The check";
    const form = new URLSearchParams({
      mode: "payment",
      submit_type: "pay",
      "line_items[0][quantity]": "1",
      "line_items[0][price_data][currency]": check.currency,
      "line_items[0][price_data][unit_amount]": String(hold.subtotal),
      "line_items[0][price_data][product_data][name]": `${check.table} · ${what}`,
      client_reference_id: id,
      "metadata[checkId]": check._id,
      "branding_settings[display_name]": SHOP_NAME,
      expires_at: String(Math.floor(Date.now() / 1000) + HOLD_SECONDS),
      success_url: appUrl(ctx, `#check=${check._id}&paid=${id}`),
      cancel_url: appUrl(ctx, `#check=${check._id}&cancelled=${id}`),
    });
    if (tipAmount > 0) {
      form.set("line_items[1][quantity]", "1");
      form.set("line_items[1][price_data][currency]", check.currency);
      form.set("line_items[1][price_data][unit_amount]", String(tipAmount));
      form.set("line_items[1][price_data][product_data][name]", `Tip (${tip}%)`);
    }
    const session = await stripe(ctx, mode, "POST", "/checkout/sessions", form, { "idempotency-key": id });
    if (!session.ok) {
      await settle(ctx, await ctx.db.get(id, { db: DB }), true); // no session: give the hold back now
      return json(session, session.reason === "stripe" ? 502 : 503);
    }
    const stored = await ctx.db.get(id, { db: DB });
    await ctx.db.put({ ...stored, sessionId: session.body.id }, { db: DB, id, ifRev: stored._rev });
    return json({ ok: true, paymentId: id, url: session.body.url });
  }

  // The payer is back: settle by what Stripe says, and answer from it.
  if (url.pathname === "/confirm" && request.method === "POST") {
    const { paymentId } = await request.json().catch(() => ({}));
    const p = typeof paymentId === "string" ? await ctx.db.get(paymentId, { db: DB }) : null;
    if (p?.type !== "payment") return json({ ok: false, reason: "not-found" }, 404);
    const settled = await settle(ctx, p);
    return json({ ok: true, state: settled.status });
  }

  if (url.pathname === "/release" && request.method === "POST") {
    const { paymentId } = await request.json().catch(() => ({}));
    await release(ctx, paymentId);
    return json({ ok: true });
  }

  return json({ ok: false, reason: "not-found" }, 404);
}

// The safety net: a payer who paid and closed the tab, or walked away from Stripe's page, is
// settled within a minute, and their hold comes back to the table.
export async function scheduled(event, ctx) {
  let after;
  let settled = 0;
  do {
    const page = await ctx.db.query({ db: DB, field: "status", key: "pending", limit: 100, after });
    for (const p of page) {
      if (p.type !== "payment") continue;
      const next = await settle(ctx, p);
      if (next !== p) settled += 1;
    }
    after = page.next;
  } while (after);
  ctx.log("info", "check sweep", { settled, at: event.scheduledTime });
}
```

### `access.js`
```js app=table-check
export function checks(doc, oldDoc, user, ctx) {
  const table = (checkId) => {
    if (typeof checkId !== "string" || !/^check-[\w-]+$/.test(checkId)) throw { forbidden: "a record names its check" };
    return `check:${checkId}`;
  };
  // Each type owns its ids, so no record can stand in for another.
  const idFor = { setup: "setup:live", check: doc._id?.startsWith("check-") && doc._id, payment: doc._id?.startsWith("pay-") && doc._id, ledger: `ledger:${doc.mode}:${doc.checkId}` };
  if (!(doc.type in idFor) || doc._id !== idFor[doc.type]) throw { forbidden: "that id belongs to another kind of record" };
  if (oldDoc && oldDoc.type !== doc.type) throw { forbidden: "a record keeps its type" };

  // The owner's go-live choice: backend.js writes it on the owner's own /go-live call.
  if (doc.type === "setup") {
    ctx.requireBackend("fetch");
    ctx.requireRole("owner");
    if (doc.mode !== "live") throw { forbidden: "the setup record says live" };
    return { channels: ["admin"], grant: { roles: { owner: ["admin"] } } };
  }
  // A check: the owner opens it with its lines, and anyone with the table's link reads it.
  if (doc.type === "check") {
    ctx.requireRole("owner");
    const priced = Array.isArray(doc.lines) && doc.lines.every((l) => typeof l.id === "string" && Number.isInteger(l.price) && l.price > 0);
    if (!priced) throw { forbidden: "each line has an id and a whole-cent price" };
    if (doc.payBy !== undefined && (!/^\d{4}-\d{2}-\d{2}$/.test(doc.payBy) || typeof doc.tz !== "string")) {
      throw { forbidden: "a pay-by date is YYYY-MM-DD, with the owner's time zone" };
    }
    if (oldDoc && oldDoc.lines.some((l) => !doc.lines.some((m) => m.id === l.id && m.price === l.price))) {
      throw { forbidden: "a check keeps the lines it opened with; add a new line instead" };
    }
    return { channels: [table(doc._id)], grant: { public: [table(doc._id)] } };
  }
  if (doc.mode !== "test" && doc.mode !== "live") throw { forbidden: "money records name their mode" };
  // A payment: /checkout writes it pending for a guest, and only backend.js settles it.
  if (doc.type === "payment") {
    if (oldDoc) {
      ctx.requireBackend(); // /confirm, /release or the sweep, each after reading Stripe
      if (doc.checkId !== oldDoc.checkId || doc.amount !== oldDoc.amount || doc.currency !== oldDoc.currency || doc.mode !== oldDoc.mode || doc.holdId !== oldDoc.holdId) {
        throw { forbidden: "a payment keeps its check, its amount, its mode and its hold" };
      }
    } else {
      ctx.requireBackend("fetch");
      if (doc.status !== "pending" || !Number.isInteger(doc.amount) || !Number.isInteger(doc.createdAt)) {
        throw { forbidden: "a payment starts pending, in whole cents, with the time it was made" };
      }
    }
    table(doc.checkId);
    // allowAnonymous: backend.js writes it while serving a guest who has no account.
    return { channels: ["payments"], grant: { roles: { owner: ["payments"] } }, allowAnonymous: true };
  }
  // The check's ledger in one mode: written by backend.js alone, read by the whole table.
  ctx.requireBackend();
  if (!Number.isInteger(doc.paid) || doc.paid < 0) throw { forbidden: "a ledger counts whole cents" };
  return { channels: [table(doc.checkId)], allowAnonymous: true };
}
```

### `App.jsx`
```jsx app=table-check
import React, { useEffect, useRef, useState } from "react";
import { useFireproof } from "use-fireproof";
import { apiFetch } from "use-vibes";
import { Badge, Button, Field, Figure, Heading, Input, Metric, Row, Segmented, Stack, Text } from "@vibes.diy/ui";
import { Checkbox } from "@vibes.diy/ui/interactive";

const money = (cents) => `$${(cents / 100).toFixed(2)}`;
// A pay-by date is a YYYY-MM-DD in the owner's time zone, so every viewer sees the same day turn
// over; past it with money left, the check is overdue.
const today = (tz) => {
  try {
    return new Date().toLocaleDateString("en-CA", { timeZone: tz });
  } catch {
    return new Date().toLocaleDateString("en-CA");
  }
};
const overdue = (check, left) => Boolean(check?.payBy) && left > 0 && check.payBy < today(check.tz);
const post = (body) => ({ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
const TIPS = [
  { value: "0", label: "No tip" },
  { value: "15", label: "15%" },
  { value: "18", label: "18%" },
  { value: "20", label: "20%" },
  { value: "25", label: "25%" },
];

// Where a check stands in this mode, read off its ledger, which backend.js alone writes.
function useStanding(check, checkId, mode) {
  const { useLiveQuery } = useFireproof("checks");
  const { docs } = useLiveQuery("_id", { key: `ledger:${mode}:${checkId}` });
  const ledger = docs[0];
  const total = check ? check.lines.reduce((n, l) => n + l.price, 0) : 0;
  const paid = Math.min(total, ledger?.paid ?? 0);
  const holds = Object.values(ledger?.holds ?? {});
  const free = Math.max(0, total - paid - holds.reduce((n, h) => n + h.subtotal, 0));
  const taken = new Set([...Object.keys(ledger?.linesPaid ?? {}), ...holds.flatMap((h) => h.lines)]);
  // An even split, once someone picks it, is fixed on the ledger: the next open share's amount.
  const split = ledger?.split;
  const share = (ways) => (split ? (split.shares.find((s) => s.by === null)?.amount ?? 0) : Math.floor(free / ways));
  return { total, paid, left: total - paid, free, taken, paidLines: new Set(Object.keys(ledger?.linesPaid ?? {})), busy: holds.length > 0, split, share };
}

// The setup verdict, read on mount and again whenever the app comes back into view.
function useSetup() {
  const [setup, setSetup] = useState(null);
  const latest = useRef(0);
  useEffect(() => {
    const load = () => {
      const n = ++latest.current;
      apiFetch("/setup").then((r) => r.json()).catch(() => ({ ready: false, owner: false })).then((s) => { if (n === latest.current) setSetup(s); });
    };
    load();
    const onVisible = () => { if (document.visibilityState === "visible") load(); };
    document.addEventListener("visibilitychange", onVisible);
    window.addEventListener("focus", load);
    window.addEventListener("setup-changed", load);
    return () => { document.removeEventListener("visibilitychange", onVisible); window.removeEventListener("focus", load); window.removeEventListener("setup-changed", load); };
  }, []);
  return setup;
}

const STRIPE_BUTTON = { absent: "Connect Stripe", onboarding: "Finish Stripe setup", disconnected: "Connect Stripe again" };

// The owner's Setup surface: Connect Stripe, the go-live step, and guests' writes for this app.
function SetupScreen({ setup }) {
  const vibe = `${setup.ownerHandle}/${setup.appSlug}`;
  const settingsUrl = `https://vibes.diy/vibes/mine/${vibe}/settings`;
  const item = setup.items.find((i) => i.id === "stripe-connect");
  const live = setup.mode === "live";
  const takeLive = () => apiFetch("/go-live", { method: "POST" }).then(() => window.dispatchEvent(new Event("setup-changed")));
  return (
    <Stack>
      <Heading>Setup</Heading>
      <Row gap={2}>
        <Text>{item.label}</Text>
        <Badge tone={item.done ? "up" : "info"}>{item.done ? "Done" : item.state === "onboarding" ? "Stripe is finishing up" : "To do"}</Badge>
      </Row>
      {item.problem && <Text muted>{item.problem}</Text>}
      <ol>
        <li>
          Open <a href={settingsUrl} target="_blank" rel="noreferrer">this vibe's Settings tab</a> (My Vibes → this vibe → Settings)
          and press <b>{STRIPE_BUTTON[item.state] ?? "Connect Stripe"}</b> under <b>Payments</b>. Stripe opens its own setup pages.
        </li>
        <li>
          Come back here: tables can pay as soon as Stripe says your account is ready. In test mode the card 4242 4242 4242 4242 with any future date pays.
        </li>
        <li>
          <Badge tone={live ? "up" : "info"}>{live ? "Live" : "Test mode"}</Badge>{" "}
          {live ? (
            <>This app takes real payments into your Stripe account; refunds and payouts are in your Stripe Dashboard.</>
          ) : setup.liveReady ? (
            <>Your live Stripe account is ready. <Button onClick={takeLive}>Take live payments in this app</Button></>
          ) : setup.liveOpen ? (
            <>When a test payment goes through, press <b>Go live with Stripe</b> under <b>Payments</b> on <a href={settingsUrl} target="_blank" rel="noreferrer">the same Settings tab</a>, then come back here to take this app live.</>
          ) : (
            <>Test mode runs the whole flow end to end. The <b>Go live with Stripe</b> button appears under <b>Payments</b> on the same Settings tab when vibes.diy opens live payments.</>
          )}
        </li>
      </ol>
    </Stack>
  );
}

// One open check on the owner's list: its table link as a QR code, and what is paid and left.
function CheckRow({ check, setup }) {
  const s = useStanding(check, check._id, setup.mode);
  const link = `https://vibes.diy/vibe/${setup.ownerHandle}/${setup.appSlug}#check=${check._id}`;
  return (
    <Stack>
      <Row gap={2}>
        <Heading level={3}>{check.table}</Heading>
        {s.left === 0 ? <Badge tone="up">Paid in full</Badge> : <Badge tone="info">{money(s.left)} left</Badge>}
        {overdue(check, s.left) && <Badge tone="down">Overdue</Badge>}
      </Row>
      <Text muted>{money(s.paid)} of {money(s.total)} paid{check.payBy ? ` · pay by ${check.payBy}` : ""} · {link}</Text>
      <Figure src={`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(link)}`} alt={`QR code for ${check.table}`} width={200} height={200} />
    </Stack>
  );
}

// The owner opens a check: a table name and its lines, prices kept in whole cents.
function Tables({ setup }) {
  const { database, useLiveQuery } = useFireproof("checks");
  const { docs: checks } = useLiveQuery("type", { key: "check" });
  const [table, setTable] = useState("");
  const [lines, setLines] = useState([]);
  const [name, setName] = useState("");
  const [price, setPrice] = useState("");
  const [payBy, setPayBy] = useState(""); // optional
  const addLine = () => {
    const cents = Math.round(Number(price) * 100);
    if (!name.trim() || !(cents > 0)) return;
    setLines([...lines, { id: crypto.randomUUID().slice(0, 8), name: name.trim(), price: cents }]);
    setName("");
    setPrice("");
  };
  const openCheck = () => {
    const check = { _id: "check-" + crypto.randomUUID(), type: "check", table: table.trim(), lines, currency: "usd", openedAt: Date.now(), ...(payBy ? { payBy, tz: Intl.DateTimeFormat().resolvedOptions().timeZone } : {}) };
    // The form empties as the owner presses Open; the draft comes back only if the write is refused.
    setTable("");
    setLines([]);
    setPayBy("");
    database.put(check).catch(() => {
      setTable(check.table);
      setLines(check.lines);
      setPayBy(check.payBy ?? "");
    });
  };
  return (
    <Stack>
      <Heading>Open a check</Heading>
      <Field label="Table">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={table} onChange={setTable} placeholder="Table 4" />}</Field>
      <Row gap={2}>
        <Field label="Item">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={name} onChange={setName} placeholder="Margherita" />}</Field>
        <Field label="Price">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={price} onChange={setPrice} placeholder="14.50" inputMode="decimal" />}</Field>
        <Button variant="quiet" onClick={addLine}>Add item</Button>
      </Row>
      {lines.map((l) => <Text key={l.id}>{l.name} · {money(l.price)}</Text>)}
      <Field label="Pay by (optional)">{(id, describedBy) => <Input id={id} describedBy={describedBy} type="date" value={payBy} onChange={setPayBy} />}</Field>
      <Button onClick={openCheck} disabled={!table.trim() || lines.length === 0}>Open the check</Button>
      {checks.map((c) => <CheckRow key={c._id} check={c} setup={setup} />)}
    </Stack>
  );
}

// The paused line, in the owner's voice: a disconnected Stripe account shows this where Pay was.
const PAUSED = "Payments are paused right now. Check back soon.";

const SORRY = {
  account_disconnected: PAUSED,
  "being-paid": "Someone at the table is paying right now. This page updates the moment they finish.",
  "paid-in-full": "This check is paid in full.",
  taken: "Someone is paying for one of those. Pick again from what is left.",
  "mode-changed": "Payments here just changed mode. Refresh the page and press Pay again.",
  "try-again": "Stripe did not answer just now. Press Pay again in a moment.",
};

// The table's page: one button pays everything that is left, and splitting is there for the table that wants it.
function TableCheck({ checkId, setup }) {
  const { useLiveQuery } = useFireproof("checks");
  const { docs: found } = useLiveQuery("_id", { key: checkId });
  const check = found.find((d) => d.type === "check");
  const s = useStanding(check, checkId, setup?.mode);
  const [splitting, setSplitting] = useState(false);
  const [how, setHow] = useState("lines");
  const [picked, setPicked] = useState([]);
  const [ways, setWays] = useState("2");
  const [tip, setTip] = useState("18");
  const [mine, setMine] = useState(null); // this payer's latest payment: { id, state }
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);

  // Back from Stripe: /confirm settles the payment by what Stripe says, and the ledger moves for everyone.
  useEffect(() => {
    const back = () => {
      const h = new URLSearchParams(location.hash.slice(1));
      const paid = h.get("paid");
      const cancelled = h.get("cancelled");
      if (!paid && !cancelled) return;
      history.replaceState(null, "", `${location.pathname}#check=${checkId}`);
      if (cancelled) {
        apiFetch("/release", post({ paymentId: cancelled }));
        setMine(null);
        return;
      }
      setMine({ id: paid, state: "pending" });
      apiFetch("/confirm", post({ paymentId: paid })).then((r) => r.json()).then((d) => setMine({ id: paid, state: d.state ?? "pending" }));
    };
    back();
    window.addEventListener("hashchange", back);
    return () => window.removeEventListener("hashchange", back);
  }, [checkId]);

  const withTip = (cents) => cents + Math.round((cents * Number(tip)) / 100);
  // `quote` is the subtotal this page shows; the backend charges exactly that or answers with the new one.
  const pay = async (what) => {
    setError(null);
    const tab = window.open("", "_blank"); // opened inside the click, before any await
    if (!tab) {
      setError("Your browser blocked the Stripe tab. Allow pop-ups for this page and press Pay again.");
      return;
    }
    setBusy(true);
    try {
      const replaces = mine?.state === "pending" ? mine.id : undefined;
      const res = await apiFetch("/checkout", post({ checkId, ...what, tipPercent: Number(tip), replaces, mode: setup.mode }));
      const data = await res.json();
      if (!data.ok) {
        tab.close();
        setError(
          data.reason === "stripe" ? data.message
          : data.reason === "quote-changed" ? `The check just changed: your part is now ${money(withTip(data.quote))}. Press Pay again to pay that.`
          : SORRY[data.reason] ?? "Checkout is not open yet."
        );
        if (data.reason === "account_disconnected") window.dispatchEvent(new Event("setup-changed")); // re-read: Pay steps aside
        return;
      }
      setMine({ id: data.paymentId, state: "pending" });
      tab.location.href = data.url;
    } finally {
      setBusy(false);
    }
  };

  if (!check) return <Text muted>Finding this table's check…</Text>;
  const open = check.lines.filter((l) => !s.taken.has(l.id));
  const pickedTotal = open.filter((l) => picked.includes(l.id)).reduce((n, l) => n + l.price, 0);
  const share = s.share(Number(ways));
  return (
    <Stack>
      <Heading>{check.table}</Heading>
      <Row gap={2}>
        <Metric label="Total" value={money(s.total)} />
        <Metric label="Paid" value={money(s.paid)} />
        <Metric label="Left" value={money(s.left)} />
      </Row>
      {check.payBy && (
        <Row gap={2}>
          <Text muted>Pay by {check.payBy}</Text>
          {overdue(check, s.left) && <Badge tone="down">Overdue</Badge>}
        </Row>
      )}
      {check.lines.map((l) => (
        <Row key={l.id} gap={2}>
          <Text>{l.name}</Text>
          <Text num>{money(l.price)}</Text>
          {s.paidLines.has(l.id) && <Badge tone="up">Paid</Badge>}
        </Row>
      ))}
      {mine?.state === "paid" && <Badge tone="up">Paid. Thank you!</Badge>}
      {s.busy && mine?.state !== "pending" && <Text muted>Someone at the table is paying right now.</Text>}
      {s.left === 0 ? (
        <Badge tone="up">Paid in full</Badge>
      ) : !setup?.ready ? (
        <Text muted>{setup?.paused ? PAUSED : "Checkout is not open yet."}</Text>
      ) : (
        <Stack>
          {setup.mode === "test" && (
            <Row gap={2}>
              <Badge tone="info">Test mode</Badge>
              <Text muted>{setup.owner ? "Pay with the test card 4242 4242 4242 4242 and any future date." : "This is a rehearsal: test payments end when the app goes live."}</Text>
            </Row>
          )}
          <Segmented label="Tip" value={tip} onChange={setTip} options={TIPS} />
          {!splitting ? (
            <Stack>
              <Button onClick={() => pay({ pay: "rest", quote: s.free })} disabled={busy || s.free === 0} loading={busy}>
                Pay {money(withTip(s.free))} — Stripe opens in a new tab
              </Button>
              <Button variant="quiet" onClick={() => setSplitting(true)}>Split the check</Button>
            </Stack>
          ) : (
            <Stack>
              <Segmented label="Split by" value={how} onChange={setHow} options={[{ value: "lines", label: "What I had" }, { value: "share", label: "Even shares" }]} />
              {how === "lines" ? (
                <Stack>
                  {open.map((l) => (
                    <Checkbox key={l.id} label={`${l.name} · ${money(l.price)}`} checked={picked.includes(l.id)} onChange={(on) => setPicked(on ? [...picked, l.id] : picked.filter((id) => id !== l.id))} />
                  ))}
                  <Button onClick={() => pay({ pay: "lines", lineIds: picked, quote: pickedTotal })} disabled={busy || pickedTotal === 0} loading={busy}>
                    Pay {money(withTip(pickedTotal))} for what I had
                  </Button>
                </Stack>
              ) : (
                <Stack>
                  {s.split ? (
                    <Text muted>This check is split {s.split.ways} ways.</Text>
                  ) : (
                    <Segmented label="Ways" value={ways} onChange={setWays} options={["2", "3", "4", "5", "6"].map((n) => ({ value: n, label: `${n} ways` }))} />
                  )}
                  <Button onClick={() => pay({ pay: "share", ways: Number(ways), quote: share })} disabled={busy || share === 0} loading={busy}>
                    Pay my share, {money(withTip(share))}
                  </Button>
                </Stack>
              )}
              <Button variant="quiet" onClick={() => setSplitting(false)}>Pay the whole check instead</Button>
            </Stack>
          )}
        </Stack>
      )}
      {error && <Text>{error}</Text>}
    </Stack>
  );
}

export default function App() {
  const setup = useSetup();
  const [hash, setHash] = useState(() => location.hash);
  const [screen, setScreen] = useState("tables");
  useEffect(() => {
    const onHash = () => setHash(location.hash);
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const checkId = new URLSearchParams(hash.slice(1)).get("check");
  if (checkId) return <TableCheck checkId={checkId} setup={setup} />;
  if (!setup?.owner) return <Text muted>Scan the code on your table to see your check and pay.</Text>;
  return (
    <Stack>
      {/* The owner's own screens: the tables, and Setup while an item is still to do. */}
      <Row gap={2}>
        <Button variant="quiet" onClick={() => setScreen("tables")}>Tables</Button>
        {setup?.owner && (
          <Button variant={setup.ready ? "quiet" : "solid"} onClick={() => setScreen("setup")}>
            Setup{setup.ready ? "" : " · to do"}
          </Button>
        )}
      </Row>
      {screen === "setup" && setup?.owner ? <SetupScreen setup={setup} /> : <Tables setup={setup} />}
    </Stack>
  );
}
```

A tip jar or a donation page keeps this shape with one standing check the
owner opens once and amounts the backend prices from the page's own list, and
no split. Staff who are not the owner open checks through a `staff` role, the
way the access docs teach roles.

## Invoices: a client pays a bill by link

An invoice a client pays online is the table's check with different words: the
owner writes it with lines and amounts of their own choosing (no product
catalog), the client opens its link and pays the whole balance on Stripe's
page with no account, and the same ledger, `/confirm` read-back and sweep make
*paid* a fact. Build it from the check recipe above and change only this:

- **The record is an invoice.** `type: "invoice"`, ids `inv-…`, and on top of
  the check's `lines` and `currency` it carries `client` (the name the owner
  bills, as the owner types it), `number` (the owner's invoice number, the
  next one after their highest prefilled in the form and theirs to change)
  and `payBy` with `tz`, both required here. `access.js` keeps the check's
  write rules: the owner writes it and the lines it opened with stay.
- **An invoice is private; its link is the key.** A table's check sits on a
  public channel, which any visitor can list, and that is fine for a table's
  order but not for a client's name and bill. So an invoice and its ledgers go
  on an owner-only channel (`channels: ["invoices"]`,
  `grant: { roles: { owner: ["invoices"] } }`), and the client's page never
  queries the database: it asks backend.js, which reads unfiltered, through a
  `GET /invoice?id=` route that answers only about the invoice the id names —
  its client, number, lines, `payBy` and what is paid and left from its
  ledger — and `not-found` for anything else. The random `inv-<uuid>` id is
  the link's secret. The page asks on mount, on focus and on the way back from
  Stripe, in place of the check's live query; the owner's own screens keep
  their live queries.
- **One payer, no tip, no split.** The client's page shows the invoice, its
  lines, *Pay by* and one *Pay $X* for what is left (`pay: "rest"`). Leave the
  tip choice and *Split the check* out; the backend keeps its `"rest"` path
  and its revision-checked reservation, so a client who opens the link twice
  still pays once.
- **The owner sends the link.** The app stores no email address: each invoice
  on the owner's list has a *Copy link* button (`navigator.clipboard.writeText`
  of `…#invoice=<id>`) for the owner to paste into their own email or message,
  in place of the table's QR code. Stripe's page asks the client for their
  email and sends the receipt.
- **Paid, open, overdue.** The owner's list reads each invoice's ledger: *Paid*
  at zero left, *Overdue* once today is past `payBy` with money left, *Open*
  otherwise, with a count of each above the list.
- **The owner's notice names the invoice**: `settle` passes
  `` `Invoice ${invoice.number} from ${invoice.client} paid` `` and
  `#invoice=<id>` to `tellOwner`, so the bell says who paid which bill.
- **Stripe's line item names the invoice**:
  `` `Invoice ${invoice.number} · ${invoice.client}` ``, and the session's
  `metadata` carries `invoiceId`, so the owner finds it in their Stripe
  Dashboard.

Every payment goes through Checkout like the rest of this page. Stripe's own
Invoicing product is not part of this recipe: it needs Customer records with
stored emails and charges a fee per paid invoice. An invoice maker that only
records invoices and marks them paid by hand takes no payment and does not
need this skill; offer `▸ [pay] Let clients pay invoices by card` instead.
