@aglyn/plugins-commerce 1.33.2 → 1.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/cart.js +3 -1
  3. package/src/lib/components/cart.js.map +1 -1
  4. package/src/lib/components/console/catalog-organization-card.component.js +82 -69
  5. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  6. package/src/lib/components/console/discounts-card.component.js +46 -25
  7. package/src/lib/components/console/discounts-card.component.js.map +1 -1
  8. package/src/lib/components/console/gift-cards-card.component.js +81 -55
  9. package/src/lib/components/console/gift-cards-card.component.js.map +1 -1
  10. package/src/lib/components/console/host-coupons-card.component.js +36 -25
  11. package/src/lib/components/console/host-coupons-card.component.js.map +1 -1
  12. package/src/lib/components/console/locations-card.component.js +53 -32
  13. package/src/lib/components/console/locations-card.component.js.map +1 -1
  14. package/src/lib/components/console/member-posts-card.component.js +35 -32
  15. package/src/lib/components/console/member-posts-card.component.js.map +1 -1
  16. package/src/lib/components/console/new-store-tax-question.component.d.ts +17 -0
  17. package/src/lib/components/console/new-store-tax-question.component.js +197 -0
  18. package/src/lib/components/console/new-store-tax-question.component.js.map +1 -0
  19. package/src/lib/components/console/payments-settings-card.component.js +132 -5
  20. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  21. package/src/lib/components/console/pos/pos-api.d.ts +6 -0
  22. package/src/lib/components/console/pos/pos-api.js.map +1 -1
  23. package/src/lib/components/console/pos/pos-tax-notice.component.d.ts +21 -0
  24. package/src/lib/components/console/pos/pos-tax-notice.component.js +59 -0
  25. package/src/lib/components/console/pos/pos-tax-notice.component.js.map +1 -0
  26. package/src/lib/components/console/pos-page.component.js +65 -17
  27. package/src/lib/components/console/pos-page.component.js.map +1 -1
  28. package/src/lib/components/console/registers-card.component.js +21 -13
  29. package/src/lib/components/console/registers-card.component.js.map +1 -1
  30. package/src/lib/components/console/reviews-moderation-card.component.js +108 -68
  31. package/src/lib/components/console/reviews-moderation-card.component.js.map +1 -1
  32. package/src/lib/components/console/site-member-purchases.component.js +5 -3
  33. package/src/lib/components/console/site-member-purchases.component.js.map +1 -1
  34. package/src/lib/components/console/subscription-detail-dialog.component.d.ts +2 -0
  35. package/src/lib/components/console/subscription-detail-dialog.component.js +1 -1
  36. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
  37. package/src/lib/components/console/subscriptions-card.component.js +13 -5
  38. package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
  39. package/src/lib/components/console/suppliers-card.component.js +47 -40
  40. package/src/lib/components/console/suppliers-card.component.js.map +1 -1
  41. package/src/lib/components/product-choice-cards.js +2 -1
  42. package/src/lib/components/product-choice-cards.js.map +1 -1
  43. package/src/lib/components/product-detail.js +9 -4
  44. package/src/lib/components/product-detail.js.map +1 -1
  45. package/src/lib/components/product-grid.js +3 -1
  46. package/src/lib/components/product-grid.js.map +1 -1
  47. package/src/lib/components/related-products.js +2 -1
  48. package/src/lib/components/related-products.js.map +1 -1
  49. package/src/lib/components/store-image-sizing.d.ts +46 -0
  50. package/src/lib/components/store-image-sizing.js +53 -0
  51. package/src/lib/components/store-image-sizing.js.map +1 -0
  52. package/src/lib/components/wishlist.js +2 -1
  53. package/src/lib/components/wishlist.js.map +1 -1
  54. package/src/lib/declarations.console-server.js +10 -0
  55. package/src/lib/declarations.console-server.js.map +1 -1
  56. package/src/lib/model/commerce-tax-step.d.ts +123 -0
  57. package/src/lib/model/commerce-tax-step.js +185 -0
  58. package/src/lib/model/commerce-tax-step.js.map +1 -0
  59. package/src/lib/model/index.d.ts +1 -0
  60. package/src/lib/model/index.js +1 -0
  61. package/src/lib/model/index.js.map +1 -1
  62. package/src/lib/model/payments-setup-status.d.ts +40 -0
  63. package/src/lib/model/payments-setup-status.js +63 -0
  64. package/src/lib/model/payments-setup-status.js.map +1 -1
  65. package/src/lib/model/subscription-view.d.ts +19 -0
  66. package/src/lib/model/subscription-view.js +16 -0
  67. package/src/lib/model/subscription-view.js.map +1 -1
  68. package/src/lib/model/tap-to-pay-launch.d.ts +103 -0
  69. package/src/lib/model/tap-to-pay-launch.js +148 -0
  70. package/src/lib/model/tap-to-pay-launch.js.map +1 -0
  71. package/src/lib/plugin.js +12 -0
  72. package/src/lib/plugin.js.map +1 -1
  73. package/src/lib/server/billing-webhook.js +140 -116
  74. package/src/lib/server/billing-webhook.js.map +1 -1
  75. package/src/lib/server/checkout.js +15 -4
  76. package/src/lib/server/checkout.js.map +1 -1
  77. package/src/lib/server/connect-return.d.ts +83 -0
  78. package/src/lib/server/connect-return.js +105 -0
  79. package/src/lib/server/connect-return.js.map +1 -0
  80. package/src/lib/server/connect.d.ts +18 -0
  81. package/src/lib/server/connect.js +60 -6
  82. package/src/lib/server/connect.js.map +1 -1
  83. package/src/lib/server/new-store-tax.d.ts +10 -0
  84. package/src/lib/server/new-store-tax.js +43 -0
  85. package/src/lib/server/new-store-tax.js.map +1 -0
  86. package/src/lib/server/pos-payment.js +3 -2
  87. package/src/lib/server/pos-payment.js.map +1 -1
  88. package/src/lib/server/pos-tax-step.d.ts +43 -0
  89. package/src/lib/server/pos-tax-step.js +55 -0
  90. package/src/lib/server/pos-tax-step.js.map +1 -0
  91. package/src/lib/server/pos-terminal-connection-token.d.ts +10 -1
  92. package/src/lib/server/pos-terminal-connection-token.js +18 -7
  93. package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
  94. package/src/lib/server/pos-terminal.d.ts +9 -0
  95. package/src/lib/server/pos-terminal.js +17 -1
  96. package/src/lib/server/pos-terminal.js.map +1 -1
  97. package/src/lib/server/tap-to-pay-launch-admin.d.ts +18 -0
  98. package/src/lib/server/tap-to-pay-launch-admin.js +204 -0
  99. package/src/lib/server/tap-to-pay-launch-admin.js.map +1 -0
  100. package/src/lib/server/tap-to-pay-launch.d.ts +114 -0
  101. package/src/lib/server/tap-to-pay-launch.js +408 -0
  102. package/src/lib/server/tap-to-pay-launch.js.map +1 -0
  103. package/src/lib/server.js +15 -0
  104. package/src/lib/server.js.map +1 -1
@@ -46,7 +46,11 @@ import SubscriptionDetailDialog from "./subscription-detail-dialog.component.js"
46
46
  ]), where('interval', '==', interval), where('livemode', '==', true)), {
47
47
  subscriptions: count(),
48
48
  totalCents: sum('totals.totalCents'),
49
- taxCents: sum('totals.taxCents')
49
+ taxCents: sum('totals.taxCents'),
50
+ // A subscription sold in another currency carries the difference to
51
+ // the store currency (AGL-4257); every other one lacks the field.
52
+ baseDeltaTotalCents: sum('baseTotalsDelta.totalCents'),
53
+ baseDeltaTaxCents: sum('baseTotalsDelta.taxCents')
50
54
  });
51
55
  const counted = (status)=>getAggregateFromServer(query(subscriptions, where('status', '==', status), where('livemode', '==', true)), {
52
56
  subscriptions: count()
@@ -60,8 +64,11 @@ import SubscriptionDetailDialog from "./subscription-detail-dialog.component.js"
60
64
  counted('past_due')
61
65
  ]);
62
66
  const figure = (value)=>Number(value) || 0;
67
+ // In the store currency: the charged sums plus what turns the foreign ones
68
+ // into the store's.
69
+ const storeSum = (data, key)=>figure(data[`${key.toLowerCase()}Cents`]) + figure(data[`baseDelta${key}Cents`]);
63
70
  return {
64
- monthlyRecurringCents: CommerceModel.monthlyRecurringCents(monthly.data().totalCents, monthly.data().taxCents, 'month') + CommerceModel.monthlyRecurringCents(yearly.data().totalCents, yearly.data().taxCents, 'year'),
71
+ monthlyRecurringCents: CommerceModel.monthlyRecurringCents(storeSum(monthly.data(), 'Total'), storeSum(monthly.data(), 'Tax'), 'month') + CommerceModel.monthlyRecurringCents(storeSum(yearly.data(), 'Total'), storeSum(yearly.data(), 'Tax'), 'year'),
65
72
  payingCount: figure(monthly.data().subscriptions) + figure(yearly.data().subscriptions),
66
73
  trialCount: figure(trials.data().subscriptions),
67
74
  pastDueCount: figure(pastDue.data().subscriptions)
@@ -93,7 +100,8 @@ import SubscriptionDetailDialog from "./subscription-detail-dialog.component.js"
93
100
  hostId
94
101
  ]);
95
102
  const currency = String((_ref = store == null ? void 0 : store.currency) != null ? _ref : 'USD').toUpperCase();
96
- const money = (cents)=>CommerceModel.formatOrderMoney(cents, currency);
103
+ // A subscription is billed in its own currency (AGL-4257); the store's otherwise.
104
+ const money = (cents, code)=>CommerceModel.formatOrderMoney(cents, code || currency);
97
105
  useEffect(()=>{
98
106
  let live = true;
99
107
  setSummaryFailed(false);
@@ -216,10 +224,10 @@ import SubscriptionDetailDialog from "./subscription-detail-dialog.component.js"
216
224
  var _row_paidCents;
217
225
  var _row_totals;
218
226
  const dateText = CommerceModel.subscriptionDateText(CommerceModel.subscriptionDateLine(row));
219
- const price = ((_row_totals = row.totals) == null ? void 0 : _row_totals.totalCents) != null ? `${money(Number(row.totals.totalCents) || 0)}${CommerceModel.subscriptionIntervalSuffix(row.interval)}` : '';
227
+ const price = ((_row_totals = row.totals) == null ? void 0 : _row_totals.totalCents) != null ? `${money(Number(row.totals.totalCents) || 0, row.currency)}${CommerceModel.subscriptionIntervalSuffix(row.interval)}` : '';
220
228
  // A trial's opening invoice is $0: nothing has been paid yet,
221
229
  // so the row says nothing rather than "$0.00 paid so far".
222
- const paid = Number((_row_paidCents = row.paidCents) != null ? _row_paidCents : 0) > 0 ? `${money(Number(row.paidCents) || 0)} paid so far` : '';
230
+ const paid = Number((_row_paidCents = row.paidCents) != null ? _row_paidCents : 0) > 0 ? `${money(Number(row.paidCents) || 0, row.currency)} paid so far` : '';
223
231
  return /*#__PURE__*/ _jsxs(ListItemButton, {
224
232
  onClick: ()=>setSelectedId(row.$id),
225
233
  divider: true,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/subscriptions-card.component.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\n'use client'\n\nimport * as CommerceModel from '../../model'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n Chip,\n List,\n ListItemButton,\n ListItemText,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n getAggregateFromServer,\n limit,\n orderBy,\n query,\n sum,\n count,\n where,\n type Firestore,\n} from 'firebase/firestore'\nimport { useSearchParams } from 'next/navigation'\nimport { useEffect, useRef, useState } from 'react'\nimport {\n useFirestore,\n useFirestoreDoc,\n usePagedCollection,\n} from '@aglyn/tenant-feature-instance'\nimport CommerceStatTile from './commerce-stat-tile.component'\nimport SubscriptionDetailDialog, { type SubscriptionRow } from './subscription-detail-dialog.component'\n\nexport interface SubscriptionsCardProps {\n hostId: string\n}\n\n/** The query key that opens one subscription on arrival: the renewal notification's link. */\nexport const SUBSCRIPTIONS_SUBSCRIPTION_PARAM = 'subscription'\n\ntype SubscriptionFilter = (typeof CommerceModel.SUBSCRIPTION_FILTER_STATUSES)[number] | 'all'\n\nexport interface SubscriptionsSummary {\n monthlyRecurringCents: number\n payingCount: number\n trialCount: number\n pastDueCount: number\n}\n\n/**\n * The figures above the list, from aggregation queries: what a store with\n * thousands of subscribers pays for is a handful of index reads, never one\n * read per subscriber.\n *\n * Monthly recurring revenue is summed per billing interval, because a sum\n * cannot divide a yearly price by twelve on the way. Only LIVE-mode\n * subscriptions count: a test checkout is a rehearsal, and the order\n * analytics leave it out for the same reason (`order-analytics.ts`). A\n * subscription with no stored `interval` is left out of the figure rather\n * than guessed at; every sale since AGL-1732 stores one.\n */\nexport async function loadSubscriptionsSummary(\n firestore: Firestore,\n hostId: string,\n): Promise<SubscriptionsSummary> {\n const subscriptions = collection(firestore, 'hosts', hostId, 'subscriptions')\n const paying = (interval: CommerceModel.SubscriptionBillingInterval) =>\n getAggregateFromServer(\n query(\n subscriptions,\n where('status', 'in', [...CommerceModel.SUBSCRIPTION_PAYING_STATUSES]),\n where('interval', '==', interval),\n where('livemode', '==', true),\n ),\n {\n subscriptions: count(),\n totalCents: sum('totals.totalCents'),\n taxCents: sum('totals.taxCents'),\n },\n )\n const counted = (status: string) =>\n getAggregateFromServer(\n query(subscriptions, where('status', '==', status), where('livemode', '==', true)),\n { subscriptions: count() },\n )\n // AGL-1715-EXEMPT: four separate count queries, one per figure on the card;\n // the status words are each query's own filter, not a membership set.\n const [monthly, yearly, trials, pastDue] = await Promise.all([\n paying('month'),\n paying('year'),\n counted('trialing'),\n counted('past_due'),\n ])\n const figure = (value: unknown) => Number(value) || 0\n return {\n monthlyRecurringCents:\n CommerceModel.monthlyRecurringCents(\n monthly.data().totalCents,\n monthly.data().taxCents,\n 'month',\n ) +\n CommerceModel.monthlyRecurringCents(\n yearly.data().totalCents,\n yearly.data().taxCents,\n 'year',\n ),\n payingCount: figure(monthly.data().subscriptions) + figure(yearly.data().subscriptions),\n trialCount: figure(trials.data().subscriptions),\n pastDueCount: figure(pastDue.data().subscriptions),\n }\n}\n\n/**\n * Subscriptions (AGL-4191): every subscription on the site, newest first, and\n * what they add up to.\n *\n * Until this, a merchant could see subscriptions only one person at a time, in\n * a site member's Purchases: a digital or service subscription writes no order\n * per cycle, so Orders never showed them either.\n *\n * THE STATUS FILTER IS THE QUERY, as on Returns: `status == X` ordered by\n * `createdAtMs` descending, served by the `subscriptions(status ASC,\n * createdAtMs DESC)` composite; \"All\" is the single-field order alone. Opening\n * a row shows the subscription's invoices; `?subscription={id}` opens one on\n * arrival, which is where the renewal notification links.\n */\nexport function SubscriptionsCard(props: SubscriptionsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const [filter, setFilter] = useState<SubscriptionFilter>('all')\n const [selectedId, setSelectedId] = useState<string | null>(null)\n const [summary, setSummary] = useState<SubscriptionsSummary | null>(null)\n const [summaryFailed, setSummaryFailed] = useState(false)\n\n const { data: store } = useFirestoreDoc<Record<string, unknown>>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n const currency = String(store?.currency ?? 'USD').toUpperCase()\n const money = (cents: number) => CommerceModel.formatOrderMoney(cents, currency)\n\n useEffect(() => {\n let live = true\n setSummaryFailed(false)\n loadSubscriptionsSummary(firestore, hostId)\n .then((next) => {\n if (live) setSummary(next)\n })\n .catch((error) => {\n console.error('Subscriptions summary unavailable', error)\n if (live) setSummaryFailed(true)\n })\n return () => {\n live = false\n }\n }, [firestore, hostId])\n\n const {\n rows,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n status,\n } = usePagedCollection<SubscriptionRow>(\n (pageLimit) =>\n query(\n collection(firestore, 'hosts', hostId, 'subscriptions'),\n ...(filter === 'all' ? [] : [where('status', '==', filter)]),\n orderBy('createdAtMs', 'desc'),\n limit(pageLimit),\n ),\n [firestore, hostId, filter],\n { idField: '$id' },\n )\n\n const searchParams = useSearchParams()\n const seededId = searchParams?.get(SUBSCRIPTIONS_SUBSCRIPTION_PARAM) ?? null\n // Once per id, so closing the dialog does not reopen it on the next render.\n const seeded = useRef<string | null>(null)\n useEffect(() => {\n if (!seededId || seeded.current === seededId) return\n seeded.current = seededId\n setSelectedId(seededId)\n }, [seededId])\n\n // A linked subscription need not be on this page, so it is read by id.\n const onPage = selectedId ? (rows.find((row) => row.$id === selectedId) ?? null) : null\n const { data: linked } = useFirestoreDoc<Omit<SubscriptionRow, '$id'>>(\n () =>\n selectedId && !onPage\n ? doc(firestore, 'hosts', hostId, 'subscriptions', selectedId)\n : null,\n [firestore, hostId, selectedId, Boolean(onPage)],\n )\n const selected: SubscriptionRow | null =\n onPage ?? (selectedId && linked ? { ...linked, $id: selectedId } : null)\n\n return (\n <CardDisplay\n header={'Subscriptions'}\n help={pluginDocsHelp('catalog', { anchor: '#subscriptions-list' })}\n HeaderProps={{\n action: (\n <TextField\n label=\"Status\"\n value={filter}\n onChange={(event) => setFilter(event.target.value as SubscriptionFilter)}\n size=\"small\"\n select\n sx={{ minWidth: 160 }}\n >\n <MenuItem value=\"all\">{'All'}</MenuItem>\n {CommerceModel.SUBSCRIPTION_FILTER_STATUSES.map((value) => (\n <MenuItem key={value} value={value}>\n {CommerceModel.subscriptionStatusLabel(value)}\n </MenuItem>\n ))}\n </TextField>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Stack direction=\"row\" useFlexGap sx={{ flexWrap: 'wrap', columnGap: 4, rowGap: 1.5 }}>\n <CommerceStatTile\n label=\"Monthly recurring revenue\"\n value={summary ? money(summary.monthlyRecurringCents) : summaryFailed ? '—' : '…'}\n />\n <CommerceStatTile\n label=\"Paying subscribers\"\n value={summary ? String(summary.payingCount) : summaryFailed ? '—' : '…'}\n />\n <CommerceStatTile\n label=\"In a free trial\"\n value={summary ? String(summary.trialCount) : summaryFailed ? '—' : '…'}\n />\n <CommerceStatTile\n label=\"Past due\"\n value={summary ? String(summary.pastDueCount) : summaryFailed ? '—' : '…'}\n />\n </Stack>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {summaryFailed\n ? 'These figures could not be loaded. The list below is unaffected.'\n : 'Monthly recurring revenue counts active and past-due subscriptions paid in live mode, with a yearly plan counted as a twelfth and tax left out.'}\n </Typography>\n {rows.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {status === 'error'\n ? // The rules gate subscriptions on the order book's permission.\n 'Subscriptions take the \"See orders and webhooks\" permission on this site.'\n : status === 'loading'\n ? 'Loading subscriptions…'\n : filter === 'all'\n ? 'No subscriptions yet. When someone subscribes to a monthly or yearly product, they appear here.'\n : `No ${CommerceModel.subscriptionStatusLabel(filter).toLowerCase()} subscriptions.`}\n </Typography>\n ) : (\n <List disablePadding>\n {rows.map((row) => {\n const dateText = CommerceModel.subscriptionDateText(\n CommerceModel.subscriptionDateLine(row),\n )\n const price =\n row.totals?.totalCents != null\n ? `${money(Number(row.totals.totalCents) || 0)}${CommerceModel.subscriptionIntervalSuffix(row.interval)}`\n : ''\n // A trial's opening invoice is $0: nothing has been paid yet,\n // so the row says nothing rather than \"$0.00 paid so far\".\n const paid =\n Number(row.paidCents ?? 0) > 0\n ? `${money(Number(row.paidCents) || 0)} paid so far`\n : ''\n return (\n <ListItemButton key={row.$id} onClick={() => setSelectedId(row.$id)} divider>\n <ListItemText\n primary={`${row.customerName || row.customerEmail || 'Unknown customer'} · ${CommerceModel.subscriptionPlanName(row)}`}\n secondary={[price, dateText, paid].filter(Boolean).join(' · ')}\n />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', flexShrink: 0 }}>\n {row.livemode === false ? (\n <Chip label=\"Test\" size=\"small\" variant=\"outlined\" />\n ) : null}\n <Chip\n label={CommerceModel.subscriptionStatusLabel(row.status)}\n size=\"small\"\n color={CommerceModel.subscriptionStatusColor(row.status)}\n variant=\"outlined\"\n />\n </Stack>\n </ListItemButton>\n )\n })}\n </List>\n )}\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={rows.length}\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n </Stack>\n {selected ? (\n <SubscriptionDetailDialog\n hostId={hostId}\n subscription={selected}\n currency={currency}\n onClose={() => setSelectedId(null)}\n />\n ) : null}\n </CardDisplay>\n )\n}\nSubscriptionsCard.displayName = 'SubscriptionsCard'\n\nexport default SubscriptionsCard\n"],"names":["CommerceModel","CardDisplay","ListPagination","pluginDocsHelp","Chip","List","ListItemButton","ListItemText","MenuItem","Stack","TextField","Typography","collection","doc","getAggregateFromServer","limit","orderBy","query","sum","count","where","useSearchParams","useEffect","useRef","useState","useFirestore","useFirestoreDoc","usePagedCollection","CommerceStatTile","SubscriptionDetailDialog","SUBSCRIPTIONS_SUBSCRIPTION_PARAM","loadSubscriptionsSummary","firestore","hostId","subscriptions","paying","interval","SUBSCRIPTION_PAYING_STATUSES","totalCents","taxCents","counted","status","monthly","yearly","trials","pastDue","Promise","all","figure","value","Number","monthlyRecurringCents","data","payingCount","trialCount","pastDueCount","SubscriptionsCard","props","rows","filter","setFilter","selectedId","setSelectedId","summary","setSummary","summaryFailed","setSummaryFailed","store","currency","String","toUpperCase","money","cents","formatOrderMoney","live","then","next","catch","error","console","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","searchParams","seededId","get","seeded","current","onPage","find","row","$id","linked","Boolean","selected","header","help","anchor","HeaderProps","action","label","onChange","event","target","size","select","sx","minWidth","SUBSCRIPTION_FILTER_STATUSES","map","subscriptionStatusLabel","contentGutterX","contentGutterY","spacing","direction","useFlexGap","flexWrap","columnGap","rowGap","variant","color","length","toLowerCase","disablePadding","dateText","subscriptionDateText","subscriptionDateLine","price","totals","subscriptionIntervalSuffix","paid","paidCents","onClick","divider","primary","customerName","customerEmail","subscriptionPlanName","secondary","join","alignItems","flexShrink","livemode","subscriptionStatusColor","rowCount","onPageChange","onPageSizeChange","subscription","onClose","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,cAAc,QAAQ,eAAc;AAC7C,SACEC,IAAI,EACJC,IAAI,EACJC,cAAc,EACdC,YAAY,EACZC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,GAAG,EACHC,sBAAsB,EACtBC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,GAAG,EACHC,KAAK,EACLC,KAAK,QAEA,qBAAoB;AAC3B,SAASC,eAAe,QAAQ,kBAAiB;AACjD,SAASC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AACnD,SACEC,YAAY,EACZC,eAAe,EACfC,kBAAkB,QACb,iCAAg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AAK,GAAG,YAAY,CAAC,GAClD;4BACN,qBACE,MAACjI;gCAA6BkI,SAAS,IAAM1E,cAAcgC,IAAIC,GAAG;gCAAG0C,OAAO;;kDAC1E,KAAClI;wCACCmI,SAAS,GAAG5C,IAAI6C,YAAY,IAAI7C,IAAI8C,aAAa,IAAI,mBAAmB,GAAG,EAAE5I,cAAc6I,oBAAoB,CAAC/C,MAAM;wCACtHgD,WAAW;4CAACX;4CAAOH;4CAAUM;yCAAK,CAAC3E,MAAM,CAACsC,SAAS8C,IAAI,CAAC;;kDAE1D,MAACtI;wCAAM6G,WAAU;wCAAMD,SAAS;wCAAGP,IAAI;4CAAEkC,YAAY;4CAAUC,YAAY;wCAAE;;4CAC1EnD,IAAIoD,QAAQ,KAAK,sBAChB,KAAC9I;gDAAKoG,OAAM;gDAAOI,MAAK;gDAAQe,SAAQ;iDACtC;0DACJ,KAACvH;gDACCoG,OAAOxG,cAAckH,uBAAuB,CAACpB,IAAIrD,MAAM;gDACvDmE,MAAK;gDACLgB,OAAO5H,cAAcmJ,uBAAuB,CAACrD,IAAIrD,MAAM;gDACvDkF,SAAQ;;;;;+BAbO7B,IAAIC,GAAG;wBAkBhC;;kCAGJ,KAAC7F;wBACC+E,MAAMA;wBACNE,UAAUA;wBACViE,UAAU1F,KAAKmE,MAAM;wBACrB7C,SAASA;wBACTqE,cAAcnE;wBACdoE,kBAAkBlE;;;;YAGrBc,yBACC,KAACrE;gBACCI,QAAQA;gBACRsH,cAAcrD;gBACd9B,UAAUA;gBACVoF,SAAS,IAAM1F,cAAc;iBAE7B;;;AAGV;AACAN,kBAAkBiG,WAAW,GAAG;AAEhC,eAAejG,kBAAiB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/subscriptions-card.component.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\n'use client'\n\nimport * as CommerceModel from '../../model'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n Chip,\n List,\n ListItemButton,\n ListItemText,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n getAggregateFromServer,\n limit,\n orderBy,\n query,\n sum,\n count,\n where,\n type Firestore,\n} from 'firebase/firestore'\nimport { useSearchParams } from 'next/navigation'\nimport { useEffect, useRef, useState } from 'react'\nimport {\n useFirestore,\n useFirestoreDoc,\n usePagedCollection,\n} from '@aglyn/tenant-feature-instance'\nimport CommerceStatTile from './commerce-stat-tile.component'\nimport SubscriptionDetailDialog, { type SubscriptionRow } from './subscription-detail-dialog.component'\n\nexport interface SubscriptionsCardProps {\n hostId: string\n}\n\n/** The query key that opens one subscription on arrival: the renewal notification's link. */\nexport const SUBSCRIPTIONS_SUBSCRIPTION_PARAM = 'subscription'\n\ntype SubscriptionFilter = (typeof CommerceModel.SUBSCRIPTION_FILTER_STATUSES)[number] | 'all'\n\nexport interface SubscriptionsSummary {\n monthlyRecurringCents: number\n payingCount: number\n trialCount: number\n pastDueCount: number\n}\n\n/**\n * The figures above the list, from aggregation queries: what a store with\n * thousands of subscribers pays for is a handful of index reads, never one\n * read per subscriber.\n *\n * Monthly recurring revenue is summed per billing interval, because a sum\n * cannot divide a yearly price by twelve on the way. Only LIVE-mode\n * subscriptions count: a test checkout is a rehearsal, and the order\n * analytics leave it out for the same reason (`order-analytics.ts`). A\n * subscription with no stored `interval` is left out of the figure rather\n * than guessed at; every sale since AGL-1732 stores one.\n */\nexport async function loadSubscriptionsSummary(\n firestore: Firestore,\n hostId: string,\n): Promise<SubscriptionsSummary> {\n const subscriptions = collection(firestore, 'hosts', hostId, 'subscriptions')\n const paying = (interval: CommerceModel.SubscriptionBillingInterval) =>\n getAggregateFromServer(\n query(\n subscriptions,\n where('status', 'in', [...CommerceModel.SUBSCRIPTION_PAYING_STATUSES]),\n where('interval', '==', interval),\n where('livemode', '==', true),\n ),\n {\n subscriptions: count(),\n totalCents: sum('totals.totalCents'),\n taxCents: sum('totals.taxCents'),\n // A subscription sold in another currency carries the difference to\n // the store currency (AGL-4257); every other one lacks the field.\n baseDeltaTotalCents: sum('baseTotalsDelta.totalCents'),\n baseDeltaTaxCents: sum('baseTotalsDelta.taxCents'),\n },\n )\n const counted = (status: string) =>\n getAggregateFromServer(\n query(subscriptions, where('status', '==', status), where('livemode', '==', true)),\n { subscriptions: count() },\n )\n // AGL-1715-EXEMPT: four separate count queries, one per figure on the card;\n // the status words are each query's own filter, not a membership set.\n const [monthly, yearly, trials, pastDue] = await Promise.all([\n paying('month'),\n paying('year'),\n counted('trialing'),\n counted('past_due'),\n ])\n const figure = (value: unknown) => Number(value) || 0\n // In the store currency: the charged sums plus what turns the foreign ones\n // into the store's.\n const storeSum = (data: Record<string, unknown>, key: 'Total' | 'Tax') =>\n figure(data[`${key.toLowerCase()}Cents`]) + figure(data[`baseDelta${key}Cents`])\n return {\n monthlyRecurringCents:\n CommerceModel.monthlyRecurringCents(\n storeSum(monthly.data(), 'Total'),\n storeSum(monthly.data(), 'Tax'),\n 'month',\n ) +\n CommerceModel.monthlyRecurringCents(\n storeSum(yearly.data(), 'Total'),\n storeSum(yearly.data(), 'Tax'),\n 'year',\n ),\n payingCount: figure(monthly.data().subscriptions) + figure(yearly.data().subscriptions),\n trialCount: figure(trials.data().subscriptions),\n pastDueCount: figure(pastDue.data().subscriptions),\n }\n}\n\n/**\n * Subscriptions (AGL-4191): every subscription on the site, newest first, and\n * what they add up to.\n *\n * Until this, a merchant could see subscriptions only one person at a time, in\n * a site member's Purchases: a digital or service subscription writes no order\n * per cycle, so Orders never showed them either.\n *\n * THE STATUS FILTER IS THE QUERY, as on Returns: `status == X` ordered by\n * `createdAtMs` descending, served by the `subscriptions(status ASC,\n * createdAtMs DESC)` composite; \"All\" is the single-field order alone. Opening\n * a row shows the subscription's invoices; `?subscription={id}` opens one on\n * arrival, which is where the renewal notification links.\n */\nexport function SubscriptionsCard(props: SubscriptionsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const [filter, setFilter] = useState<SubscriptionFilter>('all')\n const [selectedId, setSelectedId] = useState<string | null>(null)\n const [summary, setSummary] = useState<SubscriptionsSummary | null>(null)\n const [summaryFailed, setSummaryFailed] = useState(false)\n\n const { data: store } = useFirestoreDoc<Record<string, unknown>>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n const currency = String(store?.currency ?? 'USD').toUpperCase()\n // A subscription is billed in its own currency (AGL-4257); the store's otherwise.\n const money = (cents: number, code?: string) => CommerceModel.formatOrderMoney(cents, code || currency)\n\n useEffect(() => {\n let live = true\n setSummaryFailed(false)\n loadSubscriptionsSummary(firestore, hostId)\n .then((next) => {\n if (live) setSummary(next)\n })\n .catch((error) => {\n console.error('Subscriptions summary unavailable', error)\n if (live) setSummaryFailed(true)\n })\n return () => {\n live = false\n }\n }, [firestore, hostId])\n\n const {\n rows,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n status,\n } = usePagedCollection<SubscriptionRow>(\n (pageLimit) =>\n query(\n collection(firestore, 'hosts', hostId, 'subscriptions'),\n ...(filter === 'all' ? [] : [where('status', '==', filter)]),\n orderBy('createdAtMs', 'desc'),\n limit(pageLimit),\n ),\n [firestore, hostId, filter],\n { idField: '$id' },\n )\n\n const searchParams = useSearchParams()\n const seededId = searchParams?.get(SUBSCRIPTIONS_SUBSCRIPTION_PARAM) ?? null\n // Once per id, so closing the dialog does not reopen it on the next render.\n const seeded = useRef<string | null>(null)\n useEffect(() => {\n if (!seededId || seeded.current === seededId) return\n seeded.current = seededId\n setSelectedId(seededId)\n }, [seededId])\n\n // A linked subscription need not be on this page, so it is read by id.\n const onPage = selectedId ? (rows.find((row) => row.$id === selectedId) ?? null) : null\n const { data: linked } = useFirestoreDoc<Omit<SubscriptionRow, '$id'>>(\n () =>\n selectedId && !onPage\n ? doc(firestore, 'hosts', hostId, 'subscriptions', selectedId)\n : null,\n [firestore, hostId, selectedId, Boolean(onPage)],\n )\n const selected: SubscriptionRow | null =\n onPage ?? (selectedId && linked ? { ...linked, $id: selectedId } : null)\n\n return (\n <CardDisplay\n header={'Subscriptions'}\n help={pluginDocsHelp('catalog', { anchor: '#subscriptions-list' })}\n HeaderProps={{\n action: (\n <TextField\n label=\"Status\"\n value={filter}\n onChange={(event) => setFilter(event.target.value as SubscriptionFilter)}\n size=\"small\"\n select\n sx={{ minWidth: 160 }}\n >\n <MenuItem value=\"all\">{'All'}</MenuItem>\n {CommerceModel.SUBSCRIPTION_FILTER_STATUSES.map((value) => (\n <MenuItem key={value} value={value}>\n {CommerceModel.subscriptionStatusLabel(value)}\n </MenuItem>\n ))}\n </TextField>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Stack direction=\"row\" useFlexGap sx={{ flexWrap: 'wrap', columnGap: 4, rowGap: 1.5 }}>\n <CommerceStatTile\n label=\"Monthly recurring revenue\"\n value={summary ? money(summary.monthlyRecurringCents) : summaryFailed ? '—' : '…'}\n />\n <CommerceStatTile\n label=\"Paying subscribers\"\n value={summary ? String(summary.payingCount) : summaryFailed ? '—' : '…'}\n />\n <CommerceStatTile\n label=\"In a free trial\"\n value={summary ? String(summary.trialCount) : summaryFailed ? '—' : '…'}\n />\n <CommerceStatTile\n label=\"Past due\"\n value={summary ? String(summary.pastDueCount) : summaryFailed ? '—' : '…'}\n />\n </Stack>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {summaryFailed\n ? 'These figures could not be loaded. The list below is unaffected.'\n : 'Monthly recurring revenue counts active and past-due subscriptions paid in live mode, with a yearly plan counted as a twelfth and tax left out.'}\n </Typography>\n {rows.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {status === 'error'\n ? // The rules gate subscriptions on the order book's permission.\n 'Subscriptions take the \"See orders and webhooks\" permission on this site.'\n : status === 'loading'\n ? 'Loading subscriptions…'\n : filter === 'all'\n ? 'No subscriptions yet. When someone subscribes to a monthly or yearly product, they appear here.'\n : `No ${CommerceModel.subscriptionStatusLabel(filter).toLowerCase()} subscriptions.`}\n </Typography>\n ) : (\n <List disablePadding>\n {rows.map((row) => {\n const dateText = CommerceModel.subscriptionDateText(\n CommerceModel.subscriptionDateLine(row),\n )\n const price =\n row.totals?.totalCents != null\n ? `${money(Number(row.totals.totalCents) || 0, row.currency)}${CommerceModel.subscriptionIntervalSuffix(row.interval)}`\n : ''\n // A trial's opening invoice is $0: nothing has been paid yet,\n // so the row says nothing rather than \"$0.00 paid so far\".\n const paid =\n Number(row.paidCents ?? 0) > 0\n ? `${money(Number(row.paidCents) || 0, row.currency)} paid so far`\n : ''\n return (\n <ListItemButton key={row.$id} onClick={() => setSelectedId(row.$id)} divider>\n <ListItemText\n primary={`${row.customerName || row.customerEmail || 'Unknown customer'} · ${CommerceModel.subscriptionPlanName(row)}`}\n secondary={[price, dateText, paid].filter(Boolean).join(' · ')}\n />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', flexShrink: 0 }}>\n {row.livemode === false ? (\n <Chip label=\"Test\" size=\"small\" variant=\"outlined\" />\n ) : null}\n <Chip\n label={CommerceModel.subscriptionStatusLabel(row.status)}\n size=\"small\"\n color={CommerceModel.subscriptionStatusColor(row.status)}\n variant=\"outlined\"\n />\n </Stack>\n </ListItemButton>\n )\n })}\n </List>\n )}\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={rows.length}\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n </Stack>\n {selected ? (\n <SubscriptionDetailDialog\n hostId={hostId}\n subscription={selected}\n currency={currency}\n onClose={() => setSelectedId(null)}\n />\n ) : null}\n </CardDisplay>\n )\n}\nSubscriptionsCard.displayName = 'SubscriptionsCard'\n\nexport default SubscriptionsCard\n"],"names":["CommerceModel","CardDisplay","ListPagination","pluginDocsHelp","Chip","List","ListItemButton","ListItemText","MenuItem","Stack","TextField","Typography","collection","doc","getAggregateFromServer","limit","orderBy","query","sum","count","where","useSearchParams","useEffect","useRef","useState","useFirestore","useFirestoreDoc","usePagedCollection","CommerceStatTile","SubscriptionDetailDialog","SUBSCRIPTIONS_SUBSCRIPTION_PARAM","loadSubscriptionsSummary","firestore","hostId","subscriptions","paying","interval","SUBSCRIPTION_PAYING_STATUSES","totalCents","taxCents","baseDeltaTotalCents","baseDeltaTaxCents","counted","status","monthly","yearly","trials","pastDue","Promise","all","figure","value","Number","storeSum","data","key","toLowerCase","monthlyRecurringCents","payingCount","trialCount","pastDueCount","SubscriptionsCard","props","rows","filter","setFilter","selectedId","setSelectedId","summary","setSummary","summaryFailed","setSummaryFailed","store","currency","String","toUpperCase","money","cents","code","formatOrderMoney","live","then","next","catch","error","console","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","searchParams","seededId","get","seeded","current","onPage","find","row","$id","linked","Boolean","selected","header","help","anchor","HeaderProps","action","label","onChange","event","target","size","select","sx","minWidth","SUBSCRIPTION_FILTER_STATUSES","map","subscriptionStatusLabel","contentGutterX","contentGutterY","spacing","direction","useFlexGap","flexWrap","columnGap","rowGap","variant","color","length","disablePadding","dateText","subscriptionDateText","subscriptionDateLine","price","totals","subscriptionIntervalSuffix","paid","paidCents","onClick","divider","primary","customerName","customerEmail","subscriptionPlanName","secondary","join","alignItems","flexShrink","livemode","subscriptionStatusColor","rowCount","onPageChange","onPageSizeChange","subscription","onClose","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,W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S;wCAAGP,IAAI;4CAAEiC,YAAY;4CAAUC,YAAY;wCAAE;;4CAC1ElD,IAAImD,QAAQ,KAAK,sBAChB,KAACnJ;gDAAK0G,OAAM;gDAAOI,MAAK;gDAAQe,SAAQ;iDACtC;0DACJ,KAAC7H;gDACC0G,OAAO9G,cAAcwH,uBAAuB,CAACpB,IAAIzD,MAAM;gDACvDuE,MAAK;gDACLgB,OAAOlI,cAAcwJ,uBAAuB,CAACpD,IAAIzD,MAAM;gDACvDsF,SAAQ;;;;;+BAbO7B,IAAIC,GAAG;wBAkBhC;;kCAGJ,KAACnG;wBACCqF,MAAMA;wBACNE,UAAUA;wBACVgE,UAAU1F,KAAKoE,MAAM;wBACrB7C,SAASA;wBACToE,cAAclE;wBACdmE,kBAAkBjE;;;;YAGrBc,yBACC,KAAC3E;gBACCI,QAAQA;gBACR2H,cAAcpD;gBACd/B,UAAUA;gBACVoF,SAAS,IAAM1F,cAAc;iBAE7B;;;AAGV;AACAN,kBAAkBiG,WAAW,GAAG;AAEhC,eAAejG,kBAAiB"}
@@ -26,6 +26,8 @@ import { useCallback } from "react";
26
26
  import { useFirestore } from "@aglyn/tenant-feature-instance";
27
27
  import { collectionPage, usePagedCollection, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
28
28
  import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.component";
29
+ import { OpenableListRow } from "@aglyn/shared-ui-jsx/components/openable-list-row.component";
30
+ import { mdiDeleteOutline, mdiPencilOutline } from "@aglyn/shared-data-mdi";
29
31
  import { EntitlementGatedCard } from "./entitlement-gate.component.js";
30
32
  import { pluginDocsHelp } from "@aglyn/aglyn";
31
33
  import { heldSaveLabel, isSeedChecking, seedCheckingText, useHeldSave } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
@@ -203,47 +205,52 @@ export function SuppliersCard(props) {
203
205
  variant: "body2",
204
206
  color: "text.secondary",
205
207
  children: 'Route paid orders straight to a fulfillment partner: add a ' + 'supplier, then assign it on products.'
206
- }) : suppliers.map((supplier)=>/*#__PURE__*/ _jsxs(Stack, {
207
- direction: "row",
208
- spacing: 1,
209
- sx: {
210
- alignItems: 'center'
211
- },
212
- children: [
213
- /*#__PURE__*/ _jsxs(Stack, {
214
- sx: {
215
- flex: 1,
216
- minWidth: 0
208
+ }) : suppliers.map((supplier)=>// A row click opens the supplier's editor; every action sits in
209
+ // the row's one ⋮ menu.
210
+ /*#__PURE__*/ _jsx(OpenableListRow, {
211
+ label: supplier.name || 'Supplier',
212
+ onOpen: ()=>setDraft(supplierDraftOf(supplier)),
213
+ items: [
214
+ {
215
+ key: 'edit',
216
+ label: 'Edit',
217
+ icon: {
218
+ path: mdiPencilOutline.path
217
219
  },
218
- children: [
219
- /*#__PURE__*/ _jsx(Typography, {
220
- variant: "body2",
221
- noWrap: true,
222
- children: supplier.name
223
- }),
224
- /*#__PURE__*/ _jsx(Typography, {
225
- variant: "caption",
226
- color: "text.secondary",
227
- noWrap: true,
228
- children: [
229
- supplier.email,
230
- supplier.webhookUrl
231
- ].filter(Boolean).join(' · ') || 'No delivery method set'
232
- })
233
- ]
234
- }),
235
- /*#__PURE__*/ _jsx(Button, {
236
- size: "small",
237
- onClick: ()=>setDraft(supplierDraftOf(supplier)),
238
- children: 'Edit'
239
- }),
240
- /*#__PURE__*/ _jsx(Button, {
241
- size: "small",
242
- color: "error",
243
- onClick: handleDelete(supplier),
244
- children: 'Remove'
245
- })
246
- ]
220
+ onClick: ()=>setDraft(supplierDraftOf(supplier))
221
+ },
222
+ {
223
+ key: 'remove',
224
+ label: 'Remove',
225
+ icon: {
226
+ path: mdiDeleteOutline.path
227
+ },
228
+ destructive: true,
229
+ onClick: ()=>void handleDelete(supplier)()
230
+ }
231
+ ],
232
+ children: /*#__PURE__*/ _jsxs(Stack, {
233
+ sx: {
234
+ flex: 1,
235
+ minWidth: 0
236
+ },
237
+ children: [
238
+ /*#__PURE__*/ _jsx(Typography, {
239
+ variant: "body2",
240
+ noWrap: true,
241
+ children: supplier.name
242
+ }),
243
+ /*#__PURE__*/ _jsx(Typography, {
244
+ variant: "caption",
245
+ color: "text.secondary",
246
+ noWrap: true,
247
+ children: [
248
+ supplier.email,
249
+ supplier.webhookUrl
250
+ ].filter(Boolean).join(' · ') || 'No delivery method set'
251
+ })
252
+ ]
253
+ })
247
254
  }, supplier.$id)),
248
255
  suppliers.length === 0 && page === 0 ? null : /*#__PURE__*/ _jsx(ListPagination, {
249
256
  page: page,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/suppliers-card.component.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'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport * as CommerceModel from '../../model'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, deleteDoc, doc, setDoc } from 'firebase/firestore'\nimport { useCallback } from 'react'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport {\n collectionPage,\n usePagedCollection,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { EntitlementGatedCard } from './entitlement-gate.component'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n heldSaveLabel,\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { useSeedDraft } from '@aglyn/tenant-feature-instance/hooks/use-seed-draft'\n\nexport interface SuppliersCardProps {\n hostId: string\n}\n\n/**\n * Dropship suppliers (AGL-289): paid orders whose product points at a\n * supplier notify it by email and/or HMAC-signed webhook, and the\n * supplier posts tracking back through a token link — no Aglyn account\n * needed. Assign suppliers per product in the product editor.\n *\n * Gated on `dropshipRouting` since AGL-2080. `server/billing-webhook.ts:2474`\n * enforces it, so an unentitled org could create suppliers, assign them to\n * products, and watch every paid order silently fail to route — a supplier\n * that looks configured and never hears about an order.\n */\n\nconst suppliersHelp = pluginDocsHelp('dropshipSuppliers', { anchor: '#add-a-supplier' })\n\n/** A stored supplier as the dialog edits it. */\nfunction supplierDraftOf(\n supplier: any,\n): CommerceModel.HostSupplier & { id: string | null } {\n return {\n id: supplier.$id,\n name: supplier.name ?? '',\n email: supplier.email ?? '',\n webhookUrl: supplier.webhookUrl ?? '',\n webhookSecret: supplier.webhookSecret ?? '',\n }\n}\n\nexport function SuppliersCard(props: SuppliersCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const {\n status: suppliersStatus,\n /**\n * The list this dialog is seeded from is unconfirmed by the server\n * (AGL-1358). Editing a supplier copies the whole stored row into\n * `draft` and writes all of it back, so a cached seed can restore a\n * ROTATED `webhookSecret` — the supplier keeps signing with a key we\n * meant to retire, and nothing anywhere reports it.\n */\n fromCache: suppliersFromCache,\n listen: suppliersListen,\n rows: suppliers,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<any>(\n /*\n * SERVER-PAGED, and ordered (AGL-2501).\n *\n * `limit(50)` alone is answered in DOCUMENT-ID order, and suppliers are\n * created with a generated id — so the fifty were a pseudo-random sample\n * and the fifty-first was not merely unrendered, it was UNREACHABLE. A\n * merchant with sixty fulfillment partners saw fifty of them and nothing\n * said which.\n *\n * This one really can be paged by the query, unlike the cards that carry a\n * duplicate-name check or a count over the whole set: nothing here is\n * derived from rows off the page. Suppliers are assigned to products by\n * document id in the product editor, and the empty state and the row list\n * are the only consumers.\n *\n * `collectionPage` orders on the document NAME, which cannot be absent —\n * `orderBy('name')` would HIDE every supplier saved without one rather\n * than mis-sorting the list, and `/api/hosts/resources` validates no field\n * for presence.\n */\n (pageLimit) =>\n collectionPage(\n collection(firestore, 'hosts', hostId, 'suppliers'),\n pageLimit,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n /*\n * The dialog's draft, kept as EDITS over the supplier as the list has it\n * now (AGL-4047): opened from the cache's row, the server's copy replaces\n * it under every field nobody touched (a rotated `webhookSecret` among\n * them), and Save is held until it has.\n */\n const [draft, setDraft] = useSeedDraft<\n CommerceModel.HostSupplier & { id: string | null }\n >((opened) => {\n const row = opened.id\n ? suppliers.find((supplier: any) => supplier.$id === opened.id)\n : undefined\n return row ? supplierDraftOf(row) : undefined\n })\n const checking =\n Boolean(draft?.id) &&\n isSeedChecking({\n fromCache: suppliersFromCache,\n unreadable: suppliersStatus === 'error',\n })\n\n const handleSave = useCallback(async () => {\n if (!draft?.name.trim()) return\n const { id, ...data } = draft\n /**\n * Refuse an EDIT whose seed the server never confirmed (AGL-1358).\n *\n * This write has no options argument at all, so it is a full document\n * replace of a payload copied wholesale off the listener — `merge`\n * would not have helped anyway, since every field is present. The one\n * that matters is `webhookSecret`: rotate it somewhere else, come back\n * to a console still serving the old row out of `persistentLocalCache`,\n * rename the supplier, and the retired secret is stored again.\n *\n * Only the edit path is guarded. A NEW supplier is built from blanks at\n * a fresh uid and can overwrite nothing, so refusing it would be a false\n * positive on a path that is never unsafe — and this guard stands in\n * front of the ordinary save.\n *\n * The guard WRAPS the write: an early return is a shape you can keep\n * while losing the protection.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'supplier',\n unreadable: Boolean(id) && suppliersStatus === 'error',\n fromCache: Boolean(id) && suppliersFromCache,\n listen: suppliersListen,\n },\n async () => {\n await setDoc(\n doc(\n firestore,\n 'hosts',\n hostId,\n 'suppliers',\n id ?? Aglyn.createResourceUid(),\n ),\n {\n ...data,\n name: draft.name.trim().slice(0, 80),\n },\n )\n },\n )\n // A refusal keeps the dialog open with what was typed. A save that\n // silently does nothing sends the user back to retype a form that will\n // be refused again just as quietly.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setDraft(null)\n enqueueSnackbar('Supplier saved', { variant: 'success', persist: false })\n }, [\n setDraft,\n draft,\n firestore,\n hostId,\n enqueueSnackbar,\n suppliersFromCache,\n suppliersListen,\n suppliersStatus,\n ])\n\n const handleDelete = useCallback(\n (supplier: any) => async () => {\n const confirmed = await confirm({\n title: 'Remove this supplier?',\n description:\n `Products assigned to \"${supplier.name}\" stop routing; orders ` +\n 'already sent are unaffected.',\n confirmationText: 'Remove',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await deleteDoc(doc(firestore, 'hosts', hostId, 'suppliers', supplier.$id))\n },\n [confirm, firestore, hostId],\n )\n\n // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const held = useHeldSave(handleSave, {\n checking,\n subject: 'supplier',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n\n return (\n <EntitlementGatedCard\n help={suppliersHelp}\n hostId={hostId}\n feature=\"dropshipRouting\"\n header={'Dropship suppliers'}\n upsell={\n 'Dropship routing forwards each paid order to the right supplier ' +\n 'by email or signed webhook, and takes tracking numbers back ' +\n `without the supplier needing an ${Aglyn.PLATFORM_BRAND_NAME} account.`\n }\n >\n <CardDisplay\n header={'Dropship suppliers'}\n help={suppliersHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {suppliers.length === 0 && page === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Route paid orders straight to a fulfillment partner: add a ' +\n 'supplier, then assign it on products.'}\n </Typography>\n ) : (\n suppliers.map((supplier: any) => (\n <Stack\n key={supplier.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {supplier.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {[supplier.email, supplier.webhookUrl]\n .filter(Boolean)\n .join(' · ') || 'No delivery method set'}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n onClick={() => setDraft(supplierDraftOf(supplier))}\n >\n {'Edit'}\n </Button>\n <Button size=\"small\" color=\"error\" onClick={handleDelete(supplier)}>\n {'Remove'}\n </Button>\n </Stack>\n ))\n )}\n {suppliers.length === 0 && page === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={suppliers.length}\n // No `count`: this is a server window, and nobody knows the total\n // without paying to read it. `hasMore` is the probe row's answer.\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n setDraft({ id: null, name: '', email: '', webhookUrl: '', webhookSecret: '' })\n }\n >\n {'Add supplier'}\n </Button>\n </Stack>\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{draft?.id ? 'Edit supplier' : 'New supplier'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <TextField\n label=\"Name\"\n value={draft?.name ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <TextField\n label=\"Notification email\"\n value={draft?.email ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, email: event.target.value } : prev,\n )\n }\n size=\"small\"\n helperText=\"Gets order details + a tracking link per sale\"\n />\n <TextField\n label=\"Webhook URL\"\n value={draft?.webhookUrl ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, webhookUrl: event.target.value } : prev,\n )\n }\n size=\"small\"\n placeholder=\"https://…\"\n />\n <TextField\n label=\"Webhook secret\"\n value={draft?.webhookSecret ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, webhookSecret: event.target.value } : prev,\n )\n }\n size=\"small\"\n helperText=\"Payloads carry an x-aglyn-signature HMAC header\"\n />\n </DialogContent>\n <DialogActions>\n {checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {seedCheckingText('supplier')}\n </Typography>\n ) : null}\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim() || held.saving}\n onClick={held.press}\n >\n {heldSaveLabel(held, 'Save')}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n </EntitlementGatedCard>\n )\n}\nSuppliersCard.displayName = 'SuppliersCard'\n\nexport default SuppliersCard\n"],"names":["Aglyn","CardDisplay","useConfirmationContext","useSnackbar","Button","Dialog","DialogActions","DialogContent","DialogTitle","Stack","TextField","Typography","collection","deleteDoc","doc","setDoc","useCallback","useFirestore","collectionPage","usePagedCollection","writeGuardedBySeed","ListPagination","EntitlementGatedCard","pluginDocsHelp","heldSaveLabel","isSeedChecking","seedCheckingText","useHeldSave","useSeedDraft","suppliersHelp","anchor","supplierDraftOf","supplier","id","$id","name","email","webhookUrl","webhookSecret","SuppliersCard","props","hostId","firestore","enqueueSnackbar","confirm","status","suppliersStatus","fromCache","suppliersFromCache","listen","suppliersListen","rows","suppliers","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","draft","setDraft","opened","row","find","undefined","checking","Boolean","unreadable","handleSave","trim","data","verdict","subject","createResourceUid","slice","ok","message","variant","persist","handleDelete","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","catch","held","onRefused","help","feature","header","upsell","PLATFORM_BRAND_NAME","contentGutterX","contentGutterY","spacing","length","map","direction","sx","alignItems","flex","minWidth","noWrap","filter","join","size","onClick","rowCount","onPageChange","onPageSizeChange","alignSelf","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","label","value","onChange","event","prev","target","autoFocus","mt","helperText","placeholder","role","mr","disabled","saving","press","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,YAAYA,WAAW,eAAc;AAErC,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,SAAS,EAAEC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AACvE,SAASC,WAAW,QAAQ,QAAO;AACnC,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SACEC,cAAc,EACdC,kBAAkB,EAClBC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,oBAAoB,QAAQ,kCAA8B;AACnE,SAASC,cAAc,QAAQ,eAAc;AAC7C,SACEC,aAAa,EACbC,cAAc,EACdC,gBAAgB,EAChBC,WAAW,QACN,sDAAqD;AAC5D,SAASC,YAAY,QAAQ,sDAAqD;AAMlF;;;;;;;;;;CAUC,GAED,MAAMC,gBAAgBN,eAAe,qBAAqB;IAAEO,QAAQ;AAAkB;AAEtF,8CAA8C,GAC9C,SAASC,gBACPC,QAAa;QAILA,gBACCA,iBACKA,sBACGA;IALjB,OAAO;QACLC,IAAID,SAASE,GAAG;QAChBC,IAAI,GAAEH,iBAAAA,SAASG,IAAI,YAAbH,iBAAiB;QACvBI,KAAK,GAAEJ,kBAAAA,SAASI,KAAK,YAAdJ,kBAAkB;QAC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AW;;;;sCAGf,MAAC5H;;gCACE4D,yBACC,KAACvD;oCAAWmE,SAAQ;oCAAQQ,OAAM;oCAAiB8C,MAAK;oCAAS9B,IAAI;wCAAE+B,IAAI;oCAAO;8CAC/E3G,iBAAiB;qCAElB;8CACJ,KAACtB;oCAAO0G,SAAS,IAAMjD,SAAS;8CAAQ;;8CACxC,KAACzD;oCACC0E,SAAQ;oCACRQ,OAAM;oCACNgD,UAAU,EAAC1E,yBAAAA,MAAOzB,IAAI,CAACmC,IAAI,OAAMmB,KAAK8C,MAAM;oCAC5CzB,SAASrB,KAAK+C,KAAK;8CAElBhH,cAAciE,MAAM;;;;;;;;;AAOjC;AACAlD,cAAckG,WAAW,GAAG;AAE5B,eAAelG,cAAa"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/suppliers-card.component.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'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport * as CommerceModel from '../../model'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, deleteDoc, doc, setDoc } from 'firebase/firestore'\nimport { useCallback } from 'react'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport {\n collectionPage,\n usePagedCollection,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { OpenableListRow } from '@aglyn/shared-ui-jsx/components/openable-list-row.component'\nimport { mdiDeleteOutline, mdiPencilOutline } from '@aglyn/shared-data-mdi'\nimport { EntitlementGatedCard } from './entitlement-gate.component'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n heldSaveLabel,\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { useSeedDraft } from '@aglyn/tenant-feature-instance/hooks/use-seed-draft'\n\nexport interface SuppliersCardProps {\n hostId: string\n}\n\n/**\n * Dropship suppliers (AGL-289): paid orders whose product points at a\n * supplier notify it by email and/or HMAC-signed webhook, and the\n * supplier posts tracking back through a token link — no Aglyn account\n * needed. Assign suppliers per product in the product editor.\n *\n * Gated on `dropshipRouting` since AGL-2080. `server/billing-webhook.ts:2474`\n * enforces it, so an unentitled org could create suppliers, assign them to\n * products, and watch every paid order silently fail to route — a supplier\n * that looks configured and never hears about an order.\n */\n\nconst suppliersHelp = pluginDocsHelp('dropshipSuppliers', { anchor: '#add-a-supplier' })\n\n/** A stored supplier as the dialog edits it. */\nfunction supplierDraftOf(\n supplier: any,\n): CommerceModel.HostSupplier & { id: string | null } {\n return {\n id: supplier.$id,\n name: supplier.name ?? '',\n email: supplier.email ?? '',\n webhookUrl: supplier.webhookUrl ?? '',\n webhookSecret: supplier.webhookSecret ?? '',\n }\n}\n\nexport function SuppliersCard(props: SuppliersCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const {\n status: suppliersStatus,\n /**\n * The list this dialog is seeded from is unconfirmed by the server\n * (AGL-1358). Editing a supplier copies the whole stored row into\n * `draft` and writes all of it back, so a cached seed can restore a\n * ROTATED `webhookSecret` — the supplier keeps signing with a key we\n * meant to retire, and nothing anywhere reports it.\n */\n fromCache: suppliersFromCache,\n listen: suppliersListen,\n rows: suppliers,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<any>(\n /*\n * SERVER-PAGED, and ordered (AGL-2501).\n *\n * `limit(50)` alone is answered in DOCUMENT-ID order, and suppliers are\n * created with a generated id — so the fifty were a pseudo-random sample\n * and the fifty-first was not merely unrendered, it was UNREACHABLE. A\n * merchant with sixty fulfillment partners saw fifty of them and nothing\n * said which.\n *\n * This one really can be paged by the query, unlike the cards that carry a\n * duplicate-name check or a count over the whole set: nothing here is\n * derived from rows off the page. Suppliers are assigned to products by\n * document id in the product editor, and the empty state and the row list\n * are the only consumers.\n *\n * `collectionPage` orders on the document NAME, which cannot be absent —\n * `orderBy('name')` would HIDE every supplier saved without one rather\n * than mis-sorting the list, and `/api/hosts/resources` validates no field\n * for presence.\n */\n (pageLimit) =>\n collectionPage(\n collection(firestore, 'hosts', hostId, 'suppliers'),\n pageLimit,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n /*\n * The dialog's draft, kept as EDITS over the supplier as the list has it\n * now (AGL-4047): opened from the cache's row, the server's copy replaces\n * it under every field nobody touched (a rotated `webhookSecret` among\n * them), and Save is held until it has.\n */\n const [draft, setDraft] = useSeedDraft<\n CommerceModel.HostSupplier & { id: string | null }\n >((opened) => {\n const row = opened.id\n ? suppliers.find((supplier: any) => supplier.$id === opened.id)\n : undefined\n return row ? supplierDraftOf(row) : undefined\n })\n const checking =\n Boolean(draft?.id) &&\n isSeedChecking({\n fromCache: suppliersFromCache,\n unreadable: suppliersStatus === 'error',\n })\n\n const handleSave = useCallback(async () => {\n if (!draft?.name.trim()) return\n const { id, ...data } = draft\n /**\n * Refuse an EDIT whose seed the server never confirmed (AGL-1358).\n *\n * This write has no options argument at all, so it is a full document\n * replace of a payload copied wholesale off the listener — `merge`\n * would not have helped anyway, since every field is present. The one\n * that matters is `webhookSecret`: rotate it somewhere else, come back\n * to a console still serving the old row out of `persistentLocalCache`,\n * rename the supplier, and the retired secret is stored again.\n *\n * Only the edit path is guarded. A NEW supplier is built from blanks at\n * a fresh uid and can overwrite nothing, so refusing it would be a false\n * positive on a path that is never unsafe — and this guard stands in\n * front of the ordinary save.\n *\n * The guard WRAPS the write: an early return is a shape you can keep\n * while losing the protection.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'supplier',\n unreadable: Boolean(id) && suppliersStatus === 'error',\n fromCache: Boolean(id) && suppliersFromCache,\n listen: suppliersListen,\n },\n async () => {\n await setDoc(\n doc(\n firestore,\n 'hosts',\n hostId,\n 'suppliers',\n id ?? Aglyn.createResourceUid(),\n ),\n {\n ...data,\n name: draft.name.trim().slice(0, 80),\n },\n )\n },\n )\n // A refusal keeps the dialog open with what was typed. A save that\n // silently does nothing sends the user back to retype a form that will\n // be refused again just as quietly.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setDraft(null)\n enqueueSnackbar('Supplier saved', { variant: 'success', persist: false })\n }, [\n setDraft,\n draft,\n firestore,\n hostId,\n enqueueSnackbar,\n suppliersFromCache,\n suppliersListen,\n suppliersStatus,\n ])\n\n const handleDelete = useCallback(\n (supplier: any) => async () => {\n const confirmed = await confirm({\n title: 'Remove this supplier?',\n description:\n `Products assigned to \"${supplier.name}\" stop routing; orders ` +\n 'already sent are unaffected.',\n confirmationText: 'Remove',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await deleteDoc(doc(firestore, 'hosts', hostId, 'suppliers', supplier.$id))\n },\n [confirm, firestore, hostId],\n )\n\n // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const held = useHeldSave(handleSave, {\n checking,\n subject: 'supplier',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n\n return (\n <EntitlementGatedCard\n help={suppliersHelp}\n hostId={hostId}\n feature=\"dropshipRouting\"\n header={'Dropship suppliers'}\n upsell={\n 'Dropship routing forwards each paid order to the right supplier ' +\n 'by email or signed webhook, and takes tracking numbers back ' +\n `without the supplier needing an ${Aglyn.PLATFORM_BRAND_NAME} account.`\n }\n >\n <CardDisplay\n header={'Dropship suppliers'}\n help={suppliersHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {suppliers.length === 0 && page === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Route paid orders straight to a fulfillment partner: add a ' +\n 'supplier, then assign it on products.'}\n </Typography>\n ) : (\n suppliers.map((supplier: any) => (\n // A row click opens the supplier's editor; every action sits in\n // the row's one ⋮ menu.\n <OpenableListRow\n key={supplier.$id}\n label={supplier.name || 'Supplier'}\n onOpen={() => setDraft(supplierDraftOf(supplier))}\n items={[\n {\n key: 'edit',\n label: 'Edit',\n icon: { path: mdiPencilOutline.path },\n onClick: () => setDraft(supplierDraftOf(supplier)),\n },\n {\n key: 'remove',\n label: 'Remove',\n icon: { path: mdiDeleteOutline.path },\n destructive: true,\n onClick: () => void handleDelete(supplier)(),\n },\n ]}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {supplier.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {[supplier.email, supplier.webhookUrl]\n .filter(Boolean)\n .join(' · ') || 'No delivery method set'}\n </Typography>\n </Stack>\n </OpenableListRow>\n ))\n )}\n {suppliers.length === 0 && page === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={suppliers.length}\n // No `count`: this is a server window, and nobody knows the total\n // without paying to read it. `hasMore` is the probe row's answer.\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n setDraft({ id: null, name: '', email: '', webhookUrl: '', webhookSecret: '' })\n }\n >\n {'Add supplier'}\n </Button>\n </Stack>\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{draft?.id ? 'Edit supplier' : 'New supplier'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <TextField\n label=\"Name\"\n value={draft?.name ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <TextField\n label=\"Notification email\"\n value={draft?.email ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, email: event.target.value } : prev,\n )\n }\n size=\"small\"\n helperText=\"Gets order details + a tracking link per sale\"\n />\n <TextField\n label=\"Webhook URL\"\n value={draft?.webhookUrl ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, webhookUrl: event.target.value } : prev,\n )\n }\n size=\"small\"\n placeholder=\"https://…\"\n />\n <TextField\n label=\"Webhook secret\"\n value={draft?.webhookSecret ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, webhookSecret: event.target.value } : prev,\n )\n }\n size=\"small\"\n helperText=\"Payloads carry an x-aglyn-signature HMAC header\"\n />\n </DialogContent>\n <DialogActions>\n {checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {seedCheckingText('supplier')}\n </Typography>\n ) : null}\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim() || held.saving}\n onClick={held.press}\n >\n {heldSaveLabel(held, 'Save')}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n </EntitlementGatedCard>\n )\n}\nSuppliersCard.displayName = 'SuppliersCard'\n\nexport default SuppliersCard\n"],"names":["Aglyn","CardDisplay","useConfirmationContext","useSnackbar","Button","Dialog","DialogActions","DialogContent","DialogTitle","Stack","TextField","Typography","collection","deleteDoc","doc","setDoc","useCallback","useFirestore","collectionPage","usePagedCollection","writeGuardedBySeed","ListPagination","OpenableListRow","mdiDeleteOutline","mdiPencilOutline","EntitlementGatedCard","pluginDocsHelp","heldSaveLabel","isSeedChecking","seedCheckingText","useHeldSave","useSeedDraft","suppliersHelp","anchor","supplierDraftOf","supplier","id","$id","name","email","webhookUrl","webhookSecret","SuppliersCard","props","hostId","firestore","enqueueSnackbar","confirm","status","suppliersStatus","fromCache","suppliersFromCache","listen","suppliersListen","rows","suppliers","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","draft","setDraft","opened","row","find","undefined","checking","Boolean","unreadable","handleSave","trim","data","verdict","subject","createResourceUid","slice","ok","message","variant","persist","handleDelete","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","catch","held","onRefused","help","feature","header","upsell","PLATFORM_BRAND_NAME","contentGutterX","contentGutterY","spacing","length","map","label","onOpen","items","key","icon","path","onClick","destructive","sx","flex","minWidth","noWrap","filter","join","rowCount","onPageChange","onPageSizeChange","size","alignSelf","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","value","onChange","event","prev","target","autoFocus","mt","helperText","placeholder","role","mr","disabled","saving","press","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,YAAYA,WAAW,eAAc;AAErC,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,SAAS,EAAEC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AACvE,SAASC,WAAW,QAAQ,QAAO;AACnC,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SACEC,cAAc,EACdC,kBAAkB,EAClBC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,eAAe,QAAQ,8DAA6D;AAC7F,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33
  import { useId, useState } from "react";
34
34
  import { modifierGroupIsWriteIn, modifierGroupRequired, modifierOptionIsCombo, modifierOptionPriceCents } from "../model/product-modifiers.js";
35
35
  import { addOnGroupHint, addOnMoney, ProductWriteInField, withGroupAnswer } from "./product-add-ons.js";
36
+ import { storeImageSizing } from "./store-image-sizing.js";
36
37
  /**
37
38
  * The variant a card for one option value stands for: the one the shopper's
38
39
  * other picks make with this value, else the first that carries the value.
@@ -113,7 +114,7 @@ import { addOnGroupHint, addOnMoney, ProductWriteInField, withGroupAnswer } from
113
114
  aspectRatio: '4 / 3',
114
115
  objectFit: 'cover'
115
116
  }
116
- }, Aglyn.DEFERRED_IMAGE_ATTRIBUTES)) : null,
117
+ }, storeImageSizing(src, '(min-width: 600px) 240px, 50vw'), Aglyn.DEFERRED_IMAGE_ATTRIBUTES)) : null,
117
118
  /*#__PURE__*/ _jsxs(CardContent, {
118
119
  sx: {
119
120
  flex: 1,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/product-choice-cards.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'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\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 Chip from '@mui/material/Chip'\nimport Collapse from '@mui/material/Collapse'\nimport List from '@mui/material/List'\nimport ListItem from '@mui/material/ListItem'\nimport ListItemText from '@mui/material/ListItemText'\nimport Stack from '@mui/material/Stack'\nimport Typography from '@mui/material/Typography'\nimport { useId, useState, type ReactNode } from 'react'\nimport {\n modifierGroupIsWriteIn,\n modifierGroupRequired,\n modifierOptionIsCombo,\n modifierOptionPriceCents,\n type ModifierSelection,\n type ProductModifierGroup,\n type ProductModifierOption,\n} from '../model/product-modifiers'\nimport { addOnGroupHint, addOnMoney, ProductWriteInField, withGroupAnswer } from './product-add-ons'\n\n/*\n * THE PRODUCT BUILDER'S PICTURE CARDS (AGL-4205).\n *\n * A Product detail block set to show its choices as picture cards draws each\n * of the product's options (size, style) and each of its add-on groups as a\n * row of cards: the choice's picture, its name, what it costs, and the\n * owner's short note. A combo's card folds out what it includes. A group\n * that takes one choice behaves as radio buttons, one that takes several as\n * check boxes up to its maximum, and a required group is marked and cannot\n * be emptied. Its own chunk: only a page that shows cards downloads it.\n */\n\n/** A variant as the cards read it. */\nexport interface CardVariant {\n id: string\n options?: Record<string, string>\n priceUsd: number | null\n /** The merchant's own price per currency (AGL-4248). */\n fixedPrices?: Record<string, number>\n soldOut?: boolean\n imageUrl?: string\n note?: string\n}\n\n/**\n * The variant a card for one option value stands for: the one the shopper's\n * other picks make with this value, else the first that carries the value.\n */\nexport function variantForOptionValue<V extends CardVariant>(\n variants: readonly V[],\n selections: Readonly<Record<string, string>>,\n optionName: string,\n value: string,\n): V | undefined {\n const wanted = { ...selections, [optionName]: value }\n return (\n variants.find((variant) =>\n Object.entries(wanted).every(([name, picked]) => (variant.options?.[name] ?? picked) === picked),\n ) ?? variants.find((variant) => variant.options?.[optionName] === value)\n )\n}\n\n/**\n * A group's answer after a card is pressed. One-choice groups act as radio\n * buttons (an optional one can be cleared by pressing its pick again); a\n * several-choice group adds or removes the choice, never past its maximum.\n * The answer keeps the group's own order.\n */\nexport function pressChoice(\n group: Pick<ProductModifierGroup, 'min' | 'max' | 'options'>,\n chosen: readonly string[],\n optionId: string,\n): string[] {\n const picked = chosen.includes(optionId)\n if (group.max === 1) {\n if (picked) return group.min > 0 ? [...chosen] : []\n return [optionId]\n }\n if (picked) return chosen.filter((id) => id !== optionId)\n if (chosen.length >= group.max) return [...chosen]\n return group.options.map((option) => option.id).filter((id) => id === optionId || chosen.includes(id))\n}\n\n/** What a card says a choice adds: its price, or that it adds nothing. */\nexport function addOnPriceLabel(cents: number, formatCents: (cents: number) => string): string {\n return cents > 0 ? `+${formatCents(cents)}` : 'No extra charge'\n}\n\ninterface ChoiceCardProps {\n name: string\n price: string\n note?: string\n imageUrl?: string\n selected: boolean\n disabled?: boolean\n role: 'radio' | 'checkbox'\n onPress: () => void\n badge?: ReactNode\n includes?: readonly string[]\n}\n\n/** One card: picture, name, price and note, pressed to pick; a combo's contents fold out below. */\nfunction ChoiceCard(props: ChoiceCardProps) {\n const { name, price, note, imageUrl, selected, disabled, role, onPress, badge, includes } = props\n const { hostId } = Aglyn.useSite()\n const [open, setOpen] = useState(false)\n const contentsId = useId()\n const src = imageUrl ? Aglyn.siteRelativeMediaSrc(imageUrl, { hostId }) : undefined\n return (\n <Card\n variant=\"outlined\"\n sx={{\n display: 'flex',\n flexDirection: 'column',\n borderWidth: 2,\n borderColor: selected ? 'primary.main' : 'divider',\n bgcolor: selected ? 'action.selected' : 'background.paper',\n opacity: disabled && !selected ? 0.6 : 1,\n }}\n >\n <CardActionArea\n role={role}\n aria-checked={selected}\n disabled={disabled}\n onClick={onPress}\n sx={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'stretch' }}\n >\n {src ? (\n <CardMedia\n component=\"img\"\n image={src}\n alt=\"\"\n sx={{ aspectRatio: '4 / 3', objectFit: 'cover' }}\n {...Aglyn.DEFERRED_IMAGE_ATTRIBUTES}\n />\n ) : null}\n <CardContent sx={{ flex: 1, p: 1.5, '&:last-child': { pb: 1.5 } }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start', justifyContent: 'space-between' }}>\n <Typography variant=\"subtitle2\" component=\"span\">\n {name}\n </Typography>\n {badge}\n </Stack>\n <Typography variant=\"body2\" color={selected ? 'primary' : 'text.primary'} sx={{ fontWeight: 600 }}>\n {price}\n </Typography>\n {note ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"p\">\n {note}\n </Typography>\n ) : null}\n </CardContent>\n </CardActionArea>\n {includes?.length ? (\n <Box sx={{ px: 1, pb: 1 }}>\n <Button\n size=\"small\"\n aria-expanded={open}\n aria-controls={contentsId}\n onClick={() => setOpen((was) => !was)}\n >\n {open ? 'Hide what’s included' : 'What’s included'}\n </Button>\n <Collapse in={open} id={contentsId}>\n <List dense disablePadding aria-label={`${name} includes`}>\n {includes.map((item) => (\n <ListItem key={item} disableGutters sx={{ py: 0 }}>\n <ListItemText primary={item} slotProps={{ primary: { variant: 'body2' } }} />\n </ListItem>\n ))}\n </List>\n </Collapse>\n </Box>\n ) : null}\n </Card>\n )\n}\n\n/** A heading, its hint, and the grid of cards under it. */\nfunction CardGroup(props: {\n label: string\n hint: string\n required: boolean\n role: 'radiogroup' | 'group'\n children: ReactNode\n}) {\n const { label, hint, required, role, children } = props\n const labelId = useId()\n return (\n <Box component=\"section\" aria-labelledby={labelId}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', mb: 1 }}>\n <Typography id={labelId} variant=\"subtitle1\" component=\"h2\">\n {label}\n </Typography>\n <Chip\n size=\"small\"\n variant=\"outlined\"\n color={required ? 'primary' : 'default'}\n label={hint}\n />\n </Stack>\n <Box\n role={role}\n aria-labelledby={labelId}\n aria-required={required || undefined}\n sx={{\n display: 'grid',\n gridTemplateColumns: (theme) => `repeat(auto-fill, minmax(${theme.spacing(19)}, 1fr))`,\n gap: 1.5,\n }}\n >\n {children}\n </Box>\n </Box>\n )\n}\n\nexport interface ProductChoiceCardsProps {\n /** The options the shopper chooses among (size, style), with their values. */\n options: ReadonlyArray<{ name: string; values: readonly string[] }>\n variants: readonly CardVariant[]\n selections: Readonly<Record<string, string>>\n onSelect: (optionName: string, value: string) => void\n /** The add-on groups the website offers; empty draws none. */\n groups: readonly ProductModifierGroup[]\n /** The variant picked: a choice priced by variant shows its price on it. */\n variantId?: string\n value: readonly ModifierSelection[]\n onChange: (next: ModifierSelection[]) => void\n /** The store's money, e.g. `$1,250.00`. */\n formatCents: (cents: number) => string\n /**\n * What a choice adds, in the shopper's currency (AGL-4248): its fixed\n * amount there when it has one. Absent: `formatCents` of its store price.\n */\n formatAddOn?: (option: ProductModifierOption, variantId?: string | null) => string\n /** A variant's price in the shopper's currency (AGL-4248); absent: `formatCents`. */\n formatVariant?: (variant: { priceUsd?: number | null; fixedPrices?: Record<string, number> }) => string\n /** What a card says where a variant has no price yet. */\n unpricedLabel: string\n disabled?: boolean\n}\n\n/** The product's options and add-ons as picture cards (AGL-4205). */\nexport function ProductChoiceCards(props: ProductChoiceCardsProps) {\n const {\n options,\n variants,\n selections,\n onSelect,\n groups,\n variantId,\n value,\n onChange,\n formatCents,\n formatAddOn,\n formatVariant,\n unpricedLabel,\n disabled,\n } = props\n const addOnCard = (group: ProductModifierGroup, option: ProductModifierOption, chosen: string[]) => {\n const selected = chosen.includes(option.id)\n const full = group.max > 1 && chosen.length >= group.max\n return (\n <ChoiceCard\n key={option.id}\n name={option.name}\n price={addOnPriceLabel(modifierOptionPriceCents(option, variantId), () =>\n addOnMoney(option, variantId, formatCents, formatAddOn),\n )}\n note={option.note}\n imageUrl={option.imageUrl}\n selected={selected}\n disabled={disabled || (!selected && full)}\n role={group.max === 1 ? 'radio' : 'checkbox'}\n badge={modifierOptionIsCombo(option) ? <Chip size=\"small\" color=\"secondary\" label=\"Combo\" /> : null}\n includes={modifierOptionIsCombo(option) ? option.includes : undefined}\n onPress={() => onChange(withGroupAnswer(groups, value, group.id, pressChoice(group, chosen, option.id)))}\n />\n )\n }\n return (\n <Stack spacing={3} sx={{ mb: 2 }}>\n {options.map((option) => (\n <CardGroup key={option.name} label={option.name} hint=\"Choose one\" required role=\"radiogroup\">\n {option.values.map((choice) => {\n const variant = variantForOptionValue(variants, selections, option.name, choice)\n return (\n <ChoiceCard\n key={choice}\n name={choice}\n price={\n typeof variant?.priceUsd === 'number'\n ? formatVariant\n ? formatVariant(variant)\n : formatCents(Math.round(variant.priceUsd * 100))\n : unpricedLabel\n }\n note={variant?.note}\n imageUrl={variant?.imageUrl}\n selected={selections[option.name] === choice}\n role=\"radio\"\n badge={variant?.soldOut ? <Chip size=\"small\" variant=\"outlined\" label=\"Sold out\" /> : null}\n onPress={() => onSelect(option.name, choice)}\n />\n )\n })}\n </CardGroup>\n ))}\n {groups.map((group) => {\n // A write-in (write-ins) is a text field among the cards: there is nothing to picture.\n if (modifierGroupIsWriteIn(group)) {\n return (\n <ProductWriteInField\n key={group.id}\n group={group}\n groups={groups}\n variantId={variantId}\n value={value}\n onChange={onChange}\n formatCents={formatCents}\n formatAddOn={formatAddOn}\n disabled={disabled}\n />\n )\n }\n const chosen = value.filter((pick) => pick.groupId === group.id).map((pick) => pick.optionId)\n return (\n <CardGroup\n key={group.id}\n label={group.name}\n hint={addOnGroupHint(group)}\n required={modifierGroupRequired(group)}\n role={group.max === 1 ? 'radiogroup' : 'group'}\n >\n {group.options.map((option) => addOnCard(group, option, chosen))}\n </CardGroup>\n )\n })}\n </Stack>\n )\n}\n\nProductChoiceCards.displayName = 'ProductChoiceCards'\n\nexport default ProductChoiceCards\n"],"names":["Aglyn","Box","Button","Card","CardActionArea","CardContent","CardMedia","Chip","Collapse","List","ListItem","ListItemText","Stack","Typography","useId","useState","modifierGroupIsWriteIn","modifierGroupRequired","modifierOptionIsCombo","modifierOptionPriceCents","addOnGroupHint","addOnMoney","ProductWriteInField","withGroupAnswer","variantForOptionValue","variants","selections","optionName","value","wanted","find","variant","Object","entries","every","name","picked","options","pressChoice","group","chosen","optionId","includes","max","min","filter","id","length","map","option","addOnPriceLabel","cents","formatCents","ChoiceCard","props","price","note","imageUrl","selected","disabled","role","onPress","badge","hostId","useSite","open","setOpen","contentsId","src","siteRelativeMediaSrc","undefined","sx","display","flexDirection","borderWidth","borderColor","bgcolor","opacity","aria-checked","onClick","flex","alignItems","component","image","alt","aspectRatio","objectFit","DEFERRED_IMAGE_ATTRIBUTES","p","pb","direction","spacing","justifyContent","color","fontWeight","px","size","aria-expanded","aria-controls","was","in","dense","disablePadding","aria-label","item","disableGutters","py","primary","slotProps","CardGroup","label","hint","required","children","labelId","aria-labelledby","mb","aria-required","gridTemplateColumns","theme","gap","ProductChoiceCards","onSelect","groups","variantId","onChange","formatAddOn","formatVariant","unpricedLabel","addOnCard","full","values","choice","priceUsd","Math","round","soldOut","pick","groupId","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,oBAAoB,+BAA8B;AACzD,OAAOC,iBAAiB,4BAA2B;AACnD,OAAOC,eAAe,0BAAyB;AAC/C,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,cAAc,yBAAwB;AAC7C,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,cAAc,yBAAwB;AAC7C,OAAOC,kBAAkB,6BAA4B;AACrD,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,gBAAgB,2BAA0B;AACjD,SAASC,KAAK,EAAEC,QAAQ,QAAwB,QAAO;AACvD,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,qBAAqB,EACrBC,wBAAwB,QAInB,gCAA4B;AACnC,SAASC,cAAc,EAAEC,UAAU,EAAEC,mBAAmB,EAAEC,eAAe,QAAQ,uBAAmB;AA0BpG;;;CAGC,GACD,OAAO,SAASC,sBACdC,QAAsB,EACtBC,UAA4C,EAC5CC,UAAkB,EAClBC,KAAa;QAIXH;IAFF,MAAMI,SAAS,aAAKH;QAAY,CAACC,WAAW,EAAEC;;IAC9C,QACEH,iBAAAA,SAASK,IAAI,CAAC,CAACC,UACbC,OAAOC,OAAO,CAACJ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AACC,SAAWgF,UAAU1F,OAAOU,QAAQT;mBANnDD,MAAMO,EAAE;YASnB;;;AAGN;AAEA2E,mBAAmBkB,WAAW,GAAG;AAEjC,eAAelB,mBAAkB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/product-choice-cards.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'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\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 Chip from '@mui/material/Chip'\nimport Collapse from '@mui/material/Collapse'\nimport List from '@mui/material/List'\nimport ListItem from '@mui/material/ListItem'\nimport ListItemText from '@mui/material/ListItemText'\nimport Stack from '@mui/material/Stack'\nimport Typography from '@mui/material/Typography'\nimport { useId, useState, type ReactNode } from 'react'\nimport {\n modifierGroupIsWriteIn,\n modifierGroupRequired,\n modifierOptionIsCombo,\n modifierOptionPriceCents,\n type ModifierSelection,\n type ProductModifierGroup,\n type ProductModifierOption,\n} from '../model/product-modifiers'\nimport { addOnGroupHint, addOnMoney, ProductWriteInField, withGroupAnswer } from './product-add-ons'\nimport { storeImageSizing } from './store-image-sizing'\n\n/*\n * THE PRODUCT BUILDER'S PICTURE CARDS (AGL-4205).\n *\n * A Product detail block set to show its choices as picture cards draws each\n * of the product's options (size, style) and each of its add-on groups as a\n * row of cards: the choice's picture, its name, what it costs, and the\n * owner's short note. A combo's card folds out what it includes. A group\n * that takes one choice behaves as radio buttons, one that takes several as\n * check boxes up to its maximum, and a required group is marked and cannot\n * be emptied. Its own chunk: only a page that shows cards downloads it.\n */\n\n/** A variant as the cards read it. */\nexport interface CardVariant {\n id: string\n options?: Record<string, string>\n priceUsd: number | null\n /** The merchant's own price per currency (AGL-4248). */\n fixedPrices?: Record<string, number>\n soldOut?: boolean\n imageUrl?: string\n note?: string\n}\n\n/**\n * The variant a card for one option value stands for: the one the shopper's\n * other picks make with this value, else the first that carries the value.\n */\nexport function variantForOptionValue<V extends CardVariant>(\n variants: readonly V[],\n selections: Readonly<Record<string, string>>,\n optionName: string,\n value: string,\n): V | undefined {\n const wanted = { ...selections, [optionName]: value }\n return (\n variants.find((variant) =>\n Object.entries(wanted).every(([name, picked]) => (variant.options?.[name] ?? picked) === picked),\n ) ?? variants.find((variant) => variant.options?.[optionName] === value)\n )\n}\n\n/**\n * A group's answer after a card is pressed. One-choice groups act as radio\n * buttons (an optional one can be cleared by pressing its pick again); a\n * several-choice group adds or removes the choice, never past its maximum.\n * The answer keeps the group's own order.\n */\nexport function pressChoice(\n group: Pick<ProductModifierGroup, 'min' | 'max' | 'options'>,\n chosen: readonly string[],\n optionId: string,\n): string[] {\n const picked = chosen.includes(optionId)\n if (group.max === 1) {\n if (picked) return group.min > 0 ? [...chosen] : []\n return [optionId]\n }\n if (picked) return chosen.filter((id) => id !== optionId)\n if (chosen.length >= group.max) return [...chosen]\n return group.options.map((option) => option.id).filter((id) => id === optionId || chosen.includes(id))\n}\n\n/** What a card says a choice adds: its price, or that it adds nothing. */\nexport function addOnPriceLabel(cents: number, formatCents: (cents: number) => string): string {\n return cents > 0 ? `+${formatCents(cents)}` : 'No extra charge'\n}\n\ninterface ChoiceCardProps {\n name: string\n price: string\n note?: string\n imageUrl?: string\n selected: boolean\n disabled?: boolean\n role: 'radio' | 'checkbox'\n onPress: () => void\n badge?: ReactNode\n includes?: readonly string[]\n}\n\n/** One card: picture, name, price and note, pressed to pick; a combo's contents fold out below. */\nfunction ChoiceCard(props: ChoiceCardProps) {\n const { name, price, note, imageUrl, selected, disabled, role, onPress, badge, includes } = props\n const { hostId } = Aglyn.useSite()\n const [open, setOpen] = useState(false)\n const contentsId = useId()\n const src = imageUrl ? Aglyn.siteRelativeMediaSrc(imageUrl, { hostId }) : undefined\n return (\n <Card\n variant=\"outlined\"\n sx={{\n display: 'flex',\n flexDirection: 'column',\n borderWidth: 2,\n borderColor: selected ? 'primary.main' : 'divider',\n bgcolor: selected ? 'action.selected' : 'background.paper',\n opacity: disabled && !selected ? 0.6 : 1,\n }}\n >\n <CardActionArea\n role={role}\n aria-checked={selected}\n disabled={disabled}\n onClick={onPress}\n sx={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'stretch' }}\n >\n {src ? (\n <CardMedia\n component=\"img\"\n image={src}\n alt=\"\"\n sx={{ aspectRatio: '4 / 3', objectFit: 'cover' }}\n {...storeImageSizing(src, '(min-width: 600px) 240px, 50vw')}\n {...Aglyn.DEFERRED_IMAGE_ATTRIBUTES}\n />\n ) : null}\n <CardContent sx={{ flex: 1, p: 1.5, '&:last-child': { pb: 1.5 } }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start', justifyContent: 'space-between' }}>\n <Typography variant=\"subtitle2\" component=\"span\">\n {name}\n </Typography>\n {badge}\n </Stack>\n <Typography variant=\"body2\" color={selected ? 'primary' : 'text.primary'} sx={{ fontWeight: 600 }}>\n {price}\n </Typography>\n {note ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"p\">\n {note}\n </Typography>\n ) : null}\n </CardContent>\n </CardActionArea>\n {includes?.length ? (\n <Box sx={{ px: 1, pb: 1 }}>\n <Button\n size=\"small\"\n aria-expanded={open}\n aria-controls={contentsId}\n onClick={() => setOpen((was) => !was)}\n >\n {open ? 'Hide what’s included' : 'What’s included'}\n </Button>\n <Collapse in={open} id={contentsId}>\n <List dense disablePadding aria-label={`${name} includes`}>\n {includes.map((item) => (\n <ListItem key={item} disableGutters sx={{ py: 0 }}>\n <ListItemText primary={item} slotProps={{ primary: { variant: 'body2' } }} />\n </ListItem>\n ))}\n </List>\n </Collapse>\n </Box>\n ) : null}\n </Card>\n )\n}\n\n/** A heading, its hint, and the grid of cards under it. */\nfunction CardGroup(props: {\n label: string\n hint: string\n required: boolean\n role: 'radiogroup' | 'group'\n children: ReactNode\n}) {\n const { label, hint, required, role, children } = props\n const labelId = useId()\n return (\n <Box component=\"section\" aria-labelledby={labelId}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', mb: 1 }}>\n <Typography id={labelId} variant=\"subtitle1\" component=\"h2\">\n {label}\n </Typography>\n <Chip\n size=\"small\"\n variant=\"outlined\"\n color={required ? 'primary' : 'default'}\n label={hint}\n />\n </Stack>\n <Box\n role={role}\n aria-labelledby={labelId}\n aria-required={required || undefined}\n sx={{\n display: 'grid',\n gridTemplateColumns: (theme) => `repeat(auto-fill, minmax(${theme.spacing(19)}, 1fr))`,\n gap: 1.5,\n }}\n >\n {children}\n </Box>\n </Box>\n )\n}\n\nexport interface ProductChoiceCardsProps {\n /** The options the shopper chooses among (size, style), with their values. */\n options: ReadonlyArray<{ name: string; values: readonly string[] }>\n variants: readonly CardVariant[]\n selections: Readonly<Record<string, string>>\n onSelect: (optionName: string, value: string) => void\n /** The add-on groups the website offers; empty draws none. */\n groups: readonly ProductModifierGroup[]\n /** The variant picked: a choice priced by variant shows its price on it. */\n variantId?: string\n value: readonly ModifierSelection[]\n onChange: (next: ModifierSelection[]) => void\n /** The store's money, e.g. `$1,250.00`. */\n formatCents: (cents: number) => string\n /**\n * What a choice adds, in the shopper's currency (AGL-4248): its fixed\n * amount there when it has one. Absent: `formatCents` of its store price.\n */\n formatAddOn?: (option: ProductModifierOption, variantId?: string | null) => string\n /** A variant's price in the shopper's currency (AGL-4248); absent: `formatCents`. */\n formatVariant?: (variant: { priceUsd?: number | null; fixedPrices?: Record<string, number> }) => string\n /** What a card says where a variant has no price yet. */\n unpricedLabel: string\n disabled?: boolean\n}\n\n/** The product's options and add-ons as picture cards (AGL-4205). */\nexport function ProductChoiceCards(props: ProductChoiceCardsProps) {\n const {\n options,\n variants,\n selections,\n onSelect,\n groups,\n variantId,\n value,\n onChange,\n formatCents,\n formatAddOn,\n formatVariant,\n unpricedLabel,\n disabled,\n } = props\n const addOnCard = (group: ProductModifierGroup, option: ProductModifierOption, chosen: string[]) => {\n const selected = chosen.includes(option.id)\n const full = group.max > 1 && chosen.length >= group.max\n return (\n <ChoiceCard\n key={option.id}\n name={option.name}\n price={addOnPriceLabel(modifierOptionPriceCents(option, variantId), () =>\n addOnMoney(option, variantId, formatCents, formatAddOn),\n )}\n note={option.note}\n imageUrl={option.imageUrl}\n selected={selected}\n disabled={disabled || (!selected && full)}\n role={group.max === 1 ? 'radio' : 'checkbox'}\n badge={modifierOptionIsCombo(option) ? <Chip size=\"small\" color=\"secondary\" label=\"Combo\" /> : null}\n includes={modifierOptionIsCombo(option) ? option.includes : undefined}\n onPress={() => onChange(withGroupAnswer(groups, value, group.id, pressChoice(group, chosen, option.id)))}\n />\n )\n }\n return (\n <Stack spacing={3} sx={{ mb: 2 }}>\n {options.map((option) => (\n <CardGroup key={option.name} label={option.name} hint=\"Choose one\" required role=\"radiogroup\">\n {option.values.map((choice) => {\n const variant = variantForOptionValue(variants, selections, option.name, choice)\n return (\n <ChoiceCard\n key={choice}\n name={choice}\n price={\n typeof variant?.priceUsd === 'number'\n ? formatVariant\n ? formatVariant(variant)\n : formatCents(Math.round(variant.priceUsd * 100))\n : unpricedLabel\n }\n note={variant?.note}\n imageUrl={variant?.imageUrl}\n selected={selections[option.name] === choice}\n role=\"radio\"\n badge={variant?.soldOut ? <Chip size=\"small\" variant=\"outlined\" label=\"Sold out\" /> : null}\n onPress={() => onSelect(option.name, choice)}\n />\n )\n })}\n </CardGroup>\n ))}\n {groups.map((group) => {\n // A write-in (write-ins) is a text field among the cards: there is nothing to picture.\n if (modifierGroupIsWriteIn(group)) {\n return (\n <ProductWriteInField\n key={group.id}\n group={group}\n groups={groups}\n variantId={variantId}\n value={value}\n onChange={onChange}\n formatCents={formatCents}\n formatAddOn={formatAddOn}\n disabled={disabled}\n />\n )\n }\n const chosen = value.filter((pick) => pick.groupId === group.id).map((pick) => pick.optionId)\n return (\n <CardGroup\n key={group.id}\n label={group.name}\n hint={addOnGroupHint(group)}\n required={modifierGroupRequired(group)}\n role={group.max === 1 ? 'radiogroup' : 'group'}\n >\n {group.options.map((option) => addOnCard(group, option, chosen))}\n </CardGroup>\n )\n })}\n </Stack>\n )\n}\n\nProductChoiceCards.displayName = 'ProductChoiceCards'\n\nexport default ProductChoiceCards\n"],"names":["Aglyn","Box","Button","Card","CardActionArea","CardContent","CardMedia","Chip","Collapse","List","ListItem","ListItemText","Stack","Typography","useId","useState","modifierGroupIsWriteIn","modifierGroupRequired","modifierOptionIsCombo","modifierOptionPriceCents","addOnGroupHint","addOnMoney","ProductWriteInField","withGroupAnswer","storeImageSizing","variantForOptionValue","variants","selections","optionName","value","wanted","find","variant","Object","entries","every","name","picked","options","pressChoice","group","chosen","optionId","includes","max","min","filter","id","length","map","option","addOnPriceLabel","cents","formatCents","ChoiceCard","props","price","note","imageUrl","selected","disabled","role","onPress","badge","hostId","useSite","open","setOpen","contentsId","src","siteRelativeMediaSrc","undefined","sx","display","flexDirection","borderWidth","borderColor","bgcolor","opacity","aria-checked","onClick","flex","alignItems","component","image","alt","aspectRatio","objectFit","DEFERRED_IMAGE_ATTRIBUTES","p","pb","direction","spacing","justifyContent","color","fontWeight","px","size","aria-expanded","aria-controls","was","in","dense","disablePadding","aria-label","item","disableGutters","py","primary","slotProps","CardGroup","label","hint","required","children","labelId","aria-labelledby","mb","aria-required","gridTemplateColumns","theme","gap","ProductChoiceCards","onSelect","groups","variantId","onChange","formatAddOn","formatVariant","unpricedLabel","addOnCard","full","values","choice","priceUsd","Math","round","soldOut","pick","groupId","displayName"],"mappings":"AAAA;;;;;;;;;;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2BAAAA,QAAS0B,QAAQ;4BAC3BC,UAAUhC,UAAU,CAACuB,OAAOd,IAAI,CAAC,KAAKiG;4BACtCxE,MAAK;4BACLE,OAAO/B,CAAAA,2BAAAA,QAASyG,OAAO,kBAAG,KAAClI;gCAAK0F,MAAK;gCAAQjE,SAAQ;gCAAW+E,OAAM;iCAAgB;4BACtFjD,SAAS,IAAM6D,SAASzE,OAAOd,IAAI,EAAEiG;2BAdhCA;oBAiBX;mBAtBcnF,OAAOd,IAAI;YAyB5BwF,OAAO3E,GAAG,CAAC,CAACT;gBACX,uFAAuF;gBACvF,IAAIxB,uBAAuBwB,QAAQ;oBACjC,qBACE,KAAClB;wBAECkB,OAAOA;wBACPoF,QAAQA;wBACRC,WAAWA;wBACXhG,OAAOA;wBACPiG,UAAUA;wBACVzE,aAAaA;wBACb0E,aAAaA;wBACbnE,UAAUA;uBARLpB,MAAMO,EAAE;gBAWnB;gBACA,MAAMN,SAASZ,MAAMiB,MAAM,CAAC,CAAC4F,OAASA,KAAKC,OAAO,KAAKnG,MAAMO,EAAE,EAAEE,GAAG,CAAC,CAACyF,OAASA,KAAKhG,QAAQ;gBAC5F,qBACE,KAACoE;oBAECC,OAAOvE,MAAMJ,IAAI;oBACjB4E,MAAM5F,eAAeoB;oBACrByE,UAAUhG,sBAAsBuB;oBAChCqB,MAAMrB,MAAMI,GAAG,KAAK,IAAI,eAAe;8BAEtCJ,MAAMF,OAAO,CAACW,GAAG,CAAC,CAACC,SAAWgF,UAAU1F,OAAOU,QAAQT;mBANnDD,MAAMO,EAAE;YASnB;;;AAGN;AAEA2E,mBAAmBkB,WAAW,GAAG;AAEjC,eAAelB,mBAAkB"}
@@ -38,6 +38,7 @@ import { BUNDLE_ID } from "../constants/bundle-common.js";
38
38
  import { generatePresetId } from "../utils/generate-preset-id.js";
39
39
  import { useStorefrontPurchaseEvent } from "../utils/use-storefront-purchase-event.js";
40
40
  import { addToCart } from "../utils/add-to-cart.js";
41
+ import { storeImageSizing } from "./store-image-sizing.js";
41
42
  import { CartFulfillmentChoice, useCartFulfillment } from "./cart-fulfillment.js";
42
43
  import { HardwareTermsConsent, hardwareTermsAnswered, NO_HARDWARE_TERMS_ANSWER } from "./hardware-terms-consent.js";
43
44
  import { ID as PRODUCT_REVIEWS_ID } from "./product-reviews.js";
@@ -756,10 +757,11 @@ function slugFromLocation() {
756
757
  minWidth: 0
757
758
  },
758
759
  children: [
759
- galleryImage ? /*#__PURE__*/ _jsx(Box, {
760
+ galleryImage ? /*#__PURE__*/ _jsx(Box, _extends({
760
761
  component: "img",
761
762
  src: galleryImage,
762
- alt: resolved.name,
763
+ alt: resolved.name
764
+ }, storeImageSizing(galleryImage, '(min-width: 900px) 50vw, 100vw'), {
763
765
  // DELIBERATELY NOT DEFERRED (AGL-2486). This is the gallery
764
766
  // hero at the top of a product page — the one image on this
765
767
  // surface that really is the LCP candidate, and the browser
@@ -779,7 +781,7 @@ function slugFromLocation() {
779
781
  objectFit: 'cover',
780
782
  borderRadius: 1
781
783
  }
782
- }) : /*#__PURE__*/ _jsx(Box, {
784
+ })) : /*#__PURE__*/ _jsx(Box, {
783
785
  sx: {
784
786
  width: '100%',
785
787
  aspectRatio: '1 / 1',
@@ -800,7 +802,10 @@ function slugFromLocation() {
800
802
  // `<img>` on the customer's page and leaks exactly as much.
801
803
  src: Aglyn.siteRelativeMediaSrc(url, {
802
804
  hostId
803
- }),
805
+ })
806
+ }, storeImageSizing(Aglyn.siteRelativeMediaSrc(url, {
807
+ hostId
808
+ }), '64px'), {
804
809
  alt: "",
805
810
  onClick: ()=>setActiveImage(index),
806
811
  sx: {