@aglyn/plugins-marketing 1.10.0 → 1.12.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 +14 -4
- package/src/lib/components/campaign-detail-card.js.map +1 -1
- package/src/lib/components/campaigns-card.js +20 -9
- package/src/lib/components/campaigns-card.js.map +1 -1
- package/src/lib/components/site-runtime.d.ts +7 -0
- package/src/lib/components/site-runtime.js +24 -0
- package/src/lib/components/site-runtime.js.map +1 -1
- package/src/lib/components/use-campaign-containers-blocked.d.ts +69 -0
- package/src/lib/components/use-campaign-containers-blocked.js +122 -0
- package/src/lib/components/use-campaign-containers-blocked.js.map +1 -0
- package/src/lib/model/campaign-container.d.ts +5 -0
- package/src/lib/model/campaign-container.js +8 -0
- package/src/lib/model/campaign-container.js.map +1 -1
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { resolveSiteRolePresetPermissions } from "@aglyn/aglyn/app-utils/host-permissions";
|
|
17
|
+
import { isOrgWideMember } from "@aglyn/aglyn/app-utils/organizations";
|
|
18
|
+
import { useFirestore, useFirestoreDoc, useUser } from "@aglyn/tenant-feature-instance";
|
|
19
|
+
import { doc } from "firebase/firestore";
|
|
20
|
+
import { campaignPlacedOnlyOn } from "../model/campaign-container.js";
|
|
21
|
+
import { MARKETING_SITE_PERMISSIONS } from "../model/marketing-permissions.js";
|
|
22
|
+
const CAMPAIGNS_KEY = 'marketing.campaigns';
|
|
23
|
+
/**
|
|
24
|
+
* The workspace's verdict on writing a campaign container (AGL-4047), the rule's
|
|
25
|
+
* `canWriteCampaignContainers`: "Run email campaigns" as written on
|
|
26
|
+
* `resolvedPermissions`, or, for a member the projection never stamped, on their
|
|
27
|
+
* own `permissions`; else their workspace role's default. It answers for every
|
|
28
|
+
* campaign, wherever it is placed.
|
|
29
|
+
*/ export function holdsCampaignContainers(member) {
|
|
30
|
+
var _member_resolvedPermissions, _member_role;
|
|
31
|
+
var _this, _MARKETING_SITE_PERMISSIONS_;
|
|
32
|
+
const stamped = (_this = (_member_resolvedPermissions = member.resolvedPermissions) != null ? _member_resolvedPermissions : member.permissions) == null ? void 0 : _this[CAMPAIGNS_KEY];
|
|
33
|
+
if (typeof stamped === 'boolean') return stamped;
|
|
34
|
+
const defaults = (_MARKETING_SITE_PERMISSIONS_ = MARKETING_SITE_PERMISSIONS[0]) == null ? void 0 : _MARKETING_SITE_PERMISSIONS_.roleDefaults;
|
|
35
|
+
return (defaults == null ? void 0 : defaults[String((_member_role = member.role) != null ? _member_role : '')]) === true;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The site's verdict: what the rule's `canWriteOneSiteCampaign` and the campaign
|
|
39
|
+
* routes read off the host's `memberPermissions`, resolved here by the function
|
|
40
|
+
* that stamp is written from. So it costs no read of the host: the membership
|
|
41
|
+
* document on the page already holds the site role, the site's toggle and the
|
|
42
|
+
* member's overrides. A member with no access to the site does not hold it.
|
|
43
|
+
*/ export function siteHoldsCampaignContainers(member, hostId, customRole) {
|
|
44
|
+
return resolveSiteRolePresetPermissions(member, hostId, customRole)[CAMPAIGNS_KEY] === true;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The workspace door of the campaign manage route (`deleteCampaign`, with no site
|
|
48
|
+
* named): a member of the whole workspace holding the key.
|
|
49
|
+
*/ export function workspaceManagesCampaigns(member) {
|
|
50
|
+
return isOrgWideMember(member) && holdsCampaignContainers(member);
|
|
51
|
+
}
|
|
52
|
+
/** The reader's membership: `null` until one has landed, and for a reader with none, who is staff. */ function useContainerMember(orgId) {
|
|
53
|
+
var _ref;
|
|
54
|
+
const firestore = useFirestore();
|
|
55
|
+
const { data: user } = useUser();
|
|
56
|
+
const uid = (_ref = user == null ? void 0 : user.uid) != null ? _ref : '';
|
|
57
|
+
const { data, status } = useFirestoreDoc(()=>orgId && uid ? doc(firestore, 'orgs', orgId, 'members', uid) : null, [
|
|
58
|
+
firestore,
|
|
59
|
+
orgId,
|
|
60
|
+
uid
|
|
61
|
+
]);
|
|
62
|
+
return status === 'success' ? data != null ? data : null : null;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The site's verdict for this member, once it is known. A member of the whole
|
|
66
|
+
* workspace on a custom role is the one case the membership cannot answer alone,
|
|
67
|
+
* and it pays one read, of that role. With no site named, no read at all.
|
|
68
|
+
*/ function useSiteVerdict(orgId, hostId, member) {
|
|
69
|
+
var _role_data;
|
|
70
|
+
const firestore = useFirestore();
|
|
71
|
+
const carried = member == null ? void 0 : member.roleId;
|
|
72
|
+
const roleId = hostId && member && typeof carried === 'string' && isOrgWideMember(member) ? carried : '';
|
|
73
|
+
const role = useFirestoreDoc(()=>orgId && roleId ? doc(firestore, 'orgs', orgId, 'roles', roleId) : null, [
|
|
74
|
+
firestore,
|
|
75
|
+
orgId,
|
|
76
|
+
roleId
|
|
77
|
+
]);
|
|
78
|
+
if (!hostId || !member || roleId && role.status === 'loading') return {
|
|
79
|
+
held: false,
|
|
80
|
+
known: false
|
|
81
|
+
};
|
|
82
|
+
const customRole = roleId && role.status === 'success' ? (_role_data = role.data) != null ? _role_data : null : null;
|
|
83
|
+
return {
|
|
84
|
+
held: siteHoldsCampaignContainers(member, hostId, customRole),
|
|
85
|
+
known: true
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Whether Create campaign switches off with the permission named instead of
|
|
90
|
+
* failing on save. A campaign created under a site is placed on that one site, so
|
|
91
|
+
* the site's verdict counts there; with no site named, the workspace's alone.
|
|
92
|
+
*
|
|
93
|
+
* `false` until the reads land, and for a reader with no membership, who is staff.
|
|
94
|
+
*/ export function useCampaignContainersBlocked(orgId, hostId) {
|
|
95
|
+
const member = useContainerMember(orgId);
|
|
96
|
+
const refused = Boolean(member) && !holdsCampaignContainers(member);
|
|
97
|
+
const site = useSiteVerdict(orgId, refused ? hostId : null, member);
|
|
98
|
+
return refused && (!hostId || site.known && !site.held);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* The same for one campaign's own page, where Edit answers the rule and Delete
|
|
102
|
+
* answers the manage route, and the two can differ on purpose: a site that turns
|
|
103
|
+
* the key off stops its delete, and the workspace's verdict still edits it.
|
|
104
|
+
*
|
|
105
|
+
* Edit counts the site's verdict only under the site the campaign is placed on
|
|
106
|
+
* and nowhere else, so a campaign on every site or on several, and every campaign
|
|
107
|
+
* on the workspace's own page, answers to the workspace's verdict alone.
|
|
108
|
+
*
|
|
109
|
+
* Nothing but the membership is read until `campaign` is in hand: a send's report,
|
|
110
|
+
* which holds no container, offers neither control.
|
|
111
|
+
*/ export function useCampaignContainerAccess(orgId, hostId, campaign) {
|
|
112
|
+
const member = useContainerMember(orgId);
|
|
113
|
+
const site = useSiteVerdict(orgId, campaign ? hostId : null, member);
|
|
114
|
+
const refused = Boolean(member) && !holdsCampaignContainers(member);
|
|
115
|
+
const siteCounts = Boolean(hostId) && campaignPlacedOnlyOn(campaign, String(hostId));
|
|
116
|
+
return {
|
|
117
|
+
editBlocked: refused && (!siteCounts || site.known && !site.held),
|
|
118
|
+
deleteBlocked: hostId ? site.known && !site.held : Boolean(member) && !workspaceManagesCampaigns(member)
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
//# sourceMappingURL=use-campaign-containers-blocked.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/components/use-campaign-containers-blocked.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\nimport { resolveSiteRolePresetPermissions } from '@aglyn/aglyn/app-utils/host-permissions'\nimport type { AglynOrgCustomRole } from '@aglyn/aglyn/app-utils/org-permissions'\nimport { isOrgWideMember } from '@aglyn/aglyn/app-utils/organizations'\nimport type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport { useFirestore, useFirestoreDoc, useUser } from '@aglyn/tenant-feature-instance'\nimport { doc } from 'firebase/firestore'\nimport { campaignPlacedOnlyOn, type EmailCampaign } from '../model/campaign-container'\nimport { MARKETING_SITE_PERMISSIONS } from '../model/marketing-permissions'\n\n/** What the rule reads off a membership document. */\nexport interface CampaignContainerMember {\n role?: unknown\n resolvedPermissions?: Readonly<Record<string, unknown>>\n permissions?: Readonly<Record<string, unknown>>\n}\n\nconst CAMPAIGNS_KEY = 'marketing.campaigns'\n\n/**\n * The workspace's verdict on writing a campaign container (AGL-4047), the rule's\n * `canWriteCampaignContainers`: \"Run email campaigns\" as written on\n * `resolvedPermissions`, or, for a member the projection never stamped, on their\n * own `permissions`; else their workspace role's default. It answers for every\n * campaign, wherever it is placed.\n */\nexport function holdsCampaignContainers(member: CampaignContainerMember): boolean {\n const stamped = (member.resolvedPermissions ?? member.permissions)?.[CAMPAIGNS_KEY]\n if (typeof stamped === 'boolean') return stamped\n const defaults: Readonly<Record<string, boolean>> | undefined = MARKETING_SITE_PERMISSIONS[0]?.roleDefaults\n return defaults?.[String(member.role ?? '')] === true\n}\n\n/**\n * The site's verdict: what the rule's `canWriteOneSiteCampaign` and the campaign\n * routes read off the host's `memberPermissions`, resolved here by the function\n * that stamp is written from. So it costs no read of the host: the membership\n * document on the page already holds the site role, the site's toggle and the\n * member's overrides. A member with no access to the site does not hold it.\n */\nexport function siteHoldsCampaignContainers(\n member: CampaignContainerMember | null | undefined,\n hostId: string,\n customRole?: Pick<AglynOrgCustomRole, 'permissions'> | null,\n): boolean {\n return resolveSiteRolePresetPermissions(member as Partial<AglynOrgMember>, hostId, customRole)[CAMPAIGNS_KEY] === true\n}\n\n/**\n * The workspace door of the campaign manage route (`deleteCampaign`, with no site\n * named): a member of the whole workspace holding the key.\n */\nexport function workspaceManagesCampaigns(member: CampaignContainerMember): boolean {\n return isOrgWideMember(member as Partial<AglynOrgMember>) && holdsCampaignContainers(member)\n}\n\n/** The reader's membership: `null` until one has landed, and for a reader with none, who is staff. */\nfunction useContainerMember(orgId: string | null | undefined): CampaignContainerMember | null {\n const firestore = useFirestore()\n const { data: user } = useUser()\n const uid = user?.uid ?? ''\n const { data, status } = useFirestoreDoc<CampaignContainerMember>(\n () => (orgId && uid ? doc(firestore, 'orgs', orgId, 'members', uid) : null),\n [firestore, orgId, uid],\n )\n return status === 'success' ? (data ?? null) : null\n}\n\n/**\n * The site's verdict for this member, once it is known. A member of the whole\n * workspace on a custom role is the one case the membership cannot answer alone,\n * and it pays one read, of that role. With no site named, no read at all.\n */\nfunction useSiteVerdict(\n orgId: string | null | undefined,\n hostId: string | null | undefined,\n member: CampaignContainerMember | null,\n): { held: boolean; known: boolean } {\n const firestore = useFirestore()\n const carried = (member as { roleId?: unknown } | null)?.roleId\n const roleId =\n hostId && member && typeof carried === 'string' && isOrgWideMember(member as Partial<AglynOrgMember>) ? carried : ''\n const role = useFirestoreDoc<AglynOrgCustomRole>(\n () => (orgId && roleId ? doc(firestore, 'orgs', orgId, 'roles', roleId) : null),\n [firestore, orgId, roleId],\n )\n if (!hostId || !member || (roleId && role.status === 'loading')) return { held: false, known: false }\n const customRole = roleId && role.status === 'success' ? (role.data ?? null) : null\n return { held: siteHoldsCampaignContainers(member, hostId, customRole), known: true }\n}\n\n/**\n * Whether Create campaign switches off with the permission named instead of\n * failing on save. A campaign created under a site is placed on that one site, so\n * the site's verdict counts there; with no site named, the workspace's alone.\n *\n * `false` until the reads land, and for a reader with no membership, who is staff.\n */\nexport function useCampaignContainersBlocked(\n orgId: string | null | undefined,\n hostId?: string | null,\n): boolean {\n const member = useContainerMember(orgId)\n const refused = Boolean(member) && !holdsCampaignContainers(member as CampaignContainerMember)\n const site = useSiteVerdict(orgId, refused ? hostId : null, member)\n return refused && (!hostId || (site.known && !site.held))\n}\n\n/**\n * The same for one campaign's own page, where Edit answers the rule and Delete\n * answers the manage route, and the two can differ on purpose: a site that turns\n * the key off stops its delete, and the workspace's verdict still edits it.\n *\n * Edit counts the site's verdict only under the site the campaign is placed on\n * and nowhere else, so a campaign on every site or on several, and every campaign\n * on the workspace's own page, answers to the workspace's verdict alone.\n *\n * Nothing but the membership is read until `campaign` is in hand: a send's report,\n * which holds no container, offers neither control.\n */\nexport function useCampaignContainerAccess(\n orgId: string | null | undefined,\n hostId: string | null | undefined,\n campaign: Pick<EmailCampaign, 'visibleTo'> | null | undefined,\n): { editBlocked: boolean; deleteBlocked: boolean } {\n const member = useContainerMember(orgId)\n const site = useSiteVerdict(orgId, campaign ? hostId : null, member)\n const refused = Boolean(member) && !holdsCampaignContainers(member as CampaignContainerMember)\n const siteCounts = Boolean(hostId) && campaignPlacedOnlyOn(campaign, String(hostId))\n return {\n editBlocked: refused && (!siteCounts || (site.known && !site.held)),\n deleteBlocked: hostId\n ? site.known && !site.held\n : Boolean(member) && !workspaceManagesCampaigns(member as CampaignContainerMember),\n }\n}\n"],"names":["resolveSiteRolePresetPermissions","isOrgWideMember","useFirestore","useFirestoreDoc","useUser","doc","campaignPlacedOnlyOn","MARKETING_SITE_PERMISSIONS","CAMPAIGNS_KEY","holdsCampaignContainers","member","stamped","resolvedPermissions","permissions","defaults","roleDefaults","String","role","siteHoldsCampaignContainers","hostId","customRole","workspaceManagesCampaigns","useContainerMember","orgId","firestore","data","user","uid","status","useSiteVerdict","carried","roleId","held","known","useCampaignContainersBlocked","refused","Boolean","site","useCampaignContainerAccess","campaign","siteCounts","editBlocked","deleteBlocked"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gCAAgC,QAAQ,0CAAyC;AAE1F,SAASC,eAAe,QAAQ,uCAAsC;AAEtE,SAASC,YAAY,EAAEC,eAAe,EAAEC,OAAO,QAAQ,iCAAgC;AACvF,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,oBAAoB,QAA4B,iCAA6B;AACtF,SAASC,0BAA0B,QAAQ,oCAAgC;AAS3E,MAAMC,gBAAgB;AAEtB;;;;;;CAMC,GACD,OAAO,SAASC,wBAAwBC,MAA+B;QACpDA,6BAGQA;QAHRA,OAE+CH;IAFhE,MAAMI,WAAWD,SAAAA,8BAAAA,OAAOE,mBAAmB,YAA1BF,8BAA8BA,OAAOG,WAAW,qBAAjD,AAACH,KAAmD,CAACF,cAAc;IACnF,IAAI,OAAOG,YAAY,WAAW,OAAOA;IACzC,MAAMG,YAA0DP,+BAAAA,0BAA0B,CAAC,EAAE,qBAA7BA,6BAA+BQ,YAAY;IAC3G,OAAOD,CAAAA,4BAAAA,QAAU,CAACE,QAAON,eAAAA,OAAOO,IAAI,YAAXP,eAAe,IAAI,MAAK;AACnD;AAEA;;;;;;CAMC,GACD,OAAO,SAASQ,4BACdR,MAAkD,EAClDS,MAAc,EACdC,UAA2D;IAE3D,OAAOpB,iCAAiCU,QAAmCS,QAAQC,WAAW,CAACZ,cAAc,KAAK;AACpH;AAEA;;;CAGC,GACD,OAAO,SAASa,0BAA0BX,MAA+B;I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AOR,eAAeN,OAAOY,UAAUhB,SAAS,MAAMT;IAC5D,OAAOyB,WAAY,CAAA,CAAChB,UAAWkB,KAAKJ,KAAK,IAAI,CAACI,KAAKL,IAAI;AACzD;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAASM,2BACdf,KAAgC,EAChCJ,MAAiC,EACjCoB,QAA6D;IAE7D,MAAM7B,SAASY,mBAAmBC;IAClC,MAAMc,OAAOR,eAAeN,OAAOgB,WAAWpB,SAAS,MAAMT;IAC7D,MAAMyB,UAAUC,QAAQ1B,WAAW,CAACD,wBAAwBC;IAC5D,MAAM8B,aAAaJ,QAAQjB,WAAWb,qBAAqBiC,UAAUvB,OAAOG;IAC5E,OAAO;QACLsB,aAAaN,WAAY,CAAA,CAACK,cAAeH,KAAKJ,KAAK,IAAI,CAACI,KAAKL,IAAI;QACjEU,eAAevB,SACXkB,KAAKJ,KAAK,IAAI,CAACI,KAAKL,IAAI,GACxBI,QAAQ1B,WAAW,CAACW,0BAA0BX;IACpD;AACF"}
|
|
@@ -107,6 +107,11 @@ export declare function campaignSendVisibleTo(hostId: string): string[];
|
|
|
107
107
|
* recoverable direction.
|
|
108
108
|
*/
|
|
109
109
|
export declare function campaignSiteIds(campaign: Pick<EmailCampaign, 'visibleTo'> | null | undefined): string[] | null;
|
|
110
|
+
/**
|
|
111
|
+
* Whether a container is placed on this one site and no other: the placement
|
|
112
|
+
* where the site's own "Run email campaigns" counts for writing it (AGL-4047).
|
|
113
|
+
*/
|
|
114
|
+
export declare function campaignPlacedOnlyOn(campaign: Pick<EmailCampaign, 'visibleTo'> | null | undefined, hostId: string): boolean;
|
|
110
115
|
/** Whether a container is offered on this site. */
|
|
111
116
|
export declare function campaignPlacedOnHost(campaign: Pick<EmailCampaign, 'visibleTo'> | null | undefined, hostId: string): boolean;
|
|
112
117
|
/**
|
|
@@ -131,6 +131,14 @@ import { CAMPAIGN_SEQUENCE_REPORTS_COLLECTION } from "./campaign-report.js";
|
|
|
131
131
|
}
|
|
132
132
|
return ids;
|
|
133
133
|
}
|
|
134
|
+
/**
|
|
135
|
+
* Whether a container is placed on this one site and no other: the placement
|
|
136
|
+
* where the site's own "Run email campaigns" counts for writing it (AGL-4047).
|
|
137
|
+
*/ export function campaignPlacedOnlyOn(campaign, hostId) {
|
|
138
|
+
var _ref;
|
|
139
|
+
const tokens = (_ref = campaign == null ? void 0 : campaign.visibleTo) != null ? _ref : [];
|
|
140
|
+
return tokens.length === 1 && tokens[0] === campaignHostScope(hostId);
|
|
141
|
+
}
|
|
134
142
|
/** Whether a container is offered on this site. */ export function campaignPlacedOnHost(campaign, hostId) {
|
|
135
143
|
const ids = campaignSiteIds(campaign);
|
|
136
144
|
return ids === null || ids.includes(hostId);
|
|
@@ -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/** 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","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,QAAQ,QAGH,qDAAoD;AAC3D,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,G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AY,YAAzCtG,OAA6C;QACrD;IACF;IAEA,KAAK,MAAMqC,QAAQ+E,QAAS;QAC1B,MAAMS,SAAS5C,eAAe;YAAC5C;SAAK;QACpC,MAAMoE,KAAK5B,iBAAiBxC;QAC5BqF,KAAKlH,IAAI,CAAC;YACRQ,IAAIqB,KAAKuF,GAAG;YACZE,MAAMzF,KAAK8F,OAAO,IAAI;YACtBJ,QAAQ;YACRlB,WAAWJ;YACXM,SAASN;YACTuB,SAAS,EAAE;YACX5F,OAAO;gBAACC;aAAK;YACbwF;YACA,mEAAmE;YACnEI,aACE5F,KAAKG,MAAM,KAAK,cACZ,aACAiE,OAAO,OACL,YACA;YACRyB,MAAMzB;QACR;IACF;IAEA,OAAOiB,KAAKU,IAAI,CAAC,CAACC,GAAGC;QACnB,IAAID,EAAEH,IAAI,KAAK,QAAQI,EAAEJ,IAAI,KAAK,MAAM,OAAOG,EAAEP,IAAI,CAACS,aAAa,CAACD,EAAER,IAAI;QAC1E,IAAIO,EAAEH,IAAI,KAAK,MAAM,OAAO;QAC5B,IAAII,EAAEJ,IAAI,KAAK,MAAM,OAAO,CAAC;QAC7B,OAAOI,EAAEJ,IAAI,GAAGG,EAAEH,IAAI;IACxB;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/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,QAAQ,QAGH,qDAAoD;AAC3D,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,MAAc;IAClD,OAAO;QAACD,kBAAkBC;KAAQ;AACpC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASE,gBACdC,QAA6D;;IAE7D,MAAMC,iBAASD,4BAAAA,SAAUE,SAAS,mBAAI,EAAE;IACxC,IAAID,OAAOE,QAAQ,CAACR,qBAAqB,OAAO;IAChD,MAAMS,MAAgB,EAAE;IACxB,KAAK,MAAMC,SAASJ,OAAQ;QAC1B,IAAI,OAAOI,UAAU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