@aglyn/plugins-commerce 1.33.2 → 1.34.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/cart.js +3 -1
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/catalog-organization-card.component.js +82 -69
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/discounts-card.component.js +46 -25
- package/src/lib/components/console/discounts-card.component.js.map +1 -1
- package/src/lib/components/console/gift-cards-card.component.js +81 -55
- package/src/lib/components/console/gift-cards-card.component.js.map +1 -1
- package/src/lib/components/console/host-coupons-card.component.js +36 -25
- package/src/lib/components/console/host-coupons-card.component.js.map +1 -1
- package/src/lib/components/console/locations-card.component.js +53 -32
- package/src/lib/components/console/locations-card.component.js.map +1 -1
- package/src/lib/components/console/member-posts-card.component.js +35 -32
- package/src/lib/components/console/member-posts-card.component.js.map +1 -1
- package/src/lib/components/console/new-store-tax-question.component.d.ts +17 -0
- package/src/lib/components/console/new-store-tax-question.component.js +197 -0
- package/src/lib/components/console/new-store-tax-question.component.js.map +1 -0
- package/src/lib/components/console/payments-settings-card.component.js +132 -5
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-api.d.ts +6 -0
- package/src/lib/components/console/pos/pos-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-tax-notice.component.d.ts +21 -0
- package/src/lib/components/console/pos/pos-tax-notice.component.js +59 -0
- package/src/lib/components/console/pos/pos-tax-notice.component.js.map +1 -0
- package/src/lib/components/console/pos-page.component.js +65 -17
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/registers-card.component.js +21 -13
- package/src/lib/components/console/registers-card.component.js.map +1 -1
- package/src/lib/components/console/reviews-moderation-card.component.js +108 -68
- package/src/lib/components/console/reviews-moderation-card.component.js.map +1 -1
- package/src/lib/components/console/site-member-purchases.component.js +5 -3
- package/src/lib/components/console/site-member-purchases.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.d.ts +2 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscriptions-card.component.js +13 -5
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
- package/src/lib/components/console/suppliers-card.component.js +47 -40
- package/src/lib/components/console/suppliers-card.component.js.map +1 -1
- package/src/lib/components/product-choice-cards.js +2 -1
- package/src/lib/components/product-choice-cards.js.map +1 -1
- package/src/lib/components/product-detail.js +9 -4
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.js +3 -1
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/related-products.js +2 -1
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/store-image-sizing.d.ts +46 -0
- package/src/lib/components/store-image-sizing.js +53 -0
- package/src/lib/components/store-image-sizing.js.map +1 -0
- package/src/lib/components/wishlist.js +2 -1
- package/src/lib/components/wishlist.js.map +1 -1
- package/src/lib/declarations.console-server.js +10 -0
- package/src/lib/declarations.console-server.js.map +1 -1
- package/src/lib/model/commerce-tax-step.d.ts +123 -0
- package/src/lib/model/commerce-tax-step.js +185 -0
- package/src/lib/model/commerce-tax-step.js.map +1 -0
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/payments-setup-status.d.ts +40 -0
- package/src/lib/model/payments-setup-status.js +63 -0
- package/src/lib/model/payments-setup-status.js.map +1 -1
- package/src/lib/model/subscription-view.d.ts +19 -0
- package/src/lib/model/subscription-view.js +16 -0
- package/src/lib/model/subscription-view.js.map +1 -1
- package/src/lib/model/tap-to-pay-launch.d.ts +103 -0
- package/src/lib/model/tap-to-pay-launch.js +148 -0
- package/src/lib/model/tap-to-pay-launch.js.map +1 -0
- package/src/lib/plugin.js +12 -0
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/server/billing-webhook.js +140 -116
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/checkout.js +15 -4
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect-return.d.ts +83 -0
- package/src/lib/server/connect-return.js +105 -0
- package/src/lib/server/connect-return.js.map +1 -0
- package/src/lib/server/connect.d.ts +18 -0
- package/src/lib/server/connect.js +60 -6
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/new-store-tax.d.ts +10 -0
- package/src/lib/server/new-store-tax.js +43 -0
- package/src/lib/server/new-store-tax.js.map +1 -0
- package/src/lib/server/pos-payment.js +3 -2
- package/src/lib/server/pos-payment.js.map +1 -1
- package/src/lib/server/pos-tax-step.d.ts +43 -0
- package/src/lib/server/pos-tax-step.js +55 -0
- package/src/lib/server/pos-tax-step.js.map +1 -0
- package/src/lib/server/pos-terminal-connection-token.d.ts +10 -1
- package/src/lib/server/pos-terminal-connection-token.js +18 -7
- package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
- package/src/lib/server/pos-terminal.d.ts +9 -0
- package/src/lib/server/pos-terminal.js +17 -1
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/site-page-resolver.d.ts +8 -0
- package/src/lib/server/site-page-resolver.js +21 -3
- package/src/lib/server/site-page-resolver.js.map +1 -1
- package/src/lib/server/tap-to-pay-launch-admin.d.ts +18 -0
- package/src/lib/server/tap-to-pay-launch-admin.js +204 -0
- package/src/lib/server/tap-to-pay-launch-admin.js.map +1 -0
- package/src/lib/server/tap-to-pay-launch.d.ts +114 -0
- package/src/lib/server/tap-to-pay-launch.js +408 -0
- package/src/lib/server/tap-to-pay-launch.js.map +1 -0
- package/src/lib/server.js +15 -0
- package/src/lib/server.js.map +1 -1
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
18
18
|
import { CardDisplay } from "@aglyn/shared-ui-jsx";
|
|
19
19
|
import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.component";
|
|
20
|
+
import { OpenableListRow } from "@aglyn/shared-ui-jsx/components/openable-list-row.component";
|
|
21
|
+
import { mdiCancel, mdiCheckCircleOutline, mdiEyeOffOutline, mdiReplyOutline } from "@aglyn/shared-data-mdi";
|
|
20
22
|
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
21
23
|
import { Button, Chip, MenuItem, Rating, Stack, TextField, Typography } from "@mui/material";
|
|
22
24
|
import { collection, doc, limit, orderBy, query, where } from "firebase/firestore";
|
|
@@ -102,6 +104,51 @@ export function ReviewsModerationCard(props) {
|
|
|
102
104
|
hostId,
|
|
103
105
|
write: (batch)=>batch.update(doc(firestore, 'hosts', hostId, 'reviews', review.$id), moderationUpdate(status, reason, Date.now()))
|
|
104
106
|
});
|
|
107
|
+
/*
|
|
108
|
+
* The row's ⋮ menu: the same three actions on every review. One that does
|
|
109
|
+
* not apply to the review's status is disabled with the reason, not hidden.
|
|
110
|
+
*/ const reviewActions = (review)=>{
|
|
111
|
+
const pending = review.status === 'pending';
|
|
112
|
+
const alreadyHidden = review.status === 'rejected' || review.status === 'hidden';
|
|
113
|
+
return [
|
|
114
|
+
{
|
|
115
|
+
key: 'approve',
|
|
116
|
+
label: 'Approve',
|
|
117
|
+
icon: {
|
|
118
|
+
path: mdiCheckCircleOutline.path
|
|
119
|
+
},
|
|
120
|
+
disabled: review.status === 'approved',
|
|
121
|
+
disabledReason: 'Already published',
|
|
122
|
+
onClick: ()=>void setStatus(review, 'approved')
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
key: 'reply',
|
|
126
|
+
label: review.reply ? 'Edit reply' : 'Reply',
|
|
127
|
+
icon: {
|
|
128
|
+
path: mdiReplyOutline.path
|
|
129
|
+
},
|
|
130
|
+
onClick: ()=>{
|
|
131
|
+
var _review_reply;
|
|
132
|
+
setReplyFor(review.$id);
|
|
133
|
+
setReply((_review_reply = review.reply) != null ? _review_reply : '');
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
{
|
|
137
|
+
key: 'hide',
|
|
138
|
+
label: pending ? 'Reject…' : 'Hide…',
|
|
139
|
+
icon: {
|
|
140
|
+
path: pending ? mdiCancel.path : mdiEyeOffOutline.path
|
|
141
|
+
},
|
|
142
|
+
destructive: true,
|
|
143
|
+
disabled: alreadyHidden,
|
|
144
|
+
disabledReason: review.status === 'rejected' ? 'Already rejected' : 'Already hidden',
|
|
145
|
+
onClick: ()=>{
|
|
146
|
+
setHideFor(review.$id);
|
|
147
|
+
setHideReason('spam');
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
];
|
|
151
|
+
};
|
|
105
152
|
return /*#__PURE__*/ _jsx(EntitlementGatedCard, {
|
|
106
153
|
help: reviewsHelp,
|
|
107
154
|
hostId: hostId,
|
|
@@ -155,76 +202,69 @@ export function ReviewsModerationCard(props) {
|
|
|
155
202
|
}) : reviews.map((review)=>/*#__PURE__*/ _jsxs(Stack, {
|
|
156
203
|
spacing: 0.5,
|
|
157
204
|
children: [
|
|
158
|
-
/*#__PURE__*/
|
|
159
|
-
|
|
160
|
-
|
|
205
|
+
/*#__PURE__*/ _jsx(OpenableListRow, {
|
|
206
|
+
label: `Review by ${review.authorName || 'a customer'}`,
|
|
207
|
+
items: reviewActions(review),
|
|
161
208
|
sx: {
|
|
162
|
-
alignItems: '
|
|
209
|
+
alignItems: 'flex-start'
|
|
163
210
|
},
|
|
164
|
-
children:
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
var _review_reply;
|
|
222
|
-
setReplyFor(review.$id);
|
|
223
|
-
setReply((_review_reply = review.reply) != null ? _review_reply : '');
|
|
224
|
-
},
|
|
225
|
-
children: review.reply ? 'Edit reply' : 'Reply'
|
|
226
|
-
})
|
|
227
|
-
]
|
|
211
|
+
children: /*#__PURE__*/ _jsxs(Stack, {
|
|
212
|
+
spacing: 0.5,
|
|
213
|
+
sx: {
|
|
214
|
+
flex: 1,
|
|
215
|
+
minWidth: 0
|
|
216
|
+
},
|
|
217
|
+
children: [
|
|
218
|
+
/*#__PURE__*/ _jsxs(Stack, {
|
|
219
|
+
direction: "row",
|
|
220
|
+
spacing: 1,
|
|
221
|
+
sx: {
|
|
222
|
+
alignItems: 'center',
|
|
223
|
+
minWidth: 0
|
|
224
|
+
},
|
|
225
|
+
children: [
|
|
226
|
+
/*#__PURE__*/ _jsx(Rating, {
|
|
227
|
+
value: review.rating,
|
|
228
|
+
size: "small",
|
|
229
|
+
readOnly: true
|
|
230
|
+
}),
|
|
231
|
+
/*#__PURE__*/ _jsx(Typography, {
|
|
232
|
+
variant: "body2",
|
|
233
|
+
sx: {
|
|
234
|
+
fontWeight: 600,
|
|
235
|
+
minWidth: 0
|
|
236
|
+
},
|
|
237
|
+
noWrap: true,
|
|
238
|
+
children: review.authorName
|
|
239
|
+
}),
|
|
240
|
+
review.verified ? /*#__PURE__*/ _jsx(Chip, {
|
|
241
|
+
label: "Verified",
|
|
242
|
+
size: "small",
|
|
243
|
+
color: "success",
|
|
244
|
+
variant: "outlined"
|
|
245
|
+
}) : null,
|
|
246
|
+
/*#__PURE__*/ _jsx(Chip, {
|
|
247
|
+
label: review.status,
|
|
248
|
+
size: "small",
|
|
249
|
+
variant: "outlined"
|
|
250
|
+
})
|
|
251
|
+
]
|
|
252
|
+
}),
|
|
253
|
+
review.moderationReason && review.moderationReason in REVIEW_MODERATION_REASON_LABELS ? /*#__PURE__*/ _jsx(Typography, {
|
|
254
|
+
variant: "caption",
|
|
255
|
+
color: "text.secondary",
|
|
256
|
+
children: `Hidden: ${REVIEW_MODERATION_REASON_LABELS[review.moderationReason]}`
|
|
257
|
+
}) : null,
|
|
258
|
+
/*#__PURE__*/ _jsx(Typography, {
|
|
259
|
+
variant: "body2",
|
|
260
|
+
color: "text.secondary",
|
|
261
|
+
sx: {
|
|
262
|
+
overflowWrap: 'anywhere'
|
|
263
|
+
},
|
|
264
|
+
children: review.body
|
|
265
|
+
})
|
|
266
|
+
]
|
|
267
|
+
})
|
|
228
268
|
}),
|
|
229
269
|
hideFor === review.$id ? /*#__PURE__*/ _jsxs(Stack, {
|
|
230
270
|
direction: "row",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/reviews-moderation-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n Chip,\n MenuItem,\n Rating,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, doc, limit, orderBy, query, where } from 'firebase/firestore'\nimport { useMemo, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { writeSiteWideChange } from '@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change'\nimport { usePagedCollection } from '@aglyn/tenant-feature-instance'\nimport { EntitlementGatedCard } from './entitlement-gate.component'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n REVIEW_MODERATION_REASONS,\n REVIEW_MODERATION_REASON_LABELS,\n type ReviewModerationReason,\n} from '../../model/product-reviews'\n\nexport interface ReviewsModerationCardProps {\n hostId: string\n}\n\n/**\n * The status a \"Hide\" writes (AGL-3736): a published review is hidden, a\n * pending one is rejected. Either way a content reason goes with it.\n */\nexport function hiddenStatusFor(review: { status?: string }): 'hidden' | 'rejected' {\n return review.status === 'pending' ? 'rejected' : 'hidden'\n}\n\n/**\n * The fields a moderation decision writes. Exactly the keys the Firestore\n * rules let a site editor change on a review: never `verified`, the rating\n * or the text. Approving clears the reason; hiding records it.\n */\nexport function moderationUpdate(\n status: 'approved' | 'hidden' | 'rejected',\n reason: ReviewModerationReason | null,\n nowMs: number,\n): Record<string, unknown> {\n return {\n status,\n moderationReason: status === 'approved' ? null : reason,\n moderatedAtMs: nowMs,\n }\n}\n\n/**\n * Review moderation (AGL-324, AGL-3736): the queue of reviews waiting for\n * approval (unverified ones, under the store's \"anyone\" policy), with\n * approve, hide-for-a-reason and inline seller replies. Verified reviews\n * publish on their own; the merchant may hide one only for a content reason\n * (spam, abuse, off topic, private information) — the FTC's 2024 rule bars\n * suppressing an honest review for being negative — and the reason is kept.\n * Seller replies; approved reviews render on the product-reviews\n * block with the aggregate in JSON-LD.\n *\n * Gated on `productReviews` since AGL-2080. `server/reviews.ts:108` enforces\n * it, and this card rendered identically on Free — an operator could work a\n * moderation queue whose approvals the renderer would never honour.\n */\n\nconst reviewsHelp = pluginDocsHelp('catalog', { anchor: '#review-moderation' })\n\nexport function ReviewsModerationCard(props: ReviewsModerationCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [filter, setFilter] = useState('pending')\n /*\n * The status filter is the QUERY, and the order is the server's.\n *\n * This read `limit(200)` with no `orderBy` and then filtered and sorted in\n * the browser. A limited Firestore query with no ordering returns\n * DOCUMENT-ID order, and reviews are written with `.add()`, so those two\n * hundred were a pseudo-random sample — \"Pending\" showed whichever pending\n * reviews happened to fall in it, which on a busy shop is not the queue and\n * cannot be worked through.\n *\n * Filtering here rather than in the browser is what lets the window shrink:\n * a page of 25 mixed reviews might hold three pending ones, and a card that\n * rendered those three would call it a page while the queue sat behind it.\n * `reviews(status ASC, createdAtMs DESC)` is in\n * cloud/firebase-firestore.indexes.json for exactly this.\n */\n const {\n rows: reviews,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<any>(\n (pageLimit) =>\n query(\n collection(firestore, 'hosts', hostId, 'reviews'),\n ...(filter === 'all' ? [] : [where('status', '==', filter)]),\n orderBy('createdAtMs', 'desc'),\n limit(pageLimit),\n ),\n [firestore, hostId, filter],\n { idField: '$id' },\n )\n const [replyFor, setReplyFor] = useState<string | null>(null)\n const [reply, setReply] = useState('')\n const [hideFor, setHideFor] = useState<string | null>(null)\n const [hideReason, setHideReason] = useState<ReviewModerationReason>('spam')\n\n // An approved review is on the product page — its star aggregate and its\n // reply — so moderating one carries the site's cache drop (AGL-3386).\n const setStatus = (\n review: any,\n status: 'approved' | 'hidden' | 'rejected',\n reason: ReviewModerationReason | null = null,\n ) =>\n writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.update(\n doc(firestore, 'hosts', hostId, 'reviews', review.$id),\n moderationUpdate(status, reason, Date.now()),\n ),\n })\n\n return (\n <EntitlementGatedCard\n help={reviewsHelp}\n hostId={hostId}\n feature=\"productReviews\"\n header={'Review moderation'}\n upsell={\n 'Verified-buyer reviews let customers rate what they bought and ' +\n 'show the star aggregate on your product pages and in search ' +\n 'results.'\n }\n >\n <CardDisplay\n header={'Review moderation'}\n help={reviewsHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <TextField\n label=\"Show\"\n value={filter}\n onChange={(event) => setFilter(event.target.value)}\n size=\"small\"\n select\n sx={{ maxWidth: 180 }}\n >\n <MenuItem value=\"pending\">{'Pending'}</MenuItem>\n <MenuItem value=\"approved\">{'Published'}</MenuItem>\n <MenuItem value=\"hidden\">{'Hidden'}</MenuItem>\n <MenuItem value=\"rejected\">{'Rejected'}</MenuItem>\n <MenuItem value=\"all\">{'All'}</MenuItem>\n </TextField>\n {reviews.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Nothing to moderate.'}\n </Typography>\n ) : (\n reviews.map((review: any) => (\n <Stack key={review.$id} spacing={0.5}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Rating value={review.rating} size=\"small\" readOnly />\n <Typography variant=\"body2\" sx={{ fontWeight: 600 }}>\n {review.authorName}\n </Typography>\n {review.verified ? (\n <Chip label=\"Verified\" size=\"small\" color=\"success\" variant=\"outlined\" />\n ) : null}\n <Chip label={review.status} size=\"small\" variant=\"outlined\" />\n </Stack>\n {review.moderationReason &&\n review.moderationReason in REVIEW_MODERATION_REASON_LABELS ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Hidden: ${\n REVIEW_MODERATION_REASON_LABELS[\n review.moderationReason as ReviewModerationReason\n ]\n }`}\n </Typography>\n ) : null}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {review.body}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n {review.status !== 'approved' ? (\n <Button size=\"small\" onClick={() => setStatus(review, 'approved')}>\n {'Approve'}\n </Button>\n ) : null}\n {review.status !== 'rejected' && review.status !== 'hidden' ? (\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() => {\n setHideFor(review.$id)\n setHideReason('spam')\n }}\n >\n {review.status === 'pending' ? 'Reject…' : 'Hide…'}\n </Button>\n ) : null}\n <Button\n size=\"small\"\n onClick={() => {\n setReplyFor(review.$id)\n setReply(review.reply ?? '')\n }}\n >\n {review.reply ? 'Edit reply' : 'Reply'}\n </Button>\n </Stack>\n {hideFor === review.$id ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TextField\n label=\"Reason\"\n value={hideReason}\n onChange={(event) =>\n setHideReason(event.target.value as ReviewModerationReason)\n }\n size=\"small\"\n select\n sx={{ minWidth: 220 }}\n helperText=\"Reviews can't be hidden for being negative.\"\n >\n {REVIEW_MODERATION_REASONS.map((reason) => (\n <MenuItem key={reason} value={reason}>\n {REVIEW_MODERATION_REASON_LABELS[reason]}\n </MenuItem>\n ))}\n </TextField>\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"error\"\n onClick={async () => {\n await setStatus(review, hiddenStatusFor(review), hideReason)\n setHideFor(null)\n }}\n >\n {review.status === 'pending' ? 'Reject' : 'Hide'}\n </Button>\n <Button size=\"small\" onClick={() => setHideFor(null)}>\n {'Cancel'}\n </Button>\n </Stack>\n ) : null}\n {replyFor === review.$id ? (\n <Stack direction=\"row\" spacing={1}>\n <TextField\n value={reply}\n onChange={(event) => setReply(event.target.value)}\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Public seller reply\"\n />\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n onClick={async () => {\n await writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.update(\n doc(firestore, 'hosts', hostId, 'reviews', review.$id),\n { reply: reply.trim().slice(0, 500) || null },\n ),\n })\n setReplyFor(null)\n enqueueSnackbar('Reply saved', {\n variant: 'success',\n persist: false,\n })\n }}\n >\n {'Save'}\n </Button>\n </Stack>\n ) : null}\n </Stack>\n ))\n )}\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={reviews.length}\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n </Stack>\n </CardDisplay>\n </EntitlementGatedCard>\n )\n}\nReviewsModerationCard.displayName = 'ReviewsModerationCard'\n\nexport default ReviewsModerationCard\n"],"names":["CardDisplay","ListPagination","useSnackbar","Button","Chip","MenuItem","Rating","Stack","TextField","Typography","collection","doc","limit","orderBy","query","where","useState","useFirestore","useUser","writeSiteWideChange","usePagedCollection","EntitlementGatedCard","pluginDocsHelp","REVIEW_MODERATION_REASONS","REVIEW_MODERATION_REASON_LABELS","hiddenStatusFor","review","status","moderationUpdate","reason","nowMs","moderationReason","moderatedAtMs","reviewsHelp","anchor","ReviewsModerationCard","props","hostId","firestore","data","user","enqueueSnackbar","filter","setFilter","rows","reviews","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","replyFor","setReplyFor","reply","setReply","hideFor","setHideFor","hideReason","setHideReason","setStatus","write","batch","update","$id","Date","now","help","feature","header","upsell","contentGutterX","contentGutterY","spacing","label","value","onChange","event","target","size","select","sx","maxWidth","length","variant","color","map","direction","alignItems","rating","readOnly","fontWeight","authorName","verified","body","onClick","minWidth","helperText","flex","placeholder","trim","slice","persist","rowCount","onPageChange","onPageSizeChange","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,WAAW,QAAQ,uBAAsB;AAClD,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,MAAM,EACNC,IAAI,EACJC,QAAQ,EACRC,MAAM,EACNC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,GAAG,EAAEC,KAAK,EAAEC,OAAO,EAAEC,KAAK,EAAEC,KAAK,QAAQ,qBAAoB;AAClF,SAAkBC,QAAQ,QAAQ,QAAO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M7E,OAAOuC,GAAG;kCA6H1B,KAAChE;wBACC8C,MAAMA;wBACNE,UAAUA;wBACVuD,UAAU3D,QAAQuC,MAAM;wBACxBtC,SAASA;wBACT2D,cAAczD;wBACd0D,kBAAkBxD;;;;;;AAM5B;AACAf,sBAAsBwE,WAAW,GAAG;AAEpC,eAAexE,sBAAqB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/reviews-moderation-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { OpenableListRow } from '@aglyn/shared-ui-jsx/components/openable-list-row.component'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport {\n mdiCancel,\n mdiCheckCircleOutline,\n mdiEyeOffOutline,\n mdiReplyOutline,\n} from '@aglyn/shared-data-mdi'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n Chip,\n MenuItem,\n Rating,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { collection, doc, limit, orderBy, query, where } from 'firebase/firestore'\nimport { useMemo, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { writeSiteWideChange } from '@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change'\nimport { usePagedCollection } from '@aglyn/tenant-feature-instance'\nimport { EntitlementGatedCard } from './entitlement-gate.component'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n REVIEW_MODERATION_REASONS,\n REVIEW_MODERATION_REASON_LABELS,\n type ReviewModerationReason,\n} from '../../model/product-reviews'\n\nexport interface ReviewsModerationCardProps {\n hostId: string\n}\n\n/**\n * The status a \"Hide\" writes (AGL-3736): a published review is hidden, a\n * pending one is rejected. Either way a content reason goes with it.\n */\nexport function hiddenStatusFor(review: { status?: string }): 'hidden' | 'rejected' {\n return review.status === 'pending' ? 'rejected' : 'hidden'\n}\n\n/**\n * The fields a moderation decision writes. Exactly the keys the Firestore\n * rules let a site editor change on a review: never `verified`, the rating\n * or the text. Approving clears the reason; hiding records it.\n */\nexport function moderationUpdate(\n status: 'approved' | 'hidden' | 'rejected',\n reason: ReviewModerationReason | null,\n nowMs: number,\n): Record<string, unknown> {\n return {\n status,\n moderationReason: status === 'approved' ? null : reason,\n moderatedAtMs: nowMs,\n }\n}\n\n/**\n * Review moderation (AGL-324, AGL-3736): the queue of reviews waiting for\n * approval (unverified ones, under the store's \"anyone\" policy), with\n * approve, hide-for-a-reason and inline seller replies. Verified reviews\n * publish on their own; the merchant may hide one only for a content reason\n * (spam, abuse, off topic, private information) — the FTC's 2024 rule bars\n * suppressing an honest review for being negative — and the reason is kept.\n * Seller replies; approved reviews render on the product-reviews\n * block with the aggregate in JSON-LD.\n *\n * Gated on `productReviews` since AGL-2080. `server/reviews.ts:108` enforces\n * it, and this card rendered identically on Free — an operator could work a\n * moderation queue whose approvals the renderer would never honour.\n */\n\nconst reviewsHelp = pluginDocsHelp('catalog', { anchor: '#review-moderation' })\n\nexport function ReviewsModerationCard(props: ReviewsModerationCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [filter, setFilter] = useState('pending')\n /*\n * The status filter is the QUERY, and the order is the server's.\n *\n * This read `limit(200)` with no `orderBy` and then filtered and sorted in\n * the browser. A limited Firestore query with no ordering returns\n * DOCUMENT-ID order, and reviews are written with `.add()`, so those two\n * hundred were a pseudo-random sample — \"Pending\" showed whichever pending\n * reviews happened to fall in it, which on a busy shop is not the queue and\n * cannot be worked through.\n *\n * Filtering here rather than in the browser is what lets the window shrink:\n * a page of 25 mixed reviews might hold three pending ones, and a card that\n * rendered those three would call it a page while the queue sat behind it.\n * `reviews(status ASC, createdAtMs DESC)` is in\n * cloud/firebase-firestore.indexes.json for exactly this.\n */\n const {\n rows: reviews,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<any>(\n (pageLimit) =>\n query(\n collection(firestore, 'hosts', hostId, 'reviews'),\n ...(filter === 'all' ? [] : [where('status', '==', filter)]),\n orderBy('createdAtMs', 'desc'),\n limit(pageLimit),\n ),\n [firestore, hostId, filter],\n { idField: '$id' },\n )\n const [replyFor, setReplyFor] = useState<string | null>(null)\n const [reply, setReply] = useState('')\n const [hideFor, setHideFor] = useState<string | null>(null)\n const [hideReason, setHideReason] = useState<ReviewModerationReason>('spam')\n\n // An approved review is on the product page — its star aggregate and its\n // reply — so moderating one carries the site's cache drop (AGL-3386).\n const setStatus = (\n review: any,\n status: 'approved' | 'hidden' | 'rejected',\n reason: ReviewModerationReason | null = null,\n ) =>\n writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.update(\n doc(firestore, 'hosts', hostId, 'reviews', review.$id),\n moderationUpdate(status, reason, Date.now()),\n ),\n })\n\n /*\n * The row's ⋮ menu: the same three actions on every review. One that does\n * not apply to the review's status is disabled with the reason, not hidden.\n */\n const reviewActions = (review: any): RowActionsMenuItem[] => {\n const pending = review.status === 'pending'\n const alreadyHidden = review.status === 'rejected' || review.status === 'hidden'\n return [\n {\n key: 'approve',\n label: 'Approve',\n icon: { path: mdiCheckCircleOutline.path },\n disabled: review.status === 'approved',\n disabledReason: 'Already published',\n onClick: () => void setStatus(review, 'approved'),\n },\n {\n key: 'reply',\n label: review.reply ? 'Edit reply' : 'Reply',\n icon: { path: mdiReplyOutline.path },\n onClick: () => {\n setReplyFor(review.$id)\n setReply(review.reply ?? '')\n },\n },\n {\n key: 'hide',\n label: pending ? 'Reject…' : 'Hide…',\n icon: { path: pending ? mdiCancel.path : mdiEyeOffOutline.path },\n destructive: true,\n disabled: alreadyHidden,\n disabledReason:\n review.status === 'rejected' ? 'Already rejected' : 'Already hidden',\n onClick: () => {\n setHideFor(review.$id)\n setHideReason('spam')\n },\n },\n ]\n }\n\n return (\n <EntitlementGatedCard\n help={reviewsHelp}\n hostId={hostId}\n feature=\"productReviews\"\n header={'Review moderation'}\n upsell={\n 'Verified-buyer reviews let customers rate what they bought and ' +\n 'show the star aggregate on your product pages and in search ' +\n 'results.'\n }\n >\n <CardDisplay\n header={'Review moderation'}\n help={reviewsHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <TextField\n label=\"Show\"\n value={filter}\n onChange={(event) => setFilter(event.target.value)}\n size=\"small\"\n select\n sx={{ maxWidth: 180 }}\n >\n <MenuItem value=\"pending\">{'Pending'}</MenuItem>\n <MenuItem value=\"approved\">{'Published'}</MenuItem>\n <MenuItem value=\"hidden\">{'Hidden'}</MenuItem>\n <MenuItem value=\"rejected\">{'Rejected'}</MenuItem>\n <MenuItem value=\"all\">{'All'}</MenuItem>\n </TextField>\n {reviews.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Nothing to moderate.'}\n </Typography>\n ) : (\n reviews.map((review: any) => (\n <Stack key={review.$id} spacing={0.5}>\n {/* A review has no editor of its own, so the row opens nothing;\n its actions sit in the ⋮ menu. */}\n <OpenableListRow\n label={`Review by ${review.authorName || 'a customer'}`}\n items={reviewActions(review)}\n sx={{ alignItems: 'flex-start' }}\n >\n <Stack spacing={0.5} sx={{ flex: 1, minWidth: 0 }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', minWidth: 0 }}>\n <Rating value={review.rating} size=\"small\" readOnly />\n <Typography variant=\"body2\" sx={{ fontWeight: 600, minWidth: 0 }} noWrap>\n {review.authorName}\n </Typography>\n {review.verified ? (\n <Chip label=\"Verified\" size=\"small\" color=\"success\" variant=\"outlined\" />\n ) : null}\n <Chip label={review.status} size=\"small\" variant=\"outlined\" />\n </Stack>\n {review.moderationReason &&\n review.moderationReason in REVIEW_MODERATION_REASON_LABELS ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Hidden: ${\n REVIEW_MODERATION_REASON_LABELS[\n review.moderationReason as ReviewModerationReason\n ]\n }`}\n </Typography>\n ) : null}\n <Typography\n variant=\"body2\"\n color=\"text.secondary\"\n sx={{ overflowWrap: 'anywhere' }}\n >\n {review.body}\n </Typography>\n </Stack>\n </OpenableListRow>\n {hideFor === review.$id ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TextField\n label=\"Reason\"\n value={hideReason}\n onChange={(event) =>\n setHideReason(event.target.value as ReviewModerationReason)\n }\n size=\"small\"\n select\n sx={{ minWidth: 220 }}\n helperText=\"Reviews can't be hidden for being negative.\"\n >\n {REVIEW_MODERATION_REASONS.map((reason) => (\n <MenuItem key={reason} value={reason}>\n {REVIEW_MODERATION_REASON_LABELS[reason]}\n </MenuItem>\n ))}\n </TextField>\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"error\"\n onClick={async () => {\n await setStatus(review, hiddenStatusFor(review), hideReason)\n setHideFor(null)\n }}\n >\n {review.status === 'pending' ? 'Reject' : 'Hide'}\n </Button>\n <Button size=\"small\" onClick={() => setHideFor(null)}>\n {'Cancel'}\n </Button>\n </Stack>\n ) : null}\n {replyFor === review.$id ? (\n <Stack direction=\"row\" spacing={1}>\n <TextField\n value={reply}\n onChange={(event) => setReply(event.target.value)}\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Public seller reply\"\n />\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n onClick={async () => {\n await writeSiteWideChange({\n firestore,\n user,\n hostId,\n write: (batch) =>\n batch.update(\n doc(firestore, 'hosts', hostId, 'reviews', review.$id),\n { reply: reply.trim().slice(0, 500) || null },\n ),\n })\n setReplyFor(null)\n enqueueSnackbar('Reply saved', {\n variant: 'success',\n persist: false,\n })\n }}\n >\n {'Save'}\n </Button>\n </Stack>\n ) : null}\n </Stack>\n ))\n )}\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={reviews.length}\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n </Stack>\n </CardDisplay>\n </EntitlementGatedCard>\n )\n}\nReviewsModerationCard.displayName = 'ReviewsModerationCard'\n\nexport default ReviewsModerationCard\n"],"names":["CardDisplay","ListPagination","OpenableListRow","mdiCancel","mdiCheckCircleOutline","mdiEyeOffOutline","mdiReplyOutline","useSnackbar","Button","Chip","MenuItem","Rating","Stack","TextField","Typography","collection","doc","limit","orderBy","query","where","useState","useFirestore","useUser","writeSiteWideChange","usePagedCollection","EntitlementGatedCard","pluginDocsHelp","REVIEW_MODERATION_REASONS","REVIEW_MODERATION_REASON_LABELS","hiddenStatusFor","review","status","moderationUpdate","reason","nowMs","moderationReason","moderatedAtMs","reviewsHelp","anchor","ReviewsModerationCard","props","hostId","firestore","data","user","enqueueSnackbar","filter","setFilter","rows","reviews","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","replyFor","setReplyFor","reply","setReply","hideFor","setHideFor","hideReason","setHideReason","setStatus","write","batch","update","$id","Date","now","reviewActions","pending","alreadyHidden","key","label","icon","path","disabled","disabledReason","onClick","destructive","help","feature","header","upsell","contentGutterX","contentGutterY","spacing","value","onChange","event","target","size","select","sx","maxWidth","length","variant","color","map","authorName","items","alignItems","flex","minWidth","direction","rating","readOnly","fontWeight","noWrap","verified","overflowWrap","body","helperText","placeholder","trim","slice","persist","rowCount","onPageChange","onPageSizeChange","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,WAAW,QAAQ,uBAAsB;AAClD,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,eAAe,QAAQ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
|
@@ -23,7 +23,9 @@ import { collection, documentId, limit, orderBy, query, where } from "firebase/f
|
|
|
23
23
|
import { useEffect, useMemo, useState } from "react";
|
|
24
24
|
import { splitOrderReversal } from "../../model/commerce-dispute.js";
|
|
25
25
|
import { computeLifetimePurchaseCents } from "../../model/site-member-purchases.js";
|
|
26
|
+
import { saleMoneyText } from "../../model/commerce-currency.js";
|
|
26
27
|
const usd = (cents)=>`$${(cents / 100).toFixed(2)}`;
|
|
28
|
+
/** An amount in the currency it was charged in (AGL-4257); USD when unrecorded. */ const charged = (cents, currency)=>typeof currency === 'string' && currency && currency.toLowerCase() !== 'usd' ? saleMoneyText(cents, currency) : usd(cents);
|
|
27
29
|
/**
|
|
28
30
|
* How many order documents this reads for one member.
|
|
29
31
|
*
|
|
@@ -225,7 +227,7 @@ const orderCreatedMs = (order)=>{
|
|
|
225
227
|
flex: 1
|
|
226
228
|
},
|
|
227
229
|
noWrap: true,
|
|
228
|
-
children: `${orderNumber(order)} · ${
|
|
230
|
+
children: `${orderNumber(order)} · ${charged(Number((_ref = (_ref1 = (_order_totals = order.totals) == null ? void 0 : _order_totals.totalCents) != null ? _ref1 : order.amountCents) != null ? _ref : 0) || 0, order.currency)}`
|
|
229
231
|
}),
|
|
230
232
|
/*#__PURE__*/ _jsx(Chip, {
|
|
231
233
|
label: String((_order_status = order.status) != null ? _order_status : 'paid').replace('_', ' '),
|
|
@@ -292,7 +294,7 @@ const orderCreatedMs = (order)=>{
|
|
|
292
294
|
noWrap: true,
|
|
293
295
|
children: [
|
|
294
296
|
(_ref = (_productNames_subscription_productId = productNames[subscription.productId]) != null ? _productNames_subscription_productId : subscription.productId) != null ? _ref : 'Subscription',
|
|
295
|
-
((_subscription_totals = subscription.totals) == null ? void 0 : _subscription_totals.totalCents) != null ? ` · ${
|
|
297
|
+
((_subscription_totals = subscription.totals) == null ? void 0 : _subscription_totals.totalCents) != null ? ` · ${charged(Number(subscription.totals.totalCents) || 0, subscription.currency)}${subscription.interval ? `/${subscription.interval}` : ''}` : ''
|
|
296
298
|
]
|
|
297
299
|
}),
|
|
298
300
|
/*#__PURE__*/ _jsxs(Typography, {
|
|
@@ -300,7 +302,7 @@ const orderCreatedMs = (order)=>{
|
|
|
300
302
|
color: "text.secondary",
|
|
301
303
|
children: [
|
|
302
304
|
subscription.currentPeriodEndMs ? `Renews ${new Date(Number(subscription.currentPeriodEndMs)).toLocaleDateString()}` : '—',
|
|
303
|
-
Number((_subscription_invoicesCount = subscription.invoicesCount) != null ? _subscription_invoicesCount : 0) > 0 ? ` · ${
|
|
305
|
+
Number((_subscription_invoicesCount = subscription.invoicesCount) != null ? _subscription_invoicesCount : 0) > 0 ? ` · ${charged(Number(subscription.paidCents) || 0, subscription.currency)} paid over ${Number(subscription.invoicesCount) === 1 ? '1 invoice' : `${Number(subscription.invoicesCount)} invoices`}` : ''
|
|
304
306
|
]
|
|
305
307
|
})
|
|
306
308
|
]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/site-member-purchases.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 type { ConsoleSiteMemberZoneProps } from '@aglyn/aglyn'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport {\n ceilingedWindow,\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport { Chip, Divider, Stack, Typography } from '@mui/material'\nimport {\n collection,\n documentId,\n limit,\n orderBy,\n query,\n where,\n} from 'firebase/firestore'\nimport { useEffect, useMemo, useState } from 'react'\nimport { splitOrderReversal } from '../../model/commerce-dispute'\nimport { computeLifetimePurchaseCents } from '../../model/site-member-purchases'\n\nconst usd = (cents: number) => `$${(cents / 100).toFixed(2)}`\n\n/**\n * How many order documents this reads for one member.\n *\n * A CEILING, not a page size: the lifetime-purchase figure above the list is\n * summed from these rows, so every one it intends to count has to be held. A\n * server page would make that headline number the total of ten orders and\n * print it as a lifetime.\n */\nconst ORDER_CEILING = 100\n/** The same, for the subscriptions this member holds. */\nconst SUBSCRIPTION_CEILING = 25\n\n/**\n * The reversal suffix on one order row, split by the door the money left\n * through (AGL-1810). `refundedCents` carries a lost chargeback as well as a\n * refund (AGL-1787 puts both there deliberately), so rendering the whole\n * figure as \"refunded\" told the merchant they chose a reversal a bank took.\n * `computeLifetimePurchaseCents` keeps netting the total; only the label\n * splits.\n */\nconst reversalSuffix = (order: any) => {\n const { refundedCents, chargedBackCents } = splitOrderReversal(order)\n return (\n (refundedCents ? ` · refunded ${usd(refundedCents)}` : '') +\n (chargedBackCents ? ` · charged back ${usd(chargedBackCents)}` : '')\n )\n}\n\n/** Display order number: v1 sequential `#1042`, else a doc-id stub. */\nconst orderNumber = (order: any) =>\n order.number != null\n ? `#${order.number}`\n : `#${String(order.$id ?? '').slice(-6).toUpperCase()}`\n\nconst orderCreatedMs = (order: any) =>\n Number(order.createdAtMs ?? (order.createdAt?.seconds ?? 0) * 1000) || 0\n\n/**\n * What a site user bought (AGL-546): the lifetime purchase total, the order\n * history (the payment records — Stripe intent id and refunds included) and\n * storefront subscriptions — the `siteMember` zone of the account's drawer.\n *\n * Orders match by email (mirrors membership-account, AGL-294) and sort\n * client-side. The QUERY orders on the document name: `orderBy('createdAt')`\n * would want a composite index and, worse, would drop every order missing the\n * field, while an equality filter plus `orderBy(documentId())` rides the\n * automatic single-field index and can drop nothing — a document's name\n * cannot be absent. That makes the window total rather than a pseudo-random\n * hundred, which is what the newest-first sort below was quietly disguising.\n * `orders` reads are admin/editor-only in rules (AGL-502), so viewers get a\n * note instead of history.\n *\n * One section per element, as a fragment: the zone is `bare`, and the drawer's\n * own column spaces what it holds.\n */\nexport function SiteMemberPurchases(props: ConsoleSiteMemberZoneProps) {\n const { hostId, member } = props\n const firestore = useFirestore()\n const memberId = String(member.$id ?? '')\n const email = String(member['email'] ?? '')\n\n const { data: orderDocs, status: ordersStatus } = useFirestoreCollection<any>(\n () =>\n email\n ? query(\n collection(firestore, 'hosts', hostId, 'orders'),\n where('customerEmail', '==', email),\n orderBy(documentId()),\n // One document past the ceiling, so \"this member has more\" is a\n // fact. `length === 100` cannot tell a member with exactly a\n // hundred orders from one with a thousand, and the difference is\n // whether the lifetime figure above is a total or a floor.\n limit(ORDER_CEILING + 1),\n )\n : null,\n [firestore, hostId, email],\n { idField: '$id' },\n )\n const { rows: readOrders, truncated: ordersTruncated } = ceilingedWindow<any>(\n orderDocs,\n ORDER_CEILING,\n )\n const orders = useMemo(\n () =>\n [...readOrders].sort((a, b) => orderCreatedMs(b) - orderCreatedMs(a)),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [orderDocs],\n )\n const lifetimeCents = useMemo(\n () => computeLifetimePurchaseCents(orders),\n [orders],\n )\n /**\n * The order query failed AND nothing came back with it (AGL-1066).\n *\n * The copy this gates blames the reader's ROLE, which is the right\n * explanation for the denial this was written for — orders are\n * admin/editor-only in rules. It is the wrong explanation once a stale\n * SESSION can push a listen to `'error'` too, and flatly wrong when\n * `persistentLocalCache` is still serving the rows: telling someone their\n * role is insufficient while their orders sit right there is a support\n * ticket about permissions that was never about permissions.\n */\n const ordersUnreadable = ordersStatus === 'error' && orders.length === 0\n\n const { data: subscriptionDocs } = useFirestoreCollection<any>(\n () =>\n email\n ? query(\n collection(firestore, 'hosts', hostId, 'subscriptions'),\n where('customerEmail', '==', email),\n // The same decision as the orders above, for the same reason: a\n // subscription written without `createdAt` would be hidden by a\n // field ordering rather than mis-sorted by it.\n orderBy(documentId()),\n limit(SUBSCRIPTION_CEILING + 1),\n )\n : null,\n [firestore, hostId, email],\n { idField: '$id' },\n )\n const { rows: subscriptions, truncated: subscriptionsTruncated } =\n ceilingedWindow<any>(subscriptionDocs, SUBSCRIPTION_CEILING)\n // Product names for subscriptions, loaded only when any exist.\n const { data: productDocs } = useFirestoreCollection<any>(\n () =>\n email && (subscriptionDocs?.length ?? 0) > 0\n ? query(\n collection(firestore, 'hosts', hostId, 'products'),\n // A LOOKUP, not a list — but the same ordering decision, so the\n // hundred it reads is a reachable hundred rather than a sample,\n // and a product past it degrades a subscription's label to its\n // id rather than hiding the subscription.\n orderBy(documentId()),\n limit(100),\n )\n : null,\n [firestore, hostId, email, (subscriptionDocs?.length ?? 0) > 0],\n { idField: '$id' },\n )\n /*==========================================\n * BOTH LISTS PAGE IN MEMORY.\n *\n * Each ceiling is held whole, which is what lets the orders sort\n * newest-first and the lifetime figure sum over all of them. A server page\n * would have made both about ten rows instead of about this member.\n *=========================================*/\n const [orderPage, setOrderPage] = useState(0)\n const [orderPageSize, setOrderPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleOrders = useMemo(\n () =>\n orders.slice(\n orderPage * orderPageSize,\n orderPage * orderPageSize + orderPageSize,\n ),\n [orders, orderPage, orderPageSize],\n )\n const [subscriptionPage, setSubscriptionPage] = useState(0)\n const [subscriptionPageSize, setSubscriptionPageSize] = useState(\n TABLE_PAGE_SIZE_DEFAULT,\n )\n const visibleSubscriptions = useMemo(\n () =>\n subscriptions.slice(\n subscriptionPage * subscriptionPageSize,\n subscriptionPage * subscriptionPageSize + subscriptionPageSize,\n ),\n [subscriptions, subscriptionPage, subscriptionPageSize],\n )\n /*\n * A different member starts at page one. The drawer is reused for whoever\n * is selected, so without this the next member opens three pages into a\n * history they may not have — which renders as an empty list and reads as\n * \"this person never bought anything\".\n */\n useEffect(() => {\n setOrderPage(0)\n setSubscriptionPage(0)\n }, [memberId])\n\n const productNames = useMemo(() => {\n const map: Record<string, string> = {}\n for (const product of productDocs ?? []) {\n map[product.$id] = product.name ?? product.$id\n }\n return map\n }, [productDocs])\n\n return (\n <>\n <Divider textAlign=\"left\">{'Lifetime purchases'}</Divider>\n <Typography variant=\"h6\">\n {/*\n \"at least\", or nothing at all. This figure is summed over the order\n WINDOW, so once the probe finds an order past the ceiling it is a\n lower bound — and a lower bound printed as a lifetime is the number\n a support agent quotes back to the customer.\n */}\n {ordersUnreadable\n ? '—'\n : `${ordersTruncated ? 'at least ' : ''}${usd(lifetimeCents)}`}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Charged order totals minus refunds; pending and canceled ' +\n 'orders excluded.'}\n {ordersTruncated\n ? ` Summed over the ${ORDER_CEILING} orders read here; this ` +\n 'member has more.'\n : ''}\n </Typography>\n\n <Divider textAlign=\"left\">{'Orders'}</Divider>\n {ordersUnreadable ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Order history takes the \"See orders and webhooks\" permission on this site.'}\n </Typography>\n ) : orders.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No orders yet.'}\n </Typography>\n ) : (\n visibleOrders.map((order: any) => (\n <Stack key={order.$id} spacing={0}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }} noWrap>\n {`${orderNumber(order)} · ${usd(\n Number(order.totals?.totalCents ?? order.amountCents ?? 0) ||\n 0,\n )}`}\n </Typography>\n <Chip\n label={String(order.status ?? 'paid').replace('_', ' ')}\n size=\"small\"\n variant=\"outlined\"\n />\n </Stack>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {orderCreatedMs(order)\n ? new Date(orderCreatedMs(order)).toLocaleDateString()\n : '—'}\n {reversalSuffix(order)}\n </Typography>\n {order.paymentIntentId ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n sx={{ fontFamily: 'monospace' }}\n noWrap\n >\n {order.paymentIntentId}\n </Typography>\n ) : null}\n </Stack>\n ))\n )}\n {ordersUnreadable || orders.length === 0 ? null : (\n <ListPagination\n page={orderPage}\n pageSize={orderPageSize}\n rowCount={visibleOrders.length}\n // The orders held here — a slice of rows already read, so the\n // total is exact for the window. The lifetime caption above is\n // where the window's own shortfall is stated.\n count={orders.length}\n onPageChange={setOrderPage}\n onPageSizeChange={setOrderPageSize}\n />\n )}\n\n {subscriptions.length > 0 ? (\n <>\n <Divider textAlign=\"left\">{'Subscriptions'}</Divider>\n {visibleSubscriptions.map((subscription: any) => (\n <Stack\n key={subscription.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {/*\n * The amount (AGL-1732). This row named the product and the\n * renewal date and stopped, and no other console surface\n * carried the figure either — orders, analytics and the CSV\n * all read `orders`, which a subscription sale does not\n * create. Subscriptions written before that fix have no\n * `totals`, so the amount is omitted rather than shown as\n * $0.00.\n */}\n {productNames[subscription.productId] ??\n subscription.productId ??\n 'Subscription'}\n {subscription.totals?.totalCents != null\n ? ` · ${usd(Number(subscription.totals.totalCents) || 0)}${\n subscription.interval ? `/${subscription.interval}` : ''\n }`\n : ''}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {subscription.currentPeriodEndMs\n ? `Renews ${new Date(\n Number(subscription.currentPeriodEndMs),\n ).toLocaleDateString()}`\n : '—'}\n {/*\n * What this subscriber has actually paid, across every cycle\n * (AGL-1743). Omitted, not shown as 0, for subscriptions\n * whose cycles all predate `invoice.payment_succeeded`\n * being handled: those invoices are recoverable only from\n * Stripe.\n */}\n {Number(subscription.invoicesCount ?? 0) > 0\n ? ` · ${usd(Number(subscription.paidCents) || 0)} paid over ${\n Number(subscription.invoicesCount) === 1\n ? '1 invoice'\n : `${Number(subscription.invoicesCount)} invoices`\n }`\n : ''}\n </Typography>\n </Stack>\n <Chip\n label={String(subscription.status ?? 'active')}\n size=\"small\"\n variant=\"outlined\"\n color={subscription.status === 'active' ? 'success' : 'default'}\n />\n </Stack>\n ))}\n <ListPagination\n page={subscriptionPage}\n pageSize={subscriptionPageSize}\n rowCount={visibleSubscriptions.length}\n // This member's subscriptions, in full for the window.\n count={subscriptions.length}\n onPageChange={setSubscriptionPage}\n onPageSizeChange={setSubscriptionPageSize}\n />\n {subscriptionsTruncated ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Showing ${SUBSCRIPTION_CEILING} subscriptions; this ` +\n 'member has more.'}\n </Typography>\n ) : null}\n </>\n ) : null}\n </>\n )\n}\nSiteMemberPurchases.displayName = 'SiteMemberPurchases'\n\nexport default SiteMemberPurchases\n"],"names":["ListPagination","TABLE_PAGE_SIZE_DEFAULT","ceilingedWindow","useFirestore","useFirestoreCollection","Chip","Divider","Stack","Typography","collection","documentId","limit","orderBy","query","where","useEffect","useMemo","useState","splitOrderReversal","computeLifetimePurchaseCents","usd","cents","toFixed","ORDER_CEILING","SUBSCRIPTION_CEILING","reversalSuffix","order","refundedCents","chargedBackCents","orderNumber","number","String","$id","slice","toUpperCase","orderCreatedMs","Number","createdAtMs","createdAt","seconds","SiteMemberPurchases","props","member","hostId","firestore","memberId","email","data","orderDocs","status","ordersStatus","idField","rows","readOrders","truncated","ordersTruncated","orders","sort","a","b","lifetimeCents","ordersUnreadable","length","subscriptionDocs","subscriptions","subscriptionsTruncated","productDocs","orderPage","setOrderPage","orderPageSize","setOrderPageSize","visibleOrders","subscriptionPage","setSubscriptionPage","subscriptionPageSize","setSubscriptionPageSize","visibleSubscriptions","productNames","map","product","name","textAlign","variant","color","spacing","direction","sx","alignItems","flex","noWrap","totals","totalCents","amountCents","label","replace","size","Date","toLocaleDateString","paymentIntentId","fontFamily","page","pageSize","rowCount","count","onPageChange","onPageSizeChange","subscription","minWidth","productId","interval","currentPeriodEndMs","invoicesCount","paidCents","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAC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F;;;sDAEN,MAACrG;4CAAW0E,SAAQ;4CAAUC,OAAM;;gDACjCuB,aAAaI,kBAAkB,GAC5B,CAAC,OAAO,EAAE,IAAId,KACZ5D,OAAOsE,aAAaI,kBAAkB,GACtCb,kBAAkB,IAAI,GACxB;gDAQH7D,QAAOsE,8BAAAA,aAAaK,aAAa,YAA1BL,8BAA8B,KAAK,IACvC,CAAC,GAAG,EAAEtF,IAAIgB,OAAOsE,aAAaM,SAAS,KAAK,GAAG,WAAW,EACxD5E,OAAOsE,aAAaK,aAAa,MAAM,IACnC,cACA,GAAG3E,OAAOsE,aAAaK,aAAa,EAAE,SAAS,CAAC,EACpD,GACF;;;;;8CAGR,KAAC1G;oCACCwF,OAAO9D,QAAO2E,uBAAAA,aAAazD,MAAM,YAAnByD,uBAAuB;oCACrCX,MAAK;oCACLb,SAAQ;oCACRC,OAAOuB,aAAazD,MAAM,KAAK,WAAW,YAAY;;;2BAnDnDyD,aAAa1E,GAAG;;kCAuDzB,KAAChC;wBACCoG,MAAM5B;wBACN6B,UAAU3B;wBACV4B,UAAU1B,qBAAqBd,MAAM;wBACrC,uDAAuD;wBACvDyC,OAAOvC,cAAcF,MAAM;wBAC3B0C,cAAc/B;wBACdgC,kBAAkB9B;;oBAEnBV,uCACC,KAACzD;wBAAW0E,SAAQ;wBAAUC,OAAM;kCACjC,CAAC,QAAQ,EAAE3D,qBAAqB,qBAAqB,CAAC,GACrD;yBAEF;;iBAEJ;;;AAGV;AACAgB,oBAAoByE,WAAW,GAAG;AAElC,eAAezE,oBAAmB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/site-member-purchases.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 type { ConsoleSiteMemberZoneProps } from '@aglyn/aglyn'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport {\n ceilingedWindow,\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport { Chip, Divider, Stack, Typography } from '@mui/material'\nimport {\n collection,\n documentId,\n limit,\n orderBy,\n query,\n where,\n} from 'firebase/firestore'\nimport { useEffect, useMemo, useState } from 'react'\nimport { splitOrderReversal } from '../../model/commerce-dispute'\nimport { computeLifetimePurchaseCents } from '../../model/site-member-purchases'\nimport { saleMoneyText } from '../../model/commerce-currency'\n\nconst usd = (cents: number) => `$${(cents / 100).toFixed(2)}`\n/** An amount in the currency it was charged in (AGL-4257); USD when unrecorded. */\nconst charged = (cents: number, currency: unknown) =>\n typeof currency === 'string' && currency && currency.toLowerCase() !== 'usd'\n ? saleMoneyText(cents, currency)\n : usd(cents)\n\n/**\n * How many order documents this reads for one member.\n *\n * A CEILING, not a page size: the lifetime-purchase figure above the list is\n * summed from these rows, so every one it intends to count has to be held. A\n * server page would make that headline number the total of ten orders and\n * print it as a lifetime.\n */\nconst ORDER_CEILING = 100\n/** The same, for the subscriptions this member holds. */\nconst SUBSCRIPTION_CEILING = 25\n\n/**\n * The reversal suffix on one order row, split by the door the money left\n * through (AGL-1810). `refundedCents` carries a lost chargeback as well as a\n * refund (AGL-1787 puts both there deliberately), so rendering the whole\n * figure as \"refunded\" told the merchant they chose a reversal a bank took.\n * `computeLifetimePurchaseCents` keeps netting the total; only the label\n * splits.\n */\nconst reversalSuffix = (order: any) => {\n const { refundedCents, chargedBackCents } = splitOrderReversal(order)\n return (\n (refundedCents ? ` · refunded ${usd(refundedCents)}` : '') +\n (chargedBackCents ? ` · charged back ${usd(chargedBackCents)}` : '')\n )\n}\n\n/** Display order number: v1 sequential `#1042`, else a doc-id stub. */\nconst orderNumber = (order: any) =>\n order.number != null\n ? `#${order.number}`\n : `#${String(order.$id ?? '').slice(-6).toUpperCase()}`\n\nconst orderCreatedMs = (order: any) =>\n Number(order.createdAtMs ?? (order.createdAt?.seconds ?? 0) * 1000) || 0\n\n/**\n * What a site user bought (AGL-546): the lifetime purchase total, the order\n * history (the payment records — Stripe intent id and refunds included) and\n * storefront subscriptions — the `siteMember` zone of the account's drawer.\n *\n * Orders match by email (mirrors membership-account, AGL-294) and sort\n * client-side. The QUERY orders on the document name: `orderBy('createdAt')`\n * would want a composite index and, worse, would drop every order missing the\n * field, while an equality filter plus `orderBy(documentId())` rides the\n * automatic single-field index and can drop nothing — a document's name\n * cannot be absent. That makes the window total rather than a pseudo-random\n * hundred, which is what the newest-first sort below was quietly disguising.\n * `orders` reads are admin/editor-only in rules (AGL-502), so viewers get a\n * note instead of history.\n *\n * One section per element, as a fragment: the zone is `bare`, and the drawer's\n * own column spaces what it holds.\n */\nexport function SiteMemberPurchases(props: ConsoleSiteMemberZoneProps) {\n const { hostId, member } = props\n const firestore = useFirestore()\n const memberId = String(member.$id ?? '')\n const email = String(member['email'] ?? '')\n\n const { data: orderDocs, status: ordersStatus } = useFirestoreCollection<any>(\n () =>\n email\n ? query(\n collection(firestore, 'hosts', hostId, 'orders'),\n where('customerEmail', '==', email),\n orderBy(documentId()),\n // One document past the ceiling, so \"this member has more\" is a\n // fact. `length === 100` cannot tell a member with exactly a\n // hundred orders from one with a thousand, and the difference is\n // whether the lifetime figure above is a total or a floor.\n limit(ORDER_CEILING + 1),\n )\n : null,\n [firestore, hostId, email],\n { idField: '$id' },\n )\n const { rows: readOrders, truncated: ordersTruncated } = ceilingedWindow<any>(\n orderDocs,\n ORDER_CEILING,\n )\n const orders = useMemo(\n () =>\n [...readOrders].sort((a, b) => orderCreatedMs(b) - orderCreatedMs(a)),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [orderDocs],\n )\n const lifetimeCents = useMemo(\n () => computeLifetimePurchaseCents(orders),\n [orders],\n )\n /**\n * The order query failed AND nothing came back with it (AGL-1066).\n *\n * The copy this gates blames the reader's ROLE, which is the right\n * explanation for the denial this was written for — orders are\n * admin/editor-only in rules. It is the wrong explanation once a stale\n * SESSION can push a listen to `'error'` too, and flatly wrong when\n * `persistentLocalCache` is still serving the rows: telling someone their\n * role is insufficient while their orders sit right there is a support\n * ticket about permissions that was never about permissions.\n */\n const ordersUnreadable = ordersStatus === 'error' && orders.length === 0\n\n const { data: subscriptionDocs } = useFirestoreCollection<any>(\n () =>\n email\n ? query(\n collection(firestore, 'hosts', hostId, 'subscriptions'),\n where('customerEmail', '==', email),\n // The same decision as the orders above, for the same reason: a\n // subscription written without `createdAt` would be hidden by a\n // field ordering rather than mis-sorted by it.\n orderBy(documentId()),\n limit(SUBSCRIPTION_CEILING + 1),\n )\n : null,\n [firestore, hostId, email],\n { idField: '$id' },\n )\n const { rows: subscriptions, truncated: subscriptionsTruncated } =\n ceilingedWindow<any>(subscriptionDocs, SUBSCRIPTION_CEILING)\n // Product names for subscriptions, loaded only when any exist.\n const { data: productDocs } = useFirestoreCollection<any>(\n () =>\n email && (subscriptionDocs?.length ?? 0) > 0\n ? query(\n collection(firestore, 'hosts', hostId, 'products'),\n // A LOOKUP, not a list — but the same ordering decision, so the\n // hundred it reads is a reachable hundred rather than a sample,\n // and a product past it degrades a subscription's label to its\n // id rather than hiding the subscription.\n orderBy(documentId()),\n limit(100),\n )\n : null,\n [firestore, hostId, email, (subscriptionDocs?.length ?? 0) > 0],\n { idField: '$id' },\n )\n /*==========================================\n * BOTH LISTS PAGE IN MEMORY.\n *\n * Each ceiling is held whole, which is what lets the orders sort\n * newest-first and the lifetime figure sum over all of them. A server page\n * would have made both about ten rows instead of about this member.\n *=========================================*/\n const [orderPage, setOrderPage] = useState(0)\n const [orderPageSize, setOrderPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleOrders = useMemo(\n () =>\n orders.slice(\n orderPage * orderPageSize,\n orderPage * orderPageSize + orderPageSize,\n ),\n [orders, orderPage, orderPageSize],\n )\n const [subscriptionPage, setSubscriptionPage] = useState(0)\n const [subscriptionPageSize, setSubscriptionPageSize] = useState(\n TABLE_PAGE_SIZE_DEFAULT,\n )\n const visibleSubscriptions = useMemo(\n () =>\n subscriptions.slice(\n subscriptionPage * subscriptionPageSize,\n subscriptionPage * subscriptionPageSize + subscriptionPageSize,\n ),\n [subscriptions, subscriptionPage, subscriptionPageSize],\n )\n /*\n * A different member starts at page one. The drawer is reused for whoever\n * is selected, so without this the next member opens three pages into a\n * history they may not have — which renders as an empty list and reads as\n * \"this person never bought anything\".\n */\n useEffect(() => {\n setOrderPage(0)\n setSubscriptionPage(0)\n }, [memberId])\n\n const productNames = useMemo(() => {\n const map: Record<string, string> = {}\n for (const product of productDocs ?? []) {\n map[product.$id] = product.name ?? product.$id\n }\n return map\n }, [productDocs])\n\n return (\n <>\n <Divider textAlign=\"left\">{'Lifetime purchases'}</Divider>\n <Typography variant=\"h6\">\n {/*\n \"at least\", or nothing at all. This figure is summed over the order\n WINDOW, so once the probe finds an order past the ceiling it is a\n lower bound — and a lower bound printed as a lifetime is the number\n a support agent quotes back to the customer.\n */}\n {ordersUnreadable\n ? '—'\n : `${ordersTruncated ? 'at least ' : ''}${usd(lifetimeCents)}`}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Charged order totals minus refunds; pending and canceled ' +\n 'orders excluded.'}\n {ordersTruncated\n ? ` Summed over the ${ORDER_CEILING} orders read here; this ` +\n 'member has more.'\n : ''}\n </Typography>\n\n <Divider textAlign=\"left\">{'Orders'}</Divider>\n {ordersUnreadable ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Order history takes the \"See orders and webhooks\" permission on this site.'}\n </Typography>\n ) : orders.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No orders yet.'}\n </Typography>\n ) : (\n visibleOrders.map((order: any) => (\n <Stack key={order.$id} spacing={0}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"body2\" sx={{ flex: 1 }} noWrap>\n {`${orderNumber(order)} · ${charged(\n Number(order.totals?.totalCents ?? order.amountCents ?? 0) ||\n 0,\n order.currency,\n )}`}\n </Typography>\n <Chip\n label={String(order.status ?? 'paid').replace('_', ' ')}\n size=\"small\"\n variant=\"outlined\"\n />\n </Stack>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {orderCreatedMs(order)\n ? new Date(orderCreatedMs(order)).toLocaleDateString()\n : '—'}\n {reversalSuffix(order)}\n </Typography>\n {order.paymentIntentId ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n sx={{ fontFamily: 'monospace' }}\n noWrap\n >\n {order.paymentIntentId}\n </Typography>\n ) : null}\n </Stack>\n ))\n )}\n {ordersUnreadable || orders.length === 0 ? null : (\n <ListPagination\n page={orderPage}\n pageSize={orderPageSize}\n rowCount={visibleOrders.length}\n // The orders held here — a slice of rows already read, so the\n // total is exact for the window. The lifetime caption above is\n // where the window's own shortfall is stated.\n count={orders.length}\n onPageChange={setOrderPage}\n onPageSizeChange={setOrderPageSize}\n />\n )}\n\n {subscriptions.length > 0 ? (\n <>\n <Divider textAlign=\"left\">{'Subscriptions'}</Divider>\n {visibleSubscriptions.map((subscription: any) => (\n <Stack\n key={subscription.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {/*\n * The amount (AGL-1732). This row named the product and the\n * renewal date and stopped, and no other console surface\n * carried the figure either — orders, analytics and the CSV\n * all read `orders`, which a subscription sale does not\n * create. Subscriptions written before that fix have no\n * `totals`, so the amount is omitted rather than shown as\n * $0.00.\n */}\n {productNames[subscription.productId] ??\n subscription.productId ??\n 'Subscription'}\n {subscription.totals?.totalCents != null\n ? ` · ${charged(Number(subscription.totals.totalCents) || 0, subscription.currency)}${\n subscription.interval ? `/${subscription.interval}` : ''\n }`\n : ''}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {subscription.currentPeriodEndMs\n ? `Renews ${new Date(\n Number(subscription.currentPeriodEndMs),\n ).toLocaleDateString()}`\n : '—'}\n {/*\n * What this subscriber has actually paid, across every cycle\n * (AGL-1743). Omitted, not shown as 0, for subscriptions\n * whose cycles all predate `invoice.payment_succeeded`\n * being handled: those invoices are recoverable only from\n * Stripe.\n */}\n {Number(subscription.invoicesCount ?? 0) > 0\n ? ` · ${charged(Number(subscription.paidCents) || 0, subscription.currency)} paid over ${\n Number(subscription.invoicesCount) === 1\n ? '1 invoice'\n : `${Number(subscription.invoicesCount)} invoices`\n }`\n : ''}\n </Typography>\n </Stack>\n <Chip\n label={String(subscription.status ?? 'active')}\n size=\"small\"\n variant=\"outlined\"\n color={subscription.status === 'active' ? 'success' : 'default'}\n />\n </Stack>\n ))}\n <ListPagination\n page={subscriptionPage}\n pageSize={subscriptionPageSize}\n rowCount={visibleSubscriptions.length}\n // This member's subscriptions, in full for the window.\n count={subscriptions.length}\n onPageChange={setSubscriptionPage}\n onPageSizeChange={setSubscriptionPageSize}\n />\n {subscriptionsTruncated ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Showing ${SUBSCRIPTION_CEILING} subscriptions; this ` +\n 'member has more.'}\n </Typography>\n ) : null}\n </>\n ) : null}\n </>\n )\n}\nSiteMemberPurchases.displayName = 'SiteMemberPurchases'\n\nexport default SiteMemberPurchases\n"],"names":["ListPagination","TABLE_PAGE_SIZE_DEFAULT","ceilingedWindow","useFirestore","useFirestoreCollection","Chip","Divider","Stack","Typography","collection","documentId","limit","orderBy","query","where","useEffect","useMemo","useState","splitOrderReversal","computeLifetimePurchaseCents","saleMoneyText","usd","cents","toFixed","charged","currency","toLowerCase","ORDER_CEILING","SUBSCRIPTION_CEILING","reversalSuffix","order","refundedCents","chargedBackCents","orderNumber","number","String","$id","slice","toUpperCase","orderCreatedMs","Number","createdAtMs","createdAt","seconds","SiteMemberPurchases","props","member","hostId","firestore","memberId","email","data","orderDocs","status","ordersStatus","idField","rows","readOrders","truncated","ordersTruncated","orders","sort","a","b","lifetimeCents","ordersUnreadable","length","subscriptionDocs","subscriptions","subscriptionsTruncated","productDocs","orderPage","setOrderPage","orderPageSize","setOrderPageSize","visibleOrders","subscriptionPage","setSubscriptionPage","subscriptionPageSize","setSubscriptionPageSize","visibleSubscriptions","productNames","map","product","name","textAlign","variant","color","spacing","direction","sx","alignItems","flex","noWrap","totals","totalCents","amountCents","label","replace","size","Date","toLocaleDateString","paymentIntentId","fontFamily","page","pageSize","rowCount","count","onPageChange","onPageSizeChange","subscription","minWidth","productId","interval","currentPeriodEndMs","invoicesCount","paidCents","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAGA,SAASA,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SACEC,eAAe,EACfC,YAAY,EACZC,sBAAsB,QACjB,iCAAgC;AACvC,SAASC,IAAI,EAAEC,OAAO,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AAChE,SACEC,UAAU,EACVC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,KAAK,QACA,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACpD,SAASC,kBAAkB,QAAQ,kCAA8B;AACjE,SAASC,4BAA4B,QAAQ,uCAAmC;AAChF,SAASC,aAAa,QAAQ,mCAA+B;AAE7D,MAAMC,MAAM,CAACC,QAAkB,CAAC,CAAC,EAAE,AAACA,CAAAA,QAAQ,GAAE,EAAGC,OAAO,CAAC,IAAI;AAC7D,iFAAiF,GACjF,MAAMC,UAAU,CAACF,OAAeG,WAC9B,OAAOA,aAAa,YAAYA,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ACF;;;;;8CAGR,KAAC9G;oCACC4F,OAAO9D,QAAO2E,uBAAAA,aAAazD,MAAM,YAAnByD,uBAAuB;oCACrCX,MAAK;oCACLb,SAAQ;oCACRC,OAAOuB,aAAazD,MAAM,KAAK,WAAW,YAAY;;;2BAnDnDyD,aAAa1E,GAAG;;kCAuDzB,KAACpC;wBACCwG,MAAM5B;wBACN6B,UAAU3B;wBACV4B,UAAU1B,qBAAqBd,MAAM;wBACrC,uDAAuD;wBACvDyC,OAAOvC,cAAcF,MAAM;wBAC3B0C,cAAc/B;wBACdgC,kBAAkB9B;;oBAEnBV,uCACC,KAAC7D;wBAAW8E,SAAQ;wBAAUC,OAAM;kCACjC,CAAC,QAAQ,EAAE3D,qBAAqB,qBAAqB,CAAC,GACrD;yBAEF;;iBAEJ;;;AAGV;AACAgB,oBAAoByE,WAAW,GAAG;AAElC,eAAezE,oBAAmB"}
|
|
@@ -59,7 +59,7 @@ function Fact(props) {
|
|
|
59
59
|
idField: '$id'
|
|
60
60
|
});
|
|
61
61
|
const invoices = invoiceDocs != null ? invoiceDocs : [];
|
|
62
|
-
const money = (cents, code = currency)=>CommerceModel.formatOrderMoney(cents, code);
|
|
62
|
+
const money = (cents, code = subscription.currency || currency)=>CommerceModel.formatOrderMoney(cents, code);
|
|
63
63
|
const date = CommerceModel.formatSubscriptionDate;
|
|
64
64
|
const dateText = CommerceModel.subscriptionDateText(CommerceModel.subscriptionDateLine(subscription));
|
|
65
65
|
const price = ((_subscription_totals = subscription.totals) == null ? void 0 : _subscription_totals.totalCents) != null ? `${money(Number(subscription.totals.totalCents) || 0)}${CommerceModel.subscriptionIntervalSuffix(subscription.interval)}` : '';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/subscription-detail-dialog.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\n'use client'\n\nimport * as CommerceModel from '../../model'\nimport {\n Box,\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Divider,\n Link,\n Stack,\n Typography,\n} from '@mui/material'\nimport { collection, limit, orderBy, query } from 'firebase/firestore'\nimport { useFirestore, useFirestoreCollection } from '@aglyn/tenant-feature-instance'\n\n/** How many of a subscription's invoices the dialog lists: two years of monthly cycles. */\nexport const SUBSCRIPTION_INVOICE_WINDOW = 24\n\n/** A stored subscription, as far as this list reads one. */\nexport interface SubscriptionRow {\n $id: string\n productId?: string\n customerEmail?: string | null\n customerName?: string | null\n status?: string\n interval?: string\n cancelAtPeriodEnd?: boolean\n currentPeriodEndMs?: number | null\n paidThroughMs?: number\n createdAtMs?: number\n paidCents?: number\n invoicesCount?: number\n livemode?: boolean\n lineItems?: Array<{ name?: string; quantity?: number }>\n totals?: { totalCents?: number; taxCents?: number }\n}\n\nexport interface SubscriptionDetailDialogProps {\n hostId: string\n subscription: SubscriptionRow\n currency: string\n onClose: () => void\n}\n\ninterface InvoiceRow {\n $id: string\n number?: string\n paidCents?: number\n currency?: string\n paidAtMs?: number\n periodStartMs?: number\n periodEndMs?: number\n billingReason?: string\n hostedInvoiceUrl?: string\n}\n\nfunction Fact(props: { label: string; value: string }) {\n return (\n <Box sx={{ display: 'flex', gap: 2 }}>\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ minWidth: 140 }}>\n {props.label}\n </Typography>\n <Typography variant=\"body2\">{props.value}</Typography>\n </Box>\n )\n}\n\n/**\n * One subscription and its invoices (AGL-4191). Every paid cycle is recorded\n * under `subscriptions/{id}/invoices` by the billing webhook, and this is the\n * first place a merchant can read them without opening Stripe.\n */\nexport function SubscriptionDetailDialog(props: SubscriptionDetailDialogProps) {\n const { hostId, subscription, currency, onClose } = props\n const firestore = useFirestore()\n const { data: invoiceDocs, status } = useFirestoreCollection<InvoiceRow>(\n () =>\n query(\n collection(firestore, 'hosts', hostId, 'subscriptions', subscription.$id, 'invoices'),\n orderBy('paidAtMs', 'desc'),\n limit(SUBSCRIPTION_INVOICE_WINDOW),\n ),\n [firestore, hostId, subscription.$id],\n { idField: '$id' },\n )\n const invoices = invoiceDocs ?? []\n const money = (cents: number, code = currency) => CommerceModel.formatOrderMoney(cents, code)\n const date = CommerceModel.formatSubscriptionDate\n const dateText = CommerceModel.subscriptionDateText(\n CommerceModel.subscriptionDateLine(subscription),\n )\n const price =\n subscription.totals?.totalCents != null\n ? `${money(Number(subscription.totals.totalCents) || 0)}${CommerceModel.subscriptionIntervalSuffix(subscription.interval)}`\n : ''\n\n return (\n <Dialog open onClose={onClose} maxWidth=\"sm\" fullWidth>\n <DialogTitle>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Box sx={{ flex: 1, minWidth: 0 }}>{CommerceModel.subscriptionPlanName(subscription)}</Box>\n <Chip\n label={CommerceModel.subscriptionStatusLabel(subscription.status)}\n size=\"small\"\n color={CommerceModel.subscriptionStatusColor(subscription.status)}\n variant=\"outlined\"\n />\n </Stack>\n </DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>\n <Fact\n label=\"Customer\"\n value={\n [subscription.customerName, subscription.customerEmail].filter(Boolean).join(' · ') ||\n 'Unknown customer'\n }\n />\n {price ? <Fact label=\"Price\" value={price} /> : null}\n {subscription.createdAtMs ? (\n <Fact label=\"Started\" value={date(subscription.createdAtMs)} />\n ) : null}\n {dateText ? <Fact label=\"Next\" value={dateText} /> : null}\n <Fact\n label=\"Paid so far\"\n value={\n Number(subscription.paidCents ?? 0) > 0\n ? `${money(Number(subscription.paidCents) || 0)} over ${Number(subscription.invoicesCount ?? 0)} ${\n Number(subscription.invoicesCount ?? 0) === 1 ? 'invoice' : 'invoices'\n }`\n : 'Nothing yet'\n }\n />\n {subscription.livemode === false ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'A test-mode subscription: no real money moved, and it is not counted in your recurring revenue.'}\n </Typography>\n ) : null}\n <Divider textAlign=\"left\" sx={{ mt: 1 }}>\n {'Invoices'}\n </Divider>\n {invoices.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {status === 'loading' ? 'Loading invoices…' : 'No invoices recorded yet.'}\n </Typography>\n ) : (\n invoices.map((invoice) => (\n <Box key={invoice.$id} sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>\n <Box sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\">\n {invoice.paidAtMs ? date(invoice.paidAtMs) : 'Date unknown'}\n {invoice.number ? ` · ${invoice.number}` : ''}\n </Typography>\n {invoice.periodStartMs && invoice.periodEndMs ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`For ${date(invoice.periodStartMs)} to ${date(invoice.periodEndMs)}`}\n </Typography>\n ) : null}\n </Box>\n <Typography variant=\"body2\">\n {money(Number(invoice.paidCents) || 0, invoice.currency || currency)}\n </Typography>\n {invoice.hostedInvoiceUrl ? (\n <Link href={invoice.hostedInvoiceUrl} target=\"_blank\" rel=\"noopener noreferrer\" variant=\"body2\">\n {'View'}\n </Link>\n ) : null}\n </Box>\n ))\n )}\n {invoices.length >= SUBSCRIPTION_INVOICE_WINDOW ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`The ${SUBSCRIPTION_INVOICE_WINDOW} most recent invoices.`}\n </Typography>\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose}>{'Close'}</Button>\n </DialogActions>\n </Dialog>\n )\n}\nSubscriptionDetailDialog.displayName = 'SubscriptionDetailDialog'\n\nexport default SubscriptionDetailDialog\n"],"names":["CommerceModel","Box","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Divider","Link","Stack","Typography","collection","limit","orderBy","query","useFirestore","useFirestoreCollection","SUBSCRIPTION_INVOICE_WINDOW","Fact","props","sx","display","gap","variant","color","minWidth","label","value","SubscriptionDetailDialog","subscription","hostId","currency","onClose","firestore","data","invoiceDocs","status","$id","idField","invoices","money","cents","code","formatOrderMoney","date","formatSubscriptionDate","dateText","subscriptionDateText","subscriptionDateLine","price","totals","totalCents","Number","subscriptionIntervalSuffix","interval","open","maxWidth","fullWidth","direction","spacing","alignItems","flex","subscriptionPlanName","subscriptionStatusLabel","size","subscriptionStatusColor","flexDirection","customerName","customerEmail","filter","Boolean","join","createdAtMs","paidCents","invoicesCount","livemode","textAlign","mt","length","map","invoice","paidAtMs","number","periodStartMs","periodEndMs","hostedInvoiceUrl","href","target","rel","onClick","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;AAEA,YAAYA,mBAAmB,uBAAa;AAC5C,SACEC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,OAAO,EACPC,IAAI,EACJC,KAAK,EACLC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,KAAK,EAAEC,OAAO,EAAEC,KAAK,QAAQ,qBAAoB;AACtE,SAASC,YAAY,EAAEC,sBAAsB,QAAQ,iCAAgC;AAErF,yFAAyF,GACzF,OAAO,MAAMC,8BAA8B,GAAE;AAwC7C,SAASC,KAAKC,KAAuC;IACnD,qBACE,MAACnB;QAAIoB,IAAI;YAAEC,SAAS;YAAQC,KAAK;QAAE;;0BACjC,KAACZ;gBAAWa,SAAQ;gBAAQC,OAAM;gBAAiBJ,IAAI;oBAAEK,UAAU;gBAAI;0BACpEN,MAAMO,KAAK;;0BAEd,KAAChB;gBAAWa,SAAQ;0BAASJ,MAAMQ,KAAK;;;;AAG9C;AAEA;;;;CAIC,GACD,OAAO,SAASC,yBAAyBT,KAAoC;QAqD1DU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AAM;wCAAGpC,UAAU;oCAAE;;sDAC9B,MAACf;4CAAWa,SAAQ;;gDACjByD,QAAQC,QAAQ,GAAGrC,KAAKoC,QAAQC,QAAQ,IAAI;gDAC5CD,QAAQE,MAAM,GAAG,CAAC,GAAG,EAAEF,QAAQE,MAAM,EAAE,GAAG;;;wCAE5CF,QAAQG,aAAa,IAAIH,QAAQI,WAAW,iBAC3C,KAAC1E;4CAAWa,SAAQ;4CAAUC,OAAM;sDACjC,CAAC,IAAI,EAAEoB,KAAKoC,QAAQG,aAAa,EAAE,IAAI,EAAEvC,KAAKoC,QAAQI,WAAW,GAAG;6CAErE;;;8CAEN,KAAC1E;oCAAWa,SAAQ;8CACjBiB,MAAMY,OAAO4B,QAAQP,SAAS,KAAK,GAAGO,QAAQjD,QAAQ,IAAIA;;gCAE5DiD,QAAQK,gBAAgB,iBACvB,KAAC7E;oCAAK8E,MAAMN,QAAQK,gBAAgB;oCAAEE,QAAO;oCAASC,KAAI;oCAAsBjE,SAAQ;8CACrF;qCAED;;2BAnBIyD,QAAQ3C,GAAG;oBAuBxBE,SAASuC,MAAM,IAAI7D,4CAClB,KAACP;wBAAWa,SAAQ;wBAAUC,OAAM;kCACjC,CAAC,IAAI,EAAEP,4BAA4B,sBAAsB,CAAC;yBAE3D;;;0BAEN,KAACb;0BACC,cAAA,KAACH;oBAAOwF,SAASzD;8BAAU;;;;;AAInC;AACAJ,yBAAyB8D,WAAW,GAAG;AAEvC,eAAe9D,yBAAwB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/subscription-detail-dialog.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\n'use client'\n\nimport * as CommerceModel from '../../model'\nimport {\n Box,\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Divider,\n Link,\n Stack,\n Typography,\n} from '@mui/material'\nimport { collection, limit, orderBy, query } from 'firebase/firestore'\nimport { useFirestore, useFirestoreCollection } from '@aglyn/tenant-feature-instance'\n\n/** How many of a subscription's invoices the dialog lists: two years of monthly cycles. */\nexport const SUBSCRIPTION_INVOICE_WINDOW = 24\n\n/** A stored subscription, as far as this list reads one. */\nexport interface SubscriptionRow {\n $id: string\n productId?: string\n customerEmail?: string | null\n customerName?: string | null\n status?: string\n interval?: string\n cancelAtPeriodEnd?: boolean\n currentPeriodEndMs?: number | null\n paidThroughMs?: number\n createdAtMs?: number\n paidCents?: number\n invoicesCount?: number\n livemode?: boolean\n lineItems?: Array<{ name?: string; quantity?: number }>\n totals?: { totalCents?: number; taxCents?: number }\n /** The currency it is billed in (AGL-4257); absent is the store's. */\n currency?: string\n}\n\nexport interface SubscriptionDetailDialogProps {\n hostId: string\n subscription: SubscriptionRow\n currency: string\n onClose: () => void\n}\n\ninterface InvoiceRow {\n $id: string\n number?: string\n paidCents?: number\n currency?: string\n paidAtMs?: number\n periodStartMs?: number\n periodEndMs?: number\n billingReason?: string\n hostedInvoiceUrl?: string\n}\n\nfunction Fact(props: { label: string; value: string }) {\n return (\n <Box sx={{ display: 'flex', gap: 2 }}>\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ minWidth: 140 }}>\n {props.label}\n </Typography>\n <Typography variant=\"body2\">{props.value}</Typography>\n </Box>\n )\n}\n\n/**\n * One subscription and its invoices (AGL-4191). Every paid cycle is recorded\n * under `subscriptions/{id}/invoices` by the billing webhook, and this is the\n * first place a merchant can read them without opening Stripe.\n */\nexport function SubscriptionDetailDialog(props: SubscriptionDetailDialogProps) {\n const { hostId, subscription, currency, onClose } = props\n const firestore = useFirestore()\n const { data: invoiceDocs, status } = useFirestoreCollection<InvoiceRow>(\n () =>\n query(\n collection(firestore, 'hosts', hostId, 'subscriptions', subscription.$id, 'invoices'),\n orderBy('paidAtMs', 'desc'),\n limit(SUBSCRIPTION_INVOICE_WINDOW),\n ),\n [firestore, hostId, subscription.$id],\n { idField: '$id' },\n )\n const invoices = invoiceDocs ?? []\n const money = (cents: number, code = subscription.currency || currency) => CommerceModel.formatOrderMoney(cents, code)\n const date = CommerceModel.formatSubscriptionDate\n const dateText = CommerceModel.subscriptionDateText(\n CommerceModel.subscriptionDateLine(subscription),\n )\n const price =\n subscription.totals?.totalCents != null\n ? `${money(Number(subscription.totals.totalCents) || 0)}${CommerceModel.subscriptionIntervalSuffix(subscription.interval)}`\n : ''\n\n return (\n <Dialog open onClose={onClose} maxWidth=\"sm\" fullWidth>\n <DialogTitle>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Box sx={{ flex: 1, minWidth: 0 }}>{CommerceModel.subscriptionPlanName(subscription)}</Box>\n <Chip\n label={CommerceModel.subscriptionStatusLabel(subscription.status)}\n size=\"small\"\n color={CommerceModel.subscriptionStatusColor(subscription.status)}\n variant=\"outlined\"\n />\n </Stack>\n </DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>\n <Fact\n label=\"Customer\"\n value={\n [subscription.customerName, subscription.customerEmail].filter(Boolean).join(' · ') ||\n 'Unknown customer'\n }\n />\n {price ? <Fact label=\"Price\" value={price} /> : null}\n {subscription.createdAtMs ? (\n <Fact label=\"Started\" value={date(subscription.createdAtMs)} />\n ) : null}\n {dateText ? <Fact label=\"Next\" value={dateText} /> : null}\n <Fact\n label=\"Paid so far\"\n value={\n Number(subscription.paidCents ?? 0) > 0\n ? `${money(Number(subscription.paidCents) || 0)} over ${Number(subscription.invoicesCount ?? 0)} ${\n Number(subscription.invoicesCount ?? 0) === 1 ? 'invoice' : 'invoices'\n }`\n : 'Nothing yet'\n }\n />\n {subscription.livemode === false ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'A test-mode subscription: no real money moved, and it is not counted in your recurring revenue.'}\n </Typography>\n ) : null}\n <Divider textAlign=\"left\" sx={{ mt: 1 }}>\n {'Invoices'}\n </Divider>\n {invoices.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {status === 'loading' ? 'Loading invoices…' : 'No invoices recorded yet.'}\n </Typography>\n ) : (\n invoices.map((invoice) => (\n <Box key={invoice.$id} sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>\n <Box sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\">\n {invoice.paidAtMs ? date(invoice.paidAtMs) : 'Date unknown'}\n {invoice.number ? ` · ${invoice.number}` : ''}\n </Typography>\n {invoice.periodStartMs && invoice.periodEndMs ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`For ${date(invoice.periodStartMs)} to ${date(invoice.periodEndMs)}`}\n </Typography>\n ) : null}\n </Box>\n <Typography variant=\"body2\">\n {money(Number(invoice.paidCents) || 0, invoice.currency || currency)}\n </Typography>\n {invoice.hostedInvoiceUrl ? (\n <Link href={invoice.hostedInvoiceUrl} target=\"_blank\" rel=\"noopener noreferrer\" variant=\"body2\">\n {'View'}\n </Link>\n ) : null}\n </Box>\n ))\n )}\n {invoices.length >= SUBSCRIPTION_INVOICE_WINDOW ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`The ${SUBSCRIPTION_INVOICE_WINDOW} most recent invoices.`}\n </Typography>\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose}>{'Close'}</Button>\n </DialogActions>\n </Dialog>\n )\n}\nSubscriptionDetailDialog.displayName = 'SubscriptionDetailDialog'\n\nexport default SubscriptionDetailDialog\n"],"names":["CommerceModel","Box","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Divider","Link","Stack","Typography","collection","limit","orderBy","query","useFirestore","useFirestoreCollection","SUBSCRIPTION_INVOICE_WINDOW","Fact","props","sx","display","gap","variant","color","minWidth","label","value","SubscriptionDetailDialog","subscription","hostId","currency","onClose","firestore","data","invoiceDocs","status","$id","idField","invoices","money","cents","code","formatOrderMoney","date","formatSubscriptionDate","dateText","subscriptionDateText","subscriptionDateLine","price","totals","totalCents","Number","subscriptionIntervalSuffix","interval","open","maxWidth","fullWidth","direction","spacing","alignItems","flex","subscriptionPlanName","subscriptionStatusLabel","size","subscriptionStatusColor","flexDirection","customerName","customerEmail","filter","Boolean","join","createdAtMs","paidCents","invoicesCount","livemode","textAlign","mt","length","map","invoice","paidAtMs","number","periodStartMs","periodEndMs","hostedInvoiceUrl","href","target","rel","onClick","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;AAEA,YAAYA,mBAAmB,uBAAa;AAC5C,SACEC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,OAAO,EACPC,IAAI,EACJC,KAAK,EACLC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,KAAK,EAAEC,OAAO,EAAEC,KAAK,QAAQ,qBAAoB;AACtE,SAASC,YAAY,EAAEC,sBAAsB,QAAQ,iCAAgC;AAErF,yFAAyF,GACzF,OAAO,MAAMC,8BAA8B,GAAE;AA0C7C,SAASC,KAAKC,KAAuC;IACnD,qBACE,MAACnB;QAAIoB,IAAI;YAAEC,SAAS;YAAQC,KAAK;QAAE;;0BACjC,KAACZ;gBAAWa,SAAQ;gBAAQC,OAAM;gBAAiBJ,IAAI;oBAAEK,UAAU;gBAAI;0BACpEN,MAAMO,KAAK;;0BAEd,KAAChB;gBAAWa,SAAQ;0BAASJ,MAAMQ,KAAK;;;;AAG9C;AAEA;;;;CAIC,GACD,OAAO,SAASC,yBAAyBT,KAAoC;QAqD1DU,yBAC0DA,6BACpDA;QAnCrBA;IAnBF,MAAM,EAAEC,MAAM,EAAED,YAAY,EAAEE,QAAQ,E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