@aglyn/plugins-marketing 1.0.0-beta.199 → 1.0.0-beta.201
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +15 -15
- package/src/lib/components/campaign-composer.js +14 -6
- package/src/lib/components/campaign-composer.js.map +1 -1
- package/src/lib/components/campaign-conversions-card.js +6 -0
- package/src/lib/components/campaign-conversions-card.js.map +1 -1
- package/src/lib/components/campaign-detail-card.js +107 -37
- package/src/lib/components/campaign-detail-card.js.map +1 -1
- package/src/lib/components/campaign-members-section.d.ts +16 -4
- package/src/lib/components/campaign-members-section.js +171 -105
- package/src/lib/components/campaign-members-section.js.map +1 -1
- package/src/lib/components/campaign-queries.d.ts +11 -0
- package/src/lib/components/campaign-queries.js +13 -0
- package/src/lib/components/campaign-queries.js.map +1 -1
- package/src/lib/components/campaigns-card.d.ts +8 -6
- package/src/lib/components/campaigns-card.js +296 -128
- package/src/lib/components/campaigns-card.js.map +1 -1
- package/src/lib/components/email-compose-card.js +4 -3
- package/src/lib/components/email-compose-card.js.map +1 -1
- package/src/lib/components/email-detail.js +16 -5
- package/src/lib/components/email-detail.js.map +1 -1
- package/src/lib/components/email-recipients-card.js +3 -1
- package/src/lib/components/email-recipients-card.js.map +1 -1
- package/src/lib/components/emails-list-card.d.ts +11 -15
- package/src/lib/components/emails-list-card.js +142 -143
- package/src/lib/components/emails-list-card.js.map +1 -1
- package/src/lib/components/host-experiments-card.component.js +110 -78
- package/src/lib/components/host-experiments-card.component.js.map +1 -1
- package/src/lib/components/org-experiments-card.js +7 -3
- package/src/lib/components/org-experiments-card.js.map +1 -1
- package/src/lib/model/campaign-list-query.d.ts +99 -0
- package/src/lib/model/campaign-list-query.js +373 -0
- package/src/lib/model/campaign-list-query.js.map +1 -0
- package/src/lib/model/campaign-members-query.d.ts +37 -0
- package/src/lib/model/campaign-members-query.js +120 -0
- package/src/lib/model/campaign-members-query.js.map +1 -0
- package/src/lib/model/experiment-list-query.d.ts +22 -0
- package/src/lib/model/experiment-list-query.js +85 -0
- package/src/lib/model/experiment-list-query.js.map +1 -0
- package/src/lib/server/campaign-form-flags.d.ts +35 -0
- package/src/lib/server/campaign-form-flags.js +52 -0
- package/src/lib/server/campaign-form-flags.js.map +1 -0
- package/src/lib/server/campaign-manage.d.ts +1 -1
- package/src/lib/server/campaign-manage.js +42 -20
- package/src/lib/server/campaign-manage.js.map +1 -1
- package/src/lib/server/campaign-send.d.ts +42 -1
- package/src/lib/server/campaign-send.js +247 -16
- package/src/lib/server/campaign-send.js.map +1 -1
- package/src/lib/server/email-events.js +13 -1
- package/src/lib/server/email-events.js.map +1 -1
- package/src/lib/components/email-send-filter.d.ts +0 -32
- package/src/lib/components/email-send-filter.js +0 -55
- package/src/lib/components/email-send-filter.js.map +0 -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 { 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 {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { inMemoryListField } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListRowsFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-rows-filter'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport { collection, limit, query, setDoc } 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 '@aglyn/shared-ui-email-campaigns/model'\nimport { CreateArtifactDrawer } from '@aglyn/shared-ui-jsx-forms'\nimport {\n campaignContainerDoc,\n campaignContainersQuery,\n campaignSendsQuery,\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 { useCampaignTopicOptions } from './use-campaign-topic-options'\n\n/**\n * How many sends the list reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server until a send carries one date field every\n * writer stamps.\n */\nconst CAMPAIGN_CEILING = 30\n\n/** How many campaign containers the list reads. */\nconst CONTAINER_CEILING = 50\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 (AGL-3317). The card reads\n * every campaign under its ceiling, so the panel and the search answer over\n * all of them. A campaign's lists are ids, matched member by member.\n */\nconst CAMPAIGN_FILTER_FIELDS = [\n inMemoryListField('name', 'text'),\n inMemoryListField('windowState', 'select'),\n { ...inMemoryListField('listIds', 'select'), tokensPath: 'listIds', verbatimTokens: true },\n inMemoryListField('kind', 'select'),\n inMemoryListField('sitesLabel', 'text'),\n]\nconst CAMPAIGN_FILTER_HEADERS: Readonly<Record<string, string>> = {\n name: 'Campaign',\n windowState: 'Window',\n listIds: 'Lists',\n kind: 'Kind',\n sitesLabel: 'Sites',\n}\nconst CAMPAIGN_KIND_OPTIONS = [\n { value: 'campaign', label: 'Campaign' },\n { value: 'single', label: 'Single send' },\n]\nconst CAMPAIGN_WINDOW_OPTIONS = (\n Object.keys(WINDOW_LABEL) as Array<CampaignListRow['windowState']>\n).map((state) => ({ value: state, label: WINDOW_LABEL[state] }))\n/** What the quick search reads on a campaign row. */\nconst CAMPAIGN_SEARCH_FIELDS = ['name', 'sitesLabel'] as const\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, and the second is why this reads\n * without a migration. `emailCampaigns` holds the containers.\n * `campaigns` holds every send, including thousands written before containers\n * existed; those carry no container id, and `campaignListRows` presents each\n * as a campaign of one rather than dropping it. Nothing is rewritten, so no\n * unsubscribe link and no pasted report URL stops 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 * ORDERED AND CEILINGED, and not orderable on any DATE.\n *\n * No field here is on every send: a sent one is written `{status:'sent',\n * sentAt}` and a scheduled one `{status:'scheduled', sendAtMs}`, by the two\n * branches of `campaign-send.ts`, and there is no `createdAt` at all.\n * `orderBy` on either would not mis-sort the list, it would DROP half of it.\n *\n * A bare `limit(30)` is answered in DOCUMENT-ID order, so the window is\n * thirty sends chosen by id and then sorted by date, which reads as the most\n * recent thirty and is not. `collectionCeiling` returns that same thirty —\n * document-id order is what the bare cap already gave — but it says so,\n * which is what stops the next edit reaching for `sentAt`, and it probes one\n * past the ceiling so the reader is told the history is longer.\n */\n const { data: sendDocs } = useFirestoreCollection<any>(\n () => {\n const sends = campaignSendsQuery(firestore, orgId, hostId)\n return sends ? collectionCeiling(sends, CAMPAIGN_CEILING) : null\n },\n [firestore, orgId, hostId],\n { idField: '$id' },\n )\n const { rows: readSends, truncated: sendsTruncated } = ceilingedWindow<any>(\n sendDocs,\n CAMPAIGN_CEILING,\n )\n\n const { data: campaignDocs } = useFirestoreCollection<any>(\n () => {\n const containers = campaignContainersQuery(firestore, orgId, hostId)\n return containers ? collectionCeiling(containers, CONTAINER_CEILING) : null\n },\n [firestore, orgId, hostId],\n { idField: '$id' },\n )\n const { rows: readCampaigns, truncated: campaignsTruncated } =\n ceilingedWindow<any>(campaignDocs, CONTAINER_CEILING)\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 const rows = useMemo(() => {\n const campaigns = (readCampaigns as EmailCampaign[]).filter(\n (campaign: any) => !campaign.deletedAt,\n )\n const byId = new Map(campaigns.map((campaign) => [campaign.$id, campaign]))\n return campaignListRows(\n campaigns,\n readSends as CampaignSend[],\n Date.now(),\n ).map((row) => ({\n ...row,\n $id: row.id,\n kind: row.legacy ? 'single' : 'campaign',\n sitesLabel: orgMount\n ? campaignSitesLabel(orgMount, row, byId.get(row.id))\n : '',\n }))\n }, [readCampaigns, readSends, orgMount])\n\n const filterOptions = useMemo(\n () => ({\n windowState: CAMPAIGN_WINDOW_OPTIONS,\n listIds: listOptions,\n kind: CAMPAIGN_KIND_OPTIONS,\n }),\n [listOptions],\n )\n // Sites is a column on the org hub only; under a site it would say one thing.\n const filterFields = useMemo(\n () =>\n orgMount\n ? CAMPAIGN_FILTER_FIELDS\n : CAMPAIGN_FILTER_FIELDS.filter((field) => field.column !== 'sitesLabel'),\n [orgMount],\n )\n const listFilter = useListRowsFilter({\n rows,\n fields: filterFields,\n options: filterOptions,\n headers: CAMPAIGN_FILTER_HEADERS,\n search: CAMPAIGN_SEARCH_FIELDS,\n })\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 try {\n await setDoc(campaignContainerDoc(firestore, orgId, id), {\n 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 /*\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\n * site would be a decision nobody made. From the org hub, the sites\n * picked, and every site when none are.\n */\n visibleTo: campaignVisibleTo(\n hostId\n ? [hostId]\n : Array.isArray(values.siteIds)\n ? values.siteIds.map(String)\n : null,\n ),\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 screens, 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: 'Campaign',\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],\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 <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 ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <ListFilterChips {...listFilter.chipsProps} />\n <ListTable\n rows={listFilter.rows}\n columns={listFilter.filterColumns(columns as any)}\n onOpen={(id) => openCampaign(id)}\n // The panel and the search are the grid's; the card answers them\n // over every campaign it read (AGL-3317).\n {...listFilter.gridProps}\n initialState={{ columns: { columnVisibilityModel: { kind: false } } }}\n noRowsLabel={rows.length ? 'No campaigns match these filters' : 'No campaigns yet'}\n noRowsDescription={\n rows.length ? undefined : 'A campaign groups the emails you send to a set of lists.'\n }\n noRowsAction={\n rows.length ? undefined : (\n <Button variant=\"contained\" onClick={() => setCreateOpen(true)}>\n {'Create campaign'}\n </Button>\n )\n }\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 {sendsTruncated || campaignsTruncated ? (\n <Alert severity=\"info\">\n {`Showing the most recent ${CONTAINER_CEILING} campaigns and ` +\n `${CAMPAIGN_CEILING} sends. ${\n hostId ? 'This site' : 'This organization'\n } has more — the ones ` +\n 'listed are not necessarily the most recent, because a send ' +\n 'carries no date field that every writer stamps.'}\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","mdiDeleteOutline","mdiEyeOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListFilterChips","ListRowActions","ListTable","listActionsColumn","inMemoryListField","useListRowsFilter","useSnackbar","Alert","Button","Chip","Stack","Typography","collection","limit","query","setDoc","useCallback","useMemo","useState","useRouter","useConsoleHostRoute","useFirestore","useFirestoreCollection","useUser","campaignListRows","campaignSiteIds","campaignVisibleTo","CreateArtifactDrawer","campaignContainerDoc","campaignContainersQuery","campaignSendsQuery","orgSiteName","orgSiteOptions","topicCatalogHostId","useMarketingOrgId","useMarketingOrgMount","useCampaignManageApi","useCampaignTopicOptions","CAMPAIGN_CEILING","CONTAINER_CEILING","formatDay","ms","Date","toLocaleDateString","figure","value","toLocaleString","WINDOW_LABEL","undated","upcoming","running","ended","CAMPAIGN_FILTER_FIELDS","tokensPath","verbatimTokens","CAMPAIGN_FILTER_HEADERS","name","windowState","listIds","kind","sitesLabel","CAMPAIGN_KIND_OPTIONS","label","CAMPAIGN_WINDOW_OPTIONS","Object","keys","map","state","CAMPAIGN_SEARCH_FIELDS","HostCampaignsCard","props","hostId","basePath","firestore","router","orgSlug","subdomain","hubPath","HOST_PLUGIN","host","pluginSlug","data","user","enqueueSnackbar","confirm","orgMount","orgId","manageApi","sendDocs","sends","idField","rows","readSends","truncated","sendsTruncated","campaignDocs","containers","readCampaigns","campaignsTruncated","listDocs","createOpen","setCreateOpen","topics","source","topicSource","enabled","topicOptions","topic","id","listNames","names","Map","list","set","String","$id","listOptions","campaigns","filter","campaign","deletedAt","byId","now","row","legacy","campaignSitesLabel","get","filterOptions","filterFields","field","column","listFilter","fields","options","headers","search","createError","setCreateError","creating","setCreating","deletingId","setDeletingId","openCampaign","push","handleCreate","values","displayName","trim","startAtMs","startAt","parse","endAtMs","endAt","Number","isFinite","Array","isArray","topicId","visibleTo","siteIds","createdAtMs","createdBy","uid","error","console","variant","allowDuplicate","campaignHref","handleDelete","emails","length","unfinished","rollup","scheduled","sending","agreed","title","description","confirmationText","then","catch","response","payload","action","campaignId","ok","persist","columns","headerName","flex","minWidth","renderCell","direction","spacing","sx","alignItems","width","href","onClick","event","stopPropagation","style","noWrap","size","flexShrink","sortable","start","end","range","color","join","align","headerAlign","note","Boolean","sent","opens","clicks","items","key","icon","path","undefined","disabled","disabledReason","destructive","header","help","anchor","excerpt","HeaderProps","contentGutterX","contentGutterY","chipsProps","filterColumns","onOpen","gridProps","initialState","columnVisibilityModel","noRowsLabel","noRowsDescription","noRowsAction","severity","open","onClose","submitLabel","includeDescription","onSubmit","extraFields","campaignFields","errorSlot","mt","mb","lists","sites","component","multiple","initialValue","helperText","disableDefaultOption","type","InputLabelProps","shrink","mount","container","ids"],"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,gBAAgB,EAAEC,aAAa,QAAQ,yBAAwB;AACxE,SACEC,OAAO,EACPC,WA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ources":["../../../../../../../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 '@aglyn/shared-ui-email-campaigns/model'\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 { 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 screens, 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 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 <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 ),\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 <Button variant=\"contained\" onClick={() => setCreateOpen(true)}>\n {'Create campaign'}\n </Button>\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","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","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,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,oBACLC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,sBAAsB,QAAQ,yCAAwC;AAC/E,SAEEC,qBAAqB,QAChB,8CAA6C;AACpD,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,KAAK,EACLC,YAAY,EACZC,iBAAiB,EACjBC,UAAU,QACL,gBAAe;AACtB,SAASC,UAAU,EAAEC,KAAK,EAAEC,KAAK,EAAEC,MAAM,EAAEC,KAAK,QAAQ,qBAAoB;AAC5E,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,Q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,EAAE;YAChB,wEAAwE;YACxE,oEAAoE;YACpEC,YAAY;YACZC,sBAAsB;YACtBzC,SAASoC;QACX;QACA;YACEC,WAAW;YACX3P,MAAM;YACNsF,OAAO;YACPwK,YAAY;YACZC,sBAAsB;YACtBzC,SAASvI;QACX;KACD;AACH;AAEA;;;;;;CAMC,GACD,SAAS0B,mBACP0J,KAAwB,EACxBvM,GAAoB,EACpBwM,SAAoC;QAEMxM;IAA1C,IAAIA,IAAIkH,MAAM,EAAE,OAAOrM,YAAY0R,QAAOvM,cAAAA,IAAIK,KAAK,CAAC,EAAE,qBAAZL,YAAcpD,MAAM,KAAK;IACnE,MAAMwD,MAAMrG,gBAAgByS;IAC5B,IAAIpM,QAAQ,MAAM,OAAO;IACzB,IAAI,CAACA,IAAIX,MAAM,EAAE,OAAO;IACxB,OAAOW,IAAIL,GAAG,CAAC,CAAC0B,KAAO5G,YAAY0R,OAAO9K,KAAKf,IAAI,CAAC;AACtD;AAEAhE,kBAAkBiH,WAAW,GAAG;AAEhC,eAAejH,kBAAiB"}
|
|
@@ -63,7 +63,7 @@ import { AppLink, CardDisplay } from "@aglyn/shared-ui-jsx";
|
|
|
63
63
|
import { Button, Typography } from "@mui/material";
|
|
64
64
|
import { useFirestore, useFirestoreDoc } from "@aglyn/tenant-feature-instance";
|
|
65
65
|
import { useRouter } from "next/navigation";
|
|
66
|
-
import { campaignSendDisplay, CAMPAIGN_SEND_CONTAINER_FIELD } from "@aglyn/shared-ui-email-campaigns/model/campaign-container";
|
|
66
|
+
import { campaignHeldForReviewNotice, campaignSendDisplay, CAMPAIGN_SEND_CONTAINER_FIELD } from "@aglyn/shared-ui-email-campaigns/model/campaign-container";
|
|
67
67
|
import CampaignComposer from "./campaign-composer.js";
|
|
68
68
|
import { campaignSendDoc } from "./campaign-queries.js";
|
|
69
69
|
import { useMarketingOrgId } from "./marketing-org-mount.js";
|
|
@@ -99,14 +99,15 @@ export function EmailComposeCard(props) {
|
|
|
99
99
|
const displayName = String((_ref1 = email == null ? void 0 : email.displayName) != null ? _ref1 : '');
|
|
100
100
|
const state = String((_ref2 = email == null ? void 0 : email.status) != null ? _ref2 : '');
|
|
101
101
|
const display = email ? campaignSendDisplay(email) : null;
|
|
102
|
-
const editable = (state === 'draft' || state === 'scheduled') && (display == null ? void 0 : display.state) !== 'sending'
|
|
102
|
+
const editable = (state === 'draft' || state === 'scheduled') && (display == null ? void 0 : display.state) !== 'sending' && // A held send is written by nobody until staff decide (AGL-3356).
|
|
103
|
+
(display == null ? void 0 : display.state) !== 'held';
|
|
103
104
|
/**
|
|
104
105
|
* Why this email cannot be written, in the words that say what to do next.
|
|
105
106
|
*
|
|
106
107
|
* Empty while it still can be. Each case is a different fact about the
|
|
107
108
|
* record and not a variation on "no": one has not loaded, one is in inboxes
|
|
108
109
|
* already, one is being delivered right now.
|
|
109
|
-
*/ const refusal = !email ? status === 'loading' ? 'Loading this email…' : 'This email could not be loaded. It may have been deleted.' : !hostId ? 'This email does not record which site it is sent as, so it can ' + 'only be written from that site’s own Emails page.' : editable ? '' : (display == null ? void 0 : display.state) === 'sending' ? 'This email is being sent right now, so its message can no longer ' + 'be changed. Its page reports what it has reached so far.' : state === 'sent' ? 'This email has been sent, so its subject, message and audience ' + 'describe mail that is already in inboxes. Compose a new email ' + 'to say something else.' : 'This email was canceled, so it can no longer be written or put ' + 'back on the schedule. Compose a new email.';
|
|
110
|
+
*/ const refusal = !email ? status === 'loading' ? 'Loading this email…' : 'This email could not be loaded. It may have been deleted.' : !hostId ? 'This email does not record which site it is sent as, so it can ' + 'only be written from that site’s own Emails page.' : editable ? '' : (display == null ? void 0 : display.state) === 'held' ? campaignHeldForReviewNotice(email) : (display == null ? void 0 : display.state) === 'sending' ? 'This email is being sent right now, so its message can no longer ' + 'be changed. Its page reports what it has reached so far.' : state === 'sent' ? 'This email has been sent, so its subject, message and audience ' + 'describe mail that is already in inboxes. Compose a new email ' + 'to say something else.' : 'This email was canceled, so it can no longer be written or put ' + 'back on the schedule. Compose a new email.';
|
|
110
111
|
return /*#__PURE__*/ _jsx(CardDisplay, {
|
|
111
112
|
header: subject || displayName || 'Untitled email',
|
|
112
113
|
subheader: 'Write this email',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/email-compose-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\n/**\n * WRITING ONE EMAIL — its own route, and its own card.\n *\n * ## Why it is not on the message's page\n *\n * `/emails/messages/{emailId}` answers \"what did this email do\": delivery,\n * engagement, every rate over its own denominator, the links that were\n * followed and who it reached. Writing the thing is a different job with a\n * different shape — a form, a preview, and one irreversible button — and\n * carrying both on one route made the reader of a report scroll past a\n * composer and the writer of an email scroll past a table of zeros.\n *\n * So the record's page reports, and `…/edit` writes. It is the grammar this\n * surface already reads by: an audience is `…/audiences/{listId}` and its\n * settings are `…/audiences/{listId}/edit`, and a screen's page and its\n * besigner are two addresses for the same reason. Creating is still a drawer\n * on the list — it collects the name, mints the record and routes here — so no\n * list on this surface carries a form above it.\n *\n * ## Why the card is HERE and not inside the composer\n *\n * The composer is also mounted inside the campaign detail card, which already\n * supplies a card of its own; a `CardDisplay` in the component would nest one\n * inside another there. The surface owns the chrome, exactly as `ListEditCard`\n * owns the chrome around the audience rule fields.\n *\n * ## What may be edited\n *\n * Only an email that is still unsent. The route enforces it too — `schedule`\n * and `draft` answer 409 on a sent or canceled record — and this is the same\n * refusal said before the merchant types rather than after they press Send. An\n * email PART WAY THROUGH a send is stored as `scheduled` between batches, so\n * the stored status alone would let somebody rewrite the copy of a message\n * that is already reaching inboxes; `campaignSendDisplay` is what tells the\n * two apart.\n *\n * ## The site it is written as\n *\n * The record is the org's; the composer is a site's — its senders, its\n * designs, its experiments. Under a site that is the site. On the org hub it\n * is the send's own `hostId`, and a send that names none is not opened for\n * writing there.\n */\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { Button, Typography } from '@mui/material'\nimport { useFirestore, useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useRouter } from 'next/navigation'\nimport {\n campaignSendDisplay,\n CAMPAIGN_SEND_CONTAINER_FIELD,\n} from '@aglyn/shared-ui-email-campaigns/model/campaign-container'\nimport CampaignComposer from './campaign-composer'\nimport { campaignSendDoc } from './campaign-queries'\nimport { useMarketingOrgId } from './marketing-org-mount'\n\nconst composeDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#send-a-campaign',\n excerpt:\n 'Everything one email decides: who it goes to, how it is written, who ' +\n 'it appears to come from, and how many people it reaches.',\n})\n\nexport interface EmailComposeCardProps {\n /** The site, or `null` on the organization's Emails page. */\n hostId: string | null\n /** The message document under `orgs/{orgId}/campaigns`. */\n emailId: string\n /**\n * The Emails page's own URL, under the site or the organization, for the\n * way back to the message's own page.\n */\n basePath: string\n}\n\nexport function EmailComposeCard(props: EmailComposeCardProps) {\n const { emailId, basePath } = props\n const firestore = useFirestore()\n const router = useRouter()\n const { orgId } = useMarketingOrgId(props.hostId)\n\n const { data: email, status } = useFirestoreDoc<Record<string, any>>(\n () => (orgId ? campaignSendDoc(firestore, orgId, emailId) : null),\n [firestore, orgId, emailId],\n )\n /** The site this email is written as; see the file header. */\n const hostId: string | null =\n props.hostId ?? (email?.hostId ? String(email.hostId) : null)\n\n const detailHref = `${basePath}/messages/${emailId}`\n const headerActions = (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={detailHref}\n size=\"small\"\n color=\"primary\"\n >\n {'Back to the email'}\n </Button>\n )\n\n const subject = String(email?.subject ?? '')\n const displayName = String(email?.displayName ?? '')\n const state = String(email?.status ?? '')\n const display = email ? campaignSendDisplay(email as never) : null\n const editable =\n (state === 'draft' || state === 'scheduled') && display?.state !== 'sending'\n\n /**\n * Why this email cannot be written, in the words that say what to do next.\n *\n * Empty while it still can be. Each case is a different fact about the\n * record and not a variation on \"no\": one has not loaded, one is in inboxes\n * already, one is being delivered right now.\n */\n const refusal = !email\n ? status === 'loading'\n ? 'Loading this email…'\n : 'This email could not be loaded. It may have been deleted.'\n : !hostId\n ? 'This email does not record which site it is sent as, so it can ' +\n 'only be written from that site’s own Emails page.'\n : editable\n ? ''\n : display?.state === 'sending'\n ? 'This email is being sent right now, so its message can no longer ' +\n 'be changed. Its page reports what it has reached so far.'\n : state === 'sent'\n ? 'This email has been sent, so its subject, message and audience ' +\n 'describe mail that is already in inboxes. Compose a new email ' +\n 'to say something else.'\n : 'This email was canceled, so it can no longer be written or put ' +\n 'back on the schedule. Compose a new email.'\n\n return (\n <CardDisplay\n header={subject || displayName || 'Untitled email'}\n subheader={'Write this email'}\n help={composeDocsHelp}\n contentGutterX\n contentGutterY\n HeaderProps={{ action: headerActions }}\n >\n {refusal ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {refusal}\n </Typography>\n ) : (\n <CampaignComposer\n hostId={hostId}\n campaignId={emailId}\n emailCampaignId={\n email?.[CAMPAIGN_SEND_CONTAINER_FIELD]\n ? String(email[CAMPAIGN_SEND_CONTAINER_FIELD])\n : undefined\n }\n displayName={displayName || undefined}\n initial={{\n subject,\n body: String(email?.body ?? ''),\n fromName: String(email?.fromName ?? ''),\n replyTo: String(email?.replyTo ?? ''),\n /*\n * The sender this email is set to go out as, so reopening a draft\n * does not silently move it onto whichever sender has become the\n * site's default since it was saved.\n */\n senderId: String(email?.senderId ?? ''),\n preheader: String(email?.preheader ?? ''),\n audience: String(email?.audience ?? ''),\n listId: String(email?.listId ?? ''),\n segmentId: String(email?.segmentId ?? ''),\n topicId: String(email?.topicId ?? ''),\n /*\n * Which of the two ways this email is written. The composer\n * resolves the mode from this field through the same function the\n * send path reads, so a designed draft reopens designed.\n */\n templateScreenId: String(email?.templateScreenId ?? ''),\n /*\n * The plain-text half, and the design version it was written\n * against. Absent means the design generates it — the composer\n * reads that through the same resolver the record's shape is\n * defined by, so a stale override is named rather than guessed at.\n */\n plainText: String(email?.plainText ?? ''),\n plainTextVersionId: String(email?.plainTextVersionId ?? ''),\n }}\n /*\n * A send or a schedule lands on the record, and the record's page is\n * where its report will be — so the merchant is left looking at what\n * they just did rather than at the form that did it.\n */\n onSent={() => router.push(detailHref)}\n />\n )}\n </CardDisplay>\n )\n}\nEmailComposeCard.displayName = 'EmailComposeCard'\n\nexport default EmailComposeCard\n"],"names":["pluginDocsHelp","AppLink","CardDisplay","Button","Typography","useFirestore","useFirestoreDoc","useRouter","campaignSendDisplay","CAMPAIGN_SEND_CONTAINER_FIELD","CampaignComposer","campaignSendDoc","useMarketingOrgId","composeDocsHelp","anchor","excerpt","EmailComposeCard","props","emailId","basePath","firestore","router","orgId","hostId","data","email","status","String","detailHref","headerActions","component","componentVariant","nativeButton","href","size","color","subject","displayName","state","display","editable","refusal","header","subheader","help","contentGutterX","contentGutterY","HeaderProps","action","variant","campaignId","emailCampaignId","undefined","initial","body","fromName","replyTo","senderId","preheader","audience","listId","segmentId","topicId","templateScreenId","plainText","plainTextVersionId","onSent","push"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CC,GAED,SAASA,cAAc,QAAQ,eAAc;AAC7C,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,SAASC,MAAM,EAAEC,UAAU,QAAQ,gBAAe;AAClD,SAASC,YAAY,EAAEC,eAAe,QAAQ,iCAAgC;AAC9E,SAASC,SAAS,QAAQ,kBAAiB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C,oBAAoBtC,iBAAOF,yBAAAA,MAAOwC,kBAAkB,qBAAI;YAC1D;YACA;;;;WAIC,GACDC,QAAQ,IAAM7C,OAAO8C,IAAI,CAACvC;;;AAKpC;AACAZ,iBAAiBqB,WAAW,GAAG;AAE/B,eAAerB,iBAAgB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/email-compose-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\n/**\n * WRITING ONE EMAIL — its own route, and its own card.\n *\n * ## Why it is not on the message's page\n *\n * `/emails/messages/{emailId}` answers \"what did this email do\": delivery,\n * engagement, every rate over its own denominator, the links that were\n * followed and who it reached. Writing the thing is a different job with a\n * different shape — a form, a preview, and one irreversible button — and\n * carrying both on one route made the reader of a report scroll past a\n * composer and the writer of an email scroll past a table of zeros.\n *\n * So the record's page reports, and `…/edit` writes. It is the grammar this\n * surface already reads by: an audience is `…/audiences/{listId}` and its\n * settings are `…/audiences/{listId}/edit`, and a screen's page and its\n * besigner are two addresses for the same reason. Creating is still a drawer\n * on the list — it collects the name, mints the record and routes here — so no\n * list on this surface carries a form above it.\n *\n * ## Why the card is HERE and not inside the composer\n *\n * The composer is also mounted inside the campaign detail card, which already\n * supplies a card of its own; a `CardDisplay` in the component would nest one\n * inside another there. The surface owns the chrome, exactly as `ListEditCard`\n * owns the chrome around the audience rule fields.\n *\n * ## What may be edited\n *\n * Only an email that is still unsent. The route enforces it too — `schedule`\n * and `draft` answer 409 on a sent or canceled record — and this is the same\n * refusal said before the merchant types rather than after they press Send. An\n * email PART WAY THROUGH a send is stored as `scheduled` between batches, so\n * the stored status alone would let somebody rewrite the copy of a message\n * that is already reaching inboxes; `campaignSendDisplay` is what tells the\n * two apart.\n *\n * ## The site it is written as\n *\n * The record is the org's; the composer is a site's — its senders, its\n * designs, its experiments. Under a site that is the site. On the org hub it\n * is the send's own `hostId`, and a send that names none is not opened for\n * writing there.\n */\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { Button, Typography } from '@mui/material'\nimport { useFirestore, useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useRouter } from 'next/navigation'\nimport {\n campaignHeldForReviewNotice,\n campaignSendDisplay,\n CAMPAIGN_SEND_CONTAINER_FIELD,\n} from '@aglyn/shared-ui-email-campaigns/model/campaign-container'\nimport CampaignComposer from './campaign-composer'\nimport { campaignSendDoc } from './campaign-queries'\nimport { useMarketingOrgId } from './marketing-org-mount'\n\nconst composeDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#send-a-campaign',\n excerpt:\n 'Everything one email decides: who it goes to, how it is written, who ' +\n 'it appears to come from, and how many people it reaches.',\n})\n\nexport interface EmailComposeCardProps {\n /** The site, or `null` on the organization's Emails page. */\n hostId: string | null\n /** The message document under `orgs/{orgId}/campaigns`. */\n emailId: string\n /**\n * The Emails page's own URL, under the site or the organization, for the\n * way back to the message's own page.\n */\n basePath: string\n}\n\nexport function EmailComposeCard(props: EmailComposeCardProps) {\n const { emailId, basePath } = props\n const firestore = useFirestore()\n const router = useRouter()\n const { orgId } = useMarketingOrgId(props.hostId)\n\n const { data: email, status } = useFirestoreDoc<Record<string, any>>(\n () => (orgId ? campaignSendDoc(firestore, orgId, emailId) : null),\n [firestore, orgId, emailId],\n )\n /** The site this email is written as; see the file header. */\n const hostId: string | null =\n props.hostId ?? (email?.hostId ? String(email.hostId) : null)\n\n const detailHref = `${basePath}/messages/${emailId}`\n const headerActions = (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={detailHref}\n size=\"small\"\n color=\"primary\"\n >\n {'Back to the email'}\n </Button>\n )\n\n const subject = String(email?.subject ?? '')\n const displayName = String(email?.displayName ?? '')\n const state = String(email?.status ?? '')\n const display = email ? campaignSendDisplay(email as never) : null\n const editable =\n (state === 'draft' || state === 'scheduled') &&\n display?.state !== 'sending' &&\n // A held send is written by nobody until staff decide (AGL-3356).\n display?.state !== 'held'\n\n /**\n * Why this email cannot be written, in the words that say what to do next.\n *\n * Empty while it still can be. Each case is a different fact about the\n * record and not a variation on \"no\": one has not loaded, one is in inboxes\n * already, one is being delivered right now.\n */\n const refusal = !email\n ? status === 'loading'\n ? 'Loading this email…'\n : 'This email could not be loaded. It may have been deleted.'\n : !hostId\n ? 'This email does not record which site it is sent as, so it can ' +\n 'only be written from that site’s own Emails page.'\n : editable\n ? ''\n : display?.state === 'held'\n ? campaignHeldForReviewNotice(email as never)\n : display?.state === 'sending'\n ? 'This email is being sent right now, so its message can no longer ' +\n 'be changed. Its page reports what it has reached so far.'\n : state === 'sent'\n ? 'This email has been sent, so its subject, message and audience ' +\n 'describe mail that is already in inboxes. Compose a new email ' +\n 'to say something else.'\n : 'This email was canceled, so it can no longer be written or put ' +\n 'back on the schedule. Compose a new email.'\n\n return (\n <CardDisplay\n header={subject || displayName || 'Untitled email'}\n subheader={'Write this email'}\n help={composeDocsHelp}\n contentGutterX\n contentGutterY\n HeaderProps={{ action: headerActions }}\n >\n {refusal ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {refusal}\n </Typography>\n ) : (\n <CampaignComposer\n hostId={hostId}\n campaignId={emailId}\n emailCampaignId={\n email?.[CAMPAIGN_SEND_CONTAINER_FIELD]\n ? String(email[CAMPAIGN_SEND_CONTAINER_FIELD])\n : undefined\n }\n displayName={displayName || undefined}\n initial={{\n subject,\n body: String(email?.body ?? ''),\n fromName: String(email?.fromName ?? ''),\n replyTo: String(email?.replyTo ?? ''),\n /*\n * The sender this email is set to go out as, so reopening a draft\n * does not silently move it onto whichever sender has become the\n * site's default since it was saved.\n */\n senderId: String(email?.senderId ?? ''),\n preheader: String(email?.preheader ?? ''),\n audience: String(email?.audience ?? ''),\n listId: String(email?.listId ?? ''),\n segmentId: String(email?.segmentId ?? ''),\n topicId: String(email?.topicId ?? ''),\n /*\n * Which of the two ways this email is written. The composer\n * resolves the mode from this field through the same function the\n * send path reads, so a designed draft reopens designed.\n */\n templateScreenId: String(email?.templateScreenId ?? ''),\n /*\n * The plain-text half, and the design version it was written\n * against. Absent means the design generates it — the composer\n * reads that through the same resolver the record's shape is\n * defined by, so a stale override is named rather than guessed at.\n */\n plainText: String(email?.plainText ?? ''),\n plainTextVersionId: String(email?.plainTextVersionId ?? ''),\n }}\n /*\n * A send or a schedule lands on the record, and the record's page is\n * where its report will be — so the merchant is left looking at what\n * they just did rather than at the form that did it.\n */\n onSent={() => router.push(detailHref)}\n />\n )}\n </CardDisplay>\n )\n}\nEmailComposeCard.displayName = 'EmailComposeCard'\n\nexport default EmailComposeCard\n"],"names":["pluginDocsHelp","AppLink","CardDisplay","Button","Typography","useFirestore","useFirestoreDoc","useRouter","campaignHeldForReviewNotice","campaignSendDisplay","CAMPAIGN_SEND_CONTAINER_FIELD","CampaignComposer","campaignSendDoc","useMarketingOrgId","composeDocsHelp","anchor","excerpt","EmailComposeCard","props","emailId","basePath","firestore","router","orgId","hostId","data","email","status","String","detailHref","headerActions","component","componentVariant","nativeButton","href","size","color","subject","displayName","state","display","editable","refusal","header","subheader","help","contentGutterX","contentGutterY","HeaderProps","action","variant","campaignId","emailCampaignId","undefined","initial","body","fromName","replyTo","senderId","preheader","audience","listId","segmentId","topicId","templateScreenId","plainText","plainTextVersionId","onSent","push"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CC,GAED,SAASA,cAAc,QAAQ,eAA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gBACpCC,QAAQjC,gBAAOF,yBAAAA,MAAOmC,MAAM,oBAAI;gBAChCC,WAAWlC,iBAAOF,yBAAAA,MAAOoC,SAAS,qBAAI;gBACtCC,SAASnC,iBAAOF,yBAAAA,MAAOqC,OAAO,qBAAI;gBAClC;;;;aAIC,GACDC,kBAAkBpC,iBAAOF,yBAAAA,MAAOsC,gBAAgB,qBAAI;gBACpD;;;;;aAKC,GACDC,WAAWrC,iBAAOF,yBAAAA,MAAOuC,SAAS,qBAAI;gBACtCC,oBAAoBtC,iBAAOF,yBAAAA,MAAOwC,kBAAkB,qBAAI;YAC1D;YACA;;;;WAIC,GACDC,QAAQ,IAAM7C,OAAO8C,IAAI,CAACvC;;;AAKpC;AACAZ,iBAAiBqB,WAAW,GAAG;AAE/B,eAAerB,iBAAgB"}
|
|
@@ -28,7 +28,7 @@ import { doc } from "firebase/firestore";
|
|
|
28
28
|
import { useRouter } from "next/navigation";
|
|
29
29
|
import { useCallback, useMemo, useState } from "react";
|
|
30
30
|
import { campaignLinkReport, campaignReport } from "@aglyn/shared-ui-email-campaigns/model/campaign-report";
|
|
31
|
-
import { campaignSendDisplay, CAMPAIGN_SEND_CONTAINER_FIELD } from "@aglyn/shared-ui-email-campaigns/model/campaign-container";
|
|
31
|
+
import { campaignHeldForReviewNotice, campaignSendDisplay, CAMPAIGN_SEND_CONTAINER_FIELD } from "@aglyn/shared-ui-email-campaigns/model/campaign-container";
|
|
32
32
|
import { emailAudienceLabel, emailIsUnsent, emailSendTimeMs, emailSentAs } from "@aglyn/shared-ui-email-campaigns/model/email-record";
|
|
33
33
|
import { emailPlainTextState } from "@aglyn/aglyn/app-utils/recipient-email-render";
|
|
34
34
|
import { useMarketingHubPath } from "./use-marketing-hub-path.js";
|
|
@@ -170,6 +170,13 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
170
170
|
* action about an email that is already going out.
|
|
171
171
|
*/ const midFlight = display.state === 'sending';
|
|
172
172
|
/**
|
|
173
|
+
* Held for staff review by the phishing screen (AGL-3356). Stored as
|
|
174
|
+
* `scheduled`, so every control below that offers to send, reschedule or
|
|
175
|
+
* edit a scheduled email is withheld on it: none of them is the merchant's
|
|
176
|
+
* to use until staff decide. Canceling it stays — withdrawing an email is
|
|
177
|
+
* always theirs.
|
|
178
|
+
*/ const held = display.state === 'held';
|
|
179
|
+
/**
|
|
173
180
|
* This email has not gone to anybody yet.
|
|
174
181
|
*
|
|
175
182
|
* Everything below the state table is a REPORT, and an unsent email has
|
|
@@ -553,7 +560,7 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
553
560
|
offer: its remaining batches are due when the sender said, and moving
|
|
554
561
|
`sendAtMs` under the processor mid-campaign changes when the rest of a
|
|
555
562
|
delivery happens rather than when it starts.
|
|
556
|
-
*/ ...(draft || scheduled) && !midFlight ? [
|
|
563
|
+
*/ ...(draft || scheduled) && !midFlight && !held ? [
|
|
557
564
|
{
|
|
558
565
|
key: 'schedule',
|
|
559
566
|
label: scheduled ? 'Reschedule' : 'Schedule',
|
|
@@ -611,7 +618,7 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
611
618
|
* no primary act at all — it was withdrawn deliberately, and offering a way
|
|
612
619
|
* to un-withdraw it would be a resurrect path this model does not have —
|
|
613
620
|
* and neither does one that is mid-send.
|
|
614
|
-
*/ const primaryAction = (draft || scheduled) && !midFlight ? /*#__PURE__*/ _jsx(Button, {
|
|
621
|
+
*/ const primaryAction = held ? null : (draft || scheduled) && !midFlight ? /*#__PURE__*/ _jsx(Button, {
|
|
615
622
|
size: "small",
|
|
616
623
|
variant: "contained",
|
|
617
624
|
disabled: Boolean(busy),
|
|
@@ -672,7 +679,7 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
672
679
|
color: "primary",
|
|
673
680
|
children: 'All messages'
|
|
674
681
|
})),
|
|
675
|
-
(draft || scheduled) && !midFlight && !siteless ? /*#__PURE__*/ _jsx(Button, _extends({
|
|
682
|
+
(draft || scheduled) && !midFlight && !held && !siteless ? /*#__PURE__*/ _jsx(Button, _extends({
|
|
676
683
|
component: AppLink
|
|
677
684
|
}, {
|
|
678
685
|
componentVariant: 'naked',
|
|
@@ -723,6 +730,10 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
723
730
|
/*#__PURE__*/ _jsx(PageHeaderRecord, {
|
|
724
731
|
title: email ? subject : undefined
|
|
725
732
|
}),
|
|
733
|
+
held ? /*#__PURE__*/ _jsx(Alert, {
|
|
734
|
+
severity: "warning",
|
|
735
|
+
children: campaignHeldForReviewNotice(email)
|
|
736
|
+
}) : null,
|
|
726
737
|
siteless ? /*#__PURE__*/ _jsx(Alert, {
|
|
727
738
|
severity: "info",
|
|
728
739
|
children: 'This email does not record which site it was sent as, so it can ' + 'only be managed from that site’s own Emails page. Its figures ' + 'below are complete.'
|
|
@@ -763,7 +774,7 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
763
774
|
align: "right",
|
|
764
775
|
children: /*#__PURE__*/ _jsx(Chip, {
|
|
765
776
|
size: "small",
|
|
766
|
-
color: display.state === 'sending' ? 'info' : display.state === 'stopped' ? 'warning' : undefined,
|
|
777
|
+
color: display.state === 'sending' ? 'info' : display.state === 'stopped' || held ? 'warning' : undefined,
|
|
767
778
|
label: display.label
|
|
768
779
|
})
|
|
769
780
|
})
|