@aglyn/plugins-commerce 1.20.2 → 1.21.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 (33) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/cart.js +106 -9
  3. package/src/lib/components/cart.js.map +1 -1
  4. package/src/lib/components/console/catalog-organization-card.component.js +81 -30
  5. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  6. package/src/lib/components/console/discounts-card.component.js +28 -3
  7. package/src/lib/components/console/discounts-card.component.js.map +1 -1
  8. package/src/lib/components/console/local-delivery-settings-card.component.js +23 -7
  9. package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -1
  10. package/src/lib/components/console/product-editor-dialog.component.js +61 -44
  11. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  12. package/src/lib/components/console/products-hub-card.component.js +32 -4
  13. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  14. package/src/lib/components/console/quote-settings-card.component.js +20 -6
  15. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  16. package/src/lib/components/console/reservations-card.component.js +28 -2
  17. package/src/lib/components/console/reservations-card.component.js.map +1 -1
  18. package/src/lib/components/console/return-settings-card.component.js +28 -15
  19. package/src/lib/components/console/return-settings-card.component.js.map +1 -1
  20. package/src/lib/components/console/shipping-settings-card.component.js +23 -8
  21. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  22. package/src/lib/components/console/store-settings-card.component.js +27 -11
  23. package/src/lib/components/console/store-settings-card.component.js.map +1 -1
  24. package/src/lib/components/console/suppliers-card.component.js +38 -13
  25. package/src/lib/components/console/suppliers-card.component.js.map +1 -1
  26. package/src/lib/components/console/tax-settings-card.component.js +25 -10
  27. package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
  28. package/src/lib/server/cart.js +57 -0
  29. package/src/lib/server/cart.js.map +1 -1
  30. package/src/lib/server/pos-terminal.js +2 -2
  31. package/src/lib/server/pos-terminal.js.map +1 -1
  32. package/src/lib/transfer/product-transfer.js +15 -1
  33. package/src/lib/transfer/product-transfer.js.map +1 -1
@@ -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 { isSeedChecking, seedCheckingText } 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,
@@ -200,16 +225,7 @@ export function SuppliersCard(props) {
200
225
  }),
201
226
  /*#__PURE__*/ _jsx(Button, {
202
227
  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
- },
228
+ onClick: ()=>setDraft(supplierDraftOf(supplier)),
213
229
  children: 'Edit'
214
230
  }),
215
231
  /*#__PURE__*/ _jsx(Button, {
@@ -305,6 +321,15 @@ export function SuppliersCard(props) {
305
321
  }),
306
322
  /*#__PURE__*/ _jsxs(DialogActions, {
307
323
  children: [
324
+ checking ? /*#__PURE__*/ _jsx(Typography, {
325
+ variant: "body2",
326
+ color: "text.secondary",
327
+ role: "status",
328
+ sx: {
329
+ mr: 'auto'
330
+ },
331
+ children: seedCheckingText('supplier')
332
+ }) : null,
308
333
  /*#__PURE__*/ _jsx(Button, {
309
334
  onClick: ()=>setDraft(null),
310
335
  children: 'Cancel'
@@ -312,7 +337,7 @@ export function SuppliersCard(props) {
312
337
  /*#__PURE__*/ _jsx(Button, {
313
338
  variant: "contained",
314
339
  color: "primary",
315
- disabled: !(draft == null ? void 0 : draft.name.trim()),
340
+ disabled: checking || !(draft == null ? void 0 : draft.name.trim()),
316
341
  onClick: handleSave,
317
342
  children: 'Save'
318
343
  })
@@ -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,WAA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G5DlB,MAAK;oCACLsB,YAAW;;;;sCAGf,MAAChH;;8CACC,KAACF;oCAAO6F,SAAS,IAAMhD,SAAS;8CAAQ;;8CACxC,KAAC7C;oCACC2D,SAAQ;oCACRS,OAAM;oCACNgD,UAAU,EAACxE,yBAAAA,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 isSeedChecking,\n seedCheckingText,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { useSeedDraft } from '@aglyn/tenant-feature-instance/hooks/use-seed-draft'\n\nexport interface SuppliersCardProps {\n hostId: string\n}\n\n/**\n * Dropship suppliers (AGL-289): paid orders whose product points at a\n * supplier notify it by email and/or HMAC-signed webhook, and the\n * supplier posts tracking back through a token link — no Aglyn account\n * needed. Assign suppliers per product in the product editor.\n *\n * Gated on `dropshipRouting` since AGL-2080. `server/billing-webhook.ts:2474`\n * enforces it, so an unentitled org could create suppliers, assign them to\n * products, and watch every paid order silently fail to route — a supplier\n * that looks configured and never hears about an order.\n */\n\nconst suppliersHelp = pluginDocsHelp('dropshipSuppliers', { anchor: '#add-a-supplier' })\n\n/** A stored supplier as the dialog edits it. */\nfunction supplierDraftOf(\n supplier: any,\n): CommerceModel.HostSupplier & { id: string | null } {\n return {\n id: supplier.$id,\n name: supplier.name ?? '',\n email: supplier.email ?? '',\n webhookUrl: supplier.webhookUrl ?? '',\n webhookSecret: supplier.webhookSecret ?? '',\n }\n}\n\nexport function SuppliersCard(props: SuppliersCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const {\n status: suppliersStatus,\n /**\n * The list this dialog is seeded from is unconfirmed by the server\n * (AGL-1358). Editing a supplier copies the whole stored row into\n * `draft` and writes all of it back, so a cached seed can restore a\n * ROTATED `webhookSecret` — the supplier keeps signing with a key we\n * meant to retire, and nothing anywhere reports it.\n */\n fromCache: suppliersFromCache,\n listen: suppliersListen,\n rows: suppliers,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<any>(\n /*\n * SERVER-PAGED, and ordered (AGL-2501).\n *\n * `limit(50)` alone is answered in DOCUMENT-ID order, and suppliers are\n * created with a generated id — so the fifty were a pseudo-random sample\n * and the fifty-first was not merely unrendered, it was UNREACHABLE. A\n * merchant with sixty fulfillment partners saw fifty of them and nothing\n * said which.\n *\n * This one really can be paged by the query, unlike the cards that carry a\n * duplicate-name check or a count over the whole set: nothing here is\n * derived from rows off the page. Suppliers are assigned to products by\n * document id in the product editor, and the empty state and the row list\n * are the only consumers.\n *\n * `collectionPage` orders on the document NAME, which cannot be absent —\n * `orderBy('name')` would HIDE every supplier saved without one rather\n * than mis-sorting the list, and `/api/hosts/resources` validates no field\n * for presence.\n */\n (pageLimit) =>\n collectionPage(\n collection(firestore, 'hosts', hostId, 'suppliers'),\n pageLimit,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n /*\n * The dialog's draft, kept as EDITS over the supplier as the list has it\n * now (AGL-4047): opened from the cache's row, the server's copy replaces\n * it under every field nobody touched (a rotated `webhookSecret` among\n * them), and Save is held until it has.\n */\n const [draft, setDraft] = useSeedDraft<\n CommerceModel.HostSupplier & { id: string | null }\n >((opened) => {\n const row = opened.id\n ? suppliers.find((supplier: any) => supplier.$id === opened.id)\n : undefined\n return row ? supplierDraftOf(row) : undefined\n })\n const checking =\n Boolean(draft?.id) &&\n isSeedChecking({\n fromCache: suppliersFromCache,\n unreadable: suppliersStatus === 'error',\n })\n\n const handleSave = useCallback(async () => {\n if (!draft?.name.trim()) return\n const { id, ...data } = draft\n /**\n * Refuse an EDIT whose seed the server never confirmed (AGL-1358).\n *\n * This write has no options argument at all, so it is a full document\n * replace of a payload copied wholesale off the listener — `merge`\n * would not have helped anyway, since every field is present. The one\n * that matters is `webhookSecret`: rotate it somewhere else, come back\n * to a console still serving the old row out of `persistentLocalCache`,\n * rename the supplier, and the retired secret is stored again.\n *\n * Only the edit path is guarded. A NEW supplier is built from blanks at\n * a fresh uid and can overwrite nothing, so refusing it would be a false\n * positive on a path that is never unsafe — and this guard stands in\n * front of the ordinary save.\n *\n * The guard WRAPS the write: an early return is a shape you can keep\n * while losing the protection.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'supplier',\n unreadable: Boolean(id) && suppliersStatus === 'error',\n fromCache: Boolean(id) && suppliersFromCache,\n listen: suppliersListen,\n },\n async () => {\n await setDoc(\n doc(\n firestore,\n 'hosts',\n hostId,\n 'suppliers',\n id ?? Aglyn.createResourceUid(),\n ),\n {\n ...data,\n name: draft.name.trim().slice(0, 80),\n },\n )\n },\n )\n // A refusal keeps the dialog open with what was typed. A save that\n // silently does nothing sends the user back to retype a form that will\n // be refused again just as quietly.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setDraft(null)\n enqueueSnackbar('Supplier saved', { variant: 'success', persist: false })\n }, [\n setDraft,\n draft,\n firestore,\n hostId,\n enqueueSnackbar,\n suppliersFromCache,\n suppliersListen,\n suppliersStatus,\n ])\n\n const handleDelete = useCallback(\n (supplier: any) => async () => {\n const confirmed = await confirm({\n title: 'Remove this supplier?',\n description:\n `Products assigned to \"${supplier.name}\" stop routing; orders ` +\n 'already sent are unaffected.',\n confirmationText: 'Remove',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await deleteDoc(doc(firestore, 'hosts', hostId, 'suppliers', supplier.$id))\n },\n [confirm, firestore, hostId],\n )\n\n return (\n <EntitlementGatedCard\n help={suppliersHelp}\n hostId={hostId}\n feature=\"dropshipRouting\"\n header={'Dropship suppliers'}\n upsell={\n 'Dropship routing forwards each paid order to the right supplier ' +\n 'by email or signed webhook, and takes tracking numbers back ' +\n `without the supplier needing an ${Aglyn.PLATFORM_BRAND_NAME} account.`\n }\n >\n <CardDisplay\n header={'Dropship suppliers'}\n help={suppliersHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {suppliers.length === 0 && page === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Route paid orders straight to a fulfillment partner: add a ' +\n 'supplier, then assign it on products.'}\n </Typography>\n ) : (\n suppliers.map((supplier: any) => (\n <Stack\n key={supplier.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {supplier.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {[supplier.email, supplier.webhookUrl]\n .filter(Boolean)\n .join(' · ') || 'No delivery method set'}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n onClick={() => setDraft(supplierDraftOf(supplier))}\n >\n {'Edit'}\n </Button>\n <Button size=\"small\" color=\"error\" onClick={handleDelete(supplier)}>\n {'Remove'}\n </Button>\n </Stack>\n ))\n )}\n {suppliers.length === 0 && page === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={suppliers.length}\n // No `count`: this is a server window, and nobody knows the total\n // without paying to read it. `hasMore` is the probe row's answer.\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n setDraft({ id: null, name: '', email: '', webhookUrl: '', webhookSecret: '' })\n }\n >\n {'Add supplier'}\n </Button>\n </Stack>\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{draft?.id ? 'Edit supplier' : 'New supplier'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <TextField\n label=\"Name\"\n value={draft?.name ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <TextField\n label=\"Notification email\"\n value={draft?.email ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, email: event.target.value } : prev,\n )\n }\n size=\"small\"\n helperText=\"Gets order details + a tracking link per sale\"\n />\n <TextField\n label=\"Webhook URL\"\n value={draft?.webhookUrl ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, webhookUrl: event.target.value } : prev,\n )\n }\n size=\"small\"\n placeholder=\"https://…\"\n />\n <TextField\n label=\"Webhook secret\"\n value={draft?.webhookSecret ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, webhookSecret: event.target.value } : prev,\n )\n }\n size=\"small\"\n helperText=\"Payloads carry an x-aglyn-signature HMAC header\"\n />\n </DialogContent>\n <DialogActions>\n {checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {seedCheckingText('supplier')}\n </Typography>\n ) : null}\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={checking || !draft?.name.trim()}\n onClick={handleSave}\n >\n {'Save'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n </EntitlementGatedCard>\n )\n}\nSuppliersCard.displayName = 'SuppliersCard'\n\nexport default SuppliersCard\n"],"names":["Aglyn","CardDisplay","useConfirmationContext","useSnackbar","Button","Dialog","DialogActions","DialogContent","DialogTitle","Stack","TextField","Typography","collection","deleteDoc","doc","setDoc","useCallback","useFirestore","collectionPage","usePagedCollection","writeGuardedBySeed","ListPagination","EntitlementGatedCard","pluginDocsHelp","isSeedChecking","seedCheckingText","useSeedDraft","suppliersHelp","anchor","supplierDraftOf","supplier","id","$id","name","email","webhookUrl","webhookSecret","SuppliersCard","props","hostId","firestore","enqueueSnackbar","confirm","status","suppliersStatus","fromCache","suppliersFromCache","listen","suppliersListen","rows","suppliers","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","draft","setDraft","opened","row","find","undefined","checking","Boolean","unreadable","handleSave","trim","data","verdict","subject","createResourceUid","slice","ok","message","variant","persist","handleDelete","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","catch","help","feature","header","upsell","PLATFORM_BRAND_NAME","contentGutterX","contentGutterY","spacing","length","map","direction","sx","alignItems","flex","minWidth","noWrap","filter","join","size","onClick","rowCount","onPageChange","onPageSizeChange","alignSelf","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","label","value","onChange","event","prev","target","autoFocus","mt","helperText","placeholder","role","mr","disabled","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,YAAYA,WAAW,eAAc;AAErC,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,SAAS,EAAEC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AACvE,SAASC,WAAW,QAAQ,QAAO;AACnC,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SACEC,cAAc,EACdC,kBAAkB,EAClBC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,oBAAoB,QAAQ,kCAA8B;AACnE,SAASC,cAAc,QAAQ,eAAc;AAC7C,SACEC,cAAc,EACdC,gBAAgB,QACX,sDAAqD;AAC5D,SAASC,YAAY,QAAQ,sDAAqD;AAMlF;;;;;;;;;;CAUC,GAED,MAAMC,gBAAgBJ,eAAe,qBAAqB;IAAEK,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,EAAEC,MAAM,EAAE,GAAGD;IACnB,MAAME,YAAYvB;IAClB,MAAM,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W,GAAG;AAE5B,eAAe9F,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 { isSeedChecking, seedCheckingText, 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,
@@ -464,13 +473,19 @@ import { pluginDocsHelp } from "@aglyn/aglyn";
464
473
  // An undecided store saves the choice on screen as it stands. The
465
474
  // select fires no change for the option already shown, so waiting
466
475
  // for an edit left "Manual rates" unsaveable and checkout off.
467
- disabled: storeStatus === 'loading' || decided && !draft,
476
+ disabled: storeStatus === 'loading' || decided && !form.dirty || checking,
468
477
  onClick: handleSave,
469
478
  sx: {
470
479
  alignSelf: 'flex-start'
471
480
  },
472
481
  children: 'Save tax settings'
473
- })
482
+ }),
483
+ (!decided || form.dirty) && checking ? /*#__PURE__*/ _jsx(Typography, {
484
+ variant: "body2",
485
+ color: "text.secondary",
486
+ role: "status",
487
+ children: seedCheckingText('tax settings')
488
+ }) : null
474
489
  ]
475
490
  })
476
491
  });
@@ -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;AACh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9D,eAAe;oCAC9BkF,UAAU,GAAElF,mBAAAA,eAAe,sBAAfA,mBAA6B;oCACzCyE,WAAW;wCAAEC,WAAW;4CAAEC,WAAW;wCAAU;oCAAE;;8CAEnD,KAACzF;oCACCgE,OAAM;oCACNC,KAAK,YAAEpD,mBAAAA,QAAQqF,OAAO,qBAAfrF,iBAAiBmD,KAAK,oBAAI;oCACjCE,UAAU,CAACC,QACT7B,WAAW,WAAW;4CAAE0B,OAAOG,MAAMC,MAAM,CAACH,KAAK;wCAAC;oCAEpDI,MAAK;oCACLE,IAAI;wCAAEmB,MAAM;oCAAE;oCACdP,aAAY;oCACZa,YAAW;;;;sCAKf,KAACvG;4BAAMsE,UAAS;sCACb,GAAGzE,oBAAoB,wCAAwC,CAAC,GAC/D,8DACA,gEACA;;;;8BAGN,KAACI;oBACC4D,SAAQ;oBACRmB,OAAM;oBACNJ,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 isSeedChecking,\n seedCheckingText,\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 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) || checking}\n onClick={handleSave}\n sx={{ alignSelf: 'flex-start' }}\n >\n {'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","isSeedChecking","seedCheckingText","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","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","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,cAAc,EACdC,gBAAgB,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UAAU,GAAExF,mBAAAA,eAAe,sBAAfA,mBAA6B;oCACzC+E,WAAW;wCAAEC,WAAW;4CAAEC,WAAW;wCAAU;oCAAE;;8CAEnD,KAAChG;oCACCuE,OAAM;oCACNC,KAAK,YAAE1D,mBAAAA,QAAQ2F,OAAO,qBAAf3F,iBAAiByD,KAAK,oBAAI;oCACjCE,UAAU,CAACC,QACT/B,WAAW,WAAW;4CAAE4B,OAAOG,MAAMC,MAAM,CAACH,KAAK;wCAAC;oCAEpDI,MAAK;oCACLE,IAAI;wCAAEmB,MAAM;oCAAE;oCACdP,aAAY;oCACZa,YAAW;;;;sCAKf,KAAC9G;4BAAM6E,UAAS;sCACb,GAAGhF,oBAAoB,wCAAwC,CAAC,GAC/D,8DACA,gEACA;;;;8BAGN,KAACI;oBACCkE,SAAQ;oBACRoB,OAAM;oBACNJ,MAAK;oBACL,kEAAkE;oBAClE,kEAAkE;oBAClE,+DAA+D;oBAC/D8B,UAAUpF,gBAAgB,aAAcW,WAAW,CAACN,KAAKgF,KAAK,IAAK5E;oBACnEmE,SAAS9C;oBACT0B,IAAI;wBAAEqB,WAAW;oBAAa;8BAE7B;;gBAED,CAAA,CAAClE,WAAWN,KAAKgF,KAAK,AAAD,KAAM5E,yBAC3B,KAAC9B;oBAAW2D,SAAQ;oBAAQoB,OAAM;oBAAiB4B,MAAK;8BACrDlG,iBAAiB;qBAElB;;;;AAIZ;AACAE,gBAAgBiG,WAAW,GAAG;AAE9B,eAAejG,gBAAe"}
@@ -20,6 +20,7 @@ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
20
20
  import { isDocumentId } from "@aglyn/tenant-data-admin/server/document-id";
21
21
  import { cartCookieName, mintCartId, readCartId } from "./cart-cookie.js";
22
22
  import { readStoreDay } from "./store-day.js";
23
+ import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
23
24
  /**
24
25
  * Server-backed cart (AGL-293): cookie-keyed doc under
25
26
  * `hosts/{hostId}/carts`. GET returns the resolved cart; POST mutates
@@ -252,12 +253,25 @@ import { readStoreDay } from "./store-day.js";
252
253
  var _productsById_get;
253
254
  return isPosHardwareSkuId((_productsById_get = productsById.get(line.productId)) == null ? void 0 : _productsById_get.hardwareSku);
254
255
  });
256
+ // Where it is going, asked WITH the cart rather than after the first
257
+ // Checkout press: the same plan checkout makes, with no destination yet.
258
+ const askShippingCountry = await shippingCountryNeeded({
259
+ hostRef,
260
+ lines,
261
+ productsById,
262
+ subtotalCents
263
+ });
255
264
  return res.status(200).json(_extends({
256
265
  lines,
257
266
  count: CommerceModel.cartCount(cart),
258
267
  subtotalCents
259
268
  }, hardwareTerms ? {
260
269
  hardwareTerms: true
270
+ } : {}, askShippingCountry ? {
271
+ needsShippingCountry: true,
272
+ shippingCountries: [
273
+ ...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES
274
+ ]
261
275
  } : {}));
262
276
  } catch (error) {
263
277
  console.error(error);
@@ -266,5 +280,48 @@ import { readStoreDay } from "./store-day.js";
266
280
  });
267
281
  }
268
282
  };
283
+ /**
284
+ * Whether checkout will ask this cart where it is shipping to, answered while
285
+ * the cart is shown so the cart can ask up front. A shopper who pressed
286
+ * Checkout used to be refused with "Choose where you’re shipping to." and only
287
+ * then shown the field.
288
+ *
289
+ * The same plan `cart-checkout.ts` makes, with no destination, so the two
290
+ * cannot disagree: rates that differ by zone, or carrier rates, need one. A
291
+ * cart with nothing posted reads nothing more, and a store with one zone, a
292
+ * rest-of-world zone or no shipping at all is never asked. Checkout still asks
293
+ * and enforces the answer on its own; this only moves the question earlier.
294
+ */ async function shippingCountryNeeded(input) {
295
+ let physical = false;
296
+ let totalGrams = 0;
297
+ for (const line of input.lines){
298
+ var _product_type, _ref;
299
+ if (line.unavailable) continue;
300
+ const product = input.productsById.get(line.productId);
301
+ if (!product) continue;
302
+ // A missing `type` reads as physical, as checkout reads it.
303
+ if (((_product_type = product.type) != null ? _product_type : 'physical') !== 'physical') continue;
304
+ physical = true;
305
+ const variant = line.variantId ? product.variants.find((item)=>item.id === line.variantId) : product.variants[0];
306
+ totalGrams += Math.max(0, Number((_ref = variant == null ? void 0 : variant.weightGrams) != null ? _ref : 0)) * line.quantity;
307
+ }
308
+ if (!physical) return false;
309
+ try {
310
+ const storeSettings = await input.hostRef.collection('settings').doc('store').get();
311
+ const plan = await planCheckoutShippingWithCarriers({
312
+ hostId: input.hostRef.id,
313
+ settings: storeSettings.get('shipping'),
314
+ cart: {
315
+ subtotalCents: input.subtotalCents,
316
+ totalGrams
317
+ },
318
+ destination: {}
319
+ });
320
+ return plan.refusal === 'destination-required';
321
+ } catch (unused) {
322
+ // The cart still shows; checkout asks, as it always has.
323
+ return false;
324
+ }
325
+ }
269
326
 
270
327
  //# sourceMappingURL=cart.js.map