@base44/app-plugin-commerce 0.6.8 → 0.6.10
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/base44/entities/commerce.ProductReview.jsonc +2 -2
- package/base44/functions/commerce/storefront-catalog/entry.ts +7 -3
- package/package.json +1 -1
- package/skills/commerce/SKILL.md +1 -1
- package/skills/commerce/docs/api-storefront.md +3 -3
- package/skills/commerce/install/02-storefront.md +18 -6
- package/skills/commerce/references/reviews.md +2 -2
- package/src/commerce/admin/pages/products/Reviews.jsx +4 -1
- package/src/commerce/utils/storefront.js +43 -2
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
},
|
|
25
25
|
"review": {
|
|
26
26
|
"type": "string",
|
|
27
|
-
"description": "Review
|
|
27
|
+
"description": "Review text. May be empty for a stars-only review (submit-review requires text or a rating, not both)."
|
|
28
28
|
},
|
|
29
29
|
"rating": {
|
|
30
30
|
"type": "integer",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"description": "Derived: reviewer purchased the product. Set by commerce/storefront-catalog submit-review."
|
|
39
39
|
}
|
|
40
40
|
},
|
|
41
|
-
"required": ["product_id"
|
|
41
|
+
"required": ["product_id"],
|
|
42
42
|
"rls": {
|
|
43
43
|
"read": { "user_condition": { "role": "admin" } },
|
|
44
44
|
"create": { "user_condition": { "role": "admin" } },
|
|
@@ -396,12 +396,16 @@ async function submitReview(sr: any, p: any, user: any): Promise<any> {
|
|
|
396
396
|
const review = String(p.review ?? "").trim();
|
|
397
397
|
const rating = p.rating == null ? null : Math.floor(Number(p.rating));
|
|
398
398
|
|
|
399
|
-
if (!review) {
|
|
400
|
-
throw new HttpError(400, "review is required.", "review_incomplete");
|
|
401
|
-
}
|
|
402
399
|
if (rating != null && (rating < 0 || rating > 5)) {
|
|
403
400
|
throw new HttpError(400, "Rating must be between 0 and 5.", "invalid_rating");
|
|
404
401
|
}
|
|
402
|
+
// Text or stars — either alone is a valid review. Requiring text rejected
|
|
403
|
+
// every stars-only submission from a form that treats the write-up as
|
|
404
|
+
// optional, with a 400 the customer can't act on. Rating 0 is "unrated"
|
|
405
|
+
// (the aggregates ignore it), so it can't stand in for the missing text.
|
|
406
|
+
if (!review && !(rating != null && rating >= 1)) {
|
|
407
|
+
throw new HttpError(400, "A review needs text or a star rating.", "review_incomplete");
|
|
408
|
+
}
|
|
405
409
|
|
|
406
410
|
const verified = await hasPurchased(sr, reviewerEmail, product.id);
|
|
407
411
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@base44/app-plugin-commerce",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.10",
|
|
4
4
|
"description": "Base44 Commerce plugin — entities, backend functions, shared commerce engine, admin UI and the commerce skill, shipped as copyable source",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"base44",
|
package/skills/commerce/SKILL.md
CHANGED
|
@@ -118,7 +118,7 @@ batch (above).
|
|
|
118
118
|
| Topic | Open when | Size |
|
|
119
119
|
|---|---|---|
|
|
120
120
|
| [`install/01-install.md`](./install/01-install.md) | installing — routes you to 02 and 03 | 6K |
|
|
121
|
-
| [`install/02-storefront.md`](./install/02-storefront.md) | building storefront pages |
|
|
121
|
+
| [`install/02-storefront.md`](./install/02-storefront.md) | building storefront pages | 37K |
|
|
122
122
|
| [`install/03-data.md`](./install/03-data.md) | seeding catalog, shipping rates/zones, payments; re-callable per slice | 11K |
|
|
123
123
|
| [`docs/entities.md`](./docs/entities.md) | any direct entity read/write ("which entity holds X") | 11K |
|
|
124
124
|
| [`references/catalog-rendering.md`](./references/catalog-rendering.md) | field shapes each catalog call returns, variant edge cases | 16K |
|
|
@@ -114,14 +114,14 @@ This is the **only** way a storefront can enumerate ribbons (the entity is admin
|
|
|
114
114
|
No payload. Returns `{ "attributes": [ { ...attribute, "terms": [ ...values ] } ] }` — each attribute (`id, name, code, order`) with its values (`id, attribute_id, name, order, count`), both sorted by `order`; for filter UIs. Filter with `list-products` `attribute_id` (id or attribute **name**) + `attribute_term` (the value name); `code` is the stable key for a URL.
|
|
115
115
|
|
|
116
116
|
### `submit-review`
|
|
117
|
-
**Payload:** `{ product_id, email?, reviewer?, review
|
|
117
|
+
**Payload:** `{ product_id, email?, reviewer?, review?, rating? }` — at least one of `review` (text) or `rating` (1–5); `email` is required for guests (`400 email_required`); a signed-in caller's session email always wins.
|
|
118
118
|
|
|
119
119
|
> A React storefront reaches this call as `submitReview` (and the paginated list as `getProductReviews`) on the client from `@/commerce/storefront`'s `useStorefront()`, with the list itself already riding along on the product; policies and moderation are [`../references/reviews.md`](../references/reviews.md). Read on for the raw contract.
|
|
120
120
|
|
|
121
|
-
**Public by default: anyone can review with an email address — no login.** A guest passes `email`; for a signed-in caller the session email always wins (the payload cannot impersonate). `reviewer` is the display name only, defaulting to the account's `full_name` then the email's local part. `rating` is
|
|
121
|
+
**Public by default: anyone can review with an email address — no login.** A guest passes `email`; for a signed-in caller the session email always wins (the payload cannot impersonate). `reviewer` is the display name only, defaulting to the account's `full_name` then the email's local part. **Text or stars — either alone is valid**: `rating` is 0–5 (0 = unrated, so a stars-only submission needs 1–5); `review_incomplete` fires only when both are missing. `verified` is derived from the email's order history. Status is `hold` unless `products.auto_approve_reviews` — the one server-side switch, so a hardcoded "awaiting approval" message is wrong when it is on. Stricter policies (login-gated, verified buyers only, rating required) are the storefront's own gate around this call — the server accepts any valid email: [`../references/reviews.md`](../references/reviews.md).
|
|
122
122
|
|
|
123
123
|
**Response:** `{ "review_id", "status": "hold"|"approved", "verified": true }`
|
|
124
|
-
**Errors:** `404 not_found`, `400 email_required|review_incomplete
|
|
124
|
+
**Errors:** `404 not_found`, `400 email_required|review_incomplete` (neither text nor stars)`|invalid_rating`.
|
|
125
125
|
|
|
126
126
|
---
|
|
127
127
|
|
|
@@ -116,7 +116,7 @@ import { useProductList, useCategories, useStoreInfo, useFormatMoney, productPri
|
|
|
116
116
|
|
|
117
117
|
⚑ **Render paging whenever `hasNext` is true** — `{list.hasNext && <button type="button" onClick={list.next} disabled={list.busy}>…</button>}` (append mode: `list.loadMore`); a page that renders nothing for paging ships a catalog silently capped at `per_page`. Drive filters from `useCategories()`/`useRibbons()` data via `setParams`, never from hardcoded names — a renamed ribbon must not strand a dead button.
|
|
118
118
|
|
|
119
|
-
A card can render `name`, `productImages(row)[0]`, `productPrice(row, { formatMoney }).label` (already "From €19.99" when the product sells variants — there is no product `type` flag, and `product.price` alone is a rolled-up from-price), `on_sale`, `short_description`, `stock_status`, `average_rating`/`rating_count`, `productRibbons(row)`, `productSpecs(row)`. ⚑ **Images and ribbons are objects, either may be empty** — render your placeholder, never a broken `<img>` or a raw object. Field matrix: [`../references/catalog-rendering.md`](../references/catalog-rendering.md). That list is an inventory, not a card design and not an order to render in. An even grid of identical cards, each carrying the same name/price/stars trio, is where a generated store lands by default and almost never where this catalog belongs: give the grid a rhythm (a hero piece spanning two columns, an editorial break between rows, a denser tile for a large catalog), and lead each card with the one or two fields *these* products are judged on — carat weight, focal length,
|
|
119
|
+
A card can render `name`, `productImages(row)[0]`, `productPrice(row, { formatMoney }).label` (already "From €19.99" when the product sells variants — there is no product `type` flag, and `product.price` alone is a rolled-up from-price), `on_sale`, `short_description`, `stock_status`, `average_rating`/`rating_count`, `productRibbons(row)`, `productSpecs(row)`. ⚑ **Images and ribbons are objects, either may be empty** — render your placeholder, never a broken `<img>` or a raw object. Field matrix: [`../references/catalog-rendering.md`](../references/catalog-rendering.md). That list is an inventory, not a card design and not an order to render in. An even grid of identical cards, each carrying the same name/price/stars trio, is where a generated store lands by default and almost never where this catalog belongs: give the grid a rhythm (a hero piece spanning two columns, an editorial break between rows, a denser tile for a large catalog), and lead each card with the one or two fields *these* products are judged on — carat weight, focal length, ABV — read off `productSpecs(row)`.
|
|
120
120
|
|
|
121
121
|
⚑ **Ribbons belong in both views** — grid and product page. They are the merchant's own merchandising ("Limited", "Last pieces"), and each links to its filtered listing (`/collection?ribbon_id=<id>`). `productRibbons(row)` hands you `{id, name}` **objects** — render `r.name`, key the link on `r.id`; the entry itself in JSX is React's "Objects are not valid as a React child". Never render a bare "Ribbons:" label with nothing after it. ⚑ **A ribbon link inside a card that is itself a link nests `<a>` in `<a>`** — invalid, React warns. In the grid use plain labels, or link the image and title rather than the whole card; keep ribbon links on the product page.
|
|
122
122
|
|
|
@@ -156,9 +156,13 @@ Build your layout from — all optional, **not one component style**:
|
|
|
156
156
|
- **Variant selector** — `variantAxes(view, p.pick)`, one entry per axis:
|
|
157
157
|
|
|
158
158
|
```jsx
|
|
159
|
+
const SWATCH = { Ivory: "#F2EDE4", "Obsidian Black": "#101014" }; // this catalog's colour names → CSS
|
|
159
160
|
{variantAxes(view, p.pick).map((axis) => (
|
|
160
161
|
<fieldset key={axis.key}>{/* label from axis.name / axis.selectedOption */}
|
|
161
|
-
{axis.options.map((o) => (
|
|
162
|
+
{axis.options.map((o) => /colou?r/i.test(axis.name) ? (
|
|
163
|
+
<button key={o.value} disabled={o.disabled} aria-pressed={o.selected} onClick={o.pick}
|
|
164
|
+
className="swatch" style={{ background: SWATCH[o.value] }} title={o.value} aria-label={o.value} />
|
|
165
|
+
) : (
|
|
162
166
|
<button key={o.value} disabled={o.disabled} aria-pressed={o.selected} onClick={o.pick}>
|
|
163
167
|
{o.value}{/* o.outOfStock → mark visibly */}
|
|
164
168
|
</button>
|
|
@@ -167,7 +171,7 @@ Build your layout from — all optional, **not one component style**:
|
|
|
167
171
|
))}
|
|
168
172
|
```
|
|
169
173
|
|
|
170
|
-
⚑ **One control per axis, never a list of variations**, and ⚑ **an unbuyable option renders `disabled`, never hidden** (`outOfStock` stays visible, just marked). `view.missingAxes` names what's unpicked. **
|
|
174
|
+
⚑ **One control per axis, never a list of variations**, and ⚑ **an unbuyable option renders `disabled`, never hidden** (`outOfStock` stays visible, just marked). `view.missingAxes` names what's unpicked. ⚑ **Pick the control per attribute, as the branch above does**: a colour axis as colour circles (the name stays reachable — `title`, `aria-label`, and the axis label showing `selectedOption`), size chips beside a size guide, a select for a long list; a specialty control where it genuinely fits, not on every axis — but every axis as the same bare chip row is the flattest page this kit produces. Any control keeps the contract: disabled, out-of-stock marked, selection visible.
|
|
171
175
|
- **Buy box** — one button, and **you supply its four words**:
|
|
172
176
|
|
|
173
177
|
```jsx
|
|
@@ -190,7 +194,15 @@ Build your layout from — all optional, **not one component style**:
|
|
|
190
194
|
|
|
191
195
|
⚑ **Never `.map()` the whole list into one grey label/value table** — that is the single most reliable tell of a generated product page. Design the two or three rows that carry *this* catalog's meaning as what they are (a weight set in the display face, a composition as bars, a provenance beside its place); let the rest fall through to the plain row, and don't feel obliged to keep them in one block — a spec can sit under the gallery, beside the price, or inside the description. Branch on `s.key` too where one particular modifier deserves its own treatment regardless of type. ⚑ **Look a spec up with `findSpec(rows, "care")`** (ignores case, spaces, `_`, `-`): meta keys are free text (`care`, `Care`, `Care Instructions`), so `rows.find(s => s.label === "Care")` silently never matches and renders the fallback forever. `[]` means no section at all.
|
|
192
196
|
- **Breadcrumbs** — from `categories` (`/collection?category_id=${c.id}`); skip on a flat catalog. Ribbons (`productRibbons(product)`) are labels, not breadcrumbs.
|
|
193
|
-
- **Reviews, only if the store wants them** — no review UI is a complete outcome (then no star ratings on cards either: an average of nothing is `0`).
|
|
197
|
+
- **Reviews, only if the store wants them** — no review UI is a complete outcome (then no star ratings on cards either: an average of nothing is `0`). ⚑ **Both shapes are exact — invented names fail silently** (a 400 naming a field you *did* fill in; blank authors):
|
|
198
|
+
|
|
199
|
+
```jsx
|
|
200
|
+
p.reviews // { items, page, per_page, has_next }
|
|
201
|
+
p.reviews.items[0] // { id, reviewer, review, rating, verified, created_date }
|
|
202
|
+
await submitReview({ product_id, review, rating, reviewer, email }) // NOT content/reviewer_name/reviewer_email
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Text or stars — either alone submits. ⚑ **The form renders for every visitor by default** (guests supply an email; hide it when signed in) — login-gate it only when the store asks. ⚑ Derive the confirmation from the response's `status` (`"approved"` vs `"hold"`) — a hardcoded "awaiting approval" lies to every auto-approving store — and refresh the list after, or the review doesn't appear. Codes, policies, moderation: [`../references/reviews.md`](../references/reviews.md).
|
|
194
206
|
- **Title** — give each page type its own `<title>` and description; a store whose every page shares one static title is invisible to search. Nothing here emits structured data either — if the store wants rich results, emit your own `Product`/`Offer` JSON-LD from `product` and `view.display` (price, currency, availability).
|
|
195
207
|
|
|
196
208
|
## Cart / bag
|
|
@@ -251,7 +263,7 @@ import { CheckoutProvider, useCheckoutContext, AddressFields, ShippingMethodPick
|
|
|
251
263
|
|
|
252
264
|
⚑ Rules: render each picker's `hint` and every branch; a single shipping or payment option still *shows* what it is — never a picker of one, never "nothing selected". ⚑ Picks are instant: both pickers reflect a click immediately (shipping optimistically), and `mustChoose` stays true after a choice — the radios keep rendering, still changeable; never disable options while `syncing`/`choosing` (the hint covers it). Render `addressError` on the address fields. ⚑ Payment methods, currency and countries come from `useStoreInfo()`/`useCountries()` only — `cart.payment_gateways` is always `undefined`, and a default store offers `offline` only, so never hardcode a card option.
|
|
253
265
|
|
|
254
|
-
⚑ **A disabled place-order button must say why** — the silent disabled button is the most common checkout dead end. `blockers` is an array of codes; write one line per code, in the store's voice, anchored near the field that fixes it: `empty_cart`
|
|
266
|
+
⚑ **A disabled place-order button must say why** — the silent disabled button is the most common checkout dead end. `blockers` is an array of codes; write one line per code, in the store's voice, anchored near the field that fixes it: `empty_cart` · `billing_incomplete` (required address fields — `missingBillingFields` names them) · `shipping_address_incomplete` (the separate delivery address) · `shipping_address_required` (no address to price yet) · `shipping_method_required` (choose a delivery option) · `shipping_not_available` (can't deliver there) · `payment_method_required` · `cart_loading` / `shipping_recalculating` (transient — a quiet "one moment", not an error).
|
|
255
267
|
|
|
256
268
|
The pickers' `hint.code` works the same way (`missing_address`, `none_available`, `syncing` for shipping; `none_available` for payment): write those words once, and prefer `hint.serverMessage` when it is set — the backend's explanation is more specific than anything you can write.
|
|
257
269
|
|
|
@@ -304,7 +316,7 @@ function CheckoutForm() {
|
|
|
304
316
|
|
|
305
317
|
**`<AddressFields>` is the one shipped component — use it, never hand-roll the address form.** It owns what hand-rolled forms get wrong: the state/province field appears with the right options once a country is picked (shipping rates and taxes match on country *plus* state, so a form without it mis-prices US/CA/AU orders with no error anywhere), every field keeps its `autoComplete` token (what makes browser autofill work), required marks arm on first blur, and the server's "we don't ship there" lands on the country field. `which="shipping"` renders null until `shipToDifferent` is on — the deliver-elsewhere checkbox itself is yours, wired to `c.shipToDifferent` / `c.setShipToDifferent`.
|
|
306
318
|
|
|
307
|
-
It ships **no CSS** bar a `max-width:100%` cap on the selects (an unstyled checkout must not scroll sideways): every element carries `data-part` (`address-fields`, `field`, `label`, `control`, `required`, `error`) plus `data-key` (the field) and `data-span` (1 or 2 — the field's natural width in a two-column grid), so style it in your `index.css` via `[data-part]` selectors or pass `className`/`classes={{ field, label, control, error }}`. ⚑ **`data-part` sits on the element, not a wrapper** — `select[data-part="control"]`, never `[data-part="control"] input`: the descendant form matches nothing and ships the form unstyled. Props: `includeCompany` (
|
|
319
|
+
It ships **no CSS** bar a `max-width:100%` cap on the selects (an unstyled checkout must not scroll sideways): every element carries `data-part` (`address-fields`, `field`, `label`, `control`, `required`, `error`) plus `data-key` (the field) and `data-span` (1 or 2 — the field's natural width in a two-column grid), so style it in your `index.css` via `[data-part]` selectors or pass `className`/`classes={{ field, label, control, error }}`. ⚑ **`data-part` sits on the element, not a wrapper** — `select[data-part="control"]`, never `[data-part="control"] input`: the descendant form matches nothing and ships the form unstyled. Props: `includeCompany` (false), `includePhone` (true), `omit={["…"]}`, `labels={{ postcode: "ZIP code" }}`, `selectPlaceholder`, and two escape hatches — `inputRender` swaps the control only (spread the handed `dom` props onto your input), `fieldRender` replaces the whole labeled block. `c.missingBillingFields` stays the live list of what is missing, for your own per-field marks.
|
|
308
320
|
|
|
309
321
|
⚑ **The `stage === "submitted"` guard goes above the empty-cart branch** — placing an order clears the cart before the browser navigates, and without the guard the page flashes an empty bag over a just-placed order.
|
|
310
322
|
|
|
@@ -17,7 +17,7 @@ Reviews are **part of the happy path**, not an extra: the backend always shipped
|
|
|
17
17
|
Both live on the storefront client in `@/commerce/utils` — in React, `useStorefront()` is that client:
|
|
18
18
|
|
|
19
19
|
- **`getProductReviews(slugOrRef, { page, per_page })`** → `{ items, page, per_page, has_next, average_rating, rating_count }`. The same reviews `get-product` returns — page or refresh the list without re-fetching the page; `useProduct(slug, { reviewsPerPage })` sizes the first one.
|
|
20
|
-
- **`submitReview({ product_id, review
|
|
20
|
+
- **`submitReview({ product_id, review?, rating?, reviewer?, email? })`** → `{ review_id, status, verified }`. **Text or stars — at least one**: `review` is the body text, `rating` is **1–5 stars** (0 counts as unrated); stars-only and text-only are both valid, only both missing rejects. `reviewer` is the display name. ⚑ **These are the API's names, not the entity's columns** — a form built on `content`/`reviewer_name`/`reviewer_email` is submitting nothing; those three are accepted as aliases, but the reviews you render back are always `{ id, reviewer, review, rating, verified, created_date }`, so an author read off `reviewer_name` renders blank. It **rejects** with `email_required` | `review_incomplete` (neither text nor stars) | `invalid_rating` | `not_found` — catch it, read `storefrontErrorCode(e)`, and land each code on its own field, so a failed submit says what to fix instead of resolving into nothing. After an approved submission, refresh the list yourself so the review actually appears.
|
|
21
21
|
|
|
22
22
|
## What ships
|
|
23
23
|
|
|
@@ -36,7 +36,7 @@ Which visitors may submit is a gate **you** render, in your own words — and **
|
|
|
36
36
|
| **Login-gated** | a signed-in visitor only | one conditional around the same form: render it when your app has a user, otherwise your "sign in to review" line |
|
|
37
37
|
| **Verified buyers** | someone whose own orders include a `processing`/`completed` order for this product | check `storefront-account` `my-orders` for the product, gate on the result |
|
|
38
38
|
|
|
39
|
-
Policies are **UI-side by design**: the server accepts any valid email, so a stricter rule is exactly this gate — and a policy that must hold against handcrafted API calls too belongs in a backend function of your own wrapping `submit-review`. Either way: hide the email field for a signed-in visitor (the session's email wins server-side)
|
|
39
|
+
Policies are **UI-side by design**: the server accepts any valid email, so a stricter rule is exactly this gate — and a policy that must hold against handcrafted API calls too belongs in a backend function of your own wrapping `submit-review`. Either way: hide the email field for a signed-in visitor (the session's email wins server-side). The server needs only one of text/stars — if your form makes either (or both) mandatory, validate before you call, so the customer meets your words rather than a raw 400. An honest middle ground for most stores: accept everything and render the `verified` flag as a "Verified purchase" badge.
|
|
40
40
|
|
|
41
41
|
## Auto-approval and moderation
|
|
42
42
|
|
|
@@ -137,7 +137,10 @@ export default function Reviews() {
|
|
|
137
137
|
label: "Review",
|
|
138
138
|
render: (row) => (
|
|
139
139
|
<div className="max-w-md">
|
|
140
|
-
|
|
140
|
+
{/* A rating-only review is valid — say so, or the row reads as blank. */}
|
|
141
|
+
{row.review
|
|
142
|
+
? <p className="line-clamp-2 text-sm">{row.review}</p>
|
|
143
|
+
: <p className="text-sm italic text-muted-foreground">Rating only — no text</p>}
|
|
141
144
|
{row.verified && <span className="text-xs text-green-700">✓ Verified owner</span>}
|
|
142
145
|
</div>
|
|
143
146
|
),
|
|
@@ -24,6 +24,15 @@
|
|
|
24
24
|
* payload) returns an action's payload as-is.
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
|
+
/** First of `keys` holding a non-empty string on `obj` ("" when none does). */
|
|
28
|
+
function firstFilled(obj, keys) {
|
|
29
|
+
for (const k of keys) {
|
|
30
|
+
const v = obj?.[k];
|
|
31
|
+
if (typeof v === "string" && v.trim()) return v.trim();
|
|
32
|
+
}
|
|
33
|
+
return "";
|
|
34
|
+
}
|
|
35
|
+
|
|
27
36
|
/** The stable error code a failed storefront call carries, if any. */
|
|
28
37
|
export function storefrontErrorCode(e) {
|
|
29
38
|
return e?.response?.data?.code ?? e?.data?.code ?? e?.code ?? null;
|
|
@@ -111,7 +120,18 @@ export function createStorefront(base44, { storageKey = "cart_token", storage }
|
|
|
111
120
|
/**
|
|
112
121
|
* Submit a review. `email` is required for a guest and ignored for a
|
|
113
122
|
* signed-in caller (the session's email always wins, so nobody can
|
|
114
|
-
* review as someone else). `
|
|
123
|
+
* review as someone else). At least one of `review` (the text) or
|
|
124
|
+
* `rating` (1–5 stars) is required — a stars-only submission is valid,
|
|
125
|
+
* and so is text-only; with neither this **throws synchronously**, naming
|
|
126
|
+
* the keys it did receive, instead of letting the server answer about a
|
|
127
|
+
* field the customer filled in.
|
|
128
|
+
*
|
|
129
|
+
* The payload is `{ product_id, review, rating, reviewer, email }` — the
|
|
130
|
+
* API's names, which are **not** the ProductReview entity's columns.
|
|
131
|
+
* Common near-misses (`content`, `text`, `body`, `comment`;
|
|
132
|
+
* `reviewer_name`, `name`; `reviewer_email`) are accepted as aliases, so a
|
|
133
|
+
* form written against the entity still submits. The reviews you render
|
|
134
|
+
* back always use the API's names: `{ reviewer, review, rating, verified }`.
|
|
115
135
|
*
|
|
116
136
|
* Resolves to `{ review_id, status, verified }` — **`status` is
|
|
117
137
|
* `"approved"` or `"hold"` depending on the store's `auto_approve_reviews`
|
|
@@ -119,7 +139,28 @@ export function createStorefront(base44, { storageKey = "cart_token", storage }
|
|
|
119
139
|
* moderation. Rejects with `email_required` | `review_incomplete` |
|
|
120
140
|
* `invalid_rating` | `not_found`.
|
|
121
141
|
*/
|
|
122
|
-
submitReview(
|
|
142
|
+
submitReview(payload = {}) {
|
|
143
|
+
const { product_id, rating } = payload;
|
|
144
|
+
// Accept the names a review form naturally reaches for. The payload keys
|
|
145
|
+
// are NOT the entity's columns, and a plain destructure dropped every
|
|
146
|
+
// mismatch on the floor: a form posting `content`/`reviewer_name`/
|
|
147
|
+
// `reviewer_email` sent no text at all and got back "review is required"
|
|
148
|
+
// — naming a field the customer had filled in. Canonical names win when
|
|
149
|
+
// both are present; anything still unrecognized throws below rather than
|
|
150
|
+
// vanishing.
|
|
151
|
+
const review = firstFilled(payload, ["review", "content", "text", "body", "comment"]);
|
|
152
|
+
const reviewer = firstFilled(payload, ["reviewer", "reviewer_name", "name", "author"]);
|
|
153
|
+
const email = firstFilled(payload, ["email", "reviewer_email"]);
|
|
154
|
+
const rated = rating != null && Number(rating) >= 1;
|
|
155
|
+
if (!review && !rated) {
|
|
156
|
+
// Fail here, not after a round trip: the server can only report the
|
|
157
|
+
// field it didn't receive, which is never the one that is wrong.
|
|
158
|
+
throw new Error(
|
|
159
|
+
`submitReview needs \`review\` text or a \`rating\` of 1-5. Received: ${
|
|
160
|
+
Object.keys(payload).join(", ") || "nothing"
|
|
161
|
+
}. The payload is { product_id, review, rating, reviewer, email } — not the entity's column names.`,
|
|
162
|
+
);
|
|
163
|
+
}
|
|
123
164
|
return inv("commerce/storefront-catalog", {
|
|
124
165
|
action: "submit-review",
|
|
125
166
|
product_id,
|