@aglyn/plugins-commerce 1.33.1 → 1.34.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.
- package/package.json +13 -13
- package/src/lib/components/cart.js +3 -1
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/catalog-organization-card.component.js +82 -69
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/discounts-card.component.js +46 -25
- package/src/lib/components/console/discounts-card.component.js.map +1 -1
- package/src/lib/components/console/gift-cards-card.component.js +81 -55
- package/src/lib/components/console/gift-cards-card.component.js.map +1 -1
- package/src/lib/components/console/host-coupons-card.component.js +36 -25
- package/src/lib/components/console/host-coupons-card.component.js.map +1 -1
- package/src/lib/components/console/locations-card.component.js +53 -32
- package/src/lib/components/console/locations-card.component.js.map +1 -1
- package/src/lib/components/console/member-posts-card.component.js +35 -32
- package/src/lib/components/console/member-posts-card.component.js.map +1 -1
- package/src/lib/components/console/new-store-tax-question.component.d.ts +17 -0
- package/src/lib/components/console/new-store-tax-question.component.js +197 -0
- package/src/lib/components/console/new-store-tax-question.component.js.map +1 -0
- package/src/lib/components/console/payments-settings-card.component.js +132 -5
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-api.d.ts +6 -0
- package/src/lib/components/console/pos/pos-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-tax-notice.component.d.ts +21 -0
- package/src/lib/components/console/pos/pos-tax-notice.component.js +59 -0
- package/src/lib/components/console/pos/pos-tax-notice.component.js.map +1 -0
- package/src/lib/components/console/pos-page.component.js +65 -17
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/registers-card.component.js +21 -13
- package/src/lib/components/console/registers-card.component.js.map +1 -1
- package/src/lib/components/console/reviews-moderation-card.component.js +108 -68
- package/src/lib/components/console/reviews-moderation-card.component.js.map +1 -1
- package/src/lib/components/console/site-member-purchases.component.js +5 -3
- package/src/lib/components/console/site-member-purchases.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.d.ts +2 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscriptions-card.component.js +13 -5
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
- package/src/lib/components/console/suppliers-card.component.js +47 -40
- package/src/lib/components/console/suppliers-card.component.js.map +1 -1
- package/src/lib/components/product-choice-cards.js +2 -1
- package/src/lib/components/product-choice-cards.js.map +1 -1
- package/src/lib/components/product-detail.js +9 -4
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.js +3 -1
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/related-products.js +2 -1
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/store-image-sizing.d.ts +46 -0
- package/src/lib/components/store-image-sizing.js +53 -0
- package/src/lib/components/store-image-sizing.js.map +1 -0
- package/src/lib/components/wishlist.js +2 -1
- package/src/lib/components/wishlist.js.map +1 -1
- package/src/lib/declarations.console-server.js +10 -0
- package/src/lib/declarations.console-server.js.map +1 -1
- package/src/lib/model/commerce-tax-step.d.ts +123 -0
- package/src/lib/model/commerce-tax-step.js +185 -0
- package/src/lib/model/commerce-tax-step.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/payments-setup-status.d.ts +40 -0
- package/src/lib/model/payments-setup-status.js +63 -0
- package/src/lib/model/payments-setup-status.js.map +1 -1
- package/src/lib/model/subscription-view.d.ts +19 -0
- package/src/lib/model/subscription-view.js +16 -0
- package/src/lib/model/subscription-view.js.map +1 -1
- package/src/lib/model/tap-to-pay-launch.d.ts +103 -0
- package/src/lib/model/tap-to-pay-launch.js +148 -0
- package/src/lib/model/tap-to-pay-launch.js.map +1 -0
- package/src/lib/plugin.js +12 -0
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/server/billing-webhook.js +140 -116
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/checkout.js +15 -4
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect-return.d.ts +83 -0
- package/src/lib/server/connect-return.js +105 -0
- package/src/lib/server/connect-return.js.map +1 -0
- package/src/lib/server/connect.d.ts +18 -0
- package/src/lib/server/connect.js +60 -6
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/new-store-tax.d.ts +10 -0
- package/src/lib/server/new-store-tax.js +43 -0
- package/src/lib/server/new-store-tax.js.map +1 -0
- package/src/lib/server/pos-payment.js +3 -2
- package/src/lib/server/pos-payment.js.map +1 -1
- package/src/lib/server/pos-tax-step.d.ts +43 -0
- package/src/lib/server/pos-tax-step.js +55 -0
- package/src/lib/server/pos-tax-step.js.map +1 -0
- package/src/lib/server/pos-terminal-connection-token.d.ts +10 -1
- package/src/lib/server/pos-terminal-connection-token.js +18 -7
- package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
- package/src/lib/server/pos-terminal.d.ts +9 -0
- package/src/lib/server/pos-terminal.js +17 -1
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/tap-to-pay-launch-admin.d.ts +18 -0
- package/src/lib/server/tap-to-pay-launch-admin.js +204 -0
- package/src/lib/server/tap-to-pay-launch-admin.js.map +1 -0
- package/src/lib/server/tap-to-pay-launch.d.ts +114 -0
- package/src/lib/server/tap-to-pay-launch.js +408 -0
- package/src/lib/server/tap-to-pay-launch.js.map +1 -0
- package/src/lib/server.js +15 -0
- package/src/lib/server.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/discounts-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 } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n deleteDoc,\n doc,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useCallback } from 'react'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport {\n collectionPage,\n usePagedCollection,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n heldSaveLabel,\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { useSeedDraft } from '@aglyn/tenant-feature-instance/hooks/use-seed-draft'\nimport TransferHeaderActions from '../../transfer/transfer-header-actions.component'\nimport { COMMERCE_DISCOUNTS_TRANSFER } from '../../transfer/transfer-keys'\n\nexport interface DiscountsCardProps {\n hostId: string\n}\n\n/**\n * Discounts hub (AGL-305): code and automatic promotions with value,\n * min-subtotal, schedule, and usage-limit controls, resolved at\n * checkout/POS by the shared engine. Supersedes the simple coupons\n * card (which keeps working for existing codes).\n */\nexport function DiscountsCard(props: DiscountsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const {\n status: discountsStatus,\n /**\n * The row this dialog is seeded from is unconfirmed by the server\n * (AGL-1358). `redemptions` is a LIVE counter the checkout engine\n * increments, and editing a discount copies it out of the seed and\n * writes it straight back — so a cached seed rolls the count backwards\n * and hands out redemptions that were already spent.\n */\n fromCache: discountsFromCache,\n listen: discountsListen,\n rows: discounts,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<any>(\n /*\n * SERVER-PAGED, and ordered (AGL-2501).\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order and the ids are\n * `createResourceUid()`, so the hundred were a pseudo-random sample of the\n * shop's promotions — and the hundred-and-first was UNREACHABLE, because\n * nothing rendered it and no control asked for more.\n *\n * The query can be paged here, unlike the cards carrying a duplicate-name\n * check: a discount's identity is its document id, `code` is an ordinary\n * field with no uniqueness test on this surface, and nothing on the card\n * is computed from rows that are off the page.\n *\n * `collectionPage` orders on the document NAME. `orderBy('code')` is the\n * tempting one and would be wrong twice: an AUTOMATIC promotion is stored\n * with `code: null`, so ordering on it would hide every automatic discount\n * the shop has, and a merchant reading \"no automatic promotions\" would be\n * reading a query artifact.\n */\n (pageLimit) =>\n collectionPage(\n collection(firestore, 'hosts', hostId, 'discounts'),\n pageLimit,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n /*\n * The dialog's draft, kept as EDITS over the discount as the list has it\n * now (AGL-4047): opened from the cache's row, the server's copy replaces\n * it under every field nobody touched, and Save is held until it has.\n */\n const [draft, setDraft] = useSeedDraft<\n Partial<CommerceModel.HostDiscount> & { id: string | null }\n >((opened) => {\n const row = opened.id\n ? discounts.find((discount: any) => discount.$id === opened.id)\n : undefined\n return row ? { id: row.$id, ...row } : undefined\n })\n const checking =\n Boolean(draft?.id) &&\n isSeedChecking({\n fromCache: discountsFromCache,\n unreadable: discountsStatus === 'error',\n })\n\n const handleSave = useCallback(async () => {\n if (!draft) return\n /**\n * `$id` comes off with `id` (AGL-1374).\n *\n * The editor is seeded `{ id: discount.$id, ...discount }`, and that\n * spread carries the listener's SYNTHETIC `$id` — `idField: '$id'`\n * stamps the document id onto the in-memory row, where nothing persists\n * it. Destructuring only `id` left `$id` in `data`, so every save wrote\n * it into the stored document as a real field. Nothing reads it; it is\n * the listener's bookkeeping leaking into storage, and once there no\n * reader can tell it from a field the card meant to write.\n */\n const seeded = draft as typeof draft & { $id?: string }\n const { id, $id: _syntheticId, ...data } = seeded\n const code = data.code?.trim().toUpperCase().replace(/[^A-Z0-9_-]/g, '')\n /**\n * Refuse an EDIT whose seed the server never confirmed (AGL-1358).\n *\n * `merge: true` protects nothing here — `{...data}` carries every field\n * of the seeded row, `redemptions` included, so it is written back\n * whether or not anyone touched it. Under `persistentLocalCache` that\n * seed can be arbitrarily old, and a redemption cap silently regains\n * uses that buyers already spent.\n *\n * Only the edit path is guarded: a NEW discount is built from blanks at\n * a fresh uid and can overwrite nothing.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'discount',\n unreadable: Boolean(id) && discountsStatus === 'error',\n fromCache: Boolean(id) && discountsFromCache,\n listen: discountsListen,\n },\n async () => {\n await setDoc(\n doc(\n firestore,\n 'hosts',\n hostId,\n 'discounts',\n id ?? Aglyn.createResourceUid(),\n ),\n {\n ...data,\n ...(code ? { code } : { code: null }),\n enabled: data.enabled !== false,\n redemptions: data.redemptions ?? 0,\n },\n { merge: true },\n )\n },\n )\n // Keep the dialog open with what was typed rather than failing silently.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setDraft(null)\n enqueueSnackbar('Discount saved', { variant: 'success', persist: false })\n }, [\n setDraft,\n draft,\n firestore,\n hostId,\n enqueueSnackbar,\n discountsFromCache,\n discountsListen,\n discountsStatus,\n ])\n\n /**\n * Switches a discount on or off (AGL-3774). Imported and AI-proposed\n * discounts start switched off, and Save keeps `enabled` as it was, so\n * without this a disabled discount could never be turned back on here.\n *\n * Writes ONLY `enabled`: unlike Save it carries no copy of the seeded row,\n * so it cannot roll back the live `redemptions` counter (AGL-1358).\n */\n const handleToggle = useCallback(\n async (discount: any) => {\n const enabled = discount.enabled === false\n try {\n await updateDoc(\n doc(firestore, 'hosts', hostId, 'discounts', discount.$id),\n { enabled },\n )\n enqueueSnackbar(enabled ? 'Discount enabled' : 'Discount disabled', {\n variant: 'success',\n persist: false,\n })\n } catch {\n enqueueSnackbar('Could not change the discount. Try again.', {\n variant: 'error',\n persist: false,\n })\n }\n },\n [firestore, hostId, enqueueSnackbar],\n )\n\n const describe = (discount: any) => {\n const value =\n discount.kind === 'percent'\n ? `${discount.valuePct}% off`\n : discount.kind === 'fixed'\n ? `$${((discount.valueCents ?? 0) / 100).toFixed(2)} off`\n : 'Free shipping'\n const scopeCount = Array.isArray(discount.productIds)\n ? discount.productIds.length\n : 0\n const extras = [\n // THE SCOPE, SAID OUT LOUD. A discount can cover named\n // products rather than the catalog, and the card showed no sign of it —\n // so a merchant could not tell a store-wide discount from a scoped one,\n // and had no way to understand why a scoped one takes less off than the\n // basket total. \"Store-wide\" is stated rather than left blank, because a\n // silent absence is what a narrower scope would also look like.\n scopeCount > 0\n ? `${scopeCount} product${scopeCount === 1 ? '' : 's'} only`\n : 'store-wide',\n discount.minSubtotalCents\n ? `min $${(discount.minSubtotalCents / 100).toFixed(0)}`\n : '',\n // Held slots are NAMED, not folded into the used figure (AGL-2453). A\n // live checkout now consumes a slot for as long as it can still be paid,\n // so `redemptions` alone would show a cap of 100 sitting at 100 against\n // 97 orders with nothing to explain the other three.\n discount.maxRedemptions\n ? CommerceModel.promotionUsageLabel(discount, Date.now())\n : '',\n ]\n .filter(Boolean)\n .join(' · ')\n return `${value}${extras ? ` · ${extras}` : ''}`\n }\n\n // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const held = useHeldSave(handleSave, {\n checking,\n subject: 'discount',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n\n return (\n <CardDisplay\n header={'Discounts'}\n HeaderProps={{\n action: <TransferHeaderActions resource={COMMERCE_DISCOUNTS_TRANSFER} hostId={hostId} />,\n }}\n help={pluginDocsHelp('discountsAndCoupons', { anchor: '#add-a-discount' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {discounts.length === 0 && page === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Codes buyers enter at checkout, or automatic promotions that ' +\n 'apply on their own.'}\n </Typography>\n ) : (\n discounts.map((discount: any) => (\n <Stack\n key={discount.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Chip\n label={discount.code || discount.name || 'Automatic'}\n size=\"small\"\n variant=\"outlined\"\n color={discount.code ? 'primary' : 'info'}\n />\n <Typography variant=\"body2\" sx={{ flex: 1 }} noWrap>\n {describe(discount)}\n {discount.enabled === false ? ' · disabled' : ''}\n </Typography>\n <Button size=\"small\" onClick={() => void handleToggle(discount)}>\n {discount.enabled === false ? 'Enable' : 'Disable'}\n </Button>\n <Button\n size=\"small\"\n onClick={() => setDraft({ id: discount.$id, ...discount })}\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() =>\n deleteDoc(\n doc(firestore, 'hosts', hostId, 'discounts', discount.$id),\n )\n }\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {discounts.length === 0 && page === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={discounts.length}\n // No `count`: a server window does not know the collection's\n // total, and `hasMore` is the probe row's answer rather than a\n // comparison against the cap.\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n setDraft({ id: null, kind: 'percent', valuePct: 10, enabled: true })\n }\n >\n {'Add discount'}\n </Button>\n </Stack>\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{draft?.id ? 'Edit discount' : 'New discount'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <TextField\n label=\"Code (blank = automatic)\"\n value={draft?.code ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, code: event.target.value } : prev,\n )\n }\n size=\"small\"\n sx={{ mt: 1 }}\n placeholder=\"SAVE10\"\n />\n {!draft?.code ? (\n <TextField\n label=\"Promotion name\"\n value={draft?.name ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n placeholder=\"Summer sale\"\n />\n ) : null}\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Type\"\n value={draft?.kind ?? 'percent'}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? { ...prev, kind: event.target.value as CommerceModel.DiscountKind }\n : prev,\n )\n }\n size=\"small\"\n select\n sx={{ minWidth: 150 }}\n >\n <MenuItem value=\"percent\">{'Percent off'}</MenuItem>\n <MenuItem value=\"fixed\">{'Fixed amount off'}</MenuItem>\n <MenuItem value=\"free_shipping\">{'Free shipping'}</MenuItem>\n </TextField>\n {draft?.kind === 'percent' ? (\n <TextField\n label=\"%\"\n value={draft?.valuePct ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n valuePct: Math.min(\n 100,\n Math.max(0, Number(event.target.value) || 0),\n ),\n }\n : prev,\n )\n }\n size=\"small\"\n sx={{ width: 90 }}\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n ) : null}\n {draft?.kind === 'fixed' ? (\n <TextField\n label=\"$ off\"\n value={\n draft?.valueCents != null ? draft.valueCents / 100 : ''\n }\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n valueCents: Math.round(\n (Number(event.target.value) || 0) * 100,\n ),\n }\n : prev,\n )\n }\n size=\"small\"\n sx={{ width: 110 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n ) : null}\n </Stack>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Min subtotal ($)\"\n placeholder=\"None\"\n value={\n draft?.minSubtotalCents != null\n ? draft.minSubtotalCents / 100\n : ''\n }\n onChange={(event) => {\n const raw = event.target.value.trim()\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n minSubtotalCents:\n raw === ''\n ? undefined\n : Math.round((Number(raw) || 0) * 100),\n }\n : prev,\n )\n }}\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Max uses\"\n placeholder=\"Unlimited\"\n value={draft?.maxRedemptions ?? ''}\n onChange={(event) => {\n const raw = event.target.value.trim()\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n maxRedemptions:\n raw === ''\n ? undefined\n : Math.max(1, Math.round(Number(raw))),\n }\n : prev,\n )\n }}\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n </Stack>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Starts\"\n type=\"date\"\n value={\n draft?.startAtMs\n ? new Date(draft.startAtMs).toISOString().slice(0, 10)\n : ''\n }\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n startAtMs: event.target.value\n ? Date.parse(`${event.target.value}T00:00:00Z`)\n : undefined,\n }\n : prev,\n )\n }\n size=\"small\"\n fullWidth\n slotProps={{ inputLabel: { shrink: true } }}\n />\n <TextField\n label=\"Ends\"\n type=\"date\"\n value={\n draft?.endAtMs\n ? new Date(draft.endAtMs).toISOString().slice(0, 10)\n : ''\n }\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n endAtMs: event.target.value\n ? Date.parse(`${event.target.value}T23:59:59Z`)\n : undefined,\n }\n : prev,\n )\n }\n size=\"small\"\n fullWidth\n slotProps={{ inputLabel: { shrink: true } }}\n />\n </Stack>\n </DialogContent>\n <DialogActions>\n {checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {seedCheckingText('discount')}\n </Typography>\n ) : null}\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n (draft?.kind === 'percent' && !((draft?.valuePct ?? 0) > 0)) ||\n (draft?.kind === 'fixed' && !((draft?.valueCents ?? 0) > 0)) ||\n held.saving\n }\n onClick={held.press}\n >\n {heldSaveLabel(held, 'Save')}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nDiscountsCard.displayName = 'DiscountsCard'\n\nexport default DiscountsCard\n"],"names":["Aglyn","CommerceModel","CardDisplay","useSnackbar","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Typography","collection","deleteDoc","doc","setDoc","updateDoc","useCallback","useFirestore","collectionPage","usePagedCollection","writeGuardedBySeed","ListPagination","pluginDocsHelp","heldSaveLabel","isSeedChecking","seedCheckingText","useHeldSave","useSeedDraft","TransferHeaderActions","COMMERCE_DISCOUNTS_TRANSFER","DiscountsCard","props","hostId","firestore","enqueueSnackbar","status","discountsStatus","fromCache","discountsFromCache","listen","discountsListen","rows","discounts","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","draft","setDraft","opened","row","id","find","discount","$id","undefined","checking","Boolean","unreadable","handleSave","data","seeded","_syntheticId","code","trim","toUpperCase","replace","verdict","subject","createResourceUid","enabled","redemptions","merge","ok","message","variant","persist","handleToggle","describe","value","kind","valuePct","valueCents","toFixed","scopeCount","Array","isArray","productIds","length","extras","minSubtotalCents","maxRedemptions","promotionUsageLabel","Date","now","filter","join","held","onRefused","header","HeaderProps","action","resource","help","anchor","contentGutterX","contentGutterY","spacing","color","map","direction","sx","alignItems","label","name","size","flex","noWrap","onClick","rowCount","onPageChange","onPageSizeChange","alignSelf","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","onChange","event","prev","target","mt","placeholder","select","minWidth","Math","min","max","Number","width","slotProps","htmlInput","inputMode","round","raw","type","startAtMs","toISOString","slice","parse","inputLabel","shrink","endAtMs","role","mr","disabled","saving","press","displayName"],"mapp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ACE,CAAC/G,yBAAAA,MAAOiC,IAAI,MAAK,aAAa,CAAE,CAAA,UAACjC,yBAAAA,MAAOkC,QAAQ,oBAAI,KAAK,CAAA,KACxDlC,CAAAA,yBAAAA,MAAOiC,IAAI,MAAK,WAAW,CAAE,CAAA,UAACjC,yBAAAA,MAAOmC,UAAU,oBAAI,KAAK,CAAA,KACzDe,KAAK8D,MAAM;gCAEbzC,SAASrB,KAAK+D,KAAK;0CAElB5I,cAAc6E,MAAM;;;;;;;;AAMjC;AACAtE,cAAcsI,WAAW,GAAG;AAE5B,eAAetI,cAAa"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/discounts-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 } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n deleteDoc,\n doc,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useCallback } from 'react'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport {\n collectionPage,\n usePagedCollection,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { OpenableListRow } from '@aglyn/shared-ui-jsx/components/openable-list-row.component'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport {\n mdiDeleteOutline,\n mdiPencilOutline,\n mdiToggleSwitchOffOutline,\n mdiToggleSwitchOutline,\n} from '@aglyn/shared-data-mdi'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n heldSaveLabel,\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { useSeedDraft } from '@aglyn/tenant-feature-instance/hooks/use-seed-draft'\nimport TransferHeaderActions from '../../transfer/transfer-header-actions.component'\nimport { COMMERCE_DISCOUNTS_TRANSFER } from '../../transfer/transfer-keys'\n\nexport interface DiscountsCardProps {\n hostId: string\n}\n\n/**\n * Discounts hub (AGL-305): code and automatic promotions with value,\n * min-subtotal, schedule, and usage-limit controls, resolved at\n * checkout/POS by the shared engine. Supersedes the simple coupons\n * card (which keeps working for existing codes).\n */\nexport function DiscountsCard(props: DiscountsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const {\n status: discountsStatus,\n /**\n * The row this dialog is seeded from is unconfirmed by the server\n * (AGL-1358). `redemptions` is a LIVE counter the checkout engine\n * increments, and editing a discount copies it out of the seed and\n * writes it straight back — so a cached seed rolls the count backwards\n * and hands out redemptions that were already spent.\n */\n fromCache: discountsFromCache,\n listen: discountsListen,\n rows: discounts,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<any>(\n /*\n * SERVER-PAGED, and ordered (AGL-2501).\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order and the ids are\n * `createResourceUid()`, so the hundred were a pseudo-random sample of the\n * shop's promotions — and the hundred-and-first was UNREACHABLE, because\n * nothing rendered it and no control asked for more.\n *\n * The query can be paged here, unlike the cards carrying a duplicate-name\n * check: a discount's identity is its document id, `code` is an ordinary\n * field with no uniqueness test on this surface, and nothing on the card\n * is computed from rows that are off the page.\n *\n * `collectionPage` orders on the document NAME. `orderBy('code')` is the\n * tempting one and would be wrong twice: an AUTOMATIC promotion is stored\n * with `code: null`, so ordering on it would hide every automatic discount\n * the shop has, and a merchant reading \"no automatic promotions\" would be\n * reading a query artifact.\n */\n (pageLimit) =>\n collectionPage(\n collection(firestore, 'hosts', hostId, 'discounts'),\n pageLimit,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n /*\n * The dialog's draft, kept as EDITS over the discount as the list has it\n * now (AGL-4047): opened from the cache's row, the server's copy replaces\n * it under every field nobody touched, and Save is held until it has.\n */\n const [draft, setDraft] = useSeedDraft<\n Partial<CommerceModel.HostDiscount> & { id: string | null }\n >((opened) => {\n const row = opened.id\n ? discounts.find((discount: any) => discount.$id === opened.id)\n : undefined\n return row ? { id: row.$id, ...row } : undefined\n })\n const checking =\n Boolean(draft?.id) &&\n isSeedChecking({\n fromCache: discountsFromCache,\n unreadable: discountsStatus === 'error',\n })\n\n const handleSave = useCallback(async () => {\n if (!draft) return\n /**\n * `$id` comes off with `id` (AGL-1374).\n *\n * The editor is seeded `{ id: discount.$id, ...discount }`, and that\n * spread carries the listener's SYNTHETIC `$id` — `idField: '$id'`\n * stamps the document id onto the in-memory row, where nothing persists\n * it. Destructuring only `id` left `$id` in `data`, so every save wrote\n * it into the stored document as a real field. Nothing reads it; it is\n * the listener's bookkeeping leaking into storage, and once there no\n * reader can tell it from a field the card meant to write.\n */\n const seeded = draft as typeof draft & { $id?: string }\n const { id, $id: _syntheticId, ...data } = seeded\n const code = data.code?.trim().toUpperCase().replace(/[^A-Z0-9_-]/g, '')\n /**\n * Refuse an EDIT whose seed the server never confirmed (AGL-1358).\n *\n * `merge: true` protects nothing here — `{...data}` carries every field\n * of the seeded row, `redemptions` included, so it is written back\n * whether or not anyone touched it. Under `persistentLocalCache` that\n * seed can be arbitrarily old, and a redemption cap silently regains\n * uses that buyers already spent.\n *\n * Only the edit path is guarded: a NEW discount is built from blanks at\n * a fresh uid and can overwrite nothing.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'discount',\n unreadable: Boolean(id) && discountsStatus === 'error',\n fromCache: Boolean(id) && discountsFromCache,\n listen: discountsListen,\n },\n async () => {\n await setDoc(\n doc(\n firestore,\n 'hosts',\n hostId,\n 'discounts',\n id ?? Aglyn.createResourceUid(),\n ),\n {\n ...data,\n ...(code ? { code } : { code: null }),\n enabled: data.enabled !== false,\n redemptions: data.redemptions ?? 0,\n },\n { merge: true },\n )\n },\n )\n // Keep the dialog open with what was typed rather than failing silently.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setDraft(null)\n enqueueSnackbar('Discount saved', { variant: 'success', persist: false })\n }, [\n setDraft,\n draft,\n firestore,\n hostId,\n enqueueSnackbar,\n discountsFromCache,\n discountsListen,\n discountsStatus,\n ])\n\n /**\n * Switches a discount on or off (AGL-3774). Imported and AI-proposed\n * discounts start switched off, and Save keeps `enabled` as it was, so\n * without this a disabled discount could never be turned back on here.\n *\n * Writes ONLY `enabled`: unlike Save it carries no copy of the seeded row,\n * so it cannot roll back the live `redemptions` counter (AGL-1358).\n */\n const handleToggle = useCallback(\n async (discount: any) => {\n const enabled = discount.enabled === false\n try {\n await updateDoc(\n doc(firestore, 'hosts', hostId, 'discounts', discount.$id),\n { enabled },\n )\n enqueueSnackbar(enabled ? 'Discount enabled' : 'Discount disabled', {\n variant: 'success',\n persist: false,\n })\n } catch {\n enqueueSnackbar('Could not change the discount. Try again.', {\n variant: 'error',\n persist: false,\n })\n }\n },\n [firestore, hostId, enqueueSnackbar],\n )\n\n const describe = (discount: any) => {\n const value =\n discount.kind === 'percent'\n ? `${discount.valuePct}% off`\n : discount.kind === 'fixed'\n ? `$${((discount.valueCents ?? 0) / 100).toFixed(2)} off`\n : 'Free shipping'\n const scopeCount = Array.isArray(discount.productIds)\n ? discount.productIds.length\n : 0\n const extras = [\n // THE SCOPE, SAID OUT LOUD. A discount can cover named\n // products rather than the catalog, and the card showed no sign of it —\n // so a merchant could not tell a store-wide discount from a scoped one,\n // and had no way to understand why a scoped one takes less off than the\n // basket total. \"Store-wide\" is stated rather than left blank, because a\n // silent absence is what a narrower scope would also look like.\n scopeCount > 0\n ? `${scopeCount} product${scopeCount === 1 ? '' : 's'} only`\n : 'store-wide',\n discount.minSubtotalCents\n ? `min $${(discount.minSubtotalCents / 100).toFixed(0)}`\n : '',\n // Held slots are NAMED, not folded into the used figure (AGL-2453). A\n // live checkout now consumes a slot for as long as it can still be paid,\n // so `redemptions` alone would show a cap of 100 sitting at 100 against\n // 97 orders with nothing to explain the other three.\n discount.maxRedemptions\n ? CommerceModel.promotionUsageLabel(discount, Date.now())\n : '',\n ]\n .filter(Boolean)\n .join(' · ')\n return `${value}${extras ? ` · ${extras}` : ''}`\n }\n\n /** Every action a discount row offers, in its ⋮ menu. */\n const discountRowActions = (discount: any): RowActionsMenuItem[] => [\n {\n key: 'edit',\n label: 'Edit',\n icon: { path: mdiPencilOutline.path },\n onClick: () => setDraft({ id: discount.$id, ...discount }),\n },\n discount.enabled === false\n ? {\n key: 'enable',\n label: 'Enable',\n icon: { path: mdiToggleSwitchOutline.path },\n onClick: () => void handleToggle(discount),\n }\n : {\n key: 'disable',\n label: 'Disable',\n icon: { path: mdiToggleSwitchOffOutline.path },\n onClick: () => void handleToggle(discount),\n },\n {\n key: 'delete',\n label: 'Delete',\n icon: { path: mdiDeleteOutline.path },\n destructive: true,\n onClick: () =>\n void deleteDoc(doc(firestore, 'hosts', hostId, 'discounts', discount.$id)),\n },\n ]\n\n // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const held = useHeldSave(handleSave, {\n checking,\n subject: 'discount',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n\n return (\n <CardDisplay\n header={'Discounts'}\n HeaderProps={{\n action: <TransferHeaderActions resource={COMMERCE_DISCOUNTS_TRANSFER} hostId={hostId} />,\n }}\n help={pluginDocsHelp('discountsAndCoupons', { anchor: '#add-a-discount' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {discounts.length === 0 && page === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Codes buyers enter at checkout, or automatic promotions that ' +\n 'apply on their own.'}\n </Typography>\n ) : (\n discounts.map((discount: any) => (\n <OpenableListRow\n key={discount.$id}\n label={discount.code || discount.name || 'Automatic'}\n onOpen={() => setDraft({ id: discount.$id, ...discount })}\n items={discountRowActions(discount)}\n >\n <Chip\n label={discount.code || discount.name || 'Automatic'}\n size=\"small\"\n variant=\"outlined\"\n color={discount.code ? 'primary' : 'info'}\n />\n <Typography variant=\"body2\" sx={{ flex: 1, minWidth: 0 }} noWrap>\n {describe(discount)}\n {discount.enabled === false ? ' · disabled' : ''}\n </Typography>\n </OpenableListRow>\n ))\n )}\n {discounts.length === 0 && page === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={discounts.length}\n // No `count`: a server window does not know the collection's\n // total, and `hasMore` is the probe row's answer rather than a\n // comparison against the cap.\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n setDraft({ id: null, kind: 'percent', valuePct: 10, enabled: true })\n }\n >\n {'Add discount'}\n </Button>\n </Stack>\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{draft?.id ? 'Edit discount' : 'New discount'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <TextField\n label=\"Code (blank = automatic)\"\n value={draft?.code ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, code: event.target.value } : prev,\n )\n }\n size=\"small\"\n sx={{ mt: 1 }}\n placeholder=\"SAVE10\"\n />\n {!draft?.code ? (\n <TextField\n label=\"Promotion name\"\n value={draft?.name ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n placeholder=\"Summer sale\"\n />\n ) : null}\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Type\"\n value={draft?.kind ?? 'percent'}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? { ...prev, kind: event.target.value as CommerceModel.DiscountKind }\n : prev,\n )\n }\n size=\"small\"\n select\n sx={{ minWidth: 150 }}\n >\n <MenuItem value=\"percent\">{'Percent off'}</MenuItem>\n <MenuItem value=\"fixed\">{'Fixed amount off'}</MenuItem>\n <MenuItem value=\"free_shipping\">{'Free shipping'}</MenuItem>\n </TextField>\n {draft?.kind === 'percent' ? (\n <TextField\n label=\"%\"\n value={draft?.valuePct ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n valuePct: Math.min(\n 100,\n Math.max(0, Number(event.target.value) || 0),\n ),\n }\n : prev,\n )\n }\n size=\"small\"\n sx={{ width: 90 }}\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n ) : null}\n {draft?.kind === 'fixed' ? (\n <TextField\n label=\"$ off\"\n value={\n draft?.valueCents != null ? draft.valueCents / 100 : ''\n }\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n valueCents: Math.round(\n (Number(event.target.value) || 0) * 100,\n ),\n }\n : prev,\n )\n }\n size=\"small\"\n sx={{ width: 110 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n ) : null}\n </Stack>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Min subtotal ($)\"\n placeholder=\"None\"\n value={\n draft?.minSubtotalCents != null\n ? draft.minSubtotalCents / 100\n : ''\n }\n onChange={(event) => {\n const raw = event.target.value.trim()\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n minSubtotalCents:\n raw === ''\n ? undefined\n : Math.round((Number(raw) || 0) * 100),\n }\n : prev,\n )\n }}\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Max uses\"\n placeholder=\"Unlimited\"\n value={draft?.maxRedemptions ?? ''}\n onChange={(event) => {\n const raw = event.target.value.trim()\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n maxRedemptions:\n raw === ''\n ? undefined\n : Math.max(1, Math.round(Number(raw))),\n }\n : prev,\n )\n }}\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n </Stack>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Starts\"\n type=\"date\"\n value={\n draft?.startAtMs\n ? new Date(draft.startAtMs).toISOString().slice(0, 10)\n : ''\n }\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n startAtMs: event.target.value\n ? Date.parse(`${event.target.value}T00:00:00Z`)\n : undefined,\n }\n : prev,\n )\n }\n size=\"small\"\n fullWidth\n slotProps={{ inputLabel: { shrink: true } }}\n />\n <TextField\n label=\"Ends\"\n type=\"date\"\n value={\n draft?.endAtMs\n ? new Date(draft.endAtMs).toISOString().slice(0, 10)\n : ''\n }\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n endAtMs: event.target.value\n ? Date.parse(`${event.target.value}T23:59:59Z`)\n : undefined,\n }\n : prev,\n )\n }\n size=\"small\"\n fullWidth\n slotProps={{ inputLabel: { shrink: true } }}\n />\n </Stack>\n </DialogContent>\n <DialogActions>\n {checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {seedCheckingText('discount')}\n </Typography>\n ) : null}\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n (draft?.kind === 'percent' && !((draft?.valuePct ?? 0) > 0)) ||\n (draft?.kind === 'fixed' && !((draft?.valueCents ?? 0) > 0)) ||\n held.saving\n }\n onClick={held.press}\n >\n {heldSaveLabel(held, 'Save')}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nDiscountsCard.displayName = 'DiscountsCard'\n\nexport default DiscountsCard\n"],"names":["Aglyn","CommerceModel","CardDisplay","useSnackbar","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Typography","collection","deleteDoc","doc","setDoc","updateDoc","useCallback","useFirestore","collectionPage","usePagedCollection","writeGuardedBySeed","ListPagination","OpenableListRow","mdiDeleteOutline","mdiPencilOutline","mdiToggleSwitchOffOutline","mdiToggleSwitchOutline","pluginDocsHelp","heldSaveLabel","isSeedChecking","seedCheckingText","useHeldSave","useSeedDraft","TransferHeaderActions","COMMERCE_DISCOUNTS_TRANSFER","DiscountsCard","props","hostId","firestore","enqueueSnackbar","status","discountsStatus","fromCache","discountsFromCache","listen","discountsListen","rows","discounts","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","draft","setDraft","opened","row","id","find","discount","$id","undefined","checking","Boolean","unreadable","handleSave","data","seeded","_syntheticId","code","trim","toUpperCase","replace","verdict","subject","createResourceUid","enabled","redemptions","merge","ok","message","variant","persist","handleToggle","describe","value","kind","valuePct","valueCents","toFixed","scopeCount","Array","isArray","productIds","length","extras","minSubtotalCents","maxRedemptions","promotionUsageLabel","Date","now","filter","join","discountRowActions","key","label","icon","path","onClick","destructive","held","onRefused","header","HeaderProps","action","resource","help","anchor","contentGutterX","contentGutterY","spacing","color","map","name","onOpen","items","size","sx","flex","minWidth","noWrap","rowCount","onPageChange","onPageSizeChange","alignSelf","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","onChange","event","prev","target","mt","placeholder","direction","select","Math","min","max","Number","width","slotProps","htmlInput","inputMode","round","raw","type","startAtMs","toISOString","slice","parse","inputLabel","shrink","endAtMs","role","mr","disabled","saving","press","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,YAAYA,WAAW,eAAc;AACrC,YAAYC,mBAAmB,uBAAa;AAC5C,SA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ACHuB,SAASxB,MAAME,MAAM,CAAC5D,KAAK,GACvBc,KAAKiE,KAAK,CAAC,GAAGrB,MAAME,MAAM,CAAC5D,KAAK,CAAC,UAAU,CAAC,IAC5CxB;qDAENmF;wCAGRlB,MAAK;wCACLY,SAAS;wCACTiB,WAAW;4CAAEU,YAAY;gDAAEC,QAAQ;4CAAK;wCAAE;;;;;;kCAIhD,MAACpK;;4BACE4D,yBACC,KAACtD;gCAAWyE,SAAQ;gCAAQwC,OAAM;gCAAiB+C,MAAK;gCAASzC,IAAI;oCAAE0C,IAAI;gCAAO;0CAC/E7I,iBAAiB;iCAElB;0CACJ,KAAC7B;gCAAO6G,SAAS,IAAMtD,SAAS;0CAAQ;;0CACxC,KAACvD;gCACCkF,SAAQ;gCACRwC,OAAM;gCACNiD,UACE,CAACrH,yBAAAA,MAAOiC,IAAI,MAAK,aAAa,CAAE,CAAA,UAACjC,yBAAAA,MAAOkC,QAAQ,oBAAI,KAAK,CAAA,KACxDlC,CAAAA,yBAAAA,MAAOiC,IAAI,MAAK,WAAW,CAAE,CAAA,UAACjC,yBAAAA,MAAOmC,UAAU,oBAAI,KAAK,CAAA,KACzDsB,KAAK6D,MAAM;gCAEb/D,SAASE,KAAK8D,KAAK;0CAElBlJ,cAAcoF,MAAM;;;;;;;;AAMjC;AACA7E,cAAc4I,WAAW,GAAG;AAE5B,eAAe5I,cAAa"}
|
|
@@ -18,6 +18,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
18
18
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } 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 { OpenableListRow } from "@aglyn/shared-ui-jsx/components/openable-list-row.component";
|
|
22
|
+
import { mdiCancel, mdiLockOpenVariantOutline } from "@aglyn/shared-data-mdi";
|
|
21
23
|
import { ListQueryNotices, listQueryRefusals } from "@aglyn/shared-ui-jsx/components/list-query-notices.component";
|
|
22
24
|
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
23
25
|
import { Button, Chip, Stack, TextField, Typography } from "@mui/material";
|
|
@@ -253,6 +255,38 @@ const giftCardsHelp = pluginDocsHelp('commerce', {
|
|
|
253
255
|
confirm,
|
|
254
256
|
post
|
|
255
257
|
]);
|
|
258
|
+
/**
|
|
259
|
+
* Every action a gift card row offers, in its ⋮ menu. Both are on every
|
|
260
|
+
* row; one that does not apply to this card is disabled with the reason.
|
|
261
|
+
* A card has no editor, so the row itself opens nothing.
|
|
262
|
+
*/ const giftCardRowActions = (card)=>{
|
|
263
|
+
var _card_balanceCents;
|
|
264
|
+
const onHold = !card.voidedAtMs && Number(card.frozenAtMs) > 0;
|
|
265
|
+
const voidable = !card.voidedAtMs && Number((_card_balanceCents = card.balanceCents) != null ? _card_balanceCents : 0) > 0;
|
|
266
|
+
return [
|
|
267
|
+
{
|
|
268
|
+
key: 'release',
|
|
269
|
+
label: 'Release',
|
|
270
|
+
icon: {
|
|
271
|
+
path: mdiLockOpenVariantOutline.path
|
|
272
|
+
},
|
|
273
|
+
disabled: busy || !onHold,
|
|
274
|
+
disabledReason: !onHold ? 'Only a card on hold can be released' : busy ? 'Working…' : undefined,
|
|
275
|
+
onClick: ()=>void handleRelease(card)
|
|
276
|
+
},
|
|
277
|
+
{
|
|
278
|
+
key: 'void',
|
|
279
|
+
label: 'Void',
|
|
280
|
+
icon: {
|
|
281
|
+
path: mdiCancel.path
|
|
282
|
+
},
|
|
283
|
+
destructive: true,
|
|
284
|
+
disabled: busy || !voidable,
|
|
285
|
+
disabledReason: card.voidedAtMs ? 'Already voided' : !voidable ? 'No balance left to void' : busy ? 'Working…' : undefined,
|
|
286
|
+
onClick: ()=>void handleVoid(card)
|
|
287
|
+
}
|
|
288
|
+
];
|
|
289
|
+
};
|
|
256
290
|
return /*#__PURE__*/ _jsx(EntitlementGatedCard, {
|
|
257
291
|
help: giftCardsHelp,
|
|
258
292
|
hostId: hostId,
|
|
@@ -358,66 +392,58 @@ const giftCardsHelp = pluginDocsHelp('commerce', {
|
|
|
358
392
|
cards.length ? /*#__PURE__*/ _jsx(Stack, {
|
|
359
393
|
spacing: 1,
|
|
360
394
|
children: cards.map((card)=>{
|
|
361
|
-
var _card_balanceCents
|
|
362
|
-
return /*#__PURE__*/
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
395
|
+
var _card_balanceCents;
|
|
396
|
+
return /*#__PURE__*/ _jsx(OpenableListRow, {
|
|
397
|
+
label: card.$id,
|
|
398
|
+
items: giftCardRowActions(card),
|
|
399
|
+
children: /*#__PURE__*/ _jsxs(Stack, {
|
|
400
|
+
direction: "row",
|
|
401
|
+
spacing: 1,
|
|
402
|
+
useFlexGap: true,
|
|
403
|
+
sx: {
|
|
404
|
+
flex: 1,
|
|
405
|
+
minWidth: 0,
|
|
406
|
+
flexWrap: 'wrap',
|
|
407
|
+
alignItems: 'center'
|
|
408
|
+
},
|
|
409
|
+
children: [
|
|
410
|
+
/*#__PURE__*/ _jsx(Typography, {
|
|
411
|
+
variant: "body2",
|
|
412
|
+
sx: {
|
|
413
|
+
fontFamily: 'monospace'
|
|
414
|
+
},
|
|
415
|
+
children: card.$id
|
|
416
|
+
}),
|
|
417
|
+
/*#__PURE__*/ _jsx(Chip, {
|
|
418
|
+
size: "small",
|
|
419
|
+
color: Number((_card_balanceCents = card.balanceCents) != null ? _card_balanceCents : 0) > 0 ? 'success' : 'default',
|
|
420
|
+
label: `${usd(card.balanceCents)} of ${usd(card.initialCents)}`
|
|
421
|
+
}),
|
|
422
|
+
card.recipientEmail ? /*#__PURE__*/ _jsx(Typography, {
|
|
423
|
+
variant: "body2",
|
|
424
|
+
color: "text.secondary",
|
|
425
|
+
children: card.recipientEmail
|
|
426
|
+
}) : null,
|
|
427
|
+
card.orderId ? null : /*#__PURE__*/ _jsx(Chip, {
|
|
428
|
+
size: "small",
|
|
429
|
+
variant: "outlined",
|
|
430
|
+
label: 'Issued by hand'
|
|
431
|
+
}),
|
|
432
|
+
!card.voidedAtMs && Number(card.frozenAtMs) > 0 ? /*#__PURE__*/ _jsx(_Fragment, {
|
|
433
|
+
children: /*#__PURE__*/ _jsx(Chip, {
|
|
396
434
|
size: "small",
|
|
397
435
|
color: "warning",
|
|
398
436
|
variant: "outlined",
|
|
399
437
|
label: 'On hold: payment questioned'
|
|
400
|
-
}),
|
|
401
|
-
/*#__PURE__*/ _jsx(Button, {
|
|
402
|
-
size: "small",
|
|
403
|
-
disabled: busy,
|
|
404
|
-
onClick: ()=>handleRelease(card),
|
|
405
|
-
children: 'Release'
|
|
406
438
|
})
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
color: "error",
|
|
416
|
-
disabled: busy,
|
|
417
|
-
onClick: ()=>handleVoid(card),
|
|
418
|
-
children: 'Void'
|
|
419
|
-
}) : null
|
|
420
|
-
]
|
|
439
|
+
}) : null,
|
|
440
|
+
card.voidedAtMs ? /*#__PURE__*/ _jsx(Chip, {
|
|
441
|
+
size: "small",
|
|
442
|
+
variant: "outlined",
|
|
443
|
+
label: card.voidedReason === 'refund' ? 'Voided: order refunded' : card.voidedReason === 'dispute-lost' ? 'Voided: chargeback lost' : 'Voided'
|
|
444
|
+
}) : null
|
|
445
|
+
]
|
|
446
|
+
})
|
|
421
447
|
}, card.$id);
|
|
422
448
|
})
|
|
423
449
|
}) : /*#__PURE__*/ _jsx(Typography, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/gift-cards-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport {\n ListQueryNotices,\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport type { ListQueryDeclaration } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n Chip,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n count,\n getAggregateFromServer,\n query,\n sum,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useListQuery } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { GIFT_CARD_SEARCH_TOKENS_PATH } from '../../model/gift-card-search'\nimport { EntitlementGatedCard } from './entitlement-gate.component'\nimport TransferHeaderActions from '../../transfer/transfer-header-actions.component'\nimport { COMMERCE_GIFT_CARDS_TRANSFER } from '../../transfer/transfer-keys'\n\nexport interface GiftCardsCardProps {\n hostId: string\n}\n\nconst usd = (cents: number | undefined) => `$${((cents ?? 0) / 100).toFixed(2)}`\n\n/**\n * The card list's one query (AGL-3321): newest first, and the search an\n * `array-contains` on the tokens every card writer stamps from its code and\n * its recipient's address (`giftCardSearchTokens`), so a card on page forty\n * is found exactly as one on page one is. One composite:\n * `(searchTokens CONTAINS, createdAtMs DESC)`.\n */\nexport const GIFT_CARD_LIST_QUERY: ListQueryDeclaration = {\n fields: [],\n sorts: [{ path: 'createdAtMs', direction: 'desc' }],\n search: { tokensPath: GIFT_CARD_SEARCH_TOKENS_PATH },\n}\n\nconst giftCardsHelp = pluginDocsHelp('commerce', {\n anchor: '#gift-cards',\n title: 'Gift cards',\n excerpt:\n 'Every gift card your store has issued, what is left on it, and what ' +\n 'that adds up to in outstanding store credit.',\n})\n\n/**\n * Gift cards & store credit (AGL-2226).\n *\n * `hosts/{hostId}/giftCards` has existed since AGL-322 with no console at\n * either end: `billing-webhook.ts` mints a card when one is bought,\n * `cart-checkout.ts` decrements it at redemption, and nothing in the product\n * ever showed the merchant a code, a balance, or the total they owe.\n *\n * The total is the point. Outstanding gift-card balance is a real liability\n * on the merchant's books, and it was invisible — which is also why AGL-1767\n * (a redemption resurrecting a deleted card at a NEGATIVE balance,\n * understating that liability) could not have been noticed from the console.\n * The sum below deliberately floors each card at zero so a stray negative row\n * cannot flatter the number the way that bug did.\n *\n * Reads are client-side because the Firestore host catch-all already grants\n * them and the merchant wants the list live. The two operations that MOVE\n * MONEY — issue and void — go through `commerce/gift-cards`, because that same\n * catch-all would otherwise let any site admin write their own `balanceCents`\n * and redeem it at checkout.\n */\nexport function GiftCardsCard(props: GiftCardsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const [search, setSearch] = useState('')\n /*\n * Ordered by the server and paged by it, and the search is the QUERY's\n * (AGL-3321): it used to match the code and the address over the page in\n * front of the merchant, and said so.\n */\n const {\n rows: cards,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n plan,\n } = useListQuery<any>({\n collection: collection(firestore, 'hosts', hostId, 'giftCards'),\n declaration: GIFT_CARD_LIST_QUERY,\n request: { clauses: [], search: search.trim() ? [search.trim()] : [] },\n deps: [firestore, hostId],\n idField: '$id',\n })\n const [amount, setAmount] = useState('')\n const [recipient, setRecipient] = useState('')\n const [busy, setBusy] = useState(false)\n\n\n /*==========================================\n * OUTSTANDING LIABILITY IS A SERVER AGGREGATE, not a page total.\n *\n * These two numbers are what the merchant owes their customers, and they\n * were `reduce`d over whatever the window happened to hold — 300 cards\n * chosen by code. A shop with 400 gift cards under-reported its own\n * liability and had no way to know: the chip does not say \"of the cards on\n * screen\", and there is no reading of \"$X outstanding\" under which a\n * sample is the answer.\n *\n * `where('balanceCents','>',0)` IS the per-card floor the reduce applied\n * by hand. A negative balance is a data fault (AGL-1767), not credit the\n * merchant gets back; excluding it contributes zero, exactly as flooring\n * it did. Zero-balance cards contribute nothing either way and are what\n * `liveCount` was already counting.\n *\n * An aggregation is billed per 1,000 documents scanned rather than per\n * document, so this is cheaper than the read it replaces as well as\n * correct.\n *=========================================*/\n const [totalsEpoch, setTotalsEpoch] = useState(0)\n const [totals, setTotals] = useState<{\n outstandingCents: number\n liveCount: number\n issuedCount: number\n } | null>(null)\n useEffect(() => {\n let active = true\n const cardsRef = collection(firestore, 'hosts', hostId, 'giftCards')\n void Promise.all([\n getAggregateFromServer(query(cardsRef, where('balanceCents', '>', 0)), {\n outstandingCents: sum('balanceCents'),\n liveCount: count(),\n }),\n // \"Issued\" is every card ever, so this one carries no predicate.\n getAggregateFromServer(cardsRef, { issuedCount: count() }),\n ])\n .then(([balances, issued]) => {\n if (!active) return\n setTotals({\n outstandingCents: Number(balances.data().outstandingCents ?? 0),\n liveCount: Number(balances.data().liveCount ?? 0),\n issuedCount: Number(issued.data().issuedCount ?? 0),\n })\n })\n .catch(() => {\n // Held at null rather than zeroed. \"$0.00 outstanding\" is a\n // confident wrong number in the flattering direction; an absent one\n // renders as unknown and cannot be mistaken for a settled book.\n if (active) setTotals(null)\n })\n return () => {\n active = false\n }\n }, [firestore, hostId, totalsEpoch])\n\n const post = useCallback(\n async (payload: Record<string, unknown>, success: (body: any) => string) => {\n setBusy(true)\n try {\n const response = await authorizedFetch(\n user,\n '/api/commerce/gift-cards',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, ...payload }),\n },\n )\n const body = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(body?.error ?? 'Gift card action failed', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n enqueueSnackbar(success(body), { variant: 'success', persist: false })\n // Issuing, voiding or adjusting moves the liability. The list is a\n // live listener and updates itself; the aggregate is a one-shot read\n // and would otherwise keep reporting the balance from before.\n setTotalsEpoch((epoch) => epoch + 1)\n } finally {\n setBusy(false)\n }\n },\n [user, hostId, enqueueSnackbar],\n )\n\n const handleIssue = useCallback(async () => {\n const dollars = Number(amount)\n if (!Number.isFinite(dollars) || dollars <= 0) {\n return void enqueueSnackbar('Enter an amount above zero', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n await post(\n {\n action: 'issue',\n amountCents: Math.round(dollars * 100),\n recipientEmail: recipient.trim(),\n },\n (body) =>\n body.emailed\n ? `Issued ${body.code} — emailed to ${recipient.trim()}`\n : `Issued ${body.code}`,\n )\n setAmount('')\n setRecipient('')\n }, [amount, recipient, post, enqueueSnackbar])\n\n const handleVoid = useCallback(\n async (card: any) => {\n // This provider REJECTS on dismissal rather than resolving false, so\n // the `.then/.catch` pair is the read — awaiting the promise bare would\n // throw out of the handler on a cancel.\n const confirmed = await confirm({\n title: `Void ${card.$id}?`,\n description:\n `This zeroes the ${usd(card.balanceCents)} left on the card. The ` +\n 'holder will no longer be able to redeem it, and it cannot be undone.',\n confirmationText: 'Void gift card',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await post({ action: 'void', code: card.$id }, () => `${card.$id} voided`)\n },\n [confirm, post],\n )\n\n // A card frozen by a fraud signal on its purchase (AGL-3363).\n const handleRelease = useCallback(\n async (card: any) => {\n const confirmed = await confirm({\n title: `Release ${card.$id}?`,\n description:\n 'The payment that bought this card was questioned by the card ' +\n 'issuer, held for review, or disputed. Release it only if you are ' +\n 'satisfied the payment is genuine: the holder can then spend the ' +\n `${usd(card.balanceCents)} left on it.`,\n confirmationText: 'Release gift card',\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await post({ action: 'release', code: card.$id }, () => `${card.$id} released`)\n },\n [confirm, post],\n )\n\n return (\n <EntitlementGatedCard\n help={giftCardsHelp}\n hostId={hostId}\n feature=\"giftCards\"\n header={'Gift cards'}\n upsell={\n 'Gift cards let shoppers buy store credit for someone else, and let ' +\n 'you issue credit by hand for a goodwill gesture or a service ' +\n 'recovery. Balances apply automatically at checkout.'\n }\n >\n <CardDisplay\n header={'Gift cards'}\n HeaderProps={{\n action: (\n <TransferHeaderActions resource={COMMERCE_GIFT_CARDS_TRANSFER} hostId={hostId} />\n ),\n }}\n help={giftCardsHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n <Chip\n size=\"small\"\n color={totals?.outstandingCents ? 'warning' : 'default'}\n label={\n totals\n ? `${usd(totals.outstandingCents)} outstanding`\n : 'Outstanding unavailable'\n }\n />\n {totals ? (\n <Chip\n size=\"small\"\n label={`${totals.liveCount} with a balance`}\n />\n ) : null}\n {totals ? (\n <Chip size=\"small\" label={`${totals.issuedCount} issued`} />\n ) : null}\n </Stack>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Outstanding balance is store credit your customers have already ' +\n 'paid for and not yet spent — it is a liability, not revenue.'}\n </Typography>\n\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n <TextField\n label=\"Issue amount (USD)\"\n value={amount}\n onChange={(event) => setAmount(event.target.value)}\n size=\"small\"\n type=\"number\"\n sx={{ maxWidth: 180 }}\n />\n <TextField\n label=\"Email it to (optional)\"\n value={recipient}\n onChange={(event) => setRecipient(event.target.value)}\n size=\"small\"\n sx={{ minWidth: 240 }}\n />\n <Button\n variant=\"contained\"\n size=\"small\"\n disabled={busy || !amount}\n onClick={handleIssue}\n >\n {'Issue card'}\n </Button>\n </Stack>\n\n <TextField\n label=\"Search by code or email\"\n value={search}\n onChange={(event) => {\n setSearch(event.target.value)\n setPage(0)\n }}\n size=\"small\"\n sx={{ maxWidth: 320 }}\n />\n <ListQueryNotices\n refused={listQueryRefusals(plan.refused, { fields: GIFT_CARD_LIST_QUERY.fields })}\n notices={plan.notices}\n />\n\n {cards.length ? (\n <Stack spacing={1}>\n {cards.map((card: any) => (\n <Stack\n key={card.$id}\n direction=\"row\"\n spacing={1}\n useFlexGap\n sx={{ flexWrap: 'wrap', alignItems: 'center' }}\n >\n <Typography variant=\"body2\" sx={{ fontFamily: 'monospace' }}>\n {card.$id}\n </Typography>\n <Chip\n size=\"small\"\n color={\n Number(card.balanceCents ?? 0) > 0 ? 'success' : 'default'\n }\n label={`${usd(card.balanceCents)} of ${usd(card.initialCents)}`}\n />\n {card.recipientEmail ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {card.recipientEmail}\n </Typography>\n ) : null}\n {card.orderId ? null : (\n <Chip size=\"small\" variant=\"outlined\" label={'Issued by hand'} />\n )}\n {!card.voidedAtMs && Number(card.frozenAtMs) > 0 ? (\n <>\n <Chip\n size=\"small\"\n color=\"warning\"\n variant=\"outlined\"\n label={'On hold: payment questioned'}\n />\n <Button\n size=\"small\"\n disabled={busy}\n onClick={() => handleRelease(card)}\n >\n {'Release'}\n </Button>\n </>\n ) : null}\n {card.voidedAtMs ? (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n label={\n card.voidedReason === 'refund'\n ? 'Voided: order refunded'\n : card.voidedReason === 'dispute-lost'\n ? 'Voided: chargeback lost'\n : 'Voided'\n }\n />\n ) : Number(card.balanceCents ?? 0) > 0 ? (\n <Button\n size=\"small\"\n color=\"error\"\n disabled={busy}\n onClick={() => handleVoid(card)}\n >\n {'Void'}\n </Button>\n ) : null}\n </Stack>\n ))}\n </Stack>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {search.trim()\n ? 'No gift card matches that code or email.'\n : 'No gift cards yet. Sell a gift-card product, or issue one above.'}\n </Typography>\n )}\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={cards.length}\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n </Stack>\n </CardDisplay>\n </EntitlementGatedCard>\n )\n}\nGiftCardsCard.displayName = 'GiftCardsCard'\n\nexport default GiftCardsCard\n"],"names":["CardDisplay","useConfirmationContext","ListPagination","ListQueryNotices","listQueryRefusals","useSnackbar","Button","Chip","Stack","TextField","Typography","collection","count","getAggregateFromServer","query","sum","where","useCallback","useEffect","useState","useFirestore","useUser","useListQuery","pluginDocsHelp","authorizedFetch","GIFT_CARD_SEARCH_TOKENS_PATH","EntitlementGatedCard","TransferHeaderActions","COMMERCE_GIFT_CARDS_TRANSFER","usd","cents","toFixed","GIFT_CARD_LIST_QUERY","fields","sorts","path","direction","search","tokensPath","giftCardsHelp","anchor","title","excerpt","GiftCardsCard","props","hostId","firestore","data","user","enqueueSnackbar","confirm","setSearch","rows","cards","hasMore","page","setPage","pageSize","setPageSize","plan","declaration","request","clauses","trim","deps","idField","amount","setAmount","recipient","setRecipient","busy","setBusy","totalsEpoch","setTotalsEpoch","totals","setTotals","active","cardsRef","Promise","all","outstandingCents","liveCount","issuedCount","then","balances","issued","Number","catch","post","payload","success","response","method","headers","body","JSON","stringify","json","ok","error","variant","allowDuplicate","persist","epoch","handleIssue","dollars","isFinite","action","amountCents","Math","round","recipientEmail","emailed","code","handleVoid","card","confirmed","$id","description","balanceCents","confirmationText","confirmationButtonProps","color","handleRelease","help","feature","header","upsell","HeaderProps","resource","contentGutterX","contentGutterY","spacing","useFlexGap","sx","flexWrap","size","label","value","onChange","event","target","type","maxWidth","minWidth","disabled","onClick","refused","notices","length","map","alignItems","fontFamily","initialCents","orderId","voidedAtMs","frozenAtMs","voidedReason","rowCount","onPageChange","onPageSizeChange","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SACEC,gBAAgB,EAChBC,iBAAiB,QACZ,+DAA8D;AAErE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,KAAK,EACLC,sBAAsB,EACtBC,KAAK,EACLC,GAAG,EACHC,KAAK,QACA,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACxD,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,YAAY,QAAQ,sDAAqD;AAClF,SAASC,cAAc,QAAQ,eAAc;AAC7C,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,4BAA4B,QAAQ,kCAA8B;AAC3E,SAASC,oBAAoB,QAAQ,kCAA8B;AACnE,OAAOC,2BAA2B,sDAAkD;AACpF,SAASC,4BAA4B,QAAQ,kCAA8B;AAM3E,MAAMC,MAAM,CAACC,QAA8B,CAAC,CAAC,EAAE,AAAC,CAAA,CAACA,gBAAAA,QAAS,KAAK,GAAE,EAAGC,OAAO,CAAC,IAAI;AAEhF;;;;;;CAMC,GACD,OAAO,MAAMC,uBAA6C;IACxDC,QAAQ,EAAE;IACVC,OAAO;QAAC;YAAEC,MAAM;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sH,WAAW,GAAG;AAE5B,eAAetH,cAAa"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/gift-cards-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { OpenableListRow } from '@aglyn/shared-ui-jsx/components/openable-list-row.component'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { mdiCancel, mdiLockOpenVariantOutline } from '@aglyn/shared-data-mdi'\nimport {\n ListQueryNotices,\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport type { ListQueryDeclaration } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n Chip,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n count,\n getAggregateFromServer,\n query,\n sum,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useListQuery } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { GIFT_CARD_SEARCH_TOKENS_PATH } from '../../model/gift-card-search'\nimport { EntitlementGatedCard } from './entitlement-gate.component'\nimport TransferHeaderActions from '../../transfer/transfer-header-actions.component'\nimport { COMMERCE_GIFT_CARDS_TRANSFER } from '../../transfer/transfer-keys'\n\nexport interface GiftCardsCardProps {\n hostId: string\n}\n\nconst usd = (cents: number | undefined) => `$${((cents ?? 0) / 100).toFixed(2)}`\n\n/**\n * The card list's one query (AGL-3321): newest first, and the search an\n * `array-contains` on the tokens every card writer stamps from its code and\n * its recipient's address (`giftCardSearchTokens`), so a card on page forty\n * is found exactly as one on page one is. One composite:\n * `(searchTokens CONTAINS, createdAtMs DESC)`.\n */\nexport const GIFT_CARD_LIST_QUERY: ListQueryDeclaration = {\n fields: [],\n sorts: [{ path: 'createdAtMs', direction: 'desc' }],\n search: { tokensPath: GIFT_CARD_SEARCH_TOKENS_PATH },\n}\n\nconst giftCardsHelp = pluginDocsHelp('commerce', {\n anchor: '#gift-cards',\n title: 'Gift cards',\n excerpt:\n 'Every gift card your store has issued, what is left on it, and what ' +\n 'that adds up to in outstanding store credit.',\n})\n\n/**\n * Gift cards & store credit (AGL-2226).\n *\n * `hosts/{hostId}/giftCards` has existed since AGL-322 with no console at\n * either end: `billing-webhook.ts` mints a card when one is bought,\n * `cart-checkout.ts` decrements it at redemption, and nothing in the product\n * ever showed the merchant a code, a balance, or the total they owe.\n *\n * The total is the point. Outstanding gift-card balance is a real liability\n * on the merchant's books, and it was invisible — which is also why AGL-1767\n * (a redemption resurrecting a deleted card at a NEGATIVE balance,\n * understating that liability) could not have been noticed from the console.\n * The sum below deliberately floors each card at zero so a stray negative row\n * cannot flatter the number the way that bug did.\n *\n * Reads are client-side because the Firestore host catch-all already grants\n * them and the merchant wants the list live. The two operations that MOVE\n * MONEY — issue and void — go through `commerce/gift-cards`, because that same\n * catch-all would otherwise let any site admin write their own `balanceCents`\n * and redeem it at checkout.\n */\nexport function GiftCardsCard(props: GiftCardsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const [search, setSearch] = useState('')\n /*\n * Ordered by the server and paged by it, and the search is the QUERY's\n * (AGL-3321): it used to match the code and the address over the page in\n * front of the merchant, and said so.\n */\n const {\n rows: cards,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n plan,\n } = useListQuery<any>({\n collection: collection(firestore, 'hosts', hostId, 'giftCards'),\n declaration: GIFT_CARD_LIST_QUERY,\n request: { clauses: [], search: search.trim() ? [search.trim()] : [] },\n deps: [firestore, hostId],\n idField: '$id',\n })\n const [amount, setAmount] = useState('')\n const [recipient, setRecipient] = useState('')\n const [busy, setBusy] = useState(false)\n\n\n /*==========================================\n * OUTSTANDING LIABILITY IS A SERVER AGGREGATE, not a page total.\n *\n * These two numbers are what the merchant owes their customers, and they\n * were `reduce`d over whatever the window happened to hold — 300 cards\n * chosen by code. A shop with 400 gift cards under-reported its own\n * liability and had no way to know: the chip does not say \"of the cards on\n * screen\", and there is no reading of \"$X outstanding\" under which a\n * sample is the answer.\n *\n * `where('balanceCents','>',0)` IS the per-card floor the reduce applied\n * by hand. A negative balance is a data fault (AGL-1767), not credit the\n * merchant gets back; excluding it contributes zero, exactly as flooring\n * it did. Zero-balance cards contribute nothing either way and are what\n * `liveCount` was already counting.\n *\n * An aggregation is billed per 1,000 documents scanned rather than per\n * document, so this is cheaper than the read it replaces as well as\n * correct.\n *=========================================*/\n const [totalsEpoch, setTotalsEpoch] = useState(0)\n const [totals, setTotals] = useState<{\n outstandingCents: number\n liveCount: number\n issuedCount: number\n } | null>(null)\n useEffect(() => {\n let active = true\n const cardsRef = collection(firestore, 'hosts', hostId, 'giftCards')\n void Promise.all([\n getAggregateFromServer(query(cardsRef, where('balanceCents', '>', 0)), {\n outstandingCents: sum('balanceCents'),\n liveCount: count(),\n }),\n // \"Issued\" is every card ever, so this one carries no predicate.\n getAggregateFromServer(cardsRef, { issuedCount: count() }),\n ])\n .then(([balances, issued]) => {\n if (!active) return\n setTotals({\n outstandingCents: Number(balances.data().outstandingCents ?? 0),\n liveCount: Number(balances.data().liveCount ?? 0),\n issuedCount: Number(issued.data().issuedCount ?? 0),\n })\n })\n .catch(() => {\n // Held at null rather than zeroed. \"$0.00 outstanding\" is a\n // confident wrong number in the flattering direction; an absent one\n // renders as unknown and cannot be mistaken for a settled book.\n if (active) setTotals(null)\n })\n return () => {\n active = false\n }\n }, [firestore, hostId, totalsEpoch])\n\n const post = useCallback(\n async (payload: Record<string, unknown>, success: (body: any) => string) => {\n setBusy(true)\n try {\n const response = await authorizedFetch(\n user,\n '/api/commerce/gift-cards',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, ...payload }),\n },\n )\n const body = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(body?.error ?? 'Gift card action failed', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n enqueueSnackbar(success(body), { variant: 'success', persist: false })\n // Issuing, voiding or adjusting moves the liability. The list is a\n // live listener and updates itself; the aggregate is a one-shot read\n // and would otherwise keep reporting the balance from before.\n setTotalsEpoch((epoch) => epoch + 1)\n } finally {\n setBusy(false)\n }\n },\n [user, hostId, enqueueSnackbar],\n )\n\n const handleIssue = useCallback(async () => {\n const dollars = Number(amount)\n if (!Number.isFinite(dollars) || dollars <= 0) {\n return void enqueueSnackbar('Enter an amount above zero', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n await post(\n {\n action: 'issue',\n amountCents: Math.round(dollars * 100),\n recipientEmail: recipient.trim(),\n },\n (body) =>\n body.emailed\n ? `Issued ${body.code} — emailed to ${recipient.trim()}`\n : `Issued ${body.code}`,\n )\n setAmount('')\n setRecipient('')\n }, [amount, recipient, post, enqueueSnackbar])\n\n const handleVoid = useCallback(\n async (card: any) => {\n // This provider REJECTS on dismissal rather than resolving false, so\n // the `.then/.catch` pair is the read — awaiting the promise bare would\n // throw out of the handler on a cancel.\n const confirmed = await confirm({\n title: `Void ${card.$id}?`,\n description:\n `This zeroes the ${usd(card.balanceCents)} left on the card. The ` +\n 'holder will no longer be able to redeem it, and it cannot be undone.',\n confirmationText: 'Void gift card',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await post({ action: 'void', code: card.$id }, () => `${card.$id} voided`)\n },\n [confirm, post],\n )\n\n // A card frozen by a fraud signal on its purchase (AGL-3363).\n const handleRelease = useCallback(\n async (card: any) => {\n const confirmed = await confirm({\n title: `Release ${card.$id}?`,\n description:\n 'The payment that bought this card was questioned by the card ' +\n 'issuer, held for review, or disputed. Release it only if you are ' +\n 'satisfied the payment is genuine: the holder can then spend the ' +\n `${usd(card.balanceCents)} left on it.`,\n confirmationText: 'Release gift card',\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await post({ action: 'release', code: card.$id }, () => `${card.$id} released`)\n },\n [confirm, post],\n )\n\n /**\n * Every action a gift card row offers, in its ⋮ menu. Both are on every\n * row; one that does not apply to this card is disabled with the reason.\n * A card has no editor, so the row itself opens nothing.\n */\n const giftCardRowActions = (card: any): RowActionsMenuItem[] => {\n const onHold = !card.voidedAtMs && Number(card.frozenAtMs) > 0\n const voidable = !card.voidedAtMs && Number(card.balanceCents ?? 0) > 0\n return [\n {\n key: 'release',\n label: 'Release',\n icon: { path: mdiLockOpenVariantOutline.path },\n disabled: busy || !onHold,\n disabledReason: !onHold ? 'Only a card on hold can be released' : busy ? 'Working…' : undefined,\n onClick: () => void handleRelease(card),\n },\n {\n key: 'void',\n label: 'Void',\n icon: { path: mdiCancel.path },\n destructive: true,\n disabled: busy || !voidable,\n disabledReason: card.voidedAtMs\n ? 'Already voided'\n : !voidable\n ? 'No balance left to void'\n : busy\n ? 'Working…'\n : undefined,\n onClick: () => void handleVoid(card),\n },\n ]\n }\n\n return (\n <EntitlementGatedCard\n help={giftCardsHelp}\n hostId={hostId}\n feature=\"giftCards\"\n header={'Gift cards'}\n upsell={\n 'Gift cards let shoppers buy store credit for someone else, and let ' +\n 'you issue credit by hand for a goodwill gesture or a service ' +\n 'recovery. Balances apply automatically at checkout.'\n }\n >\n <CardDisplay\n header={'Gift cards'}\n HeaderProps={{\n action: (\n <TransferHeaderActions resource={COMMERCE_GIFT_CARDS_TRANSFER} hostId={hostId} />\n ),\n }}\n help={giftCardsHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n <Chip\n size=\"small\"\n color={totals?.outstandingCents ? 'warning' : 'default'}\n label={\n totals\n ? `${usd(totals.outstandingCents)} outstanding`\n : 'Outstanding unavailable'\n }\n />\n {totals ? (\n <Chip\n size=\"small\"\n label={`${totals.liveCount} with a balance`}\n />\n ) : null}\n {totals ? (\n <Chip size=\"small\" label={`${totals.issuedCount} issued`} />\n ) : null}\n </Stack>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Outstanding balance is store credit your customers have already ' +\n 'paid for and not yet spent — it is a liability, not revenue.'}\n </Typography>\n\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n <TextField\n label=\"Issue amount (USD)\"\n value={amount}\n onChange={(event) => setAmount(event.target.value)}\n size=\"small\"\n type=\"number\"\n sx={{ maxWidth: 180 }}\n />\n <TextField\n label=\"Email it to (optional)\"\n value={recipient}\n onChange={(event) => setRecipient(event.target.value)}\n size=\"small\"\n sx={{ minWidth: 240 }}\n />\n <Button\n variant=\"contained\"\n size=\"small\"\n disabled={busy || !amount}\n onClick={handleIssue}\n >\n {'Issue card'}\n </Button>\n </Stack>\n\n <TextField\n label=\"Search by code or email\"\n value={search}\n onChange={(event) => {\n setSearch(event.target.value)\n setPage(0)\n }}\n size=\"small\"\n sx={{ maxWidth: 320 }}\n />\n <ListQueryNotices\n refused={listQueryRefusals(plan.refused, { fields: GIFT_CARD_LIST_QUERY.fields })}\n notices={plan.notices}\n />\n\n {cards.length ? (\n <Stack spacing={1}>\n {cards.map((card: any) => (\n <OpenableListRow\n key={card.$id}\n label={card.$id}\n items={giftCardRowActions(card)}\n >\n <Stack\n direction=\"row\"\n spacing={1}\n useFlexGap\n sx={{ flex: 1, minWidth: 0, flexWrap: 'wrap', alignItems: 'center' }}\n >\n <Typography variant=\"body2\" sx={{ fontFamily: 'monospace' }}>\n {card.$id}\n </Typography>\n <Chip\n size=\"small\"\n color={\n Number(card.balanceCents ?? 0) > 0 ? 'success' : 'default'\n }\n label={`${usd(card.balanceCents)} of ${usd(card.initialCents)}`}\n />\n {card.recipientEmail ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {card.recipientEmail}\n </Typography>\n ) : null}\n {card.orderId ? null : (\n <Chip size=\"small\" variant=\"outlined\" label={'Issued by hand'} />\n )}\n {!card.voidedAtMs && Number(card.frozenAtMs) > 0 ? (\n <>\n <Chip\n size=\"small\"\n color=\"warning\"\n variant=\"outlined\"\n label={'On hold: payment questioned'}\n />\n </>\n ) : null}\n {card.voidedAtMs ? (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n label={\n card.voidedReason === 'refund'\n ? 'Voided: order refunded'\n : card.voidedReason === 'dispute-lost'\n ? 'Voided: chargeback lost'\n : 'Voided'\n }\n />\n ) : null}\n </Stack>\n </OpenableListRow>\n ))}\n </Stack>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {search.trim()\n ? 'No gift card matches that code or email.'\n : 'No gift cards yet. Sell a gift-card product, or issue one above.'}\n </Typography>\n )}\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={cards.length}\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n </Stack>\n </CardDisplay>\n </EntitlementGatedCard>\n )\n}\nGiftCardsCard.displayName = 'GiftCardsCard'\n\nexport default GiftCardsCard\n"],"names":["CardDisplay","useConfirmationContext","ListPagination","OpenableListRow","mdiCancel","mdiLockOpenVariantOutline","ListQueryNotices","listQueryRefusals","useSnackbar","Button","Chip","Stack","TextField","Typography","collection","count","getAggregateFromServer","query","sum","where","useCallback","useEffect","useState","useFirestore","useUser","useListQuery","pluginDocsHelp","authorizedFetch","GIFT_CARD_SEARCH_TOKENS_PATH","EntitlementGatedCard","TransferHeaderActions","COMMERCE_GIFT_CARDS_TRANSFER","usd","cents","toFixed","GIFT_CARD_LIST_QUERY","fields","sorts","path","direction","search","tokensPath","giftCardsHelp","anchor","title","excerpt","GiftCardsCard","props","hostId","firestore","data","user","enqueueSnackbar","confirm","setSearch","rows","cards","hasMore","page","setPage","pageSize","setPageSize","plan","declaration","request","clauses","trim","deps","idField","amount","setAmount","recipient","setRecipient","busy","setBusy","totalsEpoch","setTotalsEpoch","totals","setTotals","active","cardsRef","Promise","all","outstandingCents","liveCount","issuedCount","then","balances","issued","Number","catch","post","payload","success","response","method","headers","body","JSON","stringify","json","ok","error","variant","allowDuplicate","persist","epoch","handleIssue","dollars","isFinite","action","amountCents","Math","round","recipientEmail","emailed","code","handleVoid","card","confirmed","$id","description","balanceCents","confirmationText","confirmationButtonProps","color","handleRelease","giftCardRowActions","onHold","voidedAtMs","frozenAtMs","voidable","key","label","icon","disabled","disabledReason","undefined","onClick","destructive","help","feature","header","upsell","HeaderProps","resource","contentGutterX","contentGutterY","spacing","useFlexGap","sx","flexWrap","size","value","onChange","event","target","type","maxWidth","minWidth","refused","notices","length","map","items","flex","alignItems","fontFamily","initialCents","orderId","voidedReason","rowCount","onPageChange","onPageSizeChange","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,eAAe,QAAQ,8DAA6D;AAE7F,SAASC,SAAS,EAAEC,yBAAyB,QAAQ,yBAAwB;AAC7E,SACEC,gBAAgB,EAChBC,iBAAiB,QACZ,+DAA8D;AAErE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,SAAS,EACTC,UAA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;;AAM9B;AACAf,cAAcgI,WAAW,GAAG;AAE5B,eAAehI,cAAa"}
|
|
@@ -19,6 +19,8 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
19
19
|
import * as CommerceModel from "../../model/index.js";
|
|
20
20
|
import { CardDisplay } from "@aglyn/shared-ui-jsx";
|
|
21
21
|
import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.component";
|
|
22
|
+
import { OpenableListRow } from "@aglyn/shared-ui-jsx/components/openable-list-row.component";
|
|
23
|
+
import { mdiToggleSwitchOffOutline, mdiToggleSwitchOutline } from "@aglyn/shared-data-mdi";
|
|
22
24
|
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
23
25
|
import { Timestamp } from "@aglyn/shared-util-timestamp";
|
|
24
26
|
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, Stack, TextField, Typography } from "@mui/material";
|
|
@@ -118,32 +120,41 @@ import { COMMERCE_COUPONS_TRANSFER } from "../../transfer/transfer-keys.js";
|
|
|
118
120
|
variant: "body2",
|
|
119
121
|
color: "text.secondary",
|
|
120
122
|
children: 'Percent-off codes buyers can enter at checkout.'
|
|
121
|
-
}) : coupons.map((coupon)
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
flex: 1
|
|
123
|
+
}) : coupons.map((coupon)=>// A coupon has no editor, so the row opens nothing and its ⋮
|
|
124
|
+
// menu holds the one action it has.
|
|
125
|
+
/*#__PURE__*/ _jsx(OpenableListRow, {
|
|
126
|
+
label: coupon.$id,
|
|
127
|
+
items: [
|
|
128
|
+
coupon.enabled === false ? {
|
|
129
|
+
key: 'enable',
|
|
130
|
+
label: 'Enable',
|
|
131
|
+
icon: {
|
|
132
|
+
path: mdiToggleSwitchOutline.path
|
|
132
133
|
},
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
134
|
+
onClick: ()=>void handleCouponToggle(coupon)()
|
|
135
|
+
} : {
|
|
136
|
+
key: 'disable',
|
|
137
|
+
label: 'Disable',
|
|
138
|
+
icon: {
|
|
139
|
+
path: mdiToggleSwitchOffOutline.path
|
|
140
|
+
},
|
|
141
|
+
onClick: ()=>void handleCouponToggle(coupon)()
|
|
142
|
+
}
|
|
143
|
+
],
|
|
144
|
+
children: /*#__PURE__*/ _jsx(Typography, {
|
|
145
|
+
variant: "body2",
|
|
146
|
+
sx: {
|
|
147
|
+
flex: 1,
|
|
148
|
+
minWidth: 0
|
|
149
|
+
},
|
|
150
|
+
noWrap: true,
|
|
151
|
+
children: `${coupon.$id} · ${coupon.percentOff}% off · ` + // Held slots are named separately (AGL-2453) — see the
|
|
152
|
+
// discounts card for why the used figure alone now misleads.
|
|
153
|
+
CommerceModel.promotionUsageLabel(coupon, Date.now()) + // An expiry nobody can see is one the merchant cannot act
|
|
154
|
+
// on, and an EXPIRED coupon still listed as live is the
|
|
155
|
+
// question this card exists to answer.
|
|
156
|
+
(coupon.expiresAtMs != null ? Number(coupon.expiresAtMs) < Date.now() ? ' · expired' : ` · expires ${new Date(Number(coupon.expiresAtMs)).toLocaleDateString()}` : '') + (coupon.enabled === false ? ' · disabled' : '')
|
|
157
|
+
})
|
|
147
158
|
}, coupon.$id)),
|
|
148
159
|
/*#__PURE__*/ _jsx(ListPagination, {
|
|
149
160
|
page: page,
|