@aglyn/plugins-commerce 1.14.0 → 1.15.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/account-subscriptions.d.ts +51 -0
- package/src/lib/components/account-subscriptions.js +168 -0
- package/src/lib/components/account-subscriptions.js.map +1 -0
- package/src/lib/components/account.js +12 -48
- package/src/lib/components/account.js.map +1 -1
- package/src/lib/components/cart.js +30 -6
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/commerce-console-page.js +6 -0
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/commerce-console-sections.d.ts +1 -1
- package/src/lib/components/commerce-console-sections.js +5 -0
- package/src/lib/components/commerce-console-sections.js.map +1 -1
- package/src/lib/components/console/paid-media.d.ts +1 -0
- package/src/lib/components/console/paid-media.js +15 -4
- package/src/lib/components/console/paid-media.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +1 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
- package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
- package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
- package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
- package/src/lib/components/console/pos-cellular-control.component.js +5 -5
- package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
- package/src/lib/components/console/pos-devices-card.component.js +2 -2
- package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
- package/src/lib/components/console/pos-hardware-card.component.js +77 -8
- package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
- package/src/lib/components/console/pos-page.component.js +19 -2
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +21 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
- package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
- package/src/lib/components/console/subscriptions-card.component.js +280 -0
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
- package/src/lib/components/hardware-terms-consent.d.ts +22 -0
- package/src/lib/components/hardware-terms-consent.js +85 -0
- package/src/lib/components/hardware-terms-consent.js.map +1 -0
- package/src/lib/components/product-detail.js +25 -5
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/constants/operator-alerts.d.ts +1 -1
- package/src/lib/constants/operator-alerts.js +4 -4
- package/src/lib/constants/operator-alerts.js.map +1 -1
- package/src/lib/model/commerce-orders.d.ts +6 -2
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-payment-methods.d.ts +24 -0
- package/src/lib/model/commerce-payment-methods.js +35 -0
- package/src/lib/model/commerce-payment-methods.js.map +1 -1
- package/src/lib/model/commerce.d.ts +6 -0
- package/src/lib/model/commerce.js.map +1 -1
- 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/paid-media.d.ts +8 -0
- package/src/lib/model/paid-media.js +13 -0
- package/src/lib/model/paid-media.js.map +1 -1
- package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
- package/src/lib/model/pos-hardware-in-person.js +52 -20
- package/src/lib/model/pos-hardware-in-person.js.map +1 -1
- package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
- package/src/lib/model/pos-hardware-tax-summary.js +2 -1
- package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
- package/src/lib/model/pos-hardware-terms.d.ts +37 -2
- package/src/lib/model/pos-hardware-terms.js +68 -3
- package/src/lib/model/pos-hardware-terms.js.map +1 -1
- package/src/lib/model/pos-hardware.d.ts +101 -15
- package/src/lib/model/pos-hardware.js +128 -18
- package/src/lib/model/pos-hardware.js.map +1 -1
- package/src/lib/model/pos-reader-splash.js +2 -2
- package/src/lib/model/pos-reader-splash.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/model/subscription-view.d.ts +90 -0
- package/src/lib/model/subscription-view.js +176 -0
- package/src/lib/model/subscription-view.js.map +1 -0
- package/src/lib/server/billing-webhook.d.ts +4 -6
- package/src/lib/server/billing-webhook.js +109 -51
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cart-checkout.js +45 -10
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.js +15 -3
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/checkout.js +58 -16
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/draft-order.js +7 -3
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/membership-account.d.ts +22 -0
- package/src/lib/server/membership-account.js +52 -8
- package/src/lib/server/membership-account.js.map +1 -1
- package/src/lib/server/pos-auth.d.ts +3 -3
- package/src/lib/server/pos-auth.js +3 -3
- package/src/lib/server/pos-auth.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.js +1 -1
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular-notify.js +1 -1
- package/src/lib/server/pos-cellular-notify.js.map +1 -1
- package/src/lib/server/pos-cellular.js +1 -1
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-hardware-admin.js +86 -13
- package/src/lib/server/pos-hardware-admin.js.map +1 -1
- package/src/lib/server/pos-hardware-attach.js +5 -5
- package/src/lib/server/pos-hardware-attach.js.map +1 -1
- package/src/lib/server/pos-hardware-cancel.js +65 -0
- package/src/lib/server/pos-hardware-cancel.js.map +1 -1
- package/src/lib/server/pos-hardware-closure-notices.js +2 -5
- package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
- package/src/lib/server/pos-hardware-closure.js +5 -8
- package/src/lib/server/pos-hardware-closure.js.map +1 -1
- package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
- package/src/lib/server/pos-hardware-in-person.js +72 -17
- package/src/lib/server/pos-hardware-in-person.js.map +1 -1
- package/src/lib/server/pos-hardware-notify.d.ts +2 -0
- package/src/lib/server/pos-hardware-notify.js +30 -5
- package/src/lib/server/pos-hardware-notify.js.map +1 -1
- package/src/lib/server/pos-hardware-readers.d.ts +25 -0
- package/src/lib/server/pos-hardware-readers.js +206 -85
- package/src/lib/server/pos-hardware-readers.js.map +1 -1
- package/src/lib/server/pos-hardware-returns.d.ts +8 -3
- package/src/lib/server/pos-hardware-returns.js +39 -7
- package/src/lib/server/pos-hardware-returns.js.map +1 -1
- package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
- package/src/lib/server/pos-hardware-sale-fields.js +114 -1
- package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
- package/src/lib/server/pos-hardware-sale.d.ts +2 -0
- package/src/lib/server/pos-hardware-sale.js +1 -0
- package/src/lib/server/pos-hardware-sale.js.map +1 -1
- package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
- package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
- package/src/lib/server/pos-hardware-webhook.js +16 -3
- package/src/lib/server/pos-hardware-webhook.js.map +1 -1
- package/src/lib/server/pos-hardware.d.ts +14 -3
- package/src/lib/server/pos-hardware.js +83 -18
- package/src/lib/server/pos-hardware.js.map +1 -1
- package/src/lib/server/pos-ops-routes.js +2 -10
- package/src/lib/server/pos-ops-routes.js.map +1 -1
- package/src/lib/server/quote-pay.js +8 -4
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/stream.d.ts +2 -0
- package/src/lib/server/stream.js +22 -2
- package/src/lib/server/stream.js.map +1 -1
- package/src/lib/server/tax-return-source.js +5 -1
- package/src/lib/server/tax-return-source.js.map +1 -1
- package/src/lib/server.js +2 -2
- package/src/lib/server.js.map +1 -1
|
@@ -24,7 +24,7 @@ import { useFirestore, useUser } from "@aglyn/tenant-feature-instance";
|
|
|
24
24
|
import { Button, Chip, Stack, Tooltip, Typography } from "@mui/material";
|
|
25
25
|
import { doc, getDoc } from "firebase/firestore";
|
|
26
26
|
import { useCallback, useEffect, useState } from "react";
|
|
27
|
-
import { PAID_MEDIA_COPY, paidMediaConfirmation, paidMediaScopeBody, usesBesideProduct } from "../../model/paid-media.js";
|
|
27
|
+
import { PAID_MEDIA_COPY, paidMediaCheckingNotice, paidMediaConfirmation, paidMediaScopeBody, paidMediaTitle, usesBesideProduct } from "../../model/paid-media.js";
|
|
28
28
|
/**
|
|
29
29
|
* A product's members videos (AGL-2814) and paid downloads (AGL-2847) are
|
|
30
30
|
* private files.
|
|
@@ -51,11 +51,18 @@ import { PAID_MEDIA_COPY, paidMediaConfirmation, paidMediaScopeBody, usesBesideP
|
|
|
51
51
|
const copy = PAID_MEDIA_COPY[kind];
|
|
52
52
|
const { data: user } = useUser();
|
|
53
53
|
const { confirm } = useConfirmationContext();
|
|
54
|
-
const { enqueueSnackbar } = useSnackbar();
|
|
54
|
+
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
|
|
55
55
|
const protect = useCallback(async (asset, options)=>{
|
|
56
56
|
const scopeBody = paidMediaScopeBody(asset.scope);
|
|
57
57
|
let others = [];
|
|
58
58
|
let checked = 'failed';
|
|
59
|
+
// The where-used scan can take seconds (AGL-4189). Without a word on
|
|
60
|
+
// screen the pick looks like it did nothing, and the question then
|
|
61
|
+
// opens over whatever the author did next.
|
|
62
|
+
const checking = enqueueSnackbar(paidMediaCheckingNotice(options.fileName), {
|
|
63
|
+
variant: 'info',
|
|
64
|
+
persist: true
|
|
65
|
+
});
|
|
59
66
|
try {
|
|
60
67
|
const response = await authorizedFetch(user, '/api/media/references', {
|
|
61
68
|
method: 'POST',
|
|
@@ -77,9 +84,11 @@ import { PAID_MEDIA_COPY, paidMediaConfirmation, paidMediaScopeBody, usesBesideP
|
|
|
77
84
|
} catch (unused) {
|
|
78
85
|
// Said in the confirmation instead: "we could not check" is not
|
|
79
86
|
// "nothing uses it".
|
|
87
|
+
} finally{
|
|
88
|
+
closeSnackbar == null ? void 0 : closeSnackbar(checking);
|
|
80
89
|
}
|
|
81
90
|
const confirmed = await confirm({
|
|
82
|
-
title:
|
|
91
|
+
title: paidMediaTitle(kind, options.fileName),
|
|
83
92
|
description: paidMediaConfirmation({
|
|
84
93
|
others,
|
|
85
94
|
checked,
|
|
@@ -117,6 +126,7 @@ import { PAID_MEDIA_COPY, paidMediaConfirmation, paidMediaScopeBody, usesBesideP
|
|
|
117
126
|
}
|
|
118
127
|
return true;
|
|
119
128
|
}, [
|
|
129
|
+
closeSnackbar,
|
|
120
130
|
confirm,
|
|
121
131
|
copy,
|
|
122
132
|
enqueueSnackbar,
|
|
@@ -139,7 +149,8 @@ import { PAID_MEDIA_COPY, paidMediaConfirmation, paidMediaScopeBody, usesBesideP
|
|
|
139
149
|
scope: picked.mediaScope,
|
|
140
150
|
mediaId: picked.mediaId
|
|
141
151
|
}, {
|
|
142
|
-
adding: true
|
|
152
|
+
adding: true,
|
|
153
|
+
fileName: picked.fileName
|
|
143
154
|
});
|
|
144
155
|
return madePrivate ? reference : null;
|
|
145
156
|
}, [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/paid-media.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\n'use client'\n\nimport {\n formatMediaRef,\n paidMediaAssetOf,\n parsePaidMediaSource,\n type PickedMedia,\n useMediaPicker,\n} from '@aglyn/aglyn'\nimport { useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { Button, Chip, Stack, Tooltip, Typography } from '@mui/material'\nimport { doc, getDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport {\n PAID_MEDIA_COPY,\n paidMediaConfirmation,\n paidMediaScopeBody,\n usesBesideProduct,\n type PaidMediaKind,\n type PaidMediaReference,\n type PaidMediaUsageCheck,\n} from '../../model/paid-media'\n\n/**\n * A product's members videos (AGL-2814) and paid downloads (AGL-2847) are\n * private files.\n *\n * The stream and download routes only ever hand a buyer a link that expires,\n * and they can only do that for a PRIVATE asset: a public one already has a\n * URL that works for anyone, forever, and the routes refuse to deliver it. So\n * adding a file to a product makes it private, and the product editor shows,\n * per file, whether that is still true.\n *\n * Making a file private is visible outside the product. A trailer that is\n * also on a public page stops playing there, and every public link to it that\n * was already shared dies. The author is told which places use it before\n * confirming, from the same where-used scan the media library runs before a\n * delete.\n */\n\nexport {\n paidMediaConfirmation,\n paidMediaScopeBody,\n usesBesideProduct,\n type PaidMediaKind,\n type PaidMediaReference,\n type PaidMediaUsageCheck,\n} from '../../model/paid-media'\n/**\n * Adds a picked file to a product as paid media, making it private first when\n * it is not, and makes an already-added one private.\n */\nexport function usePaidMediaAttach(product: {\n hostId: string\n productId?: string\n kind?: PaidMediaKind\n}) {\n const { hostId, productId } = product\n const kind = product.kind ?? 'video'\n const copy = PAID_MEDIA_COPY[kind]\n const { data: user } = useUser()\n const { confirm } = useConfirmationContext()\n const { enqueueSnackbar } = useSnackbar()\n\n const protect = useCallback(\n async (\n asset: { scope: string; mediaId: string },\n options: { adding: boolean },\n ): Promise<boolean> => {\n const scopeBody = paidMediaScopeBody(asset.scope)\n let others: PaidMediaReference[] = []\n let checked: PaidMediaUsageCheck = 'failed'\n try {\n const response = await authorizedFetch(user, '/api/media/references', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ ...scopeBody, mediaId: asset.mediaId }),\n })\n if (response.ok) {\n const payload = await response.json()\n others = usesBesideProduct(\n Array.isArray(payload?.references) ? payload.references : [],\n { hostId, productId },\n )\n checked = payload?.complete ? 'full' : 'partial'\n }\n } catch {\n // Said in the confirmation instead: \"we could not check\" is not\n // \"nothing uses it\".\n }\n const confirmed = await confirm({\n title: copy.title,\n description: paidMediaConfirmation({ others, checked, kind }),\n confirmationText: 'Make private',\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return false\n const response = await authorizedFetch(user, '/api/media/folders', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n ...scopeBody,\n action: 'set-private',\n mediaId: asset.mediaId,\n private: true,\n }),\n })\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n const reason = String(payload?.error ?? 'Could not make the video private')\n enqueueSnackbar(\n `${reason}. ${options.adding ? copy.notAdded : copy.unusable}`,\n { variant: 'error', allowDuplicate: true },\n )\n return false\n }\n if (payload?.rawUrlCleared === false) {\n enqueueSnackbar(\n 'The video is private, but an old public download link to it could ' +\n 'not be confirmed dead. Make it private again from the media ' +\n 'library to retry.',\n { variant: 'warning', persist: false },\n )\n }\n return true\n },\n [confirm, copy, enqueueSnackbar, hostId, kind, productId, user],\n )\n\n /** The value to store on the product, or null when nothing was added. */\n const attach = useCallback(\n async (picked: PickedMedia): Promise<string | null> => {\n const reference =\n picked.mediaScope && picked.mediaId\n ? formatMediaRef(picked.mediaScope, picked.mediaId)\n : undefined\n if (!reference || !picked.mediaScope || !picked.mediaId) {\n enqueueSnackbar(copy.choose, { variant: 'warning', persist: false })\n return null\n }\n if (picked.private) return reference\n const madePrivate = await protect(\n { scope: picked.mediaScope, mediaId: picked.mediaId },\n { adding: true },\n )\n return madePrivate ? reference : null\n },\n [copy, enqueueSnackbar, protect],\n )\n\n return { attach, protect }\n}\n\ntype Protection = 'checking' | 'private' | 'public' | 'missing' | 'unknown'\n\n/**\n * Whether one stored paid file can be delivered, read off its media document.\n * A public one gets the button that fixes it.\n */\nexport function PaidMediaProtection(props: {\n url: string\n hostId: string\n productId?: string\n kind?: PaidMediaKind\n}) {\n const { url, hostId, productId, kind } = props\n const firestore = useFirestore()\n const { protect } = usePaidMediaAttach({ hostId, productId, kind })\n const [protection, setProtection] = useState<Protection>('checking')\n const [generation, setGeneration] = useState(0)\n const source = parsePaidMediaSource(url)\n const asset = paidMediaAssetOf(url)\n\n useEffect(() => {\n const target = paidMediaAssetOf(url)\n if (!target) return\n let active = true\n setProtection('checking')\n const reference = target.scope.startsWith('org:')\n ? doc(\n firestore,\n 'orgs',\n target.scope.slice('org:'.length).split(':')[0],\n 'media',\n target.mediaId,\n )\n : doc(firestore, 'hosts', target.scope, 'media', target.mediaId)\n getDoc(reference)\n .then((snapshot) => {\n if (!active) return\n if (!snapshot.exists() || snapshot.get('deletedAt')) {\n setProtection('missing')\n } else {\n setProtection(snapshot.get('private') === true ? 'private' : 'public')\n }\n })\n .catch(() => {\n if (active) setProtection('unknown')\n })\n return () => {\n active = false\n }\n }, [firestore, url, generation])\n\n if (source.kind === 'external') {\n return (\n <Tooltip title=\"Served by another site, so its links cannot be made to expire.\">\n <Chip size=\"small\" label=\"Hosted elsewhere\" />\n </Tooltip>\n )\n }\n if (source.kind === 'malformed') {\n return <Chip size=\"small\" color=\"error\" label=\"Cannot be played\" />\n }\n if (!asset) return null\n if (protection === 'private') {\n return (\n <Tooltip title=\"Buyers get a link that expires.\">\n <Chip size=\"small\" color=\"success\" label=\"Private\" />\n </Tooltip>\n )\n }\n if (protection === 'public') {\n return (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Tooltip title=\"Anyone with its link can open a public file, so buyers cannot get it until it is private.\">\n <Chip size=\"small\" color=\"warning\" label=\"Public\" />\n </Tooltip>\n <Button\n size=\"small\"\n onClick={() =>\n void protect(asset, { adding: false }).then((madePrivate) => {\n if (madePrivate) setGeneration((value) => value + 1)\n })\n }\n >\n {'Make private'}\n </Button>\n </Stack>\n )\n }\n if (protection === 'missing') {\n return <Chip size=\"small\" color=\"error\" label=\"Not in the media library\" />\n }\n return null\n}\n\n/** One entry of a product's members video list. */\nexport interface MembersVideo {\n url: string\n title?: string\n}\n\n/**\n * A product's members videos: each with whether it can play, and the button\n * that adds one.\n *\n * Its own component so the product editor's body stays free while the editor\n * is closed: the editor is rendered on every visit to the catalog, and this\n * only mounts inside the open dialog.\n */\nexport function MembersVideosField(props: {\n hostId: string\n productId?: string\n videos: readonly MembersVideo[]\n onChange: (videos: MembersVideo[]) => void\n}) {\n const { hostId, productId, videos, onChange } = props\n const { pickMedia } = useMediaPicker()\n const { attach } = usePaidMediaAttach({ hostId, productId })\n return (\n <>\n {videos.map((video, index) => (\n <Stack key={index} direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }} noWrap>\n {`🎬 ${video.title || video.url}`}\n </Typography>\n <PaidMediaProtection url={video.url} hostId={hostId} productId={productId} />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() =>\n onChange(videos.filter((_item, itemIndex) => itemIndex !== index))\n }\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n void (async () => {\n // A private file is the only kind a members video can be, so the\n // picker offers private files here and nowhere else. And a film is\n // the only kind of file it can play, so the picker lists and\n // uploads nothing else (AGL-2953).\n const media = await pickMedia?.({\n allowPrivate: true,\n kind: 'video',\n })\n if (!media) return\n const url = await attach(media)\n if (!url) return\n onChange([...videos, { url, title: media.fileName ?? '' }])\n })()\n }\n >\n {'Add members video'}\n </Button>\n </>\n )\n}\n\n/**\n * The button that adds a paid download (AGL-2847): the picker offers private\n * files, and a public one is made private before it is added.\n *\n * Its own component for the same reason as {@link MembersVideosField}: the\n * product editor's body runs while the editor is closed, and this only mounts\n * inside the open dialog.\n */\nexport function PaidDownloadAddButton(props: {\n hostId: string\n productId?: string\n onAdd: (file: { url: string; fileName: string }) => void\n}) {\n const { hostId, productId, onAdd } = props\n const { pickMedia } = useMediaPicker()\n const { attach } = usePaidMediaAttach({ hostId, productId, kind: 'download' })\n return (\n <Button\n size=\"small\"\n onClick={() =>\n void (async () => {\n const media = await pickMedia?.({ allowPrivate: true })\n if (!media) return\n const url = await attach(media)\n if (!url) return\n onAdd({ url, fileName: media.fileName ?? 'download' })\n })()\n }\n >\n {'Add file (media library)'}\n </Button>\n )\n}\n"],"names":["formatMediaRef","paidMediaAssetOf","parsePaidMediaSource","useMediaPicker","useConfirmationContext","useSnackbar","authorizedFetch","useFirestore","useUser","Button","Chip","Stack","Tooltip","Typography","doc","getDoc","useCallback","useEffect","useState","PAID_MEDIA_COPY","paidMediaConfirmation","paidMediaScopeBody","usesBesideProduct","usePaidMediaAttach","product","hostId","productId","kind","copy","data","user","confirm","enqueueSnackbar","protect","asset","options","scopeBody","scope","others","checked","response","method","headers","body","JSON","stringify","mediaId","ok","payload","json","Array","isArray","references","complete","confirmed","title","description","confirmationText","then","catch","action","private","reason","String","error","adding","notAdded","unusable","variant","allowDuplicate","rawUrlCleared","persist","attach","picked","reference","mediaScope","undefined","choose","madePrivate","PaidMediaProtection","props","url","firestore","protection","setProtection","generation","setGeneration","source","target","active","startsWith","slice","length","split","snapshot","exists","get","size","label","color","direction","spacing","sx","alignItems","onClick","value","MembersVideosField","videos","onChange","pickMedia","map","video","index","flex","noWrap","filter","_item","itemIndex","alignSelf","media","allowPrivate","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E,6DAA6D;wBAC7D,mCAAmC;wBACnC,MAAMA,QAAQ,OAAMV,6BAAAA,UAAY;4BAC9BW,cAAc;4BACd7F,MAAM;wBACR;wBACA,IAAI,CAAC4F,OAAO;wBACZ,MAAMtC,MAAM,MAAMT,OAAO+C;wBACzB,IAAI,CAACtC,KAAK;wBACV2B,SAAS;+BAAID;4BAAQ;gCAAE1B;gCAAK1B,KAAK,GAAEgE,kBAAAA,MAAME,QAAQ,YAAdF,kBAAkB;4BAAG;yBAAE;oBAC5D,CAAA;0BAGD;;;;AAIT;AAEA;;;;;;;CAOC,GACD,OAAO,SAASG,sBAAsB1C,KAIrC;IACC,MAAM,EAAEvD,MAAM,EAAEC,SAAS,EAAEiG,KAAK,EAAE,GAAG3C;IACrC,MAAM,EAAE6B,SAAS,EAAE,GAAG1G;IACtB,MAAM,EAAEqE,MAAM,EAAE,GAAGjD,mBAAmB;QAAEE;QAAQC;QAAWC,MAAM;IAAW;IAC5E,qBACE,KAAClB;QACCwF,MAAK;QACLO,SAAS,IACP,KAAK,AAAC,CAAA;oBAKmBe;gBAJvB,MAAMA,QAAQ,OAAMV,6BAAAA,UAAY;oBAAEW,cAAc;gBAAK;gBACrD,IAAI,CAACD,OAAO;gBACZ,MAAMtC,MAAM,MAAMT,OAAO+C;gBACzB,IAAI,CAACtC,KAAK;gBACV0C,MAAM;oBAAE1C;oBAAKwC,QAAQ,GAAEF,kBAAAA,MAAME,QAAQ,YAAdF,kBAAkB;gBAAW;YACtD,CAAA;kBAGD;;AAGP"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/paid-media.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\n'use client'\n\nimport {\n formatMediaRef,\n paidMediaAssetOf,\n parsePaidMediaSource,\n type PickedMedia,\n useMediaPicker,\n} from '@aglyn/aglyn'\nimport { useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { Button, Chip, Stack, Tooltip, Typography } from '@mui/material'\nimport { doc, getDoc } from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport {\n PAID_MEDIA_COPY,\n paidMediaCheckingNotice,\n paidMediaConfirmation,\n paidMediaScopeBody,\n paidMediaTitle,\n usesBesideProduct,\n type PaidMediaKind,\n type PaidMediaReference,\n type PaidMediaUsageCheck,\n} from '../../model/paid-media'\n\n/**\n * A product's members videos (AGL-2814) and paid downloads (AGL-2847) are\n * private files.\n *\n * The stream and download routes only ever hand a buyer a link that expires,\n * and they can only do that for a PRIVATE asset: a public one already has a\n * URL that works for anyone, forever, and the routes refuse to deliver it. So\n * adding a file to a product makes it private, and the product editor shows,\n * per file, whether that is still true.\n *\n * Making a file private is visible outside the product. A trailer that is\n * also on a public page stops playing there, and every public link to it that\n * was already shared dies. The author is told which places use it before\n * confirming, from the same where-used scan the media library runs before a\n * delete.\n */\n\nexport {\n paidMediaConfirmation,\n paidMediaScopeBody,\n usesBesideProduct,\n type PaidMediaKind,\n type PaidMediaReference,\n type PaidMediaUsageCheck,\n} from '../../model/paid-media'\n/**\n * Adds a picked file to a product as paid media, making it private first when\n * it is not, and makes an already-added one private.\n */\nexport function usePaidMediaAttach(product: {\n hostId: string\n productId?: string\n kind?: PaidMediaKind\n}) {\n const { hostId, productId } = product\n const kind = product.kind ?? 'video'\n const copy = PAID_MEDIA_COPY[kind]\n const { data: user } = useUser()\n const { confirm } = useConfirmationContext()\n const { enqueueSnackbar, closeSnackbar } = useSnackbar()\n\n const protect = useCallback(\n async (\n asset: { scope: string; mediaId: string },\n options: { adding: boolean; fileName?: string },\n ): Promise<boolean> => {\n const scopeBody = paidMediaScopeBody(asset.scope)\n let others: PaidMediaReference[] = []\n let checked: PaidMediaUsageCheck = 'failed'\n // The where-used scan can take seconds (AGL-4189). Without a word on\n // screen the pick looks like it did nothing, and the question then\n // opens over whatever the author did next.\n const checking = enqueueSnackbar(paidMediaCheckingNotice(options.fileName), {\n variant: 'info',\n persist: true,\n })\n try {\n const response = await authorizedFetch(user, '/api/media/references', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ ...scopeBody, mediaId: asset.mediaId }),\n })\n if (response.ok) {\n const payload = await response.json()\n others = usesBesideProduct(\n Array.isArray(payload?.references) ? payload.references : [],\n { hostId, productId },\n )\n checked = payload?.complete ? 'full' : 'partial'\n }\n } catch {\n // Said in the confirmation instead: \"we could not check\" is not\n // \"nothing uses it\".\n } finally {\n closeSnackbar?.(checking)\n }\n const confirmed = await confirm({\n title: paidMediaTitle(kind, options.fileName),\n description: paidMediaConfirmation({ others, checked, kind }),\n confirmationText: 'Make private',\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return false\n const response = await authorizedFetch(user, '/api/media/folders', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n ...scopeBody,\n action: 'set-private',\n mediaId: asset.mediaId,\n private: true,\n }),\n })\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n const reason = String(payload?.error ?? 'Could not make the video private')\n enqueueSnackbar(\n `${reason}. ${options.adding ? copy.notAdded : copy.unusable}`,\n { variant: 'error', allowDuplicate: true },\n )\n return false\n }\n if (payload?.rawUrlCleared === false) {\n enqueueSnackbar(\n 'The video is private, but an old public download link to it could ' +\n 'not be confirmed dead. Make it private again from the media ' +\n 'library to retry.',\n { variant: 'warning', persist: false },\n )\n }\n return true\n },\n [closeSnackbar, confirm, copy, enqueueSnackbar, hostId, kind, productId, user],\n )\n\n /** The value to store on the product, or null when nothing was added. */\n const attach = useCallback(\n async (picked: PickedMedia): Promise<string | null> => {\n const reference =\n picked.mediaScope && picked.mediaId\n ? formatMediaRef(picked.mediaScope, picked.mediaId)\n : undefined\n if (!reference || !picked.mediaScope || !picked.mediaId) {\n enqueueSnackbar(copy.choose, { variant: 'warning', persist: false })\n return null\n }\n if (picked.private) return reference\n const madePrivate = await protect(\n { scope: picked.mediaScope, mediaId: picked.mediaId },\n { adding: true, fileName: picked.fileName },\n )\n return madePrivate ? reference : null\n },\n [copy, enqueueSnackbar, protect],\n )\n\n return { attach, protect }\n}\n\ntype Protection = 'checking' | 'private' | 'public' | 'missing' | 'unknown'\n\n/**\n * Whether one stored paid file can be delivered, read off its media document.\n * A public one gets the button that fixes it.\n */\nexport function PaidMediaProtection(props: {\n url: string\n hostId: string\n productId?: string\n kind?: PaidMediaKind\n}) {\n const { url, hostId, productId, kind } = props\n const firestore = useFirestore()\n const { protect } = usePaidMediaAttach({ hostId, productId, kind })\n const [protection, setProtection] = useState<Protection>('checking')\n const [generation, setGeneration] = useState(0)\n const source = parsePaidMediaSource(url)\n const asset = paidMediaAssetOf(url)\n\n useEffect(() => {\n const target = paidMediaAssetOf(url)\n if (!target) return\n let active = true\n setProtection('checking')\n const reference = target.scope.startsWith('org:')\n ? doc(\n firestore,\n 'orgs',\n target.scope.slice('org:'.length).split(':')[0],\n 'media',\n target.mediaId,\n )\n : doc(firestore, 'hosts', target.scope, 'media', target.mediaId)\n getDoc(reference)\n .then((snapshot) => {\n if (!active) return\n if (!snapshot.exists() || snapshot.get('deletedAt')) {\n setProtection('missing')\n } else {\n setProtection(snapshot.get('private') === true ? 'private' : 'public')\n }\n })\n .catch(() => {\n if (active) setProtection('unknown')\n })\n return () => {\n active = false\n }\n }, [firestore, url, generation])\n\n if (source.kind === 'external') {\n return (\n <Tooltip title=\"Served by another site, so its links cannot be made to expire.\">\n <Chip size=\"small\" label=\"Hosted elsewhere\" />\n </Tooltip>\n )\n }\n if (source.kind === 'malformed') {\n return <Chip size=\"small\" color=\"error\" label=\"Cannot be played\" />\n }\n if (!asset) return null\n if (protection === 'private') {\n return (\n <Tooltip title=\"Buyers get a link that expires.\">\n <Chip size=\"small\" color=\"success\" label=\"Private\" />\n </Tooltip>\n )\n }\n if (protection === 'public') {\n return (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Tooltip title=\"Anyone with its link can open a public file, so buyers cannot get it until it is private.\">\n <Chip size=\"small\" color=\"warning\" label=\"Public\" />\n </Tooltip>\n <Button\n size=\"small\"\n onClick={() =>\n void protect(asset, { adding: false }).then((madePrivate) => {\n if (madePrivate) setGeneration((value) => value + 1)\n })\n }\n >\n {'Make private'}\n </Button>\n </Stack>\n )\n }\n if (protection === 'missing') {\n return <Chip size=\"small\" color=\"error\" label=\"Not in the media library\" />\n }\n return null\n}\n\n/** One entry of a product's members video list. */\nexport interface MembersVideo {\n url: string\n title?: string\n}\n\n/**\n * A product's members videos: each with whether it can play, and the button\n * that adds one.\n *\n * Its own component so the product editor's body stays free while the editor\n * is closed: the editor is rendered on every visit to the catalog, and this\n * only mounts inside the open dialog.\n */\nexport function MembersVideosField(props: {\n hostId: string\n productId?: string\n videos: readonly MembersVideo[]\n onChange: (videos: MembersVideo[]) => void\n}) {\n const { hostId, productId, videos, onChange } = props\n const { pickMedia } = useMediaPicker()\n const { attach } = usePaidMediaAttach({ hostId, productId })\n return (\n <>\n {videos.map((video, index) => (\n <Stack key={index} direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }} noWrap>\n {`🎬 ${video.title || video.url}`}\n </Typography>\n <PaidMediaProtection url={video.url} hostId={hostId} productId={productId} />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() =>\n onChange(videos.filter((_item, itemIndex) => itemIndex !== index))\n }\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() =>\n void (async () => {\n // A private file is the only kind a members video can be, so the\n // picker offers private files here and nowhere else. And a film is\n // the only kind of file it can play, so the picker lists and\n // uploads nothing else (AGL-2953).\n const media = await pickMedia?.({\n allowPrivate: true,\n kind: 'video',\n })\n if (!media) return\n const url = await attach(media)\n if (!url) return\n onChange([...videos, { url, title: media.fileName ?? '' }])\n })()\n }\n >\n {'Add members video'}\n </Button>\n </>\n )\n}\n\n/**\n * The button that adds a paid download (AGL-2847): the picker offers private\n * files, and a public one is made private before it is added.\n *\n * Its own component for the same reason as {@link MembersVideosField}: the\n * product editor's body runs while the editor is closed, and this only mounts\n * inside the open dialog.\n */\nexport function PaidDownloadAddButton(props: {\n hostId: string\n productId?: string\n onAdd: (file: { url: string; fileName: string }) => void\n}) {\n const { hostId, productId, onAdd } = props\n const { pickMedia } = useMediaPicker()\n const { attach } = usePaidMediaAttach({ hostId, productId, kind: 'download' })\n return (\n <Button\n size=\"small\"\n onClick={() =>\n void (async () => {\n const media = await pickMedia?.({ allowPrivate: true })\n if (!media) return\n const url = await attach(media)\n if (!url) return\n onAdd({ url, fileName: media.fileName ?? 'download' })\n })()\n }\n >\n {'Add file (media library)'}\n </Button>\n )\n}\n"],"names":["formatMediaRef","paidMediaAssetOf","parsePaidMediaSource","useMediaPicker","useConfirmationContext","useSnackbar","authorizedFetch","useFirestore","useUser","Button","Chip","Stack","Tooltip","Typography","doc","getDoc","useCallback","useEffect","useState","PAID_MEDIA_COPY","paidMediaCheckingNotice","paidMediaConfirmation","paidMediaScopeBody","paidMediaTitle","usesBesideProduct","usePaidMediaAttach","product","hostId","productId","kind","copy","data","user","confirm","enqueueSnackbar","closeSnackbar","protect","asset","options","scopeBody","scope","others","checked","checking","fileName","variant","persist","response","method","headers","body","JSON","stringify","mediaId","ok","payload","json","Array","isArray","references","complete","confirmed","title","description","confirmationText","then","catch","action","private","reason","String","error","adding","notAdded","unusable","allowDuplicate","rawUrlCleared","attach","picked","reference","mediaScope","undefined","choose","madePrivate","PaidMediaProtection","props","url","firestore","protection","setProtection","generation","setGeneration","source","target","active","startsWith","slice","length","split","snapshot","exists","get","size","label","color","direction","spacing","sx","alignItems","onClick","value","MembersVideosField","videos","onChange","pickMedia","map","video","index","flex","noWrap","filter","_item","itemIndex","alignSelf","media","allowPrivate","PaidDownloadAddButton","onAdd"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,SACEA,cAAc,EACdC,gBAAgB,EAChBC,oBAAoB,EAEpBC,cAAc,QACT,eAAc;AACrB,SAASC,sBAAsB,QAAQ,uBAAsB;AAC7D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,OAAO,EAAEC,UAAU,QAAQ,gBAAe;AACxE,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACxD,SACEC,eAAe,EACfC,uBAAuB,EACvBC,qBAAqB,EACrBC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,QAIZ,4BAAwB;AAE/B;;;;;;;;;;;;;;;CAeC,GAED,SACEH,qBAAqB,EACrBC,kBAAkB,EAClBE,iBAAiB,QAIZ,4BAAwB;AAC/B;;;CAGC,GACD,OAAO,SAASC,mBAAmBC,OAIlC;QAEcA;IADb,MAAM,EAAEC,MAAM,EAAEC,SAAS,EAAE,GAAGF;IAC9B,MAAMG,QAAOH,gBAAAA,QAAQG,IAAI,YAAZH,gBAAgB;IAC7B,MAAMI,OAAOX,eAAe,CAACU,KAAK;IAClC,MAAM,EAAEE,MAAMC,IAAI,EAAE,GAAGxB;IACvB,MAAM,EAAEyB,OAAO,EAAE,GAAG7B;I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,6BAAAA,UAAY;oBAAEW,cAAc;gBAAK;gBACrD,IAAI,CAACD,OAAO;gBACZ,MAAMtC,MAAM,MAAMT,OAAO+C;gBACzB,IAAI,CAACtC,KAAK;gBACVyC,MAAM;oBAAEzC;oBAAK1C,QAAQ,GAAEgF,kBAAAA,MAAMhF,QAAQ,YAAdgF,kBAAkB;gBAAW;YACtD,CAAA;kBAGD;;AAGP"}
|
|
@@ -247,7 +247,7 @@ import { useCommerceEntitlement } from "./entitlement-gate.component.js";
|
|
|
247
247
|
/*#__PURE__*/ _jsx(Typography, {
|
|
248
248
|
variant: "body2",
|
|
249
249
|
color: "text.secondary",
|
|
250
|
-
children: 'Card processing is passed through at cost on top of that: ' + `${Aglyn.CARD_PROCESSING_PERCENT}–` + `${Aglyn.BNPL_PROCESSING_PERCENT}% + ` + `${Aglyn.PROCESSING_FIXED_CENTS}¢ per online ` + 'sale, what Stripe charges to take the payment. It is not a ' + `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} margin
|
|
250
|
+
children: 'Card processing is passed through at cost on top of that: ' + `${Aglyn.CARD_PROCESSING_PERCENT}–` + `${Aglyn.BNPL_PROCESSING_PERCENT}% + ` + `${Aglyn.PROCESSING_FIXED_CENTS}¢ per online ` + 'sale, what Stripe charges to take the payment. It is not a ' + `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} margin. Quotes and invoices ` + 'are paid by card or wallet, never buy-now-pay-later, so they carry ' + `${Aglyn.PAY_LINK_PROCESSING_PERCENT}% + ` + `${Aglyn.PROCESSING_FIXED_CENTS}¢.`
|
|
251
251
|
}),
|
|
252
252
|
physicalPct > 0 || digitalPct > 0 ? /*#__PURE__*/ _jsx(Typography, {
|
|
253
253
|
variant: "body2",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/payments-settings-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { trackEvent } from '@aglyn/aglyn/app-utils/analytics-events'\nimport * as Aglyn from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useOrgPlan } from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { PrerequisiteNotice } from '@aglyn/shared-ui-jsx/components/prerequisite-notice.component'\nimport { useCommerceEntitlement } from './entitlement-gate.component'\n\nexport interface PaymentsSettingsCardProps {\n hostId: string\n}\n\n/** The element id the Payments card carries, for a link on the same page that lands on it (AGL-3982). */\nexport const PAYMENTS_SETTINGS_ANCHOR = 'store-payments'\n\n/**\n * Merchant payments card (AGL-284): Stripe Connect Express onboarding\n * status for the org owner + the plan's transaction-fee ladder so the\n * \"upgrade to kill fees\" motion (AGL-278) is visible where it matters.\n */\nexport function PaymentsSettingsCard(props: PaymentsSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [busy, setBusy] = useState(false)\n /**\n * A one-time Stripe Express dashboard link, minted by the connect route on\n * request. Not persisted: login links are single-use and short-lived, so a\n * stored one would be a button that fails the second time it is pressed.\n */\n const [dashboardUrl, setDashboardUrl] = useState<string | null>(null)\n const { org, ready: planReady } = useOrgPlan(hostId)\n /** Bumped by Retry to re-subscribe the profile listen (AGL-1380). */\n const [retryNonce, setRetryNonce] = useState(0)\n const { upgradeHref } = useCommerceEntitlement(hostId, 'commerce')\n /**\n * The OWNER's profile: the Stripe account every money route charges\n * against is the one on the workspace owner's profile. Reading the\n * signed-in member's instead told an admin who is not the owner that a\n * connected store was not set up.\n */\n const ownerUid =\n typeof org?.ownerUid === 'string' && org.ownerUid ? org.ownerUid : undefined\n const { data: profile, status: profileStatus } = useFirestoreDoc<any>(\n // Held at null rather than addressed as `profiles/-pending-` — that\n // sentinel issued a guaranteed-denied read on every pre-auth mount, and\n // a denial lands in `status: 'error'`, which now means something.\n () => (ownerUid ? doc(firestore, 'profiles', ownerUid) : null),\n [firestore, ownerUid, retryNonce],\n )\n const isOwner = Boolean(\n org?.ownerUid && (user as any)?.uid === org.ownerUid,\n )\n /**\n * Three outcomes, not two (AGL-1380). An absent profile doc is the value\n * BEFORE an answer as much as it is the value of a merchant who never\n * connected Stripe, so \"Not set up\" off a falsy `stripeChargesEnabled` is a\n * claim about this org's payment setup made without having heard back. It\n * is wrong in the direction that provokes action: the same falsy value\n * turns the button into \"Set up payments\", which sends a merchant who is\n * already taking money into Stripe onboarding.\n */\n const stripeState: 'pending' | 'error' | 'loaded' =\n !planReady || (ownerUid && profileStatus === 'loading')\n ? 'pending'\n : profileStatus === 'error'\n ? 'error'\n : 'loaded'\n /**\n * WHICH STRIPE WORLD THE STORED ACCOUNT BELONGS TO (AGL-2471).\n *\n * `stripeChargesEnabled: true` was the whole readiness claim, and a\n * production profile carrying it named a TEST-mode account: this card said\n * \"Charges enabled\" about three storefronts that could not take a single\n * payment. Only a literal boolean counts as recorded — the same\n * three-valued reading `merchantAccountIsReady` uses on the server, so the\n * chip and the checkout cannot disagree.\n */\n const modeVerified = typeof profile?.stripeAccountLivemode === 'boolean'\n const chargesConnected =\n stripeState === 'loaded' && Boolean(profile?.stripeChargesEnabled)\n const modeUnverified = chargesConnected && !modeVerified\n const chargesEnabled = chargesConnected && modeVerified\n const physicalPct = Aglyn.resolveTransactionFeePct(org, 'physical')\n const digitalPct = Aglyn.resolveTransactionFeePct(org, 'digital')\n const commerceEnabled = Aglyn.checkEntitlement(org, 'commerce')\n\n const handleConnect = useCallback(async () => {\n setBusy(true)\n try {\n const response = await authorizedFetch(user, '/api/commerce/connect', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId }),\n })\n const payload = await response.json()\n if (response.status === 501) {\n return void enqueueSnackbar(\n 'Payments are not configured on this deployment',\n { variant: 'info', persist: false },\n )\n }\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'Payment setup failed', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n if (payload.chargesEnabled) {\n // \"% who connect Stripe\" — a GTM plan §6 activation metric\n // (AGL-1561). Gated on the TRANSITION, not the state: this handler\n // is a re-entrant create-or-resume, so it answers `chargesEnabled:\n // true` on every subsequent visit to a connected account, and a bare\n // event here would count one merchant once per click forever.\n // `chargesEnabled` is the state read from the profile BEFORE this\n // request, so the event fires only when onboarding actually completed.\n if (!chargesEnabled) trackEvent('stripe_connected', {})\n // CHARGES AND PAYOUTS ARE TWO FLAGS, AND ONLY ONE OF THEM IS THIS\n // SENTENCE (AGL-1997). `chargesEnabled` says Stripe will let the\n // account take money; whether the money can LEAVE is `payoutsEnabled`,\n // which the route answers alongside it. Charges-yes/payouts-no is an\n // ordinary Stripe state — verification pending or lapsed, no payout\n // method — and announcing \"Payments are enabled\" in it is false in the\n // direction that costs the merchant: they sell believing they are\n // paid, and the funds sit in a Connect account that cannot release\n // them. Read three-valued, so only a literal `false` from Stripe\n // downgrades the claim; an absent flag means unasked, not off.\n const payoutsBlocked = payload.payoutsEnabled === false\n // A WARNING THAT NAMES A PROBLEM MUST OFFER THE FIX.\n //\n // Stripe is the only place payouts can be released — an Express\n // account has no password and no direct login — so telling the\n // merchant their funds are stranded and then keeping them here is half\n // an answer. The route now mints the remediation link for exactly this\n // state; going there is the whole point of pressing the button.\n if (payoutsBlocked && payload.url) {\n return void window.location.assign(payload.url)\n }\n // Payouts are flowing, so the link is the Express dashboard: balance,\n // payout schedule, and the reason a payout failed. Held in state\n // rather than followed, because this click was a status check and\n // navigating away from one nobody asked to leave is its own defect.\n if (!payoutsBlocked && typeof payload.dashboardUrl === 'string') {\n setDashboardUrl(payload.dashboardUrl)\n }\n return void enqueueSnackbar(\n payoutsBlocked\n ? 'Connected — payouts are not released yet'\n : 'Payments are enabled',\n {\n variant: payoutsBlocked ? 'warning' : 'success',\n persist: false,\n },\n )\n }\n if (payload.url) window.location.assign(payload.url)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [user, hostId, chargesEnabled, enqueueSnackbar])\n\n return (\n <CardDisplay\n id={PAYMENTS_SETTINGS_ANCHOR}\n header={'Payments'}\n help={pluginDocsHelp('commerceEndToEnd', {\n anchor: '#1-connect-payments',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }}>\n {'Stripe account'}\n </Typography>\n {/*\n No chip at all on error: both labels it could carry — \"Charges\n enabled\" and \"Not set up\" — assert something we failed to find\n out. Whatever Stripe is doing right now it carries on doing.\n */}\n {stripeState === 'error' ? null : (\n <Chip\n size=\"small\"\n label={\n stripeState === 'pending'\n ? 'Checking…'\n : chargesEnabled\n ? 'Charges enabled'\n : modeUnverified\n ? 'Not verified'\n : 'Not set up'\n }\n color={\n stripeState === 'pending'\n ? 'default'\n : chargesEnabled\n ? 'success'\n : modeUnverified\n ? 'error'\n : 'warning'\n }\n variant=\"outlined\"\n />\n )}\n </Stack>\n {stripeState === 'error' ? (\n <Alert\n severity=\"error\"\n action={\n <Button\n color=\"inherit\"\n size=\"small\"\n onClick={() => setRetryNonce((n) => n + 1)}\n >\n {'Retry'}\n </Button>\n }\n >\n {'We couldn’t load your payment setup. This says nothing about ' +\n 'whether payments are on — we could not reach the setting to ' +\n 'find out. Nothing has changed.'}\n </Alert>\n ) : null}\n {/*\n Every line below reads the plan, and an org doc still in flight\n resolves to the FREE tier (AGL-1064) — which would flash \"Selling\n requires a paid plan\" and the wrong fee percentages at a paying\n seller, then correct itself. Say nothing until it is known.\n */}\n {!planReady ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Checking your plan…'}\n </Typography>\n ) : (\n <>\n {!commerceEnabled ? (\n <PrerequisiteNotice href={upgradeHref} actionLabel=\"See plans\">\n {'Selling needs a paid plan. Choose one on Billing, then connect Stripe here.'}\n </PrerequisiteNotice>\n ) : null}\n {/*\n THE LEGAL NAME, not the org's resolved `productName`\n (AGL-2351). This sentence says who takes money off the\n merchant's own Stripe account, and the application fee lands in\n the platform Stripe account — held by the operating entity, not\n by a white-label agency reselling the console. Naming the\n agency here would assert a fee relationship that does not\n exist. `PLATFORM_BRAND_LEGAL_NAME` still configures cleanly for\n a self-host operator, who really is the entity collecting it.\n */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Buyers pay on your own Stripe account; ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} collects a platform fee ` +\n 'per sale based on your plan:'}\n </Typography>\n {/* The DIGITAL rate is not products-only (AGL-2315). A paid\n booking is a service sale and resolves through the same\n `'service'`/digital axis, so a bookings-only merchant pays this\n exact number — and this card was the one place they could read\n their own rate while naming only \"products\". Stated here rather\n than adding a third figure: it is one rate, not two. */}\n <Typography variant=\"body2\">\n {`Physical products: ${physicalPct}% · Digital products, ` +\n `services & bookings: ${digitalPct}%`}\n {physicalPct > 0 || digitalPct > 0 ? (\n <Typography\n component=\"span\"\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {' — higher plans reduce fees to 0%'}\n </Typography>\n ) : null}\n </Typography>\n {/* CARD PROCESSING, PASSED THROUGH AT COST (AGL-2152).\n\n Unconditional, including on the 0% plans, because it is\n exactly those plans where the merchant would otherwise read\n \"0%\" and be surprised by a deduction. Their PLATFORM fee\n really is zero — the figure below is Stripe's own charge for\n taking the payment, which every storefront sale incurs and\n which used to be absorbed silently out of the platform's\n balance rather than passed through.\n\n Named as a range rather than one number because the buyer\n chooses the payment method after the session is created:\n cards settle at the low end, buy-now-pay-later at the high\n end, and the deduction is sized for the dearest so a sale can\n never cost more to process than it collects. */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Card processing is passed through at cost on top of that: ' +\n `${Aglyn.CARD_PROCESSING_PERCENT}–` +\n `${Aglyn.BNPL_PROCESSING_PERCENT}% + ` +\n `${Aglyn.PROCESSING_FIXED_CENTS}¢ per online ` +\n 'sale, what Stripe charges to take the payment. It is not a ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} margin.`}\n </Typography>\n {/* WHICH REGISTER TENDERS CARRY THE FEE, AND HOW EACH IS\n COLLECTED (AGL-2111, AGL-4036).\n\n Card and room-charge payments at the register carry the fee;\n cash, gift cards and store credit carry none\n (`CommerceModel.paymentCarriesPlatformFee`). A room charge's\n fee leaves by a door the merchant has never seen money leave\n by, their monthly invoice, so it is said here BEFORE it\n appears there.\n\n Shown only when a rate actually applies: on a 0% plan there is\n nothing to collect either way, and the paragraph would be noise\n on the card of the merchants who upgraded to escape fees. */}\n {physicalPct > 0 || digitalPct > 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'At the register, cash, gift card and store credit payments ' +\n 'carry no fee. On card payments it is deducted from your ' +\n 'Stripe payout; on room-charge payments there is no payout to ' +\n 'deduct from, so it is added to your monthly ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} invoice instead.`}\n </Typography>\n ) : null}\n </>\n )}\n {/*\n AGL-2471: connected, and refused by every money door because the\n account was never verified against this deployment's Stripe mode.\n \"Not set up\" would be a lie in the other direction — the merchant\n did set something up — so the card names what is actually wrong and\n what to do about it.\n */}\n {modeUnverified ? (\n <Alert severity=\"error\">\n {'Your Stripe account has not been verified for payments on ' +\n 'this site, so sales will be refused. Set up payments again ' +\n 'to verify it — if it was connected against Stripe test mode, ' +\n 'you will need to connect a live account.'}\n </Alert>\n ) : null}\n {/*\n The button's own label is a claim — \"Set up payments\" tells the\n owner they have none. Withheld until the answer is in, for the same\n reason as the chip (AGL-1380); on error the Retry above is the only\n action offered, because acting on a setup we could not read is how\n a connected merchant gets sent back through onboarding.\n */}\n {/*\n WHERE THE MONEY STOPPED. Mirrored onto this profile by the\n `payout.failed` handler and retired by the next successful payout, so\n it names a live problem rather than a scar. Without it a merchant sold\n into an account that could not release the funds and the card said\n \"Payments are enabled\" the whole time — the storefront looked healthy\n from every angle available to them.\n */}\n {stripeState === 'loaded' && profile?.lastPayoutFailureAtMs ? (\n <Alert severity=\"warning\" variant=\"outlined\">\n {`A payout of $${(\n Number(profile.lastPayoutFailureCents ?? 0) / 100\n ).toFixed(2)} did not reach your bank on ${new Date(\n Number(profile.lastPayoutFailureAtMs),\n ).toLocaleDateString()} — ${String(\n profile.lastPayoutFailureReason ?? 'Stripe did not say why',\n )} The money is still in your Stripe account. Open Stripe to fix your payout details.`}\n </Alert>\n ) : null}\n {!planReady || stripeState !== 'loaded' ? null : isOwner ? (\n <>\n <Button\n size=\"small\"\n variant={chargesEnabled ? 'text' : 'contained'}\n color=\"primary\"\n disabled={busy}\n onClick={handleConnect}\n sx={{ alignSelf: 'flex-start' }}\n >\n {chargesEnabled\n ? 'Refresh status'\n : busy\n ? 'Opening Stripe…'\n : 'Set up payments'}\n </Button>\n {/*\n Where the money actually is. Aglyn records none of it —\n no balance, no payout schedule, and no `payout.failed` handling\n anywhere — so a merchant whose payout bounced has no way to learn\n that from this console. An Express account has no direct login\n either, which leaves a link minted by the platform as the only\n route in. `target=\"_blank\"` because it leaves the app entirely.\n */}\n {dashboardUrl ? (\n <Button\n size=\"small\"\n variant=\"text\"\n color=\"primary\"\n href={dashboardUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n sx={{ alignSelf: 'flex-start' }}\n >\n {'View payouts in Stripe'}\n </Button>\n ) : null}\n </>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Only the organization owner can set up payments.'}\n </Typography>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nPaymentsSettingsCard.displayName = 'PaymentsSettingsCard'\n\nexport default PaymentsSettingsCard\n"],"names":["trackEvent","Aglyn","CardDisplay","useSnackbar","Alert","Button","Chip","Stack","Typography","doc","useCallback","useState","useFirestore","useUser","useFirestoreDoc","useOrgPlan","pluginDocsHelp","authorizedFetch","PrerequisiteNotice","useCommerceEntitlement","PAYMENTS_SETTINGS_ANCHOR","PaymentsSettingsCard","props","profile","hostId","firestore","data","user","enqueueSnackbar","busy","setBusy","dashboardUrl","setDashboardUrl","org","ready","planReady","retryNonce","setRetryNonce","upgradeHref","ownerUid","undefined","status","profileStatus","isOwner","Boolean","uid","stripeState","modeVerified","stripeAccountLivemode","chargesConnected","stripeChargesEnabled","modeUnverified","chargesEnabled","physicalPct","resolveTransactionFeePct","digitalPct","commerceEnabled","checkEntitlement","handleConnect","response","method","headers","body","JSON","stringify","payload","json","variant","persist","ok","error","allowDuplicate","payoutsBlocked","payoutsEnabled","url","window","location","assign","console","id","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","flex","size","label","color","severity","action","onClick","n","href","actionLabel","PLATFORM_BRAND_LEGAL_NAME","component","CARD_PROCESSING_PERCENT","BNPL_PROCESSING_PERCENT","PROCESSING_FIXED_CENTS","lastPayoutFailureAtMs","Number","lastPayoutFailureCents","toFixed","Date","toLocaleDateString","String","lastPayoutFailureReason","disabled","alignSelf","target","rel","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,UAAU,QAAQ,0CAAyC;AACpE,YAAYC,WAAW,eAAc;AACrC,SAASC,WAAW,QAAQ,uBAAsB;A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AQ;oBAAUyB,OAAM;8BACjC;;;;;AAMb;AACAvE,qBAAqB+F,WAAW,GAAG;AAEnC,eAAe/F,qBAAoB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/payments-settings-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { trackEvent } from '@aglyn/aglyn/app-utils/analytics-events'\nimport * as Aglyn from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useOrgPlan } from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { PrerequisiteNotice } from '@aglyn/shared-ui-jsx/components/prerequisite-notice.component'\nimport { useCommerceEntitlement } from './entitlement-gate.component'\n\nexport interface PaymentsSettingsCardProps {\n hostId: string\n}\n\n/** The element id the Payments card carries, for a link on the same page that lands on it (AGL-3982). */\nexport const PAYMENTS_SETTINGS_ANCHOR = 'store-payments'\n\n/**\n * Merchant payments card (AGL-284): Stripe Connect Express onboarding\n * status for the org owner + the plan's transaction-fee ladder so the\n * \"upgrade to kill fees\" motion (AGL-278) is visible where it matters.\n */\nexport function PaymentsSettingsCard(props: PaymentsSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [busy, setBusy] = useState(false)\n /**\n * A one-time Stripe Express dashboard link, minted by the connect route on\n * request. Not persisted: login links are single-use and short-lived, so a\n * stored one would be a button that fails the second time it is pressed.\n */\n const [dashboardUrl, setDashboardUrl] = useState<string | null>(null)\n const { org, ready: planReady } = useOrgPlan(hostId)\n /** Bumped by Retry to re-subscribe the profile listen (AGL-1380). */\n const [retryNonce, setRetryNonce] = useState(0)\n const { upgradeHref } = useCommerceEntitlement(hostId, 'commerce')\n /**\n * The OWNER's profile: the Stripe account every money route charges\n * against is the one on the workspace owner's profile. Reading the\n * signed-in member's instead told an admin who is not the owner that a\n * connected store was not set up.\n */\n const ownerUid =\n typeof org?.ownerUid === 'string' && org.ownerUid ? org.ownerUid : undefined\n const { data: profile, status: profileStatus } = useFirestoreDoc<any>(\n // Held at null rather than addressed as `profiles/-pending-` — that\n // sentinel issued a guaranteed-denied read on every pre-auth mount, and\n // a denial lands in `status: 'error'`, which now means something.\n () => (ownerUid ? doc(firestore, 'profiles', ownerUid) : null),\n [firestore, ownerUid, retryNonce],\n )\n const isOwner = Boolean(\n org?.ownerUid && (user as any)?.uid === org.ownerUid,\n )\n /**\n * Three outcomes, not two (AGL-1380). An absent profile doc is the value\n * BEFORE an answer as much as it is the value of a merchant who never\n * connected Stripe, so \"Not set up\" off a falsy `stripeChargesEnabled` is a\n * claim about this org's payment setup made without having heard back. It\n * is wrong in the direction that provokes action: the same falsy value\n * turns the button into \"Set up payments\", which sends a merchant who is\n * already taking money into Stripe onboarding.\n */\n const stripeState: 'pending' | 'error' | 'loaded' =\n !planReady || (ownerUid && profileStatus === 'loading')\n ? 'pending'\n : profileStatus === 'error'\n ? 'error'\n : 'loaded'\n /**\n * WHICH STRIPE WORLD THE STORED ACCOUNT BELONGS TO (AGL-2471).\n *\n * `stripeChargesEnabled: true` was the whole readiness claim, and a\n * production profile carrying it named a TEST-mode account: this card said\n * \"Charges enabled\" about three storefronts that could not take a single\n * payment. Only a literal boolean counts as recorded — the same\n * three-valued reading `merchantAccountIsReady` uses on the server, so the\n * chip and the checkout cannot disagree.\n */\n const modeVerified = typeof profile?.stripeAccountLivemode === 'boolean'\n const chargesConnected =\n stripeState === 'loaded' && Boolean(profile?.stripeChargesEnabled)\n const modeUnverified = chargesConnected && !modeVerified\n const chargesEnabled = chargesConnected && modeVerified\n const physicalPct = Aglyn.resolveTransactionFeePct(org, 'physical')\n const digitalPct = Aglyn.resolveTransactionFeePct(org, 'digital')\n const commerceEnabled = Aglyn.checkEntitlement(org, 'commerce')\n\n const handleConnect = useCallback(async () => {\n setBusy(true)\n try {\n const response = await authorizedFetch(user, '/api/commerce/connect', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId }),\n })\n const payload = await response.json()\n if (response.status === 501) {\n return void enqueueSnackbar(\n 'Payments are not configured on this deployment',\n { variant: 'info', persist: false },\n )\n }\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'Payment setup failed', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n if (payload.chargesEnabled) {\n // \"% who connect Stripe\" — a GTM plan §6 activation metric\n // (AGL-1561). Gated on the TRANSITION, not the state: this handler\n // is a re-entrant create-or-resume, so it answers `chargesEnabled:\n // true` on every subsequent visit to a connected account, and a bare\n // event here would count one merchant once per click forever.\n // `chargesEnabled` is the state read from the profile BEFORE this\n // request, so the event fires only when onboarding actually completed.\n if (!chargesEnabled) trackEvent('stripe_connected', {})\n // CHARGES AND PAYOUTS ARE TWO FLAGS, AND ONLY ONE OF THEM IS THIS\n // SENTENCE (AGL-1997). `chargesEnabled` says Stripe will let the\n // account take money; whether the money can LEAVE is `payoutsEnabled`,\n // which the route answers alongside it. Charges-yes/payouts-no is an\n // ordinary Stripe state — verification pending or lapsed, no payout\n // method — and announcing \"Payments are enabled\" in it is false in the\n // direction that costs the merchant: they sell believing they are\n // paid, and the funds sit in a Connect account that cannot release\n // them. Read three-valued, so only a literal `false` from Stripe\n // downgrades the claim; an absent flag means unasked, not off.\n const payoutsBlocked = payload.payoutsEnabled === false\n // A WARNING THAT NAMES A PROBLEM MUST OFFER THE FIX.\n //\n // Stripe is the only place payouts can be released — an Express\n // account has no password and no direct login — so telling the\n // merchant their funds are stranded and then keeping them here is half\n // an answer. The route now mints the remediation link for exactly this\n // state; going there is the whole point of pressing the button.\n if (payoutsBlocked && payload.url) {\n return void window.location.assign(payload.url)\n }\n // Payouts are flowing, so the link is the Express dashboard: balance,\n // payout schedule, and the reason a payout failed. Held in state\n // rather than followed, because this click was a status check and\n // navigating away from one nobody asked to leave is its own defect.\n if (!payoutsBlocked && typeof payload.dashboardUrl === 'string') {\n setDashboardUrl(payload.dashboardUrl)\n }\n return void enqueueSnackbar(\n payoutsBlocked\n ? 'Connected — payouts are not released yet'\n : 'Payments are enabled',\n {\n variant: payoutsBlocked ? 'warning' : 'success',\n persist: false,\n },\n )\n }\n if (payload.url) window.location.assign(payload.url)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [user, hostId, chargesEnabled, enqueueSnackbar])\n\n return (\n <CardDisplay\n id={PAYMENTS_SETTINGS_ANCHOR}\n header={'Payments'}\n help={pluginDocsHelp('commerceEndToEnd', {\n anchor: '#1-connect-payments',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }}>\n {'Stripe account'}\n </Typography>\n {/*\n No chip at all on error: both labels it could carry — \"Charges\n enabled\" and \"Not set up\" — assert something we failed to find\n out. Whatever Stripe is doing right now it carries on doing.\n */}\n {stripeState === 'error' ? null : (\n <Chip\n size=\"small\"\n label={\n stripeState === 'pending'\n ? 'Checking…'\n : chargesEnabled\n ? 'Charges enabled'\n : modeUnverified\n ? 'Not verified'\n : 'Not set up'\n }\n color={\n stripeState === 'pending'\n ? 'default'\n : chargesEnabled\n ? 'success'\n : modeUnverified\n ? 'error'\n : 'warning'\n }\n variant=\"outlined\"\n />\n )}\n </Stack>\n {stripeState === 'error' ? (\n <Alert\n severity=\"error\"\n action={\n <Button\n color=\"inherit\"\n size=\"small\"\n onClick={() => setRetryNonce((n) => n + 1)}\n >\n {'Retry'}\n </Button>\n }\n >\n {'We couldn’t load your payment setup. This says nothing about ' +\n 'whether payments are on — we could not reach the setting to ' +\n 'find out. Nothing has changed.'}\n </Alert>\n ) : null}\n {/*\n Every line below reads the plan, and an org doc still in flight\n resolves to the FREE tier (AGL-1064) — which would flash \"Selling\n requires a paid plan\" and the wrong fee percentages at a paying\n seller, then correct itself. Say nothing until it is known.\n */}\n {!planReady ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Checking your plan…'}\n </Typography>\n ) : (\n <>\n {!commerceEnabled ? (\n <PrerequisiteNotice href={upgradeHref} actionLabel=\"See plans\">\n {'Selling needs a paid plan. Choose one on Billing, then connect Stripe here.'}\n </PrerequisiteNotice>\n ) : null}\n {/*\n THE LEGAL NAME, not the org's resolved `productName`\n (AGL-2351). This sentence says who takes money off the\n merchant's own Stripe account, and the application fee lands in\n the platform Stripe account — held by the operating entity, not\n by a white-label agency reselling the console. Naming the\n agency here would assert a fee relationship that does not\n exist. `PLATFORM_BRAND_LEGAL_NAME` still configures cleanly for\n a self-host operator, who really is the entity collecting it.\n */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Buyers pay on your own Stripe account; ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} collects a platform fee ` +\n 'per sale based on your plan:'}\n </Typography>\n {/* The DIGITAL rate is not products-only (AGL-2315). A paid\n booking is a service sale and resolves through the same\n `'service'`/digital axis, so a bookings-only merchant pays this\n exact number — and this card was the one place they could read\n their own rate while naming only \"products\". Stated here rather\n than adding a third figure: it is one rate, not two. */}\n <Typography variant=\"body2\">\n {`Physical products: ${physicalPct}% · Digital products, ` +\n `services & bookings: ${digitalPct}%`}\n {physicalPct > 0 || digitalPct > 0 ? (\n <Typography\n component=\"span\"\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {' — higher plans reduce fees to 0%'}\n </Typography>\n ) : null}\n </Typography>\n {/* CARD PROCESSING, PASSED THROUGH AT COST (AGL-2152).\n\n Unconditional, including on the 0% plans, because it is\n exactly those plans where the merchant would otherwise read\n \"0%\" and be surprised by a deduction. Their PLATFORM fee\n really is zero — the figure below is Stripe's own charge for\n taking the payment, which every storefront sale incurs and\n which used to be absorbed silently out of the platform's\n balance rather than passed through.\n\n Named as a range rather than one number because the buyer\n chooses the payment method after the session is created:\n cards settle at the low end, buy-now-pay-later at the high\n end, and the deduction is sized for the dearest so a sale can\n never cost more to process than it collects. A quote's or an\n invoice's pay link offers no buy-now-pay-later, so it carries\n the card rate alone (`PAY_LINK_PROCESSING_PERCENT`). */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Card processing is passed through at cost on top of that: ' +\n `${Aglyn.CARD_PROCESSING_PERCENT}–` +\n `${Aglyn.BNPL_PROCESSING_PERCENT}% + ` +\n `${Aglyn.PROCESSING_FIXED_CENTS}¢ per online ` +\n 'sale, what Stripe charges to take the payment. It is not a ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} margin. Quotes and invoices ` +\n 'are paid by card or wallet, never buy-now-pay-later, so they carry ' +\n `${Aglyn.PAY_LINK_PROCESSING_PERCENT}% + ` +\n `${Aglyn.PROCESSING_FIXED_CENTS}¢.`}\n </Typography>\n {/* WHICH REGISTER TENDERS CARRY THE FEE, AND HOW EACH IS\n COLLECTED (AGL-2111, AGL-4036).\n\n Card and room-charge payments at the register carry the fee;\n cash, gift cards and store credit carry none\n (`CommerceModel.paymentCarriesPlatformFee`). A room charge's\n fee leaves by a door the merchant has never seen money leave\n by, their monthly invoice, so it is said here BEFORE it\n appears there.\n\n Shown only when a rate actually applies: on a 0% plan there is\n nothing to collect either way, and the paragraph would be noise\n on the card of the merchants who upgraded to escape fees. */}\n {physicalPct > 0 || digitalPct > 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'At the register, cash, gift card and store credit payments ' +\n 'carry no fee. On card payments it is deducted from your ' +\n 'Stripe payout; on room-charge payments there is no payout to ' +\n 'deduct from, so it is added to your monthly ' +\n `${Aglyn.PLATFORM_BRAND_LEGAL_NAME} invoice instead.`}\n </Typography>\n ) : null}\n </>\n )}\n {/*\n AGL-2471: connected, and refused by every money door because the\n account was never verified against this deployment's Stripe mode.\n \"Not set up\" would be a lie in the other direction — the merchant\n did set something up — so the card names what is actually wrong and\n what to do about it.\n */}\n {modeUnverified ? (\n <Alert severity=\"error\">\n {'Your Stripe account has not been verified for payments on ' +\n 'this site, so sales will be refused. Set up payments again ' +\n 'to verify it — if it was connected against Stripe test mode, ' +\n 'you will need to connect a live account.'}\n </Alert>\n ) : null}\n {/*\n The button's own label is a claim — \"Set up payments\" tells the\n owner they have none. Withheld until the answer is in, for the same\n reason as the chip (AGL-1380); on error the Retry above is the only\n action offered, because acting on a setup we could not read is how\n a connected merchant gets sent back through onboarding.\n */}\n {/*\n WHERE THE MONEY STOPPED. Mirrored onto this profile by the\n `payout.failed` handler and retired by the next successful payout, so\n it names a live problem rather than a scar. Without it a merchant sold\n into an account that could not release the funds and the card said\n \"Payments are enabled\" the whole time — the storefront looked healthy\n from every angle available to them.\n */}\n {stripeState === 'loaded' && profile?.lastPayoutFailureAtMs ? (\n <Alert severity=\"warning\" variant=\"outlined\">\n {`A payout of $${(\n Number(profile.lastPayoutFailureCents ?? 0) / 100\n ).toFixed(2)} did not reach your bank on ${new Date(\n Number(profile.lastPayoutFailureAtMs),\n ).toLocaleDateString()} — ${String(\n profile.lastPayoutFailureReason ?? 'Stripe did not say why',\n )} The money is still in your Stripe account. Open Stripe to fix your payout details.`}\n </Alert>\n ) : null}\n {!planReady || stripeState !== 'loaded' ? null : isOwner ? (\n <>\n <Button\n size=\"small\"\n variant={chargesEnabled ? 'text' : 'contained'}\n color=\"primary\"\n disabled={busy}\n onClick={handleConnect}\n sx={{ alignSelf: 'flex-start' }}\n >\n {chargesEnabled\n ? 'Refresh status'\n : busy\n ? 'Opening Stripe…'\n : 'Set up payments'}\n </Button>\n {/*\n Where the money actually is. Aglyn records none of it —\n no balance, no payout schedule, and no `payout.failed` handling\n anywhere — so a merchant whose payout bounced has no way to learn\n that from this console. An Express account has no direct login\n either, which leaves a link minted by the platform as the only\n route in. `target=\"_blank\"` because it leaves the app entirely.\n */}\n {dashboardUrl ? (\n <Button\n size=\"small\"\n variant=\"text\"\n color=\"primary\"\n href={dashboardUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n sx={{ alignSelf: 'flex-start' }}\n >\n {'View payouts in Stripe'}\n </Button>\n ) : null}\n </>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Only the organization owner can set up payments.'}\n </Typography>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nPaymentsSettingsCard.displayName = 'PaymentsSettingsCard'\n\nexport default PaymentsSettingsCard\n"],"names":["trackEvent","Aglyn","CardDisplay","useSnackbar","Alert","Button","Chip","Stack","Typography","doc","useCallback","useState","useFirestore","useUser","useFirestoreDoc","useOrgPlan","pluginDocsHelp","authorizedFetch","PrerequisiteNotice","useCommerceEntitlement","PAYMENTS_SETTINGS_ANCHOR","PaymentsSettingsCard","props","profile","hostId","firestore","data","user","enqueueSnackbar","busy","setBusy","dashboardUrl","setDashboardUrl","org","ready","planReady","retryNonce","setRetryNonce","upgradeHref","ownerUid","undefined","status","profileStatus","isOwner","Boolean","uid","stripeState","modeVerified","stripeAccountLivemode","chargesConnected","stripeChargesEnabled","modeUnverified","chargesEnabled","physicalPct","resolveTransactionFeePct","digitalPct","commerceEnabled","checkEntitlement","handleConnect","response","method","headers","body","JSON","stringify","payload","json","variant","persist","ok","error","allowDuplicate","payoutsBlocked","payoutsEnabled","url","window","location","assign","console","id","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","flex","size","label","color","severity","action","onClick","n","href","actionLabel","PLATFORM_BRAND_LEGAL_NAME","component","CARD_PROCESSING_PERCENT","BNPL_PROCESSING_PERCENT","PROCESSING_FIXED_CENTS","PAY_LINK_PROCESSING_PERCENT","lastPayoutFailureAtMs","Number","lastPayoutFailureCents","toFixed","Date","toLocaleDateString","String","lastPayoutFailureReason","disabled","alignSelf","target","rel","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,UAAU,QAAQ,0CAAyC;AACpE,YAAYC,WAAW,eAAc;AACrC,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACtE,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAC7C,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,eAAe,QAAQ,iCAAgC;AAChE,SAASC,UAAU,QAAQ,iCAAgC;AAC3D,SAASC,cAAc,QAAQ,eAAc;AAC7C,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,kBAAkB,QAAQ,gEAA+D;AAClG,SAASC,sBAAsB,QAAQ,kCAA8B;AAMrE,uGAAuG,GACvG,OAAO,MAAMC,2BAA2B,iBAAgB;AAExD;;;;CAIC,GACD,OAAO,SAASC,qBAAqBC,KAAgC;QA2VhDC,iCAIPA;IA9VZ,MAAM,EAAEC,MAAM,EAAE,GAAGF;IACnB,MAAMG,YAAYb;IAClB,MAAM,EAAEc,MAAMC,IAAI,EAAE,GAAGd;IACvB,MAAM,EAAEe,eAAe,EAAE,GAAGzB;IAC5B,MAAM,CAAC0B,MAAMC,QAAQ,GAA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AIC,KAC7CH,OAAOnF,QAAQkF,qBAAqB,GACpCK,kBAAkB,GAAG,GAAG,EAAEC,QAC1BxF,mCAAAA,QAAQyF,uBAAuB,YAA/BzF,mCAAmC,0BACnC,mFAAmF,CAAC;qBAEtF;gBACH,CAACY,aAAaW,gBAAgB,WAAW,OAAOH,wBAC/C;;sCACE,KAACtC;4BACCqF,MAAK;4BACLvB,SAASf,iBAAiB,SAAS;4BACnCwC,OAAM;4BACNqB,UAAUpF;4BACVkE,SAASrC;4BACT6B,IAAI;gCAAE2B,WAAW;4BAAa;sCAE7B9D,iBACG,mBACAvB,OACE,oBACA;;wBAUPE,6BACC,KAAC1B;4BACCqF,MAAK;4BACLvB,SAAQ;4BACRyB,OAAM;4BACNK,MAAMlE;4BACNoF,QAAO;4BACPC,KAAI;4BACJ7B,IAAI;gCAAE2B,WAAW;4BAAa;sCAE7B;6BAED;;mCAGN,KAAC1G;oBAAW2D,SAAQ;oBAAUyB,OAAM;8BACjC;;;;;AAMb;AACAvE,qBAAqBgG,WAAW,GAAG;AAEnC,eAAehG,qBAAoB"}
|
|
@@ -82,6 +82,11 @@ export declare function posHardwareCheckout(user: User, attemptKey: string, body
|
|
|
82
82
|
quantity: number;
|
|
83
83
|
}>;
|
|
84
84
|
shippingMethod: PosHardwareShippingMethod;
|
|
85
|
+
/** The terms of sale accepted and business use confirmed (AGL-4038); both required. */
|
|
86
|
+
hardwareTerms: {
|
|
87
|
+
accepted: boolean;
|
|
88
|
+
businessUse: boolean;
|
|
89
|
+
};
|
|
85
90
|
}): Promise<{
|
|
86
91
|
url: string;
|
|
87
92
|
orderId: string;
|
|
@@ -164,7 +169,11 @@ export declare function staffHardwareOrders(user: User, filter: StaffHardwareFil
|
|
|
164
169
|
canWrite: boolean;
|
|
165
170
|
}>;
|
|
166
171
|
export declare function staffHardwareOrderAction(user: User, body: {
|
|
167
|
-
action: 'update' | 'cancel' | 'refund' | 'refund-return' | 'forget-buyer' | 'decline-return';
|
|
172
|
+
action: 'update' | 'cancel' | 'refund' | 'refund-return' | 'forget-buyer' | 'decline-return' | 'serials' | 'register-reader';
|
|
173
|
+
/** Setting the order up before it ships (AGL-4038): its readers' serial numbers, in reader order. */
|
|
174
|
+
serials?: string[];
|
|
175
|
+
/** The code a reader shows, to register it to the buyer's store (AGL-4038). */
|
|
176
|
+
registrationCode?: string;
|
|
168
177
|
/** An online return's restocking fee, in cents (AGL-4038). */
|
|
169
178
|
restockingFeeCents?: number;
|
|
170
179
|
note?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../libs/plugins/commerce/src/lib/components/console/pos/pos-hardware-api.ts"],"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\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport type {\n PosHardwareAttachment,\n PosHardwareLine,\n PosHardwareOffer,\n PosHardwareOrderShippingMethod,\n PosHardwareOrderSource,\n PosHardwareOrderStatus,\n PosHardwarePaidTo,\n PosHardwareRefund,\n PosHardwareRegisterSale,\n PosHardwareReturnRequest,\n PosHardwareShippingMethod,\n PosHardwareTracking,\n PosHardwareUnit,\n} from '../../../model/pos-hardware'\n\n/*\n * The POS hardware shop's client half (AGL-4038): the Hardware card's calls\n * and the staff page's, so neither component builds a request by hand.\n */\n\ntype User = Parameters<typeof authorizedFetch>[0]\n\nexport class PosHardwareRequestError extends Error {\n constructor(\n message: string,\n readonly status: number,\n /** The route's `reason`, when it names a step the caller takes next. */\n readonly reason?: string,\n ) {\n super(message)\n }\n}\n\n/** One request to a hardware route, refused with the route's own words. */\nexport async function sendPosHardwareRequest<T>(\n user: User,\n url: string,\n init: { method: 'GET' | 'POST'; body?: unknown; attemptKey?: string },\n): Promise<T> {\n const response = await authorizedFetch(user, url, {\n method: init.method,\n headers: {\n ...(init.method === 'POST' ? { 'Content-Type': 'application/json' } : {}),\n ...(init.attemptKey ? { 'Idempotency-Key': init.attemptKey } : {}),\n },\n ...(init.method === 'POST' ? { body: JSON.stringify(init.body ?? {}) } : {}),\n })\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n throw new PosHardwareRequestError(\n String(payload?.error ?? 'Something went wrong'),\n response.status,\n typeof payload?.reason === 'string' ? payload.reason : undefined,\n )\n }\n return payload as T\n}\n\nexport type PosHardwareCatalog =\n | { available: false }\n | {\n available: true\n offers: PosHardwareOffer[]\n shipping: Array<{ method: PosHardwareShippingMethod; label: string; cents: number }>\n automaticTax: boolean\n shipCountries: string[]\n }\n\n/** An order as the Hardware card lists it. */\nexport interface PosHardwareOrderRow {\n id: string\n number: string\n status: PosHardwareOrderStatus\n lines: PosHardwareLine[]\n subtotalCents: number\n shippingCents: number\n shippingLabel: string\n taxCents: number\n totalCents: number\n tracking: PosHardwareTracking | null\n createdAtMs: number\n updatedAtMs: number\n /** Bought in person at the platform's own store (AGL-4038), and its readers still to set up. */\n source?: PosHardwareOrderSource\n discountCents?: number\n readersToSetUp?: number\n refundedCents?: number\n returnRequest?: { state: PosHardwareReturnRequest['state']; requestedAtMs: number; note: string | null } | null\n}\n\nconst SHOP = '/api/commerce/pos-hardware'\n\n/** Leaves the console for Stripe Checkout, which returns to the card. */\nexport function openPosHardwareCheckout(url: string): void {\n window.location.assign(url)\n}\n\nexport function posHardwareCatalog(user: User, hostId: string) {\n return sendPosHardwareRequest<PosHardwareCatalog>(user, SHOP, { method: 'POST', body: { action: 'catalog', hostId } })\n}\n\nexport function posHardwareOrders(user: User, hostId: string) {\n return sendPosHardwareRequest<{ orders: PosHardwareOrderRow[] }>(user, SHOP, {\n method: 'POST',\n body: { action: 'orders', hostId },\n })\n}\n\nexport function posHardwareCheckout(\n user: User,\n attemptKey: string,\n body: {\n hostId: string\n lines: Array<{ sku: string; quantity: number }>\n shippingMethod: PosHardwareShippingMethod\n },\n) {\n return sendPosHardwareRequest<{ url: string; orderId: string }>(user, SHOP, {\n method: 'POST',\n body: { ...body, action: 'checkout' },\n attemptKey,\n })\n}\n\n/** A reader the workspace bought in person, waiting to be set up (AGL-4038). */\nexport interface WaitingReaderOrder extends PosHardwareOrderRow {\n /** The store it is for; empty while the buyer has still to choose. */\n hostId: string\n /** Readers whose serial was taken at the sale: they set themselves up. */\n serialsTaken: number\n}\n\nexport interface WaitingReaders {\n posPlan: boolean\n stores: Array<{ hostId: string; name: string; hasLocation: boolean; setupUrl: string }>\n orders: WaitingReaderOrder[]\n}\n\nexport function posHardwareWaiting(user: User, hostId: string) {\n return sendPosHardwareRequest<WaitingReaders>(user, SHOP, { method: 'POST', body: { action: 'waiting', hostId } })\n}\n\n/** Chooses the store (`hostId`) a reader bought in person is for. */\nexport function posHardwareChooseStore(user: User, hostId: string, orderId: string) {\n return sendPosHardwareRequest<{ ok: true; order: PosHardwareOrderRow }>(user, SHOP, {\n method: 'POST',\n body: { action: 'choose-store', hostId, orderId },\n })\n}\n\nexport function posHardwareMarkSetUp(user: User, hostId: string, orderId: string) {\n return sendPosHardwareRequest<{ ok: true; order: PosHardwareOrderRow }>(user, SHOP, {\n method: 'POST',\n body: { action: 'mark-set-up', hostId, orderId },\n })\n}\n\n/** An order as the staff page lists it. */\nexport interface StaffHardwareOrderRow extends Omit<PosHardwareOrderRow, 'shippingCents' | 'shippingLabel'> {\n orgId: string\n hostId: string\n contactEmail: string | null\n shipping: {\n method: PosHardwareOrderShippingMethod\n label: string\n cents: number\n name: string | null\n phone: string | null\n address: {\n line1: string\n line2?: string\n city: string\n state?: string\n postalCode: string\n country: string\n } | null\n /** What an account erasure left of the address: where tax is sourced. */\n taxRegion?: { country: string; state: string | null; postalCode: string | null } | null\n } | null\n stripeCheckoutSessionId: string | null\n stripePaymentIntentId: string | null\n stripeHardwareOrderId: string | null\n livemode: boolean\n refundPending: boolean\n /** Sold in person at the platform's own store (AGL-4038), and what that sale says. */\n source: PosHardwareOrderSource\n discountCents: number\n posSale: PosHardwareRegisterSale | null\n paidTo: PosHardwarePaidTo | null\n attachment: PosHardwareAttachment | null\n units: PosHardwareUnit[]\n refundedCents: number\n refunds: PosHardwareRefund[]\n returnRequest: PosHardwareReturnRequest | null\n}\n\nconst STAFF = '/api/commerce/admin/hardware-orders'\n\n/** The staff list's filter: one status, every order, or the in-person sales still to attach. */\nexport type StaffHardwareFilter = PosHardwareOrderStatus | '' | 'to-attach' | 'returns'\n\nexport function staffHardwareOrders(user: User, filter: StaffHardwareFilter, after: string | null = null) {\n const params = new URLSearchParams()\n if (filter === 'to-attach') params.set('attach', 'pending')\n else if (filter === 'returns') params.set('returns', 'requested')\n else if (filter) params.set('status', filter)\n if (after) params.set('after', after)\n const search = params.toString()\n return sendPosHardwareRequest<{ orders: StaffHardwareOrderRow[]; next: string | null; pageSize: number; canWrite: boolean }>(\n user,\n search ? `${STAFF}?${search}` : STAFF,\n { method: 'GET' },\n )\n}\n\nexport function staffHardwareOrderAction(\n user: User,\n body: {\n action: 'update' | 'cancel' | 'refund' | 'refund-return' | 'forget-buyer' | 'decline-return'\n /** An online return's restocking fee, in cents (AGL-4038). */\n restockingFeeCents?: number\n note?: string\n orgId: string\n orderId: string\n stripeHardwareOrderId?: string | null\n tracking?: { carrier: string; number: string; url?: string } | null\n status?: PosHardwareOrderStatus\n /** A cancel or a refund: email the buyer about it (AGL-4038). */\n notifyBuyer?: boolean\n },\n) {\n return sendPosHardwareRequest<{\n ok: true\n order: StaffHardwareOrderRow\n /** A cancel or a refund: what became of the buyer's email, `off` when staff chose none. */\n buyerEmail?: 'sent' | 'already' | 'skipped' | 'failed' | 'off'\n }>(user, STAFF, { method: 'POST', body })\n}\n\n/** Asks to return a card reader bought in person, with the reason (AGL-4038). */\nexport function posHardwareRequestReturn(user: User, hostId: string, orderId: string, reason: string) {\n return sendPosHardwareRequest<{ ok: true; order: PosHardwareOrderRow }>(user, SHOP, {\n method: 'POST',\n body: { action: 'request-return', hostId, orderId, reason },\n })\n}\n"],"names":["authorizedFetch","PosHardwareRequestError","Error","message","status","reason","sendPosHardwareRequest","user","url","init","response","method","headers","attemptKey","body","JSON","stringify","payload","json","catch","ok","String","error","undefined","SHOP","openPosHardwareCheckout","window","location","assign","posHardwareCatalog","hostId","action","posHardwareOrders","posHardwareCheckout","posHardwareWaiting","posHardwareChooseStore","orderId","posHardwareMarkSetUp","STAFF","staffHardwareOrders","filter","after","params","URLSearchParams","set","search","toString","staffHardwareOrderAction","posHardwareRequestReturn"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,eAAe,QAAQ,2CAA0C;AAwB1E,OAAO,MAAMC,gCAAgCC;IAC3C,YACEC,OAAe,EACf,AAASC,MAAc,EACvB,sEAAsE,GACtE,AAASC,MAAe,CACxB;QACA,KAAK,CAACF,eAJGC,SAAAA,aAEAC,SAAAA;IAGX;AACF;AAEA,yEAAyE,GACzE,OAAO,eAAeC,uBACpBC,IAAU,EACVC,GAAW,EACXC,IAAqE;QAQfA;IANtD,MAAMC,WAAW,MAAMV,gBAAgBO,MAAMC,KAAK;QAChDG,QAAQF,KAAKE,MAAM;QACnBC,SAAS,aACHH,KAAKE,MAAM,KAAK,SAAS;YAAE,gBAAgB;QAAmB,IAAI,CAAC,GACnEF,KAAKI,UAAU,GAAG;YAAE,mBAAmBJ,KAAKI,UAAU;QAAC,IAAI,CAAC;OAE9DJ,KAAKE,MAAM,KAAK,SAAS;QAAEG,MAAMC,KAAKC,SAAS,EAACP,aAAAA,KAAKK,IAAI,YAATL,aAAa,CAAC;IAAG,IAAI,CAAC;IAE5E,MAAMQ,UAAU,MAAMP,SAASQ,IAAI,GAAGC,KAAK,CAAC,IAAO,CAAA,CAAC,CAAA;IACpD,IAAI,CA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BAAiEC,MAAMiB,MAAM;QAClFb,QAAQ;QACRG,MAAM;YAAEiB,QAAQ;YAAeD;YAAQM;QAAQ;IACjD;AACF;AAyCA,MAAME,QAAQ;AAKd,OAAO,SAASC,oBAAoBhC,IAAU,EAAEiC,MAA2B,EAAEC,QAAuB,IAAI;IACtG,MAAMC,SAAS,IAAIC;IACnB,IAAIH,WAAW,aAAaE,OAAOE,GAAG,CAAC,UAAU;SAC5C,IAAIJ,WAAW,WAAWE,OAAOE,GAAG,CAAC,WAAW;SAChD,IAAIJ,QAAQE,OAAOE,GAAG,CAAC,UAAUJ;IACtC,IAAIC,OAAOC,OAAOE,GAAG,CAAC,SAASH;IAC/B,MAAMI,SAASH,OAAOI,QAAQ;IAC9B,OAAOxC,uBACLC,MACAsC,SAAS,GAAGP,MAAM,CAAC,EAAEO,QAAQ,GAAGP,OAChC;QAAE3B,QAAQ;IAAM;AAEpB;AAEA,OAAO,SAASoC,yBACdxC,IAAU,EACVO,IAYC;IAED,OAAOR,uBAKJC,MAAM+B,OAAO;QAAE3B,QAAQ;QAAQG;IAAK;AACzC;AAEA,+EAA+E,GAC/E,OAAO,SAASkC,yBAAyBzC,IAAU,EAAEuB,MAAc,EAAEM,OAAe,EAAE/B,MAAc;IAClG,OAAOC,uBAAiEC,MAAMiB,MAAM;QAClFb,QAAQ;QACRG,MAAM;YAAEiB,QAAQ;YAAkBD;YAAQM;YAAS/B;QAAO;IAC5D;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/plugins/commerce/src/lib/components/console/pos/pos-hardware-api.ts"],"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\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport type {\n PosHardwareAttachment,\n PosHardwareLine,\n PosHardwareOffer,\n PosHardwareOrderShippingMethod,\n PosHardwareOrderSource,\n PosHardwareOrderStatus,\n PosHardwarePaidTo,\n PosHardwareRefund,\n PosHardwareRegisterSale,\n PosHardwareReturnRequest,\n PosHardwareShippingMethod,\n PosHardwareTracking,\n PosHardwareUnit,\n} from '../../../model/pos-hardware'\n\n/*\n * The POS hardware shop's client half (AGL-4038): the Hardware card's calls\n * and the staff page's, so neither component builds a request by hand.\n */\n\ntype User = Parameters<typeof authorizedFetch>[0]\n\nexport class PosHardwareRequestError extends Error {\n constructor(\n message: string,\n readonly status: number,\n /** The route's `reason`, when it names a step the caller takes next. */\n readonly reason?: string,\n ) {\n super(message)\n }\n}\n\n/** One request to a hardware route, refused with the route's own words. */\nexport async function sendPosHardwareRequest<T>(\n user: User,\n url: string,\n init: { method: 'GET' | 'POST'; body?: unknown; attemptKey?: string },\n): Promise<T> {\n const response = await authorizedFetch(user, url, {\n method: init.method,\n headers: {\n ...(init.method === 'POST' ? { 'Content-Type': 'application/json' } : {}),\n ...(init.attemptKey ? { 'Idempotency-Key': init.attemptKey } : {}),\n },\n ...(init.method === 'POST' ? { body: JSON.stringify(init.body ?? {}) } : {}),\n })\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n throw new PosHardwareRequestError(\n String(payload?.error ?? 'Something went wrong'),\n response.status,\n typeof payload?.reason === 'string' ? payload.reason : undefined,\n )\n }\n return payload as T\n}\n\nexport type PosHardwareCatalog =\n | { available: false }\n | {\n available: true\n offers: PosHardwareOffer[]\n shipping: Array<{ method: PosHardwareShippingMethod; label: string; cents: number }>\n automaticTax: boolean\n shipCountries: string[]\n }\n\n/** An order as the Hardware card lists it. */\nexport interface PosHardwareOrderRow {\n id: string\n number: string\n status: PosHardwareOrderStatus\n lines: PosHardwareLine[]\n subtotalCents: number\n shippingCents: number\n shippingLabel: string\n taxCents: number\n totalCents: number\n tracking: PosHardwareTracking | null\n createdAtMs: number\n updatedAtMs: number\n /** Bought in person at the platform's own store (AGL-4038), and its readers still to set up. */\n source?: PosHardwareOrderSource\n discountCents?: number\n readersToSetUp?: number\n refundedCents?: number\n returnRequest?: { state: PosHardwareReturnRequest['state']; requestedAtMs: number; note: string | null } | null\n}\n\nconst SHOP = '/api/commerce/pos-hardware'\n\n/** Leaves the console for Stripe Checkout, which returns to the card. */\nexport function openPosHardwareCheckout(url: string): void {\n window.location.assign(url)\n}\n\nexport function posHardwareCatalog(user: User, hostId: string) {\n return sendPosHardwareRequest<PosHardwareCatalog>(user, SHOP, { method: 'POST', body: { action: 'catalog', hostId } })\n}\n\nexport function posHardwareOrders(user: User, hostId: string) {\n return sendPosHardwareRequest<{ orders: PosHardwareOrderRow[] }>(user, SHOP, {\n method: 'POST',\n body: { action: 'orders', hostId },\n })\n}\n\nexport function posHardwareCheckout(\n user: User,\n attemptKey: string,\n body: {\n hostId: string\n lines: Array<{ sku: string; quantity: number }>\n shippingMethod: PosHardwareShippingMethod\n /** The terms of sale accepted and business use confirmed (AGL-4038); both required. */\n hardwareTerms: { accepted: boolean; businessUse: boolean }\n },\n) {\n return sendPosHardwareRequest<{ url: string; orderId: string }>(user, SHOP, {\n method: 'POST',\n body: { ...body, action: 'checkout' },\n attemptKey,\n })\n}\n\n/** A reader the workspace bought in person, waiting to be set up (AGL-4038). */\nexport interface WaitingReaderOrder extends PosHardwareOrderRow {\n /** The store it is for; empty while the buyer has still to choose. */\n hostId: string\n /** Readers whose serial was taken at the sale: they set themselves up. */\n serialsTaken: number\n}\n\nexport interface WaitingReaders {\n posPlan: boolean\n stores: Array<{ hostId: string; name: string; hasLocation: boolean; setupUrl: string }>\n orders: WaitingReaderOrder[]\n}\n\nexport function posHardwareWaiting(user: User, hostId: string) {\n return sendPosHardwareRequest<WaitingReaders>(user, SHOP, { method: 'POST', body: { action: 'waiting', hostId } })\n}\n\n/** Chooses the store (`hostId`) a reader bought in person is for. */\nexport function posHardwareChooseStore(user: User, hostId: string, orderId: string) {\n return sendPosHardwareRequest<{ ok: true; order: PosHardwareOrderRow }>(user, SHOP, {\n method: 'POST',\n body: { action: 'choose-store', hostId, orderId },\n })\n}\n\nexport function posHardwareMarkSetUp(user: User, hostId: string, orderId: string) {\n return sendPosHardwareRequest<{ ok: true; order: PosHardwareOrderRow }>(user, SHOP, {\n method: 'POST',\n body: { action: 'mark-set-up', hostId, orderId },\n })\n}\n\n/** An order as the staff page lists it. */\nexport interface StaffHardwareOrderRow extends Omit<PosHardwareOrderRow, 'shippingCents' | 'shippingLabel'> {\n orgId: string\n hostId: string\n contactEmail: string | null\n shipping: {\n method: PosHardwareOrderShippingMethod\n label: string\n cents: number\n name: string | null\n phone: string | null\n address: {\n line1: string\n line2?: string\n city: string\n state?: string\n postalCode: string\n country: string\n } | null\n /** What an account erasure left of the address: where tax is sourced. */\n taxRegion?: { country: string; state: string | null; postalCode: string | null } | null\n } | null\n stripeCheckoutSessionId: string | null\n stripePaymentIntentId: string | null\n stripeHardwareOrderId: string | null\n livemode: boolean\n refundPending: boolean\n /** Sold in person at the platform's own store (AGL-4038), and what that sale says. */\n source: PosHardwareOrderSource\n discountCents: number\n posSale: PosHardwareRegisterSale | null\n paidTo: PosHardwarePaidTo | null\n attachment: PosHardwareAttachment | null\n units: PosHardwareUnit[]\n refundedCents: number\n refunds: PosHardwareRefund[]\n returnRequest: PosHardwareReturnRequest | null\n}\n\nconst STAFF = '/api/commerce/admin/hardware-orders'\n\n/** The staff list's filter: one status, every order, or the in-person sales still to attach. */\nexport type StaffHardwareFilter = PosHardwareOrderStatus | '' | 'to-attach' | 'returns'\n\nexport function staffHardwareOrders(user: User, filter: StaffHardwareFilter, after: string | null = null) {\n const params = new URLSearchParams()\n if (filter === 'to-attach') params.set('attach', 'pending')\n else if (filter === 'returns') params.set('returns', 'requested')\n else if (filter) params.set('status', filter)\n if (after) params.set('after', after)\n const search = params.toString()\n return sendPosHardwareRequest<{ orders: StaffHardwareOrderRow[]; next: string | null; pageSize: number; canWrite: boolean }>(\n user,\n search ? `${STAFF}?${search}` : STAFF,\n { method: 'GET' },\n )\n}\n\nexport function staffHardwareOrderAction(\n user: User,\n body: {\n action: 'update' | 'cancel' | 'refund' | 'refund-return' | 'forget-buyer' | 'decline-return' | 'serials' | 'register-reader'\n /** Setting the order up before it ships (AGL-4038): its readers' serial numbers, in reader order. */\n serials?: string[]\n /** The code a reader shows, to register it to the buyer's store (AGL-4038). */\n registrationCode?: string\n /** An online return's restocking fee, in cents (AGL-4038). */\n restockingFeeCents?: number\n note?: string\n orgId: string\n orderId: string\n stripeHardwareOrderId?: string | null\n tracking?: { carrier: string; number: string; url?: string } | null\n status?: PosHardwareOrderStatus\n /** A cancel or a refund: email the buyer about it (AGL-4038). */\n notifyBuyer?: boolean\n },\n) {\n return sendPosHardwareRequest<{\n ok: true\n order: StaffHardwareOrderRow\n /** A cancel or a refund: what became of the buyer's email, `off` when staff chose none. */\n buyerEmail?: 'sent' | 'already' | 'skipped' | 'failed' | 'off'\n }>(user, STAFF, { method: 'POST', body })\n}\n\n/** Asks to return a card reader bought in person, with the reason (AGL-4038). */\nexport function posHardwareRequestReturn(user: User, hostId: string, orderId: string, reason: string) {\n return sendPosHardwareRequest<{ ok: true; order: PosHardwareOrderRow }>(user, SHOP, {\n method: 'POST',\n body: { action: 'request-return', hostId, orderId, reason },\n })\n}\n"],"names":["authorizedFetch","PosHardwareRequestError","Error","message","status","reason","sendPosHardwareRequest","user","url","init","response","method","headers","attemptKey","body","JSON","stringify","payload","json","catch","ok","String","error","undefined","SHOP","openPosHardwareCheckout","window","location","assign","posHardwareCatalog","hostId","action","posHardwareOrders","posHardwareCheckout","posHardwareWaiting","posHardwareChooseStore","orderId","posHardwareMarkSetUp","STAFF","staffHardwareOrders","filter","after","params","URLSearchParams","set","search","toString","staffHardwareOrderAction","posHardwareRequestReturn"],"mapp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ACLC,MACAsC,SAAS,GAAGP,MAAM,CAAC,EAAEO,QAAQ,GAAGP,OAChC;QAAE3B,QAAQ;IAAM;AAEpB;AAEA,OAAO,SAASoC,yBACdxC,IAAU,EACVO,IAgBC;IAED,OAAOR,uBAKJC,MAAM+B,OAAO;QAAE3B,QAAQ;QAAQG;IAAK;AACzC;AAEA,+EAA+E,GAC/E,OAAO,SAASkC,yBAAyBzC,IAAU,EAAEuB,MAAc,EAAEM,OAAe,EAAE/B,MAAc;IAClG,OAAOC,uBAAiEC,MAAMiB,MAAM;QAClFb,QAAQ;QACRG,MAAM;YAAEiB,QAAQ;YAAkBD;YAAQM;YAAS/B;QAAO;IAC5D;AACF"}
|
|
@@ -304,7 +304,7 @@ function newKey() {
|
|
|
304
304
|
children: /*#__PURE__*/ _jsx(ListItemText, {
|
|
305
305
|
primary: `${row.lines.map((line)=>`${line.quantity} × ${line.name}`).join(', ')} · ${formatPosHardwareCents(row.totalCents)}`,
|
|
306
306
|
secondary: [
|
|
307
|
-
row.registerNumber ?
|
|
307
|
+
row.registerNumber ? `${row.online ? 'Online order' : 'Sale'} #${row.registerNumber}` : row.number,
|
|
308
308
|
new Date(row.createdAtMs).toLocaleString(),
|
|
309
309
|
row.kiosk ? 'at the kiosk' : null,
|
|
310
310
|
row.offline ? 'rung offline' : null,
|
|
@@ -411,7 +411,7 @@ function newKey() {
|
|
|
411
411
|
sx: {
|
|
412
412
|
gridColumn: '1 / -1'
|
|
413
413
|
},
|
|
414
|
-
children: 'Their store has no address for card readers yet. Enter it with the buyer to register the reader now: ' + '
|
|
414
|
+
children: 'Their store has no address for card readers yet. Enter it with the buyer to register the reader now: ' + 'the reader is set up for this country. Or leave it, and they add it on their POS devices card.'
|
|
415
415
|
}),
|
|
416
416
|
/*#__PURE__*/ _jsx(TextField, {
|
|
417
417
|
size: "small",
|