@aglyn/plugins-commerce 1.30.0 → 1.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/cart.js +11 -5
  3. package/src/lib/components/cart.js.map +1 -1
  4. package/src/lib/components/console/product-editor-dialog.component.js +5 -0
  5. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  6. package/src/lib/components/console/product-traffic-card.component.d.ts +24 -0
  7. package/src/lib/components/console/product-traffic-card.component.js +172 -0
  8. package/src/lib/components/console/product-traffic-card.component.js.map +1 -0
  9. package/src/lib/components/console/products-hub-card.component.js +181 -59
  10. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  11. package/src/lib/components/console/shipping-settings-card.component.js +31 -9
  12. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  13. package/src/lib/model/commerce-record-routes.js +31 -0
  14. package/src/lib/model/commerce-record-routes.js.map +1 -1
  15. package/src/lib/model/commerce-shipping.d.ts +39 -16
  16. package/src/lib/model/commerce-shipping.js +315 -30
  17. package/src/lib/model/commerce-shipping.js.map +1 -1
  18. package/src/lib/model/product-write.d.ts +10 -1
  19. package/src/lib/model/product-write.js +13 -2
  20. package/src/lib/model/product-write.js.map +1 -1
  21. package/src/lib/server/carrier-shipping.js +3 -2
  22. package/src/lib/server/carrier-shipping.js.map +1 -1
  23. package/src/lib/server/cart-checkout.js +10 -4
  24. package/src/lib/server/cart-checkout.js.map +1 -1
  25. package/src/lib/server/cart.js +2 -2
  26. package/src/lib/server/cart.js.map +1 -1
  27. package/src/lib/server/checkout.js +6 -4
  28. package/src/lib/server/checkout.js.map +1 -1
  29. package/src/lib/server/draft-order.js +3 -3
  30. package/src/lib/server/draft-order.js.map +1 -1
  31. package/src/lib/server/products-write.js +10 -2
  32. package/src/lib/server/products-write.js.map +1 -1
@@ -0,0 +1,24 @@
1
+ /** The last `days` UTC day ids, oldest first — the ids the beacon writes under. */
2
+ export declare function productTrafficDayIds(now: number, days?: number): string[];
3
+ /**
4
+ * One product's page views, day by day (AGL-4253) — the product's own row of
5
+ * the site's Pages table, where a merchant edits it.
6
+ *
7
+ * Read from `hosts/{hostId}/analytics/{day}.paths['/products/{slug}']`, never
8
+ * from the product template screen's counts: every product renders through
9
+ * that ONE screen, so its counts are the whole catalog's (the AGL-2498
10
+ * lesson). Devices and referrers are counted for the site, not per page, so
11
+ * this card does not show them.
12
+ *
13
+ * Paid like the Pages table (`screenAnalytics`, Pro+); a plan without it sees
14
+ * nothing here — the Pages table is where the upgrade is offered.
15
+ */
16
+ export declare function ProductTrafficCard(props: {
17
+ hostId: string;
18
+ /** The product's STORED slug; a retyped, unsaved one names no page yet. */
19
+ slug: string | null | undefined;
20
+ }): import("react").JSX.Element;
21
+ export declare namespace ProductTrafficCard {
22
+ var displayName: string;
23
+ }
24
+ export default ProductTrafficCard;
@@ -0,0 +1,172 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ 'use client';
17
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
18
+ import { analyticsPathKey, checkEntitlement } from "@aglyn/aglyn";
19
+ import { Box, LinearProgress, Stack, Tooltip, Typography } from "@mui/material";
20
+ import { doc, getDoc } from "firebase/firestore";
21
+ import { useEffect, useState } from "react";
22
+ import { useFirestore, useOrgPlan } from "@aglyn/tenant-feature-instance";
23
+ const DAYS = 14;
24
+ const DAY_MS = 24 * 60 * 60 * 1000;
25
+ /** The last `days` UTC day ids, oldest first — the ids the beacon writes under. */ export function productTrafficDayIds(now, days = DAYS) {
26
+ const ids = [];
27
+ for(let back = days - 1; back >= 0; back -= 1){
28
+ ids.push(new Date(now - back * DAY_MS).toISOString().slice(0, 10));
29
+ }
30
+ return ids;
31
+ }
32
+ /**
33
+ * Module cache of closed days' counts for one path (the live day is re-read
34
+ * after a minute): reopening a product's editor does not re-read fourteen
35
+ * day documents.
36
+ */ const dayCache = new Map();
37
+ const LIVE_TTL_MS = 60000;
38
+ /**
39
+ * One product's page views, day by day (AGL-4253) — the product's own row of
40
+ * the site's Pages table, where a merchant edits it.
41
+ *
42
+ * Read from `hosts/{hostId}/analytics/{day}.paths['/products/{slug}']`, never
43
+ * from the product template screen's counts: every product renders through
44
+ * that ONE screen, so its counts are the whole catalog's (the AGL-2498
45
+ * lesson). Devices and referrers are counted for the site, not per page, so
46
+ * this card does not show them.
47
+ *
48
+ * Paid like the Pages table (`screenAnalytics`, Pro+); a plan without it sees
49
+ * nothing here — the Pages table is where the upgrade is offered.
50
+ */ export function ProductTrafficCard(props) {
51
+ const { hostId, slug } = props;
52
+ const firestore = useFirestore();
53
+ const { org, ready } = useOrgPlan(hostId);
54
+ const entitled = ready && checkEntitlement(org, 'screenAnalytics');
55
+ const [days, setDays] = useState(null);
56
+ const path = slug ? `/products/${slug}` : null;
57
+ useEffect(()=>{
58
+ if (!entitled || !path) return;
59
+ let active = true;
60
+ const now = Date.now();
61
+ const ids = productTrafficDayIds(now);
62
+ const live = ids[ids.length - 1];
63
+ const key = analyticsPathKey(path);
64
+ void Promise.all(ids.map(async (day)=>{
65
+ const cacheKey = `${hostId}|${key}|${day}`;
66
+ const hit = dayCache.get(cacheKey);
67
+ if (hit && (day !== live || now - hit.storedAt < LIVE_TTL_MS)) {
68
+ return {
69
+ day,
70
+ views: hit.views,
71
+ failed: false
72
+ };
73
+ }
74
+ try {
75
+ var _snapshot_get, _paths_key;
76
+ const snapshot = await getDoc(doc(firestore, 'hosts', hostId, 'analytics', day));
77
+ const paths = (_snapshot_get = snapshot.get('paths')) != null ? _snapshot_get : {};
78
+ const views = Number((_paths_key = paths[key]) != null ? _paths_key : 0);
79
+ dayCache.set(cacheKey, {
80
+ views,
81
+ storedAt: now
82
+ });
83
+ return {
84
+ day,
85
+ views,
86
+ failed: false
87
+ };
88
+ } catch (unused) {
89
+ return {
90
+ day,
91
+ views: 0,
92
+ failed: true
93
+ };
94
+ }
95
+ })).then((counts)=>{
96
+ if (active) setDays(counts);
97
+ });
98
+ return ()=>{
99
+ active = false;
100
+ };
101
+ }, [
102
+ entitled,
103
+ firestore,
104
+ hostId,
105
+ path
106
+ ]);
107
+ if (!entitled || !path) return null;
108
+ const total = (days != null ? days : []).reduce((sum, day)=>sum + day.views, 0);
109
+ const failed = (days != null ? days : []).filter((day)=>day.failed).length;
110
+ const max = Math.max(1, ...(days != null ? days : []).map((day)=>day.views));
111
+ return /*#__PURE__*/ _jsxs(Stack, {
112
+ spacing: 1,
113
+ "aria-label": 'Product page views',
114
+ children: [
115
+ /*#__PURE__*/ _jsxs(Stack, {
116
+ direction: "row",
117
+ spacing: 1,
118
+ sx: {
119
+ alignItems: 'baseline'
120
+ },
121
+ children: [
122
+ /*#__PURE__*/ _jsx(Typography, {
123
+ variant: "subtitle2",
124
+ children: 'Page views (14 days)'
125
+ }),
126
+ days !== null && /*#__PURE__*/ _jsx(Typography, {
127
+ variant: "subtitle2",
128
+ color: "text.secondary",
129
+ children: total.toLocaleString()
130
+ })
131
+ ]
132
+ }),
133
+ days === null ? /*#__PURE__*/ _jsx(LinearProgress, {}) : total === 0 && failed === 0 ? /*#__PURE__*/ _jsx(Typography, {
134
+ variant: "body2",
135
+ color: "text.secondary",
136
+ children: `No views of ${path} in the last 14 days.`
137
+ }) : /*#__PURE__*/ _jsx(Box, {
138
+ sx: {
139
+ display: 'flex',
140
+ alignItems: 'flex-end',
141
+ gap: 0.5,
142
+ height: 48
143
+ },
144
+ children: days.map((day)=>/*#__PURE__*/ _jsx(Tooltip, {
145
+ title: day.failed ? `${day.day} · could not be read` : `${day.day} · ${day.views} view${day.views === 1 ? '' : 's'}`,
146
+ children: /*#__PURE__*/ _jsx(Box, {
147
+ sx: {
148
+ flexGrow: 1,
149
+ height: `${Math.max(2, day.views / max * 48)}px`,
150
+ bgcolor: day.failed ? 'warning.light' : day.views > 0 ? 'primary.main' : 'divider',
151
+ borderRadius: 0.5
152
+ }
153
+ })
154
+ }, day.day))
155
+ }),
156
+ /*#__PURE__*/ _jsxs(Typography, {
157
+ variant: "caption",
158
+ color: "text.secondary",
159
+ children: [
160
+ failed > 0 ? `${failed} of the 14 days could not be read and are left out. ` : '',
161
+ 'Counted at ',
162
+ path,
163
+ '. Every product side by side is in Analytics → Pages.'
164
+ ]
165
+ })
166
+ ]
167
+ });
168
+ }
169
+ ProductTrafficCard.displayName = 'ProductTrafficCard';
170
+ export default ProductTrafficCard;
171
+
172
+ //# sourceMappingURL=product-traffic-card.component.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/product-traffic-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 { analyticsPathKey, checkEntitlement } from '@aglyn/aglyn'\nimport { Box, LinearProgress, Stack, Tooltip, Typography } from '@mui/material'\nimport { doc, getDoc } from 'firebase/firestore'\nimport { useEffect, useState } from 'react'\nimport { useFirestore, useOrgPlan } from '@aglyn/tenant-feature-instance'\n\nconst DAYS = 14\nconst DAY_MS = 24 * 60 * 60 * 1000\n\n/** The last `days` UTC day ids, oldest first — the ids the beacon writes under. */\nexport function productTrafficDayIds(now: number, days = DAYS): string[] {\n const ids: string[] = []\n for (let back = days - 1; back >= 0; back -= 1) {\n ids.push(new Date(now - back * DAY_MS).toISOString().slice(0, 10))\n }\n return ids\n}\n\ninterface DayCount {\n day: string\n views: number\n failed: boolean\n}\n\n/**\n * Module cache of closed days' counts for one path (the live day is re-read\n * after a minute): reopening a product's editor does not re-read fourteen\n * day documents.\n */\nconst dayCache = new Map<string, { views: number; storedAt: number }>()\nconst LIVE_TTL_MS = 60_000\n\n/**\n * One product's page views, day by day (AGL-4253) — the product's own row of\n * the site's Pages table, where a merchant edits it.\n *\n * Read from `hosts/{hostId}/analytics/{day}.paths['/products/{slug}']`, never\n * from the product template screen's counts: every product renders through\n * that ONE screen, so its counts are the whole catalog's (the AGL-2498\n * lesson). Devices and referrers are counted for the site, not per page, so\n * this card does not show them.\n *\n * Paid like the Pages table (`screenAnalytics`, Pro+); a plan without it sees\n * nothing here — the Pages table is where the upgrade is offered.\n */\nexport function ProductTrafficCard(props: {\n hostId: string\n /** The product's STORED slug; a retyped, unsaved one names no page yet. */\n slug: string | null | undefined\n}) {\n const { hostId, slug } = props\n const firestore = useFirestore()\n const { org, ready } = useOrgPlan(hostId)\n const entitled = ready && checkEntitlement(org as never, 'screenAnalytics')\n const [days, setDays] = useState<DayCount[] | null>(null)\n const path = slug ? `/products/${slug}` : null\n\n useEffect(() => {\n if (!entitled || !path) return\n let active = true\n const now = Date.now()\n const ids = productTrafficDayIds(now)\n const live = ids[ids.length - 1]\n const key = analyticsPathKey(path)\n void Promise.all(\n ids.map(async (day): Promise<DayCount> => {\n const cacheKey = `${hostId}|${key}|${day}`\n const hit = dayCache.get(cacheKey)\n if (hit && (day !== live || now - hit.storedAt < LIVE_TTL_MS)) {\n return { day, views: hit.views, failed: false }\n }\n try {\n const snapshot = await getDoc(doc(firestore, 'hosts', hostId, 'analytics', day))\n const paths = (snapshot.get('paths') ?? {}) as Record<string, number>\n const views = Number(paths[key] ?? 0)\n dayCache.set(cacheKey, { views, storedAt: now })\n return { day, views, failed: false }\n } catch {\n return { day, views: 0, failed: true }\n }\n }),\n ).then((counts) => {\n if (active) setDays(counts)\n })\n return () => {\n active = false\n }\n }, [entitled, firestore, hostId, path])\n\n if (!entitled || !path) return null\n\n const total = (days ?? []).reduce((sum, day) => sum + day.views, 0)\n const failed = (days ?? []).filter((day) => day.failed).length\n const max = Math.max(1, ...(days ?? []).map((day) => day.views))\n\n return (\n <Stack spacing={1} aria-label={'Product page views'}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'baseline' }}>\n <Typography variant=\"subtitle2\">{'Page views (14 days)'}</Typography>\n {days !== null && (\n <Typography variant=\"subtitle2\" color=\"text.secondary\">\n {total.toLocaleString()}\n </Typography>\n )}\n </Stack>\n {days === null ? (\n <LinearProgress />\n ) : total === 0 && failed === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`No views of ${path} in the last 14 days.`}\n </Typography>\n ) : (\n <Box sx={{ display: 'flex', alignItems: 'flex-end', gap: 0.5, height: 48 }}>\n {days.map((day) => (\n <Tooltip\n key={day.day}\n title={\n day.failed\n ? `${day.day} · could not be read`\n : `${day.day} · ${day.views} view${day.views === 1 ? '' : 's'}`\n }\n >\n <Box\n sx={{\n flexGrow: 1,\n height: `${Math.max(2, (day.views / max) * 48)}px`,\n bgcolor: day.failed ? 'warning.light' : day.views > 0 ? 'primary.main' : 'divider',\n borderRadius: 0.5,\n }}\n />\n </Tooltip>\n ))}\n </Box>\n )}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {failed > 0\n ? `${failed} of the 14 days could not be read and are left out. `\n : ''}\n {'Counted at '}\n {path}\n {'. Every product side by side is in Analytics → Pages.'}\n </Typography>\n </Stack>\n )\n}\nProductTrafficCard.displayName = 'ProductTrafficCard'\n\nexport default ProductTrafficCard\n"],"names":["analyticsPathKey","checkEntitlement","Box","LinearProgress","Stack","Tooltip","Typography","doc","getDoc","useEffect","useState","useFirestore","useOrgPlan","DAYS","DAY_MS","productTrafficDayIds","now","days","ids","back","push","Date","toISOString","slice","dayCache","Map","LIVE_TTL_MS","ProductTrafficCard","props","hostId","slug","firestore","org","ready","entitled","setDays","path","active","live","length","key","Promise","all","map","day","cacheKey","hit","get","storedAt","views","failed","snapshot","paths","Number","set","then","counts","total","reduce","sum","filter","max","Math","spacing","aria-label","direction","sx","alignItems","variant","color","toLocaleString","display","gap","height","title","flexGrow","bgcolor","borderRadius","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,gBAAgB,EAAEC,gBAAgB,QAAQ,eAAc;AACjE,SAASC,GAAG,EAAEC,cAAc,EAAEC,KAAK,EAAEC,OAAO,EAAEC,UAAU,QAAQ,gBAAe;AAC/E,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAC3C,SAASC,YAAY,EAAEC,UAAU,QAAQ,iCAAgC;AAEzE,MAAMC,OAAO;AACb,MAAMC,SAAS,KAAK,KAAK,KAAK;AAE9B,iFAAiF,GACjF,OAAO,SAASC,qBAAqBC,GAAW,EAAEC,OAAOJ,IAAI;IAC3D,MAAMK,MAAgB,EAAE;IACxB,IAAK,IAAIC,OAAOF,OAAO,GAAGE,QAAQ,GAAGA,QAAQ,EAAG;QAC9CD,IAAIE,IAAI,CAAC,IAAIC,KAAKL,MAAMG,OAAOL,QAAQQ,WAAW,GAAGC,KAAK,CAAC,GAAG;IAChE;IACA,OAAOL;AACT;AAQA;;;;CAIC,GACD,MAAMM,WAAW,IAAIC;AACrB,MAAMC,cAAc;AAEpB;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,mBAAmBC,KAIlC;IACC,MAAM,EAAEC,MAAM,EAAEC,IAAI,EAAE,GAAGF;IACzB,MAAMG,YAAYpB;IAClB,MAAM,EAAEqB,GAAG,EAAEC,KAAK,EAAE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;kCAGnE,cAAA,KAAC/C;4BACCgE,IAAI;gCACFS,UAAU;gCACVF,QAAQ,GAAGX,KAAKD,GAAG,CAAC,GAAG,AAACjB,IAAIK,KAAK,GAAGY,MAAO,IAAI,EAAE,CAAC;gCAClDe,SAAShC,IAAIM,MAAM,GAAG,kBAAkBN,IAAIK,KAAK,GAAG,IAAI,iBAAiB;gCACzE4B,cAAc;4BAChB;;uBAbGjC,IAAIA,GAAG;;0BAmBpB,MAACtC;gBAAW8D,SAAQ;gBAAUC,OAAM;;oBACjCnB,SAAS,IACN,GAAGA,OAAO,oDAAoD,CAAC,GAC/D;oBACH;oBACAd;oBACA;;;;;AAIT;AACAT,mBAAmBmD,WAAW,GAAG;AAEjC,eAAenD,mBAAkB"}
@@ -25,7 +25,10 @@ import { CardDisplay, useConfirmationContext } from "@aglyn/shared-ui-jsx";
25
25
  import ListFilterChips from "@aglyn/shared-ui-jsx/components/list-filter-chips.component";
26
26
  import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.component";
27
27
  import { ListQueryNotices, listQueryRefusals } from "@aglyn/shared-ui-jsx/components/list-query-notices.component";
28
- import { ListTable, listActionsColumn } from "@aglyn/shared-ui-jsx/components/list-table.component";
28
+ import { ListRowActions, ListTable, listActionsColumn } from "@aglyn/shared-ui-jsx/components/list-table.component";
29
+ import { MdiIcon } from "@aglyn/shared-ui-jsx/components/mdi-icon/mdi-icon";
30
+ import { mdiArchiveArrowUpOutline, mdiArchiveOutline, mdiBarcode, mdiCheckCircleOutline, mdiContentCopy, mdiDeleteOutline, mdiEyeOutline, mdiFileDocumentEditOutline, mdiKeyOutline, mdiPackageVariant, mdiPencilOutline } from "@aglyn/shared-data-mdi";
31
+ import { siteLiveUrlForSlug } from "@aglyn/aglyn/app-utils/site-live-url";
29
32
  import QuotaReadoutComponent from "@aglyn/shared-ui-jsx/components/quota-readout.component";
30
33
  import { hiddenFilterVisibility } from "@aglyn/shared-ui-jsx/const/list-filter";
31
34
  import { listFilterGridColumns } from "@aglyn/shared-ui-jsx/const/list-grid-filter";
@@ -34,7 +37,7 @@ import { useListGridFilter } from "@aglyn/shared-ui-jsx/hooks/use-list-grid-filt
34
37
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
35
38
  import { Timestamp } from "@aglyn/shared-util-timestamp";
36
39
  import { Alert, Box, Button, Chip, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Tooltip, Typography } from "@mui/material";
37
- import { addDoc, collection, doc, documentId, getDocFromServer, limit, orderBy, query, updateDoc, where } from "firebase/firestore";
40
+ import { addDoc, arrayUnion, collection, doc, documentId, getDoc, getDocFromServer, getDocs, limit, orderBy, query, updateDoc, where } from "firebase/firestore";
38
41
  import { getLiveCountFromServer } from "@aglyn/aglyn/app-utils/live-document-count.client";
39
42
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
40
43
  import { useSearchParams } from "next/navigation";
@@ -74,6 +77,20 @@ const PRODUCT_PAGE_SORT_HEADERS = {
74
77
  stock: 'Stock',
75
78
  variants: 'Variants'
76
79
  };
80
+ /** What a status change from a row's menu says when it has been written. */ const PRODUCT_STATUS_DONE = {
81
+ active: 'Product is active',
82
+ draft: 'Product set to draft',
83
+ archived: 'Product archived'
84
+ };
85
+ /**
86
+ * The address one product's editor opens at, on the Catalog this list is
87
+ * on: what a cmd-click or middle-click on a row opens in a new tab.
88
+ */ function productEditorHref(productId) {
89
+ const path = typeof window === 'undefined' ? '' : window.location.pathname;
90
+ return `${path}?${new URLSearchParams({
91
+ [PRODUCTS_PRODUCT_PARAM]: productId
92
+ }).toString()}`;
93
+ }
77
94
  const STATUS_COLOR = {
78
95
  active: 'success',
79
96
  draft: 'warning',
@@ -209,6 +226,28 @@ const STATUS_COLOR = {
209
226
  idField: '$id'
210
227
  });
211
228
  /*
229
+ * The site's address, for a row's "View on site" (its subdomain and custom
230
+ * domain). Read once: a site's address does not move under an open list.
231
+ */ const [siteAddress, setSiteAddress] = useState(null);
232
+ useEffect(()=>{
233
+ let active = true;
234
+ void Promise.resolve().then(()=>getDoc(doc(firestore, 'hosts', hostId))).then((snapshot)=>{
235
+ var _snapshot_get, _snapshot_get1;
236
+ var _snapshot_exists;
237
+ if (!active || !(snapshot == null ? void 0 : (_snapshot_exists = snapshot.exists) == null ? void 0 : _snapshot_exists.call(snapshot))) return;
238
+ setSiteAddress({
239
+ subdomain: (_snapshot_get = snapshot.get('subdomain')) != null ? _snapshot_get : null,
240
+ cname: (_snapshot_get1 = snapshot.get('cname')) != null ? _snapshot_get1 : null
241
+ });
242
+ }).catch(()=>undefined);
243
+ return ()=>{
244
+ active = false;
245
+ };
246
+ }, [
247
+ firestore,
248
+ hostId
249
+ ]);
250
+ /*
212
251
  * The PAGE on screen, lifted from legacy shapes. It is what the table
213
252
  * draws, the reserved-stock clock watches and the zone hands its widgets,
214
253
  * and nothing narrows it: the query already answered every filter, and
@@ -396,13 +435,29 @@ const STATUS_COLOR = {
396
435
  // The source's SKU and barcode keys are not copied: the copy's own
397
436
  // are derived (`productDuplicateFields`), and a copy of a product
398
437
  // with none must have none.
399
- await createHostResource({
438
+ const { id: copyId } = await createHostResource({
400
439
  hostId,
401
440
  resource: 'product',
402
441
  data: _extends({}, CommerceModel.productDuplicateFields(product, slug, Date.now()), await productCollectionFields(firestore, hostId, _extends({}, product, {
403
442
  name: CommerceModel.productDuplicateName(product.name)
404
443
  })))
405
444
  });
445
+ /*
446
+ * The MANUAL collections the source is in hold it by id in their own
447
+ * `productIds`, which nothing on the product carries, so the copy
448
+ * joins each of them here. A draft is on no storefront until it is
449
+ * made active, so this changes nothing a visitor sees.
450
+ */ try {
451
+ const manual = await getDocs(query(collection(firestore, 'hosts', hostId, 'collections'), where('productIds', 'array-contains', product.$id)));
452
+ await Promise.all(manual.docs.map((collectionDoc)=>updateDoc(collectionDoc.ref, {
453
+ productIds: arrayUnion(copyId)
454
+ })));
455
+ } catch (unused) {
456
+ enqueueSnackbar('Product duplicated, but it could not be added to the source’s collections: add it in Collections.', {
457
+ variant: 'warning',
458
+ persist: false
459
+ });
460
+ }
406
461
  // A create moves the count and the aggregate is a one-shot — the
407
462
  // listener refreshes the ROWS for free, the count has to be asked
408
463
  // again or the cap drifts stale for the rest of the session.
@@ -445,6 +500,10 @@ const STATUS_COLOR = {
445
500
  updatedAt: Timestamp.now()
446
501
  })
447
502
  });
503
+ enqueueSnackbar(PRODUCT_STATUS_DONE[status], {
504
+ variant: 'success',
505
+ persist: false
506
+ });
448
507
  }, [
449
508
  firestore,
450
509
  hostId,
@@ -625,6 +684,114 @@ const STATUS_COLOR = {
625
684
  const held = CommerceModel.heldProductUnits(product, nowMs);
626
685
  return held > 0 ? ` (${held} reserved)` : '';
627
686
  };
687
+ const icon = (path)=>/*#__PURE__*/ _jsx(MdiIcon, {
688
+ path: path,
689
+ size: 0.8
690
+ });
691
+ /**
692
+ * Every action a product row offers, in its ⋮ menu. An action that does
693
+ * not apply to this product is left out (labels are for physical goods,
694
+ * keys for digital ones, stock for tracked inventory); one that applies
695
+ * but cannot run now is shown disabled with the reason.
696
+ */ const productRowActions = (product)=>{
697
+ const items = [
698
+ {
699
+ key: 'edit',
700
+ label: 'Edit',
701
+ icon: icon(mdiPencilOutline.path),
702
+ onClick: ()=>setEditing(product)
703
+ },
704
+ {
705
+ key: 'duplicate',
706
+ label: 'Duplicate',
707
+ icon: icon(mdiContentCopy.path),
708
+ description: 'Copies it as a draft',
709
+ disabled: !productQuota,
710
+ disabledReason: productQuota ? undefined : 'Checking your plan…',
711
+ onClick: ()=>void handleDuplicate(product)()
712
+ }
713
+ ];
714
+ const liveUrl = product.slug && siteAddress ? siteLiveUrlForSlug(siteAddress, `/products/${product.slug}`) : undefined;
715
+ const offline = product.status !== 'active' ? 'Only active products are on the site' : !CommerceModel.productSellsOnline(product) ? 'Sold in person only, so it has no page on the site' : !liveUrl ? 'This site has no address yet' : undefined;
716
+ items.push({
717
+ key: 'view',
718
+ label: 'View on site',
719
+ icon: icon(mdiEyeOutline.path),
720
+ href: offline ? undefined : liveUrl,
721
+ external: true,
722
+ disabled: Boolean(offline),
723
+ disabledReason: offline
724
+ });
725
+ if (CommerceModel.productInventory(product) != null) {
726
+ items.push({
727
+ key: 'stock',
728
+ label: 'Adjust stock',
729
+ icon: icon(mdiPackageVariant.path),
730
+ onClick: ()=>{
731
+ var _ref, _ref1, _ref2;
732
+ var _product_variants_find, _find, _;
733
+ return setAdjusting({
734
+ product,
735
+ variantId: (_ref = (_product_variants_find = product.variants.find((variant)=>variant.inventory != null)) == null ? void 0 : _product_variants_find.id) != null ? _ref : product.variants[0].id,
736
+ delta: '',
737
+ reason: 'restock',
738
+ locationId: (_ref1 = (_ref2 = (_find = (locationDocs != null ? locationDocs : []).find((location)=>location.isDefault)) == null ? void 0 : _find.$id) != null ? _ref2 : (_ = (locationDocs != null ? locationDocs : [])[0]) == null ? void 0 : _.$id) != null ? _ref1 : ''
739
+ });
740
+ }
741
+ });
742
+ }
743
+ if (product.type === 'physical') {
744
+ items.push({
745
+ key: 'labels',
746
+ label: 'Print labels',
747
+ icon: icon(mdiBarcode.path),
748
+ onClick: ()=>setLabelsFor(product)
749
+ });
750
+ }
751
+ if (product.type === 'digital') {
752
+ items.push({
753
+ key: 'keys',
754
+ label: 'License keys',
755
+ icon: icon(mdiKeyOutline.path),
756
+ onClick: ()=>setKeysFor(product)
757
+ });
758
+ }
759
+ if (product.status !== 'active') {
760
+ items.push({
761
+ key: 'activate',
762
+ label: 'Set active',
763
+ icon: icon(mdiCheckCircleOutline.path),
764
+ onClick: ()=>void handleStatus(product, 'active')()
765
+ });
766
+ }
767
+ if (product.status === 'active') {
768
+ items.push({
769
+ key: 'draft',
770
+ label: 'Set to draft',
771
+ icon: icon(mdiFileDocumentEditOutline.path),
772
+ description: 'Takes it off the site',
773
+ onClick: ()=>void handleStatus(product, 'draft')()
774
+ });
775
+ }
776
+ items.push(product.status === 'archived' ? {
777
+ key: 'unarchive',
778
+ label: 'Unarchive as draft',
779
+ icon: icon(mdiArchiveArrowUpOutline.path),
780
+ onClick: ()=>void handleStatus(product, 'draft')()
781
+ } : {
782
+ key: 'archive',
783
+ label: 'Archive',
784
+ icon: icon(mdiArchiveOutline.path),
785
+ onClick: ()=>void handleStatus(product, 'archived')()
786
+ }, {
787
+ key: 'delete',
788
+ label: 'Delete',
789
+ icon: icon(mdiDeleteOutline.path),
790
+ destructive: true,
791
+ onClick: ()=>void handleDelete(product)()
792
+ });
793
+ return items;
794
+ };
628
795
  const productColumns = listFilterGridColumns([
629
796
  {
630
797
  field: 'name',
@@ -726,63 +893,14 @@ const STATUS_COLOR = {
726
893
  width: 100,
727
894
  valueGetter: (_value, row)=>row.variants.length
728
895
  },
729
- listActionsColumn((product)=>/*#__PURE__*/ _jsxs(Stack, {
730
- direction: "row",
731
- spacing: 0.5,
732
- sx: {
733
- justifyContent: 'flex-end',
734
- whiteSpace: 'nowrap'
735
- },
736
- children: [
737
- /*#__PURE__*/ _jsx(Button, {
738
- size: "small",
739
- onClick: ()=>setEditing(product),
740
- children: 'Edit'
741
- }),
742
- /*#__PURE__*/ _jsx(Button, {
743
- size: "small",
744
- onClick: handleDuplicate(product),
745
- children: 'Duplicate'
746
- }),
747
- product.type === 'physical' ? /*#__PURE__*/ _jsx(Button, {
748
- size: "small",
749
- onClick: ()=>setLabelsFor(product),
750
- children: 'Labels'
751
- }) : null,
752
- product.type === 'digital' ? /*#__PURE__*/ _jsx(Button, {
753
- size: "small",
754
- onClick: ()=>setKeysFor(product),
755
- children: 'Keys'
756
- }) : null,
757
- CommerceModel.productInventory(product) != null ? /*#__PURE__*/ _jsx(Button, {
758
- size: "small",
759
- onClick: ()=>{
760
- var _ref, _ref1, _ref2;
761
- var _product_variants_find, _find, _;
762
- return setAdjusting({
763
- product,
764
- variantId: (_ref = (_product_variants_find = product.variants.find((variant)=>variant.inventory != null)) == null ? void 0 : _product_variants_find.id) != null ? _ref : product.variants[0].id,
765
- delta: '',
766
- reason: 'restock',
767
- locationId: (_ref1 = (_ref2 = (_find = (locationDocs != null ? locationDocs : []).find((location)=>location.isDefault)) == null ? void 0 : _find.$id) != null ? _ref2 : (_ = (locationDocs != null ? locationDocs : [])[0]) == null ? void 0 : _.$id) != null ? _ref1 : ''
768
- });
769
- },
770
- children: 'Stock'
771
- }) : null,
772
- /*#__PURE__*/ _jsx(Button, {
773
- size: "small",
774
- onClick: handleStatus(product, product.status === 'archived' ? 'active' : 'archived'),
775
- children: product.status === 'archived' ? 'Activate' : 'Archive'
776
- }),
777
- /*#__PURE__*/ _jsx(Button, {
778
- size: "small",
779
- color: "error",
780
- onClick: handleDelete(product),
781
- children: 'Delete'
782
- })
783
- ]
896
+ // ONE menu per row, the same on every row (Zach, 2026-11-25): the
897
+ // inline buttons were wider than the column, so the table clipped
898
+ // them and a row showed whichever ones happened to fit.
899
+ listActionsColumn((product)=>/*#__PURE__*/ _jsx(ListRowActions, {
900
+ label: product.name,
901
+ items: productRowActions(product)
784
902
  }), {
785
- width: 470
903
+ width: 64
786
904
  })
787
905
  ], PRODUCT_LIST_FIELDS, PRODUCT_LIST_OPTIONS, PRODUCT_LIST_HEADERS);
788
906
  /** Add product: the quota first, then the create drawer. */ const startAddProduct = ()=>{
@@ -924,6 +1042,10 @@ const STATUS_COLOR = {
924
1042
  }),
925
1043
  /*#__PURE__*/ _jsx(ListTable, {
926
1044
  "aria-label": "Products",
1045
+ // A row opens its product in the editor; cmd-, ctrl-, shift- or
1046
+ // middle-click opens the editor in a new tab.
1047
+ onOpen: (_id, row)=>setEditing(row),
1048
+ openHref: (id)=>productEditorHref(id),
927
1049
  rows: columnSort.rows,
928
1050
  columns: productColumns,
929
1051
  loading: productsStatus === 'loading',