@aglyn/plugins-commerce 1.20.3 → 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 (51) 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/cart.js +106 -9
  5. package/src/lib/components/cart.js.map +1 -1
  6. package/src/lib/components/console/catalog-organization-card.component.js +102 -32
  7. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  8. package/src/lib/components/console/discounts-card.component.js +39 -5
  9. package/src/lib/components/console/discounts-card.component.js.map +1 -1
  10. package/src/lib/components/console/local-delivery-settings-card.component.js +34 -9
  11. package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -1
  12. package/src/lib/components/console/product-editor-dialog.component.js +72 -46
  13. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  14. package/src/lib/components/console/products-hub-card.component.js +43 -6
  15. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  16. package/src/lib/components/console/quote-settings-card.component.js +31 -8
  17. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  18. package/src/lib/components/console/reservations-card.component.js +39 -4
  19. package/src/lib/components/console/reservations-card.component.js.map +1 -1
  20. package/src/lib/components/console/return-settings-card.component.js +39 -17
  21. package/src/lib/components/console/return-settings-card.component.js.map +1 -1
  22. package/src/lib/components/console/shipping-settings-card.component.js +34 -10
  23. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  24. package/src/lib/components/console/store-settings-card.component.js +38 -13
  25. package/src/lib/components/console/store-settings-card.component.js.map +1 -1
  26. package/src/lib/components/console/suppliers-card.component.js +49 -15
  27. package/src/lib/components/console/suppliers-card.component.js.map +1 -1
  28. package/src/lib/components/console/tax-settings-card.component.js +36 -12
  29. package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
  30. package/src/lib/model/commerce-pos-offline.d.ts +21 -3
  31. package/src/lib/model/commerce-pos-offline.js +17 -5
  32. package/src/lib/model/commerce-pos-offline.js.map +1 -1
  33. package/src/lib/server/cart.js +57 -0
  34. package/src/lib/server/cart.js.map +1 -1
  35. package/src/lib/server/pos-offline-card-order.d.ts +2 -0
  36. package/src/lib/server/pos-offline-card-order.js +6 -2
  37. package/src/lib/server/pos-offline-card-order.js.map +1 -1
  38. package/src/lib/server/pos-offline-card-reconcile.d.ts +5 -1
  39. package/src/lib/server/pos-offline-card-reconcile.js +42 -10
  40. package/src/lib/server/pos-offline-card-reconcile.js.map +1 -1
  41. package/src/lib/server/pos-offline-sync.d.ts +48 -6
  42. package/src/lib/server/pos-offline-sync.js +142 -31
  43. package/src/lib/server/pos-offline-sync.js.map +1 -1
  44. package/src/lib/server/pos-stripe.d.ts +11 -0
  45. package/src/lib/server/pos-stripe.js +14 -0
  46. package/src/lib/server/pos-stripe.js.map +1 -1
  47. package/src/lib/server/pos-terminal.d.ts +21 -1
  48. package/src/lib/server/pos-terminal.js +41 -7
  49. package/src/lib/server/pos-terminal.js.map +1 -1
  50. package/src/lib/transfer/product-transfer.js +15 -1
  51. package/src/lib/transfer/product-transfer.js.map +1 -1
@@ -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, 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 { writeSiteWideChange } from '@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change'\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 const [draft, setDraft] = useState<StoreSettings | null>(null)\n const current: StoreSettings = draft ?? {\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 update = (patch: Partial<StoreSettings>) =>\n setDraft({ ...current, ...patch })\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 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 `setDraft(null)`, 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 setDraft(null)\n enqueueSnackbar('Store settings saved', {\n variant: 'success',\n persist: false,\n })\n }, [\n current,\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={!draft}\n onClick={handleSave}\n sx={{ alignSelf: 'flex-start' }}\n >\n {'Save store settings'}\n </Button>\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","useState","useFirestore","useUser","useFirestoreDoc","writeGuardedBySeed","pluginDocsHelp","writeSiteWideChange","StoreSettingsCard","props","current","hostId","firestore","data","user","enqueueSnackbar","store","status","storeStatus","fromCache","storeFromCache","listen","storeListen","host","draft","setDraft","pdpScreenId","collectionScreenId","currency","guestCheckout","termsUrl","receiptFooter","update","patch","screenEntries","Object","entries","screens","sort","a","b","String","localeCompare","handleSave","verdict","subject","unreadable","write","batch","set","merge","ok","message","variant","persist","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","onClick","alignSelf","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,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAASC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C,QACThC,OAAO;gCAAEH,eAAemC,MAAMC,MAAM,CAACU,OAAO;4BAAC;;oBAInDd,OAAM;;8BAER,KAAChE;oBACCgE,OAAM;oBACNC,KAAK,GAAEpD,oBAAAA,QAAQoB,QAAQ,YAAhBpB,oBAAoB;oBAC3BqD,UAAU,CAACC,QAAUhC,OAAO;4BAAEF,UAAUkC,MAAMC,MAAM,CAACH,KAAK;wBAAC;oBAC3DI,MAAK;oBACLU,aAAY;oBACZR,YAAW;;8BAEb,KAACvE;oBACCgE,OAAM;oBACNC,KAAK,GAAEpD,yBAAAA,QAAQqB,aAAa,YAArBrB,yBAAyB;oBAChCqD,UAAU,CAACC,QAAUhC,OAAO;4BAAED,eAAeiC,MAAMC,MAAM,CAACH,KAAK;wBAAC;oBAChEI,MAAK;oBACLW,SAAS;oBACTC,SAAS;oBACTF,aAAY;;8BAEd,KAAC9E;oBAAWuD,SAAQ;oBAAU0B,OAAM;8BACjC,8DACC;;8BAEJ,KAACvF;oBACC6D,SAAQ;oBACR0B,OAAM;oBACNb,MAAK;oBACLc,UAAU,CAACxD;oBACXyD,SAAStC;oBACT6B,IAAI;wBAAEU,WAAW;oBAAa;8BAE7B;;;;;AAKX;AACA1E,kBAAkB2E,WAAW,GAAG;AAEhC,eAAe3E,kBAAiB"}
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 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,YAAY,QACP,sDAAqD;AAiB5D;;;;;CAKC,GACD,OAAO,SAASC,kBAAkBC,KAA6B;iDA6I9CC,sBAkBAA,6BAoBAA,mBAuBAA,mBAQAA;IAjNf,MAAM,EAAEC,MAAM,EAAE,GAAGF;IACnB,MAAMG,YAAYf;IAClB,MAAM,EAAEgB,MAAMC,IAAI,EAAE,GAAGhB;IACvB,MAAM,EAAEiB,eAAe,EAAE,GAAG5B;IAC5B,MAAM,EACJ0B,MAAMG,KAAK,EACXC,QAAQC,WAAW,EACnB;;;;;;;;KAQC,GACDC,WAAWC,cAAc,EACzBC,QAAQC,WAAW,EACpB,GAAGvB,gBACF,IAAMJ,IA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,KAAK;wBAAC;oBAC3DI,MAAK;oBACLU,aAAY;oBACZR,YAAW;;8BAEb,KAAClF;oBACC2E,OAAM;oBACNC,KAAK,GAAE3D,yBAAAA,QAAQoB,aAAa,YAArBpB,yBAAyB;oBAChC4D,UAAU,CAACC,QAAUvC,OAAO;4BAAEF,eAAeyC,MAAMC,MAAM,CAACH,KAAK;wBAAC;oBAChEI,MAAK;oBACLW,SAAS;oBACTC,SAAS;oBACTF,aAAY;;8BAEd,KAACzF;oBAAW+D,SAAQ;oBAAU6B,OAAM;8BACjC,8DACC;;8BAEJ,KAAClG;oBACCqE,SAAQ;oBACR6B,OAAM;oBACNb,MAAK;oBACLc,UAAU,CAAC/D,KAAKgE,KAAK,IAAI5B,KAAK6B,MAAM;oBACpCC,SAAS9B,KAAK+B,KAAK;oBACnBZ,IAAI;wBAAEa,WAAW;oBAAa;8BAE7BzF,cAAcyD,MAAM;;gBAEtBpC,KAAKgE,KAAK,IAAIrD,yBACb,KAACzC;oBAAW+D,SAAQ;oBAAQ6B,OAAM;oBAAiBO,MAAK;8BACrDxF,iBAAiB;qBAElB;;;;AAIZ;AACAG,kBAAkBsF,WAAW,GAAG;AAEhC,eAAetF,kBAAiB"}
@@ -22,12 +22,14 @@ import { CardDisplay, useConfirmationContext } from "@aglyn/shared-ui-jsx";
22
22
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
23
23
  import { Button, Dialog, DialogActions, DialogContent, DialogTitle, Stack, TextField, Typography } from "@mui/material";
24
24
  import { collection, deleteDoc, doc, setDoc } from "firebase/firestore";
25
- import { useCallback, useState } from "react";
25
+ import { useCallback } from "react";
26
26
  import { useFirestore } from "@aglyn/tenant-feature-instance";
27
27
  import { collectionPage, usePagedCollection, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
28
28
  import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.component";
29
29
  import { EntitlementGatedCard } from "./entitlement-gate.component.js";
30
30
  import { pluginDocsHelp } from "@aglyn/aglyn";
31
+ import { heldSaveLabel, isSeedChecking, seedCheckingText, useHeldSave } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
32
+ import { useSeedDraft } from "@aglyn/tenant-feature-instance/hooks/use-seed-draft";
31
33
  /**
32
34
  * Dropship suppliers (AGL-289): paid orders whose product points at a
33
35
  * supplier notify it by email and/or HMAC-signed webhook, and the
@@ -41,6 +43,16 @@ import { pluginDocsHelp } from "@aglyn/aglyn";
41
43
  */ const suppliersHelp = pluginDocsHelp('dropshipSuppliers', {
42
44
  anchor: '#add-a-supplier'
43
45
  });
46
+ /** A stored supplier as the dialog edits it. */ function supplierDraftOf(supplier) {
47
+ var _supplier_name, _supplier_email, _supplier_webhookUrl, _supplier_webhookSecret;
48
+ return {
49
+ id: supplier.$id,
50
+ name: (_supplier_name = supplier.name) != null ? _supplier_name : '',
51
+ email: (_supplier_email = supplier.email) != null ? _supplier_email : '',
52
+ webhookUrl: (_supplier_webhookUrl = supplier.webhookUrl) != null ? _supplier_webhookUrl : '',
53
+ webhookSecret: (_supplier_webhookSecret = supplier.webhookSecret) != null ? _supplier_webhookSecret : ''
54
+ };
55
+ }
44
56
  export function SuppliersCard(props) {
45
57
  var _ref, _ref1, _ref2, _ref3;
46
58
  const { hostId } = props;
@@ -78,7 +90,19 @@ export function SuppliersCard(props) {
78
90
  ], {
79
91
  idField: '$id'
80
92
  });
81
- const [draft, setDraft] = useState(null);
93
+ /*
94
+ * The dialog's draft, kept as EDITS over the supplier as the list has it
95
+ * now (AGL-4047): opened from the cache's row, the server's copy replaces
96
+ * it under every field nobody touched (a rotated `webhookSecret` among
97
+ * them), and Save is held until it has.
98
+ */ const [draft, setDraft] = useSeedDraft((opened)=>{
99
+ const row = opened.id ? suppliers.find((supplier)=>supplier.$id === opened.id) : undefined;
100
+ return row ? supplierDraftOf(row) : undefined;
101
+ });
102
+ const checking = Boolean(draft == null ? void 0 : draft.id) && isSeedChecking({
103
+ fromCache: suppliersFromCache,
104
+ unreadable: suppliersStatus === 'error'
105
+ });
82
106
  const handleSave = useCallback(async ()=>{
83
107
  if (!(draft == null ? void 0 : draft.name.trim())) return;
84
108
  const { id } = draft, data = _object_without_properties_loose(draft, [
@@ -126,6 +150,7 @@ export function SuppliersCard(props) {
126
150
  persist: false
127
151
  });
128
152
  }, [
153
+ setDraft,
129
154
  draft,
130
155
  firestore,
131
156
  hostId,
@@ -150,6 +175,15 @@ export function SuppliersCard(props) {
150
175
  firestore,
151
176
  hostId
152
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
+ });
153
187
  return /*#__PURE__*/ _jsx(EntitlementGatedCard, {
154
188
  help: suppliersHelp,
155
189
  hostId: hostId,
@@ -200,16 +234,7 @@ export function SuppliersCard(props) {
200
234
  }),
201
235
  /*#__PURE__*/ _jsx(Button, {
202
236
  size: "small",
203
- onClick: ()=>{
204
- var _supplier_name, _supplier_email, _supplier_webhookUrl, _supplier_webhookSecret;
205
- return setDraft({
206
- id: supplier.$id,
207
- name: (_supplier_name = supplier.name) != null ? _supplier_name : '',
208
- email: (_supplier_email = supplier.email) != null ? _supplier_email : '',
209
- webhookUrl: (_supplier_webhookUrl = supplier.webhookUrl) != null ? _supplier_webhookUrl : '',
210
- webhookSecret: (_supplier_webhookSecret = supplier.webhookSecret) != null ? _supplier_webhookSecret : ''
211
- });
212
- },
237
+ onClick: ()=>setDraft(supplierDraftOf(supplier)),
213
238
  children: 'Edit'
214
239
  }),
215
240
  /*#__PURE__*/ _jsx(Button, {
@@ -305,6 +330,15 @@ export function SuppliersCard(props) {
305
330
  }),
306
331
  /*#__PURE__*/ _jsxs(DialogActions, {
307
332
  children: [
333
+ checking ? /*#__PURE__*/ _jsx(Typography, {
334
+ variant: "body2",
335
+ color: "text.secondary",
336
+ role: "status",
337
+ sx: {
338
+ mr: 'auto'
339
+ },
340
+ children: seedCheckingText('supplier')
341
+ }) : null,
308
342
  /*#__PURE__*/ _jsx(Button, {
309
343
  onClick: ()=>setDraft(null),
310
344
  children: 'Cancel'
@@ -312,9 +346,9 @@ export function SuppliersCard(props) {
312
346
  /*#__PURE__*/ _jsx(Button, {
313
347
  variant: "contained",
314
348
  color: "primary",
315
- disabled: !(draft == null ? void 0 : draft.name.trim()),
316
- onClick: handleSave,
317
- children: 'Save'
349
+ disabled: !(draft == null ? void 0 : draft.name.trim()) || held.saving,
350
+ onClick: held.press,
351
+ children: heldSaveLabel(held, 'Save')
318
352
  })
319
353
  ]
320
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, useState } 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'\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\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 const [draft, setDraft] = useState<\n (CommerceModel.HostSupplier & { id: string | null }) | null\n >(null)\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 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={() =>\n setDraft({\n id: supplier.$id,\n name: supplier.name ?? '',\n email: supplier.email ?? '',\n webhookUrl: supplier.webhookUrl ?? '',\n webhookSecret: supplier.webhookSecret ?? '',\n })\n }\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 <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!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","useState","useFirestore","collectionPage","usePagedCollection","writeGuardedBySeed","ListPagination","EntitlementGatedCard","pluginDocsHelp","suppliersHelp","anchor","SuppliersCard","props","hostId","firestore","enqueueSnackbar","confirm","status","suppliersStatus","fromCache","suppliersFromCache","listen","suppliersListen","rows","suppliers","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","draft","setDraft","handleSave","name","trim","id","data","verdict","subject","unreadable","Boolean","createResourceUid","slice","ok","message","variant","persist","handleDelete","supplier","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","catch","$id","help","feature","header","upsell","PLATFORM_BRAND_NAME","contentGutterX","contentGutterY","spacing","length","map","direction","sx","alignItems","flex","minWidth","noWrap","email","webhookUrl","filter","join","size","onClick","webhookSecret","rowCount","onPageChange","onPageSizeChange","alignSelf","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","label","value","onChange","event","prev","target","autoFocus","mt","helperText","placeholder","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,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SACEC,cAAc,EACdC,kBAAkB,EAClBC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,4DAA2D;AAC1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BAAAA,MAAOG,IAAI,CAACC,IAAI;oCAC3B6C,SAAS/C;8CAER;;;;;;;;;AAOb;AACAvB,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,cAAc,QAAQ,eAAc;AAC7C,SACEC,aAAa,EACbC,cAAc,EACdC,gBAAgB,EAChBC,WAAW,QACN,sDAAqD;AAC5D,SAASC,YAAY,QAAQ,sDAAqD;AAMlF;;;;;;;;;;CAUC,GAED,MAAMC,gBAAgBN,eAAe,qBAAqB;IAAEO,QAAQ;AAAkB;AAEtF,8CAA8C,GAC9C,SAASC,gBACPC,QAAa;QAILA,gBACCA,iBACKA,sBACGA;IALjB,OAAO;QACLC,IAAID,SAASE,GAAG;QAChBC,IAAI,GAAEH,iBAAAA,SAASG,IAAI,YAAbH,iBAAiB;QACvBI,KAAK,GAAEJ,kBAAAA,SAASI,KAAK,YAAdJ,kBAAkB;QACzBK,UAAU,GAAEL,uBAAAA,SAASK,UAAU,YAAnBL,uBAAuB;QACnCM,aAAa,GAAEN,0BAAAA,SAASM,aAAa,YAAtBN,0BAA0B;IAC3C;AACF;AAEA,OAAO,SAASO,cAAcC,KAAyB;;IACrD,MAAM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ACtB;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"}
@@ -22,10 +22,11 @@ import { CardDisplay } from "@aglyn/shared-ui-jsx";
22
22
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
23
23
  import { Alert, Button, Divider, FormControlLabel, MenuItem, Stack, Switch, TextField, Typography } from "@mui/material";
24
24
  import { doc, setDoc } from "firebase/firestore";
25
- import { useCallback, useState } from "react";
25
+ 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 { heldSaveLabel, isSeedChecking, seedCheckingText, useHeldSave, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
29
30
  /**
30
31
  * Tax settings (AGL-285): manual per-region rates (most-specific wins)
31
32
  * or Stripe Tax automatic calculation, stored on
@@ -49,10 +50,16 @@ import { pluginDocsHelp } from "@aglyn/aglyn";
49
50
  firestore,
50
51
  hostId
51
52
  ]);
52
- const [draft, setDraft] = useState(null);
53
- const current = (_ref = draft != null ? draft : store == null ? void 0 : store.tax) != null ? _ref : {
53
+ // What was typed, kept as edits over the stored settings, and Save held
54
+ // until the server has confirmed them (AGL-4047).
55
+ const form = useSeedEdits((_ref = store == null ? void 0 : store.tax) != null ? _ref : {
54
56
  mode: 'manual'
55
- };
57
+ });
58
+ const current = form.values;
59
+ const checking = isSeedChecking({
60
+ fromCache: storeFromCache,
61
+ unreadable: storeStatus === 'error'
62
+ });
56
63
  /**
57
64
  * Whether anyone has ever answered the tax question for this store
58
65
  * (AGL-1999). Read from the SAVED document, never from `current` — the
@@ -62,7 +69,7 @@ import { pluginDocsHelp } from "@aglyn/aglyn";
62
69
  * sold untaxed. Every storefront path now refuses that state, so the card
63
70
  * has to show it rather than paper over it.
64
71
  */ const decided = storeStatus !== 'loading' && typeof (store == null ? void 0 : (_store_tax = store.tax) == null ? void 0 : _store_tax.mode) === 'string';
65
- const update = (patch)=>setDraft(_extends({}, current, patch));
72
+ const update = (patch)=>form.edit(patch);
66
73
  const updateRate = (index, patch)=>{
67
74
  var _current_rates;
68
75
  const rates = [
@@ -114,7 +121,8 @@ import { pluginDocsHelp } from "@aglyn/aglyn";
114
121
  *
115
122
  * The guard WRAPS the write — an early return is a shape you can keep
116
123
  * while losing the protection.
117
- */ const verdict = await writeGuardedBySeed({
124
+ */ const written = form.edits;
125
+ const verdict = await writeGuardedBySeed({
118
126
  subject: 'tax settings',
119
127
  unreadable: storeStatus === 'error',
120
128
  fromCache: storeFromCache,
@@ -126,20 +134,21 @@ import { pluginDocsHelp } from "@aglyn/aglyn";
126
134
  merge: true
127
135
  });
128
136
  });
129
- // Before `setDraft(null)`, so a refusal keeps every typed rate on screen.
137
+ // Before `settle`, so a refusal keeps every typed rate on screen.
130
138
  if (!verdict.ok) {
131
139
  return void enqueueSnackbar(verdict.message, {
132
140
  variant: 'warning',
133
141
  persist: false
134
142
  });
135
143
  }
136
- setDraft(null);
144
+ form.settle(written);
137
145
  enqueueSnackbar('Tax settings saved', {
138
146
  variant: 'success',
139
147
  persist: false
140
148
  });
141
149
  }, [
142
150
  current,
151
+ form,
143
152
  firestore,
144
153
  hostId,
145
154
  enqueueSnackbar,
@@ -147,6 +156,15 @@ import { pluginDocsHelp } from "@aglyn/aglyn";
147
156
  storeFromCache,
148
157
  storeListen
149
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
+ });
150
168
  return /*#__PURE__*/ _jsx(CardDisplay, {
151
169
  // Another plugin's card scrolls here (the tax service's "Go to Taxes",
152
170
  // AGL-3693), restating this id rather than importing this package.
@@ -464,13 +482,19 @@ import { pluginDocsHelp } from "@aglyn/aglyn";
464
482
  // An undecided store saves the choice on screen as it stands. The
465
483
  // select fires no change for the option already shown, so waiting
466
484
  // for an edit left "Manual rates" unsaveable and checkout off.
467
- disabled: storeStatus === 'loading' || decided && !draft,
468
- onClick: handleSave,
485
+ disabled: storeStatus === 'loading' || decided && !form.dirty || held.saving,
486
+ onClick: held.press,
469
487
  sx: {
470
488
  alignSelf: 'flex-start'
471
489
  },
472
- children: 'Save tax settings'
473
- })
490
+ children: heldSaveLabel(held, 'Save tax settings')
491
+ }),
492
+ (!decided || form.dirty) && checking ? /*#__PURE__*/ _jsx(Typography, {
493
+ variant: "body2",
494
+ color: "text.secondary",
495
+ role: "status",
496
+ children: seedCheckingText('tax settings')
497
+ }) : null
474
498
  ]
475
499
  })
476
500
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/tax-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 { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Button,\n Divider,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { doc, setDoc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport {\n useFirestoreDoc,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\n\nexport interface TaxSettingsCardProps {\n hostId: string\n}\n\n/**\n * Tax settings (AGL-285): manual per-region rates (most-specific wins)\n * or Stripe Tax automatic calculation, stored on\n * `hosts/{hostId}/settings/store` under `tax`. The legacy quick-buy\n * checkout taxes by the store origin; Checkout v2 taxes by destination.\n */\nexport function TaxSettingsCard(props: TaxSettingsCardProps) {\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?.tax ?? {mode: 'manual'}` and\n * the save writes `{tax: current}`, so `merge: true` protects the doc's\n * other maps and nothing inside this one. `mode` is the field that costs\n * money: a cached seed flipping `stripe` back to `manual` stops automatic\n * tax calculation — `resolveTaxRate` returns null in stripe mode — and\n * the store under-collects with nothing anywhere reporting it.\n */\n fromCache: storeFromCache,\n listen: storeListen,\n } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n const [draft, setDraft] = useState<CommerceModel.TaxSettings | null>(null)\n const current: CommerceModel.TaxSettings = draft ?? store?.tax ?? { mode: 'manual' }\n /**\n * Whether anyone has ever answered the tax question for this store\n * (AGL-1999). Read from the SAVED document, never from `current` — the\n * `{ mode: 'manual' }` seed above is local state that has never reached\n * Firestore, and it is exactly what made this invisible: the card looked\n * configured while the server saw `mode: undefined`, took no branch, and\n * sold untaxed. Every storefront path now refuses that state, so the card\n * has to show it rather than paper over it.\n */\n const decided =\n storeStatus !== 'loading' && typeof store?.tax?.mode === 'string'\n const update = (patch: Partial<CommerceModel.TaxSettings>) =>\n setDraft({ ...current, ...patch })\n const updateRate = (\n index: number,\n patch: Partial<CommerceModel.TaxRate> | null,\n ) => {\n const rates = [...(current.rates ?? [])]\n if (patch === null) rates.splice(index, 1)\n else rates[index] = { country: '', pct: 0, ...rates[index], ...patch }\n update({ rates })\n }\n /**\n * One of the flat, per-regime rates (AGL-1969 lodging, AGL-2028 services).\n *\n * A blank field clears the rate rather than storing `NaN`: clearing is how a\n * merchant turns the regime back off, and `Number('')` is 0 while\n * `Number(' ')` is also 0 — neither of which should ever reach the document\n * as a \"rate\".\n */\n const updateFlat = (\n key: 'lodging' | 'service',\n patch: Partial<CommerceModel.FlatTaxRate>,\n ) => update({ [key]: { ...current[key], ...patch } })\n const flatPctText = (key: 'lodging' | 'service') => {\n const pct = current[key]?.pct\n return pct === undefined || pct === null ? '' : String(pct)\n }\n /**\n * Shown under a typed rate this will NOT apply. Silence here would be the\n * failure: `resolveFlatTaxCents` treats an out-of-range percentage as off,\n * so a decimal-point typo would otherwise save cleanly and collect nothing.\n */\n const flatPctProblem = (key: 'lodging' | 'service'): string | null => {\n const raw = current[key]?.pct\n if (raw === undefined || raw === null || String(raw) === '') return null\n if (Number(raw) === 0) return null\n return CommerceModel.isUsableFlatTaxPct(raw)\n ? null\n : `Enter a percentage between 0 and ${CommerceModel.FLAT_TAX_MAX_PCT}. ` +\n 'This rate is not being applied.'\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\n * `{mode: 'manual'}` default produced when the cache has never seen the\n * map is not the harmless blank a fresh uid would be — writing it turns\n * automatic tax calculation off on a store that had it on.\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: 'tax 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 { tax: current },\n { merge: true },\n )\n },\n )\n // Before `setDraft(null)`, so a refusal keeps every typed rate on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setDraft(null)\n enqueueSnackbar('Tax settings saved', { variant: 'success', persist: false })\n }, [current, firestore, hostId, enqueueSnackbar, storeStatus, storeFromCache, storeListen])\n\n return (\n <CardDisplay\n // Another plugin's card scrolls here (the tax service's \"Go to Taxes\",\n // AGL-3693), restating this id rather than importing this package.\n id=\"commerce-store-taxes\"\n header={'Taxes'}\n help={pluginDocsHelp('commerce', { anchor: '#tax-settings' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n {decided ? null : (\n // The store is not selling. Saying so here is the whole point: the\n // silent version of this state charged shoppers an untaxed total.\n <Alert severity=\"warning\">\n {'Choose how this store handles sales tax and save. Until you ' +\n 'do, checkout is turned off — we won’t take an order we can’t ' +\n 'tax correctly.'}\n </Alert>\n )}\n <TextField\n label=\"Calculation\"\n value={current.mode ?? 'manual'}\n onChange={(event) =>\n update({\n mode: event.target.value as 'manual' | 'stripe' | 'none',\n })\n }\n size=\"small\"\n select\n sx={{ maxWidth: 280 }}\n >\n <MenuItem value=\"manual\">{'Manual rates (below)'}</MenuItem>\n <MenuItem value=\"stripe\">{'Stripe Tax (automatic)'}</MenuItem>\n {/* An explicit decision, not an omission (AGL-1999) — the option a\n merchant under a nexus threshold, or selling non-taxable goods,\n needs in order to sell at all. */}\n <MenuItem value=\"none\">{'Don’t collect sales tax'}</MenuItem>\n </TextField>\n {current.mode === 'none' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This store adds no sales tax to any order. Orders still go ' +\n 'through — the decision is recorded, not the tax.'}\n </Typography>\n ) : current.mode === 'stripe' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Stripe Tax calculates per buyer location at checkout. ' +\n 'Activate Stripe Tax in your Stripe dashboard first.'}\n </Typography>\n ) : (\n <>\n <FormControlLabel\n control={\n <Switch\n size=\"small\"\n checked={Boolean(current.pricesIncludeTax)}\n onChange={(event) =>\n update({ pricesIncludeTax: event.target.checked })\n }\n />\n }\n label=\"Prices include tax (VAT-style)\"\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Origin country\"\n value={current.origin?.country ?? ''}\n onChange={(event) =>\n update({\n origin: {\n ...current.origin,\n country: event.target.value.toUpperCase().slice(0, 2),\n },\n })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"US\"\n />\n <TextField\n label=\"Origin state\"\n value={current.origin?.state ?? ''}\n onChange={(event) =>\n update({\n origin: {\n ...current.origin,\n state: event.target.value.toUpperCase().slice(0, 3),\n },\n })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"TX\"\n />\n </Stack>\n {/* Which of the product's three addresses this is. A merchant\n who reads an unlabeled origin as \"our address\" may set it\n from the wrong one: the address the workspace pays Aglyn\n from is a different jurisdiction question, and the payout\n identity is a third. Naming the two it is NOT costs a line\n and prevents a mis-taxed order. */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Where this store ships or sells FROM — the jurisdiction the ' +\n 'manual rates below are applied from. Not the address your ' +\n 'workspace is billed at by Aglyn, and not where your payouts ' +\n 'are sent.'}\n </Typography>\n {(current.rates ?? []).map((rate, index) => (\n <Stack key={index} direction=\"row\" spacing={1}>\n <TextField\n label=\"Country\"\n value={rate.country}\n onChange={(event) =>\n updateRate(index, {\n country: event.target.value.toUpperCase().slice(0, 2),\n })\n }\n size=\"small\"\n sx={{ width: 90 }}\n />\n <TextField\n label=\"State\"\n value={rate.state ?? ''}\n onChange={(event) =>\n updateRate(index, {\n state:\n event.target.value.toUpperCase().slice(0, 3) ||\n undefined,\n })\n }\n size=\"small\"\n sx={{ width: 80 }}\n />\n <TextField\n label=\"%\"\n value={rate.pct}\n onChange={(event) =>\n updateRate(index, { pct: Number(event.target.value) || 0 })\n }\n size=\"small\"\n sx={{ width: 80 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={rate.label ?? ''}\n onChange={(event) =>\n updateRate(index, { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Sales tax\"\n />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() => updateRate(index, null)}\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => updateRate(current.rates?.length ?? 0, {})}\n >\n {'Add rate'}\n </Button>\n </>\n )}\n {/*\n LODGING TAX (AGL-1969) — deliberately OUTSIDE the calculation branch\n above, and deliberately not a `rates[]` row.\n\n The setting above is a goods SALES rate resolved against an address.\n Occupancy tax is a different regime with its own rates, registration\n and return, and it applies to reservations, which sell nights rather\n than goods. Nesting it under \"Manual rates\" would have said the two\n are the same machinery; putting it here says a store on Stripe Tax —\n which cannot compute occupancy tax from these sessions at all — can\n still set one.\n\n It is off until the merchant fills it in, so nothing an existing\n store charges moves.\n */}\n <Divider sx={{ my: 0.5 }} />\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Lodging tax'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Charged on reservations, on top of the price, using the rate ' +\n 'you enter here. It is separate from the sales tax above ' +\n 'because occupancy tax is its own regime with its own rates ' +\n 'and its own return. Leave it blank to charge none — that is ' +\n 'the default.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Rate %\"\n value={flatPctText('lodging')}\n onChange={(event) =>\n updateFlat('lodging', {\n pct:\n event.target.value === ''\n ? undefined\n : Number(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 110 }}\n placeholder=\"0\"\n error={Boolean(flatPctProblem('lodging'))}\n helperText={flatPctProblem('lodging') ?? ' '}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={current.lodging?.label ?? ''}\n onChange={(event) =>\n updateFlat('lodging', { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Occupancy tax\"\n helperText=\"Shown to the guest on the receipt\"\n />\n </Stack>\n {/*\n MECHANISM ONLY, AND NO REMITTANCE DETERMINATION.\n\n Whether a jurisdiction imposes occupancy tax, who must register for\n it and who must remit it are legal conclusions that attach by\n operation of law (AGL-1904/AGL-1956) and are the merchant's under\n the Terms. This copy says what the software DOES and what it does\n not do, and stops there — including the deposit basis, which is a\n real limitation rather than an answer this product has taken.\n */}\n <Alert severity=\"info\">\n {`${PLATFORM_BRAND_NAME} applies the rate you enter and records ` +\n 'what was charged. It does not determine whether this tax ' +\n 'applies to you, at what rate, or where it should be paid — ' +\n 'that is yours to decide.'}\n </Alert>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'On a reservation that takes a deposit, the rate is applied to ' +\n 'the deposit — the amount actually charged here — not to the ' +\n 'whole stay. If tax is due on the full stay, collect the ' +\n 'difference the same way you collect the rest of the balance.'}\n </Typography>\n </Stack>\n {/*\n SERVICE TAX (AGL-2028) — the bookings sibling of the block above,\n and here for the same reason it is not in the bookings plugin's own\n settings: this is the one card a merchant comes to with a tax\n question, and a second tax surface elsewhere is how one of them ends\n up unanswered.\n\n Its EXISTENCE is also the opt-in AGL-2000 wanted. That issue\n declined to apply the goods rate to an appointment partly because\n nothing said the merchant meant these settings to cover bookings; a\n field labelled for services, blank until they fill it in, is them\n saying so.\n */}\n <Divider sx={{ my: 0.5 }} />\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Service tax'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Charged on paid bookings, on top of the price, using the rate ' +\n 'you enter here. It is separate from the sales tax above ' +\n 'because whether a service is taxable is often a different ' +\n 'question from whether goods are. Leave it blank to charge ' +\n 'none — that is the default.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Rate %\"\n value={flatPctText('service')}\n onChange={(event) =>\n updateFlat('service', {\n pct:\n event.target.value === ''\n ? undefined\n : Number(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 110 }}\n placeholder=\"0\"\n error={Boolean(flatPctProblem('service'))}\n helperText={flatPctProblem('service') ?? ' '}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={current.service?.label ?? ''}\n onChange={(event) =>\n updateFlat('service', { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Service tax\"\n helperText=\"Shown to the client on the receipt\"\n />\n </Stack>\n {/* MECHANISM ONLY, AND NO REMITTANCE DETERMINATION — see the\n lodging block above. */}\n <Alert severity=\"info\">\n {`${PLATFORM_BRAND_NAME} applies the rate you enter and records ` +\n 'what was charged. It does not determine whether this tax ' +\n 'applies to you, at what rate, or where it should be paid — ' +\n 'that is yours to decide.'}\n </Alert>\n </Stack>\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n // An undecided store saves the choice on screen as it stands. The\n // select fires no change for the option already shown, so waiting\n // for an edit left \"Manual rates\" unsaveable and checkout off.\n disabled={storeStatus === 'loading' || (decided && !draft)}\n onClick={handleSave}\n sx={{ alignSelf: 'flex-start' }}\n >\n {'Save tax settings'}\n </Button>\n </Stack>\n </CardDisplay>\n )\n}\nTaxSettingsCard.displayName = 'TaxSettingsCard'\n\nexport default TaxSettingsCard\n"],"names":["CommerceModel","PLATFORM_BRAND_NAME","CardDisplay","useSnackbar","Alert","Button","Divider","FormControlLabel","MenuItem","Stack","Switch","TextField","Typography","doc","setDoc","useCallback","useState","useFirestore","useFirestoreDoc","writeGuardedBySeed","pluginDocsHelp","TaxSettingsCard","props","draft","current","flatPctProblem","store","hostId","firestore","enqueueSnackbar","data","status","storeStatus","fromCache","storeFromCache","listen","storeListen","setDraft","tax","mode","decided","update","patch","updateRate","index","rates","splice","country","pct","updateFlat","key","flatPctText","undefined","String","raw","Number","isUsableFlatTaxPct","FLAT_TAX_MAX_PCT","handleSave","verdict","subject","unreadable","merge","ok","message","variant","persist","id","header","help","anchor","contentGutterX","contentGutterY","spacing","severity","label","value","onChange","event","target","size","select","sx","maxWidth","color","control","checked","Boolean","pricesIncludeTax","direction","origin","toUpperCase","slice","width","placeholder","state","map","rate","slotProps","htmlInput","inputMode","flex","onClick","alignSelf","length","my","error","helperText","lodging","service","disabled","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,KAAK,EACLC,MAAM,EACNC,OAAO,EACPC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SACEC,eAAe,EACfC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,eAAc;AAM7C;;;;;CAKC,GACD,OAAO,SAASC,gBAAgBC,KAA2B;QAuBdC,MAkH5BC,6BAqFHA,gBAyGYC,wBA6EAA;QAlXcC,YAmJjBF,iBAeAA,kBAwIFA,kBA6EAA;IAxZnB,MAAM,EAAEG,MAAM,EAAE,GAAGL;IACnB,MAAMM,YAAYX;IAClB,MAAM,EAAEY,eAAe,EAAE,GAAG1B;IAC5B,MAAM,EACJ2B,MAAMJ,KAAK,EACXK,QAAQC,WAAW,EACnB;;;;;;;;KAQC,GACDC,WAAWC,cAAc,EACzBC,QAAQC,WAAW,EACpB,GAAGlB,gBACF,IAAML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NJ,MAAK;oBACL,kEAAkE;oBAClE,kEAAkE;oBAClE,+DAA+D;oBAC/D8B,UAAU9E,gBAAgB,aAAcQ,WAAW,CAACjB;oBACpD+E,SAAS5C;oBACTwB,IAAI;wBAAEqB,WAAW;oBAAa;8BAE7B;;;;;AAKX;AACAlF,gBAAgB0F,WAAW,GAAG;AAE9B,eAAe1F,gBAAe"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/tax-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 { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Button,\n Divider,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { doc, setDoc } from 'firebase/firestore'\nimport { useCallback } from 'react'\nimport { useFirestore } 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 TaxSettingsCardProps {\n hostId: string\n}\n\n/**\n * Tax settings (AGL-285): manual per-region rates (most-specific wins)\n * or Stripe Tax automatic calculation, stored on\n * `hosts/{hostId}/settings/store` under `tax`. The legacy quick-buy\n * checkout taxes by the store origin; Checkout v2 taxes by destination.\n */\nexport function TaxSettingsCard(props: TaxSettingsCardProps) {\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?.tax ?? {mode: 'manual'}` and\n * the save writes `{tax: current}`, so `merge: true` protects the doc's\n * other maps and nothing inside this one. `mode` is the field that costs\n * money: a cached seed flipping `stripe` back to `manual` stops automatic\n * tax calculation — `resolveTaxRate` returns null in stripe mode — and\n * the store under-collects with nothing anywhere reporting it.\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.TaxSettings>(store?.tax ?? { mode: 'manual' })\n const current = form.values\n const checking = isSeedChecking({ fromCache: storeFromCache, unreadable: storeStatus === 'error' })\n /**\n * Whether anyone has ever answered the tax question for this store\n * (AGL-1999). Read from the SAVED document, never from `current` — the\n * `{ mode: 'manual' }` seed above is local state that has never reached\n * Firestore, and it is exactly what made this invisible: the card looked\n * configured while the server saw `mode: undefined`, took no branch, and\n * sold untaxed. Every storefront path now refuses that state, so the card\n * has to show it rather than paper over it.\n */\n const decided =\n storeStatus !== 'loading' && typeof store?.tax?.mode === 'string'\n const update = (patch: Partial<CommerceModel.TaxSettings>) =>\n form.edit(patch)\n const updateRate = (\n index: number,\n patch: Partial<CommerceModel.TaxRate> | null,\n ) => {\n const rates = [...(current.rates ?? [])]\n if (patch === null) rates.splice(index, 1)\n else rates[index] = { country: '', pct: 0, ...rates[index], ...patch }\n update({ rates })\n }\n /**\n * One of the flat, per-regime rates (AGL-1969 lodging, AGL-2028 services).\n *\n * A blank field clears the rate rather than storing `NaN`: clearing is how a\n * merchant turns the regime back off, and `Number('')` is 0 while\n * `Number(' ')` is also 0 — neither of which should ever reach the document\n * as a \"rate\".\n */\n const updateFlat = (\n key: 'lodging' | 'service',\n patch: Partial<CommerceModel.FlatTaxRate>,\n ) => update({ [key]: { ...current[key], ...patch } })\n const flatPctText = (key: 'lodging' | 'service') => {\n const pct = current[key]?.pct\n return pct === undefined || pct === null ? '' : String(pct)\n }\n /**\n * Shown under a typed rate this will NOT apply. Silence here would be the\n * failure: `resolveFlatTaxCents` treats an out-of-range percentage as off,\n * so a decimal-point typo would otherwise save cleanly and collect nothing.\n */\n const flatPctProblem = (key: 'lodging' | 'service'): string | null => {\n const raw = current[key]?.pct\n if (raw === undefined || raw === null || String(raw) === '') return null\n if (Number(raw) === 0) return null\n return CommerceModel.isUsableFlatTaxPct(raw)\n ? null\n : `Enter a percentage between 0 and ${CommerceModel.FLAT_TAX_MAX_PCT}. ` +\n 'This rate is not being applied.'\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\n * `{mode: 'manual'}` default produced when the cache has never seen the\n * map is not the harmless blank a fresh uid would be — writing it turns\n * automatic tax calculation off on a store that had it on.\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: 'tax 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 { tax: current },\n { merge: true },\n )\n },\n )\n // Before `settle`, so a refusal keeps every typed rate 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('Tax settings saved', { variant: 'success', persist: false })\n }, [current, form, firestore, hostId, enqueueSnackbar, storeStatus, storeFromCache, 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: 'tax settings',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n\n return (\n <CardDisplay\n // Another plugin's card scrolls here (the tax service's \"Go to Taxes\",\n // AGL-3693), restating this id rather than importing this package.\n id=\"commerce-store-taxes\"\n header={'Taxes'}\n help={pluginDocsHelp('commerce', { anchor: '#tax-settings' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n {decided ? null : (\n // The store is not selling. Saying so here is the whole point: the\n // silent version of this state charged shoppers an untaxed total.\n <Alert severity=\"warning\">\n {'Choose how this store handles sales tax and save. Until you ' +\n 'do, checkout is turned off — we won’t take an order we can’t ' +\n 'tax correctly.'}\n </Alert>\n )}\n <TextField\n label=\"Calculation\"\n value={current.mode ?? 'manual'}\n onChange={(event) =>\n update({\n mode: event.target.value as 'manual' | 'stripe' | 'none',\n })\n }\n size=\"small\"\n select\n sx={{ maxWidth: 280 }}\n >\n <MenuItem value=\"manual\">{'Manual rates (below)'}</MenuItem>\n <MenuItem value=\"stripe\">{'Stripe Tax (automatic)'}</MenuItem>\n {/* An explicit decision, not an omission (AGL-1999) — the option a\n merchant under a nexus threshold, or selling non-taxable goods,\n needs in order to sell at all. */}\n <MenuItem value=\"none\">{'Don’t collect sales tax'}</MenuItem>\n </TextField>\n {current.mode === 'none' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This store adds no sales tax to any order. Orders still go ' +\n 'through — the decision is recorded, not the tax.'}\n </Typography>\n ) : current.mode === 'stripe' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Stripe Tax calculates per buyer location at checkout. ' +\n 'Activate Stripe Tax in your Stripe dashboard first.'}\n </Typography>\n ) : (\n <>\n <FormControlLabel\n control={\n <Switch\n size=\"small\"\n checked={Boolean(current.pricesIncludeTax)}\n onChange={(event) =>\n update({ pricesIncludeTax: event.target.checked })\n }\n />\n }\n label=\"Prices include tax (VAT-style)\"\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Origin country\"\n value={current.origin?.country ?? ''}\n onChange={(event) =>\n update({\n origin: {\n ...current.origin,\n country: event.target.value.toUpperCase().slice(0, 2),\n },\n })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"US\"\n />\n <TextField\n label=\"Origin state\"\n value={current.origin?.state ?? ''}\n onChange={(event) =>\n update({\n origin: {\n ...current.origin,\n state: event.target.value.toUpperCase().slice(0, 3),\n },\n })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"TX\"\n />\n </Stack>\n {/* Which of the product's three addresses this is. A merchant\n who reads an unlabeled origin as \"our address\" may set it\n from the wrong one: the address the workspace pays Aglyn\n from is a different jurisdiction question, and the payout\n identity is a third. Naming the two it is NOT costs a line\n and prevents a mis-taxed order. */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Where this store ships or sells FROM — the jurisdiction the ' +\n 'manual rates below are applied from. Not the address your ' +\n 'workspace is billed at by Aglyn, and not where your payouts ' +\n 'are sent.'}\n </Typography>\n {(current.rates ?? []).map((rate, index) => (\n <Stack key={index} direction=\"row\" spacing={1}>\n <TextField\n label=\"Country\"\n value={rate.country}\n onChange={(event) =>\n updateRate(index, {\n country: event.target.value.toUpperCase().slice(0, 2),\n })\n }\n size=\"small\"\n sx={{ width: 90 }}\n />\n <TextField\n label=\"State\"\n value={rate.state ?? ''}\n onChange={(event) =>\n updateRate(index, {\n state:\n event.target.value.toUpperCase().slice(0, 3) ||\n undefined,\n })\n }\n size=\"small\"\n sx={{ width: 80 }}\n />\n <TextField\n label=\"%\"\n value={rate.pct}\n onChange={(event) =>\n updateRate(index, { pct: Number(event.target.value) || 0 })\n }\n size=\"small\"\n sx={{ width: 80 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={rate.label ?? ''}\n onChange={(event) =>\n updateRate(index, { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Sales tax\"\n />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() => updateRate(index, null)}\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => updateRate(current.rates?.length ?? 0, {})}\n >\n {'Add rate'}\n </Button>\n </>\n )}\n {/*\n LODGING TAX (AGL-1969) — deliberately OUTSIDE the calculation branch\n above, and deliberately not a `rates[]` row.\n\n The setting above is a goods SALES rate resolved against an address.\n Occupancy tax is a different regime with its own rates, registration\n and return, and it applies to reservations, which sell nights rather\n than goods. Nesting it under \"Manual rates\" would have said the two\n are the same machinery; putting it here says a store on Stripe Tax —\n which cannot compute occupancy tax from these sessions at all — can\n still set one.\n\n It is off until the merchant fills it in, so nothing an existing\n store charges moves.\n */}\n <Divider sx={{ my: 0.5 }} />\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Lodging tax'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Charged on reservations, on top of the price, using the rate ' +\n 'you enter here. It is separate from the sales tax above ' +\n 'because occupancy tax is its own regime with its own rates ' +\n 'and its own return. Leave it blank to charge none — that is ' +\n 'the default.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Rate %\"\n value={flatPctText('lodging')}\n onChange={(event) =>\n updateFlat('lodging', {\n pct:\n event.target.value === ''\n ? undefined\n : Number(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 110 }}\n placeholder=\"0\"\n error={Boolean(flatPctProblem('lodging'))}\n helperText={flatPctProblem('lodging') ?? ' '}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={current.lodging?.label ?? ''}\n onChange={(event) =>\n updateFlat('lodging', { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Occupancy tax\"\n helperText=\"Shown to the guest on the receipt\"\n />\n </Stack>\n {/*\n MECHANISM ONLY, AND NO REMITTANCE DETERMINATION.\n\n Whether a jurisdiction imposes occupancy tax, who must register for\n it and who must remit it are legal conclusions that attach by\n operation of law (AGL-1904/AGL-1956) and are the merchant's under\n the Terms. This copy says what the software DOES and what it does\n not do, and stops there — including the deposit basis, which is a\n real limitation rather than an answer this product has taken.\n */}\n <Alert severity=\"info\">\n {`${PLATFORM_BRAND_NAME} applies the rate you enter and records ` +\n 'what was charged. It does not determine whether this tax ' +\n 'applies to you, at what rate, or where it should be paid — ' +\n 'that is yours to decide.'}\n </Alert>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'On a reservation that takes a deposit, the rate is applied to ' +\n 'the deposit — the amount actually charged here — not to the ' +\n 'whole stay. If tax is due on the full stay, collect the ' +\n 'difference the same way you collect the rest of the balance.'}\n </Typography>\n </Stack>\n {/*\n SERVICE TAX (AGL-2028) — the bookings sibling of the block above,\n and here for the same reason it is not in the bookings plugin's own\n settings: this is the one card a merchant comes to with a tax\n question, and a second tax surface elsewhere is how one of them ends\n up unanswered.\n\n Its EXISTENCE is also the opt-in AGL-2000 wanted. That issue\n declined to apply the goods rate to an appointment partly because\n nothing said the merchant meant these settings to cover bookings; a\n field labelled for services, blank until they fill it in, is them\n saying so.\n */}\n <Divider sx={{ my: 0.5 }} />\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Service tax'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Charged on paid bookings, on top of the price, using the rate ' +\n 'you enter here. It is separate from the sales tax above ' +\n 'because whether a service is taxable is often a different ' +\n 'question from whether goods are. Leave it blank to charge ' +\n 'none — that is the default.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Rate %\"\n value={flatPctText('service')}\n onChange={(event) =>\n updateFlat('service', {\n pct:\n event.target.value === ''\n ? undefined\n : Number(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 110 }}\n placeholder=\"0\"\n error={Boolean(flatPctProblem('service'))}\n helperText={flatPctProblem('service') ?? ' '}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={current.service?.label ?? ''}\n onChange={(event) =>\n updateFlat('service', { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Service tax\"\n helperText=\"Shown to the client on the receipt\"\n />\n </Stack>\n {/* MECHANISM ONLY, AND NO REMITTANCE DETERMINATION — see the\n lodging block above. */}\n <Alert severity=\"info\">\n {`${PLATFORM_BRAND_NAME} applies the rate you enter and records ` +\n 'what was charged. It does not determine whether this tax ' +\n 'applies to you, at what rate, or where it should be paid — ' +\n 'that is yours to decide.'}\n </Alert>\n </Stack>\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n // An undecided store saves the choice on screen as it stands. The\n // select fires no change for the option already shown, so waiting\n // for an edit left \"Manual rates\" unsaveable and checkout off.\n disabled={storeStatus === 'loading' || (decided && !form.dirty) || held.saving}\n onClick={held.press}\n sx={{ alignSelf: 'flex-start' }}\n >\n {heldSaveLabel(held, 'Save tax settings')}\n </Button>\n {(!decided || form.dirty) && checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {seedCheckingText('tax settings')}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nTaxSettingsCard.displayName = 'TaxSettingsCard'\n\nexport default TaxSettingsCard\n"],"names":["CommerceModel","PLATFORM_BRAND_NAME","CardDisplay","useSnackbar","Alert","Button","Divider","FormControlLabel","MenuItem","Stack","Switch","TextField","Typography","doc","setDoc","useCallback","useFirestore","useFirestoreDoc","writeGuardedBySeed","pluginDocsHelp","heldSaveLabel","isSeedChecking","seedCheckingText","useHeldSave","useSeedEdits","TaxSettingsCard","props","current","flatPctProblem","store","hostId","firestore","enqueueSnackbar","data","status","storeStatus","fromCache","storeFromCache","listen","storeListen","form","tax","mode","values","checking","unreadable","decided","update","patch","edit","updateRate","index","rates","splice","country","pct","updateFlat","key","flatPctText","undefined","String","raw","Number","isUsableFlatTaxPct","FLAT_TAX_MAX_PCT","handleSave","written","edits","verdict","subject","merge","ok","message","variant","persist","settle","held","onRefused","id","header","help","anchor","contentGutterX","contentGutterY","spacing","severity","label","value","onChange","event","target","size","select","sx","maxWidth","color","control","checked","Boolean","pricesIncludeTax","direction","origin","toUpperCase","slice","width","placeholder","state","map","rate","slotProps","htmlInput","inputMode","flex","onClick","alignSelf","length","my","error","helperText","lodging","service","disabled","dirty","saving","press","role","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,KAAK,EACLC,MAAM,EACNC,OAAO,EACPC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,QAAQ,QAAO;AACnC,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,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;;;;;CAKC,GACD,OAAO,SAASC,gBAAgBC,KAA2B;cAoJ1CC,6BAqFHA,gBAyGYC,wBA6EAA;QA1XcC,YA2JjBF,iBAeAA,kBAwIFA,kBA6EAA;IAnanB,MAAM,EAAEG,MAAM,EAAE,GAAGJ;IACnB,MAAMK,YAAYf;IAClB,MAAM,EAAEgB,eAAe,EAAE,GAAG7B;IAC5B,MAAM,EACJ8B,MAAMJ,KAAK,EACXK,QAAQC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