@aglyn/plugins-marketing 1.0.0-beta.173 → 1.0.0-beta.175
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/package.json +15 -15
- package/src/lib/components/campaign-detail-card.d.ts +12 -1
- package/src/lib/components/campaign-detail-card.js +146 -35
- package/src/lib/components/campaign-detail-card.js.map +1 -1
- package/src/lib/components/campaign-edit-drawer.d.ts +13 -0
- package/src/lib/components/campaign-edit-drawer.js +56 -4
- package/src/lib/components/campaign-edit-drawer.js.map +1 -1
- package/src/lib/components/campaign-glance-card.component.js +10 -2
- package/src/lib/components/campaign-glance-card.component.js.map +1 -1
- package/src/lib/components/campaign-members-section.d.ts +6 -0
- package/src/lib/components/campaign-members-section.js +2 -2
- package/src/lib/components/campaign-members-section.js.map +1 -1
- package/src/lib/components/campaign-queries.d.ts +58 -0
- package/src/lib/components/campaign-queries.js +72 -0
- package/src/lib/components/campaign-queries.js.map +1 -0
- package/src/lib/components/campaign-reach-sections.d.ts +21 -7
- package/src/lib/components/campaign-reach-sections.js +20 -17
- package/src/lib/components/campaign-reach-sections.js.map +1 -1
- package/src/lib/components/campaign-report-card.d.ts +8 -1
- package/src/lib/components/campaign-report-card.js +33 -16
- package/src/lib/components/campaign-report-card.js.map +1 -1
- package/src/lib/components/campaigns-card.d.ts +10 -1
- package/src/lib/components/campaigns-card.js +102 -19
- package/src/lib/components/campaigns-card.js.map +1 -1
- package/src/lib/components/email-compose-card.d.ts +3 -2
- package/src/lib/components/email-compose-card.js +18 -7
- package/src/lib/components/email-compose-card.js.map +1 -1
- package/src/lib/components/email-detail.d.ts +11 -2
- package/src/lib/components/email-detail.js +50 -23
- package/src/lib/components/email-detail.js.map +1 -1
- package/src/lib/components/emails-list-card.d.ts +10 -1
- package/src/lib/components/emails-list-card.js +129 -23
- package/src/lib/components/emails-list-card.js.map +1 -1
- package/src/lib/components/host-marketing-summary-card.component.js +9 -1
- package/src/lib/components/host-marketing-summary-card.component.js.map +1 -1
- package/src/lib/components/marketing-console-page.js +81 -4
- package/src/lib/components/marketing-console-page.js.map +1 -1
- package/src/lib/components/marketing-console-sections.d.ts +16 -1
- package/src/lib/components/marketing-console-sections.js +25 -2
- package/src/lib/components/marketing-console-sections.js.map +1 -1
- package/src/lib/components/marketing-org-mount.d.ts +71 -0
- package/src/lib/components/marketing-org-mount.js +84 -0
- package/src/lib/components/marketing-org-mount.js.map +1 -0
- package/src/lib/components/use-campaign-send-api.d.ts +2 -2
- package/src/lib/components/use-campaign-send-api.js +22 -6
- package/src/lib/components/use-campaign-send-api.js.map +1 -1
- package/src/lib/components/use-emails-hub-path.d.ts +13 -3
- package/src/lib/components/use-emails-hub-path.js +25 -4
- package/src/lib/components/use-emails-hub-path.js.map +1 -1
- package/src/lib/components/use-marketing-hub-path.d.ts +19 -16
- package/src/lib/components/use-marketing-hub-path.js +6 -32
- package/src/lib/components/use-marketing-hub-path.js.map +1 -1
- package/src/lib/model/marketing-record-routes.js +11 -4
- package/src/lib/model/marketing-record-routes.js.map +1 -1
- package/src/lib/plugin.js +31 -1
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/server/campaign-manage.d.ts +31 -2
- package/src/lib/server/campaign-manage.js +365 -137
- package/src/lib/server/campaign-manage.js.map +1 -1
- package/src/lib/server/campaign-org-refs.d.ts +45 -0
- package/src/lib/server/campaign-org-refs.js +83 -0
- package/src/lib/server/campaign-org-refs.js.map +1 -0
- package/src/lib/server/campaign-process-scheduled.d.ts +32 -2
- package/src/lib/server/campaign-process-scheduled.js +79 -9
- package/src/lib/server/campaign-process-scheduled.js.map +1 -1
- package/src/lib/server/campaign-recipients.js +18 -4
- package/src/lib/server/campaign-recipients.js.map +1 -1
- package/src/lib/server/campaign-send.js +139 -55
- package/src/lib/server/campaign-send.js.map +1 -1
- package/src/lib/server/email-campaign-reach.d.ts +6 -5
- package/src/lib/server/email-campaign-reach.js +14 -14
- package/src/lib/server/email-campaign-reach.js.map +1 -1
- package/src/lib/server/email-events.js +48 -17
- package/src/lib/server/email-events.js.map +1 -1
- package/src/lib/server/marketing-figures.js +12 -1
- package/src/lib/server/marketing-figures.js.map +1 -1
- package/src/lib/server.js +7 -3
- package/src/lib/server.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/campaigns-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { buildRoute, createResourceUid, pluginDocsHelp, Route } from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers — a spec that mocks\n * `@aglyn/tenant-feature-instance` wholesale to stage its Firestore hooks\n * would otherwise lose them, and neither is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { mdiDeleteOutline, mdiEyeOutline } from '@aglyn/shared-data-mdi'\nimport {\n AppLink,\n CardDisplay,\n MdiIcon,\n useConfirmationContext,\n} from '@aglyn/shared-ui-jsx'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport { collection, doc, limit, query, setDoc } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useRouter } from 'next/navigation'\nimport {\n useConsoleHostRoute,\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n campaignListRows,\n type CampaignAggregate,\n type CampaignListRow,\n type CampaignSend,\n type EmailCampaign,\n} from '@aglyn/shared-ui-email-campaigns/model'\nimport { CreateArtifactDrawer } from '@aglyn/shared-ui-jsx-forms'\nimport { useCampaignManageApi } from './use-campaign-send-api'\nimport { useCampaignTopicOptions } from './use-campaign-topic-options'\n\n/**\n * How many sends the list reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server until a send carries one date field every\n * writer stamps.\n */\nconst CAMPAIGN_CEILING = 30\n\n/** How many campaign containers the list reads. */\nconst CONTAINER_CEILING = 50\n\nconst formatDay = (ms: number | null): string =>\n ms === null ? '' : new Date(ms).toLocaleDateString()\n\n/** A rolled-up figure, or an em dash where nothing recorded one. */\nconst figure = (value: CampaignAggregate): string =>\n value.value === null ? '—' : value.value.toLocaleString()\n\nconst WINDOW_LABEL: Record<CampaignListRow['windowState'], string> = {\n undated: 'No dates',\n upcoming: 'Upcoming',\n running: 'Running',\n ended: 'Ended',\n}\n\n/**\n * THE CAMPAIGNS LIST.\n *\n * A campaign is a container — a name, a window, the lists it is aimed at, and\n * the emails sent inside it — so this is a table of campaigns and not of\n * messages. Composing is not here: a message belongs to a campaign, and the\n * campaign's own page is where one is written.\n *\n * The rows come from two collections, and the second is why this reads\n * without a migration. `emailCampaigns` holds the containers.\n * `campaigns` holds every send, including thousands written before containers\n * existed; those carry no container id, and `campaignListRows` presents each\n * as a campaign of one rather than dropping it. Nothing is rewritten, so no\n * unsubscribe link and no pasted report URL stops resolving.\n */\nexport function HostCampaignsCard(props: {\n hostId: string\n /**\n * The marketing hub URL, when the caller already has it.\n *\n * Resolved from the host route when it does not: the inbox console page\n * embeds this card on a tab of its own, and its `basePath` names the INBOX\n * hub. Deriving one hub's URL from another's by string surgery is the kind\n * of link that breaks silently when a surface moves.\n */\n basePath?: string\n}) {\n const { hostId, basePath } = props\n const firestore = useFirestore()\n const router = useRouter()\n const { orgSlug, subdomain } = useConsoleHostRoute(hostId)\n const hubPath =\n basePath ??\n (orgSlug && subdomain\n ? buildRoute(Route.HOST_PLUGIN, {\n orgSlug,\n host: subdomain,\n pluginSlug: 'marketing',\n })\n : null)\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const manageApi = useCampaignManageApi(hostId)\n const { scope: dataScope } = useOrgDataScope({ hostId })\n\n /*\n * ORDERED AND CEILINGED, and not orderable on any DATE.\n *\n * No field here is on every send: a sent one is written `{status:'sent',\n * sentAt}` and a scheduled one `{status:'scheduled', sendAtMs}`, by the two\n * branches of `campaign-send.ts`, and there is no `createdAt` at all.\n * `orderBy` on either would not mis-sort the list, it would DROP half of it.\n *\n * A bare `limit(30)` is answered in DOCUMENT-ID order, so the window is\n * thirty sends chosen by id and then sorted by date, which reads as the most\n * recent thirty and is not. `collectionCeiling` returns that same thirty —\n * document-id order is what the bare cap already gave — but it says so,\n * which is what stops the next edit reaching for `sentAt`, and it probes one\n * past the ceiling so the reader is told the history is longer.\n */\n const { data: sendDocs } = useFirestoreCollection<any>(\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'campaigns'),\n CAMPAIGN_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readSends, truncated: sendsTruncated } = ceilingedWindow<any>(\n sendDocs,\n CAMPAIGN_CEILING,\n )\n\n const { data: campaignDocs } = useFirestoreCollection<any>(\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'emailCampaigns'),\n CONTAINER_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readCampaigns, truncated: campaignsTruncated } =\n ceilingedWindow<any>(campaignDocs, CONTAINER_CEILING)\n\n // Org email lists, so a row can name what it is aimed at rather than\n // showing ids.\n const { data: listDocs } = useFirestoreCollection<any>(\n () =>\n dataScope\n ? query(\n collection(firestore, dataScope[0], dataScope[1], 'lists'),\n limit(50),\n )\n : null,\n [firestore, dataScope],\n { idField: '$id' },\n )\n const [createOpen, setCreateOpen] = useState(false)\n /*\n * The org's topic catalog, read only while the CREATE DRAWER is open.\n *\n * It fills one picker in that drawer and is drawn nowhere in the table, so\n * a reader who came to look at their campaigns must not pay for it — the\n * same rule the emails list already applies to the campaigns it offers its\n * own drawer, and the one the audiences section applies to a list's\n * members. It is the largest read on this section at 200 documents, and it\n * is the only one nothing on screen needs.\n */\n const { topics, source: topicSource } = useCampaignTopicOptions(hostId, {\n enabled: createOpen,\n })\n const topicOptions = useMemo(\n () =>\n topics.map((topic) => ({\n value: topic.id,\n label: topic.name,\n })),\n [topics],\n )\n\n const listNames = useMemo(() => {\n const names = new Map<string, string>()\n for (const list of listDocs ?? []) {\n names.set(String(list.$id), String(list.name ?? list.$id))\n }\n return names\n }, [listDocs])\n\n const listOptions = useMemo(\n () =>\n (listDocs ?? []).map((list: any) => ({\n value: String(list.$id),\n label: String(list.name ?? list.$id),\n })),\n [listDocs],\n )\n\n const rows = useMemo(() => {\n const campaigns = (readCampaigns as EmailCampaign[]).filter(\n (campaign: any) => !campaign.deletedAt,\n )\n return campaignListRows(\n campaigns,\n readSends as CampaignSend[],\n Date.now(),\n ).map((row) => ({ ...row, $id: row.id }))\n }, [readCampaigns, readSends])\n\n const [createError, setCreateError] = useState<string | null>(null)\n const [creating, setCreating] = useState(false)\n /** The campaign a delete is in flight for, so its row menu can say so. */\n const [deletingId, setDeletingId] = useState('')\n\n const openCampaign = useCallback(\n (id: string) => {\n if (hubPath) void router.push(`${hubPath}/campaigns/${id}`)\n },\n [hubPath, router],\n )\n\n const handleCreate = useCallback(\n async (values: Record<string, any>) => {\n if (creating) return\n /*\n * `displayName` is the shared drawer's own field, and every artifact\n * create in the console collects a name under that key. The campaign\n * stores it as `name` — the container has one name and no second\n * internal label — so the mapping happens here rather than by giving\n * this one drawer a field the others do not have.\n */\n const name = String(values.displayName ?? '').trim()\n if (!name) return\n const startAtMs = values.startAt ? Date.parse(String(values.startAt)) : null\n const endAtMs = values.endAt ? Date.parse(String(values.endAt)) : null\n // Refused here rather than stored and rendered as a campaign that ends\n // before it starts, which no window state describes.\n if (startAtMs !== null && endAtMs !== null && endAtMs < startAtMs) {\n return setCreateError('The end date is before the start date')\n }\n setCreating(true)\n setCreateError(null)\n const id = createResourceUid()\n try {\n await setDoc(doc(firestore, 'hosts', hostId, 'emailCampaigns', id), {\n name,\n ...(Number.isFinite(startAtMs) && startAtMs !== null\n ? { startAtMs }\n : {}),\n ...(Number.isFinite(endAtMs) && endAtMs !== null ? { endAtMs } : {}),\n listIds: Array.isArray(values.listIds)\n ? values.listIds.map(String)\n : [],\n ...(values.topicId ? { topicId: String(values.topicId) } : {}),\n createdAtMs: Date.now(),\n createdBy: String((user as any)?.uid ?? ''),\n })\n setCreateOpen(false)\n openCampaign(id)\n } catch (error) {\n console.error(error)\n setCreateError('The campaign could not be created')\n enqueueSnackbar('Could not create the campaign', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setCreating(false)\n }\n },\n [creating, firestore, hostId, user, enqueueSnackbar, openCampaign],\n )\n\n const campaignHref = useCallback(\n (id: string) => (hubPath ? `${hubPath}/campaigns/${id}` : null),\n [hubPath],\n )\n\n /*==========================================\n * DELETING A CAMPAIGN FROM ITS ROW.\n *\n * The container goes and its emails stay — the route detaches them first,\n * so each one keeps its id, its report and its unsubscribe links, and\n * reappears in this very table as a \"Single send\". That is not a\n * convenience: a send id is inside the HMAC of every unsubscribe footer\n * already delivered, so a delete that took the sends with it would break\n * opt-outs that must go on working.\n *\n * The confirmation names the count and says what the delete does NOT do.\n * Deleting a campaign cancels nothing — a scheduled email inside it still\n * goes out — and a merchant who reads the button as \"stop this campaign\"\n * has to be told before they press it.\n *\n * EDITING is deliberately not offered here. A record is edited on its own\n * page in this console; the campaign's page carries the edit drawer, and\n * this row's first entry is the way to it.\n *=========================================*/\n const handleDelete = useCallback(\n async (row: CampaignListRow) => {\n if (deletingId) return\n const emails = row.sends.length\n /*\n * Emails with mail still to go: waiting for their time, AND part way\n * through an audience larger than one batch. Counting only `scheduled`\n * would miss the case that needs the warning most — an email delivering\n * right now is stored as `scheduled` too, and `rollup.scheduled` is the\n * narrower reading that leaves it out.\n */\n const unfinished = row.rollup.scheduled + row.rollup.sending\n const agreed = await confirm({\n title: `Delete ${row.name}?`,\n description:\n (emails\n ? `The ${emails.toLocaleString()} ` +\n `${emails === 1 ? 'email' : 'emails'} in it are kept — each ` +\n 'keeps its own report and its unsubscribe links, and they stay ' +\n 'in this list as single sends. '\n : 'It holds no emails. ') +\n (unfinished\n ? `${unfinished.toLocaleString()} of them ${\n unfinished === 1 ? 'is' : 'are'\n } still going out or still due, and deleting the campaign does ` +\n 'not stop that — the sender picks each one up from its own ' +\n 'record. Stop a send from its own page. '\n : '') +\n 'Any screens, forms and contacts assigned to it come out of it and ' +\n 'are otherwise untouched. Only the campaign itself goes.',\n confirmationText: 'Delete campaign',\n })\n .then(() => true)\n .catch(() => false)\n if (!agreed) return\n setDeletingId(row.id)\n try {\n const { response, payload } = await manageApi({\n action: 'deleteCampaign',\n campaignId: row.id,\n })\n if (!response.ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'The campaign could not be deleted',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n enqueueSnackbar('Campaign deleted', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('The campaign could not be deleted', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setDeletingId('')\n }\n },\n [confirm, deletingId, enqueueSnackbar, manageApi],\n )\n\n const columns = useMemo(\n () => [\n {\n field: 'name',\n headerName: 'Campaign',\n flex: 1,\n minWidth: 180,\n renderCell: ({ row }: any) => (\n <Stack\n direction=\"row\"\n spacing={1}\n /*\n `minWidth: 0` on the row AND on the name: a flex child will not\n shrink below its content without it, so the chip beside it is\n what gets clipped instead of the name being ellipsed.\n */\n sx={{ alignItems: 'center', minWidth: 0, width: 1 }}\n >\n {/*\n The name is a real anchor as well as the row being clickable, so\n a campaign can be middle-clicked into a tab or copied out of the\n context menu — affordances a row handler cannot offer. The grid's\n own row click fires too, so the link stops the event rather than\n pushing the same route twice.\n */}\n {campaignHref(row.id) ? (\n <AppLink\n href={campaignHref(row.id) as string}\n onClick={(event: { stopPropagation: () => void }) =>\n event.stopPropagation()\n }\n style={{ minWidth: 0 }}\n >\n <Typography variant=\"body2\" noWrap>\n {row.name}\n </Typography>\n </AppLink>\n ) : (\n <Typography variant=\"body2\" noWrap sx={{ minWidth: 0 }}>\n {row.name}\n </Typography>\n )}\n {row.legacy ? (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n label=\"Single send\"\n // A label that reads \"Single sen\" is worse than a shorter name.\n sx={{ flexShrink: 0 }}\n title={\n 'Sent before campaigns grouped their emails. Its report ' +\n 'and its unsubscribe links are unchanged.'\n }\n />\n ) : null}\n </Stack>\n ),\n },\n {\n field: 'windowState',\n headerName: 'Window',\n width: 170,\n renderCell: ({ row }: any) => {\n const start = formatDay(row.startAtMs)\n const end = formatDay(row.endAtMs)\n const range =\n start && end && start !== end\n ? `${start} – ${end}`\n : start || end || ''\n return (\n <Stack sx={{ minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {WINDOW_LABEL[row.windowState as CampaignListRow['windowState']]}\n </Typography>\n {range ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {range}\n </Typography>\n ) : null}\n </Stack>\n )\n },\n },\n {\n field: 'listIds',\n headerName: 'Lists',\n width: 140,\n sortable: false,\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\" noWrap>\n {row.listIds.length\n ? row.listIds\n .map((id: string) => listNames.get(id) ?? id)\n .join(', ')\n : '—'}\n </Typography>\n ),\n },\n /*\n THE FOUR COUNTS, RIGHT-ALIGNED HEAD AND BODY.\n A figure is read by its last digit, so a column of them lines up on\n the right or it does not line up at all. `headerAlign` has to be said\n as well as `align`: a grid column defaults its header to the column\n type's alignment rather than to the cell's, which is how these came to\n sit with left headers over figures nobody could compare down the page.\n\n EVERY ONE OF THEM MEASURES THE MAIL, and the headings say so. What a\n campaign CAUSED — the submissions, leads, contacts and bookings\n credited to it — is not a column here, because there is no figure to\n read: a container has no conversion counter of its own, so a column\n would be an aggregation per row for a campaign and a subcollection\n document per row for a single send, on a list that costs two queries\n however many campaigns it holds. Headings that named the campaign over\n figures that all described its mail were the cheaper mistake, so the\n headings name the mail and the note under the table says where the\n outcome figures are.\n */\n {\n field: 'emails',\n headerName: 'Emails',\n width: 128,\n align: 'right',\n headerAlign: 'right',\n /*\n THE COUNT, AND WHAT IS STILL HAPPENING TO IT.\n\n `sending` is called out apart from `scheduled` because the two are\n opposite readings of the same stored status: an email delivering an\n audience larger than one batch sits as `scheduled` between runs, and\n rolling it in with the ones that have mailed nobody reports a\n campaign that is half delivered as a campaign that has not started.\n\n The note sits UNDER the figure rather than beside it — the column\n would otherwise have to be wide enough for the longest sentence, and\n the figure is what the column is read for.\n */\n renderCell: ({ row }: any) => {\n const { sends, sending, scheduled } = row.rollup\n const note = [\n sending ? `${sending} sending` : '',\n scheduled ? `${scheduled} scheduled` : '',\n ]\n .filter(Boolean)\n .join(', ')\n return (\n <Stack sx={{ alignItems: 'flex-end', minWidth: 0, width: 1 }}>\n <Typography variant=\"body2\">{String(sends)}</Typography>\n {note ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {note}\n </Typography>\n ) : null}\n </Stack>\n )\n },\n },\n {\n field: 'sent',\n headerName: 'Mail sent',\n width: 112,\n align: 'right',\n headerAlign: 'right',\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\">{figure(row.rollup.sent)}</Typography>\n ),\n },\n {\n field: 'opens',\n headerName: 'Mail opens',\n width: 112,\n align: 'right',\n headerAlign: 'right',\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\">{figure(row.rollup.opens)}</Typography>\n ),\n },\n {\n field: 'clicks',\n headerName: 'Mail clicks',\n width: 112,\n align: 'right',\n headerAlign: 'right',\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\">{figure(row.rollup.clicks)}</Typography>\n ),\n },\n /*\n THE TRAILING CLUSTER, through the grid's own actions column.\n `listActionsColumn` is what every other grid list in the console\n renders, so the reader cannot tell which family of table they are\n standing in — the hand-rolled tables on this surface reach the same\n `RowActionsMenu` from the other direction.\n\n Opening the campaign is restated here even though the row click does\n the same thing, for the reason the screens table restates its own: the\n menu is where a row's actions are NAMED, and an action absent from it\n reads as an action the row does not have.\n\n A \"Single send\" row is a SEND with no container — the table adopts it\n so a merchant's history is not missing — and there is no container\n under it to delete. Its entry is shown disabled with that reason\n rather than hidden, because a control that vanishes and one that does\n not apply look identical from the outside.\n */\n listActionsColumn(\n (row: any) => (\n <ListRowActions\n label={String(row.name ?? row.id)}\n items={[\n {\n key: 'details',\n label: 'Open campaign',\n icon: <MdiIcon path={mdiEyeOutline.path} size={0.8} />,\n href: campaignHref(row.id) ?? undefined,\n disabled: !campaignHref(row.id),\n disabledReason: campaignHref(row.id)\n ? undefined\n : 'This site’s console URL has not resolved yet',\n },\n {\n key: 'delete',\n label: 'Delete campaign',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: row.legacy || Boolean(deletingId),\n disabledReason: row.legacy\n ? 'This is a single send, not a campaign. Open it to ' +\n 'manage the email itself.'\n : 'A campaign is being deleted',\n onClick: () => void handleDelete(row as CampaignListRow),\n },\n ]}\n />\n ),\n { width: 72 },\n ),\n ],\n [listNames, campaignHref, deletingId, handleDelete],\n )\n\n return (\n <CardDisplay\n header={'Campaigns'}\n help={pluginDocsHelp('emailCampaigns', {\n anchor: '#campaigns-group-emails',\n excerpt:\n 'A campaign groups the emails you send to a set of lists over a ' +\n 'window of dates. Open one to write and send an email inside it.',\n })}\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={creating}\n onClick={() => {\n setCreateError(null)\n setCreateOpen(true)\n }}\n >\n {creating ? 'Creating…' : 'Create campaign'}\n </Button>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <ListTable\n rows={rows}\n columns={columns as any}\n onOpen={(id) => openCampaign(id)}\n noRowsLabel=\"No campaigns yet\"\n noRowsDescription=\"A campaign groups the emails you send to a set of lists.\"\n noRowsAction={\n <Button variant=\"contained\" onClick={() => setCreateOpen(true)}>\n {'Create campaign'}\n </Button>\n }\n />\n {/*\n WHAT THIS TABLE MEASURES, said rather than inferred from the column\n names. Every figure in it is a fact about the campaign's mail, and a\n reader comparing rows is comparing mailings — the conversions and the\n destinations credited to a campaign are on the campaign's own page,\n because counting them for every row is a read per row on a list whose\n whole cost is two queries.\n */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'These figures measure each campaign’s mail. What a campaign ' +\n 'caused — the form submissions, leads, contacts and bookings ' +\n 'credited to it — and the pages it sent people to are on the ' +\n 'campaign’s own page.'}\n </Typography>\n {sendsTruncated || campaignsTruncated ? (\n <Alert severity=\"info\">\n {`Showing the most recent ${CONTAINER_CEILING} campaigns and ` +\n `${CAMPAIGN_CEILING} sends. This site has more — the ones ` +\n 'listed are not necessarily the most recent, because a send ' +\n 'carries no date field that every writer stamps.'}\n </Alert>\n ) : null}\n </Stack>\n {/*\n The console's own create drawer, from the shared library rather than a\n second one that looks like it. What a campaign collects beyond a name\n is its window, the lists it is aimed at and the stream its emails open\n on; the description box is left off because the container stores none,\n and a field the writer discards is worse than one never offered.\n */}\n {/* Draws nothing: the zone the topic catalog's owner answers through. */}\n {topicSource}\n <CreateArtifactDrawer\n open={createOpen}\n onClose={() => setCreateOpen(false)}\n title=\"Create campaign\"\n submitLabel=\"Create campaign\"\n includeDescription={false}\n onSubmit={handleCreate}\n extraFields={campaignFields(listOptions, topicOptions)}\n errorSlot={\n createError ? (\n <Alert severity=\"error\" sx={{ mt: 2, mb: 1 }}>\n {createError}\n </Alert>\n ) : null\n }\n />\n </CardDisplay>\n )\n}\n/**\n * What a campaign collects beyond its name.\n *\n * Data-driven-forms field descriptors, built from the org's own lists and\n * topics so the drawer offers what this workspace actually has. Dates are\n * plain `date` inputs: a campaign window is a day at each end, and a time of\n * day would be a precision the model does not carry.\n */\nfunction campaignFields(\n lists: Array<{ value: string; label: string }>,\n topics: Array<{ value: string; label: string }>,\n): any[] {\n return [\n {\n component: 'text-field',\n name: 'startAt',\n label: 'Starts',\n type: 'date',\n helperText: 'When the campaign window opens',\n },\n {\n component: 'text-field',\n name: 'endAt',\n label: 'Ends',\n type: 'date',\n helperText: 'Leave empty for an open-ended campaign',\n InputLabelProps: { shrink: true },\n },\n {\n component: 'select',\n name: 'listIds',\n label: 'Lists',\n multiple: true,\n initialValue: [],\n // A campaign with no list is legitimate: its emails can go to leads, to\n // site members, or to a segment. The lists are what it is AIMED at.\n helperText: 'The lists this campaign is aimed at',\n disableDefaultOption: true,\n options: lists,\n },\n {\n component: 'select',\n name: 'topicId',\n label: 'Topic',\n helperText: 'The stream its emails open on — each one can change it',\n disableDefaultOption: true,\n options: topics,\n },\n ]\n}\n\nHostCampaignsCard.displayName = 'HostCampaignsCard'\n\nexport default HostCampaignsCard\n"],"names":["buildRoute","createResourceUid","pluginDocsHelp","Route","ceilingedWindow","collectionCeiling","mdiDeleteOutline","mdiEyeOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListRowActions","ListTable","listActionsColumn","useSnackbar","Alert","Button","Chip","Stack","Typography","collection","doc","limit","query","setDoc","useCallback","useMemo","useState","useRouter","useConsoleHostRoute","useFirestore","useFirestoreCollection","useOrgDataScope","useUser","campaignListRows","CreateArtifactDrawer","useCampaignManageApi","useCampaignTopicOptions","CAMPAIGN_CEILING","CONTAINER_CEILING","formatDay","ms","Date","toLocaleDateString","figure","value","toLocaleString","WINDOW_LABEL","undated","upcoming","running","ended","HostCampaignsCard","props","hostId","basePath","firestore","router","orgSlug","subdomain","hubPath","HOST_PLUGIN","host","pluginSlug","data","user","enqueueSnackbar","confirm","manageApi","scope","dataScope","sendDocs","idField","rows","readSends","truncated","sendsTruncated","campaignDocs","readCampaigns","campaignsTruncated","listDocs","createOpen","setCreateOpen","topics","source","topicSource","enabled","topicOptions","map","topic","id","label","name","listNames","names","Map","list","set","String","$id","listOptions","campaigns","filter","campaign","deletedAt","now","row","createError","setCreateError","creating","setCreating","deletingId","setDeletingId","openCampaign","push","handleCreate","values","displayName","trim","startAtMs","startAt","parse","endAtMs","endAt","Number","isFinite","listIds","Array","isArray","topicId","createdAtMs","createdBy","uid","error","console","variant","allowDuplicate","campaignHref","handleDelete","emails","sends","length","unfinished","rollup","scheduled","sending","agreed","title","description","confirmationText","then","catch","response","payload","action","campaignId","ok","persist","columns","field","headerName","flex","minWidth","renderCell","direction","spacing","sx","alignItems","width","href","onClick","event","stopPropagation","style","noWrap","legacy","size","flexShrink","start","end","range","windowState","color","sortable","get","join","align","headerAlign","note","Boolean","sent","opens","clicks","items","key","icon","path","undefined","disabled","disabledReason","destructive","header","help","anchor","excerpt","HeaderProps","contentGutterX","contentGutterY","onOpen","noRowsLabel","noRowsDescription","noRowsAction","severity","open","onClose","submitLabel","includeDescription","onSubmit","extraFields","campaignFields","errorSlot","mt","mb","lists","component","type","helperText","InputLabelProps","shrink","multiple","initialValue","disableDefaultOption","options"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,UAAU,EAAEC,iBAAiB,EAAEC,cAAc,EAAEC,KAAK,QAAQ,eAAc;AACnF;;;;CAIC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,yBAAwB;AACxE,SACEC,OAAO,EACPC,WAAW,EACXC,OAAO,EACPC,sBAAsB,QACjB,uBAAsB;AAC7B,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;A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C,YAAY;QACd;QACA;YACEF,WAAW;YACXpI,MAAM;YACND,OAAO;YACPsI,MAAM;YACNC,YAAY;YACZC,iBAAiB;gBAAEC,QAAQ;YAAK;QAClC;QACA;YACEJ,WAAW;YACXpI,MAAM;YACND,OAAO;YACP0I,UAAU;YACVC,cAAc,EAAE;YAChB,wEAAwE;YACxE,oEAAoE;YACpEJ,YAAY;YACZK,sBAAsB;YACtBC,SAAST;QACX;QACA;YACEC,WAAW;YACXpI,MAAM;YACND,OAAO;YACPuI,YAAY;YACZK,sBAAsB;YACtBC,SAASrJ;QACX;KACD;AACH;AAEA/B,kBAAkBiE,WAAW,GAAG;AAEhC,eAAejE,kBAAiB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/campaigns-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { buildRoute, createResourceUid, pluginDocsHelp, Route } from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers — a spec that mocks\n * `@aglyn/tenant-feature-instance` wholesale to stage its Firestore hooks\n * would otherwise lose them, and neither is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { mdiDeleteOutline, mdiEyeOutline } from '@aglyn/shared-data-mdi'\nimport {\n AppLink,\n CardDisplay,\n MdiIcon,\n useConfirmationContext,\n} from '@aglyn/shared-ui-jsx'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Alert, Button, Chip, Stack, Typography } from '@mui/material'\nimport { collection, limit, query, setDoc } from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport { useRouter } from 'next/navigation'\nimport {\n useConsoleHostRoute,\n useFirestore,\n useFirestoreCollection,\n useUser,\n} from '@aglyn/tenant-feature-instance'\nimport {\n campaignListRows,\n campaignSiteIds,\n campaignVisibleTo,\n type CampaignAggregate,\n type CampaignListRow,\n type CampaignSend,\n type EmailCampaign,\n} from '@aglyn/shared-ui-email-campaigns/model'\nimport { CreateArtifactDrawer } from '@aglyn/shared-ui-jsx-forms'\nimport {\n campaignContainerDoc,\n campaignContainersQuery,\n campaignSendsQuery,\n} from './campaign-queries'\nimport {\n orgSiteName,\n orgSiteOptions,\n topicCatalogHostId,\n useMarketingOrgId,\n useMarketingOrgMount,\n type MarketingOrgMount,\n} from './marketing-org-mount'\nimport { useCampaignManageApi } from './use-campaign-send-api'\nimport { useCampaignTopicOptions } from './use-campaign-topic-options'\n\n/**\n * How many sends the list reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server until a send carries one date field every\n * writer stamps.\n */\nconst CAMPAIGN_CEILING = 30\n\n/** How many campaign containers the list reads. */\nconst CONTAINER_CEILING = 50\n\nconst formatDay = (ms: number | null): string =>\n ms === null ? '' : new Date(ms).toLocaleDateString()\n\n/** A rolled-up figure, or an em dash where nothing recorded one. */\nconst figure = (value: CampaignAggregate): string =>\n value.value === null ? '—' : value.value.toLocaleString()\n\nconst WINDOW_LABEL: Record<CampaignListRow['windowState'], string> = {\n undated: 'No dates',\n upcoming: 'Upcoming',\n running: 'Running',\n ended: 'Ended',\n}\n\n/**\n * THE CAMPAIGNS LIST.\n *\n * A campaign is a container — a name, a window, the lists it is aimed at, and\n * the emails sent inside it — so this is a table of campaigns and not of\n * messages. Composing is not here: a message belongs to a campaign, and the\n * campaign's own page is where one is written.\n *\n * The rows come from two collections, and the second is why this reads\n * without a migration. `emailCampaigns` holds the containers.\n * `campaigns` holds every send, including thousands written before containers\n * existed; those carry no container id, and `campaignListRows` presents each\n * as a campaign of one rather than dropping it. Nothing is rewritten, so no\n * unsubscribe link and no pasted report URL stops resolving.\n *\n * ## At two levels\n *\n * Both collections are the organization's. Under a site the card lists the\n * campaigns PLACED on that site and the sends sent AS it (see\n * `campaign-queries.ts` for why those filters are what make the read legal);\n * on the org hub, with `hostId` null, it lists every campaign with the sites\n * each one is placed on, and a new campaign is placed where its creator says.\n */\nexport function HostCampaignsCard(props: {\n /** The site, or `null` on the org Marketing hub. */\n hostId: string | null\n /**\n * The marketing hub URL, when the caller already has it.\n *\n * Resolved from the host route when it does not: the inbox console page\n * embeds this card on a tab of its own, and its `basePath` names the INBOX\n * hub. Deriving one hub's URL from another's by string surgery is the kind\n * of link that breaks silently when a surface moves.\n */\n basePath?: string\n}) {\n const { hostId, basePath } = props\n const firestore = useFirestore()\n const router = useRouter()\n const { orgSlug, subdomain } = useConsoleHostRoute(hostId)\n const hubPath =\n basePath ??\n (orgSlug && subdomain\n ? buildRoute(Route.HOST_PLUGIN, {\n orgSlug,\n host: subdomain,\n pluginSlug: 'marketing',\n })\n : null)\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const orgMount = useMarketingOrgMount()\n const { orgId } = useMarketingOrgId(hostId)\n // A container is the org's, so deleting one from the org hub names the org.\n const manageApi = useCampaignManageApi(hostId, orgId)\n\n /*\n * ORDERED AND CEILINGED, and not orderable on any DATE.\n *\n * No field here is on every send: a sent one is written `{status:'sent',\n * sentAt}` and a scheduled one `{status:'scheduled', sendAtMs}`, by the two\n * branches of `campaign-send.ts`, and there is no `createdAt` at all.\n * `orderBy` on either would not mis-sort the list, it would DROP half of it.\n *\n * A bare `limit(30)` is answered in DOCUMENT-ID order, so the window is\n * thirty sends chosen by id and then sorted by date, which reads as the most\n * recent thirty and is not. `collectionCeiling` returns that same thirty —\n * document-id order is what the bare cap already gave — but it says so,\n * which is what stops the next edit reaching for `sentAt`, and it probes one\n * past the ceiling so the reader is told the history is longer.\n */\n const { data: sendDocs } = useFirestoreCollection<any>(\n () => {\n const sends = campaignSendsQuery(firestore, orgId, hostId)\n return sends ? collectionCeiling(sends, CAMPAIGN_CEILING) : null\n },\n [firestore, orgId, hostId],\n { idField: '$id' },\n )\n const { rows: readSends, truncated: sendsTruncated } = ceilingedWindow<any>(\n sendDocs,\n CAMPAIGN_CEILING,\n )\n\n const { data: campaignDocs } = useFirestoreCollection<any>(\n () => {\n const containers = campaignContainersQuery(firestore, orgId, hostId)\n return containers ? collectionCeiling(containers, CONTAINER_CEILING) : null\n },\n [firestore, orgId, hostId],\n { idField: '$id' },\n )\n const { rows: readCampaigns, truncated: campaignsTruncated } =\n ceilingedWindow<any>(campaignDocs, CONTAINER_CEILING)\n\n // Org email lists, so a row can name what it is aimed at rather than\n // showing ids.\n const { data: listDocs } = useFirestoreCollection<any>(\n () =>\n orgId\n ? query(collection(firestore, 'orgs', orgId, 'lists'), limit(50))\n : null,\n [firestore, orgId],\n { idField: '$id' },\n )\n const [createOpen, setCreateOpen] = useState(false)\n /*\n * The org's topic catalog, read only while the CREATE DRAWER is open.\n *\n * It fills one picker in that drawer and is drawn nowhere in the table, so\n * a reader who came to look at their campaigns must not pay for it — the\n * same rule the emails list already applies to the campaigns it offers its\n * own drawer, and the one the audiences section applies to a list's\n * members. It is the largest read on this section at 200 documents, and it\n * is the only one nothing on screen needs.\n */\n const { topics, source: topicSource } = useCampaignTopicOptions(\n topicCatalogHostId(hostId, orgMount),\n { enabled: createOpen },\n )\n const topicOptions = useMemo(\n () =>\n topics.map((topic) => ({\n value: topic.id,\n label: topic.name,\n })),\n [topics],\n )\n\n const listNames = useMemo(() => {\n const names = new Map<string, string>()\n for (const list of listDocs ?? []) {\n names.set(String(list.$id), String(list.name ?? list.$id))\n }\n return names\n }, [listDocs])\n\n const listOptions = useMemo(\n () =>\n (listDocs ?? []).map((list: any) => ({\n value: String(list.$id),\n label: String(list.name ?? list.$id),\n })),\n [listDocs],\n )\n\n const rows = useMemo(() => {\n const campaigns = (readCampaigns as EmailCampaign[]).filter(\n (campaign: any) => !campaign.deletedAt,\n )\n const byId = new Map(campaigns.map((campaign) => [campaign.$id, campaign]))\n return campaignListRows(\n campaigns,\n readSends as CampaignSend[],\n Date.now(),\n ).map((row) => ({\n ...row,\n $id: row.id,\n sitesLabel: orgMount\n ? campaignSitesLabel(orgMount, row, byId.get(row.id))\n : '',\n }))\n }, [readCampaigns, readSends, orgMount])\n\n const [createError, setCreateError] = useState<string | null>(null)\n const [creating, setCreating] = useState(false)\n /** The campaign a delete is in flight for, so its row menu can say so. */\n const [deletingId, setDeletingId] = useState('')\n\n const openCampaign = useCallback(\n (id: string) => {\n if (hubPath) void router.push(`${hubPath}/campaigns/${id}`)\n },\n [hubPath, router],\n )\n\n const handleCreate = useCallback(\n async (values: Record<string, any>) => {\n if (creating) return\n /*\n * `displayName` is the shared drawer's own field, and every artifact\n * create in the console collects a name under that key. The campaign\n * stores it as `name` — the container has one name and no second\n * internal label — so the mapping happens here rather than by giving\n * this one drawer a field the others do not have.\n */\n const name = String(values.displayName ?? '').trim()\n if (!name) return\n const startAtMs = values.startAt ? Date.parse(String(values.startAt)) : null\n const endAtMs = values.endAt ? Date.parse(String(values.endAt)) : null\n // Refused here rather than stored and rendered as a campaign that ends\n // before it starts, which no window state describes.\n if (startAtMs !== null && endAtMs !== null && endAtMs < startAtMs) {\n return setCreateError('The end date is before the start date')\n }\n /*\n * Held until the org is known. A container has one home, and a write\n * that raced the site's org lookup would have nowhere to go.\n */\n if (!orgId) {\n return setCreateError('This workspace is still loading — try again')\n }\n setCreating(true)\n setCreateError(null)\n const id = createResourceUid()\n try {\n await setDoc(campaignContainerDoc(firestore, orgId, id), {\n name,\n ...(Number.isFinite(startAtMs) && startAtMs !== null\n ? { startAtMs }\n : {}),\n ...(Number.isFinite(endAtMs) && endAtMs !== null ? { endAtMs } : {}),\n listIds: Array.isArray(values.listIds)\n ? values.listIds.map(String)\n : [],\n ...(values.topicId ? { topicId: String(values.topicId) } : {}),\n /*\n * Where it is placed. From a site's hub, that site — the creator is\n * standing on it, and a campaign that appeared on every sibling\n * site would be a decision nobody made. From the org hub, the sites\n * picked, and every site when none are.\n */\n visibleTo: campaignVisibleTo(\n hostId\n ? [hostId]\n : Array.isArray(values.siteIds)\n ? values.siteIds.map(String)\n : null,\n ),\n createdAtMs: Date.now(),\n createdBy: String((user as any)?.uid ?? ''),\n })\n setCreateOpen(false)\n openCampaign(id)\n } catch (error) {\n console.error(error)\n setCreateError('The campaign could not be created')\n enqueueSnackbar('Could not create the campaign', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setCreating(false)\n }\n },\n [creating, firestore, hostId, orgId, user, enqueueSnackbar, openCampaign],\n )\n\n const campaignHref = useCallback(\n (id: string) => (hubPath ? `${hubPath}/campaigns/${id}` : null),\n [hubPath],\n )\n\n /*==========================================\n * DELETING A CAMPAIGN FROM ITS ROW.\n *\n * The container goes and its emails stay — the route detaches them first,\n * so each one keeps its id, its report and its unsubscribe links, and\n * reappears in this very table as a \"Single send\". That is not a\n * convenience: a send id is inside the HMAC of every unsubscribe footer\n * already delivered, so a delete that took the sends with it would break\n * opt-outs that must go on working.\n *\n * The confirmation names the count and says what the delete does NOT do.\n * Deleting a campaign cancels nothing — a scheduled email inside it still\n * goes out — and a merchant who reads the button as \"stop this campaign\"\n * has to be told before they press it.\n *\n * EDITING is deliberately not offered here. A record is edited on its own\n * page in this console; the campaign's page carries the edit drawer, and\n * this row's first entry is the way to it.\n *=========================================*/\n const handleDelete = useCallback(\n async (row: CampaignListRow) => {\n if (deletingId) return\n const emails = row.sends.length\n /*\n * Emails with mail still to go: waiting for their time, AND part way\n * through an audience larger than one batch. Counting only `scheduled`\n * would miss the case that needs the warning most — an email delivering\n * right now is stored as `scheduled` too, and `rollup.scheduled` is the\n * narrower reading that leaves it out.\n */\n const unfinished = row.rollup.scheduled + row.rollup.sending\n const agreed = await confirm({\n title: `Delete ${row.name}?`,\n description:\n (emails\n ? `The ${emails.toLocaleString()} ` +\n `${emails === 1 ? 'email' : 'emails'} in it are kept — each ` +\n 'keeps its own report and its unsubscribe links, and they stay ' +\n 'in this list as single sends. '\n : 'It holds no emails. ') +\n (unfinished\n ? `${unfinished.toLocaleString()} of them ${\n unfinished === 1 ? 'is' : 'are'\n } still going out or still due, and deleting the campaign does ` +\n 'not stop that — the sender picks each one up from its own ' +\n 'record. Stop a send from its own page. '\n : '') +\n 'Any screens, forms and contacts assigned to it come out of it and ' +\n 'are otherwise untouched. Only the campaign itself goes.',\n confirmationText: 'Delete campaign',\n })\n .then(() => true)\n .catch(() => false)\n if (!agreed) return\n setDeletingId(row.id)\n try {\n const { response, payload } = await manageApi({\n action: 'deleteCampaign',\n campaignId: row.id,\n })\n if (!response.ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'The campaign could not be deleted',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n enqueueSnackbar('Campaign deleted', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('The campaign could not be deleted', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setDeletingId('')\n }\n },\n [confirm, deletingId, enqueueSnackbar, manageApi],\n )\n\n const columns = useMemo(\n () => [\n {\n field: 'name',\n headerName: 'Campaign',\n flex: 1,\n minWidth: 180,\n renderCell: ({ row }: any) => (\n <Stack\n direction=\"row\"\n spacing={1}\n /*\n `minWidth: 0` on the row AND on the name: a flex child will not\n shrink below its content without it, so the chip beside it is\n what gets clipped instead of the name being ellipsed.\n */\n sx={{ alignItems: 'center', minWidth: 0, width: 1 }}\n >\n {/*\n The name is a real anchor as well as the row being clickable, so\n a campaign can be middle-clicked into a tab or copied out of the\n context menu — affordances a row handler cannot offer. The grid's\n own row click fires too, so the link stops the event rather than\n pushing the same route twice.\n */}\n {campaignHref(row.id) ? (\n <AppLink\n href={campaignHref(row.id) as string}\n onClick={(event: { stopPropagation: () => void }) =>\n event.stopPropagation()\n }\n style={{ minWidth: 0 }}\n >\n <Typography variant=\"body2\" noWrap>\n {row.name}\n </Typography>\n </AppLink>\n ) : (\n <Typography variant=\"body2\" noWrap sx={{ minWidth: 0 }}>\n {row.name}\n </Typography>\n )}\n {row.legacy ? (\n <Chip\n size=\"small\"\n variant=\"outlined\"\n label=\"Single send\"\n // A label that reads \"Single sen\" is worse than a shorter name.\n sx={{ flexShrink: 0 }}\n title={\n 'Sent before campaigns grouped their emails. Its report ' +\n 'and its unsubscribe links are unchanged.'\n }\n />\n ) : null}\n </Stack>\n ),\n },\n /*\n WHERE IT IS PLACED, on the org hub only. Under a site every row is on\n that site by construction, so the column would say one thing thirty\n times.\n */\n ...(orgMount\n ? [\n {\n field: 'sitesLabel',\n headerName: 'Sites',\n width: 170,\n sortable: false,\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\" noWrap>\n {row.sitesLabel}\n </Typography>\n ),\n },\n ]\n : []),\n {\n field: 'windowState',\n headerName: 'Window',\n width: 170,\n renderCell: ({ row }: any) => {\n const start = formatDay(row.startAtMs)\n const end = formatDay(row.endAtMs)\n const range =\n start && end && start !== end\n ? `${start} – ${end}`\n : start || end || ''\n return (\n <Stack sx={{ minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {WINDOW_LABEL[row.windowState as CampaignListRow['windowState']]}\n </Typography>\n {range ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {range}\n </Typography>\n ) : null}\n </Stack>\n )\n },\n },\n {\n field: 'listIds',\n headerName: 'Lists',\n width: 140,\n sortable: false,\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\" noWrap>\n {row.listIds.length\n ? row.listIds\n .map((id: string) => listNames.get(id) ?? id)\n .join(', ')\n : '—'}\n </Typography>\n ),\n },\n /*\n THE FOUR COUNTS, RIGHT-ALIGNED HEAD AND BODY.\n A figure is read by its last digit, so a column of them lines up on\n the right or it does not line up at all. `headerAlign` has to be said\n as well as `align`: a grid column defaults its header to the column\n type's alignment rather than to the cell's, which is how these came to\n sit with left headers over figures nobody could compare down the page.\n\n EVERY ONE OF THEM MEASURES THE MAIL, and the headings say so. What a\n campaign CAUSED — the submissions, leads, contacts and bookings\n credited to it — is not a column here, because there is no figure to\n read: a container has no conversion counter of its own, so a column\n would be an aggregation per row for a campaign and a subcollection\n document per row for a single send, on a list that costs two queries\n however many campaigns it holds. Headings that named the campaign over\n figures that all described its mail were the cheaper mistake, so the\n headings name the mail and the note under the table says where the\n outcome figures are.\n */\n {\n field: 'emails',\n headerName: 'Emails',\n width: 128,\n align: 'right',\n headerAlign: 'right',\n /*\n THE COUNT, AND WHAT IS STILL HAPPENING TO IT.\n\n `sending` is called out apart from `scheduled` because the two are\n opposite readings of the same stored status: an email delivering an\n audience larger than one batch sits as `scheduled` between runs, and\n rolling it in with the ones that have mailed nobody reports a\n campaign that is half delivered as a campaign that has not started.\n\n The note sits UNDER the figure rather than beside it — the column\n would otherwise have to be wide enough for the longest sentence, and\n the figure is what the column is read for.\n */\n renderCell: ({ row }: any) => {\n const { sends, sending, scheduled } = row.rollup\n const note = [\n sending ? `${sending} sending` : '',\n scheduled ? `${scheduled} scheduled` : '',\n ]\n .filter(Boolean)\n .join(', ')\n return (\n <Stack sx={{ alignItems: 'flex-end', minWidth: 0, width: 1 }}>\n <Typography variant=\"body2\">{String(sends)}</Typography>\n {note ? (\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {note}\n </Typography>\n ) : null}\n </Stack>\n )\n },\n },\n {\n field: 'sent',\n headerName: 'Mail sent',\n width: 112,\n align: 'right',\n headerAlign: 'right',\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\">{figure(row.rollup.sent)}</Typography>\n ),\n },\n {\n field: 'opens',\n headerName: 'Mail opens',\n width: 112,\n align: 'right',\n headerAlign: 'right',\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\">{figure(row.rollup.opens)}</Typography>\n ),\n },\n {\n field: 'clicks',\n headerName: 'Mail clicks',\n width: 112,\n align: 'right',\n headerAlign: 'right',\n renderCell: ({ row }: any) => (\n <Typography variant=\"body2\">{figure(row.rollup.clicks)}</Typography>\n ),\n },\n /*\n THE TRAILING CLUSTER, through the grid's own actions column.\n `listActionsColumn` is what every other grid list in the console\n renders, so the reader cannot tell which family of table they are\n standing in — the hand-rolled tables on this surface reach the same\n `RowActionsMenu` from the other direction.\n\n Opening the campaign is restated here even though the row click does\n the same thing, for the reason the screens table restates its own: the\n menu is where a row's actions are NAMED, and an action absent from it\n reads as an action the row does not have.\n\n A \"Single send\" row is a SEND with no container — the table adopts it\n so a merchant's history is not missing — and there is no container\n under it to delete. Its entry is shown disabled with that reason\n rather than hidden, because a control that vanishes and one that does\n not apply look identical from the outside.\n */\n listActionsColumn(\n (row: any) => (\n <ListRowActions\n label={String(row.name ?? row.id)}\n items={[\n {\n key: 'details',\n label: 'Open campaign',\n icon: <MdiIcon path={mdiEyeOutline.path} size={0.8} />,\n href: campaignHref(row.id) ?? undefined,\n disabled: !campaignHref(row.id),\n disabledReason: campaignHref(row.id)\n ? undefined\n : 'This site’s console URL has not resolved yet',\n },\n {\n key: 'delete',\n label: 'Delete campaign',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: row.legacy || Boolean(deletingId),\n disabledReason: row.legacy\n ? 'This is a single send, not a campaign. Open it to ' +\n 'manage the email itself.'\n : 'A campaign is being deleted',\n onClick: () => void handleDelete(row as CampaignListRow),\n },\n ]}\n />\n ),\n { width: 72 },\n ),\n ],\n [listNames, campaignHref, deletingId, handleDelete, orgMount],\n )\n\n return (\n <CardDisplay\n header={'Campaigns'}\n help={pluginDocsHelp('emailCampaigns', {\n anchor: '#campaigns-group-emails',\n excerpt:\n 'A campaign groups the emails you send to a set of lists over a ' +\n 'window of dates. Open one to write and send an email inside it.',\n })}\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={creating}\n onClick={() => {\n setCreateError(null)\n setCreateOpen(true)\n }}\n >\n {creating ? 'Creating…' : 'Create campaign'}\n </Button>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n <ListTable\n rows={rows}\n columns={columns as any}\n onOpen={(id) => openCampaign(id)}\n noRowsLabel=\"No campaigns yet\"\n noRowsDescription=\"A campaign groups the emails you send to a set of lists.\"\n noRowsAction={\n <Button variant=\"contained\" onClick={() => setCreateOpen(true)}>\n {'Create campaign'}\n </Button>\n }\n />\n {/*\n WHAT THIS TABLE MEASURES, said rather than inferred from the column\n names. Every figure in it is a fact about the campaign's mail, and a\n reader comparing rows is comparing mailings — the conversions and the\n destinations credited to a campaign are on the campaign's own page,\n because counting them for every row is a read per row on a list whose\n whole cost is two queries.\n */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'These figures measure each campaign’s mail. What a campaign ' +\n 'caused — the form submissions, leads, contacts and bookings ' +\n 'credited to it — and the pages it sent people to are on the ' +\n 'campaign’s own page.'}\n </Typography>\n {sendsTruncated || campaignsTruncated ? (\n <Alert severity=\"info\">\n {`Showing the most recent ${CONTAINER_CEILING} campaigns and ` +\n `${CAMPAIGN_CEILING} sends. ${\n hostId ? 'This site' : 'This organization'\n } has more — the ones ` +\n 'listed are not necessarily the most recent, because a send ' +\n 'carries no date field that every writer stamps.'}\n </Alert>\n ) : null}\n </Stack>\n {/*\n The console's own create drawer, from the shared library rather than a\n second one that looks like it. What a campaign collects beyond a name\n is its window, the lists it is aimed at and the stream its emails open\n on; the description box is left off because the container stores none,\n and a field the writer discards is worse than one never offered.\n */}\n {/* Draws nothing: the zone the topic catalog's owner answers through. */}\n {topicSource}\n <CreateArtifactDrawer\n open={createOpen}\n onClose={() => setCreateOpen(false)}\n title=\"Create campaign\"\n submitLabel=\"Create campaign\"\n includeDescription={false}\n onSubmit={handleCreate}\n extraFields={campaignFields(\n listOptions,\n topicOptions,\n orgMount ? orgSiteOptions(orgMount) : null,\n )}\n errorSlot={\n createError ? (\n <Alert severity=\"error\" sx={{ mt: 2, mb: 1 }}>\n {createError}\n </Alert>\n ) : null\n }\n />\n </CardDisplay>\n )\n}\n/**\n * What a campaign collects beyond its name.\n *\n * Data-driven-forms field descriptors, built from the org's own lists and\n * topics so the drawer offers what this workspace actually has. Dates are\n * plain `date` inputs: a campaign window is a day at each end, and a time of\n * day would be a precision the model does not carry.\n */\nfunction campaignFields(\n lists: Array<{ value: string; label: string }>,\n topics: Array<{ value: string; label: string }>,\n /** The org's sites, on the org hub only — a site hub places on itself. */\n sites: Array<{ value: string; label: string }> | null,\n): any[] {\n return [\n ...(sites\n ? [\n {\n component: 'select',\n name: 'siteIds',\n label: 'Sites',\n multiple: true,\n initialValue: [],\n helperText:\n 'The sites this campaign is offered on. Leave empty for every site.',\n disableDefaultOption: true,\n options: sites,\n },\n ]\n : []),\n {\n component: 'text-field',\n name: 'startAt',\n label: 'Starts',\n type: 'date',\n helperText: 'When the campaign window opens',\n },\n {\n component: 'text-field',\n name: 'endAt',\n label: 'Ends',\n type: 'date',\n helperText: 'Leave empty for an open-ended campaign',\n InputLabelProps: { shrink: true },\n },\n {\n component: 'select',\n name: 'listIds',\n label: 'Lists',\n multiple: true,\n initialValue: [],\n // A campaign with no list is legitimate: its emails can go to leads, to\n // site members, or to a segment. The lists are what it is AIMED at.\n helperText: 'The lists this campaign is aimed at',\n disableDefaultOption: true,\n options: lists,\n },\n {\n component: 'select',\n name: 'topicId',\n label: 'Topic',\n helperText: 'The stream its emails open on — each one can change it',\n disableDefaultOption: true,\n options: topics,\n },\n ]\n}\n\n/**\n * The Sites cell: where a campaign is offered.\n *\n * A container reads its `visibleTo`; a single send, which has no container,\n * is on the one site it was sent as. An empty placement is said rather than\n * left blank, because a blank cell reads as \"every site\" and it means none.\n */\nfunction campaignSitesLabel(\n mount: MarketingOrgMount,\n row: CampaignListRow,\n container: EmailCampaign | undefined,\n): string {\n if (row.legacy) return orgSiteName(mount, row.sends[0]?.hostId) || '—'\n const ids = campaignSiteIds(container)\n if (ids === null) return 'Every site'\n if (!ids.length) return 'No site'\n return ids.map((id) => orgSiteName(mount, id)).join(', ')\n}\n\nHostCampaignsCard.displayName = 'HostCampaignsCard'\n\nexport default HostCampaignsCard\n"],"names":["buildRoute","createResourceUid","pluginDocsHelp","Route","ceilingedWindow","collectionCeiling","mdiDeleteOutline","mdiEyeOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListRowActions","ListTable","listActionsColumn","useSnackbar","Alert","Button","Chip","Stack","Typography","collection","limit","query","setDoc","useCallback","useMemo","useState","useRouter","useConsoleHostRoute","useFirestore","useFirestoreCollection","useUser","campaignListRows","campaignSiteIds","campaignVisibleTo","CreateArtifactDrawer","campaignContainerDoc","campaignContainersQuery","campaignSendsQuery","orgSiteName","orgSiteOptions","topicCatalogHostId","useMarketingOrgId","useMarketingOrgMount","useCampaignManageApi","useCampaignTopicOptions","CAMPAIGN_CEILING","CONTAINER_CEILING","formatDay","ms","Date","toLocaleDateString","figure","value","toLocaleString","WINDOW_LABEL","undated","upcoming","running","ended","HostCampaignsCard","props","hostId","basePath","firestore","router","orgSlug","subdomain","hubPath","HOST_PLUGIN","host","pluginSlug","data","user","enqueueSnackbar","confirm","orgMount","orgId","manageApi","sendDocs","sends","idField","rows","readSends","truncated","sendsTruncated","campaignDocs","containers","readCampaigns","campaignsTruncated","listDocs","createOpen","setCreateOpen","topics","source","topicSource","enabled","topicOptions","map","topic","id","label","name","listNames","names","Map","list","set","String","$id","listOptions","campaigns","filter","campaign","deletedAt","byId","now","row","sitesLabel","campaignSitesLabel","get","createError","setCreateError","creating","setCreating","deletingId","setDeletingId","openCampaign","push","handleCreate","values","displayName","trim","startAtMs","startAt","parse","endAtMs","endAt","Number","isFinite","listIds","Array","isArray","topicId","visibleTo","siteIds","createdAtMs","createdBy","uid","error","console","variant","allowDuplicate","campaignHref","handleDelete","emails","length","unfinished","rollup","scheduled","sending","agreed","title","description","confirmationText","then","catch","response","payload","action","campaignId","ok","persist","columns","field","headerName","flex","minWidth","renderCell","direction","spacing","sx","alignItems","width","href","onClick","event","stopPropagation","style","noWrap","legacy","size","flexShrink","sortable","start","end","range","windowState","color","join","align","headerAlign","note","Boolean","sent","opens","clicks","items","key","icon","path","undefined","disabled","disabledReason","destructive","header","help","anchor","excerpt","HeaderProps","contentGutterX","contentGutterY","onOpen","noRowsLabel","noRowsDescription","noRowsAction","severity","open","onClose","submitLabel","includeDescription","onSubmit","extraFields","campaignFields","errorSlot","mt","mb","lists","sites","component","multiple","initialValue","helperText","disableDefaultOption","options","type","InputLabelProps","shrink","mount","container","ids"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,UAAU,EAAEC,iBAAiB,EAAEC,cAAc,EAAEC,KAAK,QAAQ,eAAc;AACnF;;;;CAIC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,yBAAwB;AACxE,SACEC,OAAO,EACPC,WAAW,EACXC,OAAO,EACPC,sBAAsB,QACjB,uBAAsB;AAC7B,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACtE,SAASC,UAAU,EAAEC,KAAK,EAAEC,KAAK,EAAEC,MAAM,QAAQ,qBAAoB;AACrE,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SAASC,SAAS,QAAQ,kBAAiB;AAC3C,SACEC,mBAAmB,EACnBC,YAAY,EACZC,sBAAsB,EACtBC,OAAO,QACF,iCAAgC;AACvC,SACEC,gBAAgB,EAChBC,eAAe,EACfC,iBAAiB,QAKZ,yCAAwC;AAC/C,SAASC,oBAAoB,QAAQ,6BAA4B;A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,SAAS0B,mBACPiI,KAAwB,EACxBnI,GAAoB,EACpBoI,SAAoC;QAEMpI;IAA1C,IAAIA,IAAIyE,MAAM,EAAE,OAAOvJ,YAAYiN,QAAOnI,cAAAA,IAAIrC,KAAK,CAAC,EAAE,qBAAZqC,YAAcvD,MAAM,KAAK;IACnE,MAAM4L,MAAMzN,gBAAgBwN;IAC5B,IAAIC,QAAQ,MAAM,OAAO;IACzB,IAAI,CAACA,IAAI9F,MAAM,EAAE,OAAO;IACxB,OAAO8F,IAAIxJ,GAAG,CAAC,CAACE,KAAO7D,YAAYiN,OAAOpJ,KAAKmG,IAAI,CAAC;AACtD;AAEA3I,kBAAkBuE,WAAW,GAAG;AAEhC,eAAevE,kBAAiB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export interface EmailComposeCardProps {
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
/** The site, or `null` on the org Marketing hub. */
|
|
3
|
+
hostId: string | null;
|
|
4
|
+
/** The message document under `orgs/{orgId}/campaigns`. */
|
|
4
5
|
emailId: string;
|
|
5
6
|
/** The emails hub URL, for the way back to the message's own page. */
|
|
6
7
|
basePath: string;
|
|
@@ -51,29 +51,40 @@ import { jsx as _jsx } from "react/jsx-runtime";
|
|
|
51
51
|
* the stored status alone would let somebody rewrite the copy of a message
|
|
52
52
|
* that is already reaching inboxes; `campaignSendDisplay` is what tells the
|
|
53
53
|
* two apart.
|
|
54
|
+
*
|
|
55
|
+
* ## The site it is written as
|
|
56
|
+
*
|
|
57
|
+
* The record is the org's; the composer is a site's — its senders, its
|
|
58
|
+
* designs, its experiments. Under a site that is the site. On the org hub it
|
|
59
|
+
* is the send's own `hostId`, and a send that names none is not opened for
|
|
60
|
+
* writing there.
|
|
54
61
|
*/ import { pluginDocsHelp } from "@aglyn/aglyn";
|
|
55
62
|
import { AppLink, CardDisplay } from "@aglyn/shared-ui-jsx";
|
|
56
63
|
import { Button, Typography } from "@mui/material";
|
|
57
64
|
import { useFirestore, useFirestoreDoc } from "@aglyn/tenant-feature-instance";
|
|
58
|
-
import { doc } from "firebase/firestore";
|
|
59
65
|
import { useRouter } from "next/navigation";
|
|
60
66
|
import { campaignSendDisplay, CAMPAIGN_SEND_CONTAINER_FIELD } from "@aglyn/shared-ui-email-campaigns/model/campaign-container";
|
|
61
67
|
import CampaignComposer from "./campaign-composer.js";
|
|
68
|
+
import { campaignSendDoc } from "./campaign-queries.js";
|
|
69
|
+
import { useMarketingOrgId, useMarketingOrgMount } from "./marketing-org-mount.js";
|
|
62
70
|
const composeDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
63
71
|
anchor: '#send-a-campaign',
|
|
64
72
|
excerpt: 'Everything one email decides: who it goes to, how it is written, who ' + 'it appears to come from, and how many people it reaches.'
|
|
65
73
|
});
|
|
66
74
|
export function EmailComposeCard(props) {
|
|
67
|
-
var _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9, _ref10, _ref11, _ref12, _ref13, _ref14;
|
|
68
|
-
const {
|
|
75
|
+
var _props_hostId, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9, _ref10, _ref11, _ref12, _ref13, _ref14;
|
|
76
|
+
const { emailId, basePath } = props;
|
|
69
77
|
const firestore = useFirestore();
|
|
70
78
|
const router = useRouter();
|
|
71
|
-
const
|
|
79
|
+
const orgMount = useMarketingOrgMount();
|
|
80
|
+
const { orgId } = useMarketingOrgId(props.hostId);
|
|
81
|
+
const { data: email, status } = useFirestoreDoc(()=>orgId ? campaignSendDoc(firestore, orgId, emailId) : null, [
|
|
72
82
|
firestore,
|
|
73
|
-
|
|
83
|
+
orgId,
|
|
74
84
|
emailId
|
|
75
85
|
]);
|
|
76
|
-
const
|
|
86
|
+
/** The site this email is written as; see the file header. */ const hostId = (_props_hostId = props.hostId) != null ? _props_hostId : (email == null ? void 0 : email.hostId) ? String(email.hostId) : null;
|
|
87
|
+
const detailHref = orgMount ? `${orgMount.basePath}/emails/${emailId}` : `${basePath}/messages/${emailId}`;
|
|
77
88
|
const headerActions = /*#__PURE__*/ _jsx(Button, _extends({
|
|
78
89
|
component: AppLink
|
|
79
90
|
}, {
|
|
@@ -96,7 +107,7 @@ export function EmailComposeCard(props) {
|
|
|
96
107
|
* Empty while it still can be. Each case is a different fact about the
|
|
97
108
|
* record and not a variation on "no": one has not loaded, one is in inboxes
|
|
98
109
|
* already, one is being delivered right now.
|
|
99
|
-
*/ const refusal = !email ? status === 'loading' ? 'Loading this email…' : 'This email could not be loaded. It may have been deleted.' : editable ? '' : (display == null ? void 0 : display.state) === 'sending' ? 'This email is being sent right now, so its message can no longer ' + 'be changed. Its page reports what it has reached so far.' : state === 'sent' ? 'This email has been sent, so its subject, message and audience ' + 'describe mail that is already in inboxes. Compose a new email ' + 'to say something else.' : 'This email was canceled, so it can no longer be written or put ' + 'back on the schedule. Compose a new email.';
|
|
110
|
+
*/ const refusal = !email ? status === 'loading' ? 'Loading this email…' : 'This email could not be loaded. It may have been deleted.' : !hostId ? 'This email does not record which site it is sent as, so it can ' + 'only be written from that site’s own Emails page.' : editable ? '' : (display == null ? void 0 : display.state) === 'sending' ? 'This email is being sent right now, so its message can no longer ' + 'be changed. Its page reports what it has reached so far.' : state === 'sent' ? 'This email has been sent, so its subject, message and audience ' + 'describe mail that is already in inboxes. Compose a new email ' + 'to say something else.' : 'This email was canceled, so it can no longer be written or put ' + 'back on the schedule. Compose a new email.';
|
|
100
111
|
return /*#__PURE__*/ _jsx(CardDisplay, {
|
|
101
112
|
header: subject || displayName || 'Untitled email',
|
|
102
113
|
subheader: 'Write this email',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/email-compose-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\n/**\n * WRITING ONE EMAIL — its own route, and its own card.\n *\n * ## Why it is not on the message's page\n *\n * `/emails/messages/{emailId}` answers \"what did this email do\": delivery,\n * engagement, every rate over its own denominator, the links that were\n * followed and who it reached. Writing the thing is a different job with a\n * different shape — a form, a preview, and one irreversible button — and\n * carrying both on one route made the reader of a report scroll past a\n * composer and the writer of an email scroll past a table of zeros.\n *\n * So the record's page reports, and `…/edit` writes. It is the grammar this\n * surface already reads by: an audience is `…/audiences/{listId}` and its\n * settings are `…/audiences/{listId}/edit`, and a screen's page and its\n * besigner are two addresses for the same reason. Creating is still a drawer\n * on the list — it collects the name, mints the record and routes here — so no\n * list on this surface carries a form above it.\n *\n * ## Why the card is HERE and not inside the composer\n *\n * The composer is also mounted inside the campaign detail card, which already\n * supplies a card of its own; a `CardDisplay` in the component would nest one\n * inside another there. The surface owns the chrome, exactly as `ListEditCard`\n * owns the chrome around the audience rule fields.\n *\n * ## What may be edited\n *\n * Only an email that is still unsent. The route enforces it too — `schedule`\n * and `draft` answer 409 on a sent or canceled record — and this is the same\n * refusal said before the merchant types rather than after they press Send. An\n * email PART WAY THROUGH a send is stored as `scheduled` between batches, so\n * the stored status alone would let somebody rewrite the copy of a message\n * that is already reaching inboxes; `campaignSendDisplay` is what tells the\n * two apart.\n */\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { Button, Typography } from '@mui/material'\nimport { useFirestore, useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { doc } from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport {\n campaignSendDisplay,\n CAMPAIGN_SEND_CONTAINER_FIELD,\n} from '@aglyn/shared-ui-email-campaigns/model/campaign-container'\nimport CampaignComposer from './campaign-composer'\n\nconst composeDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#send-a-campaign',\n excerpt:\n 'Everything one email decides: who it goes to, how it is written, who ' +\n 'it appears to come from, and how many people it reaches.',\n})\n\nexport interface EmailComposeCardProps {\n hostId: string\n /** The message document under `hosts/{hostId}/campaigns`. */\n emailId: string\n /** The emails hub URL, for the way back to the message's own page. */\n basePath: string\n}\n\nexport function EmailComposeCard(props: EmailComposeCardProps) {\n const { hostId, emailId, basePath } = props\n const firestore = useFirestore()\n const router = useRouter()\n\n const { data: email, status } = useFirestoreDoc<Record<string, any>>(\n () => doc(firestore, 'hosts', hostId, 'campaigns', emailId),\n [firestore, hostId, emailId],\n )\n\n const detailHref = `${basePath}/messages/${emailId}`\n const headerActions = (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={detailHref}\n size=\"small\"\n color=\"primary\"\n >\n {'Back to the email'}\n </Button>\n )\n\n const subject = String(email?.subject ?? '')\n const displayName = String(email?.displayName ?? '')\n const state = String(email?.status ?? '')\n const display = email ? campaignSendDisplay(email as never) : null\n const editable =\n (state === 'draft' || state === 'scheduled') && display?.state !== 'sending'\n\n /**\n * Why this email cannot be written, in the words that say what to do next.\n *\n * Empty while it still can be. Each case is a different fact about the\n * record and not a variation on \"no\": one has not loaded, one is in inboxes\n * already, one is being delivered right now.\n */\n const refusal = !email\n ? status === 'loading'\n ? 'Loading this email…'\n : 'This email could not be loaded. It may have been deleted.'\n : editable\n ? ''\n : display?.state === 'sending'\n ? 'This email is being sent right now, so its message can no longer ' +\n 'be changed. Its page reports what it has reached so far.'\n : state === 'sent'\n ? 'This email has been sent, so its subject, message and audience ' +\n 'describe mail that is already in inboxes. Compose a new email ' +\n 'to say something else.'\n : 'This email was canceled, so it can no longer be written or put ' +\n 'back on the schedule. Compose a new email.'\n\n return (\n <CardDisplay\n header={subject || displayName || 'Untitled email'}\n subheader={'Write this email'}\n help={composeDocsHelp}\n contentGutterX\n contentGutterY\n HeaderProps={{ action: headerActions }}\n >\n {refusal ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {refusal}\n </Typography>\n ) : (\n <CampaignComposer\n hostId={hostId}\n campaignId={emailId}\n emailCampaignId={\n email?.[CAMPAIGN_SEND_CONTAINER_FIELD]\n ? String(email[CAMPAIGN_SEND_CONTAINER_FIELD])\n : undefined\n }\n displayName={displayName || undefined}\n initial={{\n subject,\n body: String(email?.body ?? ''),\n fromName: String(email?.fromName ?? ''),\n replyTo: String(email?.replyTo ?? ''),\n /*\n * The sender this email is set to go out as, so reopening a draft\n * does not silently move it onto whichever sender has become the\n * site's default since it was saved.\n */\n senderId: String(email?.senderId ?? ''),\n preheader: String(email?.preheader ?? ''),\n audience: String(email?.audience ?? ''),\n listId: String(email?.listId ?? ''),\n segmentId: String(email?.segmentId ?? ''),\n topicId: String(email?.topicId ?? ''),\n /*\n * Which of the two ways this email is written. The composer\n * resolves the mode from this field through the same function the\n * send path reads, so a designed draft reopens designed.\n */\n templateScreenId: String(email?.templateScreenId ?? ''),\n /*\n * The plain-text half, and the design version it was written\n * against. Absent means the design generates it — the composer\n * reads that through the same resolver the record's shape is\n * defined by, so a stale override is named rather than guessed at.\n */\n plainText: String(email?.plainText ?? ''),\n plainTextVersionId: String(email?.plainTextVersionId ?? ''),\n }}\n /*\n * A send or a schedule lands on the record, and the record's page is\n * where its report will be — so the merchant is left looking at what\n * they just did rather than at the form that did it.\n */\n onSent={() => router.push(detailHref)}\n />\n )}\n </CardDisplay>\n )\n}\nEmailComposeCard.displayName = 'EmailComposeCard'\n\nexport default EmailComposeCard\n"],"names":["pluginDocsHelp","AppLink","CardDisplay","Button","Typography","useFirestore","useFirestoreDoc","doc","useRouter","campaignSendDisplay","CAMPAIGN_SEND_CONTAINER_FIELD","CampaignComposer","composeDocsHelp","anchor","excerpt","EmailComposeCard","props","hostId","emailId","basePath","firestore","router","data","email","status","detailHref","headerActions","component","componentVariant","nativeButton","href","size","color","subject","String","displayName","state","display","editable","refusal","header","subheader","help","contentGutterX","contentGutterY","HeaderProps","action","variant","campaignId","emailCampaignId","undefined","initial","body","fromName","replyTo","senderId","preheader","audience","listId","segmentId","topicId","templateScreenId","plainText","plainTextVersionId","onSent","push"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCC,GAED,SAASA,cAAc,QAAQ,eAAc;AAC7C,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,SAASC,MAAM,EAAEC,UAAU,QAAQ,gBAAe;AAClD,SAASC,YAAY,EAAEC,eAAe,QAAQ,iCAAgC;AAC9E,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,SAAS,QAAQ,kBAAiB;AAC3C,SACEC,mBAAmB,EACnBC,6BAA6B,QACxB,4DAA2D;AAClE,OAAOC,sBAAsB,yBAAqB;AAElD,MAAMC,kBAAkBZ,eAAe,kBAAkB;IACvDa,QAAQ;IACRC,SACE,0EACA;AACJ;AAUA,OAAO,SAASC,iBAAiBC,KAA4B;;IAC3D,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAEC,QAAQ,EAAE,GAAGH;IACtC,MAAMI,YAAYf;IAClB,MAAMgB,SAASb;IAEf,MAAM,EAAEc,MAAMC,KAAK,EAAEC,MAAM,EAAE,GAAGlB,gBAC9B,IAAMC,IAAIa,WAAW,SAASH,QAAQ,aAAaC,UACnD;QAACE;QAAWH;QAAQC;KAAQ;IAG9B,MAAMO,aAAa,GAAGN,SAAS,UAAU,EAAED,SAAS;IACpD,MAAMQ,8BACJ,KAACvB;QACCwB,WAAW1B;OACN;QAAE2B,kBAAkB;QAASC,cAAc;IAAM;QACtDC,MAAML;QACNM,MAAK;QACLC,OAAM;kBAEL;;IAIL,MAAMC,UAAUC,eAAOX,yBAAAA,MAAOU,OAAO,mBAAI;IACzC,MAAME,cAAcD,gBAA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C,SAAS,qBAAI;gBACtCC,SAAS1B,iBAAOX,yBAAAA,MAAOqC,OAAO,qBAAI;gBAClC;;;;aAIC,GACDC,kBAAkB3B,iBAAOX,yBAAAA,MAAOsC,gBAAgB,qBAAI;gBACpD;;;;;aAKC,GACDC,WAAW5B,iBAAOX,yBAAAA,MAAOuC,SAAS,qBAAI;gBACtCC,oBAAoB7B,iBAAOX,yBAAAA,MAAOwC,kBAAkB,qBAAI;YAC1D;YACA;;;;WAIC,GACDC,QAAQ,IAAM3C,OAAO4C,IAAI,CAACxC;;;AAKpC;AACAV,iBAAiBoB,WAAW,GAAG;AAE/B,eAAepB,iBAAgB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/email-compose-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\n/**\n * WRITING ONE EMAIL — its own route, and its own card.\n *\n * ## Why it is not on the message's page\n *\n * `/emails/messages/{emailId}` answers \"what did this email do\": delivery,\n * engagement, every rate over its own denominator, the links that were\n * followed and who it reached. Writing the thing is a different job with a\n * different shape — a form, a preview, and one irreversible button — and\n * carrying both on one route made the reader of a report scroll past a\n * composer and the writer of an email scroll past a table of zeros.\n *\n * So the record's page reports, and `…/edit` writes. It is the grammar this\n * surface already reads by: an audience is `…/audiences/{listId}` and its\n * settings are `…/audiences/{listId}/edit`, and a screen's page and its\n * besigner are two addresses for the same reason. Creating is still a drawer\n * on the list — it collects the name, mints the record and routes here — so no\n * list on this surface carries a form above it.\n *\n * ## Why the card is HERE and not inside the composer\n *\n * The composer is also mounted inside the campaign detail card, which already\n * supplies a card of its own; a `CardDisplay` in the component would nest one\n * inside another there. The surface owns the chrome, exactly as `ListEditCard`\n * owns the chrome around the audience rule fields.\n *\n * ## What may be edited\n *\n * Only an email that is still unsent. The route enforces it too — `schedule`\n * and `draft` answer 409 on a sent or canceled record — and this is the same\n * refusal said before the merchant types rather than after they press Send. An\n * email PART WAY THROUGH a send is stored as `scheduled` between batches, so\n * the stored status alone would let somebody rewrite the copy of a message\n * that is already reaching inboxes; `campaignSendDisplay` is what tells the\n * two apart.\n *\n * ## The site it is written as\n *\n * The record is the org's; the composer is a site's — its senders, its\n * designs, its experiments. Under a site that is the site. On the org hub it\n * is the send's own `hostId`, and a send that names none is not opened for\n * writing there.\n */\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { Button, Typography } from '@mui/material'\nimport { useFirestore, useFirestoreDoc } from '@aglyn/tenant-feature-instance'\nimport { useRouter } from 'next/navigation'\nimport {\n campaignSendDisplay,\n CAMPAIGN_SEND_CONTAINER_FIELD,\n} from '@aglyn/shared-ui-email-campaigns/model/campaign-container'\nimport CampaignComposer from './campaign-composer'\nimport { campaignSendDoc } from './campaign-queries'\nimport { useMarketingOrgId, useMarketingOrgMount } from './marketing-org-mount'\n\nconst composeDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#send-a-campaign',\n excerpt:\n 'Everything one email decides: who it goes to, how it is written, who ' +\n 'it appears to come from, and how many people it reaches.',\n})\n\nexport interface EmailComposeCardProps {\n /** The site, or `null` on the org Marketing hub. */\n hostId: string | null\n /** The message document under `orgs/{orgId}/campaigns`. */\n emailId: string\n /** The emails hub URL, for the way back to the message's own page. */\n basePath: string\n}\n\nexport function EmailComposeCard(props: EmailComposeCardProps) {\n const { emailId, basePath } = props\n const firestore = useFirestore()\n const router = useRouter()\n const orgMount = useMarketingOrgMount()\n const { orgId } = useMarketingOrgId(props.hostId)\n\n const { data: email, status } = useFirestoreDoc<Record<string, any>>(\n () => (orgId ? campaignSendDoc(firestore, orgId, emailId) : null),\n [firestore, orgId, emailId],\n )\n /** The site this email is written as; see the file header. */\n const hostId: string | null =\n props.hostId ?? (email?.hostId ? String(email.hostId) : null)\n\n const detailHref = orgMount\n ? `${orgMount.basePath}/emails/${emailId}`\n : `${basePath}/messages/${emailId}`\n const headerActions = (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={detailHref}\n size=\"small\"\n color=\"primary\"\n >\n {'Back to the email'}\n </Button>\n )\n\n const subject = String(email?.subject ?? '')\n const displayName = String(email?.displayName ?? '')\n const state = String(email?.status ?? '')\n const display = email ? campaignSendDisplay(email as never) : null\n const editable =\n (state === 'draft' || state === 'scheduled') && display?.state !== 'sending'\n\n /**\n * Why this email cannot be written, in the words that say what to do next.\n *\n * Empty while it still can be. Each case is a different fact about the\n * record and not a variation on \"no\": one has not loaded, one is in inboxes\n * already, one is being delivered right now.\n */\n const refusal = !email\n ? status === 'loading'\n ? 'Loading this email…'\n : 'This email could not be loaded. It may have been deleted.'\n : !hostId\n ? 'This email does not record which site it is sent as, so it can ' +\n 'only be written from that site’s own Emails page.'\n : editable\n ? ''\n : display?.state === 'sending'\n ? 'This email is being sent right now, so its message can no longer ' +\n 'be changed. Its page reports what it has reached so far.'\n : state === 'sent'\n ? 'This email has been sent, so its subject, message and audience ' +\n 'describe mail that is already in inboxes. Compose a new email ' +\n 'to say something else.'\n : 'This email was canceled, so it can no longer be written or put ' +\n 'back on the schedule. Compose a new email.'\n\n return (\n <CardDisplay\n header={subject || displayName || 'Untitled email'}\n subheader={'Write this email'}\n help={composeDocsHelp}\n contentGutterX\n contentGutterY\n HeaderProps={{ action: headerActions }}\n >\n {refusal ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {refusal}\n </Typography>\n ) : (\n <CampaignComposer\n hostId={hostId}\n campaignId={emailId}\n emailCampaignId={\n email?.[CAMPAIGN_SEND_CONTAINER_FIELD]\n ? String(email[CAMPAIGN_SEND_CONTAINER_FIELD])\n : undefined\n }\n displayName={displayName || undefined}\n initial={{\n subject,\n body: String(email?.body ?? ''),\n fromName: String(email?.fromName ?? ''),\n replyTo: String(email?.replyTo ?? ''),\n /*\n * The sender this email is set to go out as, so reopening a draft\n * does not silently move it onto whichever sender has become the\n * site's default since it was saved.\n */\n senderId: String(email?.senderId ?? ''),\n preheader: String(email?.preheader ?? ''),\n audience: String(email?.audience ?? ''),\n listId: String(email?.listId ?? ''),\n segmentId: String(email?.segmentId ?? ''),\n topicId: String(email?.topicId ?? ''),\n /*\n * Which of the two ways this email is written. The composer\n * resolves the mode from this field through the same function the\n * send path reads, so a designed draft reopens designed.\n */\n templateScreenId: String(email?.templateScreenId ?? ''),\n /*\n * The plain-text half, and the design version it was written\n * against. Absent means the design generates it — the composer\n * reads that through the same resolver the record's shape is\n * defined by, so a stale override is named rather than guessed at.\n */\n plainText: String(email?.plainText ?? ''),\n plainTextVersionId: String(email?.plainTextVersionId ?? ''),\n }}\n /*\n * A send or a schedule lands on the record, and the record's page is\n * where its report will be — so the merchant is left looking at what\n * they just did rather than at the form that did it.\n */\n onSent={() => router.push(detailHref)}\n />\n )}\n </CardDisplay>\n )\n}\nEmailComposeCard.displayName = 'EmailComposeCard'\n\nexport default EmailComposeCard\n"],"names":["pluginDocsHelp","AppLink","CardDisplay","Button","Typography","useFirestore","useFirestoreDoc","useRouter","campaignSendDisplay","CAMPAIGN_SEND_CONTAINER_FIELD","CampaignComposer","campaignSendDoc","useMarketingOrgId","useMarketingOrgMount","composeDocsHelp","anchor","excerpt","EmailComposeCard","props","emailId","basePath","firestore","router","orgMount","orgId","hostId","data","email","status","String","detailHref","headerActions","component","componentVariant","nativeButton","href","size","color","subject","displayName","state","display","editable","refusal","header","subheader","help","contentGutterX","contentGutterY","HeaderProps","action","variant","campaignId","emailCampaignId","undefined","initial","body","fromName","replyTo","senderId","preheader","audience","listId","segmentId","topicId","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oBAAI;gBACpCC,WAAW/B,gBAAOF,yBAAAA,MAAOiC,SAAS,oBAAI;gBACtCC,UAAUhC,gBAAOF,yBAAAA,MAAOkC,QAAQ,oBAAI;gBACpCC,QAAQjC,gBAAOF,yBAAAA,MAAOmC,MAAM,oBAAI;gBAChCC,WAAWlC,iBAAOF,yBAAAA,MAAOoC,SAAS,qBAAI;gBACtCC,SAASnC,iBAAOF,yBAAAA,MAAOqC,OAAO,qBAAI;gBAClC;;;;aAIC,GACDC,kBAAkBpC,iBAAOF,yBAAAA,MAAOsC,gBAAgB,qBAAI;gBACpD;;;;;aAKC,GACDC,WAAWrC,iBAAOF,yBAAAA,MAAOuC,SAAS,qBAAI;gBACtCC,oBAAoBtC,iBAAOF,yBAAAA,MAAOwC,kBAAkB,qBAAI;YAC1D;YACA;;;;WAIC,GACDC,QAAQ,IAAM9C,OAAO+C,IAAI,CAACvC;;;AAKpC;AACAb,iBAAiBsB,WAAW,GAAG;AAE/B,eAAetB,iBAAgB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export interface EmailDetailProps {
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
/** The site, or `null` on the org Marketing hub. */
|
|
3
|
+
hostId: string | null;
|
|
4
|
+
/** The message document under `orgs/{orgId}/campaigns`. */
|
|
4
5
|
emailId: string;
|
|
5
6
|
/** The emails hub URL, for the way back and for sibling links. */
|
|
6
7
|
basePath: string;
|
|
@@ -32,6 +33,14 @@ export interface EmailDetailProps {
|
|
|
32
33
|
* template's version. None of them grows with the size of the send. The
|
|
33
34
|
* recipient list is the one read that does, and it is its own card with its
|
|
34
35
|
* own request.
|
|
36
|
+
*
|
|
37
|
+
* ## The site it is sent as
|
|
38
|
+
*
|
|
39
|
+
* The message is the org's, but its template, its sender, its recipients and
|
|
40
|
+
* every action on it belong to the one site it is sent as. Under a site that
|
|
41
|
+
* is the site. On the org hub it is the send's own `hostId` — and a send
|
|
42
|
+
* written before sends named their site cannot be acted on from there, so it
|
|
43
|
+
* says so instead of guessing a site.
|
|
35
44
|
*/
|
|
36
45
|
export declare function EmailDetail(props: EmailDetailProps): import("react").JSX.Element;
|
|
37
46
|
export declare namespace EmailDetail {
|
|
@@ -32,6 +32,8 @@ import { campaignSendDisplay, CAMPAIGN_SEND_CONTAINER_FIELD } from "@aglyn/share
|
|
|
32
32
|
import { emailAudienceLabel, emailIsUnsent, emailSendTimeMs, emailSentAs } from "@aglyn/shared-ui-email-campaigns/model/email-record";
|
|
33
33
|
import { emailPlainTextState } from "@aglyn/aglyn/app-utils/recipient-email-render";
|
|
34
34
|
import { useMarketingHubPath } from "./use-marketing-hub-path.js";
|
|
35
|
+
import { campaignSendDoc, campaignSendReportDoc } from "./campaign-queries.js";
|
|
36
|
+
import { orgSiteHubPath, useMarketingOrgId, useMarketingOrgMount } from "./marketing-org-mount.js";
|
|
35
37
|
import { CampaignDesignPreview as EmailDesignPreview } from "./campaign-email-zones.js";
|
|
36
38
|
import EmailEditDrawer from "./email-edit-drawer.js";
|
|
37
39
|
import EmailRecipientsCard from "./email-recipients-card.js";
|
|
@@ -72,37 +74,58 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
72
74
|
* template's version. None of them grows with the size of the send. The
|
|
73
75
|
* recipient list is the one read that does, and it is its own card with its
|
|
74
76
|
* own request.
|
|
77
|
+
*
|
|
78
|
+
* ## The site it is sent as
|
|
79
|
+
*
|
|
80
|
+
* The message is the org's, but its template, its sender, its recipients and
|
|
81
|
+
* every action on it belong to the one site it is sent as. Under a site that
|
|
82
|
+
* is the site. On the org hub it is the send's own `hostId` — and a send
|
|
83
|
+
* written before sends named their site cannot be acted on from there, so it
|
|
84
|
+
* says so instead of guessing a site.
|
|
75
85
|
*/ export function EmailDetail(props) {
|
|
76
|
-
var _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _sentAs_fromName, _sentAs_replyTo, _ref7, _ref8;
|
|
77
|
-
const {
|
|
86
|
+
var _props_hostId, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _sentAs_fromName, _sentAs_replyTo, _ref7, _ref8;
|
|
87
|
+
const { emailId, basePath } = props;
|
|
78
88
|
// The sibling hub: a campaign's page belongs to the Marketing console.
|
|
79
89
|
const marketingHub = useMarketingHubPath();
|
|
90
|
+
const orgMount = useMarketingOrgMount();
|
|
91
|
+
const { orgId } = useMarketingOrgId(props.hostId);
|
|
80
92
|
const firestore = useFirestore();
|
|
81
|
-
const { data: email, status } = useFirestoreDoc(()=>
|
|
93
|
+
const { data: email, status } = useFirestoreDoc(()=>orgId ? campaignSendDoc(firestore, orgId, emailId) : null, [
|
|
82
94
|
firestore,
|
|
83
|
-
|
|
95
|
+
orgId,
|
|
84
96
|
emailId
|
|
85
97
|
]);
|
|
86
98
|
const notFound = status !== 'loading' && !email;
|
|
99
|
+
/**
|
|
100
|
+
* The site this email is sent as — every site-scoped read and action below
|
|
101
|
+
* is that site's. `null` on the org hub for a send that names none.
|
|
102
|
+
*/ const hostId = (_props_hostId = props.hostId) != null ? _props_hostId : (email == null ? void 0 : email.hostId) ? String(email.hostId) : null;
|
|
103
|
+
/** On the org hub, a send with no site: readable, but nothing to act as. */ const siteless = !props.hostId && Boolean(email) && !hostId;
|
|
104
|
+
/*
|
|
105
|
+
* The message pages' own addresses. Under a site they are the Emails
|
|
106
|
+
* console's; on the org hub, its Emails section. A template is always the
|
|
107
|
+
* sending site's design, so on the org hub it opens on that site.
|
|
108
|
+
*/ const messagesPath = orgMount ? `${orgMount.basePath}/emails` : `${basePath}/messages`;
|
|
109
|
+
const templatesHub = orgMount ? orgSiteHubPath(orgMount, hostId, 'emails') : basePath;
|
|
87
110
|
/*
|
|
88
111
|
* The link rollup, its own document rather than a field on the message.
|
|
89
112
|
*
|
|
90
113
|
* A map of destinations grows with the content, and the message document is
|
|
91
114
|
* read by the list, the glance widget and the send path; putting an
|
|
92
115
|
* unbounded map on it would make every one of those reads larger.
|
|
93
|
-
*/ const { data: links } = useFirestoreDoc(()=>
|
|
116
|
+
*/ const { data: links } = useFirestoreDoc(()=>orgId ? campaignSendReportDoc(firestore, orgId, emailId, 'links') : null, [
|
|
94
117
|
firestore,
|
|
95
|
-
|
|
118
|
+
orgId,
|
|
96
119
|
emailId
|
|
97
120
|
]);
|
|
98
121
|
const templateScreenId = email == null ? void 0 : email.templateScreenId;
|
|
99
|
-
const { data: template } = useFirestoreDoc(()=>templateScreenId ? doc(firestore, 'hosts', hostId, 'screens', templateScreenId) : null, [
|
|
122
|
+
const { data: template } = useFirestoreDoc(()=>templateScreenId && hostId ? doc(firestore, 'hosts', hostId, 'screens', templateScreenId) : null, [
|
|
100
123
|
firestore,
|
|
101
124
|
hostId,
|
|
102
125
|
templateScreenId
|
|
103
126
|
]);
|
|
104
127
|
const templateVersionId = template == null ? void 0 : template.versionId;
|
|
105
|
-
const { data: templateVersion } = useFirestoreDoc(()=>templateScreenId && templateVersionId ? doc(firestore, 'hosts', hostId, 'screens', templateScreenId, 'versions', templateVersionId) : null, [
|
|
128
|
+
const { data: templateVersion } = useFirestoreDoc(()=>templateScreenId && templateVersionId && hostId ? doc(firestore, 'hosts', hostId, 'screens', templateScreenId, 'versions', templateVersionId) : null, [
|
|
106
129
|
firestore,
|
|
107
130
|
hostId,
|
|
108
131
|
templateScreenId,
|
|
@@ -468,7 +491,7 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
468
491
|
variant: 'success',
|
|
469
492
|
persist: false
|
|
470
493
|
});
|
|
471
|
-
router.push(
|
|
494
|
+
router.push(messagesPath);
|
|
472
495
|
} catch (error) {
|
|
473
496
|
console.error(error);
|
|
474
497
|
enqueueSnackbar('This draft could not be discarded', {
|
|
@@ -479,12 +502,12 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
479
502
|
setBusy('');
|
|
480
503
|
}
|
|
481
504
|
}, [
|
|
482
|
-
basePath,
|
|
483
505
|
busy,
|
|
484
506
|
confirm,
|
|
485
507
|
emailId,
|
|
486
508
|
enqueueSnackbar,
|
|
487
509
|
manageApi,
|
|
510
|
+
messagesPath,
|
|
488
511
|
router
|
|
489
512
|
]);
|
|
490
513
|
const handleRename = useCallback(async (values)=>{
|
|
@@ -630,7 +653,7 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
630
653
|
* through a send is stored as `scheduled`, so `midFlight` is what keeps the
|
|
631
654
|
* link off a message that is already reaching inboxes — the same distinction
|
|
632
655
|
* "Send now" is withheld on.
|
|
633
|
-
*/ const editHref = `${
|
|
656
|
+
*/ const editHref = `${messagesPath}/${emailId}/edit`;
|
|
634
657
|
const headerActions = /*#__PURE__*/ _jsxs(Stack, {
|
|
635
658
|
direction: "row",
|
|
636
659
|
spacing: 1,
|
|
@@ -644,12 +667,12 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
644
667
|
componentVariant: 'naked',
|
|
645
668
|
nativeButton: false
|
|
646
669
|
}, {
|
|
647
|
-
href:
|
|
670
|
+
href: messagesPath,
|
|
648
671
|
size: "small",
|
|
649
672
|
color: "primary",
|
|
650
673
|
children: 'All messages'
|
|
651
674
|
})),
|
|
652
|
-
(draft || scheduled) && !midFlight ? /*#__PURE__*/ _jsx(Button, _extends({
|
|
675
|
+
(draft || scheduled) && !midFlight && !siteless ? /*#__PURE__*/ _jsx(Button, _extends({
|
|
653
676
|
component: AppLink
|
|
654
677
|
}, {
|
|
655
678
|
componentVariant: 'naked',
|
|
@@ -660,19 +683,19 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
660
683
|
color: "primary",
|
|
661
684
|
children: 'Write this email'
|
|
662
685
|
})) : null,
|
|
663
|
-
templateScreenId ? /*#__PURE__*/ _jsx(Button, _extends({
|
|
686
|
+
templateScreenId && templatesHub ? /*#__PURE__*/ _jsx(Button, _extends({
|
|
664
687
|
component: AppLink
|
|
665
688
|
}, {
|
|
666
689
|
componentVariant: 'naked',
|
|
667
690
|
nativeButton: false
|
|
668
691
|
}, {
|
|
669
|
-
href: `${
|
|
692
|
+
href: `${templatesHub}/templates/${templateScreenId}`,
|
|
670
693
|
size: "small",
|
|
671
694
|
color: "primary",
|
|
672
695
|
children: 'Open template'
|
|
673
696
|
})) : null,
|
|
674
|
-
primaryAction,
|
|
675
|
-
/*#__PURE__*/ _jsx(RowActionsMenu, {
|
|
697
|
+
siteless ? null : primaryAction,
|
|
698
|
+
siteless ? null : /*#__PURE__*/ _jsx(RowActionsMenu, {
|
|
676
699
|
label: subject,
|
|
677
700
|
items: overflowItems
|
|
678
701
|
})
|
|
@@ -700,6 +723,10 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
700
723
|
/*#__PURE__*/ _jsx(PageHeaderRecord, {
|
|
701
724
|
title: email ? subject : undefined
|
|
702
725
|
}),
|
|
726
|
+
siteless ? /*#__PURE__*/ _jsx(Alert, {
|
|
727
|
+
severity: "info",
|
|
728
|
+
children: 'This email does not record which site it was sent as, so it can ' + 'only be managed from that site’s own Emails page. Its figures ' + 'below are complete.'
|
|
729
|
+
}) : null,
|
|
703
730
|
/*#__PURE__*/ _jsx(CardDisplay, {
|
|
704
731
|
header: 'Email',
|
|
705
732
|
help: emailDocsHelp,
|
|
@@ -869,8 +896,8 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
869
896
|
}),
|
|
870
897
|
/*#__PURE__*/ _jsx(TableCell, {
|
|
871
898
|
align: "right",
|
|
872
|
-
children: templateScreenId ? /*#__PURE__*/ _jsx(AppLink, {
|
|
873
|
-
href: `${
|
|
899
|
+
children: templateScreenId && templatesHub ? /*#__PURE__*/ _jsx(AppLink, {
|
|
900
|
+
href: `${templatesHub}/templates/${templateScreenId}`,
|
|
874
901
|
children: (_ref7 = template == null ? void 0 : template.displayName) != null ? _ref7 : 'Untitled template'
|
|
875
902
|
}) : /*#__PURE__*/ _jsx(Typography, {
|
|
876
903
|
variant: "body2",
|
|
@@ -1132,11 +1159,11 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
1132
1159
|
]
|
|
1133
1160
|
})
|
|
1134
1161
|
}),
|
|
1135
|
-
/*#__PURE__*/ _jsx(EmailRecipientsCard, {
|
|
1162
|
+
hostId ? /*#__PURE__*/ _jsx(EmailRecipientsCard, {
|
|
1136
1163
|
hostId: hostId,
|
|
1137
1164
|
emailId: emailId
|
|
1138
|
-
}),
|
|
1139
|
-
/*#__PURE__*/ _jsx(CardDisplay, {
|
|
1165
|
+
}) : null,
|
|
1166
|
+
hostId ? /*#__PURE__*/ _jsx(CardDisplay, {
|
|
1140
1167
|
header: 'Preview',
|
|
1141
1168
|
help: previewDocsHelp,
|
|
1142
1169
|
contentGutterX: true,
|
|
@@ -1158,7 +1185,7 @@ const emailDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
1158
1185
|
emptyMessage: 'This email carries no body, so there is nothing to draw.',
|
|
1159
1186
|
note: 'Written as plain text in the composer. Merge tokens are ' + 'left standing here — the mail itself resolves them per ' + 'recipient at send time and is not kept.'
|
|
1160
1187
|
})
|
|
1161
|
-
}),
|
|
1188
|
+
}) : null,
|
|
1162
1189
|
/*#__PURE__*/ _jsx(EmailEditDrawer, {
|
|
1163
1190
|
open: editing !== null,
|
|
1164
1191
|
onClose: ()=>setEditing(null),
|