@aglyn/plugins-marketing 1.0.0-beta.196 → 1.0.0-beta.198

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-marketing",
3
- "version": "1.0.0-beta.196",
3
+ "version": "1.0.0-beta.198",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,20 +25,20 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.196",
29
- "@aglyn/shared-data-enums": "1.0.0-beta.196",
30
- "@aglyn/shared-data-mdi": "1.0.0-beta.196",
31
- "@aglyn/shared-ui-email-campaigns": "1.0.0-beta.196",
32
- "@aglyn/shared-ui-jsx": "1.0.0-beta.196",
33
- "@aglyn/shared-ui-jsx-forms": "1.0.0-beta.196",
34
- "@aglyn/shared-ui-next": "1.0.0-beta.196",
35
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.196",
36
- "@aglyn/shared-util-email": "1.0.0-beta.196",
37
- "@aglyn/shared-util-http": "1.0.0-beta.196",
38
- "@aglyn/shared-util-timestamp": "1.0.0-beta.196",
39
- "@aglyn/tenant-data-admin": "1.0.0-beta.196",
40
- "@aglyn/tenant-feature-instance": "1.0.0-beta.196",
41
- "@aglyn/tenant-runtime": "1.0.0-beta.196",
28
+ "@aglyn/aglyn": "1.0.0-beta.198",
29
+ "@aglyn/shared-data-enums": "1.0.0-beta.198",
30
+ "@aglyn/shared-data-mdi": "1.0.0-beta.198",
31
+ "@aglyn/shared-ui-email-campaigns": "1.0.0-beta.198",
32
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.198",
33
+ "@aglyn/shared-ui-jsx-forms": "1.0.0-beta.198",
34
+ "@aglyn/shared-ui-next": "1.0.0-beta.198",
35
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.198",
36
+ "@aglyn/shared-util-email": "1.0.0-beta.198",
37
+ "@aglyn/shared-util-http": "1.0.0-beta.198",
38
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.198",
39
+ "@aglyn/tenant-data-admin": "1.0.0-beta.198",
40
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.198",
41
+ "@aglyn/tenant-runtime": "1.0.0-beta.198",
42
42
  "@swc/helpers": "0.5.23"
43
43
  },
44
44
  "peerDependencies": {
@@ -322,7 +322,9 @@ const recipientsDocsHelp = pluginDocsHelp('emailCampaigns', {
322
322
  headers: RECIPIENT_FILTER_HEADERS,
323
323
  clauses: gridFilter.clauses,
324
324
  onChange: gridFilter.setClauses,
325
- options: RECIPIENT_FILTER_OPTIONS
325
+ options: RECIPIENT_FILTER_OPTIONS,
326
+ // The route answers Engagement across the whole log.
327
+ servedField: "engagement"
326
328
  }),
327
329
  failure ? /*#__PURE__*/ _jsx(Alert, {
328
330
  severity: "warning",
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/email-recipients-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListTable } from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport type { ListFilterField } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { Alert, Chip, Stack, Typography } from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { useEffect, useMemo, useState } from 'react'\n\n/** The server's page size. Fixed, so the reader is not offered a choice. */\nconst PAGE_SIZE = 25\n\n/** Which recipients the table asks for. Matches the route's own vocabulary. */\ntype EngagementFilter = 'all' | 'opened' | 'clicked'\n\n/*\n * What the recipients grid's Filters panel offers (AGL-3317): the one filter\n * the route serves, as a hidden select column. The route answers it over the\n * whole delivery log, one cursor page at a time, and serves nothing else —\n * so no other column filters, and there is no quick search, which could only\n * ever narrow the page on screen.\n */\nconst RECIPIENT_FILTER_FIELDS: readonly ListFilterField[] = [\n { column: 'engagement', kind: 'exact', path: 'engagement', operators: ['equals'] },\n]\nconst RECIPIENT_FILTER_HEADERS: Readonly<Record<string, string>> = {\n engagement: 'Engagement',\n}\nconst RECIPIENT_FILTER_OPTIONS = {\n engagement: [\n { value: 'opened', label: 'Opened it' },\n { value: 'clicked', label: 'Clicked something' },\n ],\n}\nconst RECIPIENT_HIDDEN_COLUMNS = { engagement: false }\n\ninterface RecipientRow {\n messageId: string\n to: string\n subject: string | null\n campaignId: string | null\n status: string\n openCount: number\n clickCount: number\n clickedLinks: string[]\n firstSeenAtMs: number\n lastEventAtMs: number\n}\n\nconst recipientsDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#opens--clicks',\n excerpt:\n 'The people an email reached, and which of them opened it or clicked ' +\n 'a link — read from the per-recipient delivery log.',\n})\n\nexport interface EmailRecipientsCardProps {\n hostId: string\n /**\n * Read every message built from this template.\n *\n * Exactly one of `screenId` and `emailId` is passed. The route takes the\n * SCOPE rather than a list of message ids because a caller who could name\n * ids could name another site's, and the narrower input is the one that\n * cannot be got wrong later.\n */\n screenId?: string\n /** Read one message. */\n emailId?: string\n}\n\n/**\n * WHO, not how many.\n *\n * ## Why this is a fetch and not a listen\n *\n * Every other card on this page reads Firestore directly. This one cannot:\n * the per-recipient delivery log lives at `emailDeliveries/{sha256(address)}`\n * — one platform-level collection holding every site's mail and every\n * transactional message besides — and the query that narrows it to this\n * site's campaigns is a collection-group query whose scoping predicate is\n * part of the query. A security rule cannot require a `where` clause, so\n * there is no rule that would admit this read and refuse the same read\n * without the filter. The narrowing happens on the server, behind the same\n * site role the send path requires.\n *\n * ## Why it is its own card\n *\n * A separate card is a separate mount, and this is the only read on either\n * detail page whose cost grows with how much mail there has been. It asks\n * once on mount and once per page turn — never on a poll — so a reader who\n * came for the preview and the totals above pays for one page of this and\n * nothing more.\n *\n * ## The cursor, and why \"Previous\" keeps a stack\n *\n * The route pages forward with an opaque cursor, which is the only shape a\n * Firestore query offers without counting the whole result first. Going back\n * therefore means remembering where each page started, so the cursors are\n * kept in a list indexed by page — `null` for the first — rather than\n * re-walking forward from the beginning.\n */\nexport function EmailRecipientsCard(props: EmailRecipientsCardProps) {\n const { hostId, screenId, emailId } = props\n const { data: user } = useUser()\n\n const gridFilter = useListGridFilter({ selectFields: ['engagement'], single: true })\n const asked = gridFilter.clauses.find((clause) => clause.field === 'engagement')?.value\n const filter: EngagementFilter =\n asked === 'opened' || asked === 'clicked' ? asked : 'all'\n const [page, setPage] = useState(0)\n /** Cursor for each page. Index 0 is always `null` — the first page. */\n const [cursors, setCursors] = useState<(string | null)[]>([null])\n const [rows, setRows] = useState<RecipientRow[]>([])\n const [hasMore, setHasMore] = useState(false)\n const [loading, setLoading] = useState(true)\n const [failure, setFailure] = useState<string | null>(null)\n const [campaignsOmitted, setCampaignsOmitted] = useState(0)\n const [campaignsRead, setCampaignsRead] = useState(0)\n\n const cursor = cursors[page] ?? null\n\n useEffect(() => {\n if (!user) return undefined\n let active = true\n setLoading(true)\n setFailure(null)\n void (async () => {\n try {\n const response = await authorizedFetch(\n user,\n '/api/campaigns/recipients',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n ...(screenId ? { screenId } : {}),\n ...(emailId ? { emailId } : {}),\n filter,\n cursor,\n }),\n },\n )\n const payload = await response.json().catch(() => ({}))\n if (!active) return\n if (!response.ok) {\n setRows([])\n setHasMore(false)\n setFailure(String(payload?.error ?? 'Could not read recipients'))\n return\n }\n /*\n * A read that FAILED is not a campaign nobody opened.\n *\n * The route answers 200 with `lookupFailed` for a delivery-log read\n * that could not run — a missing collection-group index is the likely\n * one — because the rest of the payload is still true. Rendering that\n * as an empty table is how a merchant concludes their campaign\n * reached nobody, which is the one wrong answer this table can give.\n */\n if (payload?.lookupFailed) {\n setRows([])\n setHasMore(false)\n setFailure(\n 'The delivery log could not be read, so this table is empty for ' +\n 'a reason that has nothing to do with your campaign. The ' +\n 'numbers above come from the campaigns themselves and are ' +\n 'unaffected.',\n )\n return\n }\n const nextRows: RecipientRow[] = Array.isArray(payload?.rows)\n ? payload.rows\n : []\n setRows(nextRows)\n setCampaignsOmitted(Number(payload?.campaignsOmitted ?? 0))\n setCampaignsRead(Number(payload?.campaignsRead ?? 0))\n const nextCursor: string | null = payload?.cursor ?? null\n setHasMore(Boolean(nextCursor))\n if (nextCursor) {\n setCursors((existing) => {\n if (existing[page + 1] === nextCursor) return existing\n const next = existing.slice(0, page + 1)\n next[page + 1] = nextCursor\n return next\n })\n }\n } catch (error) {\n console.error(error)\n if (active) {\n setRows([])\n setHasMore(false)\n setFailure('Could not read recipients')\n }\n } finally {\n if (active) setLoading(false)\n }\n })()\n return () => {\n active = false\n }\n }, [user, hostId, screenId, emailId, filter, cursor, page])\n\n // A new filter is a new result set, so the cursors collected under the old\n // one describe positions in a query that no longer exists.\n const [askedFilter, setAskedFilter] = useState<EngagementFilter>(filter)\n if (askedFilter !== filter) {\n setAskedFilter(filter)\n setPage(0)\n setCursors([null])\n }\n\n const columns = useMemo<GridColDef<RecipientRow>[]>(\n () => [\n {\n field: 'to',\n headerName: 'Recipient',\n flex: 1,\n minWidth: 240,\n renderCell: ({ row }) => (\n <Stack spacing={0.5} sx={{ py: 1, minWidth: 0, wordBreak: 'break-all' }}>\n <Typography variant=\"body2\">{row.to}</Typography>\n {/*\n * WHICH links, under the person who followed them. The\n * per-campaign link rollup counts destinations and names nobody;\n * this is the other half of the same question, and it is the half\n * a merchant asks when they want to know who to call.\n */}\n {row.clickedLinks.map((link) => (\n <Typography key={link} variant=\"caption\" color=\"text.secondary\">\n {link}\n </Typography>\n ))}\n </Stack>\n ),\n },\n ...(emailId\n ? []\n : [\n {\n field: 'subject',\n headerName: 'Email',\n flex: 1,\n minWidth: 180,\n valueGetter: (_value: unknown, row: RecipientRow) => row.subject ?? '—',\n } satisfies GridColDef<RecipientRow>,\n ]),\n {\n field: 'status',\n headerName: 'State',\n width: 130,\n renderCell: ({ row }) => <Chip size=\"small\" label={row.status} />,\n },\n {\n field: 'openCount',\n headerName: 'Opens',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 100,\n renderCell: ({ row }) => (\n <Typography variant=\"body2\" sx={{ fontWeight: 'bold' }}>\n {row.openCount.toLocaleString()}\n </Typography>\n ),\n },\n {\n field: 'clickCount',\n headerName: 'Clicks',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 100,\n renderCell: ({ row }) => (\n <Typography variant=\"body2\" sx={{ fontWeight: 'bold' }}>\n {row.clickCount.toLocaleString()}\n </Typography>\n ),\n },\n {\n field: 'lastEventAtMs',\n headerName: 'Last event',\n width: 190,\n renderCell: ({ row }) =>\n row.lastEventAtMs ? new Date(row.lastEventAtMs).toLocaleString() : '—',\n },\n ],\n [emailId],\n )\n const filterColumns = useMemo(\n () =>\n listFilterGridColumns(\n columns as GridColDef[],\n RECIPIENT_FILTER_FIELDS,\n RECIPIENT_FILTER_OPTIONS,\n RECIPIENT_FILTER_HEADERS,\n ),\n [columns],\n )\n\n return (\n <CardDisplay\n header={'Recipients'}\n help={recipientsDocsHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {(emailId\n ? 'One row per address this email was sent to, newest first. '\n : 'One row per message sent from this template, newest first. ') +\n 'Opens are counted by a tracking pixel a mail client may block ' +\n 'or pre-fetch, so an absent open is weaker evidence than a click.'}\n </Typography>\n\n <ListFilterChips\n fields={RECIPIENT_FILTER_FIELDS}\n headers={RECIPIENT_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={RECIPIENT_FILTER_OPTIONS}\n />\n\n {failure ? <Alert severity=\"warning\">{failure}</Alert> : null}\n\n {campaignsOmitted ? (\n <Alert severity=\"info\">\n {'This template has been used by more emails than one read can ' +\n `span. These rows cover its ${campaignsRead} most recent ` +\n `emails; ${campaignsOmitted} older ` +\n `${campaignsOmitted === 1 ? 'email is' : 'emails are'} ` +\n 'not included.'}\n </Alert>\n ) : null}\n\n {rows.length === 0 && !loading && !failure && filter === 'all' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No delivery records have been kept for this yet.'}\n </Typography>\n ) : (\n <ListTable\n aria-label=\"Recipients\"\n rows={rows}\n columns={filterColumns}\n loading={loading}\n getRowId={(row: RecipientRow) => row.messageId}\n rowHeight={TABLE_ROW_HEIGHT}\n // A recipient carries the links they followed beneath the\n // address, so a row is as tall as its list of links.\n getRowHeight={() => 'auto'}\n // One page of a cursor feed, turned by the footer below: the grid\n // neither slices it nor filters the page and calls that the log.\n // Its panel's one filter is the route's (AGL-3317).\n hideFooter\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n initialState={{ columns: { columnVisibilityModel: RECIPIENT_HIDDEN_COLUMNS } }}\n noRowsLabel=\"Nobody in the delivery log matches that yet\"\n />\n )}\n\n {/*\n * A cursor feed knows whether ANOTHER page exists and never how many\n * rows there are in total, so `hasMore` is passed and `count` is not\n * — the control renders \"1–25 of more than 25\" rather than inventing\n * a total nobody paid to count.\n */}\n <ListPagination\n page={page}\n pageSize={PAGE_SIZE}\n rowCount={rows.length}\n hasMore={hasMore}\n disabled={loading}\n onPageChange={setPage}\n />\n\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Up to ten distinct destinations are kept per recipient, so a ' +\n 'reader who clicked more links than that has the rest counted ' +\n 'but not listed.'}\n </Typography>\n </Stack>\n </CardDisplay>\n )\n}\nEmailRecipientsCard.displayName = 'EmailRecipientsCard'\n\nexport default EmailRecipientsCard\n"],"names":["pluginDocsHelp","CardDisplay","ListPagination","ListFilterChips","ListTable","listFilterGridColumns","useListGridFilter","TABLE_ROW_HEIGHT","useUser","authorizedFetch","Alert","Chip","Stack","Typography","useEffect","useMemo","useState","PAGE_SIZE","RECIPIENT_FILTER_FIELDS","column","kind","path","operators","RECIPIENT_FILTER_HEADERS","engagement","RECIPIENT_FILTER_OPTIONS","value","label","RECIPIENT_HIDDEN_COLUMNS","recipientsDocsHelp","anchor","excerpt","EmailRecipientsCard","props","cursors","gridFilter","hostId","screenId","emailId","data","user","selectFields","single","asked","clauses","find","clause","field","filter","page","setPage","setCursors","rows","setRows","hasMore","setHasMore","loading","setLoading","failure","setFailure","campaignsOmitted","setCampaignsOmitted","campaignsRead","setCampaignsRead","cursor","undefined","active","response","method","headers","body","JSON","stringify","payload","json","catch","ok","String","error","lookupFailed","nextRows","Array","isArray","Number","nextCursor","Boolean","existing","next","slice","console","askedFilter","setAskedFilter","columns","headerName","flex","minWidth","renderCell","row","spacing","sx","py","wordBreak","variant","to","clickedLinks","map","link","color","valueGetter","_value","subject","width","size","status","type","align","headerAlign","fontWeight","openCount","toLocaleString","clickCount","lastEventAtMs","Date","filterColumns","header","help","contentGutterX","contentGutterY","fields","onChange","setClauses","options","severity","length","aria-label","getRowId","messageId","rowHeight","getRowHeight","hideFooter","filterMode","filterModel","onFilterModelChange","initialState","columnVisibilityModel","noRowsLabel","pageSize","rowCount","disabled","onPageChange","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,cAAc,QAAQ,eAAc;AAC7C,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,qBAAqB,8DAA6D;AACzF,SAASC,SAAS,QAAQ,uDAAsD;AAEhF,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,KAAK,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AAE9D,SAASC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAEpD,0EAA0E,GAC1E,MAAMC,YAAY;AAKlB;;;;;;CAMC,GACD,MAAMC,0BAAsD;IAC1D;QAAEC,QAAQ;QAAcC,MAAM;QAASC,MAAM;QAAcC,WAAW;YAAC;SAAS;IAAC;CAClF;AACD,MAAMC,2BAA6D;IACjEC,YAAY;AACd;AACA,MAAMC,2BAA2B;IAC/BD,YAAY;QACV;YAAEE,OAAO;YAAUC,OAAO;QAAY;QACtC;YAAED,OAAO;YAAWC,OAAO;QAAoB;KAChD;AACH;AACA,MAAMC,2BAA2B;IAAEJ,YAAY;AAAM;AAerD,MAAMK,qBAAqB7B,eAAe,kBAAkB;IAC1D8B,QAAQ;IACRC,SACE,yEACA;AACJ;AAiBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GACD,OAAO,SAASC,oBAAoBC,KAA+B;QAkBlDC;QAbDC;IAJd,MAAM,EAAEC,MAAM,EAAEC,QAAQ,EAAEC,OAAO,EAAE,GAAGL;IACtC,MAAM,EAAEM,MA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c,IAAM;oBACpB,kEAAkE;oBAClE,iEAAiE;oBACjE,oDAAoD;oBACpDC,UAAU;oBACVC,YAAW;oBACXC,aAAa1G,WAAW0G,WAAW;oBACnCC,qBAAqB3G,WAAW2G,mBAAmB;oBACnDC,cAAc;wBAAEnD,SAAS;4BAAEoD,uBAAuBpH;wBAAyB;oBAAE;oBAC7EqH,aAAY;;8BAUhB,KAAC/I;oBACC+C,MAAMA;oBACNiG,UAAUjI;oBACVkI,UAAU/F,KAAKiF,MAAM;oBACrB/E,SAASA;oBACT8F,UAAU5F;oBACV6F,cAAcnG;;8BAGhB,KAACrC;oBAAWyF,SAAQ;oBAAUK,OAAM;8BACjC,kEACC,kEACA;;;;;AAKZ;AACA3E,oBAAoBsH,WAAW,GAAG;AAElC,eAAetH,oBAAmB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/email-recipients-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListTable } from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport type { ListFilterField } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { Alert, Chip, Stack, Typography } from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { useEffect, useMemo, useState } from 'react'\n\n/** The server's page size. Fixed, so the reader is not offered a choice. */\nconst PAGE_SIZE = 25\n\n/** Which recipients the table asks for. Matches the route's own vocabulary. */\ntype EngagementFilter = 'all' | 'opened' | 'clicked'\n\n/*\n * What the recipients grid's Filters panel offers (AGL-3317): the one filter\n * the route serves, as a hidden select column. The route answers it over the\n * whole delivery log, one cursor page at a time, and serves nothing else —\n * so no other column filters, and there is no quick search, which could only\n * ever narrow the page on screen.\n */\nconst RECIPIENT_FILTER_FIELDS: readonly ListFilterField[] = [\n { column: 'engagement', kind: 'exact', path: 'engagement', operators: ['equals'] },\n]\nconst RECIPIENT_FILTER_HEADERS: Readonly<Record<string, string>> = {\n engagement: 'Engagement',\n}\nconst RECIPIENT_FILTER_OPTIONS = {\n engagement: [\n { value: 'opened', label: 'Opened it' },\n { value: 'clicked', label: 'Clicked something' },\n ],\n}\nconst RECIPIENT_HIDDEN_COLUMNS = { engagement: false }\n\ninterface RecipientRow {\n messageId: string\n to: string\n subject: string | null\n campaignId: string | null\n status: string\n openCount: number\n clickCount: number\n clickedLinks: string[]\n firstSeenAtMs: number\n lastEventAtMs: number\n}\n\nconst recipientsDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#opens--clicks',\n excerpt:\n 'The people an email reached, and which of them opened it or clicked ' +\n 'a link — read from the per-recipient delivery log.',\n})\n\nexport interface EmailRecipientsCardProps {\n hostId: string\n /**\n * Read every message built from this template.\n *\n * Exactly one of `screenId` and `emailId` is passed. The route takes the\n * SCOPE rather than a list of message ids because a caller who could name\n * ids could name another site's, and the narrower input is the one that\n * cannot be got wrong later.\n */\n screenId?: string\n /** Read one message. */\n emailId?: string\n}\n\n/**\n * WHO, not how many.\n *\n * ## Why this is a fetch and not a listen\n *\n * Every other card on this page reads Firestore directly. This one cannot:\n * the per-recipient delivery log lives at `emailDeliveries/{sha256(address)}`\n * — one platform-level collection holding every site's mail and every\n * transactional message besides — and the query that narrows it to this\n * site's campaigns is a collection-group query whose scoping predicate is\n * part of the query. A security rule cannot require a `where` clause, so\n * there is no rule that would admit this read and refuse the same read\n * without the filter. The narrowing happens on the server, behind the same\n * site role the send path requires.\n *\n * ## Why it is its own card\n *\n * A separate card is a separate mount, and this is the only read on either\n * detail page whose cost grows with how much mail there has been. It asks\n * once on mount and once per page turn — never on a poll — so a reader who\n * came for the preview and the totals above pays for one page of this and\n * nothing more.\n *\n * ## The cursor, and why \"Previous\" keeps a stack\n *\n * The route pages forward with an opaque cursor, which is the only shape a\n * Firestore query offers without counting the whole result first. Going back\n * therefore means remembering where each page started, so the cursors are\n * kept in a list indexed by page — `null` for the first — rather than\n * re-walking forward from the beginning.\n */\nexport function EmailRecipientsCard(props: EmailRecipientsCardProps) {\n const { hostId, screenId, emailId } = props\n const { data: user } = useUser()\n\n const gridFilter = useListGridFilter({ selectFields: ['engagement'], single: true })\n const asked = gridFilter.clauses.find((clause) => clause.field === 'engagement')?.value\n const filter: EngagementFilter =\n asked === 'opened' || asked === 'clicked' ? asked : 'all'\n const [page, setPage] = useState(0)\n /** Cursor for each page. Index 0 is always `null` — the first page. */\n const [cursors, setCursors] = useState<(string | null)[]>([null])\n const [rows, setRows] = useState<RecipientRow[]>([])\n const [hasMore, setHasMore] = useState(false)\n const [loading, setLoading] = useState(true)\n const [failure, setFailure] = useState<string | null>(null)\n const [campaignsOmitted, setCampaignsOmitted] = useState(0)\n const [campaignsRead, setCampaignsRead] = useState(0)\n\n const cursor = cursors[page] ?? null\n\n useEffect(() => {\n if (!user) return undefined\n let active = true\n setLoading(true)\n setFailure(null)\n void (async () => {\n try {\n const response = await authorizedFetch(\n user,\n '/api/campaigns/recipients',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n ...(screenId ? { screenId } : {}),\n ...(emailId ? { emailId } : {}),\n filter,\n cursor,\n }),\n },\n )\n const payload = await response.json().catch(() => ({}))\n if (!active) return\n if (!response.ok) {\n setRows([])\n setHasMore(false)\n setFailure(String(payload?.error ?? 'Could not read recipients'))\n return\n }\n /*\n * A read that FAILED is not a campaign nobody opened.\n *\n * The route answers 200 with `lookupFailed` for a delivery-log read\n * that could not run — a missing collection-group index is the likely\n * one — because the rest of the payload is still true. Rendering that\n * as an empty table is how a merchant concludes their campaign\n * reached nobody, which is the one wrong answer this table can give.\n */\n if (payload?.lookupFailed) {\n setRows([])\n setHasMore(false)\n setFailure(\n 'The delivery log could not be read, so this table is empty for ' +\n 'a reason that has nothing to do with your campaign. The ' +\n 'numbers above come from the campaigns themselves and are ' +\n 'unaffected.',\n )\n return\n }\n const nextRows: RecipientRow[] = Array.isArray(payload?.rows)\n ? payload.rows\n : []\n setRows(nextRows)\n setCampaignsOmitted(Number(payload?.campaignsOmitted ?? 0))\n setCampaignsRead(Number(payload?.campaignsRead ?? 0))\n const nextCursor: string | null = payload?.cursor ?? null\n setHasMore(Boolean(nextCursor))\n if (nextCursor) {\n setCursors((existing) => {\n if (existing[page + 1] === nextCursor) return existing\n const next = existing.slice(0, page + 1)\n next[page + 1] = nextCursor\n return next\n })\n }\n } catch (error) {\n console.error(error)\n if (active) {\n setRows([])\n setHasMore(false)\n setFailure('Could not read recipients')\n }\n } finally {\n if (active) setLoading(false)\n }\n })()\n return () => {\n active = false\n }\n }, [user, hostId, screenId, emailId, filter, cursor, page])\n\n // A new filter is a new result set, so the cursors collected under the old\n // one describe positions in a query that no longer exists.\n const [askedFilter, setAskedFilter] = useState<EngagementFilter>(filter)\n if (askedFilter !== filter) {\n setAskedFilter(filter)\n setPage(0)\n setCursors([null])\n }\n\n const columns = useMemo<GridColDef<RecipientRow>[]>(\n () => [\n {\n field: 'to',\n headerName: 'Recipient',\n flex: 1,\n minWidth: 240,\n renderCell: ({ row }) => (\n <Stack spacing={0.5} sx={{ py: 1, minWidth: 0, wordBreak: 'break-all' }}>\n <Typography variant=\"body2\">{row.to}</Typography>\n {/*\n * WHICH links, under the person who followed them. The\n * per-campaign link rollup counts destinations and names nobody;\n * this is the other half of the same question, and it is the half\n * a merchant asks when they want to know who to call.\n */}\n {row.clickedLinks.map((link) => (\n <Typography key={link} variant=\"caption\" color=\"text.secondary\">\n {link}\n </Typography>\n ))}\n </Stack>\n ),\n },\n ...(emailId\n ? []\n : [\n {\n field: 'subject',\n headerName: 'Email',\n flex: 1,\n minWidth: 180,\n valueGetter: (_value: unknown, row: RecipientRow) => row.subject ?? '—',\n } satisfies GridColDef<RecipientRow>,\n ]),\n {\n field: 'status',\n headerName: 'State',\n width: 130,\n renderCell: ({ row }) => <Chip size=\"small\" label={row.status} />,\n },\n {\n field: 'openCount',\n headerName: 'Opens',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 100,\n renderCell: ({ row }) => (\n <Typography variant=\"body2\" sx={{ fontWeight: 'bold' }}>\n {row.openCount.toLocaleString()}\n </Typography>\n ),\n },\n {\n field: 'clickCount',\n headerName: 'Clicks',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 100,\n renderCell: ({ row }) => (\n <Typography variant=\"body2\" sx={{ fontWeight: 'bold' }}>\n {row.clickCount.toLocaleString()}\n </Typography>\n ),\n },\n {\n field: 'lastEventAtMs',\n headerName: 'Last event',\n width: 190,\n renderCell: ({ row }) =>\n row.lastEventAtMs ? new Date(row.lastEventAtMs).toLocaleString() : '—',\n },\n ],\n [emailId],\n )\n const filterColumns = useMemo(\n () =>\n listFilterGridColumns(\n columns as GridColDef[],\n RECIPIENT_FILTER_FIELDS,\n RECIPIENT_FILTER_OPTIONS,\n RECIPIENT_FILTER_HEADERS,\n ),\n [columns],\n )\n\n return (\n <CardDisplay\n header={'Recipients'}\n help={recipientsDocsHelp}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {(emailId\n ? 'One row per address this email was sent to, newest first. '\n : 'One row per message sent from this template, newest first. ') +\n 'Opens are counted by a tracking pixel a mail client may block ' +\n 'or pre-fetch, so an absent open is weaker evidence than a click.'}\n </Typography>\n\n <ListFilterChips\n fields={RECIPIENT_FILTER_FIELDS}\n headers={RECIPIENT_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={RECIPIENT_FILTER_OPTIONS}\n // The route answers Engagement across the whole log.\n servedField=\"engagement\"\n />\n\n {failure ? <Alert severity=\"warning\">{failure}</Alert> : null}\n\n {campaignsOmitted ? (\n <Alert severity=\"info\">\n {'This template has been used by more emails than one read can ' +\n `span. These rows cover its ${campaignsRead} most recent ` +\n `emails; ${campaignsOmitted} older ` +\n `${campaignsOmitted === 1 ? 'email is' : 'emails are'} ` +\n 'not included.'}\n </Alert>\n ) : null}\n\n {rows.length === 0 && !loading && !failure && filter === 'all' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No delivery records have been kept for this yet.'}\n </Typography>\n ) : (\n <ListTable\n aria-label=\"Recipients\"\n rows={rows}\n columns={filterColumns}\n loading={loading}\n getRowId={(row: RecipientRow) => row.messageId}\n rowHeight={TABLE_ROW_HEIGHT}\n // A recipient carries the links they followed beneath the\n // address, so a row is as tall as its list of links.\n getRowHeight={() => 'auto'}\n // One page of a cursor feed, turned by the footer below: the grid\n // neither slices it nor filters the page and calls that the log.\n // Its panel's one filter is the route's (AGL-3317).\n hideFooter\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n initialState={{ columns: { columnVisibilityModel: RECIPIENT_HIDDEN_COLUMNS } }}\n noRowsLabel=\"Nobody in the delivery log matches that yet\"\n />\n )}\n\n {/*\n * A cursor feed knows whether ANOTHER page exists and never how many\n * rows there are in total, so `hasMore` is passed and `count` is not\n * — the control renders \"1–25 of more than 25\" rather than inventing\n * a total nobody paid to count.\n */}\n <ListPagination\n page={page}\n pageSize={PAGE_SIZE}\n rowCount={rows.length}\n hasMore={hasMore}\n disabled={loading}\n onPageChange={setPage}\n />\n\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Up to ten distinct destinations are kept per recipient, so a ' +\n 'reader who clicked more links than that has the rest counted ' +\n 'but not listed.'}\n </Typography>\n </Stack>\n </CardDisplay>\n )\n}\nEmailRecipientsCard.displayName = 'EmailRecipientsCard'\n\nexport default EmailRecipientsCard\n"],"names":["pluginDocsHelp","CardDisplay","ListPagination","ListFilterChips","ListTable","listFilterGridColumns","useListGridFilter","TABLE_ROW_HEIGHT","useUser","authorizedFetch","Alert","Chip","Stack","Typography","useEffect","useMemo","useState","PAGE_SIZE","RECIPIENT_FILTER_FIELDS","column","kind","path","operators","RECIPIENT_FILTER_HEADERS","engagement","RECIPIENT_FILTER_OPTIONS","value","label","RECIPIENT_HIDDEN_COLUMNS","recipientsDocsHelp","anchor","excerpt","EmailRecipientsCard","props","cursors","gridFilter","hostId","screenId","emailId","data","user","selectFields","single","asked","clauses","find","clause","field","filter","page","setPage","setCursors","rows","setRows","hasMore","setHasMore","loading","setLoading","failure","setFailure","campaignsOmitted","setCampaignsOmitted","campaignsRead","setCampaignsRead","cursor","undefined","active","response","method","headers","body","JSON","stringify","payload","json","catch","ok","String","error","lookupFailed","nextRows","Array","isArray","Number","nextCursor","Boolean","existing","next","slice","console","askedFilter","setAskedFilter","columns","headerName","flex","minWidth","renderCell","row","spacing","sx","py","wordBreak","variant","to","clickedLinks","map","link","color","valueGetter","_value","subject","width","size","status","type","align","headerAlign","fontWeight","openCount","toLocaleString","clickCount","lastEventAtMs","Date","filterColumns","header","help","contentGutterX","contentGutterY","fields","onChange","setClauses","options","servedField","severity","length","aria-label","getRowId","messageId","rowHeight","getRowHeight","hideFooter","filterMode","filterModel","onFilterModelChange","initialState","columnVisibilityModel","noRowsLabel","pageSize","rowCount","disabled","on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ACjE,oDAAoD;oBACpDC,UAAU;oBACVC,YAAW;oBACXC,aAAa3G,WAAW2G,WAAW;oBACnCC,qBAAqB5G,WAAW4G,mBAAmB;oBACnDC,cAAc;wBAAEpD,SAAS;4BAAEqD,uBAAuBrH;wBAAyB;oBAAE;oBAC7EsH,aAAY;;8BAUhB,KAAChJ;oBACC+C,MAAMA;oBACNkG,UAAUlI;oBACVmI,UAAUhG,KAAKkF,MAAM;oBACrBhF,SAASA;oBACT+F,UAAU7F;oBACV8F,cAAcpG;;8BAGhB,KAACrC;oBAAWyF,SAAQ;oBAAUK,OAAM;8BACjC,kEACC,kEACA;;;;;AAKZ;AACA3E,oBAAoBuH,WAAW,GAAG;AAElC,eAAevH,oBAAmB"}
@@ -39,7 +39,15 @@ import { useMarketingHubPath } from "./use-marketing-hub-path.js";
39
39
  import { campaignContainersQuery, campaignSendsQuery } from "./campaign-queries.js";
40
40
  import { orgSiteHubPath, orgSiteName, orgSiteOptions, useMarketingOrgId, useMarketingOrgMount } from "./marketing-org-mount.js";
41
41
  /** How many messages one read of this list covers. */ const EMAIL_CEILING = 30;
42
- /** How many campaigns the create drawer offers to file a new email under. */ const CONTAINER_CEILING = 50;
42
+ /**
43
+ * How many campaigns the Campaign filter and the create drawer offer — the
44
+ * same read serves both.
45
+ */ const CONTAINER_CEILING = 50;
46
+ /**
47
+ * The Campaign filter's value for an email filed under no campaign. An empty
48
+ * value reads as "no value" to the filter, so a clause on it would never
49
+ * apply; a sentinel is a value like any campaign id.
50
+ */ const SINGLE_SEND_FILTER_VALUE = '__single__';
43
51
  /**
44
52
  * Why discard is refused, keyed by the state that refuses it.
45
53
  *
@@ -77,7 +85,9 @@ import { orgSiteHubPath, orgSiteName, orgSiteOptions, useMarketingOrgId, useMark
77
85
  */ const EMAIL_FILTER_FIELDS = [
78
86
  EMAIL_SUBJECT_FILTER_FIELD,
79
87
  EMAIL_STATE_FILTER_FIELD,
80
- inMemoryListField('emailCampaignId', 'select'),
88
+ // Matched on a derived key, so the row's own container field stays what
89
+ // was stored for the row menu that reads it.
90
+ inMemoryListField('emailCampaignId', 'select', 'campaignFilterKey'),
81
91
  inMemoryListField('site', 'text', 'siteName')
82
92
  ];
83
93
  const EMAIL_FILTER_HEADERS = {
@@ -375,21 +385,16 @@ const emailsDocsHelp = pluginDocsHelp('emailCampaigns', {
375
385
  ]);
376
386
  const askSite = !hostId && orgSites.length > 1;
377
387
  /*
378
- * The campaigns a new email may be filed under, read only while the drawer
379
- * is OPEN.
380
- *
381
- * A null query opens no listener, so the list costs what it always did until
382
- * somebody asks to write something. Mounting this unconditionally would put
383
- * a second collection read on every reader who came to look at the table,
384
- * which is the cost the whole surface is routed to avoid.
388
+ * The campaigns, read while the list is shown: the Campaign filter offers
389
+ * them by name, and the create drawer offers them to file a new email
390
+ * under. One capped read of the containers serves both.
385
391
  */ const { data: campaignDocs } = useFirestoreCollection(()=>{
386
- const containers = createOpen ? campaignContainersQuery(firestore, orgId, hostId) : null;
392
+ const containers = campaignContainersQuery(firestore, orgId, hostId);
387
393
  return containers ? collectionCeiling(containers, CONTAINER_CEILING) : null;
388
394
  }, [
389
395
  firestore,
390
396
  orgId,
391
- hostId,
392
- createOpen
397
+ hostId
393
398
  ], {
394
399
  idField: '$id'
395
400
  });
@@ -402,7 +407,7 @@ const emailsDocsHelp = pluginDocsHelp('emailCampaigns', {
402
407
  campaignDocs
403
408
  ]);
404
409
  const filterRows = useMemo(()=>emails.map((email)=>_extends({}, email, emailFilterValues(email), {
405
- emailCampaignId: email.emailCampaignId ? String(email.emailCampaignId) : '',
410
+ campaignFilterKey: email.emailCampaignId ? String(email.emailCampaignId) : SINGLE_SEND_FILTER_VALUE,
406
411
  siteName: orgMount && (email == null ? void 0 : email.hostId) ? orgSiteName(orgMount, email.hostId) : ''
407
412
  })), [
408
413
  emails,
@@ -415,7 +420,7 @@ const emailsDocsHelp = pluginDocsHelp('emailCampaigns', {
415
420
  state: EMAIL_STATE_OPTIONS,
416
421
  emailCampaignId: [
417
422
  {
418
- value: '',
423
+ value: SINGLE_SEND_FILTER_VALUE,
419
424
  label: 'Single send'
420
425
  },
421
426
  ...campaignOptions
@@ -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 {\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 {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { inMemoryListField } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListRowsFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-rows-filter'\nimport 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 {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport {\n DUPLICATE_MENU_LABEL,\n useDuplicateResource,\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport { Alert, 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 '@aglyn/shared-ui-email-campaigns/model/campaign-container'\nimport {\n emailListTimeMs,\n emailSendTimeMs,\n} from '@aglyn/shared-ui-email-campaigns/model/email-record'\nimport {\n useCampaignManageApi,\n useCampaignSendApi,\n} from './use-campaign-send-api'\nimport {\n EMAIL_STATE_FILTER_FIELD,\n EMAIL_STATE_OPTIONS,\n EMAIL_SUBJECT_FILTER_FIELD,\n emailFilterValues,\n} from './email-send-filter'\nimport { useMarketingHubPath } from './use-marketing-hub-path'\nimport { campaignContainersQuery, campaignSendsQuery } from './campaign-queries'\nimport {\n orgSiteHubPath,\n orgSiteName,\n orgSiteOptions,\n useMarketingOrgId,\n useMarketingOrgMount,\n} from './marketing-org-mount'\n\n/** How many messages one read of this list covers. */\nconst EMAIL_CEILING = 30\n\n/** How many campaigns the create drawer offers to file a new email under. */\nconst CONTAINER_CEILING = 50\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}\n\n/*\n * What the messages grid's Filters panel offers (AGL-3317). The card reads\n * every message under its ceiling, so the panel and the search answer over\n * all of them. State is what the email is DOING (`campaignSendDisplay`),\n * not the status it stores.\n */\nconst EMAIL_FILTER_FIELDS = [\n EMAIL_SUBJECT_FILTER_FIELD,\n EMAIL_STATE_FILTER_FIELD,\n inMemoryListField('emailCampaignId', 'select'),\n inMemoryListField('site', 'text', 'siteName'),\n]\nconst EMAIL_FILTER_HEADERS: Readonly<Record<string, string>> = {\n subject: 'Subject',\n state: 'State',\n emailCampaignId: 'Campaign',\n site: 'Site',\n}\n/** What the quick search reads on a message row. */\nconst EMAIL_SEARCH_FIELDS = ['subjectText', 'siteName'] as const\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 * ## Ordered in the browser, deliberately\n *\n * No SEND date is on every message: a sent one carries `sentAt` and a\n * scheduled one carries `sendAtMs`, written by two different branches of the\n * send path, and a draft carries neither — so `orderBy` on either would not\n * mis-sort this list, it would DROP half of it. `collectionCeiling` reads a\n * bounded window in document-id order and probes one past the ceiling, so the\n * rows are sorted here and the reader is told when there are more.\n *\n * Every writer stamps a `createdAtMs`, which is the field this list could be\n * ordered on in Firestore. Moving it there is a query change with the same\n * hazard as the two above — `orderBy` drops a document missing the field —\n * so it needs the corpus proven to carry one, not just the writers.\n *\n * The page is therefore a SLICE of a window this card already holds, not a\n * query: paging an id-ordered walk and re-sorting each page by date would run\n * in one order within a page and another across them.\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 const { data: emailDocs } = useFirestoreCollection<any>(\n () => {\n const sends = campaignSendsQuery(firestore, orgId, hostId)\n return sends ? collectionCeiling(sends, EMAIL_CEILING) : null\n },\n [firestore, orgId, hostId],\n { idField: '$id' },\n )\n const { rows: readEmails, truncated } = ceilingedWindow<any>(\n emailDocs,\n EMAIL_CEILING,\n )\n /*\n * Newest first on the time each message SITS at — its send time where it\n * has one, its creation where it does not.\n *\n * A draft has neither `sentAt` nor `sendAtMs`, so sorting on the send time\n * alone gave every draft the key 0 and filed the email a merchant is in the\n * middle of writing at the very bottom of the list, behind whatever paging\n * it has. `emailListTimeMs` is the same ordering with that one gap closed;\n * a SENT message still orders by when it went out, never by when it was\n * drafted.\n */\n const emails = useMemo(\n () =>\n [...readEmails].sort(\n (a: any, b: any) => emailListTimeMs(b) - emailListTimeMs(a),\n ),\n [readEmails],\n )\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 templatesHub = (email: any): string | null =>\n orgMount ? orgSiteHubPath(orgMount, email?.hostId, 'emails') : basePath\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 readEmails.map((email: any) => [\n String(email.$id),\n email?.hostId ? String(email.hostId) : null,\n ]),\n ),\n [readEmails],\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 = templatesHub(email)\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:\n templateScreenId && templates\n ? `${templates}/templates/${templateScreenId}`\n : undefined,\n disabled: !templateScreenId || !templates,\n disabledReason: templateScreenId\n ? 'This site’s console URL has not resolved yet'\n : 'This message was not built from a template',\n },\n {\n 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 a new email may be filed under, read only while the drawer\n * is OPEN.\n *\n * A null query opens no listener, so the list costs what it always did until\n * somebody asks to write something. Mounting this unconditionally would put\n * a second collection read on every reader who came to look at the table,\n * which is the cost the whole surface is routed to avoid.\n */\n const { data: campaignDocs } = useFirestoreCollection<any>(\n () => {\n const containers = createOpen\n ? campaignContainersQuery(firestore, orgId, hostId)\n : null\n return containers ? collectionCeiling(containers, CONTAINER_CEILING) : null\n },\n [firestore, orgId, hostId, createOpen],\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 filterRows = useMemo(\n () =>\n emails.map((email: any) => ({\n ...email,\n ...emailFilterValues(email),\n emailCampaignId: email.emailCampaignId ? String(email.emailCampaignId) : '',\n siteName: orgMount && email?.hostId ? orgSiteName(orgMount, email.hostId) : '',\n })),\n [emails, orgMount],\n )\n const filterFields = useMemo(\n () =>\n orgMount\n ? EMAIL_FILTER_FIELDS\n : EMAIL_FILTER_FIELDS.filter((field) => field.column !== 'site'),\n [orgMount],\n )\n const filterOptions = useMemo(\n () => ({\n state: EMAIL_STATE_OPTIONS,\n emailCampaignId: [\n { value: '', label: 'Single send' },\n ...campaignOptions,\n ],\n }),\n [campaignOptions],\n )\n const listFilter = useListRowsFilter({\n rows: filterRows,\n fields: filterFields,\n options: filterOptions,\n headers: EMAIL_FILTER_HEADERS,\n search: EMAIL_SEARCH_FIELDS,\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 order above; the whole window is in hand, so\n * the grid pages it. The subject is a link AND the row opens the report: a\n * click handler cannot be middle-clicked or opened 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 // Sorted on the time the list is ordered by, so a draft sorts by its\n // creation rather than as the oldest thing on the page.\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 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 {emails.length === 0 ? (\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 {...listFilter.chipsProps} />\n <ListTable\n aria-label=\"Messages\"\n rows={listFilter.rows}\n columns={listFilter.filterColumns(columns)}\n rowHeight={TABLE_ROW_HEIGHT}\n onOpen={(_id, row) => router.push(emailHref(row))}\n // The panel and the search are the grid's; the card answers\n // them over every message it read (AGL-3317).\n {...listFilter.gridProps}\n initialState={{ columns: { columnVisibilityModel: { emailCampaignId: false } } }}\n noRowsLabel=\"No messages match these filters\"\n />\n </>\n )}\n {truncated ? (\n <Alert severity=\"info\">\n {`Showing ${EMAIL_CEILING} messages. ${\n hostId ? 'This site' : 'This organization'\n } has sent or ` +\n 'scheduled more than that, and the rest are not in this list.'}\n </Alert>\n ) : null}\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","mdiBullhornOutline","mdiContentCopy","mdiDeleteOutline","mdiEyeOutline","mdiPaletteOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListFilterChips","ListRowActions","ListTable","listActionsColumn","inMemoryListField","useListRowsFilter","TABLE_ROW_HEIGHT","CreateArtifactDrawer","useSnackbar","ceilingedWindow","collectionCeiling","DUPLICATE_MENU_LABEL","useDuplicateResource","useFirestore","useFirestoreCollection","Alert","Button","Chip","Stack","Typography","useRouter","useCallback","useMemo","useState","campaignPlacedOnHost","campaignSendDisplay","CAMPAIGN_SEND_CONTAINER_FIELD","emailListTimeMs","emailSendTimeMs","useCampaignManageApi","useCampaignSendApi","EMAIL_STATE_FILTER_FIELD","EMAIL_STATE_OPTIONS","EMAIL_SUBJECT_FILTER_FIELD","emailFilterValues","useMarketingHubPath","campaignContainersQuery","campaignSendsQuery","orgSiteHubPath","orgSiteName","orgSiteOptions","useMarketingOrgId","useMarketingOrgMount","EMAIL_CEILING","CONTAINER_CEILING","DISCARD_REFUSAL","sent","scheduled","sending","canceled","STATE_COLOR","stopped","EMAIL_FILTER_FIELDS","EMAIL_FILTER_HEADERS","subject","state","emailCampaignId","site","EMAIL_SEARCH_FIELDS","emailsDocsHelp","anchor","excerpt","EmailsListCard","props","hostId","basePath","firestore","orgMount","orgId","siteMarketingHub","marketingHub","router","data","emailDocs","sends","idField","rows","readEmails","truncated","emails","sort","a","b","messagesPath","emailHref","email","$id","templatesHub","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","templateScreenId","status","templates","siteless","sitelessReason","key","label","icon","path","size","href","disabled","disabledReason","onClick","request","destructive","Boolean","createOpen","setCreateOpen","creating","setCreating","campaignSendApi","orgSites","askSite","length","campaignDocs","containers","campaignOptions","campaign","value","localeCompare","filterRows","siteName","filterFields","filter","field","column","filterOptions","listFilter","fields","options","headers","search","handleCreate","values","sendAs","chosenCampaign","find","trim","push","columns","headerName","flex","minWidth","valueGetter","_value","row","renderCell","event","stopPropagation","width","display","color","at","Date","toLocaleString","stat","type","align","headerAlign","Number","stats","valueFormatter","items","header","help","HeaderProps","contentGutterX","contentGutterY","dialog","spacing","sx","alignItems","chipsProps","aria-label","filterColumns","rowHeight","onOpen","_id","gridProps","initialState","columnVisibilityModel","noRowsLabel","severity","open","onClose","submitLabel","includeDescription","onSubmit","extraFields","component","isRequired","initialValue","helperText","disableDefaultOption"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,cAAc,QAAQ,eAAc;AAC7C,SACEC,kBAAkB,EAClBC,cAAc,EACdC,gBAAgB,EAChBC,aAAa,EACbC,iBAAiB,QACZ,yBAAwB;AAC/B,SACEC,OAAO,EACPC,WAAW,EACXC,OAAO,EACPC,sBAAsB,QACjB,uBAAsB;AAC7B,OAAOC,qBAAqB,8DAA6D;AACzF,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,iBAAiB,QAAQ,8CAA6C;AAC/E,SAASC,iBAAiB,QAAQ,kDAAiD;AAEnF,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,oBAAoB,QAAQ,6BAA4B;AACjE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,oBAAoB,EACpBC,oBAAoB,EACpBC,YAAY,EACZC,sBAAsB,QACjB,iCAAgC;AACvC,SAASC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AAEtE,SAASC,SAAS,QAAQ,kBAAiB;AAC3C,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SACEC,oBAAoB,EACpBC,mBAAmB,EACnBC,6BAA6B,QAExB,4DAA2D;AAClE,SACEC,eAAe,EACfC,eAAe,QACV,sDAAqD;AAC5D,SACEC,oBAAoB,EACpBC,kBAAkB,QACb,6BAAyB;AAChC,SACE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;;;AAIT;AACAlG,eAAe2D,WAAW,GAAG;AAE7B,eAAe3D,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 {\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 {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { inMemoryListField } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListRowsFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-rows-filter'\nimport 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 {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport {\n DUPLICATE_MENU_LABEL,\n useDuplicateResource,\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport { Alert, 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 '@aglyn/shared-ui-email-campaigns/model/campaign-container'\nimport {\n emailListTimeMs,\n emailSendTimeMs,\n} from '@aglyn/shared-ui-email-campaigns/model/email-record'\nimport {\n useCampaignManageApi,\n useCampaignSendApi,\n} from './use-campaign-send-api'\nimport {\n EMAIL_STATE_FILTER_FIELD,\n EMAIL_STATE_OPTIONS,\n EMAIL_SUBJECT_FILTER_FIELD,\n emailFilterValues,\n} from './email-send-filter'\nimport { useMarketingHubPath } from './use-marketing-hub-path'\nimport { campaignContainersQuery, campaignSendsQuery } from './campaign-queries'\nimport {\n orgSiteHubPath,\n orgSiteName,\n orgSiteOptions,\n useMarketingOrgId,\n useMarketingOrgMount,\n} from './marketing-org-mount'\n\n/** How many messages one read of this list covers. */\nconst EMAIL_CEILING = 30\n\n/**\n * How many campaigns the Campaign filter and the create drawer offer — the\n * same read serves both.\n */\nconst CONTAINER_CEILING = 50\n\n/**\n * The Campaign filter's value for an email filed under no campaign. An empty\n * value reads as \"no value\" to the filter, so a clause on it would never\n * apply; a sentinel is a value like any campaign id.\n */\nconst SINGLE_SEND_FILTER_VALUE = '__single__'\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}\n\n/*\n * What the messages grid's Filters panel offers (AGL-3317). The card reads\n * every message under its ceiling, so the panel and the search answer over\n * all of them. State is what the email is DOING (`campaignSendDisplay`),\n * not the status it stores.\n */\nconst EMAIL_FILTER_FIELDS = [\n EMAIL_SUBJECT_FILTER_FIELD,\n EMAIL_STATE_FILTER_FIELD,\n // Matched on a derived key, so the row's own container field stays what\n // was stored for the row menu that reads it.\n inMemoryListField('emailCampaignId', 'select', 'campaignFilterKey'),\n inMemoryListField('site', 'text', 'siteName'),\n]\nconst EMAIL_FILTER_HEADERS: Readonly<Record<string, string>> = {\n subject: 'Subject',\n state: 'State',\n emailCampaignId: 'Campaign',\n site: 'Site',\n}\n/** What the quick search reads on a message row. */\nconst EMAIL_SEARCH_FIELDS = ['subjectText', 'siteName'] as const\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 * ## Ordered in the browser, deliberately\n *\n * No SEND date is on every message: a sent one carries `sentAt` and a\n * scheduled one carries `sendAtMs`, written by two different branches of the\n * send path, and a draft carries neither — so `orderBy` on either would not\n * mis-sort this list, it would DROP half of it. `collectionCeiling` reads a\n * bounded window in document-id order and probes one past the ceiling, so the\n * rows are sorted here and the reader is told when there are more.\n *\n * Every writer stamps a `createdAtMs`, which is the field this list could be\n * ordered on in Firestore. Moving it there is a query change with the same\n * hazard as the two above — `orderBy` drops a document missing the field —\n * so it needs the corpus proven to carry one, not just the writers.\n *\n * The page is therefore a SLICE of a window this card already holds, not a\n * query: paging an id-ordered walk and re-sorting each page by date would run\n * in one order within a page and another across them.\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 const { data: emailDocs } = useFirestoreCollection<any>(\n () => {\n const sends = campaignSendsQuery(firestore, orgId, hostId)\n return sends ? collectionCeiling(sends, EMAIL_CEILING) : null\n },\n [firestore, orgId, hostId],\n { idField: '$id' },\n )\n const { rows: readEmails, truncated } = ceilingedWindow<any>(\n emailDocs,\n EMAIL_CEILING,\n )\n /*\n * Newest first on the time each message SITS at — its send time where it\n * has one, its creation where it does not.\n *\n * A draft has neither `sentAt` nor `sendAtMs`, so sorting on the send time\n * alone gave every draft the key 0 and filed the email a merchant is in the\n * middle of writing at the very bottom of the list, behind whatever paging\n * it has. `emailListTimeMs` is the same ordering with that one gap closed;\n * a SENT message still orders by when it went out, never by when it was\n * drafted.\n */\n const emails = useMemo(\n () =>\n [...readEmails].sort(\n (a: any, b: any) => emailListTimeMs(b) - emailListTimeMs(a),\n ),\n [readEmails],\n )\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 templatesHub = (email: any): string | null =>\n orgMount ? orgSiteHubPath(orgMount, email?.hostId, 'emails') : basePath\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 readEmails.map((email: any) => [\n String(email.$id),\n email?.hostId ? String(email.hostId) : null,\n ]),\n ),\n [readEmails],\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 = templatesHub(email)\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:\n templateScreenId && templates\n ? `${templates}/templates/${templateScreenId}`\n : undefined,\n disabled: !templateScreenId || !templates,\n disabledReason: templateScreenId\n ? 'This site’s console URL has not resolved yet'\n : 'This message was not built from a template',\n },\n {\n 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 filterRows = useMemo(\n () =>\n emails.map((email: any) => ({\n ...email,\n ...emailFilterValues(email),\n campaignFilterKey: email.emailCampaignId\n ? String(email.emailCampaignId)\n : SINGLE_SEND_FILTER_VALUE,\n siteName: orgMount && email?.hostId ? orgSiteName(orgMount, email.hostId) : '',\n })),\n [emails, orgMount],\n )\n const filterFields = useMemo(\n () =>\n orgMount\n ? EMAIL_FILTER_FIELDS\n : EMAIL_FILTER_FIELDS.filter((field) => field.column !== 'site'),\n [orgMount],\n )\n const filterOptions = useMemo(\n () => ({\n state: EMAIL_STATE_OPTIONS,\n emailCampaignId: [\n { value: SINGLE_SEND_FILTER_VALUE, label: 'Single send' },\n ...campaignOptions,\n ],\n }),\n [campaignOptions],\n )\n const listFilter = useListRowsFilter({\n rows: filterRows,\n fields: filterFields,\n options: filterOptions,\n headers: EMAIL_FILTER_HEADERS,\n search: EMAIL_SEARCH_FIELDS,\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 order above; the whole window is in hand, so\n * the grid pages it. The subject is a link AND the row opens the report: a\n * click handler cannot be middle-clicked or opened 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 // Sorted on the time the list is ordered by, so a draft sorts by its\n // creation rather than as the oldest thing on the page.\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 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 {emails.length === 0 ? (\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 {...listFilter.chipsProps} />\n <ListTable\n aria-label=\"Messages\"\n rows={listFilter.rows}\n columns={listFilter.filterColumns(columns)}\n rowHeight={TABLE_ROW_HEIGHT}\n onOpen={(_id, row) => router.push(emailHref(row))}\n // The panel and the search are the grid's; the card answers\n // them over every message it read (AGL-3317).\n {...listFilter.gridProps}\n initialState={{ columns: { columnVisibilityModel: { emailCampaignId: false } } }}\n noRowsLabel=\"No messages match these filters\"\n />\n </>\n )}\n {truncated ? (\n <Alert severity=\"info\">\n {`Showing ${EMAIL_CEILING} messages. ${\n hostId ? 'This site' : 'This organization'\n } has sent or ` +\n 'scheduled more than that, and the rest are not in this list.'}\n </Alert>\n ) : null}\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","mdiBullhornOutline","mdiContentCopy","mdiDeleteOutline","mdiEyeOutline","mdiPaletteOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListFilterChips","ListRowActions","ListTable","listActionsColumn","inMemoryListField","useListRowsFilter","TABLE_ROW_HEIGHT","CreateArtifactDrawer","useSnackbar","ceilingedWindow","collectionCeiling","DUPLICATE_MENU_LABEL","useDuplicateResource","useFirestore","useFirestoreCollection","Alert","Button","Chip","Stack","Typography","useRouter","useCallback","useMemo","useState","campaignPlacedOnHost","campaignSendDisplay","CAMPAIGN_SEND_CONTAINER_FIELD","emailListTimeMs","emailSendTimeMs","useCampaignManageApi","useCampaignSendApi","EMAIL_STATE_FILTER_FIELD","EMAIL_STATE_OPTIONS","EMAIL_SUBJECT_FILTER_FIELD","emailFilterValues","useMarketingHubPath","campaignContainersQuery","campaignSendsQuery","orgSiteHubPath","orgSiteName","orgSiteOptions","useMarketingOrgId","useMarketingOrgMount","EMAIL_CEILING","CONTAINER_CEILING","SINGLE_SEND_FILTER_VALUE","DISCARD_REFUSAL","sent","scheduled","sending","canceled","STATE_COLOR","stopped","EMAIL_FILTER_FIELDS","EMAIL_FILTER_HEADERS","subject","state","emailCampaignId","site","EMAIL_SEARCH_FIELDS","emailsDocsHelp","anchor","excerpt","EmailsListCard","props","hostId","basePath","firestore","orgMount","orgId","siteMarketingHub","marketingHub","router","data","emailDocs","sends","idField","rows","readEmails","truncated","emails","sort","a","b","messagesPath","emailHref","email","$id","templatesHub","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","templateScreenId","status","templates","siteless","sitelessReason","key","label","icon","path","size","href","disabled","disabledReason","onClick","request","destructive","Boolean","createOpen","setCreateOpen","creating","setCreating","campaignSendApi","orgSites","askSite","length","campaignDocs","containers","campaignOptions","campaign","value","localeCompare","filterRows","campaignFilterKey","siteName","filterFields","filter","field","column","filterOptions","listFilter","fields","options","headers","search","handleCreate","values","sendAs","chosenCampaign","find","trim","push","columns","headerName","flex","minWidth","valueGetter","_value","row","renderCell","event","stopPropagation","width","display","color","at","Date","toLocaleString","stat","type","align","headerAlign","Number","stats","valueFormatter","items","header","help","HeaderProps","contentGutterX","contentGutterY","dialog","spacing","sx","alignItems","chipsProps","aria-label","filterColumns","rowHeight","onOpen","_id","gridProps","initialState","columnVisibilityModel","noRowsLabel","severity","open","onClose","submitLabel","includeDescription","onSubmit","extraFields","component","isRequired","initialValue","helperText","disableDefaultOption"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,cAAc,QAAQ,eAAc;AAC7C,SACEC,kBAAkB,EAClBC,cAAc,EACdC,gBAAgB,EAChBC,aAAa,EACbC,iBAAiB,QACZ,yBAAwB;AAC/B,SACEC,OAAO,EACPC,WAAW,EACXC,OAAO,EACPC,sBAAsB,QACjB,uBAAsB;AAC7B,OAAOC,qBAAqB,8DAA6D;AACzF,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,iBAAiB,QAAQ,8CAA6C;AAC/E,SAASC,iBAAiB,QAAQ,kDAAiD;AAEnF,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,oBAAoB,QAAQ,6BAA4B;AACjE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,oBAAoB,EACpBC,oBAAoB,EACpBC,YAAY,EACZC,sBAAsB,QACjB,iCAAgC;AACvC,SAASC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AAEtE,SAASC,SAAS,QAAQ,kBAAiB;AAC3C,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,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