@aglyn/plugins-commerce 1.0.0-beta.219 → 1.0.0-beta.220

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 (80) hide show
  1. package/README.md +5 -0
  2. package/package.json +14 -14
  3. package/src/lib/components/console/catalog-organization-card.component.js +626 -446
  4. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  6. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  7. package/src/lib/components/console/product-editor-dialog.component.js +1127 -846
  8. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  9. package/src/lib/components/console/site-member-purchases.component.d.ts +24 -0
  10. package/src/lib/components/console/site-member-purchases.component.js +339 -0
  11. package/src/lib/components/console/site-member-purchases.component.js.map +1 -0
  12. package/src/lib/components/member-signup.js +2 -2
  13. package/src/lib/components/member-signup.js.map +1 -1
  14. package/src/lib/components/newsletter-signup.js +2 -2
  15. package/src/lib/components/newsletter-signup.js.map +1 -1
  16. package/src/lib/constants/operator-alerts.js +5 -3
  17. package/src/lib/constants/operator-alerts.js.map +1 -1
  18. package/src/lib/model/commerce-io.js +1 -1
  19. package/src/lib/model/commerce-io.js.map +1 -1
  20. package/src/lib/model/commerce-record-lists.d.ts +31 -0
  21. package/src/lib/model/commerce-record-lists.js +45 -0
  22. package/src/lib/model/commerce-record-lists.js.map +1 -0
  23. package/src/lib/model/commerce-record-routes.d.ts +18 -0
  24. package/src/lib/model/commerce-record-routes.js +1 -1
  25. package/src/lib/model/commerce-record-routes.js.map +1 -1
  26. package/src/lib/model/commerce-search-sources.js +4 -2
  27. package/src/lib/model/commerce-search-sources.js.map +1 -1
  28. package/src/lib/model/commerce-topics.d.ts +20 -0
  29. package/src/lib/model/commerce-topics.js +33 -0
  30. package/src/lib/model/commerce-topics.js.map +1 -0
  31. package/src/lib/model/index.d.ts +1 -0
  32. package/src/lib/model/index.js +1 -0
  33. package/src/lib/model/index.js.map +1 -1
  34. package/src/lib/model/product-record.d.ts +32 -0
  35. package/src/lib/model/product-record.js +82 -0
  36. package/src/lib/model/product-record.js.map +1 -0
  37. package/src/lib/model/site-member-purchases.d.ts +48 -0
  38. package/src/lib/model/site-member-purchases.js +50 -0
  39. package/src/lib/model/site-member-purchases.js.map +1 -0
  40. package/src/lib/plugin.js +12 -0
  41. package/src/lib/plugin.js.map +1 -1
  42. package/src/lib/server/billing-webhook.js +342 -170
  43. package/src/lib/server/billing-webhook.js.map +1 -1
  44. package/src/lib/server/cart-checkout.js +1 -1
  45. package/src/lib/server/cart-checkout.js.map +1 -1
  46. package/src/lib/server/gift-cards.js +7 -3
  47. package/src/lib/server/gift-cards.js.map +1 -1
  48. package/src/lib/server/low-stock.js +3 -1
  49. package/src/lib/server/low-stock.js.map +1 -1
  50. package/src/lib/server/member-post.js +2 -2
  51. package/src/lib/server/member-post.js.map +1 -1
  52. package/src/lib/server/membership-admin-password.js +4 -1
  53. package/src/lib/server/membership-admin-password.js.map +1 -1
  54. package/src/lib/server/membership-register.js +13 -2
  55. package/src/lib/server/membership-register.js.map +1 -1
  56. package/src/lib/server/newsletter.js +32 -19
  57. package/src/lib/server/newsletter.js.map +1 -1
  58. package/src/lib/server/pos-order.js +1 -1
  59. package/src/lib/server/pos-order.js.map +1 -1
  60. package/src/lib/server/process-abandoned.js +4 -2
  61. package/src/lib/server/process-abandoned.js.map +1 -1
  62. package/src/lib/server/process-restock.js +7 -5
  63. package/src/lib/server/process-restock.js.map +1 -1
  64. package/src/lib/server/product-record-index.js +5 -37
  65. package/src/lib/server/product-record-index.js.map +1 -1
  66. package/src/lib/server/reconcile-stock.js +1 -1
  67. package/src/lib/server/reconcile-stock.js.map +1 -1
  68. package/src/lib/server/reserve-stock.js +6 -1
  69. package/src/lib/server/reserve-stock.js.map +1 -1
  70. package/src/lib/server/revenue-source.js +3 -3
  71. package/src/lib/server/revenue-source.js.map +1 -1
  72. package/src/lib/server/supplier-outbox.js +16 -1
  73. package/src/lib/server/supplier-outbox.js.map +1 -1
  74. package/src/lib/server/supplier-update.js +19 -9
  75. package/src/lib/server/supplier-update.js.map +1 -1
  76. package/src/lib/starter-templates.d.ts +19 -0
  77. package/src/lib/starter-templates.js +157 -0
  78. package/src/lib/starter-templates.js.map +1 -0
  79. package/src/lib/tenant-emails.js +54 -14
  80. package/src/lib/tenant-emails.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/catalog-organization-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 { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Autocomplete,\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Divider,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, deleteDoc, doc, setDoc } from 'firebase/firestore'\nimport { memo, useCallback, useMemo, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport {\n ceilingedWindow,\n collectionCeiling,\n useFirestoreCollection,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\n\n/**\n * How many category documents the card reads.\n *\n * A CEILING, not a page size — the walk below is a TREE and cannot be sliced\n * by document without orphaning children from parents on another page.\n */\nconst CATEGORY_CEILING = 250\n/** The same, for collections: the slug check needs every row to be correct. */\nconst COLLECTION_CEILING = 250\n/**\n * The catalog the match counts are computed over.\n *\n * Neither a page size nor a promise: it is how much of the catalog this card\n * is willing to read, and the counts below say \"at least\" once the probe finds\n * a product past it.\n */\nconst PRODUCT_CEILING = 500\n\nexport interface CatalogOrganizationCardProps {\n hostId: string\n}\n\ntype CategoryRow = CommerceModel.ProductCategory & { $id: string }\ntype CollectionRow = CommerceModel.HostCollection & { $id: string }\ntype ProductRow = CommerceModel.HostProduct & { $id: string }\n\nconst RULE_FIELDS: Array<{ value: CommerceModel.CollectionRuleField; label: string }> = [\n { value: 'tag', label: 'Tag' },\n { value: 'categoryId', label: 'Category' },\n { value: 'priceUsd', label: 'Price' },\n { value: 'name', label: 'Name' },\n { value: 'type', label: 'Type' },\n]\nconst RULE_OPS: Array<{ value: CommerceModel.CollectionRuleOp; label: string }> = [\n { value: 'eq', label: 'is' },\n { value: 'neq', label: 'is not' },\n { value: 'lt', label: 'below' },\n { value: 'gt', label: 'above' },\n { value: 'contains', label: 'contains' },\n]\n\nconst productLabel = (product: ProductRow): string => product.name\nconst sameProduct = (option: ProductRow, value: ProductRow): boolean =>\n option.$id === value.$id\n\n/**\n * A manual collection's products, as chips — MEMOIZED, and every prop it\n * takes is stable while the picked products are (AGL-3423).\n *\n * A multiple Autocomplete hands its input a new chip array as\n * `startAdornment` on every render, and MUI's `InputBase` copies that into\n * its `FormControl` from a passive effect: a state update left pending after\n * every commit the field takes part in. React 19 counts each such commit as a\n * nested update, and keystrokes delivered back to back commit one after\n * another with nothing to clear the count, so the fifty-first throws\n * \"Maximum update depth exceeded\" (#185). The collection's name, slug and\n * rules share one draft with this list, so each keystroke in them\n * re-rendered it; kept out of those renders, it commits only when it changes.\n */\nconst CollectionProductsField = memo(function CollectionProductsField(props: {\n products: readonly ProductRow[]\n value: readonly ProductRow[]\n onChange(picked: ProductRow[]): void\n}) {\n const { onChange } = props\n return (\n <Autocomplete\n multiple\n options={props.products as ProductRow[]}\n getOptionLabel={productLabel}\n isOptionEqualToValue={sameProduct}\n value={props.value as ProductRow[]}\n onChange={(_event, picked) => onChange(picked)}\n renderInput={(params) => (\n <TextField {...params} label=\"Products\" size=\"small\" />\n )}\n />\n )\n})\n\n/**\n * Categories & collections manager (AGL-280): category tree (parentId)\n * at `hosts/{hostId}/productCategories`, manual + smart collections at\n * `hosts/{hostId}/collections` with a live matched-product preview from\n * the same `matchesCollection` matcher the storefront uses.\n */\nexport function CatalogOrganizationCard(props: CatalogOrganizationCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { data: user } = useUser()\n\n const {\n data: categoryDocs,\n status: categoriesStatus,\n /**\n * The category rows are unconfirmed by the server (AGL-1358). Two writes\n * are seeded from them: the editor carries `parentId` off the row whether\n * or not the author touched it, and the delete REPARENTS every child of\n * the deleted category — a set computed entirely from this cached read,\n * so a stale snapshot can miss children that should have been moved.\n * (The reparent write itself is narrow since AGL-1374; what remains\n * cache-dependent is WHICH rows it runs on.)\n */\n fromCache: categoriesFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501).\n *\n * `limit(250)` alone is answered in DOCUMENT-ID order and the ids are\n * `createResourceUid()`, so the window was a pseudo-random sample. Naming\n * the order does not change WHICH 250 come back; what it changes is that\n * the obvious next edit is caught — `orderBy('name')` would HIDE every\n * category saved without one, and `orderBy('order')` is worse still, since\n * the walk below already treats a missing `order` as 0.\n *\n * The QUERY is not paged because this is a TREE. The walk puts parents\n * before children and collects orphans by scanning the whole set, so a\n * page boundary would separate a child from the parent that positions it\n * and re-label as an orphan every category whose parent is on another\n * page. The parent PICKER in the dialog reads the same rows for the same\n * reason.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'productCategories'),\n CATEGORY_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readCategories, truncated: categoriesTruncated } =\n ceilingedWindow<any>(categoryDocs, CATEGORY_CEILING)\n const {\n data: collectionDocs,\n status: collectionsStatus,\n /**\n * The collection rows are unconfirmed by the server (AGL-1358). The\n * editor copies a whole stored row and the save posts all of it — the\n * transport is the AGL-978 route rather than a client `setDoc`, but the\n * shape is identical, and so is the damage: `productIds` is the manual\n * membership, so a cached seed drops every product added since that\n * snapshot and the storefront blocks pointing at the collection go empty.\n */\n fromCache: collectionsFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged (AGL-2501).\n *\n * The slug check below tests a draft against these rows — two catalog\n * collections answering `/collections/{slug}` is a storefront route that\n * resolves to whichever the server reaches first — so a ten-row server\n * page would compare a new collection against a tenth of the catalog and\n * create the collision the check exists to prevent.\n *\n * The rows are also filtered after reading: content collections (AGL-81)\n * share this subcollection and are classified out below, so a page of ten\n * documents arrives holding anywhere from zero to ten catalog collections.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'collections'),\n COLLECTION_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readCollections, truncated: collectionsTruncated } =\n ceilingedWindow<any>(collectionDocs, COLLECTION_CEILING)\n const { data: productDocs } = useFirestoreCollection<any>(\n /*\n * The catalog behind the MATCH COUNTS, ceilinged with a probe (AGL-2501).\n *\n * `collectionCount` and the smart-collection preview both count this array\n * and print the result as a number of products. It was a bare `limit(500)`,\n * so on a three-thousand-product catalog \"Matches 47 products\" meant \"47 of\n * the five hundred I read\" — a count that is a window length, on the\n * control that decides what a collection contains.\n *\n * It stays a window, because the honest alternative is reading the whole\n * catalog on every mount of this card. What changes is that the probe makes\n * the shortfall a FACT, and the counts say \"at least\" when it bit rather\n * than stating a total they cannot know.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'products'),\n PRODUCT_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readProducts, truncated: productsTruncated } =\n ceilingedWindow<any>(productDocs, PRODUCT_CEILING)\n const products: ProductRow[] = useMemo(\n () =>\n [...readProducts]\n .filter((product: any) => !product.deletedAt)\n .map((product: any) => ({\n ...CommerceModel.liftLegacyProduct(product),\n $id: product.$id,\n })),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [productDocs],\n )\n // Content collections (AGL-81) live in the same `hosts/{hostId}/collections`\n // subcollection. This used to keep them out by requiring a non-empty\n // `name`, which held only because the Content page happens to write\n // `displayName` — a content doc that ever acquired a `name` (an import, a\n // hand edit) would land in this list, and its Delete reached the\n // recursiveDelete route (AGL-947). The shared classifier is the real\n // check (AGL-954); the route re-checks it, and AGL-1324 now refuses any\n // collection with entries besides.\n const commerceCollections: CollectionRow[] = useMemo(\n () => readCollections.filter(Aglyn.isHostCollectionKind('catalog')),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [collectionDocs],\n )\n\n // Categories ordered as a walked tree: parents before children.\n const categories: Array<CategoryRow & { depth: number }> = useMemo(() => {\n const rows = [...readCategories] as CategoryRow[]\n rows.sort(\n (a, b) => (a.order ?? 0) - (b.order ?? 0) || a.name.localeCompare(b.name),\n )\n const byParent = new Map<string | null, CategoryRow[]>()\n for (const row of rows) {\n const key = row.parentId ?? null\n byParent.set(key, [...(byParent.get(key) ?? []), row])\n }\n const walked: Array<CategoryRow & { depth: number }> = []\n const walk = (parentId: string | null, depth: number) => {\n for (const row of byParent.get(parentId) ?? []) {\n walked.push({ ...row, depth })\n if (depth < 4) walk(row.$id, depth + 1)\n }\n }\n walk(null, 0)\n // Orphans (parent deleted) still show, at the root.\n for (const row of rows) {\n if (!walked.some((item) => item.$id === row.$id)) {\n walked.push({ ...row, depth: 0 })\n }\n }\n return walked\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [categoryDocs])\n\n /*\n * Both pages are SLICES: the rows are already in hand, and the tree walk,\n * the parent picker and the slug check all need every one of them.\n */\n const [categoryPage, setCategoryPage] = useState(0)\n const [categoryPageSize, setCategoryPageSize] = useState(\n TABLE_PAGE_SIZE_DEFAULT,\n )\n const visibleCategories = useMemo(\n () =>\n categories.slice(\n categoryPage * categoryPageSize,\n categoryPage * categoryPageSize + categoryPageSize,\n ),\n [categories, categoryPage, categoryPageSize],\n )\n const [collectionPage, setCollectionPage] = useState(0)\n const [collectionPageSize, setCollectionPageSize] = useState(\n TABLE_PAGE_SIZE_DEFAULT,\n )\n const visibleCollections = useMemo(\n () =>\n commerceCollections.slice(\n collectionPage * collectionPageSize,\n collectionPage * collectionPageSize + collectionPageSize,\n ),\n [commerceCollections, collectionPage, collectionPageSize],\n )\n\n const [categoryDraft, setCategoryDraft] = useState<{\n id: string | null\n name: string\n parentId: string\n } | null>(null)\n const [collectionDraft, setCollectionDraft] = useState<\n (CommerceModel.HostCollection & { id: string | null }) | null\n >(null)\n\n const handleCategorySave = useCallback(async () => {\n if (!categoryDraft?.name.trim()) return\n const id = categoryDraft.id ?? Aglyn.createResourceUid()\n /**\n * Refuse an EDIT whose seed the server never confirmed (AGL-1358).\n *\n * The payload is narrower than most sites in this issue, but `parentId`\n * is carried off the seeded row on every save whether or not the author\n * opened the parent picker — so renaming a category against a cached read\n * can move it, and the whole subtree under it, back to a parent someone\n * had already reorganised away from.\n *\n * Only the edit path. A NEW category is built from blanks at a fresh uid\n * and can overwrite nothing, and the first snapshot of any listener is\n * `fromCache: true`, so guarding a create would refuse a save that was\n * never unsafe.\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: 'category',\n unreadable: Boolean(categoryDraft.id) && categoriesStatus === 'error',\n fromCache: Boolean(categoryDraft.id) && categoriesFromCache,\n },\n async () => {\n /**\n * `merge: true`, because this payload is NARROWER than the document\n * (AGL-1372). A replacing write deletes every stored key the form\n * does not send, and this form sends four:\n *\n * - `order` — the tree position. Both sorts read it (the walk above,\n * and `queryPublicCatalog`'s facet chips), and nothing in this card\n * can set it, so it is not the form's to send: a rename dropped it\n * and the category fell back to `?? 0`, reordering the storefront's\n * filter chips.\n * - `createdAt` — written at creation by the seeder, never by this\n * card, so a rename erased it too.\n *\n * Carrying `order` in the payload would have fixed the field we\n * happened to notice and left `createdAt`, plus whatever the document\n * grows next. Merging fixes the shape. Nothing here needs delete\n * semantics — `parentId` clears to an explicit `null`, which merges.\n */\n await setDoc(\n doc(firestore, 'hosts', hostId, 'productCategories', id),\n {\n name: categoryDraft.name.trim().slice(0, 80),\n slug: CommerceModel.commerceSlug(categoryDraft.name),\n parentId: categoryDraft.parentId || null,\n updatedAt: Timestamp.now(),\n },\n { merge: true },\n )\n },\n )\n // Before `setCategoryDraft(null)`, so a refusal keeps the dialog open\n // with what was typed.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setCategoryDraft(null)\n enqueueSnackbar('Category saved', { variant: 'success', persist: false })\n }, [\n categoryDraft,\n firestore,\n hostId,\n enqueueSnackbar,\n categoriesStatus,\n categoriesFromCache,\n ])\n\n const handleCategoryDelete = useCallback(\n (category: CategoryRow) => async () => {\n const confirmed = await confirm({\n title: 'Delete this category?',\n description:\n `Products keep their other categories; children of ` +\n `\"${category.name}\" move to the top level.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n /**\n * Refuse the whole sequence when the rows it reads were never confirmed\n * by the server (AGL-1358).\n *\n * The reparent is this issue's shape at its least visible: the author\n * opened no editor, so there is nothing on screen to look stale, and\n * `children` is read straight out of the cache. The write itself is\n * now narrow (see below), so a stale row can no longer be copied back\n * over a child — but WHICH rows are children is still a cached answer.\n *\n * The guard encloses the DELETE as well, for the reason the site\n * details rename did: `children` is computed from the same seed, so a\n * cached read can miss children entirely, and deleting the parent\n * without reparenting them leaves them pointing at a category that no\n * longer exists. Half of this sequence is worse than none of it.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'categories',\n unreadable: categoriesStatus === 'error',\n fromCache: categoriesFromCache,\n },\n async () => {\n // Reparent children to root, then remove.\n const children = (categoryDocs ?? []).filter(\n (row: any) => row.parentId === category.$id,\n )\n /**\n * Write only the field the reparent changes (AGL-1374).\n *\n * `{...child}` spread the listener row, and that row carries a\n * SYNTHETIC `$id` — `idField: '$id'` stamps the document id onto\n * the in-memory object, where nothing persists it. Spreading it\n * into the payload persisted it: every delete-with-children added\n * a real `$id` key to each child, permanently, and a child\n * reparented twice could end up carrying one that no longer\n * matched its own document id. Nothing reads it, so nothing broke\n * — it is the listener's bookkeeping leaking into storage, and\n * once there no reader can tell it from a real field.\n *\n * `{ parentId: null }` with `{ merge: true }` is what the reparent\n * actually means, and it is the stronger fix than stripping `$id`\n * off a full spread: the old write had no options argument, so it\n * was also a whole-document REPLACE of a cached row — the AGL-1358\n * hazard in miniature (and AGL-1372's, one collection over). A\n * narrow merge cannot carry a synthetic key it never names, and\n * cannot rewrite a field the delete has no business touching.\n *\n * `null` is a value, not a deletion, so it merges: the child ends\n * up at the top level, which is what the confirmation promised.\n */\n for (const child of children) {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'productCategories', child.$id),\n { parentId: null },\n { merge: true },\n )\n }\n await deleteDoc(\n doc(firestore, 'hosts', hostId, 'productCategories', category.$id),\n )\n },\n )\n // This path had no report of its own. A delete that silently does\n // nothing after the user confirmed it reads as a delete that worked.\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n },\n [\n confirm,\n categoryDocs,\n firestore,\n hostId,\n enqueueSnackbar,\n categoriesStatus,\n categoriesFromCache,\n ],\n )\n\n const draftSlug = collectionDraft\n ? collectionDraft.slug || CommerceModel.commerceSlug(collectionDraft.name)\n : ''\n // The slug is the collection's public address at /collections/{slug} and\n // nothing enforced uniqueness (AGL-957) — a second one at the same slug\n // made the first unreachable with no error anywhere. Checked against the\n // catalog collections only; content collections have their own namespace.\n const slugTaken =\n collectionDraft !== null &&\n Aglyn.isCollectionSlugTaken(\n draftSlug,\n 'catalog',\n commerceCollections,\n collectionDraft.id,\n )\n const collectionError = collectionDraft\n ? collectionDraft.name\n ? (CommerceModel.validateCollection({\n ...collectionDraft,\n slug: draftSlug,\n }) ??\n (slugTaken\n ? `Another collection already serves /collections/${draftSlug}`\n : null))\n : null\n : null\n\n const collectionProductIds = collectionDraft?.productIds\n const collectionProducts = useMemo(\n () =>\n products.filter((product) =>\n (collectionProductIds ?? []).includes(product.$id),\n ),\n [products, collectionProductIds],\n )\n const setCollectionProducts = useCallback(\n (picked: ProductRow[]) =>\n setCollectionDraft((prev) =>\n prev ? { ...prev, productIds: picked.map((item) => item.$id) } : prev,\n ),\n [],\n )\n\n const previewMatches = useMemo(() => {\n if (!collectionDraft) return []\n const candidate: CommerceModel.HostCollection = {\n ...collectionDraft,\n slug: collectionDraft.slug || CommerceModel.commerceSlug(collectionDraft.name),\n }\n return products.filter((product) =>\n CommerceModel.matchesCollection(product, candidate, product.$id),\n )\n }, [collectionDraft, products])\n\n /**\n * Which products a smart collection holds is stored on the products\n * (`collectionIds`, AGL-3321), so a save or a delete re-stamps them —\n * bounded passes through the commerce route until it says it is done.\n * A failure is reported, not thrown: the collection itself saved.\n */\n const restampMembership = useCallback(\n async (collectionId: string) => {\n try {\n let after: string | undefined\n for (let pass = 0; pass < 100; pass += 1) {\n const response = await authorizedFetch(\n user,\n '/api/commerce/collection-membership',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, collectionId, ...(after ? { after } : {}) }),\n },\n )\n const result = await response.json().catch(() => ({}))\n if (!response.ok) throw new Error(result?.error ?? 'Membership update failed')\n if (result.done || !result.after) return\n after = result.after\n }\n } catch (error: any) {\n enqueueSnackbar(\n `${error?.message ?? 'Membership update failed'} — the storefront may list this collection's old products until it is saved again.`,\n { variant: 'warning' },\n )\n }\n },\n [user, hostId, enqueueSnackbar],\n )\n\n const handleCollectionSave = useCallback(async () => {\n if (!collectionDraft?.name.trim() || collectionError) return\n const { id: draftId, ...data } = collectionDraft\n // Both create and rename go through the route (AGL-978): this save writes\n // the whole document including `slug`, which is the collection's public\n // address and is claimed transactionally there. Rules deny a client\n // create, and freeze `slug`/`kind` on update.\n /**\n * Refuse an UPDATE whose seed the server never confirmed (AGL-1358).\n *\n * The transport is the route rather than a client `setDoc`, but the shape\n * is the one this issue is about: `data` is the whole stored row copied\n * out of the listener, and the route writes what it is sent. `productIds`\n * is the manual membership, so a cached seed drops every product added\n * since that snapshot and the storefront blocks pointing at the\n * collection go empty; `rules` and `matchAll` do the same for a smart\n * collection. That the write leaves the browser over HTTP changes who\n * performs it, not what it destroys.\n *\n * Only the update path. A CREATE is built from blanks, and the route\n * claims a fresh slug transactionally, so it can overwrite nothing.\n *\n * The guard WRAPS the request — an early return is a shape you can keep\n * while losing the protection.\n */\n let verdict: Awaited<ReturnType<typeof writeGuardedBySeed>>\n let savedId = ''\n try {\n verdict = await writeGuardedBySeed(\n {\n subject: 'collection',\n unreadable: Boolean(draftId) && collectionsStatus === 'error',\n fromCache: Boolean(draftId) && collectionsFromCache,\n },\n async () => {\n const response = await authorizedFetch(\n user,\n '/api/hosts/collections',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n action: draftId ? 'update' : 'create',\n kind: 'catalog',\n ...(draftId ? { id: draftId } : {}),\n data: {\n ...data,\n name: collectionDraft.name.trim().slice(0, 80),\n slug: draftSlug,\n },\n }),\n },\n )\n const result = await response.json().catch(() => ({}))\n if (!response.ok) {\n throw new Error(result?.error ?? 'Collection save failed')\n }\n savedId = String(draftId ?? result?.id ?? '')\n },\n )\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Collection save failed', {\n variant: 'error',\n })\n }\n // Before `setCollectionDraft(null)`, so a refusal keeps the dialog open\n // with the membership that was picked.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setCollectionDraft(null)\n enqueueSnackbar('Collection saved', { variant: 'success', persist: false })\n if (savedId) await restampMembership(savedId)\n }, [\n restampMembership,\n collectionDraft,\n collectionError,\n draftSlug,\n user,\n hostId,\n enqueueSnackbar,\n collectionsStatus,\n collectionsFromCache,\n ])\n\n const handleCollectionDelete = useCallback(\n (row: CollectionRow) => async () => {\n const confirmed = await confirm({\n title: 'Delete this collection?',\n // NOT a cascade any more (AGL-1324/AGL-1336): the route REFUSES a\n // collection anything still depends on. Promising to take the\n // entries with it was the opposite of what happens, and the two\n // blockers are the whole point of the feature — say them before the\n // button is armed, not in a 409 afterwards.\n description:\n `Storefront blocks pointing at \"${row.name}\" go empty. The delete ` +\n 'is refused while the collection still has entries, or while a ' +\n 'page uses it as a list or entry template — empty it and detach ' +\n 'those pages first. It also takes the site admin role.',\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n // A collection owns an `entries` subcollection (the Content page's\n // published entries) and Firestore doesn't cascade, so deleting the\n // doc from here stranded them — still editor-writable through the\n // host catch-all rule, just unreachable. recursiveDelete is\n // Admin-SDK-only, hence the route (AGL-947). Since AGL-1324 the route\n // also refuses rather than cascading; the 409's message names the\n // blockers and is surfaced by the catch below.\n try {\n const response = await authorizedFetch(user, '/api/resources/erase', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n scope: 'hosts',\n scopeId: hostId,\n kind: 'collections',\n id: row.$id,\n // The route re-checks this server-side (AGL-954): a stale client\n // must not be able to recursiveDelete a content collection's\n // entries through the catalog card.\n collectionKind: 'catalog',\n }),\n })\n const result = await response.json().catch(() => ({}))\n if (!response.ok) {\n throw new Error(result?.error ?? 'Collection delete failed')\n }\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Collection delete failed', {\n variant: 'error',\n })\n }\n enqueueSnackbar('Collection deleted', { variant: 'success', persist: false })\n await restampMembership(row.$id)\n },\n [confirm, user, hostId, enqueueSnackbar, restampMembership],\n )\n\n /**\n * How many products a collection holds — over the CATALOG WINDOW.\n *\n * Rendered with \"at least\" when the probe found a product past the ceiling,\n * because past that point this is a lower bound and printing it as a total\n * is the count-that-is-a-window-length defect. The number itself is honest\n * either way; only the claim around it changes.\n */\n const collectionCount = (row: CollectionRow) =>\n products.filter((product) =>\n CommerceModel.matchesCollection(product, row, product.$id),\n ).length\n /*\n * \"at least\", or nothing at all.\n *\n * Every count on this card is computed over `products`, which is the catalog\n * WINDOW rather than the catalog. While the probe finds a product past the\n * ceiling those counts are lower bounds, and printing one as a total is the\n * count-that-is-a-window-length defect this ceiling exists to make visible.\n *\n * Keyed on the probe rather than on `products.length >= PRODUCT_CEILING`,\n * because a catalog of exactly the ceiling is complete: nothing is missing,\n * and a comparison would put \"at least\" on a number that is exact.\n */\n const countPrefix = productsTruncated ? 'at least ' : ''\n\n const updateRule = (\n index: number,\n patch: Partial<CommerceModel.CollectionRule> | null,\n ) => {\n if (!collectionDraft) return\n const rules = [...(collectionDraft.rules ?? [])]\n if (patch === null) rules.splice(index, 1)\n else\n rules[index] = {\n field: 'tag',\n op: 'eq',\n value: '',\n ...rules[index],\n ...patch,\n }\n setCollectionDraft({ ...collectionDraft, rules })\n }\n\n return (\n <CardDisplay\n header={'Categories & collections'}\n help={pluginDocsHelp('catalog', { anchor: '#categories-and-tags' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Categories'}</Typography>\n {categories.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Group products into a browsable tree (e.g. Brakes → Pads).'}\n </Typography>\n ) : (\n visibleCategories.map((category) => (\n <Stack\n key={category.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', pl: category.depth * 2 }}\n >\n <Typography variant=\"body2\" sx={{ flex: 1 }} noWrap>\n {category.name}\n <Typography\n component=\"span\"\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {` /${category.slug}`}\n </Typography>\n </Typography>\n <Button\n size=\"small\"\n onClick={() =>\n setCategoryDraft({\n id: category.$id,\n name: category.name,\n parentId: category.parentId ?? '',\n })\n }\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleCategoryDelete(category)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {categories.length === 0 ? null : (\n <ListPagination\n page={categoryPage}\n pageSize={categoryPageSize}\n rowCount={visibleCategories.length}\n // The categories the card HOLDS — a client slice of rows already\n // read, so the total is known exactly.\n count={categories.length}\n onPageChange={setCategoryPage}\n onPageSizeChange={setCategoryPageSize}\n />\n )}\n {categoriesTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${CATEGORY_CEILING} categories, ordered by id. This ` +\n 'catalog has more — a category whose parent is past that ' +\n 'boundary is drawn at the top level here rather than under it.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => setCategoryDraft({ id: null, name: '', parentId: '' })}\n >\n {'Add category'}\n </Button>\n\n <Divider sx={{ my: 1 }} />\n <Typography variant=\"subtitle2\">{'Collections'}</Typography>\n {visibleCollections.map((row) => (\n <Stack\n key={row.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Typography variant=\"body2\" sx={{ flex: 1 }} noWrap>\n {row.name}\n <Typography\n component=\"span\"\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {` · ${row.mode ?? 'manual'} · ${countPrefix}${collectionCount(\n row,\n )} products`}\n </Typography>\n </Typography>\n <Button\n size=\"small\"\n onClick={() =>\n setCollectionDraft({\n id: row.$id,\n name: row.name,\n slug: row.slug ?? '',\n mode: row.mode ?? 'manual',\n productIds: row.productIds ?? [],\n rules: row.rules ?? [],\n matchAll: row.matchAll !== false,\n })\n }\n >\n {'Edit'}\n </Button>\n <Button size=\"small\" color=\"error\" onClick={handleCollectionDelete(row)}>\n {'Delete'}\n </Button>\n </Stack>\n ))}\n {commerceCollections.length === 0 ? null : (\n <ListPagination\n page={collectionPage}\n pageSize={collectionPageSize}\n rowCount={visibleCollections.length}\n // The CATALOG collections, which is what this list is. Not the\n // window's length: content collections share the subcollection\n // and are classified out before this count is taken.\n count={commerceCollections.length}\n onPageChange={setCollectionPage}\n onPageSizeChange={setCollectionPageSize}\n />\n )}\n {collectionsTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${COLLECTION_CEILING} collections, ordered by id. This ` +\n 'site has more — the slug check below only covers the ones ' +\n 'listed here, so an address may already be taken by one that ' +\n 'is not.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n setCollectionDraft({\n id: null,\n name: '',\n slug: '',\n mode: 'manual',\n productIds: [],\n rules: [],\n matchAll: true,\n })\n }\n >\n {'Add collection'}\n </Button>\n </Stack>\n\n <Dialog\n open={Boolean(categoryDraft)}\n onClose={() => setCategoryDraft(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>\n {categoryDraft?.id ? 'Edit category' : 'New category'}\n </DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <TextField\n label=\"Name\"\n value={categoryDraft?.name ?? ''}\n onChange={(event) =>\n setCategoryDraft((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=\"Parent category\"\n value={categoryDraft?.parentId ?? ''}\n onChange={(event) =>\n setCategoryDraft((prev) =>\n prev ? { ...prev, parentId: event.target.value } : prev,\n )\n }\n size=\"small\"\n select\n >\n <MenuItem value=\"\">{'None (top level)'}</MenuItem>\n {/* The whole set, not `visibleCategories` — a parent picker\n that offered only the current page could not reparent a\n category under one two pages away. */}\n {categories\n .filter((category) => category.$id !== categoryDraft?.id)\n .map((category) => (\n <MenuItem key={category.$id} value={category.$id}>\n {`${'— '.repeat(category.depth)}${category.name}`}\n </MenuItem>\n ))}\n </TextField>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setCategoryDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!categoryDraft?.name.trim()}\n onClick={handleCategorySave}\n >\n {'Save'}\n </Button>\n </DialogActions>\n </Dialog>\n\n <Dialog\n open={Boolean(collectionDraft)}\n onClose={() => setCollectionDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>\n {collectionDraft?.id ? 'Edit collection' : 'New collection'}\n </DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <TextField\n label=\"Name\"\n value={collectionDraft?.name ?? ''}\n onChange={(event) =>\n setCollectionDraft((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n error={slugTaken}\n helperText={\n collectionDraft?.name ? `/collections/${draftSlug}` : undefined\n }\n />\n <TextField\n label=\"Mode\"\n value={collectionDraft?.mode ?? 'manual'}\n onChange={(event) =>\n setCollectionDraft((prev) =>\n prev\n ? { ...prev, mode: event.target.value as 'manual' | 'smart' }\n : prev,\n )\n }\n size=\"small\"\n select\n >\n <MenuItem value=\"manual\">{'Manual — pick products'}</MenuItem>\n <MenuItem value=\"smart\">{'Smart — rule based'}</MenuItem>\n </TextField>\n {collectionDraft?.mode === 'manual' ? (\n <CollectionProductsField\n products={products}\n value={collectionProducts}\n onChange={setCollectionProducts}\n />\n ) : (\n <>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\">{'Match'}</Typography>\n <Switch\n size=\"small\"\n checked={collectionDraft?.matchAll !== false}\n onChange={(event) =>\n setCollectionDraft((prev) =>\n prev ? { ...prev, matchAll: event.target.checked } : prev,\n )\n }\n />\n <Typography variant=\"body2\">\n {collectionDraft?.matchAll !== false\n ? 'all rules'\n : 'any rule'}\n </Typography>\n </Stack>\n {(collectionDraft?.rules ?? []).map((rule, index) => (\n <Stack key={index} direction=\"row\" spacing={1}>\n <TextField\n value={rule.field}\n onChange={(event) =>\n updateRule(index, {\n field: event.target.value as CommerceModel.CollectionRuleField,\n })\n }\n size=\"small\"\n select\n sx={{ width: 130 }}\n >\n {RULE_FIELDS.map((field) => (\n <MenuItem key={field.value} value={field.value}>\n {field.label}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n value={rule.op}\n onChange={(event) =>\n updateRule(index, {\n op: event.target.value as CommerceModel.CollectionRuleOp,\n })\n }\n size=\"small\"\n select\n sx={{ width: 110 }}\n >\n {RULE_OPS.map((op) => (\n <MenuItem key={op.value} value={op.value}>\n {op.label}\n </MenuItem>\n ))}\n </TextField>\n {rule.field === 'categoryId' ? (\n <TextField\n value={rule.value}\n onChange={(event) =>\n updateRule(index, { value: event.target.value })\n }\n size=\"small\"\n select\n sx={{ flex: 1 }}\n >\n {categories.map((category) => (\n <MenuItem key={category.$id} value={category.$id}>\n {category.name}\n </MenuItem>\n ))}\n </TextField>\n ) : (\n <TextField\n value={rule.value}\n onChange={(event) =>\n updateRule(index, {\n value:\n rule.field === 'priceUsd'\n ? Number(event.target.value)\n : event.target.value,\n })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder={rule.field === 'type' ? 'physical' : 'Value'}\n />\n )}\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() => updateRule(index, null)}\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n updateRule(collectionDraft?.rules?.length ?? 0, {})\n }\n >\n {'Add rule'}\n </Button>\n </>\n )}\n {collectionError ? (\n <Alert severity=\"warning\">{collectionError}</Alert>\n ) : null}\n {collectionDraft ? (\n <Stack direction=\"row\" spacing={0.5} sx={{ flexWrap: 'wrap' }}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Matches ${countPrefix}${previewMatches.length} products: `}\n </Typography>\n {previewMatches.slice(0, 6).map((product) => (\n <Chip key={product.$id} label={product.name} size=\"small\" />\n ))}\n {previewMatches.length > 6 ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`+${previewMatches.length - 6} more`}\n </Typography>\n ) : null}\n </Stack>\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setCollectionDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!collectionDraft?.name.trim() || Boolean(collectionError)}\n onClick={handleCollectionSave}\n >\n {'Save'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nCatalogOrganizationCard.displayName = 'CatalogOrganizationCard'\n\nexport default CatalogOrganizationCard\n"],"names":["Aglyn","CommerceModel","CardDisplay","useConfirmationContext","useSnackbar","Timestamp","Alert","Autocomplete","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Divider","MenuItem","Stack","Switch","TextField","Typography","collection","deleteDoc","doc","setDoc","memo","useCallback","useMemo","useState","useFirestore","useUser","ceilingedWindow","collectionCeiling","useFirestoreCollection","writeGuardedBySeed","ListPagination","TABLE_PAGE_SIZE_DEFAULT","pluginDocsHelp","authorizedFetch","CATEGORY_CEILING","COLLECTION_CEILING","PRODUCT_CEILING","RULE_FIELDS","value","label","RULE_OPS","productLabel","product","name","sameProduct","option","$id","CollectionProductsField","props","onChange","multiple","options","products","getOptionLabel","isOptionEqualToValue","_event","picked","renderInput","params","size","CatalogOrganizationCard","hostId","firestore","enqueueSnackbar","confirm","data","user","categoryDocs","status","categoriesStatus","fromCache","categoriesFromCache","idField","rows","readCategories","truncated","categoriesTruncated","collectionDocs","collectionsStatus","collectionsFromCache","readCollections","collectionsTruncated","productDocs","readProducts","productsTruncated","filter","deletedAt","map","liftLegacyProduct","commerceCollections","isHostCollectionKind","categories","sort","a","b","order","localeCompare","byParent","Map","row","key","parentId","set","get","walked","walk","depth","push","some","item","categoryPage","setCategoryPage","categoryPageSize","setCategoryPageSize","visibleCategories","slice","collectionPage","setCollectionPage","collectionPageSize","setCollectionPageSize","visibleCollections","categoryDraft","setCategoryDraft","collectionDraft","setCollectionDraft","handleCategorySave","trim","id","createResourceUid","verdict","subject","unreadable","Boolean","slug","commerceSlug","updatedAt","now","merge","ok","message","variant","persist","handleCategoryDelete","category","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","catch","children","child","draftSlug","slugTaken","isCollectionSlugTaken","collectionError","validateCollection","collectionProductIds","productIds","collectionProducts","includes","setCollectionProducts","prev","previewMatches","candidate","matchesCollection","restampMembership","collectionId","after","pass","response","method","headers","body","JSON","stringify","result","json","Error","error","done","handleCollectionSave","draftId","savedId","action","kind","String","handleCollectionDelete","scope","scopeId","collectionKind","collectionCount","length","countPrefix","updateRule","index","patch","rules","splice","field","op","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","pl","flex","noWrap","component","onClick","page","pageSize","rowCount","count","onPageChange","onPageSizeChange","severity","alignSelf","my","mode","matchAll","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","event","target","autoFocus","mt","select","repeat","disabled","helperText","undefined","checked","rule","width","Number","placeholder","flexWrap","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,YAAYA,WAAW,eAAc;AACrC,YAAYC,mBAAmB,uBAAa;AAC5C,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,KAAK,EACLC,YAAY,EACZC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,OAAO,EACPC,QAAQ,EACR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rM;oDACCuD,MAAK;oDACL0F,OAAM;oDACNmE,SAAS,IAAMpB,WAAWC,OAAO;8DAEhC;;;2CAxEOA;kDA4Ed,KAACjM;wCACCuD,MAAK;wCACLuJ,IAAI;4CAAEc,WAAW;wCAAa;wCAC9BR,SAAS;;gDACI7F;mDAAXyE,mBAAWzE,oCAAAA,yBAAAA,gBAAiB4E,KAAK,qBAAtB5E,uBAAwBuE,MAAM,mBAAI,GAAG,CAAC;;kDAGlD;;;;4BAINrC,gCACC,KAAC3J;gCAAM6N,UAAS;0CAAWlE;iCACzB;4BACHlC,gCACC,MAAC/G;gCAAMqM,WAAU;gCAAMD,SAAS;gCAAKE,IAAI;oCAAEuC,UAAU;gCAAO;;kDAC1D,KAAC1O;wCAAW6H,SAAQ;wCAAUS,OAAM;kDACjC,CAAC,QAAQ,EAAE8C,cAAc9B,eAAe6B,MAAM,CAAC,WAAW,CAAC;;oCAE7D7B,eAAelD,KAAK,CAAC,GAAG,GAAG5B,GAAG,CAAC,CAAC7C,wBAC/B,KAACrC;4CAAuBkC,OAAOG,QAAQC,IAAI;4CAAEgB,MAAK;2CAAvCjB,QAAQI,GAAG;oCAEvBuH,eAAe6B,MAAM,GAAG,kBACvB,KAACnL;wCAAW6H,SAAQ;wCAAUS,OAAM;kDACjC,CAAC,CAAC,EAAEgB,eAAe6B,MAAM,GAAG,EAAE,KAAK,CAAC;yCAErC;;iCAEJ;;;kCAEN,MAAC3L;;0CACC,KAACH;gCAAOoN,SAAS,IAAM5F,mBAAmB;0CAAQ;;0CAClD,KAACxH;gCACCwI,SAAQ;gCACRS,OAAM;gCACN4F,UAAU,EAACtH,mCAAAA,gBAAiBhF,IAAI,CAACmF,IAAI,OAAMM,QAAQyB;gCACnD2D,SAASjC;0CAER;;;;;;;;AAMb;AACA3H,wBAAwB8L,WAAW,GAAG;AAEtC,eAAe9L,wBAAuB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/catalog-organization-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 { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Autocomplete,\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Divider,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, deleteDoc, doc, setDoc } from 'firebase/firestore'\nimport {\n type Dispatch,\n type SetStateAction,\n memo,\n useCallback,\n useMemo,\n useRef,\n useState,\n} from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport {\n ceilingedWindow,\n collectionCeiling,\n useFirestoreCollection,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\n\n/**\n * How many category documents the card reads.\n *\n * A CEILING, not a page size — the walk below is a TREE and cannot be sliced\n * by document without orphaning children from parents on another page.\n */\nconst CATEGORY_CEILING = 250\n/** The same, for collections: the slug check needs every row to be correct. */\nconst COLLECTION_CEILING = 250\n/**\n * The catalog the match counts are computed over.\n *\n * Neither a page size nor a promise: it is how much of the catalog this card\n * is willing to read, and the counts below say \"at least\" once the probe finds\n * a product past it.\n */\nconst PRODUCT_CEILING = 500\n\nexport interface CatalogOrganizationCardProps {\n hostId: string\n}\n\ntype CategoryRow = CommerceModel.ProductCategory & { $id: string }\ntype CollectionRow = CommerceModel.HostCollection & { $id: string }\ntype ProductRow = CommerceModel.HostProduct & { $id: string }\n\nconst RULE_FIELDS: Array<{ value: CommerceModel.CollectionRuleField; label: string }> = [\n { value: 'tag', label: 'Tag' },\n { value: 'categoryId', label: 'Category' },\n { value: 'priceUsd', label: 'Price' },\n { value: 'name', label: 'Name' },\n { value: 'type', label: 'Type' },\n]\nconst RULE_OPS: Array<{ value: CommerceModel.CollectionRuleOp; label: string }> = [\n { value: 'eq', label: 'is' },\n { value: 'neq', label: 'is not' },\n { value: 'lt', label: 'below' },\n { value: 'gt', label: 'above' },\n { value: 'contains', label: 'contains' },\n]\n\nconst productLabel = (product: ProductRow): string => product.name\nconst sameProduct = (option: ProductRow, value: ProductRow): boolean =>\n option.$id === value.$id\n\n/**\n * A manual collection's products, as chips — MEMOIZED, and every prop it\n * takes is stable while the picked products are (AGL-3423).\n *\n * A multiple Autocomplete hands its input a new chip array as\n * `startAdornment` on every render, and MUI's `InputBase` copies that into\n * its `FormControl` from a passive effect: a state update left pending after\n * every commit the field takes part in. React 19 counts each such commit as a\n * nested update, and keystrokes delivered back to back commit one after\n * another with nothing to clear the count, so the fifty-first throws\n * \"Maximum update depth exceeded\" (#185). The collection's name, slug and\n * rules share one draft with this list, so each keystroke in them\n * re-rendered it; kept out of those renders, it commits only when it changes.\n */\nconst CollectionProductsField = memo(function CollectionProductsField(props: {\n products: readonly ProductRow[]\n value: readonly ProductRow[]\n onChange(picked: ProductRow[]): void\n}) {\n const { onChange } = props\n return (\n <Autocomplete\n multiple\n options={props.products as ProductRow[]}\n getOptionLabel={productLabel}\n isOptionEqualToValue={sameProduct}\n value={props.value as ProductRow[]}\n onChange={(_event, picked) => onChange(picked)}\n renderInput={(params) => (\n <TextField {...params} label=\"Products\" size=\"small\" />\n )}\n />\n )\n})\n\ntype CategoryDraft = { id: string | null; name: string; parentId: string }\ntype CollectionDraft = CommerceModel.HostCollection & { id: string | null }\ntype WalkedCategory = CategoryRow & { depth: number }\ntype DraftSetter<T> = Dispatch<SetStateAction<T | null>>\n\n/** A change to one rule, or `null` to remove it. */\ntype RuleChange = (\n index: number,\n patch: Partial<CommerceModel.CollectionRule> | null,\n) => void\n\ntype FieldChange = { target: { value: string } }\n\n/**\n * A text field that redraws only when what it shows changes (AGL-3423).\n *\n * Both editors keep their draft in this card, so a keystroke in either one\n * re-renders the card, and drawn whole that is both lists with a match count\n * per collection, their pagers, and every field of the dialog typed into.\n * When a keystroke costs that much, typed input queues and is processed back\n * to back, which is what lets a chip list's pending update climb to #185 (see\n * `CollectionProductsField`). The lists and each part of the dialogs are\n * memoized on what they show, and each field is this, handed a handler and\n * styles that keep their identity, so the keystroke redraws the field it\n * lands in.\n */\nconst MemoTextField = memo(TextField) as typeof TextField\n\nconst FIRST_FIELD = { mt: 1 } as const\nconst RULE_FIELD = { width: 130 } as const\nconst RULE_OP = { width: 110 } as const\nconst RULE_VALUE = { flex: 1 } as const\n\nconst MODE_MENU = [\n <MenuItem key=\"manual\" value=\"manual\">\n {'Manual — pick products'}\n </MenuItem>,\n <MenuItem key=\"smart\" value=\"smart\">\n {'Smart — rule based'}\n </MenuItem>,\n]\nconst RULE_FIELD_MENU = RULE_FIELDS.map((field) => (\n <MenuItem key={field.value} value={field.value}>\n {field.label}\n </MenuItem>\n))\nconst RULE_OP_MENU = RULE_OPS.map((op) => (\n <MenuItem key={op.value} value={op.value}>\n {op.label}\n </MenuItem>\n))\n\n/** The category tree, a page at a time, and the button that adds one. */\nconst CategoriesSection = memo(function CategoriesSection(props: {\n /** Every category, walked; the page is `visible`. */\n categories: readonly WalkedCategory[]\n visible: readonly WalkedCategory[]\n page: number\n pageSize: number\n truncated: boolean\n onPageChange(page: number): void\n onPageSizeChange(pageSize: number): void\n onEdit: DraftSetter<CategoryDraft>\n onDelete(category: CategoryRow): () => Promise<void>\n}) {\n const { categories, visible, onEdit, onDelete } = props\n return (\n <>\n <Typography variant=\"subtitle2\">{'Categories'}</Typography>\n {categories.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Group products into a browsable tree (e.g. Brakes → Pads).'}\n </Typography>\n ) : (\n visible.map((category) => (\n <Stack\n key={category.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', pl: category.depth * 2 }}\n >\n <Typography variant=\"body2\" sx={{ flex: 1 }} noWrap>\n {category.name}\n <Typography\n component=\"span\"\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {` /${category.slug}`}\n </Typography>\n </Typography>\n <Button\n size=\"small\"\n onClick={() =>\n onEdit({\n id: category.$id,\n name: category.name,\n parentId: category.parentId ?? '',\n })\n }\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={onDelete(category)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {categories.length === 0 ? null : (\n <ListPagination\n page={props.page}\n pageSize={props.pageSize}\n rowCount={visible.length}\n // The categories the card HOLDS — a client slice of rows already\n // read, so the total is known exactly.\n count={categories.length}\n onPageChange={props.onPageChange}\n onPageSizeChange={props.onPageSizeChange}\n />\n )}\n {props.truncated ? (\n <Alert severity=\"info\">\n {`Showing ${CATEGORY_CEILING} categories, ordered by id. This ` +\n 'catalog has more — a category whose parent is past that ' +\n 'boundary is drawn at the top level here rather than under it.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => onEdit({ id: null, name: '', parentId: '' })}\n >\n {'Add category'}\n </Button>\n </>\n )\n})\n\n/** The catalog collections, a page at a time, and the button that adds one. */\nconst CollectionsSection = memo(function CollectionsSection(props: {\n /** Every catalog collection; the page is `visible`. */\n collections: readonly CollectionRow[]\n visible: readonly CollectionRow[]\n products: readonly ProductRow[]\n /** \"at least \" while the catalog window is short of the catalog. */\n countPrefix: string\n page: number\n pageSize: number\n truncated: boolean\n onPageChange(page: number): void\n onPageSizeChange(pageSize: number): void\n onEdit: DraftSetter<CollectionDraft>\n onDelete(row: CollectionRow): () => Promise<void>\n}) {\n const { collections, visible, products, countPrefix, onEdit, onDelete } = props\n /**\n * How many products a collection holds — over the CATALOG WINDOW.\n *\n * Rendered with \"at least\" when the probe found a product past the ceiling,\n * because past that point this is a lower bound and printing it as a total\n * is the count-that-is-a-window-length defect. The number itself is honest\n * either way; only the claim around it changes.\n */\n const collectionCount = (row: CollectionRow) =>\n products.filter((product) =>\n CommerceModel.matchesCollection(product, row, product.$id),\n ).length\n return (\n <>\n <Typography variant=\"subtitle2\">{'Collections'}</Typography>\n {visible.map((row) => (\n <Stack\n key={row.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Typography variant=\"body2\" sx={{ flex: 1 }} noWrap>\n {row.name}\n <Typography\n component=\"span\"\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {` · ${row.mode ?? 'manual'} · ${countPrefix}${collectionCount(\n row,\n )} products`}\n </Typography>\n </Typography>\n <Button\n size=\"small\"\n onClick={() =>\n onEdit({\n id: row.$id,\n name: row.name,\n slug: row.slug ?? '',\n mode: row.mode ?? 'manual',\n productIds: row.productIds ?? [],\n rules: row.rules ?? [],\n matchAll: row.matchAll !== false,\n })\n }\n >\n {'Edit'}\n </Button>\n <Button size=\"small\" color=\"error\" onClick={onDelete(row)}>\n {'Delete'}\n </Button>\n </Stack>\n ))}\n {collections.length === 0 ? null : (\n <ListPagination\n page={props.page}\n pageSize={props.pageSize}\n rowCount={visible.length}\n // The CATALOG collections, which is what this list is. Not the\n // window's length: content collections share the subcollection\n // and are classified out before this count is taken.\n count={collections.length}\n onPageChange={props.onPageChange}\n onPageSizeChange={props.onPageSizeChange}\n />\n )}\n {props.truncated ? (\n <Alert severity=\"info\">\n {`Showing ${COLLECTION_CEILING} collections, ordered by id. This ` +\n 'site has more — the slug check below only covers the ones ' +\n 'listed here, so an address may already be taken by one that ' +\n 'is not.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n onEdit({\n id: null,\n name: '',\n slug: '',\n mode: 'manual',\n productIds: [],\n rules: [],\n matchAll: true,\n })\n }\n >\n {'Add collection'}\n </Button>\n </>\n )\n})\n\n/** The category editor: a name and a parent. */\nconst CategoryDialog = memo(function CategoryDialog(props: {\n draft: CategoryDraft | null\n /** Every category, as the parent picker offers them. */\n categories: readonly WalkedCategory[]\n setDraft: DraftSetter<CategoryDraft>\n onSave(): void\n}) {\n const { draft, categories, setDraft } = props\n const draftId = draft?.id\n const close = useCallback(() => setDraft(null), [setDraft])\n const setName = useCallback(\n (event: FieldChange) =>\n setDraft((prev) => (prev ? { ...prev, name: event.target.value } : prev)),\n [setDraft],\n )\n const setParent = useCallback(\n (event: FieldChange) =>\n setDraft((prev) =>\n prev ? { ...prev, parentId: event.target.value } : prev,\n ),\n [setDraft],\n )\n const parentMenu = useMemo(\n () => [\n <MenuItem key=\"\" value=\"\">\n {'None (top level)'}\n </MenuItem>,\n // The whole set, not `visibleCategories` — a parent picker that\n // offered only the current page could not reparent a category under\n // one two pages away.\n ...categories\n .filter((category) => category.$id !== draftId)\n .map((category) => (\n <MenuItem key={category.$id} value={category.$id}>\n {`${'— '.repeat(category.depth)}${category.name}`}\n </MenuItem>\n )),\n ],\n [categories, draftId],\n )\n return (\n <Dialog open={Boolean(draft)} onClose={close} maxWidth=\"xs\" fullWidth>\n <DialogTitle>{draft?.id ? 'Edit category' : 'New category'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <MemoTextField\n label=\"Name\"\n value={draft?.name ?? ''}\n onChange={setName}\n size=\"small\"\n autoFocus\n sx={FIRST_FIELD}\n />\n <MemoTextField\n label=\"Parent category\"\n value={draft?.parentId ?? ''}\n onChange={setParent}\n size=\"small\"\n select\n >\n {parentMenu}\n </MemoTextField>\n </DialogContent>\n <DialogActions>\n <Button onClick={close}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim()}\n onClick={props.onSave}\n >\n {'Save'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n})\n\nconst CollectionRuleRow = memo(function CollectionRuleRow(props: {\n index: number\n rule: CommerceModel.CollectionRule\n /** The category picker's entries, for a rule on a category. */\n categoryMenu: readonly JSX.Element[]\n onChange: RuleChange\n}) {\n const { index, rule, onChange } = props\n const setField = useCallback(\n (event: FieldChange) =>\n onChange(index, {\n field: event.target.value as CommerceModel.CollectionRuleField,\n }),\n [index, onChange],\n )\n const setOp = useCallback(\n (event: FieldChange) =>\n onChange(index, {\n op: event.target.value as CommerceModel.CollectionRuleOp,\n }),\n [index, onChange],\n )\n const setCategory = useCallback(\n (event: FieldChange) => onChange(index, { value: event.target.value }),\n [index, onChange],\n )\n const ruleField = rule.field\n const setValue = useCallback(\n (event: FieldChange) =>\n onChange(index, {\n value:\n ruleField === 'priceUsd'\n ? Number(event.target.value)\n : event.target.value,\n }),\n [index, onChange, ruleField],\n )\n return (\n <Stack direction=\"row\" spacing={1}>\n <MemoTextField\n value={rule.field}\n onChange={setField}\n size=\"small\"\n select\n sx={RULE_FIELD}\n >\n {RULE_FIELD_MENU}\n </MemoTextField>\n <MemoTextField\n value={rule.op}\n onChange={setOp}\n size=\"small\"\n select\n sx={RULE_OP}\n >\n {RULE_OP_MENU}\n </MemoTextField>\n {rule.field === 'categoryId' ? (\n <MemoTextField\n value={rule.value}\n onChange={setCategory}\n size=\"small\"\n select\n sx={RULE_VALUE}\n >\n {props.categoryMenu}\n </MemoTextField>\n ) : (\n <MemoTextField\n value={rule.value}\n onChange={setValue}\n size=\"small\"\n sx={RULE_VALUE}\n placeholder={rule.field === 'type' ? 'physical' : 'Value'}\n />\n )}\n <Button size=\"small\" color=\"error\" onClick={() => onChange(index, null)}>\n {'✕'}\n </Button>\n </Stack>\n )\n})\n\n/** Whether every rule must hold, or any one. */\nconst CollectionMatchSwitch = memo(function CollectionMatchSwitch(props: {\n matchAll: boolean\n setDraft: DraftSetter<CollectionDraft>\n}) {\n const { matchAll, setDraft } = props\n return (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\">{'Match'}</Typography>\n <Switch\n size=\"small\"\n checked={matchAll}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, matchAll: event.target.checked } : prev,\n )\n }\n />\n <Typography variant=\"body2\">\n {matchAll ? 'all rules' : 'any rule'}\n </Typography>\n </Stack>\n )\n})\n\n/** A smart collection's rules, whether all or any must hold, and the button that adds one. */\nconst CollectionRulesFields = memo(function CollectionRulesFields(props: {\n rules: readonly CommerceModel.CollectionRule[]\n matchAll: boolean\n categories: readonly WalkedCategory[]\n setDraft: DraftSetter<CollectionDraft>\n onRule: RuleChange\n}) {\n const { rules, matchAll, categories, setDraft, onRule } = props\n const categoryMenu = useMemo(\n () =>\n categories.map((category) => (\n <MenuItem key={category.$id} value={category.$id}>\n {category.name}\n </MenuItem>\n )),\n [categories],\n )\n return (\n <>\n <CollectionMatchSwitch matchAll={matchAll} setDraft={setDraft} />\n {rules.map((rule, index) => (\n <CollectionRuleRow\n key={index}\n index={index}\n rule={rule}\n categoryMenu={categoryMenu}\n onChange={onRule}\n />\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => onRule(rules.length, {})}\n >\n {'Add rule'}\n </Button>\n </>\n )\n})\n\n/** The products a draft collection holds, the first few by name. */\nconst CollectionPreview = memo(function CollectionPreview(props: {\n matches: readonly ProductRow[]\n countPrefix: string\n}) {\n const { matches, countPrefix } = props\n return (\n <Stack direction=\"row\" spacing={0.5} sx={{ flexWrap: 'wrap' }}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Matches ${countPrefix}${matches.length} products: `}\n </Typography>\n {matches.slice(0, 6).map((product) => (\n <Chip key={product.$id} label={product.name} size=\"small\" />\n ))}\n {matches.length > 6 ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`+${matches.length - 6} more`}\n </Typography>\n ) : null}\n </Stack>\n )\n})\n\n/** The collection editor: a name, a mode, and the products or rules it holds. */\nconst CollectionDialog = memo(function CollectionDialog(props: {\n draft: CollectionDraft | null\n /** The address the draft will be saved at. */\n slug: string\n slugTaken: boolean\n error: string | null\n products: readonly ProductRow[]\n /** The draft's manual products, as rows. */\n picked: readonly ProductRow[]\n categories: readonly WalkedCategory[]\n matches: readonly ProductRow[]\n countPrefix: string\n setDraft: DraftSetter<CollectionDraft>\n onProducts(picked: ProductRow[]): void\n onRule: RuleChange\n onSave(): void\n}) {\n const { draft, error, setDraft } = props\n const close = useCallback(() => setDraft(null), [setDraft])\n const setName = useCallback(\n (event: FieldChange) =>\n setDraft((prev) => (prev ? { ...prev, name: event.target.value } : prev)),\n [setDraft],\n )\n const setMode = useCallback(\n (event: FieldChange) =>\n setDraft((prev) =>\n prev\n ? { ...prev, mode: event.target.value as 'manual' | 'smart' }\n : prev,\n ),\n [setDraft],\n )\n return (\n <Dialog open={Boolean(draft)} onClose={close} maxWidth=\"sm\" fullWidth>\n <DialogTitle>{draft?.id ? 'Edit collection' : 'New collection'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <MemoTextField\n label=\"Name\"\n value={draft?.name ?? ''}\n onChange={setName}\n size=\"small\"\n autoFocus\n sx={FIRST_FIELD}\n error={props.slugTaken}\n helperText={draft?.name ? `/collections/${props.slug}` : undefined}\n />\n <MemoTextField\n label=\"Mode\"\n value={draft?.mode ?? 'manual'}\n onChange={setMode}\n size=\"small\"\n select\n >\n {MODE_MENU}\n </MemoTextField>\n {draft?.mode === 'manual' ? (\n <CollectionProductsField\n products={props.products}\n value={props.picked}\n onChange={props.onProducts}\n />\n ) : (\n <CollectionRulesFields\n rules={draft?.rules ?? NO_RULES}\n matchAll={draft?.matchAll !== false}\n categories={props.categories}\n setDraft={setDraft}\n onRule={props.onRule}\n />\n )}\n {error ? <Alert severity=\"warning\">{error}</Alert> : null}\n {draft ? (\n <CollectionPreview matches={props.matches} countPrefix={props.countPrefix} />\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button onClick={close}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim() || Boolean(error)}\n onClick={props.onSave}\n >\n {'Save'}\n </Button>\n </DialogActions>\n </Dialog>\n )\n})\n\n/** A collection with no rules yet, the same list on every render. */\nconst NO_RULES: readonly CommerceModel.CollectionRule[] = []\n\n/**\n * Categories & collections manager (AGL-280): category tree (parentId)\n * at `hosts/{hostId}/productCategories`, manual + smart collections at\n * `hosts/{hostId}/collections` with a live matched-product preview from\n * the same `matchesCollection` matcher the storefront uses.\n */\nexport function CatalogOrganizationCard(props: CatalogOrganizationCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { data: user } = useUser()\n\n const {\n data: categoryDocs,\n status: categoriesStatus,\n /**\n * The category rows are unconfirmed by the server (AGL-1358). Two writes\n * are seeded from them: the editor carries `parentId` off the row whether\n * or not the author touched it, and the delete REPARENTS every child of\n * the deleted category — a set computed entirely from this cached read,\n * so a stale snapshot can miss children that should have been moved.\n * (The reparent write itself is narrow since AGL-1374; what remains\n * cache-dependent is WHICH rows it runs on.)\n */\n fromCache: categoriesFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501).\n *\n * `limit(250)` alone is answered in DOCUMENT-ID order and the ids are\n * `createResourceUid()`, so the window was a pseudo-random sample. Naming\n * the order does not change WHICH 250 come back; what it changes is that\n * the obvious next edit is caught — `orderBy('name')` would HIDE every\n * category saved without one, and `orderBy('order')` is worse still, since\n * the walk below already treats a missing `order` as 0.\n *\n * The QUERY is not paged because this is a TREE. The walk puts parents\n * before children and collects orphans by scanning the whole set, so a\n * page boundary would separate a child from the parent that positions it\n * and re-label as an orphan every category whose parent is on another\n * page. The parent PICKER in the dialog reads the same rows for the same\n * reason.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'productCategories'),\n CATEGORY_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readCategories, truncated: categoriesTruncated } =\n ceilingedWindow<any>(categoryDocs, CATEGORY_CEILING)\n const {\n data: collectionDocs,\n status: collectionsStatus,\n /**\n * The collection rows are unconfirmed by the server (AGL-1358). The\n * editor copies a whole stored row and the save posts all of it — the\n * transport is the AGL-978 route rather than a client `setDoc`, but the\n * shape is identical, and so is the damage: `productIds` is the manual\n * membership, so a cached seed drops every product added since that\n * snapshot and the storefront blocks pointing at the collection go empty.\n */\n fromCache: collectionsFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged (AGL-2501).\n *\n * The slug check below tests a draft against these rows — two catalog\n * collections answering `/collections/{slug}` is a storefront route that\n * resolves to whichever the server reaches first — so a ten-row server\n * page would compare a new collection against a tenth of the catalog and\n * create the collision the check exists to prevent.\n *\n * The rows are also filtered after reading: content collections (AGL-81)\n * share this subcollection and are classified out below, so a page of ten\n * documents arrives holding anywhere from zero to ten catalog collections.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'collections'),\n COLLECTION_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readCollections, truncated: collectionsTruncated } =\n ceilingedWindow<any>(collectionDocs, COLLECTION_CEILING)\n const { data: productDocs } = useFirestoreCollection<any>(\n /*\n * The catalog behind the MATCH COUNTS, ceilinged with a probe (AGL-2501).\n *\n * `collectionCount` and the smart-collection preview both count this array\n * and print the result as a number of products. It was a bare `limit(500)`,\n * so on a three-thousand-product catalog \"Matches 47 products\" meant \"47 of\n * the five hundred I read\" — a count that is a window length, on the\n * control that decides what a collection contains.\n *\n * It stays a window, because the honest alternative is reading the whole\n * catalog on every mount of this card. What changes is that the probe makes\n * the shortfall a FACT, and the counts say \"at least\" when it bit rather\n * than stating a total they cannot know.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'products'),\n PRODUCT_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readProducts, truncated: productsTruncated } =\n ceilingedWindow<any>(productDocs, PRODUCT_CEILING)\n const products: ProductRow[] = useMemo(\n () =>\n [...readProducts]\n .filter((product: any) => !product.deletedAt)\n .map((product: any) => ({\n ...CommerceModel.liftLegacyProduct(product),\n $id: product.$id,\n })),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [productDocs],\n )\n // Content collections (AGL-81) live in the same `hosts/{hostId}/collections`\n // subcollection. This used to keep them out by requiring a non-empty\n // `name`, which held only because the Content page happens to write\n // `displayName` — a content doc that ever acquired a `name` (an import, a\n // hand edit) would land in this list, and its Delete reached the\n // recursiveDelete route (AGL-947). The shared classifier is the real\n // check (AGL-954); the route re-checks it, and AGL-1324 now refuses any\n // collection with entries besides.\n const commerceCollections: CollectionRow[] = useMemo(\n () => readCollections.filter(Aglyn.isHostCollectionKind('catalog')),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [collectionDocs],\n )\n\n // Categories ordered as a walked tree: parents before children.\n const categories: Array<CategoryRow & { depth: number }> = useMemo(() => {\n const rows = [...readCategories] as CategoryRow[]\n rows.sort(\n (a, b) => (a.order ?? 0) - (b.order ?? 0) || a.name.localeCompare(b.name),\n )\n const byParent = new Map<string | null, CategoryRow[]>()\n for (const row of rows) {\n const key = row.parentId ?? null\n byParent.set(key, [...(byParent.get(key) ?? []), row])\n }\n const walked: Array<CategoryRow & { depth: number }> = []\n const walk = (parentId: string | null, depth: number) => {\n for (const row of byParent.get(parentId) ?? []) {\n walked.push({ ...row, depth })\n if (depth < 4) walk(row.$id, depth + 1)\n }\n }\n walk(null, 0)\n // Orphans (parent deleted) still show, at the root.\n for (const row of rows) {\n if (!walked.some((item) => item.$id === row.$id)) {\n walked.push({ ...row, depth: 0 })\n }\n }\n return walked\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [categoryDocs])\n\n /*\n * Both pages are SLICES: the rows are already in hand, and the tree walk,\n * the parent picker and the slug check all need every one of them.\n */\n const [categoryPage, setCategoryPage] = useState(0)\n const [categoryPageSize, setCategoryPageSize] = useState(\n TABLE_PAGE_SIZE_DEFAULT,\n )\n const visibleCategories = useMemo(\n () =>\n categories.slice(\n categoryPage * categoryPageSize,\n categoryPage * categoryPageSize + categoryPageSize,\n ),\n [categories, categoryPage, categoryPageSize],\n )\n const [collectionPage, setCollectionPage] = useState(0)\n const [collectionPageSize, setCollectionPageSize] = useState(\n TABLE_PAGE_SIZE_DEFAULT,\n )\n const visibleCollections = useMemo(\n () =>\n commerceCollections.slice(\n collectionPage * collectionPageSize,\n collectionPage * collectionPageSize + collectionPageSize,\n ),\n [commerceCollections, collectionPage, collectionPageSize],\n )\n\n const [categoryDraft, setCategoryDraft] = useState<CategoryDraft | null>(null)\n const [collectionDraft, setCollectionDraft] = useState<CollectionDraft | null>(\n null,\n )\n\n const handleCategorySave = useCallback(async () => {\n if (!categoryDraft?.name.trim()) return\n const id = categoryDraft.id ?? Aglyn.createResourceUid()\n /**\n * Refuse an EDIT whose seed the server never confirmed (AGL-1358).\n *\n * The payload is narrower than most sites in this issue, but `parentId`\n * is carried off the seeded row on every save whether or not the author\n * opened the parent picker — so renaming a category against a cached read\n * can move it, and the whole subtree under it, back to a parent someone\n * had already reorganised away from.\n *\n * Only the edit path. A NEW category is built from blanks at a fresh uid\n * and can overwrite nothing, and the first snapshot of any listener is\n * `fromCache: true`, so guarding a create would refuse a save that was\n * never unsafe.\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: 'category',\n unreadable: Boolean(categoryDraft.id) && categoriesStatus === 'error',\n fromCache: Boolean(categoryDraft.id) && categoriesFromCache,\n },\n async () => {\n /**\n * `merge: true`, because this payload is NARROWER than the document\n * (AGL-1372). A replacing write deletes every stored key the form\n * does not send, and this form sends four:\n *\n * - `order` — the tree position. Both sorts read it (the walk above,\n * and `queryPublicCatalog`'s facet chips), and nothing in this card\n * can set it, so it is not the form's to send: a rename dropped it\n * and the category fell back to `?? 0`, reordering the storefront's\n * filter chips.\n * - `createdAt` — written at creation by the seeder, never by this\n * card, so a rename erased it too.\n *\n * Carrying `order` in the payload would have fixed the field we\n * happened to notice and left `createdAt`, plus whatever the document\n * grows next. Merging fixes the shape. Nothing here needs delete\n * semantics — `parentId` clears to an explicit `null`, which merges.\n */\n await setDoc(\n doc(firestore, 'hosts', hostId, 'productCategories', id),\n {\n name: categoryDraft.name.trim().slice(0, 80),\n slug: CommerceModel.commerceSlug(categoryDraft.name),\n parentId: categoryDraft.parentId || null,\n updatedAt: Timestamp.now(),\n },\n { merge: true },\n )\n },\n )\n // Before `setCategoryDraft(null)`, so a refusal keeps the dialog open\n // with what was typed.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setCategoryDraft(null)\n enqueueSnackbar('Category saved', { variant: 'success', persist: false })\n }, [\n categoryDraft,\n firestore,\n hostId,\n enqueueSnackbar,\n categoriesStatus,\n categoriesFromCache,\n ])\n\n const handleCategoryDelete = useCallback(\n (category: CategoryRow) => async () => {\n const confirmed = await confirm({\n title: 'Delete this category?',\n description:\n `Products keep their other categories; children of ` +\n `\"${category.name}\" move to the top level.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n /**\n * Refuse the whole sequence when the rows it reads were never confirmed\n * by the server (AGL-1358).\n *\n * The reparent is this issue's shape at its least visible: the author\n * opened no editor, so there is nothing on screen to look stale, and\n * `children` is read straight out of the cache. The write itself is\n * now narrow (see below), so a stale row can no longer be copied back\n * over a child — but WHICH rows are children is still a cached answer.\n *\n * The guard encloses the DELETE as well, for the reason the site\n * details rename did: `children` is computed from the same seed, so a\n * cached read can miss children entirely, and deleting the parent\n * without reparenting them leaves them pointing at a category that no\n * longer exists. Half of this sequence is worse than none of it.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'categories',\n unreadable: categoriesStatus === 'error',\n fromCache: categoriesFromCache,\n },\n async () => {\n // Reparent children to root, then remove.\n const children = (categoryDocs ?? []).filter(\n (row: any) => row.parentId === category.$id,\n )\n /**\n * Write only the field the reparent changes (AGL-1374).\n *\n * `{...child}` spread the listener row, and that row carries a\n * SYNTHETIC `$id` — `idField: '$id'` stamps the document id onto\n * the in-memory object, where nothing persists it. Spreading it\n * into the payload persisted it: every delete-with-children added\n * a real `$id` key to each child, permanently, and a child\n * reparented twice could end up carrying one that no longer\n * matched its own document id. Nothing reads it, so nothing broke\n * — it is the listener's bookkeeping leaking into storage, and\n * once there no reader can tell it from a real field.\n *\n * `{ parentId: null }` with `{ merge: true }` is what the reparent\n * actually means, and it is the stronger fix than stripping `$id`\n * off a full spread: the old write had no options argument, so it\n * was also a whole-document REPLACE of a cached row — the AGL-1358\n * hazard in miniature (and AGL-1372's, one collection over). A\n * narrow merge cannot carry a synthetic key it never names, and\n * cannot rewrite a field the delete has no business touching.\n *\n * `null` is a value, not a deletion, so it merges: the child ends\n * up at the top level, which is what the confirmation promised.\n */\n for (const child of children) {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'productCategories', child.$id),\n { parentId: null },\n { merge: true },\n )\n }\n await deleteDoc(\n doc(firestore, 'hosts', hostId, 'productCategories', category.$id),\n )\n },\n )\n // This path had no report of its own. A delete that silently does\n // nothing after the user confirmed it reads as a delete that worked.\n if (!verdict.ok) {\n enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n },\n [\n confirm,\n categoryDocs,\n firestore,\n hostId,\n enqueueSnackbar,\n categoriesStatus,\n categoriesFromCache,\n ],\n )\n\n const draftSlug = collectionDraft\n ? collectionDraft.slug || CommerceModel.commerceSlug(collectionDraft.name)\n : ''\n // The slug is the collection's public address at /collections/{slug} and\n // nothing enforced uniqueness (AGL-957) — a second one at the same slug\n // made the first unreachable with no error anywhere. Checked against the\n // catalog collections only; content collections have their own namespace.\n const slugTaken =\n collectionDraft !== null &&\n Aglyn.isCollectionSlugTaken(\n draftSlug,\n 'catalog',\n commerceCollections,\n collectionDraft.id,\n )\n const collectionError = collectionDraft\n ? collectionDraft.name\n ? (CommerceModel.validateCollection({\n ...collectionDraft,\n slug: draftSlug,\n }) ??\n (slugTaken\n ? `Another collection already serves /collections/${draftSlug}`\n : null))\n : null\n : null\n\n const collectionProductIds = collectionDraft?.productIds\n const collectionProducts = useMemo(\n () =>\n products.filter((product) =>\n (collectionProductIds ?? []).includes(product.$id),\n ),\n [products, collectionProductIds],\n )\n const setCollectionProducts = useCallback(\n (picked: ProductRow[]) =>\n setCollectionDraft((prev) =>\n prev ? { ...prev, productIds: picked.map((item) => item.$id) } : prev,\n ),\n [],\n )\n\n /*\n * Recomputed when what decides membership changes — the mode, the picked\n * products, the rules and whether all must hold — and not on a keystroke in\n * the name, which no match reads (AGL-3423).\n */\n const draftMode = collectionDraft?.mode\n const draftRules = collectionDraft?.rules\n const draftMatchAll = collectionDraft?.matchAll\n const previewMatches = useMemo(() => {\n if (!draftMode) return []\n const candidate = {\n mode: draftMode,\n productIds: collectionProductIds,\n rules: draftRules,\n matchAll: draftMatchAll,\n } as CommerceModel.HostCollection\n return products.filter((product) =>\n CommerceModel.matchesCollection(product, candidate, product.$id),\n )\n }, [draftMode, collectionProductIds, draftRules, draftMatchAll, products])\n\n /**\n * Which products a smart collection holds is stored on the products\n * (`collectionIds`, AGL-3321), so a save or a delete re-stamps them —\n * bounded passes through the commerce route until it says it is done.\n * A failure is reported, not thrown: the collection itself saved.\n */\n const restampMembership = useCallback(\n async (collectionId: string) => {\n try {\n let after: string | undefined\n for (let pass = 0; pass < 100; pass += 1) {\n const response = await authorizedFetch(\n user,\n '/api/commerce/collection-membership',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, collectionId, ...(after ? { after } : {}) }),\n },\n )\n const result = await response.json().catch(() => ({}))\n if (!response.ok) throw new Error(result?.error ?? 'Membership update failed')\n if (result.done || !result.after) return\n after = result.after\n }\n } catch (error: any) {\n enqueueSnackbar(\n `${error?.message ?? 'Membership update failed'} — the storefront may list this collection's old products until it is saved again.`,\n { variant: 'warning' },\n )\n }\n },\n [user, hostId, enqueueSnackbar],\n )\n\n const handleCollectionSave = useCallback(async () => {\n if (!collectionDraft?.name.trim() || collectionError) return\n const { id: draftId, ...data } = collectionDraft\n // Both create and rename go through the route (AGL-978): this save writes\n // the whole document including `slug`, which is the collection's public\n // address and is claimed transactionally there. Rules deny a client\n // create, and freeze `slug`/`kind` on update.\n /**\n * Refuse an UPDATE whose seed the server never confirmed (AGL-1358).\n *\n * The transport is the route rather than a client `setDoc`, but the shape\n * is the one this issue is about: `data` is the whole stored row copied\n * out of the listener, and the route writes what it is sent. `productIds`\n * is the manual membership, so a cached seed drops every product added\n * since that snapshot and the storefront blocks pointing at the\n * collection go empty; `rules` and `matchAll` do the same for a smart\n * collection. That the write leaves the browser over HTTP changes who\n * performs it, not what it destroys.\n *\n * Only the update path. A CREATE is built from blanks, and the route\n * claims a fresh slug transactionally, so it can overwrite nothing.\n *\n * The guard WRAPS the request — an early return is a shape you can keep\n * while losing the protection.\n */\n let verdict: Awaited<ReturnType<typeof writeGuardedBySeed>>\n let savedId = ''\n try {\n verdict = await writeGuardedBySeed(\n {\n subject: 'collection',\n unreadable: Boolean(draftId) && collectionsStatus === 'error',\n fromCache: Boolean(draftId) && collectionsFromCache,\n },\n async () => {\n const response = await authorizedFetch(\n user,\n '/api/hosts/collections',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n action: draftId ? 'update' : 'create',\n kind: 'catalog',\n ...(draftId ? { id: draftId } : {}),\n data: {\n ...data,\n name: collectionDraft.name.trim().slice(0, 80),\n slug: draftSlug,\n },\n }),\n },\n )\n const result = await response.json().catch(() => ({}))\n if (!response.ok) {\n throw new Error(result?.error ?? 'Collection save failed')\n }\n savedId = String(draftId ?? result?.id ?? '')\n },\n )\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Collection save failed', {\n variant: 'error',\n })\n }\n // Before `setCollectionDraft(null)`, so a refusal keeps the dialog open\n // with the membership that was picked.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setCollectionDraft(null)\n enqueueSnackbar('Collection saved', { variant: 'success', persist: false })\n if (savedId) await restampMembership(savedId)\n }, [\n restampMembership,\n collectionDraft,\n collectionError,\n draftSlug,\n user,\n hostId,\n enqueueSnackbar,\n collectionsStatus,\n collectionsFromCache,\n ])\n\n const handleCollectionDelete = useCallback(\n (row: CollectionRow) => async () => {\n const confirmed = await confirm({\n title: 'Delete this collection?',\n // NOT a cascade any more (AGL-1324/AGL-1336): the route REFUSES a\n // collection anything still depends on. Promising to take the\n // entries with it was the opposite of what happens, and the two\n // blockers are the whole point of the feature — say them before the\n // button is armed, not in a 409 afterwards.\n description:\n `Storefront blocks pointing at \"${row.name}\" go empty. The delete ` +\n 'is refused while the collection still has entries, or while a ' +\n 'page uses it as a list or entry template — empty it and detach ' +\n 'those pages first. It also takes the site admin role.',\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n // A collection owns an `entries` subcollection (the Content page's\n // published entries) and Firestore doesn't cascade, so deleting the\n // doc from here stranded them — still editor-writable through the\n // host catch-all rule, just unreachable. recursiveDelete is\n // Admin-SDK-only, hence the route (AGL-947). Since AGL-1324 the route\n // also refuses rather than cascading; the 409's message names the\n // blockers and is surfaced by the catch below.\n try {\n const response = await authorizedFetch(user, '/api/resources/erase', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n scope: 'hosts',\n scopeId: hostId,\n kind: 'collections',\n id: row.$id,\n // The route re-checks this server-side (AGL-954): a stale client\n // must not be able to recursiveDelete a content collection's\n // entries through the catalog card.\n collectionKind: 'catalog',\n }),\n })\n const result = await response.json().catch(() => ({}))\n if (!response.ok) {\n throw new Error(result?.error ?? 'Collection delete failed')\n }\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'Collection delete failed', {\n variant: 'error',\n })\n }\n enqueueSnackbar('Collection deleted', { variant: 'success', persist: false })\n await restampMembership(row.$id)\n },\n [confirm, user, hostId, enqueueSnackbar, restampMembership],\n )\n\n /*\n * \"at least\", or nothing at all.\n *\n * Every count on this card is computed over `products`, which is the catalog\n * WINDOW rather than the catalog. While the probe finds a product past the\n * ceiling those counts are lower bounds, and printing one as a total is the\n * count-that-is-a-window-length defect this ceiling exists to make visible.\n *\n * Keyed on the probe rather than on `products.length >= PRODUCT_CEILING`,\n * because a catalog of exactly the ceiling is complete: nothing is missing,\n * and a comparison would put \"at least\" on a number that is exact.\n */\n const countPrefix = productsTruncated ? 'at least ' : ''\n\n /*\n * A rule's change, written over the collection draft as last rendered, from\n * a handler that keeps its identity so a rule row redraws only when its own\n * rule changes (AGL-3423).\n */\n const latestCollectionDraft = useRef(collectionDraft)\n latestCollectionDraft.current = collectionDraft\n const updateRule = useCallback<RuleChange>((index, patch) => {\n const draft = latestCollectionDraft.current\n if (!draft) return\n const rules = [...(draft.rules ?? [])]\n if (patch === null) rules.splice(index, 1)\n else\n rules[index] = {\n field: 'tag',\n op: 'eq',\n value: '',\n ...rules[index],\n ...patch,\n }\n setCollectionDraft({ ...draft, rules })\n }, [])\n\n return (\n <CardDisplay\n header={'Categories & collections'}\n help={pluginDocsHelp('catalog', { anchor: '#categories-and-tags' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <CategoriesSection\n categories={categories}\n visible={visibleCategories}\n page={categoryPage}\n pageSize={categoryPageSize}\n truncated={categoriesTruncated}\n onPageChange={setCategoryPage}\n onPageSizeChange={setCategoryPageSize}\n onEdit={setCategoryDraft}\n onDelete={handleCategoryDelete}\n />\n\n <Divider sx={{ my: 1 }} />\n <CollectionsSection\n collections={commerceCollections}\n visible={visibleCollections}\n products={products}\n countPrefix={countPrefix}\n page={collectionPage}\n pageSize={collectionPageSize}\n truncated={collectionsTruncated}\n onPageChange={setCollectionPage}\n onPageSizeChange={setCollectionPageSize}\n onEdit={setCollectionDraft}\n onDelete={handleCollectionDelete}\n />\n </Stack>\n\n <CategoryDialog\n draft={categoryDraft}\n categories={categories}\n setDraft={setCategoryDraft}\n onSave={handleCategorySave}\n />\n\n <CollectionDialog\n draft={collectionDraft}\n slug={draftSlug}\n slugTaken={slugTaken}\n error={collectionError}\n products={products}\n picked={collectionProducts}\n categories={categories}\n matches={previewMatches}\n countPrefix={countPrefix}\n setDraft={setCollectionDraft}\n onProducts={setCollectionProducts}\n onRule={updateRule}\n onSave={handleCollectionSave}\n />\n </CardDisplay>\n )\n}\nCatalogOrganizationCard.displayName = 'CatalogOrganizationCard'\n\nexport default CatalogOrganizationCard\n"],"names":["Aglyn","CommerceModel","CardDisplay","useConfirmationContext","useSnackbar","Timestamp","Alert","Autocomplete","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Divider","MenuItem","Stack","Switch","TextField","Typography","collection","deleteDoc","doc","setDoc","memo","useCallback","useMemo","useRef","useState","useFirestore","useUser","ceilingedWindow","collectionCeiling","useFirestoreCollection","writeGuardedBySeed","ListPagination","TABLE_PAGE_SIZE_DEFAULT","pluginDocsHelp","authorizedFetch","CATEGORY_CEILING","COLLECTION_CEILING","PRODUCT_CEILING","RULE_FIELDS","value","label","RULE_OPS","productLabel","product","name","sameProduct","option","$id","CollectionProductsField","props","onChange","multiple","options","products","getOptionLabel","isOptionEqualToValue","_event","picked","renderInput","params","size","MemoTextField","FIRST_FIELD","mt","RULE_FIELD","width","RULE_OP","RULE_VALUE","flex","MODE_MENU","RULE_FIELD_MENU","map","field","RULE_OP_MENU","op","CategoriesSection","categories","visible","onEdit","onDelete","variant","length","color","category","direction","spacing","sx","alignItems","pl","depth","noWrap","component","slug","onClick","id","parentId","page","pageSize","rowCount","count","onPageChange","onPageSizeChange","truncated","severity","alignSelf","CollectionsSection","collections","countPrefix","collectionCount","row","filter","matchesCollection","mode","productIds","rules","matchAll","CategoryDialog","draft","setDraft","draftId","close","setName","event","prev","target","setParent","parentMenu","repeat","open","Boolean","onClose","maxWidth","fullWidth","display","flexDirection","gap","autoFocus","select","disabled","trim","onSave","CollectionRuleRow","index","rule","setField","setOp","setCategory","ruleField","setValue","Number","categoryMenu","placeholder","CollectionMatchSwitch","checked","CollectionRulesFields","onRule","CollectionPreview","matches","flexWrap","slice","CollectionDialog","error","setMode","slugTaken","helperText","undefined","onProducts","NO_RULES","CatalogOrganizationCard","hostId","firestore","enqueueSnackbar","confirm","data","user","categoryDocs","status","categoriesStatus","fromCache","categoriesFromCache","idField","rows","readCategories","categoriesTruncated","collectionDocs","collectionsStatus","collectionsFromCache","readCollections","collectionsTruncated","productDocs","readProducts","productsTruncated","deletedAt","liftLegacyProduct","commerceCollections","isHostCollectionKind","sort","a","b","order","localeCompare","byParent","Map","key","set","get","walked","walk","push","some","item","categoryPage","setCategoryPage","categoryPageSize","setCategoryPageSize","visibleCategories","collectionPage","setCollectionPage","collectionPageSize","setCollectionPageSize","visibleCollections","categoryDraft","setCategoryDraft","collectionDraft","setCollectionDraft","handleCategorySave","createResourceUid","verdict","subject","unreadable","commerceSlug","updatedAt","now","merge","ok","message","persist","handleCategoryDelete","confirmed","title","description","confirmationText","confirmationButtonProps","then","catch","children","child","draftSlug","isCollectionSlugTaken","collectionError","validateCollection","collectionProductIds","collectionProducts","includes","setCollectionProducts","draftMode","draftRules","draftMatchAll","previewMatches","candidate","restampMembership","collectionId","after","pass","response","method","headers","body","JSON","stringify","result","json","Error","done","handleCollectionSave","savedId","action","kind","String","handleCollectionDelete","scope","scopeId","collectionKind","latestCollectionDraft","current","updateRule","patch","splice","header","help","anchor","contentGutterX","contentGutterY","my","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,YAAYA,WAAW,eAAc;AACrC,YAAYC,mBAAmB,uBAAa;AAC5C,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,KAAK,EACLC,YAAY,EACZC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,OAAO,EACPC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,SAAS,EAAEC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AACvE,SAGEC,IAAI,EACJC,WAAW,EACXC,OAAO,EACPC,MAAM,EACNC,QAAQ,QACH,QAAO;AACd,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SACEC,eAAe,EACfC,iBAAiB,EACjBC,sBAAsB,EACtBC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SAASC,cAAc,QAAQ,eAAc;AAC7C,SAASC,eAAe,QAAQ,2CAA0C;AAE1E;;;;;CAKC,GACD,MAAMC,mBAAmB;AACzB,6EAA6E,GAC7E,MAAMC,qBAAqB;AAC3B;;;;;;CAMC,GACD,MAAMC,kBAAkB;AAUxB,MAAMC,cAAkF;IACtF;QAAEC,OAAO;QAAOC,OAAO;IAAM;IAC7B;QAAED,OAAO;QAAcC,OAAO;IAAW;IACzC;QAAED,OAAO;QAAYC,OAAO;IAAQ;IACpC;QAAED,OAAO;QAAQC,OAAO;IAAO;IAC/B;QAAED,OAAO;QAAQC,OAAO;IAAO;CACh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AM2J;gBACNpF,WAAWA;gBACXF,OAAOwF;gBACPpM,UAAUA;gBACVI,QAAQmM;gBACRhL,YAAYA;gBACZiF,SAASqG;gBACTvJ,aAAaA;gBACbW,UAAU0G;gBACV1D,YAAYwF;gBACZnG,QAAQkI;gBACRjJ,QAAQsI;;;;AAIhB;AACA1G,wBAAwB8H,WAAW,GAAG;AAEtC,eAAe9H,wBAAuB"}
@@ -236,7 +236,7 @@ import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
236
236
  /*#__PURE__*/ _jsx(Typography, {
237
237
  variant: "body2",
238
238
  color: "text.secondary",
239
- children: 'Card processing is passed through at cost on top of that: ' + `${Aglyn.MARKETPLACE_PROCESSING_PERCENT_CARD}–` + `${Aglyn.MARKETPLACE_PROCESSING_PERCENT_BNPL}% + ` + `${Aglyn.MARKETPLACE_PROCESSING_FIXED_CENTS}¢ per online ` + 'sale, what Stripe charges to take the payment. It is not a ' + `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} margin.`
239
+ children: 'Card processing is passed through at cost on top of that: ' + `${Aglyn.CARD_PROCESSING_PERCENT}–` + `${Aglyn.BNPL_PROCESSING_PERCENT}% + ` + `${Aglyn.PROCESSING_FIXED_CENTS}¢ per online ` + 'sale, what Stripe charges to take the payment. It is not a ' + `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} margin.`
240
240
  }),
241
241
  physicalPct > 0 || digitalPct > 0 ? /*#__PURE__*/ _jsx(Typography, {
242
242
  variant: "body2",
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/payments-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 { trackEvent } from '@aglyn/aglyn/app-utils/analytics-events'\nimport * as Aglyn from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useOrgPlan } from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\n\nexport interface PaymentsSettingsCardProps {\n hostId: string\n}\n\n/**\n * Merchant payments card (AGL-284): Stripe Connect Express onboarding\n * status for the org owner + the plan's transaction-fee ladder so the\n * \"upgrade to kill fees\" motion (AGL-278) is visible where it matters.\n */\nexport function PaymentsSettingsCard(props: PaymentsSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [busy, setBusy] = useState(false)\n /**\n * A one-time Stripe Express dashboard link, minted by the connect route on\n * request. Not persisted: login links are single-use and short-lived, so a\n * stored one would be a button that fails the second time it is pressed.\n */\n const [dashboardUrl, setDashboardUrl] = useState<string | null>(null)\n const { org, ready: planReady } = useOrgPlan(hostId)\n /** Bumped by Retry to re-subscribe the profile listen (AGL-1380). */\n const [retryNonce, setRetryNonce] = useState(0)\n const uid = (user as any)?.uid as string | undefined\n const { data: profile, status: profileStatus } = useFirestoreDoc<any>(\n // Held at null rather than addressed as `profiles/-pending-` — that\n // sentinel issued a guaranteed-denied read on every pre-auth mount, and\n // a denial lands in `status: 'error'`, which now means something.\n () => (uid ? doc(firestore, 'profiles', uid) : null),\n [firestore, uid, retryNonce],\n )\n const isOwner = Boolean(\n org?.ownerUid && (user as any)?.uid === org.ownerUid,\n )\n /**\n * Three outcomes, not two (AGL-1380). An absent profile doc is the value\n * BEFORE an answer as much as it is the value of a merchant who never\n * connected Stripe, so \"Not set up\" off a falsy `stripeChargesEnabled` is a\n * claim about this org's payment setup made without having heard back. It\n * is wrong in the direction that provokes action: the same falsy value\n * turns the button into \"Set up payments\", which sends a merchant who is\n * already taking money into Stripe onboarding.\n */\n const stripeState: 'pending' | 'error' | 'loaded' =\n !uid || profileStatus === 'loading'\n ? 'pending'\n : profileStatus === 'error'\n ? 'error'\n : 'loaded'\n /**\n * WHICH STRIPE WORLD THE STORED ACCOUNT BELONGS TO (AGL-2471).\n *\n * `stripeChargesEnabled: true` was the whole readiness claim, and a\n * production profile carrying it named a TEST-mode account: this card said\n * \"Charges enabled\" about three storefronts that could not take a single\n * payment. Only a literal boolean counts as recorded — the same\n * three-valued reading `merchantAccountIsReady` uses on the server, so the\n * chip and the checkout cannot disagree.\n */\n const modeVerified = typeof profile?.stripeAccountLivemode === 'boolean'\n const chargesConnected =\n stripeState === 'loaded' && Boolean(profile?.stripeChargesEnabled)\n const modeUnverified = chargesConnected && !modeVerified\n const chargesEnabled = chargesConnected && modeVerified\n const physicalPct = Aglyn.resolveTransactionFeePct(org, 'physical')\n const digitalPct = Aglyn.resolveTransactionFeePct(org, 'digital')\n const commerceEnabled = Aglyn.checkEntitlement(org, 'commerce')\n\n const handleConnect = useCallback(async () => {\n setBusy(true)\n try {\n const response = await authorizedFetch(user, '/api/commerce/connect', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId }),\n })\n const payload = await response.json()\n if (response.status === 501) {\n return void enqueueSnackbar(\n 'Payments are not configured on this deployment',\n { variant: 'info', persist: false },\n )\n }\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'Payment setup failed', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n if (payload.chargesEnabled) {\n // \"% who connect Stripe\" — a GTM plan §6 activation metric\n // (AGL-1561). Gated on the TRANSITION, not the state: this handler\n // is a re-entrant create-or-resume, so it answers `chargesEnabled:\n // true` on every subsequent visit to a connected account, and a bare\n // event here would count one merchant once per click forever.\n // `chargesEnabled` is the state read from the profile BEFORE this\n // request, so the event fires only when onboarding actually completed.\n if (!chargesEnabled) trackEvent('stripe_connected', {})\n // CHARGES AND PAYOUTS ARE TWO FLAGS, AND ONLY ONE OF THEM IS THIS\n // SENTENCE (AGL-1997). `chargesEnabled` says Stripe will let the\n // account take money; whether the money can LEAVE is `payoutsEnabled`,\n // which the route answers alongside it. Charges-yes/payouts-no is an\n // ordinary Stripe state — verification pending or lapsed, no payout\n // method — and announcing \"Payments are enabled\" in it is false in the\n // direction that costs the merchant: they sell believing they are\n // paid, and the funds sit in a Connect account that cannot release\n // them. Read three-valued, so only a literal `false` from Stripe\n // downgrades the claim; an absent flag means unasked, not off.\n const payoutsBlocked = payload.payoutsEnabled === false\n // A WARNING THAT NAMES A PROBLEM MUST OFFER THE FIX.\n //\n // Stripe is the only place payouts can be released — an Express\n // account has no password and no direct login — so telling the\n // merchant their funds are stranded and then keeping them here is half\n // an answer. The route now mints the remediation link for exactly this\n // state; going there is the whole point of pressing the button.\n if (payoutsBlocked && payload.url) {\n return void window.location.assign(payload.url)\n }\n // Payouts are flowing, so the link is the Express dashboard: balance,\n // payout schedule, and the reason a payout failed. Held in state\n // rather than followed, because this click was a status check and\n // navigating away from one nobody asked to leave is its own defect.\n if (!payoutsBlocked && typeof payload.dashboardUrl === 'string') {\n setDashboardUrl(payload.dashboardUrl)\n }\n return void enqueueSnackbar(\n payoutsBlocked\n ? 'Connected — payouts are not released yet'\n : 'Payments are enabled',\n {\n variant: payoutsBlocked ? 'warning' : 'success',\n persist: false,\n },\n )\n }\n if (payload.url) window.location.assign(payload.url)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [user, hostId, chargesEnabled, enqueueSnackbar])\n\n return (\n <CardDisplay\n header={'Payments'}\n help={pluginDocsHelp('commerceEndToEnd', {\n anchor: '#1-connect-payments',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }}>\n {'Stripe account'}\n </Typography>\n {/*\n No chip at all on error: both labels it could carry — \"Charges\n enabled\" and \"Not set up\" — assert something we failed to find\n out. Whatever Stripe is doing right now it carries on doing.\n */}\n {stripeState === 'error' ? null : (\n <Chip\n size=\"small\"\n label={\n stripeState === 'pending'\n ? 'Checking…'\n : chargesEnabled\n ? 'Charges enabled'\n : modeUnverified\n ? 'Not verified'\n : 'Not set up'\n }\n color={\n stripeState === 'pending'\n ? 'default'\n : chargesEnabled\n ? 'success'\n : modeUnverified\n ? 'error'\n : 'warning'\n }\n variant=\"outlined\"\n />\n )}\n </Stack>\n {stripeState === 'error' ? (\n <Alert\n severity=\"error\"\n action={\n <Button\n color=\"inherit\"\n size=\"small\"\n onClick={() => setRetryNonce((n) => n + 1)}\n >\n {'Retry'}\n </Button>\n }\n >\n {'We couldn’t load your payment setup. This says nothing about ' +\n 'whether payments are on — we could not reach the setting to ' +\n 'find out. Nothing has changed.'}\n </Alert>\n ) : null}\n {/*\n Every line below reads the plan, and an org doc still in flight\n resolves to the FREE tier (AGL-1064) — which would flash \"Selling\n requires a paid plan\" and the wrong fee percentages at a paying\n seller, then correct itself. Say nothing until it is known.\n */}\n {!planReady ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Checking your plan…'}\n </Typography>\n ) : (\n <>\n {!commerceEnabled ? (\n <Alert severity=\"info\">\n {'Selling requires a paid plan — upgrade on the billing page.'}\n </Alert>\n ) : null}\n {/*\n THE LEGAL NAME, not the org's resolved `productName`\n (AGL-2351). This sentence says who takes money off the\n merchant's own Stripe account, and the application fee lands in\n the platform Stripe account — held by the operating entity, not\n by a white-label agency reselling the console. Naming the\n agency here would assert a fee relationship that does not\n exist. `PLATFORM_BRAND_LEGAL_NAME` still configures cleanly for\n a self-host operator, who really is the entity collecting it.\n */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Buyers pay on your own Stripe account; ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} collects a platform fee ` +\n 'per sale based on your plan:'}\n </Typography>\n {/* The DIGITAL rate is not products-only (AGL-2315). A paid\n booking is a service sale and resolves through the same\n `'service'`/digital axis, so a bookings-only merchant pays this\n exact number — and this card was the one place they could read\n their own rate while naming only \"products\". Stated here rather\n than adding a third figure: it is one rate, not two. */}\n <Typography variant=\"body2\">\n {`Physical products: ${physicalPct}% · Digital products, ` +\n `services & bookings: ${digitalPct}%`}\n {physicalPct > 0 || digitalPct > 0 ? (\n <Typography\n component=\"span\"\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {' — higher plans reduce fees to 0%'}\n </Typography>\n ) : null}\n </Typography>\n {/* CARD PROCESSING, PASSED THROUGH AT COST (AGL-2152).\n\n Unconditional, including on the 0% plans, because it is\n exactly those plans where the merchant would otherwise read\n \"0%\" and be surprised by a deduction. Their PLATFORM fee\n really is zero — the figure below is Stripe's own charge for\n taking the payment, which every storefront sale incurs and\n which used to be absorbed silently out of the platform's\n balance rather than passed through.\n\n Named as a range rather than one number because the buyer\n chooses the payment method after the session is created:\n cards settle at the low end, buy-now-pay-later at the high\n end, and the deduction is sized for the dearest so a sale can\n never cost more to process than it collects. */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Card processing is passed through at cost on top of that: ' +\n `${Aglyn.MARKETPLACE_PROCESSING_PERCENT_CARD}–` +\n `${Aglyn.MARKETPLACE_PROCESSING_PERCENT_BNPL}% + ` +\n `${Aglyn.MARKETPLACE_PROCESSING_FIXED_CENTS}¢ per online ` +\n 'sale, what Stripe charges to take the payment. It is not a ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} margin.`}\n </Typography>\n {/* EVERY TENDER, AND HOW EACH IS COLLECTED (AGL-2111).\n\n Until now this card said \"per sale\" and meant it for online and\n card sales only: cash and room-charge sales at the register\n recorded no fee at all, so a merchant could read this sentence,\n ring everything as cash, and pay nothing. The fee now attaches\n to the sale on every tender, which makes the sentence above\n true — and creates a second, visible collection route the\n merchant has to be told about BEFORE it appears on their\n invoice, because it is money leaving by a door they have never\n seen it leave by.\n\n Shown only when a rate actually applies: on a 0% plan there is\n nothing to collect either way, and the paragraph would be noise\n on the card of the merchants who upgraded to escape fees. */}\n {physicalPct > 0 || digitalPct > 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The fee is charged on the sale, not on how it was paid — ' +\n 'in-person cash and room-charge sales carry it too. On card ' +\n 'sales it is deducted from your Stripe payout; on cash and ' +\n 'room-charge sales there is no payout to deduct from, so it ' +\n `is added to your monthly ${Aglyn.PLATFORM_BRAND_LEGAL_NAME} ` +\n 'invoice instead.'}\n </Typography>\n ) : null}\n </>\n )}\n {/*\n AGL-2471: connected, and refused by every money door because the\n account was never verified against this deployment's Stripe mode.\n \"Not set up\" would be a lie in the other direction — the merchant\n did set something up — so the card names what is actually wrong and\n what to do about it.\n */}\n {modeUnverified ? (\n <Alert severity=\"error\">\n {'Your Stripe account has not been verified for payments on ' +\n 'this site, so sales will be refused. Set up payments again ' +\n 'to verify it — if it was connected against Stripe test mode, ' +\n 'you will need to connect a live account.'}\n </Alert>\n ) : null}\n {/*\n The button's own label is a claim — \"Set up payments\" tells the\n owner they have none. Withheld until the answer is in, for the same\n reason as the chip (AGL-1380); on error the Retry above is the only\n action offered, because acting on a setup we could not read is how\n a connected merchant gets sent back through onboarding.\n */}\n {/*\n WHERE THE MONEY STOPPED. Mirrored onto this profile by the\n `payout.failed` handler and retired by the next successful payout, so\n it names a live problem rather than a scar. Without it a merchant sold\n into an account that could not release the funds and the card said\n \"Payments are enabled\" the whole time — the storefront looked healthy\n from every angle available to them.\n */}\n {stripeState === 'loaded' && profile?.lastPayoutFailureAtMs ? (\n <Alert severity=\"warning\" variant=\"outlined\">\n {`A payout of $${(\n Number(profile.lastPayoutFailureCents ?? 0) / 100\n ).toFixed(2)} did not reach your bank on ${new Date(\n Number(profile.lastPayoutFailureAtMs),\n ).toLocaleDateString()} — ${String(\n profile.lastPayoutFailureReason ?? 'Stripe did not say why',\n )} The money is still in your Stripe account. Open Stripe to fix your payout details.`}\n </Alert>\n ) : null}\n {!planReady || stripeState !== 'loaded' ? null : isOwner ? (\n <>\n <Button\n size=\"small\"\n variant={chargesEnabled ? 'text' : 'contained'}\n color=\"primary\"\n disabled={busy}\n onClick={handleConnect}\n sx={{ alignSelf: 'flex-start' }}\n >\n {chargesEnabled\n ? 'Refresh status'\n : busy\n ? 'Opening Stripe…'\n : 'Set up payments'}\n </Button>\n {/*\n Where the money actually is. Aglyn records none of it —\n no balance, no payout schedule, and no `payout.failed` handling\n anywhere — so a merchant whose payout bounced has no way to learn\n that from this console. An Express account has no direct login\n either, which leaves a link minted by the platform as the only\n route in. `target=\"_blank\"` because it leaves the app entirely.\n */}\n {dashboardUrl ? (\n <Button\n size=\"small\"\n variant=\"text\"\n color=\"primary\"\n href={dashboardUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n sx={{ alignSelf: 'flex-start' }}\n >\n {'View payouts in Stripe'}\n </Button>\n ) : null}\n </>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Only the organization owner can set up payments.'}\n </Typography>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nPaymentsSettingsCard.displayName = 'PaymentsSettingsCard'\n\nexport default PaymentsSettingsCard\n"],"names":["trackEvent","Aglyn","CardDisplay","useSnackbar","Alert","Button","Chip","Stack","Typography","doc","useCallback","useState","useFirestore","useUser","useFirestoreDoc","useOrgPlan","pluginDocsHelp","authorizedFetch","PaymentsSettingsCard","props","profile","hostId","firestore","data","user","enqueueSnackbar","busy","setBusy","dashboardUrl","setDashboardUrl","org","ready","planReady","retryNonce","setRetryNonce","uid","status","profileStatus","isOwner","Boolean","ownerUid","stripeState","modeVerified","stripeAccountLivemode","chargesConnected","stripeChargesEnabled","modeUnverified","chargesEnabled","physicalPct","resolveTransactionFeePct","digitalPct","commerceEnabled","checkEntitlement","handleConnect","response","method","headers","body","JSON","stringify","payload","json","variant","persist","ok","error","allowDuplicate","payoutsBlocked","payoutsEnabled","url","window","location","assign","console","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","flex","size","label","color","severity","action","onClick","n","PLATFORM_BRAND_LEGAL_NAME","component","MARKETPLACE_PROCESSING_PERCENT_CARD","MARKETPLACE_PROCESSING_PERCENT_BNPL","MARKETPLACE_PROCESSING_FIXED_CENTS","lastPayoutFailureAtMs","Number","lastPayoutFailureCents","toFixed","Date","toLocaleDateString","String","lastPayoutFailureReason","disabled","alignSelf","href","target","rel","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,UAAU,QAAQ,0CAAyC;AACpE,YAAYC,WAAW,eAAc;AACrC,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACtE,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,eAAe,QAAQ,iCAAgC;AAChE,SAASC,UAAU,QAAQ,iCAAgC;AAC3D,SAASC,cAAc,QAAQ,eAAc;AAC7C,SAASC,eAAe,QAAQ,2CAA0C;AAM1E;;;;CAIC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;QAgVhDC,iCAIPA;IAnVZ,MAAM,EAAEC,MAAM,EAAE,GAAGF;IACnB,MAAMG,YAAYV;IAClB,MAAM,EAAEW,MAAMC,IAAI,EAAE,GAAG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AAgB,WAAW,OAAOH,wBAC/C;;sCACE,KAACjC;4BACC+E,MAAK;4BACLtB,SAASf,iBAAiB,SAAS;4BACnCuC,OAAM;4BACNkB,UAAU9E;4BACV+D,SAASpC;4BACT4B,IAAI;gCAAEwB,WAAW;4BAAa;sCAE7B1D,iBACG,mBACArB,OACE,oBACA;;wBAUPE,6BACC,KAACvB;4BACC+E,MAAK;4BACLtB,SAAQ;4BACRwB,OAAM;4BACNoB,MAAM9E;4BACN+E,QAAO;4BACPC,KAAI;4BACJ3B,IAAI;gCAAEwB,WAAW;4BAAa;sCAE7B;6BAED;;mCAGN,KAACjG;oBAAWsD,SAAQ;oBAAUwB,OAAM;8BACjC;;;;;AAMb;AACApE,qBAAqB2F,WAAW,GAAG;AAEnC,eAAe3F,qBAAoB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/payments-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 { trackEvent } from '@aglyn/aglyn/app-utils/analytics-events'\nimport * as Aglyn from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useOrgPlan } from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\n\nexport interface PaymentsSettingsCardProps {\n hostId: string\n}\n\n/**\n * Merchant payments card (AGL-284): Stripe Connect Express onboarding\n * status for the org owner + the plan's transaction-fee ladder so the\n * \"upgrade to kill fees\" motion (AGL-278) is visible where it matters.\n */\nexport function PaymentsSettingsCard(props: PaymentsSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [busy, setBusy] = useState(false)\n /**\n * A one-time Stripe Express dashboard link, minted by the connect route on\n * request. Not persisted: login links are single-use and short-lived, so a\n * stored one would be a button that fails the second time it is pressed.\n */\n const [dashboardUrl, setDashboardUrl] = useState<string | null>(null)\n const { org, ready: planReady } = useOrgPlan(hostId)\n /** Bumped by Retry to re-subscribe the profile listen (AGL-1380). */\n const [retryNonce, setRetryNonce] = useState(0)\n const uid = (user as any)?.uid as string | undefined\n const { data: profile, status: profileStatus } = useFirestoreDoc<any>(\n // Held at null rather than addressed as `profiles/-pending-` — that\n // sentinel issued a guaranteed-denied read on every pre-auth mount, and\n // a denial lands in `status: 'error'`, which now means something.\n () => (uid ? doc(firestore, 'profiles', uid) : null),\n [firestore, uid, retryNonce],\n )\n const isOwner = Boolean(\n org?.ownerUid && (user as any)?.uid === org.ownerUid,\n )\n /**\n * Three outcomes, not two (AGL-1380). An absent profile doc is the value\n * BEFORE an answer as much as it is the value of a merchant who never\n * connected Stripe, so \"Not set up\" off a falsy `stripeChargesEnabled` is a\n * claim about this org's payment setup made without having heard back. It\n * is wrong in the direction that provokes action: the same falsy value\n * turns the button into \"Set up payments\", which sends a merchant who is\n * already taking money into Stripe onboarding.\n */\n const stripeState: 'pending' | 'error' | 'loaded' =\n !uid || profileStatus === 'loading'\n ? 'pending'\n : profileStatus === 'error'\n ? 'error'\n : 'loaded'\n /**\n * WHICH STRIPE WORLD THE STORED ACCOUNT BELONGS TO (AGL-2471).\n *\n * `stripeChargesEnabled: true` was the whole readiness claim, and a\n * production profile carrying it named a TEST-mode account: this card said\n * \"Charges enabled\" about three storefronts that could not take a single\n * payment. Only a literal boolean counts as recorded — the same\n * three-valued reading `merchantAccountIsReady` uses on the server, so the\n * chip and the checkout cannot disagree.\n */\n const modeVerified = typeof profile?.stripeAccountLivemode === 'boolean'\n const chargesConnected =\n stripeState === 'loaded' && Boolean(profile?.stripeChargesEnabled)\n const modeUnverified = chargesConnected && !modeVerified\n const chargesEnabled = chargesConnected && modeVerified\n const physicalPct = Aglyn.resolveTransactionFeePct(org, 'physical')\n const digitalPct = Aglyn.resolveTransactionFeePct(org, 'digital')\n const commerceEnabled = Aglyn.checkEntitlement(org, 'commerce')\n\n const handleConnect = useCallback(async () => {\n setBusy(true)\n try {\n const response = await authorizedFetch(user, '/api/commerce/connect', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId }),\n })\n const payload = await response.json()\n if (response.status === 501) {\n return void enqueueSnackbar(\n 'Payments are not configured on this deployment',\n { variant: 'info', persist: false },\n )\n }\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'Payment setup failed', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n if (payload.chargesEnabled) {\n // \"% who connect Stripe\" — a GTM plan §6 activation metric\n // (AGL-1561). Gated on the TRANSITION, not the state: this handler\n // is a re-entrant create-or-resume, so it answers `chargesEnabled:\n // true` on every subsequent visit to a connected account, and a bare\n // event here would count one merchant once per click forever.\n // `chargesEnabled` is the state read from the profile BEFORE this\n // request, so the event fires only when onboarding actually completed.\n if (!chargesEnabled) trackEvent('stripe_connected', {})\n // CHARGES AND PAYOUTS ARE TWO FLAGS, AND ONLY ONE OF THEM IS THIS\n // SENTENCE (AGL-1997). `chargesEnabled` says Stripe will let the\n // account take money; whether the money can LEAVE is `payoutsEnabled`,\n // which the route answers alongside it. Charges-yes/payouts-no is an\n // ordinary Stripe state — verification pending or lapsed, no payout\n // method — and announcing \"Payments are enabled\" in it is false in the\n // direction that costs the merchant: they sell believing they are\n // paid, and the funds sit in a Connect account that cannot release\n // them. Read three-valued, so only a literal `false` from Stripe\n // downgrades the claim; an absent flag means unasked, not off.\n const payoutsBlocked = payload.payoutsEnabled === false\n // A WARNING THAT NAMES A PROBLEM MUST OFFER THE FIX.\n //\n // Stripe is the only place payouts can be released — an Express\n // account has no password and no direct login — so telling the\n // merchant their funds are stranded and then keeping them here is half\n // an answer. The route now mints the remediation link for exactly this\n // state; going there is the whole point of pressing the button.\n if (payoutsBlocked && payload.url) {\n return void window.location.assign(payload.url)\n }\n // Payouts are flowing, so the link is the Express dashboard: balance,\n // payout schedule, and the reason a payout failed. Held in state\n // rather than followed, because this click was a status check and\n // navigating away from one nobody asked to leave is its own defect.\n if (!payoutsBlocked && typeof payload.dashboardUrl === 'string') {\n setDashboardUrl(payload.dashboardUrl)\n }\n return void enqueueSnackbar(\n payoutsBlocked\n ? 'Connected — payouts are not released yet'\n : 'Payments are enabled',\n {\n variant: payoutsBlocked ? 'warning' : 'success',\n persist: false,\n },\n )\n }\n if (payload.url) window.location.assign(payload.url)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [user, hostId, chargesEnabled, enqueueSnackbar])\n\n return (\n <CardDisplay\n header={'Payments'}\n help={pluginDocsHelp('commerceEndToEnd', {\n anchor: '#1-connect-payments',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }}>\n {'Stripe account'}\n </Typography>\n {/*\n No chip at all on error: both labels it could carry — \"Charges\n enabled\" and \"Not set up\" — assert something we failed to find\n out. Whatever Stripe is doing right now it carries on doing.\n */}\n {stripeState === 'error' ? null : (\n <Chip\n size=\"small\"\n label={\n stripeState === 'pending'\n ? 'Checking…'\n : chargesEnabled\n ? 'Charges enabled'\n : modeUnverified\n ? 'Not verified'\n : 'Not set up'\n }\n color={\n stripeState === 'pending'\n ? 'default'\n : chargesEnabled\n ? 'success'\n : modeUnverified\n ? 'error'\n : 'warning'\n }\n variant=\"outlined\"\n />\n )}\n </Stack>\n {stripeState === 'error' ? (\n <Alert\n severity=\"error\"\n action={\n <Button\n color=\"inherit\"\n size=\"small\"\n onClick={() => setRetryNonce((n) => n + 1)}\n >\n {'Retry'}\n </Button>\n }\n >\n {'We couldn’t load your payment setup. This says nothing about ' +\n 'whether payments are on — we could not reach the setting to ' +\n 'find out. Nothing has changed.'}\n </Alert>\n ) : null}\n {/*\n Every line below reads the plan, and an org doc still in flight\n resolves to the FREE tier (AGL-1064) — which would flash \"Selling\n requires a paid plan\" and the wrong fee percentages at a paying\n seller, then correct itself. Say nothing until it is known.\n */}\n {!planReady ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Checking your plan…'}\n </Typography>\n ) : (\n <>\n {!commerceEnabled ? (\n <Alert severity=\"info\">\n {'Selling requires a paid plan — upgrade on the billing page.'}\n </Alert>\n ) : null}\n {/*\n THE LEGAL NAME, not the org's resolved `productName`\n (AGL-2351). This sentence says who takes money off the\n merchant's own Stripe account, and the application fee lands in\n the platform Stripe account — held by the operating entity, not\n by a white-label agency reselling the console. Naming the\n agency here would assert a fee relationship that does not\n exist. `PLATFORM_BRAND_LEGAL_NAME` still configures cleanly for\n a self-host operator, who really is the entity collecting it.\n */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Buyers pay on your own Stripe account; ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} collects a platform fee ` +\n 'per sale based on your plan:'}\n </Typography>\n {/* The DIGITAL rate is not products-only (AGL-2315). A paid\n booking is a service sale and resolves through the same\n `'service'`/digital axis, so a bookings-only merchant pays this\n exact number — and this card was the one place they could read\n their own rate while naming only \"products\". Stated here rather\n than adding a third figure: it is one rate, not two. */}\n <Typography variant=\"body2\">\n {`Physical products: ${physicalPct}% · Digital products, ` +\n `services & bookings: ${digitalPct}%`}\n {physicalPct > 0 || digitalPct > 0 ? (\n <Typography\n component=\"span\"\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {' — higher plans reduce fees to 0%'}\n </Typography>\n ) : null}\n </Typography>\n {/* CARD PROCESSING, PASSED THROUGH AT COST (AGL-2152).\n\n Unconditional, including on the 0% plans, because it is\n exactly those plans where the merchant would otherwise read\n \"0%\" and be surprised by a deduction. Their PLATFORM fee\n really is zero — the figure below is Stripe's own charge for\n taking the payment, which every storefront sale incurs and\n which used to be absorbed silently out of the platform's\n balance rather than passed through.\n\n Named as a range rather than one number because the buyer\n chooses the payment method after the session is created:\n cards settle at the low end, buy-now-pay-later at the high\n end, and the deduction is sized for the dearest so a sale can\n never cost more to process than it collects. */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Card processing is passed through at cost on top of that: ' +\n `${Aglyn.CARD_PROCESSING_PERCENT}–` +\n `${Aglyn.BNPL_PROCESSING_PERCENT}% + ` +\n `${Aglyn.PROCESSING_FIXED_CENTS}¢ per online ` +\n 'sale, what Stripe charges to take the payment. It is not a ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} margin.`}\n </Typography>\n {/* EVERY TENDER, AND HOW EACH IS COLLECTED (AGL-2111).\n\n Until now this card said \"per sale\" and meant it for online and\n card sales only: cash and room-charge sales at the register\n recorded no fee at all, so a merchant could read this sentence,\n ring everything as cash, and pay nothing. The fee now attaches\n to the sale on every tender, which makes the sentence above\n true — and creates a second, visible collection route the\n merchant has to be told about BEFORE it appears on their\n invoice, because it is money leaving by a door they have never\n seen it leave by.\n\n Shown only when a rate actually applies: on a 0% plan there is\n nothing to collect either way, and the paragraph would be noise\n on the card of the merchants who upgraded to escape fees. */}\n {physicalPct > 0 || digitalPct > 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The fee is charged on the sale, not on how it was paid — ' +\n 'in-person cash and room-charge sales carry it too. On card ' +\n 'sales it is deducted from your Stripe payout; on cash and ' +\n 'room-charge sales there is no payout to deduct from, so it ' +\n `is added to your monthly ${Aglyn.PLATFORM_BRAND_LEGAL_NAME} ` +\n 'invoice instead.'}\n </Typography>\n ) : null}\n </>\n )}\n {/*\n AGL-2471: connected, and refused by every money door because the\n account was never verified against this deployment's Stripe mode.\n \"Not set up\" would be a lie in the other direction — the merchant\n did set something up — so the card names what is actually wrong and\n what to do about it.\n */}\n {modeUnverified ? (\n <Alert severity=\"error\">\n {'Your Stripe account has not been verified for payments on ' +\n 'this site, so sales will be refused. Set up payments again ' +\n 'to verify it — if it was connected against Stripe test mode, ' +\n 'you will need to connect a live account.'}\n </Alert>\n ) : null}\n {/*\n The button's own label is a claim — \"Set up payments\" tells the\n owner they have none. Withheld until the answer is in, for the same\n reason as the chip (AGL-1380); on error the Retry above is the only\n action offered, because acting on a setup we could not read is how\n a connected merchant gets sent back through onboarding.\n */}\n {/*\n WHERE THE MONEY STOPPED. Mirrored onto this profile by the\n `payout.failed` handler and retired by the next successful payout, so\n it names a live problem rather than a scar. Without it a merchant sold\n into an account that could not release the funds and the card said\n \"Payments are enabled\" the whole time — the storefront looked healthy\n from every angle available to them.\n */}\n {stripeState === 'loaded' && profile?.lastPayoutFailureAtMs ? (\n <Alert severity=\"warning\" variant=\"outlined\">\n {`A payout of $${(\n Number(profile.lastPayoutFailureCents ?? 0) / 100\n ).toFixed(2)} did not reach your bank on ${new Date(\n Number(profile.lastPayoutFailureAtMs),\n ).toLocaleDateString()} — ${String(\n profile.lastPayoutFailureReason ?? 'Stripe did not say why',\n )} The money is still in your Stripe account. Open Stripe to fix your payout details.`}\n </Alert>\n ) : null}\n {!planReady || stripeState !== 'loaded' ? null : isOwner ? (\n <>\n <Button\n size=\"small\"\n variant={chargesEnabled ? 'text' : 'contained'}\n color=\"primary\"\n disabled={busy}\n onClick={handleConnect}\n sx={{ alignSelf: 'flex-start' }}\n >\n {chargesEnabled\n ? 'Refresh status'\n : busy\n ? 'Opening Stripe…'\n : 'Set up payments'}\n </Button>\n {/*\n Where the money actually is. Aglyn records none of it —\n no balance, no payout schedule, and no `payout.failed` handling\n anywhere — so a merchant whose payout bounced has no way to learn\n that from this console. An Express account has no direct login\n either, which leaves a link minted by the platform as the only\n route in. `target=\"_blank\"` because it leaves the app entirely.\n */}\n {dashboardUrl ? (\n <Button\n size=\"small\"\n variant=\"text\"\n color=\"primary\"\n href={dashboardUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n sx={{ alignSelf: 'flex-start' }}\n >\n {'View payouts in Stripe'}\n </Button>\n ) : null}\n </>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Only the organization owner can set up payments.'}\n </Typography>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nPaymentsSettingsCard.displayName = 'PaymentsSettingsCard'\n\nexport default PaymentsSettingsCard\n"],"names":["trackEvent","Aglyn","CardDisplay","useSnackbar","Alert","Button","Chip","Stack","Typography","doc","useCallback","useState","useFirestore","useUser","useFirestoreDoc","useOrgPlan","pluginDocsHelp","authorizedFetch","PaymentsSettingsCard","props","profile","hostId","firestore","data","user","enqueueSnackbar","busy","setBusy","dashboardUrl","setDashboardUrl","org","ready","planReady","retryNonce","setRetryNonce","uid","status","profileStatus","isOwner","Boolean","ownerUid","stripeState","modeVerified","stripeAccountLivemode","chargesConnected","stripeChargesEnabled","modeUnverified","chargesEnabled","physicalPct","resolveTransactionFeePct","digitalPct","commerceEnabled","checkEntitlement","handleConnect","response","method","headers","body","JSON","stringify","payload","json","variant","persist","ok","error","allowDuplicate","payoutsBlocked","payoutsEnabled","url","window","location","assign","console","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","flex","size","label","color","severity","action","onClick","n","PLATFORM_BRAND_LEGAL_NAME","component","CARD_PROCESSING_PERCENT","BNPL_PROCESSING_PERCENT","PROCESSING_FIXED_CENTS","lastPayoutFailureAtMs","Number","lastPayoutFailureCents","toFixed","Date","toLocaleDateString","String","lastPay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