@aglyn/plugins-commerce 1.21.0 → 1.22.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 (45) hide show
  1. package/package.json +16 -16
  2. package/src/lib/components/cart-fulfillment.js +19 -8
  3. package/src/lib/components/cart-fulfillment.js.map +1 -1
  4. package/src/lib/components/console/catalog-organization-card.component.js +28 -9
  5. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  6. package/src/lib/components/console/discounts-card.component.js +13 -4
  7. package/src/lib/components/console/discounts-card.component.js.map +1 -1
  8. package/src/lib/components/console/local-delivery-settings-card.component.js +13 -4
  9. package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -1
  10. package/src/lib/components/console/product-editor-dialog.component.js +13 -4
  11. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  12. package/src/lib/components/console/products-hub-card.component.js +13 -4
  13. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  14. package/src/lib/components/console/quote-settings-card.component.js +13 -4
  15. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  16. package/src/lib/components/console/reservations-card.component.js +13 -4
  17. package/src/lib/components/console/reservations-card.component.js.map +1 -1
  18. package/src/lib/components/console/return-settings-card.component.js +13 -4
  19. package/src/lib/components/console/return-settings-card.component.js.map +1 -1
  20. package/src/lib/components/console/shipping-settings-card.component.js +13 -4
  21. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  22. package/src/lib/components/console/store-settings-card.component.js +13 -4
  23. package/src/lib/components/console/store-settings-card.component.js.map +1 -1
  24. package/src/lib/components/console/suppliers-card.component.js +13 -4
  25. package/src/lib/components/console/suppliers-card.component.js.map +1 -1
  26. package/src/lib/components/console/tax-settings-card.component.js +13 -4
  27. package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
  28. package/src/lib/model/commerce-pos-offline.d.ts +21 -3
  29. package/src/lib/model/commerce-pos-offline.js +17 -5
  30. package/src/lib/model/commerce-pos-offline.js.map +1 -1
  31. package/src/lib/server/pos-offline-card-order.d.ts +2 -0
  32. package/src/lib/server/pos-offline-card-order.js +6 -2
  33. package/src/lib/server/pos-offline-card-order.js.map +1 -1
  34. package/src/lib/server/pos-offline-card-reconcile.d.ts +5 -1
  35. package/src/lib/server/pos-offline-card-reconcile.js +42 -10
  36. package/src/lib/server/pos-offline-card-reconcile.js.map +1 -1
  37. package/src/lib/server/pos-offline-sync.d.ts +48 -6
  38. package/src/lib/server/pos-offline-sync.js +142 -31
  39. package/src/lib/server/pos-offline-sync.js.map +1 -1
  40. package/src/lib/server/pos-stripe.d.ts +11 -0
  41. package/src/lib/server/pos-stripe.js +14 -0
  42. package/src/lib/server/pos-stripe.js.map +1 -1
  43. package/src/lib/server/pos-terminal.d.ts +21 -1
  44. package/src/lib/server/pos-terminal.js +39 -5
  45. package/src/lib/server/pos-terminal.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/shipping-settings-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 } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n AlertTitle,\n Button,\n Divider,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { doc, setDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport {\n useFirestoreDoc,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n isSeedChecking,\n seedCheckingText,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\n\nexport interface ShippingSettingsCardProps {\n hostId: string\n}\n\n/**\n * Shipping settings (AGL-288): zones (countries, '*' = rest of world)\n * and rates (flat / free-over / subtotal or weight tiers), stored on\n * `hosts/{hostId}/settings/store` under `shipping`. Cart checkout (AGL-1707)\n * and buy-now (AGL-1720) both read this document and declare the rates as\n * Stripe `shipping_options` (`planCheckoutShipping`) — until those landed\n * nothing read it, and everything saved here was charged to nobody. Buy-now\n * resolves only for physical one-time sales; draft orders and POS still\n * resolve no shipping at all.\n *\n * WHAT A ZONE LAYOUT COSTS THE SHOPPER (AGL-1721). A session's rates are\n * charged as picked and never re-checked against the address, so the checkout\n * can only offer rates that hold for every country it will ship to. Saving\n * zones whose rates DIFFER therefore makes the storefront ask the shopper\n * where the parcel is going before it can price one, and a destination no\n * zone covers is refused outright rather than shipped for free. One zone, or\n * one '*' zone, needs neither: the shopper is asked nothing.\n *\n * AND THE MERCHANT HAS TO BE ABLE TO SEE IT (AGL-1791). Both consequences\n * were invisible here: a merchant saved zones and the checkouts they refused\n * were refused with nothing on this page saying so, which is a support ticket\n * from someone who did nothing wrong. The coverage block reads\n * `summarizeShippingCoverage` off the same `current` object the save writes,\n * so it moves as the form is typed rather than after a round trip.\n *\n * It escalates to a warning ONLY for a merchant who priced some destinations\n * and not others. A merchant whose rates reach nowhere is not misconfigured —\n * that store charges no shipping and refuses nobody — and warning them would\n * nag every store selling downloads.\n */\nexport function ShippingSettingsCard(props: ShippingSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const {\n data: store,\n status: storeStatus,\n /**\n * The settings doc this form is seeded from is unconfirmed by the server\n * (AGL-1358). `current` is `draft ?? store?.shipping ?? {}` and the save\n * writes `{shipping: current}`, so `merge: true` protects the doc's other\n * maps and nothing inside this one — `zones` and `rates` are arrays, and\n * a merge replaces an array wholesale. Against a cached read, adding one\n * rate restores that snapshot's whole price table, and a zone that\n * disappears with it means `resolveShippingRates` matches nothing, which\n * is a checkout offering no shipping option at all.\n */\n fromCache: storeFromCache,\n listen: storeListen,\n } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n // What was typed, kept as edits over the stored settings, and Save held\n // until the server has confirmed them (AGL-4047).\n const form = useSeedEdits<CommerceModel.ShippingSettings>(store?.shipping ?? {})\n const current = form.values\n const checking = isSeedChecking({ fromCache: storeFromCache, unreadable: storeStatus === 'error' })\n /*\n * Live carrier rates (AGL-3612) are offered only where a plugin quotes\n * carriers for this site — the server asks core's quoter seam. A rate\n * already saved as `carrier` stays editable either way, so a merchant can\n * still see and change what checkout falls back to.\n */\n const { data: user } = useUser()\n const [carrier, setCarrier] = useState<{\n available: boolean\n services: Array<{ serviceKey: string; label: string }>\n }>({ available: false, services: [] })\n useEffect(() => {\n let live = true\n authorizedFetch(user, `/api/commerce/shipping/carrier-rates?hostId=${encodeURIComponent(hostId)}`)\n .then((response) => (response.ok ? response.json() : null))\n .then((answer) => {\n if (live && answer) setCarrier({ available: Boolean(answer.available), services: answer.services ?? [] })\n })\n .catch(() => undefined)\n return () => {\n live = false\n }\n }, [hostId, user])\n const update = (patch: Partial<CommerceModel.ShippingSettings>) =>\n form.edit(patch)\n\n const updateZone = (\n index: number,\n patch: Partial<CommerceModel.ShippingZone> | null,\n ) => {\n const zones = [...(current.zones ?? [])]\n if (patch === null) {\n const removed = zones.splice(index, 1)[0]\n update({\n zones,\n rates: (current.rates ?? []).filter(\n (rate) => rate.zoneId !== removed?.id,\n ),\n })\n return\n }\n zones[index] = {\n id: Aglyn.createResourceUid(),\n name: '',\n countries: [],\n ...zones[index],\n ...patch,\n }\n update({ zones })\n }\n\n const updateRate = (\n index: number,\n patch: Partial<CommerceModel.ShippingRate> | null,\n ) => {\n const rates = [...(current.rates ?? [])]\n if (patch === null) rates.splice(index, 1)\n else\n rates[index] = {\n id: Aglyn.createResourceUid(),\n zoneId: current.zones?.[0]?.id ?? '',\n name: '',\n kind: 'flat',\n ...rates[index],\n ...patch,\n }\n update({ rates })\n }\n\n const handleSave = useCallback(async () => {\n /**\n * Refuse a save whose seed the server never confirmed (AGL-1358).\n *\n * No create path to exempt: this is a FIXED document path, so the empty\n * `{}` that `store?.shipping ?? {}` yields when the cache has never seen\n * the map is not the harmless blank a fresh uid would be — it replaces\n * the real zones and rates with nothing.\n *\n * The guard WRAPS the write — an early return is a shape you can keep\n * while losing the protection.\n */\n const written = form.edits\n const verdict = await writeGuardedBySeed(\n {\n subject: 'shipping settings',\n unreadable: storeStatus === 'error',\n fromCache: storeFromCache,\n listen: storeListen,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'settings', 'store'),\n { shipping: current },\n { merge: true },\n )\n },\n )\n // Before `settle`, so a refusal keeps every zone and rate that\n // was typed on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n form.settle(written)\n enqueueSnackbar('Shipping settings saved', {\n variant: 'success',\n persist: false,\n })\n }, [current, form, firestore, hostId, enqueueSnackbar, storeStatus, storeFromCache, storeListen])\n\n /**\n * Recomputed from `current` on every render, so the block answers for what\n * is typed rather than for what was last saved — a merchant deleting the\n * zone that covered France should see France go uncovered before they\n * commit it, not after.\n */\n const coverage = CommerceModel.summarizeShippingCoverage(current)\n const words = CommerceModel.describeShippingCoverage(coverage)\n /**\n * The one-click half of the fix: a zone claiming everywhere the merchant\n * has not named. It adds the ZONE only — a rate on it prices the parcel,\n * and choosing that price is the merchant's call, not ours. A rate row\n * defaulted here would post at whatever we picked, and a blank flat rate\n * resolves to free.\n */\n const addRestOfWorldZone = () =>\n updateZone(current.zones?.length ?? 0, {\n name: 'Rest of world',\n countries: ['*'],\n })\n\n const usd = (cents: number | undefined) =>\n cents == null ? '' : String(cents / 100)\n const cents = (raw: string) =>\n raw.trim() === '' ? undefined : Math.round(Number(raw) * 100)\n\n return (\n <CardDisplay\n header={'Shipping'}\n help={pluginDocsHelp('shipping', { anchor: '#zones-and-rates' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <Typography variant=\"subtitle2\">{'Zones'}</Typography>\n {(current.zones ?? []).map((zone, index) => (\n <Stack key={zone.id} direction=\"row\" spacing={1}>\n <TextField\n label=\"Zone name\"\n value={zone.name}\n onChange={(event) =>\n updateZone(index, { name: event.target.value })\n }\n size=\"small\"\n sx={{ width: 180 }}\n />\n <TextField\n label=\"Countries\"\n value={zone.countries.join(', ')}\n onChange={(event) =>\n updateZone(index, {\n countries: event.target.value\n .split(',')\n .map((code) => code.trim().toUpperCase())\n .filter(Boolean),\n })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"US, CA — or * for everywhere else\"\n />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() => updateZone(index, null)}\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => updateZone(current.zones?.length ?? 0, {})}\n >\n {'Add zone'}\n </Button>\n\n <Divider />\n <Typography variant=\"subtitle2\">{'Rates'}</Typography>\n {(current.rates ?? []).map((rate, index) => (\n <Stack key={rate.id} spacing={1}>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Zone\"\n value={rate.zoneId}\n onChange={(event) =>\n updateRate(index, { zoneId: event.target.value })\n }\n size=\"small\"\n select\n sx={{ width: 150 }}\n >\n {(current.zones ?? []).map((zone) => (\n <MenuItem key={zone.id} value={zone.id}>\n {zone.name || zone.countries.join(',')}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Name\"\n value={rate.name}\n onChange={(event) =>\n updateRate(index, { name: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Standard\"\n /**\n * A rate with no name is DROPPED at checkout, silently\n * (AGL-1791): Stripe requires a `display_name`, so\n * `resolveCheckoutShippingOptions` skips the row rather than\n * emit a session Stripe would reject. Saved blank it looks\n * like a priced rate on this page and is not one anywhere\n * else, which is the same invisibility the coverage block\n * below exists to end — said on the row that causes it,\n * because the block can only report the destination it costs.\n */\n error={!rate.name.trim()}\n helperText={\n rate.name.trim() ? undefined : 'Needed — checkout drops it'\n }\n />\n <TextField\n label=\"Type\"\n value={rate.kind}\n onChange={(event) =>\n updateRate(index, {\n kind: event.target.value as CommerceModel.ShippingRate['kind'],\n })\n }\n size=\"small\"\n select\n sx={{ width: 170 }}\n >\n <MenuItem value=\"flat\">{'Flat'}</MenuItem>\n <MenuItem value=\"free_over\">{'Free over subtotal'}</MenuItem>\n <MenuItem value=\"price_tiers\">{'Subtotal tiers'}</MenuItem>\n <MenuItem value=\"weight_tiers\">{'Weight tiers'}</MenuItem>\n {carrier.available || rate.kind === 'carrier' ? (\n <MenuItem value=\"carrier\">{'Carrier rates'}</MenuItem>\n ) : null}\n </TextField>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() => updateRate(index, null)}\n >\n {'✕'}\n </Button>\n </Stack>\n {rate.kind === 'carrier' ? (\n <CarrierRateFields\n rate={rate}\n services={carrier.services}\n available={carrier.available}\n fallbacks={(current.rates ?? []).filter(\n (other) =>\n other.id !== rate.id &&\n other.zoneId === rate.zoneId &&\n other.kind !== 'carrier',\n )}\n onChange={(patch) => updateRate(index, patch)}\n />\n ) : rate.kind === 'flat' || rate.kind === 'free_over' ? (\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Price ($)\"\n value={usd(rate.amountCents)}\n onChange={(event) =>\n updateRate(index, { amountCents: cents(event.target.value) })\n }\n size=\"small\"\n sx={{ width: 120 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n {rate.kind === 'free_over' ? (\n <TextField\n label=\"Free at subtotal ($)\"\n value={usd(rate.freeOverCents)}\n onChange={(event) =>\n updateRate(index, {\n freeOverCents: cents(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 160 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n ) : null}\n </Stack>\n ) : (\n <Stack spacing={1} sx={{ pl: 2 }}>\n {(rate.tiers ?? []).map((tier, tierIndex) => (\n <Stack key={tierIndex} direction=\"row\" spacing={1}>\n <TextField\n label={\n rate.kind === 'weight_tiers'\n ? 'Up to (g)'\n : 'Up to subtotal ($)'\n }\n value={\n rate.kind === 'weight_tiers'\n ? tier.upTo\n : tier.upTo / 100\n }\n onChange={(event) => {\n const tiers = [...(rate.tiers ?? [])]\n const value = Number(event.target.value) || 0\n tiers[tierIndex] = {\n ...tier,\n upTo:\n rate.kind === 'weight_tiers'\n ? Math.round(value)\n : Math.round(value * 100),\n }\n updateRate(index, { tiers })\n }}\n size=\"small\"\n sx={{ width: 160 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Price ($)\"\n value={tier.amountCents / 100}\n onChange={(event) => {\n const tiers = [...(rate.tiers ?? [])]\n tiers[tierIndex] = {\n ...tier,\n amountCents: Math.round(\n (Number(event.target.value) || 0) * 100,\n ),\n }\n updateRate(index, { tiers })\n }}\n size=\"small\"\n sx={{ width: 120 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() =>\n updateRate(index, {\n tiers: (rate.tiers ?? []).filter(\n (_item, itemIndex) => itemIndex !== tierIndex,\n ),\n })\n }\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n updateRate(index, {\n tiers: [\n ...(rate.tiers ?? []),\n { upTo: 0, amountCents: 0 },\n ],\n })\n }\n >\n {'Add tier'}\n </Button>\n </Stack>\n )}\n </Stack>\n ))}\n <Button\n size=\"small\"\n disabled={(current.zones?.length ?? 0) === 0}\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => updateRate(current.rates?.length ?? 0, {})}\n >\n {'Add rate'}\n </Button>\n\n <Stack spacing={0}>\n <FormControlLabel\n control={\n <Switch\n size=\"small\"\n checked={Boolean(current.localPickup)}\n onChange={(event) =>\n update({ localPickup: event.target.checked })\n }\n />\n }\n label=\"Offer free local pickup\"\n />\n {/*\n What the toggle does NOT do, said on the toggle (AGL-2325). It\n used to silently switch off every \"we don't ship there\" refusal,\n because pickup resolved for every destination and checkout read a\n non-empty list as coverage. It no longer does — but a merchant\n reading one line of label still has to be told that turning\n collection on is not the same as adding a destination.\n */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {\n 'A free collection choice at checkout. It does not widen where ' +\n 'you ship — a destination none of your rates reaches is still ' +\n 'turned away. To let buyers choose WHERE to collect, with hours ' +\n 'and a ready-for-pickup email, turn on pickup for a location ' +\n 'under Inventory locations; this choice then gives way to it.'\n }\n </Typography>\n </Stack>\n\n <Divider />\n <Typography variant=\"subtitle2\">{'Coverage'}</Typography>\n {coverage.unserved.length > 0 ? (\n <Alert\n severity=\"warning\"\n action={\n coverage.hasRestOfWorldZone ? undefined : (\n <Button\n size=\"small\"\n color=\"inherit\"\n onClick={addRestOfWorldZone}\n >\n {'Add rest-of-world zone'}\n </Button>\n )\n }\n >\n <AlertTitle>{words.headline}</AlertTitle>\n {words.detail}\n </Alert>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {words.note}\n </Typography>\n )}\n {words.asks ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {words.asks}\n </Typography>\n ) : null}\n\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n disabled={!form.dirty || checking}\n onClick={handleSave}\n sx={{ alignSelf: 'flex-start' }}\n >\n {'Save shipping settings'}\n </Button>\n {form.dirty && checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {seedCheckingText('shipping settings')}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nShippingSettingsCard.displayName = 'ShippingSettingsCard'\n\nexport default ShippingSettingsCard\n\ninterface CarrierRateFieldsProps {\n rate: CommerceModel.ShippingRate\n services: Array<{ serviceKey: string; label: string }>\n available: boolean\n /** The zone's other rates, any of which checkout may fall back to. */\n fallbacks: CommerceModel.ShippingRate[]\n onChange: (patch: Partial<CommerceModel.ShippingRate>) => void\n}\n\n/**\n * A carrier rate's options (AGL-3612): which services checkout offers, what\n * is added to each quote, and the zone's rate offered when no live quote is.\n */\nfunction CarrierRateFields(props: CarrierRateFieldsProps) {\n const { rate, services, available, fallbacks, onChange } = props\n const options = rate.carrier ?? {}\n const set = (patch: Partial<CommerceModel.CarrierRateSettings>) =>\n onChange({ carrier: { ...options, ...patch } })\n const picked = new Set(options.services ?? [])\n return (\n <Stack spacing={1} sx={{ pl: 2 }}>\n {!available ? (\n <Alert severity=\"info\">\n {'Live carrier rates are not available on this site right now, so checkout offers the fallback rate.'}\n </Alert>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Shoppers see each carrier’s price for their address. Leave every service unticked to offer all of them.'}\n </Typography>\n <Stack direction=\"row\" sx={{ flexWrap: 'wrap', columnGap: 2 }}>\n {services.map((service) => (\n <FormControlLabel\n key={service.serviceKey}\n control={\n <Switch\n size=\"small\"\n checked={picked.has(service.serviceKey)}\n onChange={(event) =>\n set({\n services: event.target.checked\n ? [...picked, service.serviceKey]\n : [...picked].filter((key) => key !== service.serviceKey),\n })\n }\n />\n }\n label={service.label}\n />\n ))}\n </Stack>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Markup (%)\"\n value={options.markupPct ?? ''}\n onChange={(event) => {\n const pct = Number(event.target.value)\n set({ markupPct: Number.isFinite(pct) && pct > 0 ? Math.min(pct, 500) : 0 })\n }}\n size=\"small\"\n sx={{ width: 120 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Handling fee ($)\"\n value={options.handlingCents ? options.handlingCents / 100 : ''}\n onChange={(event) => {\n const dollars = Number(event.target.value)\n set({ handlingCents: Number.isFinite(dollars) && dollars > 0 ? Math.round(dollars * 100) : 0 })\n }}\n size=\"small\"\n sx={{ width: 150 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n select\n label=\"If no live rate\"\n value={options.fallbackRateId ?? ''}\n onChange={(event) => set({ fallbackRateId: event.target.value })}\n size=\"small\"\n sx={{ minWidth: 200 }}\n error={!options.fallbackRateId}\n helperText={\n options.fallbackRateId ? undefined : 'Pick a rate of this zone, or checkout can’t price without a quote'\n }\n >\n <MenuItem value=\"\">{'None'}</MenuItem>\n {fallbacks.map((fallback) => (\n <MenuItem key={fallback.id} value={fallback.id}>\n {fallback.name || 'Unnamed rate'}\n </MenuItem>\n ))}\n </TextField>\n </Stack>\n </Stack>\n )\n}\n"],"names":["Aglyn","CommerceModel","CardDisplay","useSnackbar","Alert","AlertTitle","Button","Divider","FormControlLabel","MenuItem","Stack","Switch","TextField","Typography","authorizedFetch","doc","setDoc","useCallback","useEffect","useState","useFirestore","useUser","useFirestoreDoc","writeGuardedBySeed","pluginDocsHelp","isSeedChecking","seedCheckingText","useSeedEdits","ShippingSettingsCard","props","current","hostId","firestore","enqueueSnackbar","data","store","status","storeStatus","fromCache","storeFromCache","listen","storeListen","form","shipping","values","checking","unreadable","user","carrier","setCarrier","available","services","live","encodeURIComponent","then","response","ok","json","answer","Boolean","catch","undefined","update","patch","edit","updateZone","index","zones","removed","splice","rates","filter","rate","zoneId","id","createResourceUid","name","countries","updateRate","kind","handleSave","written","edits","verdict","subject","merge","message","variant","persist","settle","coverage","summarizeShippingCoverage","words","describeShippingCoverage","addRestOfWorldZone","length","usd","cents","String","raw","trim","Math","round","Number","header","help","anchor","contentGutterX","contentGutterY","spacing","map","zone","direction","label","value","onChange","event","target","size","sx","width","join","split","code","toUpperCase","flex","placeholder","color","onClick","alignSelf","select","error","helperText","CarrierRateFields","fallbacks","other","amountCents","slotProps","htmlInput","inputMode","freeOverCents","pl","tiers","tier","tierIndex","upTo","_item","itemIndex","disabled","control","checked","localPickup","unserved","severity","action","hasRestOfWorldZone","headline","detail","note","asks","dirty","role","displayName","options","set","picked","Set","flexWrap","columnGap","service","has","serviceKey","key","markupPct","pct","isFinite","min","handlingCents","dollars","fallbackRateId","minWidth","fallback"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,YAAYC,mBAAmB,uBAAa;AAC5C,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,KAAK,EACLC,UAAU,EACVC,MAAM,EACNC,OAAO,EACPC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACxD,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SACEC,eAAe,EACfC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,eAAc;AAC7C,SACEC,cAAc,EACdC,gBAAgB,EAChBC,YAAY,QACP,sDAAqD;AAM5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;cA+K3DC,gBA6CAA;QAkMWA;IA7ZnB,MAAM,EAAEC,MAAM,EAAE,GAAGF;IACnB,MAAMG,YAAYZ;IAClB,MAAM,EAAEa,eAAe,EAAE,GAAG9B;IAC5B,MAAM,EACJ+B,MAAMC,KAAK,EACXC,QAAQC,WAAW,EACnB;;;;;;;;;K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AK;wBACLC,IAAI;4BAAE6D,UAAU;wBAAI;wBACpBjD,OAAO,CAACgC,QAAQgB,cAAc;wBAC9B/C,YACE+B,QAAQgB,cAAc,GAAGtH,YAAY;;0CAGvC,KAACpD;gCAASyG,OAAM;0CAAI;;4BACnBoB,UAAUxB,GAAG,CAAC,CAACuE,yBACd,KAAC5K;oCAA2ByG,OAAOmE,SAAS3G,EAAE;8CAC3C2G,SAASzG,IAAI,IAAI;mCADLyG,SAAS3G,EAAE;;;;;;;AAQtC"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/shipping-settings-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 } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n AlertTitle,\n Button,\n Divider,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { doc, setDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport {\n useFirestoreDoc,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n heldSaveLabel,\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\n\nexport interface ShippingSettingsCardProps {\n hostId: string\n}\n\n/**\n * Shipping settings (AGL-288): zones (countries, '*' = rest of world)\n * and rates (flat / free-over / subtotal or weight tiers), stored on\n * `hosts/{hostId}/settings/store` under `shipping`. Cart checkout (AGL-1707)\n * and buy-now (AGL-1720) both read this document and declare the rates as\n * Stripe `shipping_options` (`planCheckoutShipping`) — until those landed\n * nothing read it, and everything saved here was charged to nobody. Buy-now\n * resolves only for physical one-time sales; draft orders and POS still\n * resolve no shipping at all.\n *\n * WHAT A ZONE LAYOUT COSTS THE SHOPPER (AGL-1721). A session's rates are\n * charged as picked and never re-checked against the address, so the checkout\n * can only offer rates that hold for every country it will ship to. Saving\n * zones whose rates DIFFER therefore makes the storefront ask the shopper\n * where the parcel is going before it can price one, and a destination no\n * zone covers is refused outright rather than shipped for free. One zone, or\n * one '*' zone, needs neither: the shopper is asked nothing.\n *\n * AND THE MERCHANT HAS TO BE ABLE TO SEE IT (AGL-1791). Both consequences\n * were invisible here: a merchant saved zones and the checkouts they refused\n * were refused with nothing on this page saying so, which is a support ticket\n * from someone who did nothing wrong. The coverage block reads\n * `summarizeShippingCoverage` off the same `current` object the save writes,\n * so it moves as the form is typed rather than after a round trip.\n *\n * It escalates to a warning ONLY for a merchant who priced some destinations\n * and not others. A merchant whose rates reach nowhere is not misconfigured —\n * that store charges no shipping and refuses nobody — and warning them would\n * nag every store selling downloads.\n */\nexport function ShippingSettingsCard(props: ShippingSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const {\n data: store,\n status: storeStatus,\n /**\n * The settings doc this form is seeded from is unconfirmed by the server\n * (AGL-1358). `current` is `draft ?? store?.shipping ?? {}` and the save\n * writes `{shipping: current}`, so `merge: true` protects the doc's other\n * maps and nothing inside this one — `zones` and `rates` are arrays, and\n * a merge replaces an array wholesale. Against a cached read, adding one\n * rate restores that snapshot's whole price table, and a zone that\n * disappears with it means `resolveShippingRates` matches nothing, which\n * is a checkout offering no shipping option at all.\n */\n fromCache: storeFromCache,\n listen: storeListen,\n } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n // What was typed, kept as edits over the stored settings, and Save held\n // until the server has confirmed them (AGL-4047).\n const form = useSeedEdits<CommerceModel.ShippingSettings>(store?.shipping ?? {})\n const current = form.values\n const checking = isSeedChecking({ fromCache: storeFromCache, unreadable: storeStatus === 'error' })\n /*\n * Live carrier rates (AGL-3612) are offered only where a plugin quotes\n * carriers for this site — the server asks core's quoter seam. A rate\n * already saved as `carrier` stays editable either way, so a merchant can\n * still see and change what checkout falls back to.\n */\n const { data: user } = useUser()\n const [carrier, setCarrier] = useState<{\n available: boolean\n services: Array<{ serviceKey: string; label: string }>\n }>({ available: false, services: [] })\n useEffect(() => {\n let live = true\n authorizedFetch(user, `/api/commerce/shipping/carrier-rates?hostId=${encodeURIComponent(hostId)}`)\n .then((response) => (response.ok ? response.json() : null))\n .then((answer) => {\n if (live && answer) setCarrier({ available: Boolean(answer.available), services: answer.services ?? [] })\n })\n .catch(() => undefined)\n return () => {\n live = false\n }\n }, [hostId, user])\n const update = (patch: Partial<CommerceModel.ShippingSettings>) =>\n form.edit(patch)\n\n const updateZone = (\n index: number,\n patch: Partial<CommerceModel.ShippingZone> | null,\n ) => {\n const zones = [...(current.zones ?? [])]\n if (patch === null) {\n const removed = zones.splice(index, 1)[0]\n update({\n zones,\n rates: (current.rates ?? []).filter(\n (rate) => rate.zoneId !== removed?.id,\n ),\n })\n return\n }\n zones[index] = {\n id: Aglyn.createResourceUid(),\n name: '',\n countries: [],\n ...zones[index],\n ...patch,\n }\n update({ zones })\n }\n\n const updateRate = (\n index: number,\n patch: Partial<CommerceModel.ShippingRate> | null,\n ) => {\n const rates = [...(current.rates ?? [])]\n if (patch === null) rates.splice(index, 1)\n else\n rates[index] = {\n id: Aglyn.createResourceUid(),\n zoneId: current.zones?.[0]?.id ?? '',\n name: '',\n kind: 'flat',\n ...rates[index],\n ...patch,\n }\n update({ rates })\n }\n\n const handleSave = useCallback(async () => {\n /**\n * Refuse a save whose seed the server never confirmed (AGL-1358).\n *\n * No create path to exempt: this is a FIXED document path, so the empty\n * `{}` that `store?.shipping ?? {}` yields when the cache has never seen\n * the map is not the harmless blank a fresh uid would be — it replaces\n * the real zones and rates with nothing.\n *\n * The guard WRAPS the write — an early return is a shape you can keep\n * while losing the protection.\n */\n const written = form.edits\n const verdict = await writeGuardedBySeed(\n {\n subject: 'shipping settings',\n unreadable: storeStatus === 'error',\n fromCache: storeFromCache,\n listen: storeListen,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'settings', 'store'),\n { shipping: current },\n { merge: true },\n )\n },\n )\n // Before `settle`, so a refusal keeps every zone and rate that\n // was typed on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n form.settle(written)\n enqueueSnackbar('Shipping settings saved', {\n variant: 'success',\n persist: false,\n })\n }, [current, form, firestore, hostId, enqueueSnackbar, storeStatus, storeFromCache, storeListen])\n\n /**\n * Recomputed from `current` on every render, so the block answers for what\n * is typed rather than for what was last saved — a merchant deleting the\n * zone that covered France should see France go uncovered before they\n * commit it, not after.\n */\n const coverage = CommerceModel.summarizeShippingCoverage(current)\n const words = CommerceModel.describeShippingCoverage(coverage)\n /**\n * The one-click half of the fix: a zone claiming everywhere the merchant\n * has not named. It adds the ZONE only — a rate on it prices the parcel,\n * and choosing that price is the merchant's call, not ours. A rate row\n * defaulted here would post at whatever we picked, and a blank flat rate\n * resolves to free.\n */\n const addRestOfWorldZone = () =>\n updateZone(current.zones?.length ?? 0, {\n name: 'Rest of world',\n countries: ['*'],\n })\n\n const usd = (cents: number | undefined) =>\n cents == null ? '' : String(cents / 100)\n const cents = (raw: string) =>\n raw.trim() === '' ? undefined : Math.round(Number(raw) * 100)\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: 'shipping settings',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n\n return (\n <CardDisplay\n header={'Shipping'}\n help={pluginDocsHelp('shipping', { anchor: '#zones-and-rates' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <Typography variant=\"subtitle2\">{'Zones'}</Typography>\n {(current.zones ?? []).map((zone, index) => (\n <Stack key={zone.id} direction=\"row\" spacing={1}>\n <TextField\n label=\"Zone name\"\n value={zone.name}\n onChange={(event) =>\n updateZone(index, { name: event.target.value })\n }\n size=\"small\"\n sx={{ width: 180 }}\n />\n <TextField\n label=\"Countries\"\n value={zone.countries.join(', ')}\n onChange={(event) =>\n updateZone(index, {\n countries: event.target.value\n .split(',')\n .map((code) => code.trim().toUpperCase())\n .filter(Boolean),\n })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"US, CA — or * for everywhere else\"\n />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() => updateZone(index, null)}\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => updateZone(current.zones?.length ?? 0, {})}\n >\n {'Add zone'}\n </Button>\n\n <Divider />\n <Typography variant=\"subtitle2\">{'Rates'}</Typography>\n {(current.rates ?? []).map((rate, index) => (\n <Stack key={rate.id} spacing={1}>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Zone\"\n value={rate.zoneId}\n onChange={(event) =>\n updateRate(index, { zoneId: event.target.value })\n }\n size=\"small\"\n select\n sx={{ width: 150 }}\n >\n {(current.zones ?? []).map((zone) => (\n <MenuItem key={zone.id} value={zone.id}>\n {zone.name || zone.countries.join(',')}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Name\"\n value={rate.name}\n onChange={(event) =>\n updateRate(index, { name: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Standard\"\n /**\n * A rate with no name is DROPPED at checkout, silently\n * (AGL-1791): Stripe requires a `display_name`, so\n * `resolveCheckoutShippingOptions` skips the row rather than\n * emit a session Stripe would reject. Saved blank it looks\n * like a priced rate on this page and is not one anywhere\n * else, which is the same invisibility the coverage block\n * below exists to end — said on the row that causes it,\n * because the block can only report the destination it costs.\n */\n error={!rate.name.trim()}\n helperText={\n rate.name.trim() ? undefined : 'Needed — checkout drops it'\n }\n />\n <TextField\n label=\"Type\"\n value={rate.kind}\n onChange={(event) =>\n updateRate(index, {\n kind: event.target.value as CommerceModel.ShippingRate['kind'],\n })\n }\n size=\"small\"\n select\n sx={{ width: 170 }}\n >\n <MenuItem value=\"flat\">{'Flat'}</MenuItem>\n <MenuItem value=\"free_over\">{'Free over subtotal'}</MenuItem>\n <MenuItem value=\"price_tiers\">{'Subtotal tiers'}</MenuItem>\n <MenuItem value=\"weight_tiers\">{'Weight tiers'}</MenuItem>\n {carrier.available || rate.kind === 'carrier' ? (\n <MenuItem value=\"carrier\">{'Carrier rates'}</MenuItem>\n ) : null}\n </TextField>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() => updateRate(index, null)}\n >\n {'✕'}\n </Button>\n </Stack>\n {rate.kind === 'carrier' ? (\n <CarrierRateFields\n rate={rate}\n services={carrier.services}\n available={carrier.available}\n fallbacks={(current.rates ?? []).filter(\n (other) =>\n other.id !== rate.id &&\n other.zoneId === rate.zoneId &&\n other.kind !== 'carrier',\n )}\n onChange={(patch) => updateRate(index, patch)}\n />\n ) : rate.kind === 'flat' || rate.kind === 'free_over' ? (\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Price ($)\"\n value={usd(rate.amountCents)}\n onChange={(event) =>\n updateRate(index, { amountCents: cents(event.target.value) })\n }\n size=\"small\"\n sx={{ width: 120 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n {rate.kind === 'free_over' ? (\n <TextField\n label=\"Free at subtotal ($)\"\n value={usd(rate.freeOverCents)}\n onChange={(event) =>\n updateRate(index, {\n freeOverCents: cents(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 160 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n ) : null}\n </Stack>\n ) : (\n <Stack spacing={1} sx={{ pl: 2 }}>\n {(rate.tiers ?? []).map((tier, tierIndex) => (\n <Stack key={tierIndex} direction=\"row\" spacing={1}>\n <TextField\n label={\n rate.kind === 'weight_tiers'\n ? 'Up to (g)'\n : 'Up to subtotal ($)'\n }\n value={\n rate.kind === 'weight_tiers'\n ? tier.upTo\n : tier.upTo / 100\n }\n onChange={(event) => {\n const tiers = [...(rate.tiers ?? [])]\n const value = Number(event.target.value) || 0\n tiers[tierIndex] = {\n ...tier,\n upTo:\n rate.kind === 'weight_tiers'\n ? Math.round(value)\n : Math.round(value * 100),\n }\n updateRate(index, { tiers })\n }}\n size=\"small\"\n sx={{ width: 160 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Price ($)\"\n value={tier.amountCents / 100}\n onChange={(event) => {\n const tiers = [...(rate.tiers ?? [])]\n tiers[tierIndex] = {\n ...tier,\n amountCents: Math.round(\n (Number(event.target.value) || 0) * 100,\n ),\n }\n updateRate(index, { tiers })\n }}\n size=\"small\"\n sx={{ width: 120 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() =>\n updateRate(index, {\n tiers: (rate.tiers ?? []).filter(\n (_item, itemIndex) => itemIndex !== tierIndex,\n ),\n })\n }\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n updateRate(index, {\n tiers: [\n ...(rate.tiers ?? []),\n { upTo: 0, amountCents: 0 },\n ],\n })\n }\n >\n {'Add tier'}\n </Button>\n </Stack>\n )}\n </Stack>\n ))}\n <Button\n size=\"small\"\n disabled={(current.zones?.length ?? 0) === 0}\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => updateRate(current.rates?.length ?? 0, {})}\n >\n {'Add rate'}\n </Button>\n\n <Stack spacing={0}>\n <FormControlLabel\n control={\n <Switch\n size=\"small\"\n checked={Boolean(current.localPickup)}\n onChange={(event) =>\n update({ localPickup: event.target.checked })\n }\n />\n }\n label=\"Offer free local pickup\"\n />\n {/*\n What the toggle does NOT do, said on the toggle (AGL-2325). It\n used to silently switch off every \"we don't ship there\" refusal,\n because pickup resolved for every destination and checkout read a\n non-empty list as coverage. It no longer does — but a merchant\n reading one line of label still has to be told that turning\n collection on is not the same as adding a destination.\n */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {\n 'A free collection choice at checkout. It does not widen where ' +\n 'you ship — a destination none of your rates reaches is still ' +\n 'turned away. To let buyers choose WHERE to collect, with hours ' +\n 'and a ready-for-pickup email, turn on pickup for a location ' +\n 'under Inventory locations; this choice then gives way to it.'\n }\n </Typography>\n </Stack>\n\n <Divider />\n <Typography variant=\"subtitle2\">{'Coverage'}</Typography>\n {coverage.unserved.length > 0 ? (\n <Alert\n severity=\"warning\"\n action={\n coverage.hasRestOfWorldZone ? undefined : (\n <Button\n size=\"small\"\n color=\"inherit\"\n onClick={addRestOfWorldZone}\n >\n {'Add rest-of-world zone'}\n </Button>\n )\n }\n >\n <AlertTitle>{words.headline}</AlertTitle>\n {words.detail}\n </Alert>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {words.note}\n </Typography>\n )}\n {words.asks ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {words.asks}\n </Typography>\n ) : null}\n\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n disabled={!form.dirty || held.saving}\n onClick={held.press}\n sx={{ alignSelf: 'flex-start' }}\n >\n {heldSaveLabel(held, 'Save shipping settings')}\n </Button>\n {form.dirty && checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {seedCheckingText('shipping settings')}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nShippingSettingsCard.displayName = 'ShippingSettingsCard'\n\nexport default ShippingSettingsCard\n\ninterface CarrierRateFieldsProps {\n rate: CommerceModel.ShippingRate\n services: Array<{ serviceKey: string; label: string }>\n available: boolean\n /** The zone's other rates, any of which checkout may fall back to. */\n fallbacks: CommerceModel.ShippingRate[]\n onChange: (patch: Partial<CommerceModel.ShippingRate>) => void\n}\n\n/**\n * A carrier rate's options (AGL-3612): which services checkout offers, what\n * is added to each quote, and the zone's rate offered when no live quote is.\n */\nfunction CarrierRateFields(props: CarrierRateFieldsProps) {\n const { rate, services, available, fallbacks, onChange } = props\n const options = rate.carrier ?? {}\n const set = (patch: Partial<CommerceModel.CarrierRateSettings>) =>\n onChange({ carrier: { ...options, ...patch } })\n const picked = new Set(options.services ?? [])\n return (\n <Stack spacing={1} sx={{ pl: 2 }}>\n {!available ? (\n <Alert severity=\"info\">\n {'Live carrier rates are not available on this site right now, so checkout offers the fallback rate.'}\n </Alert>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Shoppers see each carrier’s price for their address. Leave every service unticked to offer all of them.'}\n </Typography>\n <Stack direction=\"row\" sx={{ flexWrap: 'wrap', columnGap: 2 }}>\n {services.map((service) => (\n <FormControlLabel\n key={service.serviceKey}\n control={\n <Switch\n size=\"small\"\n checked={picked.has(service.serviceKey)}\n onChange={(event) =>\n set({\n services: event.target.checked\n ? [...picked, service.serviceKey]\n : [...picked].filter((key) => key !== service.serviceKey),\n })\n }\n />\n }\n label={service.label}\n />\n ))}\n </Stack>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Markup (%)\"\n value={options.markupPct ?? ''}\n onChange={(event) => {\n const pct = Number(event.target.value)\n set({ markupPct: Number.isFinite(pct) && pct > 0 ? Math.min(pct, 500) : 0 })\n }}\n size=\"small\"\n sx={{ width: 120 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Handling fee ($)\"\n value={options.handlingCents ? options.handlingCents / 100 : ''}\n onChange={(event) => {\n const dollars = Number(event.target.value)\n set({ handlingCents: Number.isFinite(dollars) && dollars > 0 ? Math.round(dollars * 100) : 0 })\n }}\n size=\"small\"\n sx={{ width: 150 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n select\n label=\"If no live rate\"\n value={options.fallbackRateId ?? ''}\n onChange={(event) => set({ fallbackRateId: event.target.value })}\n size=\"small\"\n sx={{ minWidth: 200 }}\n error={!options.fallbackRateId}\n helperText={\n options.fallbackRateId ? undefined : 'Pick a rate of this zone, or checkout can’t price without a quote'\n }\n >\n <MenuItem value=\"\">{'None'}</MenuItem>\n {fallbacks.map((fallback) => (\n <MenuItem key={fallback.id} value={fallback.id}>\n {fallback.name || 'Unnamed rate'}\n </MenuItem>\n ))}\n </TextField>\n </Stack>\n </Stack>\n )\n}\n"],"names":["Aglyn","CommerceModel","CardDisplay","useSnackbar","Alert","AlertTitle","Button","Divider","FormControlLabel","MenuItem","Stack","Switch","TextField","Typography","authorizedFetch","doc","setDoc","useCallback","useEffect","useState","useFirestore","useUser","useFirestoreDoc","writeGuardedBySeed","pluginDocsHelp","heldSaveLabel","isSeedChecking","seedCheckingText","useHeldSave","useSeedEdits","ShippingSettingsCard","props","current","hostId","firestore","enqueueSnackbar","data","store","status","storeStatus","fromCache","storeFromCache","listen","storeListen","form","shipping","values","checking","unreadable","user","carrier","setCarrier","available","services","live","encodeURIComponent","then","response","ok","json","answer","Boolean","catch","undefined","update","patch","edit","updateZone","index","zones","removed","splice","rates","filter","rate","zoneId","id","createResourceUid","name","countries","updateRate","kind","handleSave","written","edits","verdict","subject","merge","message","variant","persist","settle","coverage","summarizeShippingCoverage","words","describeShippingCoverage","addRestOfWorldZone","length","usd","cents","String","raw","trim","Math","round","Number","held","onRefused","header","help","anchor","contentGutterX","contentGutterY","spacing","map","zone","direction","label","value","onChange","event","target","size","sx","width","join","split","code","toUpperCase","flex","placeholder","color","onClick","alignSelf","select","error","helperText","CarrierRateFields","fallbacks","other","amountCents","slotProps","htmlInput","inputMode","freeOverCents","pl","tiers","tier","tierIndex","upTo","_item","itemIndex","disabled","control","checked","localPickup","unserved","severity","action","hasRestOfWorldZone","headline","detail","note","asks","dirty","saving","press","role","displayName","options","set","picked","Set","flexWrap","columnGap","service","has","serviceKey","key","markupPct","pct","isFinite","min","handlingCents","dollars","fallbackRateId","minWidth","fallback"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,YAAYC,mBAAmB,uBAAa;AAC5C,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,KAAK,EACLC,UAAU,EACVC,MAAM,EACNC,OAAO,EACPC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACxD,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SACEC,eAAe,EACfC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,eAAc;AAC7C,SACEC,aAAa,EACbC,cAAc,EACdC,gBAAgB,EAChBC,WAAW,EACXC,YAAY,QACP,sDAAqD;AAM5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;cAsL3DC,gBA6CAA;QAkMWA;IApanB,MAAM,EAAEC,MAAM,EAAE,GAAGF;IACnB,MAAMG,YAAYd;IAClB,MAAM,EAAEe,eAAe,EAAE,GAAGhC;IAC5B,MAAM,EACJiC,MAAMC,KAAK,EACXC,QAAQC,WAAW,EACnB;;;;;;;;;KASC,GACDC,WAAWC,cAAc,EAC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ACnI;wBACC0H,MAAM;wBACNjB,OAAM;wBACNC,KAAK,GAAEmD,0BAAAA,QAAQgB,cAAc,YAAtBhB,0BAA0B;wBACjClD,UAAU,CAACC,QAAUkD,IAAI;gCAAEe,gBAAgBjE,MAAMC,MAAM,CAACH,KAAK;4BAAC;wBAC9DI,MAAK;wBACLC,IAAI;4BAAE+D,UAAU;wBAAI;wBACpBnD,OAAO,CAACkC,QAAQgB,cAAc;wBAC9BjD,YACEiC,QAAQgB,cAAc,GAAG1H,YAAY;;0CAGvC,KAACtD;gCAAS6G,OAAM;0CAAI;;4BACnBoB,UAAUxB,GAAG,CAAC,CAACyE,yBACd,KAAClL;oCAA2B6G,OAAOqE,SAAS/G,EAAE;8CAC3C+G,SAAS7G,IAAI,IAAI;mCADL6G,SAAS/G,EAAE;;;;;;;AAQtC"}
@@ -24,7 +24,7 @@ import { useFirestore, useUser } from "@aglyn/tenant-feature-instance";
24
24
  import { useFirestoreDoc, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
25
25
  import { pluginDocsHelp } from "@aglyn/aglyn";
26
26
  import { writeSiteWideChange } from "@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change";
27
- import { isSeedChecking, seedCheckingText, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
27
+ import { heldSaveLabel, isSeedChecking, seedCheckingText, useHeldSave, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
28
28
  /**
29
29
  * Store settings (AGL-295) on `hosts/{hostId}/settings/store`: the PDP
30
30
  * template screen (drives /products/{slug}), currency display, checkout
@@ -139,6 +139,15 @@ import { isSeedChecking, seedCheckingText, useSeedEdits } from "@aglyn/tenant-fe
139
139
  storeFromCache,
140
140
  storeListen
141
141
  ]);
142
+ // A press while Save is held is kept, and saves once confirmed (AGL-4047).
143
+ const held = useHeldSave(handleSave, {
144
+ checking,
145
+ subject: 'store settings',
146
+ onRefused: (message)=>enqueueSnackbar(message, {
147
+ variant: 'warning',
148
+ persist: false
149
+ })
150
+ });
142
151
  return /*#__PURE__*/ _jsx(CardDisplay, {
143
152
  header: 'Store settings',
144
153
  help: pluginDocsHelp('commerce', {
@@ -246,12 +255,12 @@ import { isSeedChecking, seedCheckingText, useSeedEdits } from "@aglyn/tenant-fe
246
255
  variant: "contained",
247
256
  color: "primary",
248
257
  size: "small",
249
- disabled: !form.dirty || checking,
250
- onClick: handleSave,
258
+ disabled: !form.dirty || held.saving,
259
+ onClick: held.press,
251
260
  sx: {
252
261
  alignSelf: 'flex-start'
253
262
  },
254
- children: 'Save store settings'
263
+ children: heldSaveLabel(held, 'Save store settings')
255
264
  }),
256
265
  form.dirty && checking ? /*#__PURE__*/ _jsx(Typography, {
257
266
  variant: "body2",
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/store-settings-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 { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport {\n useFirestoreDoc,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { writeSiteWideChange } from '@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change'\nimport {\n isSeedChecking,\n seedCheckingText,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\n\nexport interface StoreSettingsCardProps {\n hostId: string\n}\n\ninterface StoreSettings {\n /** Screen rendered for /products/{slug} with product tokens (AGL-292). */\n pdpScreenId?: string\n /** Screen rendered for /collections/{slug} (AGL-298). */\n collectionScreenId?: string\n currency?: string\n guestCheckout?: boolean\n termsUrl?: string\n receiptFooter?: string\n}\n\n/**\n * Store settings (AGL-295) on `hosts/{hostId}/settings/store`: the PDP\n * template screen (drives /products/{slug}), currency display, checkout\n * preferences, and receipt branding. Tax and shipping have their own\n * cards; store password/maintenance live in Site Protection.\n */\nexport function StoreSettingsCard(props: StoreSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const {\n data: store,\n status: storeStatus,\n /**\n * The settings doc this form is seeded from is unconfirmed by the server\n * (AGL-1358). `current` is `draft ?? {…store}` and the save writes all\n * six keys, so `merge: true` protects only the tax and shipping maps that\n * belong to other cards — never this card's own fields. Against a cached\n * read, changing the currency rewrites `guestCheckout`, and the two\n * template ids fall back to `|| null`, which is how a storefront's\n * product and collection URLs start returning 404.\n */\n fromCache: storeFromCache,\n listen: storeListen,\n } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n const { data: host } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId),\n [firestore, hostId],\n )\n /*\n * What was typed, kept as EDITS over the stored settings (AGL-4047), so\n * the server's copy arriving after a keystroke replaces the cache's under\n * every field nobody touched. Save is held until it has (`checking`).\n */\n const form = useSeedEdits<StoreSettings>({\n pdpScreenId: store?.pdpScreenId ?? '',\n collectionScreenId: store?.collectionScreenId ?? '',\n currency: store?.currency ?? 'USD',\n guestCheckout: store?.guestCheckout !== false,\n termsUrl: store?.termsUrl ?? '',\n receiptFooter: store?.receiptFooter ?? '',\n })\n const current = form.values\n const update = (patch: Partial<StoreSettings>) => form.edit(patch)\n const checking = isSeedChecking({\n fromCache: storeFromCache,\n unreadable: storeStatus === 'error',\n })\n\n // Host screen directory: {screenId: path} (AGL-292 template pick).\n const screenEntries = Object.entries(\n (host?.screens ?? {}) as Record<string, string>,\n ).sort(([, a], [, b]) => String(a).localeCompare(String(b)))\n\n const handleSave = useCallback(async () => {\n /**\n * Refuse a save whose seed the server never confirmed (AGL-1358).\n *\n * There is no create path to exempt, and that is deliberate rather than\n * an oversight: unlike a new row at a fresh uid, this writes a FIXED\n * document path, so the all-defaults `current` produced when the cache\n * has never seen this doc is not the harmless blank a fresh uid would\n * be. It would put `USD`, guest checkout on and two null template ids\n * over whatever the server really holds.\n *\n * The guard WRAPS the write — an early return is a shape you can keep\n * while losing the protection.\n */\n const written = form.edits\n const verdict = await writeGuardedBySeed(\n {\n subject: 'store settings',\n unreadable: storeStatus === 'error',\n fromCache: storeFromCache,\n listen: storeListen,\n },\n async () => {\n // The product and collection templates, the currency and the\n // checkout rules render on the live store with no publish step, so\n // the save carries the site's cache drop with it.\n await writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.set(\n doc(firestore, 'hosts', hostId, 'settings', 'store'),\n {\n pdpScreenId: current.pdpScreenId || null,\n collectionScreenId: current.collectionScreenId || null,\n currency: current.currency ?? 'USD',\n guestCheckout: current.guestCheckout !== false,\n termsUrl: current.termsUrl || null,\n receiptFooter: current.receiptFooter || null,\n },\n { merge: true },\n ),\n })\n },\n )\n // Before `settle`, so a refusal keeps every typed value on\n // screen. A save that silently does nothing sends the user back to\n // retype a form that will 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 form.settle(written)\n enqueueSnackbar('Store settings saved', {\n variant: 'success',\n persist: false,\n })\n }, [\n current,\n form,\n firestore,\n hostId,\n user,\n enqueueSnackbar,\n storeStatus,\n storeFromCache,\n storeListen,\n ])\n\n return (\n <CardDisplay\n header={'Store settings'}\n help={pluginDocsHelp('commerce', { anchor: '#store-settings' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <TextField\n label=\"Product page template\"\n value={current.pdpScreenId ?? ''}\n onChange={(event) => update({ pdpScreenId: event.target.value })}\n size=\"small\"\n select\n helperText={\n 'Page rendered at /products/{slug} — design it in the ' +\n 'Besigner with the Product detail block and {{product.*}} tokens.'\n }\n >\n <MenuItem value=\"\">{'None (product URLs 404)'}</MenuItem>\n {screenEntries.map(([screenId, path]) => (\n <MenuItem key={screenId} value={screenId}>\n {`/${path === '/' ? '' : path}`}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Collection page template\"\n value={current.collectionScreenId ?? ''}\n onChange={(event) =>\n update({ collectionScreenId: event.target.value })\n }\n size=\"small\"\n select\n helperText={\n 'Page rendered at /collections/{slug} — drop a Product grid ' +\n 'with source \"A collection\" and {{collection.*}} tokens.'\n }\n >\n <MenuItem value=\"\">{'None (collection URLs 404)'}</MenuItem>\n {screenEntries.map(([screenId, path]) => (\n <MenuItem key={screenId} value={screenId}>\n {`/${path === '/' ? '' : path}`}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Currency\"\n value={current.currency ?? 'USD'}\n onChange={(event) => update({ currency: event.target.value })}\n size=\"small\"\n select\n sx={{ maxWidth: 200 }}\n helperText=\"Charges settle in USD; more currencies are coming\"\n >\n <MenuItem value=\"USD\">{'USD ($)'}</MenuItem>\n </TextField>\n <FormControlLabel\n control={\n <Switch\n size=\"small\"\n checked={current.guestCheckout !== false}\n onChange={(event) =>\n update({ guestCheckout: event.target.checked })\n }\n />\n }\n label=\"Allow guest checkout (no account required)\"\n />\n <TextField\n label=\"Terms URL\"\n value={current.termsUrl ?? ''}\n onChange={(event) => update({ termsUrl: event.target.value })}\n size=\"small\"\n placeholder=\"/terms\"\n helperText=\"Linked from checkout when set\"\n />\n <TextField\n label=\"Receipt footer\"\n value={current.receiptFooter ?? ''}\n onChange={(event) => update({ receiptFooter: event.target.value })}\n size=\"small\"\n multiline\n minRows={2}\n placeholder=\"Thanks for supporting our shop!\"\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Password protection and maintenance mode live under Site ' +\n 'Protection.'}\n </Typography>\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n disabled={!form.dirty || checking}\n onClick={handleSave}\n sx={{ alignSelf: 'flex-start' }}\n >\n {'Save store settings'}\n </Button>\n {form.dirty && checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {seedCheckingText('store settings')}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nStoreSettingsCard.displayName = 'StoreSettingsCard'\n\nexport default StoreSettingsCard\n"],"names":["CardDisplay","useSnackbar","Button","FormControlLabel","MenuItem","Stack","Switch","TextField","Typography","doc","useCallback","useFirestore","useUser","useFirestoreDoc","writeGuardedBySeed","pluginDocsHelp","writeSiteWideChange","isSeedChecking","seedCheckingText","useSeedEdits","StoreSettingsCard","props","current","hostId","firestore","data","user","enqueueSnackbar","store","status","storeStatus","fromCache","storeFromCache","listen","storeListen","host","form","pdpScreenId","collectionScreenId","currency","guestCheckout","termsUrl","receiptFooter","values","update","patch","edit","checking","unreadable","screenEntries","Object","entries","screens","sort","a","b","String","localeCompare","handleSave","written","edits","verdict","subject","write","batch","set","merge","ok","message","variant","persist","settle","header","help","anchor","contentGutterX","contentGutterY","spacing","label","value","onChange","event","target","size","select","helperText","map","screenId","path","sx","maxWidth","control","checked","placeholder","multiline","minRows","color","disabled","dirty","onClick","alignSelf","role","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,MAAM,EACNC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB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":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/store-settings-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 { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport {\n useFirestoreDoc,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { writeSiteWideChange } from '@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change'\nimport {\n heldSaveLabel,\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\n\nexport interface StoreSettingsCardProps {\n hostId: string\n}\n\ninterface StoreSettings {\n /** Screen rendered for /products/{slug} with product tokens (AGL-292). */\n pdpScreenId?: string\n /** Screen rendered for /collections/{slug} (AGL-298). */\n collectionScreenId?: string\n currency?: string\n guestCheckout?: boolean\n termsUrl?: string\n receiptFooter?: string\n}\n\n/**\n * Store settings (AGL-295) on `hosts/{hostId}/settings/store`: the PDP\n * template screen (drives /products/{slug}), currency display, checkout\n * preferences, and receipt branding. Tax and shipping have their own\n * cards; store password/maintenance live in Site Protection.\n */\nexport function StoreSettingsCard(props: StoreSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const {\n data: store,\n status: storeStatus,\n /**\n * The settings doc this form is seeded from is unconfirmed by the server\n * (AGL-1358). `current` is `draft ?? {…store}` and the save writes all\n * six keys, so `merge: true` protects only the tax and shipping maps that\n * belong to other cards — never this card's own fields. Against a cached\n * read, changing the currency rewrites `guestCheckout`, and the two\n * template ids fall back to `|| null`, which is how a storefront's\n * product and collection URLs start returning 404.\n */\n fromCache: storeFromCache,\n listen: storeListen,\n } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n const { data: host } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId),\n [firestore, hostId],\n )\n /*\n * What was typed, kept as EDITS over the stored settings (AGL-4047), so\n * the server's copy arriving after a keystroke replaces the cache's under\n * every field nobody touched. Save is held until it has (`checking`).\n */\n const form = useSeedEdits<StoreSettings>({\n pdpScreenId: store?.pdpScreenId ?? '',\n collectionScreenId: store?.collectionScreenId ?? '',\n currency: store?.currency ?? 'USD',\n guestCheckout: store?.guestCheckout !== false,\n termsUrl: store?.termsUrl ?? '',\n receiptFooter: store?.receiptFooter ?? '',\n })\n const current = form.values\n const update = (patch: Partial<StoreSettings>) => form.edit(patch)\n const checking = isSeedChecking({\n fromCache: storeFromCache,\n unreadable: storeStatus === 'error',\n })\n\n // Host screen directory: {screenId: path} (AGL-292 template pick).\n const screenEntries = Object.entries(\n (host?.screens ?? {}) as Record<string, string>,\n ).sort(([, a], [, b]) => String(a).localeCompare(String(b)))\n\n const handleSave = useCallback(async () => {\n /**\n * Refuse a save whose seed the server never confirmed (AGL-1358).\n *\n * There is no create path to exempt, and that is deliberate rather than\n * an oversight: unlike a new row at a fresh uid, this writes a FIXED\n * document path, so the all-defaults `current` produced when the cache\n * has never seen this doc is not the harmless blank a fresh uid would\n * be. It would put `USD`, guest checkout on and two null template ids\n * over whatever the server really holds.\n *\n * The guard WRAPS the write — an early return is a shape you can keep\n * while losing the protection.\n */\n const written = form.edits\n const verdict = await writeGuardedBySeed(\n {\n subject: 'store settings',\n unreadable: storeStatus === 'error',\n fromCache: storeFromCache,\n listen: storeListen,\n },\n async () => {\n // The product and collection templates, the currency and the\n // checkout rules render on the live store with no publish step, so\n // the save carries the site's cache drop with it.\n await writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.set(\n doc(firestore, 'hosts', hostId, 'settings', 'store'),\n {\n pdpScreenId: current.pdpScreenId || null,\n collectionScreenId: current.collectionScreenId || null,\n currency: current.currency ?? 'USD',\n guestCheckout: current.guestCheckout !== false,\n termsUrl: current.termsUrl || null,\n receiptFooter: current.receiptFooter || null,\n },\n { merge: true },\n ),\n })\n },\n )\n // Before `settle`, so a refusal keeps every typed value on\n // screen. A save that silently does nothing sends the user back to\n // retype a form that will 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 form.settle(written)\n enqueueSnackbar('Store settings saved', {\n variant: 'success',\n persist: false,\n })\n }, [\n current,\n form,\n firestore,\n hostId,\n user,\n enqueueSnackbar,\n storeStatus,\n storeFromCache,\n storeListen,\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: 'store settings',\n onRefused: (message) =>\n enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n\n return (\n <CardDisplay\n header={'Store settings'}\n help={pluginDocsHelp('commerce', { anchor: '#store-settings' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <TextField\n label=\"Product page template\"\n value={current.pdpScreenId ?? ''}\n onChange={(event) => update({ pdpScreenId: event.target.value })}\n size=\"small\"\n select\n helperText={\n 'Page rendered at /products/{slug} — design it in the ' +\n 'Besigner with the Product detail block and {{product.*}} tokens.'\n }\n >\n <MenuItem value=\"\">{'None (product URLs 404)'}</MenuItem>\n {screenEntries.map(([screenId, path]) => (\n <MenuItem key={screenId} value={screenId}>\n {`/${path === '/' ? '' : path}`}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Collection page template\"\n value={current.collectionScreenId ?? ''}\n onChange={(event) =>\n update({ collectionScreenId: event.target.value })\n }\n size=\"small\"\n select\n helperText={\n 'Page rendered at /collections/{slug} — drop a Product grid ' +\n 'with source \"A collection\" and {{collection.*}} tokens.'\n }\n >\n <MenuItem value=\"\">{'None (collection URLs 404)'}</MenuItem>\n {screenEntries.map(([screenId, path]) => (\n <MenuItem key={screenId} value={screenId}>\n {`/${path === '/' ? '' : path}`}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Currency\"\n value={current.currency ?? 'USD'}\n onChange={(event) => update({ currency: event.target.value })}\n size=\"small\"\n select\n sx={{ maxWidth: 200 }}\n helperText=\"Charges settle in USD; more currencies are coming\"\n >\n <MenuItem value=\"USD\">{'USD ($)'}</MenuItem>\n </TextField>\n <FormControlLabel\n control={\n <Switch\n size=\"small\"\n checked={current.guestCheckout !== false}\n onChange={(event) =>\n update({ guestCheckout: event.target.checked })\n }\n />\n }\n label=\"Allow guest checkout (no account required)\"\n />\n <TextField\n label=\"Terms URL\"\n value={current.termsUrl ?? ''}\n onChange={(event) => update({ termsUrl: event.target.value })}\n size=\"small\"\n placeholder=\"/terms\"\n helperText=\"Linked from checkout when set\"\n />\n <TextField\n label=\"Receipt footer\"\n value={current.receiptFooter ?? ''}\n onChange={(event) => update({ receiptFooter: event.target.value })}\n size=\"small\"\n multiline\n minRows={2}\n placeholder=\"Thanks for supporting our shop!\"\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Password protection and maintenance mode live under Site ' +\n 'Protection.'}\n </Typography>\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n disabled={!form.dirty || held.saving}\n onClick={held.press}\n sx={{ alignSelf: 'flex-start' }}\n >\n {heldSaveLabel(held, 'Save store settings')}\n </Button>\n {form.dirty && checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {seedCheckingText('store settings')}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nStoreSettingsCard.displayName = 'StoreSettingsCard'\n\nexport default StoreSettingsCard\n"],"names":["CardDisplay","useSnackbar","Button","FormControlLabel","MenuItem","Stack","Switch","TextField","Typography","doc","useCallback","useFirestore","useUser","useFirestoreDoc","writeGuardedBySeed","pluginDocsHelp","writeSiteWideChange","heldSaveLabel","isSeedChecking","seedCheckingText","useHeldSave","useSeedEdits","StoreSettingsCard","props","current","hostId","firestore","data","user","enqueueSnackbar","store","status","storeStatus","fromCache","storeFromCache","listen","storeListen","host","form","pdpScreenId","collectionScreenId","currency","guestCheckout","termsUrl","receiptFooter","values","update","patch","edit","checking","unreadable","screenEntries","Object","entries","screens","sort","a","b","String","localeCompare","handleSave","written","edits","verdict","subject","write","batch","set","merge","ok","message","variant","persist","settle","held","onRefused","header","help","anchor","contentGutterX","contentGutterY","spacing","label","value","onChange","event","target","size","select","helperText","map","screenId","path","sx","maxWidth","control","checked","placeholder","multiline","minRows","color","disabled","dirty","saving","onClick","press","alignSelf","role","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,MAAM,EACNC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,WAAW,QAAQ,QAAO;AACnC,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SACEC,eAAe,EACfC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,eAAc;AAC7C,SAASC,mBAAmB,QAAQ,gEAA+D;AACnG,SACEC,aAAa,EACbC,cAAc,EACdC,gBAAgB,EAChBC,WAAW,EACXC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28
  import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.component";
29
29
  import { EntitlementGatedCard } from "./entitlement-gate.component.js";
30
30
  import { pluginDocsHelp } from "@aglyn/aglyn";
31
- import { isSeedChecking, seedCheckingText } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
31
+ import { heldSaveLabel, isSeedChecking, seedCheckingText, useHeldSave } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
32
32
  import { useSeedDraft } from "@aglyn/tenant-feature-instance/hooks/use-seed-draft";
33
33
  /**
34
34
  * Dropship suppliers (AGL-289): paid orders whose product points at a
@@ -175,6 +175,15 @@ export function SuppliersCard(props) {
175
175
  firestore,
176
176
  hostId
177
177
  ]);
178
+ // A press while Save is held is kept, and saves once confirmed (AGL-4047).
179
+ const held = useHeldSave(handleSave, {
180
+ checking,
181
+ subject: 'supplier',
182
+ onRefused: (message)=>enqueueSnackbar(message, {
183
+ variant: 'warning',
184
+ persist: false
185
+ })
186
+ });
178
187
  return /*#__PURE__*/ _jsx(EntitlementGatedCard, {
179
188
  help: suppliersHelp,
180
189
  hostId: hostId,
@@ -337,9 +346,9 @@ export function SuppliersCard(props) {
337
346
  /*#__PURE__*/ _jsx(Button, {
338
347
  variant: "contained",
339
348
  color: "primary",
340
- disabled: checking || !(draft == null ? void 0 : draft.name.trim()),
341
- onClick: handleSave,
342
- children: 'Save'
349
+ disabled: !(draft == null ? void 0 : draft.name.trim()) || held.saving,
350
+ onClick: held.press,
351
+ children: heldSaveLabel(held, 'Save')
343
352
  })
344
353
  ]
345
354
  })
@@ -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 isSeedChecking,\n seedCheckingText,\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 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={checking || !draft?.name.trim()}\n onClick={handleSave}\n >\n {'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","isSeedChecking","seedCheckingText","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","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","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,4DA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KA;gDAAMvF,YAAYsF,MAAME,MAAM,CAACJ,KAAK;iDAAKG;oCAGzDjB,MAAK;oCACLsB,aAAY;;8CAEd,KAACrH;oCACC4G,OAAM;oCACNC,KAAK,WAAE7D,yBAAAA,MAAOtB,aAAa,oBAAI;oCAC/BoF,UAAU,CAACC,QACT9D,SAAS,CAAC+D,OACRA,OAAO,aAAKA;gDAAMtF,eAAeqF,MAAME,MAAM,CAACJ,KAAK;iDAAKG;oCAG5DjB,MAAK;oCACLqB,YAAW;;;;sCAGf,MAACxH;;gCACE0D,yBACC,KAACrD;oCAAWiE,SAAQ;oCAAQQ,OAAM;oCAAiB4C,MAAK;oCAAS9B,IAAI;wCAAE+B,IAAI;oCAAO;8CAC/ExG,iBAAiB;qCAElB;8CACJ,KAACrB;oCAAOsG,SAAS,IAAM/C,SAAS;8CAAQ;;8CACxC,KAACvD;oCACCwE,SAAQ;oCACRQ,OAAM;oCACN8C,UAAUlE,YAAY,EAACN,yBAAAA,MAAOzB,IAAI,CAACmC,IAAI;oCACvCsC,SAASvC;8CAER;;;;;;;;;AAOb;AACA9B,cAAc8F,WAAW,GAAG;AAE5B,eAAe9F,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 { 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,cA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CgH,OAAM;oCACNC,KAAK,WAAE/D,yBAAAA,MAAOvB,UAAU,oBAAI;oCAC5BuF,UAAU,CAACC,QACThE,SAAS,CAACiE,OACRA,OAAO,aAAKA;gDAAMzF,YAAYwF,MAAME,MAAM,CAACJ,KAAK;iDAAKG;oCAGzDjB,MAAK;oCACLsB,aAAY;;8CAEd,KAACzH;oCACCgH,OAAM;oCACNC,KAAK,WAAE/D,yBAAAA,MAAOtB,aAAa,oBAAI;oCAC/BsF,UAAU,CAACC,QACThE,SAAS,CAACiE,OACRA,OAAO,aAAKA;gDAAMxF,eAAeuF,MAAME,MAAM,CAACJ,KAAK;iDAAKG;oCAG5DjB,MAAK;oCACLqB,YAAW;;;;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"}
@@ -26,7 +26,7 @@ import { useCallback } from "react";
26
26
  import { useFirestore } from "@aglyn/tenant-feature-instance";
27
27
  import { useFirestoreDoc, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
28
28
  import { pluginDocsHelp } from "@aglyn/aglyn";
29
- import { isSeedChecking, seedCheckingText, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
29
+ import { heldSaveLabel, isSeedChecking, seedCheckingText, useHeldSave, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
30
30
  /**
31
31
  * Tax settings (AGL-285): manual per-region rates (most-specific wins)
32
32
  * or Stripe Tax automatic calculation, stored on
@@ -156,6 +156,15 @@ import { isSeedChecking, seedCheckingText, useSeedEdits } from "@aglyn/tenant-fe
156
156
  storeFromCache,
157
157
  storeListen
158
158
  ]);
159
+ // A press while Save is held is kept, and saves once confirmed (AGL-4047).
160
+ const held = useHeldSave(handleSave, {
161
+ checking,
162
+ subject: 'tax settings',
163
+ onRefused: (message)=>enqueueSnackbar(message, {
164
+ variant: 'warning',
165
+ persist: false
166
+ })
167
+ });
159
168
  return /*#__PURE__*/ _jsx(CardDisplay, {
160
169
  // Another plugin's card scrolls here (the tax service's "Go to Taxes",
161
170
  // AGL-3693), restating this id rather than importing this package.
@@ -473,12 +482,12 @@ import { isSeedChecking, seedCheckingText, useSeedEdits } from "@aglyn/tenant-fe
473
482
  // An undecided store saves the choice on screen as it stands. The
474
483
  // select fires no change for the option already shown, so waiting
475
484
  // for an edit left "Manual rates" unsaveable and checkout off.
476
- disabled: storeStatus === 'loading' || decided && !form.dirty || checking,
477
- onClick: handleSave,
485
+ disabled: storeStatus === 'loading' || decided && !form.dirty || held.saving,
486
+ onClick: held.press,
478
487
  sx: {
479
488
  alignSelf: 'flex-start'
480
489
  },
481
- children: 'Save tax settings'
490
+ children: heldSaveLabel(held, 'Save tax settings')
482
491
  }),
483
492
  (!decided || form.dirty) && checking ? /*#__PURE__*/ _jsx(Typography, {
484
493
  variant: "body2",