@aglyn/plugins-commerce 1.10.0 → 1.12.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.
Files changed (93) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/host-quotes-card.component.js +20 -11
  3. package/src/lib/components/console/host-quotes-card.component.js.map +1 -1
  4. package/src/lib/components/console/invoice-send.component.d.ts +9 -2
  5. package/src/lib/components/console/invoice-send.component.js +58 -30
  6. package/src/lib/components/console/invoice-send.component.js.map +1 -1
  7. package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +84 -0
  8. package/src/lib/components/console/pay-link-readiness-notice.component.js +164 -0
  9. package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -0
  10. package/src/lib/components/console/pos-kiosk/kiosk-menu.d.ts +10 -3
  11. package/src/lib/components/console/pos-kiosk/kiosk-menu.js +29 -8
  12. package/src/lib/components/console/pos-kiosk/kiosk-menu.js.map +1 -1
  13. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.d.ts +2 -0
  14. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js +7 -0
  15. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js.map +1 -1
  16. package/src/lib/components/console/pos-kiosk-page.component.d.ts +2 -0
  17. package/src/lib/components/console/pos-kiosk-page.component.js +54 -3
  18. package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
  19. package/src/lib/components/console/product-add-ons-fields.component.d.ts +0 -2
  20. package/src/lib/components/console/product-add-ons-fields.component.js +1 -6
  21. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  22. package/src/lib/components/console/quote-editor-dialog.component.d.ts +2 -0
  23. package/src/lib/components/console/quote-editor-dialog.component.js +35 -27
  24. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  25. package/src/lib/components/console/quote-pay-link.component.d.ts +3 -0
  26. package/src/lib/components/console/quote-pay-link.component.js +9 -0
  27. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  28. package/src/lib/components/console/quote-send.component.d.ts +3 -0
  29. package/src/lib/components/console/quote-send.component.js +9 -0
  30. package/src/lib/components/console/quote-send.component.js.map +1 -1
  31. package/src/lib/components/product-detail.js +1 -1
  32. package/src/lib/components/product-detail.js.map +1 -1
  33. package/src/lib/components/product-grid.js +5 -3
  34. package/src/lib/components/product-grid.js.map +1 -1
  35. package/src/lib/components/product-reviews.js +17 -12
  36. package/src/lib/components/product-reviews.js.map +1 -1
  37. package/src/lib/components/quote-page-body.js +5 -3
  38. package/src/lib/components/quote-page-body.js.map +1 -1
  39. package/src/lib/components/related-products.js +2 -1
  40. package/src/lib/components/related-products.js.map +1 -1
  41. package/src/lib/model/commerce-invoices.d.ts +45 -5
  42. package/src/lib/model/commerce-invoices.js +46 -9
  43. package/src/lib/model/commerce-invoices.js.map +1 -1
  44. package/src/lib/model/commerce-kiosk-search.d.ts +22 -0
  45. package/src/lib/model/commerce-kiosk-search.js +32 -0
  46. package/src/lib/model/commerce-kiosk-search.js.map +1 -0
  47. package/src/lib/model/commerce-pos-kiosk.d.ts +7 -1
  48. package/src/lib/model/commerce-pos-kiosk.js +1 -1
  49. package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
  50. package/src/lib/model/commerce-quote-pay.d.ts +110 -6
  51. package/src/lib/model/commerce-quote-pay.js +182 -23
  52. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  53. package/src/lib/model/product-modifiers.d.ts +4 -0
  54. package/src/lib/model/product-modifiers.js +5 -0
  55. package/src/lib/model/product-modifiers.js.map +1 -1
  56. package/src/lib/server/billing-webhook.js +4 -1
  57. package/src/lib/server/billing-webhook.js.map +1 -1
  58. package/src/lib/server/commerce-pdf.js +2 -1
  59. package/src/lib/server/commerce-pdf.js.map +1 -1
  60. package/src/lib/server/invoice-email.js +2 -1
  61. package/src/lib/server/invoice-email.js.map +1 -1
  62. package/src/lib/server/order-invoice-send.js +1 -1
  63. package/src/lib/server/order-invoice-send.js.map +1 -1
  64. package/src/lib/server/order-status.d.ts +5 -1
  65. package/src/lib/server/order-status.js +19 -5
  66. package/src/lib/server/order-status.js.map +1 -1
  67. package/src/lib/server/pos-kiosk.js +70 -15
  68. package/src/lib/server/pos-kiosk.js.map +1 -1
  69. package/src/lib/server/quote-email.js +2 -1
  70. package/src/lib/server/quote-email.js.map +1 -1
  71. package/src/lib/server/quote-pay.d.ts +39 -0
  72. package/src/lib/server/quote-pay.js +103 -43
  73. package/src/lib/server/quote-pay.js.map +1 -1
  74. package/src/lib/server/quote-proofs.js +20 -11
  75. package/src/lib/server/quote-proofs.js.map +1 -1
  76. package/src/lib/server/site-page-enricher.js +5 -1
  77. package/src/lib/server/site-page-enricher.js.map +1 -1
  78. package/src/lib/testing/fake-firestore.js +34 -5
  79. package/src/lib/testing/fake-firestore.js.map +1 -1
  80. package/src/lib/transfer/product-register-cells.d.ts +75 -0
  81. package/src/lib/transfer/product-register-cells.js +487 -0
  82. package/src/lib/transfer/product-register-cells.js.map +1 -0
  83. package/src/lib/transfer/product-transfer.d.ts +12 -0
  84. package/src/lib/transfer/product-transfer.js +174 -10
  85. package/src/lib/transfer/product-transfer.js.map +1 -1
  86. package/src/lib/transfer/products.server.js +24 -9
  87. package/src/lib/transfer/products.server.js.map +1 -1
  88. package/src/lib/utils/invoice-email-content.d.ts +3 -1
  89. package/src/lib/utils/invoice-email-content.js +1 -1
  90. package/src/lib/utils/invoice-email-content.js.map +1 -1
  91. package/src/lib/utils/quote-email-content.d.ts +3 -1
  92. package/src/lib/utils/quote-email-content.js +3 -3
  93. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/product-reviews.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport { mdiStarOutline } from '@aglyn/shared-data-mdi'\nimport Alert from '@mui/material/Alert'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Chip from '@mui/material/Chip'\nimport Divider from '@mui/material/Divider'\nimport Rating from '@mui/material/Rating'\nimport TextField from '@mui/material/TextField'\nimport Typography from '@mui/material/Typography'\nimport { forwardRef, useEffect, useState } from 'react'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { generatePresetId } from '../utils/generate-preset-id'\n\n// Component ids are persisted in screen documents; never rename.\nexport const ID: Aglyn.ComponentId = 'product-reviews'\n\nexport interface ProductReviewsProps {\n /** Product id; blank resolves from the /products/{slug} page product. */\n productId?: string\n heading?: string\n /**\n * `product` (default): one product's reviews with the submit form.\n * `store`: the store's latest approved reviews across every product, with\n * the average and count, and no form — for a storefront home. In store\n * scope the block draws its own heading (`heading`, default \"What\n * customers say\") and draws NOTHING when there are no approved reviews,\n * so a page never shows an empty reviews band.\n */\n scope?: 'product' | 'store'\n /** Store scope: how many reviews to show (default 6, at most 12). */\n maxItems?: number\n /** Store scope: the heading's level, 2–4 (default 2). */\n headingLevel?: 2 | 3 | 4 | '2' | '3' | '4'\n}\n\ninterface StoreReviewView {\n id: string\n rating: number\n body: string\n authorName: string\n verified: boolean\n createdAtMs: number\n productName?: string\n productSlug?: string\n /** Sold in person only, and the store shows its reviews (AGL-4060). */\n soldInStore?: boolean\n}\n\nconst EDITOR_HINT_SX = {\n p: 3,\n border: '1px dashed',\n borderColor: 'divider',\n borderRadius: 1,\n color: 'text.secondary',\n fontSize: 13,\n fontFamily: 'system-ui, sans-serif',\n} as const\n\ninterface ReviewView {\n id: string\n rating: number\n body: string\n authorName: string\n verified: boolean\n reply?: string | null\n createdAtMs: number\n}\n\n/** What `GET /api/commerce/reviews?mode=eligibility` answers (AGL-3736). */\nexport interface ReviewFormEligibility {\n enabled?: boolean\n policy?: 'verified' | 'anyone'\n signedIn?: boolean\n verifiedVia?: 'member' | 'token' | null\n canReview?: boolean\n needsEmail?: boolean\n tokenProblem?: string\n}\n\n/** Where a shopper signs in to their account on the store. */\nexport const REVIEW_SIGN_IN_HREF = '/account'\n\n/** The review link from the review-request email, if the page carries one. */\nexport function reviewTokenFromLocation(search: string): string {\n const token = new URLSearchParams(search).get('review') ?? ''\n return /^[A-Za-z0-9_-]{32}$/.test(token) ? token : ''\n}\n\n/**\n * Which form the block draws, from the server's answer. Pure, so the three\n * states are specified in one place:\n * - `form`: the visitor may review (verified or, under `anyone`, pending);\n * - `sign-in`: the store takes verified reviews only and this visitor is\n * not one — \"Only customers who bought this can review.\" and a sign-in\n * link (no form: a typed email verifies nothing);\n * - `none`: reviews are off on this plan, or the answer has not come yet.\n */\nexport function reviewFormMode(\n eligibility: ReviewFormEligibility | null,\n): 'form' | 'sign-in' | 'none' {\n if (!eligibility || eligibility.enabled === false) return 'none'\n if (eligibility.canReview) return 'form'\n return 'sign-in'\n}\n\nconst TOKEN_PROBLEM_TEXT: Record<string, string> = {\n review_token_used: 'This review link has already been used.',\n review_token_expired: 'This review link has expired.',\n review_token_invalid: 'This review link is not valid for this product.',\n}\n\nasync function resolveProductIdFromSlug(hostId: string): Promise<string> {\n const match = window.location.pathname.match(/\\/products\\/([^/?#]+)/)\n if (!match) return ''\n const response = await fetch(\n `/api/commerce/product?hostId=${encodeURIComponent(hostId)}` +\n `&slug=${encodeURIComponent(decodeURIComponent(match[1]))}`,\n ).catch(() => null)\n if (!response?.ok) return ''\n const payload = await response.json().catch(() => ({}))\n return String(payload?.product?.id ?? '')\n}\n\n/**\n * Product reviews block (AGL-324): approved reviews with verified-buyer\n * badges, seller replies, an aggregate summary (emitted as JSON-LD\n * AggregateRating), and a submit form. Since AGL-3736 the form asks the server\n * who the visitor is first: a verified buyer (signed in, or arriving with the\n * review-request email's link) gets the form and publishes at once; anyone\n * else sees \"Only customers who bought this can review\" and a sign-in link,\n * unless the store accepts reviews from anyone (held for moderation).\n */\nconst ProductReviews = forwardRef<HTMLDivElement, ProductReviewsProps>(\n (props, ref) => {\n if (props.scope === 'store') return <StoreReviews ref={ref} {...props} />\n return <SingleProductReviews ref={ref} {...props} />\n },\n)\nProductReviews.displayName = 'AglynProductReviews'\n\n/**\n * The store-wide reviews band (`scope: 'store'`): the store's latest APPROVED\n * reviews, read-only stars, the reviewer's first name and initial, a verified\n * badge, and the product reviewed — linked to its page, or, for a product\n * sold in person only, marked \"Sold in store\" and linked nowhere (AGL-4060).\n * Real reviews or nothing: with none it\n * renders an empty, zero-height element — never sample reviews on a live page\n * (sample testimonials presented as customers' would be fake reviews). The\n * editor, which has no site, gets a dashed hint instead.\n */\nconst StoreReviews = forwardRef<HTMLDivElement, ProductReviewsProps>(\n (props, ref) => {\n const {\n productId: _productId,\n heading,\n scope: _scope,\n maxItems,\n headingLevel,\n ...rest\n } = props\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const [payload, setPayload] = useState<{\n reviews: StoreReviewView[]\n aggregate: { count: number; average: number }\n } | null>(null)\n const limit = maxItems && Number(maxItems) > 0 ? Math.min(12, Math.floor(Number(maxItems))) : 6\n\n useEffect(() => {\n if (!hostId) return\n let active = true\n void fetch(\n `/api/commerce/reviews?hostId=${encodeURIComponent(hostId)}` +\n `&scope=store&limit=${limit}`,\n )\n .then((response) => (response.ok ? response.json() : null))\n .then((body) => {\n if (!active || !body) return\n setPayload({\n reviews: Array.isArray(body.reviews) ? body.reviews : [],\n aggregate: body.aggregate ?? { count: 0, average: 0 },\n })\n })\n .catch(() => undefined)\n return () => {\n active = false\n }\n }, [hostId, limit])\n\n if (!hostId) {\n return (\n <Box ref={ref} {...rest} sx={[EDITOR_HINT_SX, ...nodeSx]}>\n {'★★★★★ Customer reviews appear here once shoppers review your products'}\n </Box>\n )\n }\n // Loading, failed, or none approved: nothing at all — not the node's\n // padding, not a heading over an empty band.\n if (!payload || payload.reviews.length === 0) {\n return <Box ref={ref} data-store-reviews-empty=\"\" sx={{ display: 'none' }} />\n }\n // A select may store the level as a string; read it as a number.\n const asked = Number(headingLevel)\n const level = asked === 3 || asked === 4 ? asked : 2\n const { aggregate } = payload\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[{ display: 'flex', flexDirection: 'column', gap: 3 }, ...nodeSx]}\n >\n <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1, textAlign: 'center' }}>\n <Typography variant={level === 2 ? 'h4' : level === 3 ? 'h5' : 'h6'} component={`h${level}`}>\n {heading || 'What customers say'}\n </Typography>\n {aggregate.count > 0 ? (\n <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>\n <Rating value={aggregate.average} precision={0.1} readOnly size=\"small\" />\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`${aggregate.average} out of 5 · ${aggregate.count} ${aggregate.count === 1 ? 'review' : 'reviews'}`}\n </Typography>\n </Box>\n ) : null}\n </Box>\n <Box\n sx={{\n display: 'grid',\n gap: 2,\n gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', md: 'repeat(3, 1fr)' },\n }}\n >\n {payload.reviews.map((review) => (\n <Box\n key={review.id}\n component=\"figure\"\n sx={{\n m: 0,\n p: 2.5,\n display: 'flex',\n flexDirection: 'column',\n gap: 1,\n border: 1,\n borderColor: 'divider',\n borderRadius: 2,\n bgcolor: 'background.paper',\n }}\n >\n <Rating value={review.rating} readOnly size=\"small\" />\n <Typography component=\"blockquote\" variant=\"body1\" sx={{ m: 0, flex: 1 }}>\n {review.body}\n </Typography>\n <Box component=\"figcaption\" sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ fontWeight: 600 }}>\n {review.authorName}\n </Typography>\n {review.verified ? (\n <Chip label=\"Verified buyer\" size=\"small\" variant=\"outlined\" color=\"success\" />\n ) : null}\n </Box>\n {review.productName || review.soldInStore ? (\n <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, alignItems: 'center' }}>\n {review.productName ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n component={review.productSlug && !review.soldInStore ? 'a' : 'span'}\n {...(review.productSlug && !review.soldInStore ? { href: `/products/${review.productSlug}` } : {})}\n sx={{ textDecoration: 'none' }}\n >\n {review.productName}\n </Typography>\n ) : null}\n {review.soldInStore ? <Chip label=\"Sold in store\" size=\"small\" variant=\"outlined\" /> : null}\n </Box>\n ) : null}\n </Box>\n ))}\n </Box>\n </Box>\n )\n },\n)\nStoreReviews.displayName = 'AglynStoreReviews'\n\nconst SingleProductReviews = forwardRef<HTMLDivElement, ProductReviewsProps>(\n (props, ref) => {\n const {\n productId: productIdProp,\n heading,\n scope: _scope,\n maxItems: _maxItems,\n headingLevel: _headingLevel,\n ...rest\n } = props\n // Node styles ride the renderer-merged sx; recompose (stack.ts pattern).\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const siteFetch = Aglyn.useSiteFetch()\n const [productId, setProductId] = useState(productIdProp ?? '')\n const [reviews, setReviews] = useState<ReviewView[] | null>(null)\n const [aggregate, setAggregate] = useState({ count: 0, average: 0 })\n const [form, setForm] = useState({\n rating: 5,\n body: '',\n authorName: '',\n authorEmail: '',\n })\n const [state, setState] = useState<'idle' | 'busy' | 'done' | 'error'>(\n 'idle',\n )\n const [eligibility, setEligibility] = useState<ReviewFormEligibility | null>(null)\n const [reviewToken, setReviewToken] = useState('')\n const [submitted, setSubmitted] = useState<{ pending: boolean } | null>(null)\n const [errorText, setErrorText] = useState('')\n\n useEffect(() => {\n if (!hostId) return\n let active = true\n void (async () => {\n const resolved =\n productIdProp || (await resolveProductIdFromSlug(hostId))\n if (!active || !resolved) return\n setProductId(resolved)\n const response = await fetch(\n `/api/commerce/reviews?hostId=${encodeURIComponent(hostId)}` +\n `&productId=${encodeURIComponent(resolved)}`,\n ).catch(() => null)\n if (!active || !response?.ok) return\n const payload = await response.json().catch(() => ({}))\n setReviews(payload?.reviews ?? [])\n setAggregate(payload?.aggregate ?? { count: 0, average: 0 })\n // May this visitor review, and would it be verified? (AGL-3736)\n const token = reviewTokenFromLocation(window.location.search)\n setReviewToken(token)\n const answer = await fetch(\n `/api/commerce/reviews?hostId=${encodeURIComponent(hostId)}` +\n `&productId=${encodeURIComponent(resolved)}&mode=eligibility` +\n (token ? `&review=${encodeURIComponent(token)}` : ''),\n { credentials: 'same-origin' },\n ).catch(() => null)\n if (!active || !answer?.ok) return\n setEligibility(await answer.json().catch(() => null))\n })()\n return () => {\n active = false\n }\n }, [hostId, productIdProp])\n\n const handleSubmit = async () => {\n if (!hostId || !productId || state === 'busy') return\n setState('busy')\n try {\n const response = await siteFetch('/api/commerce/reviews', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n productId,\n rating: form.rating,\n body: form.body,\n authorName: form.authorName,\n ...(eligibility?.needsEmail ? { authorEmail: form.authorEmail } : {}),\n ...(reviewToken ? { reviewToken } : {}),\n }),\n })\n const payload = await response.json().catch(() => ({}))\n if (response.ok) {\n setSubmitted({ pending: Boolean(payload?.pending) })\n setState('done')\n } else {\n setErrorText(String(payload?.error ?? ''))\n setState('error')\n }\n } catch {\n setState('error')\n }\n }\n\n if (!hostId) {\n return (\n <Box ref={ref} {...rest} sx={[EDITOR_HINT_SX, ...nodeSx]}>\n {'★★★★★ Product reviews render here'}\n </Box>\n )\n }\n\n return (\n <Box ref={ref} {...rest} sx={[{ display: 'flex', flexDirection: 'column', gap: 1.5 }, ...nodeSx]}>\n {/* No JSON-LD here any more (AGL-686). This block used to emit a\n free-standing `AggregateRating` node, which schema.org ignores —\n a rating has to be a PROPERTY of the Product it rates. The PDP's\n server-rendered Product node now carries `aggregateRating`,\n built from the same `readProductReviews` reader this block's API\n uses, so the structured data and the visible stars cannot\n disagree. It also removes the one call site that was primed to\n become stored XSS the moment a reviewer name went into it. */}\n <Typography variant=\"h6\">\n {heading || 'Reviews'}\n {aggregate.count > 0 ? ` (${aggregate.average} ★ · ${aggregate.count})` : ''}\n </Typography>\n {(reviews ?? []).map((review) => (\n <Box key={review.id}>\n <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>\n <Rating value={review.rating} size=\"small\" readOnly />\n <Typography variant=\"body2\" sx={{ fontWeight: 600 }}>\n {review.authorName}\n </Typography>\n {review.verified ? (\n <Chip label=\"Verified buyer\" size=\"small\" variant=\"outlined\" color=\"success\" />\n ) : null}\n </Box>\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n {review.body}\n </Typography>\n {review.reply ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n sx={{ display: 'block', pl: 2, mt: 0.5, borderLeft: 2, borderColor: 'divider' }}\n >\n {`Seller: ${review.reply}`}\n </Typography>\n ) : null}\n <Divider sx={{ mt: 1.5 }} />\n </Box>\n ))}\n {reviews && reviews.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No reviews yet — be the first.'}\n </Typography>\n ) : null}\n {eligibility?.tokenProblem && TOKEN_PROBLEM_TEXT[eligibility.tokenProblem] ? (\n <Alert severity=\"info\">{TOKEN_PROBLEM_TEXT[eligibility.tokenProblem]}</Alert>\n ) : null}\n {state === 'done' ? (\n <Alert severity=\"success\">\n {submitted?.pending\n ? 'Thanks — your review is awaiting moderation.'\n : 'Thanks — your review is posted.'}\n </Alert>\n ) : reviewFormMode(eligibility) === 'sign-in' ? (\n <Typography variant=\"body2\" color=\"text.secondary\" data-review-sign-in=\"\">\n {'Only customers who bought this can review. '}\n <Box component=\"a\" href={REVIEW_SIGN_IN_HREF} sx={{ color: 'primary.main' }}>\n {'Sign in'}\n </Box>\n </Typography>\n ) : reviewFormMode(eligibility) === 'none' ? null : (\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1, maxWidth: 480 }}>\n <Typography variant=\"subtitle2\">{'Write a review'}</Typography>\n {eligibility?.verifiedVia ? (\n <Chip\n label=\"Your review will show as Verified buyer\"\n size=\"small\"\n variant=\"outlined\"\n color=\"success\"\n sx={{ alignSelf: 'flex-start' }}\n />\n ) : null}\n <Rating\n value={form.rating}\n onChange={(_event, value) =>\n setForm((prev) => ({ ...prev, rating: value ?? 5 }))\n }\n />\n <TextField\n placeholder=\"What did you think?\"\n value={form.body}\n onChange={(event) =>\n setForm((prev) => ({ ...prev, body: event.target.value }))\n }\n size=\"small\"\n multiline\n minRows={2}\n />\n <Box sx={{ display: 'flex', gap: 1 }}>\n <TextField\n placeholder=\"Name\"\n value={form.authorName}\n onChange={(event) =>\n setForm((prev) => ({ ...prev, authorName: event.target.value }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n {eligibility?.needsEmail ? (\n <TextField\n placeholder=\"Email (never shown)\"\n type=\"email\"\n value={form.authorEmail}\n onChange={(event) =>\n setForm((prev) => ({ ...prev, authorEmail: event.target.value }))\n }\n size=\"small\"\n sx={{ flex: 1.4 }}\n />\n ) : null}\n </Box>\n {state === 'error' ? (\n <Alert severity=\"error\">\n {errorText || 'Could not submit — check the fields.'}\n </Alert>\n ) : null}\n <Button\n variant=\"outlined\"\n size=\"small\"\n disabled={\n state === 'busy' ||\n !form.body.trim() ||\n Boolean(eligibility?.needsEmail && !form.authorEmail.trim())\n }\n onClick={handleSubmit}\n sx={{ alignSelf: 'flex-start' }}\n >\n {'Submit review'}\n </Button>\n </Box>\n )}\n </Box>\n )\n },\n)\nSingleProductReviews.displayName = 'AglynSingleProductReviews'\n\nexport const schema: Aglyn.ComponentSchema<ProductReviewsProps> = {\n $id: ID,\n pluginId: BUNDLE_ID,\n displayName: 'Product reviews',\n description:\n 'Approved reviews with verified-buyer badges, and a form for customers ' +\n 'who bought the product to add one.',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiStarOutline.path, sx: { color: '#2e7d32' } },\n flags: { selfClosing: Aglyn.FEATURE_FLAG.ENABLED },\n attributes: [\n {\n name: 'productId',\n label: 'Product id',\n description:\n 'Whose reviews these are. Blank reads the product from the URL, ' +\n 'which is what you want on a product template; naming one pins the ' +\n 'block to that product wherever it is placed.',\n component: Aglyn.FieldComponentType.PRODUCT_SELECT,\n },\n {\n name: 'heading',\n label: 'Heading',\n description: 'Defaults to \"Reviews\" (\"What customers say\" store-wide).',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n {\n // Default `product`, so a page that already places this block keeps it.\n name: 'scope',\n label: 'Show',\n description:\n 'One product’s reviews with a form, or the store’s latest approved ' +\n 'reviews across every product. Store-wide shows nothing until a ' +\n 'shopper’s review is approved.',\n component: Aglyn.FieldComponentType.SELECT,\n options: [\n { label: 'This product', value: 'product' },\n { label: 'Whole store', value: 'store' },\n ],\n },\n {\n name: 'maxItems',\n label: 'Max reviews',\n description: 'Store-wide: how many to show (default 6, at most 12).',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n type: 'number',\n },\n {\n name: 'headingLevel',\n label: 'Heading level',\n description: 'Store-wide: the heading’s level on the page (default H2).',\n component: Aglyn.FieldComponentType.SELECT,\n options: [\n { label: 'H2', value: '2' },\n { label: 'H3', value: '3' },\n { label: 'H4', value: '4' },\n ],\n },\n ],\n}\n\nexport const presets: Aglyn.PresetSchema[] = [\n {\n $id: generatePresetId(ID),\n type: Aglyn.NodeType.PRESET,\n displayName: 'Product reviews',\n pluginId: BUNDLE_ID,\n description: 'Verified-buyer reviews with a submit form',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiStarOutline.path, sx: { color: '#2e7d32' } },\n data: {\n $id: null,\n componentId: ID,\n pluginId: BUNDLE_ID,\n props: {},\n },\n },\n]\n\nexport default ProductReviews\n"],"names":["Aglyn","mdiStarOutline","Alert","Box","Button","Chip","Divider","Rating","TextField","Typography","forwardRef","useEffect","useState","BUNDLE_ID","generatePresetId","ID","EDITOR_HINT_SX","p","border","borderColor","borderRadius","color","fontSize","fontFamily","REVIEW_SIGN_IN_HREF","reviewTokenFromLocation","search","token","URLSearchParams","get","test","reviewFormMode","eligibility","enabled","canReview","TOKEN_PROBLEM_TEXT","review_token_used","review_token_expired","review_token_invalid","resolveProductIdFromSlug","hostId","payload","match","window","location","pathname","response","fetch","encodeURIComponent","decodeURIComponent","catch","ok","json","String","product","id","ProductReviews","props","ref","scope","StoreReviews","SingleProductReviews","displayName","productId","_productId","heading","_scope","maxItems","headingLevel","rest","nodeSx","Array","isArray","useSite","setPayload","limit","Number","Math","min","floor","active","then","body","reviews","aggregate","count","average","undefined","sx","length","data-store-reviews-empty","display","asked","level","flexDirection","gap","alignItems","textAlign","variant","component","value","precision","readOnly","size","gridTemplateColumns","xs","sm","md","map","review","m","bgcolor","rating","flex","flexWrap","fontWeight","authorName","verified","label","productName","soldInStore","productSlug","href","textDecoration","productIdProp","_maxItems","_headingLevel","siteFetch","useSiteFetch","setProductId","setReviews","setAggregate","form","setForm","authorEmail","state","setState","setEligibility","reviewToken","setReviewToken","submitted","setSubmitted","errorText","setErrorText","resolved","answer","credentials","handleSubmit","method","headers","JSON","stringify","needsEmail","pending","Boolean","error","mt","reply","pl","borderLeft","tokenProblem","severity","data-review-sign-in","maxWidth","verifiedVia","alignSelf","onChange","_event","prev","placeholder","event","target","multiline","minRows","type","disabled","trim","onClick","schema","$id","pluginId","description","category","ComponentCategory","COMMERCE","icon","path","flags","selfClosing","FEATURE_FLAG","ENABLED","attributes","name","FieldComponentType","PRODUCT_SELECT","TEXT_FIELD","SELECT","options","presets","NodeType","PRESET","data","componentId"],"mappings":";;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,cAAc,QAAQ,yBAAwB;AACvD,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC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YACN1E,OAAO;YACP+D,aACE,uEACA,oEACA;YACFlF,WAAWnG,MAAMiM,kBAAkB,CAACG,MAAM;YAC1CC,SAAS;gBACP;oBAAE/E,OAAO;oBAAgBlB,OAAO;gBAAU;gBAC1C;oBAAEkB,OAAO;oBAAelB,OAAO;gBAAQ;aACxC;QACH;QACA;YACE4F,MAAM;YACN1E,OAAO;YACP+D,aAAa;YACblF,WAAWnG,MAAMiM,kBAAkB,CAACE,UAAU;YAC9CrB,MAAM;QACR;QACA;YACEkB,MAAM;YACN1E,OAAO;YACP+D,aAAa;YACblF,WAAWnG,MAAMiM,kBAAkB,CAACG,MAAM;YAC1CC,SAAS;gBACP;oBAAE/E,OAAO;oBAAMlB,OAAO;gBAAI;gBAC1B;oBAAEkB,OAAO;oBAAMlB,OAAO;gBAAI;gBAC1B;oBAAEkB,OAAO;oBAAMlB,OAAO;gBAAI;aAC3B;QACH;KACD;AACH,EAAC;AAED,OAAO,MAAMkG,UAAgC;IAC3C;QACEnB,KAAKrK,iBAAiBC;QACtB+J,MAAM9K,MAAMuM,QAAQ,CAACC,MAAM;QAC3B1I,aAAa;QACbsH,UAAUvK;QACVwK,aAAa;QACbC,UAAUtL,MAAMuL,iBAAiB,CAACC,QAAQ;QAC1CC,MAAM;YAAEC,MAAMzL,eAAeyL,IAAI;YAAElG,IAAI;gBAAEnE,OAAO;YAAU;QAAE;QAC5DoL,MAAM;YACJtB,KAAK;YACLuB,aAAa3L;YACbqK,UAAUvK;YACV4C,OAAO,CAAC;QACV;IACF;CACD,CAAA;AAED,eAAeD,eAAc"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/product-reviews.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport { mdiStarOutline } from '@aglyn/shared-data-mdi'\nimport Alert from '@mui/material/Alert'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Chip from '@mui/material/Chip'\nimport Divider from '@mui/material/Divider'\nimport Rating from '@mui/material/Rating'\nimport TextField from '@mui/material/TextField'\nimport Typography from '@mui/material/Typography'\nimport { forwardRef, useEffect, useState } from 'react'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { generatePresetId } from '../utils/generate-preset-id'\n\n// Component ids are persisted in screen documents; never rename.\nexport const ID: Aglyn.ComponentId = 'product-reviews'\n\nexport interface ProductReviewsProps {\n /** Product id; blank resolves from the /products/{slug} page product. */\n productId?: string\n heading?: string\n /**\n * `product` (default): one product's reviews with the submit form.\n * `store`: the store's latest approved reviews across every product, with\n * the average and count, and no form — for a storefront home. In store\n * scope the block draws its own heading (`heading`, default \"What\n * customers say\") and draws NOTHING when there are no approved reviews,\n * so a page never shows an empty reviews band.\n */\n scope?: 'product' | 'store'\n /** Store scope: how many reviews to show (default 6, at most 12). */\n maxItems?: number\n /** Store scope: the heading's level, 2–4 (default 2). */\n headingLevel?: 2 | 3 | 4 | '2' | '3' | '4'\n}\n\ninterface StoreReviewView {\n id: string\n rating: number\n body: string\n authorName: string\n verified: boolean\n createdAtMs: number\n productName?: string\n productSlug?: string\n /** Sold in person only, and the store shows its reviews (AGL-4060). */\n soldInStore?: boolean\n}\n\nconst EDITOR_HINT_SX = {\n p: 3,\n border: '1px dashed',\n borderColor: 'divider',\n borderRadius: 1,\n color: 'text.secondary',\n fontSize: 13,\n fontFamily: 'system-ui, sans-serif',\n} as const\n\ninterface ReviewView {\n id: string\n rating: number\n body: string\n authorName: string\n verified: boolean\n reply?: string | null\n createdAtMs: number\n}\n\n/** What `GET /api/commerce/reviews?mode=eligibility` answers (AGL-3736). */\nexport interface ReviewFormEligibility {\n enabled?: boolean\n policy?: 'verified' | 'anyone'\n signedIn?: boolean\n verifiedVia?: 'member' | 'token' | null\n canReview?: boolean\n needsEmail?: boolean\n tokenProblem?: string\n}\n\n/** Where a shopper signs in to their account on the store. */\nexport const REVIEW_SIGN_IN_HREF = '/account'\n\n/** The review link from the review-request email, if the page carries one. */\nexport function reviewTokenFromLocation(search: string): string {\n const token = new URLSearchParams(search).get('review') ?? ''\n return /^[A-Za-z0-9_-]{32}$/.test(token) ? token : ''\n}\n\n/**\n * Which form the block draws, from the server's answer. Pure, so the three\n * states are specified in one place:\n * - `form`: the visitor may review (verified or, under `anyone`, pending);\n * - `sign-in`: the store takes verified reviews only and this visitor is\n * not one — \"Only customers who bought this can review.\" and a sign-in\n * link (no form: a typed email verifies nothing);\n * - `none`: reviews are off on this plan, or the answer has not come yet.\n */\nexport function reviewFormMode(\n eligibility: ReviewFormEligibility | null,\n): 'form' | 'sign-in' | 'none' {\n if (!eligibility || eligibility.enabled === false) return 'none'\n if (eligibility.canReview) return 'form'\n return 'sign-in'\n}\n\n/**\n * The badge a bought-it review wears. The green stays on the border: as 12px\n * words `success.main` is 3.3:1 on white and 2.9:1 on a cream section, so they\n * print in the theme's own text color (AGL-4179).\n */\nfunction VerifiedBuyerChip() {\n return (\n <Chip\n label=\"Verified buyer\"\n size=\"small\"\n variant=\"outlined\"\n color=\"success\"\n sx={{ color: 'text.primary' }}\n />\n )\n}\n\nconst TOKEN_PROBLEM_TEXT: Record<string, string> = {\n review_token_used: 'This review link has already been used.',\n review_token_expired: 'This review link has expired.',\n review_token_invalid: 'This review link is not valid for this product.',\n}\n\nasync function resolveProductIdFromSlug(hostId: string): Promise<string> {\n const match = window.location.pathname.match(/\\/products\\/([^/?#]+)/)\n if (!match) return ''\n const response = await fetch(\n `/api/commerce/product?hostId=${encodeURIComponent(hostId)}` +\n `&slug=${encodeURIComponent(decodeURIComponent(match[1]))}`,\n ).catch(() => null)\n if (!response?.ok) return ''\n const payload = await response.json().catch(() => ({}))\n return String(payload?.product?.id ?? '')\n}\n\n/**\n * Product reviews block (AGL-324): approved reviews with verified-buyer\n * badges, seller replies, an aggregate summary (emitted as JSON-LD\n * AggregateRating), and a submit form. Since AGL-3736 the form asks the server\n * who the visitor is first: a verified buyer (signed in, or arriving with the\n * review-request email's link) gets the form and publishes at once; anyone\n * else sees \"Only customers who bought this can review\" and a sign-in link,\n * unless the store accepts reviews from anyone (held for moderation).\n */\nconst ProductReviews = forwardRef<HTMLDivElement, ProductReviewsProps>(\n (props, ref) => {\n if (props.scope === 'store') return <StoreReviews ref={ref} {...props} />\n return <SingleProductReviews ref={ref} {...props} />\n },\n)\nProductReviews.displayName = 'AglynProductReviews'\n\n/**\n * The store-wide reviews band (`scope: 'store'`): the store's latest APPROVED\n * reviews, read-only stars, the reviewer's first name and initial, a verified\n * badge, and the product reviewed — linked to its page, or, for a product\n * sold in person only, marked \"Sold in store\" and linked nowhere (AGL-4060).\n * Real reviews or nothing: with none it\n * renders an empty, zero-height element — never sample reviews on a live page\n * (sample testimonials presented as customers' would be fake reviews). The\n * editor, which has no site, gets a dashed hint instead.\n */\nconst StoreReviews = forwardRef<HTMLDivElement, ProductReviewsProps>(\n (props, ref) => {\n const {\n productId: _productId,\n heading,\n scope: _scope,\n maxItems,\n headingLevel,\n ...rest\n } = props\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const [payload, setPayload] = useState<{\n reviews: StoreReviewView[]\n aggregate: { count: number; average: number }\n } | null>(null)\n const limit = maxItems && Number(maxItems) > 0 ? Math.min(12, Math.floor(Number(maxItems))) : 6\n\n useEffect(() => {\n if (!hostId) return\n let active = true\n void fetch(\n `/api/commerce/reviews?hostId=${encodeURIComponent(hostId)}` +\n `&scope=store&limit=${limit}`,\n )\n .then((response) => (response.ok ? response.json() : null))\n .then((body) => {\n if (!active || !body) return\n setPayload({\n reviews: Array.isArray(body.reviews) ? body.reviews : [],\n aggregate: body.aggregate ?? { count: 0, average: 0 },\n })\n })\n .catch(() => undefined)\n return () => {\n active = false\n }\n }, [hostId, limit])\n\n if (!hostId) {\n return (\n <Box ref={ref} {...rest} sx={[EDITOR_HINT_SX, ...nodeSx]}>\n {'★★★★★ Customer reviews appear here once shoppers review your products'}\n </Box>\n )\n }\n // Loading, failed, or none approved: nothing at all — not the node's\n // padding, not a heading over an empty band.\n if (!payload || payload.reviews.length === 0) {\n return <Box ref={ref} data-store-reviews-empty=\"\" sx={{ display: 'none' }} />\n }\n // A select may store the level as a string; read it as a number.\n const asked = Number(headingLevel)\n const level = asked === 3 || asked === 4 ? asked : 2\n const { aggregate } = payload\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[{ display: 'flex', flexDirection: 'column', gap: 3 }, ...nodeSx]}\n >\n <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1, textAlign: 'center' }}>\n <Typography variant={level === 2 ? 'h4' : level === 3 ? 'h5' : 'h6'} component={`h${level}`}>\n {heading || 'What customers say'}\n </Typography>\n {aggregate.count > 0 ? (\n <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>\n <Rating value={aggregate.average} precision={0.1} readOnly size=\"small\" />\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`${aggregate.average} out of 5 · ${aggregate.count} ${aggregate.count === 1 ? 'review' : 'reviews'}`}\n </Typography>\n </Box>\n ) : null}\n </Box>\n <Box\n sx={{\n display: 'grid',\n gap: 2,\n gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)', md: 'repeat(3, 1fr)' },\n }}\n >\n {payload.reviews.map((review) => (\n <Box\n key={review.id}\n component=\"figure\"\n sx={{\n m: 0,\n p: 2.5,\n display: 'flex',\n flexDirection: 'column',\n gap: 1,\n border: 1,\n borderColor: 'divider',\n borderRadius: 2,\n bgcolor: 'background.paper',\n }}\n >\n <Rating value={review.rating} readOnly size=\"small\" />\n <Typography component=\"blockquote\" variant=\"body1\" sx={{ m: 0, flex: 1 }}>\n {review.body}\n </Typography>\n <Box component=\"figcaption\" sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ fontWeight: 600 }}>\n {review.authorName}\n </Typography>\n {review.verified ? (\n <VerifiedBuyerChip />\n ) : null}\n </Box>\n {review.productName || review.soldInStore ? (\n <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, alignItems: 'center' }}>\n {review.productName ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n component={review.productSlug && !review.soldInStore ? 'a' : 'span'}\n {...(review.productSlug && !review.soldInStore ? { href: `/products/${review.productSlug}` } : {})}\n sx={{ textDecoration: 'none' }}\n >\n {review.productName}\n </Typography>\n ) : null}\n {review.soldInStore ? <Chip label=\"Sold in store\" size=\"small\" variant=\"outlined\" /> : null}\n </Box>\n ) : null}\n </Box>\n ))}\n </Box>\n </Box>\n )\n },\n)\nStoreReviews.displayName = 'AglynStoreReviews'\n\nconst SingleProductReviews = forwardRef<HTMLDivElement, ProductReviewsProps>(\n (props, ref) => {\n const {\n productId: productIdProp,\n heading,\n scope: _scope,\n maxItems: _maxItems,\n headingLevel: _headingLevel,\n ...rest\n } = props\n // Node styles ride the renderer-merged sx; recompose (stack.ts pattern).\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const siteFetch = Aglyn.useSiteFetch()\n const [productId, setProductId] = useState(productIdProp ?? '')\n const [reviews, setReviews] = useState<ReviewView[] | null>(null)\n const [aggregate, setAggregate] = useState({ count: 0, average: 0 })\n const [form, setForm] = useState({\n rating: 5,\n body: '',\n authorName: '',\n authorEmail: '',\n })\n const [state, setState] = useState<'idle' | 'busy' | 'done' | 'error'>(\n 'idle',\n )\n const [eligibility, setEligibility] = useState<ReviewFormEligibility | null>(null)\n const [reviewToken, setReviewToken] = useState('')\n const [submitted, setSubmitted] = useState<{ pending: boolean } | null>(null)\n const [errorText, setErrorText] = useState('')\n\n useEffect(() => {\n if (!hostId) return\n let active = true\n void (async () => {\n const resolved =\n productIdProp || (await resolveProductIdFromSlug(hostId))\n if (!active || !resolved) return\n setProductId(resolved)\n const response = await fetch(\n `/api/commerce/reviews?hostId=${encodeURIComponent(hostId)}` +\n `&productId=${encodeURIComponent(resolved)}`,\n ).catch(() => null)\n if (!active || !response?.ok) return\n const payload = await response.json().catch(() => ({}))\n setReviews(payload?.reviews ?? [])\n setAggregate(payload?.aggregate ?? { count: 0, average: 0 })\n // May this visitor review, and would it be verified? (AGL-3736)\n const token = reviewTokenFromLocation(window.location.search)\n setReviewToken(token)\n const answer = await fetch(\n `/api/commerce/reviews?hostId=${encodeURIComponent(hostId)}` +\n `&productId=${encodeURIComponent(resolved)}&mode=eligibility` +\n (token ? `&review=${encodeURIComponent(token)}` : ''),\n { credentials: 'same-origin' },\n ).catch(() => null)\n if (!active || !answer?.ok) return\n setEligibility(await answer.json().catch(() => null))\n })()\n return () => {\n active = false\n }\n }, [hostId, productIdProp])\n\n const handleSubmit = async () => {\n if (!hostId || !productId || state === 'busy') return\n setState('busy')\n try {\n const response = await siteFetch('/api/commerce/reviews', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n productId,\n rating: form.rating,\n body: form.body,\n authorName: form.authorName,\n ...(eligibility?.needsEmail ? { authorEmail: form.authorEmail } : {}),\n ...(reviewToken ? { reviewToken } : {}),\n }),\n })\n const payload = await response.json().catch(() => ({}))\n if (response.ok) {\n setSubmitted({ pending: Boolean(payload?.pending) })\n setState('done')\n } else {\n setErrorText(String(payload?.error ?? ''))\n setState('error')\n }\n } catch {\n setState('error')\n }\n }\n\n if (!hostId) {\n return (\n <Box ref={ref} {...rest} sx={[EDITOR_HINT_SX, ...nodeSx]}>\n {'★★★★★ Product reviews render here'}\n </Box>\n )\n }\n\n return (\n <Box ref={ref} {...rest} sx={[{ display: 'flex', flexDirection: 'column', gap: 1.5 }, ...nodeSx]}>\n {/* No JSON-LD here any more (AGL-686). This block used to emit a\n free-standing `AggregateRating` node, which schema.org ignores —\n a rating has to be a PROPERTY of the Product it rates. The PDP's\n server-rendered Product node now carries `aggregateRating`,\n built from the same `readProductReviews` reader this block's API\n uses, so the structured data and the visible stars cannot\n disagree. It also removes the one call site that was primed to\n become stored XSS the moment a reviewer name went into it. */}\n <Typography variant=\"h6\">\n {heading || 'Reviews'}\n {aggregate.count > 0 ? ` (${aggregate.average} ★ · ${aggregate.count})` : ''}\n </Typography>\n {(reviews ?? []).map((review) => (\n <Box key={review.id}>\n <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>\n <Rating value={review.rating} size=\"small\" readOnly />\n <Typography variant=\"body2\" sx={{ fontWeight: 600 }}>\n {review.authorName}\n </Typography>\n {review.verified ? (\n <VerifiedBuyerChip />\n ) : null}\n </Box>\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n {review.body}\n </Typography>\n {review.reply ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n sx={{ display: 'block', pl: 2, mt: 0.5, borderLeft: 2, borderColor: 'divider' }}\n >\n {`Seller: ${review.reply}`}\n </Typography>\n ) : null}\n <Divider sx={{ mt: 1.5 }} />\n </Box>\n ))}\n {reviews && reviews.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No reviews yet — be the first.'}\n </Typography>\n ) : null}\n {eligibility?.tokenProblem && TOKEN_PROBLEM_TEXT[eligibility.tokenProblem] ? (\n <Alert severity=\"info\">{TOKEN_PROBLEM_TEXT[eligibility.tokenProblem]}</Alert>\n ) : null}\n {state === 'done' ? (\n <Alert severity=\"success\">\n {submitted?.pending\n ? 'Thanks — your review is awaiting moderation.'\n : 'Thanks — your review is posted.'}\n </Alert>\n ) : reviewFormMode(eligibility) === 'sign-in' ? (\n <Typography variant=\"body2\" color=\"text.secondary\" data-review-sign-in=\"\">\n {'Only customers who bought this can review. '}\n <Box component=\"a\" href={REVIEW_SIGN_IN_HREF} sx={{ color: 'primary.main' }}>\n {'Sign in'}\n </Box>\n </Typography>\n ) : reviewFormMode(eligibility) === 'none' ? null : (\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1, maxWidth: 480 }}>\n <Typography variant=\"subtitle2\">{'Write a review'}</Typography>\n {eligibility?.verifiedVia ? (\n <Chip\n label=\"Your review will show as Verified buyer\"\n size=\"small\"\n variant=\"outlined\"\n color=\"success\"\n sx={{ alignSelf: 'flex-start' }}\n />\n ) : null}\n <Rating\n value={form.rating}\n onChange={(_event, value) =>\n setForm((prev) => ({ ...prev, rating: value ?? 5 }))\n }\n />\n <TextField\n placeholder=\"What did you think?\"\n value={form.body}\n onChange={(event) =>\n setForm((prev) => ({ ...prev, body: event.target.value }))\n }\n size=\"small\"\n multiline\n minRows={2}\n />\n <Box sx={{ display: 'flex', gap: 1 }}>\n <TextField\n placeholder=\"Name\"\n value={form.authorName}\n onChange={(event) =>\n setForm((prev) => ({ ...prev, authorName: event.target.value }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n {eligibility?.needsEmail ? (\n <TextField\n placeholder=\"Email (never shown)\"\n type=\"email\"\n value={form.authorEmail}\n onChange={(event) =>\n setForm((prev) => ({ ...prev, authorEmail: event.target.value }))\n }\n size=\"small\"\n sx={{ flex: 1.4 }}\n />\n ) : null}\n </Box>\n {state === 'error' ? (\n <Alert severity=\"error\">\n {errorText || 'Could not submit — check the fields.'}\n </Alert>\n ) : null}\n <Button\n variant=\"outlined\"\n size=\"small\"\n disabled={\n state === 'busy' ||\n !form.body.trim() ||\n Boolean(eligibility?.needsEmail && !form.authorEmail.trim())\n }\n onClick={handleSubmit}\n sx={{ alignSelf: 'flex-start' }}\n >\n {'Submit review'}\n </Button>\n </Box>\n )}\n </Box>\n )\n },\n)\nSingleProductReviews.displayName = 'AglynSingleProductReviews'\n\nexport const schema: Aglyn.ComponentSchema<ProductReviewsProps> = {\n $id: ID,\n pluginId: BUNDLE_ID,\n displayName: 'Product reviews',\n description:\n 'Approved reviews with verified-buyer badges, and a form for customers ' +\n 'who bought the product to add one.',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiStarOutline.path, sx: { color: '#2e7d32' } },\n flags: { selfClosing: Aglyn.FEATURE_FLAG.ENABLED },\n attributes: [\n {\n name: 'productId',\n label: 'Product id',\n description:\n 'Whose reviews these are. Blank reads the product from the URL, ' +\n 'which is what you want on a product template; naming one pins the ' +\n 'block to that product wherever it is placed.',\n component: Aglyn.FieldComponentType.PRODUCT_SELECT,\n },\n {\n name: 'heading',\n label: 'Heading',\n description: 'Defaults to \"Reviews\" (\"What customers say\" store-wide).',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n {\n // Default `product`, so a page that already places this block keeps it.\n name: 'scope',\n label: 'Show',\n description:\n 'One product’s reviews with a form, or the store’s latest approved ' +\n 'reviews across every product. Store-wide shows nothing until a ' +\n 'shopper’s review is approved.',\n component: Aglyn.FieldComponentType.SELECT,\n options: [\n { label: 'This product', value: 'product' },\n { label: 'Whole store', value: 'store' },\n ],\n },\n {\n name: 'maxItems',\n label: 'Max reviews',\n description: 'Store-wide: how many to show (default 6, at most 12).',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n type: 'number',\n },\n {\n name: 'headingLevel',\n label: 'Heading level',\n description: 'Store-wide: the heading’s level on the page (default H2).',\n component: Aglyn.FieldComponentType.SELECT,\n options: [\n { label: 'H2', value: '2' },\n { label: 'H3', value: '3' },\n { label: 'H4', value: '4' },\n ],\n },\n ],\n}\n\nexport const presets: Aglyn.PresetSchema[] = [\n {\n $id: generatePresetId(ID),\n type: Aglyn.NodeType.PRESET,\n displayName: 'Product reviews',\n pluginId: BUNDLE_ID,\n description: 'Verified-buyer reviews with a submit form',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiStarOutline.path, sx: { color: '#2e7d32' } },\n data: {\n $id: null,\n componentId: ID,\n pluginId: BUNDLE_ID,\n props: {},\n },\n },\n]\n\nexport default ProductReviews\n"],"names":["Aglyn","mdiStarOutline","Alert","Box","Button","Chip","Divider","Rating","TextField","Typography","forwardRef","useEffect","useState","BUNDLE_ID","generatePresetId","ID","EDITOR_HINT_SX","p","border","borderColor","borderRadius","color","fontSize","fontFamily","REVIEW_SIGN_IN_HREF","reviewTokenFromLocation","search","token","URLSearchParams","get","test","reviewFormMode","eligibility","enabled","canReview","VerifiedBuyerChip","label","size","variant","sx","TOKEN_PROBLEM_TEXT","review_token_used","review_token_expired","review_token_invalid","resolveProductIdFromSlug","hostId","payload","match","window","location","pathname","response","fetch","encodeURIComponent","decodeURIComponent","catch","ok","json","String","product","id","ProductReviews","props","ref","scope","StoreReviews","SingleProductReviews","displayName","productId","_productId","heading","_scope","maxItems","headingLevel","rest","nodeSx","Array","isArray","useSite","setPayload","limit","Number","Math","min","floor","active","then","body","reviews","aggregate","count","average","undefined","length","data-store-reviews-empty","display","asked","level","flexDirection","gap","alignItems","textAlign","component","value","precision","readOnly","gridTemplateColumns","xs","sm","md","map","review","m","bgcolor","rating","flex","flexWrap","fontWeight","authorName","verified","productName","soldInStore","productSlug","href","textDecoration","productIdProp","_maxItems","_headingLevel","siteFetch","useSiteFetch","setProductId","setReviews","setAggregate","form","setForm","authorEmail","state","setState","setEligibility","reviewToken","setReviewToken","submitted","setSubmitted","errorText","setErrorText","resolved","answer","credentials","handleSubmit","method","headers","JSON","stringify","needsEmail","pending","Boolean","error","mt","reply","pl","borderLeft","tokenProblem","severity","data-review-sign-in","maxWidth","verifiedVia","alignSelf","onChange","_event","prev","placeholder","event","target","multiline","minRows","type","disabled","trim","onClick","schema","$id","pluginId","description","category","ComponentCategory","COMMERCE","icon","path","flags","selfClosing","FEATURE_FLAG","ENABLED","attributes","name","FieldComponentType","PRODUCT_SELECT","TEXT_FIELD","SELECT","options","presets","NodeType","PRESET","data","componentId"],"mappings":";;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAA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A,uEACA;YACFhF,WAAWtG,MAAMkM,kBAAkB,CAACC,cAAc;QACpD;QACA;YACEF,MAAM;YACN7J,OAAO;YACPkJ,aAAa;YACbhF,WAAWtG,MAAMkM,kBAAkB,CAACE,UAAU;QAChD;QACA;YACE,wEAAwE;YACxEH,MAAM;YACN7J,OAAO;YACPkJ,aACE,uEACA,oEACA;YACFhF,WAAWtG,MAAMkM,kBAAkB,CAACG,MAAM;YAC1CC,SAAS;gBACP;oBAAElK,OAAO;oBAAgBmE,OAAO;gBAAU;gBAC1C;oBAAEnE,OAAO;oBAAemE,OAAO;gBAAQ;aACxC;QACH;QACA;YACE0F,MAAM;YACN7J,OAAO;YACPkJ,aAAa;YACbhF,WAAWtG,MAAMkM,kBAAkB,CAACE,UAAU;YAC9CrB,MAAM;QACR;QACA;YACEkB,MAAM;YACN7J,OAAO;YACPkJ,aAAa;YACbhF,WAAWtG,MAAMkM,kBAAkB,CAACG,MAAM;YAC1CC,SAAS;gBACP;oBAAElK,OAAO;oBAAMmE,OAAO;gBAAI;gBAC1B;oBAAEnE,OAAO;oBAAMmE,OAAO;gBAAI;gBAC1B;oBAAEnE,OAAO;oBAAMmE,OAAO;gBAAI;aAC3B;QACH;KACD;AACH,EAAC;AAED,OAAO,MAAMgG,UAAgC;IAC3C;QACEnB,KAAKtK,iBAAiBC;QACtBgK,MAAM/K,MAAMwM,QAAQ,CAACC,MAAM;QAC3BtI,aAAa;QACbkH,UAAUxK;QACVyK,aAAa;QACbC,UAAUvL,MAAMwL,iBAAiB,CAACC,QAAQ;QAC1CC,MAAM;YAAEC,MAAM1L,eAAe0L,IAAI;YAAEpJ,IAAI;gBAAElB,OAAO;YAAU;QAAE;QAC5DqL,MAAM;YACJtB,KAAK;YACLuB,aAAa5L;YACbsK,UAAUxK;YACViD,OAAO,CAAC;QACV;IACF;CACD,CAAA;AAED,eAAeD,eAAc"}
@@ -259,12 +259,14 @@ function TotalRow({ label, value, strong }) {
259
259
  'Content-Type': 'application/json',
260
260
  'Idempotency-Key': attemptKey
261
261
  },
262
- body: JSON.stringify({
262
+ body: JSON.stringify(_extends({
263
263
  hostId,
264
264
  q: link.current.quoteId,
265
265
  t: link.current.token,
266
266
  v: view.version
267
- })
267
+ }, view.taxKey ? {
268
+ tax: view.taxKey
269
+ } : {}))
268
270
  });
269
271
  const payload = await response.json().catch(()=>({}));
270
272
  // A session with a client secret is the in-page form; checked before the
@@ -699,7 +701,7 @@ function TotalRow({ label, value, strong }) {
699
701
  ]
700
702
  }) : /*#__PURE__*/ _jsx(Alert, {
701
703
  severity: "info",
702
- children: `Contact ${quote.storeName || 'the business'} to pay this ${noun}.`
704
+ children: quote.notPayableMessage || `Contact ${quote.storeName || 'the business'} to pay this ${noun}.`
703
705
  })
704
706
  })
705
707
  }) : /*#__PURE__*/ _jsx(Paper, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/quote-page-body.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport Alert from '@mui/material/Alert'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Chip from '@mui/material/Chip'\nimport CircularProgress from '@mui/material/CircularProgress'\nimport Divider from '@mui/material/Divider'\nimport Paper from '@mui/material/Paper'\nimport Stack from '@mui/material/Stack'\nimport Typography from '@mui/material/Typography'\nimport type { StripeCheckoutContact } from '@stripe/stripe-js'\nimport { forwardRef, lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'\nimport {\n formatOrderMoney,\n readStorefrontCheckoutWallets,\n type QuotePageAddress,\n type QuotePageView,\n type StorefrontCheckoutWallets,\n} from '../model'\nimport type { QuotePageProps } from './quote-page'\nimport { QuoteProofPanel } from './quote-proof-panel'\nimport { StorefrontPaymentElementFallback } from './storefront-payment-element-fallback'\n\n/** The Payment Element, lazily: Stripe.js loads only when a customer presses Pay. */\nconst StorefrontPaymentElement = lazy(() =>\n import('./storefront-payment-element').then((module) => ({\n default: module.StorefrontPaymentElement,\n })),\n)\n\ntype LoadState =\n | { kind: 'loading' }\n | { kind: 'missing'; message: string }\n | { kind: 'replaced'; storeName: string; noun: string }\n | { kind: 'ready'; view: QuotePageView }\n\n/** `quote` or `invoice`, as the page says it (AGL-4099). */\nconst nounOf = (kind: unknown) => (kind === 'invoice' ? 'invoice' : 'quote')\n\n/** What is added when the customer pays: `shipping`, `tax`, `shipping and tax`, or nothing. */\nfunction addedAtPayment(view: Pick<QuotePageView, 'shippingAtPayment' | 'taxAtPayment'>): string {\n if (view.shippingAtPayment && view.taxAtPayment) return 'shipping and tax'\n if (view.shippingAtPayment) return 'shipping'\n return view.taxAtPayment ? 'tax' : ''\n}\n\n/** After a payment returns here, how often and how long the page asks whether it landed. */\nconst CONFIRM_POLL_MS = 2_000\nconst CONFIRM_POLLS = 15\n\nfunction dateLabel(atMs: number | null): string {\n if (!atMs) return ''\n return new Date(atMs).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })\n}\n\nfunction addressLines(address: QuotePageAddress): string[] {\n const cityLine = [address.city, [address.state, address.postalCode].filter(Boolean).join(' ')]\n .filter(Boolean)\n .join(', ')\n return [address.name, address.line1, address.line2, cityLine, address.country].filter(\n (line): line is string => Boolean(line),\n )\n}\n\nfunction stripeContact(address: QuotePageAddress | null): StripeCheckoutContact | undefined {\n if (!address?.country) return undefined\n return {\n name: address.name,\n address: {\n country: address.country,\n line1: address.line1,\n line2: address.line2,\n city: address.city,\n state: address.state,\n postal_code: address.postalCode,\n },\n }\n}\n\nfunction AddressBlock({ label, lines }: { label: string; lines: string[] }) {\n return (\n <Stack spacing={0.25} sx={{ minWidth: 0, flex: 1 }}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {label}\n </Typography>\n {lines.map((line, index) => (\n <Typography key={index} variant=\"body2\">\n {line}\n </Typography>\n ))}\n </Stack>\n )\n}\n\nfunction TotalRow({ label, value, strong }: { label: string; value: string; strong?: boolean }) {\n return (\n <Stack direction=\"row\" spacing={2} sx={{ justifyContent: 'space-between' }}>\n <Typography variant={strong ? 'subtitle1' : 'body2'} color={strong ? 'text.primary' : 'text.secondary'}>\n {label}\n </Typography>\n <Typography variant={strong ? 'subtitle1' : 'body2'} color={strong ? 'text.primary' : 'text.secondary'}>\n {value}\n </Typography>\n </Stack>\n )\n}\n\n/**\n * The customer's quote page (AGL-4094), loaded when the page draws it (see\n * `quote-page.tsx`): what a customer sees when they open\n * the pay link a business sent them. The commerce page resolver serves it at\n * `/pay-quote` inside the site's own header and footer; a business can also\n * place it on a page of their own design at that address.\n *\n * The quote is read AFTER hydration from `?q=&t=`, so the page itself is the\n * same for every customer and may be cached, and the quote never is. Pay asks\n * the server for a fresh payment for the quote as the page shows it: Stripe's\n * own page, or the payment form here when in-page payments are on. Nothing\n * here decides a quote is paid; after paying, the page reads that from the\n * server like any other visit.\n */\nconst QuotePageBody = forwardRef<HTMLDivElement, QuotePageProps>((props, ref) => {\n const { heading, ...rest } = props\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const siteFetch = Aglyn.useSiteFetch()\n const [state, setState] = useState<LoadState>({ kind: 'loading' })\n const [paying, setPaying] = useState(false)\n const [payError, setPayError] = useState('')\n const [nativeCheckout, setNativeCheckout] = useState<{\n clientSecret: string\n publishableKey: string\n wallets?: StorefrontCheckoutWallets\n } | null>(null)\n /** What a return from paying turned out to be: still being confirmed, or not paid. */\n const [returned, setReturned] = useState<'confirming' | 'unconfirmed' | 'failed' | null>(null)\n const link = useRef({ quoteId: '', token: '', sessionId: '' })\n\n const load = useCallback(async (): Promise<LoadState> => {\n const { quoteId, token } = link.current\n try {\n const response = await siteFetch(\n `/api/commerce/quote-view?hostId=${encodeURIComponent(hostId ?? '')}` +\n `&q=${encodeURIComponent(quoteId)}&t=${encodeURIComponent(token)}`,\n )\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return { kind: 'missing', message: String(payload?.error ?? 'We could not find that quote or invoice.') }\n }\n if (payload?.state === 'replaced') {\n return { kind: 'replaced', storeName: String(payload.storeName ?? ''), noun: nounOf(payload.kind) }\n }\n return { kind: 'ready', view: payload as QuotePageView }\n } catch {\n return { kind: 'missing', message: 'This page could not be loaded. Check your connection and try again.' }\n }\n }, [hostId, siteFetch])\n\n useEffect(() => {\n if (!hostId) return\n const params = new URLSearchParams(window.location.search)\n link.current = {\n quoteId: params.get('q') ?? '',\n token: params.get('t') ?? '',\n sessionId: params.get('session_id') ?? '',\n }\n if (!link.current.quoteId || !link.current.token) {\n setState({ kind: 'missing', message: 'Open this page from the link you were sent with your quote or invoice.' })\n return\n }\n let live = true\n void (async () => {\n const first = await load()\n if (!live) return\n setState(first)\n const sessionId = link.current.sessionId\n if (first.kind !== 'ready' || first.view.status !== 'unpaid' || !sessionId) return\n // Back from paying: the payment may have landed before the record of it.\n const status = await siteFetch(\n `/api/commerce/checkout-status?hostId=${encodeURIComponent(hostId)}` +\n `&sessionId=${encodeURIComponent(sessionId)}`,\n )\n .then((response) => (response.ok ? response.json() : null))\n .catch(() => null)\n if (!live) return\n if (status?.status === 'open') {\n setReturned('failed')\n return\n }\n if (status?.status !== 'complete') return\n setReturned('confirming')\n for (let poll = 0; poll < CONFIRM_POLLS && live; poll++) {\n await new Promise((resolve) => setTimeout(resolve, CONFIRM_POLL_MS))\n if (!live) return\n const next = await load()\n if (!live) return\n if (next.kind === 'ready' && next.view.status !== 'unpaid') {\n setState(next)\n setReturned(null)\n return\n }\n }\n if (live) setReturned('unconfirmed')\n })()\n return () => {\n live = false\n }\n }, [hostId, load, siteFetch])\n\n const view = state.kind === 'ready' ? state.view : null\n\n const pay = useCallback(async () => {\n if (!view || paying) return\n setPaying(true)\n setPayError('')\n setReturned(null)\n // One key per press: a press is one attempt, and a retry after a failure is a new one.\n const attemptKey =\n globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`\n try {\n const response = await siteFetch('/api/commerce/quote-pay', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'Idempotency-Key': attemptKey },\n body: JSON.stringify({\n hostId,\n q: link.current.quoteId,\n t: link.current.token,\n v: view.version,\n }),\n })\n const payload = await response.json().catch(() => ({}))\n // A session with a client secret is the in-page form; checked before the\n // redirect, so a form is never navigated away from.\n if (response.ok && payload?.clientSecret && payload?.publishableKey) {\n setNativeCheckout({\n clientSecret: String(payload.clientSecret),\n publishableKey: String(payload.publishableKey),\n wallets: readStorefrontCheckoutWallets(payload.wallets),\n })\n setPaying(false)\n return\n }\n if (response.ok && payload?.url) {\n window.location.assign(String(payload.url))\n return\n }\n if (payload?.replaced) {\n setState({ kind: 'replaced', storeName: view.storeName, noun: nounOf(view.kind) })\n return\n }\n if (payload?.reason === 'paid' || payload?.reason === 'updated') {\n const next = await load()\n setState(next)\n }\n setPayError(String(payload?.error ?? 'Your payment could not be set up. Try again.'))\n setPaying(false)\n } catch {\n setPayError('Your payment could not be set up. Check your connection and try again.')\n setPaying(false)\n }\n }, [view, paying, siteFetch, hostId, load])\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[{ p: 3, border: '1px dashed', borderColor: 'divider', borderRadius: 1 }, ...nodeSx]}\n >\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Quote — a customer’s quote and its Pay button render here'}\n </Typography>\n </Box>\n )\n }\n\n if (state.kind === 'loading') {\n return (\n <Box ref={ref} {...rest} sx={[{ py: 6, textAlign: 'center' }, ...nodeSx]}>\n <CircularProgress size={28} aria-label=\"Loading\" />\n </Box>\n )\n }\n\n if (state.kind === 'missing') {\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={2}>\n <Typography variant=\"h4\" component=\"h1\">\n {heading || 'Your quote or invoice'}\n </Typography>\n <Alert severity=\"info\">{state.message}</Alert>\n </Stack>\n </Box>\n )\n }\n\n if (state.kind === 'replaced') {\n const business = state.storeName || 'The business'\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={2}>\n {state.storeName ? (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {state.storeName}\n </Typography>\n ) : null}\n <Typography variant=\"h4\" component=\"h1\">\n {`This ${state.noun} was updated`}\n </Typography>\n <Typography variant=\"body1\" color=\"text.secondary\">\n {`${business} updated this ${state.noun} and sent you a newer link. Open their most recent message to see it.`}\n </Typography>\n </Stack>\n </Box>\n )\n }\n\n const quote = state.view\n const money = (cents: number) => formatOrderMoney(cents, quote.currency)\n // The same signed link as the page's data; the server makes the PDF from the same view.\n const pdfHref =\n `/api/commerce/quote-pdf?hostId=${encodeURIComponent(hostId)}` +\n `&q=${encodeURIComponent(link.current.quoteId)}&t=${encodeURIComponent(link.current.token)}`\n const unpaid = quote.status === 'unpaid'\n const noun = nounOf(quote.kind)\n const later = addedAtPayment(quote)\n const addresses = [\n quote.customerName || quote.company\n ? { label: 'Prepared for', lines: [quote.customerName, quote.company].filter((line): line is string => Boolean(line)) }\n : null,\n quote.billTo ? { label: 'Bill to', lines: addressLines(quote.billTo) } : null,\n quote.shipTo ? { label: 'Ship to', lines: addressLines(quote.shipTo) } : null,\n ].filter((block): block is { label: string; lines: string[] } => Boolean(block && block.lines.length))\n const totalRows = (\n [\n ['Subtotal', money(quote.totals.itemsCents), true],\n [\n quote.discountLabel ? `Discount (${quote.discountLabel})` : 'Discount',\n `−${money(quote.totals.discountCents)}`,\n quote.totals.discountCents > 0,\n ],\n ['Shipping', money(quote.totals.shippingCents), quote.totals.shippingCents > 0],\n [quote.taxLabel, money(quote.totals.taxCents), quote.totals.taxCents > 0],\n // The rate an invoiced draft's customer picks when they pay (AGL-4099).\n ['Shipping is chosen when you pay', '', quote.shippingAtPayment === true],\n // `Tax is added at payment`, with no figure: Stripe works it out from the address.\n [quote.taxLabel, '', quote.taxAtPayment],\n ] as Array<[string, string, boolean]>\n ).filter(([, , shown]) => shown)\n\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={3}>\n <Stack spacing={1}>\n {quote.storeName ? (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {quote.storeName}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1.5} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}>\n <Typography variant=\"h4\" component=\"h1\">\n {/* The element's own heading is a quote's; an invoice always says its number. */}\n {(quote.kind !== 'invoice' && heading) || quote.number}\n </Typography>\n <Chip\n label={quote.statusLabel}\n color={quote.status === 'paid' ? 'success' : unpaid ? 'primary' : 'default'}\n size=\"small\"\n />\n </Stack>\n {quote.dateMs ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Dated ${dateLabel(quote.dateMs)}`}\n </Typography>\n ) : null}\n <Box>\n <Button variant=\"outlined\" size=\"small\" href={pdfHref} download>\n {'Download PDF'}\n </Button>\n </Box>\n </Stack>\n\n {addresses.length ? (\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={{ xs: 2, sm: 3 }}>\n {addresses.map((block) => (\n <AddressBlock key={block.label} label={block.label} lines={block.lines} />\n ))}\n </Stack>\n ) : null}\n\n <Stack spacing={1.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Items'}\n </Typography>\n {quote.lines.map((line, index) => (\n <Stack key={index} direction=\"row\" spacing={2} sx={{ justifyContent: 'space-between' }}>\n <Stack spacing={0.25} sx={{ minWidth: 0 }}>\n <Typography variant=\"body2\">\n {line.name}\n {line.variantLabel ? ` (${line.variantLabel})` : ''}\n </Typography>\n {line.description ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ whiteSpace: 'pre-line' }}>\n {line.description}\n </Typography>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {[\n line.included ? `${line.quantity} included` : `${line.quantity} × ${money(line.unitAmountCents)}`,\n line.sku ? `SKU ${line.sku}` : '',\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n </Stack>\n <Typography variant=\"body2\" sx={{ flexShrink: 0 }}>\n {line.included ? 'Included' : money(line.amountCents)}\n </Typography>\n </Stack>\n ))}\n <Divider />\n {totalRows.map(([label, value]) => (\n <TotalRow key={`${label}-${value}`} label={label} value={value} />\n ))}\n <TotalRow label=\"Total\" value={money(quote.totals.totalCents)} strong />\n </Stack>\n\n {quote.notes ? (\n <Stack spacing={0.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Notes'}\n </Typography>\n <Typography variant=\"body2\" sx={{ whiteSpace: 'pre-line' }}>\n {quote.notes}\n </Typography>\n </Stack>\n ) : null}\n {quote.terms ? (\n <Stack spacing={0.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Terms'}\n </Typography>\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ whiteSpace: 'pre-line' }}>\n {quote.terms}\n </Typography>\n </Stack>\n ) : null}\n\n <QuoteProofPanel\n view={quote}\n hostId={hostId}\n quoteId={link.current.quoteId}\n token={link.current.token}\n siteFetch={siteFetch}\n onView={(next) => setState({ kind: 'ready', view: next })}\n onReload={() => void load().then(setState)}\n onReplaced={() => setState({ kind: 'replaced', storeName: quote.storeName, noun })}\n />\n\n {unpaid ? (\n <Paper variant=\"outlined\" sx={{ p: { xs: 2, sm: 3 } }}>\n <Stack spacing={2}>\n {returned === 'confirming' ? (\n <Alert severity=\"info\" icon={<CircularProgress size={20} />}>\n {'Thank you. We’re confirming your payment.'}\n </Alert>\n ) : returned === 'unconfirmed' ? (\n <Alert severity=\"info\">\n {'Your payment is still being confirmed. Your receipt will arrive by email.'}\n </Alert>\n ) : quote.approvalRequired ? (\n <Alert severity=\"info\">\n {`${quote.storeName || 'The business'} asks you to approve the proof before you pay.`}\n </Alert>\n ) : quote.payable ? (\n <>\n {returned === 'failed' ? (\n <Alert severity=\"warning\">{'Your payment did not go through. Nothing was charged.'}</Alert>\n ) : null}\n {nativeCheckout ? (\n <Suspense fallback={<StorefrontPaymentElementFallback />}>\n <StorefrontPaymentElement\n clientSecret={nativeCheckout.clientSecret}\n publishableKey={nativeCheckout.publishableKey}\n wallets={nativeCheckout.wallets}\n payLabel={later ? 'Pay now' : `Pay ${money(quote.totals.totalCents)}`}\n defaultShippingAddress={stripeContact(quote.shipTo)}\n // An expired or unloadable session is replaced by a new press.\n onRestart={() => {\n setNativeCheckout(null)\n void pay()\n }}\n onCancel={() => setNativeCheckout(null)}\n />\n </Suspense>\n ) : (\n <Button\n variant=\"contained\"\n size=\"large\"\n onClick={() => void pay()}\n disabled={paying}\n sx={{ alignSelf: { xs: 'stretch', sm: 'flex-start' } }}\n >\n {paying\n ? 'Opening…'\n : later\n ? `Pay ${money(quote.totals.totalCents)} plus ${later}`\n : `Pay ${money(quote.totals.totalCents)}`}\n </Button>\n )}\n {payError ? <Alert severity=\"error\">{payError}</Alert> : null}\n </>\n ) : (\n <Alert severity=\"info\">\n {`Contact ${quote.storeName || 'the business'} to pay this ${noun}.`}\n </Alert>\n )}\n </Stack>\n </Paper>\n ) : (\n <Paper variant=\"outlined\" sx={{ p: { xs: 2, sm: 3 } }}>\n <Stack spacing={1.5} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body1\">\n {quote.status === 'paid'\n ? quote.paidAtMs\n ? `Paid ${dateLabel(quote.paidAtMs)}. Thank you.`\n : 'Paid. Thank you.'\n : `This ${noun} is ${quote.statusLabel.toLowerCase()}.`}\n </Typography>\n {quote.receiptUrl ? (\n <Button variant=\"outlined\" href={quote.receiptUrl}>\n {'View your order'}\n </Button>\n ) : null}\n </Stack>\n </Paper>\n )}\n\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Questions about this ${noun}? Contact ${quote.storeName || 'the business'}.`}\n </Typography>\n </Stack>\n </Box>\n )\n})\nQuotePageBody.displayName = 'QuotePageBody'\n\nexport default QuotePageBody\n\n"],"names":["Aglyn","Alert","Box","Button","Chip","CircularProgress","Divider","Paper","Stack","Typography","forwardRef","lazy","Suspense","useCallback","useEffect","useRef","useState","formatOrderMoney","readStorefrontCheckoutWallets","QuoteProofPanel","StorefrontPaymentElementFallback","StorefrontPaymentElement","then","module","default","nounOf","kind","addedAtPayment","view","shippingAtPayment","taxAtPayment","CONFIRM_POLL_MS","CONFIRM_POLLS","dateLabel","atMs","Date","toLocaleDateString","undefined","month","day","year","addressLines","address","cityLine","city","state","postalCode","filter","Boolean","join","name","line1","line2","country","line","stripeContact","postal_code","AddressBlock","label","lines","spacing","sx","minWidth","flex","variant","color","map","index","TotalRow","value","strong","direction","justifyContent","QuotePageBody","props","ref","heading","rest","nodeSx","Array","isArray","hostId","useSite","siteFetch","useSiteFetch","setState","paying","setPaying","payError","setPayError","nativeCheckout","setNativeCheckout","returned","setReturned","link","quoteId","token","sessionId","load","current","response","encodeURIComponent","payload","json","catch","ok","message","String","error","storeName","noun","params","URLSearchParams","window","location","search","get","live","first","status","poll","Promise","resolve","setTimeout","next","pay","globalThis","attemptKey","crypto","randomUUID","now","Math","random","toString","slice","method","headers","body","JSON","stringify","q","t","v","version","clientSecret","publishableKey","wallets","url","assign","replaced","reason","p","border","borderColor","borderRadius","py","textAlign","size","aria-label","component","severity","business","quote","money","cents","currency","pdfHref","unpaid","later","addresses","customerName","company","billTo","shipTo","block","length","totalRows","totals","itemsCents","discountLabel","discountCents","shippingCents","taxLabel","taxCents","shown","alignItems","flexWrap","rowGap","number","statusLabel","dateMs","href","download","xs","sm","variantLabel","description","whiteSpace","included","quantity","unitAmountCents","sku","flexShrink","amountCents","totalCents","notes","terms","onView","onReload","onReplaced","icon","approvalRequired","payable","fallback","payLabel","defaultShippingAddress","onRestart","onCancel","onClick","disabled","alignSelf","paidAtMs","toLowerCase","receiptUrl","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,QAAQ,EAAEE,MAAMrD,SAAS,IAAI,eAAe,aAAa,EAAEC,KAAK,CAAC,CAAC;;;mCAM5E,KAACvG;oBAAMyD,SAAQ;oBAAWH,IAAI;wBAAE0F,GAAG;4BAAE0C,IAAI;4BAAGC,IAAI;wBAAE;oBAAE;8BAClD,cAAA,MAAC1L;wBAAMoD,SAAS;wBAAKC,IAAI;4BAAE4H,YAAY;wBAAa;;0CAClD,KAAChL;gCAAWuD,SAAQ;0CACjBkG,MAAM3C,MAAM,KAAK,SACd2C,MAAM2D,QAAQ,GACZ,CAAC,KAAK,EAAE5L,UAAUiI,MAAM2D,QAAQ,EAAE,YAAY,CAAC,GAC/C,qBACF,CAAC,KAAK,EAAE/G,KAAK,IAAI,EAAEoD,MAAM2B,WAAW,CAACiC,WAAW,GAAG,CAAC,CAAC;;4BAE1D5D,MAAM6D,UAAU,iBACf,KAAC5N;gCAAO6D,SAAQ;gCAAW+H,MAAM7B,MAAM6D,UAAU;0CAC9C;iCAED;;;;8BAKV,KAACtN;oBAAWuD,SAAQ;oBAAQC,OAAM;8BAC/B,CAAC,qBAAqB,EAAE6C,KAAK,UAAU,EAAEoD,MAAMrD,SAAS,IAAI,eAAe,CAAC,CAAC;;;;;AAKxF;AACApC,cAAcuJ,WAAW,GAAG;AAE5B,eAAevJ,cAAa"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/quote-page-body.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport Alert from '@mui/material/Alert'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Chip from '@mui/material/Chip'\nimport CircularProgress from '@mui/material/CircularProgress'\nimport Divider from '@mui/material/Divider'\nimport Paper from '@mui/material/Paper'\nimport Stack from '@mui/material/Stack'\nimport Typography from '@mui/material/Typography'\nimport type { StripeCheckoutContact } from '@stripe/stripe-js'\nimport { forwardRef, lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'\nimport {\n formatOrderMoney,\n readStorefrontCheckoutWallets,\n type QuotePageAddress,\n type QuotePageView,\n type StorefrontCheckoutWallets,\n} from '../model'\nimport type { QuotePageProps } from './quote-page'\nimport { QuoteProofPanel } from './quote-proof-panel'\nimport { StorefrontPaymentElementFallback } from './storefront-payment-element-fallback'\n\n/** The Payment Element, lazily: Stripe.js loads only when a customer presses Pay. */\nconst StorefrontPaymentElement = lazy(() =>\n import('./storefront-payment-element').then((module) => ({\n default: module.StorefrontPaymentElement,\n })),\n)\n\ntype LoadState =\n | { kind: 'loading' }\n | { kind: 'missing'; message: string }\n | { kind: 'replaced'; storeName: string; noun: string }\n | { kind: 'ready'; view: QuotePageView }\n\n/** `quote` or `invoice`, as the page says it (AGL-4099). */\nconst nounOf = (kind: unknown) => (kind === 'invoice' ? 'invoice' : 'quote')\n\n/** What is added when the customer pays: `shipping`, `tax`, `shipping and tax`, or nothing. */\nfunction addedAtPayment(view: Pick<QuotePageView, 'shippingAtPayment' | 'taxAtPayment'>): string {\n if (view.shippingAtPayment && view.taxAtPayment) return 'shipping and tax'\n if (view.shippingAtPayment) return 'shipping'\n return view.taxAtPayment ? 'tax' : ''\n}\n\n/** After a payment returns here, how often and how long the page asks whether it landed. */\nconst CONFIRM_POLL_MS = 2_000\nconst CONFIRM_POLLS = 15\n\nfunction dateLabel(atMs: number | null): string {\n if (!atMs) return ''\n return new Date(atMs).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })\n}\n\nfunction addressLines(address: QuotePageAddress): string[] {\n const cityLine = [address.city, [address.state, address.postalCode].filter(Boolean).join(' ')]\n .filter(Boolean)\n .join(', ')\n return [address.name, address.line1, address.line2, cityLine, address.country].filter(\n (line): line is string => Boolean(line),\n )\n}\n\nfunction stripeContact(address: QuotePageAddress | null): StripeCheckoutContact | undefined {\n if (!address?.country) return undefined\n return {\n name: address.name,\n address: {\n country: address.country,\n line1: address.line1,\n line2: address.line2,\n city: address.city,\n state: address.state,\n postal_code: address.postalCode,\n },\n }\n}\n\nfunction AddressBlock({ label, lines }: { label: string; lines: string[] }) {\n return (\n <Stack spacing={0.25} sx={{ minWidth: 0, flex: 1 }}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {label}\n </Typography>\n {lines.map((line, index) => (\n <Typography key={index} variant=\"body2\">\n {line}\n </Typography>\n ))}\n </Stack>\n )\n}\n\nfunction TotalRow({ label, value, strong }: { label: string; value: string; strong?: boolean }) {\n return (\n <Stack direction=\"row\" spacing={2} sx={{ justifyContent: 'space-between' }}>\n <Typography variant={strong ? 'subtitle1' : 'body2'} color={strong ? 'text.primary' : 'text.secondary'}>\n {label}\n </Typography>\n <Typography variant={strong ? 'subtitle1' : 'body2'} color={strong ? 'text.primary' : 'text.secondary'}>\n {value}\n </Typography>\n </Stack>\n )\n}\n\n/**\n * The customer's quote page (AGL-4094), loaded when the page draws it (see\n * `quote-page.tsx`): what a customer sees when they open\n * the pay link a business sent them. The commerce page resolver serves it at\n * `/pay-quote` inside the site's own header and footer; a business can also\n * place it on a page of their own design at that address.\n *\n * The quote is read AFTER hydration from `?q=&t=`, so the page itself is the\n * same for every customer and may be cached, and the quote never is. Pay asks\n * the server for a fresh payment for the quote as the page shows it: Stripe's\n * own page, or the payment form here when in-page payments are on. Nothing\n * here decides a quote is paid; after paying, the page reads that from the\n * server like any other visit.\n */\nconst QuotePageBody = forwardRef<HTMLDivElement, QuotePageProps>((props, ref) => {\n const { heading, ...rest } = props\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const siteFetch = Aglyn.useSiteFetch()\n const [state, setState] = useState<LoadState>({ kind: 'loading' })\n const [paying, setPaying] = useState(false)\n const [payError, setPayError] = useState('')\n const [nativeCheckout, setNativeCheckout] = useState<{\n clientSecret: string\n publishableKey: string\n wallets?: StorefrontCheckoutWallets\n } | null>(null)\n /** What a return from paying turned out to be: still being confirmed, or not paid. */\n const [returned, setReturned] = useState<'confirming' | 'unconfirmed' | 'failed' | null>(null)\n const link = useRef({ quoteId: '', token: '', sessionId: '' })\n\n const load = useCallback(async (): Promise<LoadState> => {\n const { quoteId, token } = link.current\n try {\n const response = await siteFetch(\n `/api/commerce/quote-view?hostId=${encodeURIComponent(hostId ?? '')}` +\n `&q=${encodeURIComponent(quoteId)}&t=${encodeURIComponent(token)}`,\n )\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return { kind: 'missing', message: String(payload?.error ?? 'We could not find that quote or invoice.') }\n }\n if (payload?.state === 'replaced') {\n return { kind: 'replaced', storeName: String(payload.storeName ?? ''), noun: nounOf(payload.kind) }\n }\n return { kind: 'ready', view: payload as QuotePageView }\n } catch {\n return { kind: 'missing', message: 'This page could not be loaded. Check your connection and try again.' }\n }\n }, [hostId, siteFetch])\n\n useEffect(() => {\n if (!hostId) return\n const params = new URLSearchParams(window.location.search)\n link.current = {\n quoteId: params.get('q') ?? '',\n token: params.get('t') ?? '',\n sessionId: params.get('session_id') ?? '',\n }\n if (!link.current.quoteId || !link.current.token) {\n setState({ kind: 'missing', message: 'Open this page from the link you were sent with your quote or invoice.' })\n return\n }\n let live = true\n void (async () => {\n const first = await load()\n if (!live) return\n setState(first)\n const sessionId = link.current.sessionId\n if (first.kind !== 'ready' || first.view.status !== 'unpaid' || !sessionId) return\n // Back from paying: the payment may have landed before the record of it.\n const status = await siteFetch(\n `/api/commerce/checkout-status?hostId=${encodeURIComponent(hostId)}` +\n `&sessionId=${encodeURIComponent(sessionId)}`,\n )\n .then((response) => (response.ok ? response.json() : null))\n .catch(() => null)\n if (!live) return\n if (status?.status === 'open') {\n setReturned('failed')\n return\n }\n if (status?.status !== 'complete') return\n setReturned('confirming')\n for (let poll = 0; poll < CONFIRM_POLLS && live; poll++) {\n await new Promise((resolve) => setTimeout(resolve, CONFIRM_POLL_MS))\n if (!live) return\n const next = await load()\n if (!live) return\n if (next.kind === 'ready' && next.view.status !== 'unpaid') {\n setState(next)\n setReturned(null)\n return\n }\n }\n if (live) setReturned('unconfirmed')\n })()\n return () => {\n live = false\n }\n }, [hostId, load, siteFetch])\n\n const view = state.kind === 'ready' ? state.view : null\n\n const pay = useCallback(async () => {\n if (!view || paying) return\n setPaying(true)\n setPayError('')\n setReturned(null)\n // One key per press: a press is one attempt, and a retry after a failure is a new one.\n const attemptKey =\n globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`\n try {\n const response = await siteFetch('/api/commerce/quote-pay', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'Idempotency-Key': attemptKey },\n body: JSON.stringify({\n hostId,\n q: link.current.quoteId,\n t: link.current.token,\n v: view.version,\n // The tax the page priced it under; a quote whose tax moved since is shown again.\n ...(view.taxKey ? { tax: view.taxKey } : {}),\n }),\n })\n const payload = await response.json().catch(() => ({}))\n // A session with a client secret is the in-page form; checked before the\n // redirect, so a form is never navigated away from.\n if (response.ok && payload?.clientSecret && payload?.publishableKey) {\n setNativeCheckout({\n clientSecret: String(payload.clientSecret),\n publishableKey: String(payload.publishableKey),\n wallets: readStorefrontCheckoutWallets(payload.wallets),\n })\n setPaying(false)\n return\n }\n if (response.ok && payload?.url) {\n window.location.assign(String(payload.url))\n return\n }\n if (payload?.replaced) {\n setState({ kind: 'replaced', storeName: view.storeName, noun: nounOf(view.kind) })\n return\n }\n if (payload?.reason === 'paid' || payload?.reason === 'updated') {\n const next = await load()\n setState(next)\n }\n setPayError(String(payload?.error ?? 'Your payment could not be set up. Try again.'))\n setPaying(false)\n } catch {\n setPayError('Your payment could not be set up. Check your connection and try again.')\n setPaying(false)\n }\n }, [view, paying, siteFetch, hostId, load])\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[{ p: 3, border: '1px dashed', borderColor: 'divider', borderRadius: 1 }, ...nodeSx]}\n >\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Quote — a customer’s quote and its Pay button render here'}\n </Typography>\n </Box>\n )\n }\n\n if (state.kind === 'loading') {\n return (\n <Box ref={ref} {...rest} sx={[{ py: 6, textAlign: 'center' }, ...nodeSx]}>\n <CircularProgress size={28} aria-label=\"Loading\" />\n </Box>\n )\n }\n\n if (state.kind === 'missing') {\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={2}>\n <Typography variant=\"h4\" component=\"h1\">\n {heading || 'Your quote or invoice'}\n </Typography>\n <Alert severity=\"info\">{state.message}</Alert>\n </Stack>\n </Box>\n )\n }\n\n if (state.kind === 'replaced') {\n const business = state.storeName || 'The business'\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={2}>\n {state.storeName ? (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {state.storeName}\n </Typography>\n ) : null}\n <Typography variant=\"h4\" component=\"h1\">\n {`This ${state.noun} was updated`}\n </Typography>\n <Typography variant=\"body1\" color=\"text.secondary\">\n {`${business} updated this ${state.noun} and sent you a newer link. Open their most recent message to see it.`}\n </Typography>\n </Stack>\n </Box>\n )\n }\n\n const quote = state.view\n const money = (cents: number) => formatOrderMoney(cents, quote.currency)\n // The same signed link as the page's data; the server makes the PDF from the same view.\n const pdfHref =\n `/api/commerce/quote-pdf?hostId=${encodeURIComponent(hostId)}` +\n `&q=${encodeURIComponent(link.current.quoteId)}&t=${encodeURIComponent(link.current.token)}`\n const unpaid = quote.status === 'unpaid'\n const noun = nounOf(quote.kind)\n const later = addedAtPayment(quote)\n const addresses = [\n quote.customerName || quote.company\n ? { label: 'Prepared for', lines: [quote.customerName, quote.company].filter((line): line is string => Boolean(line)) }\n : null,\n quote.billTo ? { label: 'Bill to', lines: addressLines(quote.billTo) } : null,\n quote.shipTo ? { label: 'Ship to', lines: addressLines(quote.shipTo) } : null,\n ].filter((block): block is { label: string; lines: string[] } => Boolean(block && block.lines.length))\n const totalRows = (\n [\n ['Subtotal', money(quote.totals.itemsCents), true],\n [\n quote.discountLabel ? `Discount (${quote.discountLabel})` : 'Discount',\n `−${money(quote.totals.discountCents)}`,\n quote.totals.discountCents > 0,\n ],\n ['Shipping', money(quote.totals.shippingCents), quote.totals.shippingCents > 0],\n [quote.taxLabel, money(quote.totals.taxCents), quote.totals.taxCents > 0],\n // The rate an invoiced draft's customer picks when they pay (AGL-4099).\n ['Shipping is chosen when you pay', '', quote.shippingAtPayment === true],\n // `Tax is added at payment`, with no figure: Stripe works it out from the address.\n [quote.taxLabel, '', quote.taxAtPayment],\n ] as Array<[string, string, boolean]>\n ).filter(([, , shown]) => shown)\n\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={3}>\n <Stack spacing={1}>\n {quote.storeName ? (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {quote.storeName}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1.5} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}>\n <Typography variant=\"h4\" component=\"h1\">\n {/* The element's own heading is a quote's; an invoice always says its number. */}\n {(quote.kind !== 'invoice' && heading) || quote.number}\n </Typography>\n <Chip\n label={quote.statusLabel}\n color={quote.status === 'paid' ? 'success' : unpaid ? 'primary' : 'default'}\n size=\"small\"\n />\n </Stack>\n {quote.dateMs ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Dated ${dateLabel(quote.dateMs)}`}\n </Typography>\n ) : null}\n <Box>\n <Button variant=\"outlined\" size=\"small\" href={pdfHref} download>\n {'Download PDF'}\n </Button>\n </Box>\n </Stack>\n\n {addresses.length ? (\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={{ xs: 2, sm: 3 }}>\n {addresses.map((block) => (\n <AddressBlock key={block.label} label={block.label} lines={block.lines} />\n ))}\n </Stack>\n ) : null}\n\n <Stack spacing={1.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Items'}\n </Typography>\n {quote.lines.map((line, index) => (\n <Stack key={index} direction=\"row\" spacing={2} sx={{ justifyContent: 'space-between' }}>\n <Stack spacing={0.25} sx={{ minWidth: 0 }}>\n <Typography variant=\"body2\">\n {line.name}\n {line.variantLabel ? ` (${line.variantLabel})` : ''}\n </Typography>\n {line.description ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ whiteSpace: 'pre-line' }}>\n {line.description}\n </Typography>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {[\n line.included ? `${line.quantity} included` : `${line.quantity} × ${money(line.unitAmountCents)}`,\n line.sku ? `SKU ${line.sku}` : '',\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n </Stack>\n <Typography variant=\"body2\" sx={{ flexShrink: 0 }}>\n {line.included ? 'Included' : money(line.amountCents)}\n </Typography>\n </Stack>\n ))}\n <Divider />\n {totalRows.map(([label, value]) => (\n <TotalRow key={`${label}-${value}`} label={label} value={value} />\n ))}\n <TotalRow label=\"Total\" value={money(quote.totals.totalCents)} strong />\n </Stack>\n\n {quote.notes ? (\n <Stack spacing={0.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Notes'}\n </Typography>\n <Typography variant=\"body2\" sx={{ whiteSpace: 'pre-line' }}>\n {quote.notes}\n </Typography>\n </Stack>\n ) : null}\n {quote.terms ? (\n <Stack spacing={0.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Terms'}\n </Typography>\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ whiteSpace: 'pre-line' }}>\n {quote.terms}\n </Typography>\n </Stack>\n ) : null}\n\n <QuoteProofPanel\n view={quote}\n hostId={hostId}\n quoteId={link.current.quoteId}\n token={link.current.token}\n siteFetch={siteFetch}\n onView={(next) => setState({ kind: 'ready', view: next })}\n onReload={() => void load().then(setState)}\n onReplaced={() => setState({ kind: 'replaced', storeName: quote.storeName, noun })}\n />\n\n {unpaid ? (\n <Paper variant=\"outlined\" sx={{ p: { xs: 2, sm: 3 } }}>\n <Stack spacing={2}>\n {returned === 'confirming' ? (\n <Alert severity=\"info\" icon={<CircularProgress size={20} />}>\n {'Thank you. We’re confirming your payment.'}\n </Alert>\n ) : returned === 'unconfirmed' ? (\n <Alert severity=\"info\">\n {'Your payment is still being confirmed. Your receipt will arrive by email.'}\n </Alert>\n ) : quote.approvalRequired ? (\n <Alert severity=\"info\">\n {`${quote.storeName || 'The business'} asks you to approve the proof before you pay.`}\n </Alert>\n ) : quote.payable ? (\n <>\n {returned === 'failed' ? (\n <Alert severity=\"warning\">{'Your payment did not go through. Nothing was charged.'}</Alert>\n ) : null}\n {nativeCheckout ? (\n <Suspense fallback={<StorefrontPaymentElementFallback />}>\n <StorefrontPaymentElement\n clientSecret={nativeCheckout.clientSecret}\n publishableKey={nativeCheckout.publishableKey}\n wallets={nativeCheckout.wallets}\n payLabel={later ? 'Pay now' : `Pay ${money(quote.totals.totalCents)}`}\n defaultShippingAddress={stripeContact(quote.shipTo)}\n // An expired or unloadable session is replaced by a new press.\n onRestart={() => {\n setNativeCheckout(null)\n void pay()\n }}\n onCancel={() => setNativeCheckout(null)}\n />\n </Suspense>\n ) : (\n <Button\n variant=\"contained\"\n size=\"large\"\n onClick={() => void pay()}\n disabled={paying}\n sx={{ alignSelf: { xs: 'stretch', sm: 'flex-start' } }}\n >\n {paying\n ? 'Opening…'\n : later\n ? `Pay ${money(quote.totals.totalCents)} plus ${later}`\n : `Pay ${money(quote.totals.totalCents)}`}\n </Button>\n )}\n {payError ? <Alert severity=\"error\">{payError}</Alert> : null}\n </>\n ) : (\n <Alert severity=\"info\">\n {quote.notPayableMessage || `Contact ${quote.storeName || 'the business'} to pay this ${noun}.`}\n </Alert>\n )}\n </Stack>\n </Paper>\n ) : (\n <Paper variant=\"outlined\" sx={{ p: { xs: 2, sm: 3 } }}>\n <Stack spacing={1.5} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body1\">\n {quote.status === 'paid'\n ? quote.paidAtMs\n ? `Paid ${dateLabel(quote.paidAtMs)}. Thank you.`\n : 'Paid. Thank you.'\n : `This ${noun} is ${quote.statusLabel.toLowerCase()}.`}\n </Typography>\n {quote.receiptUrl ? (\n <Button variant=\"outlined\" href={quote.receiptUrl}>\n {'View your order'}\n </Button>\n ) : null}\n </Stack>\n </Paper>\n )}\n\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Questions about this ${noun}? Contact ${quote.storeName || 'the business'}.`}\n </Typography>\n </Stack>\n </Box>\n )\n})\nQuotePageBody.displayName = 'QuotePageBody'\n\nexport default QuotePageBody\n\n"],"names":["Aglyn","Alert","Box","Button","Chip","CircularProgress","Divider","Paper","Stack","Typography","forwardRef","lazy","Suspense","useCallback","useEffect","useRef","useState","formatOrderMoney","readStorefrontCheckoutWallets","QuoteProofPanel","StorefrontPaymentElementFallback","StorefrontPaymentElement","then","module","default","nounOf","kind","addedAtPayment","view","shippingAtPayment","taxAtPayment","CONFIRM_POLL_MS","CONFIRM_POLLS","dateLabel","atMs","Date","toLocaleDateString","undefined","month","day","year","addressLines","address","cityLine","city","state","postalCode","filter","Boolean","join","name","line1","line2","country","line","stripeContact","postal_code","AddressBlock","label","lines","spacing","sx","minWidth","flex","variant","color","map","index","TotalRow","value","strong","direction","justifyContent","QuotePageBody","props","ref","heading","rest","nodeSx","Array","isArray","hostId","useSite","siteFetch","useSiteFetch","setState","paying","setPaying","payError","setPayError","nativeCheckout","setNativeCheckout","returned","setReturned","link","quoteId","token","sessionId","load","current","response","encodeURIComponent","payload","json","catch","ok","message","String","error","storeName","noun","params","URLSearchParams","window","location","search","get","live","first","status","poll","Promise","resolve","setTimeout","next","pay","globalThis","attemptKey","crypto","randomUUID","now","Math","random","toString","slice","method","headers","body","JSON","stringify","q","t","v","version","taxKey","tax","clientSecret","publishableKey","wallets","url","assign","replaced","reason","p","border","borderColor","borderRadius","py","textAlign","size","aria-label","component","severity","business","quote","money","cents","currency","pdfHref","unpaid","later","addresses","customerName","company","billTo","shipTo","block","length","totalRows","totals","itemsCents","discountLabel","discountCents","shippingCents","taxLabel","taxCents","shown","alignItems","flexWrap","rowGap","number","statusLabel","dateMs","href","download","xs","sm","variantLabel","description","whiteSpace","included","quantity","unitAmountCents","sku","flexShrink","amountCents","totalCents","notes","terms","onView","onReload","onReplaced","icon","approvalRequired","payable","fallback","payLabel","defaultShippingAddress","onRestart","onCancel","onClick","disabled","alignSelf","notPayableMessage","paidAtMs","toLowerCase","receiptUrl","displayName"],"mappings":";;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,sBAAsB,iCAAgC;AAC7D,OAAOC,aAAa,wBAAuB;AAC3C,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,gBAAgB,2BAA0B;AAEjD,SAASC,UAAU,EAAEC,IAAI,EAAEC,QAAQ,EAAEC,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAC5F,SACEC,gBAAgB,EAChBC,6BAA6B,QAIxB,oBAAU;AAEjB,SAASC,eAAe,QAAQ,yBAAqB;AACrD,SAASC,gCAAgC,QAAQ,2CAAuC;AAExF,mFAAmF,GACnF,MAAMC,yCAA2BV,KAAK,IACpC,MAAM,CAAC,mCAAgCW,IAAI,CAAC,CAACC,SAAY,CAAA;YACvDC,SAASD,OAAOF,wBAAwB;QAC1C,CAAA;AASF,0DAA0D,GAC1D,MAAMI,SAAS,CAACC,OAAmBA,SAAS,YAAY,YAAY;AAEpE,6FAA6F,GAC7F,SAASC,eAAeC,IAA+D;IACrF,IAAIA,KAAKC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AAS,IAAI,eAAe,CAAC,CAAC;;;;;AAKxF;AACApC,cAAc0J,WAAW,GAAG;AAE5B,eAAe1J,cAAa"}
@@ -27,6 +27,7 @@ import Typography from "@mui/material/Typography";
27
27
  import { forwardRef, useEffect, useState } from "react";
28
28
  import { BUNDLE_ID } from "../constants/bundle-common.js";
29
29
  import { generatePresetId } from "../utils/generate-preset-id.js";
30
+ import { formatOrderMoney } from "../model/buyer-notifications.js";
30
31
  import { ProductImagePlaceholder } from "./product-image-placeholder.js";
31
32
  // Component ids are persisted in screen documents; never rename.
32
33
  export const ID = 'related-products';
@@ -192,7 +193,7 @@ export const ID = 'related-products';
192
193
  /*#__PURE__*/ _jsx(Typography, {
193
194
  variant: grid ? 'body2' : 'caption',
194
195
  color: "text.secondary",
195
- children: item.priceComingSoon ? 'Price coming soon' : `$${item.priceUsd}`
196
+ children: item.priceComingSoon ? 'Price coming soon' : formatOrderMoney(Math.round(item.priceUsd * 100))
196
197
  })
197
198
  ]
198
199
  })
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/related-products.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport { mdiShapePlus } from '@aglyn/shared-data-mdi'\nimport Box from '@mui/material/Box'\nimport Card from '@mui/material/Card'\nimport CardActionArea from '@mui/material/CardActionArea'\nimport CardContent from '@mui/material/CardContent'\nimport CardMedia from '@mui/material/CardMedia'\nimport Typography from '@mui/material/Typography'\nimport { forwardRef, useEffect, useState } from 'react'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { generatePresetId } from '../utils/generate-preset-id'\nimport { ProductImagePlaceholder } from './product-image-placeholder'\n\n// Component ids are persisted in screen documents; never rename.\nexport const ID: Aglyn.ComponentId = 'related-products'\n\nexport interface RelatedProductsProps {\n /** Anchor product id; blank follows the /products/{slug} page. */\n productId?: string\n heading?: string\n maxItems?: number\n /**\n * How the items are drawn: `strip`, the default, a scrolling row of small\n * cards; `grid`, tall photo cards (4:5) with the name and price under\n * them in a grid of up to four across — the product grid's photo look.\n */\n layout?: 'strip' | 'grid'\n}\n\ninterface CatalogItem {\n id: string\n name: string\n slug: string\n priceUsd: number\n imageUrl?: string\n /** Listed before it has a price (AGL-3676). */\n priceComingSoon?: boolean\n}\n\n/**\n * Related products / upsell strip (AGL-325): the product's manual list,\n * else \"frequently bought together\" from recent orders, else tag and\n * category neighbors — resolved server-side, rendered as cards.\n */\nconst RelatedProducts = forwardRef<HTMLDivElement, RelatedProductsProps>(\n (props, ref) => {\n const { productId: productIdProp, heading, maxItems, layout, ...rest } = props\n // Node styles ride the renderer-merged sx; recompose (stack.ts pattern).\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const site = Aglyn.useSite()\n const { hostId } = site\n // The page's product, when the server seeded it (AGL-659): its id is the\n // anchor, so the rail skips a product lookup the page already made.\n const seededProductId = (\n site.pageData as { commerce?: { product?: { id?: string } } } | undefined\n )?.commerce?.product?.id\n const [items, setItems] = useState<CatalogItem[] | null>(null)\n\n useEffect(() => {\n if (!hostId) return\n let active = true\n void (async () => {\n let anchor = productIdProp || seededProductId || ''\n if (!anchor) {\n const match = window.location.pathname.match(/\\/products\\/([^/?#]+)/)\n if (!match) return\n const response = await fetch(\n `/api/commerce/product?hostId=${encodeURIComponent(hostId)}` +\n `&slug=${encodeURIComponent(decodeURIComponent(match[1]))}`,\n ).catch(() => null)\n const payload = await response?.json().catch(() => ({}))\n anchor = String(payload?.product?.id ?? '')\n }\n if (!active || !anchor) return\n const relatedResponse = await fetch(\n `/api/commerce/related?hostId=${encodeURIComponent(hostId)}` +\n `&productId=${encodeURIComponent(anchor)}`,\n ).catch(() => null)\n const related = await relatedResponse?.json().catch(() => ({}))\n const ids: string[] = related?.productIds ?? []\n if (!active || ids.length === 0) return setItems([])\n const catalogResponse = await fetch(\n `/api/commerce/catalog?hostId=${encodeURIComponent(hostId)}` +\n `&ids=${encodeURIComponent(ids.join(','))}`,\n ).catch(() => null)\n const catalog = await catalogResponse?.json().catch(() => ({}))\n if (active) setItems(catalog?.items ?? [])\n })()\n return () => {\n active = false\n }\n }, [hostId, productIdProp, seededProductId])\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[\n {\n p: 3,\n border: '1px dashed',\n borderColor: 'divider',\n borderRadius: 1,\n color: 'text.secondary',\n fontSize: 13,\n fontFamily: 'system-ui, sans-serif',\n },\n ...nodeSx,\n ]}\n >\n {'Related products render here'}\n </Box>\n )\n }\n if (!items || items.length === 0) return <Box ref={ref} {...rest} />\n\n const grid = layout === 'grid'\n return (\n <Box ref={ref} {...rest}>\n <Typography variant={grid ? 'h5' : 'h6'} component=\"h2\" gutterBottom sx={grid ? { mb: 2 } : undefined}>\n {heading || 'You may also like'}\n </Typography>\n <Box\n sx={\n grid\n ? {\n display: 'grid',\n gap: 2,\n gridTemplateColumns: { xs: 'repeat(2, minmax(0, 1fr))', md: 'repeat(4, minmax(0, 1fr))' },\n }\n : { display: 'flex', gap: 1.5, overflowX: 'auto', pb: 1 }\n }\n >\n {items\n .slice(0, maxItems && maxItems > 0 ? maxItems : 6)\n .map((item) => {\n // AGL-1726: resolved BEFORE the guard — see the note in\n // `product-detail.tsx`.\n const imageUrl = Aglyn.siteRelativeMediaSrc(item.imageUrl, {\n hostId,\n })\n const mediaSx = grid\n ? { aspectRatio: '4 / 5', borderRadius: 2 }\n : { height: 110 }\n return (\n <Card\n key={item.id}\n variant={grid ? 'elevation' : 'outlined'}\n elevation={0}\n sx={grid ? { bgcolor: 'transparent', overflow: 'visible', minWidth: 0 } : { minWidth: 160 }}\n >\n <CardActionArea\n href={`/products/${item.slug}`}\n sx={grid ? { borderRadius: 2 } : undefined}\n >\n {imageUrl ? (\n <CardMedia\n component=\"img\"\n image={imageUrl}\n alt={item.name}\n sx={{ ...mediaSx, objectFit: 'cover' }}\n // Deferred (AGL-2486). A related-products rail sits at\n // the BOTTOM of a product page by construction, and it\n // was fetching eagerly against the gallery hero above\n // it — the one image on that page that is the LCP.\n {...Aglyn.DEFERRED_IMAGE_ATTRIBUTES}\n />\n ) : (\n // Never a blank tile: a product with no photo yet says\n // so, in the theme's colours (AGL-3676 follow-up).\n <ProductImagePlaceholder name={item.name} sx={mediaSx} />\n )}\n <CardContent sx={grid ? { px: 0.5, pt: 1.5, pb: 1 } : { py: 1 }}>\n <Typography variant={grid ? 'subtitle1' : 'body2'} noWrap>\n {item.name}\n </Typography>\n <Typography variant={grid ? 'body2' : 'caption'} color=\"text.secondary\">\n {item.priceComingSoon ? 'Price coming soon' : `$${item.priceUsd}`}\n </Typography>\n </CardContent>\n </CardActionArea>\n </Card>\n )\n })}\n </Box>\n </Box>\n )\n },\n)\nRelatedProducts.displayName = 'AglynRelatedProducts'\n\nexport const schema: Aglyn.ComponentSchema<RelatedProductsProps> = {\n $id: ID,\n pluginId: BUNDLE_ID,\n displayName: 'Related products',\n description:\n 'An upsell strip — your manual picks, or what people buy together.',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiShapePlus.path, sx: { color: '#2e7d32' } },\n flags: { selfClosing: Aglyn.FEATURE_FLAG.ENABLED },\n attributes: [\n {\n name: 'productId',\n label: 'Product id',\n description:\n 'The product to find relatives OF. Blank reads it from the URL, so ' +\n 'a product template shows each product’s own related items; naming ' +\n 'one pins the rail to that product’s relatives everywhere.',\n component: Aglyn.FieldComponentType.PRODUCT_SELECT,\n },\n {\n name: 'heading',\n label: 'Heading',\n description: 'Defaults to \"You may also like\".',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n {\n name: 'maxItems',\n label: 'Max items',\n description: 'Cap the strip (default 6).',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n type: 'number',\n },\n {\n // Default `strip`, so a page that already places this block keeps it.\n name: 'layout',\n label: 'Layout',\n description: 'A scrolling strip of small cards, or a grid of tall photo cards.',\n component: Aglyn.FieldComponentType.SELECT,\n options: [\n { label: 'Strip', value: 'strip' },\n { label: 'Photo grid', value: 'grid' },\n ],\n },\n ],\n}\n\nexport const presets: Aglyn.PresetSchema[] = [\n {\n $id: generatePresetId(ID),\n type: Aglyn.NodeType.PRESET,\n displayName: 'Related products',\n pluginId: BUNDLE_ID,\n description: 'Manual picks or frequently-bought-together',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiShapePlus.path, sx: { color: '#2e7d32' } },\n data: {\n $id: null,\n componentId: ID,\n pluginId: BUNDLE_ID,\n props: {},\n },\n },\n]\n\nexport default RelatedProducts\n"],"names":["Aglyn","mdiShapePlus","Box","Card","CardActionArea","CardContent","CardMedia","Typography","forwardRef","useEffect","useState","BUNDLE_ID","generatePresetId","ProductImagePlaceholder","ID","RelatedProducts","props","ref","site","productId","productIdProp","heading","maxItems","layout","rest","nodeSx","Array","isArray","useSite","hostId","seededProductId","pageData","commerce","product","id","items","setItems","active","anchor","payload","match","window","location","pathname","response","fetch","encodeURIComponent","decodeURIComponent","catch","json","String","relatedResponse","related","ids","productIds","length","catalogResponse","join","catalog","sx","p","border","borderColor","borderRadius","color","fontSize","fontFamily","grid","variant","component","gutterBottom","mb","undefined","display","gap","gridTemplateColumns","xs","md","overflowX","pb","slice","map","item","imageUrl","siteRelativeMediaSrc","mediaSx","aspectRatio","height","elevation","bgcolor","overflow","minWidth","href","slug","image","alt","name","objectFit","DEFERRED_IMAGE_ATTRIBUTES","px","pt","py","noWrap","priceComingSoon","priceUsd","displayName","schema","$id","pluginId","description","category","ComponentCategory","COMMERCE","icon","path","flags","selfClosing","FEATURE_FLAG","ENABLED","attributes","label","FieldComponentType","PRODUCT_SELECT","TEXT_FIELD","type","SELECT","options","value","presets","NodeType","PRESET","data","componentId"],"mappings":";;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,YAAY,QAAQ,yBAAwB;AACrD,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,oBAAoB,+BAA8B;AACzD,OAAOC,iBAAiB,4BAA2B;AACnD,OAAOC,eAAe,0BAAyB;AAC/C,OAAOC,gBAAgB,2BAA0B;AACjD,SAASC,UAAU,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACvD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SAASC,gBAAgB,QAAQ,iCAA6B;AAC9D,SAASC,uBAAuB,QAAQ,iCAA6B;AAErE,iEAAiE;AACjE,OAAO,MAAMC,KAAwB,mBAAkB;AAyBvD;;;;CAIC,GACD,MAAMC,gCAAkBP,WACtB,CAACQ,OAAOC;QAQkB,iCAAA,yBACtBC;IARF,MAAM,EAAEC,WAAWC,aAAa,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,MAAM,EAAW,GAAGP,OAATQ,wCAASR;;;;;;IACzE,yEAAyE;IACzE,MAAMS,SAASC,MAAMC,OAAO,CAACX,KAAK,CAAC,KAAK,IAAIA,KAAK,CAAC,KAAK,GAAG;QAACA,KAAK,CAAC,KAAK;KAAC;IACvE,MAAME,OAAOlB,MAAM4B,OAAO;IAC1B,MAAM,EAAEC,MAAM,EAAE,GAAGX;IACnB,yEAAyE;IACzE,oEAAoE;IACpE,MAAMY,mBACJZ,iBAAAA,KAAKa,QAAQ,sBADS,0BAAA,AACtBb,eACCc,QAAQ,sBAFa,kCAAA,wBAEXC,OAAO,qBAFI,gCAEFC,EAAE;IACxB,MAAM,CAACC,OAAOC,SAAS,GAAG1B,SAA+B;IAEzDD,UAAU;QACR,IAAI,CAACoB,QAAQ;QACb,IAAIQ,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B,CAACC,cAAc;QACpD;QACA;YACE1B,MAAM;YACNwB,OAAO;YACPX,aAAa;YACbxC,WAAWrE,MAAMyH,kBAAkB,CAACE,UAAU;QAChD;QACA;YACE3B,MAAM;YACNwB,OAAO;YACPX,aAAa;YACbxC,WAAWrE,MAAMyH,kBAAkB,CAACE,UAAU;YAC9CC,MAAM;QACR;QACA;YACE,sEAAsE;YACtE5B,MAAM;YACNwB,OAAO;YACPX,aAAa;YACbxC,WAAWrE,MAAMyH,kBAAkB,CAACI,MAAM;YAC1CC,SAAS;gBACP;oBAAEN,OAAO;oBAASO,OAAO;gBAAQ;gBACjC;oBAAEP,OAAO;oBAAcO,OAAO;gBAAO;aACtC;QACH;KACD;AACH,EAAC;AAED,OAAO,MAAMC,UAAgC;IAC3C;QACErB,KAAK/F,iBAAiBE;QACtB8G,MAAM5H,MAAMiI,QAAQ,CAACC,MAAM;QAC3BzB,aAAa;QACbG,UAAUjG;QACVkG,aAAa;QACbC,UAAU9G,MAAM+G,iBAAiB,CAACC,QAAQ;QAC1CC,MAAM;YAAEC,MAAMjH,aAAaiH,IAAI;YAAEvD,IAAI;gBAAEK,OAAO;YAAU;QAAE;QAC1DmE,MAAM;YACJxB,KAAK;YACLyB,aAAatH;YACb8F,UAAUjG;YACVK,OAAO,CAAC;QACV;IACF;CACD,CAAA;AAED,eAAeD,gBAAe"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/related-products.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport { mdiShapePlus } from '@aglyn/shared-data-mdi'\nimport Box from '@mui/material/Box'\nimport Card from '@mui/material/Card'\nimport CardActionArea from '@mui/material/CardActionArea'\nimport CardContent from '@mui/material/CardContent'\nimport CardMedia from '@mui/material/CardMedia'\nimport Typography from '@mui/material/Typography'\nimport { forwardRef, useEffect, useState } from 'react'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { generatePresetId } from '../utils/generate-preset-id'\nimport { formatOrderMoney } from '../model/buyer-notifications'\nimport { ProductImagePlaceholder } from './product-image-placeholder'\n\n// Component ids are persisted in screen documents; never rename.\nexport const ID: Aglyn.ComponentId = 'related-products'\n\nexport interface RelatedProductsProps {\n /** Anchor product id; blank follows the /products/{slug} page. */\n productId?: string\n heading?: string\n maxItems?: number\n /**\n * How the items are drawn: `strip`, the default, a scrolling row of small\n * cards; `grid`, tall photo cards (4:5) with the name and price under\n * them in a grid of up to four across — the product grid's photo look.\n */\n layout?: 'strip' | 'grid'\n}\n\ninterface CatalogItem {\n id: string\n name: string\n slug: string\n priceUsd: number\n imageUrl?: string\n /** Listed before it has a price (AGL-3676). */\n priceComingSoon?: boolean\n}\n\n/**\n * Related products / upsell strip (AGL-325): the product's manual list,\n * else \"frequently bought together\" from recent orders, else tag and\n * category neighbors — resolved server-side, rendered as cards.\n */\nconst RelatedProducts = forwardRef<HTMLDivElement, RelatedProductsProps>(\n (props, ref) => {\n const { productId: productIdProp, heading, maxItems, layout, ...rest } = props\n // Node styles ride the renderer-merged sx; recompose (stack.ts pattern).\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const site = Aglyn.useSite()\n const { hostId } = site\n // The page's product, when the server seeded it (AGL-659): its id is the\n // anchor, so the rail skips a product lookup the page already made.\n const seededProductId = (\n site.pageData as { commerce?: { product?: { id?: string } } } | undefined\n )?.commerce?.product?.id\n const [items, setItems] = useState<CatalogItem[] | null>(null)\n\n useEffect(() => {\n if (!hostId) return\n let active = true\n void (async () => {\n let anchor = productIdProp || seededProductId || ''\n if (!anchor) {\n const match = window.location.pathname.match(/\\/products\\/([^/?#]+)/)\n if (!match) return\n const response = await fetch(\n `/api/commerce/product?hostId=${encodeURIComponent(hostId)}` +\n `&slug=${encodeURIComponent(decodeURIComponent(match[1]))}`,\n ).catch(() => null)\n const payload = await response?.json().catch(() => ({}))\n anchor = String(payload?.product?.id ?? '')\n }\n if (!active || !anchor) return\n const relatedResponse = await fetch(\n `/api/commerce/related?hostId=${encodeURIComponent(hostId)}` +\n `&productId=${encodeURIComponent(anchor)}`,\n ).catch(() => null)\n const related = await relatedResponse?.json().catch(() => ({}))\n const ids: string[] = related?.productIds ?? []\n if (!active || ids.length === 0) return setItems([])\n const catalogResponse = await fetch(\n `/api/commerce/catalog?hostId=${encodeURIComponent(hostId)}` +\n `&ids=${encodeURIComponent(ids.join(','))}`,\n ).catch(() => null)\n const catalog = await catalogResponse?.json().catch(() => ({}))\n if (active) setItems(catalog?.items ?? [])\n })()\n return () => {\n active = false\n }\n }, [hostId, productIdProp, seededProductId])\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[\n {\n p: 3,\n border: '1px dashed',\n borderColor: 'divider',\n borderRadius: 1,\n color: 'text.secondary',\n fontSize: 13,\n fontFamily: 'system-ui, sans-serif',\n },\n ...nodeSx,\n ]}\n >\n {'Related products render here'}\n </Box>\n )\n }\n if (!items || items.length === 0) return <Box ref={ref} {...rest} />\n\n const grid = layout === 'grid'\n return (\n <Box ref={ref} {...rest}>\n <Typography variant={grid ? 'h5' : 'h6'} component=\"h2\" gutterBottom sx={grid ? { mb: 2 } : undefined}>\n {heading || 'You may also like'}\n </Typography>\n <Box\n sx={\n grid\n ? {\n display: 'grid',\n gap: 2,\n gridTemplateColumns: { xs: 'repeat(2, minmax(0, 1fr))', md: 'repeat(4, minmax(0, 1fr))' },\n }\n : { display: 'flex', gap: 1.5, overflowX: 'auto', pb: 1 }\n }\n >\n {items\n .slice(0, maxItems && maxItems > 0 ? maxItems : 6)\n .map((item) => {\n // AGL-1726: resolved BEFORE the guard — see the note in\n // `product-detail.tsx`.\n const imageUrl = Aglyn.siteRelativeMediaSrc(item.imageUrl, {\n hostId,\n })\n const mediaSx = grid\n ? { aspectRatio: '4 / 5', borderRadius: 2 }\n : { height: 110 }\n return (\n <Card\n key={item.id}\n variant={grid ? 'elevation' : 'outlined'}\n elevation={0}\n sx={grid ? { bgcolor: 'transparent', overflow: 'visible', minWidth: 0 } : { minWidth: 160 }}\n >\n <CardActionArea\n href={`/products/${item.slug}`}\n sx={grid ? { borderRadius: 2 } : undefined}\n >\n {imageUrl ? (\n <CardMedia\n component=\"img\"\n image={imageUrl}\n alt={item.name}\n sx={{ ...mediaSx, objectFit: 'cover' }}\n // Deferred (AGL-2486). A related-products rail sits at\n // the BOTTOM of a product page by construction, and it\n // was fetching eagerly against the gallery hero above\n // it — the one image on that page that is the LCP.\n {...Aglyn.DEFERRED_IMAGE_ATTRIBUTES}\n />\n ) : (\n // Never a blank tile: a product with no photo yet says\n // so, in the theme's colours (AGL-3676 follow-up).\n <ProductImagePlaceholder name={item.name} sx={mediaSx} />\n )}\n <CardContent sx={grid ? { px: 0.5, pt: 1.5, pb: 1 } : { py: 1 }}>\n <Typography variant={grid ? 'subtitle1' : 'body2'} noWrap>\n {item.name}\n </Typography>\n <Typography variant={grid ? 'body2' : 'caption'} color=\"text.secondary\">\n {item.priceComingSoon\n ? 'Price coming soon'\n : formatOrderMoney(Math.round(item.priceUsd * 100))}\n </Typography>\n </CardContent>\n </CardActionArea>\n </Card>\n )\n })}\n </Box>\n </Box>\n )\n },\n)\nRelatedProducts.displayName = 'AglynRelatedProducts'\n\nexport const schema: Aglyn.ComponentSchema<RelatedProductsProps> = {\n $id: ID,\n pluginId: BUNDLE_ID,\n displayName: 'Related products',\n description:\n 'An upsell strip — your manual picks, or what people buy together.',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiShapePlus.path, sx: { color: '#2e7d32' } },\n flags: { selfClosing: Aglyn.FEATURE_FLAG.ENABLED },\n attributes: [\n {\n name: 'productId',\n label: 'Product id',\n description:\n 'The product to find relatives OF. Blank reads it from the URL, so ' +\n 'a product template shows each product’s own related items; naming ' +\n 'one pins the rail to that product’s relatives everywhere.',\n component: Aglyn.FieldComponentType.PRODUCT_SELECT,\n },\n {\n name: 'heading',\n label: 'Heading',\n description: 'Defaults to \"You may also like\".',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n {\n name: 'maxItems',\n label: 'Max items',\n description: 'Cap the strip (default 6).',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n type: 'number',\n },\n {\n // Default `strip`, so a page that already places this block keeps it.\n name: 'layout',\n label: 'Layout',\n description: 'A scrolling strip of small cards, or a grid of tall photo cards.',\n component: Aglyn.FieldComponentType.SELECT,\n options: [\n { label: 'Strip', value: 'strip' },\n { label: 'Photo grid', value: 'grid' },\n ],\n },\n ],\n}\n\nexport const presets: Aglyn.PresetSchema[] = [\n {\n $id: generatePresetId(ID),\n type: Aglyn.NodeType.PRESET,\n displayName: 'Related products',\n pluginId: BUNDLE_ID,\n description: 'Manual picks or frequently-bought-together',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiShapePlus.path, sx: { color: '#2e7d32' } },\n data: {\n $id: null,\n componentId: ID,\n pluginId: BUNDLE_ID,\n props: {},\n },\n },\n]\n\nexport default RelatedProducts\n"],"names":["Aglyn","mdiShapePlus","Box","Card","CardActionArea","CardContent","CardMedia","Typography","forwardRef","useEffect","useState","BUNDLE_ID","generatePresetId","formatOrderMoney","ProductImagePlaceholder","ID","RelatedProducts","props","ref","site","productId","productIdProp","heading","maxItems","layout","rest","nodeSx","Array","isArray","useSite","hostId","seededProductId","pageData","commerce","product","id","items","setItems","active","anchor","payload","match","window","location","pathname","response","fetch","encodeURIComponent","decodeURIComponent","catch","json","String","relatedResponse","related","ids","productIds","length","catalogResponse","join","catalog","sx","p","border","borderColor","borderRadius","color","fontSize","fontFamily","grid","variant","component","gutterBottom","mb","undefined","display","gap","gridTemplateColumns","xs","md","overflowX","pb","slice","map","item","imageUrl","siteRelativeMediaSrc","mediaSx","aspectRatio","height","elevation","bgcolor","overflow","minWidth","href","slug","image","alt","name","objectFit","DEFERRED_IMAGE_ATTRIBUTES","px","pt","py","noWrap","priceComingSoon","Math","round","priceUsd","displayName","schema","$id","pluginId","description","category","ComponentCategory","COMMERCE","icon","path","flags","selfClosing","FEATURE_FLAG","ENABLED","attributes","label","FieldComponentType","PRODUCT_SELECT","TEXT_FIELD","type","SELECT","options","value","presets","NodeType","PRESET","data","componentId"],"mappings":";;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,YAAY,QAAQ,yBAAwB;AACrD,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,oBAAoB,+BAA8B;AACzD,OAAOC,iBAAiB,4BAA2B;AACnD,OAAOC,eAAe,0BAAyB;AAC/C,OAAOC,gBAAgB,2BAA0B;AACjD,SAASC,UAAU,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACvD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SAASC,gBAAgB,QAAQ,iCAA6B;AAC9D,SAASC,gBAAgB,QAAQ,kCAA8B;AAC/D,SAASC,uBAAuB,QAAQ,iCAA6B;AAErE,iEAAiE;AACjE,OAAO,MAAMC,KAAwB,mBAAkB;AAyBvD;;;;CAIC,GACD,MAAMC,gCAAkBR,WACtB,CAACS,OAAOC;QAQkB,iCAAA,yBACtBC;IARF,MAAM,EAAEC,WAAWC,aAAa,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,MAAM,EAAW,GAAGP,OAATQ,wCAASR;;;;;;IACzE,yEAAyE;IACzE,MAAMS,SAASC,MAAMC,OAAO,CAACX,KAAK,CAAC,KAAK,IAAIA,KAAK,CAAC,KAAK,GAAG;QAACA,KAAK,CAAC,KAAK;KAAC;IACvE,MAAME,O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