@aglyn/plugins-commerce 1.0.0-beta.199 → 1.0.0-beta.201
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.
- package/package.json +13 -13
- package/src/lib/components/console/catalog-organization-card.component.js +48 -3
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/gift-cards-card.component.d.ts +9 -0
- package/src/lib/components/console/gift-cards-card.component.js +53 -28
- package/src/lib/components/console/gift-cards-card.component.js.map +1 -1
- package/src/lib/components/console/host-orders-card.component.d.ts +26 -0
- package/src/lib/components/console/host-orders-card.component.js +264 -194
- package/src/lib/components/console/host-orders-card.component.js.map +1 -1
- package/src/lib/components/console/order-detail-dialog.component.js +12 -0
- package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/pos-page.component.d.ts +14 -0
- package/src/lib/components/console/pos-page.component.js +86 -45
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +30 -6
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/product-slugs.d.ts +43 -0
- package/src/lib/components/console/product-slugs.js +60 -0
- package/src/lib/components/console/product-slugs.js.map +1 -0
- package/src/lib/components/console/products-hub-card.component.d.ts +2 -2
- package/src/lib/components/console/products-hub-card.component.js +229 -282
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/products-hub-zone.component.d.ts +10 -5
- package/src/lib/components/console/products-hub-zone.component.js +32 -9
- package/src/lib/components/console/products-hub-zone.component.js.map +1 -1
- package/src/lib/components/console/recovery-queue-card.component.d.ts +37 -5
- package/src/lib/components/console/recovery-queue-card.component.js +107 -86
- package/src/lib/components/console/recovery-queue-card.component.js.map +1 -1
- package/src/lib/components/console/reservations-card.component.js +15 -3
- package/src/lib/components/console/reservations-card.component.js.map +1 -1
- package/src/lib/components/console/smart-collections.d.ts +32 -0
- package/src/lib/components/console/smart-collections.js +57 -0
- package/src/lib/components/console/smart-collections.js.map +1 -0
- package/src/lib/components/console/stock-movements-card.component.d.ts +13 -4
- package/src/lib/components/console/stock-movements-card.component.js +142 -180
- package/src/lib/components/console/stock-movements-card.component.js.map +1 -1
- package/src/lib/components/product-grid.d.ts +5 -0
- package/src/lib/components/product-grid.js +95 -34
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/constants/orders-list-query.d.ts +40 -0
- package/src/lib/constants/orders-list-query.js +205 -0
- package/src/lib/constants/orders-list-query.js.map +1 -0
- package/src/lib/constants/product-list-query.d.ts +42 -0
- package/src/lib/constants/product-list-query.js +217 -0
- package/src/lib/constants/product-list-query.js.map +1 -0
- package/src/lib/constants/stock-movement-query.d.ts +27 -0
- package/src/lib/constants/stock-movement-query.js +110 -0
- package/src/lib/constants/stock-movement-query.js.map +1 -0
- package/src/lib/constants/storefront-catalog-query.d.ts +103 -0
- package/src/lib/constants/storefront-catalog-query.js +312 -0
- package/src/lib/constants/storefront-catalog-query.js.map +1 -0
- package/src/lib/model/checkout-recovery.d.ts +37 -0
- package/src/lib/model/checkout-recovery.js +44 -0
- package/src/lib/model/checkout-recovery.js.map +1 -0
- package/src/lib/model/commerce-orders.d.ts +7 -0
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce.d.ts +80 -0
- package/src/lib/model/commerce.js +67 -6
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/gift-card-search.d.ts +24 -0
- package/src/lib/model/gift-card-search.js +48 -0
- package/src/lib/model/gift-card-search.js.map +1 -0
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/order-list-fields.d.ts +80 -0
- package/src/lib/model/order-list-fields.js +112 -0
- package/src/lib/model/order-list-fields.js.map +1 -0
- package/src/lib/server/billing-webhook.js +180 -99
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +6 -6
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/cart-checkout.js +9 -2
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/catalog.d.ts +46 -30
- package/src/lib/server/catalog.js +507 -170
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout.js +3 -1
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/collection-membership.d.ts +35 -0
- package/src/lib/server/collection-membership.js +172 -0
- package/src/lib/server/collection-membership.js.map +1 -0
- package/src/lib/server/draft-order.js +5 -3
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/gift-cards.js +7 -1
- package/src/lib/server/gift-cards.js.map +1 -1
- package/src/lib/server/member-name-search.d.ts +17 -0
- package/src/lib/server/member-name-search.js +23 -1
- package/src/lib/server/member-name-search.js.map +1 -1
- package/src/lib/server/membership-account.js +7 -3
- package/src/lib/server/membership-account.js.map +1 -1
- package/src/lib/server/membership-admin-password.js +8 -2
- package/src/lib/server/membership-admin-password.js.map +1 -1
- package/src/lib/server/membership-recover.js +4 -1
- package/src/lib/server/membership-recover.js.map +1 -1
- package/src/lib/server/membership-register.js +3 -1
- package/src/lib/server/membership-register.js.map +1 -1
- package/src/lib/server/pos-order.js +9 -5
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/process-abandoned.js +20 -7
- package/src/lib/server/process-abandoned.js.map +1 -1
- package/src/lib/server/process-restock.js +6 -2
- package/src/lib/server/process-restock.js.map +1 -1
- package/src/lib/server/reserve-stock.js +3 -4
- package/src/lib/server/reserve-stock.js.map +1 -1
- package/src/lib/server/reserve.js +3 -1
- package/src/lib/server/reserve.js.map +1 -1
- package/src/lib/server/site-page-enricher.js +3 -3
- package/src/lib/server/site-page-enricher.js.map +1 -1
- package/src/lib/server.js +4 -0
- package/src/lib/server.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-commerce",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.201",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,18 +25,18 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.0.0-beta.
|
|
29
|
-
"@aglyn/shared-data-mdi": "1.0.0-beta.
|
|
30
|
-
"@aglyn/shared-ui-jsx": "1.0.0-beta.
|
|
31
|
-
"@aglyn/shared-ui-next": "1.0.0-beta.
|
|
32
|
-
"@aglyn/shared-ui-snackstack": "1.0.0-beta.
|
|
33
|
-
"@aglyn/shared-util-email": "1.0.0-beta.
|
|
34
|
-
"@aglyn/shared-util-http": "1.0.0-beta.
|
|
35
|
-
"@aglyn/shared-util-timestamp": "1.0.0-beta.
|
|
36
|
-
"@aglyn/shared-util-tools": "1.0.0-beta.
|
|
37
|
-
"@aglyn/tenant-data-admin": "1.0.0-beta.
|
|
38
|
-
"@aglyn/tenant-feature-instance": "1.0.0-beta.
|
|
39
|
-
"@aglyn/tenant-runtime": "1.0.0-beta.
|
|
28
|
+
"@aglyn/aglyn": "1.0.0-beta.201",
|
|
29
|
+
"@aglyn/shared-data-mdi": "1.0.0-beta.201",
|
|
30
|
+
"@aglyn/shared-ui-jsx": "1.0.0-beta.201",
|
|
31
|
+
"@aglyn/shared-ui-next": "1.0.0-beta.201",
|
|
32
|
+
"@aglyn/shared-ui-snackstack": "1.0.0-beta.201",
|
|
33
|
+
"@aglyn/shared-util-email": "1.0.0-beta.201",
|
|
34
|
+
"@aglyn/shared-util-http": "1.0.0-beta.201",
|
|
35
|
+
"@aglyn/shared-util-timestamp": "1.0.0-beta.201",
|
|
36
|
+
"@aglyn/shared-util-tools": "1.0.0-beta.201",
|
|
37
|
+
"@aglyn/tenant-data-admin": "1.0.0-beta.201",
|
|
38
|
+
"@aglyn/tenant-feature-instance": "1.0.0-beta.201",
|
|
39
|
+
"@aglyn/tenant-runtime": "1.0.0-beta.201",
|
|
40
40
|
"@stripe/react-stripe-js": "^3.10.0",
|
|
41
41
|
"@stripe/stripe-js": "^5.10.0",
|
|
42
42
|
"@swc/helpers": "0.5.23",
|
|
@@ -431,6 +431,44 @@ const RULE_OPS = [
|
|
|
431
431
|
collectionDraft,
|
|
432
432
|
products
|
|
433
433
|
]);
|
|
434
|
+
/**
|
|
435
|
+
* Which products a smart collection holds is stored on the products
|
|
436
|
+
* (`collectionIds`, AGL-3321), so a save or a delete re-stamps them —
|
|
437
|
+
* bounded passes through the commerce route until it says it is done.
|
|
438
|
+
* A failure is reported, not thrown: the collection itself saved.
|
|
439
|
+
*/ const restampMembership = useCallback(async (collectionId)=>{
|
|
440
|
+
try {
|
|
441
|
+
let after;
|
|
442
|
+
for(let pass = 0; pass < 100; pass += 1){
|
|
443
|
+
var _ref;
|
|
444
|
+
const response = await authorizedFetch(user, '/api/commerce/collection-membership', {
|
|
445
|
+
method: 'POST',
|
|
446
|
+
headers: {
|
|
447
|
+
'Content-Type': 'application/json'
|
|
448
|
+
},
|
|
449
|
+
body: JSON.stringify(_extends({
|
|
450
|
+
hostId,
|
|
451
|
+
collectionId
|
|
452
|
+
}, after ? {
|
|
453
|
+
after
|
|
454
|
+
} : {}))
|
|
455
|
+
});
|
|
456
|
+
const result = await response.json().catch(()=>({}));
|
|
457
|
+
if (!response.ok) throw new Error((_ref = result == null ? void 0 : result.error) != null ? _ref : 'Membership update failed');
|
|
458
|
+
if (result.done || !result.after) return;
|
|
459
|
+
after = result.after;
|
|
460
|
+
}
|
|
461
|
+
} catch (error) {
|
|
462
|
+
var _ref1;
|
|
463
|
+
enqueueSnackbar(`${(_ref1 = error == null ? void 0 : error.message) != null ? _ref1 : 'Membership update failed'} — the storefront may list this collection's old products until it is saved again.`, {
|
|
464
|
+
variant: 'warning'
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
}, [
|
|
468
|
+
user,
|
|
469
|
+
hostId,
|
|
470
|
+
enqueueSnackbar
|
|
471
|
+
]);
|
|
434
472
|
const handleCollectionSave = useCallback(async ()=>{
|
|
435
473
|
if (!(collectionDraft == null ? void 0 : collectionDraft.name.trim()) || collectionError) return;
|
|
436
474
|
const { id: draftId } = collectionDraft, data = _object_without_properties_loose(collectionDraft, [
|
|
@@ -458,12 +496,14 @@ const RULE_OPS = [
|
|
|
458
496
|
* The guard WRAPS the request — an early return is a shape you can keep
|
|
459
497
|
* while losing the protection.
|
|
460
498
|
*/ let verdict;
|
|
499
|
+
let savedId = '';
|
|
461
500
|
try {
|
|
462
501
|
verdict = await writeGuardedBySeed({
|
|
463
502
|
subject: 'collection',
|
|
464
503
|
unreadable: Boolean(draftId) && collectionsStatus === 'error',
|
|
465
504
|
fromCache: Boolean(draftId) && collectionsFromCache
|
|
466
505
|
}, async ()=>{
|
|
506
|
+
var _ref;
|
|
467
507
|
const response = await authorizedFetch(user, '/api/hosts/collections', {
|
|
468
508
|
method: 'POST',
|
|
469
509
|
headers: {
|
|
@@ -484,9 +524,10 @@ const RULE_OPS = [
|
|
|
484
524
|
});
|
|
485
525
|
const result = await response.json().catch(()=>({}));
|
|
486
526
|
if (!response.ok) {
|
|
487
|
-
var
|
|
488
|
-
throw new Error((
|
|
527
|
+
var _ref1;
|
|
528
|
+
throw new Error((_ref1 = result == null ? void 0 : result.error) != null ? _ref1 : 'Collection save failed');
|
|
489
529
|
}
|
|
530
|
+
savedId = String((_ref = draftId != null ? draftId : result == null ? void 0 : result.id) != null ? _ref : '');
|
|
490
531
|
});
|
|
491
532
|
} catch (error) {
|
|
492
533
|
var _ref;
|
|
@@ -507,7 +548,9 @@ const RULE_OPS = [
|
|
|
507
548
|
variant: 'success',
|
|
508
549
|
persist: false
|
|
509
550
|
});
|
|
551
|
+
if (savedId) await restampMembership(savedId);
|
|
510
552
|
}, [
|
|
553
|
+
restampMembership,
|
|
511
554
|
collectionDraft,
|
|
512
555
|
collectionError,
|
|
513
556
|
draftSlug,
|
|
@@ -571,11 +614,13 @@ const RULE_OPS = [
|
|
|
571
614
|
variant: 'success',
|
|
572
615
|
persist: false
|
|
573
616
|
});
|
|
617
|
+
await restampMembership(row.$id);
|
|
574
618
|
}, [
|
|
575
619
|
confirm,
|
|
576
620
|
user,
|
|
577
621
|
hostId,
|
|
578
|
-
enqueueSnackbar
|
|
622
|
+
enqueueSnackbar,
|
|
623
|
+
restampMembership
|
|
579
624
|
]);
|
|
580
625
|
/**
|
|
581
626
|
* How many products a collection holds — over the CATALOG WINDOW.
|
|
@@ -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 { 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\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 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 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 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 },\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 }, [\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 'screen uses it as a list or entry template — empty it and detach ' +\n 'those screens 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 },\n [confirm, user, hostId, enqueueSnackbar],\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 <Autocomplete\n multiple\n options={products}\n getOptionLabel={(product) => product.name}\n isOptionEqualToValue={(option, value) => option.$id === value.$id}\n value={products.filter((product) =>\n (collectionDraft.productIds ?? []).includes(product.$id),\n )}\n onChange={(_event, picked) =>\n setCollectionDraft((prev) =>\n prev\n ? { ...prev, productIds: picked.map((item) => item.$id) }\n : prev,\n )\n }\n renderInput={(params) => (\n <TextField {...params} label=\"Products\" size=\"small\" />\n )}\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","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","CatalogOrganizationCard","props","hostId","firestore","enqueueSnackbar","confirm","data","user","categoryDocs","status","categoriesStatus","fromCache","categoriesFromCache","idField","rows","readCategories","truncated","categoriesTruncated","collectionDocs","collectionsStatus","collectionsFromCache","readCollections","collectionsTruncated","productDocs","readProducts","productsTruncated","products","filter","product","deletedAt","map","liftLegacyProduct","$id","commerceCollections","isHostCollectionKind","categories","sort","a","b","order","name","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","previewMatches","candidate","matchesCollection","handleCollectionSave","draftId","response","method","headers","body","JSON","stringify","action","kind","result","json","Error","error","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","size","onClick","page","pageSize","rowCount","count","onPageChange","onPageSizeChange","severity","alignSelf","my","mode","productIds","matchAll","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","onChange","event","prev","target","autoFocus","mt","select","repeat","disabled","helperText","undefined","multiple","options","getOptionLabel","isOptionEqualToValue","option","includes","_event","picked","renderInput","params","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,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,SAAS,EAAEC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;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WAAU;gCAAMD,SAAS;gCAAKE,IAAI;oCAAEqD,UAAU;gCAAO;;kDAC1D,KAAC5N;wCAAW8G,SAAQ;wCAAUS,OAAM;kDACjC,CAAC,QAAQ,EAAEiC,cAAcvB,eAAesB,MAAM,CAAC,WAAW,CAAC;;oCAE7DtB,eAAe5C,KAAK,CAAC,GAAG,GAAG9B,GAAG,CAAC,CAACF,wBAC/B,KAAC/D;4CAAuBiC,OAAO8B,QAAQY,IAAI;4CAAE4G,MAAK;2CAAvCxH,QAAQI,GAAG;oCAEvBwE,eAAesB,MAAM,GAAG,kBACvB,KAACvJ;wCAAW8G,SAAQ;wCAAUS,OAAM;kDACjC,CAAC,CAAC,EAAEU,eAAesB,MAAM,GAAG,EAAE,KAAK,CAAC;yCAErC;;iCAEJ;;;kCAEN,MAAC/J;;0CACC,KAACH;gCAAOyL,SAAS,IAAMhF,mBAAmB;0CAAQ;;0CAClD,KAACzG;gCACCyH,SAAQ;gCACRS,OAAM;gCACNmF,UAAU,EAAC7G,mCAAAA,gBAAiB5B,IAAI,CAAC+B,IAAI,OAAMM,QAAQyB;gCACnD+C,SAAS1C;0CAER;;;;;;;;AAMb;AACA3G,wBAAwBoM,WAAW,GAAG;AAEtC,eAAepM,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 { 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\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 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 'screen uses it as a list or entry template — empty it and detach ' +\n 'those screens 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 <Autocomplete\n multiple\n options={products}\n getOptionLabel={(product) => product.name}\n isOptionEqualToValue={(option, value) => option.$id === value.$id}\n value={products.filter((product) =>\n (collectionDraft.productIds ?? []).includes(product.$id),\n )}\n onChange={(_event, picked) =>\n setCollectionDraft((prev) =>\n prev\n ? { ...prev, productIds: picked.map((item) => item.$id) }\n : prev,\n )\n }\n renderInput={(params) => (\n <TextField {...params} label=\"Products\" size=\"small\" />\n )}\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","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","CatalogOrganizationCard","props","hostId","firestore","enqueueSnackbar","confirm","data","user","categoryDocs","status","categoriesStatus","fromCache","categoriesFromCache","idField","rows","readCategories","truncated","categoriesTruncated","collectionDocs","collectionsStatus","collectionsFromCache","readCollections","collectionsTruncated","productDocs","readProducts","productsTruncated","products","filter","product","deletedAt","map","liftLegacyProduct","$id","commerceCollections","isHostCollectionKind","categories","sort","a","b","order","name","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","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","size","onClick","page","pageSize","rowCount","count","onPageChange","onPageSizeChange","severity","alignSelf","my","mode","productIds","matchAll","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","onChange","event","prev","target","autoFocus","mt","select","repeat","disabled","helperText","undefined","multiple","options","getOptionLabel","isOptionEqualToValue","option","includes","_event","picked","renderInput","params","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,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,SAAS,EAAEC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AACvE,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SACEC,eAAe,EACfC,iBAAiB,EACjBC,sBA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AM,GAAG,kBACvB,KAAC9J;wCAAW8G,SAAQ;wCAAUS,OAAM;kDACjC,CAAC,CAAC,EAAEU,eAAe6B,MAAM,GAAG,EAAE,KAAK,CAAC;yCAErC;;iCAEJ;;;kCAEN,MAACtK;;0CACC,KAACH;gCAAOgM,SAAS,IAAMvF,mBAAmB;0CAAQ;;0CAClD,KAACzG;gCACCyH,SAAQ;gCACRS,OAAM;gCACN0F,UAAU,EAACpH,mCAAAA,gBAAiB5B,IAAI,CAAC+B,IAAI,OAAMM,QAAQyB;gCACnDsD,SAASlC;0CAER;;;;;;;;AAMb;AACA1H,wBAAwB2M,WAAW,GAAG;AAEtC,eAAe3M,wBAAuB"}
|
|
@@ -1,6 +1,15 @@
|
|
|
1
|
+
import type { ListQueryDeclaration } from '@aglyn/shared-ui-jsx/const/list-query-plan';
|
|
1
2
|
export interface GiftCardsCardProps {
|
|
2
3
|
hostId: string;
|
|
3
4
|
}
|
|
5
|
+
/**
|
|
6
|
+
* The card list's one query (AGL-3321): newest first, and the search an
|
|
7
|
+
* `array-contains` on the tokens every card writer stamps from its code and
|
|
8
|
+
* its recipient's address (`giftCardSearchTokens`), so a card on page forty
|
|
9
|
+
* is found exactly as one on page one is. One composite:
|
|
10
|
+
* `(searchTokens CONTAINS, createdAtMs DESC)`.
|
|
11
|
+
*/
|
|
12
|
+
export declare const GIFT_CARD_LIST_QUERY: ListQueryDeclaration;
|
|
4
13
|
/**
|
|
5
14
|
* Gift cards & store credit (AGL-2226).
|
|
6
15
|
*
|
|
@@ -18,15 +18,36 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
18
18
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
19
19
|
import { CardDisplay, useConfirmationContext } from "@aglyn/shared-ui-jsx";
|
|
20
20
|
import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.component";
|
|
21
|
+
import { ListQueryNotices, listQueryRefusals } from "@aglyn/shared-ui-jsx/components/list-query-notices.component";
|
|
21
22
|
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
22
23
|
import { Button, Chip, Stack, TextField, Typography } from "@mui/material";
|
|
23
|
-
import { collection, count, getAggregateFromServer,
|
|
24
|
-
import { useCallback, useEffect,
|
|
25
|
-
import { useFirestore,
|
|
24
|
+
import { collection, count, getAggregateFromServer, query, sum, where } from "firebase/firestore";
|
|
25
|
+
import { useCallback, useEffect, useState } from "react";
|
|
26
|
+
import { useFirestore, useUser } from "@aglyn/tenant-feature-instance";
|
|
27
|
+
import { useListQuery } from "@aglyn/tenant-feature-instance/hooks/use-list-query";
|
|
26
28
|
import { pluginDocsHelp } from "@aglyn/aglyn";
|
|
27
29
|
import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
|
|
30
|
+
import { GIFT_CARD_SEARCH_TOKENS_PATH } from "../../model/gift-card-search.js";
|
|
28
31
|
import { EntitlementGatedCard } from "./entitlement-gate.component.js";
|
|
29
32
|
const usd = (cents)=>`$${((cents != null ? cents : 0) / 100).toFixed(2)}`;
|
|
33
|
+
/**
|
|
34
|
+
* The card list's one query (AGL-3321): newest first, and the search an
|
|
35
|
+
* `array-contains` on the tokens every card writer stamps from its code and
|
|
36
|
+
* its recipient's address (`giftCardSearchTokens`), so a card on page forty
|
|
37
|
+
* is found exactly as one on page one is. One composite:
|
|
38
|
+
* `(searchTokens CONTAINS, createdAtMs DESC)`.
|
|
39
|
+
*/ export const GIFT_CARD_LIST_QUERY = {
|
|
40
|
+
fields: [],
|
|
41
|
+
sorts: [
|
|
42
|
+
{
|
|
43
|
+
path: 'createdAtMs',
|
|
44
|
+
direction: 'desc'
|
|
45
|
+
}
|
|
46
|
+
],
|
|
47
|
+
search: {
|
|
48
|
+
tokensPath: GIFT_CARD_SEARCH_TOKENS_PATH
|
|
49
|
+
}
|
|
50
|
+
};
|
|
30
51
|
const giftCardsHelp = pluginDocsHelp('commerce', {
|
|
31
52
|
anchor: '#gift-cards',
|
|
32
53
|
title: 'Gift cards',
|
|
@@ -58,34 +79,29 @@ const giftCardsHelp = pluginDocsHelp('commerce', {
|
|
|
58
79
|
const { data: user } = useUser();
|
|
59
80
|
const { enqueueSnackbar } = useSnackbar();
|
|
60
81
|
const { confirm } = useConfirmationContext();
|
|
82
|
+
const [search, setSearch] = useState('');
|
|
61
83
|
/*
|
|
62
|
-
* Ordered by the server
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
84
|
+
* Ordered by the server and paged by it, and the search is the QUERY's
|
|
85
|
+
* (AGL-3321): it used to match the code and the address over the page in
|
|
86
|
+
* front of the merchant, and said so.
|
|
87
|
+
*/ const { rows: cards, hasMore, page, setPage, pageSize, setPageSize, plan } = useListQuery({
|
|
88
|
+
collection: collection(firestore, 'hosts', hostId, 'giftCards'),
|
|
89
|
+
declaration: GIFT_CARD_LIST_QUERY,
|
|
90
|
+
request: {
|
|
91
|
+
clauses: [],
|
|
92
|
+
search: search.trim() ? [
|
|
93
|
+
search.trim()
|
|
94
|
+
] : []
|
|
95
|
+
},
|
|
96
|
+
deps: [
|
|
97
|
+
firestore,
|
|
98
|
+
hostId
|
|
99
|
+
],
|
|
72
100
|
idField: '$id'
|
|
73
101
|
});
|
|
74
|
-
const [search, setSearch] = useState('');
|
|
75
102
|
const [amount, setAmount] = useState('');
|
|
76
103
|
const [recipient, setRecipient] = useState('');
|
|
77
104
|
const [busy, setBusy] = useState(false);
|
|
78
|
-
const cards = useMemo(()=>{
|
|
79
|
-
const term = search.trim().toUpperCase();
|
|
80
|
-
if (!term) return allCards;
|
|
81
|
-
return allCards.filter((card)=>{
|
|
82
|
-
var _card_recipientEmail;
|
|
83
|
-
return card.$id.includes(term) || String((_card_recipientEmail = card.recipientEmail) != null ? _card_recipientEmail : '').toUpperCase().includes(term);
|
|
84
|
-
});
|
|
85
|
-
}, [
|
|
86
|
-
allCards,
|
|
87
|
-
search
|
|
88
|
-
]);
|
|
89
105
|
/*==========================================
|
|
90
106
|
* OUTSTANDING LIABILITY IS A SERVER AGGREGATE, not a page total.
|
|
91
107
|
*
|
|
@@ -298,14 +314,23 @@ const giftCardsHelp = pluginDocsHelp('commerce', {
|
|
|
298
314
|
]
|
|
299
315
|
}),
|
|
300
316
|
/*#__PURE__*/ _jsx(TextField, {
|
|
301
|
-
label: "
|
|
317
|
+
label: "Search by code or email",
|
|
302
318
|
value: search,
|
|
303
|
-
onChange: (event)=>
|
|
319
|
+
onChange: (event)=>{
|
|
320
|
+
setSearch(event.target.value);
|
|
321
|
+
setPage(0);
|
|
322
|
+
},
|
|
304
323
|
size: "small",
|
|
305
324
|
sx: {
|
|
306
325
|
maxWidth: 320
|
|
307
326
|
}
|
|
308
327
|
}),
|
|
328
|
+
/*#__PURE__*/ _jsx(ListQueryNotices, {
|
|
329
|
+
refused: listQueryRefusals(plan.refused, {
|
|
330
|
+
fields: GIFT_CARD_LIST_QUERY.fields
|
|
331
|
+
}),
|
|
332
|
+
notices: plan.notices
|
|
333
|
+
}),
|
|
309
334
|
cards.length ? /*#__PURE__*/ _jsx(Stack, {
|
|
310
335
|
spacing: 1,
|
|
311
336
|
children: cards.map((card)=>{
|
|
@@ -358,7 +383,7 @@ const giftCardsHelp = pluginDocsHelp('commerce', {
|
|
|
358
383
|
}) : /*#__PURE__*/ _jsx(Typography, {
|
|
359
384
|
variant: "body2",
|
|
360
385
|
color: "text.secondary",
|
|
361
|
-
children: search ? 'No gift card
|
|
386
|
+
children: search.trim() ? 'No gift card matches that code or email.' : 'No gift cards yet. Sell a gift-card product, or issue one above.'
|
|
362
387
|
}),
|
|
363
388
|
/*#__PURE__*/ _jsx(ListPagination, {
|
|
364
389
|
page: page,
|