@aglyn/plugins-marketing 1.0.0-beta.234 → 1.0.0-beta.236

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/package.json +16 -16
  2. package/src/lib/components/campaign-conversions-card.d.ts +7 -0
  3. package/src/lib/components/campaign-conversions-card.js +4 -5
  4. package/src/lib/components/campaign-conversions-card.js.map +1 -1
  5. package/src/lib/components/campaign-detail-card.js +3 -4
  6. package/src/lib/components/campaign-detail-card.js.map +1 -1
  7. package/src/lib/components/campaign-glance-card.component.js +1 -2
  8. package/src/lib/components/campaign-glance-card.component.js.map +1 -1
  9. package/src/lib/components/campaign-report-card.js +1 -2
  10. package/src/lib/components/campaign-report-card.js.map +1 -1
  11. package/src/lib/components/campaigns-card.js +2 -2
  12. package/src/lib/components/campaigns-card.js.map +1 -1
  13. package/src/lib/components/email-detail.js +2 -4
  14. package/src/lib/components/email-detail.js.map +1 -1
  15. package/src/lib/components/email-recipients-card.js +1 -2
  16. package/src/lib/components/email-recipients-card.js.map +1 -1
  17. package/src/lib/components/email-template-report-card.js +3 -4
  18. package/src/lib/components/email-template-report-card.js.map +1 -1
  19. package/src/lib/components/emails-list-card.js +3 -4
  20. package/src/lib/components/emails-list-card.js.map +1 -1
  21. package/src/lib/components/org-conversions-section.js +2 -5
  22. package/src/lib/components/org-conversions-section.js.map +1 -1
  23. package/src/lib/components/org-marketing-overview-card.js +1 -1
  24. package/src/lib/components/org-marketing-overview-card.js.map +1 -1
  25. package/src/lib/components/org-overlays-card.js +1 -1
  26. package/src/lib/components/org-overlays-card.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/email-template-report-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\n'use client'\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { pluginRecordHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { mdiBullhornOutline, mdiEyeOutline } from '@aglyn/shared-data-mdi'\nimport { AppLink, CardDisplay, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport {\n Figure,\n RateRow,\n Section,\n} from '@aglyn/shared-ui-jsx/components/measured-figures.component'\nimport RowActionsMenu, {\n type RowActionsMenuItem,\n} from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport {\n useConsoleHostRoute,\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Chip,\n Divider,\n Stack,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n documentId,\n limit,\n orderBy,\n query,\n where,\n} from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport { useMemo } from 'react'\nimport {\n CAMPAIGN_SEND_CONTAINER_FIELD,\n campaignSendDisplay,\n campaignSendVisibleTo,\n orgCampaignSendsPath,\n} from '../model/campaign-container'\nimport { emailSendTimeMs } from '../model/email-record'\nimport { templateReport, type TemplateCampaign } from '../model/template-report'\n\n/**\n * How many of a template's messages one read covers.\n *\n * A CEILING on the read, not a page size: the report is a single figure per\n * quantity, so there is nothing to page through. Past it every total is a\n * floor and the report says so — the same treatment `audienceSizeTruncated`\n * gets, and for the same reason.\n */\nexport const TEMPLATE_CAMPAIGN_CEILING = 100\n\nconst reportDocsHelp = pluginDocsHelp('designedEmails', {\n anchor: '#send-it',\n excerpt:\n 'Every message sent from this template, and what those messages did — ' +\n 'each rate over the population it was measured against.',\n})\n\n/** What the Email plugin's template page hands its report zone. */\nexport interface EmailTemplateReportCardProps {\n hostId: string\n /** The `kind: 'email'` screen document the template page is about. */\n screenId: string\n /** The Emails page's own path, which every message link hangs beneath. */\n basePath: string\n}\n\n/**\n * A message row on this card: what the report needs, plus what the ROW needs.\n *\n * `TemplateCampaign` is the report's shape and stays that — it is the input to\n * `templateReport`, and a field the figures do not read has no business in it.\n * The send time this table sorts on and the campaign its row menu offers are\n * both properties of the row rather than of the report.\n */\ntype TemplateMessage = TemplateCampaign & {\n scheduledForMs: number\n /** Absent on a message written before campaigns grouped their emails. */\n emailCampaignId?: string\n}\n\n/**\n * WHAT ONE TEMPLATE'S EMAILS DID, SUMMED (AGL-3080).\n *\n * The template is the Email plugin's; the messages sent from it are this\n * plugin's campaign sends. So the template's page hosts a zone and this card\n * fills it: the page names the template, and the sends are read here, where\n * their collection is owned.\n *\n * ## What this card reads\n *\n * The messages naming this template, bounded at\n * {@link TEMPLATE_CAMPAIGN_CEILING}. The recipients table is its own card and\n * its own request, so a reader who came for the totals does not pay for the\n * delivery-log query.\n */\nexport function EmailTemplateReportCard(props: EmailTemplateReportCardProps) {\n const { hostId, screenId, basePath } = props\n const { orgSlug, subdomain } = useConsoleHostRoute(hostId)\n /*\n * A campaign's page is published on the record-route seam like every other\n * kind, and read the same way here: one place decides where a `campaign`\n * is read. Null before the console's URL has resolved.\n */\n const campaignHref = (campaignId: string): string | null =>\n orgSlug && subdomain\n ? pluginRecordHref('campaign', { orgSlug, host: subdomain }, campaignId)\n : null\n const firestore = useFirestore()\n const router = useRouter()\n\n /*\n * The messages sent from this template, ordered by DOCUMENT ID.\n *\n * Not by date, and that is forced rather than chosen: a sent message\n * carries `sentAt`, a scheduled one carries `sendAtMs`, and no writer\n * stamps a `createdAt` — so `orderBy` on either would not mis-sort this\n * list, it would DROP every message written by the other branch. Ordering\n * on the document id is the one ordering every message satisfies, and the\n * rows are sorted by date below over a window this component already holds.\n * The index the filters need is `visibleTo` + `templateScreenId`, declared\n * in `cloud/firebase-firestore.indexes.json`.\n *\n * One MORE than the ceiling, so truncation is a fact rather than a guess.\n *\n * The sends are the ORGANIZATION'S, each stamped with the one site it is\n * sent as. The `visibleTo` clause names this site: it keeps a sibling\n * site's sends of a same-id design out, and it is what makes the read\n * provable for a collaborator scoped to this site — the rules evaluate a\n * list per document, and an unfiltered one is refused whole. Nothing is\n * read until the site's org is known.\n */\n const { orgId } = useOrgDataScope({ hostId })\n const sendScope = useMemo(() => campaignSendVisibleTo(hostId), [hostId])\n const { data: messageDocs } = useFirestoreCollection<any>(\n () =>\n orgId\n ? query(\n collection(firestore, ...orgCampaignSendsPath(orgId)),\n where('visibleTo', 'array-contains-any', sendScope),\n where('templateScreenId', '==', screenId),\n orderBy(documentId()),\n limit(TEMPLATE_CAMPAIGN_CEILING + 1),\n )\n : null,\n [firestore, orgId, sendScope, screenId],\n { idField: '$id' },\n )\n\n const truncated = (messageDocs?.length ?? 0) > TEMPLATE_CAMPAIGN_CEILING\n const messages = useMemo<TemplateMessage[]>(\n () =>\n (messageDocs ?? [])\n .slice(0, TEMPLATE_CAMPAIGN_CEILING)\n .map((message: any) => ({\n campaignId: String(message.$id),\n subject: String(message.subject || 'Untitled email'),\n /*\n * A message that has not gone out has NO send time, and that is\n * what `null` means here — not \"unknown\". The report measures\n * engagement over sent messages only, so a scheduled one\n * contributes to the list below and to no figure above it.\n */\n sentAtMs:\n String(message.status ?? '') === 'sent'\n ? emailSendTimeMs(message) || null\n : null,\n status: String(message.status ?? 'sent'),\n audience: String(message.audience ?? ''),\n ...(message.listId ? { listId: String(message.listId) } : {}),\n ...(message.listName ? { listName: String(message.listName) } : {}),\n stats: message.stats,\n scheduledForMs: emailSendTimeMs(message),\n /*\n * The campaign this message belongs to, carried through so the row\n * can offer it. A message written before campaigns grouped anything\n * names no container, which is why it is optional rather than\n * defaulted to the message's own id — a menu item that navigated to\n * the message you are already looking at would be worse than one\n * that says the message belongs to no campaign.\n */\n ...(message[CAMPAIGN_SEND_CONTAINER_FIELD]\n ? {\n emailCampaignId: String(\n message[CAMPAIGN_SEND_CONTAINER_FIELD],\n ),\n }\n : {}),\n })),\n [messageDocs],\n )\n const orderedMessages = useMemo(\n () => [...messages].sort((a, b) => b.scheduledForMs - a.scheduledForMs),\n [messages],\n )\n const report = useMemo(\n () => templateReport(messages, truncated),\n [messages, truncated],\n )\n\n const messageHref = (message: TemplateMessage) =>\n `${basePath}/messages/${message.campaignId}`\n\n /**\n * What one message sent from this template can be opened into.\n *\n * Its own report, and the campaign that grouped it. The template is the page\n * the reader is standing on, so it is not offered a third time. A message\n * sent before campaigns existed belongs to no container, and the item says\n * so rather than vanishing.\n */\n const messageActions = (message: TemplateMessage): RowActionsMenuItem[] => [\n {\n key: 'details',\n label: 'Open report',\n icon: <MdiIcon path={mdiEyeOutline.path} size={0.8} />,\n href: messageHref(message),\n },\n {\n key: 'campaign',\n label: 'Open its campaign',\n icon: <MdiIcon path={mdiBullhornOutline.path} size={0.8} />,\n // The one href here that is not under the Emails page's base path.\n href:\n (message.emailCampaignId && campaignHref(message.emailCampaignId)) ||\n undefined,\n disabled:\n !message.emailCampaignId || !campaignHref(message.emailCampaignId),\n disabledReason: message.emailCampaignId\n ? 'This site’s console URL has not resolved yet'\n : 'Sent before campaigns grouped their emails, so it belongs to none',\n },\n ]\n\n return (\n <CardDisplay\n header={'Sent from this template'}\n help={reportDocsHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={3}>\n {report.caveats.map((caveat) => (\n <Alert key={caveat.id} severity=\"info\">\n {caveat.message}\n </Alert>\n ))}\n\n {/*==========================================\n * WHAT HAPPENED TO THE MAIL, SUMMED.\n *\n * Counts first and rates second, because a rate is only readable\n * once you know what it was taken over — and because a count here\n * covers every message while a rate covers only the messages that\n * recorded its denominator. The rate labels say which.\n *=========================================*/}\n <Section title=\"Delivery\">\n <Stack\n direction=\"row\"\n spacing={4}\n useFlexGap\n sx={{ flexWrap: 'wrap' }}\n >\n <Figure\n label=\"Emails\"\n value={report.sentCampaigns}\n note=\"sent from this template\"\n />\n <Figure\n label=\"Addressed\"\n value={report.recipients}\n note=\"after each send's cap\"\n />\n <Figure\n label=\"Sent\"\n value={report.sent}\n note=\"accepted by the provider\"\n />\n <Figure\n label=\"Delivered\"\n value={report.delivered}\n note=\"accepted by the receiving server\"\n />\n <Figure label=\"Bounced\" value={report.bounced} note=\"of sent\" />\n <Figure\n label=\"Marked as spam\"\n value={report.complained}\n note=\"of delivered\"\n />\n </Stack>\n </Section>\n\n <Divider />\n\n <Section title=\"Engagement\">\n <Stack\n direction=\"row\"\n spacing={4}\n useFlexGap\n sx={{ flexWrap: 'wrap' }}\n >\n <Figure\n label=\"Opens\"\n value={report.opens}\n note=\"every open, repeats included\"\n />\n <Figure\n label=\"Readers who opened\"\n value={report.uniqueOpens}\n note=\"distinct recipients\"\n />\n <Figure\n label=\"Clicks\"\n value={report.clicks}\n note=\"every click, repeats included\"\n />\n <Figure\n label=\"Readers who clicked\"\n value={report.uniqueClicks}\n note=\"distinct recipients\"\n />\n <Figure\n label=\"Unsubscribed\"\n value={report.unsubscribes}\n note=\"through these emails' links\"\n />\n </Stack>\n </Section>\n\n <Divider />\n\n <Section title=\"Rates\">\n <Stack spacing={1}>\n <RateRow label=\"Delivery rate\" rate={report.rates.delivery} />\n <RateRow label=\"Open rate\" rate={report.rates.open} />\n <RateRow label=\"Click rate\" rate={report.rates.click} />\n <RateRow\n label=\"Click-to-open rate\"\n rate={report.rates.clickToOpen}\n />\n <RateRow label=\"Bounce rate\" rate={report.rates.bounce} />\n <RateRow label=\"Complaint rate\" rate={report.rates.complaint} />\n <RateRow\n label=\"Unsubscribe rate\"\n rate={report.rates.unsubscribe}\n />\n </Stack>\n </Section>\n\n <Divider />\n\n <Section title=\"Who this went to\">\n {report.audiences.length ? (\n <>\n <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell>{'Audience'}</TableCell>\n <TableCell align=\"right\">{'Emails'}</TableCell>\n <TableCell align=\"right\">{'Addressed'}</TableCell>\n </TableRow>\n </TableHead>\n <TableBody>\n {report.audiences.map((audience) => (\n <TableRow key={audience.id}>\n <TableCell>{audience.label}</TableCell>\n <TableCell align=\"right\">\n {audience.campaigns.toLocaleString()}\n </TableCell>\n <TableCell align=\"right\" sx={{ fontWeight: 'bold' }}>\n {audience.addressed.toLocaleString()}\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n {/*\n * The naming rule, stated rather than left to be discovered\n * from a list whose name no longer matches the one in the\n * audiences section.\n */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Each list is named as it was when the email was sent, so ' +\n 'renaming or deleting a list does not rewrite what a past ' +\n 'send went to.'}\n </Typography>\n </>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No email sent from this template has gone out yet.'}\n </Typography>\n )}\n </Section>\n\n {orderedMessages.length ? (\n <>\n <Divider />\n <Section title=\"Emails using this template\">\n <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell>{'Subject'}</TableCell>\n <TableCell>{'State'}</TableCell>\n <TableCell>{'When'}</TableCell>\n <TableCell align=\"right\">{'Addressed'}</TableCell>\n <TableCell align=\"right\">{'Opens'}</TableCell>\n <TableCell align=\"right\">{'Clicks'}</TableCell>\n <TableCell align=\"right\" />\n </TableRow>\n </TableHead>\n <TableBody>\n {orderedMessages.map((message) => (\n <TableRow\n key={message.campaignId}\n hover\n onClick={() => router.push(messageHref(message))}\n sx={{ cursor: 'pointer' }}\n >\n <TableCell>\n {/*\n The row's own handler would fire too and push the\n same route twice — one history entry per back\n press.\n */}\n <AppLink\n href={messageHref(message)}\n onClick={(event: {\n stopPropagation: () => void\n }) => event.stopPropagation()}\n >\n {message.subject}\n </AppLink>\n </TableCell>\n <TableCell>\n {/*\n What the message is DOING. One delivering an\n audience larger than one batch is written back as\n `scheduled` between runs, so the stored status\n reads \"Scheduled\" about a send already in progress.\n */}\n <Chip\n size=\"small\"\n label={campaignSendDisplay(message as never).label}\n />\n </TableCell>\n <TableCell>\n {message.scheduledForMs\n ? new Date(message.scheduledForMs).toLocaleString()\n : '—'}\n </TableCell>\n <TableCell align=\"right\">\n {Number(\n message.stats?.recipients ?? 0,\n ).toLocaleString()}\n </TableCell>\n <TableCell align=\"right\">\n {Number(message.stats?.opens ?? 0).toLocaleString()}\n </TableCell>\n <TableCell align=\"right\">\n {Number(message.stats?.clicks ?? 0).toLocaleString()}\n </TableCell>\n <TableCell\n align=\"right\"\n sx={{ width: 56 }}\n onClick={(event) => event.stopPropagation()}\n >\n <RowActionsMenu\n label={String(message.subject)}\n items={messageActions(message)}\n />\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n </Section>\n </>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nEmailTemplateReportCard.displayName = 'EmailTemplateReportCard'\n\nexport default EmailTemplateReportCard\n"],"names":["pluginDocsHelp","pluginRecordHref","mdiBullhornOutline","mdiEyeOutline","AppLink","CardDisplay","MdiIcon","Figure","RateRow","Section","RowActionsMenu","ScrollTable","useConsoleHostRoute","useFirestore","useFirestoreCollection","useOrgDataScope","Alert","Chip","Divider","Stack","TableBody","TableCell","TableHead","TableRow","Typography","collection","documentId","limit","orderBy","query","where","useRouter","useMemo","CAMPAIGN_SEND_CONTAINER_FIELD","campaignSendDisplay","campaignSendVisibleTo","orgCampaignSendsPath","emailSendTimeMs","templateReport","TEMPLATE_CAMPAIGN_CEILING","reportDocsHelp","anchor","excerpt","EmailTemplateReportCard","props","hostId","screenId","basePath","orgSlug","subdomain","campaignHref","campaignId","host","firestore","router","orgId","sendScope","data","messageDocs","idField","truncated","length","messages","slice","map","message","String","$id","subject","sentAtMs","status","audience","listId","listName","stats","scheduledForMs","emailCampaignId","orderedMessages","sort","a","b","report","messageHref","messageActions","key","label","icon","path","size","href","undefined","disabled","disabledReason","header","help","contentGutterX","contentGutterY","spacing","caveats","caveat","severity","id","title","direction","useFlexGap","sx","flexWrap","value","sentCampaigns","note","recipients","sent","delivered","bounced","complained","opens","uniqueOpens","clicks","uniqueClicks","unsubscribes","rate","rates","delivery","open","click","clickToOpen","bounce","complaint","unsubscribe","audiences","align","campaigns","toLocaleString","fontWeight","addressed","variant","color","hover","onClick","push","cursor","event","stopPropagation","Date","Number","width","items","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,SAASA,cAAc,QAAQ,eAAc;AAC7C,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,kBAAkB,EAAEC,aAAa,QAAQ,yBAAwB;AAC1E,SAASC,OAAO,EAAEC,WAAW,EAAEC,OAAO,QAAQ,uBAAsB;AACpE,SACEC,MAAM,EACNC,OAAO,EACPC,OAAO,QACF,6DAA4D;AACnE,OAAOC,oBAEA,6DAA4D;AACnE,SAASC,WAAW,QAAQ,yDAAwD;AACpF,SACEC,mBAAmB,EACnBC,YAAY,EACZC,sBAAsB,EACtBC,eAAe,QACV,iCAAgC;AACvC,SACEC,KAAK,EACLC,IAAI,EACJC,OAAO,EACPC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,SAAS,EACTC,QAAQ,EACRC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,KAAK,QACA,qBAAoB;AAC3B,SAASC,SAAS,QAAQ,kBAAiB;AAC3C,SAASC,OAAO,QAAQ,QAAO;AAC/B,SACEC,6BAA6B,EAC7BC,mBAAmB,EACnBC,qBAAqB,EACrBC,oBAAoB,QACf,iCAA6B;AACpC,SAASC,eAAe,QAAQ,2BAAuB;AACvD,SAASC,cAAc,QAA+B,8BAA0B;AAEhF;;;;;;;CAOC,GACD,OAAO,MAAMC,4BAA4B,IAAG;AAE5C,MAAMC,iBAAiBxC,eAAe,kBAAkB;IACtDyC,QAAQ;IACRC,SACE,0EACA;AACJ;AAyBA;;;;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AC/G;wDAAU6G,OAAM;kEACdc,iBAAO/E,kBAAAA,QAAQS,KAAK,qBAAbT,gBAAekD,KAAK,oBAAI,GAAGiB,cAAc;;kEAEnD,KAAC/G;wDAAU6G,OAAM;kEACdc,iBAAO/E,kBAAAA,QAAQS,KAAK,qBAAbT,gBAAeoD,MAAM,oBAAI,GAAGe,cAAc;;kEAEpD,KAAC/G;wDACC6G,OAAM;wDACNzB,IAAI;4DAAEwC,OAAO;wDAAG;wDAChBP,SAAS,CAACG,QAAUA,MAAMC,eAAe;kEAEzC,cAAA,KAACpI;4DACC2E,OAAOnB,OAAOD,QAAQG,OAAO;4DAC7B8E,OAAO/D,eAAelB;;;;+CAvDrBA,QAAQd,UAAU;;;;;;;qBAgEjC;;;;AAIZ;AACAR,wBAAwBwG,WAAW,GAAG;AAEtC,eAAexG,wBAAuB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/email-template-report-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\n'use client'\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { pluginRecordHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { mdiBullhornOutline, mdiPageNextOutline } from '@aglyn/shared-data-mdi'\nimport { AppLink, CardDisplay, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport {\n Figure,\n RateRow,\n Section,\n} from '@aglyn/shared-ui-jsx/components/measured-figures.component'\nimport RowActionsMenu, {\n type RowActionsMenuItem,\n} from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport {\n useConsoleHostRoute,\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Chip,\n Divider,\n Stack,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n documentId,\n limit,\n orderBy,\n query,\n where,\n} from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport { useMemo } from 'react'\nimport {\n CAMPAIGN_SEND_CONTAINER_FIELD,\n campaignSendDisplay,\n campaignSendVisibleTo,\n orgCampaignSendsPath,\n} from '../model/campaign-container'\nimport { emailSendTimeMs } from '../model/email-record'\nimport { templateReport, type TemplateCampaign } from '../model/template-report'\n\n/**\n * How many of a template's messages one read covers.\n *\n * A CEILING on the read, not a page size: the report is a single figure per\n * quantity, so there is nothing to page through. Past it every total is a\n * floor and the report says so — the same treatment `audienceSizeTruncated`\n * gets, and for the same reason.\n */\nexport const TEMPLATE_CAMPAIGN_CEILING = 100\n\nconst reportDocsHelp = pluginDocsHelp('designedEmails', { anchor: '#template-report' })\n\n/** What the Email plugin's template page hands its report zone. */\nexport interface EmailTemplateReportCardProps {\n hostId: string\n /** The `kind: 'email'` screen document the template page is about. */\n screenId: string\n /** The Emails page's own path, which every message link hangs beneath. */\n basePath: string\n}\n\n/**\n * A message row on this card: what the report needs, plus what the ROW needs.\n *\n * `TemplateCampaign` is the report's shape and stays that — it is the input to\n * `templateReport`, and a field the figures do not read has no business in it.\n * The send time this table sorts on and the campaign its row menu offers are\n * both properties of the row rather than of the report.\n */\ntype TemplateMessage = TemplateCampaign & {\n scheduledForMs: number\n /** Absent on a message written before campaigns grouped their emails. */\n emailCampaignId?: string\n}\n\n/**\n * WHAT ONE TEMPLATE'S EMAILS DID, SUMMED (AGL-3080).\n *\n * The template is the Email plugin's; the messages sent from it are this\n * plugin's campaign sends. So the template's page hosts a zone and this card\n * fills it: the page names the template, and the sends are read here, where\n * their collection is owned.\n *\n * ## What this card reads\n *\n * The messages naming this template, bounded at\n * {@link TEMPLATE_CAMPAIGN_CEILING}. The recipients table is its own card and\n * its own request, so a reader who came for the totals does not pay for the\n * delivery-log query.\n */\nexport function EmailTemplateReportCard(props: EmailTemplateReportCardProps) {\n const { hostId, screenId, basePath } = props\n const { orgSlug, subdomain } = useConsoleHostRoute(hostId)\n /*\n * A campaign's page is published on the record-route seam like every other\n * kind, and read the same way here: one place decides where a `campaign`\n * is read. Null before the console's URL has resolved.\n */\n const campaignHref = (campaignId: string): string | null =>\n orgSlug && subdomain\n ? pluginRecordHref('campaign', { orgSlug, host: subdomain }, campaignId)\n : null\n const firestore = useFirestore()\n const router = useRouter()\n\n /*\n * The messages sent from this template, ordered by DOCUMENT ID.\n *\n * Not by date, and that is forced rather than chosen: a sent message\n * carries `sentAt`, a scheduled one carries `sendAtMs`, and no writer\n * stamps a `createdAt` — so `orderBy` on either would not mis-sort this\n * list, it would DROP every message written by the other branch. Ordering\n * on the document id is the one ordering every message satisfies, and the\n * rows are sorted by date below over a window this component already holds.\n * The index the filters need is `visibleTo` + `templateScreenId`, declared\n * in `cloud/firebase-firestore.indexes.json`.\n *\n * One MORE than the ceiling, so truncation is a fact rather than a guess.\n *\n * The sends are the ORGANIZATION'S, each stamped with the one site it is\n * sent as. The `visibleTo` clause names this site: it keeps a sibling\n * site's sends of a same-id design out, and it is what makes the read\n * provable for a collaborator scoped to this site — the rules evaluate a\n * list per document, and an unfiltered one is refused whole. Nothing is\n * read until the site's org is known.\n */\n const { orgId } = useOrgDataScope({ hostId })\n const sendScope = useMemo(() => campaignSendVisibleTo(hostId), [hostId])\n const { data: messageDocs } = useFirestoreCollection<any>(\n () =>\n orgId\n ? query(\n collection(firestore, ...orgCampaignSendsPath(orgId)),\n where('visibleTo', 'array-contains-any', sendScope),\n where('templateScreenId', '==', screenId),\n orderBy(documentId()),\n limit(TEMPLATE_CAMPAIGN_CEILING + 1),\n )\n : null,\n [firestore, orgId, sendScope, screenId],\n { idField: '$id' },\n )\n\n const truncated = (messageDocs?.length ?? 0) > TEMPLATE_CAMPAIGN_CEILING\n const messages = useMemo<TemplateMessage[]>(\n () =>\n (messageDocs ?? [])\n .slice(0, TEMPLATE_CAMPAIGN_CEILING)\n .map((message: any) => ({\n campaignId: String(message.$id),\n subject: String(message.subject || 'Untitled email'),\n /*\n * A message that has not gone out has NO send time, and that is\n * what `null` means here — not \"unknown\". The report measures\n * engagement over sent messages only, so a scheduled one\n * contributes to the list below and to no figure above it.\n */\n sentAtMs:\n String(message.status ?? '') === 'sent'\n ? emailSendTimeMs(message) || null\n : null,\n status: String(message.status ?? 'sent'),\n audience: String(message.audience ?? ''),\n ...(message.listId ? { listId: String(message.listId) } : {}),\n ...(message.listName ? { listName: String(message.listName) } : {}),\n stats: message.stats,\n scheduledForMs: emailSendTimeMs(message),\n /*\n * The campaign this message belongs to, carried through so the row\n * can offer it. A message written before campaigns grouped anything\n * names no container, which is why it is optional rather than\n * defaulted to the message's own id — a menu item that navigated to\n * the message you are already looking at would be worse than one\n * that says the message belongs to no campaign.\n */\n ...(message[CAMPAIGN_SEND_CONTAINER_FIELD]\n ? {\n emailCampaignId: String(\n message[CAMPAIGN_SEND_CONTAINER_FIELD],\n ),\n }\n : {}),\n })),\n [messageDocs],\n )\n const orderedMessages = useMemo(\n () => [...messages].sort((a, b) => b.scheduledForMs - a.scheduledForMs),\n [messages],\n )\n const report = useMemo(\n () => templateReport(messages, truncated),\n [messages, truncated],\n )\n\n const messageHref = (message: TemplateMessage) =>\n `${basePath}/messages/${message.campaignId}`\n\n /**\n * What one message sent from this template can be opened into.\n *\n * Its own report, and the campaign that grouped it. The template is the page\n * the reader is standing on, so it is not offered a third time. A message\n * sent before campaigns existed belongs to no container, and the item says\n * so rather than vanishing.\n */\n const messageActions = (message: TemplateMessage): RowActionsMenuItem[] => [\n {\n key: 'details',\n label: 'Open report',\n icon: <MdiIcon path={mdiPageNextOutline.path} size={0.8} />,\n href: messageHref(message),\n },\n {\n key: 'campaign',\n label: 'Open its campaign',\n icon: <MdiIcon path={mdiBullhornOutline.path} size={0.8} />,\n // The one href here that is not under the Emails page's base path.\n href:\n (message.emailCampaignId && campaignHref(message.emailCampaignId)) ||\n undefined,\n disabled:\n !message.emailCampaignId || !campaignHref(message.emailCampaignId),\n disabledReason: message.emailCampaignId\n ? 'This site’s console URL has not resolved yet'\n : 'Sent before campaigns grouped their emails, so it belongs to none',\n },\n ]\n\n return (\n <CardDisplay\n header={'Sent from this template'}\n help={reportDocsHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={3}>\n {report.caveats.map((caveat) => (\n <Alert key={caveat.id} severity=\"info\">\n {caveat.message}\n </Alert>\n ))}\n\n {/*==========================================\n * WHAT HAPPENED TO THE MAIL, SUMMED.\n *\n * Counts first and rates second, because a rate is only readable\n * once you know what it was taken over — and because a count here\n * covers every message while a rate covers only the messages that\n * recorded its denominator. The rate labels say which.\n *=========================================*/}\n <Section title=\"Delivery\">\n <Stack\n direction=\"row\"\n spacing={4}\n useFlexGap\n sx={{ flexWrap: 'wrap' }}\n >\n <Figure\n label=\"Emails\"\n value={report.sentCampaigns}\n note=\"sent from this template\"\n />\n <Figure\n label=\"Addressed\"\n value={report.recipients}\n note=\"after each send's cap\"\n />\n <Figure\n label=\"Sent\"\n value={report.sent}\n note=\"accepted by the provider\"\n />\n <Figure\n label=\"Delivered\"\n value={report.delivered}\n note=\"accepted by the receiving server\"\n />\n <Figure label=\"Bounced\" value={report.bounced} note=\"of sent\" />\n <Figure\n label=\"Marked as spam\"\n value={report.complained}\n note=\"of delivered\"\n />\n </Stack>\n </Section>\n\n <Divider />\n\n <Section title=\"Engagement\">\n <Stack\n direction=\"row\"\n spacing={4}\n useFlexGap\n sx={{ flexWrap: 'wrap' }}\n >\n <Figure\n label=\"Opens\"\n value={report.opens}\n note=\"every open, repeats included\"\n />\n <Figure\n label=\"Readers who opened\"\n value={report.uniqueOpens}\n note=\"distinct recipients\"\n />\n <Figure\n label=\"Clicks\"\n value={report.clicks}\n note=\"every click, repeats included\"\n />\n <Figure\n label=\"Readers who clicked\"\n value={report.uniqueClicks}\n note=\"distinct recipients\"\n />\n <Figure\n label=\"Unsubscribed\"\n value={report.unsubscribes}\n note=\"through these emails' links\"\n />\n </Stack>\n </Section>\n\n <Divider />\n\n <Section title=\"Rates\">\n <Stack spacing={1}>\n <RateRow label=\"Delivery rate\" rate={report.rates.delivery} />\n <RateRow label=\"Open rate\" rate={report.rates.open} />\n <RateRow label=\"Click rate\" rate={report.rates.click} />\n <RateRow\n label=\"Click-to-open rate\"\n rate={report.rates.clickToOpen}\n />\n <RateRow label=\"Bounce rate\" rate={report.rates.bounce} />\n <RateRow label=\"Complaint rate\" rate={report.rates.complaint} />\n <RateRow\n label=\"Unsubscribe rate\"\n rate={report.rates.unsubscribe}\n />\n </Stack>\n </Section>\n\n <Divider />\n\n <Section title=\"Who this went to\">\n {report.audiences.length ? (\n <>\n <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell>{'Audience'}</TableCell>\n <TableCell align=\"right\">{'Emails'}</TableCell>\n <TableCell align=\"right\">{'Addressed'}</TableCell>\n </TableRow>\n </TableHead>\n <TableBody>\n {report.audiences.map((audience) => (\n <TableRow key={audience.id}>\n <TableCell>{audience.label}</TableCell>\n <TableCell align=\"right\">\n {audience.campaigns.toLocaleString()}\n </TableCell>\n <TableCell align=\"right\" sx={{ fontWeight: 'bold' }}>\n {audience.addressed.toLocaleString()}\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n {/*\n * The naming rule, stated rather than left to be discovered\n * from a list whose name no longer matches the one in the\n * audiences section.\n */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Each list is named as it was when the email was sent, so ' +\n 'renaming or deleting a list does not rewrite what a past ' +\n 'send went to.'}\n </Typography>\n </>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No email sent from this template has gone out yet.'}\n </Typography>\n )}\n </Section>\n\n {orderedMessages.length ? (\n <>\n <Divider />\n <Section title=\"Emails using this template\">\n <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell>{'Subject'}</TableCell>\n <TableCell>{'State'}</TableCell>\n <TableCell>{'When'}</TableCell>\n <TableCell align=\"right\">{'Addressed'}</TableCell>\n <TableCell align=\"right\">{'Opens'}</TableCell>\n <TableCell align=\"right\">{'Clicks'}</TableCell>\n <TableCell align=\"right\" />\n </TableRow>\n </TableHead>\n <TableBody>\n {orderedMessages.map((message) => (\n <TableRow\n key={message.campaignId}\n hover\n onClick={() => router.push(messageHref(message))}\n sx={{ cursor: 'pointer' }}\n >\n <TableCell>\n {/*\n The row's own handler would fire too and push the\n same route twice — one history entry per back\n press.\n */}\n <AppLink\n href={messageHref(message)}\n onClick={(event: {\n stopPropagation: () => void\n }) => event.stopPropagation()}\n >\n {message.subject}\n </AppLink>\n </TableCell>\n <TableCell>\n {/*\n What the message is DOING. One delivering an\n audience larger than one batch is written back as\n `scheduled` between runs, so the stored status\n reads \"Scheduled\" about a send already in progress.\n */}\n <Chip\n size=\"small\"\n label={campaignSendDisplay(message as never).label}\n />\n </TableCell>\n <TableCell>\n {message.scheduledForMs\n ? new Date(message.scheduledForMs).toLocaleString()\n : '—'}\n </TableCell>\n <TableCell align=\"right\">\n {Number(\n message.stats?.recipients ?? 0,\n ).toLocaleString()}\n </TableCell>\n <TableCell align=\"right\">\n {Number(message.stats?.opens ?? 0).toLocaleString()}\n </TableCell>\n <TableCell align=\"right\">\n {Number(message.stats?.clicks ?? 0).toLocaleString()}\n </TableCell>\n <TableCell\n align=\"right\"\n sx={{ width: 56 }}\n onClick={(event) => event.stopPropagation()}\n >\n <RowActionsMenu\n label={String(message.subject)}\n items={messageActions(message)}\n />\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n </Section>\n </>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nEmailTemplateReportCard.displayName = 'EmailTemplateReportCard'\n\nexport default EmailTemplateReportCard\n"],"names":["pluginDocsHelp","pluginRecordHref","mdiBullhornOutline","mdiPageNextOutline","AppLink","CardDisplay","MdiIcon","Figure","RateRow","Section","RowActionsMenu","ScrollTable","useConsoleHostRoute","useFirestore","useFirestoreCollection","useOrgDataScope","Alert","Chip","Divider","Stack","TableBody","TableCell","TableHead","TableRow","Typography","collection","documentId","limit","orderBy","query","where","useRouter","useMemo","CAMPAIGN_SEND_CONTAINER_FIELD","campaignSendDisplay","campaignSendVisibleTo","orgCampaignSendsPath","emailSendTimeMs","templateReport","TEMPLATE_CAMPAIGN_CEILING","reportDocsHelp","anchor","EmailTemplateReportCard","props","hostId","screenId","basePath","orgSlug","subdomain","campaignHref","campaignId","host","firestore","router","orgId","sendScope","data","messageDocs","idField","truncated","length","messages","slice","map","message","String","$id","subject","sentAtMs","status","audience","listId","listName","stats","scheduledForMs","emailCampaignId","orderedMessages","sort","a","b","report","messageHref","messageActions","key","label","icon","path","size","href","undefined","disabled","disabledReason","header","help","contentGutterX","contentGutterY","spacing","caveats","caveat","severity","id","title","direction","useFlexGap","sx","flexWrap","value","sentCampaigns","note","recipients","sent","delivered","bounced","complained","opens","uniqueOpens","clicks","uniqueClicks","unsubscribes","rate","rates","delivery","open","click","clickToOpen","bounce","complaint","unsubscribe","audiences","align","campaigns","toLocaleString","fontWeight","addressed","variant","color","hover","onClick","push","cursor","event","stopPropagation","Date","Number","width","items","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,SAASA,cAAc,QAAQ,eAAc;AAC7C,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,kBAAkB,EAAEC,kBAAkB,QAAQ,yBAAwB;AAC/E,SAASC,OAAO,EAAEC,WAAW,EAAEC,OAAO,QAAQ,uBAAsB;AACpE,SACEC,MAAM,EACNC,OAAO,EACPC,OAAO,QACF,6DAA4D;AACnE,OAAOC,oBAEA,6DAA4D;AACnE,SAASC,WAAW,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/_extends";
18
18
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
19
19
  import { pluginDocsHelp } from "@aglyn/aglyn";
20
20
  import { pluginRecordHref } from "@aglyn/aglyn/plugin-manager/plugin-record-routes";
21
- import { mdiBullhornOutline, mdiContentCopy, mdiDeleteOutline, mdiEyeOutline, mdiPaletteOutline } from "@aglyn/shared-data-mdi";
21
+ import { mdiBullhornOutline, mdiContentCopy, mdiDeleteOutline, mdiPageNextOutline, mdiPaletteOutline } from "@aglyn/shared-data-mdi";
22
22
  import { AppLink, CardDisplay, MdiIcon, useConfirmationContext } from "@aglyn/shared-ui-jsx";
23
23
  import ListFilterChips from "@aglyn/shared-ui-jsx/components/list-filter-chips.component";
24
24
  import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.component";
@@ -101,8 +101,7 @@ import { orgSiteName, orgSiteOptions, useMarketingOrgId, useMarketingOrgMount }
101
101
  createdAtMs: 'Created'
102
102
  };
103
103
  const emailsDocsHelp = pluginDocsHelp('emailCampaigns', {
104
- anchor: '#opens--clicks',
105
- excerpt: 'Every message this site has sent or has scheduled, each with its own ' + 'report: what was delivered, who opened it, and which links they followed.'
104
+ anchor: '#messages-list'
106
105
  });
107
106
  /**
108
107
  * EVERY MESSAGE, AS AGAINST EVERY CAMPAIGN.
@@ -356,7 +355,7 @@ const emailsDocsHelp = pluginDocsHelp('emailCampaigns', {
356
355
  key: 'details',
357
356
  label: 'Open report',
358
357
  icon: /*#__PURE__*/ _jsx(MdiIcon, {
359
- path: mdiEyeOutline.path,
358
+ path: mdiPageNextOutline.path,
360
359
  size: 0.8
361
360
  }),
362
361
  href: emailHref(email)
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/emails-list-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { pluginRecordHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport {\n mdiBullhornOutline,\n mdiContentCopy,\n mdiDeleteOutline,\n mdiEyeOutline,\n mdiPaletteOutline,\n} from '@aglyn/shared-data-mdi'\nimport {\n AppLink,\n CardDisplay,\n MdiIcon,\n useConfirmationContext,\n} from '@aglyn/shared-ui-jsx'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { hiddenFilterVisibility } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { useListColumnSort } from '@aglyn/shared-ui-jsx/hooks/use-list-column-sort'\nimport type { ListQuerySort } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { CreateArtifactDrawer } from '@aglyn/shared-ui-jsx-forms'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { collectionCeiling } from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { useListQuery } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport {\n DUPLICATE_MENU_LABEL,\n useDuplicateResource,\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport { Button, Chip, Stack, Typography } from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useMemo, useState } from 'react'\nimport {\n campaignPlacedOnHost,\n campaignSendDisplay,\n CAMPAIGN_SEND_CONTAINER_FIELD,\n type CampaignSendDisplayState,\n} from '../model/campaign-container'\nimport {\n emailListTimeMs,\n emailSendTimeMs,\n} from '../model/email-record'\nimport {\n useCampaignManageApi,\n useCampaignSendApi,\n} from './use-campaign-send-api'\nimport {\n CAMPAIGN_SEND_STATUS_OPTIONS,\n SINGLE_SEND_FILTER_VALUE,\n campaignEmailsListQuery,\n campaignSendsScope,\n emailCampaignQueryClauses,\n} from '../model/campaign-list-query'\nimport { useMarketingHubPath } from './use-marketing-hub-path'\nimport { siteRecordRouteContext, useRecordRouteContext } from './record-route-context'\nimport {\n campaignContainersQuery,\n campaignSendsCollection,\n} from './campaign-queries'\nimport {\n orgSiteName,\n orgSiteOptions,\n useMarketingOrgId,\n useMarketingOrgMount,\n} from './marketing-org-mount'\n\n/**\n * How many campaigns the Campaign filter and the create drawer offer — the\n * same read serves both. A picker's options, not a list.\n */\nconst CONTAINER_CEILING = 50\n\n/** The headers a page sort names in its notice. */\nconst EMAIL_PAGE_SORT_HEADERS = {\n site: 'Site',\n state: 'State',\n when: 'When',\n recipients: 'Addressed',\n opens: 'Opens',\n clicks: 'Clicks',\n}\n\n/**\n * Why discard is refused, keyed by the state that refuses it.\n *\n * The KEYS are persisted status values written by the send path. Each line\n * says what to do instead, because \"you cannot\" on its own leaves a merchant\n * with an email they wanted rid of and no next step — and for a scheduled one\n * the next step is a different act with a different consequence, so naming it\n * is the difference between withdrawing mail and losing the record of it.\n *\n * A state absent from here falls through to the generic refusal rather than\n * being flattened into one of these: a state this list cannot name is worth\n * seeing.\n */\nconst DISCARD_REFUSAL: Record<string, string> = {\n sent: 'This email has been sent. Its report and its unsubscribe links have to go on resolving.',\n scheduled: 'Cancel the send first — cancelling takes it off the clock and keeps the email.',\n sending: 'This email is being sent right now.',\n canceled: 'A canceled email is kept as the record that it was withdrawn.',\n}\n\n/**\n * The chip color for one display state.\n *\n * `sending` is the one worth a color: an email part way through an audience\n * larger than one batch is doing something right now, and a merchant scanning\n * the list for what needs attention should find it without reading. The rest\n * are neutral, because a finished send and a draft are not events.\n */\nconst STATE_COLOR: Partial<\n Record<CampaignSendDisplayState, 'info' | 'warning'>\n> = {\n sending: 'info',\n stopped: 'warning',\n // Waiting on staff, not on the merchant (AGL-3356): worth finding on a scan.\n held: 'warning',\n}\n\n/*\n * What the messages grid's Filters panel offers, each clause and the search\n * on the list's Firestore query (AGL-3321, `campaignEmailsListQuery`). The\n * State column is what the email is DOING (`campaignSendDisplay`), which no\n * query can ask, so the panel offers the Status it STORES instead.\n */\nconst EMAIL_FILTER_HEADERS: Readonly<Record<string, string>> = {\n subject: 'Subject',\n status: 'Status',\n emailCampaignId: 'Campaign',\n site: 'Site',\n createdAtMs: 'Created',\n}\n\nconst emailsDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#opens--clicks',\n excerpt:\n 'Every message this site has sent or has scheduled, each with its own ' +\n 'report: what was delivered, who opened it, and which links they followed.',\n})\n\nexport interface EmailsListCardProps {\n /** The site, or `null` on the organization's Emails page. */\n hostId: string | null\n /**\n * The Emails page's own URL, under the site or the organization, so a row\n * can link to the message's own page beneath it.\n */\n basePath: string\n}\n\n/**\n * EVERY MESSAGE, AS AGAINST EVERY CAMPAIGN.\n *\n * A campaign groups messages; this is the messages. The two are different\n * questions — \"how did the spring promotion do\" and \"what went out on the\n * 14th, and to whom\" — and they were previously the same list because a\n * campaign document WAS a single send.\n *\n * ## Asked of Firestore, a page at a time\n *\n * No SEND date is on every message — a sent one carries `sentAt`, a\n * scheduled one `sendAtMs`, a draft neither — so the list is ordered on\n * `createdAtMs`, the one date every writer stamps when it mints a record\n * (and `backfill-campaign-list-fields.mjs` stamped on the ones before).\n * Newest first, paged by the query itself.\n *\n * The Filters panel and the search box are the grid's; every clause and the\n * search word go onto that ONE query (AGL-3321, `campaignEmailsListQuery`),\n * so each page is a page of matches — an email that matches on page four is\n * found — and a combination one query cannot hold is refused by name above\n * the table, never answered over the rows that happen to be loaded.\n *\n * ## Under a site, and over the organization\n *\n * Sends are the org's. Under a site this lists the ones sent as that site;\n * on the organization's Emails page it lists every site's, with a Site column,\n * and every action on a row names the site that row is sent as — the only\n * site that can duplicate it, discard it or open its template. Creating one\n * there first asks which site it is sent as.\n */\nexport function EmailsListCard(props: EmailsListCardProps) {\n const { hostId, basePath } = props\n const firestore = useFirestore()\n const orgMount = useMarketingOrgMount()\n const { orgId } = useMarketingOrgId(hostId)\n // The sibling hub: a campaign's page belongs to the Marketing console —\n // over the org, the organization's own Marketing page the mount names.\n const siteMarketingHub = useMarketingHubPath()\n const marketingHub = orgMount ? orgMount.basePath : siteMarketingHub\n const router = useRouter()\n\n /*\n * The Filters panel and the search, bound to the grid. Held here rather\n * than in a saved view: this list keeps no views.\n */\n const declaration = campaignEmailsListQuery(!hostId)\n const gridFilter = useListGridFilter({\n selectFields: ['status', 'emailCampaignId', 'site'],\n })\n /*\n * EVERY HEADER SORTS (AGL-3680): Subject orders the query\n * (`declaration.sorts`); Site, State, When and the figures are derived or\n * may be absent, and sort the page.\n */\n const [askedSort, setAskedSort] = useState<ListQuerySort | null>(null)\n const emailPage = useListQuery<any>({\n collection: campaignSendsCollection(firestore, orgId),\n declaration,\n request: {\n clauses: emailCampaignQueryClauses(gridFilter.clauses),\n search: gridFilter.searchWords,\n base: campaignSendsScope(hostId),\n sort: askedSort,\n },\n deps: [firestore, orgId, hostId],\n idField: '$id',\n })\n const emailPageSorts = useMemo(\n () => ({\n ...(orgMount\n ? { site: (row: any) => (row?.hostId ? orgSiteName(orgMount, row.hostId) : null) }\n : {}),\n state: (row: any) => campaignSendDisplay(row).label,\n when: (row: any) => emailListTimeMs(row),\n // Counters stay absent until something is counted (see\n // `campaign-list-query.ts`), so no query can order by them.\n recipients: (row: any) => row.stats?.recipients ?? null,\n opens: (row: any) => row.stats?.opens ?? null,\n clicks: (row: any) => row.stats?.clicks ?? null,\n }),\n [orgMount],\n )\n const emailSort = useListColumnSort<any>({\n sorts: declaration.sorts,\n sort: askedSort,\n onSortChange: setAskedSort,\n orderBy: emailPage.plan.orderBy,\n rows: emailPage.rows,\n pageSorts: emailPageSorts,\n headers: EMAIL_PAGE_SORT_HEADERS,\n })\n const emails = emailPage.rows\n const filtering =\n gridFilter.clauses.length > 0 ||\n gridFilter.searchWords.some((word) => word.trim())\n\n /*\n * A message's own pages, beneath the Emails page this list is on — the\n * site's or the organization's. A template is a site's design, so over the\n * org it opens on the site the row is sent as.\n */\n const messagesPath = `${basePath}/messages`\n const emailHref = (email: any) => `${messagesPath}/${email.$id}`\n const routeContext = useRecordRouteContext()\n const templateHref = (email: any, templateScreenId: string): string | null => {\n const siteContext = siteRecordRouteContext(routeContext, orgMount, email?.hostId)\n return siteContext ? pluginRecordHref('emailTemplate', siteContext, templateScreenId) : null\n }\n /** The site a row is sent as, which every action on it must name. */\n const rowHostId = useCallback(\n (email: any): string | null =>\n hostId ?? (email?.hostId ? String(email.hostId) : null),\n [hostId],\n )\n const hostOfEmail = useMemo(\n () =>\n new Map<string, string | null>(\n emails.map((email: any) => [\n String(email.$id),\n email?.hostId ? String(email.hostId) : null,\n ]),\n ),\n [emails],\n )\n\n const { confirm } = useConfirmationContext()\n const { enqueueSnackbar } = useSnackbar()\n // Duplicate (AGL-2936): a new draft with the message and its design, and\n // nobody to send to until the person chooses — through the manage door,\n // which is the plugin's own.\n const manageForCopy = useCampaignManageApi(hostId)\n const duplicate = useDuplicateResource({\n hostId: hostId ?? '',\n perform: async ({ sourceId, name, attemptKey }) => {\n const { response, payload } = await manageForCopy({\n action: 'duplicate',\n campaignId: sourceId,\n name,\n attemptKey,\n // The copy is made as the site the source is sent as.\n ...(hostId ? {} : { hostId: hostOfEmail.get(sourceId) ?? undefined }),\n })\n if (!response.ok) throw new Error(payload?.error ?? 'Duplicate failed')\n return {\n id: String(payload.emailId),\n versionId: null,\n name: String(payload.name ?? name),\n }\n },\n onDuplicated: (_kind, copy) =>\n enqueueSnackbar(`Duplicated as “${copy.name}” — a draft with no audience yet`, {\n variant: 'success',\n }),\n })\n const manageApi = useCampaignManageApi(hostId)\n /** The email a discard is in flight for, so its row menu can say so. */\n const [discardingId, setDiscardingId] = useState('')\n\n /*==========================================\n * THROWING AWAY A DRAFT.\n *\n * The one removal this surface has, and it is deliberately the narrowest\n * one: an email that was never sent, whose record nobody outside the\n * console has ever seen. Everything else on this list is evidence — a sent\n * message's report is what a merchant answers a complaint with, and its id\n * is inside the HMAC of every unsubscribe footer it delivered — and a\n * scheduled one is withdrawn with Cancel, which keeps the record and takes\n * it off the clock.\n *\n * The menu already refuses anything but a draft, and so does the route.\n * That is not belt and braces: the state on screen is a snapshot that can\n * be seconds old, and the record can be claimed by `sendNow` in between.\n * The route's refusal is the one that decides, inside the transaction that\n * does the delete.\n *=========================================*/\n const handleDiscard = useCallback(\n async (email: any) => {\n if (discardingId) return\n const id = String(email?.$id ?? '')\n const name = String(email?.subject || email?.displayName || 'this draft')\n const agreed = await confirm({\n title: 'Discard this draft?',\n description:\n `${name} has not been sent to anybody, and discarding it removes ` +\n 'it for good — the subject, the message and everything else ' +\n 'written on it. There is no undo.',\n confirmationText: 'Discard',\n })\n .then(() => true)\n .catch(() => false)\n if (!agreed) return\n setDiscardingId(id)\n try {\n const { response, payload } = await manageApi({\n action: 'discardEmail',\n campaignId: id,\n ...(hostId ? {} : { hostId: rowHostId(email) ?? undefined }),\n })\n if (!response.ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'This draft could not be discarded',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n enqueueSnackbar('Draft discarded', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('This draft could not be discarded', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setDiscardingId('')\n }\n },\n [confirm, discardingId, enqueueSnackbar, hostId, manageApi, rowHostId],\n )\n\n /**\n * What a message can be opened INTO, from the list.\n *\n * All three are places the message's own report already links to, moved one\n * screen earlier: the report itself, the campaign it belongs to, and the\n * template it was rendered from. A message need have neither of the last\n * two — one sent before campaigns grouped anything names no container, and\n * one composed inline was built from no template — so those entries are\n * shown DISABLED with the reason rather than hidden. A control that\n * disappears and a control that does not apply look identical, and only one\n * of them tells the reader which case they are in.\n *\n * DISCARD is the fourth entry and is offered on the same terms: a draft can\n * be thrown away, and nothing else can. It stays visible on a sent or\n * scheduled message carrying the reason it is refused, because that is the\n * honest answer to “how do I get rid of this” — and the route refuses it\n * too, so the menu is describing a rule rather than being one.\n */\n const rowActions = (email: any): RowActionsMenuItem[] => {\n const containerId = String(email?.[CAMPAIGN_SEND_CONTAINER_FIELD] ?? '')\n const templateScreenId = String(email?.templateScreenId ?? '')\n const state = String(email?.status ?? '')\n const templates = templateScreenId ? templateHref(email, templateScreenId) : null\n /** On the org hub, a send that names no site has nothing to act as. */\n const siteless = !rowHostId(email)\n const sitelessReason =\n 'This email does not record which site it was sent as. Manage it from ' +\n 'that site’s own Emails page.'\n return [\n {\n key: 'details',\n label: 'Open report',\n icon: <MdiIcon path={mdiEyeOutline.path} size={0.8} />,\n href: emailHref(email),\n },\n {\n key: 'campaign',\n label: 'Open its campaign',\n icon: <MdiIcon path={mdiBullhornOutline.path} size={0.8} />,\n // The campaign's page belongs to the Marketing console, so this one\n // href is built from the sibling hub rather than this surface's own.\n href:\n containerId && marketingHub\n ? `${marketingHub}/campaigns/${containerId}`\n : undefined,\n disabled: !containerId || !marketingHub,\n disabledReason: containerId\n ? 'This site’s console URL has not resolved yet'\n : 'Sent before campaigns grouped their emails, so it belongs to none',\n },\n {\n key: 'template',\n label: 'Open its template',\n icon: <MdiIcon path={mdiPaletteOutline.path} size={0.8} />,\n href: templates ?? undefined,\n disabled: !templates,\n disabledReason: templateScreenId\n ? 'This site’s console URL has not resolved yet'\n : 'This message was not built from a template',\n },\n {\n key: 'duplicate',\n label: DUPLICATE_MENU_LABEL,\n icon: <MdiIcon path={mdiContentCopy.path} size={0.8} />,\n disabled: siteless,\n disabledReason: sitelessReason,\n onClick: () =>\n duplicate.request('campaign', {\n id: String(email.$id),\n name: String(email?.displayName ?? email?.subject ?? ''),\n }),\n },\n {\n key: 'discard',\n label: 'Discard draft',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: siteless || state !== 'draft' || Boolean(discardingId),\n disabledReason: siteless\n ? sitelessReason\n : (DISCARD_REFUSAL[state] ?? 'Only a draft can be discarded'),\n onClick: () => void handleDiscard(email),\n },\n ]\n }\n\n const [createOpen, setCreateOpen] = useState(false)\n const [creating, setCreating] = useState(false)\n const campaignSendApi = useCampaignSendApi(hostId)\n /*\n * The sites a new email can be sent as, on the org hub. One site answers\n * the question itself, so the field is asked only when there is a choice.\n */\n const orgSites = useMemo(\n () => (orgMount ? orgSiteOptions(orgMount) : []),\n [orgMount],\n )\n const askSite = !hostId && orgSites.length > 1\n\n /*\n * The campaigns, read while the list is shown: the Campaign filter offers\n * them by name, and the create drawer offers them to file a new email\n * under. One capped read of the containers serves both.\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 campaignOptions = useMemo(\n () =>\n [...(campaignDocs ?? [])]\n .map((campaign: any) => ({\n value: String(campaign.$id),\n label: String(campaign.name || 'Untitled campaign'),\n }))\n .sort((a, b) => a.label.localeCompare(b.label)),\n [campaignDocs],\n )\n\n const filterOptions = useMemo(\n () => ({\n status: CAMPAIGN_SEND_STATUS_OPTIONS,\n emailCampaignId: [\n { value: SINGLE_SEND_FILTER_VALUE, label: 'Single send' },\n ...campaignOptions,\n ],\n ...(hostId ? {} : { site: orgSites }),\n }),\n [campaignOptions, hostId, orgSites],\n )\n\n /*==========================================\n * CREATE, THEN GO TO THE EMAIL'S OWN PAGE.\n *\n * The drawer collects only what it takes to MINT the record — the friendly\n * name, and the campaign it belongs to. Everything else about the email is\n * written on the email's own page, which is where a record is edited\n * throughout this console: a list page carries no form.\n *\n * The record is real from this moment: `/marketing/campaigns/{id}` resolves,\n * the row appears in the table below as a Draft, and the id it is created\n * under is the id it keeps when it is eventually sent. It costs nothing to\n * exist — the route reserves no allowance and moves no meter for a draft,\n * and the scheduled processor only ever picks up `scheduled`.\n *=========================================*/\n const handleCreate = useCallback(\n async (values: Record<string, any>) => {\n if (creating) return\n const sendAs =\n hostId ?? (askSite ? String(values.hostId ?? '') : orgSites[0]?.value)\n if (!sendAs) {\n return void enqueueSnackbar('Choose the site this email is sent as', {\n variant: 'warning',\n allowDuplicate: true,\n })\n }\n /*\n * The organization hub offers every campaign, because the site is\n * chosen in the same form. An email can only join a campaign placed on\n * the site it is sent as — the send route refuses anything else — so\n * the mismatch is named here, where it can be fixed, rather than\n * arriving as the route's bare refusal. A site hub lists only the\n * campaigns placed on it, so there is nothing to check there.\n */\n const chosenCampaign =\n !hostId && values.emailCampaignId\n ? (campaignDocs ?? []).find(\n (campaign: any) =>\n String(campaign.$id) === String(values.emailCampaignId),\n )\n : null\n if (chosenCampaign && !campaignPlacedOnHost(chosenCampaign, sendAs)) {\n return void enqueueSnackbar(\n 'That campaign is not offered on the site this email is sent as. ' +\n 'Choose another, or add the site to the campaign first.',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n setCreating(true)\n try {\n const { response, payload } = await campaignSendApi({\n action: 'draft',\n ...(hostId ? {} : { hostId: sendAs }),\n displayName: String(values.displayName ?? '').trim(),\n ...(values.emailCampaignId\n ? { emailCampaignId: String(values.emailCampaignId) }\n : {}),\n })\n if (!response.ok || !payload?.campaignId) {\n return void enqueueSnackbar(\n payload?.error ?? 'This email could not be created',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n setCreateOpen(false)\n /*\n * Straight to where it is WRITTEN. The drawer collected the name and\n * the campaign; the record now exists and holds nothing else, so the\n * next thing to do with it is compose it — and its own page is a\n * report of a send that has not happened.\n */\n router.push(`${messagesPath}/${payload.campaignId}/edit`)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('This email could not be created', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setCreating(false)\n }\n },\n [\n askSite,\n campaignDocs,\n campaignSendApi,\n creating,\n enqueueSnackbar,\n hostId,\n messagesPath,\n orgSites,\n router,\n ],\n )\n\n /*\n * One row per message, in the query's order. The subject is a link AND the\n * row opens the report: a click handler cannot be middle-clicked or opened\n * in a new tab.\n */\n const columns: GridColDef[] = [\n {\n field: 'subject',\n headerName: 'Subject',\n flex: 1,\n minWidth: 220,\n valueGetter: (_value, row) => row.subject || 'Untitled email',\n renderCell: ({ row, value }) => (\n <AppLink\n href={emailHref(row)}\n // The row's own handler would fire too and push the same route\n // twice — one history entry per back press.\n onClick={(event: { stopPropagation: () => void }) =>\n event.stopPropagation()\n }\n >\n {value}\n </AppLink>\n ),\n },\n // Which site each row is sent as, on the org hub only.\n ...(orgMount\n ? [\n {\n field: 'site',\n headerName: 'Site',\n width: 150,\n valueGetter: (_value: unknown, row: any) =>\n row?.hostId ? orgSiteName(orgMount, row.hostId) : '—',\n } satisfies GridColDef,\n ]\n : []),\n {\n /*\n * WHAT THIS EMAIL IS DOING, not what field it stores.\n *\n * An email delivering an audience larger than one batch is written back\n * as `scheduled` between runs, so a chip rendering the status said\n * \"Scheduled\" about a send that had already reached five hundred people.\n * The derivation reads the counters beside the status and says which of\n * the two it is.\n */\n field: 'state',\n headerName: 'State',\n width: 150,\n valueGetter: (_value, row) => campaignSendDisplay(row).label,\n renderCell: ({ row }) => {\n const display = campaignSendDisplay(row)\n return (\n <Chip\n size=\"small\"\n color={STATE_COLOR[display.state]}\n label={display.label}\n />\n )\n },\n },\n {\n field: 'when',\n headerName: 'When',\n width: 190,\n valueGetter: (_value, row) => emailListTimeMs(row),\n renderCell: ({ row }) => {\n const at = emailSendTimeMs(row)\n return at ? new Date(at).toLocaleString() : '—'\n },\n },\n ...(\n [\n ['recipients', 'Addressed'],\n ['opens', 'Opens'],\n ['clicks', 'Clicks'],\n ] as const\n ).map(\n ([stat, headerName]): GridColDef => ({\n field: stat,\n headerName,\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 110,\n valueGetter: (_value, row) => Number(row.stats?.[stat] ?? 0),\n valueFormatter: (value: number) => value.toLocaleString(),\n }),\n ),\n listActionsColumn(\n (row) => (\n <ListRowActions\n label={String(row.subject || 'Untitled email')}\n items={rowActions(row)}\n />\n ),\n { width: 72 },\n ),\n ]\n\n const gridColumns = listFilterGridColumns(\n columns,\n declaration.fields,\n filterOptions,\n EMAIL_FILTER_HEADERS,\n )\n /** Nothing stored at all — not a filter that matched nothing. */\n const none =\n emailPage.status !== 'loading' &&\n emails.length === 0 &&\n !filtering &&\n emailPage.page === 0\n\n return (\n <CardDisplay\n header={'Messages'}\n help={emailsDocsHelp}\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"contained\"\n onClick={() => setCreateOpen(true)}\n >\n {'New email'}\n </Button>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n {duplicate.dialog}\n <Stack spacing={2}>\n {none ? (\n <Stack spacing={2} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Nothing has been sent or scheduled yet. Write one here, or ' +\n 'from a campaign, and it appears in this list with its own ' +\n 'report.'}\n </Typography>\n <Button variant=\"contained\" onClick={() => setCreateOpen(true)}>\n {'New email'}\n </Button>\n </Stack>\n ) : (\n <>\n <ListFilterChips\n fields={declaration.fields}\n headers={EMAIL_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={filterOptions}\n />\n <ListQueryNotices\n refused={listQueryRefusals(emailPage.plan.refused, {\n fields: declaration.fields,\n headers: EMAIL_FILTER_HEADERS,\n options: filterOptions,\n })}\n notices={[...emailPage.plan.notices, ...emailSort.notices]}\n />\n <ListTable\n aria-label=\"Messages\"\n rows={emailSort.rows}\n columns={gridColumns}\n rowHeight={TABLE_ROW_HEIGHT}\n onOpen={(_id, row) => router.push(emailHref(row))}\n loading={emailPage.status === 'loading'}\n /*\n * The panel and the search are the grid's; every clause and\n * the search word are on the list's query (AGL-3321), and the\n * grid neither filters nor sorts the page it is handed:\n * Subject's header orders the query, the rest the page\n * (AGL-3680), newest first until one is clicked.\n */\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n columnSort={emailSort}\n hideFooter\n initialState={{\n columns: {\n columnVisibilityModel: hiddenFilterVisibility(\n declaration.fields,\n columns.map((column) => column.field),\n ),\n },\n }}\n noRowsLabel=\"No messages match these filters\"\n />\n <ListPagination\n page={emailPage.page}\n pageSize={emailPage.pageSize}\n rowCount={emails.length}\n hasMore={emailPage.hasMore}\n onPageChange={emailPage.setPage}\n onPageSizeChange={emailPage.setPageSize}\n />\n </>\n )}\n </Stack>\n {/*\n AN EMAIL WRITTEN HERE BELONGS TO A CAMPAIGN, OR TO NO CAMPAIGN.\n\n The second is a real answer and not a gap in the model. A send with no\n container is what the product has always had — every message that\n predates campaigns is one — and `campaignListRows` adopts each of them\n as a campaign of one at read time, which is the \"Single send\" chip on\n the campaigns table. So composing from this list mints nothing, files\n nothing, and requires nobody to invent a campaign first: it leaves the\n container empty, and the send that results is presented the way every\n containerless send already is.\n\n Offering the campaigns anyway is what stops the opposite mistake — a\n merchant who DOES have a spring campaign writing its third email into\n a single send that never joins the rollup.\n */}\n <CreateArtifactDrawer\n open={createOpen}\n onClose={() => setCreateOpen(false)}\n title=\"New email\"\n submitLabel={creating ? 'Creating…' : 'Start writing'}\n includeDescription={false}\n onSubmit={handleCreate}\n extraFields={[\n ...(askSite\n ? [\n {\n component: 'select',\n name: 'hostId',\n label: 'Send as',\n isRequired: true,\n initialValue: '',\n helperText:\n 'The site this email is sent from — its sender, designs ' +\n 'and unsubscribe page',\n disableDefaultOption: true,\n options: orgSites,\n },\n ]\n : []),\n {\n component: 'select',\n name: 'emailCampaignId',\n label: 'Campaign',\n initialValue: '',\n helperText:\n 'Leave this as a single send unless the email belongs with ' +\n 'others',\n disableDefaultOption: true,\n options: [\n { value: '', label: 'Single send — not part of a campaign' },\n ...campaignOptions,\n ],\n },\n ]}\n />\n </CardDisplay>\n )\n}\nEmailsListCard.displayName = 'EmailsListCard'\n\nexport default EmailsListCard\n"],"names":["pluginDocsHelp","pluginRecordHref","mdiBullhornOutline","mdiContentCopy","mdiDeleteOutline","mdiEyeOutline","mdiPaletteOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListRowActions","ListTable","listActionsColumn","hiddenFilterVisibility","listFilterGridColumns","useListGridFilter","useListColumnSort","TABLE_ROW_HEIGHT","CreateArtifactDrawer","useSnackbar","collectionCeiling","useListQuery","DUPLICATE_MENU_LABEL","useDuplicateResource","useFirestore","useFirestoreCollection","Button","Chip","Stack","Typography","useRouter","useCallback","useMemo","useState","campaignPlacedOnHost","campaignSendDisplay","CAMPAIGN_SEND_CONTAINER_FIELD","emailListTimeMs","emailSendTimeMs","useCampaignManageApi","useCampaignSendApi","CAMPAIGN_SEND_STATUS_OPTIONS","SINGLE_SEND_FILTER_VALUE","campaignEmailsListQuery","campaignSendsScope","emailCampaignQueryClauses","useMarketingHubPath","siteRecordRouteContext","useRecordRouteContext","campaignContainersQuery","campaignSendsCollection","orgSiteName","orgSiteOptions","useMarketingOrgId","useMarketingOrgMount","CONTAINER_CEILING","EMAIL_PAGE_SORT_HEADERS","site","state","when","recipients","opens","clicks","DISCARD_REFUSAL","sent","scheduled","sending","canceled","STATE_COLOR","stopped","held","EMAIL_FILTER_HEADERS","subject","status","emailCampaignId","createdAtMs","emailsDocsHelp","anchor","excerpt","EmailsListCard","props","hostId","basePath","firestore","orgMount","orgId","siteMarketingHub","marketingHub","router","declaration","gridFilter","selectFields","askedSort","setAskedSort","emailPage","collection","request","clauses","search","searchWords","base","sort","deps","idField","emailPageSorts","row","label","stats","emailSort","sorts","onSortChange","orderBy","plan","rows","pageSorts","headers","emails","filtering","length","some","word","trim","messagesPath","emailHref","email","$id","routeContext","templateHref","templateScreenId","siteContext","rowHostId","String","hostOfEmail","Map","map","confirm","enqueueSnackbar","manageForCopy","duplicate","perform","sourceId","name","attemptKey","payload","response","action","campaignId","get","undefined","ok","Error","error","id","emailId","versionId","onDuplicated","_kind","copy","variant","manageApi","discardingId","setDiscardingId","handleDiscard","displayName","agreed","title","description","confirmationText","then","catch","allowDuplicate","persist","console","rowActions","containerId","templates","siteless","sitelessReason","key","icon","path","size","href","disabled","disabledReason","onClick","destructive","Boolean","createOpen","setCreateOpen","creating","setCreating","campaignSendApi","orgSites","askSite","data","campaignDocs","containers","campaignOptions","campaign","value","a","b","localeCompare","filterOptions","handleCreate","values","sendAs","chosenCampaign","find","push","columns","field","headerName","flex","minWidth","valueGetter","_value","renderCell","event","stopPropagation","width","display","color","at","Date","toLocaleString","stat","type","align","headerAlign","Number","valueFormatter","items","gridColumns","fields","none","page","header","help","HeaderProps","contentGutterX","contentGutterY","dialog","spacing","sx","alignItems","onChange","setClauses","options","refused","notices","aria-label","rowHeight","onOpen","_id","loading","filterMode","filterModel","onFilterModelChange","quickFilter","columnSort","hideFooter","initialState","columnVisibilityModel","column","noRowsLabel","pageSize","rowCount","hasMore","onPageChange","setPage","onPageSizeChange","setPageSize","open","onClose","submitLabel","includeDescription","onSubmit","extraFields","component","isRequired","initialValue","helperText","disableDefaultOption"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,cAAc,QAAQ,eAAc;AAC7C,SAASC,gBAAgB,QAAQ,mDA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,KAAKtJ,MAAQjB,OAAO0H,IAAI,CAACvF,UAAUlB;4BAC5CuJ,SAASlK,UAAUrB,MAAM,KAAK;4BAC9B;;;;;;eAMC,GACDwL,YAAW;4BACXC,aAAaxK,WAAWwK,WAAW;4BACnCC,qBAAqBzK,WAAWyK,mBAAmB;4BACnDC,WAAW;4BACXC,YAAYzJ;4BACZ0J,UAAU;4BACVC,cAAc;gCACZpD,SAAS;oCACPqD,uBAAuB3P,uBACrB4E,YAAYkJ,MAAM,EAClBxB,QAAQ7E,GAAG,CAAC,CAACmI,SAAWA,OAAOrD,KAAK;gCAExC;4BACF;4BACAsD,aAAY;;sCAEd,KAACnQ;4BACCsO,MAAM/I,UAAU+I,IAAI;4BACpB8B,UAAU7K,UAAU6K,QAAQ;4BAC5BC,UAAUxJ,OAAOE,MAAM;4BACvBuJ,SAAS/K,UAAU+K,OAAO;4BAC1BC,cAAchL,UAAUiL,OAAO;4BAC/BC,kBAAkBlL,UAAUmL,WAAW;;;;;0BAqB/C,KAAC/P;gBACCgQ,MAAMtF;gBACNuF,SAAS,IAAMtF,cAAc;gBAC7BxB,OAAM;gBACN+G,aAAatF,WAAW,cAAc;gBACtCuF,oBAAoB;gBACpBC,UAAUzE;gBACV0E,aAAa;uBACPrF,UACA;wBACE;4BACEsF,WAAW;4BACX3I,MAAM;4BACNnC,OAAO;4BACP+K,YAAY;4BACZC,cAAc;4BACdC,YACE,4DACA;4BACFC,sBAAsB;4BACtBnC,SAASxD;wBACX;qBACD,GACD,EAAE;oBACN;wBACEuF,WAAW;wBACX3I,MAAM;wBACNnC,OAAO;wBACPgL,cAAc;wBACdC,YACE,+DACA;wBACFC,sBAAsB;wBACtBnC,SAAS;4BACP;gCAAEjD,OAAO;gCAAI9F,OAAO;4BAAuC;+BACxD4F;yBACJ;oBACH;iBACD;;;;AAIT;AACAvH,eAAeoF,WAAW,GAAG;AAE7B,eAAepF,eAAc"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/emails-list-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { pluginRecordHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport {\n mdiBullhornOutline,\n mdiContentCopy,\n mdiDeleteOutline,\n mdiPageNextOutline,\n mdiPaletteOutline,\n} from '@aglyn/shared-data-mdi'\nimport {\n AppLink,\n CardDisplay,\n MdiIcon,\n useConfirmationContext,\n} from '@aglyn/shared-ui-jsx'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { hiddenFilterVisibility } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { useListColumnSort } from '@aglyn/shared-ui-jsx/hooks/use-list-column-sort'\nimport type { ListQuerySort } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { CreateArtifactDrawer } from '@aglyn/shared-ui-jsx-forms'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { collectionCeiling } from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { useListQuery } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport {\n DUPLICATE_MENU_LABEL,\n useDuplicateResource,\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport { Button, Chip, Stack, Typography } from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useMemo, useState } from 'react'\nimport {\n campaignPlacedOnHost,\n campaignSendDisplay,\n CAMPAIGN_SEND_CONTAINER_FIELD,\n type CampaignSendDisplayState,\n} from '../model/campaign-container'\nimport {\n emailListTimeMs,\n emailSendTimeMs,\n} from '../model/email-record'\nimport {\n useCampaignManageApi,\n useCampaignSendApi,\n} from './use-campaign-send-api'\nimport {\n CAMPAIGN_SEND_STATUS_OPTIONS,\n SINGLE_SEND_FILTER_VALUE,\n campaignEmailsListQuery,\n campaignSendsScope,\n emailCampaignQueryClauses,\n} from '../model/campaign-list-query'\nimport { useMarketingHubPath } from './use-marketing-hub-path'\nimport { siteRecordRouteContext, useRecordRouteContext } from './record-route-context'\nimport {\n campaignContainersQuery,\n campaignSendsCollection,\n} from './campaign-queries'\nimport {\n orgSiteName,\n orgSiteOptions,\n useMarketingOrgId,\n useMarketingOrgMount,\n} from './marketing-org-mount'\n\n/**\n * How many campaigns the Campaign filter and the create drawer offer — the\n * same read serves both. A picker's options, not a list.\n */\nconst CONTAINER_CEILING = 50\n\n/** The headers a page sort names in its notice. */\nconst EMAIL_PAGE_SORT_HEADERS = {\n site: 'Site',\n state: 'State',\n when: 'When',\n recipients: 'Addressed',\n opens: 'Opens',\n clicks: 'Clicks',\n}\n\n/**\n * Why discard is refused, keyed by the state that refuses it.\n *\n * The KEYS are persisted status values written by the send path. Each line\n * says what to do instead, because \"you cannot\" on its own leaves a merchant\n * with an email they wanted rid of and no next step — and for a scheduled one\n * the next step is a different act with a different consequence, so naming it\n * is the difference between withdrawing mail and losing the record of it.\n *\n * A state absent from here falls through to the generic refusal rather than\n * being flattened into one of these: a state this list cannot name is worth\n * seeing.\n */\nconst DISCARD_REFUSAL: Record<string, string> = {\n sent: 'This email has been sent. Its report and its unsubscribe links have to go on resolving.',\n scheduled: 'Cancel the send first — cancelling takes it off the clock and keeps the email.',\n sending: 'This email is being sent right now.',\n canceled: 'A canceled email is kept as the record that it was withdrawn.',\n}\n\n/**\n * The chip color for one display state.\n *\n * `sending` is the one worth a color: an email part way through an audience\n * larger than one batch is doing something right now, and a merchant scanning\n * the list for what needs attention should find it without reading. The rest\n * are neutral, because a finished send and a draft are not events.\n */\nconst STATE_COLOR: Partial<\n Record<CampaignSendDisplayState, 'info' | 'warning'>\n> = {\n sending: 'info',\n stopped: 'warning',\n // Waiting on staff, not on the merchant (AGL-3356): worth finding on a scan.\n held: 'warning',\n}\n\n/*\n * What the messages grid's Filters panel offers, each clause and the search\n * on the list's Firestore query (AGL-3321, `campaignEmailsListQuery`). The\n * State column is what the email is DOING (`campaignSendDisplay`), which no\n * query can ask, so the panel offers the Status it STORES instead.\n */\nconst EMAIL_FILTER_HEADERS: Readonly<Record<string, string>> = {\n subject: 'Subject',\n status: 'Status',\n emailCampaignId: 'Campaign',\n site: 'Site',\n createdAtMs: 'Created',\n}\n\nconst emailsDocsHelp = pluginDocsHelp('emailCampaigns', { anchor: '#messages-list' })\n\nexport interface EmailsListCardProps {\n /** The site, or `null` on the organization's Emails page. */\n hostId: string | null\n /**\n * The Emails page's own URL, under the site or the organization, so a row\n * can link to the message's own page beneath it.\n */\n basePath: string\n}\n\n/**\n * EVERY MESSAGE, AS AGAINST EVERY CAMPAIGN.\n *\n * A campaign groups messages; this is the messages. The two are different\n * questions — \"how did the spring promotion do\" and \"what went out on the\n * 14th, and to whom\" — and they were previously the same list because a\n * campaign document WAS a single send.\n *\n * ## Asked of Firestore, a page at a time\n *\n * No SEND date is on every message — a sent one carries `sentAt`, a\n * scheduled one `sendAtMs`, a draft neither — so the list is ordered on\n * `createdAtMs`, the one date every writer stamps when it mints a record\n * (and `backfill-campaign-list-fields.mjs` stamped on the ones before).\n * Newest first, paged by the query itself.\n *\n * The Filters panel and the search box are the grid's; every clause and the\n * search word go onto that ONE query (AGL-3321, `campaignEmailsListQuery`),\n * so each page is a page of matches — an email that matches on page four is\n * found — and a combination one query cannot hold is refused by name above\n * the table, never answered over the rows that happen to be loaded.\n *\n * ## Under a site, and over the organization\n *\n * Sends are the org's. Under a site this lists the ones sent as that site;\n * on the organization's Emails page it lists every site's, with a Site column,\n * and every action on a row names the site that row is sent as — the only\n * site that can duplicate it, discard it or open its template. Creating one\n * there first asks which site it is sent as.\n */\nexport function EmailsListCard(props: EmailsListCardProps) {\n const { hostId, basePath } = props\n const firestore = useFirestore()\n const orgMount = useMarketingOrgMount()\n const { orgId } = useMarketingOrgId(hostId)\n // The sibling hub: a campaign's page belongs to the Marketing console —\n // over the org, the organization's own Marketing page the mount names.\n const siteMarketingHub = useMarketingHubPath()\n const marketingHub = orgMount ? orgMount.basePath : siteMarketingHub\n const router = useRouter()\n\n /*\n * The Filters panel and the search, bound to the grid. Held here rather\n * than in a saved view: this list keeps no views.\n */\n const declaration = campaignEmailsListQuery(!hostId)\n const gridFilter = useListGridFilter({\n selectFields: ['status', 'emailCampaignId', 'site'],\n })\n /*\n * EVERY HEADER SORTS (AGL-3680): Subject orders the query\n * (`declaration.sorts`); Site, State, When and the figures are derived or\n * may be absent, and sort the page.\n */\n const [askedSort, setAskedSort] = useState<ListQuerySort | null>(null)\n const emailPage = useListQuery<any>({\n collection: campaignSendsCollection(firestore, orgId),\n declaration,\n request: {\n clauses: emailCampaignQueryClauses(gridFilter.clauses),\n search: gridFilter.searchWords,\n base: campaignSendsScope(hostId),\n sort: askedSort,\n },\n deps: [firestore, orgId, hostId],\n idField: '$id',\n })\n const emailPageSorts = useMemo(\n () => ({\n ...(orgMount\n ? { site: (row: any) => (row?.hostId ? orgSiteName(orgMount, row.hostId) : null) }\n : {}),\n state: (row: any) => campaignSendDisplay(row).label,\n when: (row: any) => emailListTimeMs(row),\n // Counters stay absent until something is counted (see\n // `campaign-list-query.ts`), so no query can order by them.\n recipients: (row: any) => row.stats?.recipients ?? null,\n opens: (row: any) => row.stats?.opens ?? null,\n clicks: (row: any) => row.stats?.clicks ?? null,\n }),\n [orgMount],\n )\n const emailSort = useListColumnSort<any>({\n sorts: declaration.sorts,\n sort: askedSort,\n onSortChange: setAskedSort,\n orderBy: emailPage.plan.orderBy,\n rows: emailPage.rows,\n pageSorts: emailPageSorts,\n headers: EMAIL_PAGE_SORT_HEADERS,\n })\n const emails = emailPage.rows\n const filtering =\n gridFilter.clauses.length > 0 ||\n gridFilter.searchWords.some((word) => word.trim())\n\n /*\n * A message's own pages, beneath the Emails page this list is on — the\n * site's or the organization's. A template is a site's design, so over the\n * org it opens on the site the row is sent as.\n */\n const messagesPath = `${basePath}/messages`\n const emailHref = (email: any) => `${messagesPath}/${email.$id}`\n const routeContext = useRecordRouteContext()\n const templateHref = (email: any, templateScreenId: string): string | null => {\n const siteContext = siteRecordRouteContext(routeContext, orgMount, email?.hostId)\n return siteContext ? pluginRecordHref('emailTemplate', siteContext, templateScreenId) : null\n }\n /** The site a row is sent as, which every action on it must name. */\n const rowHostId = useCallback(\n (email: any): string | null =>\n hostId ?? (email?.hostId ? String(email.hostId) : null),\n [hostId],\n )\n const hostOfEmail = useMemo(\n () =>\n new Map<string, string | null>(\n emails.map((email: any) => [\n String(email.$id),\n email?.hostId ? String(email.hostId) : null,\n ]),\n ),\n [emails],\n )\n\n const { confirm } = useConfirmationContext()\n const { enqueueSnackbar } = useSnackbar()\n // Duplicate (AGL-2936): a new draft with the message and its design, and\n // nobody to send to until the person chooses — through the manage door,\n // which is the plugin's own.\n const manageForCopy = useCampaignManageApi(hostId)\n const duplicate = useDuplicateResource({\n hostId: hostId ?? '',\n perform: async ({ sourceId, name, attemptKey }) => {\n const { response, payload } = await manageForCopy({\n action: 'duplicate',\n campaignId: sourceId,\n name,\n attemptKey,\n // The copy is made as the site the source is sent as.\n ...(hostId ? {} : { hostId: hostOfEmail.get(sourceId) ?? undefined }),\n })\n if (!response.ok) throw new Error(payload?.error ?? 'Duplicate failed')\n return {\n id: String(payload.emailId),\n versionId: null,\n name: String(payload.name ?? name),\n }\n },\n onDuplicated: (_kind, copy) =>\n enqueueSnackbar(`Duplicated as “${copy.name}” — a draft with no audience yet`, {\n variant: 'success',\n }),\n })\n const manageApi = useCampaignManageApi(hostId)\n /** The email a discard is in flight for, so its row menu can say so. */\n const [discardingId, setDiscardingId] = useState('')\n\n /*==========================================\n * THROWING AWAY A DRAFT.\n *\n * The one removal this surface has, and it is deliberately the narrowest\n * one: an email that was never sent, whose record nobody outside the\n * console has ever seen. Everything else on this list is evidence — a sent\n * message's report is what a merchant answers a complaint with, and its id\n * is inside the HMAC of every unsubscribe footer it delivered — and a\n * scheduled one is withdrawn with Cancel, which keeps the record and takes\n * it off the clock.\n *\n * The menu already refuses anything but a draft, and so does the route.\n * That is not belt and braces: the state on screen is a snapshot that can\n * be seconds old, and the record can be claimed by `sendNow` in between.\n * The route's refusal is the one that decides, inside the transaction that\n * does the delete.\n *=========================================*/\n const handleDiscard = useCallback(\n async (email: any) => {\n if (discardingId) return\n const id = String(email?.$id ?? '')\n const name = String(email?.subject || email?.displayName || 'this draft')\n const agreed = await confirm({\n title: 'Discard this draft?',\n description:\n `${name} has not been sent to anybody, and discarding it removes ` +\n 'it for good — the subject, the message and everything else ' +\n 'written on it. There is no undo.',\n confirmationText: 'Discard',\n })\n .then(() => true)\n .catch(() => false)\n if (!agreed) return\n setDiscardingId(id)\n try {\n const { response, payload } = await manageApi({\n action: 'discardEmail',\n campaignId: id,\n ...(hostId ? {} : { hostId: rowHostId(email) ?? undefined }),\n })\n if (!response.ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'This draft could not be discarded',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n enqueueSnackbar('Draft discarded', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('This draft could not be discarded', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setDiscardingId('')\n }\n },\n [confirm, discardingId, enqueueSnackbar, hostId, manageApi, rowHostId],\n )\n\n /**\n * What a message can be opened INTO, from the list.\n *\n * All three are places the message's own report already links to, moved one\n * screen earlier: the report itself, the campaign it belongs to, and the\n * template it was rendered from. A message need have neither of the last\n * two — one sent before campaigns grouped anything names no container, and\n * one composed inline was built from no template — so those entries are\n * shown DISABLED with the reason rather than hidden. A control that\n * disappears and a control that does not apply look identical, and only one\n * of them tells the reader which case they are in.\n *\n * DISCARD is the fourth entry and is offered on the same terms: a draft can\n * be thrown away, and nothing else can. It stays visible on a sent or\n * scheduled message carrying the reason it is refused, because that is the\n * honest answer to “how do I get rid of this” — and the route refuses it\n * too, so the menu is describing a rule rather than being one.\n */\n const rowActions = (email: any): RowActionsMenuItem[] => {\n const containerId = String(email?.[CAMPAIGN_SEND_CONTAINER_FIELD] ?? '')\n const templateScreenId = String(email?.templateScreenId ?? '')\n const state = String(email?.status ?? '')\n const templates = templateScreenId ? templateHref(email, templateScreenId) : null\n /** On the org hub, a send that names no site has nothing to act as. */\n const siteless = !rowHostId(email)\n const sitelessReason =\n 'This email does not record which site it was sent as. Manage it from ' +\n 'that site’s own Emails page.'\n return [\n {\n key: 'details',\n label: 'Open report',\n icon: <MdiIcon path={mdiPageNextOutline.path} size={0.8} />,\n href: emailHref(email),\n },\n {\n key: 'campaign',\n label: 'Open its campaign',\n icon: <MdiIcon path={mdiBullhornOutline.path} size={0.8} />,\n // The campaign's page belongs to the Marketing console, so this one\n // href is built from the sibling hub rather than this surface's own.\n href:\n containerId && marketingHub\n ? `${marketingHub}/campaigns/${containerId}`\n : undefined,\n disabled: !containerId || !marketingHub,\n disabledReason: containerId\n ? 'This site’s console URL has not resolved yet'\n : 'Sent before campaigns grouped their emails, so it belongs to none',\n },\n {\n key: 'template',\n label: 'Open its template',\n icon: <MdiIcon path={mdiPaletteOutline.path} size={0.8} />,\n href: templates ?? undefined,\n disabled: !templates,\n disabledReason: templateScreenId\n ? 'This site’s console URL has not resolved yet'\n : 'This message was not built from a template',\n },\n {\n key: 'duplicate',\n label: DUPLICATE_MENU_LABEL,\n icon: <MdiIcon path={mdiContentCopy.path} size={0.8} />,\n disabled: siteless,\n disabledReason: sitelessReason,\n onClick: () =>\n duplicate.request('campaign', {\n id: String(email.$id),\n name: String(email?.displayName ?? email?.subject ?? ''),\n }),\n },\n {\n key: 'discard',\n label: 'Discard draft',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: siteless || state !== 'draft' || Boolean(discardingId),\n disabledReason: siteless\n ? sitelessReason\n : (DISCARD_REFUSAL[state] ?? 'Only a draft can be discarded'),\n onClick: () => void handleDiscard(email),\n },\n ]\n }\n\n const [createOpen, setCreateOpen] = useState(false)\n const [creating, setCreating] = useState(false)\n const campaignSendApi = useCampaignSendApi(hostId)\n /*\n * The sites a new email can be sent as, on the org hub. One site answers\n * the question itself, so the field is asked only when there is a choice.\n */\n const orgSites = useMemo(\n () => (orgMount ? orgSiteOptions(orgMount) : []),\n [orgMount],\n )\n const askSite = !hostId && orgSites.length > 1\n\n /*\n * The campaigns, read while the list is shown: the Campaign filter offers\n * them by name, and the create drawer offers them to file a new email\n * under. One capped read of the containers serves both.\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 campaignOptions = useMemo(\n () =>\n [...(campaignDocs ?? [])]\n .map((campaign: any) => ({\n value: String(campaign.$id),\n label: String(campaign.name || 'Untitled campaign'),\n }))\n .sort((a, b) => a.label.localeCompare(b.label)),\n [campaignDocs],\n )\n\n const filterOptions = useMemo(\n () => ({\n status: CAMPAIGN_SEND_STATUS_OPTIONS,\n emailCampaignId: [\n { value: SINGLE_SEND_FILTER_VALUE, label: 'Single send' },\n ...campaignOptions,\n ],\n ...(hostId ? {} : { site: orgSites }),\n }),\n [campaignOptions, hostId, orgSites],\n )\n\n /*==========================================\n * CREATE, THEN GO TO THE EMAIL'S OWN PAGE.\n *\n * The drawer collects only what it takes to MINT the record — the friendly\n * name, and the campaign it belongs to. Everything else about the email is\n * written on the email's own page, which is where a record is edited\n * throughout this console: a list page carries no form.\n *\n * The record is real from this moment: `/marketing/campaigns/{id}` resolves,\n * the row appears in the table below as a Draft, and the id it is created\n * under is the id it keeps when it is eventually sent. It costs nothing to\n * exist — the route reserves no allowance and moves no meter for a draft,\n * and the scheduled processor only ever picks up `scheduled`.\n *=========================================*/\n const handleCreate = useCallback(\n async (values: Record<string, any>) => {\n if (creating) return\n const sendAs =\n hostId ?? (askSite ? String(values.hostId ?? '') : orgSites[0]?.value)\n if (!sendAs) {\n return void enqueueSnackbar('Choose the site this email is sent as', {\n variant: 'warning',\n allowDuplicate: true,\n })\n }\n /*\n * The organization hub offers every campaign, because the site is\n * chosen in the same form. An email can only join a campaign placed on\n * the site it is sent as — the send route refuses anything else — so\n * the mismatch is named here, where it can be fixed, rather than\n * arriving as the route's bare refusal. A site hub lists only the\n * campaigns placed on it, so there is nothing to check there.\n */\n const chosenCampaign =\n !hostId && values.emailCampaignId\n ? (campaignDocs ?? []).find(\n (campaign: any) =>\n String(campaign.$id) === String(values.emailCampaignId),\n )\n : null\n if (chosenCampaign && !campaignPlacedOnHost(chosenCampaign, sendAs)) {\n return void enqueueSnackbar(\n 'That campaign is not offered on the site this email is sent as. ' +\n 'Choose another, or add the site to the campaign first.',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n setCreating(true)\n try {\n const { response, payload } = await campaignSendApi({\n action: 'draft',\n ...(hostId ? {} : { hostId: sendAs }),\n displayName: String(values.displayName ?? '').trim(),\n ...(values.emailCampaignId\n ? { emailCampaignId: String(values.emailCampaignId) }\n : {}),\n })\n if (!response.ok || !payload?.campaignId) {\n return void enqueueSnackbar(\n payload?.error ?? 'This email could not be created',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n setCreateOpen(false)\n /*\n * Straight to where it is WRITTEN. The drawer collected the name and\n * the campaign; the record now exists and holds nothing else, so the\n * next thing to do with it is compose it — and its own page is a\n * report of a send that has not happened.\n */\n router.push(`${messagesPath}/${payload.campaignId}/edit`)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('This email could not be created', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setCreating(false)\n }\n },\n [\n askSite,\n campaignDocs,\n campaignSendApi,\n creating,\n enqueueSnackbar,\n hostId,\n messagesPath,\n orgSites,\n router,\n ],\n )\n\n /*\n * One row per message, in the query's order. The subject is a link AND the\n * row opens the report: a click handler cannot be middle-clicked or opened\n * in a new tab.\n */\n const columns: GridColDef[] = [\n {\n field: 'subject',\n headerName: 'Subject',\n flex: 1,\n minWidth: 220,\n valueGetter: (_value, row) => row.subject || 'Untitled email',\n renderCell: ({ row, value }) => (\n <AppLink\n href={emailHref(row)}\n // The row's own handler would fire too and push the same route\n // twice — one history entry per back press.\n onClick={(event: { stopPropagation: () => void }) =>\n event.stopPropagation()\n }\n >\n {value}\n </AppLink>\n ),\n },\n // Which site each row is sent as, on the org hub only.\n ...(orgMount\n ? [\n {\n field: 'site',\n headerName: 'Site',\n width: 150,\n valueGetter: (_value: unknown, row: any) =>\n row?.hostId ? orgSiteName(orgMount, row.hostId) : '—',\n } satisfies GridColDef,\n ]\n : []),\n {\n /*\n * WHAT THIS EMAIL IS DOING, not what field it stores.\n *\n * An email delivering an audience larger than one batch is written back\n * as `scheduled` between runs, so a chip rendering the status said\n * \"Scheduled\" about a send that had already reached five hundred people.\n * The derivation reads the counters beside the status and says which of\n * the two it is.\n */\n field: 'state',\n headerName: 'State',\n width: 150,\n valueGetter: (_value, row) => campaignSendDisplay(row).label,\n renderCell: ({ row }) => {\n const display = campaignSendDisplay(row)\n return (\n <Chip\n size=\"small\"\n color={STATE_COLOR[display.state]}\n label={display.label}\n />\n )\n },\n },\n {\n field: 'when',\n headerName: 'When',\n width: 190,\n valueGetter: (_value, row) => emailListTimeMs(row),\n renderCell: ({ row }) => {\n const at = emailSendTimeMs(row)\n return at ? new Date(at).toLocaleString() : '—'\n },\n },\n ...(\n [\n ['recipients', 'Addressed'],\n ['opens', 'Opens'],\n ['clicks', 'Clicks'],\n ] as const\n ).map(\n ([stat, headerName]): GridColDef => ({\n field: stat,\n headerName,\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 110,\n valueGetter: (_value, row) => Number(row.stats?.[stat] ?? 0),\n valueFormatter: (value: number) => value.toLocaleString(),\n }),\n ),\n listActionsColumn(\n (row) => (\n <ListRowActions\n label={String(row.subject || 'Untitled email')}\n items={rowActions(row)}\n />\n ),\n { width: 72 },\n ),\n ]\n\n const gridColumns = listFilterGridColumns(\n columns,\n declaration.fields,\n filterOptions,\n EMAIL_FILTER_HEADERS,\n )\n /** Nothing stored at all — not a filter that matched nothing. */\n const none =\n emailPage.status !== 'loading' &&\n emails.length === 0 &&\n !filtering &&\n emailPage.page === 0\n\n return (\n <CardDisplay\n header={'Messages'}\n help={emailsDocsHelp}\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"contained\"\n onClick={() => setCreateOpen(true)}\n >\n {'New email'}\n </Button>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n {duplicate.dialog}\n <Stack spacing={2}>\n {none ? (\n <Stack spacing={2} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Nothing has been sent or scheduled yet. Write one here, or ' +\n 'from a campaign, and it appears in this list with its own ' +\n 'report.'}\n </Typography>\n <Button variant=\"contained\" onClick={() => setCreateOpen(true)}>\n {'New email'}\n </Button>\n </Stack>\n ) : (\n <>\n <ListFilterChips\n fields={declaration.fields}\n headers={EMAIL_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={filterOptions}\n />\n <ListQueryNotices\n refused={listQueryRefusals(emailPage.plan.refused, {\n fields: declaration.fields,\n headers: EMAIL_FILTER_HEADERS,\n options: filterOptions,\n })}\n notices={[...emailPage.plan.notices, ...emailSort.notices]}\n />\n <ListTable\n aria-label=\"Messages\"\n rows={emailSort.rows}\n columns={gridColumns}\n rowHeight={TABLE_ROW_HEIGHT}\n onOpen={(_id, row) => router.push(emailHref(row))}\n loading={emailPage.status === 'loading'}\n /*\n * The panel and the search are the grid's; every clause and\n * the search word are on the list's query (AGL-3321), and the\n * grid neither filters nor sorts the page it is handed:\n * Subject's header orders the query, the rest the page\n * (AGL-3680), newest first until one is clicked.\n */\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n columnSort={emailSort}\n hideFooter\n initialState={{\n columns: {\n columnVisibilityModel: hiddenFilterVisibility(\n declaration.fields,\n columns.map((column) => column.field),\n ),\n },\n }}\n noRowsLabel=\"No messages match these filters\"\n />\n <ListPagination\n page={emailPage.page}\n pageSize={emailPage.pageSize}\n rowCount={emails.length}\n hasMore={emailPage.hasMore}\n onPageChange={emailPage.setPage}\n onPageSizeChange={emailPage.setPageSize}\n />\n </>\n )}\n </Stack>\n {/*\n AN EMAIL WRITTEN HERE BELONGS TO A CAMPAIGN, OR TO NO CAMPAIGN.\n\n The second is a real answer and not a gap in the model. A send with no\n container is what the product has always had — every message that\n predates campaigns is one — and `campaignListRows` adopts each of them\n as a campaign of one at read time, which is the \"Single send\" chip on\n the campaigns table. So composing from this list mints nothing, files\n nothing, and requires nobody to invent a campaign first: it leaves the\n container empty, and the send that results is presented the way every\n containerless send already is.\n\n Offering the campaigns anyway is what stops the opposite mistake — a\n merchant who DOES have a spring campaign writing its third email into\n a single send that never joins the rollup.\n */}\n <CreateArtifactDrawer\n open={createOpen}\n onClose={() => setCreateOpen(false)}\n title=\"New email\"\n submitLabel={creating ? 'Creating…' : 'Start writing'}\n includeDescription={false}\n onSubmit={handleCreate}\n extraFields={[\n ...(askSite\n ? [\n {\n component: 'select',\n name: 'hostId',\n label: 'Send as',\n isRequired: true,\n initialValue: '',\n helperText:\n 'The site this email is sent from — its sender, designs ' +\n 'and unsubscribe page',\n disableDefaultOption: true,\n options: orgSites,\n },\n ]\n : []),\n {\n component: 'select',\n name: 'emailCampaignId',\n label: 'Campaign',\n initialValue: '',\n helperText:\n 'Leave this as a single send unless the email belongs with ' +\n 'others',\n disableDefaultOption: true,\n options: [\n { value: '', label: 'Single send — not part of a campaign' },\n ...campaignOptions,\n ],\n },\n ]}\n />\n </CardDisplay>\n )\n}\nEmailsListCard.displayName = 'EmailsListCard'\n\nexport default EmailsListCard\n"],"names":["pluginDocsHelp","pluginRecordHref","mdiBullhornOutline","mdiContentCopy","mdiDeleteOutline","mdiPageNextOutline","mdiPaletteOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListRowActions","ListTable","listActionsColumn","hiddenFilterVisibility","listFilterGridColumns","useListGridFilter","useListColumnSort","TABLE_ROW_HEIGHT","CreateArtifactDrawer","useSnackbar","collectionCeiling","useListQuery","DUPLICATE_MENU_LABEL","useDuplicateResource","useFirestore","useFirestoreCollection","Button","Chip","Stack","Typography","useRouter","useCallback","useMemo","useState","campaignPlacedOnHost","campaignSendDisplay","CAMPAIGN_SEND_CONTAINER_FIELD","emailListTimeMs","emailSendTimeMs","useCampaignManageApi","useCampaignSendApi","CAMPAIGN_SEND_STATUS_OPTIONS","SINGLE_SEND_FILTER_VALUE","campaignEmailsListQuery","campaignSendsScope","emailCampaignQueryClauses","useMarketingHubPath","siteRecordRouteContext","useRecordRouteContext","campaignContainersQuery","campaignSendsCollection","orgSiteName","orgSiteOptions","useMarketingOrgId","useMarketingOrgMount","CONTAINER_CEILING","EMAIL_PAGE_SORT_HEADERS","site","state","when","recipients","opens","clicks","DISCARD_REFUSAL","sent","scheduled","sending","canceled","STATE_COLOR","stopped","held","EMAIL_FILTER_HEADERS","subject","status","emailCampaignId","createdAtMs","emailsDocsHelp","anchor","EmailsListCard","props","hostId","basePath","firestore","orgMount","orgId","siteMarketingHub","marketingHub","router","declaration","gridFilter","selectFields","askedSort","setAskedSort","emailPage","collection","request","clauses","search","searchWords","base","sort","deps","idField","emailPageSorts","row","label","stats","emailSort","sorts","onSortChange","orderBy","plan","rows","pageSorts","headers","emails","filtering","length","some","word","trim","messagesPath","emailHref","email","$id","routeContext","templateHref","templateScreenId","siteContext","rowHostId","String","hostOfEmail","Map","map","confirm","enqueueSnackbar","manageForCopy","duplicate","perform","sourceId","name","attemptKey","payload","response","action","campaignId","get","undefined","ok","Error","error","id","emailId","versionId","onDuplicated","_kind","copy","variant","manageApi","discardingId","setDiscardingId","handleDiscard","displayName","agreed","title","description","confirmationText","then","catch","allowDuplicate","persist","console","rowActions","containerId","templates","siteless","sitelessReason","key","icon","path","size","href","disabled","disabledReason","onClick","destructive","Boolean","createOpen","setCreateOpen","creating","setCreating","campaignSendApi","orgSites","askSite","data","campaignDocs","containers","campaignOptions","campaign","value","a","b","localeCompare","filterOptions","handleCreate","values","sendAs","chosenCampaign","find","push","columns","field","headerName","flex","minWidth","valueGetter","_value","renderCell","event","stopPropagation","width","display","color","at","Date","toLocaleString","stat","type","align","headerAlign","Number","valueFormatter","items","gridColumns","fields","none","page","header","help","HeaderProps","contentGutterX","contentGutterY","dialog","spacing","sx","alignItems","onChange","setClauses","options","refused","notices","aria-label","rowHeight","onOpen","_id","loading","filterMode","filterModel","onFilterModelChange","quickFilter","columnSort","hideFooter","initialState","columnVisibilityModel","column","noRowsLabel","pageSize","rowCount","hasMore","onPageChange","setPage","onPageSizeChange","setPageSize","open","onClose","submitLabel","includeDescription","onSubmit","extraFields","component","isRequired","initialValue","helperText","disableDefaultOption"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,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c"}
@@ -15,11 +15,10 @@
15
15
  * limitations under the License.
16
16
  */ 'use client';
17
17
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
18
- import { pluginDocsHelp } from "@aglyn/aglyn";
19
18
  import { CardDisplay } from "@aglyn/shared-ui-jsx";
20
19
  import { MenuItem, Stack, TextField, Typography } from "@mui/material";
21
20
  import { useEffect, useState } from "react";
22
- import CampaignConversionsCard from "./campaign-conversions-card.js";
21
+ import CampaignConversionsCard, { conversionsDocsHelp } from "./campaign-conversions-card.js";
23
22
  import { useMarketingOrgMount } from "./marketing-org-mount.js";
24
23
  /**
25
24
  * The session's memory of the site this section reads, per org. Session
@@ -80,9 +79,7 @@ function writeRememberedSite(orgId, hostId) {
80
79
  if (!hostId) {
81
80
  return /*#__PURE__*/ _jsx(CardDisplay, {
82
81
  header: "Conversions",
83
- help: pluginDocsHelp('emailCampaigns', {
84
- anchor: '#the-campaign-report'
85
- }),
82
+ help: conversionsDocsHelp,
86
83
  contentGutterX: true,
87
84
  contentGutterY: true,
88
85
  children: /*#__PURE__*/ _jsx(Typography, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/org-conversions-section.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { MenuItem, Stack, TextField, Typography } from '@mui/material'\nimport { useEffect, useState } from 'react'\nimport CampaignConversionsCard from './campaign-conversions-card'\nimport { useMarketingOrgMount } from './marketing-org-mount'\n\n/**\n * The session's memory of the site this section reads, per org. Session\n * storage rather than local, for the reason the CRM's own site pick gives:\n * it is a convenience for one sitting, and a site remembered for weeks\n * would open on figures the reader had forgotten choosing.\n */\nexport const conversionsSiteStorageKey = (orgId: string) =>\n `aglyn.marketing.conversionsSite.${orgId}`\n\nfunction readRememberedSite(orgId: string): string | null {\n try {\n return window.sessionStorage.getItem(conversionsSiteStorageKey(orgId))\n } catch {\n return null\n }\n}\n\nfunction writeRememberedSite(orgId: string, hostId: string): void {\n try {\n window.sessionStorage.setItem(conversionsSiteStorageKey(orgId), hostId)\n } catch {\n // A browser that refuses storage still gets the pick for this page.\n }\n}\n\nexport interface OrgConversionsSectionProps {\n /** The org Marketing hub, `/[orgSlug]/marketing` — each credited campaign opens under it. */\n basePath: string\n /** One campaign's conversions, from `…/conversions/{campaignId}`. */\n campaignId?: string\n}\n\n/**\n * The organization's Conversions section: ONE site's conversions at a time.\n *\n * A conversion is recorded by the site the visitor converted on — its\n * attribution records, its submissions, its bookings — and the card that\n * reads them is the site hub's own, unchanged, handed the site picked here.\n * Merging several sites into one list would put two different sites'\n * \"not credited\" figures under one heading, and there is no org-wide\n * collection of attributions to read instead.\n *\n * The pick defaults to the org's first site and is remembered for the\n * session. A remembered site the org no longer lists is forgotten rather\n * than read.\n */\nexport function OrgConversionsSection(props: OrgConversionsSectionProps) {\n const { basePath, campaignId } = props\n const mount = useMarketingOrgMount()\n const orgId = mount?.orgId ?? ''\n /*\n * Resolved after mount rather than in the initializer, so the first client\n * paint agrees with the server's — and the card waits for it, because\n * mounting on the first site and then remounting on the remembered one\n * would pay for the first site's reads on the way.\n */\n const [picked, setPicked] = useState<{\n orgId: string\n hostId: string | null\n } | null>(null)\n useEffect(() => {\n if (orgId) setPicked({ orgId, hostId: readRememberedSite(orgId) })\n }, [orgId])\n\n if (!mount || !mount.hostsReady || picked?.orgId !== orgId) return null\n\n const sites = mount.hosts\n const hostId =\n picked.hostId && sites.some((site) => site.id === picked.hostId)\n ? picked.hostId\n : (sites[0]?.id ?? null)\n\n if (!hostId) {\n return (\n <CardDisplay\n header=\"Conversions\"\n help={pluginDocsHelp('emailCampaigns', { anchor: '#the-campaign-report' })}\n contentGutterX\n contentGutterY\n >\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Conversions are recorded by the site a visitor converts on, and ' +\n 'this organization has no sites yet.'}\n </Typography>\n </CardDisplay>\n )\n }\n\n return (\n <Stack spacing={2}>\n {sites.length > 1 ? (\n <TextField\n select\n size=\"small\"\n label=\"Conversions on\"\n value={hostId}\n onChange={(event) => {\n const next = event.target.value\n setPicked({ orgId, hostId: next })\n writeRememberedSite(orgId, next)\n }}\n sx={{ maxWidth: 320 }}\n >\n {sites.map((site) => (\n <MenuItem key={site.id} value={site.id}>\n {site.name || site.subdomain || site.id}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {/* Keyed by site, so nothing one site's card was holding survives into another's. */}\n <CampaignConversionsCard\n key={hostId}\n hostId={hostId}\n basePath={basePath}\n campaignId={campaignId}\n />\n </Stack>\n )\n}\nOrgConversionsSection.displayName = 'OrgConversionsSection'\n\nexport default OrgConversionsSection\n"],"names":["pluginDocsHelp","CardDisplay","MenuItem","Stack","TextField","Typography","useEffect","useState","CampaignConversionsCard","useMarketingOrgMount","conversionsSiteStorageKey","orgId","readRememberedSite","window","sessionStorage","getItem","writeRememberedSite","hostId","setItem","OrgConversionsSection","props","sites","basePath","campaignId","mount","picked","setPicked","hostsReady","hosts","some","site","id","header","help","anchor","contentGutterX","contentGutterY","variant","color","spacing","length","select","size","label","value","onChange","event","next","target","sx","maxWidth","map","name","subdomain","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,cAAc,QAAQ,eAAc;AAC7C,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,QAAQ,EAAEC,KAAK,EAAEC,SAAS,EAAEC,UAAU,QAAQ,gBAAe;AACtE,SAASC,SAA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;gBAAEkC,QAAQ;YAAuB;YACxEC,cAAc;YACdC,cAAc;sBAEd,cAAA,KAAC/B;gBAAWgC,SAAQ;gBAAQC,OAAM;0BAC/B,qEACC;;;IAIV;IAEA,qBACE,MAACnC;QAAMoC,SAAS;;YACblB,MAAMmB,MAAM,GAAG,kBACd,KAACpC;gBACCqC,MAAM;gBACNC,MAAK;gBACLC,OAAM;gBACNC,OAAO3B;gBACP4B,UAAU,CAACC;oBACT,MAAMC,OAAOD,MAAME,MAAM,CAACJ,KAAK;oBAC/BlB,UAAU;wBAAEf;wBAAOM,QAAQ8B;oBAAK;oBAChC/B,oBAAoBL,OAAOoC;gBAC7B;gBACAE,IAAI;oBAAEC,UAAU;gBAAI;0BAEnB7B,MAAM8B,GAAG,CAAC,CAACrB,qBACV,KAAC5B;wBAAuB0C,OAAOd,KAAKC,EAAE;kCACnCD,KAAKsB,IAAI,IAAItB,KAAKuB,SAAS,IAAIvB,KAAKC,EAAE;uBAD1BD,KAAKC,EAAE;iBAKxB;0BAEJ,KAACvB;gBAECS,QAAQA;gBACRK,UAAUA;gBACVC,YAAYA;eAHPN;;;AAOb;AACAE,sBAAsBmC,WAAW,GAAG;AAEpC,eAAenC,sBAAqB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/org-conversions-section.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 { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { MenuItem, Stack, TextField, Typography } from '@mui/material'\nimport { useEffect, useState } from 'react'\nimport CampaignConversionsCard, { conversionsDocsHelp } from './campaign-conversions-card'\nimport { useMarketingOrgMount } from './marketing-org-mount'\n\n/**\n * The session's memory of the site this section reads, per org. Session\n * storage rather than local, for the reason the CRM's own site pick gives:\n * it is a convenience for one sitting, and a site remembered for weeks\n * would open on figures the reader had forgotten choosing.\n */\nexport const conversionsSiteStorageKey = (orgId: string) =>\n `aglyn.marketing.conversionsSite.${orgId}`\n\nfunction readRememberedSite(orgId: string): string | null {\n try {\n return window.sessionStorage.getItem(conversionsSiteStorageKey(orgId))\n } catch {\n return null\n }\n}\n\nfunction writeRememberedSite(orgId: string, hostId: string): void {\n try {\n window.sessionStorage.setItem(conversionsSiteStorageKey(orgId), hostId)\n } catch {\n // A browser that refuses storage still gets the pick for this page.\n }\n}\n\nexport interface OrgConversionsSectionProps {\n /** The org Marketing hub, `/[orgSlug]/marketing` — each credited campaign opens under it. */\n basePath: string\n /** One campaign's conversions, from `…/conversions/{campaignId}`. */\n campaignId?: string\n}\n\n/**\n * The organization's Conversions section: ONE site's conversions at a time.\n *\n * A conversion is recorded by the site the visitor converted on — its\n * attribution records, its submissions, its bookings — and the card that\n * reads them is the site hub's own, unchanged, handed the site picked here.\n * Merging several sites into one list would put two different sites'\n * \"not credited\" figures under one heading, and there is no org-wide\n * collection of attributions to read instead.\n *\n * The pick defaults to the org's first site and is remembered for the\n * session. A remembered site the org no longer lists is forgotten rather\n * than read.\n */\nexport function OrgConversionsSection(props: OrgConversionsSectionProps) {\n const { basePath, campaignId } = props\n const mount = useMarketingOrgMount()\n const orgId = mount?.orgId ?? ''\n /*\n * Resolved after mount rather than in the initializer, so the first client\n * paint agrees with the server's — and the card waits for it, because\n * mounting on the first site and then remounting on the remembered one\n * would pay for the first site's reads on the way.\n */\n const [picked, setPicked] = useState<{\n orgId: string\n hostId: string | null\n } | null>(null)\n useEffect(() => {\n if (orgId) setPicked({ orgId, hostId: readRememberedSite(orgId) })\n }, [orgId])\n\n if (!mount || !mount.hostsReady || picked?.orgId !== orgId) return null\n\n const sites = mount.hosts\n const hostId =\n picked.hostId && sites.some((site) => site.id === picked.hostId)\n ? picked.hostId\n : (sites[0]?.id ?? null)\n\n if (!hostId) {\n return (\n <CardDisplay\n header=\"Conversions\"\n help={conversionsDocsHelp}\n contentGutterX\n contentGutterY\n >\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Conversions are recorded by the site a visitor converts on, and ' +\n 'this organization has no sites yet.'}\n </Typography>\n </CardDisplay>\n )\n }\n\n return (\n <Stack spacing={2}>\n {sites.length > 1 ? (\n <TextField\n select\n size=\"small\"\n label=\"Conversions on\"\n value={hostId}\n onChange={(event) => {\n const next = event.target.value\n setPicked({ orgId, hostId: next })\n writeRememberedSite(orgId, next)\n }}\n sx={{ maxWidth: 320 }}\n >\n {sites.map((site) => (\n <MenuItem key={site.id} value={site.id}>\n {site.name || site.subdomain || site.id}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {/* Keyed by site, so nothing one site's card was holding survives into another's. */}\n <CampaignConversionsCard\n key={hostId}\n hostId={hostId}\n basePath={basePath}\n campaignId={campaignId}\n />\n </Stack>\n )\n}\nOrgConversionsSection.displayName = 'OrgConversionsSection'\n\nexport default OrgConversionsSection\n"],"names":["CardDisplay","MenuItem","Stack","TextField","Typography","useEffect","useState","CampaignConversionsCard","conversionsDocsHelp","useMarketingOrgMount","conversionsSiteStorageKey","orgId","readRememberedSite","window","sessionStorage","getItem","writeRememberedSite","hostId","setItem","OrgConversionsSection","props","sites","basePath","campaignId","mount","picked","setPicked","hostsReady","hosts","some","site","id","header","help","contentGutterX","contentGutterY","variant","color","spacing","length","select","size","label","value","onChange","event","next","target","sx","maxWidth","map","name","subdomain","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,WAAW,QAAQ,uBAAsB;AAClD,SAASC,QAAQ,EAAEC,KAAK,EAAEC,SAAS,EAAEC,UAAU,QAAQ,gBAAe;AACtE,SAASC,SAAS,EAAEC,QAAQ,QA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ACdC,cAAc;sBAEd,cAAA,KAAC/B;gBAAWgC,SAAQ;gBAAQC,OAAM;0BAC/B,qEACC;;;IAIV;IAEA,qBACE,MAACnC;QAAMoC,SAAS;;YACbjB,MAAMkB,MAAM,GAAG,kBACd,KAACpC;gBACCqC,MAAM;gBACNC,MAAK;gBACLC,OAAM;gBACNC,OAAO1B;gBACP2B,UAAU,CAACC;oBACT,MAAMC,OAAOD,MAAME,MAAM,CAACJ,KAAK;oBAC/BjB,UAAU;wBAAEf;wBAAOM,QAAQ6B;oBAAK;oBAChC9B,oBAAoBL,OAAOmC;gBAC7B;gBACAE,IAAI;oBAAEC,UAAU;gBAAI;0BAEnB5B,MAAM6B,GAAG,CAAC,CAACpB,qBACV,KAAC7B;wBAAuB0C,OAAOb,KAAKC,EAAE;kCACnCD,KAAKqB,IAAI,IAAIrB,KAAKsB,SAAS,IAAItB,KAAKC,EAAE;uBAD1BD,KAAKC,EAAE;iBAKxB;0BAEJ,KAACxB;gBAECU,QAAQA;gBACRK,UAAUA;gBACVC,YAAYA;eAHPN;;;AAOb;AACAE,sBAAsBkC,WAAW,GAAG;AAEpC,eAAelC,sBAAqB"}
@@ -149,7 +149,7 @@ import { useOneShotRead, useOrgSiteReads } from "./use-one-shot-reads.js";
149
149
  header: 'At a glance',
150
150
  subheader: 'Every site in this organization',
151
151
  help: pluginDocsHelp('marketingOverlays', {
152
- anchor: '#across-your-sites'
152
+ anchor: '#org-marketing-overview'
153
153
  }),
154
154
  contentGutterX: true,
155
155
  contentGutterY: true,