@aglyn/plugins-commerce 1.11.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.
- package/package.json +13 -13
- package/src/lib/components/console/host-quotes-card.component.js +20 -11
- package/src/lib/components/console/host-quotes-card.component.js.map +1 -1
- package/src/lib/components/console/pos-kiosk/kiosk-menu.d.ts +10 -3
- package/src/lib/components/console/pos-kiosk/kiosk-menu.js +29 -8
- package/src/lib/components/console/pos-kiosk/kiosk-menu.js.map +1 -1
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.d.ts +2 -0
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js +7 -0
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js.map +1 -1
- package/src/lib/components/console/pos-kiosk-page.component.d.ts +2 -0
- package/src/lib/components/console/pos-kiosk-page.component.js +54 -3
- package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +0 -2
- package/src/lib/components/console/product-add-ons-fields.component.js +1 -6
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.d.ts +2 -0
- package/src/lib/components/console/quote-editor-dialog.component.js +28 -19
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/product-detail.js +1 -1
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.js +5 -3
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/product-reviews.js +17 -12
- package/src/lib/components/product-reviews.js.map +1 -1
- package/src/lib/components/related-products.js +2 -1
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/model/commerce-kiosk-search.d.ts +22 -0
- package/src/lib/model/commerce-kiosk-search.js +32 -0
- package/src/lib/model/commerce-kiosk-search.js.map +1 -0
- package/src/lib/model/commerce-pos-kiosk.d.ts +7 -1
- package/src/lib/model/commerce-pos-kiosk.js +1 -1
- package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
- package/src/lib/model/product-modifiers.d.ts +4 -0
- package/src/lib/model/product-modifiers.js +5 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/server/pos-kiosk.js +70 -15
- package/src/lib/server/pos-kiosk.js.map +1 -1
- package/src/lib/server/quote-proofs.js +8 -3
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/server/site-page-enricher.js +5 -1
- package/src/lib/server/site-page-enricher.js.map +1 -1
- package/src/lib/testing/fake-firestore.js +34 -5
- package/src/lib/testing/fake-firestore.js.map +1 -1
- package/src/lib/transfer/product-register-cells.d.ts +75 -0
- package/src/lib/transfer/product-register-cells.js +487 -0
- package/src/lib/transfer/product-register-cells.js.map +1 -0
- package/src/lib/transfer/product-transfer.d.ts +12 -0
- package/src/lib/transfer/product-transfer.js +174 -10
- package/src/lib/transfer/product-transfer.js.map +1 -1
- package/src/lib/transfer/products.server.js +24 -9
- package/src/lib/transfer/products.server.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,UAAU,qBAAoB;AACrC,OAAOC,aAAa,wBAAuB;AAC3C,OAAOC,YAAY,uBAAsB;AACzC,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;AAE9D,iEAAiE;AACjE,OAAO,MAAMC,KAAwB,kBAAiB;AAkCtD,MAAMC,iBAAiB;IACrBC,GAAG;IACHC,QA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F,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,WAAW,eAAc;AACrC,SAASC,cAAc,QAAQ,yBAAwB;AACvD,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,aAAa,wBAAuB;AAC3C,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,eAAe,0BAAyB;AAC/C,OAAOC,gBAAgB,2BAA0B;AACjD,SAASC,UAAU,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACvD,SAASC,SAAS,QAA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O;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"}
|
|
@@ -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' :
|
|
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,EAAE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O;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;;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aAAa;YACb1C,WAAWtE,MAAM4H,kBAAkB,CAACE,UAAU;QAChD;QACA;YACE7B,MAAM;YACN0B,OAAO;YACPX,aAAa;YACb1C,WAAWtE,MAAM4H,kBAAkB,CAACE,UAAU;YAC9CC,MAAM;QACR;QACA;YACE,sEAAsE;YACtE9B,MAAM;YACN0B,OAAO;YACPX,aAAa;YACb1C,WAAWtE,MAAM4H,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,KAAKlG,iBAAiBG;QACtBgH,MAAM/H,MAAMoI,QAAQ,CAACC,MAAM;QAC3BzB,aAAa;QACbG,UAAUpG;QACVqG,aAAa;QACbC,UAAUjH,MAAMkH,iBAAiB,CAACC,QAAQ;QAC1CC,MAAM;YAAEC,MAAMpH,aAAaoH,IAAI;YAAEzD,IAAI;gBAAEK,OAAO;YAAU;QAAE;QAC1DqE,MAAM;YACJxB,KAAK;YACLyB,aAAaxH;YACbgG,UAAUpG;YACVM,OAAO,CAAC;QACV;IACF;CACD,CAAA;AAED,eAAeD,gBAAe"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Whether a product's name answers the words typed, the way the catalog's
|
|
19
|
+
* search does: every word is the start of a word in the name, whatever the
|
|
20
|
+
* case. The query can hold only the first word, so the rest are asked here.
|
|
21
|
+
*/
|
|
22
|
+
export declare function posKioskNameMatches(name: string, typed: string): boolean;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { nameSearchKey, nameSearchToken, nameSearchTokens } from "@aglyn/aglyn/app-utils/name-search";
|
|
17
|
+
/*
|
|
18
|
+
* Its own module, not `commerce-pos-kiosk.ts`, which the plugin's eager chunk
|
|
19
|
+
* reaches: only the kiosk route and the kiosk's server read this, and every
|
|
20
|
+
* console screen would otherwise pay for it.
|
|
21
|
+
*/ /**
|
|
22
|
+
* Whether a product's name answers the words typed, the way the catalog's
|
|
23
|
+
* search does: every word is the start of a word in the name, whatever the
|
|
24
|
+
* case. The query can hold only the first word, so the rest are asked here.
|
|
25
|
+
*/ export function posKioskNameMatches(name, typed) {
|
|
26
|
+
const key = nameSearchKey(typed);
|
|
27
|
+
if (!key) return true;
|
|
28
|
+
const tokens = new Set(nameSearchTokens(name));
|
|
29
|
+
return key.split(' ').every((word)=>tokens.has(nameSearchToken(word)));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=commerce-kiosk-search.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-kiosk-search.ts"],"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 { nameSearchKey, nameSearchToken, nameSearchTokens } from '@aglyn/aglyn/app-utils/name-search'\n\n/*\n * Its own module, not `commerce-pos-kiosk.ts`, which the plugin's eager chunk\n * reaches: only the kiosk route and the kiosk's server read this, and every\n * console screen would otherwise pay for it.\n */\n\n/**\n * Whether a product's name answers the words typed, the way the catalog's\n * search does: every word is the start of a word in the name, whatever the\n * case. The query can hold only the first word, so the rest are asked here.\n */\nexport function posKioskNameMatches(name: string, typed: string): boolean {\n const key = nameSearchKey(typed)\n if (!key) return true\n const tokens = new Set(nameSearchTokens(name))\n return key.split(' ').every((word) => tokens.has(nameSearchToken(word)))\n}\n"],"names":["nameSearchKey","nameSearchToken","nameSearchTokens","posKioskNameMatches","name","typed","key","tokens","Set","split","every","word","has"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,eAAe,EAAEC,gBAAgB,QAAQ,qCAAoC;AAErG;;;;CAIC,GAED;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,IAAY,EAAEC,KAAa;IAC7D,MAAMC,MAAMN,cAAcK;IAC1B,IAAI,CAACC,KAAK,OAAO;IACjB,MAAMC,SAAS,IAAIC,IAAIN,iBAAiBE;IACxC,OAAOE,IAAIG,KAAK,CAAC,KAAKC,KAAK,CAAC,CAACC,OAASJ,OAAOK,GAAG,CAACX,gBAAgBU;AACnE"}
|
|
@@ -50,6 +50,12 @@ export interface PosKioskCatalog {
|
|
|
50
50
|
categories: PosKioskCategory[];
|
|
51
51
|
/** The store's currency, lower case (`usd`). */
|
|
52
52
|
currency: string;
|
|
53
|
+
/**
|
|
54
|
+
* Set when the store has more to offer than this answer lists, so the menu
|
|
55
|
+
* offers a search that reaches the rest. Absent on an answer that lists
|
|
56
|
+
* everything, which is every catalog the menu can show whole.
|
|
57
|
+
*/
|
|
58
|
+
truncated?: boolean;
|
|
53
59
|
}
|
|
54
60
|
/** What the kiosk offers, resolved on the server for one paired register. */
|
|
55
61
|
export interface PosKioskContext {
|
|
@@ -131,7 +137,7 @@ export declare const POS_KIOSK_DONE_SECONDS = 15;
|
|
|
131
137
|
export declare const POS_KIOSK_MAX_LINES = 40;
|
|
132
138
|
/** Most of one line a customer may order at a kiosk. */
|
|
133
139
|
export declare const POS_KIOSK_MAX_QUANTITY = 20;
|
|
134
|
-
/** Most products the kiosk grid lists
|
|
140
|
+
/** Most products the kiosk grid lists at once, for the whole menu, a category or a search. */
|
|
135
141
|
export declare const POS_KIOSK_CATALOG_LIMIT = 200;
|
|
136
142
|
/** Wrong staff PINs a kiosk takes before it locks its unlock screen. */
|
|
137
143
|
export declare const POS_KIOSK_UNLOCK_MAX_ATTEMPTS = 5;
|
|
@@ -23,7 +23,7 @@ export const POS_KIOSK_IDLE_SECONDS_MAX = 600;
|
|
|
23
23
|
/** The order-number screen returns to the start after this long. */ export const POS_KIOSK_DONE_SECONDS = 15;
|
|
24
24
|
/** Most lines one kiosk order carries. */ export const POS_KIOSK_MAX_LINES = 40;
|
|
25
25
|
/** Most of one line a customer may order at a kiosk. */ export const POS_KIOSK_MAX_QUANTITY = 20;
|
|
26
|
-
/** Most products the kiosk grid lists
|
|
26
|
+
/** Most products the kiosk grid lists at once, for the whole menu, a category or a search. */ export const POS_KIOSK_CATALOG_LIMIT = 200;
|
|
27
27
|
/** Wrong staff PINs a kiosk takes before it locks its unlock screen. */ export const POS_KIOSK_UNLOCK_MAX_ATTEMPTS = 5;
|
|
28
28
|
/** How long a kiosk's unlock screen stays locked after too many wrong PINs. */ export const POS_KIOSK_UNLOCK_LOCKOUT_MS = 15 * 60 * 1000;
|
|
29
29
|
/** How long a staff unlock keeps the kiosk's settings open. */ export const POS_KIOSK_UNLOCK_TTL_MS = 5 * 60 * 1000;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos-kiosk.ts"],"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 { posTipFromPercent, posTipProblem, type PosReceiptChannel } from './commerce-pos'\nimport { modifierOptionPriceCents, type ModifierSelection, type ProductModifierGroup } from './product-modifiers'\n\n/*==========================================\n * THE SELF-SERVICE KIOSK (AGL-3623).\n *\n * A register's second kind of paired screen: where the customer display\n * (AGL-3608) mirrors the cashier's basket, a kiosk lets the customer build\n * their own order — a product grid with categories and modifiers, a cart, a\n * tip, payment on the register's card reader or Tap to Pay, or \"pay at\n * counter\", which sends the order to the register's queue for a cashier.\n *\n * It pairs exactly like a display (the same six-digit code and the same\n * hashed device token, with `mode: 'kiosk'` on both), and it never holds a\n * staff session: every request carries the device token and the server\n * prices everything. These are the shapes the kiosk route and every client\n * of it — the web kiosk and the native POS app — agree on.\n *=========================================*/\n\n/** Which kind of paired screen a device token opens. */\nexport type PosDeviceMode = 'display' | 'kiosk'\n\n/** A product as the kiosk grid shows it: no cost, no stock count, no supplier. */\nexport interface PosKioskProduct {\n id: string\n name: string\n description?: string\n imageUrl?: string\n categoryIds: string[]\n /** The product's option axes (\"Size\": S, M, L), for the variant picker. */\n options: Array<{ name: string; values: string[] }>\n variants: PosKioskVariant[]\n modifierGroups: ProductModifierGroup[]\n}\n\nexport interface PosKioskVariant {\n id: string\n /** Option selections keyed by option name; empty for the default variant. */\n options: Record<string, string>\n priceCents: number\n /** A tracked variant at or below zero whose product refuses to oversell. */\n soldOut: boolean\n}\n\nexport interface PosKioskCategory {\n id: string\n name: string\n}\n\nexport interface PosKioskCatalog {\n products: PosKioskProduct[]\n categories: PosKioskCategory[]\n /** The store's currency, lower case (`usd`). */\n currency: string\n}\n\n/** What the kiosk offers, resolved on the server for one paired register. */\nexport interface PosKioskContext {\n branding: {\n name: string\n logoUrl: string | null\n logoDarkUrl: string | null\n message: string\n }\n currency: string\n tipping: { enabled: boolean; percentages: number[] }\n payments: {\n /** A Stripe Terminal smart reader is assigned to this register. */\n reader: boolean\n /** Card-present payments are switched on for the platform (Tap to Pay needs the native app too). */\n cardPresent: boolean\n /** \"Pay at counter\" sends the order to the register's queue. */\n payAtCounter: boolean\n }\n receipts: PosReceiptChannel[]\n offerMarketing: boolean\n /** Seconds without a touch before the kiosk asks \"Still there?\". */\n idleSeconds: number\n /** Stripe test mode: a test card can be tapped from the payment screen. */\n testMode: boolean\n}\n\n/** One cart line as the kiosk sends it: ids and a count, never a price. */\nexport interface PosKioskLine {\n productId: string\n variantId?: string\n quantity: number\n modifiers?: ModifierSelection[]\n}\n\n/** A line of a priced kiosk order, as the customer's screen shows it. */\nexport interface PosKioskSaleLine {\n name: string\n variantLabel?: string\n quantity: number\n amountCents: number\n}\n\nexport type PosKioskSaleStatus =\n /** Priced and waiting for a card at the kiosk. */\n | 'open'\n /** Sent to the register's queue; a cashier takes payment. */\n | 'queued'\n | 'paid'\n | 'voided'\n\n/** A kiosk order as its own screen reads it back. */\nexport interface PosKioskSale {\n orderId: string\n /** The order number the customer is called by. */\n number: number\n status: PosKioskSaleStatus\n lines: PosKioskSaleLine[]\n itemsCents: number\n discountCents: number\n taxCents: number\n totalCents: number\n tipCents: number\n paidCents: number\n dueCents: number\n /** The card payment in flight, if any. */\n payment: { id: string; status: string; failureMessage?: string } | null\n}\n\n/** Seconds without a touch before the kiosk asks \"Still there?\", by default. */\nexport const POS_KIOSK_IDLE_SECONDS_DEFAULT = 90\nexport const POS_KIOSK_IDLE_SECONDS_MIN = 30\nexport const POS_KIOSK_IDLE_SECONDS_MAX = 600\n\n/** How long \"Still there?\" waits before the kiosk clears itself. */\nexport const POS_KIOSK_IDLE_WARNING_SECONDS = 20\n\n/** The order-number screen returns to the start after this long. */\nexport const POS_KIOSK_DONE_SECONDS = 15\n\n/** Most lines one kiosk order carries. */\nexport const POS_KIOSK_MAX_LINES = 40\n\n/** Most of one line a customer may order at a kiosk. */\nexport const POS_KIOSK_MAX_QUANTITY = 20\n\n/** Most products the kiosk grid lists in one category. */\nexport const POS_KIOSK_CATALOG_LIMIT = 200\n\n/** Wrong staff PINs a kiosk takes before it locks its unlock screen. */\nexport const POS_KIOSK_UNLOCK_MAX_ATTEMPTS = 5\n\n/** How long a kiosk's unlock screen stays locked after too many wrong PINs. */\nexport const POS_KIOSK_UNLOCK_LOCKOUT_MS = 15 * 60 * 1000\n\n/** How long a staff unlock keeps the kiosk's settings open. */\nexport const POS_KIOSK_UNLOCK_TTL_MS = 5 * 60 * 1000\n\nconst ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/\n\n/**\n * The cart as the kiosk may send it, or why not. Ids are shape-checked and\n * quantities bounded here; everything else — whether the product exists, is\n * for sale, what it costs and whether its modifiers are valid — is the sale\n * route's to decide from the product documents.\n */\nexport function sanitizePosKioskLines(\n raw: unknown,\n): { ok: true; lines: PosKioskLine[] } | { ok: false; error: string } {\n if (!Array.isArray(raw) || raw.length === 0) return { ok: false, error: 'Your cart is empty.' }\n if (raw.length > POS_KIOSK_MAX_LINES) {\n return { ok: false, error: `An order can have at most ${POS_KIOSK_MAX_LINES} items.` }\n }\n const lines: PosKioskLine[] = []\n for (const entry of raw as Array<Record<string, unknown>>) {\n const productId = String(entry?.['productId'] ?? '')\n const variantId = entry?.['variantId'] == null ? '' : String(entry['variantId'])\n const quantity = Number(entry?.['quantity'])\n if (!ID_PATTERN.test(productId) || (variantId && !ID_PATTERN.test(variantId))) {\n return { ok: false, error: 'An item in your cart is no longer available.' }\n }\n if (!Number.isInteger(quantity) || quantity < 1 || quantity > POS_KIOSK_MAX_QUANTITY) {\n return { ok: false, error: `Order 1 to ${POS_KIOSK_MAX_QUANTITY} of each item.` }\n }\n const rawModifiers = Array.isArray(entry?.['modifiers']) ? (entry['modifiers'] as unknown[]) : []\n if (rawModifiers.length > 200) return { ok: false, error: 'Too many choices on one item.' }\n const modifiers: ModifierSelection[] = []\n for (const pick of rawModifiers as Array<Record<string, unknown>>) {\n const groupId = String(pick?.['groupId'] ?? '')\n const optionId = String(pick?.['optionId'] ?? '')\n if (!ID_PATTERN.test(groupId) || !ID_PATTERN.test(optionId)) {\n return { ok: false, error: 'A choice on an item is no longer offered.' }\n }\n modifiers.push({ groupId, optionId })\n }\n lines.push({\n productId,\n ...(variantId ? { variantId } : {}),\n quantity,\n ...(modifiers.length ? { modifiers } : {}),\n })\n }\n return { ok: true, lines }\n}\n\n/**\n * The tip a kiosk customer chose, recomputed from the server's own figure\n * for what is being paid: a percentage only from the store's presets, a\n * custom amount bounded like every register tip. Null when the choice is\n * not one the store offers.\n */\nexport function posKioskTipCents(\n choice: unknown,\n input: { baseCents: number; enabled: boolean; percentages: readonly number[]; percent?: unknown; cents?: unknown },\n): number | null {\n if (choice === undefined || choice === null || choice === 'none') return 0\n if (!input.enabled) return null\n if (choice === 'percent') {\n const percent = Math.round(Number(input.percent))\n if (!input.percentages.includes(percent)) return null\n return posTipFromPercent(input.baseCents, percent)\n }\n if (choice === 'custom') {\n const cents = Math.round(Number(input.cents))\n return posTipProblem(cents, input.baseCents) ? null : cents\n }\n return null\n}\n\n/** The idle timeout a merchant set, bounded. */\nexport function posKioskIdleSeconds(raw: unknown): number {\n const value = Math.round(Number(raw))\n if (!Number.isFinite(value) || value <= 0) return POS_KIOSK_IDLE_SECONDS_DEFAULT\n return Math.min(POS_KIOSK_IDLE_SECONDS_MAX, Math.max(POS_KIOSK_IDLE_SECONDS_MIN, value))\n}\n\n/**\n * The kiosk's estimate of its cart, from the catalog prices it was given —\n * shown while the customer shops and never sent. The order is priced again,\n * with tax, by the server when they check out.\n */\nexport function posKioskEstimateCents(\n lines: readonly PosKioskLine[],\n products: readonly PosKioskProduct[],\n): number {\n let total = 0\n for (const line of lines) {\n const product = products.find((candidate) => candidate.id === line.productId)\n if (!product) continue\n const variant =\n product.variants.find((candidate) => candidate.id === line.variantId) ?? product.variants[0]\n if (!variant) continue\n const extra = (line.modifiers ?? []).reduce((sum, pick) => {\n const group = product.modifierGroups.find((candidate) => candidate.id === pick.groupId)\n const option = group?.options.find((candidate) => candidate.id === pick.optionId)\n // A choice priced by variant adds its price on this one (AGL-4100).\n return sum + (option ? modifierOptionPriceCents(option, variant.id) : 0)\n }, 0)\n total += (variant.priceCents + extra) * line.quantity\n }\n return total\n}\n"],"names":["posTipFromPercent","posTipProblem","modifierOptionPriceCents","POS_KIOSK_IDLE_SECONDS_DEFAULT","POS_KIOSK_IDLE_SECONDS_MIN","POS_KIOSK_IDLE_SECONDS_MAX","POS_KIOSK_IDLE_WARNING_SECONDS","POS_KIOSK_DONE_SECONDS","POS_KIOSK_MAX_LINES","POS_KIOSK_MAX_QUANTITY","POS_KIOSK_CATALOG_LIMIT","POS_KIOSK_UNLOCK_MAX_ATTEMPTS","POS_KIOSK_UNLOCK_LOCKOUT_MS","POS_KIOSK_UNLOCK_TTL_MS","ID_PATTERN","sanitizePosKioskLines","raw","Array","isArray","length","ok","error","lines","entry","productId","String","variantId","quantity","Number","test","isInteger","rawModifiers","modifiers","pick","groupId","optionId","push","posKioskTipCents","choice","input","undefined","enabled","percent","Math","round","percentages","includes","baseCents","cents","posKioskIdleSeconds","value","isFinite","min","max","posKioskEstimateCents","products","total","line","product","find","candidate","id","variant","variants","extra","reduce","sum","group","modifierGroups","option","options","priceCents"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,EAAEC,aAAa,QAAgC,oBAAgB;AACzF,SAASC,wBAAwB,QAA2D,yBAAqB;AA2HjH,8EAA8E,GAC9E,OAAO,MAAMC,iCAAiC,GAAE;AAChD,OAAO,MAAMC,6BAA6B,GAAE;AAC5C,OAAO,MAAMC,6BAA6B,IAAG;AAE7C,kEAAkE,GAClE,OAAO,MAAMC,iCAAiC,GAAE;AAEhD,kEAAkE,GAClE,OAAO,MAAMC,yBAAyB,GAAE;AAExC,wCAAwC,GACxC,OAAO,MAAMC,sBAAsB,GAAE;AAErC,sDAAsD,GACtD,OAAO,MAAMC,yBAAyB,GAAE;AAExC,wDAAwD,GACxD,OAAO,MAAMC,0BAA0B,IAAG;AAE1C,sEAAsE,GACtE,OAAO,MAAMC,gCAAgC,EAAC;AAE9C,6EAA6E,GAC7E,OAAO,MAAMC,8BAA8B,KAAK,KAAK,KAAI;AAEzD,6DAA6D,GAC7D,OAAO,MAAMC,0BAA0B,IAAI,KAAK,KAAI;AAEpD,MAAMC,aAAa;AAEnB;;;;;CAKC,GACD,OAAO,SAASC,sBACdC,GAAY;IAEZ,IAAI,CAACC,MAAMC,OAAO,CAACF,QAAQA,IAAIG,MAAM,KAAK,GAAG,OAAO;QAAEC,IAAI;QAAOC,OAAO;IAAsB;IAC9F,IAAIL,IAAIG,MAAM,GAAGX,qBAAqB;QACpC,OAAO;YAAEY,IAAI;YAAOC,OAAO,CAAC,0BAA0B,EAAEb,oBAAoB,OAAO,CAAC;QAAC;IACvF;IACA,MAAMc,QAAwB,EAAE;IAChC,KAAK,MAAMC,SAASP,IAAuC;;QACzD,MAAMQ,YAAYC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S;QACd,MAAME,QAAQ,EAACP,kBAAAA,KAAKzB,SAAS,YAAdyB,kBAAkB,EAAE,EAAEQ,MAAM,CAAC,CAACC,KAAKjC;YAChD,MAAMkC,QAAQT,QAAQU,cAAc,CAACT,IAAI,CAAC,CAACC,YAAcA,UAAUC,EAAE,KAAK5B,KAAKC,OAAO;YACtF,MAAMmC,SAASF,yBAAAA,MAAOG,OAAO,CAACX,IAAI,CAAC,CAACC,YAAcA,UAAUC,EAAE,KAAK5B,KAAKE,QAAQ;YAChF,oEAAoE;YACpE,OAAO+B,MAAOG,CAAAA,SAASnE,yBAAyBmE,QAAQP,QAAQD,EAAE,IAAI,CAAA;QACxE,GAAG;QACHL,SAAS,AAACM,CAAAA,QAAQS,UAAU,GAAGP,KAAI,IAAKP,KAAK9B,QAAQ;IACvD;IACA,OAAO6B;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos-kiosk.ts"],"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 { posTipFromPercent, posTipProblem, type PosReceiptChannel } from './commerce-pos'\nimport { modifierOptionPriceCents, type ModifierSelection, type ProductModifierGroup } from './product-modifiers'\n\n/*==========================================\n * THE SELF-SERVICE KIOSK (AGL-3623).\n *\n * A register's second kind of paired screen: where the customer display\n * (AGL-3608) mirrors the cashier's basket, a kiosk lets the customer build\n * their own order — a product grid with categories and modifiers, a cart, a\n * tip, payment on the register's card reader or Tap to Pay, or \"pay at\n * counter\", which sends the order to the register's queue for a cashier.\n *\n * It pairs exactly like a display (the same six-digit code and the same\n * hashed device token, with `mode: 'kiosk'` on both), and it never holds a\n * staff session: every request carries the device token and the server\n * prices everything. These are the shapes the kiosk route and every client\n * of it — the web kiosk and the native POS app — agree on.\n *=========================================*/\n\n/** Which kind of paired screen a device token opens. */\nexport type PosDeviceMode = 'display' | 'kiosk'\n\n/** A product as the kiosk grid shows it: no cost, no stock count, no supplier. */\nexport interface PosKioskProduct {\n id: string\n name: string\n description?: string\n imageUrl?: string\n categoryIds: string[]\n /** The product's option axes (\"Size\": S, M, L), for the variant picker. */\n options: Array<{ name: string; values: string[] }>\n variants: PosKioskVariant[]\n modifierGroups: ProductModifierGroup[]\n}\n\nexport interface PosKioskVariant {\n id: string\n /** Option selections keyed by option name; empty for the default variant. */\n options: Record<string, string>\n priceCents: number\n /** A tracked variant at or below zero whose product refuses to oversell. */\n soldOut: boolean\n}\n\nexport interface PosKioskCategory {\n id: string\n name: string\n}\n\nexport interface PosKioskCatalog {\n products: PosKioskProduct[]\n categories: PosKioskCategory[]\n /** The store's currency, lower case (`usd`). */\n currency: string\n /**\n * Set when the store has more to offer than this answer lists, so the menu\n * offers a search that reaches the rest. Absent on an answer that lists\n * everything, which is every catalog the menu can show whole.\n */\n truncated?: boolean\n}\n\n/** What the kiosk offers, resolved on the server for one paired register. */\nexport interface PosKioskContext {\n branding: {\n name: string\n logoUrl: string | null\n logoDarkUrl: string | null\n message: string\n }\n currency: string\n tipping: { enabled: boolean; percentages: number[] }\n payments: {\n /** A Stripe Terminal smart reader is assigned to this register. */\n reader: boolean\n /** Card-present payments are switched on for the platform (Tap to Pay needs the native app too). */\n cardPresent: boolean\n /** \"Pay at counter\" sends the order to the register's queue. */\n payAtCounter: boolean\n }\n receipts: PosReceiptChannel[]\n offerMarketing: boolean\n /** Seconds without a touch before the kiosk asks \"Still there?\". */\n idleSeconds: number\n /** Stripe test mode: a test card can be tapped from the payment screen. */\n testMode: boolean\n}\n\n/** One cart line as the kiosk sends it: ids and a count, never a price. */\nexport interface PosKioskLine {\n productId: string\n variantId?: string\n quantity: number\n modifiers?: ModifierSelection[]\n}\n\n/** A line of a priced kiosk order, as the customer's screen shows it. */\nexport interface PosKioskSaleLine {\n name: string\n variantLabel?: string\n quantity: number\n amountCents: number\n}\n\nexport type PosKioskSaleStatus =\n /** Priced and waiting for a card at the kiosk. */\n | 'open'\n /** Sent to the register's queue; a cashier takes payment. */\n | 'queued'\n | 'paid'\n | 'voided'\n\n/** A kiosk order as its own screen reads it back. */\nexport interface PosKioskSale {\n orderId: string\n /** The order number the customer is called by. */\n number: number\n status: PosKioskSaleStatus\n lines: PosKioskSaleLine[]\n itemsCents: number\n discountCents: number\n taxCents: number\n totalCents: number\n tipCents: number\n paidCents: number\n dueCents: number\n /** The card payment in flight, if any. */\n payment: { id: string; status: string; failureMessage?: string } | null\n}\n\n/** Seconds without a touch before the kiosk asks \"Still there?\", by default. */\nexport const POS_KIOSK_IDLE_SECONDS_DEFAULT = 90\nexport const POS_KIOSK_IDLE_SECONDS_MIN = 30\nexport const POS_KIOSK_IDLE_SECONDS_MAX = 600\n\n/** How long \"Still there?\" waits before the kiosk clears itself. */\nexport const POS_KIOSK_IDLE_WARNING_SECONDS = 20\n\n/** The order-number screen returns to the start after this long. */\nexport const POS_KIOSK_DONE_SECONDS = 15\n\n/** Most lines one kiosk order carries. */\nexport const POS_KIOSK_MAX_LINES = 40\n\n/** Most of one line a customer may order at a kiosk. */\nexport const POS_KIOSK_MAX_QUANTITY = 20\n\n/** Most products the kiosk grid lists at once, for the whole menu, a category or a search. */\nexport const POS_KIOSK_CATALOG_LIMIT = 200\n\n/** Wrong staff PINs a kiosk takes before it locks its unlock screen. */\nexport const POS_KIOSK_UNLOCK_MAX_ATTEMPTS = 5\n\n/** How long a kiosk's unlock screen stays locked after too many wrong PINs. */\nexport const POS_KIOSK_UNLOCK_LOCKOUT_MS = 15 * 60 * 1000\n\n/** How long a staff unlock keeps the kiosk's settings open. */\nexport const POS_KIOSK_UNLOCK_TTL_MS = 5 * 60 * 1000\n\nconst ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/\n\n/**\n * The cart as the kiosk may send it, or why not. Ids are shape-checked and\n * quantities bounded here; everything else — whether the product exists, is\n * for sale, what it costs and whether its modifiers are valid — is the sale\n * route's to decide from the product documents.\n */\nexport function sanitizePosKioskLines(\n raw: unknown,\n): { ok: true; lines: PosKioskLine[] } | { ok: false; error: string } {\n if (!Array.isArray(raw) || raw.length === 0) return { ok: false, error: 'Your cart is empty.' }\n if (raw.length > POS_KIOSK_MAX_LINES) {\n return { ok: false, error: `An order can have at most ${POS_KIOSK_MAX_LINES} items.` }\n }\n const lines: PosKioskLine[] = []\n for (const entry of raw as Array<Record<string, unknown>>) {\n const productId = String(entry?.['productId'] ?? '')\n const variantId = entry?.['variantId'] == null ? '' : String(entry['variantId'])\n const quantity = Number(entry?.['quantity'])\n if (!ID_PATTERN.test(productId) || (variantId && !ID_PATTERN.test(variantId))) {\n return { ok: false, error: 'An item in your cart is no longer available.' }\n }\n if (!Number.isInteger(quantity) || quantity < 1 || quantity > POS_KIOSK_MAX_QUANTITY) {\n return { ok: false, error: `Order 1 to ${POS_KIOSK_MAX_QUANTITY} of each item.` }\n }\n const rawModifiers = Array.isArray(entry?.['modifiers']) ? (entry['modifiers'] as unknown[]) : []\n if (rawModifiers.length > 200) return { ok: false, error: 'Too many choices on one item.' }\n const modifiers: ModifierSelection[] = []\n for (const pick of rawModifiers as Array<Record<string, unknown>>) {\n const groupId = String(pick?.['groupId'] ?? '')\n const optionId = String(pick?.['optionId'] ?? '')\n if (!ID_PATTERN.test(groupId) || !ID_PATTERN.test(optionId)) {\n return { ok: false, error: 'A choice on an item is no longer offered.' }\n }\n modifiers.push({ groupId, optionId })\n }\n lines.push({\n productId,\n ...(variantId ? { variantId } : {}),\n quantity,\n ...(modifiers.length ? { modifiers } : {}),\n })\n }\n return { ok: true, lines }\n}\n\n/**\n * The tip a kiosk customer chose, recomputed from the server's own figure\n * for what is being paid: a percentage only from the store's presets, a\n * custom amount bounded like every register tip. Null when the choice is\n * not one the store offers.\n */\nexport function posKioskTipCents(\n choice: unknown,\n input: { baseCents: number; enabled: boolean; percentages: readonly number[]; percent?: unknown; cents?: unknown },\n): number | null {\n if (choice === undefined || choice === null || choice === 'none') return 0\n if (!input.enabled) return null\n if (choice === 'percent') {\n const percent = Math.round(Number(input.percent))\n if (!input.percentages.includes(percent)) return null\n return posTipFromPercent(input.baseCents, percent)\n }\n if (choice === 'custom') {\n const cents = Math.round(Number(input.cents))\n return posTipProblem(cents, input.baseCents) ? null : cents\n }\n return null\n}\n\n/** The idle timeout a merchant set, bounded. */\nexport function posKioskIdleSeconds(raw: unknown): number {\n const value = Math.round(Number(raw))\n if (!Number.isFinite(value) || value <= 0) return POS_KIOSK_IDLE_SECONDS_DEFAULT\n return Math.min(POS_KIOSK_IDLE_SECONDS_MAX, Math.max(POS_KIOSK_IDLE_SECONDS_MIN, value))\n}\n\n/**\n * The kiosk's estimate of its cart, from the catalog prices it was given —\n * shown while the customer shops and never sent. The order is priced again,\n * with tax, by the server when they check out.\n */\nexport function posKioskEstimateCents(\n lines: readonly PosKioskLine[],\n products: readonly PosKioskProduct[],\n): number {\n let total = 0\n for (const line of lines) {\n const product = products.find((candidate) => candidate.id === line.productId)\n if (!product) continue\n const variant =\n product.variants.find((candidate) => candidate.id === line.variantId) ?? product.variants[0]\n if (!variant) continue\n const extra = (line.modifiers ?? []).reduce((sum, pick) => {\n const group = product.modifierGroups.find((candidate) => candidate.id === pick.groupId)\n const option = group?.options.find((candidate) => candidate.id === pick.optionId)\n // A choice priced by variant adds its price on this one (AGL-4100).\n return sum + (option ? modifierOptionPriceCents(option, variant.id) : 0)\n }, 0)\n total += (variant.priceCents + extra) * line.quantity\n }\n return total\n}\n"],"names":["posTipFromPercent","posTipProblem","modifierOptionPriceCents","POS_KIOSK_IDLE_SECONDS_DEFAULT","POS_KIOSK_IDLE_SECONDS_MIN","POS_KIOSK_IDLE_SECONDS_MAX","POS_KIOSK_IDLE_WARNING_SECONDS","POS_KIOSK_DONE_SECONDS","POS_KIOSK_MAX_LINES","POS_KIOSK_MAX_QUANTITY","POS_KIOSK_CATALOG_LIMIT","POS_KIOSK_UNLOCK_MAX_ATTEMPTS","POS_KIOSK_UNLOCK_LOCKOUT_MS","POS_KIOSK_UNLOCK_TTL_MS","ID_PATTERN","sanitizePosKioskLines","raw","Array","isArray","length","ok","error","lines","entry","productId","String","variantId","quantity","Number","test","isInteger","rawModifiers","modifiers","pick","groupId","optionId","push","posKioskTipCents","choice","input","undefined","enabled","percent","Math","round","percentages","includes","baseCents","cents","posKioskIdleSeconds","value","isFinite","min","max","posKioskEstimateCents","products","total","line","product","find","candidate","id","variant","variants","extra","reduce","sum","group","modifierGroups","option","options","priceCents"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,EAAEC,aAAa,QAAgC,oBAAgB;AACzF,SAASC,wBAAwB,QAA2D,yBAAqB;AAiIjH,8EAA8E,GAC9E,OAAO,MAAMC,iCAAiC,GAAE;AAChD,OAAO,MAAMC,6BAA6B,GAAE;AAC5C,OAAO,MAAMC,6BAA6B,IAAG;AAE7C,kEAAkE,GAClE,OAAO,MAAMC,iCAAiC,GAAE;AAEhD,kEAAkE,GAClE,OAAO,MAAMC,yBAAyB,GAAE;AAExC,wCAAwC,GACxC,OAAO,MAAMC,sBAAsB,GAAE;AAErC,sDAAsD,GACtD,OAAO,MAAMC,yBAAyB,GAAE;AAExC,4FAA4F,GAC5F,OAAO,MAAMC,0BAA0B,IAAG;AAE1C,sEAAsE,GACtE,OAAO,MAAMC,gCAAgC,EAAC;AAE9C,6EAA6E,GAC7E,OAAO,MAAMC,8BAA8B,KAAK,KAAK,KAAI;AAEzD,6DAA6D,GAC7D,OAAO,MAAMC,0BAA0B,IAAI,KAAK,KAAI;AAEpD,MAAMC,aAAa;AAEnB;;;;;CAKC,GACD,OAAO,SAASC,sBACdC,GAAY;IAEZ,IAAI,CAACC,MAAMC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,wBAEaD;QALf,MAAMC,UAAUH,SAASI,IAAI,CAAC,CAACC,YAAcA,UAAUC,EAAE,KAAKJ,KAAKjC,SAAS;QAC5E,IAAI,CAACkC,SAAS;QACd,MAAMI,WACJJ,yBAAAA,QAAQK,QAAQ,CAACJ,IAAI,CAAC,CAACC,YAAcA,UAAUC,EAAE,KAAKJ,KAAK/B,SAAS,aAApEgC,yBAAyEA,QAAQK,QAAQ,CAAC,EAAE;QAC9F,IAAI,CAACD,SAAS;QACd,MAAME,QAAQ,EAACP,kBAAAA,KAAKzB,SAAS,YAAdyB,kBAAkB,EAAE,EAAEQ,MAAM,CAAC,CAACC,KAAKjC;YAChD,MAAMkC,QAAQT,QAAQU,cAAc,CAACT,IAAI,CAAC,CAACC,YAAcA,UAAUC,EAAE,KAAK5B,KAAKC,OAAO;YACtF,MAAMmC,SAASF,yBAAAA,MAAOG,OAAO,CAACX,IAAI,CAAC,CAACC,YAAcA,UAAUC,EAAE,KAAK5B,KAAKE,QAAQ;YAChF,oEAAoE;YACpE,OAAO+B,MAAOG,CAAAA,SAASnE,yBAAyBmE,QAAQP,QAAQD,EAAE,IAAI,CAAA;QACxE,GAAG;QACHL,SAAS,AAACM,CAAAA,QAAQS,UAAU,GAAGP,KAAI,IAAKP,KAAK9B,QAAQ;IACvD;IACA,OAAO6B;AACT"}
|
|
@@ -63,6 +63,10 @@ export declare const POS_MAX_MODIFIER_OPTIONS = 20;
|
|
|
63
63
|
export declare const POS_MAX_MODIFIER_PRICE_CENTS = 100000;
|
|
64
64
|
/** Why a product's modifier groups cannot be saved, or null when they can. */
|
|
65
65
|
export declare function modifierGroupsProblem(groups: unknown): string | null;
|
|
66
|
+
/** How a variant is named in a choice's price list, in the editor and in an import file. */
|
|
67
|
+
export declare function variantPriceLabel(variant: {
|
|
68
|
+
options?: Record<string, string>;
|
|
69
|
+
}): string;
|
|
66
70
|
/** The product's groups, or none when they are missing or malformed. */
|
|
67
71
|
export declare function productModifierGroups(product: {
|
|
68
72
|
modifierGroups?: unknown;
|
|
@@ -88,6 +88,11 @@ function modifierPriceIsValid(price) {
|
|
|
88
88
|
}
|
|
89
89
|
return null;
|
|
90
90
|
}
|
|
91
|
+
/** How a variant is named in a choice's price list, in the editor and in an import file. */ export function variantPriceLabel(variant) {
|
|
92
|
+
var _variant_options;
|
|
93
|
+
const values = Object.values((_variant_options = variant.options) != null ? _variant_options : {}).filter(Boolean);
|
|
94
|
+
return values.length ? values.join(' / ') : 'Default';
|
|
95
|
+
}
|
|
91
96
|
/** The product's groups, or none when they are missing or malformed. */ export function productModifierGroups(product) {
|
|
92
97
|
const groups = product == null ? void 0 : product.modifierGroups;
|
|
93
98
|
if (!Array.isArray(groups) || modifierGroupsProblem(groups)) return [];
|