@aglyn/plugins-marketing 1.0.0-beta.231 → 1.0.0-beta.233
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 +16 -16
- package/src/lib/components/announcement-bar-card.component.js +1 -0
- package/src/lib/components/announcement-bar-card.component.js.map +1 -1
- package/src/lib/components/campaign-composer.js +1 -0
- package/src/lib/components/campaign-composer.js.map +1 -1
- package/src/lib/components/campaign-conversions-card.js +58 -15
- package/src/lib/components/campaign-conversions-card.js.map +1 -1
- package/src/lib/components/campaign-detail-card.js +51 -5
- package/src/lib/components/campaign-detail-card.js.map +1 -1
- package/src/lib/components/campaign-edit-drawer.js +2 -0
- package/src/lib/components/campaign-edit-drawer.js.map +1 -1
- package/src/lib/components/campaign-members-section.js +37 -8
- package/src/lib/components/campaign-members-section.js.map +1 -1
- package/src/lib/components/campaign-reach-sections.js +3 -0
- package/src/lib/components/campaign-reach-sections.js.map +1 -1
- package/src/lib/components/campaigns-card.js +64 -10
- package/src/lib/components/campaigns-card.js.map +1 -1
- package/src/lib/components/email-detail.js +3 -1
- package/src/lib/components/email-detail.js.map +1 -1
- package/src/lib/components/email-recipients-card.js +37 -2
- package/src/lib/components/email-recipients-card.js.map +1 -1
- package/src/lib/components/emails-list-card.js +59 -6
- package/src/lib/components/emails-list-card.js.map +1 -1
- package/src/lib/components/host-experiments-card.component.js +33 -6
- package/src/lib/components/host-experiments-card.component.js.map +1 -1
- package/src/lib/components/host-marketing-summary-card.component.js +1 -0
- package/src/lib/components/host-marketing-summary-card.component.js.map +1 -1
- package/src/lib/components/org-experiments-card.js +1 -0
- package/src/lib/components/org-experiments-card.js.map +1 -1
- package/src/lib/components/org-marketing-overview-card.js +11 -0
- package/src/lib/components/org-marketing-overview-card.js.map +1 -1
- package/src/lib/components/org-overlays-card.js +1 -0
- package/src/lib/components/org-overlays-card.js.map +1 -1
- package/src/lib/components/popup-card.component.js +4 -0
- package/src/lib/components/popup-card.component.js.map +1 -1
- package/src/lib/components/staff-org-email-card.component.js +85 -6
- package/src/lib/components/staff-org-email-card.component.js.map +1 -1
- package/src/lib/model/campaign-conversions.d.ts +2 -0
- package/src/lib/model/campaign-conversions.js +32 -0
- package/src/lib/model/campaign-conversions.js.map +1 -1
- package/src/lib/model/campaign-list-query.d.ts +6 -2
- package/src/lib/model/campaign-list-query.js +64 -9
- package/src/lib/model/campaign-list-query.js.map +1 -1
- package/src/lib/model/campaign-members-query.d.ts +2 -1
- package/src/lib/model/campaign-members-query.js +23 -1
- package/src/lib/model/campaign-members-query.js.map +1 -1
- package/src/lib/model/experiment-list-query.js +30 -2
- package/src/lib/model/experiment-list-query.js.map +1 -1
- package/src/lib/model/native-vocabulary.d.ts +26 -0
- package/src/lib/model/native-vocabulary.js +31 -0
- package/src/lib/model/native-vocabulary.js.map +1 -0
- package/src/lib/server/campaign-manage.d.ts +1 -1
- package/src/lib/server/campaign-manage.js +1 -0
- package/src/lib/server/campaign-manage.js.map +1 -1
|
@@ -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 // 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). Nor does it\n // sort: a header sort would order that one page, not the log.\n hideFooter\n disableColumnSorting\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","disableColumnSorting","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,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AAW;oBACXnF,MAAMA;oBACNwC,SAAS+B;oBACTnE,SAASA;oBACTgF,UAAU,CAACvC,MAAsBA,IAAIwC,SAAS;oBAC9CC,WAAWnI;oBACX,0DAA0D;oBAC1D,qDAAqD;oBACrDoI,cAAc,IAAM;oBACpB,kEAAkE;oBAClE,iEAAiE;oBACjE,gEAAgE;oBAChE,8DAA8D;oBAC9DC,UAAU;oBACVC,oBAAoB;oBACpBC,YAAW;oBACXC,aAAa5G,WAAW4G,WAAW;oBACnCC,qBAAqB7G,WAAW6G,mBAAmB;oBACnDC,cAAc;wBAAErD,SAAS;4BAAEsD,uBAAuBtH;wBAAyB;oBAAE;oBAC7EuH,aAAY;;8BAUhB,KAACjJ;oBACC+C,MAAMA;oBACNmG,UAAUnI;oBACVoI,UAAUjG,KAAKkF,MAAM;oBACrBhF,SAASA;oBACTgG,UAAU9F;oBACV+F,cAAcrG;;8BAGhB,KAACrC;oBAAWyF,SAAQ;oBAAUK,OAAM;8BACjC,kEACC,kEACA;;;;;AAKZ;AACA3E,oBAAoBwH,WAAW,GAAG;AAElC,eAAexH,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 { useListColumnSort } from '@aglyn/shared-ui-jsx/hooks/use-list-column-sort'\nimport ListQueryNotices from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\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\n/*\n * EVERY HEADER SORTS, OVER THE PAGE (AGL-3680). The rows are an aggregate\n * the recipients route builds from the per-recipient delivery log across\n * the template's emails, paged by its cursor newest first — no query here\n * can order them by a column — so each header sorts the page on screen and\n * says so.\n */\nconst RECIPIENT_PAGE_SORTS = {\n to: (row: RecipientRow) => row.to,\n subject: (row: RecipientRow) => row.subject,\n status: (row: RecipientRow) => row.status,\n openCount: (row: RecipientRow) => row.openCount,\n clickCount: (row: RecipientRow) => row.clickCount,\n lastEventAtMs: (row: RecipientRow) => row.lastEventAtMs || null,\n}\nconst RECIPIENT_PAGE_SORT_HEADERS = {\n to: 'Recipient',\n subject: 'Email',\n status: 'State',\n openCount: 'Opens',\n clickCount: 'Clicks',\n lastEventAtMs: 'Last event',\n}\nconst NO_QUERY_SORTS = [] as const\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 columnSort = useListColumnSort<RecipientRow>({\n sorts: NO_QUERY_SORTS,\n rows,\n pageSorts: RECIPIENT_PAGE_SORTS,\n headers: RECIPIENT_PAGE_SORT_HEADERS,\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 <ListQueryNotices refused={[]} notices={columnSort.notices} />\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={columnSort.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). Nor does it\n // sort: a header sort would order that one page, not the log.\n hideFooter\n columnSort={columnSort}\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","useListColumnSort","ListQueryNotices","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","RECIPIENT_PAGE_SORTS","to","row","subject","status","openCount","clickCount","lastEventAtMs","RECIPIENT_PAGE_SORT_HEADERS","NO_QUERY_SORTS","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","spacing","sx","py","wordBreak","variant","clickedLinks","map","link","color","valueGetter","_value","width","size","type","align","headerAlign","fontWeight","toLocaleString","Date","columnSort","sorts","pageSorts","filterColumns","header","help","contentGutterX","contentGutterY","fields","onChange","setClauses","options","servedField","severity","refused","notices","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,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,OAAO;;gBAEzDvE,iCACC,KAAC5D;oBAAMiI,UAAS;8BACb,kEACC,CAAC,2BAA2B,EAAEnE,cAAc,aAAa,CAAC,GAC1D,CAAC,QAAQ,EAAEF,iBAAiB,OAAO,CAAC,GACpC,GAAGA,qBAAqB,IAAI,aAAa,aAAa,CAAC,CAAC,GACxD;qBAEF;gBAEHR,KAAKgF,MAAM,KAAK,KAAK,CAAC5E,WAAW,CAACE,WAAWV,WAAW,sBACvD,KAAC7C;oBAAWkG,SAAQ;oBAAQI,OAAM;8BAC/B;mCAGH,KAACjH;oBACC6I,cAAW;oBACXjF,MAAMgE,WAAWhE,IAAI;oBACrBwC,SAAS2B;oBACT/D,SAASA;oBACT8E,UAAU,CAACjH,MAAsBA,IAAIkH,SAAS;oBAC9CC,WAAW3I;oBACX,0DAA0D;oBAC1D,qDAAqD;oBACrD4I,cAAc,IAAM;oBACpB,kEAAkE;oBAClE,iEAAiE;oBACjE,gEAAgE;oBAChE,8DAA8D;oBAC9DC,UAAU;oBACVtB,YAAYA;oBACZuB,YAAW;oBACXC,aAAazG,WAAWyG,WAAW;oBACnCC,qBAAqB1G,WAAW0G,mBAAmB;oBACnDC,cAAc;wBAAElD,SAAS;4BAAEmD,uBAAuB7H;wBAAyB;oBAAE;oBAC7E8H,aAAY;;8BAUhB,KAAC1J;oBACC2D,MAAMA;oBACNgG,UAAU1I;oBACV2I,UAAU9F,KAAKgF,MAAM;oBACrB9E,SAASA;oBACT6F,UAAU3F;oBACV4F,cAAclG;;8BAGhB,KAAC/C;oBAAWkG,SAAQ;oBAAUI,OAAM;8BACjC,kEACC,kEACA;;;;;AAKZ;AACAzE,oBAAoBqH,WAAW,GAAG;AAElC,eAAerH,oBAAmB"}
|
|
@@ -27,6 +27,7 @@ import { ListRowActions, ListTable, listActionsColumn } from "@aglyn/shared-ui-j
|
|
|
27
27
|
import { hiddenFilterVisibility } from "@aglyn/shared-ui-jsx/const/list-filter";
|
|
28
28
|
import { listFilterGridColumns } from "@aglyn/shared-ui-jsx/const/list-grid-filter";
|
|
29
29
|
import { useListGridFilter } from "@aglyn/shared-ui-jsx/hooks/use-list-grid-filter";
|
|
30
|
+
import { useListColumnSort } from "@aglyn/shared-ui-jsx/hooks/use-list-column-sort";
|
|
30
31
|
import { TABLE_ROW_HEIGHT } from "@aglyn/shared-ui-jsx/const/table-pagination";
|
|
31
32
|
import { CreateArtifactDrawer } from "@aglyn/shared-ui-jsx-forms";
|
|
32
33
|
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
@@ -48,6 +49,14 @@ import { orgSiteName, orgSiteOptions, useMarketingOrgId, useMarketingOrgMount }
|
|
|
48
49
|
* How many campaigns the Campaign filter and the create drawer offer — the
|
|
49
50
|
* same read serves both. A picker's options, not a list.
|
|
50
51
|
*/ const CONTAINER_CEILING = 50;
|
|
52
|
+
/** The headers a page sort names in its notice. */ const EMAIL_PAGE_SORT_HEADERS = {
|
|
53
|
+
site: 'Site',
|
|
54
|
+
state: 'State',
|
|
55
|
+
when: 'When',
|
|
56
|
+
recipients: 'Addressed',
|
|
57
|
+
opens: 'Opens',
|
|
58
|
+
clicks: 'Clicks'
|
|
59
|
+
};
|
|
51
60
|
/**
|
|
52
61
|
* Why discard is refused, keyed by the state that refuses it.
|
|
53
62
|
*
|
|
@@ -145,13 +154,19 @@ const emailsDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
145
154
|
'site'
|
|
146
155
|
]
|
|
147
156
|
});
|
|
157
|
+
/*
|
|
158
|
+
* EVERY HEADER SORTS (AGL-3680): Subject orders the query
|
|
159
|
+
* (`declaration.sorts`); Site, State, When and the figures are derived or
|
|
160
|
+
* may be absent, and sort the page.
|
|
161
|
+
*/ const [askedSort, setAskedSort] = useState(null);
|
|
148
162
|
const emailPage = useListQuery({
|
|
149
163
|
collection: campaignSendsCollection(firestore, orgId),
|
|
150
164
|
declaration,
|
|
151
165
|
request: {
|
|
152
166
|
clauses: emailCampaignQueryClauses(gridFilter.clauses),
|
|
153
167
|
search: gridFilter.searchWords,
|
|
154
|
-
base: campaignSendsScope(hostId)
|
|
168
|
+
base: campaignSendsScope(hostId),
|
|
169
|
+
sort: askedSort
|
|
155
170
|
},
|
|
156
171
|
deps: [
|
|
157
172
|
firestore,
|
|
@@ -160,6 +175,40 @@ const emailsDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
160
175
|
],
|
|
161
176
|
idField: '$id'
|
|
162
177
|
});
|
|
178
|
+
const emailPageSorts = useMemo(()=>_extends({}, orgMount ? {
|
|
179
|
+
site: (row)=>(row == null ? void 0 : row.hostId) ? orgSiteName(orgMount, row.hostId) : null
|
|
180
|
+
} : {}, {
|
|
181
|
+
state: (row)=>campaignSendDisplay(row).label,
|
|
182
|
+
when: (row)=>emailListTimeMs(row),
|
|
183
|
+
// Counters stay absent until something is counted (see
|
|
184
|
+
// `campaign-list-query.ts`), so no query can order by them.
|
|
185
|
+
recipients: (row)=>{
|
|
186
|
+
var _ref;
|
|
187
|
+
var _row_stats;
|
|
188
|
+
return (_ref = (_row_stats = row.stats) == null ? void 0 : _row_stats.recipients) != null ? _ref : null;
|
|
189
|
+
},
|
|
190
|
+
opens: (row)=>{
|
|
191
|
+
var _ref;
|
|
192
|
+
var _row_stats;
|
|
193
|
+
return (_ref = (_row_stats = row.stats) == null ? void 0 : _row_stats.opens) != null ? _ref : null;
|
|
194
|
+
},
|
|
195
|
+
clicks: (row)=>{
|
|
196
|
+
var _ref;
|
|
197
|
+
var _row_stats;
|
|
198
|
+
return (_ref = (_row_stats = row.stats) == null ? void 0 : _row_stats.clicks) != null ? _ref : null;
|
|
199
|
+
}
|
|
200
|
+
}), [
|
|
201
|
+
orgMount
|
|
202
|
+
]);
|
|
203
|
+
const emailSort = useListColumnSort({
|
|
204
|
+
sorts: declaration.sorts,
|
|
205
|
+
sort: askedSort,
|
|
206
|
+
onSortChange: setAskedSort,
|
|
207
|
+
orderBy: emailPage.plan.orderBy,
|
|
208
|
+
rows: emailPage.rows,
|
|
209
|
+
pageSorts: emailPageSorts,
|
|
210
|
+
headers: EMAIL_PAGE_SORT_HEADERS
|
|
211
|
+
});
|
|
163
212
|
const emails = emailPage.rows;
|
|
164
213
|
const filtering = gridFilter.clauses.length > 0 || gridFilter.searchWords.some((word)=>word.trim());
|
|
165
214
|
/*
|
|
@@ -644,11 +693,14 @@ const emailsDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
644
693
|
headers: EMAIL_FILTER_HEADERS,
|
|
645
694
|
options: filterOptions
|
|
646
695
|
}),
|
|
647
|
-
notices:
|
|
696
|
+
notices: [
|
|
697
|
+
...emailPage.plan.notices,
|
|
698
|
+
...emailSort.notices
|
|
699
|
+
]
|
|
648
700
|
}),
|
|
649
701
|
/*#__PURE__*/ _jsx(ListTable, {
|
|
650
702
|
"aria-label": "Messages",
|
|
651
|
-
rows:
|
|
703
|
+
rows: emailSort.rows,
|
|
652
704
|
columns: gridColumns,
|
|
653
705
|
rowHeight: TABLE_ROW_HEIGHT,
|
|
654
706
|
onOpen: (_id, row)=>router.push(emailHref(row)),
|
|
@@ -656,13 +708,14 @@ const emailsDocsHelp = pluginDocsHelp('emailCampaigns', {
|
|
|
656
708
|
/*
|
|
657
709
|
* The panel and the search are the grid's; every clause and
|
|
658
710
|
* the search word are on the list's query (AGL-3321), and the
|
|
659
|
-
* grid neither filters nor sorts the page it is handed:
|
|
660
|
-
*
|
|
711
|
+
* grid neither filters nor sorts the page it is handed:
|
|
712
|
+
* Subject's header orders the query, the rest the page
|
|
713
|
+
* (AGL-3680), newest first until one is clicked.
|
|
661
714
|
*/ filterMode: "server",
|
|
662
715
|
filterModel: gridFilter.filterModel,
|
|
663
716
|
onFilterModelChange: gridFilter.onFilterModelChange,
|
|
664
717
|
quickFilter: true,
|
|
665
|
-
|
|
718
|
+
columnSort: emailSort,
|
|
666
719
|
hideFooter: true,
|
|
667
720
|
initialState: {
|
|
668
721
|
columns: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/emails-list-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { pluginRecordHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport {\n mdiBullhornOutline,\n mdiContentCopy,\n mdiDeleteOutline,\n mdiEyeOutline,\n mdiPaletteOutline,\n} from '@aglyn/shared-data-mdi'\nimport {\n AppLink,\n CardDisplay,\n MdiIcon,\n useConfirmationContext,\n} from '@aglyn/shared-ui-jsx'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { hiddenFilterVisibility } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { CreateArtifactDrawer } from '@aglyn/shared-ui-jsx-forms'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { collectionCeiling } from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { useListQuery } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport {\n DUPLICATE_MENU_LABEL,\n useDuplicateResource,\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport { Button, Chip, Stack, Typography } from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useMemo, useState } from 'react'\nimport {\n campaignPlacedOnHost,\n campaignSendDisplay,\n CAMPAIGN_SEND_CONTAINER_FIELD,\n type CampaignSendDisplayState,\n} from '../model/campaign-container'\nimport {\n emailListTimeMs,\n emailSendTimeMs,\n} from '../model/email-record'\nimport {\n useCampaignManageApi,\n useCampaignSendApi,\n} from './use-campaign-send-api'\nimport {\n CAMPAIGN_SEND_STATUS_OPTIONS,\n SINGLE_SEND_FILTER_VALUE,\n campaignEmailsListQuery,\n campaignSendsScope,\n emailCampaignQueryClauses,\n} from '../model/campaign-list-query'\nimport { useMarketingHubPath } from './use-marketing-hub-path'\nimport { siteRecordRouteContext, useRecordRouteContext } from './record-route-context'\nimport {\n campaignContainersQuery,\n campaignSendsCollection,\n} from './campaign-queries'\nimport {\n orgSiteName,\n orgSiteOptions,\n useMarketingOrgId,\n useMarketingOrgMount,\n} from './marketing-org-mount'\n\n/**\n * How many campaigns the Campaign filter and the create drawer offer — the\n * same read serves both. A picker's options, not a list.\n */\nconst CONTAINER_CEILING = 50\n\n/**\n * Why discard is refused, keyed by the state that refuses it.\n *\n * The KEYS are persisted status values written by the send path. Each line\n * says what to do instead, because \"you cannot\" on its own leaves a merchant\n * with an email they wanted rid of and no next step — and for a scheduled one\n * the next step is a different act with a different consequence, so naming it\n * is the difference between withdrawing mail and losing the record of it.\n *\n * A state absent from here falls through to the generic refusal rather than\n * being flattened into one of these: a state this list cannot name is worth\n * seeing.\n */\nconst DISCARD_REFUSAL: Record<string, string> = {\n sent: 'This email has been sent. Its report and its unsubscribe links have to go on resolving.',\n scheduled: 'Cancel the send first — cancelling takes it off the clock and keeps the email.',\n sending: 'This email is being sent right now.',\n canceled: 'A canceled email is kept as the record that it was withdrawn.',\n}\n\n/**\n * The chip color for one display state.\n *\n * `sending` is the one worth a color: an email part way through an audience\n * larger than one batch is doing something right now, and a merchant scanning\n * the list for what needs attention should find it without reading. The rest\n * are neutral, because a finished send and a draft are not events.\n */\nconst STATE_COLOR: Partial<\n Record<CampaignSendDisplayState, 'info' | 'warning'>\n> = {\n sending: 'info',\n stopped: 'warning',\n // Waiting on staff, not on the merchant (AGL-3356): worth finding on a scan.\n held: 'warning',\n}\n\n/*\n * What the messages grid's Filters panel offers, each clause and the search\n * on the list's Firestore query (AGL-3321, `campaignEmailsListQuery`). The\n * State column is what the email is DOING (`campaignSendDisplay`), which no\n * query can ask, so the panel offers the Status it STORES instead.\n */\nconst EMAIL_FILTER_HEADERS: Readonly<Record<string, string>> = {\n subject: 'Subject',\n status: 'Status',\n emailCampaignId: 'Campaign',\n site: 'Site',\n createdAtMs: 'Created',\n}\n\nconst emailsDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#opens--clicks',\n excerpt:\n 'Every message this site has sent or has scheduled, each with its own ' +\n 'report: what was delivered, who opened it, and which links they followed.',\n})\n\nexport interface EmailsListCardProps {\n /** The site, or `null` on the organization's Emails page. */\n hostId: string | null\n /**\n * The Emails page's own URL, under the site or the organization, so a row\n * can link to the message's own page beneath it.\n */\n basePath: string\n}\n\n/**\n * EVERY MESSAGE, AS AGAINST EVERY CAMPAIGN.\n *\n * A campaign groups messages; this is the messages. The two are different\n * questions — \"how did the spring promotion do\" and \"what went out on the\n * 14th, and to whom\" — and they were previously the same list because a\n * campaign document WAS a single send.\n *\n * ## Asked of Firestore, a page at a time\n *\n * No SEND date is on every message — a sent one carries `sentAt`, a\n * scheduled one `sendAtMs`, a draft neither — so the list is ordered on\n * `createdAtMs`, the one date every writer stamps when it mints a record\n * (and `backfill-campaign-list-fields.mjs` stamped on the ones before).\n * Newest first, paged by the query itself.\n *\n * The Filters panel and the search box are the grid's; every clause and the\n * search word go onto that ONE query (AGL-3321, `campaignEmailsListQuery`),\n * so each page is a page of matches — an email that matches on page four is\n * found — and a combination one query cannot hold is refused by name above\n * the table, never answered over the rows that happen to be loaded.\n *\n * ## Under a site, and over the organization\n *\n * Sends are the org's. Under a site this lists the ones sent as that site;\n * on the organization's Emails page it lists every site's, with a Site column,\n * and every action on a row names the site that row is sent as — the only\n * site that can duplicate it, discard it or open its template. Creating one\n * there first asks which site it is sent as.\n */\nexport function EmailsListCard(props: EmailsListCardProps) {\n const { hostId, basePath } = props\n const firestore = useFirestore()\n const orgMount = useMarketingOrgMount()\n const { orgId } = useMarketingOrgId(hostId)\n // The sibling hub: a campaign's page belongs to the Marketing console —\n // over the org, the organization's own Marketing page the mount names.\n const siteMarketingHub = useMarketingHubPath()\n const marketingHub = orgMount ? orgMount.basePath : siteMarketingHub\n const router = useRouter()\n\n /*\n * The Filters panel and the search, bound to the grid. Held here rather\n * than in a saved view: this list keeps no views.\n */\n const declaration = campaignEmailsListQuery(!hostId)\n const gridFilter = useListGridFilter({\n selectFields: ['status', 'emailCampaignId', 'site'],\n })\n const emailPage = useListQuery<any>({\n collection: campaignSendsCollection(firestore, orgId),\n declaration,\n request: {\n clauses: emailCampaignQueryClauses(gridFilter.clauses),\n search: gridFilter.searchWords,\n base: campaignSendsScope(hostId),\n },\n deps: [firestore, orgId, hostId],\n idField: '$id',\n })\n const emails = emailPage.rows\n const filtering =\n gridFilter.clauses.length > 0 ||\n gridFilter.searchWords.some((word) => word.trim())\n\n /*\n * A message's own pages, beneath the Emails page this list is on — the\n * site's or the organization's. A template is a site's design, so over the\n * org it opens on the site the row is sent as.\n */\n const messagesPath = `${basePath}/messages`\n const emailHref = (email: any) => `${messagesPath}/${email.$id}`\n const routeContext = useRecordRouteContext()\n const templateHref = (email: any, templateScreenId: string): string | null => {\n const siteContext = siteRecordRouteContext(routeContext, orgMount, email?.hostId)\n return siteContext ? pluginRecordHref('emailTemplate', siteContext, templateScreenId) : null\n }\n /** The site a row is sent as, which every action on it must name. */\n const rowHostId = useCallback(\n (email: any): string | null =>\n hostId ?? (email?.hostId ? String(email.hostId) : null),\n [hostId],\n )\n const hostOfEmail = useMemo(\n () =>\n new Map<string, string | null>(\n emails.map((email: any) => [\n String(email.$id),\n email?.hostId ? String(email.hostId) : null,\n ]),\n ),\n [emails],\n )\n\n const { confirm } = useConfirmationContext()\n const { enqueueSnackbar } = useSnackbar()\n // Duplicate (AGL-2936): a new draft with the message and its design, and\n // nobody to send to until the person chooses — through the manage door,\n // which is the plugin's own.\n const manageForCopy = useCampaignManageApi(hostId)\n const duplicate = useDuplicateResource({\n hostId: hostId ?? '',\n perform: async ({ sourceId, name, attemptKey }) => {\n const { response, payload } = await manageForCopy({\n action: 'duplicate',\n campaignId: sourceId,\n name,\n attemptKey,\n // The copy is made as the site the source is sent as.\n ...(hostId ? {} : { hostId: hostOfEmail.get(sourceId) ?? undefined }),\n })\n if (!response.ok) throw new Error(payload?.error ?? 'Duplicate failed')\n return {\n id: String(payload.emailId),\n versionId: null,\n name: String(payload.name ?? name),\n }\n },\n onDuplicated: (_kind, copy) =>\n enqueueSnackbar(`Duplicated as “${copy.name}” — a draft with no audience yet`, {\n variant: 'success',\n }),\n })\n const manageApi = useCampaignManageApi(hostId)\n /** The email a discard is in flight for, so its row menu can say so. */\n const [discardingId, setDiscardingId] = useState('')\n\n /*==========================================\n * THROWING AWAY A DRAFT.\n *\n * The one removal this surface has, and it is deliberately the narrowest\n * one: an email that was never sent, whose record nobody outside the\n * console has ever seen. Everything else on this list is evidence — a sent\n * message's report is what a merchant answers a complaint with, and its id\n * is inside the HMAC of every unsubscribe footer it delivered — and a\n * scheduled one is withdrawn with Cancel, which keeps the record and takes\n * it off the clock.\n *\n * The menu already refuses anything but a draft, and so does the route.\n * That is not belt and braces: the state on screen is a snapshot that can\n * be seconds old, and the record can be claimed by `sendNow` in between.\n * The route's refusal is the one that decides, inside the transaction that\n * does the delete.\n *=========================================*/\n const handleDiscard = useCallback(\n async (email: any) => {\n if (discardingId) return\n const id = String(email?.$id ?? '')\n const name = String(email?.subject || email?.displayName || 'this draft')\n const agreed = await confirm({\n title: 'Discard this draft?',\n description:\n `${name} has not been sent to anybody, and discarding it removes ` +\n 'it for good — the subject, the message and everything else ' +\n 'written on it. There is no undo.',\n confirmationText: 'Discard',\n })\n .then(() => true)\n .catch(() => false)\n if (!agreed) return\n setDiscardingId(id)\n try {\n const { response, payload } = await manageApi({\n action: 'discardEmail',\n campaignId: id,\n ...(hostId ? {} : { hostId: rowHostId(email) ?? undefined }),\n })\n if (!response.ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'This draft could not be discarded',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n enqueueSnackbar('Draft discarded', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('This draft could not be discarded', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setDiscardingId('')\n }\n },\n [confirm, discardingId, enqueueSnackbar, hostId, manageApi, rowHostId],\n )\n\n /**\n * What a message can be opened INTO, from the list.\n *\n * All three are places the message's own report already links to, moved one\n * screen earlier: the report itself, the campaign it belongs to, and the\n * template it was rendered from. A message need have neither of the last\n * two — one sent before campaigns grouped anything names no container, and\n * one composed inline was built from no template — so those entries are\n * shown DISABLED with the reason rather than hidden. A control that\n * disappears and a control that does not apply look identical, and only one\n * of them tells the reader which case they are in.\n *\n * DISCARD is the fourth entry and is offered on the same terms: a draft can\n * be thrown away, and nothing else can. It stays visible on a sent or\n * scheduled message carrying the reason it is refused, because that is the\n * honest answer to “how do I get rid of this” — and the route refuses it\n * too, so the menu is describing a rule rather than being one.\n */\n const rowActions = (email: any): RowActionsMenuItem[] => {\n const containerId = String(email?.[CAMPAIGN_SEND_CONTAINER_FIELD] ?? '')\n const templateScreenId = String(email?.templateScreenId ?? '')\n const state = String(email?.status ?? '')\n const templates = templateScreenId ? templateHref(email, templateScreenId) : null\n /** On the org hub, a send that names no site has nothing to act as. */\n const siteless = !rowHostId(email)\n const sitelessReason =\n 'This email does not record which site it was sent as. Manage it from ' +\n 'that site’s own Emails page.'\n return [\n {\n key: 'details',\n label: 'Open report',\n icon: <MdiIcon path={mdiEyeOutline.path} size={0.8} />,\n href: emailHref(email),\n },\n {\n key: 'campaign',\n label: 'Open its campaign',\n icon: <MdiIcon path={mdiBullhornOutline.path} size={0.8} />,\n // The campaign's page belongs to the Marketing console, so this one\n // href is built from the sibling hub rather than this surface's own.\n href:\n containerId && marketingHub\n ? `${marketingHub}/campaigns/${containerId}`\n : undefined,\n disabled: !containerId || !marketingHub,\n disabledReason: containerId\n ? 'This site’s console URL has not resolved yet'\n : 'Sent before campaigns grouped their emails, so it belongs to none',\n },\n {\n key: 'template',\n label: 'Open its template',\n icon: <MdiIcon path={mdiPaletteOutline.path} size={0.8} />,\n href: templates ?? undefined,\n disabled: !templates,\n disabledReason: templateScreenId\n ? 'This site’s console URL has not resolved yet'\n : 'This message was not built from a template',\n },\n {\n key: 'duplicate',\n label: DUPLICATE_MENU_LABEL,\n icon: <MdiIcon path={mdiContentCopy.path} size={0.8} />,\n disabled: siteless,\n disabledReason: sitelessReason,\n onClick: () =>\n duplicate.request('campaign', {\n id: String(email.$id),\n name: String(email?.displayName ?? email?.subject ?? ''),\n }),\n },\n {\n key: 'discard',\n label: 'Discard draft',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: siteless || state !== 'draft' || Boolean(discardingId),\n disabledReason: siteless\n ? sitelessReason\n : (DISCARD_REFUSAL[state] ?? 'Only a draft can be discarded'),\n onClick: () => void handleDiscard(email),\n },\n ]\n }\n\n const [createOpen, setCreateOpen] = useState(false)\n const [creating, setCreating] = useState(false)\n const campaignSendApi = useCampaignSendApi(hostId)\n /*\n * The sites a new email can be sent as, on the org hub. One site answers\n * the question itself, so the field is asked only when there is a choice.\n */\n const orgSites = useMemo(\n () => (orgMount ? orgSiteOptions(orgMount) : []),\n [orgMount],\n )\n const askSite = !hostId && orgSites.length > 1\n\n /*\n * The campaigns, read while the list is shown: the Campaign filter offers\n * them by name, and the create drawer offers them to file a new email\n * under. One capped read of the containers serves both.\n */\n const { data: campaignDocs } = useFirestoreCollection<any>(\n () => {\n const containers = campaignContainersQuery(firestore, orgId, hostId)\n return containers ? collectionCeiling(containers, CONTAINER_CEILING) : null\n },\n [firestore, orgId, hostId],\n { idField: '$id' },\n )\n const campaignOptions = useMemo(\n () =>\n [...(campaignDocs ?? [])]\n .map((campaign: any) => ({\n value: String(campaign.$id),\n label: String(campaign.name || 'Untitled campaign'),\n }))\n .sort((a, b) => a.label.localeCompare(b.label)),\n [campaignDocs],\n )\n\n const filterOptions = useMemo(\n () => ({\n status: CAMPAIGN_SEND_STATUS_OPTIONS,\n emailCampaignId: [\n { value: SINGLE_SEND_FILTER_VALUE, label: 'Single send' },\n ...campaignOptions,\n ],\n ...(hostId ? {} : { site: orgSites }),\n }),\n [campaignOptions, hostId, orgSites],\n )\n\n /*==========================================\n * CREATE, THEN GO TO THE EMAIL'S OWN PAGE.\n *\n * The drawer collects only what it takes to MINT the record — the friendly\n * name, and the campaign it belongs to. Everything else about the email is\n * written on the email's own page, which is where a record is edited\n * throughout this console: a list page carries no form.\n *\n * The record is real from this moment: `/marketing/campaigns/{id}` resolves,\n * the row appears in the table below as a Draft, and the id it is created\n * under is the id it keeps when it is eventually sent. It costs nothing to\n * exist — the route reserves no allowance and moves no meter for a draft,\n * and the scheduled processor only ever picks up `scheduled`.\n *=========================================*/\n const handleCreate = useCallback(\n async (values: Record<string, any>) => {\n if (creating) return\n const sendAs =\n hostId ?? (askSite ? String(values.hostId ?? '') : orgSites[0]?.value)\n if (!sendAs) {\n return void enqueueSnackbar('Choose the site this email is sent as', {\n variant: 'warning',\n allowDuplicate: true,\n })\n }\n /*\n * The organization hub offers every campaign, because the site is\n * chosen in the same form. An email can only join a campaign placed on\n * the site it is sent as — the send route refuses anything else — so\n * the mismatch is named here, where it can be fixed, rather than\n * arriving as the route's bare refusal. A site hub lists only the\n * campaigns placed on it, so there is nothing to check there.\n */\n const chosenCampaign =\n !hostId && values.emailCampaignId\n ? (campaignDocs ?? []).find(\n (campaign: any) =>\n String(campaign.$id) === String(values.emailCampaignId),\n )\n : null\n if (chosenCampaign && !campaignPlacedOnHost(chosenCampaign, sendAs)) {\n return void enqueueSnackbar(\n 'That campaign is not offered on the site this email is sent as. ' +\n 'Choose another, or add the site to the campaign first.',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n setCreating(true)\n try {\n const { response, payload } = await campaignSendApi({\n action: 'draft',\n ...(hostId ? {} : { hostId: sendAs }),\n displayName: String(values.displayName ?? '').trim(),\n ...(values.emailCampaignId\n ? { emailCampaignId: String(values.emailCampaignId) }\n : {}),\n })\n if (!response.ok || !payload?.campaignId) {\n return void enqueueSnackbar(\n payload?.error ?? 'This email could not be created',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n setCreateOpen(false)\n /*\n * Straight to where it is WRITTEN. The drawer collected the name and\n * the campaign; the record now exists and holds nothing else, so the\n * next thing to do with it is compose it — and its own page is a\n * report of a send that has not happened.\n */\n router.push(`${messagesPath}/${payload.campaignId}/edit`)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('This email could not be created', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setCreating(false)\n }\n },\n [\n askSite,\n campaignDocs,\n campaignSendApi,\n creating,\n enqueueSnackbar,\n hostId,\n messagesPath,\n orgSites,\n router,\n ],\n )\n\n /*\n * One row per message, in the query's order. The subject is a link AND the\n * row opens the report: a click handler cannot be middle-clicked or opened\n * in a new tab.\n */\n const columns: GridColDef[] = [\n {\n field: 'subject',\n headerName: 'Subject',\n flex: 1,\n minWidth: 220,\n valueGetter: (_value, row) => row.subject || 'Untitled email',\n renderCell: ({ row, value }) => (\n <AppLink\n href={emailHref(row)}\n // The row's own handler would fire too and push the same route\n // twice — one history entry per back press.\n onClick={(event: { stopPropagation: () => void }) =>\n event.stopPropagation()\n }\n >\n {value}\n </AppLink>\n ),\n },\n // Which site each row is sent as, on the org hub only.\n ...(orgMount\n ? [\n {\n field: 'site',\n headerName: 'Site',\n width: 150,\n valueGetter: (_value: unknown, row: any) =>\n row?.hostId ? orgSiteName(orgMount, row.hostId) : '—',\n } satisfies GridColDef,\n ]\n : []),\n {\n /*\n * WHAT THIS EMAIL IS DOING, not what field it stores.\n *\n * An email delivering an audience larger than one batch is written back\n * as `scheduled` between runs, so a chip rendering the status said\n * \"Scheduled\" about a send that had already reached five hundred people.\n * The derivation reads the counters beside the status and says which of\n * the two it is.\n */\n field: 'state',\n headerName: 'State',\n width: 150,\n valueGetter: (_value, row) => campaignSendDisplay(row).label,\n renderCell: ({ row }) => {\n const display = campaignSendDisplay(row)\n return (\n <Chip\n size=\"small\"\n color={STATE_COLOR[display.state]}\n label={display.label}\n />\n )\n },\n },\n {\n field: 'when',\n headerName: 'When',\n width: 190,\n valueGetter: (_value, row) => emailListTimeMs(row),\n renderCell: ({ row }) => {\n const at = emailSendTimeMs(row)\n return at ? new Date(at).toLocaleString() : '—'\n },\n },\n ...(\n [\n ['recipients', 'Addressed'],\n ['opens', 'Opens'],\n ['clicks', 'Clicks'],\n ] as const\n ).map(\n ([stat, headerName]): GridColDef => ({\n field: stat,\n headerName,\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 110,\n valueGetter: (_value, row) => Number(row.stats?.[stat] ?? 0),\n valueFormatter: (value: number) => value.toLocaleString(),\n }),\n ),\n listActionsColumn(\n (row) => (\n <ListRowActions\n label={String(row.subject || 'Untitled email')}\n items={rowActions(row)}\n />\n ),\n { width: 72 },\n ),\n ]\n\n const gridColumns = listFilterGridColumns(\n columns,\n declaration.fields,\n filterOptions,\n EMAIL_FILTER_HEADERS,\n )\n /** Nothing stored at all — not a filter that matched nothing. */\n const none =\n emailPage.status !== 'loading' &&\n emails.length === 0 &&\n !filtering &&\n emailPage.page === 0\n\n return (\n <CardDisplay\n header={'Messages'}\n help={emailsDocsHelp}\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"contained\"\n onClick={() => setCreateOpen(true)}\n >\n {'New email'}\n </Button>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n {duplicate.dialog}\n <Stack spacing={2}>\n {none ? (\n <Stack spacing={2} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Nothing has been sent or scheduled yet. Write one here, or ' +\n 'from a campaign, and it appears in this list with its own ' +\n 'report.'}\n </Typography>\n <Button variant=\"contained\" onClick={() => setCreateOpen(true)}>\n {'New email'}\n </Button>\n </Stack>\n ) : (\n <>\n <ListFilterChips\n fields={declaration.fields}\n headers={EMAIL_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={filterOptions}\n />\n <ListQueryNotices\n refused={listQueryRefusals(emailPage.plan.refused, {\n fields: declaration.fields,\n headers: EMAIL_FILTER_HEADERS,\n options: filterOptions,\n })}\n notices={emailPage.plan.notices}\n />\n <ListTable\n aria-label=\"Messages\"\n rows={emails}\n columns={gridColumns}\n rowHeight={TABLE_ROW_HEIGHT}\n onOpen={(_id, row) => router.push(emailHref(row))}\n loading={emailPage.status === 'loading'}\n /*\n * The panel and the search are the grid's; every clause and\n * the search word are on the list's query (AGL-3321), and the\n * grid neither filters nor sorts the page it is handed: the\n * query's one order, newest first, is the list's.\n */\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n disableColumnSorting\n hideFooter\n initialState={{\n columns: {\n columnVisibilityModel: hiddenFilterVisibility(\n declaration.fields,\n columns.map((column) => column.field),\n ),\n },\n }}\n noRowsLabel=\"No messages match these filters\"\n />\n <ListPagination\n page={emailPage.page}\n pageSize={emailPage.pageSize}\n rowCount={emails.length}\n hasMore={emailPage.hasMore}\n onPageChange={emailPage.setPage}\n onPageSizeChange={emailPage.setPageSize}\n />\n </>\n )}\n </Stack>\n {/*\n AN EMAIL WRITTEN HERE BELONGS TO A CAMPAIGN, OR TO NO CAMPAIGN.\n\n The second is a real answer and not a gap in the model. A send with no\n container is what the product has always had — every message that\n predates campaigns is one — and `campaignListRows` adopts each of them\n as a campaign of one at read time, which is the \"Single send\" chip on\n the campaigns table. So composing from this list mints nothing, files\n nothing, and requires nobody to invent a campaign first: it leaves the\n container empty, and the send that results is presented the way every\n containerless send already is.\n\n Offering the campaigns anyway is what stops the opposite mistake — a\n merchant who DOES have a spring campaign writing its third email into\n a single send that never joins the rollup.\n */}\n <CreateArtifactDrawer\n open={createOpen}\n onClose={() => setCreateOpen(false)}\n title=\"New email\"\n submitLabel={creating ? 'Creating…' : 'Start writing'}\n includeDescription={false}\n onSubmit={handleCreate}\n extraFields={[\n ...(askSite\n ? [\n {\n component: 'select',\n name: 'hostId',\n label: 'Send as',\n isRequired: true,\n initialValue: '',\n helperText:\n 'The site this email is sent from — its sender, designs ' +\n 'and unsubscribe page',\n disableDefaultOption: true,\n options: orgSites,\n },\n ]\n : []),\n {\n component: 'select',\n name: 'emailCampaignId',\n label: 'Campaign',\n initialValue: '',\n helperText:\n 'Leave this as a single send unless the email belongs with ' +\n 'others',\n disableDefaultOption: true,\n options: [\n { value: '', label: 'Single send — not part of a campaign' },\n ...campaignOptions,\n ],\n },\n ]}\n />\n </CardDisplay>\n )\n}\nEmailsListCard.displayName = 'EmailsListCard'\n\nexport default EmailsListCard\n"],"names":["pluginDocsHelp","pluginRecordHref","mdiBullhornOutline","mdiContentCopy","mdiDeleteOutline","mdiEyeOutline","mdiPaletteOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListRowActions","ListTable","listActionsColumn","hiddenFilterVisibility","listFilterGridColumns","useListGridFilter","TABLE_ROW_HEIGHT","CreateArtifactDrawer","useSnackbar","collectionCeiling","useListQuery","DUPLICATE_MENU_LABEL","useDuplicateResource","useFirestore","useFirestoreCollection","Button","Chip","Stack","Typography","useRouter","useCallback","useMemo","useState","campaignPlacedOnHost","campaignSendDisplay","CAMPAIGN_SEND_CONTAINER_FIELD","emailListTimeMs","emailSendTimeMs","useCampaignManageApi","useCampaignSendApi","CAMPAIGN_SEND_STATUS_OPTIONS","SINGLE_SEND_FILTER_VALUE","campaignEmailsListQuery","campaignSendsScope","emailCampaignQueryClauses","useMarketingHubPath","siteRecordRouteContext","useRecordRouteContext","campaignContainersQuery","campaignSendsCollection","orgSiteName","orgSiteOptions","useMarketingOrgId","useMarketingOrgMount","CONTAINER_CEILING","DISCARD_REFUSAL","sent","scheduled","sending","canceled","STATE_COLOR","stopped","held","EMAIL_FILTER_HEADERS","subject","status","emailCampaignId","site","createdAtMs","emailsDocsHelp","anchor","excerpt","EmailsListCard","props","hostId","basePath","firestore","orgMount","orgId","siteMarketingHub","marketingHub","router","declaration","gridFilter","selectFields","emailPage","collection","request","clauses","search","searchWords","base","deps","idField","emails","rows","filtering","length","some","word","trim","messagesPath","emailHref","email","$id","routeContext","templateHref","templateScreenId","siteContext","rowHostId","String","hostOfEmail","Map","map","confirm","enqueueSnackbar","manageForCopy","duplicate","perform","sourceId","name","attemptKey","payload","response","action","campaignId","get","undefined","ok","Error","error","id","emailId","versionId","onDuplicated","_kind","copy","variant","manageApi","discardingId","setDiscardingId","handleDiscard","displayName","agreed","title","description","confirmationText","then","catch","allowDuplicate","persist","console","rowActions","containerId","state","templates","siteless","sitelessReason","key","label","icon","path","size","href","disabled","disabledReason","onClick","destructive","Boolean","createOpen","setCreateOpen","creating","setCreating","campaignSendApi","orgSites","askSite","data","campaignDocs","containers","campaignOptions","campaign","value","sort","a","b","localeCompare","filterOptions","handleCreate","values","sendAs","chosenCampaign","find","push","columns","field","headerName","flex","minWidth","valueGetter","_value","row","renderCell","event","stopPropagation","width","display","color","at","Date","toLocaleString","stat","type","align","headerAlign","Number","stats","valueFormatter","items","gridColumns","fields","none","page","header","help","HeaderProps","contentGutterX","contentGutterY","dialog","spacing","sx","alignItems","headers","onChange","setClauses","options","refused","plan","notices","aria-label","rowHeight","onOpen","_id","loading","filterMode","filterModel","onFilterModelChange","quickFilter","disableColumnSorting","hideFooter","initialState","columnVisibilityModel","column","noRowsLabel","pageSize","rowCount","hasMore","onPageChange","setPage","onPageSizeChange","setPageSize","open","onClose","submitLabel","includeDescription","onSubmit","extraFields","component","isRequired","initialValue","helperText","disableDefaultOption"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,cAAc,QAAQ,eAAc;AAC7C,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,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,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,oBACLC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,sBAAsB,QAAQ,yCAAwC;AAC/E,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,iBAAiB,QAAQ,kDAAiD;AAEnF,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,oBAAoB,QAAQ,6BAA4B;AACjE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,iBAAiB,QAAQ,+DAA8D;AAChG,SAASC,YAAY,QAAQ,sDAAqD;AAClF,SACEC,oBAAoB,EACpBC,oBAAoB,EACpBC,YAAY,EACZC,sBAAsB,QACjB,iCAAgC;AACvC,SAASC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AAE/D,SAASC,SAAS,QAAQ,kBAAiB;AAC3C,SAASC,WAAW,EAAEC,OAAO,EAAE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,UAAU7E;gBACV8E,aAAa;uBACP1F,UACA;wBACE;4BACE2F,WAAW;4BACXlJ,MAAM;4BACNuC,OAAO;4BACP4G,YAAY;4BACZC,cAAc;4BACdC,YACE,4DACA;4BACFC,sBAAsB;4BACtBpC,SAAS5D;wBACX;qBACD,GACD,EAAE;oBACN;wBACE4F,WAAW;wBACXlJ,MAAM;wBACNuC,OAAO;wBACP6G,cAAc;wBACdC,YACE,+DACA;wBACFC,sBAAsB;wBACtBpC,SAAS;4BACP;gCAAErD,OAAO;gCAAItB,OAAO;4BAAuC;+BACxDoB;yBACJ;oBACH;iBACD;;;;AAIT;AACA3G,eAAesE,WAAW,GAAG;AAE7B,eAAetE,eAAc"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/emails-list-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { pluginRecordHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport {\n mdiBullhornOutline,\n mdiContentCopy,\n mdiDeleteOutline,\n mdiEyeOutline,\n mdiPaletteOutline,\n} from '@aglyn/shared-data-mdi'\nimport {\n AppLink,\n CardDisplay,\n MdiIcon,\n useConfirmationContext,\n} from '@aglyn/shared-ui-jsx'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { hiddenFilterVisibility } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\nimport { useListColumnSort } from '@aglyn/shared-ui-jsx/hooks/use-list-column-sort'\nimport type { ListQuerySort } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport type { RowActionsMenuItem } from '@aglyn/shared-ui-jsx/components/row-actions-menu.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { CreateArtifactDrawer } from '@aglyn/shared-ui-jsx-forms'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { collectionCeiling } from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { useListQuery } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport {\n DUPLICATE_MENU_LABEL,\n useDuplicateResource,\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport { Button, Chip, Stack, Typography } from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useMemo, useState } from 'react'\nimport {\n campaignPlacedOnHost,\n campaignSendDisplay,\n CAMPAIGN_SEND_CONTAINER_FIELD,\n type CampaignSendDisplayState,\n} from '../model/campaign-container'\nimport {\n emailListTimeMs,\n emailSendTimeMs,\n} from '../model/email-record'\nimport {\n useCampaignManageApi,\n useCampaignSendApi,\n} from './use-campaign-send-api'\nimport {\n CAMPAIGN_SEND_STATUS_OPTIONS,\n SINGLE_SEND_FILTER_VALUE,\n campaignEmailsListQuery,\n campaignSendsScope,\n emailCampaignQueryClauses,\n} from '../model/campaign-list-query'\nimport { useMarketingHubPath } from './use-marketing-hub-path'\nimport { siteRecordRouteContext, useRecordRouteContext } from './record-route-context'\nimport {\n campaignContainersQuery,\n campaignSendsCollection,\n} from './campaign-queries'\nimport {\n orgSiteName,\n orgSiteOptions,\n useMarketingOrgId,\n useMarketingOrgMount,\n} from './marketing-org-mount'\n\n/**\n * How many campaigns the Campaign filter and the create drawer offer — the\n * same read serves both. A picker's options, not a list.\n */\nconst CONTAINER_CEILING = 50\n\n/** The headers a page sort names in its notice. */\nconst EMAIL_PAGE_SORT_HEADERS = {\n site: 'Site',\n state: 'State',\n when: 'When',\n recipients: 'Addressed',\n opens: 'Opens',\n clicks: 'Clicks',\n}\n\n/**\n * Why discard is refused, keyed by the state that refuses it.\n *\n * The KEYS are persisted status values written by the send path. Each line\n * says what to do instead, because \"you cannot\" on its own leaves a merchant\n * with an email they wanted rid of and no next step — and for a scheduled one\n * the next step is a different act with a different consequence, so naming it\n * is the difference between withdrawing mail and losing the record of it.\n *\n * A state absent from here falls through to the generic refusal rather than\n * being flattened into one of these: a state this list cannot name is worth\n * seeing.\n */\nconst DISCARD_REFUSAL: Record<string, string> = {\n sent: 'This email has been sent. Its report and its unsubscribe links have to go on resolving.',\n scheduled: 'Cancel the send first — cancelling takes it off the clock and keeps the email.',\n sending: 'This email is being sent right now.',\n canceled: 'A canceled email is kept as the record that it was withdrawn.',\n}\n\n/**\n * The chip color for one display state.\n *\n * `sending` is the one worth a color: an email part way through an audience\n * larger than one batch is doing something right now, and a merchant scanning\n * the list for what needs attention should find it without reading. The rest\n * are neutral, because a finished send and a draft are not events.\n */\nconst STATE_COLOR: Partial<\n Record<CampaignSendDisplayState, 'info' | 'warning'>\n> = {\n sending: 'info',\n stopped: 'warning',\n // Waiting on staff, not on the merchant (AGL-3356): worth finding on a scan.\n held: 'warning',\n}\n\n/*\n * What the messages grid's Filters panel offers, each clause and the search\n * on the list's Firestore query (AGL-3321, `campaignEmailsListQuery`). The\n * State column is what the email is DOING (`campaignSendDisplay`), which no\n * query can ask, so the panel offers the Status it STORES instead.\n */\nconst EMAIL_FILTER_HEADERS: Readonly<Record<string, string>> = {\n subject: 'Subject',\n status: 'Status',\n emailCampaignId: 'Campaign',\n site: 'Site',\n createdAtMs: 'Created',\n}\n\nconst emailsDocsHelp = pluginDocsHelp('emailCampaigns', {\n anchor: '#opens--clicks',\n excerpt:\n 'Every message this site has sent or has scheduled, each with its own ' +\n 'report: what was delivered, who opened it, and which links they followed.',\n})\n\nexport interface EmailsListCardProps {\n /** The site, or `null` on the organization's Emails page. */\n hostId: string | null\n /**\n * The Emails page's own URL, under the site or the organization, so a row\n * can link to the message's own page beneath it.\n */\n basePath: string\n}\n\n/**\n * EVERY MESSAGE, AS AGAINST EVERY CAMPAIGN.\n *\n * A campaign groups messages; this is the messages. The two are different\n * questions — \"how did the spring promotion do\" and \"what went out on the\n * 14th, and to whom\" — and they were previously the same list because a\n * campaign document WAS a single send.\n *\n * ## Asked of Firestore, a page at a time\n *\n * No SEND date is on every message — a sent one carries `sentAt`, a\n * scheduled one `sendAtMs`, a draft neither — so the list is ordered on\n * `createdAtMs`, the one date every writer stamps when it mints a record\n * (and `backfill-campaign-list-fields.mjs` stamped on the ones before).\n * Newest first, paged by the query itself.\n *\n * The Filters panel and the search box are the grid's; every clause and the\n * search word go onto that ONE query (AGL-3321, `campaignEmailsListQuery`),\n * so each page is a page of matches — an email that matches on page four is\n * found — and a combination one query cannot hold is refused by name above\n * the table, never answered over the rows that happen to be loaded.\n *\n * ## Under a site, and over the organization\n *\n * Sends are the org's. Under a site this lists the ones sent as that site;\n * on the organization's Emails page it lists every site's, with a Site column,\n * and every action on a row names the site that row is sent as — the only\n * site that can duplicate it, discard it or open its template. Creating one\n * there first asks which site it is sent as.\n */\nexport function EmailsListCard(props: EmailsListCardProps) {\n const { hostId, basePath } = props\n const firestore = useFirestore()\n const orgMount = useMarketingOrgMount()\n const { orgId } = useMarketingOrgId(hostId)\n // The sibling hub: a campaign's page belongs to the Marketing console —\n // over the org, the organization's own Marketing page the mount names.\n const siteMarketingHub = useMarketingHubPath()\n const marketingHub = orgMount ? orgMount.basePath : siteMarketingHub\n const router = useRouter()\n\n /*\n * The Filters panel and the search, bound to the grid. Held here rather\n * than in a saved view: this list keeps no views.\n */\n const declaration = campaignEmailsListQuery(!hostId)\n const gridFilter = useListGridFilter({\n selectFields: ['status', 'emailCampaignId', 'site'],\n })\n /*\n * EVERY HEADER SORTS (AGL-3680): Subject orders the query\n * (`declaration.sorts`); Site, State, When and the figures are derived or\n * may be absent, and sort the page.\n */\n const [askedSort, setAskedSort] = useState<ListQuerySort | null>(null)\n const emailPage = useListQuery<any>({\n collection: campaignSendsCollection(firestore, orgId),\n declaration,\n request: {\n clauses: emailCampaignQueryClauses(gridFilter.clauses),\n search: gridFilter.searchWords,\n base: campaignSendsScope(hostId),\n sort: askedSort,\n },\n deps: [firestore, orgId, hostId],\n idField: '$id',\n })\n const emailPageSorts = useMemo(\n () => ({\n ...(orgMount\n ? { site: (row: any) => (row?.hostId ? orgSiteName(orgMount, row.hostId) : null) }\n : {}),\n state: (row: any) => campaignSendDisplay(row).label,\n when: (row: any) => emailListTimeMs(row),\n // Counters stay absent until something is counted (see\n // `campaign-list-query.ts`), so no query can order by them.\n recipients: (row: any) => row.stats?.recipients ?? null,\n opens: (row: any) => row.stats?.opens ?? null,\n clicks: (row: any) => row.stats?.clicks ?? null,\n }),\n [orgMount],\n )\n const emailSort = useListColumnSort<any>({\n sorts: declaration.sorts,\n sort: askedSort,\n onSortChange: setAskedSort,\n orderBy: emailPage.plan.orderBy,\n rows: emailPage.rows,\n pageSorts: emailPageSorts,\n headers: EMAIL_PAGE_SORT_HEADERS,\n })\n const emails = emailPage.rows\n const filtering =\n gridFilter.clauses.length > 0 ||\n gridFilter.searchWords.some((word) => word.trim())\n\n /*\n * A message's own pages, beneath the Emails page this list is on — the\n * site's or the organization's. A template is a site's design, so over the\n * org it opens on the site the row is sent as.\n */\n const messagesPath = `${basePath}/messages`\n const emailHref = (email: any) => `${messagesPath}/${email.$id}`\n const routeContext = useRecordRouteContext()\n const templateHref = (email: any, templateScreenId: string): string | null => {\n const siteContext = siteRecordRouteContext(routeContext, orgMount, email?.hostId)\n return siteContext ? pluginRecordHref('emailTemplate', siteContext, templateScreenId) : null\n }\n /** The site a row is sent as, which every action on it must name. */\n const rowHostId = useCallback(\n (email: any): string | null =>\n hostId ?? (email?.hostId ? String(email.hostId) : null),\n [hostId],\n )\n const hostOfEmail = useMemo(\n () =>\n new Map<string, string | null>(\n emails.map((email: any) => [\n String(email.$id),\n email?.hostId ? String(email.hostId) : null,\n ]),\n ),\n [emails],\n )\n\n const { confirm } = useConfirmationContext()\n const { enqueueSnackbar } = useSnackbar()\n // Duplicate (AGL-2936): a new draft with the message and its design, and\n // nobody to send to until the person chooses — through the manage door,\n // which is the plugin's own.\n const manageForCopy = useCampaignManageApi(hostId)\n const duplicate = useDuplicateResource({\n hostId: hostId ?? '',\n perform: async ({ sourceId, name, attemptKey }) => {\n const { response, payload } = await manageForCopy({\n action: 'duplicate',\n campaignId: sourceId,\n name,\n attemptKey,\n // The copy is made as the site the source is sent as.\n ...(hostId ? {} : { hostId: hostOfEmail.get(sourceId) ?? undefined }),\n })\n if (!response.ok) throw new Error(payload?.error ?? 'Duplicate failed')\n return {\n id: String(payload.emailId),\n versionId: null,\n name: String(payload.name ?? name),\n }\n },\n onDuplicated: (_kind, copy) =>\n enqueueSnackbar(`Duplicated as “${copy.name}” — a draft with no audience yet`, {\n variant: 'success',\n }),\n })\n const manageApi = useCampaignManageApi(hostId)\n /** The email a discard is in flight for, so its row menu can say so. */\n const [discardingId, setDiscardingId] = useState('')\n\n /*==========================================\n * THROWING AWAY A DRAFT.\n *\n * The one removal this surface has, and it is deliberately the narrowest\n * one: an email that was never sent, whose record nobody outside the\n * console has ever seen. Everything else on this list is evidence — a sent\n * message's report is what a merchant answers a complaint with, and its id\n * is inside the HMAC of every unsubscribe footer it delivered — and a\n * scheduled one is withdrawn with Cancel, which keeps the record and takes\n * it off the clock.\n *\n * The menu already refuses anything but a draft, and so does the route.\n * That is not belt and braces: the state on screen is a snapshot that can\n * be seconds old, and the record can be claimed by `sendNow` in between.\n * The route's refusal is the one that decides, inside the transaction that\n * does the delete.\n *=========================================*/\n const handleDiscard = useCallback(\n async (email: any) => {\n if (discardingId) return\n const id = String(email?.$id ?? '')\n const name = String(email?.subject || email?.displayName || 'this draft')\n const agreed = await confirm({\n title: 'Discard this draft?',\n description:\n `${name} has not been sent to anybody, and discarding it removes ` +\n 'it for good — the subject, the message and everything else ' +\n 'written on it. There is no undo.',\n confirmationText: 'Discard',\n })\n .then(() => true)\n .catch(() => false)\n if (!agreed) return\n setDiscardingId(id)\n try {\n const { response, payload } = await manageApi({\n action: 'discardEmail',\n campaignId: id,\n ...(hostId ? {} : { hostId: rowHostId(email) ?? undefined }),\n })\n if (!response.ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'This draft could not be discarded',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n enqueueSnackbar('Draft discarded', {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('This draft could not be discarded', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setDiscardingId('')\n }\n },\n [confirm, discardingId, enqueueSnackbar, hostId, manageApi, rowHostId],\n )\n\n /**\n * What a message can be opened INTO, from the list.\n *\n * All three are places the message's own report already links to, moved one\n * screen earlier: the report itself, the campaign it belongs to, and the\n * template it was rendered from. A message need have neither of the last\n * two — one sent before campaigns grouped anything names no container, and\n * one composed inline was built from no template — so those entries are\n * shown DISABLED with the reason rather than hidden. A control that\n * disappears and a control that does not apply look identical, and only one\n * of them tells the reader which case they are in.\n *\n * DISCARD is the fourth entry and is offered on the same terms: a draft can\n * be thrown away, and nothing else can. It stays visible on a sent or\n * scheduled message carrying the reason it is refused, because that is the\n * honest answer to “how do I get rid of this” — and the route refuses it\n * too, so the menu is describing a rule rather than being one.\n */\n const rowActions = (email: any): RowActionsMenuItem[] => {\n const containerId = String(email?.[CAMPAIGN_SEND_CONTAINER_FIELD] ?? '')\n const templateScreenId = String(email?.templateScreenId ?? '')\n const state = String(email?.status ?? '')\n const templates = templateScreenId ? templateHref(email, templateScreenId) : null\n /** On the org hub, a send that names no site has nothing to act as. */\n const siteless = !rowHostId(email)\n const sitelessReason =\n 'This email does not record which site it was sent as. Manage it from ' +\n 'that site’s own Emails page.'\n return [\n {\n key: 'details',\n label: 'Open report',\n icon: <MdiIcon path={mdiEyeOutline.path} size={0.8} />,\n href: emailHref(email),\n },\n {\n key: 'campaign',\n label: 'Open its campaign',\n icon: <MdiIcon path={mdiBullhornOutline.path} size={0.8} />,\n // The campaign's page belongs to the Marketing console, so this one\n // href is built from the sibling hub rather than this surface's own.\n href:\n containerId && marketingHub\n ? `${marketingHub}/campaigns/${containerId}`\n : undefined,\n disabled: !containerId || !marketingHub,\n disabledReason: containerId\n ? 'This site’s console URL has not resolved yet'\n : 'Sent before campaigns grouped their emails, so it belongs to none',\n },\n {\n key: 'template',\n label: 'Open its template',\n icon: <MdiIcon path={mdiPaletteOutline.path} size={0.8} />,\n href: templates ?? undefined,\n disabled: !templates,\n disabledReason: templateScreenId\n ? 'This site’s console URL has not resolved yet'\n : 'This message was not built from a template',\n },\n {\n key: 'duplicate',\n label: DUPLICATE_MENU_LABEL,\n icon: <MdiIcon path={mdiContentCopy.path} size={0.8} />,\n disabled: siteless,\n disabledReason: sitelessReason,\n onClick: () =>\n duplicate.request('campaign', {\n id: String(email.$id),\n name: String(email?.displayName ?? email?.subject ?? ''),\n }),\n },\n {\n key: 'discard',\n label: 'Discard draft',\n icon: <MdiIcon path={mdiDeleteOutline.path} size={0.8} />,\n destructive: true,\n disabled: siteless || state !== 'draft' || Boolean(discardingId),\n disabledReason: siteless\n ? sitelessReason\n : (DISCARD_REFUSAL[state] ?? 'Only a draft can be discarded'),\n onClick: () => void handleDiscard(email),\n },\n ]\n }\n\n const [createOpen, setCreateOpen] = useState(false)\n const [creating, setCreating] = useState(false)\n const campaignSendApi = useCampaignSendApi(hostId)\n /*\n * The sites a new email can be sent as, on the org hub. One site answers\n * the question itself, so the field is asked only when there is a choice.\n */\n const orgSites = useMemo(\n () => (orgMount ? orgSiteOptions(orgMount) : []),\n [orgMount],\n )\n const askSite = !hostId && orgSites.length > 1\n\n /*\n * The campaigns, read while the list is shown: the Campaign filter offers\n * them by name, and the create drawer offers them to file a new email\n * under. One capped read of the containers serves both.\n */\n const { data: campaignDocs } = useFirestoreCollection<any>(\n () => {\n const containers = campaignContainersQuery(firestore, orgId, hostId)\n return containers ? collectionCeiling(containers, CONTAINER_CEILING) : null\n },\n [firestore, orgId, hostId],\n { idField: '$id' },\n )\n const campaignOptions = useMemo(\n () =>\n [...(campaignDocs ?? [])]\n .map((campaign: any) => ({\n value: String(campaign.$id),\n label: String(campaign.name || 'Untitled campaign'),\n }))\n .sort((a, b) => a.label.localeCompare(b.label)),\n [campaignDocs],\n )\n\n const filterOptions = useMemo(\n () => ({\n status: CAMPAIGN_SEND_STATUS_OPTIONS,\n emailCampaignId: [\n { value: SINGLE_SEND_FILTER_VALUE, label: 'Single send' },\n ...campaignOptions,\n ],\n ...(hostId ? {} : { site: orgSites }),\n }),\n [campaignOptions, hostId, orgSites],\n )\n\n /*==========================================\n * CREATE, THEN GO TO THE EMAIL'S OWN PAGE.\n *\n * The drawer collects only what it takes to MINT the record — the friendly\n * name, and the campaign it belongs to. Everything else about the email is\n * written on the email's own page, which is where a record is edited\n * throughout this console: a list page carries no form.\n *\n * The record is real from this moment: `/marketing/campaigns/{id}` resolves,\n * the row appears in the table below as a Draft, and the id it is created\n * under is the id it keeps when it is eventually sent. It costs nothing to\n * exist — the route reserves no allowance and moves no meter for a draft,\n * and the scheduled processor only ever picks up `scheduled`.\n *=========================================*/\n const handleCreate = useCallback(\n async (values: Record<string, any>) => {\n if (creating) return\n const sendAs =\n hostId ?? (askSite ? String(values.hostId ?? '') : orgSites[0]?.value)\n if (!sendAs) {\n return void enqueueSnackbar('Choose the site this email is sent as', {\n variant: 'warning',\n allowDuplicate: true,\n })\n }\n /*\n * The organization hub offers every campaign, because the site is\n * chosen in the same form. An email can only join a campaign placed on\n * the site it is sent as — the send route refuses anything else — so\n * the mismatch is named here, where it can be fixed, rather than\n * arriving as the route's bare refusal. A site hub lists only the\n * campaigns placed on it, so there is nothing to check there.\n */\n const chosenCampaign =\n !hostId && values.emailCampaignId\n ? (campaignDocs ?? []).find(\n (campaign: any) =>\n String(campaign.$id) === String(values.emailCampaignId),\n )\n : null\n if (chosenCampaign && !campaignPlacedOnHost(chosenCampaign, sendAs)) {\n return void enqueueSnackbar(\n 'That campaign is not offered on the site this email is sent as. ' +\n 'Choose another, or add the site to the campaign first.',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n setCreating(true)\n try {\n const { response, payload } = await campaignSendApi({\n action: 'draft',\n ...(hostId ? {} : { hostId: sendAs }),\n displayName: String(values.displayName ?? '').trim(),\n ...(values.emailCampaignId\n ? { emailCampaignId: String(values.emailCampaignId) }\n : {}),\n })\n if (!response.ok || !payload?.campaignId) {\n return void enqueueSnackbar(\n payload?.error ?? 'This email could not be created',\n { variant: 'warning', allowDuplicate: true },\n )\n }\n setCreateOpen(false)\n /*\n * Straight to where it is WRITTEN. The drawer collected the name and\n * the campaign; the record now exists and holds nothing else, so the\n * next thing to do with it is compose it — and its own page is a\n * report of a send that has not happened.\n */\n router.push(`${messagesPath}/${payload.campaignId}/edit`)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('This email could not be created', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setCreating(false)\n }\n },\n [\n askSite,\n campaignDocs,\n campaignSendApi,\n creating,\n enqueueSnackbar,\n hostId,\n messagesPath,\n orgSites,\n router,\n ],\n )\n\n /*\n * One row per message, in the query's order. The subject is a link AND the\n * row opens the report: a click handler cannot be middle-clicked or opened\n * in a new tab.\n */\n const columns: GridColDef[] = [\n {\n field: 'subject',\n headerName: 'Subject',\n flex: 1,\n minWidth: 220,\n valueGetter: (_value, row) => row.subject || 'Untitled email',\n renderCell: ({ row, value }) => (\n <AppLink\n href={emailHref(row)}\n // The row's own handler would fire too and push the same route\n // twice — one history entry per back press.\n onClick={(event: { stopPropagation: () => void }) =>\n event.stopPropagation()\n }\n >\n {value}\n </AppLink>\n ),\n },\n // Which site each row is sent as, on the org hub only.\n ...(orgMount\n ? [\n {\n field: 'site',\n headerName: 'Site',\n width: 150,\n valueGetter: (_value: unknown, row: any) =>\n row?.hostId ? orgSiteName(orgMount, row.hostId) : '—',\n } satisfies GridColDef,\n ]\n : []),\n {\n /*\n * WHAT THIS EMAIL IS DOING, not what field it stores.\n *\n * An email delivering an audience larger than one batch is written back\n * as `scheduled` between runs, so a chip rendering the status said\n * \"Scheduled\" about a send that had already reached five hundred people.\n * The derivation reads the counters beside the status and says which of\n * the two it is.\n */\n field: 'state',\n headerName: 'State',\n width: 150,\n valueGetter: (_value, row) => campaignSendDisplay(row).label,\n renderCell: ({ row }) => {\n const display = campaignSendDisplay(row)\n return (\n <Chip\n size=\"small\"\n color={STATE_COLOR[display.state]}\n label={display.label}\n />\n )\n },\n },\n {\n field: 'when',\n headerName: 'When',\n width: 190,\n valueGetter: (_value, row) => emailListTimeMs(row),\n renderCell: ({ row }) => {\n const at = emailSendTimeMs(row)\n return at ? new Date(at).toLocaleString() : '—'\n },\n },\n ...(\n [\n ['recipients', 'Addressed'],\n ['opens', 'Opens'],\n ['clicks', 'Clicks'],\n ] as const\n ).map(\n ([stat, headerName]): GridColDef => ({\n field: stat,\n headerName,\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 110,\n valueGetter: (_value, row) => Number(row.stats?.[stat] ?? 0),\n valueFormatter: (value: number) => value.toLocaleString(),\n }),\n ),\n listActionsColumn(\n (row) => (\n <ListRowActions\n label={String(row.subject || 'Untitled email')}\n items={rowActions(row)}\n />\n ),\n { width: 72 },\n ),\n ]\n\n const gridColumns = listFilterGridColumns(\n columns,\n declaration.fields,\n filterOptions,\n EMAIL_FILTER_HEADERS,\n )\n /** Nothing stored at all — not a filter that matched nothing. */\n const none =\n emailPage.status !== 'loading' &&\n emails.length === 0 &&\n !filtering &&\n emailPage.page === 0\n\n return (\n <CardDisplay\n header={'Messages'}\n help={emailsDocsHelp}\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"contained\"\n onClick={() => setCreateOpen(true)}\n >\n {'New email'}\n </Button>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n {duplicate.dialog}\n <Stack spacing={2}>\n {none ? (\n <Stack spacing={2} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Nothing has been sent or scheduled yet. Write one here, or ' +\n 'from a campaign, and it appears in this list with its own ' +\n 'report.'}\n </Typography>\n <Button variant=\"contained\" onClick={() => setCreateOpen(true)}>\n {'New email'}\n </Button>\n </Stack>\n ) : (\n <>\n <ListFilterChips\n fields={declaration.fields}\n headers={EMAIL_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={filterOptions}\n />\n <ListQueryNotices\n refused={listQueryRefusals(emailPage.plan.refused, {\n fields: declaration.fields,\n headers: EMAIL_FILTER_HEADERS,\n options: filterOptions,\n })}\n notices={[...emailPage.plan.notices, ...emailSort.notices]}\n />\n <ListTable\n aria-label=\"Messages\"\n rows={emailSort.rows}\n columns={gridColumns}\n rowHeight={TABLE_ROW_HEIGHT}\n onOpen={(_id, row) => router.push(emailHref(row))}\n loading={emailPage.status === 'loading'}\n /*\n * The panel and the search are the grid's; every clause and\n * the search word are on the list's query (AGL-3321), and the\n * grid neither filters nor sorts the page it is handed:\n * Subject's header orders the query, the rest the page\n * (AGL-3680), newest first until one is clicked.\n */\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n columnSort={emailSort}\n hideFooter\n initialState={{\n columns: {\n columnVisibilityModel: hiddenFilterVisibility(\n declaration.fields,\n columns.map((column) => column.field),\n ),\n },\n }}\n noRowsLabel=\"No messages match these filters\"\n />\n <ListPagination\n page={emailPage.page}\n pageSize={emailPage.pageSize}\n rowCount={emails.length}\n hasMore={emailPage.hasMore}\n onPageChange={emailPage.setPage}\n onPageSizeChange={emailPage.setPageSize}\n />\n </>\n )}\n </Stack>\n {/*\n AN EMAIL WRITTEN HERE BELONGS TO A CAMPAIGN, OR TO NO CAMPAIGN.\n\n The second is a real answer and not a gap in the model. A send with no\n container is what the product has always had — every message that\n predates campaigns is one — and `campaignListRows` adopts each of them\n as a campaign of one at read time, which is the \"Single send\" chip on\n the campaigns table. So composing from this list mints nothing, files\n nothing, and requires nobody to invent a campaign first: it leaves the\n container empty, and the send that results is presented the way every\n containerless send already is.\n\n Offering the campaigns anyway is what stops the opposite mistake — a\n merchant who DOES have a spring campaign writing its third email into\n a single send that never joins the rollup.\n */}\n <CreateArtifactDrawer\n open={createOpen}\n onClose={() => setCreateOpen(false)}\n title=\"New email\"\n submitLabel={creating ? 'Creating…' : 'Start writing'}\n includeDescription={false}\n onSubmit={handleCreate}\n extraFields={[\n ...(askSite\n ? [\n {\n component: 'select',\n name: 'hostId',\n label: 'Send as',\n isRequired: true,\n initialValue: '',\n helperText:\n 'The site this email is sent from — its sender, designs ' +\n 'and unsubscribe page',\n disableDefaultOption: true,\n options: orgSites,\n },\n ]\n : []),\n {\n component: 'select',\n name: 'emailCampaignId',\n label: 'Campaign',\n initialValue: '',\n helperText:\n 'Leave this as a single send unless the email belongs with ' +\n 'others',\n disableDefaultOption: true,\n options: [\n { value: '', label: 'Single send — not part of a campaign' },\n ...campaignOptions,\n ],\n },\n ]}\n />\n </CardDisplay>\n )\n}\nEmailsListCard.displayName = 'EmailsListCard'\n\nexport default EmailsListCard\n"],"names":["pluginDocsHelp","pluginRecordHref","mdiBullhornOutline","mdiContentCopy","mdiDeleteOutline","mdiEyeOutline","mdiPaletteOutline","AppLink","CardDisplay","MdiIcon","useConfirmationContext","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListRowActions","ListTable","listActionsColumn","hiddenFilterVisibility","listFilterGridColumns","useListGridFilter","useListColumnSort","TABLE_ROW_HEIGHT","CreateArtifactDrawer","useSnackbar","collectionCeiling","useListQuery","DUPLICATE_MENU_LABEL","useDuplicateResource","useFirestore","useFirestoreCollection","Button","Chip","Stack","Typography","useRouter","useCallback","useMemo","useState","campaignPlacedOnHost","campaignSendDisplay","CAMPAIGN_SEND_CONTAINER_FIELD","emailListTimeMs","emailSendTimeMs","useCampaignManageApi","useCampaignSendApi","CAMPAIGN_SEND_STATUS_OPTIONS","SINGLE_SEND_FILTER_VALUE","campaignEmailsListQuery","campaignSendsScope","emailCampaignQueryClauses","useMarketingHubPath","siteRecordRouteContext","useRecordRouteContext","campaignContainersQuery","campaignSendsCollection","orgSiteName","orgSiteOptions","useMarketingOrgId","useMarketingOrgMount","CONTAINER_CEILING","EMAIL_PAGE_SORT_HEADERS","site","state","when","recipients","opens","clicks","DISCARD_REFUSAL","sent","scheduled","sending","canceled","STATE_COLOR","stopped","held","EMAIL_FILTER_HEADERS","subject","status","emailCampaignId","createdAtMs","emailsDocsHelp","anchor","excerpt","EmailsListCard","props","hostId","basePath","firestore","orgMount","orgId","siteMarketingHub","marketingHub","router","declaration","gridFilter","selectFields","askedSort","setAskedSort","emailPage","collection","request","clauses","search","searchWords","base","sort","deps","idField","emailPageSorts","row","label","stats","emailSort","sorts","onSortChange","orderBy","plan","rows","pageSorts","headers","emails","filtering","length","some","word","trim","messagesPath","emailHref","email","$id","routeContext","templateHref","templateScreenId","siteContext","rowHostId","String","hostOfEmail","Map","map","confirm","enqueueSnackbar","manageForCopy","duplicate","perform","sourceId","name","attemptKey","payload","response","action","campaignId","get","undefined","ok","Error","error","id","emailId","versionId","onDuplicated","_kind","copy","variant","manageApi","discardingId","setDiscardingId","handleDiscard","displayName","agreed","title","description","confirmationText","then","catch","allowDuplicate","persist","console","rowActions","containerId","templates","siteless","sitelessReason","key","icon","path","size","href","disabled","disabledReason","onClick","destructive","Boolean","createOpen","setCreateOpen","creating","setCreating","campaignSendApi","orgSites","askSite","data","campaignDocs","containers","campaignOptions","campaign","value","a","b","localeCompare","filterOptions","handleCreate","values","sendAs","chosenCampaign","find","push","columns","field","headerName","flex","minWidth","valueGetter","_value","renderCell","event","stopPropagation","width","display","color","at","Date","toLocaleString","stat","type","align","headerAlign","Number","valueFormatter","items","gridColumns","fields","none","page","header","help","HeaderProps","contentGutterX","contentGutterY","dialog","spacing","sx","alignItems","onChange","setClauses","options","refused","notices","aria-label","rowHeight","onOpen","_id","loading","filterMode","filterModel","onFilterModelChange","quickFilter","columnSort","hideFooter","initialState","columnVisibilityModel","column","noRowsLabel","pageSize","rowCount","hasMore","onPageChange","setPage","onPageSizeChange","setPageSize","open","onClose","submitLabel","includeDescription","onSubmit","extraFields","component","isRequired","initialValue","helperText","disableDefaultOption"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,cAAc,QAAQ,eAAc;AAC7C,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,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,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,oBACLC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,sBAAsB,QAAQ,yCAAwC;AAC/E,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,SAASC,iBAAiB,QAAQ,kDAAiD;AAGnF,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,oBAAoB,QAAQ,6BAA4B;AACjE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,iBAAiB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;;;0BAqB/C,KAAC/P;gBACCgQ,MAAMtF;gBACNuF,SAAS,IAAMtF,cAAc;gBAC7BxB,OAAM;gBACN+G,aAAatF,WAAW,cAAc;gBACtCuF,oBAAoB;gBACpBC,UAAUzE;gBACV0E,aAAa;uBACPrF,UACA;wBACE;4BACEsF,WAAW;4BACX3I,MAAM;4BACNnC,OAAO;4BACP+K,YAAY;4BACZC,cAAc;4BACdC,YACE,4DACA;4BACFC,sBAAsB;4BACtBnC,SAASxD;wBACX;qBACD,GACD,EAAE;oBACN;wBACEuF,WAAW;wBACX3I,MAAM;wBACNnC,OAAO;wBACPgL,cAAc;wBACdC,YACE,+DACA;wBACFC,sBAAsB;wBACtBnC,SAAS;4BACP;gCAAEjD,OAAO;gCAAI9F,OAAO;4BAAuC;+BACxD4F;yBACJ;oBACH;iBACD;;;;AAIT;AACAvH,eAAeoF,WAAW,GAAG;AAE7B,eAAepF,eAAc"}
|
|
@@ -29,6 +29,7 @@ import { ListPagination } from "@aglyn/shared-ui-jsx/components/list-pagination.
|
|
|
29
29
|
import { ListRowActions, ListTable, listActionsColumn } from "@aglyn/shared-ui-jsx/components/list-table.component";
|
|
30
30
|
import { listFilterGridColumns } from "@aglyn/shared-ui-jsx/const/list-grid-filter";
|
|
31
31
|
import { useListGridFilter } from "@aglyn/shared-ui-jsx/hooks/use-list-grid-filter";
|
|
32
|
+
import { useListColumnSort } from "@aglyn/shared-ui-jsx/hooks/use-list-column-sort";
|
|
32
33
|
import { ScrollTable } from "@aglyn/shared-ui-jsx/components/scroll-table.component";
|
|
33
34
|
import { TABLE_ROW_HEIGHT } from "@aglyn/shared-ui-jsx/const/table-pagination";
|
|
34
35
|
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
@@ -81,6 +82,15 @@ const EXPERIMENT_FILTER_OPTIONS = {
|
|
|
81
82
|
label: status.charAt(0).toUpperCase() + status.slice(1)
|
|
82
83
|
}))
|
|
83
84
|
};
|
|
85
|
+
/** Tests is drawn from the target and the variant count: it sorts the page (AGL-3680). */ const EXPERIMENT_PAGE_SORTS = {
|
|
86
|
+
target: (experiment)=>{
|
|
87
|
+
var _EXPERIMENT_TARGET_NOUNS_experiment_target, _experiment_variants;
|
|
88
|
+
return `${(_EXPERIMENT_TARGET_NOUNS_experiment_target = EXPERIMENT_TARGET_NOUNS[experiment.target]) != null ? _EXPERIMENT_TARGET_NOUNS_experiment_target : experiment.target} ${((_experiment_variants = experiment.variants) != null ? _experiment_variants : []).length}`;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
const EXPERIMENT_PAGE_SORT_HEADERS = {
|
|
92
|
+
target: 'Tests'
|
|
93
|
+
};
|
|
84
94
|
/**
|
|
85
95
|
* Experiments manager (AGL-252): create screen/section/email A/B tests
|
|
86
96
|
* with weighted variants and a conversion goal; start/pause/finish them
|
|
@@ -110,6 +120,8 @@ const EXPERIMENT_FILTER_OPTIONS = {
|
|
|
110
120
|
'status'
|
|
111
121
|
]
|
|
112
122
|
});
|
|
123
|
+
// Experiment and Status order the query, Tests the page (AGL-3680).
|
|
124
|
+
const [askedSort, setAskedSort] = useState(null);
|
|
113
125
|
const filtering = gridFilter.clauses.length > 0 || gridFilter.searchWords.some((word)=>word.trim());
|
|
114
126
|
const { rows: experimentRows, hasMore: hasMoreExperiments, page: experimentPage, setPage: setExperimentPage, pageSize: experimentPageSize, setPageSize: setExperimentPageSize, status: experimentsStatus, /**
|
|
115
127
|
* The rows this editor is seeded from are unconfirmed by the server
|
|
@@ -136,7 +148,8 @@ const EXPERIMENT_FILTER_OPTIONS = {
|
|
|
136
148
|
*/ declaration: EXPERIMENT_LIST_QUERY,
|
|
137
149
|
request: {
|
|
138
150
|
clauses: gridFilter.clauses,
|
|
139
|
-
search: gridFilter.searchWords
|
|
151
|
+
search: gridFilter.searchWords,
|
|
152
|
+
sort: askedSort
|
|
140
153
|
},
|
|
141
154
|
deps: [
|
|
142
155
|
firestore,
|
|
@@ -144,7 +157,17 @@ const EXPERIMENT_FILTER_OPTIONS = {
|
|
|
144
157
|
],
|
|
145
158
|
idField: '$id'
|
|
146
159
|
});
|
|
147
|
-
const
|
|
160
|
+
const experimentSort = useListColumnSort({
|
|
161
|
+
sorts: EXPERIMENT_LIST_QUERY.sorts,
|
|
162
|
+
defaultSort: EXPERIMENT_LIST_QUERY.sorts[0],
|
|
163
|
+
sort: askedSort,
|
|
164
|
+
onSortChange: setAskedSort,
|
|
165
|
+
orderBy: experimentPlan.orderBy,
|
|
166
|
+
rows: experimentRows,
|
|
167
|
+
pageSorts: EXPERIMENT_PAGE_SORTS,
|
|
168
|
+
headers: EXPERIMENT_PAGE_SORT_HEADERS
|
|
169
|
+
});
|
|
170
|
+
const experiments = experimentSort.rows;
|
|
148
171
|
const experimentColumnsFor = (columns)=>listFilterGridColumns(columns, EXPERIMENT_FILTER_FIELDS, EXPERIMENT_FILTER_OPTIONS, EXPERIMENT_FILTER_HEADERS);
|
|
149
172
|
const experimentRefusals = useMemo(()=>listQueryRefusals(experimentPlan.refused, {
|
|
150
173
|
fields: EXPERIMENT_FILTER_FIELDS,
|
|
@@ -525,7 +548,10 @@ const EXPERIMENT_FILTER_OPTIONS = {
|
|
|
525
548
|
}),
|
|
526
549
|
/*#__PURE__*/ _jsx(ListQueryNotices, {
|
|
527
550
|
refused: experimentRefusals,
|
|
528
|
-
notices:
|
|
551
|
+
notices: [
|
|
552
|
+
...experimentPlan.notices,
|
|
553
|
+
...experimentSort.notices
|
|
554
|
+
]
|
|
529
555
|
}),
|
|
530
556
|
/*#__PURE__*/ _jsx(ListTable, {
|
|
531
557
|
"aria-label": "Experiments",
|
|
@@ -535,9 +561,9 @@ const EXPERIMENT_FILTER_OPTIONS = {
|
|
|
535
561
|
onOpen: (_id, experiment)=>void openResults(experiment),
|
|
536
562
|
// Paged by the footer below, so the grid must not also slice.
|
|
537
563
|
hideFooter: true,
|
|
538
|
-
//
|
|
539
|
-
//
|
|
540
|
-
|
|
564
|
+
// Experiment and Status order the query; Tests sorts the page
|
|
565
|
+
// and says so (AGL-3680).
|
|
566
|
+
columnSort: experimentSort,
|
|
541
567
|
/*
|
|
542
568
|
* The panel and the search are the grid's; every clause and the
|
|
543
569
|
* search word are on the list's query (AGL-3321), so the grid
|
|
@@ -668,6 +694,7 @@ const EXPERIMENT_FILTER_OPTIONS = {
|
|
|
668
694
|
}, eventType))
|
|
669
695
|
}),
|
|
670
696
|
/*#__PURE__*/ _jsxs(Stack, {
|
|
697
|
+
useFlexGap: true,
|
|
671
698
|
direction: "row",
|
|
672
699
|
spacing: 1,
|
|
673
700
|
sx: {
|