@aglyn/plugins-email 1.0.0-beta.199 → 1.0.0-beta.201

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/email-screens-card.d.ts +8 -9
  3. package/src/lib/components/email-screens-card.js +83 -100
  4. package/src/lib/components/email-screens-card.js.map +1 -1
  5. package/src/lib/components/email-template-detail.js +3 -2
  6. package/src/lib/components/email-template-detail.js.map +1 -1
  7. package/src/lib/components/list-edit-card.js +2 -2
  8. package/src/lib/components/list-edit-card.js.map +1 -1
  9. package/src/lib/components/list-members-panel.js +72 -93
  10. package/src/lib/components/list-members-panel.js.map +1 -1
  11. package/src/lib/components/lists-card.js +70 -77
  12. package/src/lib/components/lists-card.js.map +1 -1
  13. package/src/lib/components/org-email-templates-card.d.ts +10 -6
  14. package/src/lib/components/org-email-templates-card.js +145 -90
  15. package/src/lib/components/org-email-templates-card.js.map +1 -1
  16. package/src/lib/components/suppressions-card.js +73 -69
  17. package/src/lib/components/suppressions-card.js.map +1 -1
  18. package/src/lib/constants/list-queries.d.ts +34 -0
  19. package/src/lib/constants/list-queries.js +256 -0
  20. package/src/lib/constants/list-queries.js.map +1 -0
  21. package/src/lib/server-email-drafts.js +6 -4
  22. package/src/lib/server-email-drafts.js.map +1 -1
  23. package/src/lib/server-suppressions.js +3 -1
  24. package/src/lib/server-suppressions.js.map +1 -1
  25. package/src/lib/server.js +3 -1
  26. package/src/lib/server.js.map +1 -1
  27. package/src/lib/utils/email-template-soft-delete.d.ts +39 -0
  28. package/src/lib/utils/email-template-soft-delete.js +41 -0
  29. package/src/lib/utils/email-template-soft-delete.js.map +1 -0
@@ -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 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","filterColumns","rowHeight","hideFooter","gridProps","noRowsLabel","pagination","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,OAAOC,qBAAqB,8DAA6D;AACzF,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SACEC,cAAc,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J,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 ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-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 { collection, deleteDoc, doc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useListQuery } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n LIST_MEMBER_FILTER_HEADERS,\n LIST_MEMBER_FILTER_OPTIONS,\n LIST_MEMBER_QUERY,\n} from '../constants/list-queries'\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/** How a member got here, by the words the column draws. */\nconst VIA_LABELS: Readonly<Record<'rule' | 'manual', string>> = {\n rule: 'Rule',\n manual: 'Added',\n}\n/** The How filter's choices are picked, so the panel shows a select. */\nconst MEMBER_SELECT_FIELDS = ['via']\n\n/** How a row reads `via`: a row that predates the field was added by hand. */\nconst viaOf = (member: MemberRow): 'rule' | 'manual' =>\n member.via === 'rule' ? 'rule' : 'manual'\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 * Every filter and search word is a predicate on the same query\n * (AGL-3321) — see `LIST_MEMBER_QUERY` — so a page is a page of the\n * matches.\n */\n const gridFilter = useListGridFilter({ selectFields: MEMBER_SELECT_FIELDS })\n const {\n rows: members,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n plan,\n } = useListQuery<MemberRow>({\n collection: collection(firestore, scope[0], scope[1], 'lists', listId, 'members'),\n declaration: LIST_MEMBER_QUERY,\n request: { clauses: gridFilter.clauses, search: gridFilter.searchWords },\n deps: [firestore, scope[0], scope[1], listId],\n idField: '$id',\n })\n const filtering =\n gridFilter.clauses.length > 0 || gridFilter.searchWords.some((word) => word.trim())\n const refusals = useMemo(\n () =>\n listQueryRefusals(plan.refused, {\n fields: LIST_MEMBER_QUERY.fields,\n headers: LIST_MEMBER_FILTER_HEADERS,\n options: LIST_MEMBER_FILTER_OPTIONS,\n }),\n [plan.refused],\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) => viaOf(row),\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[viaOf(row)]} />\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 && !hasMore && !filtering ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Nobody is on this list yet.'}\n </Typography>\n ) : (\n <>\n <ListFilterChips\n fields={LIST_MEMBER_QUERY.fields}\n headers={LIST_MEMBER_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={LIST_MEMBER_FILTER_OPTIONS}\n />\n <ListQueryNotices refused={refusals} notices={plan.notices} />\n <ListTable\n aria-label={`Members of ${listName}`}\n rows={members}\n columns={listFilterGridColumns(\n columns,\n LIST_MEMBER_QUERY.fields,\n LIST_MEMBER_FILTER_OPTIONS,\n LIST_MEMBER_FILTER_HEADERS,\n )}\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 go to the query; the grid neither\n // filters nor sorts the page it holds.\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n disableColumnSorting\n noRowsLabel=\"No members match these filters\"\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","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListRowActions","ListTable","listActionsColumn","listFilterGridColumns","TABLE_ROW_HEIGHT","useListGridFilter","useSnackbar","Alert","Box","Button","Checkbox","Chip","FormControlLabel","Stack","TextField","Typography","collection","deleteDoc","doc","useCallback","useEffect","useMemo","useState","useFirestore","useUser","useListQuery","authorizedFetch","LIST_MEMBER_FILTER_HEADERS","LIST_MEMBER_FILTER_OPTIONS","LIST_MEMBER_QUERY","consentLabel","member","group","record","when","basisAtMs","Date","toLocaleDateString","basis","key","label","color","assertedBy","otherGrant","VIA_LABELS","rule","manual","MEMBER_SELECT_FIELDS","viaOf","via","splitAddresses","value","split","map","entry","trim","replace","filter","Boolean","ListMembersPanel","props","hostId","consentGroup","scope","listId","listName","onMembershipChanged","findRule","ruleSummary","firestore","data","user","enqueueSnackbar","confirm","gridFilter","selectFields","rows","members","hasMore","page","setPage","pageSize","setPageSize","plan","declaration","request","clauses","search","searchWords","deps","idField","filtering","length","some","word","refusals","refused","fields","headers","options","addInput","setAddInput","addName","setAddName","preview","setPreview","attested","setAttested","results","setResults","busy","setBusy","found","setFound","addresses","emails","post","route","body","response","method","JSON","stringify","payload","json","catch","ok","handlePreview","error","variant","allowDuplicate","handleFind","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","direction","spacing","sx","alignItems","size","source","noWrap","consent","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","join","verdicts","verdict","refusal","input","summary","control","checked","result","enrolled","setClauses","notices","aria-label","rowHeight","hideFooter","filterMode","filterModel","onFilterModelChange","quickFilter","disableColumnSorting","noRowsLabel","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,OAAOC,qBAAqB,8DAA6D;AACzF,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,oBACLC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,iBAAiB,QAAQ,kD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;;kCAC1D,KAACnN;wBACCoN,cAAY,CAAC,WAAW,EAAEpJ,UAAU;wBACpCW,MAAMC;wBACN2E,SAASrJ,sBACPqJ,SACA3H,kBAAkBoE,MAAM,EACxBrE,4BACAD;wBAEF2L,WAAWlN;wBACX,8DAA8D;wBAC9DmN,UAAU;wBACV,6DAA6D;wBAC7D,uCAAuC;wBACvCC,YAAW;wBACXC,aAAa/I,WAAW+I,WAAW;wBACnCC,qBAAqBhJ,WAAWgJ,mBAAmB;wBACnDC,WAAW;wBACXC,oBAAoB;wBACpBC,aAAY;;kCAEd,KAAChO;wBACCkF,MAAMA;wBACNE,UAAUA;wBACV6I,UAAUjJ,QAAQe,MAAM;wBACxBd,SAASA;wBACTiJ,cAAc/I;wBACdgJ,kBAAkB9I;;;;0BAexB,KAACnE;gBAAWkH,SAAQ;gBAAUxF,OAAM;0BACjC,mEACC,wEACA,kEACA,sEACA;;0BAGJ,KAAC1B;gBAAWkH,SAAQ;gBAAUxF,OAAM;0BACjC,yEACC,wEACA;;;;AAIV;AACAkB,iBAAiBsK,WAAW,GAAG;AAE/B,eAAetK,iBAAgB"}
@@ -17,56 +17,31 @@
17
17
  import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
19
19
  import { createResourceUid, pluginDocsHelp } from "@aglyn/aglyn";
20
+ import { nameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
20
21
  import { mdiDeleteOutline, mdiEyeOutline, mdiPencilOutline } from "@aglyn/shared-data-mdi";
21
22
  import { AppLink, CardDisplay, MdiIcon, useConfirmationContext } from "@aglyn/shared-ui-jsx";
22
23
  import ListFilterChips from "@aglyn/shared-ui-jsx/components/list-filter-chips.component";
23
24
  import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.component";
25
+ import ListQueryNotices, { listQueryRefusals } from "@aglyn/shared-ui-jsx/components/list-query-notices.component";
24
26
  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";
27
+ import { listFilterGridColumns } from "@aglyn/shared-ui-jsx/const/list-grid-filter";
26
28
  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";
29
+ import { useListGridFilter } from "@aglyn/shared-ui-jsx/hooks/use-list-grid-filter";
28
30
  import { CreateArtifactDrawer } from "@aglyn/shared-ui-jsx-forms";
29
31
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
30
32
  import { Timestamp } from "@aglyn/shared-util-timestamp";
31
33
  import { Alert, Button, Chip, Stack, Typography } from "@mui/material";
32
- import { collection, doc, getCountFromServer, limit, orderBy, query, setDoc } from "firebase/firestore";
34
+ import { collection, doc, getCountFromServer, setDoc } from "firebase/firestore";
33
35
  import { useRouter } from "next/navigation";
34
36
  import { useEffect, useMemo, useState } from "react";
35
- import { useFirestore, usePagedCollection, useUser } from "@aglyn/tenant-feature-instance";
37
+ import { useFirestore, useUser } from "@aglyn/tenant-feature-instance";
38
+ import { useListQuery } from "@aglyn/tenant-feature-instance/hooks/use-list-query";
36
39
  import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
40
+ import { EMAIL_LIST_FILTER_HEADERS, EMAIL_LIST_FILTER_OPTIONS, EMAIL_LIST_QUERY } from "../constants/list-queries.js";
37
41
  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')
42
+ /** The Membership filter's choices are picked, so the panel shows a select. */ const LIST_SELECT_FIELDS = [
43
+ 'kind'
47
44
  ];
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
- });
70
45
  /**
71
46
  * Email lists (AGL-254): static audiences at `orgs/{orgId}/lists`, shared
72
47
  * across the org's sites. Members arrive via the enrollList automation
@@ -114,34 +89,34 @@ const LIST_SEARCH_FIELDS = [
114
89
  * newsletter enrollment both resolve an existing list and deliberately
115
90
  * never create one, and `lists` is absent from `IMPORTABLE_FIELDS`, so no
116
91
  * restore path can produce a nameless document for `orderBy` to drop.
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, [
118
- firestore,
119
- scope
120
- ], {
92
+ *
93
+ * Every filter and search word is a predicate on the same query
94
+ * (AGL-3321), so a page is a page of the matches — see `EMAIL_LIST_QUERY`.
95
+ */ const gridFilter = useListGridFilter({
96
+ selectFields: LIST_SELECT_FIELDS
97
+ });
98
+ const { rows: lists, hasMore, page, setPage, pageSize, setPageSize, plan } = useListQuery({
99
+ collection: scope ? collection(firestore, scope[0], scope[1], 'lists') : null,
100
+ declaration: EMAIL_LIST_QUERY,
101
+ request: {
102
+ clauses: gridFilter.clauses,
103
+ search: gridFilter.searchWords
104
+ },
105
+ deps: [
106
+ firestore,
107
+ scope == null ? void 0 : scope[0],
108
+ scope == null ? void 0 : scope[1]
109
+ ],
121
110
  idField: '$id'
122
111
  });
123
- const listWindow = useMemo(()=>listData == null ? void 0 : listData.map(withKindKey), [
124
- listData
112
+ const filtering = gridFilter.clauses.length > 0 || gridFilter.searchWords.some((word)=>word.trim());
113
+ const refusals = useMemo(()=>listQueryRefusals(plan.refused, {
114
+ fields: EMAIL_LIST_QUERY.fields,
115
+ headers: EMAIL_LIST_FILTER_HEADERS,
116
+ options: EMAIL_LIST_FILTER_OPTIONS
117
+ }), [
118
+ plan.refused
125
119
  ]);
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;
145
120
  const [counts, setCounts] = useState({});
146
121
  useEffect(()=>{
147
122
  // `lists` can only be non-empty when `scope` resolved, but the
@@ -196,8 +171,7 @@ const LIST_SEARCH_FIELDS = [
196
171
  setCreateError(null);
197
172
  const id = createResourceUid();
198
173
  try {
199
- await setDoc(doc(firestore, scope[0], scope[1], 'lists', id), {
200
- name,
174
+ await setDoc(doc(firestore, scope[0], scope[1], 'lists', id), _extends({}, nameSearchFields(name), {
201
175
  /*
202
176
  * Manual until somebody says otherwise.
203
177
  *
@@ -207,7 +181,7 @@ const LIST_SEARCH_FIELDS = [
207
181
  * decision before the thing it decides — a rule — can be seen.
208
182
  */ kind: 'manual',
209
183
  createdAt: Timestamp.now()
210
- });
184
+ }));
211
185
  setCreateOpen(false);
212
186
  enqueueSnackbar(`List "${name}" created`, {
213
187
  variant: 'success',
@@ -323,7 +297,8 @@ const LIST_SEARCH_FIELDS = [
323
297
  headerName: 'Membership',
324
298
  flex: 1,
325
299
  minWidth: 220,
326
- valueGetter: (_value, row)=>row.kindKey,
300
+ // A list that predates `kind` is a manual one.
301
+ valueGetter: (_value, row)=>row.kind === 'dynamic' ? 'dynamic' : 'manual',
327
302
  renderCell: ({ row })=>{
328
303
  var _row_lastEvaluatedAt;
329
304
  return row.kind === 'dynamic' ? /*#__PURE__*/ _jsx(Chip, {
@@ -404,26 +379,44 @@ const LIST_SEARCH_FIELDS = [
404
379
  }) : null,
405
380
  includeDescription: false
406
381
  }),
407
- listRows.length === 0 && !hasMore && !listFilter.filtering ? null : /*#__PURE__*/ _jsxs(_Fragment, {
382
+ lists.length === 0 && !hasMore && !filtering ? null : /*#__PURE__*/ _jsxs(_Fragment, {
408
383
  children: [
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({
384
+ /*#__PURE__*/ _jsx(ListFilterChips, {
385
+ fields: EMAIL_LIST_QUERY.fields,
386
+ headers: EMAIL_LIST_FILTER_HEADERS,
387
+ clauses: gridFilter.clauses,
388
+ onChange: gridFilter.setClauses,
389
+ options: EMAIL_LIST_FILTER_OPTIONS
390
+ }),
391
+ /*#__PURE__*/ _jsx(ListQueryNotices, {
392
+ refused: refusals,
393
+ notices: plan.notices
394
+ }),
395
+ /*#__PURE__*/ _jsx(ListTable, {
416
396
  "aria-label": "Email lists",
417
397
  rows: lists,
418
- columns: listFilter.filterColumns(columns),
398
+ columns: listFilterGridColumns(columns, EMAIL_LIST_QUERY.fields, EMAIL_LIST_FILTER_OPTIONS, EMAIL_LIST_FILTER_HEADERS),
419
399
  rowHeight: TABLE_ROW_HEIGHT,
420
400
  onOpen: (_id, row)=>router.push(listHref(row)),
421
401
  // Paged by the footer below, so the grid must not also slice.
422
- hideFooter: true
423
- }, listFilter.gridProps, {
402
+ hideFooter: true,
403
+ // The panel and the search go to the query; the grid neither
404
+ // filters nor sorts the page it holds.
405
+ filterMode: "server",
406
+ filterModel: gridFilter.filterModel,
407
+ onFilterModelChange: gridFilter.onFilterModelChange,
408
+ quickFilter: true,
409
+ disableColumnSorting: true,
424
410
  noRowsLabel: "No lists match these filters"
425
- })),
426
- /*#__PURE__*/ _jsx(ListPagination, _extends({}, listFilter.pagination))
411
+ }),
412
+ /*#__PURE__*/ _jsx(ListPagination, {
413
+ page: page,
414
+ pageSize: pageSize,
415
+ rowCount: lists.length,
416
+ hasMore: hasMore,
417
+ onPageChange: setPage,
418
+ onPageSizeChange: setPageSize
419
+ })
427
420
  ]
428
421
  })
429
422
  ]