@aglyn/plugins-marketing 1.0.0-beta.232 → 1.0.0-beta.233

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 (34) hide show
  1. package/package.json +16 -16
  2. package/src/lib/components/campaign-conversions-card.js +58 -15
  3. package/src/lib/components/campaign-conversions-card.js.map +1 -1
  4. package/src/lib/components/campaign-detail-card.js +50 -5
  5. package/src/lib/components/campaign-detail-card.js.map +1 -1
  6. package/src/lib/components/campaign-members-section.js +36 -8
  7. package/src/lib/components/campaign-members-section.js.map +1 -1
  8. package/src/lib/components/campaigns-card.js +64 -10
  9. package/src/lib/components/campaigns-card.js.map +1 -1
  10. package/src/lib/components/email-recipients-card.js +37 -2
  11. package/src/lib/components/email-recipients-card.js.map +1 -1
  12. package/src/lib/components/emails-list-card.js +59 -6
  13. package/src/lib/components/emails-list-card.js.map +1 -1
  14. package/src/lib/components/host-experiments-card.component.js +32 -6
  15. package/src/lib/components/host-experiments-card.component.js.map +1 -1
  16. package/src/lib/components/staff-org-email-card.component.js +82 -6
  17. package/src/lib/components/staff-org-email-card.component.js.map +1 -1
  18. package/src/lib/model/campaign-conversions.d.ts +2 -0
  19. package/src/lib/model/campaign-conversions.js +32 -0
  20. package/src/lib/model/campaign-conversions.js.map +1 -1
  21. package/src/lib/model/campaign-list-query.d.ts +6 -2
  22. package/src/lib/model/campaign-list-query.js +64 -9
  23. package/src/lib/model/campaign-list-query.js.map +1 -1
  24. package/src/lib/model/campaign-members-query.d.ts +2 -1
  25. package/src/lib/model/campaign-members-query.js +23 -1
  26. package/src/lib/model/campaign-members-query.js.map +1 -1
  27. package/src/lib/model/experiment-list-query.js +30 -2
  28. package/src/lib/model/experiment-list-query.js.map +1 -1
  29. package/src/lib/model/native-vocabulary.d.ts +26 -0
  30. package/src/lib/model/native-vocabulary.js +31 -0
  31. package/src/lib/model/native-vocabulary.js.map +1 -0
  32. package/src/lib/server/campaign-manage.d.ts +1 -1
  33. package/src/lib/server/campaign-manage.js +1 -0
  34. package/src/lib/server/campaign-manage.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/campaigns-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 { buildRoute, createResourceUid, pluginDocsHelp, Route } from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers — a spec that mocks\n * `@aglyn/tenant-feature-instance` wholesale to stage its Firestore hooks\n * would otherwise lose them, and neither is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { useListQuery } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { mdiDeleteOutline, mdiEyeOutline } from '@aglyn/shared-data-mdi'\nimport {\n AppLink,\n CardDisplay,\n MdiIcon,\n useConfirmationContext,\n} 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 { hiddenFilterVisibility } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport {\n type ListFilterClause,\n listFilterGridColumns,\n} from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Button,\n Chip,\n Stack,\n ToggleButton,\n ToggleButtonGroup,\n Typography,\n} from '@mui/material'\nimport { collection, limit, query, setDoc, where } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useRouter } from 'next/navigation'\nimport {\n useConsoleHostRoute,\n useFirestore,\n useFirestoreCollection,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n campaignListRows,\n campaignSiteIds,\n campaignVisibleTo,\n type CampaignAggregate,\n type CampaignListRow,\n type CampaignSend,\n type EmailCampaign,\n} from '../model/campaign-container'\nimport { CreateArtifactDrawer } from '@aglyn/shared-ui-jsx-forms'\nimport {\n CAMPAIGN_SITE_SEARCH_NOTICE,\n SINGLE_SENDS_BASE,\n campaignContainerSearchFields,\n campaignContainersListQuery,\n campaignContainersScope,\n campaignSendsScope,\n campaignSingleSendsListQuery,\n campaignSiteSearchClause,\n} from '../model/campaign-list-query'\nimport {\n campaignContainerDoc,\n campaignContainersCollection,\n campaignSendsCollection,\n} from './campaign-queries'\nimport {\n orgSiteName,\n orgSiteOptions,\n topicCatalogHostId,\n useMarketingOrgId,\n useMarketingOrgMount,\n type MarketingOrgMount,\n} from './marketing-org-mount'\nimport { useCampaignManageApi } from './use-campaign-send-api'\nimport { HostCampaignsZone } from './campaign-list-zones'\nimport { useCampaignTopicOptions } from './use-campaign-topic-options'\n\n/**\n * How many emails one read of a page's campaigns covers, for their figures.\n *\n * A ceiling on the ROLLUP read, not on the list: the list is paged by its\n * own query, and this reads the emails of the campaigns on the page on\n * screen, thirty campaigns to a read (`in` takes thirty ids), so the largest\n * page is two reads of this many. Past it, the figures say so.\n */\nconst ROLLUP_CEILING = 50\n\n/** Firestore's cap on an `in` clause's values. */\nconst IN_LIMIT = 30\n\n/** Which kind of row the table shows: the two are separate queries. */\ntype CampaignListKind = 'campaign' | 'single'\n\nconst formatDay = (ms: number | null): string =>\n ms === null ? '' : new Date(ms).toLocaleDateString()\n\n/** A rolled-up figure, or an em dash where nothing recorded one. */\nconst figure = (value: CampaignAggregate): string =>\n value.value === null ? '—' : value.value.toLocaleString()\n\nconst WINDOW_LABEL: Record<CampaignListRow['windowState'], string> = {\n undated: 'No dates',\n upcoming: 'Upcoming',\n running: 'Running',\n ended: 'Ended',\n}\n\n/*\n * What the campaigns grid's Filters panel offers, each clause and the search\n * on the list's Firestore query (AGL-3321, `campaignContainersListQuery` and\n * `campaignSingleSendsListQuery`). The Window column is derived from a\n * campaign's dates against the clock, which no query can ask, so it is not\n * offered; the one date range is Created, the list's own order.\n */\nconst CAMPAIGN_FILTER_HEADERS: Record<CampaignListKind, Readonly<Record<string, string>>> = {\n campaign: {\n name: 'Campaign',\n listIds: 'Lists',\n sitesLabel: 'Sites',\n createdAtMs: 'Created',\n },\n // A single send has no container; its `name` field filters by the subject.\n single: {\n name: 'Subject',\n sitesLabel: 'Sites',\n createdAtMs: 'Created',\n },\n}\nconst NO_CLAUSES: Record<CampaignListKind, ListFilterClause[]> = {\n campaign: [],\n single: [],\n}\n\n/**\n * THE CAMPAIGNS LIST.\n *\n * A campaign is a container — a name, a window, the lists it is aimed at, and\n * the emails sent inside it — so this is a table of campaigns and not of\n * messages. Composing is not here: a message belongs to a campaign, and the\n * campaign's own page is where one is written.\n *\n * The rows come from two collections. `emailCampaigns` holds the\n * containers. `campaigns` holds every send, including thousands written\n * before containers existed; those carry no container (`emailCampaignId`\n * null), and `campaignListRows` presents each as a campaign of one rather\n * than dropping it. The two are two queries, so the table lists one kind at a\n * time — Campaigns or Single sends — each paged by its own query (AGL-3321).\n * No send is re-filed, so no unsubscribe link and no pasted report URL stops\n * resolving.\n *\n * ## At two levels\n *\n * Both collections are the organization's. Under a site the card lists the\n * campaigns PLACED on that site and the sends sent AS it (see\n * `campaign-queries.ts` for why those filters are what make the read legal);\n * on the org hub, with `hostId` null, it lists every campaign with the sites\n * each one is placed on, and a new campaign is placed where its creator says.\n */\nexport function HostCampaignsCard(props: {\n /** The site, or `null` on the org Marketing hub. */\n hostId: string | null\n /**\n * The marketing hub URL, when the caller already has it.\n *\n * Resolved from the host route when it does not: the inbox console page\n * embeds this card on a tab of its own, and its `basePath` names the INBOX\n * hub. Deriving one hub's URL from another's by string surgery is the kind\n * of link that breaks silently when a surface moves.\n */\n basePath?: string\n}) {\n const { hostId, basePath } = props\n const firestore = useFirestore()\n const router = useRouter()\n const { orgSlug, subdomain } = useConsoleHostRoute(hostId)\n const hubPath =\n basePath ??\n (orgSlug && subdomain\n ? buildRoute(Route.HOST_PLUGIN, {\n orgSlug,\n host: subdomain,\n pluginSlug: 'marketing',\n })\n : null)\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const orgMount = useMarketingOrgMount()\n const { orgId } = useMarketingOrgId(hostId)\n // A container is the org's, so deleting one from the org hub names the org.\n const manageApi = useCampaignManageApi(hostId, orgId)\n\n /*==========================================\n * TWO KINDS OF ROW, EACH ITS OWN QUERY (AGL-3321).\n *\n * A campaign is a CONTAINER (`emailCampaigns`); a single send is an email\n * filed under none (`campaigns` where `emailCampaignId == null`). The two\n * live in different collections, and one Firestore query reads one\n * collection — so a table that merged them could page neither, and every\n * filter would be matched over whatever window of each it happened to\n * hold. The toggle above the table picks the kind, and the table shows a\n * page of that kind's query: newest first on `createdAtMs`, every clause\n * and the search word on the query, paged by it. Same table, same\n * columns; a single send still reads as a campaign of one.\n *\n * Each kind keeps its own clauses (their Sites values differ: a campaign\n * is asked by scope token, a send by the site it was sent as); the search\n * words are the reader's and carry across.\n *=========================================*/\n const [kind, setKind] = useState<CampaignListKind>('campaign')\n const [clausesByKind, setClausesByKind] = useState(NO_CLAUSES)\n const [searchWords, setSearchWords] = useState<string[]>([])\n const setKindClauses = useCallback(\n (next: ListFilterClause[]) =>\n setClausesByKind((current) => ({ ...current, [kind]: next })),\n [kind],\n )\n const gridFilter = useListGridFilter({\n clauses: clausesByKind[kind],\n onChange: setKindClauses,\n selectFields: ['listIds', 'sitesLabel'],\n search: { words: searchWords, onChange: setSearchWords },\n })\n const containerDeclaration = campaignContainersListQuery(!hostId)\n const singleDeclaration = campaignSingleSendsListQuery(!hostId)\n const declaration = kind === 'campaign' ? containerDeclaration : singleDeclaration\n const filterHeaders = CAMPAIGN_FILTER_HEADERS[kind]\n /*\n * A site's campaigns are searched by the START of the name: a range beside\n * the site's scope clause, the one array clause the rules can prove for a\n * site collaborator (see `campaign-list-query.ts`). The org hub keeps the\n * word search.\n */\n const siteSearch =\n hostId && kind === 'campaign' ? campaignSiteSearchClause(gridFilter.searchWords) : null\n const containerPage = useListQuery<any>({\n collection:\n kind === 'campaign' ? campaignContainersCollection(firestore, orgId) : null,\n declaration: containerDeclaration,\n request: {\n clauses:\n kind === 'campaign'\n ? siteSearch\n ? [siteSearch, ...gridFilter.clauses]\n : gridFilter.clauses\n : [],\n search: hostId ? [] : gridFilter.searchWords,\n base: campaignContainersScope(hostId),\n },\n deps: [firestore, orgId, hostId, kind],\n idField: '$id',\n })\n const singlePage = useListQuery<any>({\n collection: kind === 'single' ? campaignSendsCollection(firestore, orgId) : null,\n declaration: singleDeclaration,\n request: {\n clauses: kind === 'single' ? gridFilter.clauses : [],\n search: gridFilter.searchWords,\n base: [SINGLE_SENDS_BASE, ...campaignSendsScope(hostId)],\n },\n deps: [firestore, orgId, hostId, kind],\n idField: '$id',\n })\n const page = kind === 'campaign' ? containerPage : singlePage\n const filtering =\n gridFilter.clauses.length > 0 ||\n gridFilter.searchWords.some((word) => word.trim())\n\n /*\n * THE FIGURES OF THE CAMPAIGNS ON THE PAGE ON SCREEN.\n *\n * A container stores no counters; its row sums the emails filed under it.\n * Those are read for the page's campaigns only — `emailCampaignId in` the\n * ids on screen, thirty to a read, and under a site the ones sent as it —\n * and never used to filter: the page is already the query's answer. Past\n * `ROLLUP_CEILING` emails a read stops, and the table says the figures\n * are partial.\n */\n const pageIds = useMemo(\n () =>\n kind === 'campaign'\n ? containerPage.rows.map((row: any) => String(row.$id))\n : [],\n [kind, containerPage.rows],\n )\n const rollupRead = (ids: string[]) => () => {\n const sends = campaignSendsCollection(firestore, orgId)\n if (!sends || !ids.length) return null\n return collectionCeiling(\n query(\n sends,\n where('emailCampaignId', 'in', ids),\n ...(hostId ? [where('hostId', '==', hostId)] : []),\n ),\n ROLLUP_CEILING,\n )\n }\n const firstIds = pageIds.slice(0, IN_LIMIT)\n const restIds = pageIds.slice(IN_LIMIT, IN_LIMIT * 2)\n const { data: firstSendDocs } = useFirestoreCollection<any>(\n rollupRead(firstIds),\n [firestore, orgId, hostId, firstIds.join(',')],\n { idField: '$id' },\n )\n const { data: restSendDocs } = useFirestoreCollection<any>(\n rollupRead(restIds),\n [firestore, orgId, hostId, restIds.join(',')],\n { idField: '$id' },\n )\n const firstSends = ceilingedWindow<any>(firstSendDocs, ROLLUP_CEILING)\n const restSends = ceilingedWindow<any>(restSendDocs, ROLLUP_CEILING)\n const rollupTruncated = firstSends.truncated || restSends.truncated\n\n // Org email lists, so a row can name what it is aimed at rather than\n // showing ids.\n const { data: listDocs } = useFirestoreCollection<any>(\n () =>\n orgId\n ? query(collection(firestore, 'orgs', orgId, 'lists'), limit(50))\n : null,\n [firestore, orgId],\n { idField: '$id' },\n )\n const [createOpen, setCreateOpen] = useState(false)\n /*\n * The org's topic catalog, read only while the CREATE DRAWER is open.\n *\n * It fills one picker in that drawer and is drawn nowhere in the table, so\n * a reader who came to look at their campaigns must not pay for it — the\n * same rule the emails list already applies to the campaigns it offers its\n * own drawer, and the one the audiences section applies to a list's\n * members. It is the largest read on this section at 200 documents, and it\n * is the only one nothing on screen needs.\n */\n const { topics, source: topicSource } = useCampaignTopicOptions(\n topicCatalogHostId(hostId, orgMount),\n { enabled: createOpen },\n )\n const topicOptions = useMemo(\n () =>\n topics.map((topic) => ({\n value: topic.id,\n label: topic.name,\n })),\n [topics],\n )\n\n const listNames = useMemo(() => {\n const names = new Map<string, string>()\n for (const list of listDocs ?? []) {\n names.set(String(list.$id), String(list.name ?? list.$id))\n }\n return names\n }, [listDocs])\n\n const listOptions = useMemo(\n () =>\n (listDocs ?? []).map((list: any) => ({\n value: String(list.$id),\n label: String(list.name ?? list.$id),\n })),\n [listDocs],\n )\n\n /*\n * The page's rows, in the QUERY's order. `campaignListRows` builds each\n * row — a container with its emails summed, or a single send as a\n * campaign of one — and sorts by date, which is not this list's order, so\n * the page is put back in the order the query returned it.\n */\n const rows = useMemo(() => {\n const read = page.rows as any[]\n const order = new Map(read.map((row, at) => [String(row.$id), at]))\n const built =\n kind === 'campaign'\n ? campaignListRows(\n read as EmailCampaign[],\n [...firstSends.rows, ...restSends.rows] as CampaignSend[],\n Date.now(),\n )\n : campaignListRows([], read as CampaignSend[], Date.now())\n const byId = new Map(read.map((row) => [String(row.$id), row]))\n return built\n .filter((row) => order.has(row.id))\n .sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0))\n .map((row) => ({\n ...row,\n $id: row.id,\n sitesLabel: orgMount\n ? campaignSitesLabel(orgMount, row, byId.get(row.id))\n : '',\n }))\n }, [kind, page.rows, firstSends.rows, restSends.rows, orgMount])\n\n /*\n * The choices the picked fields offer. A campaign's Sites are asked by\n * scope token — `org` is placed on every site — and a single send's by\n * the site it was sent as.\n */\n const filterOptions = useMemo(() => {\n if (!orgMount) return {}\n const sites = orgSiteOptions(orgMount)\n return kind === 'campaign'\n ? {\n listIds: listOptions,\n sitesLabel: [\n { value: 'org', label: 'Every site' },\n ...sites.map((site) => ({\n value: `host:${site.value}`,\n label: site.label,\n })),\n ],\n }\n : { sitesLabel: sites }\n }, [kind, listOptions, orgMount])\n\n const [createError, setCreateError] = useState<string | null>(null)\n const [creating, setCreating] = useState(false)\n /** The campaign a delete is in flight for, so its row menu can say so. */\n const [deletingId, setDeletingId] = useState('')\n\n const openCampaign = useCallback(\n (id: string) => {\n if (hubPath) void router.push(`${hubPath}/campaigns/${id}`)\n },\n [hubPath, router],\n )\n\n const handleCreate = useCallback(\n async (values: Record<string, any>) => {\n if (creating) return\n /*\n * `displayName` is the shared drawer's own field, and every artifact\n * create in the console collects a name under that key. The campaign\n * stores it as `name` — the container has one name and no second\n * internal label — so the mapping happens here rather than by giving\n * this one drawer a field the others do not have.\n */\n const name = String(values.displayName ?? '').trim()\n if (!name) return\n const startAtMs = values.startAt ? Date.parse(String(values.startAt)) : null\n const endAtMs = values.endAt ? Date.parse(String(values.endAt)) : null\n // Refused here rather than stored and rendered as a campaign that ends\n // before it starts, which no window state describes.\n if (startAtMs !== null && endAtMs !== null && endAtMs < startAtMs) {\n return setCreateError('The end date is before the start date')\n }\n /*\n * Held until the org is known. A container has one home, and a write\n * that raced the site's org lookup would have nowhere to go.\n */\n if (!orgId) {\n return setCreateError('This workspace is still loading — try again')\n }\n setCreating(true)\n setCreateError(null)\n const id = createResourceUid()\n /*\n * Where it is placed. From a site's hub, that site — the creator is\n * standing on it, and a campaign that appeared on every sibling site\n * would be a decision nobody made. From the org hub, the sites picked,\n * and every site when none are.\n */\n const visibleTo = campaignVisibleTo(\n hostId\n ? [hostId]\n : Array.isArray(values.siteIds)\n ? values.siteIds.map(String)\n : null,\n )\n try {\n await setDoc(campaignContainerDoc(firestore, orgId, id), {\n name,\n // What the list's search reads (AGL-3321), from the name.\n ...campaignContainerSearchFields(name),\n ...(Number.isFinite(startAtMs) && startAtMs !== null\n ? { startAtMs }\n : {}),\n ...(Number.isFinite(endAtMs) && endAtMs !== null ? { endAtMs } : {}),\n listIds: Array.isArray(values.listIds)\n ? values.listIds.map(String)\n : [],\n ...(values.topicId ? { topicId: String(values.topicId) } : {}),\n visibleTo,\n createdAtMs: Date.now(),\n createdBy: String((user as any)?.uid ?? ''),\n })\n setCreateOpen(false)\n openCampaign(id)\n } catch (error) {\n console.error(error)\n setCreateError('The campaign could not be created')\n enqueueSnackbar('Could not create the campaign', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setCreating(false)\n }\n },\n [creating, firestore, hostId, orgId, user, enqueueSnackbar, openCampaign],\n )\n\n const campaignHref = useCallback(\n (id: string) => (hubPath ? `${hubPath}/campaigns/${id}` : null),\n [hubPath],\n )\n\n /*==========================================\n * DELETING A CAMPAIGN FROM ITS ROW.\n *\n * The container goes and its emails stay — the route detaches them first,\n * so each one keeps its id, its report and its unsubscribe links, and\n * reappears in this very table as a \"Single send\". That is not a\n * convenience: a send id is inside the HMAC of every unsubscribe footer\n * already delivered, so a delete that took the sends with it would break\n * opt-outs that must go on working.\n *\n * The confirmation names the count and says what the delete does NOT do.\n * Deleting a campaign cancels nothing — a scheduled email inside it still\n * goes out — and a merchant who reads the button as \"stop this campaign\"\n * has to be told before they press it.\n *\n * EDITING is deliberately not offered here. A record is edited on its own\n * page in this console; the campaign's page carries the edit drawer, and\n * this row's first entry is the way to it.\n *=========================================*/\n const handleDelete = useCallback(\n async (row: CampaignListRow) => {\n if (deletingId) return\n const emails = row.sends.length\n /*\n * Emails with mail still to go: waiting for their time, AND part way\n * through an audience larger than one batch. Counting only `scheduled`\n * would miss the case that needs the warning most — an email delivering\n * right now is stored as `scheduled` too, and `rollup.scheduled` is the\n * narrower reading that leaves it out.\n */\n const unfinished = row.rollup.scheduled + row.rollup.sending\n const agreed = await confirm({\n title: `Delete ${row.name}?`,\n description:\n (emails\n ? `The ${emails.toLocaleString()} ` +\n `${emails === 1 ? 'email' : 'emails'} in it are kept — each ` +\n 'keeps its own report and its unsubscribe links, and they stay ' +\n 'in this list as single sends. '\n : 'It holds no emails. ') +\n (unfinished\n ? `${unfinished.toLocaleString()} of them ${\n unfinished === 1 ? 'is' : 'are'\n } still going out or still due, and deleting the campaign does ` +\n 'not stop that — the sender picks each one up from its own ' +\n 'record. Stop a send from its own page. '\n : '') +\n 'Any pages, forms and contacts assigned to it come out of it and ' +\n 'are otherwise untouched. Only the campaign itself goes.',\n confirmationText: 'Delete campaign',\n })\n .then(() => true)\n .catch(() => false)\n if (!agreed) return\n setDeletingId(row.id)\n try {\n const { response, payload } = await manageApi({\n action: 'deleteCampaign',\n campaignId: row.id,\n })\n if (!response.ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'The campaign could not be deleted',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n enqueueSnackbar('Campaign deleted', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('The campaign could not be deleted', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setDeletingId('')\n }\n },\n [confirm, deletingId, enqueueSnackbar, manageApi],\n )\n\n const columns = useMemo(\n () => [\n {\n field: 'name',\n headerName: filterHeaders.name,\n flex: 1,\n minWidth: 180,\n renderCell: ({ row }: any) => (\n <Stack\n direction=\"row\"\n spacing={1}\n /*\n `minWidth: 0` on the row AND on the name: a flex child will not\n shrink below its content without it, so the chip beside it is\n what gets clipped instead of the name being ellipsed.\n */\n sx={{ alignItems: 'center', minWidth: 0, width: 1 }}\n >\n {/*\n The name is a real anchor as well as the row being clickable, so\n a campaign can be middle-clicked into a tab or copied out of the\n context menu — affordances a row handler cannot offer. The grid's\n own row click fires too, so the link stops the event rather than\n pushing the same route twice.\n */}\n {campaignHref(row.id) ? (\n <AppLink\n href={campaignHref(row.id) as string}\n onClick={(event: { stopPropagation: () => void }) =>\n event.stopPropagation()\n }\n style={{ minWidth: 0 }}\n >\n <Typography variant=\"body2\" noWrap>\n {row.name}\n </Typography>\n </AppLink>\n ) : (\n <Typography variant=\"body2\" noWrap sx={{ minWidth: 0 }}>\n {row.name}\n </Typography>\n )}\n {row.legacy ? (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n label=\"Single send\"\n // A label that reads \"Single sen\" is worse than a shorter name.\n sx={{ flexShrink: 0 }}\n title={\n 'Sent before campaigns grouped their emails. Its report ' +\n 'and its unsubscribe links are unchanged.'\n }\n />\n ) : null}\n </Stack>\n ),\n },\n /*\n WHERE IT IS PLACED, on the org hub only. Under a site every row is on\n that site by construction, so the column would say one thing thirty\n times.\n */\n ...(orgMount\n ? [\n {\n field: 'sitesLabel',\n headerName: 'Sites',\n width: 170,\n sortable: false,\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\" noWrap>\n {row.sitesLabel}\n </Typography>\n ),\n },\n ]\n : []),\n {\n field: 'windowState',\n headerName: 'Window',\n width: 170,\n renderCell: ({ row }: any) => {\n const start = formatDay(row.startAtMs)\n const end = formatDay(row.endAtMs)\n const range =\n start && end && start !== end\n ? `${start} – ${end}`\n : start || end || ''\n return (\n <Stack sx={{ minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {WINDOW_LABEL[row.windowState as CampaignListRow['windowState']]}\n </Typography>\n {range ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {range}\n </Typography>\n ) : null}\n </Stack>\n )\n },\n },\n {\n field: 'listIds',\n headerName: 'Lists',\n width: 140,\n sortable: false,\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\" noWrap>\n {row.listIds.length\n ? row.listIds\n .map((id: string) => listNames.get(id) ?? id)\n .join(', ')\n : '—'}\n </Typography>\n ),\n },\n /*\n THE FOUR COUNTS, RIGHT-ALIGNED HEAD AND BODY.\n A figure is read by its last digit, so a column of them lines up on\n the right or it does not line up at all. `headerAlign` has to be said\n as well as `align`: a grid column defaults its header to the column\n type's alignment rather than to the cell's, which is how these came to\n sit with left headers over figures nobody could compare down the page.\n\n EVERY ONE OF THEM MEASURES THE MAIL, and the headings say so. What a\n campaign CAUSED — the submissions, leads, contacts and bookings\n credited to it — is not a column here, because there is no figure to\n read: a container has no conversion counter of its own, so a column\n would be an aggregation per row for a campaign and a subcollection\n document per row for a single send, on a list that costs two queries\n however many campaigns it holds. Headings that named the campaign over\n figures that all described its mail were the cheaper mistake, so the\n headings name the mail and the note under the table says where the\n outcome figures are.\n */\n {\n field: 'emails',\n headerName: 'Emails',\n width: 128,\n align: 'right',\n headerAlign: 'right',\n /*\n THE COUNT, AND WHAT IS STILL HAPPENING TO IT.\n\n `sending` is called out apart from `scheduled` because the two are\n opposite readings of the same stored status: an email delivering an\n audience larger than one batch sits as `scheduled` between runs, and\n rolling it in with the ones that have mailed nobody reports a\n campaign that is half delivered as a campaign that has not started.\n\n The note sits UNDER the figure rather than beside it — the column\n would otherwise have to be wide enough for the longest sentence, and\n the figure is what the column is read for.\n */\n renderCell: ({ row }: any) => {\n const { sends, sending, scheduled } = row.rollup\n const note = [\n sending ? `${sending} sending` : '',\n scheduled ? `${scheduled} scheduled` : '',\n ]\n .filter(Boolean)\n .join(', ')\n return (\n <Stack sx={{ alignItems: 'flex-end', minWidth: 0, width: 1 }}>\n <Typography variant=\"body2\">{String(sends)}</Typography>\n {note ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {note}\n </Typography>\n ) : null}\n </Stack>\n )\n },\n },\n {\n field: 'sent',\n headerName: 'Mail sent',\n width: 112,\n align: 'right',\n headerAlign: 'right',\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\">{figure(row.rollup.sent)}</Typography>\n ),\n },\n {\n field: 'opens',\n headerName: 'Mail opens',\n width: 112,\n align: 'right',\n headerAlign: 'right',\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\">{figure(row.rollup.opens)}</Typography>\n ),\n },\n {\n field: 'clicks',\n headerName: 'Mail clicks',\n width: 112,\n align: 'right',\n headerAlign: 'right',\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\">{figure(row.rollup.clicks)}</Typography>\n ),\n },\n /*\n THE TRAILING CLUSTER, through the grid's own actions column.\n `listActionsColumn` is what every other grid list in the console\n renders, so the reader cannot tell which family of table they are\n standing in — the hand-rolled tables on this surface reach the same\n `RowActionsMenu` from the other direction.\n\n Opening the campaign is restated here even though the row click does\n the same thing, for the reason the screens table restates its own: the\n menu is where a row's actions are NAMED, and an action absent from it\n reads as an action the row does not have.\n\n A \"Single send\" row is a SEND with no container — the table adopts it\n so a merchant's history is not missing — and there is no container\n under it to delete. Its entry is shown disabled with that reason\n rather than hidden, because a control that vanishes and one that does\n not apply look identical from the outside.\n */\n listActionsColumn(\n (row: any) => (\n <ListRowActions\n label={String(row.name ?? row.id)}\n items={[\n {\n key: 'details',\n label: 'Open campaign',\n icon: <MdiIcon path={mdiEyeOutline.path} size={0.8} />,\n href: campaignHref(row.id) ?? undefined,\n disabled: !campaignHref(row.id),\n disabledReason: campaignHref(row.id)\n ? undefined\n : 'This site’s console URL has not resolved yet',\n },\n {\n key: 'delete',\n label: 'Delete campaign',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: row.legacy || Boolean(deletingId),\n disabledReason: row.legacy\n ? 'This is a single send, not a campaign. Open it to ' +\n 'manage the email itself.'\n : 'A campaign is being deleted',\n onClick: () => void handleDelete(row as CampaignListRow),\n },\n ]}\n />\n ),\n { width: 72 },\n ),\n ],\n [listNames, campaignHref, deletingId, handleDelete, orgMount, filterHeaders],\n )\n\n /** Nothing of this kind stored at all — not a filter that matched nothing. */\n const none =\n page.status !== 'loading' && !rows.length && !filtering && page.page === 0\n\n /*\n * Other ways to start a campaign, from plugins (AGL-3603): the\n * `hostCampaigns` zone this plugin declares, drawn through the shell's own\n * gated slot. On the organization's hub it is handed the sites a campaign\n * could be placed on, since there is no one site to take.\n */\n const campaignsZone = (\n <HostCampaignsZone\n hostId={hostId}\n orgId={orgId}\n sites={\n hostId\n ? []\n : (orgMount?.hosts ?? []).map((host) => ({ id: host.id, name: host.name }))\n }\n />\n )\n\n return (\n <CardDisplay\n header={'Campaigns'}\n help={pluginDocsHelp('emailCampaigns', {\n anchor: '#campaigns-group-emails',\n excerpt:\n 'A campaign groups the emails you send to a set of lists over a ' +\n 'window of dates. Open one to write and send an email inside it.',\n })}\n HeaderProps={{\n action: (\n <Stack direction=\"row\" spacing={1}>\n {campaignsZone}\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={creating}\n onClick={() => {\n setCreateError(null)\n setCreateOpen(true)\n }}\n >\n {creating ? 'Creating…' : 'Create campaign'}\n </Button>\n </Stack>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <ToggleButtonGroup\n exclusive\n size=\"small\"\n value={kind}\n onChange={(_event, next: CampaignListKind | null) => {\n if (next) setKind(next)\n }}\n aria-label=\"Which rows the table lists\"\n sx={{ alignSelf: 'flex-start' }}\n >\n <ToggleButton value=\"campaign\">{'Campaigns'}</ToggleButton>\n <ToggleButton value=\"single\">{'Single sends'}</ToggleButton>\n </ToggleButtonGroup>\n <ListFilterChips\n fields={declaration.fields}\n headers={filterHeaders}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={filterOptions}\n />\n <ListQueryNotices\n refused={listQueryRefusals(page.plan.refused, {\n fields: declaration.fields,\n headers: filterHeaders,\n options: filterOptions,\n })}\n notices={\n siteSearch\n ? [CAMPAIGN_SITE_SEARCH_NOTICE, ...page.plan.notices]\n : page.plan.notices\n }\n />\n <ListTable\n rows={rows}\n columns={listFilterGridColumns(\n columns as any,\n declaration.fields,\n filterOptions,\n filterHeaders,\n )}\n onOpen={(id) => openCampaign(id)}\n loading={page.status === 'loading'}\n /*\n * The panel and the search are the grid's; every clause and the\n * search word are on the list's query (AGL-3321), and the grid\n * neither filters nor sorts the page it is handed.\n */\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n disableColumnSorting\n hideFooter\n initialState={{\n columns: {\n columnVisibilityModel: hiddenFilterVisibility(\n declaration.fields,\n (columns as Array<{ field: string }>).map((column) => column.field),\n ),\n },\n }}\n noRowsLabel={\n none\n ? kind === 'campaign'\n ? 'No campaigns yet'\n : 'No single sends'\n : kind === 'campaign'\n ? 'No campaigns match these filters'\n : 'No single sends match these filters'\n }\n noRowsDescription={\n none\n ? kind === 'campaign'\n ? 'A campaign groups the emails you send to a set of lists.'\n : 'An email filed under no campaign is listed here.'\n : undefined\n }\n noRowsAction={\n none && kind === 'campaign' ? (\n <Stack direction=\"row\" spacing={1}>\n {/* Other ways to start a campaign, the header's zone again. */}\n {campaignsZone}\n <Button variant=\"contained\" onClick={() => setCreateOpen(true)}>\n {'Create campaign'}\n </Button>\n </Stack>\n ) : undefined\n }\n />\n <ListPagination\n page={page.page}\n pageSize={page.pageSize}\n rowCount={rows.length}\n hasMore={page.hasMore}\n onPageChange={page.setPage}\n onPageSizeChange={page.setPageSize}\n />\n {/*\n WHAT THIS TABLE MEASURES, said rather than inferred from the column\n names. Every figure in it is a fact about the campaign's mail, and a\n reader comparing rows is comparing mailings — the conversions and the\n destinations credited to a campaign are on the campaign's own page,\n because counting them for every row is a read per row on a list whose\n whole cost is two queries.\n */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'These figures measure each campaign’s mail. What a campaign ' +\n 'caused — the form submissions, leads, contacts and bookings ' +\n 'credited to it — and the pages it sent people to are on the ' +\n 'campaign’s own page.'}\n </Typography>\n {rollupTruncated ? (\n <Alert severity=\"info\">\n {`The campaigns on this page hold more than ${ROLLUP_CEILING} ` +\n 'emails between them, so their figures count the first ' +\n `${ROLLUP_CEILING} read.`}\n </Alert>\n ) : null}\n </Stack>\n {/*\n The console's own create drawer, from the shared library rather than a\n second one that looks like it. What a campaign collects beyond a name\n is its window, the lists it is aimed at and the stream its emails open\n on; the description box is left off because the container stores none,\n and a field the writer discards is worse than one never offered.\n */}\n {/* Draws nothing: the zone the topic catalog's owner answers through. */}\n {topicSource}\n <CreateArtifactDrawer\n open={createOpen}\n onClose={() => setCreateOpen(false)}\n title=\"Create campaign\"\n submitLabel=\"Create campaign\"\n includeDescription={false}\n onSubmit={handleCreate}\n extraFields={campaignFields(\n listOptions,\n topicOptions,\n orgMount ? orgSiteOptions(orgMount) : null,\n )}\n errorSlot={\n createError ? (\n <Alert severity=\"error\" sx={{ mt: 2, mb: 1 }}>\n {createError}\n </Alert>\n ) : null\n }\n />\n </CardDisplay>\n )\n}\n/**\n * What a campaign collects beyond its name.\n *\n * Data-driven-forms field descriptors, built from the org's own lists and\n * topics so the drawer offers what this workspace actually has. Dates are\n * plain `date` inputs: a campaign window is a day at each end, and a time of\n * day would be a precision the model does not carry.\n */\nfunction campaignFields(\n lists: Array<{ value: string; label: string }>,\n topics: Array<{ value: string; label: string }>,\n /** The org's sites, on the org hub only — a site hub places on itself. */\n sites: Array<{ value: string; label: string }> | null,\n): any[] {\n return [\n ...(sites\n ? [\n {\n component: 'select',\n name: 'siteIds',\n label: 'Sites',\n multiple: true,\n initialValue: [],\n helperText:\n 'The sites this campaign is offered on. Leave empty for every site.',\n disableDefaultOption: true,\n options: sites,\n },\n ]\n : []),\n {\n component: 'text-field',\n name: 'startAt',\n label: 'Starts',\n type: 'date',\n helperText: 'When the campaign window opens',\n },\n {\n component: 'text-field',\n name: 'endAt',\n label: 'Ends',\n type: 'date',\n helperText: 'Leave empty for an open-ended campaign',\n InputLabelProps: { shrink: true },\n },\n {\n component: 'select',\n name: 'listIds',\n label: 'Lists',\n multiple: true,\n initialValue: [],\n // A campaign with no list is legitimate: its emails can go to leads, to\n // site members, or to a segment. The lists are what it is AIMED at.\n helperText: 'The lists this campaign is aimed at',\n disableDefaultOption: true,\n options: lists,\n },\n {\n component: 'select',\n name: 'topicId',\n label: 'Topic',\n helperText: 'The stream its emails open on — each one can change it',\n disableDefaultOption: true,\n options: topics,\n },\n ]\n}\n\n/**\n * The Sites cell: where a campaign is offered.\n *\n * A container reads its `visibleTo`; a single send, which has no container,\n * is on the one site it was sent as. An empty placement is said rather than\n * left blank, because a blank cell reads as \"every site\" and it means none.\n */\nfunction campaignSitesLabel(\n mount: MarketingOrgMount,\n row: CampaignListRow,\n container: EmailCampaign | undefined,\n): string {\n if (row.legacy) return orgSiteName(mount, row.sends[0]?.hostId) || '—'\n const ids = campaignSiteIds(container)\n if (ids === null) return 'Every site'\n if (!ids.length) return 'No site'\n return ids.map((id) => orgSiteName(mount, id)).join(', ')\n}\n\nHostCampaignsCard.displayName = 'HostCampaignsCard'\n\nexport default HostCampaignsCard\n"],"names":["buildRoute","createResourceUid","pluginDocsHelp","Route","ceilingedWindow","collectionCeiling","useListQuery","mdiDeleteOutline","mdiEyeOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListRowActions","ListTable","listActionsColumn","hiddenFilterVisibility","listFilterGridColumns","useListGridFilter","useSnackbar","Alert","Button","Chip","Stack","ToggleButton","ToggleButtonGroup","Typography","collection","limit","query","setDoc","where","useCallback","useMemo","useState","useRouter","useConsoleHostRoute","useFirestore","useFirestoreCollection","useUser","campaignListRows","campaignSiteIds","campaignVisibleTo","CreateArtifactDrawer","CAMPAIGN_SITE_SEARCH_NOTICE","SINGLE_SENDS_BASE","campaignContainerSearchFields","campaignContainersListQuery","campaignContainersScope","campaignSendsScope","campaignSingleSendsListQuery","campaignSiteSearchClause","campaignContainerDoc","campaignContainersCollection","campaignSendsCollection","orgSiteName","orgSiteOptions","topicCatalogHostId","useMarketingOrgId","useMarketingOrgMount","useCampaignManageApi","HostCampaignsZone","useCampaignTopicOptions","ROLLUP_CEILING","IN_LIMIT","formatDay","ms","Date","toLocaleDateString","figure","value","toLocaleString","WINDOW_LABEL","undated","upcoming","running","ended","CAMPAIGN_FILTER_HEADERS","campaign","name","listIds","sitesLabel","createdAtMs","single","NO_CLAUSES","HostCampaignsCard","props","hostId","basePath","firestore","router","orgSlug","subdomain","hubPath","HOST_PLUGIN","host","pluginSlug","data","user","enqueueSnackbar","confirm","orgMount","orgId","manageApi","kind","setKind","clausesByKind","setClausesByKind","searchWords","setSearchWords","setKindClauses","next","current","gridFilter","clauses","onChange","selectFields","search","words","containerDeclaration","singleDeclaration","declaration","filterHeaders","siteSearch","containerPage","request","base","deps","idField","singlePage","page","filtering","length","some","word","trim","pageIds","rows","map","row","String","$id","rollupRead","ids","sends","firstIds","slice","restIds","firstSendDocs","join","restSendDocs","firstSends","restSends","rollupTruncated","truncated","listDocs","createOpen","setCreateOpen","topics","source","topicSource","enabled","topicOptions","topic","id","label","listNames","names","Map","list","set","listOptions","read","order","at","built","now","byId","filter","has","sort","a","b","get","campaignSitesLabel","filterOptions","sites","site","createError","setCreateError","creating","setCreating","deletingId","setDeletingId","openCampaign","push","handleCreate","values","displayName","startAtMs","startAt","parse","endAtMs","endAt","visibleTo","Array","isArray","siteIds","Number","isFinite","topicId","createdBy","uid","error","console","variant","allowDuplicate","campaignHref","handleDelete","emails","unfinished","rollup","scheduled","sending","agreed","title","description","confirmationText","then","catch","response","payload","action","campaignId","ok","persist","columns","field","headerName","flex","minWidth","renderCell","direction","spacing","sx","alignItems","width","href","onClick","event","stopPropagation","style","noWrap","legacy","size","flexShrink","sortable","start","end","range","windowState","color","align","headerAlign","note","Boolean","sent","opens","clicks","items","key","icon","path","undefined","disabled","disabledReason","destructive","none","status","campaignsZone","hosts","header","help","anchor","excerpt","HeaderProps","contentGutterX","contentGutterY","exclusive","_event","aria-label","alignSelf","fields","headers","setClauses","options","refused","plan","notices","onOpen","loading","filterMode","filterModel","onFilterModelChange","quickFilter","disableColumnSorting","hideFooter","initialState","columnVisibilityModel","column","noRowsLabel","noRowsDescription","noRowsAction","pageSize","rowCount","hasMore","onPageChange","setPage","onPageSizeChange","setPageSize","severity","open","onClose","submitLabel","includeDescription","onSubmit","extraFields","campaignFields","errorSlot","mt","mb","lists","component","multiple","initialValue","helperText","disableDefaultOption","type","InputLabelProps","shrink","mount","container"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,UAAU,EAAEC,iBAAiB,EAAEC,cAAc,EAAEC,KAAK,QAAQ,eAAc;AACnF;;;;CAIC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,YAAY,QAAQ,sDAAqD;AAClF,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,yBAAwB;AACxE,SACEC,OAAO,EACPC,WAAW,EACXC,OAAO,EACPC,sBAAsB,QACjB,uBAAsB;AAC7B,OAAOC,qBAAqB,8DAA6D;AACzF,SAAS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A,IAAIkH,MAAM,EAAE,OAAOtM,YAAY6R,QAAOzM,cAAAA,IAAIK,KAAK,CAAC,EAAE,qBAAZL,YAAcpD,MAAM,KAAK;IACnE,MAAMwD,MAAMtG,gBAAgB4S;IAC5B,IAAItM,QAAQ,MAAM,OAAO;IACzB,IAAI,CAACA,IAAIX,MAAM,EAAE,OAAO;IACxB,OAAOW,IAAIL,GAAG,CAAC,CAAC0B,KAAO7G,YAAY6R,OAAOhL,KAAKf,IAAI,CAAC;AACtD;AAEAhE,kBAAkBiH,WAAW,GAAG;AAEhC,eAAejH,kBAAiB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/campaigns-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 { buildRoute, createResourceUid, pluginDocsHelp, Route } from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers — a spec that mocks\n * `@aglyn/tenant-feature-instance` wholesale to stage its Firestore hooks\n * would otherwise lose them, and neither is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { useListQuery } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { mdiDeleteOutline, mdiEyeOutline } from '@aglyn/shared-data-mdi'\nimport {\n AppLink,\n CardDisplay,\n MdiIcon,\n useConfirmationContext,\n} 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 { hiddenFilterVisibility } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport {\n type ListFilterClause,\n listFilterGridColumns,\n} from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { useListColumnSort } from '@aglyn/shared-ui-jsx/hooks/use-list-column-sort'\nimport type { ListQuerySort } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Button,\n Chip,\n Stack,\n ToggleButton,\n ToggleButtonGroup,\n Typography,\n} from '@mui/material'\nimport { collection, limit, query, setDoc, where } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useRouter } from 'next/navigation'\nimport {\n useConsoleHostRoute,\n useFirestore,\n useFirestoreCollection,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n campaignListRows,\n campaignSiteIds,\n campaignVisibleTo,\n type CampaignAggregate,\n type CampaignListRow,\n type CampaignSend,\n type EmailCampaign,\n} from '../model/campaign-container'\nimport { CreateArtifactDrawer } from '@aglyn/shared-ui-jsx-forms'\nimport {\n CAMPAIGN_SITE_SEARCH_NOTICE,\n SINGLE_SENDS_BASE,\n campaignContainerSearchFields,\n campaignContainersListQuery,\n campaignContainersScope,\n campaignSendsScope,\n campaignSingleSendsListQuery,\n campaignSiteSearchClause,\n} from '../model/campaign-list-query'\nimport {\n campaignContainerDoc,\n campaignContainersCollection,\n campaignSendsCollection,\n} from './campaign-queries'\nimport {\n orgSiteName,\n orgSiteOptions,\n topicCatalogHostId,\n useMarketingOrgId,\n useMarketingOrgMount,\n type MarketingOrgMount,\n} from './marketing-org-mount'\nimport { useCampaignManageApi } from './use-campaign-send-api'\nimport { HostCampaignsZone } from './campaign-list-zones'\nimport { useCampaignTopicOptions } from './use-campaign-topic-options'\n\n/**\n * How many emails one read of a page's campaigns covers, for their figures.\n *\n * A ceiling on the ROLLUP read, not on the list: the list is paged by its\n * own query, and this reads the emails of the campaigns on the page on\n * screen, thirty campaigns to a read (`in` takes thirty ids), so the largest\n * page is two reads of this many. Past it, the figures say so.\n */\nconst ROLLUP_CEILING = 50\n\n/** Firestore's cap on an `in` clause's values. */\nconst IN_LIMIT = 30\n\n/** Which kind of row the table shows: the two are separate queries. */\ntype CampaignListKind = 'campaign' | 'single'\n\nconst formatDay = (ms: number | null): string =>\n ms === null ? '' : new Date(ms).toLocaleDateString()\n\n/** A rolled-up figure, or an em dash where nothing recorded one. */\nconst figure = (value: CampaignAggregate): string =>\n value.value === null ? '—' : value.value.toLocaleString()\n\n/*\n * EVERY HEADER SORTS (AGL-3680). A campaign's name and a single send's\n * subject order the kind's query (`declaration.sorts`); what a row is drawn\n * from — its sites, its window, its lists, and its figures (a campaign's\n * summed from its emails for the page, a send's counters absent until\n * something is counted) — sorts the page.\n */\nconst CAMPAIGN_PAGE_SORT_HEADERS = {\n sitesLabel: 'Sites',\n windowState: 'Window',\n listIds: 'Lists',\n emails: 'Emails',\n sent: 'Mail sent',\n opens: 'Mail opens',\n clicks: 'Mail clicks',\n}\n\nconst WINDOW_LABEL: Record<CampaignListRow['windowState'], string> = {\n undated: 'No dates',\n upcoming: 'Upcoming',\n running: 'Running',\n ended: 'Ended',\n}\n\n/*\n * What the campaigns grid's Filters panel offers, each clause and the search\n * on the list's Firestore query (AGL-3321, `campaignContainersListQuery` and\n * `campaignSingleSendsListQuery`). The Window column is derived from a\n * campaign's dates against the clock, which no query can ask, so it is not\n * offered; the one date range is Created, the list's own order.\n */\nconst CAMPAIGN_FILTER_HEADERS: Record<CampaignListKind, Readonly<Record<string, string>>> = {\n campaign: {\n name: 'Campaign',\n listIds: 'Lists',\n sitesLabel: 'Sites',\n createdAtMs: 'Created',\n },\n // A single send has no container; its `name` field filters by the subject.\n single: {\n name: 'Subject',\n sitesLabel: 'Sites',\n createdAtMs: 'Created',\n },\n}\nconst NO_CLAUSES: Record<CampaignListKind, ListFilterClause[]> = {\n campaign: [],\n single: [],\n}\n\n/**\n * THE CAMPAIGNS LIST.\n *\n * A campaign is a container — a name, a window, the lists it is aimed at, and\n * the emails sent inside it — so this is a table of campaigns and not of\n * messages. Composing is not here: a message belongs to a campaign, and the\n * campaign's own page is where one is written.\n *\n * The rows come from two collections. `emailCampaigns` holds the\n * containers. `campaigns` holds every send, including thousands written\n * before containers existed; those carry no container (`emailCampaignId`\n * null), and `campaignListRows` presents each as a campaign of one rather\n * than dropping it. The two are two queries, so the table lists one kind at a\n * time — Campaigns or Single sends — each paged by its own query (AGL-3321).\n * No send is re-filed, so no unsubscribe link and no pasted report URL stops\n * resolving.\n *\n * ## At two levels\n *\n * Both collections are the organization's. Under a site the card lists the\n * campaigns PLACED on that site and the sends sent AS it (see\n * `campaign-queries.ts` for why those filters are what make the read legal);\n * on the org hub, with `hostId` null, it lists every campaign with the sites\n * each one is placed on, and a new campaign is placed where its creator says.\n */\nexport function HostCampaignsCard(props: {\n /** The site, or `null` on the org Marketing hub. */\n hostId: string | null\n /**\n * The marketing hub URL, when the caller already has it.\n *\n * Resolved from the host route when it does not: the inbox console page\n * embeds this card on a tab of its own, and its `basePath` names the INBOX\n * hub. Deriving one hub's URL from another's by string surgery is the kind\n * of link that breaks silently when a surface moves.\n */\n basePath?: string\n}) {\n const { hostId, basePath } = props\n const firestore = useFirestore()\n const router = useRouter()\n const { orgSlug, subdomain } = useConsoleHostRoute(hostId)\n const hubPath =\n basePath ??\n (orgSlug && subdomain\n ? buildRoute(Route.HOST_PLUGIN, {\n orgSlug,\n host: subdomain,\n pluginSlug: 'marketing',\n })\n : null)\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const orgMount = useMarketingOrgMount()\n const { orgId } = useMarketingOrgId(hostId)\n // A container is the org's, so deleting one from the org hub names the org.\n const manageApi = useCampaignManageApi(hostId, orgId)\n\n /*==========================================\n * TWO KINDS OF ROW, EACH ITS OWN QUERY (AGL-3321).\n *\n * A campaign is a CONTAINER (`emailCampaigns`); a single send is an email\n * filed under none (`campaigns` where `emailCampaignId == null`). The two\n * live in different collections, and one Firestore query reads one\n * collection — so a table that merged them could page neither, and every\n * filter would be matched over whatever window of each it happened to\n * hold. The toggle above the table picks the kind, and the table shows a\n * page of that kind's query: newest first on `createdAtMs`, every clause\n * and the search word on the query, paged by it. Same table, same\n * columns; a single send still reads as a campaign of one.\n *\n * Each kind keeps its own clauses (their Sites values differ: a campaign\n * is asked by scope token, a send by the site it was sent as); the search\n * words are the reader's and carry across.\n *=========================================*/\n const [kind, setKind] = useState<CampaignListKind>('campaign')\n // The header order asked of the kind on screen; a new kind starts unsorted.\n const [askedSort, setAskedSort] = useState<ListQuerySort | null>(null)\n const [clausesByKind, setClausesByKind] = useState(NO_CLAUSES)\n const [searchWords, setSearchWords] = useState<string[]>([])\n const setKindClauses = useCallback(\n (next: ListFilterClause[]) =>\n setClausesByKind((current) => ({ ...current, [kind]: next })),\n [kind],\n )\n const gridFilter = useListGridFilter({\n clauses: clausesByKind[kind],\n onChange: setKindClauses,\n selectFields: ['listIds', 'sitesLabel'],\n search: { words: searchWords, onChange: setSearchWords },\n })\n const containerDeclaration = campaignContainersListQuery(!hostId)\n const singleDeclaration = campaignSingleSendsListQuery(!hostId)\n const declaration = kind === 'campaign' ? containerDeclaration : singleDeclaration\n const filterHeaders = CAMPAIGN_FILTER_HEADERS[kind]\n /*\n * A site's campaigns are searched by the START of the name: a range beside\n * the site's scope clause, the one array clause the rules can prove for a\n * site collaborator (see `campaign-list-query.ts`). The org hub keeps the\n * word search.\n */\n const siteSearch =\n hostId && kind === 'campaign' ? campaignSiteSearchClause(gridFilter.searchWords) : null\n const containerPage = useListQuery<any>({\n collection:\n kind === 'campaign' ? campaignContainersCollection(firestore, orgId) : null,\n declaration: containerDeclaration,\n request: {\n clauses:\n kind === 'campaign'\n ? siteSearch\n ? [siteSearch, ...gridFilter.clauses]\n : gridFilter.clauses\n : [],\n search: hostId ? [] : gridFilter.searchWords,\n base: campaignContainersScope(hostId),\n sort: kind === 'campaign' ? askedSort : null,\n },\n deps: [firestore, orgId, hostId, kind],\n idField: '$id',\n })\n const singlePage = useListQuery<any>({\n collection: kind === 'single' ? campaignSendsCollection(firestore, orgId) : null,\n declaration: singleDeclaration,\n request: {\n clauses: kind === 'single' ? gridFilter.clauses : [],\n search: gridFilter.searchWords,\n base: [SINGLE_SENDS_BASE, ...campaignSendsScope(hostId)],\n sort: kind === 'single' ? askedSort : null,\n },\n deps: [firestore, orgId, hostId, kind],\n idField: '$id',\n })\n const page = kind === 'campaign' ? containerPage : singlePage\n const filtering =\n gridFilter.clauses.length > 0 ||\n gridFilter.searchWords.some((word) => word.trim())\n\n /*\n * THE FIGURES OF THE CAMPAIGNS ON THE PAGE ON SCREEN.\n *\n * A container stores no counters; its row sums the emails filed under it.\n * Those are read for the page's campaigns only — `emailCampaignId in` the\n * ids on screen, thirty to a read, and under a site the ones sent as it —\n * and never used to filter: the page is already the query's answer. Past\n * `ROLLUP_CEILING` emails a read stops, and the table says the figures\n * are partial.\n */\n const pageIds = useMemo(\n () =>\n kind === 'campaign'\n ? containerPage.rows.map((row: any) => String(row.$id))\n : [],\n [kind, containerPage.rows],\n )\n const rollupRead = (ids: string[]) => () => {\n const sends = campaignSendsCollection(firestore, orgId)\n if (!sends || !ids.length) return null\n return collectionCeiling(\n query(\n sends,\n where('emailCampaignId', 'in', ids),\n ...(hostId ? [where('hostId', '==', hostId)] : []),\n ),\n ROLLUP_CEILING,\n )\n }\n const firstIds = pageIds.slice(0, IN_LIMIT)\n const restIds = pageIds.slice(IN_LIMIT, IN_LIMIT * 2)\n const { data: firstSendDocs } = useFirestoreCollection<any>(\n rollupRead(firstIds),\n [firestore, orgId, hostId, firstIds.join(',')],\n { idField: '$id' },\n )\n const { data: restSendDocs } = useFirestoreCollection<any>(\n rollupRead(restIds),\n [firestore, orgId, hostId, restIds.join(',')],\n { idField: '$id' },\n )\n const firstSends = ceilingedWindow<any>(firstSendDocs, ROLLUP_CEILING)\n const restSends = ceilingedWindow<any>(restSendDocs, ROLLUP_CEILING)\n const rollupTruncated = firstSends.truncated || restSends.truncated\n\n // Org email lists, so a row can name what it is aimed at rather than\n // showing ids.\n const { data: listDocs } = useFirestoreCollection<any>(\n () =>\n orgId\n ? query(collection(firestore, 'orgs', orgId, 'lists'), limit(50))\n : null,\n [firestore, orgId],\n { idField: '$id' },\n )\n const [createOpen, setCreateOpen] = useState(false)\n /*\n * The org's topic catalog, read only while the CREATE DRAWER is open.\n *\n * It fills one picker in that drawer and is drawn nowhere in the table, so\n * a reader who came to look at their campaigns must not pay for it — the\n * same rule the emails list already applies to the campaigns it offers its\n * own drawer, and the one the audiences section applies to a list's\n * members. It is the largest read on this section at 200 documents, and it\n * is the only one nothing on screen needs.\n */\n const { topics, source: topicSource } = useCampaignTopicOptions(\n topicCatalogHostId(hostId, orgMount),\n { enabled: createOpen },\n )\n const topicOptions = useMemo(\n () =>\n topics.map((topic) => ({\n value: topic.id,\n label: topic.name,\n })),\n [topics],\n )\n\n const listNames = useMemo(() => {\n const names = new Map<string, string>()\n for (const list of listDocs ?? []) {\n names.set(String(list.$id), String(list.name ?? list.$id))\n }\n return names\n }, [listDocs])\n\n const listOptions = useMemo(\n () =>\n (listDocs ?? []).map((list: any) => ({\n value: String(list.$id),\n label: String(list.name ?? list.$id),\n })),\n [listDocs],\n )\n\n /*\n * The page's rows, in the QUERY's order. `campaignListRows` builds each\n * row — a container with its emails summed, or a single send as a\n * campaign of one — and sorts by date, which is not this list's order, so\n * the page is put back in the order the query returned it.\n */\n const rows = useMemo(() => {\n const read = page.rows as any[]\n const order = new Map(read.map((row, at) => [String(row.$id), at]))\n const built =\n kind === 'campaign'\n ? campaignListRows(\n read as EmailCampaign[],\n [...firstSends.rows, ...restSends.rows] as CampaignSend[],\n Date.now(),\n )\n : campaignListRows([], read as CampaignSend[], Date.now())\n const byId = new Map(read.map((row) => [String(row.$id), row]))\n return built\n .filter((row) => order.has(row.id))\n .sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0))\n .map((row) => ({\n ...row,\n $id: row.id,\n sitesLabel: orgMount\n ? campaignSitesLabel(orgMount, row, byId.get(row.id))\n : '',\n }))\n }, [kind, page.rows, firstSends.rows, restSends.rows, orgMount])\n\n const pageSorts = useMemo(\n () => ({\n sitesLabel: (row: any) => row.sitesLabel || null,\n windowState: (row: any) => row.startAtMs ?? row.endAtMs ?? null,\n listIds: (row: any) =>\n (row.listIds as string[]).map((id) => listNames.get(id) ?? id).join(', ') || null,\n emails: (row: any) => row.rollup.sends,\n sent: (row: any) => row.rollup.sent.value,\n opens: (row: any) => row.rollup.opens.value,\n clicks: (row: any) => row.rollup.clicks.value,\n }),\n [listNames],\n )\n const columnSort = useListColumnSort<any>({\n sorts: declaration.sorts,\n sort: askedSort,\n onSortChange: setAskedSort,\n orderBy: page.plan.orderBy,\n rows,\n pageSorts,\n headers: CAMPAIGN_PAGE_SORT_HEADERS,\n })\n\n /*\n * The choices the picked fields offer. A campaign's Sites are asked by\n * scope token — `org` is placed on every site — and a single send's by\n * the site it was sent as.\n */\n const filterOptions = useMemo(() => {\n if (!orgMount) return {}\n const sites = orgSiteOptions(orgMount)\n return kind === 'campaign'\n ? {\n listIds: listOptions,\n sitesLabel: [\n { value: 'org', label: 'Every site' },\n ...sites.map((site) => ({\n value: `host:${site.value}`,\n label: site.label,\n })),\n ],\n }\n : { sitesLabel: sites }\n }, [kind, listOptions, orgMount])\n\n const [createError, setCreateError] = useState<string | null>(null)\n const [creating, setCreating] = useState(false)\n /** The campaign a delete is in flight for, so its row menu can say so. */\n const [deletingId, setDeletingId] = useState('')\n\n const openCampaign = useCallback(\n (id: string) => {\n if (hubPath) void router.push(`${hubPath}/campaigns/${id}`)\n },\n [hubPath, router],\n )\n\n const handleCreate = useCallback(\n async (values: Record<string, any>) => {\n if (creating) return\n /*\n * `displayName` is the shared drawer's own field, and every artifact\n * create in the console collects a name under that key. The campaign\n * stores it as `name` — the container has one name and no second\n * internal label — so the mapping happens here rather than by giving\n * this one drawer a field the others do not have.\n */\n const name = String(values.displayName ?? '').trim()\n if (!name) return\n const startAtMs = values.startAt ? Date.parse(String(values.startAt)) : null\n const endAtMs = values.endAt ? Date.parse(String(values.endAt)) : null\n // Refused here rather than stored and rendered as a campaign that ends\n // before it starts, which no window state describes.\n if (startAtMs !== null && endAtMs !== null && endAtMs < startAtMs) {\n return setCreateError('The end date is before the start date')\n }\n /*\n * Held until the org is known. A container has one home, and a write\n * that raced the site's org lookup would have nowhere to go.\n */\n if (!orgId) {\n return setCreateError('This workspace is still loading — try again')\n }\n setCreating(true)\n setCreateError(null)\n const id = createResourceUid()\n /*\n * Where it is placed. From a site's hub, that site — the creator is\n * standing on it, and a campaign that appeared on every sibling site\n * would be a decision nobody made. From the org hub, the sites picked,\n * and every site when none are.\n */\n const visibleTo = campaignVisibleTo(\n hostId\n ? [hostId]\n : Array.isArray(values.siteIds)\n ? values.siteIds.map(String)\n : null,\n )\n try {\n await setDoc(campaignContainerDoc(firestore, orgId, id), {\n name,\n // What the list's search reads (AGL-3321), from the name.\n ...campaignContainerSearchFields(name),\n ...(Number.isFinite(startAtMs) && startAtMs !== null\n ? { startAtMs }\n : {}),\n ...(Number.isFinite(endAtMs) && endAtMs !== null ? { endAtMs } : {}),\n listIds: Array.isArray(values.listIds)\n ? values.listIds.map(String)\n : [],\n ...(values.topicId ? { topicId: String(values.topicId) } : {}),\n visibleTo,\n createdAtMs: Date.now(),\n createdBy: String((user as any)?.uid ?? ''),\n })\n setCreateOpen(false)\n openCampaign(id)\n } catch (error) {\n console.error(error)\n setCreateError('The campaign could not be created')\n enqueueSnackbar('Could not create the campaign', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setCreating(false)\n }\n },\n [creating, firestore, hostId, orgId, user, enqueueSnackbar, openCampaign],\n )\n\n const campaignHref = useCallback(\n (id: string) => (hubPath ? `${hubPath}/campaigns/${id}` : null),\n [hubPath],\n )\n\n /*==========================================\n * DELETING A CAMPAIGN FROM ITS ROW.\n *\n * The container goes and its emails stay — the route detaches them first,\n * so each one keeps its id, its report and its unsubscribe links, and\n * reappears in this very table as a \"Single send\". That is not a\n * convenience: a send id is inside the HMAC of every unsubscribe footer\n * already delivered, so a delete that took the sends with it would break\n * opt-outs that must go on working.\n *\n * The confirmation names the count and says what the delete does NOT do.\n * Deleting a campaign cancels nothing — a scheduled email inside it still\n * goes out — and a merchant who reads the button as \"stop this campaign\"\n * has to be told before they press it.\n *\n * EDITING is deliberately not offered here. A record is edited on its own\n * page in this console; the campaign's page carries the edit drawer, and\n * this row's first entry is the way to it.\n *=========================================*/\n const handleDelete = useCallback(\n async (row: CampaignListRow) => {\n if (deletingId) return\n const emails = row.sends.length\n /*\n * Emails with mail still to go: waiting for their time, AND part way\n * through an audience larger than one batch. Counting only `scheduled`\n * would miss the case that needs the warning most — an email delivering\n * right now is stored as `scheduled` too, and `rollup.scheduled` is the\n * narrower reading that leaves it out.\n */\n const unfinished = row.rollup.scheduled + row.rollup.sending\n const agreed = await confirm({\n title: `Delete ${row.name}?`,\n description:\n (emails\n ? `The ${emails.toLocaleString()} ` +\n `${emails === 1 ? 'email' : 'emails'} in it are kept — each ` +\n 'keeps its own report and its unsubscribe links, and they stay ' +\n 'in this list as single sends. '\n : 'It holds no emails. ') +\n (unfinished\n ? `${unfinished.toLocaleString()} of them ${\n unfinished === 1 ? 'is' : 'are'\n } still going out or still due, and deleting the campaign does ` +\n 'not stop that — the sender picks each one up from its own ' +\n 'record. Stop a send from its own page. '\n : '') +\n 'Any pages, forms and contacts assigned to it come out of it and ' +\n 'are otherwise untouched. Only the campaign itself goes.',\n confirmationText: 'Delete campaign',\n })\n .then(() => true)\n .catch(() => false)\n if (!agreed) return\n setDeletingId(row.id)\n try {\n const { response, payload } = await manageApi({\n action: 'deleteCampaign',\n campaignId: row.id,\n })\n if (!response.ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'The campaign could not be deleted',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n enqueueSnackbar('Campaign deleted', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('The campaign could not be deleted', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setDeletingId('')\n }\n },\n [confirm, deletingId, enqueueSnackbar, manageApi],\n )\n\n const columns = useMemo(\n () => [\n {\n field: 'name',\n headerName: filterHeaders.name,\n flex: 1,\n minWidth: 180,\n renderCell: ({ row }: any) => (\n <Stack\n direction=\"row\"\n spacing={1}\n /*\n `minWidth: 0` on the row AND on the name: a flex child will not\n shrink below its content without it, so the chip beside it is\n what gets clipped instead of the name being ellipsed.\n */\n sx={{ alignItems: 'center', minWidth: 0, width: 1 }}\n >\n {/*\n The name is a real anchor as well as the row being clickable, so\n a campaign can be middle-clicked into a tab or copied out of the\n context menu — affordances a row handler cannot offer. The grid's\n own row click fires too, so the link stops the event rather than\n pushing the same route twice.\n */}\n {campaignHref(row.id) ? (\n <AppLink\n href={campaignHref(row.id) as string}\n onClick={(event: { stopPropagation: () => void }) =>\n event.stopPropagation()\n }\n style={{ minWidth: 0 }}\n >\n <Typography variant=\"body2\" noWrap>\n {row.name}\n </Typography>\n </AppLink>\n ) : (\n <Typography variant=\"body2\" noWrap sx={{ minWidth: 0 }}>\n {row.name}\n </Typography>\n )}\n {row.legacy ? (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n label=\"Single send\"\n // A label that reads \"Single sen\" is worse than a shorter name.\n sx={{ flexShrink: 0 }}\n title={\n 'Sent before campaigns grouped their emails. Its report ' +\n 'and its unsubscribe links are unchanged.'\n }\n />\n ) : null}\n </Stack>\n ),\n },\n /*\n WHERE IT IS PLACED, on the org hub only. Under a site every row is on\n that site by construction, so the column would say one thing thirty\n times.\n */\n ...(orgMount\n ? [\n {\n field: 'sitesLabel',\n headerName: 'Sites',\n width: 170,\n sortable: false,\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\" noWrap>\n {row.sitesLabel}\n </Typography>\n ),\n },\n ]\n : []),\n {\n field: 'windowState',\n headerName: 'Window',\n width: 170,\n renderCell: ({ row }: any) => {\n const start = formatDay(row.startAtMs)\n const end = formatDay(row.endAtMs)\n const range =\n start && end && start !== end\n ? `${start} – ${end}`\n : start || end || ''\n return (\n <Stack sx={{ minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {WINDOW_LABEL[row.windowState as CampaignListRow['windowState']]}\n </Typography>\n {range ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {range}\n </Typography>\n ) : null}\n </Stack>\n )\n },\n },\n {\n field: 'listIds',\n headerName: 'Lists',\n width: 140,\n sortable: false,\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\" noWrap>\n {row.listIds.length\n ? row.listIds\n .map((id: string) => listNames.get(id) ?? id)\n .join(', ')\n : '—'}\n </Typography>\n ),\n },\n /*\n THE FOUR COUNTS, RIGHT-ALIGNED HEAD AND BODY.\n A figure is read by its last digit, so a column of them lines up on\n the right or it does not line up at all. `headerAlign` has to be said\n as well as `align`: a grid column defaults its header to the column\n type's alignment rather than to the cell's, which is how these came to\n sit with left headers over figures nobody could compare down the page.\n\n EVERY ONE OF THEM MEASURES THE MAIL, and the headings say so. What a\n campaign CAUSED — the submissions, leads, contacts and bookings\n credited to it — is not a column here, because there is no figure to\n read: a container has no conversion counter of its own, so a column\n would be an aggregation per row for a campaign and a subcollection\n document per row for a single send, on a list that costs two queries\n however many campaigns it holds. Headings that named the campaign over\n figures that all described its mail were the cheaper mistake, so the\n headings name the mail and the note under the table says where the\n outcome figures are.\n */\n {\n field: 'emails',\n headerName: 'Emails',\n width: 128,\n align: 'right',\n headerAlign: 'right',\n /*\n THE COUNT, AND WHAT IS STILL HAPPENING TO IT.\n\n `sending` is called out apart from `scheduled` because the two are\n opposite readings of the same stored status: an email delivering an\n audience larger than one batch sits as `scheduled` between runs, and\n rolling it in with the ones that have mailed nobody reports a\n campaign that is half delivered as a campaign that has not started.\n\n The note sits UNDER the figure rather than beside it — the column\n would otherwise have to be wide enough for the longest sentence, and\n the figure is what the column is read for.\n */\n renderCell: ({ row }: any) => {\n const { sends, sending, scheduled } = row.rollup\n const note = [\n sending ? `${sending} sending` : '',\n scheduled ? `${scheduled} scheduled` : '',\n ]\n .filter(Boolean)\n .join(', ')\n return (\n <Stack sx={{ alignItems: 'flex-end', minWidth: 0, width: 1 }}>\n <Typography variant=\"body2\">{String(sends)}</Typography>\n {note ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {note}\n </Typography>\n ) : null}\n </Stack>\n )\n },\n },\n {\n field: 'sent',\n headerName: 'Mail sent',\n width: 112,\n align: 'right',\n headerAlign: 'right',\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\">{figure(row.rollup.sent)}</Typography>\n ),\n },\n {\n field: 'opens',\n headerName: 'Mail opens',\n width: 112,\n align: 'right',\n headerAlign: 'right',\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\">{figure(row.rollup.opens)}</Typography>\n ),\n },\n {\n field: 'clicks',\n headerName: 'Mail clicks',\n width: 112,\n align: 'right',\n headerAlign: 'right',\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\">{figure(row.rollup.clicks)}</Typography>\n ),\n },\n /*\n THE TRAILING CLUSTER, through the grid's own actions column.\n `listActionsColumn` is what every other grid list in the console\n renders, so the reader cannot tell which family of table they are\n standing in — the hand-rolled tables on this surface reach the same\n `RowActionsMenu` from the other direction.\n\n Opening the campaign is restated here even though the row click does\n the same thing, for the reason the screens table restates its own: the\n menu is where a row's actions are NAMED, and an action absent from it\n reads as an action the row does not have.\n\n A \"Single send\" row is a SEND with no container — the table adopts it\n so a merchant's history is not missing — and there is no container\n under it to delete. Its entry is shown disabled with that reason\n rather than hidden, because a control that vanishes and one that does\n not apply look identical from the outside.\n */\n listActionsColumn(\n (row: any) => (\n <ListRowActions\n label={String(row.name ?? row.id)}\n items={[\n {\n key: 'details',\n label: 'Open campaign',\n icon: <MdiIcon path={mdiEyeOutline.path} size={0.8} />,\n href: campaignHref(row.id) ?? undefined,\n disabled: !campaignHref(row.id),\n disabledReason: campaignHref(row.id)\n ? undefined\n : 'This site’s console URL has not resolved yet',\n },\n {\n key: 'delete',\n label: 'Delete campaign',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: row.legacy || Boolean(deletingId),\n disabledReason: row.legacy\n ? 'This is a single send, not a campaign. Open it to ' +\n 'manage the email itself.'\n : 'A campaign is being deleted',\n onClick: () => void handleDelete(row as CampaignListRow),\n },\n ]}\n />\n ),\n { width: 72 },\n ),\n ],\n [listNames, campaignHref, deletingId, handleDelete, orgMount, filterHeaders],\n )\n\n /** Nothing of this kind stored at all — not a filter that matched nothing. */\n const none =\n page.status !== 'loading' && !rows.length && !filtering && page.page === 0\n\n /*\n * Other ways to start a campaign, from plugins (AGL-3603): the\n * `hostCampaigns` zone this plugin declares, drawn through the shell's own\n * gated slot. On the organization's hub it is handed the sites a campaign\n * could be placed on, since there is no one site to take.\n */\n const campaignsZone = (\n <HostCampaignsZone\n hostId={hostId}\n orgId={orgId}\n sites={\n hostId\n ? []\n : (orgMount?.hosts ?? []).map((host) => ({ id: host.id, name: host.name }))\n }\n />\n )\n\n return (\n <CardDisplay\n header={'Campaigns'}\n help={pluginDocsHelp('emailCampaigns', {\n anchor: '#campaigns-group-emails',\n excerpt:\n 'A campaign groups the emails you send to a set of lists over a ' +\n 'window of dates. Open one to write and send an email inside it.',\n })}\n HeaderProps={{\n action: (\n <Stack direction=\"row\" spacing={1}>\n {campaignsZone}\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={creating}\n onClick={() => {\n setCreateError(null)\n setCreateOpen(true)\n }}\n >\n {creating ? 'Creating…' : 'Create campaign'}\n </Button>\n </Stack>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <ToggleButtonGroup\n exclusive\n size=\"small\"\n value={kind}\n onChange={(_event, next: CampaignListKind | null) => {\n if (next) {\n setKind(next)\n setAskedSort(null)\n }\n }}\n aria-label=\"Which rows the table lists\"\n sx={{ alignSelf: 'flex-start' }}\n >\n <ToggleButton value=\"campaign\">{'Campaigns'}</ToggleButton>\n <ToggleButton value=\"single\">{'Single sends'}</ToggleButton>\n </ToggleButtonGroup>\n <ListFilterChips\n fields={declaration.fields}\n headers={filterHeaders}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={filterOptions}\n />\n <ListQueryNotices\n refused={listQueryRefusals(page.plan.refused, {\n fields: declaration.fields,\n headers: filterHeaders,\n options: filterOptions,\n })}\n notices={[\n ...(siteSearch ? [CAMPAIGN_SITE_SEARCH_NOTICE] : []),\n ...page.plan.notices,\n ...columnSort.notices,\n ]}\n />\n <ListTable\n rows={columnSort.rows}\n columns={listFilterGridColumns(\n columns as any,\n declaration.fields,\n filterOptions,\n filterHeaders,\n )}\n onOpen={(id) => openCampaign(id)}\n loading={page.status === 'loading'}\n /*\n * The panel and the search are the grid's; every clause and the\n * search word are on the list's query (AGL-3321), and the grid\n * neither filters nor sorts the page it is handed: a stored\n * column's header orders the query, a drawn one the page\n * (AGL-3680).\n */\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n columnSort={columnSort}\n hideFooter\n initialState={{\n columns: {\n columnVisibilityModel: hiddenFilterVisibility(\n declaration.fields,\n (columns as Array<{ field: string }>).map((column) => column.field),\n ),\n },\n }}\n noRowsLabel={\n none\n ? kind === 'campaign'\n ? 'No campaigns yet'\n : 'No single sends'\n : kind === 'campaign'\n ? 'No campaigns match these filters'\n : 'No single sends match these filters'\n }\n noRowsDescription={\n none\n ? kind === 'campaign'\n ? 'A campaign groups the emails you send to a set of lists.'\n : 'An email filed under no campaign is listed here.'\n : undefined\n }\n noRowsAction={\n none && kind === 'campaign' ? (\n <Stack direction=\"row\" spacing={1}>\n {/* Other ways to start a campaign, the header's zone again. */}\n {campaignsZone}\n <Button variant=\"contained\" onClick={() => setCreateOpen(true)}>\n {'Create campaign'}\n </Button>\n </Stack>\n ) : undefined\n }\n />\n <ListPagination\n page={page.page}\n pageSize={page.pageSize}\n rowCount={rows.length}\n hasMore={page.hasMore}\n onPageChange={page.setPage}\n onPageSizeChange={page.setPageSize}\n />\n {/*\n WHAT THIS TABLE MEASURES, said rather than inferred from the column\n names. Every figure in it is a fact about the campaign's mail, and a\n reader comparing rows is comparing mailings — the conversions and the\n destinations credited to a campaign are on the campaign's own page,\n because counting them for every row is a read per row on a list whose\n whole cost is two queries.\n */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'These figures measure each campaign’s mail. What a campaign ' +\n 'caused — the form submissions, leads, contacts and bookings ' +\n 'credited to it — and the pages it sent people to are on the ' +\n 'campaign’s own page.'}\n </Typography>\n {rollupTruncated ? (\n <Alert severity=\"info\">\n {`The campaigns on this page hold more than ${ROLLUP_CEILING} ` +\n 'emails between them, so their figures count the first ' +\n `${ROLLUP_CEILING} read.`}\n </Alert>\n ) : null}\n </Stack>\n {/*\n The console's own create drawer, from the shared library rather than a\n second one that looks like it. What a campaign collects beyond a name\n is its window, the lists it is aimed at and the stream its emails open\n on; the description box is left off because the container stores none,\n and a field the writer discards is worse than one never offered.\n */}\n {/* Draws nothing: the zone the topic catalog's owner answers through. */}\n {topicSource}\n <CreateArtifactDrawer\n open={createOpen}\n onClose={() => setCreateOpen(false)}\n title=\"Create campaign\"\n submitLabel=\"Create campaign\"\n includeDescription={false}\n onSubmit={handleCreate}\n extraFields={campaignFields(\n listOptions,\n topicOptions,\n orgMount ? orgSiteOptions(orgMount) : null,\n )}\n errorSlot={\n createError ? (\n <Alert severity=\"error\" sx={{ mt: 2, mb: 1 }}>\n {createError}\n </Alert>\n ) : null\n }\n />\n </CardDisplay>\n )\n}\n/**\n * What a campaign collects beyond its name.\n *\n * Data-driven-forms field descriptors, built from the org's own lists and\n * topics so the drawer offers what this workspace actually has. Dates are\n * plain `date` inputs: a campaign window is a day at each end, and a time of\n * day would be a precision the model does not carry.\n */\nfunction campaignFields(\n lists: Array<{ value: string; label: string }>,\n topics: Array<{ value: string; label: string }>,\n /** The org's sites, on the org hub only — a site hub places on itself. */\n sites: Array<{ value: string; label: string }> | null,\n): any[] {\n return [\n ...(sites\n ? [\n {\n component: 'select',\n name: 'siteIds',\n label: 'Sites',\n multiple: true,\n initialValue: [],\n helperText:\n 'The sites this campaign is offered on. Leave empty for every site.',\n disableDefaultOption: true,\n options: sites,\n },\n ]\n : []),\n {\n component: 'text-field',\n name: 'startAt',\n label: 'Starts',\n type: 'date',\n helperText: 'When the campaign window opens',\n },\n {\n component: 'text-field',\n name: 'endAt',\n label: 'Ends',\n type: 'date',\n helperText: 'Leave empty for an open-ended campaign',\n InputLabelProps: { shrink: true },\n },\n {\n component: 'select',\n name: 'listIds',\n label: 'Lists',\n multiple: true,\n initialValue: [],\n // A campaign with no list is legitimate: its emails can go to leads, to\n // site members, or to a segment. The lists are what it is AIMED at.\n helperText: 'The lists this campaign is aimed at',\n disableDefaultOption: true,\n options: lists,\n },\n {\n component: 'select',\n name: 'topicId',\n label: 'Topic',\n helperText: 'The stream its emails open on — each one can change it',\n disableDefaultOption: true,\n options: topics,\n },\n ]\n}\n\n/**\n * The Sites cell: where a campaign is offered.\n *\n * A container reads its `visibleTo`; a single send, which has no container,\n * is on the one site it was sent as. An empty placement is said rather than\n * left blank, because a blank cell reads as \"every site\" and it means none.\n */\nfunction campaignSitesLabel(\n mount: MarketingOrgMount,\n row: CampaignListRow,\n container: EmailCampaign | undefined,\n): string {\n if (row.legacy) return orgSiteName(mount, row.sends[0]?.hostId) || '—'\n const ids = campaignSiteIds(container)\n if (ids === null) return 'Every site'\n if (!ids.length) return 'No site'\n return ids.map((id) => orgSiteName(mount, id)).join(', ')\n}\n\nHostCampaignsCard.displayName = 'HostCampaignsCard'\n\nexport default HostCampaignsCard\n"],"names":["buildRoute","createResourceUid","pluginDocsHelp","Route","ceilingedWindow","collectionCeiling","useListQuery","mdiDeleteOutline","mdiEyeOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListRowActions","ListTable","listActionsColumn","hiddenFilterVisibility","listFilterGridColumns","useListGridFilter","useListColumnSort","useSnackbar","Alert","Button","Chip","Stack","ToggleButton","ToggleButtonGroup","Typography","collection","limit","query","setDoc","where","useCallback","useMemo","useState","useRouter","useConsoleHostRoute","useFirestore","useFirestoreCollection","useUser","campaignListRows","campaignSiteIds","campaignVisibleTo","CreateArtifactDrawer","CAMPAIGN_SITE_SEARCH_NOTICE","SINGLE_SENDS_BASE","campaignContainerSearchFields","campaignContainersListQuery","campaignContainersScope","campaignSendsScope","campaignSingleSendsListQuery","campaignSiteSearchClause","campaignContainerDoc","campaignContainersCollection","campaignSendsCollection","orgSiteName","orgSiteOptions","topicCatalogHostId","useMarketingOrgId","useMarketingOrgMount","useCampaignManageApi","HostCampaignsZone","useCampaignTopicOptions","ROLLUP_CEILING","IN_LIMIT","formatDay","ms","Date","toLocaleDateString","figure","value","toLocaleString","CAMPAIGN_PAGE_SORT_HEADERS","sitesLabel","windowState","listIds","emails","sent","opens","clicks","WINDOW_LABEL","undated","upcoming","running","ended","CAMPAIGN_FILTER_HEADERS","campaign","name","createdAtMs","single","NO_CLAUSES","HostCampaignsCard","props","hostId","basePath","firestore","router","orgSlug","subdomain","hubPath","HOST_PLUGIN","host","pluginSlug","data","user","enqueueSnackbar","confirm","orgMount","orgId","manageApi","kind","setKind","askedSort","setAskedSort","clausesByKind","setClausesByKind","searchWords","setSearchWords","setKindClauses","next","current","gridFilter","clauses","onChange","selectFields","search","words","containerDeclaration","singleDeclaration","declaration","filterHeaders","siteSearch","containerPage","request","base","sort","deps","idField","singlePage","page","filtering","length","some","word","trim","pageIds","rows","map","row","String","$id","rollupRead","ids","sends","firstIds","slice","restIds","firstSendDocs","join","restSendDocs","firstSends","restSends","rollupTruncated","truncated","listDocs","createOpen","setCreateOpen","topics","source","topicSource","enabled","topicOptions","topic","id","label","listNames","names","Map","list","set","listOptions","read","order","at","built","now","byId","filter","has","a","b","get","campaignSitesLabel","pageSorts","startAtMs","endAtMs","rollup","columnSort","sorts","onSortChange","orderBy","plan","headers","filterOptions","sites","site","createError","setCreateError","creating","setCreating","deletingId","setDeletingId","openCampaign","push","handleCreate","values","displayName","startAt","parse","endAt","visibleTo","Array","isArray","siteIds","Number","isFinite","topicId","createdBy","uid","error","console","variant","allowDuplicate","campaignHref","handleDelete","unfinished","scheduled","sending","agreed","title","description","confirmationText","then","catch","response","payload","action","campaignId","ok","persist","columns","field","headerName","flex","minWidth","renderCell","direction","spacing","sx","alignItems","width","href","onClick","event","stopPropagation","style","noWrap","legacy","size","flexShrink","sortable","start","end","range","color","align","headerAlign","note","Boolean","items","key","icon","path","undefined","disabled","disabledReason","destructive","none","status","campaignsZone","hosts","header","help","anchor","excerpt","HeaderProps","contentGutterX","contentGutterY","exclusive","_event","aria-label","alignSelf","fields","setClauses","options","refused","notices","onOpen","loading","filterMode","filterModel","onFilterModelChange","quickFilter","hideFooter","initialState","columnVisibilityModel","column","noRowsLabel","noRowsDescription","noRowsAction","pageSize","rowCount","hasMore","onPageChange","setPage","onPageSizeChange","setPageSize","severity","open","onClose","submitLabel","includeDescription","onSubmit","extraFields","campaignFields","errorSlot","mt","mb","lists","component","multiple","initialValue","helperText","disableDefaultOption","type","InputLabelProps","shrink","mount","container"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,UAAU,EAAEC,iBAAiB,EAAEC,cAAc,EAAEC,KAAK,QAAQ,eAAc;AACnF;;;;CAIC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,YAA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PwK,YAAY;YACZC,sBAAsB;YACtBvC,SAASzI;QACX;KACD;AACH;AAEA;;;;;;CAMC,GACD,SAASyB,mBACP2J,KAAwB,EACxBvM,GAAoB,EACpBwM,SAAoC;QAEMxM;IAA1C,IAAIA,IAAIuH,MAAM,EAAE,OAAOpN,YAAYoS,QAAOvM,cAAAA,IAAIK,KAAK,CAAC,EAAE,qBAAZL,YAAcvD,MAAM,KAAK;IACnE,MAAM2D,MAAM/G,gBAAgBmT;IAC5B,IAAIpM,QAAQ,MAAM,OAAO;IACzB,IAAI,CAACA,IAAIX,MAAM,EAAE,OAAO;IACxB,OAAOW,IAAIL,GAAG,CAAC,CAAC0B,KAAOtH,YAAYoS,OAAO9K,KAAKf,IAAI,CAAC;AACtD;AAEAnE,kBAAkB6H,WAAW,GAAG;AAEhC,eAAe7H,kBAAiB"}
@@ -23,6 +23,8 @@ import ListFilterChips from "@aglyn/shared-ui-jsx/components/list-filter-chips.c
23
23
  import { ListTable } from "@aglyn/shared-ui-jsx/components/list-table.component";
24
24
  import { listFilterGridColumns } from "@aglyn/shared-ui-jsx/const/list-grid-filter";
25
25
  import { useListGridFilter } from "@aglyn/shared-ui-jsx/hooks/use-list-grid-filter";
26
+ import { useListColumnSort } from "@aglyn/shared-ui-jsx/hooks/use-list-column-sort";
27
+ import ListQueryNotices from "@aglyn/shared-ui-jsx/components/list-query-notices.component";
26
28
  import { TABLE_ROW_HEIGHT } from "@aglyn/shared-ui-jsx/const/table-pagination";
27
29
  import { useUser } from "@aglyn/tenant-feature-instance";
28
30
  import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
@@ -63,6 +65,29 @@ const RECIPIENT_FILTER_OPTIONS = {
63
65
  const RECIPIENT_HIDDEN_COLUMNS = {
64
66
  engagement: false
65
67
  };
68
+ /*
69
+ * EVERY HEADER SORTS, OVER THE PAGE (AGL-3680). The rows are an aggregate
70
+ * the recipients route builds from the per-recipient delivery log across
71
+ * the template's emails, paged by its cursor newest first — no query here
72
+ * can order them by a column — so each header sorts the page on screen and
73
+ * says so.
74
+ */ const RECIPIENT_PAGE_SORTS = {
75
+ to: (row)=>row.to,
76
+ subject: (row)=>row.subject,
77
+ status: (row)=>row.status,
78
+ openCount: (row)=>row.openCount,
79
+ clickCount: (row)=>row.clickCount,
80
+ lastEventAtMs: (row)=>row.lastEventAtMs || null
81
+ };
82
+ const RECIPIENT_PAGE_SORT_HEADERS = {
83
+ to: 'Recipient',
84
+ subject: 'Email',
85
+ status: 'State',
86
+ openCount: 'Opens',
87
+ clickCount: 'Clicks',
88
+ lastEventAtMs: 'Last event'
89
+ };
90
+ const NO_QUERY_SORTS = [];
66
91
  const recipientsDocsHelp = pluginDocsHelp('emailCampaigns', {
67
92
  anchor: '#opens--clicks',
68
93
  excerpt: 'The people an email reached, and which of them opened it or clicked ' + 'a link — read from the per-recipient delivery log.'
@@ -301,6 +326,12 @@ const recipientsDocsHelp = pluginDocsHelp('emailCampaigns', {
301
326
  ], [
302
327
  emailId
303
328
  ]);
329
+ const columnSort = useListColumnSort({
330
+ sorts: NO_QUERY_SORTS,
331
+ rows,
332
+ pageSorts: RECIPIENT_PAGE_SORTS,
333
+ headers: RECIPIENT_PAGE_SORT_HEADERS
334
+ });
304
335
  const filterColumns = useMemo(()=>listFilterGridColumns(columns, RECIPIENT_FILTER_FIELDS, RECIPIENT_FILTER_OPTIONS, RECIPIENT_FILTER_HEADERS), [
305
336
  columns
306
337
  ]);
@@ -330,6 +361,10 @@ const recipientsDocsHelp = pluginDocsHelp('emailCampaigns', {
330
361
  severity: "warning",
331
362
  children: failure
332
363
  }) : null,
364
+ /*#__PURE__*/ _jsx(ListQueryNotices, {
365
+ refused: [],
366
+ notices: columnSort.notices
367
+ }),
333
368
  campaignsOmitted ? /*#__PURE__*/ _jsx(Alert, {
334
369
  severity: "info",
335
370
  children: 'This template has been used by more emails than one read can ' + `span. These rows cover its ${campaignsRead} most recent ` + `emails; ${campaignsOmitted} older ` + `${campaignsOmitted === 1 ? 'email is' : 'emails are'} ` + 'not included.'
@@ -340,7 +375,7 @@ const recipientsDocsHelp = pluginDocsHelp('emailCampaigns', {
340
375
  children: 'No delivery records have been kept for this yet.'
341
376
  }) : /*#__PURE__*/ _jsx(ListTable, {
342
377
  "aria-label": "Recipients",
343
- rows: rows,
378
+ rows: columnSort.rows,
344
379
  columns: filterColumns,
345
380
  loading: loading,
346
381
  getRowId: (row)=>row.messageId,
@@ -353,7 +388,7 @@ const recipientsDocsHelp = pluginDocsHelp('emailCampaigns', {
353
388
  // Its panel's one filter is the route's (AGL-3317). Nor does it
354
389
  // sort: a header sort would order that one page, not the log.
355
390
  hideFooter: true,
356
- disableColumnSorting: true,
391
+ columnSort: columnSort,
357
392
  filterMode: "server",
358
393
  filterModel: gridFilter.filterModel,
359
394
  onFilterModelChange: gridFilter.onFilterModelChange,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/email-recipients-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 { pluginDocsHelp } from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListTable } from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport type { ListFilterField } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { Alert, Chip, Stack, Typography } from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { useEffect, useMemo, useState } from 'react'\n\n/** The server's page size. Fixed, so the reader is not offered a choice. */\nconst PAGE_SIZE = 25\n\n/** Which recipients the table asks for. Matches the route's own vocabulary. */\ntype EngagementFilter = 'all' | 'opened' | 'clicked'\n\n/*\n * What the recipients grid's Filters panel offers (AGL-3317): the one filter\n * the route serves, as a hidden select column. The route answers it over the\n * whole delivery log, one cursor page at a time, and serves nothing else —\n * so no other column filters, and there is no quick search, which could only\n * ever narrow the page on screen.\n */\nconst RECIPIENT_FILTER_FIELDS: readonly ListFilterField[] = [\n { column: 'engagement', kind: 'exact', path: 'engagement', operators: ['equals'] },\n]\nconst RECIPIENT_FILTER_HEADERS: Readonly<Record<string, string>> = {\n engagement: 'Engagement',\n}\nconst RECIPIENT_FILTER_OPTIONS = {\n engagement: [\n { value: 'opened', label: 'Opened it' },\n { value: 'clicked', label: 'Clicked something' },\n ],\n}\nconst RECIPIENT_HIDDEN_COLUMNS = { engagement: false }\n\ninterface RecipientRow {\n messageId: string\n to: string\n subject: string | null\n campaignId: string | null\n status: string\n openCount: number\n clickCount: number\n clickedLinks: string[]\n firstSeenAtMs: number\n lastEventAtMs: number\n}\n\nconst recipientsDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#opens--clicks',\n excerpt:\n 'The people an email reached, and which of them opened it or clicked ' +\n 'a link — read from the per-recipient delivery log.',\n})\n\nexport interface EmailRecipientsCardProps {\n hostId: string\n /**\n * Read every message built from this template.\n *\n * Exactly one of `screenId` and `emailId` is passed. The route takes the\n * SCOPE rather than a list of message ids because a caller who could name\n * ids could name another site's, and the narrower input is the one that\n * cannot be got wrong later.\n */\n screenId?: string\n /** Read one message. */\n emailId?: string\n}\n\n/**\n * WHO, not how many.\n *\n * ## Why this is a fetch and not a listen\n *\n * Every other card on this page reads Firestore directly. This one cannot:\n * the per-recipient delivery log lives at `emailDeliveries/{sha256(address)}`\n * — one platform-level collection holding every site's mail and every\n * transactional message besides — and the query that narrows it to this\n * site's campaigns is a collection-group query whose scoping predicate is\n * part of the query. A security rule cannot require a `where` clause, so\n * there is no rule that would admit this read and refuse the same read\n * without the filter. The narrowing happens on the server, behind the same\n * site role the send path requires.\n *\n * ## Why it is its own card\n *\n * A separate card is a separate mount, and this is the only read on either\n * detail page whose cost grows with how much mail there has been. It asks\n * once on mount and once per page turn — never on a poll — so a reader who\n * came for the preview and the totals above pays for one page of this and\n * nothing more.\n *\n * ## The cursor, and why \"Previous\" keeps a stack\n *\n * The route pages forward with an opaque cursor, which is the only shape a\n * Firestore query offers without counting the whole result first. Going back\n * therefore means remembering where each page started, so the cursors are\n * kept in a list indexed by page — `null` for the first — rather than\n * re-walking forward from the beginning.\n */\nexport function EmailRecipientsCard(props: EmailRecipientsCardProps) {\n const { hostId, screenId, emailId } = props\n const { data: user } = useUser()\n\n const gridFilter = useListGridFilter({ selectFields: ['engagement'], single: true })\n const asked = gridFilter.clauses.find((clause) => clause.field === 'engagement')?.value\n const filter: EngagementFilter =\n asked === 'opened' || asked === 'clicked' ? asked : 'all'\n const [page, setPage] = useState(0)\n /** Cursor for each page. Index 0 is always `null` — the first page. */\n const [cursors, setCursors] = useState<(string | null)[]>([null])\n const [rows, setRows] = useState<RecipientRow[]>([])\n const [hasMore, setHasMore] = useState(false)\n const [loading, setLoading] = useState(true)\n const [failure, setFailure] = useState<string | null>(null)\n const [campaignsOmitted, setCampaignsOmitted] = useState(0)\n const [campaignsRead, setCampaignsRead] = useState(0)\n\n const cursor = cursors[page] ?? null\n\n useEffect(() => {\n if (!user) return undefined\n let active = true\n setLoading(true)\n setFailure(null)\n void (async () => {\n try {\n const response = await authorizedFetch(\n user,\n '/api/campaigns/recipients',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n ...(screenId ? { screenId } : {}),\n ...(emailId ? { emailId } : {}),\n filter,\n cursor,\n }),\n },\n )\n const payload = await response.json().catch(() => ({}))\n if (!active) return\n if (!response.ok) {\n setRows([])\n setHasMore(false)\n setFailure(String(payload?.error ?? 'Could not read recipients'))\n return\n }\n /*\n * A read that FAILED is not a campaign nobody opened.\n *\n * The route answers 200 with `lookupFailed` for a delivery-log read\n * that could not run — a missing collection-group index is the likely\n * one — because the rest of the payload is still true. Rendering that\n * as an empty table is how a merchant concludes their campaign\n * reached nobody, which is the one wrong answer this table can give.\n */\n if (payload?.lookupFailed) {\n setRows([])\n setHasMore(false)\n setFailure(\n 'The delivery log could not be read, so this table is empty for ' +\n 'a reason that has nothing to do with your campaign. The ' +\n 'numbers above come from the campaigns themselves and are ' +\n 'unaffected.',\n )\n return\n }\n const nextRows: RecipientRow[] = Array.isArray(payload?.rows)\n ? payload.rows\n : []\n setRows(nextRows)\n setCampaignsOmitted(Number(payload?.campaignsOmitted ?? 0))\n setCampaignsRead(Number(payload?.campaignsRead ?? 0))\n const nextCursor: string | null = payload?.cursor ?? null\n setHasMore(Boolean(nextCursor))\n if (nextCursor) {\n setCursors((existing) => {\n if (existing[page + 1] === nextCursor) return existing\n const next = existing.slice(0, page + 1)\n next[page + 1] = nextCursor\n return next\n })\n }\n } catch (error) {\n console.error(error)\n if (active) {\n setRows([])\n setHasMore(false)\n setFailure('Could not read recipients')\n }\n } finally {\n if (active) setLoading(false)\n }\n })()\n return () => {\n active = false\n }\n }, [user, hostId, screenId, emailId, filter, cursor, page])\n\n // A new filter is a new result set, so the cursors collected under the old\n // one describe positions in a query that no longer exists.\n const [askedFilter, setAskedFilter] = useState<EngagementFilter>(filter)\n if (askedFilter !== filter) {\n setAskedFilter(filter)\n setPage(0)\n setCursors([null])\n }\n\n const columns = useMemo<GridColDef<RecipientRow>[]>(\n () => [\n {\n field: 'to',\n headerName: 'Recipient',\n flex: 1,\n minWidth: 240,\n renderCell: ({ row }) => (\n <Stack spacing={0.5} sx={{ py: 1, minWidth: 0, wordBreak: 'break-all' }}>\n <Typography variant=\"body2\">{row.to}</Typography>\n {/*\n * WHICH links, under the person who followed them. The\n * per-campaign link rollup counts destinations and names nobody;\n * this is the other half of the same question, and it is the half\n * a merchant asks when they want to know who to call.\n */}\n {row.clickedLinks.map((link) => (\n <Typography key={link} variant=\"caption\" color=\"text.secondary\">\n {link}\n </Typography>\n ))}\n </Stack>\n ),\n },\n ...(emailId\n ? []\n : [\n {\n field: 'subject',\n headerName: 'Email',\n flex: 1,\n minWidth: 180,\n valueGetter: (_value: unknown, row: RecipientRow) => row.subject ?? '—',\n } satisfies GridColDef<RecipientRow>,\n ]),\n {\n field: 'status',\n headerName: 'State',\n width: 130,\n renderCell: ({ row }) => <Chip size=\"small\" label={row.status} />,\n },\n {\n field: 'openCount',\n headerName: 'Opens',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 100,\n renderCell: ({ row }) => (\n <Typography variant=\"body2\" sx={{ fontWeight: 'bold' }}>\n {row.openCount.toLocaleString()}\n </Typography>\n ),\n },\n {\n field: 'clickCount',\n headerName: 'Clicks',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 100,\n renderCell: ({ row }) => (\n <Typography variant=\"body2\" sx={{ fontWeight: 'bold' }}>\n {row.clickCount.toLocaleString()}\n </Typography>\n ),\n },\n {\n field: 'lastEventAtMs',\n headerName: 'Last event',\n width: 190,\n renderCell: ({ row }) =>\n row.lastEventAtMs ? new Date(row.lastEventAtMs).toLocaleString() : '—',\n },\n ],\n [emailId],\n )\n const filterColumns = useMemo(\n () =>\n listFilterGridColumns(\n columns as GridColDef[],\n RECIPIENT_FILTER_FIELDS,\n RECIPIENT_FILTER_OPTIONS,\n RECIPIENT_FILTER_HEADERS,\n ),\n [columns],\n )\n\n return (\n <CardDisplay\n header={'Recipients'}\n help={recipientsDocsHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {(emailId\n ? 'One row per address this email was sent to, newest first. '\n : 'One row per message sent from this template, newest first. ') +\n 'Opens are counted by a tracking pixel a mail client may block ' +\n 'or pre-fetch, so an absent open is weaker evidence than a click.'}\n </Typography>\n\n <ListFilterChips\n fields={RECIPIENT_FILTER_FIELDS}\n headers={RECIPIENT_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={RECIPIENT_FILTER_OPTIONS}\n // The route answers Engagement across the whole log.\n servedField=\"engagement\"\n />\n\n {failure ? <Alert severity=\"warning\">{failure}</Alert> : null}\n\n {campaignsOmitted ? (\n <Alert severity=\"info\">\n {'This template has been used by more emails than one read can ' +\n `span. These rows cover its ${campaignsRead} most recent ` +\n `emails; ${campaignsOmitted} older ` +\n `${campaignsOmitted === 1 ? 'email is' : 'emails are'} ` +\n 'not included.'}\n </Alert>\n ) : null}\n\n {rows.length === 0 && !loading && !failure && filter === 'all' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No delivery records have been kept for this yet.'}\n </Typography>\n ) : (\n <ListTable\n aria-label=\"Recipients\"\n rows={rows}\n columns={filterColumns}\n loading={loading}\n getRowId={(row: RecipientRow) => row.messageId}\n rowHeight={TABLE_ROW_HEIGHT}\n // A recipient carries the links they followed beneath the\n // address, so a row is as tall as its list of links.\n getRowHeight={() => 'auto'}\n // One page of a cursor feed, turned by the footer below: the grid\n // neither slices it nor filters the page and calls that the log.\n // Its panel's one filter is the route's (AGL-3317). Nor does it\n // sort: a header sort would order that one page, not the log.\n hideFooter\n disableColumnSorting\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n initialState={{ columns: { columnVisibilityModel: RECIPIENT_HIDDEN_COLUMNS } }}\n noRowsLabel=\"Nobody in the delivery log matches that yet\"\n />\n )}\n\n {/*\n * A cursor feed knows whether ANOTHER page exists and never how many\n * rows there are in total, so `hasMore` is passed and `count` is not\n * — the control renders \"1–25 of more than 25\" rather than inventing\n * a total nobody paid to count.\n */}\n <ListPagination\n page={page}\n pageSize={PAGE_SIZE}\n rowCount={rows.length}\n hasMore={hasMore}\n disabled={loading}\n onPageChange={setPage}\n />\n\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Up to ten distinct destinations are kept per recipient, so a ' +\n 'reader who clicked more links than that has the rest counted ' +\n 'but not listed.'}\n </Typography>\n </Stack>\n </CardDisplay>\n )\n}\nEmailRecipientsCard.displayName = 'EmailRecipientsCard'\n\nexport default EmailRecipientsCard\n"],"names":["pluginDocsHelp","CardDisplay","ListPagination","ListFilterChips","ListTable","listFilterGridColumns","useListGridFilter","TABLE_ROW_HEIGHT","useUser","authorizedFetch","Alert","Chip","Stack","Typography","useEffect","useMemo","useState","PAGE_SIZE","RECIPIENT_FILTER_FIELDS","column","kind","path","operators","RECIPIENT_FILTER_HEADERS","engagement","RECIPIENT_FILTER_OPTIONS","value","label","RECIPIENT_HIDDEN_COLUMNS","recipientsDocsHelp","anchor","excerpt","EmailRecipientsCard","props","cursors","gridFilter","hostId","screenId","emailId","data","user","selectFields","single","asked","clauses","find","clause","field","filter","page","setPage","setCursors","rows","setRows","hasMore","setHasMore","loading","setLoading","failure","setFailure","campaignsOmitted","setCampaignsOmitted","campaignsRead","setCampaignsRead","cursor","undefined","active","response","method","headers","body","JSON","stringify","payload","json","catch","ok","String","error","lookupFailed","nextRows","Array","isArray","Number","nextCursor","Boolean","existing","next","slice","console","askedFilter","setAskedFilter","columns","headerName","flex","minWidth","renderCell","row","spacing","sx","py","wordBreak","variant","to","clickedLinks","map","link","color","valueGetter","_value","subject","width","size","status","type","align","headerAlign","fontWeight","openCount","toLocaleString","clickCount","lastEventAtMs","Date","filterColumns","header","help","contentGutterX","contentGutterY","fields","onChange","setClauses","options","servedField","severity","length","aria-label","getRowId","messageId","rowHeight","getRowHeight","hideFooter","disableColumnSorting","filterMode","filterModel","onFilterModelChange","initialState","columnVisibilityModel","noRowsLabel","pageSize","rowCount","disabled","onPageChange","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,cAAc,QAAQ,eAAc;AAC7C,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,qBAAqB,8DAA6D;AACzF,SAASC,SAAS,QAAQ,uDAAsD;AAEhF,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,KAAK,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AAE9D,SAASC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAEpD,0EAA0E,GAC1E,MAAMC,YAAY;AAKlB;;;;;;CAMC,GACD,MAAMC,0BAAsD;IAC1D;QAAEC,QAAQ;QAAcC,MAAM;QAASC,MAAM;QAAcC,WAAW;YAAC;SAAS;IAAC;CAClF;AACD,MAAMC,2BAA6D;IACjEC,YAAY;AACd;AACA,MAAMC,2BAA2B;IAC/BD,YAAY;QACV;YAAEE,OAAO;YAAUC,OAAO;QAAY;QACtC;YAAED,OAAO;YAAWC,OAAO;QAAoB;KAChD;AACH;AACA,MAAMC,2BAA2B;IAAEJ,YAAY;AAAM;AAerD,MAAMK,qBAAqB7B,eAAe,kBAAkB;IAC1D8B,QAAQ;IACRC,SACE,yEACA;AACJ;AAiBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GACD,OAAO,SAASC,oBAAoBC,KAA+B;QAkBlDC;QAbDC;IAJd,MAAM,EAAEC,MAAM,EAAEC,QAAQ,EAAEC,OAAO,EAAE,GAAGL;IACtC,MAAM,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X,0DAA0D;oBAC1D,qDAAqD;oBACrDoI,cAAc,IAAM;oBACpB,kEAAkE;oBAClE,iEAAiE;oBACjE,gEAAgE;oBAChE,8DAA8D;oBAC9DC,UAAU;oBACVC,oBAAoB;oBACpBC,YAAW;oBACXC,aAAa5G,WAAW4G,WAAW;oBACnCC,qBAAqB7G,WAAW6G,mBAAmB;oBACnDC,cAAc;wBAAErD,SAAS;4BAAEsD,uBAAuBtH;wBAAyB;oBAAE;oBAC7EuH,aAAY;;8BAUhB,KAACjJ;oBACC+C,MAAMA;oBACNmG,UAAUnI;oBACVoI,UAAUjG,KAAKkF,MAAM;oBACrBhF,SAASA;oBACTgG,UAAU9F;oBACV+F,cAAcrG;;8BAGhB,KAACrC;oBAAWyF,SAAQ;oBAAUK,OAAM;8BACjC,kEACC,kEACA;;;;;AAKZ;AACA3E,oBAAoBwH,WAAW,GAAG;AAElC,eAAexH,oBAAmB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/email-recipients-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 { pluginDocsHelp } from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListTable } from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport type { ListFilterField } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { useListColumnSort } from '@aglyn/shared-ui-jsx/hooks/use-list-column-sort'\nimport ListQueryNotices from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { Alert, Chip, Stack, Typography } from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { useEffect, useMemo, useState } from 'react'\n\n/** The server's page size. Fixed, so the reader is not offered a choice. */\nconst PAGE_SIZE = 25\n\n/** Which recipients the table asks for. Matches the route's own vocabulary. */\ntype EngagementFilter = 'all' | 'opened' | 'clicked'\n\n/*\n * What the recipients grid's Filters panel offers (AGL-3317): the one filter\n * the route serves, as a hidden select column. The route answers it over the\n * whole delivery log, one cursor page at a time, and serves nothing else —\n * so no other column filters, and there is no quick search, which could only\n * ever narrow the page on screen.\n */\nconst RECIPIENT_FILTER_FIELDS: readonly ListFilterField[] = [\n { column: 'engagement', kind: 'exact', path: 'engagement', operators: ['equals'] },\n]\nconst RECIPIENT_FILTER_HEADERS: Readonly<Record<string, string>> = {\n engagement: 'Engagement',\n}\nconst RECIPIENT_FILTER_OPTIONS = {\n engagement: [\n { value: 'opened', label: 'Opened it' },\n { value: 'clicked', label: 'Clicked something' },\n ],\n}\nconst RECIPIENT_HIDDEN_COLUMNS = { engagement: false }\n\n/*\n * EVERY HEADER SORTS, OVER THE PAGE (AGL-3680). The rows are an aggregate\n * the recipients route builds from the per-recipient delivery log across\n * the template's emails, paged by its cursor newest first — no query here\n * can order them by a column — so each header sorts the page on screen and\n * says so.\n */\nconst RECIPIENT_PAGE_SORTS = {\n to: (row: RecipientRow) => row.to,\n subject: (row: RecipientRow) => row.subject,\n status: (row: RecipientRow) => row.status,\n openCount: (row: RecipientRow) => row.openCount,\n clickCount: (row: RecipientRow) => row.clickCount,\n lastEventAtMs: (row: RecipientRow) => row.lastEventAtMs || null,\n}\nconst RECIPIENT_PAGE_SORT_HEADERS = {\n to: 'Recipient',\n subject: 'Email',\n status: 'State',\n openCount: 'Opens',\n clickCount: 'Clicks',\n lastEventAtMs: 'Last event',\n}\nconst NO_QUERY_SORTS = [] as const\n\ninterface RecipientRow {\n messageId: string\n to: string\n subject: string | null\n campaignId: string | null\n status: string\n openCount: number\n clickCount: number\n clickedLinks: string[]\n firstSeenAtMs: number\n lastEventAtMs: number\n}\n\nconst recipientsDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#opens--clicks',\n excerpt:\n 'The people an email reached, and which of them opened it or clicked ' +\n 'a link — read from the per-recipient delivery log.',\n})\n\nexport interface EmailRecipientsCardProps {\n hostId: string\n /**\n * Read every message built from this template.\n *\n * Exactly one of `screenId` and `emailId` is passed. The route takes the\n * SCOPE rather than a list of message ids because a caller who could name\n * ids could name another site's, and the narrower input is the one that\n * cannot be got wrong later.\n */\n screenId?: string\n /** Read one message. */\n emailId?: string\n}\n\n/**\n * WHO, not how many.\n *\n * ## Why this is a fetch and not a listen\n *\n * Every other card on this page reads Firestore directly. This one cannot:\n * the per-recipient delivery log lives at `emailDeliveries/{sha256(address)}`\n * — one platform-level collection holding every site's mail and every\n * transactional message besides — and the query that narrows it to this\n * site's campaigns is a collection-group query whose scoping predicate is\n * part of the query. A security rule cannot require a `where` clause, so\n * there is no rule that would admit this read and refuse the same read\n * without the filter. The narrowing happens on the server, behind the same\n * site role the send path requires.\n *\n * ## Why it is its own card\n *\n * A separate card is a separate mount, and this is the only read on either\n * detail page whose cost grows with how much mail there has been. It asks\n * once on mount and once per page turn — never on a poll — so a reader who\n * came for the preview and the totals above pays for one page of this and\n * nothing more.\n *\n * ## The cursor, and why \"Previous\" keeps a stack\n *\n * The route pages forward with an opaque cursor, which is the only shape a\n * Firestore query offers without counting the whole result first. Going back\n * therefore means remembering where each page started, so the cursors are\n * kept in a list indexed by page — `null` for the first — rather than\n * re-walking forward from the beginning.\n */\nexport function EmailRecipientsCard(props: EmailRecipientsCardProps) {\n const { hostId, screenId, emailId } = props\n const { data: user } = useUser()\n\n const gridFilter = useListGridFilter({ selectFields: ['engagement'], single: true })\n const asked = gridFilter.clauses.find((clause) => clause.field === 'engagement')?.value\n const filter: EngagementFilter =\n asked === 'opened' || asked === 'clicked' ? asked : 'all'\n const [page, setPage] = useState(0)\n /** Cursor for each page. Index 0 is always `null` — the first page. */\n const [cursors, setCursors] = useState<(string | null)[]>([null])\n const [rows, setRows] = useState<RecipientRow[]>([])\n const [hasMore, setHasMore] = useState(false)\n const [loading, setLoading] = useState(true)\n const [failure, setFailure] = useState<string | null>(null)\n const [campaignsOmitted, setCampaignsOmitted] = useState(0)\n const [campaignsRead, setCampaignsRead] = useState(0)\n\n const cursor = cursors[page] ?? null\n\n useEffect(() => {\n if (!user) return undefined\n let active = true\n setLoading(true)\n setFailure(null)\n void (async () => {\n try {\n const response = await authorizedFetch(\n user,\n '/api/campaigns/recipients',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n ...(screenId ? { screenId } : {}),\n ...(emailId ? { emailId } : {}),\n filter,\n cursor,\n }),\n },\n )\n const payload = await response.json().catch(() => ({}))\n if (!active) return\n if (!response.ok) {\n setRows([])\n setHasMore(false)\n setFailure(String(payload?.error ?? 'Could not read recipients'))\n return\n }\n /*\n * A read that FAILED is not a campaign nobody opened.\n *\n * The route answers 200 with `lookupFailed` for a delivery-log read\n * that could not run — a missing collection-group index is the likely\n * one — because the rest of the payload is still true. Rendering that\n * as an empty table is how a merchant concludes their campaign\n * reached nobody, which is the one wrong answer this table can give.\n */\n if (payload?.lookupFailed) {\n setRows([])\n setHasMore(false)\n setFailure(\n 'The delivery log could not be read, so this table is empty for ' +\n 'a reason that has nothing to do with your campaign. The ' +\n 'numbers above come from the campaigns themselves and are ' +\n 'unaffected.',\n )\n return\n }\n const nextRows: RecipientRow[] = Array.isArray(payload?.rows)\n ? payload.rows\n : []\n setRows(nextRows)\n setCampaignsOmitted(Number(payload?.campaignsOmitted ?? 0))\n setCampaignsRead(Number(payload?.campaignsRead ?? 0))\n const nextCursor: string | null = payload?.cursor ?? null\n setHasMore(Boolean(nextCursor))\n if (nextCursor) {\n setCursors((existing) => {\n if (existing[page + 1] === nextCursor) return existing\n const next = existing.slice(0, page + 1)\n next[page + 1] = nextCursor\n return next\n })\n }\n } catch (error) {\n console.error(error)\n if (active) {\n setRows([])\n setHasMore(false)\n setFailure('Could not read recipients')\n }\n } finally {\n if (active) setLoading(false)\n }\n })()\n return () => {\n active = false\n }\n }, [user, hostId, screenId, emailId, filter, cursor, page])\n\n // A new filter is a new result set, so the cursors collected under the old\n // one describe positions in a query that no longer exists.\n const [askedFilter, setAskedFilter] = useState<EngagementFilter>(filter)\n if (askedFilter !== filter) {\n setAskedFilter(filter)\n setPage(0)\n setCursors([null])\n }\n\n const columns = useMemo<GridColDef<RecipientRow>[]>(\n () => [\n {\n field: 'to',\n headerName: 'Recipient',\n flex: 1,\n minWidth: 240,\n renderCell: ({ row }) => (\n <Stack spacing={0.5} sx={{ py: 1, minWidth: 0, wordBreak: 'break-all' }}>\n <Typography variant=\"body2\">{row.to}</Typography>\n {/*\n * WHICH links, under the person who followed them. The\n * per-campaign link rollup counts destinations and names nobody;\n * this is the other half of the same question, and it is the half\n * a merchant asks when they want to know who to call.\n */}\n {row.clickedLinks.map((link) => (\n <Typography key={link} variant=\"caption\" color=\"text.secondary\">\n {link}\n </Typography>\n ))}\n </Stack>\n ),\n },\n ...(emailId\n ? []\n : [\n {\n field: 'subject',\n headerName: 'Email',\n flex: 1,\n minWidth: 180,\n valueGetter: (_value: unknown, row: RecipientRow) => row.subject ?? '—',\n } satisfies GridColDef<RecipientRow>,\n ]),\n {\n field: 'status',\n headerName: 'State',\n width: 130,\n renderCell: ({ row }) => <Chip size=\"small\" label={row.status} />,\n },\n {\n field: 'openCount',\n headerName: 'Opens',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 100,\n renderCell: ({ row }) => (\n <Typography variant=\"body2\" sx={{ fontWeight: 'bold' }}>\n {row.openCount.toLocaleString()}\n </Typography>\n ),\n },\n {\n field: 'clickCount',\n headerName: 'Clicks',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 100,\n renderCell: ({ row }) => (\n <Typography variant=\"body2\" sx={{ fontWeight: 'bold' }}>\n {row.clickCount.toLocaleString()}\n </Typography>\n ),\n },\n {\n field: 'lastEventAtMs',\n headerName: 'Last event',\n width: 190,\n renderCell: ({ row }) =>\n row.lastEventAtMs ? new Date(row.lastEventAtMs).toLocaleString() : '—',\n },\n ],\n [emailId],\n )\n const columnSort = useListColumnSort<RecipientRow>({\n sorts: NO_QUERY_SORTS,\n rows,\n pageSorts: RECIPIENT_PAGE_SORTS,\n headers: RECIPIENT_PAGE_SORT_HEADERS,\n })\n const filterColumns = useMemo(\n () =>\n listFilterGridColumns(\n columns as GridColDef[],\n RECIPIENT_FILTER_FIELDS,\n RECIPIENT_FILTER_OPTIONS,\n RECIPIENT_FILTER_HEADERS,\n ),\n [columns],\n )\n\n return (\n <CardDisplay\n header={'Recipients'}\n help={recipientsDocsHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {(emailId\n ? 'One row per address this email was sent to, newest first. '\n : 'One row per message sent from this template, newest first. ') +\n 'Opens are counted by a tracking pixel a mail client may block ' +\n 'or pre-fetch, so an absent open is weaker evidence than a click.'}\n </Typography>\n\n <ListFilterChips\n fields={RECIPIENT_FILTER_FIELDS}\n headers={RECIPIENT_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={RECIPIENT_FILTER_OPTIONS}\n // The route answers Engagement across the whole log.\n servedField=\"engagement\"\n />\n\n {failure ? <Alert severity=\"warning\">{failure}</Alert> : null}\n\n <ListQueryNotices refused={[]} notices={columnSort.notices} />\n\n {campaignsOmitted ? (\n <Alert severity=\"info\">\n {'This template has been used by more emails than one read can ' +\n `span. These rows cover its ${campaignsRead} most recent ` +\n `emails; ${campaignsOmitted} older ` +\n `${campaignsOmitted === 1 ? 'email is' : 'emails are'} ` +\n 'not included.'}\n </Alert>\n ) : null}\n\n {rows.length === 0 && !loading && !failure && filter === 'all' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No delivery records have been kept for this yet.'}\n </Typography>\n ) : (\n <ListTable\n aria-label=\"Recipients\"\n rows={columnSort.rows}\n columns={filterColumns}\n loading={loading}\n getRowId={(row: RecipientRow) => row.messageId}\n rowHeight={TABLE_ROW_HEIGHT}\n // A recipient carries the links they followed beneath the\n // address, so a row is as tall as its list of links.\n getRowHeight={() => 'auto'}\n // One page of a cursor feed, turned by the footer below: the grid\n // neither slices it nor filters the page and calls that the log.\n // Its panel's one filter is the route's (AGL-3317). Nor does it\n // sort: a header sort would order that one page, not the log.\n hideFooter\n columnSort={columnSort}\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n initialState={{ columns: { columnVisibilityModel: RECIPIENT_HIDDEN_COLUMNS } }}\n noRowsLabel=\"Nobody in the delivery log matches that yet\"\n />\n )}\n\n {/*\n * A cursor feed knows whether ANOTHER page exists and never how many\n * rows there are in total, so `hasMore` is passed and `count` is not\n * — the control renders \"1–25 of more than 25\" rather than inventing\n * a total nobody paid to count.\n */}\n <ListPagination\n page={page}\n pageSize={PAGE_SIZE}\n rowCount={rows.length}\n hasMore={hasMore}\n disabled={loading}\n onPageChange={setPage}\n />\n\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Up to ten distinct destinations are kept per recipient, so a ' +\n 'reader who clicked more links than that has the rest counted ' +\n 'but not listed.'}\n </Typography>\n </Stack>\n </CardDisplay>\n )\n}\nEmailRecipientsCard.displayName = 'EmailRecipientsCard'\n\nexport default EmailRecipientsCard\n"],"names":["pluginDocsHelp","CardDisplay","ListPagination","ListFilterChips","ListTable","listFilterGridColumns","useListGridFilter","useListColumnSort","ListQueryNotices","TABLE_ROW_HEIGHT","useUser","authorizedFetch","Alert","Chip","Stack","Typography","useEffect","useMemo","useState","PAGE_SIZE","RECIPIENT_FILTER_FIELDS","column","kind","path","operators","RECIPIENT_FILTER_HEADERS","engagement","RECIPIENT_FILTER_OPTIONS","value","label","RECIPIENT_HIDDEN_COLUMNS","RECIPIENT_PAGE_SORTS","to","row","subject","status","openCount","clickCount","lastEventAtMs","RECIPIENT_PAGE_SORT_HEADERS","NO_QUERY_SORTS","recipientsDocsHelp","anchor","excerpt","EmailRecipientsCard","props","cursors","gridFilter","hostId","screenId","emailId","data","user","selectFields","single","asked","clauses","find","clause","field","filter","page","setPage","setCursors","rows","setRows","hasMore","setHasMore","loading","setLoading","failure","setFailure","campaignsOmitted","setCampaignsOmitted","campaignsRead","setCampaignsRead","cursor","undefined","active","response","method","headers","body","JSON","stringify","payload","json","catch","ok","String","error","lookupFailed","nextRows","Array","isArray","Number","nextCursor","Boolean","existing","next","slice","console","askedFilter","setAskedFilter","columns","headerName","flex","minWidth","renderCell","spacing","sx","py","wordBreak","variant","clickedLinks","map","link","color","valueGetter","_value","width","size","type","align","headerAlign","fontWeight","toLocaleString","Date","columnSort","sorts","pageSorts","filterColumns","header","help","contentGutterX","contentGutterY","fields","onChange","setClauses","options","servedField","severity","refused","notices","length","aria-label","getRowId","messageId","rowHeight","getRowHeight","hideFooter","filterMode","filterModel","onFilterModelChange","initialState","columnVisibilityModel","noRowsLabel","pageSize","rowCount","disabled","onPageChange","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,cAAc,QAAQ,eAAc;AAC7C,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,qBAAqB,8DAA6D;AACzF,SAASC,SAAS,QAAQ,uDAAsD;AAEhF,SAAS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