@aglyn/plugins-email 1.0.0-beta.188 → 1.0.0-beta.190

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/email/src/lib/components/list-members-panel.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\n/**\n * Who is on one list, and the three things you can do about it.\n *\n * The audience card could create a list and delete a list. It could not show\n * you a single name on one. This panel is the rest of it: read the membership,\n * add somebody, take somebody off. The list's own settings — its name, and the\n * rule behind a dynamic one — belong to the edit route, because they are\n * facts about the LIST rather than about who is on it.\n *\n * ## It mounts only on a list's own page\n *\n * The audience detail route renders this for the ONE list being read. A\n * membership listener per row would open one per list on the audiences table,\n * on a surface where most visits are to read the list of lists — the\n * read-on-mount shape `emails-console-read-cost.spec.tsx` meters. Nothing here\n * reads anything until a list is opened, and the add form reads nothing until\n * an address is typed.\n *\n * ## Whether somebody may be ADDED is the server's answer, always\n *\n * Every sentence about an address being typed in is `email/list-members-preview`\n * answering from that person's actual record and both suppression lists. This\n * component decides none of it. A screen that decided for itself would be a\n * second copy of the rule on the one surface whose job is to tell the operator\n * the truth about what is about to happen — including, and especially, that\n * the product knows nothing about this person's permission.\n *\n * ## The membership table reads consent through the SEND-TIME reader\n *\n * The `Consent` column answers the same question `performCampaignSend` asks of\n * the same document, so it asks it with the same function —\n * {@link readMarketingBasis}, against the consent group this console is being\n * viewed as. A column that picked the fields out of the row itself is a second\n * reader of a stored shape, and the two only agree until the shape moves.\n *\n * ## Removing is not suppressing, and the screen says so\n *\n * Taking somebody off a list is the operator changing their mind about an\n * audience. It is not the person asking to stop being mailed, it does not stop\n * another list reaching them, and it writes nothing to the suppression list.\n * Those are different acts with different records, and a console that let them\n * blur is a console where \"remove\" is quietly relied on as an unsubscribe.\n */\n\nimport {\n readMarketingBasis,\n type ConsentGroup,\n type DynamicListRule,\n} from '@aglyn/aglyn'\nimport { mdiAccountRemoveOutline } from '@aglyn/shared-data-mdi'\nimport { MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Box,\n Button,\n Checkbox,\n Chip,\n FormControlLabel,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport {\n collection,\n deleteDoc,\n doc,\n documentId,\n limit,\n orderBy,\n query,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useState } from 'react'\nimport {\n useFirestore,\n usePagedCollection,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\n\nexport interface ListMembersPanelProps {\n hostId: string\n /**\n * The controller this membership is being read AS — the declared group of\n * sites that are one sender, or this site alone.\n *\n * Required and undefaulted, for the reason {@link readMarketingBasis} makes\n * it required: a basis runs to a brand, so a surface that has not said which\n * brand is asking cannot report one. Defaulting to the group of one here\n * would compile and would then answer a declared group's questions with a\n * single site's facts — reporting a sibling's refusal as no record at all,\n * and a pooled grant as another brand's.\n */\n consentGroup: ConsentGroup\n /** `['orgs', orgId]` — the resolved org scope the card already holds. */\n scope: readonly [string, string]\n listId: string\n listName: string\n /**\n * Called after a membership is added or removed.\n *\n * The audience page's subscriber total is a server aggregate, taken once.\n * Left alone it would go on reporting the figure from before the add — a\n * stale total directly above a live table that disagrees with it, which\n * reads as the add having failed. The page re-takes the aggregate on this\n * signal and at no other time, so nothing is re-counted while somebody is\n * only reading.\n */\n onMembershipChanged?: () => void\n /**\n * The list's saved filters, when it has any and its membership is FIXED.\n *\n * Present, the panel offers to find the people they select and add them —\n * the same act as typing addresses, with the search doing the typing. Absent\n * (a live list, or one with no filters saved), the add form is the address\n * box alone: a live list's membership is the sweep's to decide, and offering\n * to add its own matches by hand would produce hand-added copies of rows the\n * sweep already owns.\n */\n findRule?: DynamicListRule | null\n /** The same filters in sentences, so the button says what it will find. */\n ruleSummary?: readonly string[]\n}\n\n/**\n * One member row, as stored.\n *\n * The consent fields are deliberately NOT enumerated here. They live one level\n * down, in an entry per site under `marketingConsentByHost`, and a row type\n * that named them at the top would be an invitation to read them there — which\n * is exactly what this table did while `enrollListMember` wrote them nested,\n * so every membership on every list reported \"No basis on record\" while the\n * send path mailed the same people on a basis it could see perfectly well. The\n * index signature is what {@link readMarketingBasis} takes; it is the only\n * reader of those fields on this surface.\n */\ninterface MemberRow {\n $id: string\n email?: string\n name?: string\n source?: string\n via?: 'manual' | 'rule'\n addedAt?: { toDate?: () => Date }\n [field: string]: unknown\n}\n\n/** What `email/list-members-preview` answers for one address. */\ninterface AddressVerdict {\n input: string\n email: string | null\n refusal: string | null\n requiresAttestation: boolean\n summary: string\n}\n\ninterface Preview {\n verdicts: AddressVerdict[]\n optedIn: number\n needAttestation: number\n refused: number\n}\n\n/** What a filter search found, as `email/list-rule-preview` reports it. */\ninterface FoundPeople extends Preview {\n /** People the filters matched — NOT the length of `emails`. */\n matched: number\n /** `emails` is one batch of a larger match. */\n truncated: boolean\n /** False when the scan hit its budget, so `matched` is itself a floor. */\n complete: boolean\n emails: string[]\n}\n\n/** What one address's outcome was, after the add. */\ninterface AddResult {\n input: string\n email: string | null\n enrolled: boolean\n error?: string\n}\n\n/**\n * How the basis reads on screen, for the group this console is viewed as.\n *\n * ## Read through `readMarketingBasis`, never off the row\n *\n * This picked `marketingConsent`, `marketingConsentBasis` and\n * `marketingConsentAtMs` off the top of the membership document, which is\n * where `enrollListMember` used to put them. They now live in an entry per\n * site under `marketingConsentByHost`, because a basis runs to the brand it\n * was given to rather than to the account that holds the row. Nothing here\n * moved with them, so every top-level read answered `undefined` and every\n * member of every list — including people carrying a perfectly good attested\n * basis — was reported as having no basis on record, on the one screen an\n * operator consults before mailing them. `performCampaignSend` reads the same\n * documents through the function below and mailed them, correctly, at the same\n * time.\n *\n * The fix is not a second field name. It is that the send path's reader is the\n * only reader: a surface that parses the stored shape itself agrees with the\n * sender only until the shape moves, and it moves without anybody thinking to\n * look here.\n *\n * ## Five states, because the model carries five\n *\n * An attestation and an opt-in are not the same fact — one is a person's own\n * decision, the other a claim an account made on their behalf — and a table\n * rendering both as a tick is the conflation `list-members.ts` stores the\n * basis to prevent. The three that are not a grant are not one state either.\n * Absence is not refusal, and neither of them is \"opted in, to somebody else\n * in this account\": that third one is a person the sender deliberately leaves\n * alone, and an operator who cannot see why reads it as the product having\n * lost their subscriber.\n */\nfunction consentLabel(\n member: MemberRow,\n group: ConsentGroup,\n): { label: string; color: 'default' | 'warning' | 'error' } {\n const record = readMarketingBasis(member as Record<string, unknown>, group)\n const when = record.basisAtMs\n ? ` · ${new Date(record.basisAtMs).toLocaleDateString()}`\n : ''\n if (record.basis === 'declined') {\n return { label: `Opted out${when}`, color: 'error' }\n }\n if (record.basis === 'granted') {\n /*\n * `assertedBy` rather than the stored basis field, because there are two\n * ways a record says an operator asserted it — a membership's\n * `marketingConsentBasis`, and the provenance object a backfill writes —\n * and the reader has already resolved both into this one answer.\n */\n return record.assertedBy === 'operator'\n ? { label: `Attested by your team${when}`, color: 'warning' }\n : { label: `Opted in${when}`, color: 'default' }\n }\n /*\n * A grant this site may not use. Reported rather than folded into \"no\n * basis\" because the two are different situations with different answers:\n * nobody has ever asked this person, versus somebody asked them on behalf\n * of another brand in this account and this brand may not borrow it.\n */\n if (record.otherGrant === 'other-host') {\n return { label: 'Opted in to another site', color: 'warning' }\n }\n if (record.otherGrant === 'unscoped') {\n return { label: 'Opted in — no site recorded', color: 'warning' }\n }\n return { label: 'No basis on record', color: 'default' }\n}\n\n/** Free text — a paste, a typed address, commas or newlines — to addresses. */\nexport function splitAddresses(value: string): string[] {\n return value\n .split(/[\\s,;]+/)\n .map((entry) => entry.trim())\n // A pasted mail-client line is `Name <a@b.co>`; keep the address part.\n .map((entry) => entry.replace(/^.*<|>.*$/g, ''))\n .filter(Boolean)\n}\n\nexport function ListMembersPanel(props: ListMembersPanelProps) {\n const {\n hostId,\n consentGroup,\n scope,\n listId,\n listName,\n onMembershipChanged,\n findRule,\n ruleSummary,\n } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n\n /*\n * Ordered by DOCUMENT ID and paged, not capped and re-sorted here.\n *\n * `__name__` rather than `addedAt`, which is the column a reader would\n * assume: `orderBy` FILTERS as well as sorts, so a document missing the\n * field is not in the result at all — and `addedAt` is stamped only when a\n * membership is CREATED, so every row written under the two legacy ids\n * `list-members.ts` still adopts predates it. Ordering on it would drop the\n * oldest members from their own list, silently, which is the failure that\n * turned an audience into a random sample (AGL-2501). The id is the one key\n * every row has.\n */\n const {\n rows: members,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<MemberRow>(\n (pageLimit) =>\n query(\n collection(firestore, scope[0], scope[1], 'lists', listId, 'members'),\n orderBy(documentId()),\n limit(pageLimit),\n ),\n [firestore, scope[0], scope[1], listId],\n { idField: '$id' },\n )\n\n const [addInput, setAddInput] = useState('')\n const [addName, setAddName] = useState('')\n const [preview, setPreview] = useState<Preview | null>(null)\n const [attested, setAttested] = useState(false)\n const [results, setResults] = useState<AddResult[] | null>(null)\n const [busy, setBusy] = useState(false)\n /*\n * The addresses a SEARCH found, when the operator ran one.\n *\n * A second way to fill the same candidate set, not a second way to add. Once\n * this holds addresses, everything below it — the consent readout, the\n * attestation, the Add button — is the code the typed path already used, so\n * there is exactly one place in this component where somebody is put on a\n * list and exactly one gate in front of it.\n */\n const [found, setFound] = useState<FoundPeople | null>(null)\n\n const addresses = found ? found.emails : splitAddresses(addInput)\n\n /*\n * Any edit to the box invalidates the answer.\n *\n * A preview belongs to the exact addresses it was run for. Leaving a stale\n * one on screen would show a count, and an attestation checkbox, for a set\n * the operator has since changed — so the number they stand behind would\n * not be the number that acts. Typing also abandons a search: the two are\n * alternative ways of naming a candidate set, and holding both at once\n * would leave the Add button acting on whichever the code happened to\n * prefer.\n */\n useEffect(() => {\n setPreview(null)\n setAttested(false)\n setResults(null)\n setFound(null)\n }, [addInput])\n\n const post = useCallback(\n async (route: string, body: Record<string, unknown>) => {\n const response = await authorizedFetch(user, `/api/email/${route}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, listId, ...body }),\n })\n const payload = await response.json().catch(() => ({}))\n return { ok: response.ok, payload }\n },\n [user, hostId, listId],\n )\n\n const handlePreview = useCallback(async () => {\n if (busy || !addresses.length) return\n setBusy(true)\n try {\n const { ok, payload } = await post('list-members-preview', {\n emails: addresses,\n })\n if (!ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'The addresses could not be checked.',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n setPreview(payload as Preview)\n } catch {\n enqueueSnackbar('The addresses could not be checked.', {\n variant: 'warning',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [busy, addresses, post, enqueueSnackbar])\n\n const handleFind = useCallback(async () => {\n if (busy || !findRule) return\n setBusy(true)\n try {\n const { ok, payload } = await post('list-rule-preview', {\n rule: findRule,\n })\n if (!ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'The audience could not be worked out.',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n /*\n * The verdicts come back from the SAME resolution the typed path runs,\n * so what lands in `preview` here is the same object the consent\n * readout below already knows how to draw. A search that returned its\n * own shaped summary would be a second consent readout, and the second\n * one is the one nobody reviews.\n */\n setFound(payload as FoundPeople)\n setPreview(payload as Preview)\n setAttested(false)\n setResults(null)\n if (!Number(payload?.matched ?? 0)) {\n enqueueSnackbar('These filters match nobody', {\n variant: 'info',\n persist: false,\n })\n }\n } catch {\n enqueueSnackbar('The audience could not be worked out.', {\n variant: 'warning',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [busy, findRule, post, enqueueSnackbar])\n\n const handleAdd = useCallback(async () => {\n if (busy || !preview) return\n setBusy(true)\n try {\n const { ok, payload } = await post('list-members-add', {\n emails: addresses,\n ...(addresses.length === 1 && addName.trim()\n ? { name: addName.trim() }\n : {}),\n // The operator's assertion, not a basis they named: the server\n // derives a pass-through from each person's own record, and this flag\n // can only ever add the attributable kind.\n attestConsent: attested,\n })\n if (!ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'Nobody was added to the list',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n const added = Number(payload?.added ?? 0)\n setResults((payload?.results ?? []) as AddResult[])\n setPreview(null)\n if (added) {\n setAddInput('')\n setAddName('')\n setFound(null)\n onMembershipChanged?.()\n }\n enqueueSnackbar(\n added === 1 ? 'One person added' : `${added} people added`,\n { variant: added ? 'success' : 'warning', persist: false },\n )\n } catch {\n enqueueSnackbar('Nobody was added to the list', {\n variant: 'warning',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [\n busy,\n preview,\n addresses,\n addName,\n attested,\n post,\n enqueueSnackbar,\n onMembershipChanged,\n ])\n\n const handleRemove = useCallback(\n async (member: MemberRow) => {\n const accepted = await confirm({\n title: 'Remove from this list?',\n description:\n `${member.email ?? 'This person'} stops being part of \"${listName}\" ` +\n 'and campaigns to this list stop reaching them. This is NOT an ' +\n 'unsubscribe: it does not add them to your suppression list, and ' +\n 'any other list they are on still reaches them. If they asked to ' +\n 'stop hearing from you, suppress the address instead.',\n confirmationText: 'Remove',\n confirmationButtonProps: { color: 'error' },\n })\n // `confirm` resolves with no value and REJECTS on cancel, so gating on\n // the resolved value alone would make this always proceed (AGL-950).\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n try {\n await deleteDoc(\n doc(\n firestore,\n scope[0],\n scope[1],\n 'lists',\n listId,\n 'members',\n member.$id,\n ),\n )\n onMembershipChanged?.()\n enqueueSnackbar('Removed from the list', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('They were not removed', { variant: 'error' })\n }\n },\n [\n confirm,\n listName,\n firestore,\n scope,\n listId,\n enqueueSnackbar,\n onMembershipChanged,\n ],\n )\n\n const enrollable = preview\n ? preview.optedIn + preview.needAttestation\n : 0\n\n const columns: GridColDef[] = [\n {\n field: 'email',\n headerName: 'Address',\n flex: 1,\n minWidth: 220,\n valueGetter: (_value, row) => row.email ?? '—',\n },\n {\n field: 'name',\n headerName: 'Name',\n flex: 1,\n minWidth: 160,\n valueGetter: (_value, row) => row.name ?? '—',\n },\n {\n field: 'addedAt',\n headerName: 'Joined',\n width: 120,\n // Sorted on the instant, drawn as a local date.\n valueGetter: (_value, row) => row.addedAt?.toDate?.()?.getTime?.() ?? 0,\n renderCell: ({ row }) =>\n row.addedAt?.toDate ? row.addedAt.toDate().toLocaleDateString() : '—',\n },\n {\n field: 'via',\n headerName: 'How',\n width: 200,\n valueGetter: (_value, row) => (row.via === 'rule' ? 'Rule' : 'Added'),\n /*\n `via` says whether a rule put them here or a person did, which is what\n decides whether they LEAVE on their own: the materializer reconciles its\n own rows away and never touches a manual one. `source` is the finer\n provenance underneath it.\n */\n renderCell: ({ row, value }) => (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', minWidth: 0 }}>\n <Chip size=\"small\" variant=\"outlined\" label={value} />\n {row.source ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {row.source}\n </Typography>\n ) : null}\n </Stack>\n ),\n },\n {\n field: 'consent',\n headerName: 'Consent',\n width: 190,\n valueGetter: (_value, row) => consentLabel(row, consentGroup).label,\n renderCell: ({ row }) => {\n const consent = consentLabel(row, consentGroup)\n return (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n color={consent.color}\n label={consent.label}\n />\n )\n },\n },\n /*\n A SUBSCRIBER HAS NO PAGE of their own here, so the row opens nothing —\n but taking somebody off an audience is the one act performed on one, and\n it belongs in the trailing cluster with every other list's actions rather\n than as a red text button sitting in the row.\n */\n listActionsColumn(\n (row) => (\n <ListRowActions\n label={String(row.email ?? row.$id)}\n items={[\n {\n key: 'remove',\n label: 'Remove from this list',\n icon: <MdiIcon path={mdiAccountRemoveOutline.path} size={0.8} />,\n destructive: true,\n onClick: () => void handleRemove(row),\n },\n ]}\n />\n ),\n { width: 72 },\n ),\n ]\n\n return (\n <Stack spacing={2} sx={{ py: 2 }}>\n {/*\n FINDING people, for a list whose membership is fixed.\n The filters are the same ones a live list is swept by; here they run\n once, on request, and what they find is offered for adding rather than\n enrolled. The count and the consent readout arrive together, because\n the second is the thing that decides how much of the first can act.\n */}\n {findRule ? (\n <Stack\n spacing={1}\n sx={{ border: 1, borderColor: 'divider', borderRadius: 1, p: 1.5 }}\n >\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Find people'}\n </Typography>\n {(ruleSummary ?? []).map((clause) => (\n <Typography key={clause} variant=\"body2\">\n {clause}\n </Typography>\n ))}\n <Box>\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={busy}\n onClick={() => void handleFind()}\n >\n {busy ? 'Searching…' : 'Find matching people'}\n </Button>\n </Box>\n {found ? (\n <Alert severity={found.matched ? 'info' : 'warning'}>\n {(found.matched === 1\n ? '1 person matches'\n : `${found.matched.toLocaleString()} people match`) +\n (found.truncated\n ? ` — this batch covers the first ${found.emails.length}. ` +\n 'Add them, then search again for the rest.'\n : '') +\n (found.complete\n ? ''\n : ' The search stopped at its read budget, so this is at ' +\n 'least that many rather than exactly.')}\n </Alert>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Whoever you add stays on this list. It does not keep growing — ' +\n 'change the membership to live on the edit page if you want ' +\n 'new matches enrolled automatically.'}\n </Typography>\n </Stack>\n ) : null}\n\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Add someone by typing their address, or paste a column of them. ' +\n 'Every address is checked against their consent record and both ' +\n 'suppression lists before anyone is added.'}\n </Typography>\n\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n <TextField\n size=\"small\"\n label=\"Email addresses\"\n placeholder=\"someone@example.com\"\n multiline\n minRows={1}\n maxRows={6}\n value={addInput}\n onChange={(event) => setAddInput(event.target.value)}\n helperText={\n addresses.length > 1\n ? `${addresses.length} addresses`\n : 'One address, or paste many'\n }\n sx={{ flexGrow: 1, minWidth: 260 }}\n />\n {addresses.length > 1 ? null : (\n <TextField\n size=\"small\"\n label=\"Name\"\n value={addName}\n onChange={(event) => setAddName(event.target.value)}\n sx={{ minWidth: 180 }}\n />\n )}\n <Box>\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={busy || !addresses.length || Boolean(preview)}\n onClick={() => void handlePreview()}\n >\n {busy ? 'Checking…' : 'Check'}\n </Button>\n </Box>\n </Stack>\n\n {/*\n The count, in front of the operator, BEFORE the attestation control\n exists. One assertion covers the batch, so the number it covers has to\n be on screen when it is given — an attestation offered above an\n unexamined paste is a signature on a blank page.\n */}\n {preview ? (\n <Stack spacing={1}>\n <Alert severity={enrollable ? 'info' : 'warning'}>\n {[\n preview.optedIn\n ? `${preview.optedIn} already opted in`\n : '',\n preview.needAttestation\n ? `${preview.needAttestation} with no opt-in on record`\n : '',\n preview.refused\n ? `${preview.refused} cannot be added at all`\n : '',\n ]\n .filter(Boolean)\n .join(' · ')}\n </Alert>\n {/*\n The HARD refusals only. An address that merely needs the\n attestation is not a refusal — listing it here would put the very\n people the checkbox below is about under a heading that says they\n cannot be added.\n */}\n {preview.verdicts\n .filter((verdict) => verdict.refusal)\n .map((verdict) => (\n <Typography\n key={verdict.input}\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {`${verdict.input} — ${verdict.summary}`}\n </Typography>\n ))}\n {preview.needAttestation ? (\n <FormControlLabel\n control={\n <Checkbox\n checked={attested}\n onChange={(event) => setAttested(event.target.checked)}\n />\n }\n label={\n <Typography variant=\"body2\">\n {`I have permission to send marketing email to the ` +\n `${preview.needAttestation} ` +\n `${preview.needAttestation === 1 ? 'person' : 'people'} ` +\n 'above with no opt-in on record. This is recorded against ' +\n 'my account, with the date.'}\n </Typography>\n }\n />\n ) : null}\n <Box>\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={\n busy ||\n !enrollable ||\n (preview.needAttestation > 0 && !attested)\n }\n onClick={() => void handleAdd()}\n >\n {busy ? 'Adding…' : `Add ${enrollable}`}\n </Button>\n </Box>\n </Stack>\n ) : null}\n\n {/*\n What actually happened, per address. A batch where one address was\n suppressed and forty were fine is not a failure, and a bare count would\n leave the operator to work out which of their lines is missing.\n */}\n {results?.length ? (\n <Stack spacing={0.5}>\n {results\n .filter((result) => !result.enrolled)\n .map((result) => (\n <Typography\n key={result.input}\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {`${result.input} — not added. ${result.error ?? ''}`}\n </Typography>\n ))}\n </Stack>\n ) : null}\n\n {members.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Nobody is on this list yet.'}\n </Typography>\n ) : (\n <>\n <ListTable\n aria-label={`Members of ${listName}`}\n rows={members}\n columns={columns}\n rowHeight={TABLE_ROW_HEIGHT}\n // Paged by the footer below, so the grid must not also slice.\n hideFooter\n />\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={members.length}\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n </>\n )}\n\n {/*\n What the column MEANS, and what to do about the one state an operator\n can act on. \"No basis on record\" is a fact about this site's records,\n not a refusal and not a dead end — the remedy is the add form above,\n which merges onto the membership that is already here rather than\n creating a second one. Whether a basis-less member is actually mailed\n is the org's consent policy to decide and is deliberately not claimed\n here: this surface does not hold that setting, and a caption that\n guessed it would be wrong for every org on the other mode.\n */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'\"No basis on record\" means nobody has recorded this person\\'s ' +\n 'permission for this site — it is not a refusal. To record one, put ' +\n 'their address in the box above and state that you have their ' +\n 'permission; the statement is kept against your account, with the ' +\n 'date.'}\n </Typography>\n\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Removing someone from a list is not an unsubscribe. It does not add ' +\n 'them to your suppression list, and it does not stop any other list ' +\n 'reaching them. If somebody asked you to stop, suppress the address.'}\n </Typography>\n </Stack>\n )\n}\nListMembersPanel.displayName = 'ListMembersPanel'\n\nexport default ListMembersPanel\n"],"names":["readMarketingBasis","mdiAccountRemoveOutline","MdiIcon","useConfirmationContext","ListPagination","ListRowActions","ListTable","listActionsColumn","TABLE_ROW_HEIGHT","useSnackbar","Alert","Box","Button","Checkbox","Chip","FormControlLabel","Stack","TextField","Typography","collection","deleteDoc","doc","documentId","limit","orderBy","query","useCallback","useEffect","useState","useFirestore","usePagedCollection","useUser","authorizedFetch","consentLabel","member","group","record","when","basisAtMs","Date","toLocaleDateString","basis","label","color","assertedBy","otherGrant","splitAddresses","value","split","map","entry","trim","replace","filter","Boolean","ListMembersPanel","props","hostId","consentGroup","scope","listId","listName","onMembershipChanged","findRule","ruleSummary","firestore","data","user","enqueueSnackbar","confirm","rows","members","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","addInput","setAddInput","addName","setAddName","preview","setPreview","attested","setAttested","results","setResults","busy","setBusy","found","setFound","addresses","emails","post","route","body","response","method","headers","JSON","stringify","payload","json","catch","ok","handlePreview","length","error","variant","allowDuplicate","handleFind","rule","Number","matched","persist","handleAdd","name","attestConsent","added","handleRemove","accepted","title","description","email","confirmationText","confirmationButtonProps","then","$id","console","enrollable","optedIn","needAttestation","columns","field","headerName","flex","minWidth","valueGetter","_value","row","width","addedAt","toDate","getTime","renderCell","via","direction","spacing","sx","alignItems","size","source","noWrap","consent","String","items","key","icon","path","destructive","onClick","py","border","borderColor","borderRadius","p","clause","disabled","severity","toLocaleString","truncated","complete","useFlexGap","flexWrap","placeholder","multiline","minRows","maxRows","onChange","event","target","helperText","flexGrow","refused","join","verdicts","verdict","refusal","input","summary","control","checked","result","enrolled","aria-label","rowHeight","hideFooter","rowCount","onPageChange","onPageSizeChange","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CC,GAED,SACEA,kBAAkB,QAGb,eAAc;AACrB,SAASC,uBAAuB,QAAQ,yBAAwB;AAChE,SAASC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AACtE,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,QAAQ,EACRC,IAAI,EACJC,gBAAgB,EAChBC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AAEtB,SACEC,UAAU,EACVC,SAAS,EACTC,GAAG,EACHC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,QACA,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACxD,SACEC,YAAY,EACZC,kBAAkB,EAClBC,OAAO,QACF,iCAAgC;AACvC,SAASC,eAAe,QAAQ,2CAA0C;AAuG1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCC,GACD,SAASC,aACPC,MAAiB,EACjBC,KAAmB;IAEnB,MAAMC,SAASpC,mBAAmBkC,QAAmCC;IACrE,MAAME,OA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AAW4F,SAAQ;gBAAUnE,OAAM;0BACjC,mEACC,wEACA,kEACA,sEACA;;0BAGJ,KAACzB;gBAAW4F,SAAQ;gBAAUnE,OAAM;0BACjC,yEACC,wEACA;;;;AAIV;AACAY,iBAAiBmJ,WAAW,GAAG;AAE/B,eAAenJ,iBAAgB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/email/src/lib/components/list-members-panel.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\n/**\n * Who is on one list, and the three things you can do about it.\n *\n * The audience card could create a list and delete a list. It could not show\n * you a single name on one. This panel is the rest of it: read the membership,\n * add somebody, take somebody off. The list's own settings — its name, and the\n * rule behind a dynamic one — belong to the edit route, because they are\n * facts about the LIST rather than about who is on it.\n *\n * ## It mounts only on a list's own page\n *\n * The audience detail route renders this for the ONE list being read. A\n * membership listener per row would open one per list on the audiences table,\n * on a surface where most visits are to read the list of lists — the\n * read-on-mount shape `emails-console-read-cost.spec.tsx` meters. Nothing here\n * reads anything until a list is opened, and the add form reads nothing until\n * an address is typed.\n *\n * ## Whether somebody may be ADDED is the server's answer, always\n *\n * Every sentence about an address being typed in is `email/list-members-preview`\n * answering from that person's actual record and both suppression lists. This\n * component decides none of it. A screen that decided for itself would be a\n * second copy of the rule on the one surface whose job is to tell the operator\n * the truth about what is about to happen — including, and especially, that\n * the product knows nothing about this person's permission.\n *\n * ## The membership table reads consent through the SEND-TIME reader\n *\n * The `Consent` column answers the same question `performCampaignSend` asks of\n * the same document, so it asks it with the same function —\n * {@link readMarketingBasis}, against the consent group this console is being\n * viewed as. A column that picked the fields out of the row itself is a second\n * reader of a stored shape, and the two only agree until the shape moves.\n *\n * ## Removing is not suppressing, and the screen says so\n *\n * Taking somebody off a list is the operator changing their mind about an\n * audience. It is not the person asking to stop being mailed, it does not stop\n * another list reaching them, and it writes nothing to the suppression list.\n * Those are different acts with different records, and a console that let them\n * blur is a console where \"remove\" is quietly relied on as an unsubscribe.\n */\n\nimport {\n readMarketingBasis,\n type ConsentGroup,\n type DynamicListRule,\n} from '@aglyn/aglyn'\nimport { mdiAccountRemoveOutline } from '@aglyn/shared-data-mdi'\nimport { MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { inMemoryListField } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { usePagedRowsFilter } from '@aglyn/shared-ui-jsx/hooks/use-paged-rows-filter'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Box,\n Button,\n Checkbox,\n Chip,\n FormControlLabel,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport {\n collection,\n deleteDoc,\n doc,\n documentId,\n limit,\n orderBy,\n query,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport {\n useFirestore,\n usePagedCollection,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\n\nexport interface ListMembersPanelProps {\n hostId: string\n /**\n * The controller this membership is being read AS — the declared group of\n * sites that are one sender, or this site alone.\n *\n * Required and undefaulted, for the reason {@link readMarketingBasis} makes\n * it required: a basis runs to a brand, so a surface that has not said which\n * brand is asking cannot report one. Defaulting to the group of one here\n * would compile and would then answer a declared group's questions with a\n * single site's facts — reporting a sibling's refusal as no record at all,\n * and a pooled grant as another brand's.\n */\n consentGroup: ConsentGroup\n /** `['orgs', orgId]` — the resolved org scope the card already holds. */\n scope: readonly [string, string]\n listId: string\n listName: string\n /**\n * Called after a membership is added or removed.\n *\n * The audience page's subscriber total is a server aggregate, taken once.\n * Left alone it would go on reporting the figure from before the add — a\n * stale total directly above a live table that disagrees with it, which\n * reads as the add having failed. The page re-takes the aggregate on this\n * signal and at no other time, so nothing is re-counted while somebody is\n * only reading.\n */\n onMembershipChanged?: () => void\n /**\n * The list's saved filters, when it has any and its membership is FIXED.\n *\n * Present, the panel offers to find the people they select and add them —\n * the same act as typing addresses, with the search doing the typing. Absent\n * (a live list, or one with no filters saved), the add form is the address\n * box alone: a live list's membership is the sweep's to decide, and offering\n * to add its own matches by hand would produce hand-added copies of rows the\n * sweep already owns.\n */\n findRule?: DynamicListRule | null\n /** The same filters in sentences, so the button says what it will find. */\n ruleSummary?: readonly string[]\n}\n\n/**\n * One member row, as stored.\n *\n * The consent fields are deliberately NOT enumerated here. They live one level\n * down, in an entry per site under `marketingConsentByHost`, and a row type\n * that named them at the top would be an invitation to read them there — which\n * is exactly what this table did while `enrollListMember` wrote them nested,\n * so every membership on every list reported \"No basis on record\" while the\n * send path mailed the same people on a basis it could see perfectly well. The\n * index signature is what {@link readMarketingBasis} takes; it is the only\n * reader of those fields on this surface.\n */\ninterface MemberRow {\n $id: string\n email?: string\n name?: string\n source?: string\n via?: 'manual' | 'rule'\n addedAt?: { toDate?: () => Date }\n [field: string]: unknown\n}\n\n/** What `email/list-members-preview` answers for one address. */\ninterface AddressVerdict {\n input: string\n email: string | null\n refusal: string | null\n requiresAttestation: boolean\n summary: string\n}\n\ninterface Preview {\n verdicts: AddressVerdict[]\n optedIn: number\n needAttestation: number\n refused: number\n}\n\n/** What a filter search found, as `email/list-rule-preview` reports it. */\ninterface FoundPeople extends Preview {\n /** People the filters matched — NOT the length of `emails`. */\n matched: number\n /** `emails` is one batch of a larger match. */\n truncated: boolean\n /** False when the scan hit its budget, so `matched` is itself a floor. */\n complete: boolean\n emails: string[]\n}\n\n/** What one address's outcome was, after the add. */\ninterface AddResult {\n input: string\n email: string | null\n enrolled: boolean\n error?: string\n}\n\n/**\n * How the basis reads on screen, for the group this console is viewed as.\n *\n * ## Read through `readMarketingBasis`, never off the row\n *\n * This picked `marketingConsent`, `marketingConsentBasis` and\n * `marketingConsentAtMs` off the top of the membership document, which is\n * where `enrollListMember` used to put them. They now live in an entry per\n * site under `marketingConsentByHost`, because a basis runs to the brand it\n * was given to rather than to the account that holds the row. Nothing here\n * moved with them, so every top-level read answered `undefined` and every\n * member of every list — including people carrying a perfectly good attested\n * basis — was reported as having no basis on record, on the one screen an\n * operator consults before mailing them. `performCampaignSend` reads the same\n * documents through the function below and mailed them, correctly, at the same\n * time.\n *\n * The fix is not a second field name. It is that the send path's reader is the\n * only reader: a surface that parses the stored shape itself agrees with the\n * sender only until the shape moves, and it moves without anybody thinking to\n * look here.\n *\n * ## Five states, because the model carries five\n *\n * An attestation and an opt-in are not the same fact — one is a person's own\n * decision, the other a claim an account made on their behalf — and a table\n * rendering both as a tick is the conflation `list-members.ts` stores the\n * basis to prevent. The three that are not a grant are not one state either.\n * Absence is not refusal, and neither of them is \"opted in, to somebody else\n * in this account\": that third one is a person the sender deliberately leaves\n * alone, and an operator who cannot see why reads it as the product having\n * lost their subscriber.\n */\ntype ConsentKey =\n | 'opted-out'\n | 'attested'\n | 'opted-in'\n | 'other-site'\n | 'no-site'\n | 'none'\n\nfunction consentLabel(\n member: MemberRow,\n group: ConsentGroup,\n): { key: ConsentKey; label: string; color: 'default' | 'warning' | 'error' } {\n const record = readMarketingBasis(member as Record<string, unknown>, group)\n const when = record.basisAtMs\n ? ` · ${new Date(record.basisAtMs).toLocaleDateString()}`\n : ''\n if (record.basis === 'declined') {\n return { key: 'opted-out', label: `Opted out${when}`, color: 'error' }\n }\n if (record.basis === 'granted') {\n /*\n * `assertedBy` rather than the stored basis field, because there are two\n * ways a record says an operator asserted it — a membership's\n * `marketingConsentBasis`, and the provenance object a backfill writes —\n * and the reader has already resolved both into this one answer.\n */\n return record.assertedBy === 'operator'\n ? { key: 'attested', label: `Attested by your team${when}`, color: 'warning' }\n : { key: 'opted-in', label: `Opted in${when}`, color: 'default' }\n }\n /*\n * A grant this site may not use. Reported rather than folded into \"no\n * basis\" because the two are different situations with different answers:\n * nobody has ever asked this person, versus somebody asked them on behalf\n * of another brand in this account and this brand may not borrow it.\n */\n if (record.otherGrant === 'other-host') {\n return { key: 'other-site', label: 'Opted in to another site', color: 'warning' }\n }\n if (record.otherGrant === 'unscoped') {\n return { key: 'no-site', label: 'Opted in — no site recorded', color: 'warning' }\n }\n return { key: 'none', label: 'No basis on record', color: 'default' }\n}\n\n/*\n * What the membership grid's Filters panel offers (AGL-3317). The table is a\n * paged listener, so a filter matches over what its window has read, which\n * the first filter widens (`usePagedRowsFilter`). `How` and `Consent` read\n * the keys `withFilterKeys` derives, the same answers the columns draw.\n */\nconst MEMBER_FILTER_FIELDS = [\n inMemoryListField('email', 'text'),\n inMemoryListField('name', 'text'),\n inMemoryListField('via', 'select', 'viaKey'),\n inMemoryListField('consent', 'select', 'consentKey'),\n]\nconst MEMBER_FILTER_HEADERS: Readonly<Record<string, string>> = {\n email: 'Address',\n name: 'Name',\n via: 'How',\n consent: 'Consent',\n}\nconst VIA_LABELS: Readonly<Record<'rule' | 'manual', string>> = {\n rule: 'Rule',\n manual: 'Added',\n}\nconst CONSENT_LABELS: Readonly<Record<ConsentKey, string>> = {\n 'opted-in': 'Opted in',\n attested: 'Attested by your team',\n 'opted-out': 'Opted out',\n 'other-site': 'Opted in to another site',\n 'no-site': 'Opted in — no site recorded',\n none: 'No basis on record',\n}\nconst MEMBER_FILTER_OPTIONS = {\n via: Object.entries(VIA_LABELS).map(([value, label]) => ({ value, label })),\n consent: Object.entries(CONSENT_LABELS).map(([value, label]) => ({ value, label })),\n}\nconst MEMBER_SEARCH_FIELDS = ['email', 'name', 'source'] as const\n\n/** A member row with the keys its `How` and `Consent` filters match on. */\ntype FilterableMemberRow = MemberRow & { viaKey: 'rule' | 'manual'; consentKey: ConsentKey }\n\nconst withFilterKeys = (member: MemberRow, group: ConsentGroup): FilterableMemberRow => ({\n ...member,\n viaKey: member.via === 'rule' ? 'rule' : 'manual',\n consentKey: consentLabel(member, group).key,\n})\n\n/** Free text — a paste, a typed address, commas or newlines — to addresses. */\nexport function splitAddresses(value: string): string[] {\n return value\n .split(/[\\s,;]+/)\n .map((entry) => entry.trim())\n // A pasted mail-client line is `Name <a@b.co>`; keep the address part.\n .map((entry) => entry.replace(/^.*<|>.*$/g, ''))\n .filter(Boolean)\n}\n\nexport function ListMembersPanel(props: ListMembersPanelProps) {\n const {\n hostId,\n consentGroup,\n scope,\n listId,\n listName,\n onMembershipChanged,\n findRule,\n ruleSummary,\n } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n\n /*\n * Ordered by DOCUMENT ID and paged, not capped and re-sorted here.\n *\n * `__name__` rather than `addedAt`, which is the column a reader would\n * assume: `orderBy` FILTERS as well as sorts, so a document missing the\n * field is not in the result at all — and `addedAt` is stamped only when a\n * membership is CREATED, so every row written under the two legacy ids\n * `list-members.ts` still adopts predates it. Ordering on it would drop the\n * oldest members from their own list, silently, which is the failure that\n * turned an audience into a random sample (AGL-2501). The id is the one key\n * every row has.\n */\n const {\n data: memberData,\n rows: memberRows,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<MemberRow>(\n (pageLimit) =>\n query(\n collection(firestore, scope[0], scope[1], 'lists', listId, 'members'),\n orderBy(documentId()),\n limit(pageLimit),\n ),\n [firestore, scope[0], scope[1], listId],\n { idField: '$id' },\n )\n const memberWindow = useMemo(\n () => memberData?.map((member) => withFilterKeys(member, consentGroup)),\n [memberData, consentGroup],\n )\n const memberPage = useMemo(\n () => memberRows.map((member) => withFilterKeys(member, consentGroup)),\n [memberRows, consentGroup],\n )\n const memberFilter = usePagedRowsFilter<FilterableMemberRow>(\n {\n data: memberWindow,\n rows: memberPage,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n },\n {\n fields: MEMBER_FILTER_FIELDS,\n options: MEMBER_FILTER_OPTIONS,\n headers: MEMBER_FILTER_HEADERS,\n search: MEMBER_SEARCH_FIELDS,\n },\n )\n // The rows on screen: the page, or the page of the matches.\n const members = memberFilter.rows\n\n const [addInput, setAddInput] = useState('')\n const [addName, setAddName] = useState('')\n const [preview, setPreview] = useState<Preview | null>(null)\n const [attested, setAttested] = useState(false)\n const [results, setResults] = useState<AddResult[] | null>(null)\n const [busy, setBusy] = useState(false)\n /*\n * The addresses a SEARCH found, when the operator ran one.\n *\n * A second way to fill the same candidate set, not a second way to add. Once\n * this holds addresses, everything below it — the consent readout, the\n * attestation, the Add button — is the code the typed path already used, so\n * there is exactly one place in this component where somebody is put on a\n * list and exactly one gate in front of it.\n */\n const [found, setFound] = useState<FoundPeople | null>(null)\n\n const addresses = found ? found.emails : splitAddresses(addInput)\n\n /*\n * Any edit to the box invalidates the answer.\n *\n * A preview belongs to the exact addresses it was run for. Leaving a stale\n * one on screen would show a count, and an attestation checkbox, for a set\n * the operator has since changed — so the number they stand behind would\n * not be the number that acts. Typing also abandons a search: the two are\n * alternative ways of naming a candidate set, and holding both at once\n * would leave the Add button acting on whichever the code happened to\n * prefer.\n */\n useEffect(() => {\n setPreview(null)\n setAttested(false)\n setResults(null)\n setFound(null)\n }, [addInput])\n\n const post = useCallback(\n async (route: string, body: Record<string, unknown>) => {\n const response = await authorizedFetch(user, `/api/email/${route}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, listId, ...body }),\n })\n const payload = await response.json().catch(() => ({}))\n return { ok: response.ok, payload }\n },\n [user, hostId, listId],\n )\n\n const handlePreview = useCallback(async () => {\n if (busy || !addresses.length) return\n setBusy(true)\n try {\n const { ok, payload } = await post('list-members-preview', {\n emails: addresses,\n })\n if (!ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'The addresses could not be checked.',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n setPreview(payload as Preview)\n } catch {\n enqueueSnackbar('The addresses could not be checked.', {\n variant: 'warning',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [busy, addresses, post, enqueueSnackbar])\n\n const handleFind = useCallback(async () => {\n if (busy || !findRule) return\n setBusy(true)\n try {\n const { ok, payload } = await post('list-rule-preview', {\n rule: findRule,\n })\n if (!ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'The audience could not be worked out.',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n /*\n * The verdicts come back from the SAME resolution the typed path runs,\n * so what lands in `preview` here is the same object the consent\n * readout below already knows how to draw. A search that returned its\n * own shaped summary would be a second consent readout, and the second\n * one is the one nobody reviews.\n */\n setFound(payload as FoundPeople)\n setPreview(payload as Preview)\n setAttested(false)\n setResults(null)\n if (!Number(payload?.matched ?? 0)) {\n enqueueSnackbar('These filters match nobody', {\n variant: 'info',\n persist: false,\n })\n }\n } catch {\n enqueueSnackbar('The audience could not be worked out.', {\n variant: 'warning',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [busy, findRule, post, enqueueSnackbar])\n\n const handleAdd = useCallback(async () => {\n if (busy || !preview) return\n setBusy(true)\n try {\n const { ok, payload } = await post('list-members-add', {\n emails: addresses,\n ...(addresses.length === 1 && addName.trim()\n ? { name: addName.trim() }\n : {}),\n // The operator's assertion, not a basis they named: the server\n // derives a pass-through from each person's own record, and this flag\n // can only ever add the attributable kind.\n attestConsent: attested,\n })\n if (!ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'Nobody was added to the list',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n const added = Number(payload?.added ?? 0)\n setResults((payload?.results ?? []) as AddResult[])\n setPreview(null)\n if (added) {\n setAddInput('')\n setAddName('')\n setFound(null)\n onMembershipChanged?.()\n }\n enqueueSnackbar(\n added === 1 ? 'One person added' : `${added} people added`,\n { variant: added ? 'success' : 'warning', persist: false },\n )\n } catch {\n enqueueSnackbar('Nobody was added to the list', {\n variant: 'warning',\n allowDuplicate: true,\n })\n } finally {\n setBusy(false)\n }\n }, [\n busy,\n preview,\n addresses,\n addName,\n attested,\n post,\n enqueueSnackbar,\n onMembershipChanged,\n ])\n\n const handleRemove = useCallback(\n async (member: MemberRow) => {\n const accepted = await confirm({\n title: 'Remove from this list?',\n description:\n `${member.email ?? 'This person'} stops being part of \"${listName}\" ` +\n 'and campaigns to this list stop reaching them. This is NOT an ' +\n 'unsubscribe: it does not add them to your suppression list, and ' +\n 'any other list they are on still reaches them. If they asked to ' +\n 'stop hearing from you, suppress the address instead.',\n confirmationText: 'Remove',\n confirmationButtonProps: { color: 'error' },\n })\n // `confirm` resolves with no value and REJECTS on cancel, so gating on\n // the resolved value alone would make this always proceed (AGL-950).\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n try {\n await deleteDoc(\n doc(\n firestore,\n scope[0],\n scope[1],\n 'lists',\n listId,\n 'members',\n member.$id,\n ),\n )\n onMembershipChanged?.()\n enqueueSnackbar('Removed from the list', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('They were not removed', { variant: 'error' })\n }\n },\n [\n confirm,\n listName,\n firestore,\n scope,\n listId,\n enqueueSnackbar,\n onMembershipChanged,\n ],\n )\n\n const enrollable = preview\n ? preview.optedIn + preview.needAttestation\n : 0\n\n const columns: GridColDef[] = [\n {\n field: 'email',\n headerName: 'Address',\n flex: 1,\n minWidth: 220,\n valueGetter: (_value, row) => row.email ?? '—',\n },\n {\n field: 'name',\n headerName: 'Name',\n flex: 1,\n minWidth: 160,\n valueGetter: (_value, row) => row.name ?? '—',\n },\n {\n field: 'addedAt',\n headerName: 'Joined',\n width: 120,\n // Sorted on the instant, drawn as a local date.\n valueGetter: (_value, row) => row.addedAt?.toDate?.()?.getTime?.() ?? 0,\n renderCell: ({ row }) =>\n row.addedAt?.toDate ? row.addedAt.toDate().toLocaleDateString() : '—',\n },\n {\n field: 'via',\n headerName: 'How',\n width: 200,\n valueGetter: (_value, row) => row.viaKey,\n /*\n `via` says whether a rule put them here or a person did, which is what\n decides whether they LEAVE on their own: the materializer reconciles its\n own rows away and never touches a manual one. `source` is the finer\n provenance underneath it.\n */\n renderCell: ({ row }) => (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', minWidth: 0 }}>\n <Chip size=\"small\" variant=\"outlined\" label={VIA_LABELS[row.viaKey as 'rule' | 'manual']} />\n {row.source ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {row.source}\n </Typography>\n ) : null}\n </Stack>\n ),\n },\n {\n field: 'consent',\n headerName: 'Consent',\n width: 190,\n valueGetter: (_value, row) => row.consentKey,\n renderCell: ({ row }) => {\n const consent = consentLabel(row, consentGroup)\n return (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n color={consent.color}\n label={consent.label}\n />\n )\n },\n },\n /*\n A SUBSCRIBER HAS NO PAGE of their own here, so the row opens nothing —\n but taking somebody off an audience is the one act performed on one, and\n it belongs in the trailing cluster with every other list's actions rather\n than as a red text button sitting in the row.\n */\n listActionsColumn(\n (row) => (\n <ListRowActions\n label={String(row.email ?? row.$id)}\n items={[\n {\n key: 'remove',\n label: 'Remove from this list',\n icon: <MdiIcon path={mdiAccountRemoveOutline.path} size={0.8} />,\n destructive: true,\n onClick: () => void handleRemove(row),\n },\n ]}\n />\n ),\n { width: 72 },\n ),\n ]\n\n return (\n <Stack spacing={2} sx={{ py: 2 }}>\n {/*\n FINDING people, for a list whose membership is fixed.\n The filters are the same ones a live list is swept by; here they run\n once, on request, and what they find is offered for adding rather than\n enrolled. The count and the consent readout arrive together, because\n the second is the thing that decides how much of the first can act.\n */}\n {findRule ? (\n <Stack\n spacing={1}\n sx={{ border: 1, borderColor: 'divider', borderRadius: 1, p: 1.5 }}\n >\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Find people'}\n </Typography>\n {(ruleSummary ?? []).map((clause) => (\n <Typography key={clause} variant=\"body2\">\n {clause}\n </Typography>\n ))}\n <Box>\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={busy}\n onClick={() => void handleFind()}\n >\n {busy ? 'Searching…' : 'Find matching people'}\n </Button>\n </Box>\n {found ? (\n <Alert severity={found.matched ? 'info' : 'warning'}>\n {(found.matched === 1\n ? '1 person matches'\n : `${found.matched.toLocaleString()} people match`) +\n (found.truncated\n ? ` — this batch covers the first ${found.emails.length}. ` +\n 'Add them, then search again for the rest.'\n : '') +\n (found.complete\n ? ''\n : ' The search stopped at its read budget, so this is at ' +\n 'least that many rather than exactly.')}\n </Alert>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Whoever you add stays on this list. It does not keep growing — ' +\n 'change the membership to live on the edit page if you want ' +\n 'new matches enrolled automatically.'}\n </Typography>\n </Stack>\n ) : null}\n\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Add someone by typing their address, or paste a column of them. ' +\n 'Every address is checked against their consent record and both ' +\n 'suppression lists before anyone is added.'}\n </Typography>\n\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n <TextField\n size=\"small\"\n label=\"Email addresses\"\n placeholder=\"someone@example.com\"\n multiline\n minRows={1}\n maxRows={6}\n value={addInput}\n onChange={(event) => setAddInput(event.target.value)}\n helperText={\n addresses.length > 1\n ? `${addresses.length} addresses`\n : 'One address, or paste many'\n }\n sx={{ flexGrow: 1, minWidth: 260 }}\n />\n {addresses.length > 1 ? null : (\n <TextField\n size=\"small\"\n label=\"Name\"\n value={addName}\n onChange={(event) => setAddName(event.target.value)}\n sx={{ minWidth: 180 }}\n />\n )}\n <Box>\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={busy || !addresses.length || Boolean(preview)}\n onClick={() => void handlePreview()}\n >\n {busy ? 'Checking…' : 'Check'}\n </Button>\n </Box>\n </Stack>\n\n {/*\n The count, in front of the operator, BEFORE the attestation control\n exists. One assertion covers the batch, so the number it covers has to\n be on screen when it is given — an attestation offered above an\n unexamined paste is a signature on a blank page.\n */}\n {preview ? (\n <Stack spacing={1}>\n <Alert severity={enrollable ? 'info' : 'warning'}>\n {[\n preview.optedIn\n ? `${preview.optedIn} already opted in`\n : '',\n preview.needAttestation\n ? `${preview.needAttestation} with no opt-in on record`\n : '',\n preview.refused\n ? `${preview.refused} cannot be added at all`\n : '',\n ]\n .filter(Boolean)\n .join(' · ')}\n </Alert>\n {/*\n The HARD refusals only. An address that merely needs the\n attestation is not a refusal — listing it here would put the very\n people the checkbox below is about under a heading that says they\n cannot be added.\n */}\n {preview.verdicts\n .filter((verdict) => verdict.refusal)\n .map((verdict) => (\n <Typography\n key={verdict.input}\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {`${verdict.input} — ${verdict.summary}`}\n </Typography>\n ))}\n {preview.needAttestation ? (\n <FormControlLabel\n control={\n <Checkbox\n checked={attested}\n onChange={(event) => setAttested(event.target.checked)}\n />\n }\n label={\n <Typography variant=\"body2\">\n {`I have permission to send marketing email to the ` +\n `${preview.needAttestation} ` +\n `${preview.needAttestation === 1 ? 'person' : 'people'} ` +\n 'above with no opt-in on record. This is recorded against ' +\n 'my account, with the date.'}\n </Typography>\n }\n />\n ) : null}\n <Box>\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={\n busy ||\n !enrollable ||\n (preview.needAttestation > 0 && !attested)\n }\n onClick={() => void handleAdd()}\n >\n {busy ? 'Adding…' : `Add ${enrollable}`}\n </Button>\n </Box>\n </Stack>\n ) : null}\n\n {/*\n What actually happened, per address. A batch where one address was\n suppressed and forty were fine is not a failure, and a bare count would\n leave the operator to work out which of their lines is missing.\n */}\n {results?.length ? (\n <Stack spacing={0.5}>\n {results\n .filter((result) => !result.enrolled)\n .map((result) => (\n <Typography\n key={result.input}\n variant=\"caption\"\n color=\"text.secondary\"\n >\n {`${result.input} — not added. ${result.error ?? ''}`}\n </Typography>\n ))}\n </Stack>\n ) : null}\n\n {memberRows.length === 0 && !hasMore && !memberFilter.filtering ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Nobody is on this list yet.'}\n </Typography>\n ) : (\n <>\n <ListFilterChips {...memberFilter.chipsProps} />\n {memberFilter.filtering && hasMore ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Filtering the ${memberFilter.read} members read so far — the next page reads more.`}\n </Typography>\n ) : null}\n <ListTable\n aria-label={`Members of ${listName}`}\n rows={members}\n columns={memberFilter.filterColumns(columns)}\n rowHeight={TABLE_ROW_HEIGHT}\n // Paged by the footer below, so the grid must not also slice.\n hideFooter\n // The panel and the search are the grid's; the panel answers\n // them over what its window read.\n {...memberFilter.gridProps}\n noRowsLabel=\"No members match these filters\"\n />\n <ListPagination {...memberFilter.pagination} />\n </>\n )}\n\n {/*\n What the column MEANS, and what to do about the one state an operator\n can act on. \"No basis on record\" is a fact about this site's records,\n not a refusal and not a dead end — the remedy is the add form above,\n which merges onto the membership that is already here rather than\n creating a second one. Whether a basis-less member is actually mailed\n is the org's consent policy to decide and is deliberately not claimed\n here: this surface does not hold that setting, and a caption that\n guessed it would be wrong for every org on the other mode.\n */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'\"No basis on record\" means nobody has recorded this person\\'s ' +\n 'permission for this site — it is not a refusal. To record one, put ' +\n 'their address in the box above and state that you have their ' +\n 'permission; the statement is kept against your account, with the ' +\n 'date.'}\n </Typography>\n\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Removing someone from a list is not an unsubscribe. It does not add ' +\n 'them to your suppression list, and it does not stop any other list ' +\n 'reaching them. If somebody asked you to stop, suppress the address.'}\n </Typography>\n </Stack>\n )\n}\nListMembersPanel.displayName = 'ListMembersPanel'\n\nexport default ListMembersPanel\n"],"names":["readMarketingBasis","mdiAccountRemoveOutline","MdiIcon","useConfirmationContext","ListFilterChips","ListPagination","ListRowActions","ListTable","listActionsColumn","inMemoryListField","TABLE_ROW_HEIGHT","usePagedRowsFilter","useSnackbar","Alert","Box","Button","Checkbox","Chip","FormControlLabel","Stack","TextField","Typography","collection","deleteDoc","doc","documentId","limit","orderBy","query","useCallback","useEffect","useMemo","useState","useFirestore","usePagedCollection","useUser","authorizedFetch","consentLabel","member","group","record","when","basisAtMs","Date","toLocaleDateString","basis","key","label","color","assertedBy","otherGrant","MEMBER_FILTER_FIELDS","MEMBER_FILTER_HEADERS","email","name","via","consent","VIA_LABELS","rule","manual","CONSENT_LABELS","attested","none","MEMBER_FILTER_OPTIONS","Object","entries","map","value","MEMBER_SEARCH_FIELDS","withFilterKeys","viaKey","consentKey","splitAddresses","split","entry","trim","replace","filter","Boolean","ListMembersPanel","props","hostId","consentGroup","scope","listId","listName","onMembershipChanged","findRule","ruleSummary","firestore","data","user","enqueueSnackbar","confirm","memberData","rows","memberRows","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","memberWindow","memberPage","memberFilter","fields","options","headers","search","members","addInput","setAddInput","addName","setAddName","preview","setPreview","setAttested","results","setResults","busy","setBusy","found","setFound","addresses","emails","post","route","body","response","method","JSON","stringify","payload","json","catch","ok","handlePreview","length","error","variant","allowDuplicate","handleFind","Number","matched","persist","handleAdd","attestConsent","added","handleRemove","accepted","title","description","confirmationText","confirmationButtonProps","then","$id","console","enrollable","optedIn","needAttestation","columns","field","headerName","flex","minWidth","valueGetter","_value","row","width","addedAt","toDate","getTime","renderCell","direction","spacing","sx","alignItems","size","source","noWrap","String","items","icon","path","destructive","onClick","py","border","borderColor","borderRadius","p","clause","disabled","severity","toLocaleString","truncated","complete","useFlexGap","flexWrap","placeholder","multiline","minRows","maxRows","onChange","event","target","helperText","flexGrow","refused","join","verdicts","verdict","refusal","input","summary","control","checked","result","enrolled","filtering","chipsProps","read","aria-label","filterCol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,aAAa,CAAC/D;wBACpCgE,WAAWxN;wBACX,8DAA8D;wBAC9DyN,UAAU;uBAGNzH,aAAa0H,SAAS;wBAC1BC,aAAY;;kCAEd,KAAChO,6BAAmBqG,aAAa4H,UAAU;;;0BAc/C,KAACjN;gBAAWwH,SAAQ;gBAAU7F,OAAM;0BACjC,mEACC,wEACA,kEACA,sEACA;;0BAGJ,KAAC3B;gBAAWwH,SAAQ;gBAAU7F,OAAM;0BACjC,yEACC,wEACA;;;;AAIV;AACA+B,iBAAiBwJ,WAAW,GAAG;AAE/B,eAAexJ,iBAAgB"}
@@ -14,23 +14,59 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */ 'use client';
17
+ import { _ as _extends } from "@swc/helpers/_/_extends";
17
18
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
18
19
  import { createResourceUid, pluginDocsHelp } from "@aglyn/aglyn";
19
20
  import { mdiDeleteOutline, mdiEyeOutline, mdiPencilOutline } from "@aglyn/shared-data-mdi";
20
21
  import { AppLink, CardDisplay, MdiIcon, useConfirmationContext } from "@aglyn/shared-ui-jsx";
22
+ import ListFilterChips from "@aglyn/shared-ui-jsx/components/list-filter-chips.component";
21
23
  import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.component";
22
24
  import { ListRowActions, ListTable, listActionsColumn } from "@aglyn/shared-ui-jsx/components/list-table.component";
25
+ import { inMemoryListField } from "@aglyn/shared-ui-jsx/const/list-grid-filter";
23
26
  import { TABLE_ROW_HEIGHT } from "@aglyn/shared-ui-jsx/const/table-pagination";
27
+ import { usePagedRowsFilter } from "@aglyn/shared-ui-jsx/hooks/use-paged-rows-filter";
24
28
  import { CreateArtifactDrawer } from "@aglyn/shared-ui-jsx-forms";
25
29
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
26
30
  import { Timestamp } from "@aglyn/shared-util-timestamp";
27
31
  import { Alert, Button, Chip, Stack, Typography } from "@mui/material";
28
32
  import { collection, doc, getCountFromServer, limit, orderBy, query, setDoc } from "firebase/firestore";
29
33
  import { useRouter } from "next/navigation";
30
- import { useEffect, useState } from "react";
34
+ import { useEffect, useMemo, useState } from "react";
31
35
  import { useFirestore, usePagedCollection, useUser } from "@aglyn/tenant-feature-instance";
32
36
  import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
33
37
  import { useEmailDataScope } from "./email-org-mount.js";
38
+ /*
39
+ * What the lists grid's Filters panel offers (AGL-3317). The list is a paged
40
+ * listener, so a filter matches over what its window has read, which the
41
+ * first filter widens (`usePagedRowsFilter`). Membership reads `kindKey`,
42
+ * the stored kind with a list that predates `kind` counted as manual, which
43
+ * is how the column draws it.
44
+ */ const LIST_FILTER_FIELDS = [
45
+ inMemoryListField('name', 'text'),
46
+ inMemoryListField('kind', 'select', 'kindKey')
47
+ ];
48
+ const LIST_FILTER_HEADERS = {
49
+ name: 'List',
50
+ kind: 'Membership'
51
+ };
52
+ const LIST_FILTER_OPTIONS = {
53
+ kind: [
54
+ {
55
+ value: 'manual',
56
+ label: 'Manual'
57
+ },
58
+ {
59
+ value: 'dynamic',
60
+ label: 'Rule'
61
+ }
62
+ ]
63
+ };
64
+ const LIST_SEARCH_FIELDS = [
65
+ 'name'
66
+ ];
67
+ /** A list row with the membership kind the filter matches on. */ const withKindKey = (list)=>_extends({}, list, {
68
+ kindKey: list.kind === 'dynamic' ? 'dynamic' : 'manual'
69
+ });
34
70
  /**
35
71
  * Email lists (AGL-254): static audiences at `orgs/{orgId}/lists`, shared
36
72
  * across the org's sites. Members arrive via the enrollList automation
@@ -78,12 +114,34 @@ import { useEmailDataScope } from "./email-org-mount.js";
78
114
  * newsletter enrollment both resolve an existing list and deliberately
79
115
  * never create one, and `lists` is absent from `IMPORTABLE_FIELDS`, so no
80
116
  * restore path can produce a nameless document for `orderBy` to drop.
81
- */ const { rows: lists, hasMore, page, setPage, pageSize, setPageSize } = usePagedCollection((pageLimit)=>scope ? query(collection(firestore, scope[0], scope[1], 'lists'), orderBy('name'), limit(pageLimit)) : null, [
117
+ */ const { data: listData, rows: listRows, hasMore, page, setPage, pageSize, setPageSize } = usePagedCollection((pageLimit)=>scope ? query(collection(firestore, scope[0], scope[1], 'lists'), orderBy('name'), limit(pageLimit)) : null, [
82
118
  firestore,
83
119
  scope
84
120
  ], {
85
121
  idField: '$id'
86
122
  });
123
+ const listWindow = useMemo(()=>listData == null ? void 0 : listData.map(withKindKey), [
124
+ listData
125
+ ]);
126
+ const listPage = useMemo(()=>listRows.map(withKindKey), [
127
+ listRows
128
+ ]);
129
+ const listFilter = usePagedRowsFilter({
130
+ data: listWindow,
131
+ rows: listPage,
132
+ hasMore,
133
+ page,
134
+ setPage,
135
+ pageSize,
136
+ setPageSize
137
+ }, {
138
+ fields: LIST_FILTER_FIELDS,
139
+ options: LIST_FILTER_OPTIONS,
140
+ headers: LIST_FILTER_HEADERS,
141
+ search: LIST_SEARCH_FIELDS
142
+ });
143
+ // The rows on screen: the page, or the page of the matches.
144
+ const lists = listFilter.rows;
87
145
  const [counts, setCounts] = useState({});
88
146
  useEffect(()=>{
89
147
  // `lists` can only be non-empty when `scope` resolved, but the
@@ -265,7 +323,7 @@ import { useEmailDataScope } from "./email-org-mount.js";
265
323
  headerName: 'Membership',
266
324
  flex: 1,
267
325
  minWidth: 220,
268
- valueGetter: (_value, row)=>row.kind === 'dynamic' ? 'Rule' : 'Manual',
326
+ valueGetter: (_value, row)=>row.kindKey,
269
327
  renderCell: ({ row })=>{
270
328
  var _row_lastEvaluatedAt;
271
329
  return row.kind === 'dynamic' ? /*#__PURE__*/ _jsx(Chip, {
@@ -346,25 +404,26 @@ import { useEmailDataScope } from "./email-org-mount.js";
346
404
  }) : null,
347
405
  includeDescription: false
348
406
  }),
349
- lists.length === 0 ? null : /*#__PURE__*/ _jsxs(_Fragment, {
407
+ listRows.length === 0 && !hasMore && !listFilter.filtering ? null : /*#__PURE__*/ _jsxs(_Fragment, {
350
408
  children: [
351
- /*#__PURE__*/ _jsx(ListTable, {
409
+ /*#__PURE__*/ _jsx(ListFilterChips, _extends({}, listFilter.chipsProps)),
410
+ listFilter.filtering && hasMore ? /*#__PURE__*/ _jsx(Typography, {
411
+ variant: "caption",
412
+ color: "text.secondary",
413
+ children: `Filtering the ${listFilter.read} lists read so far — the next page reads more.`
414
+ }) : null,
415
+ /*#__PURE__*/ _jsx(ListTable, _extends({
352
416
  "aria-label": "Email lists",
353
417
  rows: lists,
354
- columns: columns,
418
+ columns: listFilter.filterColumns(columns),
355
419
  rowHeight: TABLE_ROW_HEIGHT,
356
420
  onOpen: (_id, row)=>router.push(listHref(row)),
357
421
  // Paged by the footer below, so the grid must not also slice.
358
422
  hideFooter: true
359
- }),
360
- /*#__PURE__*/ _jsx(ListPagination, {
361
- page: page,
362
- pageSize: pageSize,
363
- rowCount: lists.length,
364
- hasMore: hasMore,
365
- onPageChange: setPage,
366
- onPageSizeChange: setPageSize
367
- })
423
+ }, listFilter.gridProps, {
424
+ noRowsLabel: "No lists match these filters"
425
+ })),
426
+ /*#__PURE__*/ _jsx(ListPagination, _extends({}, listFilter.pagination))
368
427
  ]
369
428
  })
370
429
  ]
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/email/src/lib/components/lists-card.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 { createResourceUid, pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n mdiDeleteOutline,\n mdiEyeOutline,\n mdiPencilOutline,\n} from '@aglyn/shared-data-mdi'\nimport { AppLink, CardDisplay, MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { CreateArtifactDrawer } from '@aglyn/shared-ui-jsx-forms'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport {\n collection,\n doc,\n getCountFromServer,\n limit,\n orderBy,\n query,\n setDoc,\n} from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport { useEffect, useState } from 'react'\nimport {\n useFirestore,\n usePagedCollection,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { useEmailDataScope } from './email-org-mount'\n\nexport interface OrgListsCardProps {\n /** The site, or `null` on the organization's Emails page. */\n hostId: string | null\n /** The emails hub URL, which every list route hangs beneath. */\n basePath: string\n}\n\n/**\n * Email lists (AGL-254): static audiences at `orgs/{orgId}/lists`, shared\n * across the org's sites. Members arrive via the enrollList automation\n * step, popup email capture, or manual adds; campaigns target a list from\n * the audience picker.\n *\n * ## A list is a resource, so it has pages\n *\n * The row opens `…/audiences/{listId}`, and everything a list can be asked or\n * told lives there or on its edit page. The membership used to expand INSIDE\n * this table, which made three things impossible at once: a merchant could not\n * link anybody to one audience, the browser's back button did not walk out of\n * a list, and the rename lived under a table it was not about.\n *\n * Row click and the row's own link are two affordances rather than one. A\n * click handler cannot be middle-clicked, copied, or opened from the browser's\n * context menu, and a link alone loses the whole-row target.\n */\nexport function OrgListsCard(props: OrgListsCardProps) {\n const { hostId, basePath } = props\n const firestore = useFirestore()\n const router = useRouter()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { data: user } = useUser()\n // The org lookup is async (AGL-1061): `scope` is null until it settles,\n // and stays null for a host with no owning org. Lists have always been\n // org-shared (AGL-254) — there is no host path to fall back to any more\n // (AGL-1050), so creating one is held rather than misdirected. On the\n // organization's page the mount names the org and nothing is looked up.\n const { scope } = useEmailDataScope(hostId)\n\n /*\n * Ordered by the server and paged, rather than capped and re-sorted here\n * (AGL-2501, AGL-2292).\n *\n * `limit(50)` carried no `orderBy`, so Firestore answered it in\n * DOCUMENT-ID order over ids from `createResourceUid()` — an arbitrary\n * fifty of the org's lists, which the `localeCompare` below then arranged\n * alphabetically. An agency past fifty lists saw a believable A-to-Z page\n * that was missing most of the alphabet, and the campaign composer's\n * audience picker reads the same collection.\n *\n * `name` is safe to order on here, which is a claim about the writers and\n * not a preference: this card is the only thing that CREATES a list\n * (`handleCreate` refuses an empty name), the automation step and the\n * newsletter enrollment both resolve an existing list and deliberately\n * never create one, and `lists` is absent from `IMPORTABLE_FIELDS`, so no\n * restore path can produce a nameless document for `orderBy` to drop.\n */\n const {\n rows: lists,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<any>(\n (pageLimit) =>\n scope\n ? query(\n collection(firestore, scope[0], scope[1], 'lists'),\n orderBy('name'),\n limit(pageLimit),\n )\n : null,\n [firestore, scope],\n { idField: '$id' },\n )\n const [counts, setCounts] = useState<Record<string, number>>({})\n useEffect(() => {\n // `lists` can only be non-empty when `scope` resolved, but the\n // effect must say so for itself — it reads `scope` outside the query.\n if (!scope) return undefined\n let active = true\n void Promise.all(\n lists.map(async (list: any) => {\n try {\n const snapshot = await getCountFromServer(\n collection(\n firestore,\n scope[0],\n scope[1],\n 'lists',\n list.$id,\n 'members',\n ),\n )\n return [list.$id, snapshot.data().count] as const\n } catch {\n return [list.$id, 0] as const\n }\n }),\n ).then((entries) => {\n if (active) setCounts(Object.fromEntries(entries))\n })\n return () => {\n active = false\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [firestore, scope, JSON.stringify(lists.map((l: any) => l.$id))])\n\n /*\n * Creating is a DRAWER, and the drawer is the shared one.\n *\n * The card used to carry a name box, a membership select and a Create\n * button stacked above the table. A create form wedged over a list has\n * nowhere to grow, which is how the rule behind a dynamic list came to be\n * authored through four controls out of nine — the form could not hold the\n * rest. Naming happens here; everything the audience IS happens on its edit\n * page, which has the room.\n */\n const [createOpen, setCreateOpen] = useState(false)\n const [createError, setCreateError] = useState<unknown>(null)\n const [creating, setCreating] = useState(false)\n\n const handleCreate = async (values: Record<string, any>) => {\n const name = String(values?.['displayName'] ?? '').trim()\n // Without an org there is nowhere org-shared to put the list, and the\n // host path that used to absorb it is gone (AGL-1050). The button is\n // disabled in this state; this is the same answer for a stale closure.\n if (!name || !scope || creating) return\n setCreating(true)\n setCreateError(null)\n const id = createResourceUid()\n try {\n await setDoc(doc(firestore, scope[0], scope[1], 'lists', id), {\n name,\n /*\n * Manual until somebody says otherwise.\n *\n * A list arrives holding the people you put on it, and becomes\n * rule-driven on its edit page where the rule can actually be\n * written. Offering the choice in the naming drawer would ask for a\n * decision before the thing it decides — a rule — can be seen.\n */\n kind: 'manual',\n createdAt: Timestamp.now(),\n })\n setCreateOpen(false)\n enqueueSnackbar(`List \"${name}\" created`, {\n variant: 'success',\n persist: false,\n })\n router.push(`${basePath}/audiences/${id}`)\n } catch (error) {\n console.error(error)\n setCreateError(error)\n enqueueSnackbar('An error has occurred', { variant: 'error' })\n } finally {\n setCreating(false)\n }\n }\n\n const handleDelete = async (list: any) => {\n if (!scope) return\n const accepted = await confirm({\n title: 'Delete list?',\n description: `\"${list.name}\" and its enrollments stop being targetable; automations enrolling into it start reporting errors.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n // `confirm` resolves with no value and REJECTS on cancel, so gating on\n // the resolved value alone made this always return (AGL-950).\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n // The list owns a `members` subcollection of enrolled contacts, and\n // Firestore doesn't cascade — deleting the doc from here left that PII\n // behind, unreachable but still readable to every org member. Only the\n // Admin SDK can recursiveDelete, so this goes through the erase route\n // (AGL-946).\n try {\n const response = await authorizedFetch(user, '/api/resources/erase', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n scope: scope[0],\n scopeId: scope[1],\n kind: 'lists',\n id: list.$id,\n }),\n })\n const result = await response.json().catch(() => ({}))\n if (!response.ok) throw new Error(result?.error ?? 'List delete failed')\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'List delete failed', {\n variant: 'error',\n })\n }\n enqueueSnackbar('List deleted', { variant: 'success', persist: false })\n }\n\n const listHref = (list: any) => `${basePath}/audiences/${list.$id}`\n\n const rowActions = (list: any): RowActionsMenuItem[] => [\n {\n key: 'details',\n label: 'Open details',\n icon: <MdiIcon path={mdiEyeOutline.path} size={0.8} />,\n href: listHref(list),\n },\n {\n key: 'edit',\n label: 'Edit list',\n icon: <MdiIcon path={mdiPencilOutline.path} size={0.8} />,\n href: `${listHref(list)}/edit`,\n },\n {\n key: 'delete',\n label: 'Delete',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n onClick: () => void handleDelete(list),\n },\n ]\n\n /*\n * One row per list. The name is a link AND the row opens the list: a click\n * handler cannot be middle-clicked, copied or opened from the context menu,\n * and a link alone loses the whole-row target.\n */\n const columns: GridColDef[] = [\n {\n field: 'name',\n headerName: 'List',\n flex: 1,\n minWidth: 200,\n renderCell: ({ row }) => (\n <AppLink\n href={listHref(row)}\n // The row's own handler would fire too and push the same route\n // twice — one history entry per back press.\n onClick={(event: { stopPropagation: () => void }) =>\n event.stopPropagation()\n }\n >\n {row.name}\n </AppLink>\n ),\n },\n {\n field: 'kind',\n headerName: 'Membership',\n flex: 1,\n minWidth: 220,\n valueGetter: (_value, row) =>\n row.kind === 'dynamic' ? 'Rule' : 'Manual',\n renderCell: ({ row }) =>\n row.kind === 'dynamic' ? (\n <Chip\n size=\"small\"\n color=\"primary\"\n variant=\"outlined\"\n /*\n Freshness, not just kind. A dynamic list that has stopped being\n swept looks exactly like one whose population has not changed,\n so the last evaluation time is the only thing that tells them\n apart — and it is the first thing to look at when a merchant\n reports that somebody is missing from an audience.\n */\n label={\n row.lastEvaluatedAt?.toDate\n ? `Rule · ${row.lastEvaluatedAt.toDate().toLocaleString()}`\n : 'Rule · not yet evaluated'\n }\n />\n ) : (\n <Chip size=\"small\" variant=\"outlined\" label=\"Manual\" />\n ),\n },\n {\n field: 'subscribers',\n headerName: 'Subscribers',\n width: 130,\n valueGetter: (_value, row) => counts[row.$id] ?? '…',\n },\n listActionsColumn(\n (row) => (\n <ListRowActions\n label={String(row.name ?? row.$id)}\n items={rowActions(row)}\n />\n ),\n { width: 72 },\n ),\n ]\n\n return (\n <CardDisplay\n header=\"Email lists\"\n help={pluginDocsHelp('emailCampaigns', { anchor: '#email-lists' })}\n contentGutterX\n contentGutterY\n contentBordered=\"all\"\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={!scope || creating}\n onClick={() => setCreateOpen(true)}\n >\n {creating ? 'Creating…' : 'Create audience'}\n </Button>\n ),\n }}\n >\n <Stack spacing={1.5}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Audiences shared across your organization. A manual list holds ' +\n 'the people you enroll into it. A dynamic list holds everyone ' +\n 'matching a rule, re-checked about every fifteen minutes. Target ' +\n 'either from the campaign composer.'}\n </Typography>\n {/*\n A list document stores a name and nothing else descriptive, so the\n shared Description box is refused: a field the writer discards on\n write is worse than a field that was never offered.\n */}\n <CreateArtifactDrawer\n open={createOpen}\n onClose={() => setCreateOpen(false)}\n title=\"Create new audience\"\n submitLabel=\"Create audience\"\n onSubmit={handleCreate}\n errorSlot={\n createError ? (\n <Alert severity=\"error\" sx={{ mt: 2, mb: 1 }}>\n {'This audience could not be created.'}\n </Alert>\n ) : null\n }\n includeDescription={false}\n />\n {lists.length === 0 ? null : (\n <>\n <ListTable\n aria-label=\"Email lists\"\n rows={lists}\n columns={columns}\n rowHeight={TABLE_ROW_HEIGHT}\n onOpen={(_id, row) => router.push(listHref(row))}\n // Paged by the footer below, so the grid must not also slice.\n hideFooter\n />\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={lists.length}\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n </>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nOrgListsCard.displayName = 'OrgListsCard'\n\nexport default OrgListsCard\n"],"names":["createResourceUid","pluginDocsHelp","mdiDeleteOutline","mdiEyeOutline","mdiPencilOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListPagination","ListRowActions","ListTable","listActionsColumn","TABLE_ROW_HEIGHT","CreateArtifactDrawer","useSnackbar","Timestamp","Alert","Button","Chip","Stack","Typography","collection","doc","getCountFromServer","limit","orderBy","query","setDoc","useRouter","useEffect","useState","useFirestore","usePagedCollection","useUser","authorizedFetch","useEmailDataScope","OrgListsCard","props","hostId","basePath","firestore","router","enqueueSnackbar","confirm","data","user","scope","rows","lists","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","counts","setCounts","undefined","active","Promise","all","map","list","snapshot","$id","count","then","entries","Object","fromEntries","JSON","stringify","l","createOpen","setCreateOpen","createError","setCreateError","creating","setCreating","handleCreate","values","name","String","trim","id","kind","createdAt","now","variant","persist","push","error","console","handleDelete","accepted","title","description","confirmationText","confirmationButtonProps","color","catch","response","method","headers","body","scopeId","result","json","ok","Error","message","listHref","rowActions","key","label","icon","path","size","href","destructive","onClick","columns","field","headerName","flex","minWidth","renderCell","row","event","stopPropagation","valueGetter","_value","lastEvaluatedAt","toDate","toLocaleString","width","items","header","help","anchor","contentGutterX","contentGutterY","contentBordered","HeaderProps","action","disabled","spacing","open","onClose","submitLabel","onSubmit","errorSlot","severity","sx","mt","mb","includeDescription","length","a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ACL7B,SAAQ;gBACRyD,UAAU,CAACpG,SAASgC;gBACpB2C,SAAS,IAAM9C,cAAc;0BAE5BG,WAAW,cAAc;;QAGhC;kBAEA,cAAA,MAAC3D;YAAMgI,SAAS;;8BACd,KAAC/H;oBAAWqE,SAAQ;oBAAQW,OAAM;8BAC/B,oEACC,kEACA,qEACA;;8BAOJ,KAACvF;oBACCuI,MAAM1E;oBACN2E,SAAS,IAAM1E,cAAc;oBAC7BqB,OAAM;oBACNsD,aAAY;oBACZC,UAAUvE;oBACVwE,WACE5E,4BACE,KAAC5D;wBAAMyI,UAAS;wBAAQC,IAAI;4BAAEC,IAAI;4BAAGC,IAAI;wBAAE;kCACxC;yBAED;oBAENC,oBAAoB;;gBAErB7G,MAAM8G,MAAM,KAAK,IAAI,qBACpB;;sCACE,KAACpJ;4BACCqJ,cAAW;4BACXhH,MAAMC;4BACN0E,SAASA;4BACTsC,WAAWpJ;4BACXqJ,QAAQ,CAACC,KAAKlC,MAAQvF,OAAOkD,IAAI,CAACqB,SAASgB;4BAC3C,8DAA8D;4BAC9DmC,UAAU;;sCAEZ,KAAC3J;4BACC0C,MAAMA;4BACNE,UAAUA;4BACVgH,UAAUpH,MAAM8G,MAAM;4BACtB7G,SAASA;4BACToH,cAAclH;4BACdmH,kBAAkBjH;;;;;;;AAOhC;AACAjB,aAAamI,WAAW,GAAG;AAE3B,eAAenI,aAAY"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/email/src/lib/components/lists-card.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 { createResourceUid, pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n mdiDeleteOutline,\n mdiEyeOutline,\n mdiPencilOutline,\n} from '@aglyn/shared-data-mdi'\nimport { AppLink, CardDisplay, MdiIcon, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { inMemoryListField } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { usePagedRowsFilter } from '@aglyn/shared-ui-jsx/hooks/use-paged-rows-filter'\nimport { CreateArtifactDrawer } from '@aglyn/shared-ui-jsx-forms'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport {\n collection,\n doc,\n getCountFromServer,\n limit,\n orderBy,\n query,\n setDoc,\n} from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport { useEffect, useMemo, useState } from 'react'\nimport {\n useFirestore,\n usePagedCollection,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { useEmailDataScope } from './email-org-mount'\n\nexport interface OrgListsCardProps {\n /** The site, or `null` on the organization's Emails page. */\n hostId: string | null\n /** The emails hub URL, which every list route hangs beneath. */\n basePath: string\n}\n\n/*\n * What the lists grid's Filters panel offers (AGL-3317). The list is a paged\n * listener, so a filter matches over what its window has read, which the\n * first filter widens (`usePagedRowsFilter`). Membership reads `kindKey`,\n * the stored kind with a list that predates `kind` counted as manual, which\n * is how the column draws it.\n */\nconst LIST_FILTER_FIELDS = [\n inMemoryListField('name', 'text'),\n inMemoryListField('kind', 'select', 'kindKey'),\n]\nconst LIST_FILTER_HEADERS: Readonly<Record<string, string>> = {\n name: 'List',\n kind: 'Membership',\n}\nconst LIST_FILTER_OPTIONS = {\n kind: [\n { value: 'manual', label: 'Manual' },\n { value: 'dynamic', label: 'Rule' },\n ],\n}\nconst LIST_SEARCH_FIELDS = ['name'] as const\n\n/** A list row with the membership kind the filter matches on. */\nconst withKindKey = (list: any) => ({\n ...list,\n kindKey: list.kind === 'dynamic' ? 'dynamic' : 'manual',\n})\n\n/**\n * Email lists (AGL-254): static audiences at `orgs/{orgId}/lists`, shared\n * across the org's sites. Members arrive via the enrollList automation\n * step, popup email capture, or manual adds; campaigns target a list from\n * the audience picker.\n *\n * ## A list is a resource, so it has pages\n *\n * The row opens `…/audiences/{listId}`, and everything a list can be asked or\n * told lives there or on its edit page. The membership used to expand INSIDE\n * this table, which made three things impossible at once: a merchant could not\n * link anybody to one audience, the browser's back button did not walk out of\n * a list, and the rename lived under a table it was not about.\n *\n * Row click and the row's own link are two affordances rather than one. A\n * click handler cannot be middle-clicked, copied, or opened from the browser's\n * context menu, and a link alone loses the whole-row target.\n */\nexport function OrgListsCard(props: OrgListsCardProps) {\n const { hostId, basePath } = props\n const firestore = useFirestore()\n const router = useRouter()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const { data: user } = useUser()\n // The org lookup is async (AGL-1061): `scope` is null until it settles,\n // and stays null for a host with no owning org. Lists have always been\n // org-shared (AGL-254) — there is no host path to fall back to any more\n // (AGL-1050), so creating one is held rather than misdirected. On the\n // organization's page the mount names the org and nothing is looked up.\n const { scope } = useEmailDataScope(hostId)\n\n /*\n * Ordered by the server and paged, rather than capped and re-sorted here\n * (AGL-2501, AGL-2292).\n *\n * `limit(50)` carried no `orderBy`, so Firestore answered it in\n * DOCUMENT-ID order over ids from `createResourceUid()` — an arbitrary\n * fifty of the org's lists, which the `localeCompare` below then arranged\n * alphabetically. An agency past fifty lists saw a believable A-to-Z page\n * that was missing most of the alphabet, and the campaign composer's\n * audience picker reads the same collection.\n *\n * `name` is safe to order on here, which is a claim about the writers and\n * not a preference: this card is the only thing that CREATES a list\n * (`handleCreate` refuses an empty name), the automation step and the\n * newsletter enrollment both resolve an existing list and deliberately\n * never create one, and `lists` is absent from `IMPORTABLE_FIELDS`, so no\n * restore path can produce a nameless document for `orderBy` to drop.\n */\n const {\n data: listData,\n rows: listRows,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<any>(\n (pageLimit) =>\n scope\n ? query(\n collection(firestore, scope[0], scope[1], 'lists'),\n orderBy('name'),\n limit(pageLimit),\n )\n : null,\n [firestore, scope],\n { idField: '$id' },\n )\n const listWindow = useMemo(() => listData?.map(withKindKey), [listData])\n const listPage = useMemo(() => listRows.map(withKindKey), [listRows])\n const listFilter = usePagedRowsFilter<any>(\n {\n data: listWindow,\n rows: listPage,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n },\n {\n fields: LIST_FILTER_FIELDS,\n options: LIST_FILTER_OPTIONS,\n headers: LIST_FILTER_HEADERS,\n search: LIST_SEARCH_FIELDS,\n },\n )\n // The rows on screen: the page, or the page of the matches.\n const lists = listFilter.rows\n const [counts, setCounts] = useState<Record<string, number>>({})\n useEffect(() => {\n // `lists` can only be non-empty when `scope` resolved, but the\n // effect must say so for itself — it reads `scope` outside the query.\n if (!scope) return undefined\n let active = true\n void Promise.all(\n lists.map(async (list: any) => {\n try {\n const snapshot = await getCountFromServer(\n collection(\n firestore,\n scope[0],\n scope[1],\n 'lists',\n list.$id,\n 'members',\n ),\n )\n return [list.$id, snapshot.data().count] as const\n } catch {\n return [list.$id, 0] as const\n }\n }),\n ).then((entries) => {\n if (active) setCounts(Object.fromEntries(entries))\n })\n return () => {\n active = false\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [firestore, scope, JSON.stringify(lists.map((l: any) => l.$id))])\n\n /*\n * Creating is a DRAWER, and the drawer is the shared one.\n *\n * The card used to carry a name box, a membership select and a Create\n * button stacked above the table. A create form wedged over a list has\n * nowhere to grow, which is how the rule behind a dynamic list came to be\n * authored through four controls out of nine — the form could not hold the\n * rest. Naming happens here; everything the audience IS happens on its edit\n * page, which has the room.\n */\n const [createOpen, setCreateOpen] = useState(false)\n const [createError, setCreateError] = useState<unknown>(null)\n const [creating, setCreating] = useState(false)\n\n const handleCreate = async (values: Record<string, any>) => {\n const name = String(values?.['displayName'] ?? '').trim()\n // Without an org there is nowhere org-shared to put the list, and the\n // host path that used to absorb it is gone (AGL-1050). The button is\n // disabled in this state; this is the same answer for a stale closure.\n if (!name || !scope || creating) return\n setCreating(true)\n setCreateError(null)\n const id = createResourceUid()\n try {\n await setDoc(doc(firestore, scope[0], scope[1], 'lists', id), {\n name,\n /*\n * Manual until somebody says otherwise.\n *\n * A list arrives holding the people you put on it, and becomes\n * rule-driven on its edit page where the rule can actually be\n * written. Offering the choice in the naming drawer would ask for a\n * decision before the thing it decides — a rule — can be seen.\n */\n kind: 'manual',\n createdAt: Timestamp.now(),\n })\n setCreateOpen(false)\n enqueueSnackbar(`List \"${name}\" created`, {\n variant: 'success',\n persist: false,\n })\n router.push(`${basePath}/audiences/${id}`)\n } catch (error) {\n console.error(error)\n setCreateError(error)\n enqueueSnackbar('An error has occurred', { variant: 'error' })\n } finally {\n setCreating(false)\n }\n }\n\n const handleDelete = async (list: any) => {\n if (!scope) return\n const accepted = await confirm({\n title: 'Delete list?',\n description: `\"${list.name}\" and its enrollments stop being targetable; automations enrolling into it start reporting errors.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n // `confirm` resolves with no value and REJECTS on cancel, so gating on\n // the resolved value alone made this always return (AGL-950).\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n // The list owns a `members` subcollection of enrolled contacts, and\n // Firestore doesn't cascade — deleting the doc from here left that PII\n // behind, unreachable but still readable to every org member. Only the\n // Admin SDK can recursiveDelete, so this goes through the erase route\n // (AGL-946).\n try {\n const response = await authorizedFetch(user, '/api/resources/erase', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n scope: scope[0],\n scopeId: scope[1],\n kind: 'lists',\n id: list.$id,\n }),\n })\n const result = await response.json().catch(() => ({}))\n if (!response.ok) throw new Error(result?.error ?? 'List delete failed')\n } catch (error: any) {\n return void enqueueSnackbar(error?.message ?? 'List delete failed', {\n variant: 'error',\n })\n }\n enqueueSnackbar('List deleted', { variant: 'success', persist: false })\n }\n\n const listHref = (list: any) => `${basePath}/audiences/${list.$id}`\n\n const rowActions = (list: any): RowActionsMenuItem[] => [\n {\n key: 'details',\n label: 'Open details',\n icon: <MdiIcon path={mdiEyeOutline.path} size={0.8} />,\n href: listHref(list),\n },\n {\n key: 'edit',\n label: 'Edit list',\n icon: <MdiIcon path={mdiPencilOutline.path} size={0.8} />,\n href: `${listHref(list)}/edit`,\n },\n {\n key: 'delete',\n label: 'Delete',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n onClick: () => void handleDelete(list),\n },\n ]\n\n /*\n * One row per list. The name is a link AND the row opens the list: a click\n * handler cannot be middle-clicked, copied or opened from the context menu,\n * and a link alone loses the whole-row target.\n */\n const columns: GridColDef[] = [\n {\n field: 'name',\n headerName: 'List',\n flex: 1,\n minWidth: 200,\n renderCell: ({ row }) => (\n <AppLink\n href={listHref(row)}\n // The row's own handler would fire too and push the same route\n // twice — one history entry per back press.\n onClick={(event: { stopPropagation: () => void }) =>\n event.stopPropagation()\n }\n >\n {row.name}\n </AppLink>\n ),\n },\n {\n field: 'kind',\n headerName: 'Membership',\n flex: 1,\n minWidth: 220,\n valueGetter: (_value, row) => row.kindKey,\n renderCell: ({ row }) =>\n row.kind === 'dynamic' ? (\n <Chip\n size=\"small\"\n color=\"primary\"\n variant=\"outlined\"\n /*\n Freshness, not just kind. A dynamic list that has stopped being\n swept looks exactly like one whose population has not changed,\n so the last evaluation time is the only thing that tells them\n apart — and it is the first thing to look at when a merchant\n reports that somebody is missing from an audience.\n */\n label={\n row.lastEvaluatedAt?.toDate\n ? `Rule · ${row.lastEvaluatedAt.toDate().toLocaleString()}`\n : 'Rule · not yet evaluated'\n }\n />\n ) : (\n <Chip size=\"small\" variant=\"outlined\" label=\"Manual\" />\n ),\n },\n {\n field: 'subscribers',\n headerName: 'Subscribers',\n width: 130,\n valueGetter: (_value, row) => counts[row.$id] ?? '…',\n },\n listActionsColumn(\n (row) => (\n <ListRowActions\n label={String(row.name ?? row.$id)}\n items={rowActions(row)}\n />\n ),\n { width: 72 },\n ),\n ]\n\n return (\n <CardDisplay\n header=\"Email lists\"\n help={pluginDocsHelp('emailCampaigns', { anchor: '#email-lists' })}\n contentGutterX\n contentGutterY\n contentBordered=\"all\"\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={!scope || creating}\n onClick={() => setCreateOpen(true)}\n >\n {creating ? 'Creating…' : 'Create audience'}\n </Button>\n ),\n }}\n >\n <Stack spacing={1.5}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Audiences shared across your organization. A manual list holds ' +\n 'the people you enroll into it. A dynamic list holds everyone ' +\n 'matching a rule, re-checked about every fifteen minutes. Target ' +\n 'either from the campaign composer.'}\n </Typography>\n {/*\n A list document stores a name and nothing else descriptive, so the\n shared Description box is refused: a field the writer discards on\n write is worse than a field that was never offered.\n */}\n <CreateArtifactDrawer\n open={createOpen}\n onClose={() => setCreateOpen(false)}\n title=\"Create new audience\"\n submitLabel=\"Create audience\"\n onSubmit={handleCreate}\n errorSlot={\n createError ? (\n <Alert severity=\"error\" sx={{ mt: 2, mb: 1 }}>\n {'This audience could not be created.'}\n </Alert>\n ) : null\n }\n includeDescription={false}\n />\n {listRows.length === 0 && !hasMore && !listFilter.filtering ? null : (\n <>\n <ListFilterChips {...listFilter.chipsProps} />\n {listFilter.filtering && hasMore ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Filtering the ${listFilter.read} lists read so far — the next page reads more.`}\n </Typography>\n ) : null}\n <ListTable\n aria-label=\"Email lists\"\n rows={lists}\n columns={listFilter.filterColumns(columns)}\n rowHeight={TABLE_ROW_HEIGHT}\n onOpen={(_id, row) => router.push(listHref(row))}\n // Paged by the footer below, so the grid must not also slice.\n hideFooter\n // The panel and the search are the grid's; the card answers\n // them over what its window read.\n {...listFilter.gridProps}\n noRowsLabel=\"No lists match these filters\"\n />\n <ListPagination {...listFilter.pagination} />\n </>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nOrgListsCard.displayName = 'OrgListsCard'\n\nexport default OrgListsCard\n"],"names":["createResourceUid","pluginDocsHelp","mdiDeleteOutline","mdiEyeOutline","mdiPencilOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListFilterChips","ListPagination","ListRowActions","ListTable","listActionsColumn","inMemoryListField","TABLE_ROW_HEIGHT","usePagedRowsFilter","CreateArtifactDrawer","useSnackbar","Timestamp","Alert","Button","Chip","Stack","Typography","collection","doc","getCountFromServer","limit","orderBy","query","setDoc","useRouter","useEffect","useMemo","useState","useFirestore","usePagedCollection","useUser","authorizedFetch","useEmailDataScope","LIST_FILTER_FIELDS","LIST_FILTER_HEADERS","name","kind","LIST_FILTER_OPTIONS","value","label","LIST_SEARCH_FIELDS","withKindKey","list","kindKey","OrgListsCard","props","hostId","basePath","firestore","router","enqueueSnackbar","confirm","data","user","scope","listData","rows","listRows","hasMore","page","setPage","pageSize","setPageSize","pageLimit","idField","listWindow","map","listPage","listFilter","fields","options","headers","search","lists","counts","setCounts","undefined","active","Promise","all","snapshot","$id","count","then","entries","Object","fromEntries","JSON","stringify","l","createOpen","setCreateOpen","createError","setCreateError","creating","setCreating","handleCreate","values","String","trim","id","createdAt","now","variant","persist","push","error","console","handleDelete","accepted","title","description","confirmationText","confirmationButtonProps","color","catch","response","method","body","scopeId","result","json","ok","Error","message","listHref","rowActions","key","icon","path","size","href","destructive","onClick","columns","field","headerName","flex","minWidth","renderCell","row","event","stopPropagation","valueGetter","_value","lastEvaluatedAt","toDate","toLocaleString","width","items","header","help","anchor","contentGutterX","contentGutterY","contentBordered","HeaderProps","action","disabled","spacing","open","onClose","submitLabel","onSubmit","errorSlot","severity","sx","mt","mb","includeDescription","length","filtering","chipsProps","read","aria-label","filterColumns","rowHeight","onOpen","_id","hideFooter","gridProps","noRowsLabel","pagination","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,iBAAiB,EAAEC,cAAc,QAAQ,eAAc;AAChE,SACEC,gBAAgB,EAChBC,aAAa,EACbC,gBAAgB,QACX,yBAAwB;AAC/B,SAASC,OAAO,EAAEC,WAAW,EAAEC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC5F,OAAOC,qBAAqB,8DAA6D;AACzF,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAE7D,SAASC,iBAAiB,QAAQ,8CAA6C;AAC/E,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,kBAAkB,QAAQ,mDAAkD;AACrF,SAASC,oBAAoB,QAAQ,6BAA4B;AACjE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SAASC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AAEtE,SACEC,UAAU,EACVC,GAAG,EACHC,kBAAkB,EAClBC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,MAAM,QACD,qBAAoB;AAC3B,SAASC,SAAS,QAAQ,kBAAiB;AAC3C,SAASC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACpD,SACEC,YAAY,EACZC,kBAAkB,EAClBC,OAAO,QACF,iCAAgC;AACvC,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