@aglyn/plugins-marketing 1.0.0-beta.199 → 1.0.0-beta.200

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/package.json +15 -15
  2. package/src/lib/components/campaign-detail-card.js +106 -36
  3. package/src/lib/components/campaign-detail-card.js.map +1 -1
  4. package/src/lib/components/campaign-queries.d.ts +11 -0
  5. package/src/lib/components/campaign-queries.js +13 -0
  6. package/src/lib/components/campaign-queries.js.map +1 -1
  7. package/src/lib/components/campaigns-card.d.ts +8 -6
  8. package/src/lib/components/campaigns-card.js +283 -125
  9. package/src/lib/components/campaigns-card.js.map +1 -1
  10. package/src/lib/components/emails-list-card.d.ts +11 -15
  11. package/src/lib/components/emails-list-card.js +139 -142
  12. package/src/lib/components/emails-list-card.js.map +1 -1
  13. package/src/lib/components/host-experiments-card.component.js +107 -78
  14. package/src/lib/components/host-experiments-card.component.js.map +1 -1
  15. package/src/lib/components/org-experiments-card.js +7 -3
  16. package/src/lib/components/org-experiments-card.js.map +1 -1
  17. package/src/lib/model/campaign-list-query.d.ts +99 -0
  18. package/src/lib/model/campaign-list-query.js +373 -0
  19. package/src/lib/model/campaign-list-query.js.map +1 -0
  20. package/src/lib/model/experiment-list-query.d.ts +22 -0
  21. package/src/lib/model/experiment-list-query.js +85 -0
  22. package/src/lib/model/experiment-list-query.js.map +1 -0
  23. package/src/lib/server/campaign-manage.d.ts +1 -1
  24. package/src/lib/server/campaign-manage.js +30 -18
  25. package/src/lib/server/campaign-manage.js.map +1 -1
  26. package/src/lib/server/campaign-send.d.ts +7 -0
  27. package/src/lib/server/campaign-send.js +17 -5
  28. package/src/lib/server/campaign-send.js.map +1 -1
  29. package/src/lib/server/email-events.js +3 -1
  30. package/src/lib/server/email-events.js.map +1 -1
  31. package/src/lib/components/email-send-filter.d.ts +0 -32
  32. package/src/lib/components/email-send-filter.js +0 -55
  33. package/src/lib/components/email-send-filter.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/campaign-detail-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 {\n mdiDeleteOutline,\n mdiEyeOutline,\n mdiPaletteOutline,\n mdiPencilOutline,\n} from '@aglyn/shared-data-mdi'\nimport {\n AppLink,\n CardDisplay,\n MdiIcon,\n useConfirmationContext,\n} from '@aglyn/shared-ui-jsx'\nimport {\n Figure,\n RateRow,\n Section,\n} from '@aglyn/shared-ui-jsx/components/measured-figures.component'\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 { useListRowsFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-rows-filter'\nimport RowActionsMenu, {\n type RowActionsMenuItem,\n} from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { ceilingedWindow } from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { PageHeaderRecord, pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n Alert,\n Box,\n Button,\n Chip,\n Divider,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport {\n collection,\n deleteField,\n documentId,\n limit,\n orderBy,\n query,\n updateDoc,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useRouter } from 'next/navigation'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useFirestoreCollection,\n useFirestoreDoc,\n} from '@aglyn/tenant-feature-instance'\nimport {\n campaignForcedListUnsubscribeSends,\n campaignListUnsubscribe,\n campaignRollup,\n campaignSendDisplay,\n campaignSiteIds,\n campaignVisibleTo,\n campaignWindowState,\n emailListTimeMs,\n type CampaignAggregate,\n type CampaignSend,\n type EmailCampaign,\n} from '@aglyn/shared-ui-email-campaigns/model'\nimport {\n EMAIL_STATE_FILTER_FIELD,\n EMAIL_STATE_OPTIONS,\n EMAIL_SUBJECT_FILTER_FIELD,\n emailFilterValues,\n} from './email-send-filter'\nimport CampaignComposer from './campaign-composer'\nimport CampaignEditDrawer, {\n type CampaignEditValues,\n} from './campaign-edit-drawer'\nimport {\n CampaignConversionsSection,\n CampaignDestinationsSection,\n CampaignRevenueSection,\n CampaignSequencesSection,\n} from './campaign-reach-sections'\nimport CampaignMembersSection from './campaign-members-section'\nimport CampaignReportCard from './campaign-report-card'\nimport { campaignContainerDoc, campaignSendsQuery } from './campaign-queries'\nimport {\n orgSiteHubPath,\n orgSiteName,\n orgSiteOptions,\n topicCatalogHostId,\n useMarketingOrgId,\n useMarketingOrgMount,\n} from './marketing-org-mount'\nimport { useCampaignManageApi } from './use-campaign-send-api'\nimport { useEmailsHubPath } from './use-emails-hub-path'\nimport { useCampaignTopicOptions } from './use-campaign-topic-options'\n\n/** How many of a campaign's emails the detail page enumerates. */\nconst CAMPAIGN_EMAIL_CEILING = 50\n\nconst detailDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#the-campaign-report',\n excerpt:\n 'A campaign groups the emails sent to its lists. The figures here are ' +\n 'the sum across those emails, and each one keeps its own report.',\n})\n\n/**\n * A rolled-up figure, in the shared `Figure`'s shape.\n *\n * The note is where an aggregate differs from a single send's count: a total\n * measured over fewer emails than the campaign holds says which part of the\n * campaign it describes, rather than presenting a partial sum as a complete\n * one. `null` still renders as an em dash and says \"not recorded\", which is\n * the property the shared component already owns.\n */\nconst rolled = (\n value: CampaignAggregate,\n): { value: number | null; note: string } => ({\n value: value.value,\n note:\n value.value !== null && value.recorded < value.sends\n ? `across ${value.recorded} of ${value.sends} emails`\n : `across ${value.sends} email${value.sends === 1 ? '' : 's'}`,\n})\n\n/* What the campaign's emails table filters by (AGL-3317). */\nconst SEND_FILTER_FIELDS = [EMAIL_SUBJECT_FILTER_FIELD, EMAIL_STATE_FILTER_FIELD]\nconst SEND_FILTER_OPTIONS = { state: EMAIL_STATE_OPTIONS }\nconst SEND_FILTER_HEADERS: Readonly<Record<string, string>> = {\n subject: 'Subject',\n state: 'State',\n}\nconst SEND_SEARCH_FIELDS = ['subjectText'] as const\n\nexport interface CampaignDetailCardProps {\n /** The site, or `null` on the org Marketing hub. */\n hostId: string | null\n /** A campaign container id, or a send id from before containers existed. */\n campaignId: string\n /** The marketing hub URL, for the way back to the campaigns list. */\n basePath: string\n}\n\n/**\n * ONE CAMPAIGN: its lists, what it caused, what it earned, where it sent\n * people, and the emails it did all of that with.\n *\n * ## Why the emails are a section rather than the page\n *\n * A campaign reaches people by email, which is not the same as a campaign\n * BEING a list of emails. It runs over a window, against a set of audiences,\n * and the pages its links land on, the money credited to it and the\n * conversions credited to it are facts about the campaign that no single\n * message in it holds. So the body is sectioned — what it caused, what it\n * earned, where it sent people, then the mail's own figures, then its emails\n * — and each section names the population it describes.\n *\n * The ORDER is the part that says which of those the page is about. Delivery,\n * engagement and rates are mechanics of a message; a page that met the reader\n * with them and reached the outcomes only after scrolling was a mail report\n * whatever its headings claimed. `campaign-report-card.tsx` — the page a\n * campaign of one email gets — carries the same two outcome headings first,\n * for the same reason and in the same words.\n *\n * The three middle sections live in `campaign-reach-sections.tsx`, which is\n * also where the reason a campaign cannot simply DECLARE the screens and\n * forms it runs across is written down: no such edge is stored, attribution\n * is the mechanism, and all three sections join on this campaign's send ids.\n *\n * ## Why this resolves two kinds of id\n *\n * The id in `campaigns/{id}` may name a campaign CONTAINER or a single SEND,\n * and which it is is answered by reading: a container at `emailCampaigns/{id}`\n * renders this page, and anything else falls through to that send's own\n * report.\n *\n * Not every send belongs to a container. One written before campaigns grouped\n * their emails names none, its own id is the only id the URL can carry, and\n * that id is also inside the HMAC of every unsubscribe footer already\n * delivered — so a send id has to go on addressing a page rather than a 404.\n * The fall-through is what makes the container additive: no send document is\n * rewritten and no id is reassigned.\n *\n * The extra read is one document, and it buys the guarantee that a pasted\n * report link resolves whichever kind of id it carries.\n *\n * ## Under a site, and over the organization\n *\n * The container and its sends are the org's, so the same page renders on the\n * org hub with `hostId` null. What changes there is everything that is a SITE\n * fact: the emails listed are every site's rather than the ones sent as this\n * site, the forms and screens filed under the campaign are gathered from each\n * site it is placed on, the conversions are one chosen site's (they are\n * recorded per site), and writing an email first asks which site it is sent\n * as — its sender, its designs and its consent all belong to that site.\n */\nexport function CampaignDetailCard(props: CampaignDetailCardProps) {\n const { hostId, campaignId, basePath } = props\n const firestore = useFirestore()\n // The sibling hub, for the two records this page links to but does not own:\n // each message's report and the template it was built from.\n const emailsHub = useEmailsHubPath()\n const router = useRouter()\n const orgMount = useMarketingOrgMount()\n const { orgId } = useMarketingOrgId(hostId)\n const { confirm } = useConfirmationContext()\n const { enqueueSnackbar } = useSnackbar()\n const manageApi = useCampaignManageApi(hostId, orgId)\n /*\n * The site an email written here is sent AS. Under a site it is that site\n * and never asked; on the org hub it is chosen before the composer opens.\n * Empty means nobody has chosen yet.\n */\n const [composeHostId, setComposeHostId] = useState('')\n /** The site whose conversions the org hub is showing; empty until chosen. */\n const [conversionsHostId, setConversionsHostId] = useState('')\n const [composing, setComposing] = useState(false)\n const [editing, setEditing] = useState(false)\n const [saving, setSaving] = useState(false)\n const [saveError, setSaveError] = useState<string | null>(null)\n const [deleting, setDeleting] = useState(false)\n\n const { data: campaign, status } = useFirestoreDoc<EmailCampaign>(\n () => (orgId ? campaignContainerDoc(firestore, orgId, campaignId) : null),\n [firestore, orgId, campaignId],\n )\n\n /*\n * ONLY WHEN THE ID NAMES A CAMPAIGN.\n *\n * Both queries below are gated on the container having been found, because\n * the other half of this component is the single-send report — and that\n * screen's whole design is that it reads two documents whatever the size of\n * the audience. Listening unconditionally would add two collection reads to\n * every legacy report URL, which is the cost the report route was split out\n * to avoid. Not listening is what a null builder means.\n *\n * The campaign's emails come back by the field each send carries: equality\n * on one field ordered by DOCUMENT NAME. On the org hub that is all the\n * query says, and the automatic single-field index serves it. Under a site\n * the sends are also narrowed to the ones sent as that site — the scope\n * filter that makes the read provable for a site collaborator — and that\n * pair is the one composite index this page needs. Ordering on a date\n * would need that index AND would drop every send missing that particular\n * date — a sent send carries `sentAt`, a scheduled one `sendAtMs`, and\n * neither is on both. Sorted by date below, over a window this page holds\n * whole.\n *\n * One document past the ceiling, so \"this campaign has more emails than are\n * listed\" is a fact rather than a guess.\n */\n const { data: sendDocs } = useFirestoreCollection<any>(\n () => {\n const sends = campaign\n ? campaignSendsQuery(firestore, orgId, hostId)\n : null\n return sends\n ? query(\n sends,\n where('emailCampaignId', '==', campaignId),\n orderBy(documentId()),\n limit(CAMPAIGN_EMAIL_CEILING + 1),\n )\n : null\n },\n [firestore, orgId, hostId, campaignId, Boolean(campaign)],\n { idField: '$id' },\n )\n\n const { data: listDocs } = useFirestoreCollection<any>(\n () =>\n campaign && orgId\n ? query(collection(firestore, 'orgs', orgId, 'lists'), limit(50))\n : null,\n [firestore, orgId, Boolean(campaign)],\n { idField: '$id' },\n )\n\n /*\n * The org's topic catalog, read only while the EDIT DRAWER is open.\n *\n * It fills one picker in that drawer and is drawn nowhere else on this\n * page, so reading it on mount would charge every reader who came for the\n * campaign's numbers for a field they are not looking at. The composer\n * carries its own read of the same catalog, behind its own button, for the\n * same reason.\n */\n const { topics, source: topicSource } = useCampaignTopicOptions(\n topicCatalogHostId(hostId, orgMount),\n { enabled: editing },\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 { rows: readSends, truncated: sendsTruncated } = ceilingedWindow<any>(\n sendDocs,\n CAMPAIGN_EMAIL_CEILING,\n )\n /*\n * Newest first on the time each email SITS at — its send time where it has\n * one, its creation where it does not. A draft has neither `sentAt` nor\n * `sendAtMs`, so ordering on the send time alone gave every draft the key 0\n * and filed the email a merchant is in the middle of writing below mail\n * sent years ago.\n */\n const sends = useMemo(\n () =>\n [...(readSends as CampaignSend[])].sort(\n (a, b) => emailListTimeMs(b) - emailListTimeMs(a),\n ),\n [readSends],\n )\n const rollup = useMemo(() => campaignRollup(sends), [sends])\n /*\n * The emails table's Filters panel and search (AGL-3317), answered over\n * every email the card read — the same window the figures above cover.\n */\n const sendFilterRows = useMemo(\n () => sends.map((send) => ({ ...send, ...emailFilterValues(send) })),\n [sends],\n )\n const sendFilter = useListRowsFilter({\n rows: sendFilterRows,\n fields: SEND_FILTER_FIELDS,\n options: SEND_FILTER_OPTIONS,\n headers: SEND_FILTER_HEADERS,\n search: SEND_SEARCH_FIELDS,\n })\n // The ids the two sections beneath the figures join on. Derived from the\n // window this card already holds, so neither of them reads the send list\n // again to find out which emails the campaign has.\n const sendIds = useMemo(\n () => sends.map((send) => String(send.$id)).filter(Boolean),\n [sends],\n )\n\n /*==========================================\n * SAVING THE CONTAINER, WITH THE CLIENT SDK.\n *\n * The same door the create drawer already uses. `emailCampaigns` is\n * deliberately outside the security rules' server-only exclusion list — a\n * container holds no counter, no consent record and no entitlement input,\n * so an editor who writes one cannot buy themselves a send — and giving the\n * edit a route of its own would be a second writer to keep in step with the\n * create.\n *\n * `updateDoc` rather than a merge-set, because this is an edit of a\n * document that exists: a set would CREATE a campaign at this id for\n * somebody who deleted it in another tab, which is the shape the delivery\n * webhook is careful about on the send collection for the same reason.\n *\n * A cleared date is written as `null` — the absence the model already\n * spells — and a cleared topic REMOVES the field, because the model has no\n * null topic and `campaignTopicId` is handed to the composer as one.\n *\n * `visibleTo` is written only from the org hub, and only when its drawer\n * says the placement changed. A site hub never touches it: the rules let a\n * site collaborator edit a campaign only while its scope is unchanged, and\n * a site hub has no field for it anyway.\n *=========================================*/\n const handleSave = useCallback(\n async (values: CampaignEditValues) => {\n if (saving || !orgId) return\n setSaving(true)\n setSaveError(null)\n try {\n await updateDoc(campaignContainerDoc(firestore, orgId, campaignId), {\n name: values.name,\n startAtMs: values.startAtMs,\n endAtMs: values.endAtMs,\n listIds: values.listIds,\n topicId: values.topicId ? values.topicId : deleteField(),\n listUnsubscribe: values.listUnsubscribe,\n ...(!hostId && values.siteIds !== undefined\n ? { visibleTo: campaignVisibleTo(values.siteIds) }\n : {}),\n })\n setEditing(false)\n enqueueSnackbar('Campaign updated', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n setSaveError('The campaign could not be saved')\n } finally {\n setSaving(false)\n }\n },\n [campaignId, enqueueSnackbar, firestore, hostId, orgId, saving],\n )\n\n /*==========================================\n * DELETING THE CONTAINER, WHICH IS NOT DELETING ITS MAIL.\n *\n * The route detaches every email first and then removes the campaign, so\n * what a merchant is agreeing to is the grouping going away — the emails\n * stay, keep their ids, keep their reports, and read afterwards as single\n * sends. Their unsubscribe links carry those ids inside an HMAC and go on\n * working, which is why the container can never take them with it.\n *\n * The confirmation says the count and says what a delete does NOT do. A\n * scheduled email inside the campaign still goes out at its time — stopping\n * somebody's mail is `cancel`, on that email's own page — and a merchant\n * who reads \"delete campaign\" as \"stop the campaign\" has to be told\n * otherwise before they press it, not after.\n *=========================================*/\n const handleDelete = useCallback(async () => {\n if (deleting) return\n /*\n * Emails with mail still to go: the ones waiting for their time AND the\n * ones part way through an audience larger than one batch. Both are what\n * a merchant needs warning about, and counting only `scheduled` would\n * miss the case that needs it most — a campaign that is delivering right\n * now is stored as `scheduled` too, but `rollup.scheduled` is the\n * narrower reading that excludes it.\n */\n const unfinished = rollup.scheduled + rollup.sending\n const agreed = await confirm({\n title: 'Delete this campaign?',\n description:\n (sends.length\n ? `The ${sends.length.toLocaleString()} ` +\n `${sends.length === 1 ? 'email' : 'emails'} in it are kept — ` +\n 'each keeps its own report and its unsubscribe links, and they ' +\n 'appear in the campaigns 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 setDeleting(true)\n try {\n const { response, payload } = await manageApi({\n action: 'deleteCampaign',\n campaignId,\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', { variant: 'success', persist: false })\n router.push(`${basePath}/campaigns`)\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 setDeleting(false)\n }\n }, [\n basePath,\n campaignId,\n confirm,\n deleting,\n enqueueSnackbar,\n manageApi,\n rollup.scheduled,\n rollup.sending,\n router,\n sends.length,\n ])\n\n // Still settling. Falling through to the send report here would flash \"this\n // campaign could not be loaded\" on every open of a campaign that exists —\n // and under a site nothing is read at all until the site's org is known.\n if (!campaign && (status === 'loading' || !orgId)) return null\n\n /*\n * NOT A CONTAINER — so it is a send id, and the send's own report is what\n * this URL has always meant.\n */\n if (!campaign) {\n return (\n <CampaignReportCard\n hostId={hostId}\n campaignId={campaignId}\n basePath={basePath}\n />\n )\n }\n\n const listIds = campaign.listIds ?? []\n const names = new Map<string, string>(\n (listDocs ?? []).map((list: any) => [\n String(list.$id),\n String(list.name ?? list.$id),\n ]),\n )\n /*==========================================\n * ONE EMAIL'S PAGE — the same one every other route to that record opens.\n *\n * The Emails hub's `emails/{sendId}`, which is where the messages list and\n * a template's messages table also send a reader. One record has one page:\n * a link that resolved somewhere else depending on which list it was\n * clicked in would give the same message two pages, and the reader would\n * have no way to tell which one they were on.\n *\n * `campaigns/{sendId}` on THIS hub goes on resolving as well, through the\n * fall-through at the top of this file. That is not a convenience — every\n * unsubscribe footer already delivered carries `cid={sendId}`, those\n * messages sit in inboxes forever, and merchants paste report URLs into\n * their own mail. Which link the console GENERATES and which URLs ANSWER\n * are two separate questions, and only the first is decided here.\n *\n * Nor is a redirect the answer to the second. A redirect would be another\n * thing to be wrong about an id that is inside an HMAC; a page that keeps\n * working has nothing to get wrong, and it costs nothing to leave standing.\n *=========================================*/\n /*\n * A message opens on the Emails page: the site's under a site, and over the\n * org the organization's own, which lists every site's messages.\n */\n const messagesPath = emailsHub ? `${emailsHub}/messages` : null\n const sendHref = (send: CampaignSend) =>\n messagesPath ? `${messagesPath}/${send.$id}` : undefined\n /** A template is a site's design, so it opens on the site the send used. */\n const templatesPath = (send: CampaignSend): string | null => {\n const hub = orgMount ? orgSiteHubPath(orgMount, send.hostId, 'emails') : emailsHub\n return hub ? `${hub}/templates` : null\n }\n\n /**\n * What one of this campaign's emails can be opened into.\n *\n * The same two the Emails hub offers, less the campaign — this page IS the\n * campaign. Both destinations are records the Emails console owns, so they\n * are built from {@link useEmailsHubPath} rather than from this surface's\n * own `basePath`.\n *\n * A message composed inline was built from no template, so that entry is\n * shown DISABLED with the reason rather than hidden: an absent control and\n * an inapplicable one look identical, and only one is honest.\n */\n const sendActions = (send: CampaignSend): RowActionsMenuItem[] => {\n const templateScreenId = String((send as any).templateScreenId ?? '')\n const templates = templatesPath(send)\n return [\n {\n key: 'details',\n label: 'Open report',\n icon: <MdiIcon path={mdiEyeOutline.path} size={0.8} />,\n href: sendHref(send),\n disabled: !sendHref(send),\n disabledReason: 'This site’s console URL has not resolved yet',\n },\n {\n key: 'template',\n label: 'Open its template',\n icon: <MdiIcon path={mdiPaletteOutline.path} size={0.8} />,\n href:\n templateScreenId && templates\n ? `${templates}/${templateScreenId}`\n : undefined,\n disabled: !templateScreenId || !templates,\n disabledReason: templateScreenId\n ? 'This site’s console URL has not resolved yet'\n : 'This message was not built from a template',\n },\n ]\n }\n\n /*\n * The campaign's emails, on the surface's own row grammar: the row opens\n * the email's report, its subject is also a real link so it can be\n * middle-clicked and copied, and the trailing cluster holds the actions.\n * The window is one the card already holds, so the grid pages it.\n */\n const sendColumns: GridColDef<CampaignSend>[] = [\n {\n field: 'subject',\n headerName: 'Subject',\n flex: 1,\n minWidth: 220,\n valueGetter: (_value, send) => send.subject || send.$id,\n /*\n Plain text until the Emails hub resolves: a link with no destination\n is worse than none, and this cell is the message's subject either way.\n */\n renderCell: ({ row: send, value }) => {\n const href = sendHref(send)\n return href ? (\n <AppLink\n href={href}\n // The row's own handler would fire too and push the same route\n // twice — one history entry per back press.\n onClick={(event: { stopPropagation: () => void }) =>\n event.stopPropagation()\n }\n >\n {value}\n </AppLink>\n ) : (\n value\n )\n },\n },\n {\n /*\n WHAT THE EMAIL IS DOING, not the field it stores.\n\n This branched on the status, which reads \"Scheduled\" about an email\n that has delivered five hundred messages and is between batches — the\n stored state the processor claims to resume it. The derivation reads\n the counters beside the status; the due date is appended only where\n there is genuinely nothing delivered yet, which is the one case a time\n answers.\n */\n field: 'state',\n headerName: 'State',\n width: 220,\n valueGetter: (_value, send) => {\n const display = campaignSendDisplay(send)\n return display.state === 'pending' && send.sendAtMs\n ? `${display.label} · ${new Date(send.sendAtMs).toLocaleString()}`\n : display.label\n },\n renderCell: ({ row: send, value }) => {\n const state = campaignSendDisplay(send).state\n return (\n <Chip\n size=\"small\"\n color={\n state === 'sending' ? 'info' : state === 'stopped' ? 'warning' : undefined\n }\n label={value}\n />\n )\n },\n },\n {\n /*\n Sent over addressed, on one line: the two figures only mean anything\n beside each other, and the gap between them is the suppression list\n doing its work.\n */\n field: 'sent',\n headerName: 'Sent',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 110,\n valueGetter: (_value, send) => Number(send.stats?.sent ?? 0),\n renderCell: ({ row: send }) =>\n `${send.stats?.sent ?? 0}/${send.stats?.recipients ?? 0}`,\n },\n {\n field: 'opens',\n headerName: 'Opens',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 100,\n valueGetter: (_value, send) => Number(send.stats?.opens ?? 0),\n valueFormatter: (value: number) => value.toLocaleString(),\n },\n {\n field: 'clicks',\n headerName: 'Clicks',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 100,\n valueGetter: (_value, send) => Number(send.stats?.clicks ?? 0),\n valueFormatter: (value: number) => value.toLocaleString(),\n },\n listActionsColumn(\n (send: CampaignSend) => (\n <ListRowActions\n label={String(send.subject || send.$id)}\n items={sendActions(send)}\n />\n ),\n { width: 72 },\n ),\n ]\n\n const windowState = campaignWindowState(campaign, Date.now())\n /*\n * The mail-client unsubscribe button (AGL-3307): the campaign's setting,\n * and the emails whose header the bulk guard turned back on while it was\n * off — read off the sends this page already holds, each of which records\n * what it did and why.\n */\n const listUnsubscribeOn = campaignListUnsubscribe(campaign)\n const forcedSends = campaignForcedListUnsubscribeSends(sends)\n const start = campaign.startAtMs\n ? new Date(campaign.startAtMs).toLocaleDateString()\n : ''\n const end = campaign.endAtMs\n ? new Date(campaign.endAtMs).toLocaleDateString()\n : ''\n\n /*\n * THE SITES IT IS PLACED ON, which the org hub needs three times over: the\n * forms and screens filed under it are gathered from each of them, its\n * conversions are read for one of them, and an email written here is sent\n * as one of them. Every site when it is placed everywhere. Under a site the\n * answer is that site, and none of this is read.\n */\n const placedIds = campaignSiteIds(campaign)\n const placedSites = orgMount\n ? orgMount.hosts.filter(\n (site) => placedIds === null || placedIds.includes(site.id),\n )\n : []\n const conversionsHost =\n hostId ?? (conversionsHostId || placedSites[0]?.id || '')\n const conversionsBasePath = hostId\n ? basePath\n : orgSiteHubPath(orgMount, conversionsHost, 'marketing')\n /** Asked only when there is a choice to make; one site answers itself. */\n const writeAsHostId =\n hostId ??\n (placedSites.length === 1 ? placedSites[0].id : composeHostId)\n\n /* The card, named so the page chrome above it is a plain list of\n what this surface publishes upward. */\n const card = (\n <CardDisplay\n header={'Campaign'}\n subheader={\n start || end\n ? `${start || 'Open'} – ${end || 'open-ended'}`\n : 'No campaign dates'\n }\n help={detailDocsHelp}\n HeaderProps={{\n /*\n NAVIGATION, THEN THE OVERFLOW.\n\n Editing and deleting a campaign live here rather than on the\n campaigns table, because a record is edited on its own page in this\n console. `RowActionsMenu` is named for table rows and its rendering\n is not — a kebab and a menu whose items carry `destructive` and\n `disabled` — so reusing it is what keeps this overflow behaving like\n every other one on the surface, including the email page's.\n */\n action: (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={`${basePath}/campaigns`}\n size=\"small\"\n color=\"primary\"\n >\n {'All campaigns'}\n </Button>\n <RowActionsMenu\n label={campaign.name || 'Campaign'}\n items={[\n {\n key: 'edit',\n label: 'Edit campaign',\n icon: <MdiIcon path={mdiPencilOutline.path} size={0.8} />,\n onClick: () => {\n setSaveError(null)\n setEditing(true)\n },\n },\n {\n key: 'delete',\n label: 'Delete campaign',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: deleting,\n disabledReason: 'This campaign is being deleted',\n onClick: () => void handleDelete(),\n },\n ]}\n />\n </Stack>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Chip size=\"small\" label={windowState} />\n {listIds.length ? (\n listIds.map((id) => (\n <Chip\n key={id}\n size=\"small\"\n variant=\"outlined\"\n label={names.get(id) ?? id}\n />\n ))\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'No lists assigned — its emails pick their own audience'}\n </Typography>\n )}\n </Stack>\n {orgMount ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {placedIds === null\n ? 'Offered on every site'\n : placedIds.length\n ? `Offered on ${placedIds\n .map((id) => orgSiteName(orgMount, id))\n .join(', ')}`\n : 'Not offered on any site yet — edit the campaign to place it'}\n </Typography>\n ) : null}\n\n <Typography variant=\"body2\" color=\"text.secondary\">\n {listUnsubscribeOn\n ? 'Mail-client unsubscribe button: on'\n : 'Mail-client unsubscribe button: off — the footer link is ' +\n 'the way out, and the button comes back for any email that ' +\n 'would make your organization a bulk sender'}\n </Typography>\n {forcedSends.length ? (\n <Alert severity=\"info\">\n {`The mail-client unsubscribe button was turned back on for ` +\n `${forcedSends.length === 1 ? 'one email' : `${forcedSends.length.toLocaleString()} emails`} ` +\n 'in this campaign, though the campaign has it off. '}\n {forcedSends\n .map(\n (send) =>\n `${send.subject || send.$id}: ` +\n (send.listUnsubscribe?.detail ||\n 'turned back on by the bulk-sender guard.'),\n )\n .join(' ')}\n </Alert>\n ) : null}\n\n <Divider />\n {/*\n A CAMPAIGN IS NOT ONLY ITS MAIL, and it leads with the part that\n is not.\n\n What the campaign CAUSED and where it SENT people are facts about the\n campaign; delivery, engagement and rates are mechanics of the\n messages it used, and the list of those messages is one section among\n several rather than the page. Ordering the mail first said the\n opposite in the only way a page can — by what a reader meets before\n they scroll — and a campaign of ONE email says it loudest, which is\n why `campaign-report-card.tsx` carries these two headings in this\n order too.\n\n All three sections join on the campaign's own send ids, which is the\n only handle the attribution, revenue and click-report collections\n offer — see `campaign-reach-sections.tsx` for why no other join\n exists, and why the web channel is named there rather than quietly\n omitted.\n */}\n {/*\n Conversions are recorded per SITE — they are that site's visitors —\n so the org hub reads them for one site at a time, defaulting to the\n first site the campaign is placed on.\n */}\n {orgMount && placedSites.length > 1 ? (\n <TextField\n select\n size=\"small\"\n label=\"Conversions on\"\n value={conversionsHost}\n onChange={(event) => setConversionsHostId(event.target.value)}\n sx={{ maxWidth: 320 }}\n >\n {placedSites.map((site) => (\n <MenuItem key={site.id} value={site.id}>\n {site.name || site.subdomain || site.id}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {conversionsHost ? (\n <CampaignConversionsSection\n key={conversionsHost}\n hostId={conversionsHost}\n sendIds={sendIds}\n truncated={sendsTruncated}\n basePath={conversionsBasePath}\n />\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Conversions are counted per site, and this campaign is not ' +\n 'placed on one yet.'}\n </Typography>\n )}\n\n <Divider />\n {/*\n WHAT ITS SEQUENCES PRODUCED (AGL-3254), beside what its mail caused:\n a sequence in this campaign is a rep's one-to-one outreach, and its\n enrollments, sends, replies, meetings and conversions are the\n campaign's numbers too. Joined on the container's own id, since a\n sequence's emails are not the campaign's sends.\n */}\n <CampaignSequencesSection orgId={orgId} campaignId={campaignId} />\n\n <Divider />\n {/*\n WHAT IT EARNED, between what it caused and where it sent people —\n the order `campaign-report-card.tsx` puts these three in, so a\n campaign of one email and a campaign of ten answer the merchant's\n questions in the same sequence.\n\n How many messages a container holds is not a fact about whether its\n revenue is knowable, so the money question is answered here whatever\n the count. Reading it costs one record per email, so it asks first —\n see `campaign-reach-sections.tsx` for that bargain, and for why the\n currencies are reported apart and never totalled.\n */}\n <CampaignRevenueSection\n orgId={orgId}\n sendIds={sendIds}\n truncated={sendsTruncated}\n />\n\n <Divider />\n <CampaignDestinationsSection\n orgId={orgId}\n sendIds={sendIds}\n truncated={sendsTruncated}\n />\n\n <Divider />\n {/*\n WHAT THE MERCHANT SAID BELONGS HERE, under what the visitors did.\n\n Everything above this line is measured — the conversions, the money\n and the pages the mail's own links pointed at, all joined on this\n campaign's send ids. This section is the only one on the page that\n reports a DECLARATION: a screen or a form carrying this campaign's\n id in its own document because somebody put it there.\n\n It sits after the evidence deliberately. A reader who met the\n assigned list first would take it for the campaign's reach, and the\n two are not the same list — a landing page can be assigned to a\n campaign no email ever linked to, and a campaign's mail can drive\n traffic to a page assigned to nothing.\n\n The dates go with it. A form's counters are lifetime, so a campaign\n with a window has to be able to confine them to its own months; a\n campaign without one is told so, and says its figures are lifetime\n rather than implying they are its own.\n */}\n {hostId ? (\n <CampaignMembersSection\n hostId={hostId}\n campaignId={campaignId}\n startAtMs={campaign.startAtMs}\n endAtMs={campaign.endAtMs}\n />\n ) : (\n /*\n * Forms and screens are a site's records, so on the org hub each\n * site the campaign is placed on answers for its own. One section\n * per site keeps each one's figures and ceilings its own rather\n * than merging lists that were bounded separately.\n */\n placedSites.map((site) => (\n <CampaignMembersSection\n key={site.id}\n hostId={site.id}\n siteName={site.name || site.subdomain || site.id}\n campaignId={campaignId}\n startAtMs={campaign.startAtMs}\n endAtMs={campaign.endAtMs}\n />\n ))\n )}\n\n <Divider />\n {/*\n THE MAIL'S OWN FIGURES, under the outcomes rather than over them.\n\n The sum over the campaign's emails, not a second set of counters.\n Nothing is stored per campaign: a rollup document would have to be\n kept true against every delivery event of every email in it, and the\n numbers it duplicates are already on the sends this page reads.\n\n Drawn by the shared figures so a campaign's rate and a single\n message's read the same way — denominator named on the line, and an\n em dash rather than a zero where nothing was recorded.\n */}\n <Section title=\"The mail, across this campaign\">\n <Stack direction=\"row\" spacing={3} sx={{ flexWrap: 'wrap' }}>\n <Figure label=\"Addressed\" {...rolled(rollup.addressed)} />\n <Figure label=\"Sent\" {...rolled(rollup.sent)} />\n <Figure label=\"Delivered\" {...rolled(rollup.delivered)} />\n <Figure label=\"Opens\" {...rolled(rollup.opens)} />\n <Figure label=\"Clicks\" {...rolled(rollup.clicks)} />\n <Figure label=\"Unsubscribed\" {...rolled(rollup.unsubscribes)} />\n </Stack>\n </Section>\n <Stack spacing={0.5}>\n <RateRow label=\"Open rate\" rate={rollup.openRate} />\n <RateRow label=\"Click rate\" rate={rollup.clickRate} />\n <RateRow label=\"Unsubscribe rate\" rate={rollup.unsubscribeRate} />\n </Stack>\n\n <Divider />\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', justifyContent: 'space-between' }}\n >\n {/*\n The section rail's own heading style, so this reads as one section\n among the others rather than as the page's subject.\n */}\n <Typography variant=\"overline\" color=\"text.secondary\">\n {`Emails (${sends.length})`}\n </Typography>\n <Button\n size=\"small\"\n variant={composing ? 'text' : 'contained'}\n onClick={() => setComposing((open) => !open)}\n >\n {composing ? 'Close composer' : 'Write an email'}\n </Button>\n </Stack>\n {sends.length ? (\n <Stack spacing={0.5}>\n <ListFilterChips {...sendFilter.chipsProps} />\n <ListTable\n aria-label=\"The campaign's emails\"\n rows={sendFilter.rows}\n columns={sendFilter.filterColumns(sendColumns as GridColDef[])}\n rowHeight={TABLE_ROW_HEIGHT}\n onOpen={(_id, send) => {\n const href = sendHref(send)\n if (href) router.push(href)\n }}\n {...sendFilter.gridProps}\n noRowsLabel=\"No emails match these filters\"\n />\n {sendsTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${CAMPAIGN_EMAIL_CEILING} of this campaign's ` +\n 'emails. It has sent more — the ones listed are not ' +\n 'necessarily the most recent, because a send carries no ' +\n 'date field that every writer stamps, and the figures above ' +\n 'cover the emails listed.'}\n </Alert>\n ) : null}\n </Stack>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No emails in this campaign yet.'}\n </Typography>\n )}\n\n {/*\n THE COMPOSER, ON DEMAND.\n\n It opens listens of its own — the site's email designs, the org's\n lists and segments, the running experiments — and this page is also\n where somebody arrives to read numbers. Mounting it unasked would\n make every reader pay for a composer they did not open, which is the\n same cost the campaign report was split onto its own route to avoid.\n */}\n {composing ? (\n <Box>\n <Divider sx={{ mb: 2 }} />\n {/*\n WHICH SITE IT IS SENT AS, asked first on the org hub. The sender,\n the designs, the consent a recipient gave and the unsubscribe\n signature are all one site's, so the composer cannot open\n without one — and the choice is limited to the sites this\n campaign is placed on.\n */}\n {!hostId && placedSites.length > 1 ? (\n <TextField\n select\n size=\"small\"\n label=\"Send as\"\n value={composeHostId}\n onChange={(event) => setComposeHostId(event.target.value)}\n helperText=\"The site this email is sent from — its sender, designs and unsubscribe page\"\n sx={{ mb: 2, maxWidth: 420 }}\n fullWidth\n >\n {placedSites.map((site) => (\n <MenuItem key={site.id} value={site.id}>\n {site.name || site.subdomain || site.id}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {writeAsHostId ? (\n <CampaignComposer\n key={writeAsHostId}\n hostId={writeAsHostId}\n emailCampaignId={campaignId}\n campaignListIds={listIds}\n campaignTopicId={campaign.topicId}\n onSent={() => setComposing(false)}\n />\n ) : !placedSites.length && !hostId ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Place this campaign on a site before writing an email in ' +\n 'it — every email is sent as one site.'}\n </Typography>\n ) : null}\n </Box>\n ) : null}\n </Stack>\n {/*\n THE EDIT DRAWER, on the campaign's own page.\n\n Its list picker reads the same `listDocs` the chips above already\n cost, so opening it adds one read — the topic catalog — and only\n while it is open.\n */}\n {/* Draws nothing: the zone the topic catalog's owner answers through. */}\n {topicSource}\n <CampaignEditDrawer\n open={editing}\n onClose={() => setEditing(false)}\n campaign={campaign}\n lists={(listDocs ?? []).map((list: any) => ({\n value: String(list.$id),\n label: String(list.name ?? list.$id),\n }))}\n topics={topicOptions}\n sites={orgMount ? orgSiteOptions(orgMount) : undefined}\n busy={saving}\n error={saveError}\n onSubmit={(values) => void handleSave(values)}\n />\n </CardDisplay>\n )\n\n return (\n <>\n {/* The page heading and the trail name the campaign; this card is\n then free to say what it holds rather than repeating the title. */}\n <PageHeaderRecord title={campaign.name || campaignId} />\n {card}\n </>\n )\n}\nCampaignDetailCard.displayName = 'CampaignDetailCard'\n\nexport default CampaignDetailCard\n"],"names":["mdiDeleteOutline","mdiEyeOutline","mdiPaletteOutline","mdiPencilOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","Figure","RateRow","Section","ListFilterChips","ListRowActions","ListTable","listActionsColumn","useListRowsFilter","RowActionsMenu","TABLE_ROW_HEIGHT","ceilingedWindow","PageHeaderRecord","pluginDocsHelp","Alert","Box","Button","Chip","Divider","MenuItem","Stack","TextField","Typography","collection","deleteField","documentId","limit","orderBy","query","updateDoc","where","useCallback","useMemo","useState","useRouter","useSnackbar","useFirestore","useFirestoreCollection","useFirestoreDoc","campaignForcedListUnsubscribeSends","campaignListUnsubscribe","campaignRollup","campaignSendDisplay","campaignSiteIds","campaignVisibleTo","campaignWindowState","emailListTimeMs","EMAIL_STATE_FILTER_FIELD","EMAIL_STATE_OPTIONS","EMAIL_SUBJECT_FILTER_FIELD","emailFilterValues","CampaignComposer","CampaignEditDrawer","CampaignConversionsSection","CampaignDestinationsSection","CampaignRevenueSection","CampaignSequencesSection","CampaignMembersSection","CampaignReportCard","campaignContainerDoc","campaignSendsQuery","orgSiteHubPath","orgSiteName","orgSiteOptions","topicCatalogHostId","useMarketingOrgId","useMarketingOrgMount","useCampaignManageApi","useEmailsHubPath","useCampaignTopicOptions","CAMPAIGN_EMAIL_CEILING","detailDocsHelp","anchor","excerpt","rolled","value","note","recorded","sends","SEND_FILTER_FIELDS","SEND_FILTER_OPTIONS","state","SEND_FILTER_HEADERS","subject","SEND_SEARCH_FIELDS","CampaignDetailCard","props","campaign","placedSites","hostId","campaignId","basePath","firestore","emailsHub","router","orgMount","orgId","confirm","enqueueSnackbar","manageApi","composeHostId","setComposeHostId","conversionsHostId","setConversionsHostId","composing","setComposing","editing","setEditing","saving","setSaving","saveError","setSaveError","deleting","setDeleting","data","status","sendDocs","Boolean","idField","listDocs","topics","source","topicSource","enabled","topicOptions","map","topic","id","label","name","rows","readSends","truncated","sendsTruncated","sort","a","b","rollup","sendFilterRows","send","sendFilter","fields","options","headers","search","sendIds","String","$id","filter","handleSave","values","startAtMs","endAtMs","listIds","topicId","listUnsubscribe","siteIds","undefined","visibleTo","variant","persist","error","console","handleDelete","unfinished","scheduled","sending","agreed","title","description","length","toLocaleString","confirmationText","then","catch","response","payload","action","ok","allowDuplicate","push","names","Map","list","messagesPath","sendHref","templatesPath","hub","sendActions","templateScreenId","templates","key","icon","path","size","href","disabled","disabledReason","sendColumns","field","headerName","flex","minWidth","valueGetter","_value","renderCell","row","onClick","event","stopPropagation","width","display","sendAtMs","Date","color","type","align","headerAlign","Number","stats","sent","recipients","opens","valueFormatter","clicks","items","windowState","now","listUnsubscribeOn","forcedSends","start","toLocaleDateString","end","placedIds","hosts","site","includes","conversionsHost","conversionsBasePath","writeAsHostId","card","header","subheader","help","HeaderProps","direction","spacing","sx","alignItems","component","componentVariant","nativeButton","destructive","contentGutterX","contentGutterY","get","join","severity","detail","select","onChange","target","maxWidth","subdomain","siteName","flexWrap","addressed","delivered","unsubscribes","rate","openRate","clickRate","unsubscribeRate","justifyContent","open","chipsProps","aria-label","columns","filterColumns","rowHeight","onOpen","_id","gridProps","noRowsLabel","mb","helperText","fullWidth","emailCampaignId","campaignListIds","campaignTopicId","onSent","onClose","lists","sites","busy","onSubmit","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,gBAAgB,EAChBC,aAAa,EACbC,iBAAiB,EACjBC,gBAAgB,QACX,yBAAwB;AAC/B,SACEC,OAAO,EACPC,WAAW,EACXC,OAAO,EACPC,sBAAsB,QACjB,uBAAsB;AAC7B,SACEC,MAAM,EACNC,OAAO,EACPC,OAAO,QACF,6DAA4D;AACnE,OAAOC,qBAAqB,8DAA6D;AACzF,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,OAAOC,oBAEA,6DAA4D;AACnE,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,eAAe,QAAQ,+DAA8D;AAC9F,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,eAAc;AAC/D,SACEC,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,OAAO,EACPC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AAEtB,SACEC,UAAU,EACVC,WAAW,EACXC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,SAAS,EACTC,KAAK,QACA,qBAAoB;AAC3B,SAASC,WAAW,EA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iBrM;gCACjBsM,iBAAiBvI;gCACjBwI,iBAAiB1M,SAASmE,OAAO;gCACjCwI,QAAQ,IAAMzL,aAAa;+BALtBsI,iBAOL,CAACvJ,YAAYkF,MAAM,IAAI,CAACjF,uBAC1B,KAACnE;gCAAWyI,SAAQ;gCAAQuD,OAAM;0CAC/B,8DACC;iCAEF;;yBAEJ;;;YAUL5F;0BACD,KAACtE;gBACC8N,MAAMxK;gBACNyL,SAAS,IAAMxL,WAAW;gBAC1BpB,UAAUA;gBACV6M,OAAO,CAAC7K,mBAAAA,WAAY,EAAE,EAAEM,GAAG,CAAC,CAAC0D;wBAEbA;2BAF4B;wBAC1C5G,OAAOuE,OAAOqC,KAAKpC,GAAG;wBACtBnB,OAAOkB,QAAOqC,aAAAA,KAAKtD,IAAI,YAATsD,aAAaA,KAAKpC,GAAG;oBACrC;;gBACA3B,QAAQI;gBACRyK,OAAOtM,WAAWhC,eAAegC,YAAY8D;gBAC7CyI,MAAM1L;gBACNqD,OAAOnD;gBACPyL,UAAU,CAACjJ,SAAW,KAAKD,WAAWC;;;;IAK5C,qBACE;;0BAGE,KAAC1I;gBAAiB4J,OAAOjF,SAAS0C,IAAI,IAAIvC;;YACzCsJ;;;AAGP;AACA3J,mBAAmBmN,WAAW,GAAG;AAEjC,eAAenN,mBAAkB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/campaign-detail-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 {\n mdiDeleteOutline,\n mdiEyeOutline,\n mdiPaletteOutline,\n mdiPencilOutline,\n} from '@aglyn/shared-data-mdi'\nimport {\n AppLink,\n CardDisplay,\n MdiIcon,\n useConfirmationContext,\n} from '@aglyn/shared-ui-jsx'\nimport {\n Figure,\n RateRow,\n Section,\n} from '@aglyn/shared-ui-jsx/components/measured-figures.component'\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 { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport RowActionsMenu, {\n type RowActionsMenuItem,\n} from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { ceilingedWindow } from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { useListQuery } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { PageHeaderRecord, pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n Alert,\n Box,\n Button,\n Chip,\n Divider,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport {\n collection,\n deleteField,\n documentId,\n limit,\n orderBy,\n query,\n updateDoc,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useRouter } from 'next/navigation'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useFirestoreCollection,\n useFirestoreDoc,\n} from '@aglyn/tenant-feature-instance'\nimport {\n campaignForcedListUnsubscribeSends,\n campaignListUnsubscribe,\n campaignRollup,\n campaignSendDisplay,\n campaignSiteIds,\n campaignVisibleTo,\n campaignWindowState,\n emailListTimeMs,\n type CampaignAggregate,\n type CampaignSend,\n type EmailCampaign,\n} from '@aglyn/shared-ui-email-campaigns/model'\nimport {\n CAMPAIGN_EMAILS_QUERY,\n CAMPAIGN_SEND_STATUS_OPTIONS,\n campaignContainerSearchFields,\n campaignSendsScope,\n} from '../model/campaign-list-query'\nimport CampaignComposer from './campaign-composer'\nimport CampaignEditDrawer, {\n type CampaignEditValues,\n} from './campaign-edit-drawer'\nimport {\n CampaignConversionsSection,\n CampaignDestinationsSection,\n CampaignRevenueSection,\n CampaignSequencesSection,\n} from './campaign-reach-sections'\nimport CampaignMembersSection from './campaign-members-section'\nimport CampaignReportCard from './campaign-report-card'\nimport {\n campaignContainerDoc,\n campaignSendsCollection,\n campaignSendsQuery,\n} from './campaign-queries'\nimport {\n orgSiteHubPath,\n orgSiteName,\n orgSiteOptions,\n topicCatalogHostId,\n useMarketingOrgId,\n useMarketingOrgMount,\n} from './marketing-org-mount'\nimport { useCampaignManageApi } from './use-campaign-send-api'\nimport { useEmailsHubPath } from './use-emails-hub-path'\nimport { useCampaignTopicOptions } from './use-campaign-topic-options'\n\n/** How many of a campaign's emails the detail page enumerates. */\nconst CAMPAIGN_EMAIL_CEILING = 50\n\nconst detailDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#the-campaign-report',\n excerpt:\n 'A campaign groups the emails sent to its lists. The figures here are ' +\n 'the sum across those emails, and each one keeps its own report.',\n})\n\n/**\n * A rolled-up figure, in the shared `Figure`'s shape.\n *\n * The note is where an aggregate differs from a single send's count: a total\n * measured over fewer emails than the campaign holds says which part of the\n * campaign it describes, rather than presenting a partial sum as a complete\n * one. `null` still renders as an em dash and says \"not recorded\", which is\n * the property the shared component already owns.\n */\nconst rolled = (\n value: CampaignAggregate,\n): { value: number | null; note: string } => ({\n value: value.value,\n note:\n value.value !== null && value.recorded < value.sends\n ? `across ${value.recorded} of ${value.sends} emails`\n : `across ${value.sends} email${value.sends === 1 ? '' : 's'}`,\n})\n\n/*\n * What the campaign's emails table filters by, each clause and the search on\n * the table's own Firestore query (AGL-3321, `CAMPAIGN_EMAILS_QUERY`). The\n * State column is derived from an email's counters and cannot be asked of a\n * query, so the panel offers the Status it stores.\n */\nconst SEND_FILTER_FIELDS = CAMPAIGN_EMAILS_QUERY.fields\nconst SEND_FILTER_OPTIONS = { status: CAMPAIGN_SEND_STATUS_OPTIONS }\nconst SEND_FILTER_HEADERS: Readonly<Record<string, string>> = {\n subject: 'Subject',\n status: 'Status',\n createdAtMs: 'Created',\n}\n\nexport interface CampaignDetailCardProps {\n /** The site, or `null` on the org Marketing hub. */\n hostId: string | null\n /** A campaign container id, or a send id from before containers existed. */\n campaignId: string\n /** The marketing hub URL, for the way back to the campaigns list. */\n basePath: string\n}\n\n/**\n * ONE CAMPAIGN: its lists, what it caused, what it earned, where it sent\n * people, and the emails it did all of that with.\n *\n * ## Why the emails are a section rather than the page\n *\n * A campaign reaches people by email, which is not the same as a campaign\n * BEING a list of emails. It runs over a window, against a set of audiences,\n * and the pages its links land on, the money credited to it and the\n * conversions credited to it are facts about the campaign that no single\n * message in it holds. So the body is sectioned — what it caused, what it\n * earned, where it sent people, then the mail's own figures, then its emails\n * — and each section names the population it describes.\n *\n * The ORDER is the part that says which of those the page is about. Delivery,\n * engagement and rates are mechanics of a message; a page that met the reader\n * with them and reached the outcomes only after scrolling was a mail report\n * whatever its headings claimed. `campaign-report-card.tsx` — the page a\n * campaign of one email gets — carries the same two outcome headings first,\n * for the same reason and in the same words.\n *\n * The three middle sections live in `campaign-reach-sections.tsx`, which is\n * also where the reason a campaign cannot simply DECLARE the screens and\n * forms it runs across is written down: no such edge is stored, attribution\n * is the mechanism, and all three sections join on this campaign's send ids.\n *\n * ## Why this resolves two kinds of id\n *\n * The id in `campaigns/{id}` may name a campaign CONTAINER or a single SEND,\n * and which it is is answered by reading: a container at `emailCampaigns/{id}`\n * renders this page, and anything else falls through to that send's own\n * report.\n *\n * Not every send belongs to a container. One written before campaigns grouped\n * their emails names none, its own id is the only id the URL can carry, and\n * that id is also inside the HMAC of every unsubscribe footer already\n * delivered — so a send id has to go on addressing a page rather than a 404.\n * The fall-through is what makes the container additive: no send document is\n * rewritten and no id is reassigned.\n *\n * The extra read is one document, and it buys the guarantee that a pasted\n * report link resolves whichever kind of id it carries.\n *\n * ## Under a site, and over the organization\n *\n * The container and its sends are the org's, so the same page renders on the\n * org hub with `hostId` null. What changes there is everything that is a SITE\n * fact: the emails listed are every site's rather than the ones sent as this\n * site, the forms and screens filed under the campaign are gathered from each\n * site it is placed on, the conversions are one chosen site's (they are\n * recorded per site), and writing an email first asks which site it is sent\n * as — its sender, its designs and its consent all belong to that site.\n */\nexport function CampaignDetailCard(props: CampaignDetailCardProps) {\n const { hostId, campaignId, basePath } = props\n const firestore = useFirestore()\n // The sibling hub, for the two records this page links to but does not own:\n // each message's report and the template it was built from.\n const emailsHub = useEmailsHubPath()\n const router = useRouter()\n const orgMount = useMarketingOrgMount()\n const { orgId } = useMarketingOrgId(hostId)\n const { confirm } = useConfirmationContext()\n const { enqueueSnackbar } = useSnackbar()\n const manageApi = useCampaignManageApi(hostId, orgId)\n /*\n * The site an email written here is sent AS. Under a site it is that site\n * and never asked; on the org hub it is chosen before the composer opens.\n * Empty means nobody has chosen yet.\n */\n const [composeHostId, setComposeHostId] = useState('')\n /** The site whose conversions the org hub is showing; empty until chosen. */\n const [conversionsHostId, setConversionsHostId] = useState('')\n const [composing, setComposing] = useState(false)\n const [editing, setEditing] = useState(false)\n const [saving, setSaving] = useState(false)\n const [saveError, setSaveError] = useState<string | null>(null)\n const [deleting, setDeleting] = useState(false)\n\n const { data: campaign, status } = useFirestoreDoc<EmailCampaign>(\n () => (orgId ? campaignContainerDoc(firestore, orgId, campaignId) : null),\n [firestore, orgId, campaignId],\n )\n\n /*\n * ONLY WHEN THE ID NAMES A CAMPAIGN.\n *\n * Both queries below are gated on the container having been found, because\n * the other half of this component is the single-send report — and that\n * screen's whole design is that it reads two documents whatever the size of\n * the audience. Listening unconditionally would add two collection reads to\n * every legacy report URL, which is the cost the report route was split out\n * to avoid. Not listening is what a null builder means.\n *\n * The campaign's emails come back by the field each send carries: equality\n * on one field ordered by DOCUMENT NAME. On the org hub that is all the\n * query says, and the automatic single-field index serves it. Under a site\n * the sends are also narrowed to the ones sent as that site — the scope\n * filter that makes the read provable for a site collaborator — and that\n * pair is the one composite index this page needs. Ordering on a date\n * would need that index AND would drop every send missing that particular\n * date — a sent send carries `sentAt`, a scheduled one `sendAtMs`, and\n * neither is on both. Sorted by date below, over a window this page holds\n * whole.\n *\n * One document past the ceiling, so \"this campaign has more emails than are\n * listed\" is a fact rather than a guess.\n */\n const { data: sendDocs } = useFirestoreCollection<any>(\n () => {\n const sends = campaign\n ? campaignSendsQuery(firestore, orgId, hostId)\n : null\n return sends\n ? query(\n sends,\n where('emailCampaignId', '==', campaignId),\n orderBy(documentId()),\n limit(CAMPAIGN_EMAIL_CEILING + 1),\n )\n : null\n },\n [firestore, orgId, hostId, campaignId, Boolean(campaign)],\n { idField: '$id' },\n )\n\n const { data: listDocs } = useFirestoreCollection<any>(\n () =>\n campaign && orgId\n ? query(collection(firestore, 'orgs', orgId, 'lists'), limit(50))\n : null,\n [firestore, orgId, Boolean(campaign)],\n { idField: '$id' },\n )\n\n /*\n * The org's topic catalog, read only while the EDIT DRAWER is open.\n *\n * It fills one picker in that drawer and is drawn nowhere else on this\n * page, so reading it on mount would charge every reader who came for the\n * campaign's numbers for a field they are not looking at. The composer\n * carries its own read of the same catalog, behind its own button, for the\n * same reason.\n */\n const { topics, source: topicSource } = useCampaignTopicOptions(\n topicCatalogHostId(hostId, orgMount),\n { enabled: editing },\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 { rows: readSends, truncated: sendsTruncated } = ceilingedWindow<any>(\n sendDocs,\n CAMPAIGN_EMAIL_CEILING,\n )\n /*\n * Newest first on the time each email SITS at — its send time where it has\n * one, its creation where it does not. A draft has neither `sentAt` nor\n * `sendAtMs`, so ordering on the send time alone gave every draft the key 0\n * and filed the email a merchant is in the middle of writing below mail\n * sent years ago.\n */\n const sends = useMemo(\n () =>\n [...(readSends as CampaignSend[])].sort(\n (a, b) => emailListTimeMs(b) - emailListTimeMs(a),\n ),\n [readSends],\n )\n const rollup = useMemo(() => campaignRollup(sends), [sends])\n /*\n * THE EMAILS TABLE IS ITS OWN QUERY (AGL-3321).\n *\n * The figures above are a sum over the window read above; the table under\n * them is a list a reader filters and searches, so each clause and the\n * search word go onto a query of their own — this campaign's emails\n * (`emailCampaignId == id`, and under a site the ones sent as it), newest\n * first, paged by the query. A match on the fifth page is found; nothing\n * is matched over the rows a read happened to hold. Gated on the container\n * like the window: a single send's report reads none of it.\n */\n const gridFilter = useListGridFilter({ selectFields: ['status'] })\n const sendPage = useListQuery<CampaignSend>({\n collection: campaign ? campaignSendsCollection(firestore, orgId) : null,\n declaration: CAMPAIGN_EMAILS_QUERY,\n request: {\n clauses: gridFilter.clauses,\n search: gridFilter.searchWords,\n base: [\n { path: 'emailCampaignId', op: '==', value: campaignId },\n ...campaignSendsScope(hostId),\n ],\n },\n deps: [firestore, orgId, hostId, campaignId, Boolean(campaign)],\n idField: '$id',\n })\n // The ids the two sections beneath the figures join on. Derived from the\n // window this card already holds, so neither of them reads the send list\n // again to find out which emails the campaign has.\n const sendIds = useMemo(\n () => sends.map((send) => String(send.$id)).filter(Boolean),\n [sends],\n )\n\n /*==========================================\n * SAVING THE CONTAINER, WITH THE CLIENT SDK.\n *\n * The same door the create drawer already uses. `emailCampaigns` is\n * deliberately outside the security rules' server-only exclusion list — a\n * container holds no counter, no consent record and no entitlement input,\n * so an editor who writes one cannot buy themselves a send — and giving the\n * edit a route of its own would be a second writer to keep in step with the\n * create.\n *\n * `updateDoc` rather than a merge-set, because this is an edit of a\n * document that exists: a set would CREATE a campaign at this id for\n * somebody who deleted it in another tab, which is the shape the delivery\n * webhook is careful about on the send collection for the same reason.\n *\n * A cleared date is written as `null` — the absence the model already\n * spells — and a cleared topic REMOVES the field, because the model has no\n * null topic and `campaignTopicId` is handed to the composer as one.\n *\n * `visibleTo` is written only from the org hub, and only when its drawer\n * says the placement changed. A site hub never touches it: the rules let a\n * site collaborator edit a campaign only while its scope is unchanged, and\n * a site hub has no field for it anyway.\n *=========================================*/\n const handleSave = useCallback(\n async (values: CampaignEditValues) => {\n if (saving || !orgId) return\n setSaving(true)\n setSaveError(null)\n try {\n const placement =\n !hostId && values.siteIds !== undefined\n ? { visibleTo: campaignVisibleTo(values.siteIds) }\n : {}\n await updateDoc(campaignContainerDoc(firestore, orgId, campaignId), {\n name: values.name,\n // The list's search keys (AGL-3321), from the name written here.\n ...campaignContainerSearchFields(values.name),\n startAtMs: values.startAtMs,\n endAtMs: values.endAtMs,\n listIds: values.listIds,\n topicId: values.topicId ? values.topicId : deleteField(),\n listUnsubscribe: values.listUnsubscribe,\n ...placement,\n })\n setEditing(false)\n enqueueSnackbar('Campaign updated', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n setSaveError('The campaign could not be saved')\n } finally {\n setSaving(false)\n }\n },\n [campaignId, enqueueSnackbar, firestore, hostId, orgId, saving],\n )\n\n /*==========================================\n * DELETING THE CONTAINER, WHICH IS NOT DELETING ITS MAIL.\n *\n * The route detaches every email first and then removes the campaign, so\n * what a merchant is agreeing to is the grouping going away — the emails\n * stay, keep their ids, keep their reports, and read afterwards as single\n * sends. Their unsubscribe links carry those ids inside an HMAC and go on\n * working, which is why the container can never take them with it.\n *\n * The confirmation says the count and says what a delete does NOT do. A\n * scheduled email inside the campaign still goes out at its time — stopping\n * somebody's mail is `cancel`, on that email's own page — and a merchant\n * who reads \"delete campaign\" as \"stop the campaign\" has to be told\n * otherwise before they press it, not after.\n *=========================================*/\n const handleDelete = useCallback(async () => {\n if (deleting) return\n /*\n * Emails with mail still to go: the ones waiting for their time AND the\n * ones part way through an audience larger than one batch. Both are what\n * a merchant needs warning about, and counting only `scheduled` would\n * miss the case that needs it most — a campaign that is delivering right\n * now is stored as `scheduled` too, but `rollup.scheduled` is the\n * narrower reading that excludes it.\n */\n const unfinished = rollup.scheduled + rollup.sending\n const agreed = await confirm({\n title: 'Delete this campaign?',\n description:\n (sends.length\n ? `The ${sends.length.toLocaleString()} ` +\n `${sends.length === 1 ? 'email' : 'emails'} in it are kept — ` +\n 'each keeps its own report and its unsubscribe links, and they ' +\n 'appear in the campaigns 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 setDeleting(true)\n try {\n const { response, payload } = await manageApi({\n action: 'deleteCampaign',\n campaignId,\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', { variant: 'success', persist: false })\n router.push(`${basePath}/campaigns`)\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 setDeleting(false)\n }\n }, [\n basePath,\n campaignId,\n confirm,\n deleting,\n enqueueSnackbar,\n manageApi,\n rollup.scheduled,\n rollup.sending,\n router,\n sends.length,\n ])\n\n // Still settling. Falling through to the send report here would flash \"this\n // campaign could not be loaded\" on every open of a campaign that exists —\n // and under a site nothing is read at all until the site's org is known.\n if (!campaign && (status === 'loading' || !orgId)) return null\n\n /*\n * NOT A CONTAINER — so it is a send id, and the send's own report is what\n * this URL has always meant.\n */\n if (!campaign) {\n return (\n <CampaignReportCard\n hostId={hostId}\n campaignId={campaignId}\n basePath={basePath}\n />\n )\n }\n\n const listIds = campaign.listIds ?? []\n const names = new Map<string, string>(\n (listDocs ?? []).map((list: any) => [\n String(list.$id),\n String(list.name ?? list.$id),\n ]),\n )\n /*==========================================\n * ONE EMAIL'S PAGE — the same one every other route to that record opens.\n *\n * The Emails hub's `emails/{sendId}`, which is where the messages list and\n * a template's messages table also send a reader. One record has one page:\n * a link that resolved somewhere else depending on which list it was\n * clicked in would give the same message two pages, and the reader would\n * have no way to tell which one they were on.\n *\n * `campaigns/{sendId}` on THIS hub goes on resolving as well, through the\n * fall-through at the top of this file. That is not a convenience — every\n * unsubscribe footer already delivered carries `cid={sendId}`, those\n * messages sit in inboxes forever, and merchants paste report URLs into\n * their own mail. Which link the console GENERATES and which URLs ANSWER\n * are two separate questions, and only the first is decided here.\n *\n * Nor is a redirect the answer to the second. A redirect would be another\n * thing to be wrong about an id that is inside an HMAC; a page that keeps\n * working has nothing to get wrong, and it costs nothing to leave standing.\n *=========================================*/\n /*\n * A message opens on the Emails page: the site's under a site, and over the\n * org the organization's own, which lists every site's messages.\n */\n const messagesPath = emailsHub ? `${emailsHub}/messages` : null\n const sendHref = (send: CampaignSend) =>\n messagesPath ? `${messagesPath}/${send.$id}` : undefined\n /** A template is a site's design, so it opens on the site the send used. */\n const templatesPath = (send: CampaignSend): string | null => {\n const hub = orgMount ? orgSiteHubPath(orgMount, send.hostId, 'emails') : emailsHub\n return hub ? `${hub}/templates` : null\n }\n\n /**\n * What one of this campaign's emails can be opened into.\n *\n * The same two the Emails hub offers, less the campaign — this page IS the\n * campaign. Both destinations are records the Emails console owns, so they\n * are built from {@link useEmailsHubPath} rather than from this surface's\n * own `basePath`.\n *\n * A message composed inline was built from no template, so that entry is\n * shown DISABLED with the reason rather than hidden: an absent control and\n * an inapplicable one look identical, and only one is honest.\n */\n const sendActions = (send: CampaignSend): RowActionsMenuItem[] => {\n const templateScreenId = String((send as any).templateScreenId ?? '')\n const templates = templatesPath(send)\n return [\n {\n key: 'details',\n label: 'Open report',\n icon: <MdiIcon path={mdiEyeOutline.path} size={0.8} />,\n href: sendHref(send),\n disabled: !sendHref(send),\n disabledReason: 'This site’s console URL has not resolved yet',\n },\n {\n key: 'template',\n label: 'Open its template',\n icon: <MdiIcon path={mdiPaletteOutline.path} size={0.8} />,\n href:\n templateScreenId && templates\n ? `${templates}/${templateScreenId}`\n : undefined,\n disabled: !templateScreenId || !templates,\n disabledReason: templateScreenId\n ? 'This site’s console URL has not resolved yet'\n : 'This message was not built from a template',\n },\n ]\n }\n\n /*\n * The campaign's emails, on the surface's own row grammar: the row opens\n * the email's report, its subject is also a real link so it can be\n * middle-clicked and copied, and the trailing cluster holds the actions.\n * A page of the table's own query, paged by that query.\n */\n const sendColumns: GridColDef<CampaignSend>[] = [\n {\n field: 'subject',\n headerName: 'Subject',\n flex: 1,\n minWidth: 220,\n valueGetter: (_value, send) => send.subject || send.$id,\n /*\n Plain text until the Emails hub resolves: a link with no destination\n is worse than none, and this cell is the message's subject either way.\n */\n renderCell: ({ row: send, value }) => {\n const href = sendHref(send)\n return href ? (\n <AppLink\n href={href}\n // The row's own handler would fire too and push the same route\n // twice — one history entry per back press.\n onClick={(event: { stopPropagation: () => void }) =>\n event.stopPropagation()\n }\n >\n {value}\n </AppLink>\n ) : (\n value\n )\n },\n },\n {\n /*\n WHAT THE EMAIL IS DOING, not the field it stores.\n\n This branched on the status, which reads \"Scheduled\" about an email\n that has delivered five hundred messages and is between batches — the\n stored state the processor claims to resume it. The derivation reads\n the counters beside the status; the due date is appended only where\n there is genuinely nothing delivered yet, which is the one case a time\n answers.\n */\n field: 'state',\n headerName: 'State',\n width: 220,\n valueGetter: (_value, send) => {\n const display = campaignSendDisplay(send)\n return display.state === 'pending' && send.sendAtMs\n ? `${display.label} · ${new Date(send.sendAtMs).toLocaleString()}`\n : display.label\n },\n renderCell: ({ row: send, value }) => {\n const state = campaignSendDisplay(send).state\n return (\n <Chip\n size=\"small\"\n color={\n state === 'sending' ? 'info' : state === 'stopped' ? 'warning' : undefined\n }\n label={value}\n />\n )\n },\n },\n {\n /*\n Sent over addressed, on one line: the two figures only mean anything\n beside each other, and the gap between them is the suppression list\n doing its work.\n */\n field: 'sent',\n headerName: 'Sent',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 110,\n valueGetter: (_value, send) => Number(send.stats?.sent ?? 0),\n renderCell: ({ row: send }) =>\n `${send.stats?.sent ?? 0}/${send.stats?.recipients ?? 0}`,\n },\n {\n field: 'opens',\n headerName: 'Opens',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 100,\n valueGetter: (_value, send) => Number(send.stats?.opens ?? 0),\n valueFormatter: (value: number) => value.toLocaleString(),\n },\n {\n field: 'clicks',\n headerName: 'Clicks',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 100,\n valueGetter: (_value, send) => Number(send.stats?.clicks ?? 0),\n valueFormatter: (value: number) => value.toLocaleString(),\n },\n listActionsColumn(\n (send: CampaignSend) => (\n <ListRowActions\n label={String(send.subject || send.$id)}\n items={sendActions(send)}\n />\n ),\n { width: 72 },\n ),\n ]\n\n const windowState = campaignWindowState(campaign, Date.now())\n /*\n * The mail-client unsubscribe button (AGL-3307): the campaign's setting,\n * and the emails whose header the bulk guard turned back on while it was\n * off — read off the sends this page already holds, each of which records\n * what it did and why.\n */\n const listUnsubscribeOn = campaignListUnsubscribe(campaign)\n const forcedSends = campaignForcedListUnsubscribeSends(sends)\n const start = campaign.startAtMs\n ? new Date(campaign.startAtMs).toLocaleDateString()\n : ''\n const end = campaign.endAtMs\n ? new Date(campaign.endAtMs).toLocaleDateString()\n : ''\n\n /*\n * THE SITES IT IS PLACED ON, which the org hub needs three times over: the\n * forms and screens filed under it are gathered from each of them, its\n * conversions are read for one of them, and an email written here is sent\n * as one of them. Every site when it is placed everywhere. Under a site the\n * answer is that site, and none of this is read.\n */\n const placedIds = campaignSiteIds(campaign)\n const placedSites = orgMount\n ? orgMount.hosts.filter(\n (site) => placedIds === null || placedIds.includes(site.id),\n )\n : []\n const conversionsHost =\n hostId ?? (conversionsHostId || placedSites[0]?.id || '')\n const conversionsBasePath = hostId\n ? basePath\n : orgSiteHubPath(orgMount, conversionsHost, 'marketing')\n /** Asked only when there is a choice to make; one site answers itself. */\n const writeAsHostId =\n hostId ??\n (placedSites.length === 1 ? placedSites[0].id : composeHostId)\n\n /* The card, named so the page chrome above it is a plain list of\n what this surface publishes upward. */\n const card = (\n <CardDisplay\n header={'Campaign'}\n subheader={\n start || end\n ? `${start || 'Open'} – ${end || 'open-ended'}`\n : 'No campaign dates'\n }\n help={detailDocsHelp}\n HeaderProps={{\n /*\n NAVIGATION, THEN THE OVERFLOW.\n\n Editing and deleting a campaign live here rather than on the\n campaigns table, because a record is edited on its own page in this\n console. `RowActionsMenu` is named for table rows and its rendering\n is not — a kebab and a menu whose items carry `destructive` and\n `disabled` — so reusing it is what keeps this overflow behaving like\n every other one on the surface, including the email page's.\n */\n action: (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={`${basePath}/campaigns`}\n size=\"small\"\n color=\"primary\"\n >\n {'All campaigns'}\n </Button>\n <RowActionsMenu\n label={campaign.name || 'Campaign'}\n items={[\n {\n key: 'edit',\n label: 'Edit campaign',\n icon: <MdiIcon path={mdiPencilOutline.path} size={0.8} />,\n onClick: () => {\n setSaveError(null)\n setEditing(true)\n },\n },\n {\n key: 'delete',\n label: 'Delete campaign',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: deleting,\n disabledReason: 'This campaign is being deleted',\n onClick: () => void handleDelete(),\n },\n ]}\n />\n </Stack>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Chip size=\"small\" label={windowState} />\n {listIds.length ? (\n listIds.map((id) => (\n <Chip\n key={id}\n size=\"small\"\n variant=\"outlined\"\n label={names.get(id) ?? id}\n />\n ))\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'No lists assigned — its emails pick their own audience'}\n </Typography>\n )}\n </Stack>\n {orgMount ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {placedIds === null\n ? 'Offered on every site'\n : placedIds.length\n ? `Offered on ${placedIds\n .map((id) => orgSiteName(orgMount, id))\n .join(', ')}`\n : 'Not offered on any site yet — edit the campaign to place it'}\n </Typography>\n ) : null}\n\n <Typography variant=\"body2\" color=\"text.secondary\">\n {listUnsubscribeOn\n ? 'Mail-client unsubscribe button: on'\n : 'Mail-client unsubscribe button: off — the footer link is ' +\n 'the way out, and the button comes back for any email that ' +\n 'would make your organization a bulk sender'}\n </Typography>\n {forcedSends.length ? (\n <Alert severity=\"info\">\n {`The mail-client unsubscribe button was turned back on for ` +\n `${forcedSends.length === 1 ? 'one email' : `${forcedSends.length.toLocaleString()} emails`} ` +\n 'in this campaign, though the campaign has it off. '}\n {forcedSends\n .map(\n (send) =>\n `${send.subject || send.$id}: ` +\n (send.listUnsubscribe?.detail ||\n 'turned back on by the bulk-sender guard.'),\n )\n .join(' ')}\n </Alert>\n ) : null}\n\n <Divider />\n {/*\n A CAMPAIGN IS NOT ONLY ITS MAIL, and it leads with the part that\n is not.\n\n What the campaign CAUSED and where it SENT people are facts about the\n campaign; delivery, engagement and rates are mechanics of the\n messages it used, and the list of those messages is one section among\n several rather than the page. Ordering the mail first said the\n opposite in the only way a page can — by what a reader meets before\n they scroll — and a campaign of ONE email says it loudest, which is\n why `campaign-report-card.tsx` carries these two headings in this\n order too.\n\n All three sections join on the campaign's own send ids, which is the\n only handle the attribution, revenue and click-report collections\n offer — see `campaign-reach-sections.tsx` for why no other join\n exists, and why the web channel is named there rather than quietly\n omitted.\n */}\n {/*\n Conversions are recorded per SITE — they are that site's visitors —\n so the org hub reads them for one site at a time, defaulting to the\n first site the campaign is placed on.\n */}\n {orgMount && placedSites.length > 1 ? (\n <TextField\n select\n size=\"small\"\n label=\"Conversions on\"\n value={conversionsHost}\n onChange={(event) => setConversionsHostId(event.target.value)}\n sx={{ maxWidth: 320 }}\n >\n {placedSites.map((site) => (\n <MenuItem key={site.id} value={site.id}>\n {site.name || site.subdomain || site.id}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {conversionsHost ? (\n <CampaignConversionsSection\n key={conversionsHost}\n hostId={conversionsHost}\n sendIds={sendIds}\n truncated={sendsTruncated}\n basePath={conversionsBasePath}\n />\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Conversions are counted per site, and this campaign is not ' +\n 'placed on one yet.'}\n </Typography>\n )}\n\n <Divider />\n {/*\n WHAT ITS SEQUENCES PRODUCED (AGL-3254), beside what its mail caused:\n a sequence in this campaign is a rep's one-to-one outreach, and its\n enrollments, sends, replies, meetings and conversions are the\n campaign's numbers too. Joined on the container's own id, since a\n sequence's emails are not the campaign's sends.\n */}\n <CampaignSequencesSection orgId={orgId} campaignId={campaignId} />\n\n <Divider />\n {/*\n WHAT IT EARNED, between what it caused and where it sent people —\n the order `campaign-report-card.tsx` puts these three in, so a\n campaign of one email and a campaign of ten answer the merchant's\n questions in the same sequence.\n\n How many messages a container holds is not a fact about whether its\n revenue is knowable, so the money question is answered here whatever\n the count. Reading it costs one record per email, so it asks first —\n see `campaign-reach-sections.tsx` for that bargain, and for why the\n currencies are reported apart and never totalled.\n */}\n <CampaignRevenueSection\n orgId={orgId}\n sendIds={sendIds}\n truncated={sendsTruncated}\n />\n\n <Divider />\n <CampaignDestinationsSection\n orgId={orgId}\n sendIds={sendIds}\n truncated={sendsTruncated}\n />\n\n <Divider />\n {/*\n WHAT THE MERCHANT SAID BELONGS HERE, under what the visitors did.\n\n Everything above this line is measured — the conversions, the money\n and the pages the mail's own links pointed at, all joined on this\n campaign's send ids. This section is the only one on the page that\n reports a DECLARATION: a screen or a form carrying this campaign's\n id in its own document because somebody put it there.\n\n It sits after the evidence deliberately. A reader who met the\n assigned list first would take it for the campaign's reach, and the\n two are not the same list — a landing page can be assigned to a\n campaign no email ever linked to, and a campaign's mail can drive\n traffic to a page assigned to nothing.\n\n The dates go with it. A form's counters are lifetime, so a campaign\n with a window has to be able to confine them to its own months; a\n campaign without one is told so, and says its figures are lifetime\n rather than implying they are its own.\n */}\n {hostId ? (\n <CampaignMembersSection\n hostId={hostId}\n campaignId={campaignId}\n startAtMs={campaign.startAtMs}\n endAtMs={campaign.endAtMs}\n />\n ) : (\n /*\n * Forms and screens are a site's records, so on the org hub each\n * site the campaign is placed on answers for its own. One section\n * per site keeps each one's figures and ceilings its own rather\n * than merging lists that were bounded separately.\n */\n placedSites.map((site) => (\n <CampaignMembersSection\n key={site.id}\n hostId={site.id}\n siteName={site.name || site.subdomain || site.id}\n campaignId={campaignId}\n startAtMs={campaign.startAtMs}\n endAtMs={campaign.endAtMs}\n />\n ))\n )}\n\n <Divider />\n {/*\n THE MAIL'S OWN FIGURES, under the outcomes rather than over them.\n\n The sum over the campaign's emails, not a second set of counters.\n Nothing is stored per campaign: a rollup document would have to be\n kept true against every delivery event of every email in it, and the\n numbers it duplicates are already on the sends this page reads.\n\n Drawn by the shared figures so a campaign's rate and a single\n message's read the same way — denominator named on the line, and an\n em dash rather than a zero where nothing was recorded.\n */}\n <Section title=\"The mail, across this campaign\">\n <Stack direction=\"row\" spacing={3} sx={{ flexWrap: 'wrap' }}>\n <Figure label=\"Addressed\" {...rolled(rollup.addressed)} />\n <Figure label=\"Sent\" {...rolled(rollup.sent)} />\n <Figure label=\"Delivered\" {...rolled(rollup.delivered)} />\n <Figure label=\"Opens\" {...rolled(rollup.opens)} />\n <Figure label=\"Clicks\" {...rolled(rollup.clicks)} />\n <Figure label=\"Unsubscribed\" {...rolled(rollup.unsubscribes)} />\n </Stack>\n </Section>\n <Stack spacing={0.5}>\n <RateRow label=\"Open rate\" rate={rollup.openRate} />\n <RateRow label=\"Click rate\" rate={rollup.clickRate} />\n <RateRow label=\"Unsubscribe rate\" rate={rollup.unsubscribeRate} />\n </Stack>\n\n <Divider />\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', justifyContent: 'space-between' }}\n >\n {/*\n The section rail's own heading style, so this reads as one section\n among the others rather than as the page's subject.\n */}\n <Typography variant=\"overline\" color=\"text.secondary\">\n {`Emails (${sends.length})`}\n </Typography>\n <Button\n size=\"small\"\n variant={composing ? 'text' : 'contained'}\n onClick={() => setComposing((open) => !open)}\n >\n {composing ? 'Close composer' : 'Write an email'}\n </Button>\n </Stack>\n {sends.length ? (\n <Stack spacing={0.5}>\n <ListFilterChips\n fields={SEND_FILTER_FIELDS}\n headers={SEND_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={SEND_FILTER_OPTIONS}\n />\n <ListQueryNotices\n refused={listQueryRefusals(sendPage.plan.refused, {\n fields: SEND_FILTER_FIELDS,\n headers: SEND_FILTER_HEADERS,\n options: SEND_FILTER_OPTIONS,\n })}\n notices={sendPage.plan.notices}\n />\n <ListTable\n aria-label=\"The campaign's emails\"\n rows={sendPage.rows}\n columns={listFilterGridColumns(\n sendColumns as GridColDef[],\n SEND_FILTER_FIELDS,\n SEND_FILTER_OPTIONS,\n SEND_FILTER_HEADERS,\n )}\n rowHeight={TABLE_ROW_HEIGHT}\n onOpen={(_id, send) => {\n const href = sendHref(send)\n if (href) router.push(href)\n }}\n loading={sendPage.status === 'loading'}\n /*\n * The panel and the search are the grid's; every clause and the\n * search word are on the table'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 SEND_FILTER_FIELDS,\n sendColumns.map((column) => String(column.field)),\n ),\n },\n }}\n noRowsLabel=\"No emails match these filters\"\n />\n <ListPagination\n page={sendPage.page}\n pageSize={sendPage.pageSize}\n rowCount={sendPage.rows.length}\n hasMore={sendPage.hasMore}\n onPageChange={sendPage.setPage}\n onPageSizeChange={sendPage.setPageSize}\n />\n {sendsTruncated ? (\n <Alert severity=\"info\">\n {`The figures above cover ${CAMPAIGN_EMAIL_CEILING} of this ` +\n 'campaign’s emails. It has sent more; the table lists ' +\n 'every one of them.'}\n </Alert>\n ) : null}\n </Stack>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No emails in this campaign yet.'}\n </Typography>\n )}\n\n {/*\n THE COMPOSER, ON DEMAND.\n\n It opens listens of its own — the site's email designs, the org's\n lists and segments, the running experiments — and this page is also\n where somebody arrives to read numbers. Mounting it unasked would\n make every reader pay for a composer they did not open, which is the\n same cost the campaign report was split onto its own route to avoid.\n */}\n {composing ? (\n <Box>\n <Divider sx={{ mb: 2 }} />\n {/*\n WHICH SITE IT IS SENT AS, asked first on the org hub. The sender,\n the designs, the consent a recipient gave and the unsubscribe\n signature are all one site's, so the composer cannot open\n without one — and the choice is limited to the sites this\n campaign is placed on.\n */}\n {!hostId && placedSites.length > 1 ? (\n <TextField\n select\n size=\"small\"\n label=\"Send as\"\n value={composeHostId}\n onChange={(event) => setComposeHostId(event.target.value)}\n helperText=\"The site this email is sent from — its sender, designs and unsubscribe page\"\n sx={{ mb: 2, maxWidth: 420 }}\n fullWidth\n >\n {placedSites.map((site) => (\n <MenuItem key={site.id} value={site.id}>\n {site.name || site.subdomain || site.id}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {writeAsHostId ? (\n <CampaignComposer\n key={writeAsHostId}\n hostId={writeAsHostId}\n emailCampaignId={campaignId}\n campaignListIds={listIds}\n campaignTopicId={campaign.topicId}\n onSent={() => setComposing(false)}\n />\n ) : !placedSites.length && !hostId ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Place this campaign on a site before writing an email in ' +\n 'it — every email is sent as one site.'}\n </Typography>\n ) : null}\n </Box>\n ) : null}\n </Stack>\n {/*\n THE EDIT DRAWER, on the campaign's own page.\n\n Its list picker reads the same `listDocs` the chips above already\n cost, so opening it adds one read — the topic catalog — and only\n while it is open.\n */}\n {/* Draws nothing: the zone the topic catalog's owner answers through. */}\n {topicSource}\n <CampaignEditDrawer\n open={editing}\n onClose={() => setEditing(false)}\n campaign={campaign}\n lists={(listDocs ?? []).map((list: any) => ({\n value: String(list.$id),\n label: String(list.name ?? list.$id),\n }))}\n topics={topicOptions}\n sites={orgMount ? orgSiteOptions(orgMount) : undefined}\n busy={saving}\n error={saveError}\n onSubmit={(values) => void handleSave(values)}\n />\n </CardDisplay>\n )\n\n return (\n <>\n {/* The page heading and the trail name the campaign; this card is\n then free to say what it holds rather than repeating the title. */}\n <PageHeaderRecord title={campaign.name || campaignId} />\n {card}\n </>\n )\n}\nCampaignDetailCard.displayName = 'CampaignDetailCard'\n\nexport default CampaignDetailCard\n"],"names":["mdiDeleteOutline","mdiEyeOutline","mdiPaletteOutline","mdiPencilOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","Figure","RateRow","Section","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListRowActions","ListTable","listActionsColumn","hiddenFilterVisibility","listFilterGridColumns","useListGridFilter","RowActionsMenu","TABLE_ROW_HEIGHT","ceilingedWindow","useListQuery","PageHeaderRecord","pluginDocsHelp","Alert","Box","Button","Chip","Divider","MenuItem","Stack","TextField","Typography","collection","deleteField","documentId","limit","orderBy","query","updateDoc","where","useCallback","useMemo","useState","useRouter","useSnackbar","useFirestore","useFirestoreCollection","useFirestoreDoc","campaignForcedListUnsubscribeSends","campaignListUnsubscribe","campaignRollup","campaignSendDisplay","campaignSiteIds","campaignVisibleTo","campaignWindowState","emailListTimeMs","CAMPAIGN_EMAILS_QUERY","CAMPAIGN_SEND_STATUS_OPTIONS","campaignContainerSearchFields","campaignSendsScope","CampaignComposer","CampaignEditDrawer","CampaignConversionsSection","CampaignDestinationsSection","CampaignRevenueSection","CampaignSequencesSection","CampaignMembersSection","CampaignReportCard","campaignContainerDoc","campaignSendsCollection","campaignSendsQuery","orgSiteHubPath","orgSiteName","orgSiteOptions","topicCatalogHostId","useMarketingOrgId","useMarketingOrgMount","useCampaignManageApi","useEmailsHubPath","useCampaignTopicOptions","CAMPAIGN_EMAIL_CEILING","detailDocsHelp","anchor","excerpt","rolled","value","note","recorded","sends","SEND_FILTER_FIELDS","fields","SEND_FILTER_OPTIONS","status","SEND_FILTER_HEADERS","subject","createdAtMs","CampaignDetailCard","props","campaign","placedSites","hostId","campaignId","basePath","firestore","emailsHub","router","orgMount","orgId","confirm","enqueueSnackbar","manageApi","composeHostId","setComposeHostId","conversionsHostId","setConversionsHostId","composing","setComposing","editing","setEditing","saving","setSaving","saveError","setSaveError","deleting","setDeleting","data","sendDocs","Boolean","idField","listDocs","topics","source","topicSource","enabled","topicOptions","map","topic","id","label","name","rows","readSends","truncated","sendsTruncated","sort","a","b","rollup","gridFilter","selectFields","sendPage","declaration","request","clauses","search","searchWords","base","path","op","deps","sendIds","send","String","$id","filter","handleSave","values","placement","siteIds","undefined","visibleTo","startAtMs","endAtMs","listIds","topicId","listUnsubscribe","variant","persist","error","console","handleDelete","unfinished","scheduled","sending","agreed","title","description","length","toLocaleString","confirmationText","then","catch","response","payload","action","ok","allowDuplicate","push","names","Map","list","messagesPath","sendHref","templatesPath","hub","sendActions","templateScreenId","templates","key","icon","size","href","disabled","disabledReason","sendColumns","field","headerName","flex","minWidth","valueGetter","_value","renderCell","row","onClick","event","stopPropagation","width","display","state","sendAtMs","Date","color","type","align","headerAlign","Number","stats","sent","recipients","opens","valueFormatter","clicks","items","windowState","now","listUnsubscribeOn","forcedSends","start","toLocaleDateString","end","placedIds","hosts","site","includes","conversionsHost","conversionsBasePath","writeAsHostId","card","header","subheader","help","HeaderProps","direction","spacing","sx","alignItems","component","componentVariant","nativeButton","destructive","contentGutterX","contentGutterY","get","join","severity","detail","select","onChange","target","maxWidth","subdomain","siteName","flexWrap","addressed","delivered","unsubscribes","rate","openRate","clickRate","unsubscribeRate","justifyContent","open","headers","setClauses","options","refused","plan","notices","aria-label","columns","rowHeight","onOpen","_id","loading","filterMode","filterModel","onFilterModelChange","quickFilter","disableColumnSorting","hideFooter","initialState","columnVisibilityModel","column","noRowsLabel","page","pageSize","rowCount","hasMore","onPageChange","setPage","onPageSizeChange","setPageSize","mb","helperText","fullWidth","emailCampaignId","campaignListIds","campaignTopicId","onSent","onClose","lists","sites","busy","onSubmit","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,gBAAgB,EAChBC,aAAa,EACbC,iBAAiB,EACjBC,gBAAgB,QACX,yBAAwB;AAC/B,SACEC,OAAO,EACPC,WAAW,EACXC,OAAO,EACPC,sBAAsB,QACjB,uBAAsB;AAC7B,SACEC,MAAM,EACNC,OAAO,EACPC,OAAO,QACF,6DAA4D;AACnE,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,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,OAAOC,oBAEA,6DAA4D;AACnE,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,eAAe,QAAQ,+DAA8D;AAC9F,SAASC,YAAY,QAAQ,sDAAqD;AAClF,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,eAAc;AAC/D,SACEC,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,OAAO,EACPC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AAEtB,SACEC,UAAU,EACVC,WAAW,EACXC,UAA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,CAAC7J,YAAYwF,MAAM,IAAI,CAACvF,uBAC1B,KAACrE;gCAAWiJ,SAAQ;gCAAQuD,OAAM;0CAC/B,8DACC;iCAEF;;yBAEJ;;;YAULnG;0BACD,KAACvE;gBACCsO,MAAM9K;gBACNoN,SAAS,IAAMnN,WAAW;gBAC1BpB,UAAUA;gBACVwO,OAAO,CAACzM,mBAAAA,WAAY,EAAE,EAAEM,GAAG,CAAC,CAACiE;wBAEbA;2BAF4B;wBAC1CnH,OAAO6E,OAAOsC,KAAKrC,GAAG;wBACtBzB,OAAOwB,QAAOsC,aAAAA,KAAK7D,IAAI,YAAT6D,aAAaA,KAAKrC,GAAG;oBACrC;;gBACAjC,QAAQI;gBACRqM,OAAOjO,WAAWjC,eAAeiC,YAAY+D;gBAC7CmK,MAAMrN;gBACN2D,OAAOzD;gBACPoN,UAAU,CAACvK,SAAW,KAAKD,WAAWC;;;;IAK5C,qBACE;;0BAGE,KAACjJ;gBAAiBoK,OAAOvF,SAASyC,IAAI,IAAItC;;YACzC4J;;;AAGP;AACAjK,mBAAmB8O,WAAW,GAAG;AAEjC,eAAe9O,mBAAkB"}
@@ -48,6 +48,17 @@ export declare function campaignContainersQuery(firestore: Firestore, orgId: str
48
48
  * site when `hostId` names a site; `null` until the org is known.
49
49
  */
50
50
  export declare function campaignSendsQuery(firestore: Firestore, orgId: string | null, hostId: string | null): Query | null;
51
+ /**
52
+ * The two collections UNSCOPED, for a paged list that puts its scope on its
53
+ * query plan (AGL-3321): `campaignSendsScope` / `campaignContainersScope` in
54
+ * `model/campaign-list-query.ts` carry the site's clause there, beside the
55
+ * list's own. A site hub's sends are asked `hostId == {site}` rather than by
56
+ * `visibleTo`, so search keeps the query's one array clause; the rules
57
+ * admit that read for the site's collaborators too.
58
+ */
59
+ export declare function campaignSendsCollection(firestore: Firestore, orgId: string | null): Query | null;
60
+ /** `orgs/{orgId}/emailCampaigns`, unscoped — see {@link campaignSendsCollection}. */
61
+ export declare function campaignContainersCollection(firestore: Firestore, orgId: string | null): Query | null;
51
62
  /** One container, `orgs/{orgId}/emailCampaigns/{id}`. */
52
63
  export declare function campaignContainerDoc(firestore: Firestore, orgId: string, campaignId: string): DocumentReference;
53
64
  /** One send, `orgs/{orgId}/campaigns/{sendId}`. */
@@ -56,6 +56,19 @@ import { collection, doc, query, where } from "firebase/firestore";
56
56
  hostScopeToken(hostId)
57
57
  ])) : sends;
58
58
  }
59
+ /**
60
+ * The two collections UNSCOPED, for a paged list that puts its scope on its
61
+ * query plan (AGL-3321): `campaignSendsScope` / `campaignContainersScope` in
62
+ * `model/campaign-list-query.ts` carry the site's clause there, beside the
63
+ * list's own. A site hub's sends are asked `hostId == {site}` rather than by
64
+ * `visibleTo`, so search keeps the query's one array clause; the rules
65
+ * admit that read for the site's collaborators too.
66
+ */ export function campaignSendsCollection(firestore, orgId) {
67
+ return orgId ? collection(firestore, ...orgCampaignSendsPath(orgId)) : null;
68
+ }
69
+ /** `orgs/{orgId}/emailCampaigns`, unscoped — see {@link campaignSendsCollection}. */ export function campaignContainersCollection(firestore, orgId) {
70
+ return orgId ? collection(firestore, ...orgEmailCampaignsPath(orgId)) : null;
71
+ }
59
72
  /** One container, `orgs/{orgId}/emailCampaigns/{id}`. */ export function campaignContainerDoc(firestore, orgId, campaignId) {
60
73
  return doc(firestore, ...orgEmailCampaignsPath(orgId), campaignId);
61
74
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/campaign-queries.ts"],"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\nimport { hostScopeToken, scopeTokensForHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n orgCampaignSendsPath,\n orgCampaignSequenceReportsPath,\n orgEmailCampaignsPath,\n} from '@aglyn/shared-ui-email-campaigns/model/campaign-container'\nimport {\n collection,\n doc,\n query,\n where,\n type DocumentReference,\n type Firestore,\n type Query,\n} from 'firebase/firestore'\n\n/**\n * WHERE A CAMPAIGN AND ITS SENDS ARE READ FROM, at either level of the hub.\n *\n * Both collections belong to the organization: containers at\n * `orgs/{orgId}/emailCampaigns`, sends at `orgs/{orgId}/campaigns`, each\n * send's rollups under it at `…/reports/{name}`. Spelled once here so no card\n * rebuilds a path from memory, and so the one rule that makes a site hub's\n * read legal is in one place:\n *\n * **A site hub's LIST reads are filtered by scope.** The rules let an\n * org-wide member read every document and a site collaborator only those\n * whose `visibleTo` names a scope they hold. A query the rules cannot prove\n * document by document is refused whole, so a site hub asks exactly for what\n * that site may see — a container placed on every site (`'org'`) or on this\n * one (`'host:{id}'`), and a send sent AS this site. An org-wide member loses\n * nothing by the filter at a site: those are the campaigns the site shows.\n *\n * The ORG hub is admitted only to org-wide members, so its reads are\n * unfiltered.\n *\n * One `array-contains-any` per query is Firestore's limit, so no caller adds\n * a second array clause to these; per-document reads need no filter at all.\n */\n\n/**\n * `orgs/{orgId}/emailCampaigns`, narrowed to one site's placements when\n * `hostId` names a site; `null` until the org is known.\n */\nexport function campaignContainersQuery(\n firestore: Firestore,\n orgId: string | null,\n hostId: string | null,\n): Query | null {\n if (!orgId) return null\n const containers = collection(firestore, ...orgEmailCampaignsPath(orgId))\n return hostId\n ? query(\n containers,\n where('visibleTo', 'array-contains-any', scopeTokensForHost(hostId)),\n )\n : containers\n}\n\n/**\n * `orgs/{orgId}/campaigns` — the sends — narrowed to the ones sent as one\n * site when `hostId` names a site; `null` until the org is known.\n */\nexport function campaignSendsQuery(\n firestore: Firestore,\n orgId: string | null,\n hostId: string | null,\n): Query | null {\n if (!orgId) return null\n const sends = collection(firestore, ...orgCampaignSendsPath(orgId))\n return hostId\n ? query(\n sends,\n where('visibleTo', 'array-contains-any', [hostScopeToken(hostId)]),\n )\n : sends\n}\n\n/** One container, `orgs/{orgId}/emailCampaigns/{id}`. */\nexport function campaignContainerDoc(\n firestore: Firestore,\n orgId: string,\n campaignId: string,\n): DocumentReference {\n return doc(firestore, ...orgEmailCampaignsPath(orgId), campaignId)\n}\n\n/** One send, `orgs/{orgId}/campaigns/{sendId}`. */\nexport function campaignSendDoc(\n firestore: Firestore,\n orgId: string,\n sendId: string,\n): DocumentReference {\n return doc(firestore, ...orgCampaignSendsPath(orgId), sendId)\n}\n\n/** One of a send's rollups, `orgs/{orgId}/campaigns/{sendId}/reports/{name}`. */\nexport function campaignSendReportDoc(\n firestore: Firestore,\n orgId: string,\n sendId: string,\n report: 'links' | 'revenue' | 'conversions' | 'reached',\n): DocumentReference {\n return doc(\n firestore,\n ...orgCampaignSendsPath(orgId),\n sendId,\n 'reports',\n report,\n )\n}\n\n/** A container's sequence rollup, `orgs/{orgId}/campaignSequenceReports/{id}`. */\nexport function campaignSequenceReportDoc(\n firestore: Firestore,\n orgId: string,\n campaignId: string,\n): DocumentReference {\n return doc(firestore, ...orgCampaignSequenceReportsPath(orgId), campaignId)\n}\n"],"names":["hostScopeToken","scopeTokensForHost","orgCampaignSendsPath","orgCampaignSequenceReportsPath","orgEmailCampaignsPath","collection","doc","query","where","campaignContainersQuery","firestore","orgId","hostId","containers","campaignSendsQuery","sends","campaignContainerDoc","campaignId","campaignSendDoc","sendId","campaignSendReportDoc","report","campaignSequenceReportDoc"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,cAAc,EAAEC,kBAAkB,QAAQ,sCAAqC;AACxF,SACEC,oBAAoB,EACpBC,8BAA8B,EAC9BC,qBAAqB,QAChB,4DAA2D;AAClE,SACEC,UAAU,EACVC,GAAG,EACHC,KAAK,EACLC,KAAK,QAIA,qBAAoB;AAE3B;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED;;;CAGC,GACD,OAAO,SAASC,wBACdC,SAAoB,EACpBC,KAAoB,EACpBC,MAAqB;IAErB,IAAI,CAACD,OAAO,OAAO;IACnB,MAAME,aAAaR,WAAWK,cAAcN,sBAAsBO;IAClE,OAAOC,SACHL,MACEM,YACAL,MAAM,aAAa,sBAAsBP,mBAAmBW,YAE9DC;AACN;AAEA;;;CAGC,GACD,OAAO,SAASC,mBACdJ,SAAoB,EACpBC,KAAoB,EACpBC,MAAqB;IAErB,IAAI,CAACD,OAAO,OAAO;IACnB,MAAMI,QAAQV,WAAWK,cAAcR,qBAAqBS;IAC5D,OAAOC,SACHL,MACEQ,OACAP,MAAM,aAAa,sBAAsB;QAACR,eAAeY;KAAQ,KAEnEG;AACN;AAEA,uDAAuD,GACvD,OAAO,SAASC,qBACdN,SAAoB,EACpBC,KAAa,EACbM,UAAkB;IAElB,OAAOX,IAAII,cAAcN,sBAAsBO,QAAQM;AACzD;AAEA,iDAAiD,GACjD,OAAO,SAASC,gBACdR,SAAoB,EACpBC,KAAa,EACbQ,MAAc;IAEd,OAAOb,IAAII,cAAcR,qBAAqBS,QAAQQ;AACxD;AAEA,+EAA+E,GAC/E,OAAO,SAASC,sBACdV,SAAoB,EACpBC,KAAa,EACbQ,MAAc,EACdE,MAAuD;IAEvD,OAAOf,IACLI,cACGR,qBAAqBS,QACxBQ,QACA,WACAE;AAEJ;AAEA,gFAAgF,GAChF,OAAO,SAASC,0BACdZ,SAAoB,EACpBC,KAAa,EACbM,UAAkB;IAElB,OAAOX,IAAII,cAAcP,+BAA+BQ,QAAQM;AAClE"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/campaign-queries.ts"],"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\nimport { hostScopeToken, scopeTokensForHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport {\n orgCampaignSendsPath,\n orgCampaignSequenceReportsPath,\n orgEmailCampaignsPath,\n} from '@aglyn/shared-ui-email-campaigns/model/campaign-container'\nimport {\n collection,\n doc,\n query,\n where,\n type DocumentReference,\n type Firestore,\n type Query,\n} from 'firebase/firestore'\n\n/**\n * WHERE A CAMPAIGN AND ITS SENDS ARE READ FROM, at either level of the hub.\n *\n * Both collections belong to the organization: containers at\n * `orgs/{orgId}/emailCampaigns`, sends at `orgs/{orgId}/campaigns`, each\n * send's rollups under it at `…/reports/{name}`. Spelled once here so no card\n * rebuilds a path from memory, and so the one rule that makes a site hub's\n * read legal is in one place:\n *\n * **A site hub's LIST reads are filtered by scope.** The rules let an\n * org-wide member read every document and a site collaborator only those\n * whose `visibleTo` names a scope they hold. A query the rules cannot prove\n * document by document is refused whole, so a site hub asks exactly for what\n * that site may see — a container placed on every site (`'org'`) or on this\n * one (`'host:{id}'`), and a send sent AS this site. An org-wide member loses\n * nothing by the filter at a site: those are the campaigns the site shows.\n *\n * The ORG hub is admitted only to org-wide members, so its reads are\n * unfiltered.\n *\n * One `array-contains-any` per query is Firestore's limit, so no caller adds\n * a second array clause to these; per-document reads need no filter at all.\n */\n\n/**\n * `orgs/{orgId}/emailCampaigns`, narrowed to one site's placements when\n * `hostId` names a site; `null` until the org is known.\n */\nexport function campaignContainersQuery(\n firestore: Firestore,\n orgId: string | null,\n hostId: string | null,\n): Query | null {\n if (!orgId) return null\n const containers = collection(firestore, ...orgEmailCampaignsPath(orgId))\n return hostId\n ? query(\n containers,\n where('visibleTo', 'array-contains-any', scopeTokensForHost(hostId)),\n )\n : containers\n}\n\n/**\n * `orgs/{orgId}/campaigns` — the sends — narrowed to the ones sent as one\n * site when `hostId` names a site; `null` until the org is known.\n */\nexport function campaignSendsQuery(\n firestore: Firestore,\n orgId: string | null,\n hostId: string | null,\n): Query | null {\n if (!orgId) return null\n const sends = collection(firestore, ...orgCampaignSendsPath(orgId))\n return hostId\n ? query(\n sends,\n where('visibleTo', 'array-contains-any', [hostScopeToken(hostId)]),\n )\n : sends\n}\n\n/**\n * The two collections UNSCOPED, for a paged list that puts its scope on its\n * query plan (AGL-3321): `campaignSendsScope` / `campaignContainersScope` in\n * `model/campaign-list-query.ts` carry the site's clause there, beside the\n * list's own. A site hub's sends are asked `hostId == {site}` rather than by\n * `visibleTo`, so search keeps the query's one array clause; the rules\n * admit that read for the site's collaborators too.\n */\nexport function campaignSendsCollection(\n firestore: Firestore,\n orgId: string | null,\n): Query | null {\n return orgId ? collection(firestore, ...orgCampaignSendsPath(orgId)) : null\n}\n\n/** `orgs/{orgId}/emailCampaigns`, unscoped — see {@link campaignSendsCollection}. */\nexport function campaignContainersCollection(\n firestore: Firestore,\n orgId: string | null,\n): Query | null {\n return orgId ? collection(firestore, ...orgEmailCampaignsPath(orgId)) : null\n}\n\n/** One container, `orgs/{orgId}/emailCampaigns/{id}`. */\nexport function campaignContainerDoc(\n firestore: Firestore,\n orgId: string,\n campaignId: string,\n): DocumentReference {\n return doc(firestore, ...orgEmailCampaignsPath(orgId), campaignId)\n}\n\n/** One send, `orgs/{orgId}/campaigns/{sendId}`. */\nexport function campaignSendDoc(\n firestore: Firestore,\n orgId: string,\n sendId: string,\n): DocumentReference {\n return doc(firestore, ...orgCampaignSendsPath(orgId), sendId)\n}\n\n/** One of a send's rollups, `orgs/{orgId}/campaigns/{sendId}/reports/{name}`. */\nexport function campaignSendReportDoc(\n firestore: Firestore,\n orgId: string,\n sendId: string,\n report: 'links' | 'revenue' | 'conversions' | 'reached',\n): DocumentReference {\n return doc(\n firestore,\n ...orgCampaignSendsPath(orgId),\n sendId,\n 'reports',\n report,\n )\n}\n\n/** A container's sequence rollup, `orgs/{orgId}/campaignSequenceReports/{id}`. */\nexport function campaignSequenceReportDoc(\n firestore: Firestore,\n orgId: string,\n campaignId: string,\n): DocumentReference {\n return doc(firestore, ...orgCampaignSequenceReportsPath(orgId), campaignId)\n}\n"],"names":["hostScopeToken","scopeTokensForHost","orgCampaignSendsPath","orgCampaignSequenceReportsPath","orgEmailCampaignsPath","collection","doc","query","where","campaignContainersQuery","firestore","orgId","hostId","containers","campaignSendsQuery","sends","campaignSendsCollection","campaignContainersCollection","campaignContainerDoc","campaignId","campaignSendDoc","sendId","campaignSendReportDoc","report","campaignSequenceReportDoc"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,cAAc,EAAEC,kBAAkB,QAAQ,sCAAqC;AACxF,SACEC,oBAAoB,EACpBC,8BAA8B,EAC9BC,qBAAqB,QAChB,4DAA2D;AAClE,SACEC,UAAU,EACVC,GAAG,EACHC,KAAK,EACLC,KAAK,QAIA,qBAAoB;AAE3B;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED;;;CAGC,GACD,OAAO,SAASC,wBACdC,SAAoB,EACpBC,KAAoB,EACpBC,MAAqB;IAErB,IAAI,CAACD,OAAO,OAAO;IACnB,MAAME,aAAaR,WAAWK,cAAcN,sBAAsBO;IAClE,OAAOC,SACHL,MACEM,YACAL,MAAM,aAAa,sBAAsBP,mBAAmBW,YAE9DC;AACN;AAEA;;;CAGC,GACD,OAAO,SAASC,mBACdJ,SAAoB,EACpBC,KAAoB,EACpBC,MAAqB;IAErB,IAAI,CAACD,OAAO,OAAO;IACnB,MAAMI,QAAQV,WAAWK,cAAcR,qBAAqBS;IAC5D,OAAOC,SACHL,MACEQ,OACAP,MAAM,aAAa,sBAAsB;QAACR,eAAeY;KAAQ,KAEnEG;AACN;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,wBACdN,SAAoB,EACpBC,KAAoB;IAEpB,OAAOA,QAAQN,WAAWK,cAAcR,qBAAqBS,UAAU;AACzE;AAEA,mFAAmF,GACnF,OAAO,SAASM,6BACdP,SAAoB,EACpBC,KAAoB;IAEpB,OAAOA,QAAQN,WAAWK,cAAcN,sBAAsBO,UAAU;AAC1E;AAEA,uDAAuD,GACvD,OAAO,SAASO,qBACdR,SAAoB,EACpBC,KAAa,EACbQ,UAAkB;IAElB,OAAOb,IAAII,cAAcN,sBAAsBO,QAAQQ;AACzD;AAEA,iDAAiD,GACjD,OAAO,SAASC,gBACdV,SAAoB,EACpBC,KAAa,EACbU,MAAc;IAEd,OAAOf,IAAII,cAAcR,qBAAqBS,QAAQU;AACxD;AAEA,+EAA+E,GAC/E,OAAO,SAASC,sBACdZ,SAAoB,EACpBC,KAAa,EACbU,MAAc,EACdE,MAAuD;IAEvD,OAAOjB,IACLI,cACGR,qBAAqBS,QACxBU,QACA,WACAE;AAEJ;AAEA,gFAAgF,GAChF,OAAO,SAASC,0BACdd,SAAoB,EACpBC,KAAa,EACbQ,UAAkB;IAElB,OAAOb,IAAII,cAAcP,+BAA+BQ,QAAQQ;AAClE"}
@@ -6,12 +6,14 @@
6
6
  * messages. Composing is not here: a message belongs to a campaign, and the
7
7
  * campaign's own page is where one is written.
8
8
  *
9
- * The rows come from two collections, and the second is why this reads
10
- * without a migration. `emailCampaigns` holds the containers.
11
- * `campaigns` holds every send, including thousands written before containers
12
- * existed; those carry no container id, and `campaignListRows` presents each
13
- * as a campaign of one rather than dropping it. Nothing is rewritten, so no
14
- * unsubscribe link and no pasted report URL stops resolving.
9
+ * The rows come from two collections. `emailCampaigns` holds the
10
+ * containers. `campaigns` holds every send, including thousands written
11
+ * before containers existed; those carry no container (`emailCampaignId`
12
+ * null), and `campaignListRows` presents each as a campaign of one rather
13
+ * than dropping it. The two are two queries, so the table lists one kind at a
14
+ * time — Campaigns or Single sends — each paged by its own query (AGL-3321).
15
+ * No send is re-filed, so no unsubscribe link and no pasted report URL stops
16
+ * resolving.
15
17
  *
16
18
  * ## At two levels
17
19
  *