@base44/app-plugin-commerce 0.3.4 → 0.4.0

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.
@@ -0,0 +1,150 @@
1
+ ---
2
+ read_when: "A cart row, checkout section or receipt region needs structure the parts' props can't express, and you are about to build it on the raw hooks."
3
+ ---
4
+
5
+ # Custom sections on the raw hooks
6
+
7
+ The parts (`Cart.*`, `CartDrawer.*`, `Checkout.*`, `OrderReceived.*`) are thin
8
+ compositions over the hooks below — same providers, same shared state — so
9
+ **replacing one section while keeping the others is normal**: a bespoke
10
+ shipping selector between `<Checkout.AddressFields>` and
11
+ `<Checkout.PaymentMethods>` reads the same checkout the parts do.
12
+
13
+ Work down this ladder; each rung is cheaper than the next:
14
+
15
+ 1. **`classes` / CSS** on `data-part` — almost every "the part looks wrong" is this rung.
16
+ 2. **Labels** — a wording problem is a copy-file problem, never a code problem.
17
+ 3. **`…Render` overrides** — `optionRender`, `lineRender`, `itemRender`, `inputRender`/`fieldRender`: your element, the part's wiring.
18
+ 4. **This file** — rebuild one section on its hook.
19
+ 5. **Edit the part's source** (`src/commerce/storefront/parts/`) — legitimate when a *user requirement* exceeds the props; the edited part is the store's code to maintain.
20
+
21
+ Never re-implement what a hook does (quantity clamps, totals math, repricing,
22
+ drawer state) — that is where storefront bugs cluster. And keep the parts'
23
+ guarantees when you replace them: every state worded, busy scoped to the row,
24
+ a disabled button that says why.
25
+
26
+ ## What the custom-section hooks resolve to
27
+
28
+ | Call | Resolves to |
29
+ |---|---|
30
+ | `useCartLine(item)` | `{ quantity, setQuantity, increase, decrease, remove, pending, error, canIncrease, canDecrease, maxQuantity, atMax, atMin }` — optimistic quantity, clicks coalesced (~250ms), rollback on rejection. `pending` is **this row's** flag: true while its request is out, false only after the new cart view lands — the only mutation-settled signal (`useCart().status` never returns to `"loading"`). |
31
+ | `useCartUI()` | `{ open, openCart, closeCart, toggleCart }` — the drawer state on `<CartUIProvider>` (Esc, open-on-add, close-on-navigate included). |
32
+ | `useCheckoutContext()` | the address (`billing`, `updateBilling`, `shipping`, `updateShipping`, `shipToDifferent`, `setShipToDifferent`, `missingBillingFields`, `addressError`), the choices (`shippingStatus`, `shippingMethods`, `chosenShippingMethod`, `chooseShippingMethod`, `paymentMethods`, `paymentMethod`, `setPaymentMethod`, `selectedGateway`), and the gate (`blockers`, `canPlaceOrder`, `placing`, `stage`, `orderError`, `placeOrder`) — plus `cart`. Works under `<Checkout.Root>` (or your own `<CheckoutProvider>`). |
33
+ | `useOrderReturn()` | `{ status, order, lines, paymentLink, paymentInstructions, error, reload }` — `status`: `"loading" \| "paid" \| "unpaid" \| "cancelled" \| "error"`; `lines` normalized (`image` is `{src, alt}\|null`, `totalLabel` pre-formatted); an order's totals are **flat** (`order.total`, no `order.totals`). |
34
+ | `cartTotalsLines(cart, { formatMoney, labels })` / `orderTotalsLines(order, …)` | `[{ key, label, amount, formatted, hidden, emphasis }]` — keys `subtotal` `discount` `shipping` `tax` `total`; discount/tax are produced and flagged `hidden` when zero, so a mapping renderer can't drop them. |
35
+ | `addressFieldSpec({ countries, country, required, includeEmail })` | `[{ key, label, type, required, autoComplete, options, colSpan }]` — the state field appears (as a select where the country carries states) once `country` is passed. |
36
+ | `ShippingMethodPicker` / `PaymentMethodPicker` | render-prop components the parts wrap — `children({ status, methods, chosen, mustChoose, single, syncing, hint, … })` / `children({ gateways, selected, single, hint })`; every option decorated with `selected`, `select()`, `costLabel`. |
37
+
38
+ ## Reference wiring
39
+
40
+ Words below come from the same copy file the parts read (`STORE_COPY`) — a
41
+ custom section never hardcodes them.
42
+
43
+ **A custom cart row** — `<CartLine>` binds `useCartLine` per row without a
44
+ hook-in-a-loop:
45
+
46
+ ```jsx
47
+ {cart.items.map((item) => (
48
+ <CartLine key={item.item_key} line={item}>
49
+ {(l) => (
50
+ <li aria-busy={l.pending}> {/* busy scope is THIS row, never the cart */}
51
+ {item.name} {attributesLabel(item.attributes)} {formatMoney(item.total)}
52
+ <button onClick={l.decrease} disabled={!l.canDecrease || l.pending}
53
+ aria-label={STORE_COPY.aria.decrease(item.name)}>−</button>
54
+ {l.quantity}
55
+ <button onClick={l.increase} disabled={!l.canIncrease || l.pending}
56
+ aria-label={STORE_COPY.aria.increase(item.name)}>+</button>
57
+ <button onClick={l.remove} disabled={l.pending}
58
+ aria-label={STORE_COPY.aria.remove(item.name)}>×</button>
59
+ {l.error && <p role="alert">{l.error.message}</p>}
60
+ </li>
61
+ )}
62
+ </CartLine>
63
+ ))}
64
+ ```
65
+
66
+ Give repeated controls unique accessible names (the item's name in the label)
67
+ — three identical "Remove" buttons are ambiguous to a screen reader and to a
68
+ script driving the page.
69
+
70
+ **A custom shipping step** — the picker encodes the branching a checkout must
71
+ not skip:
72
+
73
+ ```jsx
74
+ <ShippingMethodPicker>
75
+ {({ hint, mustChoose, methods, chosen }) => (
76
+ <fieldset>{/* renders null for a virtual cart */}
77
+ {hint && <p role={hint.severity === "error" ? "alert" : "status"}>
78
+ {hint.serverMessage ?? STORE_COPY.shipping[hint.code]}</p>}
79
+ {mustChoose && methods.map((m) => (
80
+ <label key={m.id}>
81
+ <input type="radio" name="ship" checked={m.selected} onChange={m.select} />
82
+ {m.title} {m.costLabel}
83
+ </label>
84
+ ))}
85
+ {!mustChoose && chosen && <p>{chosen.title} {chosen.costLabel}</p>}
86
+ </fieldset>
87
+ )}
88
+ </ShippingMethodPicker>
89
+ ```
90
+
91
+ Never render `cart.chosen_shipping_method` directly — it is a rate id; `chosen`
92
+ arrives resolved. A single option still *shows* what it is, never a picker of
93
+ one. `PaymentMethodPicker` is the same shape over `gateways` (titles and
94
+ descriptions are the admin's copy — render them, don't invent your own).
95
+
96
+ **A custom address form** — bind the spec, never a hand-typed field list:
97
+
98
+ ```jsx
99
+ function AddressFields({ which }) {
100
+ const c = useCheckoutContext();
101
+ const { countries } = useCountries(); // [] until store info lands — never null
102
+ const isBilling = which === "billing";
103
+ const values = isBilling ? c.billing : c.shipping;
104
+ const set = isBilling ? c.updateBilling : c.updateShipping;
105
+ const fields = addressFieldSpec({
106
+ countries, country: values.country,
107
+ required: isBilling ? REQUIRED_BILLING_FIELDS : ["country", "city"],
108
+ includeEmail: isBilling, // one email per order, on billing
109
+ });
110
+ return fields.map((f) => (
111
+ <div key={f.key}>
112
+ <label htmlFor={`${which}-${f.key}`}>{STORE_COPY.fields[f.key]}{f.required && " *"}</label>
113
+ {f.type === "select" ? (
114
+ <select id={`${which}-${f.key}`} value={values[f.key] ?? ""} autoComplete={f.autoComplete}
115
+ onChange={(e) => set({ [f.key]: e.target.value })}>
116
+ <option value="">{STORE_COPY.fields.select_placeholder}</option>
117
+ {f.options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
118
+ </select>
119
+ ) : (
120
+ <input id={`${which}-${f.key}`} type={f.type} value={values[f.key] ?? ""}
121
+ autoComplete={f.autoComplete} onChange={(e) => set({ [f.key]: e.target.value })} />
122
+ )}
123
+ {/* "we don't ship there" is an address-level error — it belongs on country */}
124
+ {f.key === "country" && c.addressError && <span role="alert">{c.addressError.message}</span>}
125
+ </div>
126
+ ));
127
+ }
128
+ ```
129
+
130
+ ⚑ Passing `country` is what makes the state/province field appear — rates and
131
+ taxes match on country *plus* state, so a form without it silently mis-prices
132
+ US/CA/AU orders. ⚑ Keep every `autoComplete` token — it is what makes browser
133
+ autofill work.
134
+
135
+ **A custom place-order region** — the gate explains itself:
136
+
137
+ ```jsx
138
+ <button type="button" onClick={c.placeOrder} disabled={!c.canPlaceOrder || c.placing}>
139
+ {c.placing ? STORE_COPY.placeOrder.placing : STORE_COPY.placeOrder.label}
140
+ </button>
141
+ {c.orderError && <p role="alert">{c.orderError.message}</p>}
142
+ {!c.canPlaceOrder && c.blockers.map((code) => <p key={code}>{STORE_COPY.blockers[code]}</p>)}
143
+ ```
144
+
145
+ `placeOrder` is safe as a direct `onClick` handler (an event is not read as
146
+ order fields) and resolves `{ ok, result }` / `{ ok: false, error }` without
147
+ throwing. ⚑ Keep the `stage === "submitted"` guard above any empty-cart branch
148
+ — placing an order clears the cart, and without the guard the page flashes
149
+ "your bag is empty" over a just-placed order (`Checkout.Root`'s gates encode
150
+ this ordering; a fully hand-built page must re-encode it).
@@ -51,3 +51,7 @@ DOM is briefly right about the *intent* and wrong about the *state*.
51
51
  (`/order-received?order_id=…&order_key=…` — the ids come back in
52
52
  `placeOrder`'s result, and `commerce/admin-orders` `search` has the order
53
53
  either way).
54
+ - **Sweep for unfinished copy.** A part whose label is missing renders a
55
+ visible `⟨copy: some.path⟩` placeholder. `⟨copy:` must appear on **no**
56
+ page the script visits — finding one means the store's copy file is
57
+ incomplete, a build defect on par with a broken button.
@@ -12,6 +12,7 @@ import {
12
12
  storefrontErrorCode,
13
13
  storefrontErrorMessage,
14
14
  } from "@/commerce/utils";
15
+ import { LabelsScope } from "./parts/labels";
15
16
 
16
17
  /**
17
18
  * StorefrontProvider — one client, one store-info cache, ONE shared cart.
@@ -26,7 +27,9 @@ import {
26
27
  * it, so the cart badge and the cart page read different carts.
27
28
  *
28
29
  * Pass `base44`, or `store={createStorefront(base44)}` when other modules need
29
- * the same client.
30
+ * the same client. `labels` (optional) is the store's copy map for the parts
31
+ * layer — pass it once here and every part resolves its words from it (the
32
+ * key list and example live in the skill's install/02-storefront.md).
30
33
  *
31
34
  * What lives here, and why it must not be duplicated per page: the client (it
32
35
  * owns the cart_token lifecycle); store info, cached for the session —
@@ -38,7 +41,7 @@ import {
38
41
 
39
42
  const StorefrontContext = createContext(null);
40
43
 
41
- export function StorefrontProvider({ base44, store, children }) {
44
+ export function StorefrontProvider({ base44, store, labels, children }) {
42
45
  const client = useMemo(
43
46
  () => store ?? createStorefront(base44),
44
47
  [store, base44],
@@ -109,7 +112,11 @@ export function StorefrontProvider({ base44, store, children }) {
109
112
  () => ({ client, info, infoError, cart, cartError, mutationError, runCart, clearCart }),
110
113
  [client, info, infoError, cart, cartError, mutationError, runCart, clearCart],
111
114
  );
112
- return <StorefrontContext.Provider value={value}>{children}</StorefrontContext.Provider>;
115
+ return (
116
+ <StorefrontContext.Provider value={value}>
117
+ <LabelsScope labels={labels}>{children}</LabelsScope>
118
+ </StorefrontContext.Provider>
119
+ );
113
120
  }
114
121
 
115
122
  /** Advanced escape hatch: the raw provider state. Prefer the hooks below. */
@@ -60,6 +60,19 @@
60
60
  *
61
61
  * The catalog and product surfaces are where the design freedom lives: these
62
62
  * hooks hand you resolved data, and the rendering is entirely yours.
63
+ *
64
+ * **Parts** — for the four commodity surfaces only (cart, drawer, checkout,
65
+ * order-received), `Checkout.*` / `Cart.*` / `CartDrawer.*` /
66
+ * `OrderReceived.*` render each section's correct semantic markup with zero
67
+ * CSS, zero copy and zero navigation: you place them in YOUR layout, style
68
+ * them via `data-part`/`data-state` selectors or `className`/`classes`, and
69
+ * supply every word through `labels` (chain: part prop → page Root →
70
+ * `<StorefrontProvider labels={…}>`; a missing key renders a visible
71
+ * `⟨copy: …⟩` placeholder). Contract tables, the copy example and the
72
+ * `data-part` inventory: the commerce skill's install/02-storefront.md — use
73
+ * the parts from there, not from these files. They compose the hooks above,
74
+ * so dropping one section down to its hook is normal; they are also the
75
+ * app's own source, editable when a requirement outgrows their props.
63
76
  */
64
77
  export {
65
78
  StorefrontProvider,
@@ -81,6 +94,13 @@ export {
81
94
  isShippingAddressComplete,
82
95
  } from "./address";
83
96
 
97
+ // ── parts: guided sections for the commodity surfaces ──────────────────────
98
+ export { Checkout } from "./parts/checkout";
99
+ export { Cart } from "./parts/cart";
100
+ export { CartDrawer } from "./parts/drawer";
101
+ export { OrderReceived } from "./parts/orderReceived";
102
+ export { REQUIRED_LABEL_KEYS } from "./parts/labels";
103
+
84
104
  // ── catalog ────────────────────────────────────────────────────────────────
85
105
  export { useProductList, useCategories, useRibbons } from "./useProductList";
86
106
  export { useProduct, useAddToCart } from "./useProduct";
@@ -0,0 +1,163 @@
1
+ import React from "react";
2
+ import { attributesLabel } from "@/commerce/utils";
3
+ import { useCart, useFormatMoney } from "../StorefrontProvider";
4
+ import { CartLine } from "../useCartLine";
5
+ import { label, nameLabel, useResolvedLabels } from "./labels";
6
+ import { CouponField, Totals } from "./shared";
7
+
8
+ /**
9
+ * Cart parts — the bag's sections, unstyled and unworded, for a cart page or
10
+ * a drawer's contents alike. Contract, styling (`data-part`), labels and
11
+ * placement: the commerce skill's install/02-storefront.md. These read the
12
+ * ONE shared cart on `<StorefrontProvider>`; there is no `Cart.Root`.
13
+ *
14
+ * `Loading` / `Empty` / `Ready` are gates: children render only in the
15
+ * matching cart status, so branching on emptiness-while-loading cannot be
16
+ * written. Children may be a node or a function of `{ cart, itemCount }`.
17
+ * The checkout link belongs in the store's own markup inside `<Cart.Ready>` —
18
+ * no part renders navigation.
19
+ */
20
+ function gate(name, match) {
21
+ function Gate({ children }) {
22
+ const { status, cart, itemCount } = useCart();
23
+ if (status !== match) return null;
24
+ return typeof children === "function" ? (children({ cart, itemCount }) ?? null) : (children ?? null);
25
+ }
26
+ Gate.displayName = `Cart.${name}`;
27
+ return Gate;
28
+ }
29
+
30
+ const Loading = gate("Loading", "loading");
31
+ const Empty = gate("Empty", "empty");
32
+ const Ready = gate("Ready", "ready");
33
+
34
+ /**
35
+ * The line rows, with the interaction premade per row (optimistic quantity,
36
+ * coalesced clicks, rollback, per-row `pending` — never a cart-wide busy
37
+ * state). `lineRender(item, controls)` replaces a row wholesale; `item.slug`
38
+ * is there when the store's row links to the product page.
39
+ */
40
+ function Lines({ lineRender, className, classes, labels: partLabels }) {
41
+ const { status, cart } = useCart();
42
+ const formatMoney = useFormatMoney();
43
+ const L = useResolvedLabels(partLabels);
44
+ if (status !== "ready") return null;
45
+ return (
46
+ <ul data-part="lines" className={className}>
47
+ {cart.items.map((item) => (
48
+ <CartLine key={item.item_key} line={item}>
49
+ {(l) =>
50
+ lineRender ? (
51
+ lineRender(item, l)
52
+ ) : (
53
+ <li
54
+ data-part="row"
55
+ data-pending={l.pending || undefined}
56
+ aria-busy={l.pending}
57
+ className={classes?.row}
58
+ >
59
+ {item.image ? (
60
+ <img data-part="media" className={classes?.media} src={item.image} alt="" loading="lazy" />
61
+ ) : (
62
+ <div data-part="media" data-empty="" className={classes?.media} />
63
+ )}
64
+ <span data-part="name" className={classes?.name}>{item.name}</span>
65
+ {attributesLabel(item.attributes) ? (
66
+ <span data-part="attributes" className={classes?.attributes}>
67
+ {attributesLabel(item.attributes)}
68
+ </span>
69
+ ) : null}
70
+ <span data-part="stepper" className={classes?.stepper}>
71
+ <button
72
+ type="button"
73
+ data-part="decrease"
74
+ className={classes?.decrease}
75
+ onClick={l.decrease}
76
+ disabled={!l.canDecrease || l.pending}
77
+ aria-label={nameLabel(L, "aria.decrease", item.name)}
78
+ >
79
+
80
+ </button>
81
+ <span data-part="quantity" className={classes?.quantity}>{l.quantity}</span>
82
+ <button
83
+ type="button"
84
+ data-part="increase"
85
+ className={classes?.increase}
86
+ onClick={l.increase}
87
+ disabled={!l.canIncrease || l.pending}
88
+ aria-label={nameLabel(L, "aria.increase", item.name)}
89
+ >
90
+ +
91
+ </button>
92
+ </span>
93
+ <button
94
+ type="button"
95
+ data-part="remove"
96
+ className={classes?.remove}
97
+ onClick={l.remove}
98
+ disabled={l.pending}
99
+ aria-label={nameLabel(L, "aria.remove", item.name)}
100
+ >
101
+ ×
102
+ </button>
103
+ <span data-part="line-total" className={classes?.["line-total"]}>
104
+ {formatMoney(item.total)}
105
+ </span>
106
+ {l.error && (
107
+ <p data-part="error" role="alert" className={classes?.error}>{l.error.message}</p>
108
+ )}
109
+ {item.purchasable && !item.purchasable.ok && (
110
+ <p data-part="error" data-code={item.purchasable.code} role="alert" className={classes?.error}>
111
+ {item.purchasable.error}
112
+ </p>
113
+ )}
114
+ </li>
115
+ )
116
+ }
117
+ </CartLine>
118
+ ))}
119
+ </ul>
120
+ );
121
+ }
122
+
123
+ /**
124
+ * What auto-dropped and why, in the server's own words — expired coupons
125
+ * (`coupon_notices`) and vanished products (`removed_items`). Renders null
126
+ * when there is nothing to say; place it above the lines so a disappearing
127
+ * row never goes unexplained.
128
+ */
129
+ function Notices({ className, classes }) {
130
+ const { cart } = useCart();
131
+ const notices = [
132
+ ...(cart?.coupon_notices ?? []).map((n, i) => ({
133
+ key: `coupon-${n.code ?? i}`,
134
+ code: n.error_code,
135
+ text: n.error,
136
+ })),
137
+ ...(cart?.removed_items ?? []).map((r, i) => ({
138
+ key: `removed-${r.item_key ?? i}`,
139
+ code: r.code,
140
+ text: r.reason,
141
+ })),
142
+ ];
143
+ if (!notices.length) return null;
144
+ return (
145
+ <ul data-part="notices" role="status" className={className}>
146
+ {notices.map((n) => (
147
+ <li key={n.key} data-part="notice" data-code={n.code} className={classes?.notice}>
148
+ {n.text}
149
+ </li>
150
+ ))}
151
+ </ul>
152
+ );
153
+ }
154
+
155
+ export const Cart = {
156
+ Loading,
157
+ Empty,
158
+ Ready,
159
+ Lines,
160
+ Notices,
161
+ CouponField,
162
+ Totals,
163
+ };