@vibes.diy/prompts 14.3.204 → 14.3.205
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +0 -1
- package/index.js +0 -1
- package/index.js.map +1 -1
- package/llms/backend.md +14 -0
- package/llms/github.md +5 -0
- package/llms/stripe-subscriptions.js +1 -1
- package/llms/stripe-subscriptions.js.map +1 -1
- package/llms/stripe-subscriptions.md +179 -35
- package/llms/stripe.js +5 -1
- package/llms/stripe.js.map +1 -1
- package/llms/stripe.md +245 -56
- package/llms/ui-storefront.js +1 -1
- package/llms/ui-storefront.js.map +1 -1
- package/llms/ui-storefront.md +326 -151
- package/package.json +5 -5
- package/system-prompt-initial-oneshot.md +1 -1
- package/system-prompt-initial.md +1 -1
- package/system-prompt.md +1 -1
- package/look-restyle.d.ts +0 -49
- package/look-restyle.js +0 -199
- package/look-restyle.js.map +0 -1
package/llms/stripe.md
CHANGED
|
@@ -18,7 +18,8 @@ that way until the person asks to charge for them. What you may do unasked is
|
|
|
18
18
|
closing row's capability option is `▸ [pay] Take card payments with Stripe`,
|
|
19
19
|
gold when nothing else fits better, and a tap on it is the ask. Words that are
|
|
20
20
|
the ask: "charge", "pay", "paid", "payment", "pay the bill", "split the check",
|
|
21
|
-
"tip", "donate", "deposit", "dues", "tickets", "sell", "
|
|
21
|
+
"tip", "donate", "deposit", "dues", "tickets", "sell", "buy now", "purchase online",
|
|
22
|
+
"checkout", "Stripe".
|
|
22
23
|
Words that are not: "orders",
|
|
23
24
|
"price", "plans", "cart" — those describe records, not money moving.
|
|
24
25
|
|
|
@@ -39,6 +40,22 @@ app where *each visitor* collects money into *their own* Stripe account is a
|
|
|
39
40
|
marketplace, a bigger thing than this recipe — say so plainly and build the
|
|
40
41
|
one-merchant half.
|
|
41
42
|
|
|
43
|
+
**The price list is the owner's, and it lives in the app.**
|
|
44
|
+
|
|
45
|
+
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.
|
|
46
|
+
|
|
47
|
+
The owner lists what they sell, sets each price, changes it next week and takes
|
|
48
|
+
a thing off sale, all from the app's own **Products** screen with no new build
|
|
49
|
+
— and asking the builder to "add a $12 bag of the Ethiopian" writes the same
|
|
50
|
+
record the screen does. `access.js` takes a `product` record from the owner
|
|
51
|
+
alone and checks its price is whole cents. The live catalog starts empty: the
|
|
52
|
+
app's code writes no product, so the owner's first view is the form for their
|
|
53
|
+
first product, and a buyer sees *Nothing for sale yet* until there is one. A
|
|
54
|
+
`seed.json` may carry a few believable products for the screenshot; they reach
|
|
55
|
+
the live app only when the owner asks for the examples, and the owner prices
|
|
56
|
+
them there like any other. A price change applies to the next purchase; an
|
|
57
|
+
order keeps the price it was made at.
|
|
58
|
+
|
|
42
59
|
**Who pays: a guest, unless the record is theirs to keep.**
|
|
43
60
|
|
|
44
61
|
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.
|
|
@@ -209,10 +226,11 @@ Every order records the mode it was made in, and every ctx.stripe.fetch call for
|
|
|
209
226
|
page is the fast cached one.
|
|
210
227
|
- `Idempotency-Key` is the order's `_id`, so a retried request mints one session,
|
|
211
228
|
not two. And a second press for the same thing reuses the open attempt: the
|
|
212
|
-
route looks for this buyer's pending order of the same
|
|
213
|
-
still inside its day, and hands back that session's
|
|
214
|
-
another order — one purchase attempt, however many
|
|
215
|
-
network retried it.
|
|
229
|
+
route looks for this buyer's pending order of the same bag at the prices it
|
|
230
|
+
has now, with a session still inside its day, and hands back that session's
|
|
231
|
+
URL rather than minting another order — one purchase attempt, however many
|
|
232
|
+
times the button or the network retried it. A bag that changed, or a price
|
|
233
|
+
the owner changed since, is a fresh order.
|
|
216
234
|
|
|
217
235
|
The routes read the `orders` database, which `access.js` binds, so `backend.js`
|
|
218
236
|
declares `config.fetch.unfilteredReads` for it — the obligation that comes
|
|
@@ -225,9 +243,19 @@ access function's `orders` channel already scopes to the owner role.
|
|
|
225
243
|
|
|
226
244
|
Amounts are integers in the currency's smallest unit: $12.50 is unit_amount 1250, never 12.5.
|
|
227
245
|
|
|
228
|
-
Keep the amount an integer in the document as well (`amount: 1250`),
|
|
229
|
-
once on the server from the
|
|
230
|
-
browser sends — the route takes *
|
|
246
|
+
Keep the amount an integer in the document as well (`amount: 1250`), read it
|
|
247
|
+
once on the server from the product records the buyer names, and never trust an
|
|
248
|
+
amount the browser sends — the route takes *which products, and how many of
|
|
249
|
+
each*, and looks every price up in the owner's catalog.
|
|
250
|
+
|
|
251
|
+
A bag is paid in one Checkout Session: the page sends each product and its quantity, backend.js prices every line from the owner's catalog, the order keeps those lines, and the session carries one line item per bag line.
|
|
252
|
+
|
|
253
|
+
A lone Pay button is a bag of one (`[{ productId, qty: 1 }]`), so a dues page
|
|
254
|
+
and a shop with a bag take the same `/checkout` route. The order's `lines` hold
|
|
255
|
+
each line's title, unit amount and quantity as they were at checkout, its
|
|
256
|
+
`amount` is their total, and the read-back matches Stripe's `amount_total` to
|
|
257
|
+
that total. A bag is one currency; the route caps it at a sensible number of
|
|
258
|
+
lines and a quantity per line.
|
|
231
259
|
The API is form-encoded, not JSON: build the body with `URLSearchParams`, and
|
|
232
260
|
write nested fields in bracket form exactly as shown. Stripe answers JSON; the
|
|
233
261
|
fields this recipe reads are `id` and `url` when it creates a session, and
|
|
@@ -325,18 +353,42 @@ export const config = {
|
|
|
325
353
|
scheduled: { interval: "5m" },
|
|
326
354
|
// The routes read a buyer's own order back; access.js binds the database, so the fetch lane
|
|
327
355
|
// needs this declaration, and the routes owe the buyerHandle check it waives.
|
|
328
|
-
fetch: { unfilteredReads: { dbs: ["orders"], why: "the /checkout and /confirm
|
|
356
|
+
fetch: { unfilteredReads: { dbs: ["orders"], why: "the /checkout route reads the product the buyer names from the owner's catalog, and /checkout and /confirm read the signed-in buyer's own order, checked by buyerHandle before anything is returned" } },
|
|
329
357
|
};
|
|
330
358
|
|
|
331
359
|
const DB = "orders";
|
|
332
360
|
const SESSION_TTL_MS = 24 * 60 * 60 * 1000; // a Checkout Session expires on its own after a day
|
|
333
361
|
|
|
334
|
-
//
|
|
335
|
-
//
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
};
|
|
362
|
+
// What is for sale is the owner's catalog: `product` records in this database, written by the owner
|
|
363
|
+
// alone from the app's Products screen (access.js), each priced in the currency's smallest unit.
|
|
364
|
+
// The browser names a product, never an amount.
|
|
365
|
+
async function productFor(ctx, productId) {
|
|
366
|
+
if (typeof productId !== "string" || !productId.startsWith("product-")) return null;
|
|
367
|
+
const product = await ctx.db.get(productId, { db: DB });
|
|
368
|
+
if (product?.type !== "product" || product.onSale !== true) return null;
|
|
369
|
+
if (!Number.isInteger(product.amount) || product.amount <= 0) return null;
|
|
370
|
+
return product;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// The buyer's bag, priced now: one line per product, each read from the owner's catalog, with the
|
|
374
|
+
// quantity the buyer asked for. One product and one quantity is a bag too, so a lone Pay button
|
|
375
|
+
// and a shop's whole bag take the same route. One currency per order.
|
|
376
|
+
const MAX_LINES = 20;
|
|
377
|
+
const MAX_QTY = 99;
|
|
378
|
+
async function priceBag(ctx, bag) {
|
|
379
|
+
if (!Array.isArray(bag) || bag.length === 0 || bag.length > MAX_LINES) return null;
|
|
380
|
+
// The shape first: whole quantities in range, each product once.
|
|
381
|
+
if (!bag.every((item) => Number.isInteger(item?.qty) && item.qty >= 1 && item.qty <= MAX_QTY)) return null;
|
|
382
|
+
if (new Set(bag.map((item) => item.productId)).size !== bag.length) return null;
|
|
383
|
+
// Then every line's product, read at once.
|
|
384
|
+
const products = await Promise.all(bag.map((item) => productFor(ctx, item.productId)));
|
|
385
|
+
if (products.some((p) => !p || p.currency !== products[0].currency)) return null;
|
|
386
|
+
const lines = products.map((p, i) => ({ productId: p._id, title: p.title, unitAmount: p.amount, currency: p.currency, qty: bag[i].qty }));
|
|
387
|
+
const amount = lines.reduce((n, l) => n + l.unitAmount * l.qty, 0);
|
|
388
|
+
// The bag's identity at these prices: the same bag at the same prices reuses its open session.
|
|
389
|
+
const key = lines.map((l) => `${l.productId}:${l.qty}:${l.unitAmount}`).sort().join(",");
|
|
390
|
+
return { lines, amount, currency: lines[0].currency, key };
|
|
391
|
+
}
|
|
340
392
|
|
|
341
393
|
function json(body, status = 200) {
|
|
342
394
|
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
@@ -456,28 +508,33 @@ export async function fetch(request, ctx) {
|
|
|
456
508
|
const me = ctx.userInfo?.userHandle;
|
|
457
509
|
if (!me) return json({ ok: false, reason: "sign-in" }, 401);
|
|
458
510
|
const { mode, open, state } = await checkoutMode(ctx);
|
|
459
|
-
const {
|
|
511
|
+
const { lines: bag, mode: shown } = await request.json();
|
|
460
512
|
// The buyer pays in the mode their page showed them, or not at all: a page that still shows
|
|
461
513
|
// the other mode refreshes first.
|
|
462
514
|
if (shown !== mode) return json({ ok: false, reason: "mode-changed", mode }, 409);
|
|
463
515
|
if (!open) return json({ ok: false, reason: state === "disconnected" ? "account_disconnected" : "not_ready" }, 503);
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
516
|
+
// Every price is the one on the owner's product record, read now: a line that is off sale, gone
|
|
517
|
+
// or out of bounds, and nothing is charged.
|
|
518
|
+
const priced = await priceBag(ctx, bag);
|
|
519
|
+
if (!priced) return json({ ok: false, reason: "unknown-item" }, 400);
|
|
520
|
+
|
|
521
|
+
// One attempt per buyer per bag at these prices: a second press, a retry after a lost answer,
|
|
522
|
+
// a reload, all land on the session already open rather than minting another order. A bag
|
|
523
|
+
// that changed, or a price the owner changed since, is a new attempt.
|
|
469
524
|
const pending = await ctx.db.query({ db: DB, field: "status", key: "pending", limit: 100 });
|
|
470
|
-
const attempt = pending.find((o) => o.buyerHandle === me && o.
|
|
525
|
+
const attempt = pending.find((o) => o.buyerHandle === me && o.bagKey === priced.key && o.currency === priced.currency && o.mode === mode && o.sessionUrl && Date.now() - o.createdAt < SESSION_TTL_MS);
|
|
471
526
|
if (attempt) return json({ ok: true, orderId: attempt._id, url: attempt.sessionUrl });
|
|
472
527
|
|
|
473
528
|
const id = "order-" + crypto.randomUUID();
|
|
474
529
|
const order = {
|
|
475
530
|
_id: id,
|
|
476
531
|
type: "order",
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
532
|
+
// The order keeps what was bought at the prices it was bought at, whatever the catalog says later.
|
|
533
|
+
lines: priced.lines.map(({ productId, title, unitAmount, qty }) => ({ productId, title, unitAmount, qty })),
|
|
534
|
+
bagKey: priced.key,
|
|
535
|
+
title: priced.lines.length === 1 ? priced.lines[0].title : `${priced.lines[0].title} and ${priced.lines.length - 1} more`,
|
|
536
|
+
amount: priced.amount,
|
|
537
|
+
currency: priced.currency,
|
|
481
538
|
buyerHandle: me,
|
|
482
539
|
mode, // the account this order is made in; every later call for it passes the same mode
|
|
483
540
|
status: "pending",
|
|
@@ -487,15 +544,18 @@ export async function fetch(request, ctx) {
|
|
|
487
544
|
|
|
488
545
|
const form = new URLSearchParams({
|
|
489
546
|
mode: "payment",
|
|
490
|
-
"line_items[0][quantity]": "1",
|
|
491
|
-
"line_items[0][price_data][currency]": price.currency,
|
|
492
|
-
"line_items[0][price_data][unit_amount]": String(price.amount),
|
|
493
|
-
"line_items[0][price_data][product_data][name]": price.title,
|
|
494
547
|
client_reference_id: id,
|
|
495
548
|
"metadata[orderId]": id,
|
|
496
549
|
success_url: appUrl(ctx, `#paid=${id}`),
|
|
497
550
|
cancel_url: appUrl(ctx, `#cancelled=${id}`),
|
|
498
551
|
});
|
|
552
|
+
// One Stripe line per bag line, so the buyer's receipt lists what they bought.
|
|
553
|
+
order.lines.forEach((l, i) => {
|
|
554
|
+
form.set(`line_items[${i}][quantity]`, String(l.qty));
|
|
555
|
+
form.set(`line_items[${i}][price_data][currency]`, order.currency);
|
|
556
|
+
form.set(`line_items[${i}][price_data][unit_amount]`, String(l.unitAmount));
|
|
557
|
+
form.set(`line_items[${i}][price_data][product_data][name]`, l.title);
|
|
558
|
+
});
|
|
499
559
|
const session = await stripe(ctx, mode, "POST", "/checkout/sessions", form, { "idempotency-key": id });
|
|
500
560
|
if (!session.ok) return json(session, session.reason === "stripe" ? 502 : 503);
|
|
501
561
|
|
|
@@ -539,6 +599,16 @@ export async function scheduled(event, ctx) {
|
|
|
539
599
|
```js app=stripe-dues
|
|
540
600
|
export function orders(doc, oldDoc, user, ctx) {
|
|
541
601
|
if (!user?.userHandle) throw { forbidden: "sign in" };
|
|
602
|
+
// The catalog: the owner lists each product and sets its price from the app's own screen, and
|
|
603
|
+
// anyone reads it. backend.js charges the price on this record, so the owner alone writes one.
|
|
604
|
+
if (doc.type === "product") {
|
|
605
|
+
ctx.requireRole("owner");
|
|
606
|
+
const named = doc._id?.startsWith("product-") && typeof doc.title === "string" && doc.title.trim() !== "";
|
|
607
|
+
if (!named || !Number.isInteger(doc.amount) || doc.amount <= 0 || !/^[a-z]{3}$/.test(doc.currency ?? "") || typeof doc.onSale !== "boolean") {
|
|
608
|
+
throw { forbidden: "a product has a name, a whole-cent price and a currency" };
|
|
609
|
+
}
|
|
610
|
+
return { channels: ["catalog"], grant: { public: ["catalog"] } };
|
|
611
|
+
}
|
|
542
612
|
// The app's go-live choice: written by backend.js on the owner's /go-live call alone, read on
|
|
543
613
|
// the owner's channel.
|
|
544
614
|
if (doc.type === "setup") {
|
|
@@ -550,7 +620,7 @@ export function orders(doc, oldDoc, user, ctx) {
|
|
|
550
620
|
// Only backend.js changes an existing order — the /checkout route adding the session, the
|
|
551
621
|
// /confirm route and the sweep settling it — so no field (sessionId included) is a buyer's to edit.
|
|
552
622
|
ctx.requireBackend();
|
|
553
|
-
if (doc.buyerHandle !== oldDoc.buyerHandle || doc.amount !== oldDoc.amount || doc.currency !== oldDoc.currency || doc.
|
|
623
|
+
if (doc.buyerHandle !== oldDoc.buyerHandle || doc.amount !== oldDoc.amount || doc.currency !== oldDoc.currency || doc.bagKey !== oldDoc.bagKey || doc.mode !== oldDoc.mode) {
|
|
554
624
|
throw { forbidden: "an order keeps its buyer, its price and its mode" };
|
|
555
625
|
}
|
|
556
626
|
} else {
|
|
@@ -570,7 +640,16 @@ export function orders(doc, oldDoc, user, ctx) {
|
|
|
570
640
|
import React, { useEffect, useRef, useState } from "react";
|
|
571
641
|
import { useFireproof } from "use-fireproof";
|
|
572
642
|
import { apiFetch, useVibe } from "use-vibes";
|
|
573
|
-
import { Badge, Button, Heading, Row, Stack, Text } from "@vibes.diy/ui";
|
|
643
|
+
import { Badge, Button, Field, Heading, Input, Row, Stack, Text } from "@vibes.diy/ui";
|
|
644
|
+
import { Checkbox } from "@vibes.diy/ui/interactive";
|
|
645
|
+
|
|
646
|
+
// Amounts are in the currency's smallest unit, the one Stripe charges in: cents for usd, whole yen
|
|
647
|
+
// for jpy. Show, edit and read them through that unit, never a fixed 100.
|
|
648
|
+
const digits = (currency) => new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits;
|
|
649
|
+
const money = (amount, currency) => new Intl.NumberFormat(undefined, { style: "currency", currency }).format(amount / 10 ** digits(currency));
|
|
650
|
+
const toMinor = (text, currency) => Math.round(Number(text) * 10 ** digits(currency));
|
|
651
|
+
const shown = (amount, currency) => (amount / 10 ** digits(currency)).toFixed(digits(currency));
|
|
652
|
+
const CURRENCY = "usd"; // the currency new products are priced in
|
|
574
653
|
|
|
575
654
|
// The setup verdict, read on mount and again whenever the app comes back into view: the owner
|
|
576
655
|
// connects Stripe in another tab and returns, and the Pay buttons unlock without a reload.
|
|
@@ -643,12 +722,76 @@ function SetupScreen({ setup }) {
|
|
|
643
722
|
);
|
|
644
723
|
}
|
|
645
724
|
|
|
725
|
+
// One product on the owner's list: its price edits in place, and On sale puts it in front of buyers
|
|
726
|
+
// or takes it away. A refused write puts the shown price back.
|
|
727
|
+
function ProductRow({ product, save }) {
|
|
728
|
+
const [price, setPrice] = useState(shown(product.amount, product.currency));
|
|
729
|
+
useEffect(() => setPrice(shown(product.amount, product.currency)), [product.amount]);
|
|
730
|
+
const commit = () => {
|
|
731
|
+
const amount = toMinor(price, product.currency);
|
|
732
|
+
if (Number.isInteger(amount) && amount > 0 && amount !== product.amount) save({ ...product, amount }, () => setPrice(shown(product.amount, product.currency)));
|
|
733
|
+
else setPrice(shown(product.amount, product.currency));
|
|
734
|
+
};
|
|
735
|
+
return (
|
|
736
|
+
<Row gap={2}>
|
|
737
|
+
<Text>{product.title}</Text>
|
|
738
|
+
<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>
|
|
739
|
+
<Checkbox label="On sale" checked={product.onSale} onChange={(on) => save({ ...product, onSale: on === true })} />
|
|
740
|
+
</Row>
|
|
741
|
+
);
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// The owner's catalog: what is for sale and what it costs. Each save is a `product` record that
|
|
745
|
+
// access.js takes from the owner alone, and the price on it is the price /checkout charges. Empty,
|
|
746
|
+
// the form for the first product leads; from then on the list leads with a compact add on top.
|
|
747
|
+
function Products({ products, onAdd }) {
|
|
748
|
+
const { database } = useFireproof("orders");
|
|
749
|
+
const [title, setTitle] = useState("");
|
|
750
|
+
const [price, setPrice] = useState("");
|
|
751
|
+
const [error, setError] = useState(null);
|
|
752
|
+
// A put lands on this device at once; the server's verdict arrives on its receipt. A refused save
|
|
753
|
+
// converges back to what the server holds, and the owner gets their draft and the reason back.
|
|
754
|
+
const save = async (product, undo) => {
|
|
755
|
+
setError(null);
|
|
756
|
+
const { synced } = await database.put(product);
|
|
757
|
+
synced.on((s) => {
|
|
758
|
+
if (s.status !== "refused") return;
|
|
759
|
+
undo?.();
|
|
760
|
+
setError(s.message ?? "That did not save: a product needs a name and a price like 12.50.");
|
|
761
|
+
});
|
|
762
|
+
};
|
|
763
|
+
const add = () => {
|
|
764
|
+
const amount = toMinor(price, CURRENCY);
|
|
765
|
+
if (!title.trim() || !Number.isInteger(amount) || amount <= 0) return setError("Give it a name and a price like 12.50.");
|
|
766
|
+
const product = { _id: "product-" + crypto.randomUUID(), type: "product", title: title.trim(), amount, currency: CURRENCY, onSale: true, createdAt: Date.now() };
|
|
767
|
+
// The form empties as the owner presses Add; the draft comes back only if the write is refused.
|
|
768
|
+
// The owner stays here: the first entry would otherwise flip the default screen to the shop.
|
|
769
|
+
onAdd?.();
|
|
770
|
+
setTitle("");
|
|
771
|
+
setPrice("");
|
|
772
|
+
save(product, () => { setTitle(product.title); setPrice(shown(product.amount, product.currency)); });
|
|
773
|
+
};
|
|
774
|
+
return (
|
|
775
|
+
<Stack>
|
|
776
|
+
<Heading>{products.length === 0 ? "Add the first thing you sell" : "Products"}</Heading>
|
|
777
|
+
<Row gap={2}>
|
|
778
|
+
<Field label="Name">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={title} onChange={setTitle} placeholder="Annual dues" />}</Field>
|
|
779
|
+
<Field label="Price">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={price} onChange={setPrice} placeholder="40.00" inputMode="decimal" />}</Field>
|
|
780
|
+
<Button onClick={add}>Add</Button>
|
|
781
|
+
</Row>
|
|
782
|
+
{error && <Text>{error}</Text>}
|
|
783
|
+
{products.map((p) => <ProductRow key={p._id} product={p} save={save} />)}
|
|
784
|
+
</Stack>
|
|
785
|
+
);
|
|
786
|
+
}
|
|
787
|
+
|
|
646
788
|
export default function App() {
|
|
647
789
|
const { me } = useVibe("orders");
|
|
648
790
|
const { useLiveQuery } = useFireproof("orders");
|
|
649
791
|
const { docs: orders } = useLiveQuery("type", { key: "order" });
|
|
792
|
+
const { docs: products } = useLiveQuery("type", { key: "product" });
|
|
650
793
|
const setup = useSetup();
|
|
651
|
-
const [
|
|
794
|
+
const [picked, setPicked] = useState(null);
|
|
652
795
|
const [error, setError] = useState(null);
|
|
653
796
|
|
|
654
797
|
// Back from Stripe: ask the backend to read the session and settle the order. The wrapper hands
|
|
@@ -667,7 +810,8 @@ export default function App() {
|
|
|
667
810
|
}, []);
|
|
668
811
|
|
|
669
812
|
const [busy, setBusy] = useState(false);
|
|
670
|
-
|
|
813
|
+
// `lines` is a bag: [{ productId, qty }]. A lone Pay button sends a bag of one.
|
|
814
|
+
const pay = async (lines) => {
|
|
671
815
|
setError(null);
|
|
672
816
|
const tab = window.open("", "_blank"); // opened inside the click, before any await, so it is not a popup
|
|
673
817
|
if (!tab) {
|
|
@@ -676,14 +820,16 @@ export default function App() {
|
|
|
676
820
|
}
|
|
677
821
|
setBusy(true);
|
|
678
822
|
try {
|
|
679
|
-
// The
|
|
680
|
-
|
|
823
|
+
// The page names the products and how many, never a price; the mode it shows rides along, so
|
|
824
|
+
// the buyer pays in the mode they saw.
|
|
825
|
+
const res = await apiFetch("/checkout", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ lines, mode: setup.mode }) });
|
|
681
826
|
const data = await res.json();
|
|
682
827
|
if (!data.ok) {
|
|
683
828
|
tab.close();
|
|
684
829
|
setError(
|
|
685
830
|
data.reason === "stripe" ? data.message
|
|
686
831
|
: data.reason === "mode-changed" ? `Payments here just moved to ${data.mode} mode. Refresh the page and press Pay again.`
|
|
832
|
+
: data.reason === "unknown-item" ? "Something in your order is no longer for sale. Refresh and try again."
|
|
687
833
|
: "Checkout is not open yet."
|
|
688
834
|
);
|
|
689
835
|
return;
|
|
@@ -695,27 +841,32 @@ export default function App() {
|
|
|
695
841
|
};
|
|
696
842
|
|
|
697
843
|
const ready = setup?.ready === true;
|
|
698
|
-
const
|
|
844
|
+
const forSale = products.filter((p) => p.onSale);
|
|
699
845
|
// Only orders made in the app's current mode count: after going live, test orders are rehearsals.
|
|
700
|
-
const
|
|
846
|
+
const mine = orders.filter((o) => o.buyerHandle === me?.userHandle && o.mode === setup?.mode);
|
|
847
|
+
// The owner with nothing listed starts on Products, the form for their first product in front.
|
|
848
|
+
const screen = picked ?? (setup?.owner && products.length === 0 ? "products" : "shop");
|
|
701
849
|
return (
|
|
702
850
|
<Stack>
|
|
703
851
|
<Row gap={2}>
|
|
704
|
-
<Button variant="quiet" onClick={() =>
|
|
705
|
-
{/* The
|
|
852
|
+
<Button variant="quiet" onClick={() => setPicked("shop")}>Shop</Button>
|
|
853
|
+
{/* The owner's own screens: the catalog, and Setup highlighted while an item is still to do. */}
|
|
854
|
+
{setup?.owner && <Button variant="quiet" onClick={() => setPicked("products")}>Products</Button>}
|
|
706
855
|
{setup?.owner && (
|
|
707
|
-
<Button variant={ready ? "quiet" : "solid"} onClick={() =>
|
|
856
|
+
<Button variant={ready ? "quiet" : "solid"} onClick={() => setPicked("setup")}>
|
|
708
857
|
Setup{ready ? "" : " · to do"}
|
|
709
858
|
</Button>
|
|
710
859
|
)}
|
|
711
860
|
</Row>
|
|
712
861
|
{screen === "setup" && setup?.owner ? (
|
|
713
862
|
<SetupScreen setup={setup} />
|
|
863
|
+
) : screen === "products" && setup?.owner ? (
|
|
864
|
+
<Products products={products} onAdd={() => setPicked("products")} />
|
|
714
865
|
) : (
|
|
715
866
|
<Stack>
|
|
716
|
-
<Heading>
|
|
717
|
-
{
|
|
718
|
-
<
|
|
867
|
+
<Heading>Shop</Heading>
|
|
868
|
+
{forSale.length === 0 ? (
|
|
869
|
+
<Text muted>{setup?.owner ? "Nothing is for sale yet. Add what you sell under Products." : "Nothing for sale yet."}</Text>
|
|
719
870
|
) : ready ? (
|
|
720
871
|
<Stack>
|
|
721
872
|
{/* Test mode is a rehearsal: the owner gets the test card, buyers learn it ends at go-live. */}
|
|
@@ -725,18 +876,30 @@ export default function App() {
|
|
|
725
876
|
<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>
|
|
726
877
|
</Row>
|
|
727
878
|
)}
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
879
|
+
{forSale.map((p) => (
|
|
880
|
+
<Row key={p._id} gap={2}>
|
|
881
|
+
<Text>{p.title}</Text>
|
|
882
|
+
<Button onClick={() => pay([{ productId: p._id, qty: 1 }])} disabled={busy} loading={busy}>
|
|
883
|
+
Pay {money(p.amount, p.currency)} — Stripe opens in a new tab
|
|
884
|
+
</Button>
|
|
885
|
+
</Row>
|
|
886
|
+
))}
|
|
731
887
|
</Stack>
|
|
732
888
|
) : (
|
|
733
889
|
<Text muted>Checkout is not open yet.</Text>
|
|
734
890
|
)}
|
|
735
891
|
{error && <Text>{error}</Text>}
|
|
892
|
+
{mine.length > 0 && (
|
|
893
|
+
<ul>
|
|
894
|
+
{mine.map((o) => (
|
|
895
|
+
<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>
|
|
896
|
+
))}
|
|
897
|
+
</ul>
|
|
898
|
+
)}
|
|
736
899
|
{setup?.owner && (
|
|
737
900
|
<ul>
|
|
738
901
|
{orders.map((o) => (
|
|
739
|
-
<li key={o._id}>@{o.buyerHandle} · {o.title} · {(o.amount
|
|
902
|
+
<li key={o._id}>@{o.buyerHandle} · {o.title} · {money(o.amount, o.currency)} · {o.status}{o.mode === setup.mode ? "" : ` · ${o.mode} rehearsal`}</li>
|
|
740
903
|
))}
|
|
741
904
|
</ul>
|
|
742
905
|
)}
|
|
@@ -747,11 +910,37 @@ export default function App() {
|
|
|
747
910
|
}
|
|
748
911
|
```
|
|
749
912
|
|
|
750
|
-
The
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
913
|
+
The catalog is records, so a page with one thing for sale and a page with
|
|
914
|
+
forty are the same code: the owner adds each one on **Products**, and the Shop
|
|
915
|
+
lists what is on sale with one `pay([{ productId, qty: 1 }])` per button. A club's dues are a
|
|
916
|
+
product called *Annual dues*; next year's dues are next year's purchase of it,
|
|
917
|
+
at whatever price the owner has set by then. Something that recurs on its own,
|
|
918
|
+
where Stripe renews and retries, is the `stripe-subscriptions` skill.
|
|
919
|
+
|
|
920
|
+
### A shop with a bag
|
|
921
|
+
|
|
922
|
+
A shop where people fill a bag (the `ui-storefront` block's shape) keeps that
|
|
923
|
+
block's page and swaps its **Place order** for this recipe's checkout: the bag
|
|
924
|
+
stays a draft in the page while someone shops, and its one lead pays the whole
|
|
925
|
+
bag. Both live in the `orders` database: the products are this recipe's `product`
|
|
926
|
+
records (the storefront adds a photo to each as `_files.photo`), and the order
|
|
927
|
+
the bag becomes is this recipe's `order`, written by `/checkout`, so the
|
|
928
|
+
storefront's own browser-written order goes away. Checkout charges the lines,
|
|
929
|
+
so the storefront's shipping row goes too, unless backend.js prices shipping as
|
|
930
|
+
a line of its own.
|
|
931
|
+
|
|
932
|
+
```jsx
|
|
933
|
+
// The storefront's `lines` already leave out anything taken off sale. Its lead sends each line's
|
|
934
|
+
// product and quantity; the backend prices every line from the catalog, so the page's sum is a
|
|
935
|
+
// preview, never the charge.
|
|
936
|
+
<Button onClick={() => pay(lines.map(({ productId, qty }) => ({ productId, qty })))} disabled={busy || lines.length === 0} loading={busy}>
|
|
937
|
+
Pay {money(subtotal, CURRENCY)} — Stripe opens in a new tab
|
|
938
|
+
</Button>
|
|
939
|
+
```
|
|
940
|
+
|
|
941
|
+
The bag empties when the order comes back paid (the `#paid=` return, or the
|
|
942
|
+
order moving to `paid` in the buyer's live query), never when the tab opens: a
|
|
943
|
+
buyer who closes Stripe's tab still has their bag.
|
|
755
944
|
|
|
756
945
|
## Guest checkout at a venue: a table's check
|
|
757
946
|
|
|
@@ -1322,10 +1511,10 @@ function Tables({ setup }) {
|
|
|
1322
1511
|
return (
|
|
1323
1512
|
<Stack>
|
|
1324
1513
|
<Heading>Open a check</Heading>
|
|
1325
|
-
<Field label="Table"
|
|
1514
|
+
<Field label="Table">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={table} onChange={setTable} placeholder="Table 4" />}</Field>
|
|
1326
1515
|
<Row gap={2}>
|
|
1327
|
-
<Field label="Item"
|
|
1328
|
-
<Field label="Price"
|
|
1516
|
+
<Field label="Item">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={name} onChange={setName} placeholder="Margherita" />}</Field>
|
|
1517
|
+
<Field label="Price">{(id, describedBy) => <Input id={id} describedBy={describedBy} value={price} onChange={setPrice} placeholder="14.50" inputMode="decimal" />}</Field>
|
|
1329
1518
|
<Button variant="quiet" onClick={addLine}>Add item</Button>
|
|
1330
1519
|
</Row>
|
|
1331
1520
|
{lines.map((l) => <Text key={l.id}>{l.name} · {money(l.price)}</Text>)}
|
package/llms/ui-storefront.js
CHANGED
|
@@ -2,6 +2,6 @@ export const uiStorefrontConfig = {
|
|
|
2
2
|
name: "ui-storefront",
|
|
3
3
|
aliases: ["pouf-storefront"],
|
|
4
4
|
label: "Storefront block",
|
|
5
|
-
description: "Product grid with filters, a shopping bag and
|
|
5
|
+
description: "Product grid the owner stocks and prices in the app, with filters, a shopping bag and an order; card payment is the stripe skill",
|
|
6
6
|
};
|
|
7
7
|
//# sourceMappingURL=ui-storefront.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ui-storefront.js","sourceRoot":"","sources":["../../jsr/llms/ui-storefront.ts"],"names":[],"mappings":"AAMA,MAAM,CAAC,MAAM,kBAAkB,GAAc;IAC3C,IAAI,EAAE,eAAe;IACrB,OAAO,EAAE,CAAC,iBAAiB,CAAC;IAC5B,KAAK,EAAE,kBAAkB;IACzB,WAAW,EAAE,
|
|
1
|
+
{"version":3,"file":"ui-storefront.js","sourceRoot":"","sources":["../../jsr/llms/ui-storefront.ts"],"names":[],"mappings":"AAMA,MAAM,CAAC,MAAM,kBAAkB,GAAc;IAC3C,IAAI,EAAE,eAAe;IACrB,OAAO,EAAE,CAAC,iBAAiB,CAAC;IAC5B,KAAK,EAAE,kBAAkB;IACzB,WAAW,EAAE,kIAAkI;CAChJ,CAAC"}
|