@aglyn/tenant-data-admin 1.0.0-beta.221 → 1.0.0-beta.222

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.
Files changed (104) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/api-keys.js +3 -3
  3. package/src/lib/server/api-keys.js.map +1 -1
  4. package/src/lib/server/api-v1-resources.d.ts +44 -3
  5. package/src/lib/server/api-v1-resources.js +82 -5
  6. package/src/lib/server/api-v1-resources.js.map +1 -1
  7. package/src/lib/server/collection-live-pages.d.ts +2 -2
  8. package/src/lib/server/collection-live-pages.js +1 -1
  9. package/src/lib/server/collection-live-pages.js.map +1 -1
  10. package/src/lib/server/email-delivery-log.d.ts +17 -73
  11. package/src/lib/server/email-delivery-log.js +44 -222
  12. package/src/lib/server/email-delivery-log.js.map +1 -1
  13. package/src/lib/server/email-flow-gate.js +27 -38
  14. package/src/lib/server/email-flow-gate.js.map +1 -1
  15. package/src/lib/server/erase-person.d.ts +34 -54
  16. package/src/lib/server/erase-person.js +44 -239
  17. package/src/lib/server/erase-person.js.map +1 -1
  18. package/src/lib/server/host-visitor-records.d.ts +12 -4
  19. package/src/lib/server/host-visitor-records.js +20 -10
  20. package/src/lib/server/host-visitor-records.js.map +1 -1
  21. package/src/lib/server/hosted-page-review.js +46 -33
  22. package/src/lib/server/hosted-page-review.js.map +1 -1
  23. package/src/lib/server/link-reputation-review.d.ts +6 -2
  24. package/src/lib/server/link-reputation-review.js +61 -20
  25. package/src/lib/server/link-reputation-review.js.map +1 -1
  26. package/src/lib/server/live-page-drops.d.ts +67 -0
  27. package/src/lib/server/live-page-drops.js +57 -0
  28. package/src/lib/server/live-page-drops.js.map +1 -0
  29. package/src/lib/server/media-bandwidth-cap.d.ts +78 -0
  30. package/src/lib/server/media-bandwidth-cap.js +180 -0
  31. package/src/lib/server/media-bandwidth-cap.js.map +1 -0
  32. package/src/lib/server/media-cdn-icon.d.ts +77 -0
  33. package/src/lib/server/media-cdn-icon.js +140 -0
  34. package/src/lib/server/media-cdn-icon.js.map +1 -0
  35. package/src/lib/server/media-delivery-regeneration.d.ts +132 -0
  36. package/src/lib/server/media-delivery-regeneration.js +216 -0
  37. package/src/lib/server/media-delivery-regeneration.js.map +1 -0
  38. package/src/lib/server/media-delivery.d.ts +2 -0
  39. package/src/lib/server/media-delivery.js +2 -1
  40. package/src/lib/server/media-delivery.js.map +1 -1
  41. package/src/lib/server/media-serve-count.d.ts +50 -0
  42. package/src/lib/server/media-serve-count.js +62 -0
  43. package/src/lib/server/media-serve-count.js.map +1 -0
  44. package/src/lib/server/media-signing.d.ts +13 -2
  45. package/src/lib/server/media-signing.js +12 -8
  46. package/src/lib/server/media-signing.js.map +1 -1
  47. package/src/lib/server/media-tombstone.js +7 -5
  48. package/src/lib/server/media-tombstone.js.map +1 -1
  49. package/src/lib/server/media-variants.d.ts +151 -20
  50. package/src/lib/server/media-variants.js +204 -27
  51. package/src/lib/server/media-variants.js.map +1 -1
  52. package/src/lib/server/organizations.d.ts +102 -2
  53. package/src/lib/server/organizations.js +388 -58
  54. package/src/lib/server/organizations.js.map +1 -1
  55. package/src/lib/server/outbound-send-review.js +5 -4
  56. package/src/lib/server/outbound-send-review.js.map +1 -1
  57. package/src/lib/server/paged-sweeps.d.ts +51 -0
  58. package/src/lib/server/paged-sweeps.js +79 -0
  59. package/src/lib/server/paged-sweeps.js.map +1 -0
  60. package/src/lib/server/platform-marketing-consent.d.ts +0 -49
  61. package/src/lib/server/platform-marketing-consent.js +27 -11
  62. package/src/lib/server/platform-marketing-consent.js.map +1 -1
  63. package/src/lib/server/serve-media-cdn.d.ts +69 -1
  64. package/src/lib/server/serve-media-cdn.js +424 -70
  65. package/src/lib/server/serve-media-cdn.js.map +1 -1
  66. package/src/lib/server/site-icon-render.d.ts +68 -0
  67. package/src/lib/server/site-icon-render.js +157 -0
  68. package/src/lib/server/site-icon-render.js.map +1 -0
  69. package/src/lib/server/staff-seat.d.ts +50 -0
  70. package/src/lib/server/staff-seat.js +118 -0
  71. package/src/lib/server/staff-seat.js.map +1 -0
  72. package/src/lib/server/transfer-export.d.ts +46 -0
  73. package/src/lib/server/transfer-export.js +221 -0
  74. package/src/lib/server/transfer-export.js.map +1 -0
  75. package/src/lib/server/transfer-jobs.d.ts +385 -0
  76. package/src/lib/server/transfer-jobs.js +2368 -0
  77. package/src/lib/server/transfer-jobs.js.map +1 -0
  78. package/src/lib/server/transfer-packages.d.ts +127 -0
  79. package/src/lib/server/transfer-packages.js +1036 -0
  80. package/src/lib/server/transfer-packages.js.map +1 -0
  81. package/src/lib/server/upgrade-proposal.d.ts +97 -0
  82. package/src/lib/server/upgrade-proposal.js +312 -0
  83. package/src/lib/server/upgrade-proposal.js.map +1 -0
  84. package/src/lib/server/upsert-contact.d.ts +17 -8
  85. package/src/lib/server/upsert-contact.js +82 -16
  86. package/src/lib/server/upsert-contact.js.map +1 -1
  87. package/src/lib/server/web-risk.d.ts +48 -9
  88. package/src/lib/server/web-risk.js +281 -143
  89. package/src/lib/server/web-risk.js.map +1 -1
  90. package/src/tenancy.d.ts +3 -1
  91. package/src/tenancy.js +5 -1
  92. package/src/tenancy.js.map +1 -1
  93. package/src/lib/server/campaign-attribution-store.d.ts +0 -55
  94. package/src/lib/server/campaign-attribution-store.js +0 -95
  95. package/src/lib/server/campaign-attribution-store.js.map +0 -1
  96. package/src/lib/server/campaign-conversion-attribution.d.ts +0 -283
  97. package/src/lib/server/campaign-conversion-attribution.js +0 -450
  98. package/src/lib/server/campaign-conversion-attribution.js.map +0 -1
  99. package/src/lib/server/dataset-live-pages.d.ts +0 -179
  100. package/src/lib/server/dataset-live-pages.js +0 -421
  101. package/src/lib/server/dataset-live-pages.js.map +0 -1
  102. package/src/lib/server/email-revenue-attribution.d.ts +0 -185
  103. package/src/lib/server/email-revenue-attribution.js +0 -321
  104. package/src/lib/server/email-revenue-attribution.js.map +0 -1
@@ -1,450 +0,0 @@
1
- import { _ as _extends } from "@swc/helpers/_/_extends";
2
- /**
3
- * @license
4
- * Copyright 2026 Aglyn LLC
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- */ import { FieldValue } from "firebase-admin/firestore";
18
- import { parseUtmTouch } from "@aglyn/aglyn/app-utils/utm-touch";
19
- /*
20
- * Stamped from the REVENUE join's constants, aliased at the import.
21
- *
22
- * They are spelled `EMAIL_` because that is where both halves of that join
23
- * could reach them, not because the window is an email fact — it is the
24
- * platform's one answer to how long a touch may be credited. Reading them
25
- * from there is what makes a lead's record and an order's record carry the
26
- * same rule rather than two that happen to agree.
27
- */ import { EMAIL_ATTRIBUTION_MODEL as ATTRIBUTION_MODEL, EMAIL_ATTRIBUTION_WINDOW_DAYS as ATTRIBUTION_WINDOW_DAYS, emailTouchIsInWindow } from "@aglyn/shared-util-email/email-revenue-window";
28
- import { personKey } from "@aglyn/aglyn/app-utils/person-key";
29
- import { CAMPAIGN_ATTRIBUTIONS_COLLECTION, eraseCampaignAttributionsForPersonKey } from "./campaign-attribution-store.js";
30
- import { readEmailCampaignTouch } from "./email-delivery-log.js";
31
- import { isDocumentId } from "./document-id.js";
32
- import firebaseAdmin from "./firebase-admin.js";
33
- import { resolveOrgIdForHost } from "./organizations.js";
34
- const defaultFirestore = ()=>firebaseAdmin.app().firestore();
35
- /**
36
- * THE IDENTIFY-MOMENT JOIN — a form, a lead, a contact or a booking, credited
37
- * to the campaign that led to it.
38
- *
39
- * ## Why there is a second join at all, and why it is not a second SCHEME
40
- *
41
- * `email-revenue-attribution.ts` credits an ORDER by looking the buyer's
42
- * address up in the touch map a click wrote. That works because an order
43
- * names its buyer. Every other outcome a campaign causes is produced by
44
- * somebody who was anonymous until the instant they produced it: they arrive
45
- * from a campaign link, browse, and only become identifiable when they submit
46
- * a form, sign up, book or check out. There is no address to look up until
47
- * the very moment being attributed.
48
- *
49
- * So the touch is carried on the VISITOR (`utm-touch.ts`) and attached
50
- * here, at each moment they become somebody. What is NOT rebuilt is the
51
- * model: the same seven-day window, the same last-click rule, the same
52
- * `model`/`windowDays` stamped onto every record so a report can say what it
53
- * counted. The email channel is not re-derived either — it is READ from the
54
- * touch the delivery webhook already wrote, so a campaign email and a
55
- * campaign ad are two inputs to one comparison rather than two schemes with
56
- * two answers.
57
- *
58
- * ## Last touch, across both channels
59
- *
60
- * At the identify moment there can be two candidate touches:
61
- *
62
- * - the WEB touch the visitor's device carried, from an ad, a partner link
63
- * or a social post; and
64
- * - the EMAIL touch on `emailDeliveries/{personKey}.campaignTouches[hostId]`,
65
- * written server-side when they clicked a campaign's mail.
66
- *
67
- * Both are window-checked and the LATER one wins. Splitting the outcome
68
- * between them is the multi-touch model the revenue work rejected for the
69
- * reason that applies here unchanged: a rule the merchant did not choose
70
- * produces a figure nobody can check. One outcome, one campaign, and a rule
71
- * stated on the record.
72
- *
73
- * ## No campaign touch means NO RECORD
74
- *
75
- * Direct traffic writes nothing at all, and there is deliberately no fallback
76
- * — no "most recent campaign on this site", no referrer inference, no
77
- * `utm_source=direct`. A conversion nobody can be credited with is a
78
- * conversion nobody is credited with, and the absence of a record is how the
79
- * report says so. The cost of a miss is one uncounted outcome; the cost of a
80
- * guess is a campaign that reads as effective because it was the last one to
81
- * run.
82
- *
83
- * ## Three reads at most, and usually one
84
- *
85
- * Resolving a touch costs ONE keyed document read, and only when the visitor
86
- * gave an address — no query, no index, nothing that can be truncated. A door
87
- * resolves once per request and hands the result to every writer beneath it,
88
- * so a form submission that creates a submission, a contact and a lead pays
89
- * for the lookup once rather than three times.
90
- *
91
- * ## Never throws
92
- *
93
- * The same contract as the revenue join and for the same reason: the visitor
94
- * has already done the thing being attributed and the record of it is already
95
- * written. A lost attribution understates a campaign; a thrown one loses a
96
- * lead.
97
- */ /**
98
- * The collection and the erasure sweep, re-exported so a caller needs one
99
- * import for the whole join. They are DEFINED in a leaf module because the
100
- * sweep runs from `email-delivery-log.ts`, which this file reads — see
101
- * `campaign-attribution-store.ts` for why that cycle is not merely untidy.
102
- */ export { CAMPAIGN_ATTRIBUTIONS_COLLECTION, eraseCampaignAttributionsForPersonKey, };
103
- /** The single conversion rollup document under an email campaign. */ export const CAMPAIGN_CONVERSIONS_REPORT_DOC = 'conversions';
104
- /**
105
- * The document id for one conversion.
106
- *
107
- * `{kind}:{refId}`, so the same submission credited twice is the same
108
- * document — which is what makes {@link attributeCampaignConversion}'s
109
- * `create()` idempotent. Scoped by kind because the ids come from different
110
- * collections and a booking id has no reason to be distinct from a form
111
- * submission's.
112
- */ export function campaignConversionId(kind, refId) {
113
- return `${kind}:${refId}`;
114
- }
115
- /**
116
- * The campaign touch to credit a conversion happening now, or `null`.
117
- *
118
- * Called ONCE per conversion request, at the door, and the result handed to
119
- * every writer beneath it. See the module docblock for the cost argument.
120
- *
121
- * @returns the winning touch, or `null` when neither channel has one inside
122
- * the window — which is the ordinary case and writes nothing.
123
- */ export async function resolveCampaignTouch(options, firestore) {
124
- try {
125
- var _options_hostId, _options_atMs, _options_email;
126
- const hostId = String((_options_hostId = options.hostId) != null ? _options_hostId : '');
127
- if (!isDocumentId(hostId)) return null;
128
- const convertedAtMs = Number((_options_atMs = options.atMs) != null ? _options_atMs : Date.now());
129
- if (!Number.isFinite(convertedAtMs) || convertedAtMs <= 0) return null;
130
- // The window is enforced inside the parser, so an expired or
131
- // future-dated wire value answers null here exactly as it does in the
132
- // browser that decided whether to send it.
133
- const web = parseUtmTouch(options.wire, convertedAtMs);
134
- const key = personKey(options.email);
135
- /*
136
- * The email channel is only askable of somebody who named an address, and
137
- * that is the whole reason this join needs the web channel at all. No
138
- * address means no keyed read: the ordinary anonymous conversion costs
139
- * nothing here.
140
- */ const emailTouch = key ? await readEmailCampaignTouch(String((_options_email = options.email) != null ? _options_email : ''), hostId, firestore != null ? firestore : defaultFirestore()) : null;
141
- const emailInWindow = emailTouch && isDocumentId(emailTouch.campaignId) && emailTouchIsInWindow(emailTouch.clickedAtMs, convertedAtMs) ? emailTouch : null;
142
- /*
143
- * LAST TOUCH decides, and a tie goes to email. A tie is only reachable
144
- * when the two instants are the same millisecond, and in that case the
145
- * email touch is the better evidence: it was recorded by the provider's
146
- * own click event on the server, while the web touch is a value the
147
- * visitor's device supplied.
148
- */ const emailWins = emailInWindow && (!web || emailInWindow.clickedAtMs >= web.atMs);
149
- if (emailWins) {
150
- const viaSequence = emailInWindow.sequenceId && emailInWindow.enrollmentId;
151
- return _extends({
152
- channel: viaSequence ? 'sequence' : 'email',
153
- campaignId: emailInWindow.campaignId
154
- }, viaSequence ? {
155
- sequenceId: emailInWindow.sequenceId,
156
- enrollmentId: emailInWindow.enrollmentId
157
- } : {}, {
158
- touchedAtMs: emailInWindow.clickedAtMs
159
- }, key ? {
160
- personKey: key
161
- } : {});
162
- }
163
- if (!web) return null;
164
- return _extends({
165
- channel: 'web'
166
- }, web.source ? {
167
- source: web.source
168
- } : {}, web.medium ? {
169
- medium: web.medium
170
- } : {}, web.campaign ? {
171
- campaign: web.campaign
172
- } : {}, {
173
- touchedAtMs: web.atMs
174
- }, key ? {
175
- personKey: key
176
- } : {});
177
- } catch (error) {
178
- console.error('resolveCampaignTouch failed', error);
179
- return null;
180
- }
181
- }
182
- /**
183
- * Credits one conversion to the campaign the visitor last came from.
184
- *
185
- * ## Why the record is a document and not a field
186
- *
187
- * The revenue join's three reasons, and the first is decisive here too.
188
- * `create()` fails when the document already exists, which is exact
189
- * idempotency for free: a retried form POST, a redelivered booking webhook
190
- * and a re-run capture all land here a second time and must all leave the
191
- * rollup where they found it. Second, the four kinds live in four different
192
- * collections — a contact is org-scoped and shared across every site in the
193
- * org — so there is no one document a field could go on. Third, the
194
- * submission, the lead and the booking are read by the inbox, the export and
195
- * the fulfilment path, and none of them wants a field about marketing.
196
- *
197
- * ## The rollup exists for the EMAIL channel only
198
- *
199
- * A campaign document is a real entity with a real id, so its conversions
200
- * roll up under it beside the revenue the same join already credits it with.
201
- * A web campaign is a LABEL the marketer typed into a URL, with no document,
202
- * no id and no bound on how many distinct values exist — the same unbounded
203
- * key space the analytics collector caps its per-day label map against. A
204
- * rollup keyed on it would be a map anybody who can vary a query string can
205
- * grow. So the web channel's records stand on their own and a report reads
206
- * them; see the module's report seam note.
207
- *
208
- * @returns the record written, or `null` when nothing was credited.
209
- */ export async function attributeCampaignConversion(options, firestore) {
210
- try {
211
- var _options_hostId, _options_refId, _options_convertedAtMs;
212
- const { touch } = options;
213
- if (!touch) return null;
214
- const hostId = String((_options_hostId = options.hostId) != null ? _options_hostId : '');
215
- const refId = String((_options_refId = options.refId) != null ? _options_refId : '');
216
- if (!isDocumentId(hostId) || !isDocumentId(refId)) return null;
217
- const convertedAtMs = Number((_options_convertedAtMs = options.convertedAtMs) != null ? _options_convertedAtMs : Date.now());
218
- if (!Number.isFinite(convertedAtMs) || convertedAtMs <= 0) return null;
219
- // Re-checked at the write rather than trusted from the resolve. The two
220
- // are separated by the writes that produced the thing being credited, and
221
- // a touch that has aged out between them is a touch outside the window.
222
- if (!emailTouchIsInWindow(touch.touchedAtMs, convertedAtMs)) return null;
223
- const record = _extends({
224
- kind: options.kind,
225
- refId,
226
- channel: touch.channel
227
- }, touch.campaignId ? {
228
- campaignId: touch.campaignId
229
- } : {}, touch.sequenceId ? {
230
- sequenceId: touch.sequenceId
231
- } : {}, touch.enrollmentId ? {
232
- enrollmentId: touch.enrollmentId
233
- } : {}, touch.source ? {
234
- source: touch.source
235
- } : {}, touch.medium ? {
236
- medium: touch.medium
237
- } : {}, touch.campaign ? {
238
- campaign: touch.campaign
239
- } : {}, {
240
- touchedAtMs: touch.touchedAtMs,
241
- convertedAtMs,
242
- model: ATTRIBUTION_MODEL,
243
- windowDays: ATTRIBUTION_WINDOW_DAYS
244
- }, touch.personKey ? {
245
- personKey: touch.personKey
246
- } : {});
247
- const db = firestore != null ? firestore : defaultFirestore();
248
- const hostRef = db.collection('hosts').doc(hostId);
249
- /*
250
- * `create()`, never `set()` — the revenue join's argument, unchanged. The
251
- * ALREADY_EXISTS failure IS the idempotency, and the rollup below is
252
- * reached only when the create succeeded, so the two can never disagree
253
- * about whether this conversion was counted.
254
- */ try {
255
- await hostRef.collection(CAMPAIGN_ATTRIBUTIONS_COLLECTION).doc(campaignConversionId(options.kind, refId)).create(_extends({}, record, {
256
- createdAt: FieldValue.serverTimestamp()
257
- }));
258
- } catch (unused) {
259
- return null;
260
- }
261
- /*
262
- * The send the touch names (`touch.campaignId` is a SEND id on the email
263
- * channel), wherever it is: the org's `campaigns` collection, or the
264
- * site's for a send the migration has not reached. A send in neither
265
- * place was discarded, and its rollup is skipped — the record above
266
- * already says what was credited.
267
- */ const sendRef = touch.channel === 'email' && touch.campaignId && isDocumentId(touch.campaignId) ? await resolveCampaignSendRef({
268
- hostId,
269
- sendId: touch.campaignId,
270
- firestore: db
271
- }) : null;
272
- if (sendRef) {
273
- /*
274
- * A merge-set that CREATES, for the reason `reports/revenue` gives: this
275
- * writes a document UNDER a campaign, so a campaign that no longer
276
- * exists gains an orphaned report rather than being resurrected as a
277
- * husk in the merchant's history — and the campaign was proven to exist
278
- * when its click wrote the touch.
279
- *
280
- * Every figure is an increment, so two conversions settling at once
281
- * both land.
282
- */ await sendRef.collection('reports').doc(CAMPAIGN_CONVERSIONS_REPORT_DOC).set({
283
- model: ATTRIBUTION_MODEL,
284
- windowDays: ATTRIBUTION_WINDOW_DAYS,
285
- byKind: {
286
- [options.kind]: FieldValue.increment(1)
287
- },
288
- updatedAt: FieldValue.serverTimestamp()
289
- }, {
290
- merge: true
291
- });
292
- }
293
- /*
294
- * A SEQUENCE touch rolls up under the campaign's sequences report, and
295
- * only a booking does: "meetings booked from a sequence link" is the one
296
- * identify moment a sequence's own outcomes do not already count. The
297
- * form, lead and contact kinds stand as records — visible on the record
298
- * they credit and on the site's conversions list — and never in
299
- * `byKind`, whose caveat promises the reader campaign emails only.
300
- */ if (touch.channel === 'sequence' && touch.campaignId && options.kind === 'booking') {
301
- await creditCampaignSequenceOutcome({
302
- hostId,
303
- campaignIds: [
304
- touch.campaignId
305
- ],
306
- outcome: 'meetings',
307
- atMs: convertedAtMs
308
- }, db);
309
- }
310
- return record;
311
- } catch (error) {
312
- console.error('attributeCampaignConversion failed', error);
313
- return null;
314
- }
315
- }
316
- /*==========================================
317
- * WHAT A CAMPAIGN'S SEQUENCES PRODUCED (AGL-3254).
318
- *
319
- * A sequence joins a campaign the way a form does, and the Outreach runtime
320
- * credits what each enrollment produced — enrolled, first email sent, a
321
- * reply, a meeting booked from a sequence link, an enrolled lead converted
322
- * — to every campaign the sequence was in when the person was enrolled. The
323
- * counts live in `orgs/{orgId}/campaignSequenceReports/{campaignId}`, beside
324
- * the org's containers: one document per campaign, server-only like every
325
- * other report here, and never inside the campaign container, which the
326
- * history list reads.
327
- *
328
- * Idempotency is the CALLER's: a plugin credits an outcome once per
329
- * enrollment from a state change that happens once — the enrollment is
330
- * created once, its first email is the first, its status moves to replied
331
- * once, its lead converts once — so this writer is a plain increment and
332
- * keeps no per-enrollment record of its own.
333
- *=========================================*/ /**
334
- * The per-org collection of sequence rollups. Restated from the reader
335
- * (`campaign-report.ts` in the campaigns UI library, which this package may
336
- * not import) and asserted equal by the reader's spec.
337
- */ export const CAMPAIGN_SEQUENCE_REPORTS_COLLECTION = 'campaignSequenceReports';
338
- /** The outcomes the runtime credits, in funnel order. */ export const CAMPAIGN_SEQUENCE_OUTCOMES = [
339
- 'enrolled',
340
- 'sent',
341
- 'replied',
342
- 'meetings',
343
- 'converted'
344
- ];
345
- /**
346
- * Credits one outcome, for one enrollment, to every campaign named.
347
- *
348
- * Never throws, and never refuses the batch for one bad id: the outcome
349
- * has already happened, and a campaign that is gone gains an orphaned
350
- * report rather than blocking the credit to one that is not — the
351
- * conversions rollup's own argument for a merge-set that creates.
352
- *
353
- * @returns how many campaigns were credited.
354
- */ export async function creditCampaignSequenceOutcome(options, firestore) {
355
- try {
356
- var _options_atMs, _options_hostId, _options_orgId;
357
- if (!CAMPAIGN_SEQUENCE_OUTCOMES.includes(options.outcome)) return 0;
358
- const atMs = Number((_options_atMs = options.atMs) != null ? _options_atMs : Date.now());
359
- const ids = [
360
- ...new Set(options.campaignIds.map((id)=>String(id != null ? id : '').trim()))
361
- ].filter((id)=>isDocumentId(id));
362
- if (!ids.length) return 0;
363
- const hostId = String((_options_hostId = options.hostId) != null ? _options_hostId : '');
364
- const given = String((_options_orgId = options.orgId) != null ? _options_orgId : '');
365
- const orgId = isDocumentId(given) ? given : isDocumentId(hostId) ? await resolveOrgIdForHost(hostId) : null;
366
- if (!orgId || !isDocumentId(orgId)) return 0;
367
- const db = firestore != null ? firestore : defaultFirestore();
368
- await Promise.all(ids.map((campaignId)=>orgCampaignSequenceReportRef(orgId, campaignId, db).set(_extends({
369
- byOutcome: {
370
- [options.outcome]: FieldValue.increment(1)
371
- }
372
- }, Number.isFinite(atMs) && atMs > 0 ? {
373
- updatedAtMs: atMs
374
- } : {}, {
375
- updatedAt: FieldValue.serverTimestamp()
376
- }), {
377
- merge: true
378
- })));
379
- return ids.length;
380
- } catch (error) {
381
- console.error('creditCampaignSequenceOutcome failed', error);
382
- return 0;
383
- }
384
- }
385
- /*==========================================
386
- * WHERE A SEND IS (AGL-3273)
387
- *=========================================*/ /**
388
- * WHERE A SEND IS, given only what a link or a delivery event carries.
389
- *
390
- * Campaign containers and sends belong to the organization
391
- * (`orgs/{orgId}/emailCampaigns`, `orgs/{orgId}/campaigns`, AGL-3273). Every
392
- * reader that starts from inside the product already holds the org id and
393
- * addresses those collections directly. This module is for the readers that
394
- * start OUTSIDE it — the unsubscribe link, the provider's delivery webhook,
395
- * the conversion join — which hold a site id and a send id and nothing else,
396
- * because that is what was signed into the link or tagged on the message
397
- * when it went out, possibly years ago.
398
- *
399
- * ## The fallback, and why it stays
400
- *
401
- * The site path (`hosts/{hostId}/campaigns/{sendId}`) is where every send
402
- * lived before the move, and the migration copies each one up under its
403
- * existing id. Between a deployment of this code and the migration reaching
404
- * an org, the send is still only at the site; and an interrupted migration
405
- * leaves some sends behind. A reader that looked only at the org would, in
406
- * that window, drop an unsubscribe's count or a bounce — and a bounce that
407
- * is dropped is an address that gets mailed again. So the org is asked
408
- * first and the site second. After the migration the second read never
409
- * happens, because the first one answers.
410
- *
411
- * The collection names are spelled here rather than imported from the
412
- * campaign model (`@aglyn/shared-ui-email-campaigns`), which this package
413
- * does not depend on. They are the same strings; `campaign-container.ts`
414
- * documents them. The join above is this lookup's first reader, and the two
415
- * move together when the campaign code leaves this package.
416
- */ const sendRefFirestore = ()=>firebaseAdmin.app().firestore();
417
- /** `orgs/{orgId}/campaigns` — one document per email send. */ const ORG_SENDS = 'campaigns';
418
- /** `orgs/{orgId}/campaignSequenceReports` — keyed by the container id. */ const ORG_SEQUENCE_REPORTS = 'campaignSequenceReports';
419
- /** `orgs/{orgId}/campaigns/{sendId}`. */ export function orgCampaignSendRef(orgId, sendId, firestore = sendRefFirestore()) {
420
- return firestore.collection('orgs').doc(orgId).collection(ORG_SENDS).doc(sendId);
421
- }
422
- /** `orgs/{orgId}/campaignSequenceReports/{campaignId}`. */ export function orgCampaignSequenceReportRef(orgId, campaignId, firestore = sendRefFirestore()) {
423
- return firestore.collection('orgs').doc(orgId).collection(ORG_SEQUENCE_REPORTS).doc(campaignId);
424
- }
425
- /** The pre-AGL-3273 location, read only as the fallback described above. */ function legacySiteSendRef(hostId, sendId, firestore) {
426
- return firestore.collection('hosts').doc(hostId).collection(ORG_SENDS).doc(sendId);
427
- }
428
- /**
429
- * The send's document, wherever it currently is. Null when neither location
430
- * holds it — a send id from a link whose send was discarded, or a forged one.
431
- *
432
- * Costs one read after the migration (the org document), plus the
433
- * `hostIndex` lookup when the caller has no org id; that lookup is
434
- * request-cached.
435
- */ export async function resolveCampaignSendRef(input) {
436
- var _input_firestore;
437
- const { hostId, sendId } = input;
438
- if (!hostId || !sendId || sendId.includes('/') || hostId.includes('/')) return null;
439
- const firestore = (_input_firestore = input.firestore) != null ? _input_firestore : sendRefFirestore();
440
- const orgId = input.orgId || await resolveOrgIdForHost(hostId);
441
- if (orgId) {
442
- const orgRef = orgCampaignSendRef(orgId, sendId, firestore);
443
- if ((await orgRef.get()).exists) return orgRef;
444
- }
445
- const siteRef = legacySiteSendRef(hostId, sendId, firestore);
446
- if ((await siteRef.get()).exists) return siteRef;
447
- return null;
448
- }
449
-
450
- //# sourceMappingURL=campaign-conversion-attribution.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/campaign-conversion-attribution.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 { FieldValue, type DocumentReference, type Firestore } from 'firebase-admin/firestore'\nimport {\n parseUtmTouch,\n type UtmTouch,\n} from '@aglyn/aglyn/app-utils/utm-touch'\n/*\n * Stamped from the REVENUE join's constants, aliased at the import.\n *\n * They are spelled `EMAIL_` because that is where both halves of that join\n * could reach them, not because the window is an email fact — it is the\n * platform's one answer to how long a touch may be credited. Reading them\n * from there is what makes a lead's record and an order's record carry the\n * same rule rather than two that happen to agree.\n */\nimport {\n EMAIL_ATTRIBUTION_MODEL as ATTRIBUTION_MODEL,\n EMAIL_ATTRIBUTION_WINDOW_DAYS as ATTRIBUTION_WINDOW_DAYS,\n emailTouchIsInWindow,\n} from '@aglyn/shared-util-email/email-revenue-window'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport {\n CAMPAIGN_ATTRIBUTIONS_COLLECTION,\n eraseCampaignAttributionsForPersonKey,\n} from './campaign-attribution-store'\nimport { readEmailCampaignTouch } from './email-delivery-log'\nimport { isDocumentId } from './document-id'\nimport firebaseAdmin from './firebase-admin'\nimport { resolveOrgIdForHost } from './organizations'\n\nconst defaultFirestore = () => firebaseAdmin.app().firestore()\n\n/**\n * THE IDENTIFY-MOMENT JOIN — a form, a lead, a contact or a booking, credited\n * to the campaign that led to it.\n *\n * ## Why there is a second join at all, and why it is not a second SCHEME\n *\n * `email-revenue-attribution.ts` credits an ORDER by looking the buyer's\n * address up in the touch map a click wrote. That works because an order\n * names its buyer. Every other outcome a campaign causes is produced by\n * somebody who was anonymous until the instant they produced it: they arrive\n * from a campaign link, browse, and only become identifiable when they submit\n * a form, sign up, book or check out. There is no address to look up until\n * the very moment being attributed.\n *\n * So the touch is carried on the VISITOR (`utm-touch.ts`) and attached\n * here, at each moment they become somebody. What is NOT rebuilt is the\n * model: the same seven-day window, the same last-click rule, the same\n * `model`/`windowDays` stamped onto every record so a report can say what it\n * counted. The email channel is not re-derived either — it is READ from the\n * touch the delivery webhook already wrote, so a campaign email and a\n * campaign ad are two inputs to one comparison rather than two schemes with\n * two answers.\n *\n * ## Last touch, across both channels\n *\n * At the identify moment there can be two candidate touches:\n *\n * - the WEB touch the visitor's device carried, from an ad, a partner link\n * or a social post; and\n * - the EMAIL touch on `emailDeliveries/{personKey}.campaignTouches[hostId]`,\n * written server-side when they clicked a campaign's mail.\n *\n * Both are window-checked and the LATER one wins. Splitting the outcome\n * between them is the multi-touch model the revenue work rejected for the\n * reason that applies here unchanged: a rule the merchant did not choose\n * produces a figure nobody can check. One outcome, one campaign, and a rule\n * stated on the record.\n *\n * ## No campaign touch means NO RECORD\n *\n * Direct traffic writes nothing at all, and there is deliberately no fallback\n * — no \"most recent campaign on this site\", no referrer inference, no\n * `utm_source=direct`. A conversion nobody can be credited with is a\n * conversion nobody is credited with, and the absence of a record is how the\n * report says so. The cost of a miss is one uncounted outcome; the cost of a\n * guess is a campaign that reads as effective because it was the last one to\n * run.\n *\n * ## Three reads at most, and usually one\n *\n * Resolving a touch costs ONE keyed document read, and only when the visitor\n * gave an address — no query, no index, nothing that can be truncated. A door\n * resolves once per request and hands the result to every writer beneath it,\n * so a form submission that creates a submission, a contact and a lead pays\n * for the lookup once rather than three times.\n *\n * ## Never throws\n *\n * The same contract as the revenue join and for the same reason: the visitor\n * has already done the thing being attributed and the record of it is already\n * written. A lost attribution understates a campaign; a thrown one loses a\n * lead.\n */\n\n/**\n * The collection and the erasure sweep, re-exported so a caller needs one\n * import for the whole join. They are DEFINED in a leaf module because the\n * sweep runs from `email-delivery-log.ts`, which this file reads — see\n * `campaign-attribution-store.ts` for why that cycle is not merely untidy.\n */\nexport {\n CAMPAIGN_ATTRIBUTIONS_COLLECTION,\n eraseCampaignAttributionsForPersonKey,\n}\n\n/** The single conversion rollup document under an email campaign. */\nexport const CAMPAIGN_CONVERSIONS_REPORT_DOC = 'conversions'\n\n/**\n * Which identify moment a record credits.\n *\n * Kept apart rather than summed, which is the whole reason the kind is on the\n * record. One form submission by a new person creates a submission, a contact\n * and possibly a lead — three true statements about one visitor action — and\n * a report that added them would treble every campaign's conversions. A\n * reader asks for one kind at a time, exactly as the revenue rollup buckets\n * by currency and never totals across them.\n */\nexport type CampaignConversionKind = 'form' | 'lead' | 'contact' | 'booking'\n\n/**\n * Which channel the credited touch arrived through.\n *\n * `sequence` (AGL-3254) is a click on, or the sending of, a one-to-one\n * email a rep's sequence sent. It is read off the same touch map as the\n * email channel — the Outreach click route stamps it there with the\n * sequence and the enrollment beside the campaign the sequence is in — so\n * a booking made from a sequence link is credited by the door that credits\n * every other booking, and nothing in this join has to know what a\n * sequence is.\n */\nexport type CampaignTouchChannel = 'email' | 'web' | 'sequence'\n\n/** The touch a conversion is credited to, once both channels have been asked. */\nexport interface ResolvedCampaignTouch {\n channel: CampaignTouchChannel\n /**\n * The campaign document, when the touch was a click on our own mail — or\n * the campaign CONTAINER (`emailCampaigns/{id}`) a sequence is in, for a\n * sequence touch.\n */\n campaignId?: string\n /** The sequence the touch came through, for a `sequence` touch. */\n sequenceId?: string\n /** The enrollment the touch came through, for a `sequence` touch. */\n enrollmentId?: string\n /** `utm_source`, when the touch was a link on the web. */\n source?: string\n /** `utm_medium`, when the touch was a link on the web. */\n medium?: string\n /** `utm_campaign`, when the touch was a link on the web. */\n campaign?: string\n /** When the visitor followed the campaign link, epoch ms. */\n touchedAtMs: number\n /**\n * `sha256` of the normalized address the touch was resolved against, when\n * the visitor gave one. The handle an erasure erases by — see\n * {@link eraseCampaignAttributionsForPersonKey}.\n */\n personKey?: string\n}\n\n/** What one conversion attribution record holds. */\nexport interface CampaignConversionRecord extends ResolvedCampaignTouch {\n kind: CampaignConversionKind\n /** The submission, lead, contact or booking this credits. */\n refId: string\n /** When the visitor became identifiable. */\n convertedAtMs: number\n /** The model this credit was decided under. */\n model: string\n /** The window, in days, it was decided inside. */\n windowDays: number\n}\n\n/**\n * The document id for one conversion.\n *\n * `{kind}:{refId}`, so the same submission credited twice is the same\n * document — which is what makes {@link attributeCampaignConversion}'s\n * `create()` idempotent. Scoped by kind because the ids come from different\n * collections and a booking id has no reason to be distinct from a form\n * submission's.\n */\nexport function campaignConversionId(\n kind: CampaignConversionKind,\n refId: string,\n): string {\n return `${kind}:${refId}`\n}\n\n/**\n * The campaign touch to credit a conversion happening now, or `null`.\n *\n * Called ONCE per conversion request, at the door, and the result handed to\n * every writer beneath it. See the module docblock for the cost argument.\n *\n * @returns the winning touch, or `null` when neither channel has one inside\n * the window — which is the ordinary case and writes nothing.\n */\nexport async function resolveCampaignTouch(\n options: {\n hostId: string\n /**\n * The wire form the conversion request carried, when the door reports\n * one. Re-parsed through the allowlist that wrote it rather than trusted:\n * it arrives from the visitor's browser, so it may claim no more than an\n * inbound URL could.\n */\n wire?: unknown\n /** The address the visitor identified with, raw. */\n email?: unknown\n /** When they identified themselves. Defaults to now. */\n atMs?: number\n },\n firestore?: any,\n): Promise<ResolvedCampaignTouch | null> {\n try {\n const hostId = String(options.hostId ?? '')\n if (!isDocumentId(hostId)) return null\n const convertedAtMs = Number(options.atMs ?? Date.now())\n if (!Number.isFinite(convertedAtMs) || convertedAtMs <= 0) return null\n\n // The window is enforced inside the parser, so an expired or\n // future-dated wire value answers null here exactly as it does in the\n // browser that decided whether to send it.\n const web: UtmTouch | null = parseUtmTouch(\n options.wire,\n convertedAtMs,\n )\n\n const key = personKey(options.email)\n /*\n * The email channel is only askable of somebody who named an address, and\n * that is the whole reason this join needs the web channel at all. No\n * address means no keyed read: the ordinary anonymous conversion costs\n * nothing here.\n */\n const emailTouch = key\n ? await readEmailCampaignTouch(\n String(options.email ?? ''),\n hostId,\n firestore ?? defaultFirestore(),\n )\n : null\n const emailInWindow =\n emailTouch &&\n isDocumentId(emailTouch.campaignId) &&\n emailTouchIsInWindow(emailTouch.clickedAtMs, convertedAtMs)\n ? emailTouch\n : null\n\n /*\n * LAST TOUCH decides, and a tie goes to email. A tie is only reachable\n * when the two instants are the same millisecond, and in that case the\n * email touch is the better evidence: it was recorded by the provider's\n * own click event on the server, while the web touch is a value the\n * visitor's device supplied.\n */\n const emailWins =\n emailInWindow && (!web || emailInWindow.clickedAtMs >= web.atMs)\n if (emailWins) {\n const viaSequence = emailInWindow.sequenceId && emailInWindow.enrollmentId\n return {\n channel: viaSequence ? 'sequence' : 'email',\n campaignId: emailInWindow.campaignId,\n ...(viaSequence\n ? { sequenceId: emailInWindow.sequenceId, enrollmentId: emailInWindow.enrollmentId }\n : {}),\n touchedAtMs: emailInWindow.clickedAtMs,\n ...(key ? { personKey: key } : {}),\n }\n }\n if (!web) return null\n return {\n channel: 'web',\n ...(web.source ? { source: web.source } : {}),\n ...(web.medium ? { medium: web.medium } : {}),\n ...(web.campaign ? { campaign: web.campaign } : {}),\n touchedAtMs: web.atMs,\n ...(key ? { personKey: key } : {}),\n }\n } catch (error) {\n console.error('resolveCampaignTouch failed', error)\n return null\n }\n}\n\n/**\n * Credits one conversion to the campaign the visitor last came from.\n *\n * ## Why the record is a document and not a field\n *\n * The revenue join's three reasons, and the first is decisive here too.\n * `create()` fails when the document already exists, which is exact\n * idempotency for free: a retried form POST, a redelivered booking webhook\n * and a re-run capture all land here a second time and must all leave the\n * rollup where they found it. Second, the four kinds live in four different\n * collections — a contact is org-scoped and shared across every site in the\n * org — so there is no one document a field could go on. Third, the\n * submission, the lead and the booking are read by the inbox, the export and\n * the fulfilment path, and none of them wants a field about marketing.\n *\n * ## The rollup exists for the EMAIL channel only\n *\n * A campaign document is a real entity with a real id, so its conversions\n * roll up under it beside the revenue the same join already credits it with.\n * A web campaign is a LABEL the marketer typed into a URL, with no document,\n * no id and no bound on how many distinct values exist — the same unbounded\n * key space the analytics collector caps its per-day label map against. A\n * rollup keyed on it would be a map anybody who can vary a query string can\n * grow. So the web channel's records stand on their own and a report reads\n * them; see the module's report seam note.\n *\n * @returns the record written, or `null` when nothing was credited.\n */\nexport async function attributeCampaignConversion(\n options: {\n hostId: string\n kind: CampaignConversionKind\n /** The submission, lead, contact or booking being credited. */\n refId: string\n /** The touch {@link resolveCampaignTouch} picked, or `null` for direct. */\n touch: ResolvedCampaignTouch | null | undefined\n /** When the visitor became identifiable. Defaults to now. */\n convertedAtMs?: number\n },\n firestore?: any,\n): Promise<CampaignConversionRecord | null> {\n try {\n const { touch } = options\n if (!touch) return null\n const hostId = String(options.hostId ?? '')\n const refId = String(options.refId ?? '')\n if (!isDocumentId(hostId) || !isDocumentId(refId)) return null\n const convertedAtMs = Number(options.convertedAtMs ?? Date.now())\n if (!Number.isFinite(convertedAtMs) || convertedAtMs <= 0) return null\n // Re-checked at the write rather than trusted from the resolve. The two\n // are separated by the writes that produced the thing being credited, and\n // a touch that has aged out between them is a touch outside the window.\n if (!emailTouchIsInWindow(touch.touchedAtMs, convertedAtMs)) return null\n\n const record: CampaignConversionRecord = {\n kind: options.kind,\n refId,\n channel: touch.channel,\n ...(touch.campaignId ? { campaignId: touch.campaignId } : {}),\n ...(touch.sequenceId ? { sequenceId: touch.sequenceId } : {}),\n ...(touch.enrollmentId ? { enrollmentId: touch.enrollmentId } : {}),\n ...(touch.source ? { source: touch.source } : {}),\n ...(touch.medium ? { medium: touch.medium } : {}),\n ...(touch.campaign ? { campaign: touch.campaign } : {}),\n touchedAtMs: touch.touchedAtMs,\n convertedAtMs,\n model: ATTRIBUTION_MODEL,\n windowDays: ATTRIBUTION_WINDOW_DAYS,\n ...(touch.personKey ? { personKey: touch.personKey } : {}),\n }\n\n const db = firestore ?? defaultFirestore()\n const hostRef = db.collection('hosts').doc(hostId)\n /*\n * `create()`, never `set()` — the revenue join's argument, unchanged. The\n * ALREADY_EXISTS failure IS the idempotency, and the rollup below is\n * reached only when the create succeeded, so the two can never disagree\n * about whether this conversion was counted.\n */\n try {\n await hostRef\n .collection(CAMPAIGN_ATTRIBUTIONS_COLLECTION)\n .doc(campaignConversionId(options.kind, refId))\n .create({ ...record, createdAt: FieldValue.serverTimestamp() })\n } catch {\n return null\n }\n\n /*\n * The send the touch names (`touch.campaignId` is a SEND id on the email\n * channel), wherever it is: the org's `campaigns` collection, or the\n * site's for a send the migration has not reached. A send in neither\n * place was discarded, and its rollup is skipped — the record above\n * already says what was credited.\n */\n const sendRef =\n touch.channel === 'email' && touch.campaignId && isDocumentId(touch.campaignId)\n ? await resolveCampaignSendRef({ hostId, sendId: touch.campaignId, firestore: db })\n : null\n if (sendRef) {\n /*\n * A merge-set that CREATES, for the reason `reports/revenue` gives: this\n * writes a document UNDER a campaign, so a campaign that no longer\n * exists gains an orphaned report rather than being resurrected as a\n * husk in the merchant's history — and the campaign was proven to exist\n * when its click wrote the touch.\n *\n * Every figure is an increment, so two conversions settling at once\n * both land.\n */\n await sendRef\n .collection('reports')\n .doc(CAMPAIGN_CONVERSIONS_REPORT_DOC)\n .set(\n {\n model: ATTRIBUTION_MODEL,\n windowDays: ATTRIBUTION_WINDOW_DAYS,\n byKind: { [options.kind]: FieldValue.increment(1) },\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n }\n\n /*\n * A SEQUENCE touch rolls up under the campaign's sequences report, and\n * only a booking does: \"meetings booked from a sequence link\" is the one\n * identify moment a sequence's own outcomes do not already count. The\n * form, lead and contact kinds stand as records — visible on the record\n * they credit and on the site's conversions list — and never in\n * `byKind`, whose caveat promises the reader campaign emails only.\n */\n if (touch.channel === 'sequence' && touch.campaignId && options.kind === 'booking') {\n await creditCampaignSequenceOutcome(\n { hostId, campaignIds: [touch.campaignId], outcome: 'meetings', atMs: convertedAtMs },\n db,\n )\n }\n\n return record\n } catch (error) {\n console.error('attributeCampaignConversion failed', error)\n return null\n }\n}\n\n/*==========================================\n * WHAT A CAMPAIGN'S SEQUENCES PRODUCED (AGL-3254).\n *\n * A sequence joins a campaign the way a form does, and the Outreach runtime\n * credits what each enrollment produced — enrolled, first email sent, a\n * reply, a meeting booked from a sequence link, an enrolled lead converted\n * — to every campaign the sequence was in when the person was enrolled. The\n * counts live in `orgs/{orgId}/campaignSequenceReports/{campaignId}`, beside\n * the org's containers: one document per campaign, server-only like every\n * other report here, and never inside the campaign container, which the\n * history list reads.\n *\n * Idempotency is the CALLER's: a plugin credits an outcome once per\n * enrollment from a state change that happens once — the enrollment is\n * created once, its first email is the first, its status moves to replied\n * once, its lead converts once — so this writer is a plain increment and\n * keeps no per-enrollment record of its own.\n *=========================================*/\n\n/**\n * The per-org collection of sequence rollups. Restated from the reader\n * (`campaign-report.ts` in the campaigns UI library, which this package may\n * not import) and asserted equal by the reader's spec.\n */\nexport const CAMPAIGN_SEQUENCE_REPORTS_COLLECTION = 'campaignSequenceReports'\n\n/** The outcomes the runtime credits, in funnel order. */\nexport const CAMPAIGN_SEQUENCE_OUTCOMES = [\n 'enrolled',\n 'sent',\n 'replied',\n 'meetings',\n 'converted',\n] as const\n\nexport type CampaignSequenceOutcome = (typeof CAMPAIGN_SEQUENCE_OUTCOMES)[number]\n\n/**\n * Credits one outcome, for one enrollment, to every campaign named.\n *\n * Never throws, and never refuses the batch for one bad id: the outcome\n * has already happened, and a campaign that is gone gains an orphaned\n * report rather than blocking the credit to one that is not — the\n * conversions rollup's own argument for a merge-set that creates.\n *\n * @returns how many campaigns were credited.\n */\nexport async function creditCampaignSequenceOutcome(\n options: {\n /** The site the enrollment emails for; resolves the org when none is given. */\n hostId: string\n /**\n * The org whose containers the campaigns are, when the caller holds it —\n * an enrollment is an org document, so its routes do. Saves the\n * `hostIndex` read.\n */\n orgId?: string | null\n /** The campaigns the enrollment carries; unusable ids are skipped. */\n campaignIds: readonly string[]\n outcome: CampaignSequenceOutcome\n /** When the outcome happened. Defaults to now. */\n atMs?: number\n },\n firestore?: any,\n): Promise<number> {\n try {\n if (!(CAMPAIGN_SEQUENCE_OUTCOMES as readonly string[]).includes(options.outcome)) return 0\n const atMs = Number(options.atMs ?? Date.now())\n const ids = [...new Set(options.campaignIds.map((id) => String(id ?? '').trim()))].filter(\n (id) => isDocumentId(id),\n )\n if (!ids.length) return 0\n const hostId = String(options.hostId ?? '')\n const given = String(options.orgId ?? '')\n const orgId = isDocumentId(given)\n ? given\n : isDocumentId(hostId)\n ? await resolveOrgIdForHost(hostId)\n : null\n if (!orgId || !isDocumentId(orgId)) return 0\n const db = firestore ?? defaultFirestore()\n await Promise.all(\n ids.map((campaignId) =>\n orgCampaignSequenceReportRef(orgId, campaignId, db).set(\n {\n byOutcome: { [options.outcome]: FieldValue.increment(1) },\n ...(Number.isFinite(atMs) && atMs > 0 ? { updatedAtMs: atMs } : {}),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n ),\n ),\n )\n return ids.length\n } catch (error) {\n console.error('creditCampaignSequenceOutcome failed', error)\n return 0\n }\n}\n\n/*==========================================\n * WHERE A SEND IS (AGL-3273)\n *=========================================*/\n\n/**\n * WHERE A SEND IS, given only what a link or a delivery event carries.\n *\n * Campaign containers and sends belong to the organization\n * (`orgs/{orgId}/emailCampaigns`, `orgs/{orgId}/campaigns`, AGL-3273). Every\n * reader that starts from inside the product already holds the org id and\n * addresses those collections directly. This module is for the readers that\n * start OUTSIDE it — the unsubscribe link, the provider's delivery webhook,\n * the conversion join — which hold a site id and a send id and nothing else,\n * because that is what was signed into the link or tagged on the message\n * when it went out, possibly years ago.\n *\n * ## The fallback, and why it stays\n *\n * The site path (`hosts/{hostId}/campaigns/{sendId}`) is where every send\n * lived before the move, and the migration copies each one up under its\n * existing id. Between a deployment of this code and the migration reaching\n * an org, the send is still only at the site; and an interrupted migration\n * leaves some sends behind. A reader that looked only at the org would, in\n * that window, drop an unsubscribe's count or a bounce — and a bounce that\n * is dropped is an address that gets mailed again. So the org is asked\n * first and the site second. After the migration the second read never\n * happens, because the first one answers.\n *\n * The collection names are spelled here rather than imported from the\n * campaign model (`@aglyn/shared-ui-email-campaigns`), which this package\n * does not depend on. They are the same strings; `campaign-container.ts`\n * documents them. The join above is this lookup's first reader, and the two\n * move together when the campaign code leaves this package.\n */\n\nconst sendRefFirestore = (): Firestore => firebaseAdmin.app().firestore()\n\n/** `orgs/{orgId}/campaigns` — one document per email send. */\nconst ORG_SENDS = 'campaigns'\n\n/** `orgs/{orgId}/campaignSequenceReports` — keyed by the container id. */\nconst ORG_SEQUENCE_REPORTS = 'campaignSequenceReports'\n\n/** `orgs/{orgId}/campaigns/{sendId}`. */\nexport function orgCampaignSendRef(\n orgId: string,\n sendId: string,\n firestore: Firestore = sendRefFirestore(),\n): DocumentReference {\n return firestore.collection('orgs').doc(orgId).collection(ORG_SENDS).doc(sendId)\n}\n\n/** `orgs/{orgId}/campaignSequenceReports/{campaignId}`. */\nexport function orgCampaignSequenceReportRef(\n orgId: string,\n campaignId: string,\n firestore: Firestore = sendRefFirestore(),\n): DocumentReference {\n return firestore\n .collection('orgs')\n .doc(orgId)\n .collection(ORG_SEQUENCE_REPORTS)\n .doc(campaignId)\n}\n\n/** The pre-AGL-3273 location, read only as the fallback described above. */\nfunction legacySiteSendRef(\n hostId: string,\n sendId: string,\n firestore: Firestore,\n): DocumentReference {\n return firestore.collection('hosts').doc(hostId).collection(ORG_SENDS).doc(sendId)\n}\n\nexport interface ResolveCampaignSendRefInput {\n /** The site the link or the message tag names. */\n hostId: string\n /** The send id (`cid` on a link, `campaignId` on a message tag). */\n sendId: string\n /**\n * The org, when the caller already has it — a message tag minted since\n * AGL-3273 carries it. Saves the `hostIndex` read.\n */\n orgId?: string | null\n firestore?: Firestore\n}\n\n/**\n * The send's document, wherever it currently is. Null when neither location\n * holds it — a send id from a link whose send was discarded, or a forged one.\n *\n * Costs one read after the migration (the org document), plus the\n * `hostIndex` lookup when the caller has no org id; that lookup is\n * request-cached.\n */\nexport async function resolveCampaignSendRef(\n input: ResolveCampaignSendRefInput,\n): Promise<DocumentReference | null> {\n const { hostId, sendId } = input\n if (!hostId || !sendId || sendId.includes('/') || hostId.includes('/')) return null\n const firestore = input.firestore ?? sendRefFirestore()\n const orgId = input.orgId || (await resolveOrgIdForHost(hostId))\n if (orgId) {\n const orgRef = orgCampaignSendRef(orgId, sendId, firestore)\n if ((await orgRef.get()).exists) return orgRef\n }\n const siteRef = legacySiteSendRef(hostId, sendId, firestore)\n if ((await siteRef.get()).exists) return siteRef\n return null\n}\n"],"names":["FieldValue","parseUtmTouch","EMAIL_ATTRIBUTION_MODEL","ATTRIBUTION_MODEL","EMAIL_ATTRIBUTION_WINDOW_DAYS","ATTRIBUTION_WINDOW_DAYS","emailTouchIsInWindow","personKey","CAMPAIGN_ATTRIBUTIONS_COLLECTION","eraseCampaignAttributionsForPersonKey","readEmailCampaignTouch","isDocumentId","firebaseAdmin","resolveOrgIdForHost","defaultFirestore","app","firestore","CAMPAIGN_CONVERSIONS_REPORT_DOC","campaignConversionId","kind","refId","resolveCampaignTouch","options","hostId","String","convertedAtMs","Number","atMs","Date","now","isFinite","web","wire","key","email","emailTouch","emailInWindow","campaignId","clickedAtMs","emailWins","viaSequence","sequenceId","enrollmentId","channel","touchedAtMs","source","medium","campaign","error","console","attributeCampaignConversion","touch","record","model","windowDays","db","hostRef","collection","doc","create","createdAt","serverTimestamp","sendRef","resolveCampaignSendRef","sendId","set","byKind","increment","updatedAt","merge","creditCampaignSequenceOutcome","campaignIds","outcome","CAMPAIGN_SEQUENCE_REPORTS_COLLECTION","CAMPAIGN_SEQUENCE_OUTCOMES","includes","ids","Set","map","id","trim","filter","length","given","orgId","Promise","all","orgCampaignSequenceReportRef","byOutcome","updatedAtMs","sendRefFirestore","ORG_SENDS","ORG_SEQUENCE_REPORTS","orgCampaignSendRef","legacySiteSendRef","input","orgRef","get","exists","siteRef"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAgD,2BAA0B;AAC7F,SACEC,aAAa,QAER,mCAAkC;AACzC;;;;;;;;CAQC,GACD,SACEC,2BAA2BC,iBAAiB,EAC5CC,iCAAiCC,uBAAuB,EACxDC,oBAAoB,QACf,gDAA+C;AACtD,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SACEC,gCAAgC,EAChCC,qCAAqC,QAChC,kCAA8B;AACrC,SAASC,sBAAsB,QAAQ,0BAAsB;AAC7D,SAASC,YAAY,QAAQ,mBAAe;AAC5C,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,mBAAmB,QAAQ,qBAAiB;AAErD,MAAMC,mBAAmB,IAAMF,cAAcG,GAAG,GAAGC,SAAS;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8DC,GAED;;;;;CAKC,GACD,SACER,gCAAgC,EAChCC,qCAAqC,KACtC;AAED,mEAAmE,GACnE,OAAO,MAAMQ,kCAAkC,cAAa;AAqE5D;;;;;;;;CAQC,GACD,OAAO,SAASC,qBACdC,IAA4B,EAC5BC,KAAa;IAEb,OAAO,GAAGD,KAAK,CAAC,EAAEC,OAAO;AAC3B;AAEA;;;;;;;;CAQC,GACD,OAAO,eAAeC,qB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