@aglyn/plugins-marketing 1.18.0 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +16 -16
- package/src/lib/components/campaign-detail-card.js +38 -13
- package/src/lib/components/campaign-detail-card.js.map +1 -1
- package/src/lib/components/campaign-edit-drawer.d.ts +11 -4
- package/src/lib/components/campaign-edit-drawer.js +57 -54
- package/src/lib/components/campaign-edit-drawer.js.map +1 -1
- package/src/lib/components/campaign-sharing-form-field.d.ts +14 -0
- package/src/lib/components/campaign-sharing-form-field.js +69 -0
- package/src/lib/components/campaign-sharing-form-field.js.map +1 -0
- package/src/lib/components/campaigns-card.js +91 -27
- package/src/lib/components/campaigns-card.js.map +1 -1
- package/src/lib/components/use-campaign-containers-blocked.d.ts +15 -1
- package/src/lib/components/use-campaign-containers-blocked.js +25 -4
- package/src/lib/components/use-campaign-containers-blocked.js.map +1 -1
- package/src/lib/model/campaign-container.d.ts +73 -7
- package/src/lib/model/campaign-container.js +121 -12
- package/src/lib/model/campaign-container.js.map +1 -1
- package/src/lib/server/campaign-manage.d.ts +5 -3
- package/src/lib/server/campaign-manage.js +111 -25
- package/src/lib/server/campaign-manage.js.map +1 -1
- package/src/lib/transfer/campaigns-package.server.js +10 -1
- package/src/lib/transfer/campaigns-package.server.js.map +1 -1
|
@@ -68,6 +68,7 @@
|
|
|
68
68
|
*/
|
|
69
69
|
import { type ListUnsubscribeForcedReason } from '@aglyn/shared-util-email/list-unsubscribe';
|
|
70
70
|
import { type SendRate, type SendStats } from '@aglyn/shared-ui-email-campaigns/model/send-report';
|
|
71
|
+
import { sharingFromChoice, type ScopeSharingChoice } from '@aglyn/aglyn/app-utils/scope-tokens';
|
|
71
72
|
/** The org collection holding campaign CONTAINERS. */
|
|
72
73
|
export declare const EMAIL_CAMPAIGNS_COLLECTION = "emailCampaigns";
|
|
73
74
|
/** The org collection holding SENDS — one document per email. */
|
|
@@ -107,21 +108,77 @@ export declare function campaignSendVisibleTo(hostId: string): string[];
|
|
|
107
108
|
* recoverable direction.
|
|
108
109
|
*/
|
|
109
110
|
export declare function campaignSiteIds(campaign: Pick<EmailCampaign, 'visibleTo'> | null | undefined): string[] | null;
|
|
111
|
+
/**
|
|
112
|
+
* Whether a container is shared with all sites except some (AGL-4047): either
|
|
113
|
+
* marker key present, as the rules' `scopeUnmarked` reads it, so a stored null
|
|
114
|
+
* or half a marker fails closed.
|
|
115
|
+
*/
|
|
116
|
+
export declare function campaignSharingMarked(campaign: Pick<EmailCampaign, 'scopeMode' | 'scopeExcept'> | null | undefined): boolean;
|
|
110
117
|
/**
|
|
111
118
|
* Whether a container is placed on this one site and no other: the placement
|
|
112
119
|
* where the site's own "Run email campaigns" counts for writing it (AGL-4047).
|
|
120
|
+
*
|
|
121
|
+
* Never for a container shared with all sites except some, however few sites
|
|
122
|
+
* it reaches today. Its list can shrink to one site while it still belongs to
|
|
123
|
+
* the whole workspace, and the next new site joins it, so that one site's
|
|
124
|
+
* Admins never come to answer for it. The rules' `scopePlacement` and core's
|
|
125
|
+
* `oneSitePlacement` answer the same.
|
|
126
|
+
*/
|
|
127
|
+
export declare function campaignPlacedOnlyOn(campaign: Pick<EmailCampaign, 'visibleTo' | 'scopeMode' | 'scopeExcept'> | null | undefined, hostId: string): boolean;
|
|
128
|
+
/**
|
|
129
|
+
* Whether the site door of the manage route may delete this container: one
|
|
130
|
+
* placed on this site and on no other, and not shared with all sites except
|
|
131
|
+
* some. Deleting anything wider takes it off other sites too, which asks for
|
|
132
|
+
* access to every site in the workspace (AGL-4047).
|
|
133
|
+
*/
|
|
134
|
+
export declare function campaignSiteMayDelete(campaign: Pick<EmailCampaign, 'visibleTo' | 'scopeMode' | 'scopeExcept'> | null | undefined, hostId: string): boolean;
|
|
135
|
+
/**
|
|
136
|
+
* Why a member with access to some sites only may not delete this container
|
|
137
|
+
* from a site's hub, as the manage route and the console both say it. Names
|
|
138
|
+
* what it takes, never a role.
|
|
139
|
+
*/
|
|
140
|
+
export declare function campaignSiteDeleteRefusal(campaign: Pick<EmailCampaign, 'scopeMode' | 'scopeExcept'> | null | undefined): string;
|
|
141
|
+
/**
|
|
142
|
+
* What a sharing choice writes on a container, or why it cannot be written
|
|
143
|
+
* (AGL-4047): `sharingFromChoice` over the workspace's sites, with a chosen
|
|
144
|
+
* site the workspace no longer holds dropped rather than stored.
|
|
145
|
+
*
|
|
146
|
+
* This is where the old silent cap went. A container used to keep the first
|
|
147
|
+
* thirty sites of a longer selection and say nothing; now a choice of more
|
|
148
|
+
* than thirty sites is refused with the reason, and "All sites except…" has
|
|
149
|
+
* no such ceiling, because a container's stored fields do not multiply by
|
|
150
|
+
* site (its search keys come from its name alone). The console asks it before
|
|
151
|
+
* a save, and the manage route asks it again with the sites it reads itself.
|
|
113
152
|
*/
|
|
114
|
-
export declare function
|
|
153
|
+
export declare function campaignSharingWrite(choice: ScopeSharingChoice, orgHostIds: readonly string[]): ReturnType<typeof sharingFromChoice>;
|
|
154
|
+
/**
|
|
155
|
+
* A container's sharing as the sharing field edits it, or null where it
|
|
156
|
+
* stores none (an absent or empty `visibleTo`, which no reader matches).
|
|
157
|
+
*/
|
|
158
|
+
export declare function campaignSharingChoice(campaign: Pick<EmailCampaign, 'visibleTo' | 'scopeMode' | 'scopeExcept'> | null | undefined): ScopeSharingChoice | null;
|
|
159
|
+
/** Two sharing choices compare by what they pick, in any order. */
|
|
160
|
+
export declare function campaignSharingKey(choice: ScopeSharingChoice | null | undefined): string;
|
|
161
|
+
/**
|
|
162
|
+
* A sharing choice off the wire, or null for anything else. The ids are
|
|
163
|
+
* checked against the workspace after, by {@link campaignSharingWrite}.
|
|
164
|
+
*/
|
|
165
|
+
export declare function campaignSharingChoiceFrom(value: unknown): ScopeSharingChoice | null;
|
|
166
|
+
/**
|
|
167
|
+
* Where a container shared with all sites except some is offered, naming the
|
|
168
|
+
* sites left out where the reader can name them (`describeSharing`), or null
|
|
169
|
+
* for any other container, whose sites the surfaces list as they always have.
|
|
170
|
+
* Listing today's sites would read as sites somebody chose, and the next new
|
|
171
|
+
* site joins it.
|
|
172
|
+
*/
|
|
173
|
+
export declare function campaignAllExceptLabel(campaign: Pick<EmailCampaign, 'visibleTo' | 'scopeMode' | 'scopeExcept'> | null | undefined, hostNames: Readonly<Record<string, string>>): string | null;
|
|
115
174
|
/** Whether a container is offered on this site. */
|
|
116
175
|
export declare function campaignPlacedOnHost(campaign: Pick<EmailCampaign, 'visibleTo'> | null | undefined, hostId: string): boolean;
|
|
117
176
|
/**
|
|
118
|
-
* The `visibleTo` a container
|
|
119
|
-
*
|
|
120
|
-
*
|
|
121
|
-
* capped at thirty, the ceiling `array-contains-any` and the rules' `hasAny`
|
|
122
|
-
* both impose.
|
|
177
|
+
* The `visibleTo` of a container created under one site: that site alone. A
|
|
178
|
+
* site hub's create and an AI draft both place a campaign where it was made.
|
|
179
|
+
* Every other placement is a sharing choice, {@link campaignSharingWrite}.
|
|
123
180
|
*/
|
|
124
|
-
export declare function
|
|
181
|
+
export declare function campaignSiteVisibleTo(hostId: string): string[];
|
|
125
182
|
/**
|
|
126
183
|
* The field on a SEND naming the campaign it belongs to.
|
|
127
184
|
*
|
|
@@ -162,6 +219,15 @@ export interface EmailCampaign {
|
|
|
162
219
|
* every site, `['host:{id}', …]` for a set. See {@link campaignSiteIds}.
|
|
163
220
|
*/
|
|
164
221
|
visibleTo?: string[];
|
|
222
|
+
/**
|
|
223
|
+
* `'allExcept'` on a container shared with all sites except some (AGL-4047),
|
|
224
|
+
* beside {@link EmailCampaign.scopeExcept}, the sites it leaves out. Both are
|
|
225
|
+
* the manage route's alone to write: the rules refuse them from a client, and
|
|
226
|
+
* the sweep keeps `visibleTo` in step as sites come and go. Absent on every
|
|
227
|
+
* other container.
|
|
228
|
+
*/
|
|
229
|
+
scopeMode?: string | null;
|
|
230
|
+
scopeExcept?: string[] | null;
|
|
165
231
|
/**
|
|
166
232
|
* Whether its emails carry `List-Unsubscribe` and `List-Unsubscribe-Post`
|
|
167
233
|
* (RFC 8058), the header mail clients draw their own Unsubscribe button
|
|
@@ -66,6 +66,7 @@
|
|
|
66
66
|
* therefore reports how many sends it could measure.
|
|
67
67
|
*/ import { readListUnsubscribeSetting } from "@aglyn/shared-util-email/list-unsubscribe";
|
|
68
68
|
import { sendRate } from "@aglyn/shared-ui-email-campaigns/model/send-report";
|
|
69
|
+
import { describeSharing, scopeSharingOf, sharingFromChoice } from "@aglyn/aglyn/app-utils/scope-tokens";
|
|
69
70
|
import { CAMPAIGN_SEQUENCE_REPORTS_COLLECTION } from "./campaign-report.js";
|
|
70
71
|
/** The org collection holding campaign CONTAINERS. */ export const EMAIL_CAMPAIGNS_COLLECTION = 'emailCampaigns';
|
|
71
72
|
/** The org collection holding SENDS — one document per email. */ export const CAMPAIGN_SENDS_COLLECTION = 'campaigns';
|
|
@@ -131,32 +132,140 @@ import { CAMPAIGN_SEQUENCE_REPORTS_COLLECTION } from "./campaign-report.js";
|
|
|
131
132
|
}
|
|
132
133
|
return ids;
|
|
133
134
|
}
|
|
135
|
+
/**
|
|
136
|
+
* Whether a container is shared with all sites except some (AGL-4047): either
|
|
137
|
+
* marker key present, as the rules' `scopeUnmarked` reads it, so a stored null
|
|
138
|
+
* or half a marker fails closed.
|
|
139
|
+
*/ export function campaignSharingMarked(campaign) {
|
|
140
|
+
return (campaign == null ? void 0 : campaign.scopeMode) !== undefined || (campaign == null ? void 0 : campaign.scopeExcept) !== undefined;
|
|
141
|
+
}
|
|
134
142
|
/**
|
|
135
143
|
* Whether a container is placed on this one site and no other: the placement
|
|
136
144
|
* where the site's own "Run email campaigns" counts for writing it (AGL-4047).
|
|
145
|
+
*
|
|
146
|
+
* Never for a container shared with all sites except some, however few sites
|
|
147
|
+
* it reaches today. Its list can shrink to one site while it still belongs to
|
|
148
|
+
* the whole workspace, and the next new site joins it, so that one site's
|
|
149
|
+
* Admins never come to answer for it. The rules' `scopePlacement` and core's
|
|
150
|
+
* `oneSitePlacement` answer the same.
|
|
137
151
|
*/ export function campaignPlacedOnlyOn(campaign, hostId) {
|
|
138
152
|
var _ref;
|
|
153
|
+
if (campaignSharingMarked(campaign)) return false;
|
|
139
154
|
const tokens = (_ref = campaign == null ? void 0 : campaign.visibleTo) != null ? _ref : [];
|
|
140
155
|
return tokens.length === 1 && tokens[0] === campaignHostScope(hostId);
|
|
141
156
|
}
|
|
157
|
+
/**
|
|
158
|
+
* Whether the site door of the manage route may delete this container: one
|
|
159
|
+
* placed on this site and on no other, and not shared with all sites except
|
|
160
|
+
* some. Deleting anything wider takes it off other sites too, which asks for
|
|
161
|
+
* access to every site in the workspace (AGL-4047).
|
|
162
|
+
*/ export function campaignSiteMayDelete(campaign, hostId) {
|
|
163
|
+
if (campaignSharingMarked(campaign)) return false;
|
|
164
|
+
const ids = campaignSiteIds(campaign);
|
|
165
|
+
return ids !== null && ids.length > 0 && ids.every((id)=>id === hostId);
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Why a member with access to some sites only may not delete this container
|
|
169
|
+
* from a site's hub, as the manage route and the console both say it. Names
|
|
170
|
+
* what it takes, never a role.
|
|
171
|
+
*/ export function campaignSiteDeleteRefusal(campaign) {
|
|
172
|
+
return campaignSharingMarked(campaign) ? 'This campaign is shared with all sites except some, so it belongs to ' + 'the whole workspace and every new site gets it. Deleting it takes ' + 'access to every site in the workspace.' : 'This campaign is on other sites too, so deleting it would take it off ' + 'them as well. Deleting it takes access to every site in the workspace.';
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* What a sharing choice writes on a container, or why it cannot be written
|
|
176
|
+
* (AGL-4047): `sharingFromChoice` over the workspace's sites, with a chosen
|
|
177
|
+
* site the workspace no longer holds dropped rather than stored.
|
|
178
|
+
*
|
|
179
|
+
* This is where the old silent cap went. A container used to keep the first
|
|
180
|
+
* thirty sites of a longer selection and say nothing; now a choice of more
|
|
181
|
+
* than thirty sites is refused with the reason, and "All sites except…" has
|
|
182
|
+
* no such ceiling, because a container's stored fields do not multiply by
|
|
183
|
+
* site (its search keys come from its name alone). The console asks it before
|
|
184
|
+
* a save, and the manage route asks it again with the sites it reads itself.
|
|
185
|
+
*/ export function campaignSharingWrite(choice, orgHostIds) {
|
|
186
|
+
return sharingFromChoice(choice.mode === 'selected' ? {
|
|
187
|
+
mode: 'selected',
|
|
188
|
+
hostIds: choice.hostIds.filter((id)=>orgHostIds.includes(id))
|
|
189
|
+
} : choice, orgHostIds);
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* A container's sharing as the sharing field edits it, or null where it
|
|
193
|
+
* stores none (an absent or empty `visibleTo`, which no reader matches).
|
|
194
|
+
*/ export function campaignSharingChoice(campaign) {
|
|
195
|
+
const sharing = scopeSharingOf(campaign);
|
|
196
|
+
if (sharing.mode === 'all') return {
|
|
197
|
+
mode: 'all'
|
|
198
|
+
};
|
|
199
|
+
if (sharing.mode === 'selected') return {
|
|
200
|
+
mode: 'selected',
|
|
201
|
+
hostIds: sharing.hostIds
|
|
202
|
+
};
|
|
203
|
+
if (sharing.mode === 'allExcept') {
|
|
204
|
+
return {
|
|
205
|
+
mode: 'allExcept',
|
|
206
|
+
exceptHostIds: sharing.exceptHostIds
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
/** Two sharing choices compare by what they pick, in any order. */ export function campaignSharingKey(choice) {
|
|
212
|
+
if (!choice) return 'unset';
|
|
213
|
+
if (choice.mode === 'all') return 'all';
|
|
214
|
+
const picked = choice.mode === 'selected' ? choice.hostIds : choice.exceptHostIds;
|
|
215
|
+
return `${choice.mode}:${[
|
|
216
|
+
...picked
|
|
217
|
+
].sort().join(',')}`;
|
|
218
|
+
}
|
|
219
|
+
/** The most site ids one sharing choice off the wire may name: far past any workspace. */ const SHARING_CHOICE_MAX_IDS = 1000;
|
|
220
|
+
/**
|
|
221
|
+
* A sharing choice off the wire, or null for anything else. The ids are
|
|
222
|
+
* checked against the workspace after, by {@link campaignSharingWrite}.
|
|
223
|
+
*/ export function campaignSharingChoiceFrom(value) {
|
|
224
|
+
const choice = value != null ? value : {};
|
|
225
|
+
const ids = (list)=>Array.isArray(list) && list.length <= SHARING_CHOICE_MAX_IDS && list.every((id)=>typeof id === 'string' && /^[^:/]+$/.test(id)) ? list : null;
|
|
226
|
+
if (choice.mode === 'all') return {
|
|
227
|
+
mode: 'all'
|
|
228
|
+
};
|
|
229
|
+
if (choice.mode === 'selected') {
|
|
230
|
+
const hostIds = ids(choice.hostIds);
|
|
231
|
+
return hostIds && {
|
|
232
|
+
mode: 'selected',
|
|
233
|
+
hostIds
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
if (choice.mode === 'allExcept') {
|
|
237
|
+
const exceptHostIds = ids(choice.exceptHostIds);
|
|
238
|
+
return exceptHostIds && {
|
|
239
|
+
mode: 'allExcept',
|
|
240
|
+
exceptHostIds
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Where a container shared with all sites except some is offered, naming the
|
|
247
|
+
* sites left out where the reader can name them (`describeSharing`), or null
|
|
248
|
+
* for any other container, whose sites the surfaces list as they always have.
|
|
249
|
+
* Listing today's sites would read as sites somebody chose, and the next new
|
|
250
|
+
* site joins it.
|
|
251
|
+
*/ export function campaignAllExceptLabel(campaign, hostNames) {
|
|
252
|
+
if (scopeSharingOf(campaign).mode !== 'allExcept') {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
return describeSharing(campaign, hostNames);
|
|
256
|
+
}
|
|
142
257
|
/** Whether a container is offered on this site. */ export function campaignPlacedOnHost(campaign, hostId) {
|
|
143
258
|
const ids = campaignSiteIds(campaign);
|
|
144
259
|
return ids === null || ids.includes(hostId);
|
|
145
260
|
}
|
|
146
261
|
/**
|
|
147
|
-
* The `visibleTo` a container
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
if (!siteIds || siteIds.length === 0) return [
|
|
154
|
-
CAMPAIGN_ORG_SCOPE
|
|
155
|
-
];
|
|
156
|
-
const unique = [
|
|
157
|
-
...new Set(siteIds.filter((id)=>typeof id === 'string' && id))
|
|
262
|
+
* The `visibleTo` of a container created under one site: that site alone. A
|
|
263
|
+
* site hub's create and an AI draft both place a campaign where it was made.
|
|
264
|
+
* Every other placement is a sharing choice, {@link campaignSharingWrite}.
|
|
265
|
+
*/ export function campaignSiteVisibleTo(hostId) {
|
|
266
|
+
return [
|
|
267
|
+
campaignHostScope(hostId)
|
|
158
268
|
];
|
|
159
|
-
return unique.slice(0, 30).map(campaignHostScope);
|
|
160
269
|
}
|
|
161
270
|
/**
|
|
162
271
|
* The field on a SEND naming the campaign it belongs to.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/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 the Marketing plugin), 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 readListUnsubscribeSetting,\n type ListUnsubscribeForcedReason,\n} from '@aglyn/shared-util-email/list-unsubscribe'\nimport {\n sendRate,\n type SendRate,\n type SendStats,\n} from '@aglyn/shared-ui-email-campaigns/model/send-report'\nimport { CAMPAIGN_SEQUENCE_REPORTS_COLLECTION } 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/**\n * Whether a container is placed on this one site and no other: the placement\n * where the site's own \"Run email campaigns\" counts for writing it (AGL-4047).\n */\nexport function campaignPlacedOnlyOn(\n campaign: Pick<EmailCampaign, 'visibleTo'> | null | undefined,\n hostId: string,\n): boolean {\n const tokens = campaign?.visibleTo ?? []\n return tokens.length === 1 && tokens[0] === campaignHostScope(hostId)\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 /**\n * Whether its emails carry `List-Unsubscribe` and `List-Unsubscribe-Post`\n * (RFC 8058), the header mail clients draw their own Unsubscribe button\n * from (AGL-3307). ON unless stored `false` — absent on every campaign\n * written before the setting existed, which read as on because that is\n * what they always did. Read it through {@link campaignListUnsubscribe}.\n *\n * Off is overridden per send by the bulk guard; see\n * {@link CampaignListUnsubscribeRecord}. The footer's unsubscribe link is\n * in every email either way.\n */\n listUnsubscribe?: boolean\n /**\n * The `utm_campaign` labels that mean this campaign (AGL-3461), stored as\n * {@link campaignUtmLabels} normalizes them. A visitor who arrives on a\n * link carrying one is credited to this campaign, as a visitor who reads a\n * page filed under it is. Read it through {@link campaignUtmLabels}.\n */\n utmCampaigns?: string[]\n createdAtMs?: number\n createdBy?: string\n deletedAt?: unknown\n}\n\n/**\n * How many `utm_campaign` labels one campaign may answer to. A ceiling on the\n * field, so an `array-contains` lookup stays one cheap index entry per label.\n */\nexport const CAMPAIGN_UTM_LABELS_MAX = 20\n\n/**\n * One `utm_campaign` label as it is stored and looked up: trimmed, lowercase,\n * at most 100 characters (the length the label parser keeps).\n *\n * Lowercase because the same push is routinely tagged `OneJob-AI` in one ad\n * and `onejob-ai` in the next, and a match that told them apart would leave\n * half a campaign's arrivals on a label nobody looks at. Empty for a value\n * that is not a label at all.\n */\nexport function normalizeCampaignUtmLabel(raw: unknown): string {\n if (typeof raw !== 'string') return ''\n const label = raw.trim().toLowerCase().slice(0, 100)\n // An address is never a campaign label — the label parser refuses one too.\n if (!label || /[^\\s@]+@[^\\s@]+\\.[^\\s@]+/.test(label)) return ''\n return label\n}\n\n/**\n * A campaign's `utm_campaign` labels as a clean list: normalized, deduped,\n * capped. Accepts the stored array or a comma- or newline-separated string,\n * which is how the edit drawer collects them.\n */\nexport function campaignUtmLabels(raw: unknown): string[] {\n const parts = Array.isArray(raw)\n ? raw\n : typeof raw === 'string'\n ? raw.split(/[\\n,]/)\n : []\n const labels: string[] = []\n for (const part of parts) {\n const label = normalizeCampaignUtmLabel(part)\n if (!label || labels.includes(label)) continue\n labels.push(label)\n if (labels.length >= CAMPAIGN_UTM_LABELS_MAX) break\n }\n return labels\n}\n\n/**\n * Whether a campaign's emails carry the mail-client unsubscribe button:\n * the shared reader sequences use, with a campaign's default of ON.\n */\nexport function campaignListUnsubscribe(\n campaign: Pick<EmailCampaign, 'listUnsubscribe'> | null | undefined,\n): boolean {\n return readListUnsubscribeSetting(campaign?.listUnsubscribe, true)\n}\n\n/**\n * What one SEND did with the List-Unsubscribe header, written by the\n * campaign sender on every batch (AGL-3307).\n */\nexport interface CampaignListUnsubscribeRecord {\n /** The campaign's setting when it went out. */\n requested?: boolean\n /** Whether the header was on the messages. */\n on?: boolean\n /** True when the setting said off and the bulk guard turned it back on. */\n forced?: boolean\n reason?: ListUnsubscribeForcedReason\n /** One sentence saying why, for the campaign page. */\n detail?: string\n /** Campaign messages in the day, this email included, it was judged on. */\n volume?: number\n /** The threshold it was judged against. */\n threshold?: number\n atMs?: number\n}\n\n/** The sends among these whose header the bulk guard forced back on. */\nexport function campaignForcedListUnsubscribeSends<\n T extends Pick<CampaignSend, 'listUnsubscribe'>,\n>(sends: readonly T[] | null | undefined): T[] {\n return (sends ?? []).filter((send) => send?.listUnsubscribe?.forced === true)\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?: SendStats\n /** How far a send that goes out over several batches has got. */\n resume?: CampaignResume\n /** What it did with the List-Unsubscribe header. Absent before AGL-3307. */\n listUnsubscribe?: CampaignListUnsubscribeRecord\n /**\n * Staff review of a send the outbound phishing screen held (AGL-3356).\n * Written by the send core, decided only by staff. See\n * {@link campaignSendHeldForReview}.\n */\n staffReview?: CampaignStaffReview\n}\n\n/** A held send's review, as the send core and the staff decision write it. */\nexport interface CampaignStaffReview {\n /** `held` until staff decide; then `released` or `rejected`. */\n state?: string\n /** `HS-…`, the reference the merchant quotes to support. */\n reference?: string\n reviewId?: string\n heldAtMs?: number\n}\n\n/**\n * Is this send waiting on a staff review (AGL-3356)?\n *\n * A held send is STORED as `scheduled`, parked at a send time no processor\n * run reaches, so the review can put it back on the clock without a second\n * record. Every surface that read the status alone therefore called it\n * \"Scheduled\" and showed a due date in the year 9999 — and offered \"Send\n * now\", \"Reschedule\" and the composer, none of which a merchant may use to\n * release it. This is the one test, so no surface restates it.\n */\nexport function campaignSendHeldForReview(\n send: Pick<CampaignSend, 'status' | 'staffReview'> | null | undefined,\n): boolean {\n const status = String(send?.status ?? '')\n return (\n send?.staffReview?.state === 'held' &&\n (status === 'scheduled' || status === 'draft')\n )\n}\n\n/**\n * What a held send's surfaces tell the merchant: that it is held, why in\n * general terms, that they cannot release it, and what happens next. One\n * sentence set, so the list, the page and the composer agree.\n */\nexport function campaignHeldForReviewNotice(\n send: Pick<CampaignSend, 'staffReview'> | null | undefined,\n): string {\n const reference = send?.staffReview?.reference\n return (\n 'This email is held for review before it sends. New workspaces have ' +\n 'their first emails checked for impersonation of other businesses, and ' +\n 'this one needs a person to look at it. It cannot be released, ' +\n 'rescheduled or edited from here — our team reviews it, and it sends ' +\n 'automatically if it is approved or is canceled if it is not. ' +\n 'Nothing has been sent or counted.' +\n (reference ? ` Quote ${reference} if you contact support.` : '')\n )\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; or canceled or failed\n * before it sent anything at all. 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 // Canceled, or failed, before a single message went out, with nobody left\n // waiting: it never sent. \"Sent to 0\" would describe a send that happened.\n if (\n (status === 'canceled' || status === 'failed') &&\n reached === 0 &&\n remaining === 0\n ) {\n return {\n state: 'stopped',\n reached: 0,\n audience,\n remaining: 0,\n batch,\n nextAtMs: 0,\n label:\n status === 'canceled'\n ? 'Canceled before it was sent'\n : 'Failed before it was sent',\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' | 'held' | 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 // Before the draft test: a held send may be stored as either (AGL-3356).\n if (campaignSendHeldForReview(send)) {\n return { state: 'held', label: 'Held for review', progress }\n }\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: SendRate | null\n /** Distinct clickers over delivered. */\n clickRate: SendRate | null\n /** Unsubscribes over delivered. */\n unsubscribeRate: SendRate | 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: SendStats) => 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: sendRate(\n aggregate(measurable, (stats) => stats.uniqueOpens).value ?? undefined,\n deliveredTotal.value ?? undefined,\n 'delivered',\n ),\n clickRate: sendRate(\n aggregate(measurable, (stats) => stats.uniqueClicks).value ?? undefined,\n deliveredTotal.value ?? undefined,\n 'delivered',\n ),\n unsubscribeRate: sendRate(\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":["readListUnsubscribeSetting","sendRate","CAMPAIGN_SEQUENCE_REPORTS_COLLECTION","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","campaignPlacedOnlyOn","campaignPlacedOnHost","campaignVisibleTo","siteIds","unique","Set","filter","id","map","CAMPAIGN_SEND_CONTAINER_FIELD","CAMPAIGN_UTM_LABELS_MAX","normalizeCampaignUtmLabel","raw","label","trim","toLowerCase","test","campaignUtmLabels","parts","Array","isArray","split","labels","part","campaignListUnsubscribe","listUnsubscribe","campaignForcedListUnsubscribeSends","sends","send","forced","campaignSendHeldForReview","status","String","staffReview","state","campaignHeldForReviewNotice","reference","progressCount","value","Math","floor","Number","isFinite","campaignSendProgress","reached","stats","sent","rawAudience","audienceSize","audience","undefined","resume","remaining","batch","nextAtMs","of","toLocaleString","why","campaignSendDisplay","progress","campaignSendIsMidFlight","campaignSendListIds","listId","aggregate","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,0BAA0B,QAErB,4CAA2C;AAClD,SACEC,QA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
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/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 the Marketing plugin), 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 readListUnsubscribeSetting,\n type ListUnsubscribeForcedReason,\n} from '@aglyn/shared-util-email/list-unsubscribe'\nimport {\n sendRate,\n type SendRate,\n type SendStats,\n} from '@aglyn/shared-ui-email-campaigns/model/send-report'\nimport {\n describeSharing,\n scopeSharingOf,\n sharingFromChoice,\n type ScopeSharingChoice,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { CAMPAIGN_SEQUENCE_REPORTS_COLLECTION } 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/**\n * Whether a container is shared with all sites except some (AGL-4047): either\n * marker key present, as the rules' `scopeUnmarked` reads it, so a stored null\n * or half a marker fails closed.\n */\nexport function campaignSharingMarked(\n campaign: Pick<EmailCampaign, 'scopeMode' | 'scopeExcept'> | null | undefined,\n): boolean {\n return (\n campaign?.scopeMode !== undefined || campaign?.scopeExcept !== undefined\n )\n}\n\n/**\n * Whether a container is placed on this one site and no other: the placement\n * where the site's own \"Run email campaigns\" counts for writing it (AGL-4047).\n *\n * Never for a container shared with all sites except some, however few sites\n * it reaches today. Its list can shrink to one site while it still belongs to\n * the whole workspace, and the next new site joins it, so that one site's\n * Admins never come to answer for it. The rules' `scopePlacement` and core's\n * `oneSitePlacement` answer the same.\n */\nexport function campaignPlacedOnlyOn(\n campaign:\n | Pick<EmailCampaign, 'visibleTo' | 'scopeMode' | 'scopeExcept'>\n | null\n | undefined,\n hostId: string,\n): boolean {\n if (campaignSharingMarked(campaign)) return false\n const tokens = campaign?.visibleTo ?? []\n return tokens.length === 1 && tokens[0] === campaignHostScope(hostId)\n}\n\n/**\n * Whether the site door of the manage route may delete this container: one\n * placed on this site and on no other, and not shared with all sites except\n * some. Deleting anything wider takes it off other sites too, which asks for\n * access to every site in the workspace (AGL-4047).\n */\nexport function campaignSiteMayDelete(\n campaign:\n | Pick<EmailCampaign, 'visibleTo' | 'scopeMode' | 'scopeExcept'>\n | null\n | undefined,\n hostId: string,\n): boolean {\n if (campaignSharingMarked(campaign)) return false\n const ids = campaignSiteIds(campaign)\n return ids !== null && ids.length > 0 && ids.every((id) => id === hostId)\n}\n\n/**\n * Why a member with access to some sites only may not delete this container\n * from a site's hub, as the manage route and the console both say it. Names\n * what it takes, never a role.\n */\nexport function campaignSiteDeleteRefusal(\n campaign: Pick<EmailCampaign, 'scopeMode' | 'scopeExcept'> | null | undefined,\n): string {\n return campaignSharingMarked(campaign)\n ? 'This campaign is shared with all sites except some, so it belongs to ' +\n 'the whole workspace and every new site gets it. Deleting it takes ' +\n 'access to every site in the workspace.'\n : 'This campaign is on other sites too, so deleting it would take it off ' +\n 'them as well. Deleting it takes access to every site in the workspace.'\n}\n\n/**\n * What a sharing choice writes on a container, or why it cannot be written\n * (AGL-4047): `sharingFromChoice` over the workspace's sites, with a chosen\n * site the workspace no longer holds dropped rather than stored.\n *\n * This is where the old silent cap went. A container used to keep the first\n * thirty sites of a longer selection and say nothing; now a choice of more\n * than thirty sites is refused with the reason, and \"All sites except…\" has\n * no such ceiling, because a container's stored fields do not multiply by\n * site (its search keys come from its name alone). The console asks it before\n * a save, and the manage route asks it again with the sites it reads itself.\n */\nexport function campaignSharingWrite(\n choice: ScopeSharingChoice,\n orgHostIds: readonly string[],\n): ReturnType<typeof sharingFromChoice> {\n return sharingFromChoice(\n choice.mode === 'selected'\n ? {\n mode: 'selected',\n hostIds: choice.hostIds.filter((id) => orgHostIds.includes(id)),\n }\n : choice,\n orgHostIds,\n )\n}\n\n/**\n * A container's sharing as the sharing field edits it, or null where it\n * stores none (an absent or empty `visibleTo`, which no reader matches).\n */\nexport function campaignSharingChoice(\n campaign: Pick<EmailCampaign, 'visibleTo' | 'scopeMode' | 'scopeExcept'> | null | undefined,\n): ScopeSharingChoice | null {\n const sharing = scopeSharingOf(campaign as Record<string, unknown> | null | undefined)\n if (sharing.mode === 'all') return { mode: 'all' }\n if (sharing.mode === 'selected') return { mode: 'selected', hostIds: sharing.hostIds }\n if (sharing.mode === 'allExcept') {\n return { mode: 'allExcept', exceptHostIds: sharing.exceptHostIds }\n }\n return null\n}\n\n/** Two sharing choices compare by what they pick, in any order. */\nexport function campaignSharingKey(choice: ScopeSharingChoice | null | undefined): string {\n if (!choice) return 'unset'\n if (choice.mode === 'all') return 'all'\n const picked = choice.mode === 'selected' ? choice.hostIds : choice.exceptHostIds\n return `${choice.mode}:${[...picked].sort().join(',')}`\n}\n\n/** The most site ids one sharing choice off the wire may name: far past any workspace. */\nconst SHARING_CHOICE_MAX_IDS = 1000\n\n/**\n * A sharing choice off the wire, or null for anything else. The ids are\n * checked against the workspace after, by {@link campaignSharingWrite}.\n */\nexport function campaignSharingChoiceFrom(value: unknown): ScopeSharingChoice | null {\n const choice = (value ?? {}) as { mode?: unknown; hostIds?: unknown; exceptHostIds?: unknown }\n const ids = (list: unknown): string[] | null =>\n Array.isArray(list) &&\n list.length <= SHARING_CHOICE_MAX_IDS &&\n list.every((id) => typeof id === 'string' && /^[^:/]+$/.test(id))\n ? (list as string[])\n : null\n if (choice.mode === 'all') return { mode: 'all' }\n if (choice.mode === 'selected') {\n const hostIds = ids(choice.hostIds)\n return hostIds && { mode: 'selected', hostIds }\n }\n if (choice.mode === 'allExcept') {\n const exceptHostIds = ids(choice.exceptHostIds)\n return exceptHostIds && { mode: 'allExcept', exceptHostIds }\n }\n return null\n}\n\n/**\n * Where a container shared with all sites except some is offered, naming the\n * sites left out where the reader can name them (`describeSharing`), or null\n * for any other container, whose sites the surfaces list as they always have.\n * Listing today's sites would read as sites somebody chose, and the next new\n * site joins it.\n */\nexport function campaignAllExceptLabel(\n campaign: Pick<EmailCampaign, 'visibleTo' | 'scopeMode' | 'scopeExcept'> | null | undefined,\n hostNames: Readonly<Record<string, string>>,\n): string | null {\n if (scopeSharingOf(campaign as Record<string, unknown> | null | undefined).mode !== 'allExcept') {\n return null\n }\n return describeSharing(campaign as Record<string, unknown> | null | undefined, hostNames)\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` of a container created under one site: that site alone. A\n * site hub's create and an AI draft both place a campaign where it was made.\n * Every other placement is a sharing choice, {@link campaignSharingWrite}.\n */\nexport function campaignSiteVisibleTo(hostId: string): string[] {\n return [campaignHostScope(hostId)]\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 /**\n * `'allExcept'` on a container shared with all sites except some (AGL-4047),\n * beside {@link EmailCampaign.scopeExcept}, the sites it leaves out. Both are\n * the manage route's alone to write: the rules refuse them from a client, and\n * the sweep keeps `visibleTo` in step as sites come and go. Absent on every\n * other container.\n */\n scopeMode?: string | null\n scopeExcept?: string[] | null\n /**\n * Whether its emails carry `List-Unsubscribe` and `List-Unsubscribe-Post`\n * (RFC 8058), the header mail clients draw their own Unsubscribe button\n * from (AGL-3307). ON unless stored `false` — absent on every campaign\n * written before the setting existed, which read as on because that is\n * what they always did. Read it through {@link campaignListUnsubscribe}.\n *\n * Off is overridden per send by the bulk guard; see\n * {@link CampaignListUnsubscribeRecord}. The footer's unsubscribe link is\n * in every email either way.\n */\n listUnsubscribe?: boolean\n /**\n * The `utm_campaign` labels that mean this campaign (AGL-3461), stored as\n * {@link campaignUtmLabels} normalizes them. A visitor who arrives on a\n * link carrying one is credited to this campaign, as a visitor who reads a\n * page filed under it is. Read it through {@link campaignUtmLabels}.\n */\n utmCampaigns?: string[]\n createdAtMs?: number\n createdBy?: string\n deletedAt?: unknown\n}\n\n/**\n * How many `utm_campaign` labels one campaign may answer to. A ceiling on the\n * field, so an `array-contains` lookup stays one cheap index entry per label.\n */\nexport const CAMPAIGN_UTM_LABELS_MAX = 20\n\n/**\n * One `utm_campaign` label as it is stored and looked up: trimmed, lowercase,\n * at most 100 characters (the length the label parser keeps).\n *\n * Lowercase because the same push is routinely tagged `OneJob-AI` in one ad\n * and `onejob-ai` in the next, and a match that told them apart would leave\n * half a campaign's arrivals on a label nobody looks at. Empty for a value\n * that is not a label at all.\n */\nexport function normalizeCampaignUtmLabel(raw: unknown): string {\n if (typeof raw !== 'string') return ''\n const label = raw.trim().toLowerCase().slice(0, 100)\n // An address is never a campaign label — the label parser refuses one too.\n if (!label || /[^\\s@]+@[^\\s@]+\\.[^\\s@]+/.test(label)) return ''\n return label\n}\n\n/**\n * A campaign's `utm_campaign` labels as a clean list: normalized, deduped,\n * capped. Accepts the stored array or a comma- or newline-separated string,\n * which is how the edit drawer collects them.\n */\nexport function campaignUtmLabels(raw: unknown): string[] {\n const parts = Array.isArray(raw)\n ? raw\n : typeof raw === 'string'\n ? raw.split(/[\\n,]/)\n : []\n const labels: string[] = []\n for (const part of parts) {\n const label = normalizeCampaignUtmLabel(part)\n if (!label || labels.includes(label)) continue\n labels.push(label)\n if (labels.length >= CAMPAIGN_UTM_LABELS_MAX) break\n }\n return labels\n}\n\n/**\n * Whether a campaign's emails carry the mail-client unsubscribe button:\n * the shared reader sequences use, with a campaign's default of ON.\n */\nexport function campaignListUnsubscribe(\n campaign: Pick<EmailCampaign, 'listUnsubscribe'> | null | undefined,\n): boolean {\n return readListUnsubscribeSetting(campaign?.listUnsubscribe, true)\n}\n\n/**\n * What one SEND did with the List-Unsubscribe header, written by the\n * campaign sender on every batch (AGL-3307).\n */\nexport interface CampaignListUnsubscribeRecord {\n /** The campaign's setting when it went out. */\n requested?: boolean\n /** Whether the header was on the messages. */\n on?: boolean\n /** True when the setting said off and the bulk guard turned it back on. */\n forced?: boolean\n reason?: ListUnsubscribeForcedReason\n /** One sentence saying why, for the campaign page. */\n detail?: string\n /** Campaign messages in the day, this email included, it was judged on. */\n volume?: number\n /** The threshold it was judged against. */\n threshold?: number\n atMs?: number\n}\n\n/** The sends among these whose header the bulk guard forced back on. */\nexport function campaignForcedListUnsubscribeSends<\n T extends Pick<CampaignSend, 'listUnsubscribe'>,\n>(sends: readonly T[] | null | undefined): T[] {\n return (sends ?? []).filter((send) => send?.listUnsubscribe?.forced === true)\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?: SendStats\n /** How far a send that goes out over several batches has got. */\n resume?: CampaignResume\n /** What it did with the List-Unsubscribe header. Absent before AGL-3307. */\n listUnsubscribe?: CampaignListUnsubscribeRecord\n /**\n * Staff review of a send the outbound phishing screen held (AGL-3356).\n * Written by the send core, decided only by staff. See\n * {@link campaignSendHeldForReview}.\n */\n staffReview?: CampaignStaffReview\n}\n\n/** A held send's review, as the send core and the staff decision write it. */\nexport interface CampaignStaffReview {\n /** `held` until staff decide; then `released` or `rejected`. */\n state?: string\n /** `HS-…`, the reference the merchant quotes to support. */\n reference?: string\n reviewId?: string\n heldAtMs?: number\n}\n\n/**\n * Is this send waiting on a staff review (AGL-3356)?\n *\n * A held send is STORED as `scheduled`, parked at a send time no processor\n * run reaches, so the review can put it back on the clock without a second\n * record. Every surface that read the status alone therefore called it\n * \"Scheduled\" and showed a due date in the year 9999 — and offered \"Send\n * now\", \"Reschedule\" and the composer, none of which a merchant may use to\n * release it. This is the one test, so no surface restates it.\n */\nexport function campaignSendHeldForReview(\n send: Pick<CampaignSend, 'status' | 'staffReview'> | null | undefined,\n): boolean {\n const status = String(send?.status ?? '')\n return (\n send?.staffReview?.state === 'held' &&\n (status === 'scheduled' || status === 'draft')\n )\n}\n\n/**\n * What a held send's surfaces tell the merchant: that it is held, why in\n * general terms, that they cannot release it, and what happens next. One\n * sentence set, so the list, the page and the composer agree.\n */\nexport function campaignHeldForReviewNotice(\n send: Pick<CampaignSend, 'staffReview'> | null | undefined,\n): string {\n const reference = send?.staffReview?.reference\n return (\n 'This email is held for review before it sends. New workspaces have ' +\n 'their first emails checked for impersonation of other businesses, and ' +\n 'this one needs a person to look at it. It cannot be released, ' +\n 'rescheduled or edited from here — our team reviews it, and it sends ' +\n 'automatically if it is approved or is canceled if it is not. ' +\n 'Nothing has been sent or counted.' +\n (reference ? ` Quote ${reference} if you contact support.` : '')\n )\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; or canceled or failed\n * before it sent anything at all. 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 // Canceled, or failed, before a single message went out, with nobody left\n // waiting: it never sent. \"Sent to 0\" would describe a send that happened.\n if (\n (status === 'canceled' || status === 'failed') &&\n reached === 0 &&\n remaining === 0\n ) {\n return {\n state: 'stopped',\n reached: 0,\n audience,\n remaining: 0,\n batch,\n nextAtMs: 0,\n label:\n status === 'canceled'\n ? 'Canceled before it was sent'\n : 'Failed before it was sent',\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' | 'held' | 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 // Before the draft test: a held send may be stored as either (AGL-3356).\n if (campaignSendHeldForReview(send)) {\n return { state: 'held', label: 'Held for review', progress }\n }\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: SendRate | null\n /** Distinct clickers over delivered. */\n clickRate: SendRate | null\n /** Unsubscribes over delivered. */\n unsubscribeRate: SendRate | 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: SendStats) => 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: sendRate(\n aggregate(measurable, (stats) => stats.uniqueOpens).value ?? undefined,\n deliveredTotal.value ?? undefined,\n 'delivered',\n ),\n clickRate: sendRate(\n aggregate(measurable, (stats) => stats.uniqueClicks).value ?? undefined,\n deliveredTotal.value ?? undefined,\n 'delivered',\n ),\n unsubscribeRate: sendRate(\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":["readListUnsubscribeSetting","sendRate","describeSharing","scopeSharingOf","sharingFromChoice","CAMPAIGN_SEQUENCE_REPORTS_COLLECTION","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","campaignSharingMarked","scopeMode","undefined","scopeExcept","campaignPlacedOnlyOn","campaignSiteMayDelete","every","id","campaignSiteDeleteRefusal","campaignSharingWrite","choice","orgHostIds","mode","hostIds","filter","campaignSharingChoice","sharing","exceptHostIds","campaignSharingKey","picked","sort","join","SHARING_CHOICE_MAX_IDS","campaignSharingChoiceFrom","value","list","Array","isArray","test","campaignAllExceptLabel","hostNames","campaignPlacedOnHost","campaignSiteVisibleTo","CAMPAIGN_SEND_CONTAINER_FIELD","CAMPAIGN_UTM_LABELS_MAX","normalizeCampaignUtmLabel","raw","label","trim","toLowerCase","campaignUtmLabels","parts","split","labels","part","campaignListUnsubscribe","listUnsubscribe","campaignForcedListUnsubscribeSends","sends","send","forced","campaignSendHeldForReview","status","String","staffReview","state","campaignHeldForReviewNotice","reference","progressCount","Math","floor","Number","isFinite","campaignSendProgress","reached","stats","sent","rawAudience","audienceSize","audience","resume","remaining","batch","nextAtMs","of","toLocaleString","why","campaignSendDisplay","progress","campaignSendIsMidFlight","campaignSendListIds","listId","aggregate","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","map","own","$id","rollup","name","legacy","listIds","windowState","atMs","subject","a","b","localeCompare"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmDC,GAED,SACEA,0BAA0B,QAErB,4CAA2C;AAClD,SACEC,QAAQ,QAGH,qDAAoD;AAC3D,SACEC,eAAe,EACfC,cAAc,EACdC,iBAAiB,QAEZ,sCAAqC;AAC5C,SAASC,oCAAoC,QAAQ,uBAAmB;AAExE,oDAAoD,GACpD,OAAO,MAAMC,6BAA6B,iBAAgB;AAE1D,+DAA+D,GAC/D,OAAO,MAAMC,4BAA4B,YAAW;AAEpD,qDAAqD,GACrD,OAAO,SAASC,sBAAsBC,KAAa;IACjD,OAAO;QAAC;QAAQA;QAAOH;KAA2B;AACpD;AAEA,gDAAgD,GAChD,OAAO,SAASI,qBAAqBD,KAAa;IAChD,OAAO;QAAC;QAAQA;QAAOF;KAA0B;AACnD;AAEA,8DAA8D,GAC9D,OAAO,SAASI,+BACdF,KAAa;IAEb,OAAO;QAAC;QAAQA;QAAOJ;KAAqC;AAC9D;AAEA;;;;;;CAMC,GACD,OAAO,MAAMO,2BAA2B,SAAQ;AAEhD,kFAAkF,GAClF,OAAO,MAAMC,qBAAqB,MAAK;AAEvC,sDAAsD,GACtD,OAAO,SAASC,kBAAkBC,MAAc;IAC9C,OAAO,CAAC,KAAK,EAAEA,QAAQ;AACzB;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,sBAAsBD,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QAC1E,IAAIM,EAAEF,IAAI,KAAK,MAAM,OAAO;QAC5B,IAAIG,EAAEH,IAAI,KAAK,MAAM,OAAO,CAAC;QAC7B,OAAOG,EAAEH,IAAI,GAAGE,EAAEF,IAAI;IACxB;AACF"}
|
|
@@ -68,8 +68,9 @@ export declare function registerCampaignDraftWriter(): void;
|
|
|
68
68
|
*/
|
|
69
69
|
export declare function campaignManageSubject(request: Request): Promise<PluginApiRequestSubject | null>;
|
|
70
70
|
/**
|
|
71
|
-
* Campaign management API: removing a campaign, discarding a draft,
|
|
72
|
-
*
|
|
71
|
+
* Campaign management API: removing a campaign, discarding a draft, copying
|
|
72
|
+
* an email, and choosing which sites a campaign is shared with (`setSharing`,
|
|
73
|
+
* AGL-4047, from the organization hub only).
|
|
73
74
|
*
|
|
74
75
|
* Separate from `campaigns/send` because nothing here sends, reserves
|
|
75
76
|
* allowance or moves a meter, and because the removals are about a record
|
|
@@ -84,6 +85,7 @@ export declare function campaignManageSubject(request: Request): Promise<PluginA
|
|
|
84
85
|
* Editing a campaign is deliberately NOT here. The container is client-
|
|
85
86
|
* writable, its create already runs on the client SDK, and a second door to
|
|
86
87
|
* the same document would be a second place for the two to disagree about
|
|
87
|
-
* what a campaign may hold.
|
|
88
|
+
* what a campaign may hold. Its SHARING is the one exception: a campaign
|
|
89
|
+
* shared with all sites except some carries a marker only a server may write.
|
|
88
90
|
*/
|
|
89
91
|
export declare const campaignManageHandler: PluginApiHandler;
|