@aglyn/shared-ui-email-campaigns 1.0.0-beta.173 → 1.0.0-beta.174

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/shared-ui-email-campaigns",
3
- "version": "1.0.0-beta.173",
3
+ "version": "1.0.0-beta.174",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -29,8 +29,8 @@
29
29
  "./package.json": "./package.json"
30
30
  },
31
31
  "dependencies": {
32
- "@aglyn/shared-ui-jsx": "1.0.0-beta.173",
33
- "@aglyn/shared-util-email": "1.0.0-beta.173",
32
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.174",
33
+ "@aglyn/shared-util-email": "1.0.0-beta.174",
34
34
  "@swc/helpers": "0.5.23"
35
35
  },
36
36
  "peerDependencies": {
@@ -17,31 +17,45 @@
17
17
  /**
18
18
  * A CAMPAIGN IS A CONTAINER; A SEND IS ONE MESSAGE INSIDE IT.
19
19
  *
20
- * ## The two collections, and why there are two
21
- *
22
- * `hosts/{hostId}/campaigns/{sendId}` holds a SEND: one subject, one body,
23
- * one audience, one set of counters. That is what the collection has always
24
- * held, and it is why the container could not simply be that document grown
25
- * new fields.
26
- *
27
- * **Its ids are load-bearing outside this repo.** Every unsubscribe link that
28
- * has ever gone out carries `cid={sendId}`, those emails sit in inboxes
29
- * forever, and the `cid` is inside the link's HMAC — so a send id that stops
30
- * resolving is an opt-out that stops working, which is a compliance failure
31
- * rather than a broken page. `/marketing/campaigns/{sendId}` is likewise
32
- * linkable by design: a merchant pastes it into a message about last week's
33
- * send.
34
- *
35
- * So the send collection is left exactly where it is, under exactly its
36
- * existing ids, and the container is a new collection above it:
37
- * `hosts/{hostId}/emailCampaigns/{campaignId}`. A send joins one by carrying
38
- * {@link CAMPAIGN_SEND_CONTAINER_FIELD}; a send written before containers
39
- * existed carries nothing, and {@link campaignListRows} presents it as a
40
- * container of one rather than hiding it.
41
- *
42
- * That last property is what makes this migration-free. There is no backfill
43
- * to run, no window in which a merchant's history is missing, and no id
44
- * rewritten anywhere.
20
+ * ## Both belong to the ORGANIZATION (AGL-3273)
21
+ *
22
+ * `orgs/{orgId}/emailCampaigns/{campaignId}` holds a CONTAINER: a name, a
23
+ * window, the lists it aims at. `orgs/{orgId}/campaigns/{sendId}` holds a
24
+ * SEND: one subject, one body, one audience, one set of counters.
25
+ *
26
+ * They lived under one site (`hosts/{hostId}/…`) until the audience side —
27
+ * contacts, lists, topics, sending domains — had long since become the
28
+ * org's. An organization's outbound sequences then had to be filed under a
29
+ * campaign that belonged to its marketing site, and the org-level Leads page
30
+ * could not name a campaign at all. Moving both up is what lets one campaign
31
+ * coordinate a push across every site, a sequence and the leads it produced.
32
+ *
33
+ * ## What stays a SITE fact, and where it is recorded
34
+ *
35
+ * A campaign's reach is {@link EmailCampaign.visibleTo}, the same scope
36
+ * tokens every org-owned resource carries: `['org']` is every site, and
37
+ * `['host:{id}', …]` is the sites it is placed on. It decides which sites'
38
+ * pickers offer the campaign and which scoped collaborators can read it —
39
+ * nothing else, because membership stays a field on the member.
40
+ *
41
+ * A send, by contrast, is always sent AS one site: that site's sender, the
42
+ * consent the person gave that site, the site's unsubscribe signature and
43
+ * its designs. {@link CAMPAIGN_SEND_HOST_FIELD} records which, and the
44
+ * send's `visibleTo` is that one site's token.
45
+ *
46
+ * ## Ids did not change, and that is load-bearing
47
+ *
48
+ * Every unsubscribe link that has ever gone out carries `hostId` and
49
+ * `cid={sendId}`, both inside the link's HMAC, and those emails sit in
50
+ * inboxes forever. So the move copied every document under its existing id,
51
+ * and every reader that starts from a link resolves the send through the
52
+ * site's org (`resolveCampaignSendRef` in `@aglyn/tenant-data-admin`), with the
53
+ * old site path as the fallback for a document the migration has not reached.
54
+ * A member's `campaignIds` names container ids, which likewise never moved.
55
+ *
56
+ * A send written before containers existed carries no
57
+ * {@link CAMPAIGN_SEND_CONTAINER_FIELD}, and {@link campaignListRows}
58
+ * presents it as a container of one rather than hiding it.
45
59
  *
46
60
  * ## Why the arithmetic is here
47
61
  *
@@ -53,6 +67,55 @@
53
67
  * therefore reports how many sends it could measure.
54
68
  */
55
69
  import { type CampaignRate, type CampaignStats } from './campaign-report';
70
+ /** The org collection holding campaign CONTAINERS. */
71
+ export declare const EMAIL_CAMPAIGNS_COLLECTION = "emailCampaigns";
72
+ /** The org collection holding SENDS — one document per email. */
73
+ export declare const CAMPAIGN_SENDS_COLLECTION = "campaigns";
74
+ /** `orgs/{orgId}/emailCampaigns`, as path segments. */
75
+ export declare function orgEmailCampaignsPath(orgId: string): [string, string, string];
76
+ /** `orgs/{orgId}/campaigns`, as path segments. */
77
+ export declare function orgCampaignSendsPath(orgId: string): [string, string, string];
78
+ /** `orgs/{orgId}/campaignSequenceReports`, as path segments. */
79
+ export declare function orgCampaignSequenceReportsPath(orgId: string): [string, string, string];
80
+ /**
81
+ * The field on a SEND naming the site it is sent AS.
82
+ *
83
+ * Required on every send written since AGL-3273. The sender, the consent
84
+ * group, the unsubscribe signature, the designs and the experiments all
85
+ * belong to that site, so a send with no site cannot be delivered.
86
+ */
87
+ export declare const CAMPAIGN_SEND_HOST_FIELD = "hostId";
88
+ /** The scope token naming every site in the org, as `scope-tokens.ts` spells it. */
89
+ export declare const CAMPAIGN_ORG_SCOPE = "org";
90
+ /** `host:{hostId}`, the scope token naming one site. */
91
+ export declare function campaignHostScope(hostId: string): string;
92
+ /**
93
+ * The `visibleTo` a send is stamped with: the one site it sends as.
94
+ *
95
+ * Not `['org']`. An org-wide member reads every send regardless, and a
96
+ * collaborator invited to a sibling site has no business reading who this
97
+ * site mailed.
98
+ */
99
+ export declare function campaignSendVisibleTo(hostId: string): string[];
100
+ /**
101
+ * The sites a container is placed on, or `null` when it is on every site.
102
+ *
103
+ * An absent or empty `visibleTo` reads as NO sites, for the reason
104
+ * `visibleToHost` in `scope-tokens.ts` gives: a document nobody scoped is
105
+ * not the same fact as one scoped to everyone, and hiding is the
106
+ * recoverable direction.
107
+ */
108
+ export declare function campaignSiteIds(campaign: Pick<EmailCampaign, 'visibleTo'> | null | undefined): string[] | null;
109
+ /** Whether a container is offered on this site. */
110
+ export declare function campaignPlacedOnHost(campaign: Pick<EmailCampaign, 'visibleTo'> | null | undefined, hostId: string): boolean;
111
+ /**
112
+ * The `visibleTo` a container is stamped with, from a site selection.
113
+ *
114
+ * `null` (or an empty selection) is every site. A selection is deduped and
115
+ * capped at thirty, the ceiling `array-contains-any` and the rules' `hasAny`
116
+ * both impose.
117
+ */
118
+ export declare function campaignVisibleTo(siteIds: readonly string[] | null): string[];
56
119
  /**
57
120
  * The field on a SEND naming the campaign it belongs to.
58
121
  *
@@ -64,7 +127,7 @@ export declare const CAMPAIGN_SEND_CONTAINER_FIELD = "emailCampaignId";
64
127
  /**
65
128
  * A campaign: the container, not a message.
66
129
  *
67
- * Stored at `hosts/{hostId}/emailCampaigns/{campaignId}`.
130
+ * Stored at `orgs/{orgId}/emailCampaigns/{campaignId}`.
68
131
  */
69
132
  export interface EmailCampaign {
70
133
  $id: string;
@@ -88,6 +151,11 @@ export interface EmailCampaign {
88
151
  * `marketing`.
89
152
  */
90
153
  topicId?: string;
154
+ /**
155
+ * The sites the campaign is placed on, as scope tokens: `['org']` for
156
+ * every site, `['host:{id}', …]` for a set. See {@link campaignSiteIds}.
157
+ */
158
+ visibleTo?: string[];
91
159
  createdAtMs?: number;
92
160
  createdBy?: string;
93
161
  deletedAt?: unknown;
@@ -104,6 +172,8 @@ export interface CampaignSend {
104
172
  segmentId?: string;
105
173
  /** Which container it belongs to, absent on a send written before them. */
106
174
  emailCampaignId?: string;
175
+ /** The site it is sent as. See {@link CAMPAIGN_SEND_HOST_FIELD}. */
176
+ hostId?: string;
107
177
  status?: string;
108
178
  sentAt?: {
109
179
  seconds?: number;
@@ -16,31 +16,45 @@
16
16
  */ /**
17
17
  * A CAMPAIGN IS A CONTAINER; A SEND IS ONE MESSAGE INSIDE IT.
18
18
  *
19
- * ## The two collections, and why there are two
19
+ * ## Both belong to the ORGANIZATION (AGL-3273)
20
20
  *
21
- * `hosts/{hostId}/campaigns/{sendId}` holds a SEND: one subject, one body,
22
- * one audience, one set of counters. That is what the collection has always
23
- * held, and it is why the container could not simply be that document grown
24
- * new fields.
21
+ * `orgs/{orgId}/emailCampaigns/{campaignId}` holds a CONTAINER: a name, a
22
+ * window, the lists it aims at. `orgs/{orgId}/campaigns/{sendId}` holds a
23
+ * SEND: one subject, one body, one audience, one set of counters.
25
24
  *
26
- * **Its ids are load-bearing outside this repo.** Every unsubscribe link that
27
- * has ever gone out carries `cid={sendId}`, those emails sit in inboxes
28
- * forever, and the `cid` is inside the link's HMAC — so a send id that stops
29
- * resolving is an opt-out that stops working, which is a compliance failure
30
- * rather than a broken page. `/marketing/campaigns/{sendId}` is likewise
31
- * linkable by design: a merchant pastes it into a message about last week's
32
- * send.
25
+ * They lived under one site (`hosts/{hostId}/…`) until the audience side —
26
+ * contacts, lists, topics, sending domains — had long since become the
27
+ * org's. An organization's outbound sequences then had to be filed under a
28
+ * campaign that belonged to its marketing site, and the org-level Leads page
29
+ * could not name a campaign at all. Moving both up is what lets one campaign
30
+ * coordinate a push across every site, a sequence and the leads it produced.
33
31
  *
34
- * So the send collection is left exactly where it is, under exactly its
35
- * existing ids, and the container is a new collection above it:
36
- * `hosts/{hostId}/emailCampaigns/{campaignId}`. A send joins one by carrying
37
- * {@link CAMPAIGN_SEND_CONTAINER_FIELD}; a send written before containers
38
- * existed carries nothing, and {@link campaignListRows} presents it as a
39
- * container of one rather than hiding it.
32
+ * ## What stays a SITE fact, and where it is recorded
40
33
  *
41
- * That last property is what makes this migration-free. There is no backfill
42
- * to run, no window in which a merchant's history is missing, and no id
43
- * rewritten anywhere.
34
+ * A campaign's reach is {@link EmailCampaign.visibleTo}, the same scope
35
+ * tokens every org-owned resource carries: `['org']` is every site, and
36
+ * `['host:{id}', …]` is the sites it is placed on. It decides which sites'
37
+ * pickers offer the campaign and which scoped collaborators can read it —
38
+ * nothing else, because membership stays a field on the member.
39
+ *
40
+ * A send, by contrast, is always sent AS one site: that site's sender, the
41
+ * consent the person gave that site, the site's unsubscribe signature and
42
+ * its designs. {@link CAMPAIGN_SEND_HOST_FIELD} records which, and the
43
+ * send's `visibleTo` is that one site's token.
44
+ *
45
+ * ## Ids did not change, and that is load-bearing
46
+ *
47
+ * Every unsubscribe link that has ever gone out carries `hostId` and
48
+ * `cid={sendId}`, both inside the link's HMAC, and those emails sit in
49
+ * inboxes forever. So the move copied every document under its existing id,
50
+ * and every reader that starts from a link resolves the send through the
51
+ * site's org (`resolveCampaignSendRef` in `@aglyn/tenant-data-admin`), with the
52
+ * old site path as the fallback for a document the migration has not reached.
53
+ * A member's `campaignIds` names container ids, which likewise never moved.
54
+ *
55
+ * A send written before containers existed carries no
56
+ * {@link CAMPAIGN_SEND_CONTAINER_FIELD}, and {@link campaignListRows}
57
+ * presents it as a container of one rather than hiding it.
44
58
  *
45
59
  * ## Why the arithmetic is here
46
60
  *
@@ -50,7 +64,90 @@
50
64
  * recorded a field and others never did — and summing those into one number
51
65
  * silently reports a partial total as a complete one. Every aggregate here
52
66
  * therefore reports how many sends it could measure.
53
- */ import { campaignRate } from "./campaign-report.js";
67
+ */ import { CAMPAIGN_SEQUENCE_REPORTS_COLLECTION, campaignRate } from "./campaign-report.js";
68
+ /** The org collection holding campaign CONTAINERS. */ export const EMAIL_CAMPAIGNS_COLLECTION = 'emailCampaigns';
69
+ /** The org collection holding SENDS — one document per email. */ export const CAMPAIGN_SENDS_COLLECTION = 'campaigns';
70
+ /** `orgs/{orgId}/emailCampaigns`, as path segments. */ export function orgEmailCampaignsPath(orgId) {
71
+ return [
72
+ 'orgs',
73
+ orgId,
74
+ EMAIL_CAMPAIGNS_COLLECTION
75
+ ];
76
+ }
77
+ /** `orgs/{orgId}/campaigns`, as path segments. */ export function orgCampaignSendsPath(orgId) {
78
+ return [
79
+ 'orgs',
80
+ orgId,
81
+ CAMPAIGN_SENDS_COLLECTION
82
+ ];
83
+ }
84
+ /** `orgs/{orgId}/campaignSequenceReports`, as path segments. */ export function orgCampaignSequenceReportsPath(orgId) {
85
+ return [
86
+ 'orgs',
87
+ orgId,
88
+ CAMPAIGN_SEQUENCE_REPORTS_COLLECTION
89
+ ];
90
+ }
91
+ /**
92
+ * The field on a SEND naming the site it is sent AS.
93
+ *
94
+ * Required on every send written since AGL-3273. The sender, the consent
95
+ * group, the unsubscribe signature, the designs and the experiments all
96
+ * belong to that site, so a send with no site cannot be delivered.
97
+ */ export const CAMPAIGN_SEND_HOST_FIELD = 'hostId';
98
+ /** The scope token naming every site in the org, as `scope-tokens.ts` spells it. */ export const CAMPAIGN_ORG_SCOPE = 'org';
99
+ /** `host:{hostId}`, the scope token naming one site. */ export function campaignHostScope(hostId) {
100
+ return `host:${hostId}`;
101
+ }
102
+ /**
103
+ * The `visibleTo` a send is stamped with: the one site it sends as.
104
+ *
105
+ * Not `['org']`. An org-wide member reads every send regardless, and a
106
+ * collaborator invited to a sibling site has no business reading who this
107
+ * site mailed.
108
+ */ export function campaignSendVisibleTo(hostId) {
109
+ return [
110
+ campaignHostScope(hostId)
111
+ ];
112
+ }
113
+ /**
114
+ * The sites a container is placed on, or `null` when it is on every site.
115
+ *
116
+ * An absent or empty `visibleTo` reads as NO sites, for the reason
117
+ * `visibleToHost` in `scope-tokens.ts` gives: a document nobody scoped is
118
+ * not the same fact as one scoped to everyone, and hiding is the
119
+ * recoverable direction.
120
+ */ export function campaignSiteIds(campaign) {
121
+ var _ref;
122
+ const tokens = (_ref = campaign == null ? void 0 : campaign.visibleTo) != null ? _ref : [];
123
+ if (tokens.includes(CAMPAIGN_ORG_SCOPE)) return null;
124
+ const ids = [];
125
+ for (const token of tokens){
126
+ if (typeof token === 'string' && token.startsWith('host:') && token.length > 5) {
127
+ ids.push(token.slice(5));
128
+ }
129
+ }
130
+ return ids;
131
+ }
132
+ /** Whether a container is offered on this site. */ export function campaignPlacedOnHost(campaign, hostId) {
133
+ const ids = campaignSiteIds(campaign);
134
+ return ids === null || ids.includes(hostId);
135
+ }
136
+ /**
137
+ * The `visibleTo` a container is stamped with, from a site selection.
138
+ *
139
+ * `null` (or an empty selection) is every site. A selection is deduped and
140
+ * capped at thirty, the ceiling `array-contains-any` and the rules' `hasAny`
141
+ * both impose.
142
+ */ export function campaignVisibleTo(siteIds) {
143
+ if (!siteIds || siteIds.length === 0) return [
144
+ CAMPAIGN_ORG_SCOPE
145
+ ];
146
+ const unique = [
147
+ ...new Set(siteIds.filter((id)=>typeof id === 'string' && id))
148
+ ];
149
+ return unique.slice(0, 30).map(campaignHostScope);
150
+ }
54
151
  /**
55
152
  * The field on a SEND naming the campaign it belongs to.
56
153
  *
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/shared/ui/email-campaigns/src/lib/model/campaign-container.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A CAMPAIGN IS A CONTAINER; A SEND IS ONE MESSAGE INSIDE IT.\n *\n * ## The two collections, and why there are two\n *\n * `hosts/{hostId}/campaigns/{sendId}` holds a SEND: one subject, one body,\n * one audience, one set of counters. That is what the collection has always\n * held, and it is why the container could not simply be that document grown\n * new fields.\n *\n * **Its ids are load-bearing outside this repo.** Every unsubscribe link that\n * has ever gone out carries `cid={sendId}`, those emails sit in inboxes\n * forever, and the `cid` is inside the link's HMAC — so a send id that stops\n * resolving is an opt-out that stops working, which is a compliance failure\n * rather than a broken page. `/marketing/campaigns/{sendId}` is likewise\n * linkable by design: a merchant pastes it into a message about last week's\n * send.\n *\n * So the send collection is left exactly where it is, under exactly its\n * existing ids, and the container is a new collection above it:\n * `hosts/{hostId}/emailCampaigns/{campaignId}`. A send joins one by carrying\n * {@link CAMPAIGN_SEND_CONTAINER_FIELD}; a send written before containers\n * existed carries nothing, and {@link campaignListRows} presents it as a\n * container of one rather than hiding it.\n *\n * That last property is what makes this migration-free. There is no backfill\n * to run, no window in which a merchant's history is missing, and no id\n * rewritten anywhere.\n *\n * ## Why the arithmetic is here\n *\n * The same reason `campaign-report.ts` gives for the per-send rates: a\n * denominator chosen in JSX is a denominator nobody tests. Aggregating across\n * sends adds one problem the single-send report does not have — some sends\n * recorded a field and others never did — and summing those into one number\n * silently reports a partial total as a complete one. Every aggregate here\n * therefore reports how many sends it could measure.\n */\n\nimport {\n campaignRate,\n type CampaignRate,\n type CampaignStats,\n} from './campaign-report'\n\n/**\n * The field on a SEND naming the campaign it belongs to.\n *\n * Not `campaignId`: on a send document that name already means the send's own\n * id — it is what `cid` carries and what the report route addresses — and one\n * word meaning both would be read into the other on the first edit.\n */\nexport const CAMPAIGN_SEND_CONTAINER_FIELD = 'emailCampaignId'\n\n/**\n * A campaign: the container, not a message.\n *\n * Stored at `hosts/{hostId}/emailCampaigns/{campaignId}`.\n */\nexport interface EmailCampaign {\n $id: string\n /** What the merchant called it. */\n name: string\n /** When the campaign window opens. Null for a campaign with no dates. */\n startAtMs?: number | null\n /** When it closes. Null for an open-ended campaign. */\n endAtMs?: number | null\n /** Org email lists this campaign is aimed at, by list id. */\n listIds?: string[]\n /**\n * The stream this campaign's emails open on.\n *\n * A DEFAULT, not a constraint. The topic decides who a send skips, what the\n * preference page linked from the footer highlights, and which stream a\n * resulting opt-out is recorded against — all facts about one MESSAGE, and\n * one campaign may legitimately carry a newsletter and a promotion. So the\n * composer's picker is what the send records; this is what the picker opens\n * on, which is what stops a \"Sales\" campaign quietly mailing under\n * `marketing`.\n */\n topicId?: string\n createdAtMs?: number\n createdBy?: string\n deletedAt?: unknown\n}\n\n/** One send, as much of it as a list or a rollup needs. */\nexport interface CampaignSend {\n $id: string\n subject?: string\n /** The audience KIND: `'leads'`, `'members'`, `'segment'`, `'list'`. */\n audience?: string\n /** The list this send addressed, when the kind is `'list'`. */\n listId?: string\n /** The segment this send addressed, when the kind is `'segment'`. */\n segmentId?: string\n /** Which container it belongs to, absent on a send written before them. */\n emailCampaignId?: string\n status?: string\n sentAt?: { seconds?: number } | null\n sendAtMs?: number\n /**\n * When the record was minted, stamped by every writer that creates one.\n *\n * Absent on a send written before the stamp existed. The lists that draw\n * drafts beside sends order on it through `emailListTimeMs`, which is why\n * it is here rather than only on the loose record shape: a draft carries\n * neither `sentAt` nor `sendAtMs`, so this is the only time it has.\n */\n createdAtMs?: number\n stats?: CampaignStats\n /** How far a send that goes out over several batches has got. */\n resume?: CampaignResume\n}\n\n/**\n * The batch state the sender writes on an email that is still going out.\n *\n * Absent on every send that finished in one batch, and on every send that\n * predates batching — which is why {@link campaignSendProgress} treats a\n * missing record as \"this is not a batched send\" rather than as zero.\n */\nexport interface CampaignResume {\n /** People the email has resolved and not yet addressed. */\n remaining?: number\n /** Batches it has run. */\n batch?: number\n /** When the next batch may go, ms. Zero when there is not going to be one. */\n nextAtMs?: number\n /** Why it stopped short, when it did. */\n stop?: string\n}\n\n/**\n * WHAT A SEND IS ACTUALLY DOING, for a row that would otherwise lie.\n *\n * An email larger than one send may carry is delivered over several batches,\n * and between them it is stored as `scheduled` — the state the processor\n * claims, and the only one that resumes it without a second index and a\n * second query. Read literally, that is a row saying \"not sent yet\" about an\n * email that has already put five hundred messages in five hundred inboxes.\n *\n * So the stored fields are not the sentence. This is: it takes the status,\n * the delivered count and the batch record, and answers what a person needs\n * to see. Derived at read time and never persisted, exactly as\n * `campaignWindowState` beside it is, because it is a description of stored\n * facts and not a fact of its own.\n *\n * ## The four states, and which stored shape each one is\n *\n * - `pending` — `scheduled`, nothing delivered. A campaign waiting for its\n * time. This is what `scheduled` meant before batching and still does.\n * - `sending` — `scheduled` or `sending` with something delivered and more to\n * come. The state this function exists for.\n * - `sent` — finished, whether in one batch or six.\n * - `stopped` — finished with people it never addressed: canceled mid-flight,\n * failed mid-flight, or stopped by the batch guard. The count is what makes\n * this legible rather than alarming — an email that reached 2,400 of 3,000\n * and stopped is a different conversation from one that reached nobody.\n */\nexport type CampaignSendProgressState =\n | 'pending'\n | 'sending'\n | 'sent'\n | 'stopped'\n\nexport interface CampaignSendProgress {\n state: CampaignSendProgressState\n /** Messages this email has delivered. */\n reached: number\n /**\n * The audience it is working through, when one was recorded. Null when the\n * send never recorded an audience size, which is every send that predates\n * the figure — reported as null rather than as `reached` so a surface does\n * not present a floor as a total.\n */\n audience: number | null\n /** People it has resolved and not yet addressed. */\n remaining: number\n /** Batches it has run. Zero for a send that never batched. */\n batch: number\n /** When the next batch may go, ms. Zero unless {@link state} is `sending`. */\n nextAtMs: number\n /** One line a surface may show verbatim. */\n label: string\n}\n\n/** A stored count as a non-negative integer, or 0. */\nfunction progressCount(raw: unknown): number {\n const value = Math.floor(Number(raw))\n return Number.isFinite(value) && value > 0 ? value : 0\n}\n\nexport function campaignSendProgress(\n send: CampaignSend | null | undefined,\n): CampaignSendProgress {\n const status = String(send?.status ?? 'sent')\n const reached = progressCount(send?.stats?.sent)\n const rawAudience = send?.stats?.audienceSize\n const audience =\n rawAudience === undefined || rawAudience === null\n ? null\n : progressCount(rawAudience)\n const resume = send?.resume\n const remaining = progressCount(resume?.remaining)\n const batch = progressCount(resume?.batch)\n const nextAtMs = progressCount(resume?.nextAtMs)\n const of = audience !== null ? ` of ${audience.toLocaleString()}` : ''\n\n // Still going: more to address, and a run that will address it. A campaign\n // a merchant CANCELED is not still going however much is left, which is why\n // the status is read before the remainder.\n if (\n remaining > 0 &&\n nextAtMs > 0 &&\n (status === 'scheduled' || status === 'sending')\n ) {\n return {\n state: 'sending',\n reached,\n audience,\n remaining,\n batch,\n nextAtMs,\n label: `Sending — reached ${reached.toLocaleString()}${of}`,\n }\n }\n // Waiting for its time, with nothing delivered. The pre-batching meaning of\n // `scheduled`, and still the common one.\n if ((status === 'scheduled' || status === 'sending') && reached === 0) {\n return {\n state: 'pending',\n reached: 0,\n audience,\n remaining,\n batch,\n nextAtMs: 0,\n label: status === 'sending' ? 'Sending' : 'Scheduled',\n }\n }\n if (remaining > 0) {\n const why =\n status === 'canceled'\n ? 'canceled'\n : status === 'failed'\n ? 'stopped by an error'\n : 'stopped'\n return {\n state: 'stopped',\n reached,\n audience,\n remaining,\n batch,\n nextAtMs: 0,\n label:\n `Reached ${reached.toLocaleString()}${of} — ${why} with ` +\n `${remaining.toLocaleString()} not addressed`,\n }\n }\n return {\n state: 'sent',\n reached,\n audience,\n remaining: 0,\n batch,\n nextAtMs: 0,\n label:\n batch > 1\n ? `Sent to ${reached.toLocaleString()}${of} over ${batch} runs`\n : `Sent to ${reached.toLocaleString()}${of}`,\n }\n}\n\n/**\n * What a ROW says about one email, in one word and one line.\n *\n * {@link campaignSendProgress} answers what a send is DOING, and a draft is\n * not doing anything: it has no status the progress states cover, and — since\n * an absent status reads as `sent` and a draft has no counters — asking it\n * about one answers \"Sent to 0\", which is the worst available sentence about\n * an email nobody has written yet. So the draft is settled here and\n * everything else is deferred, unchanged, to the derivation that owns it.\n *\n * One helper rather than the same two-line branch on four surfaces. The\n * campaigns table, the emails list, an email's own page and a campaign's\n * emails table all draw this, and four copies is how three of them come to\n * say \"Scheduled\" about a campaign that has delivered five hundred messages.\n */\nexport type CampaignSendDisplayState = 'draft' | CampaignSendProgressState\n\nexport interface CampaignSendDisplay {\n state: CampaignSendDisplayState\n /** One line a surface may show verbatim. */\n label: string\n /** The progress underneath, for a surface that wants the figures. */\n progress: CampaignSendProgress\n}\n\nexport function campaignSendDisplay(\n send: CampaignSend | null | undefined,\n): CampaignSendDisplay {\n const progress = campaignSendProgress(send)\n if (String(send?.status ?? '') === 'draft') {\n return { state: 'draft', label: 'Draft', progress }\n }\n return { state: progress.state, label: progress.label, progress }\n}\n\n/**\n * Whether this email is between batches, with more of its audience to reach.\n *\n * The one question two controls on an email's page turn on. It is stored as\n * `scheduled` — the state the processor claims — so a surface reading the\n * status alone offers \"Send now\" on a campaign that is already going out, and\n * `sendNow` re-resolves the WHOLE audience rather than continuing: everyone\n * already reached would receive a second copy under the same `cid`.\n */\nexport function campaignSendIsMidFlight(\n send: CampaignSend | null | undefined,\n): boolean {\n return campaignSendProgress(send).state === 'sending'\n}\n\n/**\n * The lists ONE SEND addressed — which can be narrower than the lists its\n * campaign is aimed at.\n *\n * A campaign holds the lists a merchant plans to reach; each send inside it\n * picks one audience, and that audience may be a segment or the site's leads\n * rather than any of them. Answering from the send is therefore the only\n * honest answer for a send's own detail page.\n *\n * An array for a document that stores one id, deliberately: the question\n * \"which lists did this reach\" has a plural answer everywhere it is asked,\n * and a caller that unwraps a single id today is a caller to revisit if a\n * send ever addresses two.\n */\nexport function campaignSendListIds(send: CampaignSend): string[] {\n return send.audience === 'list' && send.listId ? [send.listId] : []\n}\n\n/**\n * A number summed across sends, with how much of the campaign it covers.\n *\n * `value` is `null` when NO send recorded the field — which is not zero, for\n * the reason `campaign-report.ts` gives at length: an unrecorded delivery\n * count and a delivery count of zero lead a merchant to opposite conclusions\n * about their sending domain.\n *\n * `recorded` below `sends` means the total is a floor. A campaign whose\n * older sends predate the delivery webhook has a real number that describes\n * part of itself, and saying which part is the difference between a total and\n * a guess.\n */\nexport interface CampaignAggregate {\n value: number | null\n /** Sends that recorded this field. */\n recorded: number\n /** Sends in the campaign. */\n sends: number\n}\n\n/** Every rolled-up figure for one campaign. */\nexport interface CampaignRollup {\n /** Sends that have actually gone out. */\n sends: number\n /** Sends still waiting for their send time, having delivered nothing. */\n scheduled: number\n /**\n * Sends part way through an audience larger than one batch.\n *\n * Counted apart from `scheduled` and from `sends`, because it is neither:\n * mail has gone out, and more is going to. Both of those are facts a\n * merchant reading a campaign row needs, and the stored status carries\n * only the first.\n */\n sending: number\n /**\n * Emails that have been created and not yet written or sent.\n *\n * Counted apart from `sends` and from `scheduled`, because a draft is\n * neither: it has mailed nobody, and it is not on the clock to.\n */\n drafts: number\n addressed: CampaignAggregate\n sent: CampaignAggregate\n delivered: CampaignAggregate\n opens: CampaignAggregate\n uniqueOpens: CampaignAggregate\n clicks: CampaignAggregate\n uniqueClicks: CampaignAggregate\n bounced: CampaignAggregate\n complained: CampaignAggregate\n unsubscribes: CampaignAggregate\n /** Distinct openers over delivered, across every send that recorded both. */\n openRate: CampaignRate | null\n /** Distinct clickers over delivered. */\n clickRate: CampaignRate | null\n /** Unsubscribes over delivered. */\n unsubscribeRate: CampaignRate | null\n /** The most recent send time in the campaign, for ordering a list. */\n lastSentAtMs: number | null\n}\n\nconst aggregate = (\n sends: CampaignSend[],\n read: (stats: CampaignStats) => number | undefined,\n): CampaignAggregate => {\n let total = 0\n let recorded = 0\n for (const send of sends) {\n const value = read(send.stats ?? {})\n // `undefined` is \"this send never recorded it\"; a recorded 0 counts as\n // measured, and moves `recorded` without moving the total.\n if (value === undefined || value === null) continue\n const numeric = Number(value)\n if (!Number.isFinite(numeric)) continue\n total += numeric\n recorded += 1\n }\n return { value: recorded ? total : null, recorded, sends: sends.length }\n}\n\n/** When a send happened, in epoch milliseconds, or null. */\nexport function campaignSendAtMs(send: CampaignSend): number | null {\n const seconds = send.sentAt?.seconds\n if (typeof seconds === 'number') return seconds * 1000\n if (typeof send.sendAtMs === 'number') return send.sendAtMs\n return null\n}\n\n/**\n * Rolls a campaign's sends into one set of figures.\n *\n * Rates are taken over the sends that recorded BOTH sides, so a campaign\n * whose first send predates the delivery webhook reports the open rate of the\n * sends that can be measured rather than one deflated by a send with no\n * denominator.\n */\nexport function campaignRollup(sends: CampaignSend[]): CampaignRollup {\n /*==========================================\n * ONLY MAIL THAT HAS GONE OUT IS A SEND.\n *\n * An email exists from the moment it is created, so this collection now\n * holds records in three states that have mailed nobody — `draft`,\n * `scheduled` and the `sending` claim — and every figure below is about\n * mail that was delivered.\n *\n * Two separate faults if they are left in. The COUNT would report a\n * campaign as having sent three emails when it has sent two and is still\n * writing the third. And every aggregate carries `sends` as the denominator\n * of its own \"recorded by N of M\" label, so an unsent record would enlarge\n * the M — publishing a coverage figure that says the campaign is missing\n * data it was never going to have.\n *=========================================*/\n /*\n * A SEND THAT IS STILL GOING HAS STILL GONE.\n *\n * `emailIsUnsent` reads the stored status, and an email delivering an\n * audience larger than one batch is stored as `scheduled` between runs —\n * so reading it literally drops a send that has put five hundred messages\n * in five hundred inboxes out of every total on the campaign, and counts it\n * under \"scheduled\" as though nothing had happened. `campaignSendProgress`\n * is what tells \"waiting for its time\" from \"part way through\", and only\n * the first is genuinely unsent.\n *\n * A DRAFT is settled by the status because the progress states do not cover\n * it — see `campaignSendDisplay`.\n */\n const notYet = (send: CampaignSend): boolean =>\n String(send.status ?? '') === 'draft' ||\n campaignSendProgress(send).state === 'pending'\n const gone = sends.filter((send) => !notYet(send))\n const measurable = sends.filter(\n (send) => send.stats?.delivered !== undefined,\n )\n const deliveredTotal = aggregate(measurable, (stats) => stats.delivered)\n return {\n sends: gone.filter((send) => send.status !== 'canceled').length,\n // Waiting for its time with nothing delivered — which is what\n // \"scheduled\" meant before an email could be delivered over several runs,\n // and is now narrower than the stored status of that name.\n scheduled: sends.filter(\n (send) => campaignSendProgress(send).state === 'pending',\n ).length,\n sending: sends.filter(\n (send) => campaignSendProgress(send).state === 'sending',\n ).length,\n drafts: sends.filter((send) => send.status === 'draft').length,\n addressed: aggregate(gone, (stats) => stats.recipients),\n sent: aggregate(gone, (stats) => stats.sent),\n delivered: aggregate(gone, (stats) => stats.delivered),\n opens: aggregate(gone, (stats) => stats.opens),\n uniqueOpens: aggregate(gone, (stats) => stats.uniqueOpens),\n clicks: aggregate(gone, (stats) => stats.clicks),\n uniqueClicks: aggregate(gone, (stats) => stats.uniqueClicks),\n bounced: aggregate(gone, (stats) => stats.bounced),\n complained: aggregate(gone, (stats) => stats.complained),\n unsubscribes: aggregate(gone, (stats) => stats.unsubscribes),\n openRate: campaignRate(\n aggregate(measurable, (stats) => stats.uniqueOpens).value ?? undefined,\n deliveredTotal.value ?? undefined,\n 'delivered',\n ),\n clickRate: campaignRate(\n aggregate(measurable, (stats) => stats.uniqueClicks).value ?? undefined,\n deliveredTotal.value ?? undefined,\n 'delivered',\n ),\n unsubscribeRate: campaignRate(\n aggregate(measurable, (stats) => stats.unsubscribes).value ?? undefined,\n deliveredTotal.value ?? undefined,\n 'delivered',\n ),\n lastSentAtMs: sends.reduce<number | null>((latest, send) => {\n const at = campaignSendAtMs(send)\n return at !== null && (latest === null || at > latest) ? at : latest\n }, null),\n }\n}\n\n/**\n * Where a campaign stands against its own window.\n *\n * Derived at read time and never persisted — the `status` values on a SEND\n * (`sent`, `scheduled`, `canceled`, `failed`) are stored strings that a\n * processor branches on, and a display state sharing those spellings would\n * eventually be written back.\n */\nexport type CampaignWindowState = 'undated' | 'upcoming' | 'running' | 'ended'\n\nexport function campaignWindowState(\n campaign: Pick<EmailCampaign, 'startAtMs' | 'endAtMs'>,\n nowMs: number,\n): CampaignWindowState {\n const start = campaign.startAtMs ?? null\n const end = campaign.endAtMs ?? null\n if (start === null && end === null) return 'undated'\n if (start !== null && nowMs < start) return 'upcoming'\n if (end !== null && nowMs > end) return 'ended'\n return 'running'\n}\n\n/** One row of the campaigns table. */\nexport interface CampaignListRow {\n /** The id the detail route resolves — a container id, or a send id. */\n id: string\n name: string\n /**\n * True when this row IS a send with no container.\n *\n * A campaign sent before containers existed is shown as a campaign of one\n * rather than dropped from the list, and the detail route falls back to the\n * send's own report for it. Nothing about that send is rewritten.\n */\n legacy: boolean\n startAtMs: number | null\n endAtMs: number | null\n listIds: string[]\n sends: CampaignSend[]\n rollup: CampaignRollup\n windowState: CampaignWindowState\n /** For ordering: the campaign's start, else its most recent send. */\n atMs: number | null\n}\n\n/**\n * The campaigns table's rows: every container, plus every send that belongs\n * to none.\n *\n * The second half is what makes the container additive. A merchant's history\n * is the sends they already have; a list that showed only containers would\n * read as an empty product on the day this shipped, and a backfill that\n * adopted each old send into a container of one would rewrite documents whose\n * ids are cited by mail already delivered. Adopting them AT READ TIME costs a\n * pass over a list already in memory and rewrites nothing.\n *\n * Newest first, on the start date where there is one and the last send\n * otherwise. Rows with no date at all sort last: they are campaigns nobody\n * has scheduled or sent, and dating them from nothing would be an invention.\n */\nexport function campaignListRows(\n campaigns: EmailCampaign[],\n sends: CampaignSend[],\n nowMs: number,\n): CampaignListRow[] {\n const byCampaign = new Map<string, CampaignSend[]>()\n const orphans: CampaignSend[] = []\n for (const send of sends) {\n const containerId = send.emailCampaignId\n if (!containerId) {\n orphans.push(send)\n continue\n }\n const existing = byCampaign.get(containerId)\n if (existing) existing.push(send)\n else byCampaign.set(containerId, [send])\n }\n\n const rows: CampaignListRow[] = campaigns.map((campaign) => {\n const own = byCampaign.get(campaign.$id) ?? []\n const rollup = campaignRollup(own)\n return {\n id: campaign.$id,\n name: campaign.name || 'Untitled campaign',\n legacy: false,\n startAtMs: campaign.startAtMs ?? null,\n endAtMs: campaign.endAtMs ?? null,\n listIds: campaign.listIds ?? [],\n sends: own,\n rollup,\n windowState: campaignWindowState(campaign, nowMs),\n atMs: campaign.startAtMs ?? rollup.lastSentAtMs ?? null,\n }\n })\n\n for (const send of orphans) {\n const rollup = campaignRollup([send])\n const at = campaignSendAtMs(send)\n rows.push({\n id: send.$id,\n name: send.subject || 'Untitled campaign',\n legacy: true,\n startAtMs: at,\n endAtMs: at,\n listIds: [],\n sends: [send],\n rollup,\n // A send has no window of its own; it happened, or it is going to.\n windowState:\n send.status === 'scheduled'\n ? 'upcoming'\n : at === null\n ? 'undated'\n : 'ended',\n atMs: at,\n })\n }\n\n return rows.sort((a, b) => {\n if (a.atMs === null && b.atMs === null) return a.name.localeCompare(b.name)\n if (a.atMs === null) return 1\n if (b.atMs === null) return -1\n return b.atMs - a.atMs\n })\n}\n"],"names":["campaignRate","CAMPAIGN_SEND_CONTAINER_FIELD","progressCount","raw","value","Math","floor","Number","isFinite","campaignSendProgress","send","status","String","reached","stats","sent","rawAudience","audienceSize","audience","undefined","resume","remaining","batch","nextAtMs","of","toLocaleString","state","label","why","campaignSendDisplay","progress","campaignSendIsMidFlight","campaignSendListIds","listId","aggregate","sends","read","total","recorded","numeric","length","campaignSendAtMs","seconds","sentAt","sendAtMs","campaignRollup","deliveredTotal","notYet","gone","filter","measurable","delivered","scheduled","sending","drafts","addressed","recipients","opens","uniqueOpens","clicks","uniqueClicks","bounced","complained","unsubscribes","openRate","clickRate","unsubscribeRate","lastSentAtMs","reduce","latest","at","campaignWindowState","campaign","nowMs","start","startAtMs","end","endAtMs","campaignListRows","campaigns","byCampaign","Map","orphans","containerId","emailCampaignId","push","existing","get","set","rows","map","own","$id","rollup","id","name","legacy","listIds","windowState","atMs","subject","sort","a","b","localeCompare"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCC,GAED,SACEA,YAAY,QAGP,uBAAmB;AAE1B;;;;;;CAMC,GACD,OAAO,MAAMC,gCAAgC,kBAAiB;AAuI9D,oDAAoD,GACpD,SAASC,cAAcC,GAAY;IACjC,MAAMC,QAAQC,KAAKC,KAAK,CAACC,OAAOJ;IAChC,OAAOI,OAAOC,QAAQ,CAACJ,UAAUA,QAAQ,IAAIA,QAAQ;AACvD;AAEA,OAAO,SAASK,qBACdC,IAAqC;;QAGPA,aACVA;IAFpB,MAAMC,SAASC,eAAOF,wBAAAA,KAAMC,MAAM,mBAAI;IACtC,MAAME,UAAUX,cAAcQ,yBAAAA,cAAAA,KAAMI,KAAK,qBAAXJ,YAAaK,IAAI;IAC/C,MAAMC,cAAcN,yBAAAA,eAAAA,KAAMI,KAAK,qBAAXJ,aAAaO,YAAY;IAC7C,MAAMC,WACJF,gBAAgBG,aAAaH,gBAAgB,OACzC,OACAd,cAAcc;IACpB,MAAMI,SAASV,wBAAAA,KAAMU,MAAM;IAC3B,MAAMC,YAAYnB,cA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D,KAAK7B,iBAAiB/B;QAC5B+E,KAAKJ,IAAI,CAAC;YACRS,IAAIpF,KAAKkF,GAAG;YACZG,MAAMrF,KAAK0F,OAAO,IAAI;YACtBJ,QAAQ;YACRrB,WAAWL;YACXO,SAASP;YACT2B,SAAS,EAAE;YACX9D,OAAO;gBAACzB;aAAK;YACbmF;YACA,mEAAmE;YACnEK,aACExF,KAAKC,MAAM,KAAK,cACZ,aACA2D,OAAO,OACL,YACA;YACR6B,MAAM7B;QACR;IACF;IAEA,OAAOmB,KAAKY,IAAI,CAAC,CAACC,GAAGC;QACnB,IAAID,EAAEH,IAAI,KAAK,QAAQI,EAAEJ,IAAI,KAAK,MAAM,OAAOG,EAAEP,IAAI,CAACS,aAAa,CAACD,EAAER,IAAI;QAC1E,IAAIO,EAAEH,IAAI,KAAK,MAAM,OAAO;QAC5B,IAAII,EAAEJ,IAAI,KAAK,MAAM,OAAO,CAAC;QAC7B,OAAOI,EAAEJ,IAAI,GAAGG,EAAEH,IAAI;IACxB;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/shared/ui/email-campaigns/src/lib/model/campaign-container.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A CAMPAIGN IS A CONTAINER; A SEND IS ONE MESSAGE INSIDE IT.\n *\n * ## Both belong to the ORGANIZATION (AGL-3273)\n *\n * `orgs/{orgId}/emailCampaigns/{campaignId}` holds a CONTAINER: a name, a\n * window, the lists it aims at. `orgs/{orgId}/campaigns/{sendId}` holds a\n * SEND: one subject, one body, one audience, one set of counters.\n *\n * They lived under one site (`hosts/{hostId}/…`) until the audience side —\n * contacts, lists, topics, sending domains — had long since become the\n * org's. An organization's outbound sequences then had to be filed under a\n * campaign that belonged to its marketing site, and the org-level Leads page\n * could not name a campaign at all. Moving both up is what lets one campaign\n * coordinate a push across every site, a sequence and the leads it produced.\n *\n * ## What stays a SITE fact, and where it is recorded\n *\n * A campaign's reach is {@link EmailCampaign.visibleTo}, the same scope\n * tokens every org-owned resource carries: `['org']` is every site, and\n * `['host:{id}', …]` is the sites it is placed on. It decides which sites'\n * pickers offer the campaign and which scoped collaborators can read it —\n * nothing else, because membership stays a field on the member.\n *\n * A send, by contrast, is always sent AS one site: that site's sender, the\n * consent the person gave that site, the site's unsubscribe signature and\n * its designs. {@link CAMPAIGN_SEND_HOST_FIELD} records which, and the\n * send's `visibleTo` is that one site's token.\n *\n * ## Ids did not change, and that is load-bearing\n *\n * Every unsubscribe link that has ever gone out carries `hostId` and\n * `cid={sendId}`, both inside the link's HMAC, and those emails sit in\n * inboxes forever. So the move copied every document under its existing id,\n * and every reader that starts from a link resolves the send through the\n * site's org (`resolveCampaignSendRef` in `@aglyn/tenant-data-admin`), with the\n * old site path as the fallback for a document the migration has not reached.\n * A member's `campaignIds` names container ids, which likewise never moved.\n *\n * A send written before containers existed carries no\n * {@link CAMPAIGN_SEND_CONTAINER_FIELD}, and {@link campaignListRows}\n * presents it as a container of one rather than hiding it.\n *\n * ## Why the arithmetic is here\n *\n * The same reason `campaign-report.ts` gives for the per-send rates: a\n * denominator chosen in JSX is a denominator nobody tests. Aggregating across\n * sends adds one problem the single-send report does not have — some sends\n * recorded a field and others never did — and summing those into one number\n * silently reports a partial total as a complete one. Every aggregate here\n * therefore reports how many sends it could measure.\n */\n\nimport {\n CAMPAIGN_SEQUENCE_REPORTS_COLLECTION,\n campaignRate,\n type CampaignRate,\n type CampaignStats,\n} from './campaign-report'\n\n/** The org collection holding campaign CONTAINERS. */\nexport const EMAIL_CAMPAIGNS_COLLECTION = 'emailCampaigns'\n\n/** The org collection holding SENDS — one document per email. */\nexport const CAMPAIGN_SENDS_COLLECTION = 'campaigns'\n\n/** `orgs/{orgId}/emailCampaigns`, as path segments. */\nexport function orgEmailCampaignsPath(orgId: string): [string, string, string] {\n return ['orgs', orgId, EMAIL_CAMPAIGNS_COLLECTION]\n}\n\n/** `orgs/{orgId}/campaigns`, as path segments. */\nexport function orgCampaignSendsPath(orgId: string): [string, string, string] {\n return ['orgs', orgId, CAMPAIGN_SENDS_COLLECTION]\n}\n\n/** `orgs/{orgId}/campaignSequenceReports`, as path segments. */\nexport function orgCampaignSequenceReportsPath(\n orgId: string,\n): [string, string, string] {\n return ['orgs', orgId, CAMPAIGN_SEQUENCE_REPORTS_COLLECTION]\n}\n\n/**\n * The field on a SEND naming the site it is sent AS.\n *\n * Required on every send written since AGL-3273. The sender, the consent\n * group, the unsubscribe signature, the designs and the experiments all\n * belong to that site, so a send with no site cannot be delivered.\n */\nexport const CAMPAIGN_SEND_HOST_FIELD = 'hostId'\n\n/** The scope token naming every site in the org, as `scope-tokens.ts` spells it. */\nexport const CAMPAIGN_ORG_SCOPE = 'org'\n\n/** `host:{hostId}`, the scope token naming one site. */\nexport function campaignHostScope(hostId: string): string {\n return `host:${hostId}`\n}\n\n/**\n * The `visibleTo` a send is stamped with: the one site it sends as.\n *\n * Not `['org']`. An org-wide member reads every send regardless, and a\n * collaborator invited to a sibling site has no business reading who this\n * site mailed.\n */\nexport function campaignSendVisibleTo(hostId: string): string[] {\n return [campaignHostScope(hostId)]\n}\n\n/**\n * The sites a container is placed on, or `null` when it is on every site.\n *\n * An absent or empty `visibleTo` reads as NO sites, for the reason\n * `visibleToHost` in `scope-tokens.ts` gives: a document nobody scoped is\n * not the same fact as one scoped to everyone, and hiding is the\n * recoverable direction.\n */\nexport function campaignSiteIds(\n campaign: Pick<EmailCampaign, 'visibleTo'> | null | undefined,\n): string[] | null {\n const tokens = campaign?.visibleTo ?? []\n if (tokens.includes(CAMPAIGN_ORG_SCOPE)) return null\n const ids: string[] = []\n for (const token of tokens) {\n if (typeof token === 'string' && token.startsWith('host:') && token.length > 5) {\n ids.push(token.slice(5))\n }\n }\n return ids\n}\n\n/** Whether a container is offered on this site. */\nexport function campaignPlacedOnHost(\n campaign: Pick<EmailCampaign, 'visibleTo'> | null | undefined,\n hostId: string,\n): boolean {\n const ids = campaignSiteIds(campaign)\n return ids === null || ids.includes(hostId)\n}\n\n/**\n * The `visibleTo` a container is stamped with, from a site selection.\n *\n * `null` (or an empty selection) is every site. A selection is deduped and\n * capped at thirty, the ceiling `array-contains-any` and the rules' `hasAny`\n * both impose.\n */\nexport function campaignVisibleTo(siteIds: readonly string[] | null): string[] {\n if (!siteIds || siteIds.length === 0) return [CAMPAIGN_ORG_SCOPE]\n const unique = [...new Set(siteIds.filter((id) => typeof id === 'string' && id))]\n return unique.slice(0, 30).map(campaignHostScope)\n}\n\n/**\n * The field on a SEND naming the campaign it belongs to.\n *\n * Not `campaignId`: on a send document that name already means the send's own\n * id — it is what `cid` carries and what the report route addresses — and one\n * word meaning both would be read into the other on the first edit.\n */\nexport const CAMPAIGN_SEND_CONTAINER_FIELD = 'emailCampaignId'\n\n/**\n * A campaign: the container, not a message.\n *\n * Stored at `orgs/{orgId}/emailCampaigns/{campaignId}`.\n */\nexport interface EmailCampaign {\n $id: string\n /** What the merchant called it. */\n name: string\n /** When the campaign window opens. Null for a campaign with no dates. */\n startAtMs?: number | null\n /** When it closes. Null for an open-ended campaign. */\n endAtMs?: number | null\n /** Org email lists this campaign is aimed at, by list id. */\n listIds?: string[]\n /**\n * The stream this campaign's emails open on.\n *\n * A DEFAULT, not a constraint. The topic decides who a send skips, what the\n * preference page linked from the footer highlights, and which stream a\n * resulting opt-out is recorded against — all facts about one MESSAGE, and\n * one campaign may legitimately carry a newsletter and a promotion. So the\n * composer's picker is what the send records; this is what the picker opens\n * on, which is what stops a \"Sales\" campaign quietly mailing under\n * `marketing`.\n */\n topicId?: string\n /**\n * The sites the campaign is placed on, as scope tokens: `['org']` for\n * every site, `['host:{id}', …]` for a set. See {@link campaignSiteIds}.\n */\n visibleTo?: string[]\n createdAtMs?: number\n createdBy?: string\n deletedAt?: unknown\n}\n\n/** One send, as much of it as a list or a rollup needs. */\nexport interface CampaignSend {\n $id: string\n subject?: string\n /** The audience KIND: `'leads'`, `'members'`, `'segment'`, `'list'`. */\n audience?: string\n /** The list this send addressed, when the kind is `'list'`. */\n listId?: string\n /** The segment this send addressed, when the kind is `'segment'`. */\n segmentId?: string\n /** Which container it belongs to, absent on a send written before them. */\n emailCampaignId?: string\n /** The site it is sent as. See {@link CAMPAIGN_SEND_HOST_FIELD}. */\n hostId?: string\n status?: string\n sentAt?: { seconds?: number } | null\n sendAtMs?: number\n /**\n * When the record was minted, stamped by every writer that creates one.\n *\n * Absent on a send written before the stamp existed. The lists that draw\n * drafts beside sends order on it through `emailListTimeMs`, which is why\n * it is here rather than only on the loose record shape: a draft carries\n * neither `sentAt` nor `sendAtMs`, so this is the only time it has.\n */\n createdAtMs?: number\n stats?: CampaignStats\n /** How far a send that goes out over several batches has got. */\n resume?: CampaignResume\n}\n\n/**\n * The batch state the sender writes on an email that is still going out.\n *\n * Absent on every send that finished in one batch, and on every send that\n * predates batching — which is why {@link campaignSendProgress} treats a\n * missing record as \"this is not a batched send\" rather than as zero.\n */\nexport interface CampaignResume {\n /** People the email has resolved and not yet addressed. */\n remaining?: number\n /** Batches it has run. */\n batch?: number\n /** When the next batch may go, ms. Zero when there is not going to be one. */\n nextAtMs?: number\n /** Why it stopped short, when it did. */\n stop?: string\n}\n\n/**\n * WHAT A SEND IS ACTUALLY DOING, for a row that would otherwise lie.\n *\n * An email larger than one send may carry is delivered over several batches,\n * and between them it is stored as `scheduled` — the state the processor\n * claims, and the only one that resumes it without a second index and a\n * second query. Read literally, that is a row saying \"not sent yet\" about an\n * email that has already put five hundred messages in five hundred inboxes.\n *\n * So the stored fields are not the sentence. This is: it takes the status,\n * the delivered count and the batch record, and answers what a person needs\n * to see. Derived at read time and never persisted, exactly as\n * `campaignWindowState` beside it is, because it is a description of stored\n * facts and not a fact of its own.\n *\n * ## The four states, and which stored shape each one is\n *\n * - `pending` — `scheduled`, nothing delivered. A campaign waiting for its\n * time. This is what `scheduled` meant before batching and still does.\n * - `sending` — `scheduled` or `sending` with something delivered and more to\n * come. The state this function exists for.\n * - `sent` — finished, whether in one batch or six.\n * - `stopped` — finished with people it never addressed: canceled mid-flight,\n * failed mid-flight, or stopped by the batch guard. The count is what makes\n * this legible rather than alarming — an email that reached 2,400 of 3,000\n * and stopped is a different conversation from one that reached nobody.\n */\nexport type CampaignSendProgressState =\n | 'pending'\n | 'sending'\n | 'sent'\n | 'stopped'\n\nexport interface CampaignSendProgress {\n state: CampaignSendProgressState\n /** Messages this email has delivered. */\n reached: number\n /**\n * The audience it is working through, when one was recorded. Null when the\n * send never recorded an audience size, which is every send that predates\n * the figure — reported as null rather than as `reached` so a surface does\n * not present a floor as a total.\n */\n audience: number | null\n /** People it has resolved and not yet addressed. */\n remaining: number\n /** Batches it has run. Zero for a send that never batched. */\n batch: number\n /** When the next batch may go, ms. Zero unless {@link state} is `sending`. */\n nextAtMs: number\n /** One line a surface may show verbatim. */\n label: string\n}\n\n/** A stored count as a non-negative integer, or 0. */\nfunction progressCount(raw: unknown): number {\n const value = Math.floor(Number(raw))\n return Number.isFinite(value) && value > 0 ? value : 0\n}\n\nexport function campaignSendProgress(\n send: CampaignSend | null | undefined,\n): CampaignSendProgress {\n const status = String(send?.status ?? 'sent')\n const reached = progressCount(send?.stats?.sent)\n const rawAudience = send?.stats?.audienceSize\n const audience =\n rawAudience === undefined || rawAudience === null\n ? null\n : progressCount(rawAudience)\n const resume = send?.resume\n const remaining = progressCount(resume?.remaining)\n const batch = progressCount(resume?.batch)\n const nextAtMs = progressCount(resume?.nextAtMs)\n const of = audience !== null ? ` of ${audience.toLocaleString()}` : ''\n\n // Still going: more to address, and a run that will address it. A campaign\n // a merchant CANCELED is not still going however much is left, which is why\n // the status is read before the remainder.\n if (\n remaining > 0 &&\n nextAtMs > 0 &&\n (status === 'scheduled' || status === 'sending')\n ) {\n return {\n state: 'sending',\n reached,\n audience,\n remaining,\n batch,\n nextAtMs,\n label: `Sending — reached ${reached.toLocaleString()}${of}`,\n }\n }\n // Waiting for its time, with nothing delivered. The pre-batching meaning of\n // `scheduled`, and still the common one.\n if ((status === 'scheduled' || status === 'sending') && reached === 0) {\n return {\n state: 'pending',\n reached: 0,\n audience,\n remaining,\n batch,\n nextAtMs: 0,\n label: status === 'sending' ? 'Sending' : 'Scheduled',\n }\n }\n if (remaining > 0) {\n const why =\n status === 'canceled'\n ? 'canceled'\n : status === 'failed'\n ? 'stopped by an error'\n : 'stopped'\n return {\n state: 'stopped',\n reached,\n audience,\n remaining,\n batch,\n nextAtMs: 0,\n label:\n `Reached ${reached.toLocaleString()}${of} — ${why} with ` +\n `${remaining.toLocaleString()} not addressed`,\n }\n }\n return {\n state: 'sent',\n reached,\n audience,\n remaining: 0,\n batch,\n nextAtMs: 0,\n label:\n batch > 1\n ? `Sent to ${reached.toLocaleString()}${of} over ${batch} runs`\n : `Sent to ${reached.toLocaleString()}${of}`,\n }\n}\n\n/**\n * What a ROW says about one email, in one word and one line.\n *\n * {@link campaignSendProgress} answers what a send is DOING, and a draft is\n * not doing anything: it has no status the progress states cover, and — since\n * an absent status reads as `sent` and a draft has no counters — asking it\n * about one answers \"Sent to 0\", which is the worst available sentence about\n * an email nobody has written yet. So the draft is settled here and\n * everything else is deferred, unchanged, to the derivation that owns it.\n *\n * One helper rather than the same two-line branch on four surfaces. The\n * campaigns table, the emails list, an email's own page and a campaign's\n * emails table all draw this, and four copies is how three of them come to\n * say \"Scheduled\" about a campaign that has delivered five hundred messages.\n */\nexport type CampaignSendDisplayState = 'draft' | CampaignSendProgressState\n\nexport interface CampaignSendDisplay {\n state: CampaignSendDisplayState\n /** One line a surface may show verbatim. */\n label: string\n /** The progress underneath, for a surface that wants the figures. */\n progress: CampaignSendProgress\n}\n\nexport function campaignSendDisplay(\n send: CampaignSend | null | undefined,\n): CampaignSendDisplay {\n const progress = campaignSendProgress(send)\n if (String(send?.status ?? '') === 'draft') {\n return { state: 'draft', label: 'Draft', progress }\n }\n return { state: progress.state, label: progress.label, progress }\n}\n\n/**\n * Whether this email is between batches, with more of its audience to reach.\n *\n * The one question two controls on an email's page turn on. It is stored as\n * `scheduled` — the state the processor claims — so a surface reading the\n * status alone offers \"Send now\" on a campaign that is already going out, and\n * `sendNow` re-resolves the WHOLE audience rather than continuing: everyone\n * already reached would receive a second copy under the same `cid`.\n */\nexport function campaignSendIsMidFlight(\n send: CampaignSend | null | undefined,\n): boolean {\n return campaignSendProgress(send).state === 'sending'\n}\n\n/**\n * The lists ONE SEND addressed — which can be narrower than the lists its\n * campaign is aimed at.\n *\n * A campaign holds the lists a merchant plans to reach; each send inside it\n * picks one audience, and that audience may be a segment or the site's leads\n * rather than any of them. Answering from the send is therefore the only\n * honest answer for a send's own detail page.\n *\n * An array for a document that stores one id, deliberately: the question\n * \"which lists did this reach\" has a plural answer everywhere it is asked,\n * and a caller that unwraps a single id today is a caller to revisit if a\n * send ever addresses two.\n */\nexport function campaignSendListIds(send: CampaignSend): string[] {\n return send.audience === 'list' && send.listId ? [send.listId] : []\n}\n\n/**\n * A number summed across sends, with how much of the campaign it covers.\n *\n * `value` is `null` when NO send recorded the field — which is not zero, for\n * the reason `campaign-report.ts` gives at length: an unrecorded delivery\n * count and a delivery count of zero lead a merchant to opposite conclusions\n * about their sending domain.\n *\n * `recorded` below `sends` means the total is a floor. A campaign whose\n * older sends predate the delivery webhook has a real number that describes\n * part of itself, and saying which part is the difference between a total and\n * a guess.\n */\nexport interface CampaignAggregate {\n value: number | null\n /** Sends that recorded this field. */\n recorded: number\n /** Sends in the campaign. */\n sends: number\n}\n\n/** Every rolled-up figure for one campaign. */\nexport interface CampaignRollup {\n /** Sends that have actually gone out. */\n sends: number\n /** Sends still waiting for their send time, having delivered nothing. */\n scheduled: number\n /**\n * Sends part way through an audience larger than one batch.\n *\n * Counted apart from `scheduled` and from `sends`, because it is neither:\n * mail has gone out, and more is going to. Both of those are facts a\n * merchant reading a campaign row needs, and the stored status carries\n * only the first.\n */\n sending: number\n /**\n * Emails that have been created and not yet written or sent.\n *\n * Counted apart from `sends` and from `scheduled`, because a draft is\n * neither: it has mailed nobody, and it is not on the clock to.\n */\n drafts: number\n addressed: CampaignAggregate\n sent: CampaignAggregate\n delivered: CampaignAggregate\n opens: CampaignAggregate\n uniqueOpens: CampaignAggregate\n clicks: CampaignAggregate\n uniqueClicks: CampaignAggregate\n bounced: CampaignAggregate\n complained: CampaignAggregate\n unsubscribes: CampaignAggregate\n /** Distinct openers over delivered, across every send that recorded both. */\n openRate: CampaignRate | null\n /** Distinct clickers over delivered. */\n clickRate: CampaignRate | null\n /** Unsubscribes over delivered. */\n unsubscribeRate: CampaignRate | null\n /** The most recent send time in the campaign, for ordering a list. */\n lastSentAtMs: number | null\n}\n\nconst aggregate = (\n sends: CampaignSend[],\n read: (stats: CampaignStats) => number | undefined,\n): CampaignAggregate => {\n let total = 0\n let recorded = 0\n for (const send of sends) {\n const value = read(send.stats ?? {})\n // `undefined` is \"this send never recorded it\"; a recorded 0 counts as\n // measured, and moves `recorded` without moving the total.\n if (value === undefined || value === null) continue\n const numeric = Number(value)\n if (!Number.isFinite(numeric)) continue\n total += numeric\n recorded += 1\n }\n return { value: recorded ? total : null, recorded, sends: sends.length }\n}\n\n/** When a send happened, in epoch milliseconds, or null. */\nexport function campaignSendAtMs(send: CampaignSend): number | null {\n const seconds = send.sentAt?.seconds\n if (typeof seconds === 'number') return seconds * 1000\n if (typeof send.sendAtMs === 'number') return send.sendAtMs\n return null\n}\n\n/**\n * Rolls a campaign's sends into one set of figures.\n *\n * Rates are taken over the sends that recorded BOTH sides, so a campaign\n * whose first send predates the delivery webhook reports the open rate of the\n * sends that can be measured rather than one deflated by a send with no\n * denominator.\n */\nexport function campaignRollup(sends: CampaignSend[]): CampaignRollup {\n /*==========================================\n * ONLY MAIL THAT HAS GONE OUT IS A SEND.\n *\n * An email exists from the moment it is created, so this collection now\n * holds records in three states that have mailed nobody — `draft`,\n * `scheduled` and the `sending` claim — and every figure below is about\n * mail that was delivered.\n *\n * Two separate faults if they are left in. The COUNT would report a\n * campaign as having sent three emails when it has sent two and is still\n * writing the third. And every aggregate carries `sends` as the denominator\n * of its own \"recorded by N of M\" label, so an unsent record would enlarge\n * the M — publishing a coverage figure that says the campaign is missing\n * data it was never going to have.\n *=========================================*/\n /*\n * A SEND THAT IS STILL GOING HAS STILL GONE.\n *\n * `emailIsUnsent` reads the stored status, and an email delivering an\n * audience larger than one batch is stored as `scheduled` between runs —\n * so reading it literally drops a send that has put five hundred messages\n * in five hundred inboxes out of every total on the campaign, and counts it\n * under \"scheduled\" as though nothing had happened. `campaignSendProgress`\n * is what tells \"waiting for its time\" from \"part way through\", and only\n * the first is genuinely unsent.\n *\n * A DRAFT is settled by the status because the progress states do not cover\n * it — see `campaignSendDisplay`.\n */\n const notYet = (send: CampaignSend): boolean =>\n String(send.status ?? '') === 'draft' ||\n campaignSendProgress(send).state === 'pending'\n const gone = sends.filter((send) => !notYet(send))\n const measurable = sends.filter(\n (send) => send.stats?.delivered !== undefined,\n )\n const deliveredTotal = aggregate(measurable, (stats) => stats.delivered)\n return {\n sends: gone.filter((send) => send.status !== 'canceled').length,\n // Waiting for its time with nothing delivered — which is what\n // \"scheduled\" meant before an email could be delivered over several runs,\n // and is now narrower than the stored status of that name.\n scheduled: sends.filter(\n (send) => campaignSendProgress(send).state === 'pending',\n ).length,\n sending: sends.filter(\n (send) => campaignSendProgress(send).state === 'sending',\n ).length,\n drafts: sends.filter((send) => send.status === 'draft').length,\n addressed: aggregate(gone, (stats) => stats.recipients),\n sent: aggregate(gone, (stats) => stats.sent),\n delivered: aggregate(gone, (stats) => stats.delivered),\n opens: aggregate(gone, (stats) => stats.opens),\n uniqueOpens: aggregate(gone, (stats) => stats.uniqueOpens),\n clicks: aggregate(gone, (stats) => stats.clicks),\n uniqueClicks: aggregate(gone, (stats) => stats.uniqueClicks),\n bounced: aggregate(gone, (stats) => stats.bounced),\n complained: aggregate(gone, (stats) => stats.complained),\n unsubscribes: aggregate(gone, (stats) => stats.unsubscribes),\n openRate: campaignRate(\n aggregate(measurable, (stats) => stats.uniqueOpens).value ?? undefined,\n deliveredTotal.value ?? undefined,\n 'delivered',\n ),\n clickRate: campaignRate(\n aggregate(measurable, (stats) => stats.uniqueClicks).value ?? undefined,\n deliveredTotal.value ?? undefined,\n 'delivered',\n ),\n unsubscribeRate: campaignRate(\n aggregate(measurable, (stats) => stats.unsubscribes).value ?? undefined,\n deliveredTotal.value ?? undefined,\n 'delivered',\n ),\n lastSentAtMs: sends.reduce<number | null>((latest, send) => {\n const at = campaignSendAtMs(send)\n return at !== null && (latest === null || at > latest) ? at : latest\n }, null),\n }\n}\n\n/**\n * Where a campaign stands against its own window.\n *\n * Derived at read time and never persisted — the `status` values on a SEND\n * (`sent`, `scheduled`, `canceled`, `failed`) are stored strings that a\n * processor branches on, and a display state sharing those spellings would\n * eventually be written back.\n */\nexport type CampaignWindowState = 'undated' | 'upcoming' | 'running' | 'ended'\n\nexport function campaignWindowState(\n campaign: Pick<EmailCampaign, 'startAtMs' | 'endAtMs'>,\n nowMs: number,\n): CampaignWindowState {\n const start = campaign.startAtMs ?? null\n const end = campaign.endAtMs ?? null\n if (start === null && end === null) return 'undated'\n if (start !== null && nowMs < start) return 'upcoming'\n if (end !== null && nowMs > end) return 'ended'\n return 'running'\n}\n\n/** One row of the campaigns table. */\nexport interface CampaignListRow {\n /** The id the detail route resolves — a container id, or a send id. */\n id: string\n name: string\n /**\n * True when this row IS a send with no container.\n *\n * A campaign sent before containers existed is shown as a campaign of one\n * rather than dropped from the list, and the detail route falls back to the\n * send's own report for it. Nothing about that send is rewritten.\n */\n legacy: boolean\n startAtMs: number | null\n endAtMs: number | null\n listIds: string[]\n sends: CampaignSend[]\n rollup: CampaignRollup\n windowState: CampaignWindowState\n /** For ordering: the campaign's start, else its most recent send. */\n atMs: number | null\n}\n\n/**\n * The campaigns table's rows: every container, plus every send that belongs\n * to none.\n *\n * The second half is what makes the container additive. A merchant's history\n * is the sends they already have; a list that showed only containers would\n * read as an empty product on the day this shipped, and a backfill that\n * adopted each old send into a container of one would rewrite documents whose\n * ids are cited by mail already delivered. Adopting them AT READ TIME costs a\n * pass over a list already in memory and rewrites nothing.\n *\n * Newest first, on the start date where there is one and the last send\n * otherwise. Rows with no date at all sort last: they are campaigns nobody\n * has scheduled or sent, and dating them from nothing would be an invention.\n */\nexport function campaignListRows(\n campaigns: EmailCampaign[],\n sends: CampaignSend[],\n nowMs: number,\n): CampaignListRow[] {\n const byCampaign = new Map<string, CampaignSend[]>()\n const orphans: CampaignSend[] = []\n for (const send of sends) {\n const containerId = send.emailCampaignId\n if (!containerId) {\n orphans.push(send)\n continue\n }\n const existing = byCampaign.get(containerId)\n if (existing) existing.push(send)\n else byCampaign.set(containerId, [send])\n }\n\n const rows: CampaignListRow[] = campaigns.map((campaign) => {\n const own = byCampaign.get(campaign.$id) ?? []\n const rollup = campaignRollup(own)\n return {\n id: campaign.$id,\n name: campaign.name || 'Untitled campaign',\n legacy: false,\n startAtMs: campaign.startAtMs ?? null,\n endAtMs: campaign.endAtMs ?? null,\n listIds: campaign.listIds ?? [],\n sends: own,\n rollup,\n windowState: campaignWindowState(campaign, nowMs),\n atMs: campaign.startAtMs ?? rollup.lastSentAtMs ?? null,\n }\n })\n\n for (const send of orphans) {\n const rollup = campaignRollup([send])\n const at = campaignSendAtMs(send)\n rows.push({\n id: send.$id,\n name: send.subject || 'Untitled campaign',\n legacy: true,\n startAtMs: at,\n endAtMs: at,\n listIds: [],\n sends: [send],\n rollup,\n // A send has no window of its own; it happened, or it is going to.\n windowState:\n send.status === 'scheduled'\n ? 'upcoming'\n : at === null\n ? 'undated'\n : 'ended',\n atMs: at,\n })\n }\n\n return rows.sort((a, b) => {\n if (a.atMs === null && b.atMs === null) return a.name.localeCompare(b.name)\n if (a.atMs === null) return 1\n if (b.atMs === null) return -1\n return b.atMs - a.atMs\n })\n}\n"],"names":["CAMPAIGN_SEQUENCE_REPORTS_COLLECTION","campaignRate","EMAIL_CAMPAIGNS_COLLECTION","CAMPAIGN_SENDS_COLLECTION","orgEmailCampaignsPath","orgId","orgCampaignSendsPath","orgCampaignSequenceReportsPath","CAMPAIGN_SEND_HOST_FIELD","CAMPAIGN_ORG_SCOPE","campaignHostScope","hostId","campaignSendVisibleTo","campaignSiteIds","campaign","tokens","visibleTo","includes","ids","token","startsWith","length","push","slice","campaignPlacedOnHost","campaignVisibleTo","siteIds","unique","Set","filter","id","map","CAMPAIGN_SEND_CONTAINER_FIELD","progressCount","raw","value","Math","floor","Number","isFinite","campaignSendProgress","send","status","String","reached","stats","sent","rawAudience","audienceSize","audience","undefined","resume","remaining","batch","nextAtMs","of","toLocaleString","state","label","why","campaignSendDisplay","progress","campaignSendIsMidFlight","campaignSendListIds","listId","aggregate","sends","read","total","recorded","numeric","campaignSendAtMs","seconds","sentAt","sendAtMs","campaignRollup","deliveredTotal","notYet","gone","measurable","delivered","scheduled","sending","drafts","addressed","recipients","opens","uniqueOpens","clicks","uniqueClicks","bounced","complained","unsubscribes","openRate","clickRate","unsubscribeRate","lastSentAtMs","reduce","latest","at","campaignWindowState","nowMs","start","startAtMs","end","endAtMs","campaignListRows","campaigns","byCampaign","Map","orphans","containerId","emailCampaignId","existing","get","set","rows","own","$id","rollup","name","legacy","listIds","windowState","atMs","subject","sort","a","b","localeCompare"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmDC,GAED,SACEA,oCAAoC,EACpCC,YAAY,QAGP,uBAAmB;AAE1B,oDAAoD,GACpD,OAAO,MAAMC,6BAA6B,iBAAgB;AAE1D,+DAA+D,GAC/D,OAAO,MAAMC,4BAA4B,YAAW;AAEpD,qDAAqD,GACrD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,IAAIO,EAAEH,IAAI,KAAK,MAAM,OAAO;QAC5B,IAAII,EAAEJ,IAAI,KAAK,MAAM,OAAO,CAAC;QAC7B,OAAOI,EAAEJ,IAAI,GAAGG,EAAEH,IAAI;IACxB;AACF"}
@@ -309,7 +309,10 @@ export declare function campaignLinkReport(rollup: CampaignLinkRollup | undefine
309
309
  */
310
310
  export declare const CAMPAIGN_SEQUENCE_OUTCOMES: readonly ["enrolled", "sent", "replied", "meetings", "converted"];
311
311
  export type CampaignSequenceOutcome = (typeof CAMPAIGN_SEQUENCE_OUTCOMES)[number];
312
- /** The per-host collection holding one document per campaign. */
312
+ /**
313
+ * The org collection holding one document per campaign container,
314
+ * `orgs/{orgId}/campaignSequenceReports/{campaignId}`.
315
+ */
313
316
  export declare const CAMPAIGN_SEQUENCE_REPORTS_COLLECTION = "campaignSequenceReports";
314
317
  /** What a reader calls each outcome, and what the count means. */
315
318
  export declare const CAMPAIGN_SEQUENCE_OUTCOME_COPY: Readonly<Record<CampaignSequenceOutcome, {
@@ -361,7 +361,10 @@
361
361
  'meetings',
362
362
  'converted'
363
363
  ];
364
- /** The per-host collection holding one document per campaign. */ export const CAMPAIGN_SEQUENCE_REPORTS_COLLECTION = 'campaignSequenceReports';
364
+ /**
365
+ * The org collection holding one document per campaign container,
366
+ * `orgs/{orgId}/campaignSequenceReports/{campaignId}`.
367
+ */ export const CAMPAIGN_SEQUENCE_REPORTS_COLLECTION = 'campaignSequenceReports';
365
368
  /** What a reader calls each outcome, and what the count means. */ export const CAMPAIGN_SEQUENCE_OUTCOME_COPY = {
366
369
  enrolled: {
367
370
  label: 'Enrolled',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/shared/ui/email-campaigns/src/lib/model/campaign-report.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * CAMPAIGN REPORTING MATH — the only place a rate is computed.\n *\n * ## Why a pure module and not a component\n *\n * Every number on the report screen is a division, and a division is where\n * email reporting goes wrong. Putting the arithmetic in JSX means the\n * denominator is chosen by whoever writes the next card, in a file nobody\n * tests for arithmetic; putting it here means each rate is named once,\n * carries its own denominator as data, and is provable.\n *\n * ## The rule this module exists to enforce\n *\n * **A rate is a triple — numerator, denominator, and the NAME of the\n * denominator — or it is not reported.** An open rate over `sent` and an open\n * rate over `delivered` are different numbers with the same label, and the\n * gap between them is exactly the mail that bounced. The industry convention\n * is over `delivered`, and a report that quietly used `sent` would read\n * higher than the same campaign measured anywhere else.\n *\n * So {@link CampaignRate} carries `denominatorLabel`, and the screen is\n * required to render it. There is no overload that omits it.\n *\n * ## Why some rates are deliberately absent\n *\n * {@link campaignRate} answers `null`, not zero, when it cannot divide:\n *\n * - **A zero denominator.** 0 opens out of 0 delivered is not a 0% open\n * rate, it is no open rate. Rendering 0% invites the reader to compare it\n * with a campaign that really did fail.\n * - **An UNKNOWN denominator.** `delivered` is counted by the delivery\n * webhook, which was connected after some campaigns were sent. A campaign\n * with 400 sends and no delivery events has an unknown denominator, not a\n * denominator of zero — and dividing by `sent` instead is precisely the\n * flattering substitution above.\n *\n * ## The structural-zero window\n *\n * Click tracking rewrites links in the HTML part. Sends that carried no HTML\n * part were therefore untrackable, and every one of those campaigns reports 0\n * clicks whatever the recipients actually did — a real 0 and a structural 0\n * rendered identically. `send-email.ts` now synthesises an HTML part for a\n * text-only send, so every send after that carries one, and\n * `campaign-send.ts` records {@link CampaignStats.clickTracked} to say so.\n *\n * A campaign with no such marker predates the record. Its click COUNT is\n * still shown — it is a real count of real events — but no click RATE is\n * computed from it, because a rate presents the number as a measurement of\n * the audience and for those campaigns it is a measurement of the sender.\n */\n\n/**\n * The `stats` map on `hosts/{hostId}/campaigns/{campaignId}`.\n *\n * Every field is optional and every reader defaults it, because these are\n * written by three different writers at three different times — the send, the\n * delivery webhook, the unsubscribe handler — and a campaign is a legitimate,\n * readable document from the instant the first of them lands.\n */\nexport interface CampaignStats {\n /*========================================\n * WRITTEN BY THE SEND. Never recomputed.\n *\n * These are the truth of what happened, recorded once by the code that did\n * it. Re-deriving any of them at read time would produce a number that\n * disagrees with the send — the audience has moved on since, suppressions\n * have been added, consent has been recorded — and the recorded one is the\n * one that describes the campaign.\n *=======================================*/\n /** The whole audience the send was taken from, before the per-send cap. */\n audienceSize?: number\n /** `audienceSize` is a FLOOR: audience resolution hit its read ceiling. */\n audienceSizeTruncated?: boolean\n /** Addresses this send ADDRESSED — the audience after the per-send cap. */\n recipients?: number\n /** Messages the provider accepted. The `sent` in \"sent/recipients\". */\n sent?: number\n /** Of the audience, how many carry a recorded marketing consent basis. */\n consented?: number\n /** Of `consented`, how many hold a basis an operator asserted for them. */\n consentedByOperator?: number\n /** Of the audience, how many are reachable only because enforcement is\n * not retroactive — the population a strict consent policy removes. */\n grandfathered?: number\n /** Of the audience, how many the consent rule refused to mail. */\n consentWithheld?: number\n /** Of `recipients`, how many were already suppressed (unsubscribed,\n * bounced or complained on an earlier send). */\n suppressed?: number\n /** Of `recipients`, how many asked this site for mail less often than this\n * send would have arrived. Still subscribed; reached by a later campaign. */\n cadenceHeld?: number\n /** Recipients the hourly send governor refused mid-batch. */\n deferred?: number\n /**\n * This send carried an HTML part, so its links were trackable.\n *\n * Absent on every campaign sent before the field existed — see the\n * structural-zero note in this module's header. Absent is NOT false; it is\n * \"not recorded\", and the report says so rather than guessing.\n */\n clickTracked?: boolean\n /** Per-variant send counts for an A/B campaign. */\n variantSends?: Record<string, number>\n\n /*========================================\n * WRITTEN BY THE DELIVERY WEBHOOK, as increments.\n *=======================================*/\n /** Messages the receiving server accepted. The rate DENOMINATOR. */\n delivered?: number\n /** Open EVENTS. One reader opening four times counts four. */\n opens?: number\n /** Click EVENTS. One reader clicking three links counts three. */\n clicks?: number\n /** Messages whose FIRST open was seen — distinct readers who opened. */\n uniqueOpens?: number\n /** Messages whose FIRST click was seen — distinct readers who clicked. */\n uniqueClicks?: number\n /** Messages that bounced, permanent and transient together. */\n bounced?: number\n /** Recipients who pressed \"report spam\". */\n complained?: number\n\n /*========================================\n * WRITTEN BY THE UNSUBSCRIBE HANDLER.\n *=======================================*/\n /** Recipients who unsubscribed through THIS campaign's link. */\n unsubscribes?: number\n}\n\n/**\n * One rate, with the denominator it was taken over named as data.\n *\n * `denominatorLabel` is not a display nicety. It is the field that makes two\n * numbers called \"open rate\" distinguishable, and the screen renders it\n * beside the percentage for that reason.\n */\nexport interface CampaignRate {\n /** 0–1. Multiply for display; the model never formats. */\n value: number\n numerator: number\n denominator: number\n /** Reader-facing name of the denominator, e.g. `'delivered'`. */\n denominatorLabel: string\n}\n\n/**\n * A rate, or `null` when one cannot honestly be taken.\n *\n * `null` on a zero or unknown denominator — see the module header for why\n * that is not the same as 0%.\n */\nexport function campaignRate(\n numerator: number | undefined,\n denominator: number | undefined,\n denominatorLabel: string,\n): CampaignRate | null {\n const top = Number(numerator ?? 0)\n const bottom = Number(denominator ?? 0)\n if (!Number.isFinite(top) || !Number.isFinite(bottom)) return null\n if (bottom <= 0) return null\n return {\n value: top / bottom,\n numerator: top,\n denominator: bottom,\n denominatorLabel,\n }\n}\n\n/** Why a number the report would otherwise show is being withheld. */\nexport interface CampaignCaveat {\n /** Stable id, so a spec can assert on the caveat rather than its prose. */\n id:\n | 'delivery-unrecorded'\n | 'click-tracking-unrecorded'\n | 'audience-truncated'\n | 'send-deferred'\n /* Raised by `campaign-revenue.ts`, which reports through this shape so\n * the screen has one way of saying \"a number is being withheld and here\n * is why\" rather than one per section. */\n | 'revenue-denominator-unrecorded'\n | 'revenue-multi-currency'\n | 'revenue-mid-flight'\n | 'revenue-mixed-model'\n /* Raised by `campaign-conversions.ts`, through this shape for the same\n * reason: one way of saying \"a number is being withheld, or must not be\n * read the obvious way, and here is why\". The first two are the reasons\n * the four conversion kinds stand apart instead of totalling; the last\n * two qualify the uncredited figure rather than withholding it. */\n | 'conversions-kinds-overlap'\n | 'conversions-web-not-rolled-up'\n | 'conversions-unattributed-is-a-ceiling'\n | 'conversions-total-crosses-hosts'\n /* Raised by the Sequences block below (AGL-3254): the five figures are\n * a funnel read across, never a sum. */\n | 'sequences-funnel-not-summed'\n message: string\n}\n\n/** One population the send measured, for the audience breakdown. */\nexport interface CampaignPopulation {\n id: string\n label: string\n count: number\n /** What this count is a part OF, named. */\n ofLabel: string\n of: number\n}\n\n/** Everything the report screen renders, decided here rather than in JSX. */\nexport interface CampaignReport {\n sent: number\n recipients: number\n delivered: number | null\n opens: number\n clicks: number\n uniqueOpens: number | null\n uniqueClicks: number | null\n bounced: number\n complained: number\n unsubscribes: number\n /** Rates, each `null` when its denominator is zero or unrecorded. */\n rates: {\n /** Accepted by the receiving server, over what the provider accepted. */\n delivery: CampaignRate | null\n /** Distinct readers who opened, over delivered. */\n open: CampaignRate | null\n /** Distinct readers who clicked, over delivered. */\n click: CampaignRate | null\n /**\n * Distinct clickers over distinct OPENERS — a different question from\n * `click`, and the one the two get confused for. It answers \"of the\n * people who read it, how many acted\", not \"of the people who received\n * it\". Reported separately and labelled separately, never as \"click\n * rate\".\n */\n clickToOpen: CampaignRate | null\n /** Bounced over what the provider accepted. */\n bounce: CampaignRate | null\n /** Complaints over delivered — the number mailbox providers judge on. */\n complaint: CampaignRate | null\n /** Unsubscribes through this campaign's link, over delivered. */\n unsubscribe: CampaignRate | null\n }\n populations: CampaignPopulation[]\n caveats: CampaignCaveat[]\n}\n\n/**\n * Turns a stored `stats` map into the report.\n *\n * ## The denominator decisions, in one place\n *\n * - **`delivered`** carries the engagement rates — open, click, complaint,\n * unsubscribe. Mail that bounced was never in front of a human, so\n * including it in the denominator of an open rate depresses a number that\n * describes the audience with a fact about the address list. This is also\n * the convention every other tool reports, which matters: a merchant\n * comparing our figure with their previous ESP's must be comparing the same\n * quantity.\n * - **`sent`** carries the delivery and bounce rates, because those describe\n * what happened to what we handed the provider, and `delivered` is the\n * numerator of one of them — a rate cannot be over itself.\n * - **`uniqueOpens`** is the open-rate numerator, not `opens`. Open EVENTS\n * over recipients can exceed 100% the moment one person opens twice, and a\n * percentage above 100 is how a reader learns the number means something\n * other than what it says. Both are shown; only the distinct count is\n * divided.\n *\n * ## `delivered` unknown vs. zero\n *\n * A campaign predating the delivery webhook records no `delivered` at all.\n * That is reported as `null` and every rate over it is withheld, with a\n * caveat naming the reason — rather than substituting `sent`, which would\n * silently publish the flattered number this module exists to refuse.\n */\nexport function campaignReport(stats: CampaignStats | undefined): CampaignReport {\n const source = stats ?? {}\n const sent = Number(source.sent ?? 0)\n const recipients = Number(source.recipients ?? 0)\n const opens = Number(source.opens ?? 0)\n const clicks = Number(source.clicks ?? 0)\n const bounced = Number(source.bounced ?? 0)\n const complained = Number(source.complained ?? 0)\n const unsubscribes = Number(source.unsubscribes ?? 0)\n\n /*\n * ABSENT, not zero. `stats.delivered` is written only by the delivery\n * webhook, so `undefined` means \"no delivery event has ever been recorded\n * for this campaign\" — which for an old campaign means the webhook was not\n * connected, and for a campaign sent thirty seconds ago means the events\n * are still in flight. Neither is \"nothing was delivered\", and both are\n * ruined by `?? 0`, which would turn the unknown into a hard zero and make\n * every rate over it `null` for the RIGHT answer by the WRONG reasoning —\n * and would render \"0 delivered\" on screen beside \"500 sent\".\n */\n const delivered =\n source.delivered === undefined ? null : Number(source.delivered)\n const uniqueOpens =\n source.uniqueOpens === undefined ? null : Number(source.uniqueOpens)\n const uniqueClicks =\n source.uniqueClicks === undefined ? null : Number(source.uniqueClicks)\n\n /*\n * The click rate is withheld for a campaign that never recorded carrying an\n * HTML part, even when clicks are non-zero and `delivered` is known. See\n * the structural-zero note in the module header: for those sends 0 is the\n * only value the number could ever have taken, so a rate computed from it\n * measures our sending code rather than the recipients.\n */\n const clickTrackable = source.clickTracked === true\n\n const rates: CampaignReport['rates'] = {\n /*\n * `null` when `delivered` is UNRECORDED, and this is the one rate where\n * the numerator can be unknown rather than zero.\n *\n * Everywhere else an absent numerator is a genuine nought — a campaign\n * with delivery events and no opens really does have a 0% open rate, and\n * that is worth showing. Here the numerator IS the unrecorded quantity,\n * so `campaignRate(undefined, 1000, 'sent')` would divide a missing\n * measurement by a real one and publish \"0.0% delivery rate — 0 of 1,000\n * sent\" for a campaign whose delivery events were merely never recorded.\n * That is the flattering-substitution failure this module exists to\n * refuse, running in the other direction: not a rate that reads too high,\n * but a campaign that reads as a total delivery failure.\n */\n delivery:\n delivered === null ? null : campaignRate(delivered, sent, 'sent'),\n open: campaignRate(uniqueOpens ?? undefined, delivered ?? undefined, 'delivered'),\n click: clickTrackable\n ? campaignRate(uniqueClicks ?? undefined, delivered ?? undefined, 'delivered')\n : null,\n clickToOpen: clickTrackable\n ? campaignRate(uniqueClicks ?? undefined, uniqueOpens ?? undefined, 'unique openers')\n : null,\n bounce: campaignRate(bounced, sent, 'sent'),\n complaint: campaignRate(complained, delivered ?? undefined, 'delivered'),\n unsubscribe: campaignRate(unsubscribes, delivered ?? undefined, 'delivered'),\n }\n\n /*\n * The populations the SEND measured, reported as parts of a named whole\n * rather than as bare counts. \"412 withheld\" invites the question \"out of\n * what\"; the answer is the audience, and it is a different whole from the\n * one `suppressed` is measured against — consent is decided over the whole\n * audience and suppression over the capped recipient list, because that is\n * where each check runs. Netting them into one column would present two\n * different denominators as one.\n */\n const audienceSize = Number(source.audienceSize ?? 0)\n const populations: CampaignPopulation[] = []\n const addPopulation = (\n id: string,\n label: string,\n count: number | undefined,\n ofLabel: string,\n of: number,\n ) => {\n if (count === undefined) return\n populations.push({ id, label, count: Number(count), ofLabel, of })\n }\n addPopulation(\n 'consented',\n 'Had a consent basis',\n source.consented,\n 'audience',\n audienceSize,\n )\n addPopulation(\n 'consentedByOperator',\n 'Consent asserted by an operator',\n source.consentedByOperator,\n 'audience',\n audienceSize,\n )\n addPopulation(\n 'grandfathered',\n 'Reachable only because consent is not enforced retroactively',\n source.grandfathered,\n 'audience',\n audienceSize,\n )\n addPopulation(\n 'consentWithheld',\n 'Withheld by the consent rule',\n source.consentWithheld,\n 'audience',\n audienceSize,\n )\n addPopulation(\n 'suppressed',\n 'Already suppressed',\n source.suppressed,\n 'addressed',\n recipients,\n )\n addPopulation(\n 'cadenceHeld',\n 'Asked for mail less often than this',\n source.cadenceHeld,\n 'addressed',\n recipients,\n )\n\n const caveats: CampaignCaveat[] = []\n if (delivered === null) {\n caveats.push({\n id: 'delivery-unrecorded',\n message:\n 'No delivery events have been recorded for this campaign, so open, ' +\n 'click, complaint and unsubscribe rates cannot be computed — every ' +\n 'one of them is taken over delivered. Counts below are still real.',\n })\n }\n if (!clickTrackable) {\n caveats.push({\n id: 'click-tracking-unrecorded',\n message:\n 'This send did not record carrying an HTML part. Click tracking ' +\n 'rewrites links in the HTML, so a send without one reports zero ' +\n 'clicks whatever recipients did. The click count is shown; no click ' +\n 'rate is computed from it.',\n })\n }\n if (source.audienceSizeTruncated) {\n caveats.push({\n id: 'audience-truncated',\n message:\n 'Audience resolution stopped at its read ceiling, so the audience ' +\n 'size is a floor — the real audience is at least this large, and ' +\n 'every share taken over it is at most the figure shown.',\n })\n }\n if (Number(source.deferred ?? 0) > 0) {\n caveats.push({\n id: 'send-deferred',\n message:\n `${Number(source.deferred)} recipients were held back by the hourly ` +\n 'send governor and never received this campaign. They are counted in ' +\n 'addressed, not in sent.',\n })\n }\n\n return {\n sent,\n recipients,\n delivered,\n opens,\n clicks,\n uniqueOpens,\n uniqueClicks,\n bounced,\n complained,\n unsubscribes,\n rates,\n populations,\n caveats,\n }\n}\n\n/*==========================================\n * LINK-LEVEL CLICKS.\n *\n * Resend's `email.clicked` payload carries `data.click.link`, the destination\n * the recipient followed; `normalizeResendDeliveryEvents` already reads it\n * into `EmailDeliveryEvent.link`, and the per-recipient delivery log already\n * stores it. What did not exist was an aggregate — which is what \"link\n * clicks\" means, and it cannot be produced from the delivery log without\n * reading every recipient row for the campaign.\n *\n * So it is a WRITE-TIME rollup: one document per campaign,\n * `campaigns/{campaignId}/reports/links`, holding a bounded map. The report\n * reads exactly one document for the whole table.\n *=========================================*/\n\n/**\n * How many distinct destinations one campaign's rollup keeps.\n *\n * A CAP rather than a page size, and it exists because the map lives in a\n * single document with a 1 MiB ceiling. Clicks past the cap are counted in\n * {@link CampaignLinkRollup.overflowClicks} rather than dropped, so the\n * table's total still reconciles with `stats.clicks`.\n */\nexport const CAMPAIGN_LINK_ROLLUP_MAX = 50\n\n/**\n * Reduces a clicked URL to the key the rollup counts under.\n *\n * ## Why the query string is dropped\n *\n * Two reasons, and the second is the one that forces it:\n *\n * 1. **A campaign body goes through `resolveMergeTags` per recipient**, so a\n * link may carry a personalised query. Keying on the full URL would then\n * mint one rollup row per RECIPIENT — the aggregate degenerates into the\n * per-recipient log it exists to summarise, and it blows the cap on the\n * first campaign that does it.\n * 2. **A personalised query can carry the recipient's own address.** The\n * rollup is an aggregate read by everyone on the site's team; it must not\n * become a list of who clicked, and dropping the query is what guarantees\n * it cannot.\n *\n * ⚠️ The cost is real and is stated on the screen: two links to the same page\n * distinguished only by their UTM parameters count as ONE row. That is a\n * known limitation, not an oversight — see the note in the report card.\n *\n * @returns the normalized URL, or `null` for anything unparseable or not\n * http(s). A rollup key must be a URL a merchant recognises.\n */\nexport function campaignLinkKey(link: string | null | undefined): string | null {\n const raw = String(link ?? '').trim()\n if (!raw) return null\n try {\n const url = new URL(raw)\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return null\n // Trailing slash normalised away so `/pricing` and `/pricing/` are one\n // row; the bare origin keeps its slash so the key is still a valid URL.\n const path = url.pathname.length > 1\n ? url.pathname.replace(/\\/+$/, '')\n : url.pathname\n return `${url.origin}${path}`\n } catch {\n return null\n }\n}\n\n/** One destination in the rollup. */\nexport interface CampaignLinkRow {\n url: string\n /** Click EVENTS on this destination. One reader clicking twice counts two. */\n clicks: number\n /** Share of the campaign's counted link clicks. */\n share: CampaignRate | null\n}\n\n/** The stored shape of `campaigns/{campaignId}/reports/links`. */\nexport interface CampaignLinkRollup {\n links?: Record<string, { url?: string; clicks?: number }>\n /** Clicks on destinations past {@link CAMPAIGN_LINK_ROLLUP_MAX}. */\n overflowClicks?: number\n /** Click events that arrived carrying no destination at all. */\n unattributedClicks?: number\n}\n\n/** What the link table renders. */\nexport interface CampaignLinkReport {\n rows: CampaignLinkRow[]\n /** Clicks counted against a named destination — the table's total. */\n attributedClicks: number\n overflowClicks: number\n unattributedClicks: number\n /** True once the cap bit, so the table says it is not the whole list. */\n truncated: boolean\n}\n\n/**\n * The link table, sorted by clicks descending.\n *\n * `share` is over ATTRIBUTED clicks — the clicks this table accounts for —\n * and not over `stats.clicks`. The two differ by the overflow and the\n * unattributed, and a share column that did not sum to 100% because of rows\n * that are not on screen is the kind of arithmetic a reader cannot check.\n * Both excluded figures are returned so the screen can state them.\n */\nexport function campaignLinkReport(\n rollup: CampaignLinkRollup | undefined,\n): CampaignLinkReport {\n const entries = Object.values(rollup?.links ?? {})\n .map((entry) => ({\n url: String(entry?.url ?? ''),\n clicks: Number(entry?.clicks ?? 0),\n }))\n .filter((entry) => entry.url && Number.isFinite(entry.clicks))\n const attributedClicks = entries.reduce((total, one) => total + one.clicks, 0)\n const rows = [...entries]\n .sort((a, b) => b.clicks - a.clicks || a.url.localeCompare(b.url))\n .map((entry) => ({\n ...entry,\n share: campaignRate(entry.clicks, attributedClicks, 'link clicks counted'),\n }))\n const overflowClicks = Number(rollup?.overflowClicks ?? 0)\n return {\n rows,\n attributedClicks,\n overflowClicks,\n unattributedClicks: Number(rollup?.unattributedClicks ?? 0),\n truncated: entries.length >= CAMPAIGN_LINK_ROLLUP_MAX || overflowClicks > 0,\n }\n}\n\n/*==========================================\n * WHAT THE CAMPAIGN'S SEQUENCES PRODUCED (AGL-3254).\n *\n * A sequence joins a campaign the way a form does — `campaignIds` on its own\n * document — and its outcomes are then the campaign's to report: every\n * person enrolled, the first email each one was sent, the replies, the\n * meetings booked from a sequence link, and the enrolled leads that\n * converted. The Outreach runtime credits each outcome once per enrollment\n * to every campaign the sequence was in when the person was enrolled, into\n * `hosts/{hostId}/campaignSequenceReports/{campaignId}` — one document per\n * campaign, beside the conversions rollup and never inside the campaign\n * document, which the history list and the glance widget read.\n *\n * ## The five figures are a funnel, not a sum\n *\n * Each figure counts ENROLLMENTS at a stage: 40 enrolled, 38 sent, 6\n * replied, 2 meetings, 1 converted. They are read across, never added — a\n * person is in every stage they reached — and the model keeps them as an\n * ordered list rather than a total for the reason the conversion kinds are\n * kept apart.\n *\n * ## Absent is not zero\n *\n * A campaign no sequence was ever in has no document, and a stage nobody\n * reached has no field. Both are `null` here, so the screen can say\n * \"nothing recorded\" for the first and draw a dash for the second, rather\n * than printing a measured 0 replies for a campaign whose sequence went\n * out yesterday.\n *=========================================*/\n\n/**\n * The outcomes the runtime credits, in funnel order. An array first, because\n * the ORDER is the reading order and a second list is a second chance to\n * leave one out; the union is derived from it.\n */\nexport const CAMPAIGN_SEQUENCE_OUTCOMES = [\n 'enrolled',\n 'sent',\n 'replied',\n 'meetings',\n 'converted',\n] as const\n\nexport type CampaignSequenceOutcome = (typeof CAMPAIGN_SEQUENCE_OUTCOMES)[number]\n\n/** The per-host collection holding one document per campaign. */\nexport const CAMPAIGN_SEQUENCE_REPORTS_COLLECTION = 'campaignSequenceReports'\n\n/** What a reader calls each outcome, and what the count means. */\nexport const CAMPAIGN_SEQUENCE_OUTCOME_COPY: Readonly<\n Record<CampaignSequenceOutcome, { label: string; note: string }>\n> = {\n enrolled: { label: 'Enrolled', note: 'people enrolled in a sequence in this campaign' },\n sent: { label: 'Sent', note: 'of them, sent their first sequence email' },\n replied: { label: 'Replied', note: 'of them, who wrote back' },\n meetings: { label: 'Meetings', note: 'bookings made from a sequence link' },\n converted: { label: 'Converted', note: 'enrolled leads that became contacts' },\n}\n\n/**\n * The stored shape of `campaignSequenceReports/{campaignId}`.\n *\n * Read-side only, every field optional: another plugin's runtime wrote it,\n * and a reader that assumed a field was present would throw on the first\n * document written before the field existed.\n */\nexport interface CampaignSequencesRollup {\n byOutcome?: Partial<Record<CampaignSequenceOutcome, number>>\n /** When the runtime last credited anything, epoch ms. */\n updatedAtMs?: number\n}\n\n/** One outcome's figure on screen. */\nexport interface CampaignSequenceFigure {\n outcome: CampaignSequenceOutcome\n label: string\n /** The count, or `null` when the rollup holds no entry for the outcome. */\n value: number | null\n note: string\n}\n\n/** Everything the Sequences section renders. */\nexport interface CampaignSequencesReport {\n /** Always all five, always in {@link CAMPAIGN_SEQUENCE_OUTCOMES} order. */\n figures: CampaignSequenceFigure[]\n /** Whether the rollup document exists at all — see the block header. */\n recorded: boolean\n /** At least one outcome holds a figure. */\n any: boolean\n caveats: CampaignCaveat[]\n}\n\n/** Turns the stored rollup into the Sequences section. */\nexport function campaignSequencesReport(\n rollup: CampaignSequencesRollup | undefined,\n): CampaignSequencesReport {\n const stored = rollup?.byOutcome ?? {}\n const figures: CampaignSequenceFigure[] = CAMPAIGN_SEQUENCE_OUTCOMES.map((outcome) => {\n const raw = stored[outcome]\n const value = Math.floor(Number(raw ?? 0))\n return {\n outcome,\n label: CAMPAIGN_SEQUENCE_OUTCOME_COPY[outcome].label,\n // Unrecorded, negative and non-numeric all read as \"no figure\": the\n // runtime only ever increments, so a stored 0 is not a count either.\n value: raw === undefined || !Number.isFinite(value) || value <= 0 ? null : value,\n note: CAMPAIGN_SEQUENCE_OUTCOME_COPY[outcome].note,\n }\n })\n const any = figures.some((figure) => figure.value !== null)\n const caveats: CampaignCaveat[] = any\n ? [\n {\n id: 'sequences-funnel-not-summed',\n message:\n 'Each figure counts the people who reached that stage, so a person ' +\n 'who replied is counted under Enrolled and Sent as well. Read them ' +\n 'across; they are deliberately not added together.',\n },\n ]\n : []\n return { figures, recorded: rollup !== undefined, any, caveats }\n}\n"],"names":["campaignRate","numerator","denominator","denominatorLabel","top","Number","bottom","isFinite","value","campaignReport","stats","source","sent","recipients","opens","clicks","bounced","complained","unsubscribes","delivered","undefined","uniqueOpens","uniqueClicks","clickTrackable","clickTracked","rates","delivery","open","click","clickToOpen","bounce","complaint","unsubscribe","audienceSize","populations","addPopulation","id","label","count","ofLabel","of","push","consented","consentedByOperator","grandfathered","consentWithheld","suppressed","cadenceHeld","caveats","message","audienceSizeTruncated","deferred","CAMPAIGN_LINK_ROLLUP_MAX","campaignLinkKey","link","raw","String","trim","url","URL","protocol","path","pathname","length","replace","origin","campaignLinkReport","rollup","entries","Object","values","links","map","entry","filter","attributedClicks","reduce","total","one","rows","sort","a","b","localeCompare","share","overflowClicks","unattributedClicks","truncated","CAMPAIGN_SEQUENCE_OUTCOMES","CAMPAIGN_SEQUENCE_REPORTS_COLLECTION","CAMPAIGN_SEQUENCE_OUTCOME_COPY","enrolled","note","replied","meetings","converted","campaignSequencesReport","stored","byOutcome","figures","outcome","Math","floor","any","some","figure","recorded"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiDC,GAED;;;;;;;CAOC;AAwFD;;;;;CAKC,GACD,OAAO,SAASA,aACdC,SAA6B,EAC7BC,WAA+B,EAC/BC,gBAAwB;IAExB,MAAMC,MAAMC,OAAOJ,oBAAAA,YAAa;IAChC,MAAMK,SAASD,OAAOH,sBAAAA,cAAe;IACrC,IAAI,CAACG,OAAOE,QAAQ,CAACH,QAAQ,CAACC,OAAOE,QAAQ,CAACD,SAAS,OAAO;IAC9D,IAAIA,UAAU,GAAG,OAAO;IACxB,OAAO;QACLE,OAAOJ,MAAME;QACbL,WAAWG;QACXF,aAAaI;QACbH;IACF;AACF;AAiFA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASM,eAAeC,KAAgC;QAEzCC,cACMA,oBACLA,eACCA,gBACCA,iBACGA,oBACEA,sBAkEAA,s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pE,qEAAqE;YACrE7B,OAAO+C,QAAQnC,aAAa,CAACf,OAAOE,QAAQ,CAACC,UAAUA,SAAS,IAAI,OAAOA;YAC3EoF,MAAMF,8BAA8B,CAACU,QAAQ,CAACR,IAAI;QACpD;IACF;IACA,MAAMW,MAAMJ,QAAQK,IAAI,CAAC,CAACC,SAAWA,OAAOjG,KAAK,KAAK;IACtD,MAAMwC,UAA4BuD,MAC9B;QACE;YACEnE,IAAI;YACJa,SACE,uEACA,uEACA;QACJ;KACD,GACD,EAAE;IACN,OAAO;QAAEkD;QAASO,UAAUvC,WAAW/C;QAAWmF;QAAKvD;IAAQ;AACjE"}
1
+ {"version":3,"sources":["../../../../../../../../libs/shared/ui/email-campaigns/src/lib/model/campaign-report.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * CAMPAIGN REPORTING MATH — the only place a rate is computed.\n *\n * ## Why a pure module and not a component\n *\n * Every number on the report screen is a division, and a division is where\n * email reporting goes wrong. Putting the arithmetic in JSX means the\n * denominator is chosen by whoever writes the next card, in a file nobody\n * tests for arithmetic; putting it here means each rate is named once,\n * carries its own denominator as data, and is provable.\n *\n * ## The rule this module exists to enforce\n *\n * **A rate is a triple — numerator, denominator, and the NAME of the\n * denominator — or it is not reported.** An open rate over `sent` and an open\n * rate over `delivered` are different numbers with the same label, and the\n * gap between them is exactly the mail that bounced. The industry convention\n * is over `delivered`, and a report that quietly used `sent` would read\n * higher than the same campaign measured anywhere else.\n *\n * So {@link CampaignRate} carries `denominatorLabel`, and the screen is\n * required to render it. There is no overload that omits it.\n *\n * ## Why some rates are deliberately absent\n *\n * {@link campaignRate} answers `null`, not zero, when it cannot divide:\n *\n * - **A zero denominator.** 0 opens out of 0 delivered is not a 0% open\n * rate, it is no open rate. Rendering 0% invites the reader to compare it\n * with a campaign that really did fail.\n * - **An UNKNOWN denominator.** `delivered` is counted by the delivery\n * webhook, which was connected after some campaigns were sent. A campaign\n * with 400 sends and no delivery events has an unknown denominator, not a\n * denominator of zero — and dividing by `sent` instead is precisely the\n * flattering substitution above.\n *\n * ## The structural-zero window\n *\n * Click tracking rewrites links in the HTML part. Sends that carried no HTML\n * part were therefore untrackable, and every one of those campaigns reports 0\n * clicks whatever the recipients actually did — a real 0 and a structural 0\n * rendered identically. `send-email.ts` now synthesises an HTML part for a\n * text-only send, so every send after that carries one, and\n * `campaign-send.ts` records {@link CampaignStats.clickTracked} to say so.\n *\n * A campaign with no such marker predates the record. Its click COUNT is\n * still shown — it is a real count of real events — but no click RATE is\n * computed from it, because a rate presents the number as a measurement of\n * the audience and for those campaigns it is a measurement of the sender.\n */\n\n/**\n * The `stats` map on `hosts/{hostId}/campaigns/{campaignId}`.\n *\n * Every field is optional and every reader defaults it, because these are\n * written by three different writers at three different times — the send, the\n * delivery webhook, the unsubscribe handler — and a campaign is a legitimate,\n * readable document from the instant the first of them lands.\n */\nexport interface CampaignStats {\n /*========================================\n * WRITTEN BY THE SEND. Never recomputed.\n *\n * These are the truth of what happened, recorded once by the code that did\n * it. Re-deriving any of them at read time would produce a number that\n * disagrees with the send — the audience has moved on since, suppressions\n * have been added, consent has been recorded — and the recorded one is the\n * one that describes the campaign.\n *=======================================*/\n /** The whole audience the send was taken from, before the per-send cap. */\n audienceSize?: number\n /** `audienceSize` is a FLOOR: audience resolution hit its read ceiling. */\n audienceSizeTruncated?: boolean\n /** Addresses this send ADDRESSED — the audience after the per-send cap. */\n recipients?: number\n /** Messages the provider accepted. The `sent` in \"sent/recipients\". */\n sent?: number\n /** Of the audience, how many carry a recorded marketing consent basis. */\n consented?: number\n /** Of `consented`, how many hold a basis an operator asserted for them. */\n consentedByOperator?: number\n /** Of the audience, how many are reachable only because enforcement is\n * not retroactive — the population a strict consent policy removes. */\n grandfathered?: number\n /** Of the audience, how many the consent rule refused to mail. */\n consentWithheld?: number\n /** Of `recipients`, how many were already suppressed (unsubscribed,\n * bounced or complained on an earlier send). */\n suppressed?: number\n /** Of `recipients`, how many asked this site for mail less often than this\n * send would have arrived. Still subscribed; reached by a later campaign. */\n cadenceHeld?: number\n /** Recipients the hourly send governor refused mid-batch. */\n deferred?: number\n /**\n * This send carried an HTML part, so its links were trackable.\n *\n * Absent on every campaign sent before the field existed — see the\n * structural-zero note in this module's header. Absent is NOT false; it is\n * \"not recorded\", and the report says so rather than guessing.\n */\n clickTracked?: boolean\n /** Per-variant send counts for an A/B campaign. */\n variantSends?: Record<string, number>\n\n /*========================================\n * WRITTEN BY THE DELIVERY WEBHOOK, as increments.\n *=======================================*/\n /** Messages the receiving server accepted. The rate DENOMINATOR. */\n delivered?: number\n /** Open EVENTS. One reader opening four times counts four. */\n opens?: number\n /** Click EVENTS. One reader clicking three links counts three. */\n clicks?: number\n /** Messages whose FIRST open was seen — distinct readers who opened. */\n uniqueOpens?: number\n /** Messages whose FIRST click was seen — distinct readers who clicked. */\n uniqueClicks?: number\n /** Messages that bounced, permanent and transient together. */\n bounced?: number\n /** Recipients who pressed \"report spam\". */\n complained?: number\n\n /*========================================\n * WRITTEN BY THE UNSUBSCRIBE HANDLER.\n *=======================================*/\n /** Recipients who unsubscribed through THIS campaign's link. */\n unsubscribes?: number\n}\n\n/**\n * One rate, with the denominator it was taken over named as data.\n *\n * `denominatorLabel` is not a display nicety. It is the field that makes two\n * numbers called \"open rate\" distinguishable, and the screen renders it\n * beside the percentage for that reason.\n */\nexport interface CampaignRate {\n /** 0–1. Multiply for display; the model never formats. */\n value: number\n numerator: number\n denominator: number\n /** Reader-facing name of the denominator, e.g. `'delivered'`. */\n denominatorLabel: string\n}\n\n/**\n * A rate, or `null` when one cannot honestly be taken.\n *\n * `null` on a zero or unknown denominator — see the module header for why\n * that is not the same as 0%.\n */\nexport function campaignRate(\n numerator: number | undefined,\n denominator: number | undefined,\n denominatorLabel: string,\n): CampaignRate | null {\n const top = Number(numerator ?? 0)\n const bottom = Number(denominator ?? 0)\n if (!Number.isFinite(top) || !Number.isFinite(bottom)) return null\n if (bottom <= 0) return null\n return {\n value: top / bottom,\n numerator: top,\n denominator: bottom,\n denominatorLabel,\n }\n}\n\n/** Why a number the report would otherwise show is being withheld. */\nexport interface CampaignCaveat {\n /** Stable id, so a spec can assert on the caveat rather than its prose. */\n id:\n | 'delivery-unrecorded'\n | 'click-tracking-unrecorded'\n | 'audience-truncated'\n | 'send-deferred'\n /* Raised by `campaign-revenue.ts`, which reports through this shape so\n * the screen has one way of saying \"a number is being withheld and here\n * is why\" rather than one per section. */\n | 'revenue-denominator-unrecorded'\n | 'revenue-multi-currency'\n | 'revenue-mid-flight'\n | 'revenue-mixed-model'\n /* Raised by `campaign-conversions.ts`, through this shape for the same\n * reason: one way of saying \"a number is being withheld, or must not be\n * read the obvious way, and here is why\". The first two are the reasons\n * the four conversion kinds stand apart instead of totalling; the last\n * two qualify the uncredited figure rather than withholding it. */\n | 'conversions-kinds-overlap'\n | 'conversions-web-not-rolled-up'\n | 'conversions-unattributed-is-a-ceiling'\n | 'conversions-total-crosses-hosts'\n /* Raised by the Sequences block below (AGL-3254): the five figures are\n * a funnel read across, never a sum. */\n | 'sequences-funnel-not-summed'\n message: string\n}\n\n/** One population the send measured, for the audience breakdown. */\nexport interface CampaignPopulation {\n id: string\n label: string\n count: number\n /** What this count is a part OF, named. */\n ofLabel: string\n of: number\n}\n\n/** Everything the report screen renders, decided here rather than in JSX. */\nexport interface CampaignReport {\n sent: number\n recipients: number\n delivered: number | null\n opens: number\n clicks: number\n uniqueOpens: number | null\n uniqueClicks: number | null\n bounced: number\n complained: number\n unsubscribes: number\n /** Rates, each `null` when its denominator is zero or unrecorded. */\n rates: {\n /** Accepted by the receiving server, over what the provider accepted. */\n delivery: CampaignRate | null\n /** Distinct readers who opened, over delivered. */\n open: CampaignRate | null\n /** Distinct readers who clicked, over delivered. */\n click: CampaignRate | null\n /**\n * Distinct clickers over distinct OPENERS — a different question from\n * `click`, and the one the two get confused for. It answers \"of the\n * people who read it, how many acted\", not \"of the people who received\n * it\". Reported separately and labelled separately, never as \"click\n * rate\".\n */\n clickToOpen: CampaignRate | null\n /** Bounced over what the provider accepted. */\n bounce: CampaignRate | null\n /** Complaints over delivered — the number mailbox providers judge on. */\n complaint: CampaignRate | null\n /** Unsubscribes through this campaign's link, over delivered. */\n unsubscribe: CampaignRate | null\n }\n populations: CampaignPopulation[]\n caveats: CampaignCaveat[]\n}\n\n/**\n * Turns a stored `stats` map into the report.\n *\n * ## The denominator decisions, in one place\n *\n * - **`delivered`** carries the engagement rates — open, click, complaint,\n * unsubscribe. Mail that bounced was never in front of a human, so\n * including it in the denominator of an open rate depresses a number that\n * describes the audience with a fact about the address list. This is also\n * the convention every other tool reports, which matters: a merchant\n * comparing our figure with their previous ESP's must be comparing the same\n * quantity.\n * - **`sent`** carries the delivery and bounce rates, because those describe\n * what happened to what we handed the provider, and `delivered` is the\n * numerator of one of them — a rate cannot be over itself.\n * - **`uniqueOpens`** is the open-rate numerator, not `opens`. Open EVENTS\n * over recipients can exceed 100% the moment one person opens twice, and a\n * percentage above 100 is how a reader learns the number means something\n * other than what it says. Both are shown; only the distinct count is\n * divided.\n *\n * ## `delivered` unknown vs. zero\n *\n * A campaign predating the delivery webhook records no `delivered` at all.\n * That is reported as `null` and every rate over it is withheld, with a\n * caveat naming the reason — rather than substituting `sent`, which would\n * silently publish the flattered number this module exists to refuse.\n */\nexport function campaignReport(stats: CampaignStats | undefined): CampaignReport {\n const source = stats ?? {}\n const sent = Number(source.sent ?? 0)\n const recipients = Number(source.recipients ?? 0)\n const opens = Number(source.opens ?? 0)\n const clicks = Number(source.clicks ?? 0)\n const bounced = Number(source.bounced ?? 0)\n const complained = Number(source.complained ?? 0)\n const unsubscribes = Number(source.unsubscribes ?? 0)\n\n /*\n * ABSENT, not zero. `stats.delivered` is written only by the delivery\n * webhook, so `undefined` means \"no delivery event has ever been recorded\n * for this campaign\" — which for an old campaign means the webhook was not\n * connected, and for a campaign sent thirty seconds ago means the events\n * are still in flight. Neither is \"nothing was delivered\", and both are\n * ruined by `?? 0`, which would turn the unknown into a hard zero and make\n * every rate over it `null` for the RIGHT answer by the WRONG reasoning —\n * and would render \"0 delivered\" on screen beside \"500 sent\".\n */\n const delivered =\n source.delivered === undefined ? null : Number(source.delivered)\n const uniqueOpens =\n source.uniqueOpens === undefined ? null : Number(source.uniqueOpens)\n const uniqueClicks =\n source.uniqueClicks === undefined ? null : Number(source.uniqueClicks)\n\n /*\n * The click rate is withheld for a campaign that never recorded carrying an\n * HTML part, even when clicks are non-zero and `delivered` is known. See\n * the structural-zero note in the module header: for those sends 0 is the\n * only value the number could ever have taken, so a rate computed from it\n * measures our sending code rather than the recipients.\n */\n const clickTrackable = source.clickTracked === true\n\n const rates: CampaignReport['rates'] = {\n /*\n * `null` when `delivered` is UNRECORDED, and this is the one rate where\n * the numerator can be unknown rather than zero.\n *\n * Everywhere else an absent numerator is a genuine nought — a campaign\n * with delivery events and no opens really does have a 0% open rate, and\n * that is worth showing. Here the numerator IS the unrecorded quantity,\n * so `campaignRate(undefined, 1000, 'sent')` would divide a missing\n * measurement by a real one and publish \"0.0% delivery rate — 0 of 1,000\n * sent\" for a campaign whose delivery events were merely never recorded.\n * That is the flattering-substitution failure this module exists to\n * refuse, running in the other direction: not a rate that reads too high,\n * but a campaign that reads as a total delivery failure.\n */\n delivery:\n delivered === null ? null : campaignRate(delivered, sent, 'sent'),\n open: campaignRate(uniqueOpens ?? undefined, delivered ?? undefined, 'delivered'),\n click: clickTrackable\n ? campaignRate(uniqueClicks ?? undefined, delivered ?? undefined, 'delivered')\n : null,\n clickToOpen: clickTrackable\n ? campaignRate(uniqueClicks ?? undefined, uniqueOpens ?? undefined, 'unique openers')\n : null,\n bounce: campaignRate(bounced, sent, 'sent'),\n complaint: campaignRate(complained, delivered ?? undefined, 'delivered'),\n unsubscribe: campaignRate(unsubscribes, delivered ?? undefined, 'delivered'),\n }\n\n /*\n * The populations the SEND measured, reported as parts of a named whole\n * rather than as bare counts. \"412 withheld\" invites the question \"out of\n * what\"; the answer is the audience, and it is a different whole from the\n * one `suppressed` is measured against — consent is decided over the whole\n * audience and suppression over the capped recipient list, because that is\n * where each check runs. Netting them into one column would present two\n * different denominators as one.\n */\n const audienceSize = Number(source.audienceSize ?? 0)\n const populations: CampaignPopulation[] = []\n const addPopulation = (\n id: string,\n label: string,\n count: number | undefined,\n ofLabel: string,\n of: number,\n ) => {\n if (count === undefined) return\n populations.push({ id, label, count: Number(count), ofLabel, of })\n }\n addPopulation(\n 'consented',\n 'Had a consent basis',\n source.consented,\n 'audience',\n audienceSize,\n )\n addPopulation(\n 'consentedByOperator',\n 'Consent asserted by an operator',\n source.consentedByOperator,\n 'audience',\n audienceSize,\n )\n addPopulation(\n 'grandfathered',\n 'Reachable only because consent is not enforced retroactively',\n source.grandfathered,\n 'audience',\n audienceSize,\n )\n addPopulation(\n 'consentWithheld',\n 'Withheld by the consent rule',\n source.consentWithheld,\n 'audience',\n audienceSize,\n )\n addPopulation(\n 'suppressed',\n 'Already suppressed',\n source.suppressed,\n 'addressed',\n recipients,\n )\n addPopulation(\n 'cadenceHeld',\n 'Asked for mail less often than this',\n source.cadenceHeld,\n 'addressed',\n recipients,\n )\n\n const caveats: CampaignCaveat[] = []\n if (delivered === null) {\n caveats.push({\n id: 'delivery-unrecorded',\n message:\n 'No delivery events have been recorded for this campaign, so open, ' +\n 'click, complaint and unsubscribe rates cannot be computed — every ' +\n 'one of them is taken over delivered. Counts below are still real.',\n })\n }\n if (!clickTrackable) {\n caveats.push({\n id: 'click-tracking-unrecorded',\n message:\n 'This send did not record carrying an HTML part. Click tracking ' +\n 'rewrites links in the HTML, so a send without one reports zero ' +\n 'clicks whatever recipients did. The click count is shown; no click ' +\n 'rate is computed from it.',\n })\n }\n if (source.audienceSizeTruncated) {\n caveats.push({\n id: 'audience-truncated',\n message:\n 'Audience resolution stopped at its read ceiling, so the audience ' +\n 'size is a floor — the real audience is at least this large, and ' +\n 'every share taken over it is at most the figure shown.',\n })\n }\n if (Number(source.deferred ?? 0) > 0) {\n caveats.push({\n id: 'send-deferred',\n message:\n `${Number(source.deferred)} recipients were held back by the hourly ` +\n 'send governor and never received this campaign. They are counted in ' +\n 'addressed, not in sent.',\n })\n }\n\n return {\n sent,\n recipients,\n delivered,\n opens,\n clicks,\n uniqueOpens,\n uniqueClicks,\n bounced,\n complained,\n unsubscribes,\n rates,\n populations,\n caveats,\n }\n}\n\n/*==========================================\n * LINK-LEVEL CLICKS.\n *\n * Resend's `email.clicked` payload carries `data.click.link`, the destination\n * the recipient followed; `normalizeResendDeliveryEvents` already reads it\n * into `EmailDeliveryEvent.link`, and the per-recipient delivery log already\n * stores it. What did not exist was an aggregate — which is what \"link\n * clicks\" means, and it cannot be produced from the delivery log without\n * reading every recipient row for the campaign.\n *\n * So it is a WRITE-TIME rollup: one document per campaign,\n * `campaigns/{campaignId}/reports/links`, holding a bounded map. The report\n * reads exactly one document for the whole table.\n *=========================================*/\n\n/**\n * How many distinct destinations one campaign's rollup keeps.\n *\n * A CAP rather than a page size, and it exists because the map lives in a\n * single document with a 1 MiB ceiling. Clicks past the cap are counted in\n * {@link CampaignLinkRollup.overflowClicks} rather than dropped, so the\n * table's total still reconciles with `stats.clicks`.\n */\nexport const CAMPAIGN_LINK_ROLLUP_MAX = 50\n\n/**\n * Reduces a clicked URL to the key the rollup counts under.\n *\n * ## Why the query string is dropped\n *\n * Two reasons, and the second is the one that forces it:\n *\n * 1. **A campaign body goes through `resolveMergeTags` per recipient**, so a\n * link may carry a personalised query. Keying on the full URL would then\n * mint one rollup row per RECIPIENT — the aggregate degenerates into the\n * per-recipient log it exists to summarise, and it blows the cap on the\n * first campaign that does it.\n * 2. **A personalised query can carry the recipient's own address.** The\n * rollup is an aggregate read by everyone on the site's team; it must not\n * become a list of who clicked, and dropping the query is what guarantees\n * it cannot.\n *\n * ⚠️ The cost is real and is stated on the screen: two links to the same page\n * distinguished only by their UTM parameters count as ONE row. That is a\n * known limitation, not an oversight — see the note in the report card.\n *\n * @returns the normalized URL, or `null` for anything unparseable or not\n * http(s). A rollup key must be a URL a merchant recognises.\n */\nexport function campaignLinkKey(link: string | null | undefined): string | null {\n const raw = String(link ?? '').trim()\n if (!raw) return null\n try {\n const url = new URL(raw)\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return null\n // Trailing slash normalised away so `/pricing` and `/pricing/` are one\n // row; the bare origin keeps its slash so the key is still a valid URL.\n const path = url.pathname.length > 1\n ? url.pathname.replace(/\\/+$/, '')\n : url.pathname\n return `${url.origin}${path}`\n } catch {\n return null\n }\n}\n\n/** One destination in the rollup. */\nexport interface CampaignLinkRow {\n url: string\n /** Click EVENTS on this destination. One reader clicking twice counts two. */\n clicks: number\n /** Share of the campaign's counted link clicks. */\n share: CampaignRate | null\n}\n\n/** The stored shape of `campaigns/{campaignId}/reports/links`. */\nexport interface CampaignLinkRollup {\n links?: Record<string, { url?: string; clicks?: number }>\n /** Clicks on destinations past {@link CAMPAIGN_LINK_ROLLUP_MAX}. */\n overflowClicks?: number\n /** Click events that arrived carrying no destination at all. */\n unattributedClicks?: number\n}\n\n/** What the link table renders. */\nexport interface CampaignLinkReport {\n rows: CampaignLinkRow[]\n /** Clicks counted against a named destination — the table's total. */\n attributedClicks: number\n overflowClicks: number\n unattributedClicks: number\n /** True once the cap bit, so the table says it is not the whole list. */\n truncated: boolean\n}\n\n/**\n * The link table, sorted by clicks descending.\n *\n * `share` is over ATTRIBUTED clicks — the clicks this table accounts for —\n * and not over `stats.clicks`. The two differ by the overflow and the\n * unattributed, and a share column that did not sum to 100% because of rows\n * that are not on screen is the kind of arithmetic a reader cannot check.\n * Both excluded figures are returned so the screen can state them.\n */\nexport function campaignLinkReport(\n rollup: CampaignLinkRollup | undefined,\n): CampaignLinkReport {\n const entries = Object.values(rollup?.links ?? {})\n .map((entry) => ({\n url: String(entry?.url ?? ''),\n clicks: Number(entry?.clicks ?? 0),\n }))\n .filter((entry) => entry.url && Number.isFinite(entry.clicks))\n const attributedClicks = entries.reduce((total, one) => total + one.clicks, 0)\n const rows = [...entries]\n .sort((a, b) => b.clicks - a.clicks || a.url.localeCompare(b.url))\n .map((entry) => ({\n ...entry,\n share: campaignRate(entry.clicks, attributedClicks, 'link clicks counted'),\n }))\n const overflowClicks = Number(rollup?.overflowClicks ?? 0)\n return {\n rows,\n attributedClicks,\n overflowClicks,\n unattributedClicks: Number(rollup?.unattributedClicks ?? 0),\n truncated: entries.length >= CAMPAIGN_LINK_ROLLUP_MAX || overflowClicks > 0,\n }\n}\n\n/*==========================================\n * WHAT THE CAMPAIGN'S SEQUENCES PRODUCED (AGL-3254).\n *\n * A sequence joins a campaign the way a form does — `campaignIds` on its own\n * document — and its outcomes are then the campaign's to report: every\n * person enrolled, the first email each one was sent, the replies, the\n * meetings booked from a sequence link, and the enrolled leads that\n * converted. The Outreach runtime credits each outcome once per enrollment\n * to every campaign the sequence was in when the person was enrolled, into\n * `hosts/{hostId}/campaignSequenceReports/{campaignId}` — one document per\n * campaign, beside the conversions rollup and never inside the campaign\n * document, which the history list and the glance widget read.\n *\n * ## The five figures are a funnel, not a sum\n *\n * Each figure counts ENROLLMENTS at a stage: 40 enrolled, 38 sent, 6\n * replied, 2 meetings, 1 converted. They are read across, never added — a\n * person is in every stage they reached — and the model keeps them as an\n * ordered list rather than a total for the reason the conversion kinds are\n * kept apart.\n *\n * ## Absent is not zero\n *\n * A campaign no sequence was ever in has no document, and a stage nobody\n * reached has no field. Both are `null` here, so the screen can say\n * \"nothing recorded\" for the first and draw a dash for the second, rather\n * than printing a measured 0 replies for a campaign whose sequence went\n * out yesterday.\n *=========================================*/\n\n/**\n * The outcomes the runtime credits, in funnel order. An array first, because\n * the ORDER is the reading order and a second list is a second chance to\n * leave one out; the union is derived from it.\n */\nexport const CAMPAIGN_SEQUENCE_OUTCOMES = [\n 'enrolled',\n 'sent',\n 'replied',\n 'meetings',\n 'converted',\n] as const\n\nexport type CampaignSequenceOutcome = (typeof CAMPAIGN_SEQUENCE_OUTCOMES)[number]\n\n/**\n * The org collection holding one document per campaign container,\n * `orgs/{orgId}/campaignSequenceReports/{campaignId}`.\n */\nexport const CAMPAIGN_SEQUENCE_REPORTS_COLLECTION = 'campaignSequenceReports'\n\n/** What a reader calls each outcome, and what the count means. */\nexport const CAMPAIGN_SEQUENCE_OUTCOME_COPY: Readonly<\n Record<CampaignSequenceOutcome, { label: string; note: string }>\n> = {\n enrolled: { label: 'Enrolled', note: 'people enrolled in a sequence in this campaign' },\n sent: { label: 'Sent', note: 'of them, sent their first sequence email' },\n replied: { label: 'Replied', note: 'of them, who wrote back' },\n meetings: { label: 'Meetings', note: 'bookings made from a sequence link' },\n converted: { label: 'Converted', note: 'enrolled leads that became contacts' },\n}\n\n/**\n * The stored shape of `campaignSequenceReports/{campaignId}`.\n *\n * Read-side only, every field optional: another plugin's runtime wrote it,\n * and a reader that assumed a field was present would throw on the first\n * document written before the field existed.\n */\nexport interface CampaignSequencesRollup {\n byOutcome?: Partial<Record<CampaignSequenceOutcome, number>>\n /** When the runtime last credited anything, epoch ms. */\n updatedAtMs?: number\n}\n\n/** One outcome's figure on screen. */\nexport interface CampaignSequenceFigure {\n outcome: CampaignSequenceOutcome\n label: string\n /** The count, or `null` when the rollup holds no entry for the outcome. */\n value: number | null\n note: string\n}\n\n/** Everything the Sequences section renders. */\nexport interface CampaignSequencesReport {\n /** Always all five, always in {@link CAMPAIGN_SEQUENCE_OUTCOMES} order. */\n figures: CampaignSequenceFigure[]\n /** Whether the rollup document exists at all — see the block header. */\n recorded: boolean\n /** At least one outcome holds a figure. */\n any: boolean\n caveats: CampaignCaveat[]\n}\n\n/** Turns the stored rollup into the Sequences section. */\nexport function campaignSequencesReport(\n rollup: CampaignSequencesRollup | undefined,\n): CampaignSequencesReport {\n const stored = rollup?.byOutcome ?? {}\n const figures: CampaignSequenceFigure[] = CAMPAIGN_SEQUENCE_OUTCOMES.map((outcome) => {\n const raw = stored[outcome]\n const value = Math.floor(Number(raw ?? 0))\n return {\n outcome,\n label: CAMPAIGN_SEQUENCE_OUTCOME_COPY[outcome].label,\n // Unrecorded, negative and non-numeric all read as \"no figure\": the\n // runtime only ever increments, so a stored 0 is not a count either.\n value: raw === undefined || !Number.isFinite(value) || value <= 0 ? null : value,\n note: CAMPAIGN_SEQUENCE_OUTCOME_COPY[outcome].note,\n }\n })\n const any = figures.some((figure) => figure.value !== null)\n const caveats: CampaignCaveat[] = any\n ? [\n {\n id: 'sequences-funnel-not-summed',\n message:\n 'Each figure counts the people who reached that stage, so a person ' +\n 'who replied is counted under Enrolled and Sent as well. Read them ' +\n 'across; they are deliberately not added together.',\n },\n ]\n : []\n return { figures, recorded: rollup !== undefined, any, caveats }\n}\n"],"names":["campaignRate","numerator","denominator","denominatorLabel","top","Number","bottom","isFinite","value","campaignReport","stats","source","sent","recipients","opens","clicks","bounced","complained","unsubscribes","delivered","undefined","uniqueOpens","uniqueClicks","clickTrackable","clickTracked","rates","delivery","open","click","clickToOpen","bounce","complaint","unsubscribe","audienceSize","populations","addPopulation","id","label","count","ofLabel","of","push","consented","consentedByOperator","grandfathered","consentWithheld","suppressed","cadenceHeld","caveats","message","audienceSizeTruncated","deferred","CAMPAIGN_LINK_ROLLUP_MAX","campaignLinkKey","link","raw","String","trim","url","URL","protocol","path","pathname","length","replace","origin","campaignLinkReport","rollup","entries","Object","values","links","map","entry","filter","attributedClicks","reduce","total","one","rows","sort","a","b","localeCompare","share","overflowClicks","unattributedClicks","truncated","CAMPAIGN_SEQUENCE_OUTCOMES","CAMPAIGN_SEQUENCE_REPORTS_COLLECTION","CAMPAIGN_SEQUENCE_OUTCOME_COPY","enrolled","note","replied","meetings","converted","campaignSequencesReport","stored","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