@aglyn/tenant-data-admin 1.0.0-beta.173 → 1.0.0-beta.175

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.0.0-beta.173",
3
+ "version": "1.0.0-beta.175",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,11 +25,11 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.173",
29
- "@aglyn/shared-util-email": "1.0.0-beta.173",
30
- "@aglyn/shared-util-fbserver": "1.0.0-beta.173",
31
- "@aglyn/shared-util-http": "1.0.0-beta.173",
32
- "@aglyn/shared-util-tools": "1.0.0-beta.173",
28
+ "@aglyn/aglyn": "1.0.0-beta.175",
29
+ "@aglyn/shared-util-email": "1.0.0-beta.175",
30
+ "@aglyn/shared-util-fbserver": "1.0.0-beta.175",
31
+ "@aglyn/shared-util-http": "1.0.0-beta.175",
32
+ "@aglyn/shared-util-tools": "1.0.0-beta.175",
33
33
  "@msgpack/msgpack": "^3.1.3",
34
34
  "@swc/helpers": "0.5.23",
35
35
  "sharp": "^0.35.3",
@@ -14,6 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
+ import { type DocumentReference, type Firestore } from 'firebase-admin/firestore';
17
18
  import { CAMPAIGN_ATTRIBUTIONS_COLLECTION, eraseCampaignAttributionsForPersonKey } from './campaign-attribution-store';
18
19
  /**
19
20
  * THE IDENTIFY-MOMENT JOIN — a form, a lead, a contact or a booking, credited
@@ -222,7 +223,7 @@ export declare function attributeCampaignConversion(options: {
222
223
  convertedAtMs?: number;
223
224
  }, firestore?: any): Promise<CampaignConversionRecord | null>;
224
225
  /**
225
- * The per-host collection of sequence rollups. Restated from the reader
226
+ * The per-org collection of sequence rollups. Restated from the reader
226
227
  * (`campaign-report.ts` in the campaigns UI library, which this package may
227
228
  * not import) and asserted equal by the reader's spec.
228
229
  */
@@ -241,10 +242,42 @@ export type CampaignSequenceOutcome = (typeof CAMPAIGN_SEQUENCE_OUTCOMES)[number
241
242
  * @returns how many campaigns were credited.
242
243
  */
243
244
  export declare function creditCampaignSequenceOutcome(options: {
245
+ /** The site the enrollment emails for; resolves the org when none is given. */
244
246
  hostId: string;
247
+ /**
248
+ * The org whose containers the campaigns are, when the caller holds it —
249
+ * an enrollment is an org document, so its routes do. Saves the
250
+ * `hostIndex` read.
251
+ */
252
+ orgId?: string | null;
245
253
  /** The campaigns the enrollment carries; unusable ids are skipped. */
246
254
  campaignIds: readonly string[];
247
255
  outcome: CampaignSequenceOutcome;
248
256
  /** When the outcome happened. Defaults to now. */
249
257
  atMs?: number;
250
258
  }, firestore?: any): Promise<number>;
259
+ /** `orgs/{orgId}/campaigns/{sendId}`. */
260
+ export declare function orgCampaignSendRef(orgId: string, sendId: string, firestore?: Firestore): DocumentReference;
261
+ /** `orgs/{orgId}/campaignSequenceReports/{campaignId}`. */
262
+ export declare function orgCampaignSequenceReportRef(orgId: string, campaignId: string, firestore?: Firestore): DocumentReference;
263
+ export interface ResolveCampaignSendRefInput {
264
+ /** The site the link or the message tag names. */
265
+ hostId: string;
266
+ /** The send id (`cid` on a link, `campaignId` on a message tag). */
267
+ sendId: string;
268
+ /**
269
+ * The org, when the caller already has it — a message tag minted since
270
+ * AGL-3273 carries it. Saves the `hostIndex` read.
271
+ */
272
+ orgId?: string | null;
273
+ firestore?: Firestore;
274
+ }
275
+ /**
276
+ * The send's document, wherever it currently is. Null when neither location
277
+ * holds it — a send id from a link whose send was discarded, or a forged one.
278
+ *
279
+ * Costs one read after the migration (the org document), plus the
280
+ * `hostIndex` lookup when the caller has no org id; that lookup is
281
+ * request-cached.
282
+ */
283
+ export declare function resolveCampaignSendRef(input: ResolveCampaignSendRefInput): Promise<DocumentReference | null>;
@@ -30,6 +30,7 @@ import { CAMPAIGN_ATTRIBUTIONS_COLLECTION, eraseCampaignAttributionsForPersonKey
30
30
  import { readEmailCampaignTouch } from "./email-delivery-log.js";
31
31
  import { isDocumentId } from "./document-id.js";
32
32
  import firebaseAdmin from "./firebase-admin.js";
33
+ import { resolveOrgIdForHost } from "./organizations.js";
33
34
  const defaultFirestore = ()=>firebaseAdmin.app().firestore();
34
35
  /**
35
36
  * THE IDENTIFY-MOMENT JOIN — a form, a lead, a contact or a booking, credited
@@ -257,7 +258,18 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
257
258
  } catch (unused) {
258
259
  return null;
259
260
  }
260
- if (touch.channel === 'email' && touch.campaignId) {
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) {
261
273
  /*
262
274
  * A merge-set that CREATES, for the reason `reports/revenue` gives: this
263
275
  * writes a document UNDER a campaign, so a campaign that no longer
@@ -267,7 +279,7 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
267
279
  *
268
280
  * Every figure is an increment, so two conversions settling at once
269
281
  * both land.
270
- */ await hostRef.collection('campaigns').doc(touch.campaignId).collection('reports').doc(CAMPAIGN_CONVERSIONS_REPORT_DOC).set({
282
+ */ await sendRef.collection('reports').doc(CAMPAIGN_CONVERSIONS_REPORT_DOC).set({
271
283
  model: ATTRIBUTION_MODEL,
272
284
  windowDays: ATTRIBUTION_WINDOW_DAYS,
273
285
  byKind: {
@@ -308,9 +320,10 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
308
320
  * credits what each enrollment produced — enrolled, first email sent, a
309
321
  * reply, a meeting booked from a sequence link, an enrolled lead converted
310
322
  * — to every campaign the sequence was in when the person was enrolled. The
311
- * counts live in `hosts/{hostId}/campaignSequenceReports/{campaignId}`:
312
- * one document per campaign, server-only like every other report here, and
313
- * never inside the campaign container, which the history list reads.
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.
314
327
  *
315
328
  * Idempotency is the CALLER's: a plugin credits an outcome once per
316
329
  * enrollment from a state change that happens once — the enrollment is
@@ -318,7 +331,7 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
318
331
  * once, its lead converts once — so this writer is a plain increment and
319
332
  * keeps no per-enrollment record of its own.
320
333
  *=========================================*/ /**
321
- * The per-host collection of sequence rollups. Restated from the reader
334
+ * The per-org collection of sequence rollups. Restated from the reader
322
335
  * (`campaign-report.ts` in the campaigns UI library, which this package may
323
336
  * not import) and asserted equal by the reader's spec.
324
337
  */ export const CAMPAIGN_SEQUENCE_REPORTS_COLLECTION = 'campaignSequenceReports';
@@ -340,18 +353,19 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
340
353
  * @returns how many campaigns were credited.
341
354
  */ export async function creditCampaignSequenceOutcome(options, firestore) {
342
355
  try {
343
- var _options_hostId, _options_atMs;
344
- const hostId = String((_options_hostId = options.hostId) != null ? _options_hostId : '');
345
- if (!isDocumentId(hostId)) return 0;
356
+ var _options_atMs, _options_hostId, _options_orgId;
346
357
  if (!CAMPAIGN_SEQUENCE_OUTCOMES.includes(options.outcome)) return 0;
347
358
  const atMs = Number((_options_atMs = options.atMs) != null ? _options_atMs : Date.now());
348
359
  const ids = [
349
360
  ...new Set(options.campaignIds.map((id)=>String(id != null ? id : '').trim()))
350
361
  ].filter((id)=>isDocumentId(id));
351
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;
352
367
  const db = firestore != null ? firestore : defaultFirestore();
353
- const reports = db.collection('hosts').doc(hostId).collection(CAMPAIGN_SEQUENCE_REPORTS_COLLECTION);
354
- await Promise.all(ids.map((campaignId)=>reports.doc(campaignId).set(_extends({
368
+ await Promise.all(ids.map((campaignId)=>orgCampaignSequenceReportRef(orgId, campaignId, db).set(_extends({
355
369
  byOutcome: {
356
370
  [options.outcome]: FieldValue.increment(1)
357
371
  }
@@ -368,5 +382,69 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
368
382
  return 0;
369
383
  }
370
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
+ }
371
449
 
372
450
  //# sourceMappingURL=campaign-conversion-attribution.js.map
@@ -1 +1 @@
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 } from 'firebase-admin/firestore'\nimport {\n parseCampaignTouch,\n type CampaignTouch,\n} from '@aglyn/aglyn/app-utils/campaign-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'\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 (`campaign-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: CampaignTouch | null = parseCampaignTouch(\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 if (touch.channel === 'email' && touch.campaignId) {\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 hostRef\n .collection('campaigns')\n .doc(touch.campaignId)\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 `hosts/{hostId}/campaignSequenceReports/{campaignId}`:\n * one document per campaign, server-only like every other report here, and\n * never inside the campaign container, which the 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-host 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 hostId: string\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 const hostId = String(options.hostId ?? '')\n if (!isDocumentId(hostId)) return 0\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 db = firestore ?? defaultFirestore()\n const reports = db.collection('hosts').doc(hostId).collection(CAMPAIGN_SEQUENCE_REPORTS_COLLECTION)\n await Promise.all(\n ids.map((campaignId) =>\n reports.doc(campaignId).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"],"names":["FieldValue","parseCampaignTouch","EMAIL_ATTRIBUTION_MODEL","ATTRIBUTION_MODEL","EMAIL_ATTRIBUTION_WINDOW_DAYS","ATTRIBUTION_WINDOW_DAYS","emailTouchIsInWindow","personKey","CAMPAIGN_ATTRIBUTIONS_COLLECTION","eraseCampaignAttributionsForPersonKey","readEmailCampaignTouch","isDocumentId","firebaseAdmin","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","set","byKind","increment","updatedAt","merge","creditCampaignSequenceOutcome","campaignIds","outcome","CAMPAIGN_SEQUENCE_REPORTS_COLLECTION","CAMPAIGN_SEQUENCE_OUTCOMES","includes","ids","Set","map","id","trim","filter","length","reports","Promise","all","byOutcome","updatedAtMs"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,2BAA0B;AACrD,SACEC,kBAAkB,QAEb,wCAAuC;AAC9C;;;;;;;;CAQC,GACD,SACEC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,OAAO;QAClC,IAAI,CAAC,AAACgD,2BAAiDC,QAAQ,CAAClD,QAAQ+C,OAAO,GAAG,OAAO;QACzF,MAAM1C,OAAOD,QAAOJ,gBAAAA,QAAQK,IAAI,YAAZL,gBAAgBM,KAAKC,GAAG;QAC5C,MAAM4C,MAAM;eAAI,IAAIC,IAAIpD,QAAQ8C,WAAW,CAACO,GAAG,CAAC,CAACC,KAAOpD,OAAOoD,aAAAA,KAAM,IAAIC,IAAI;SAAK,CAACC,MAAM,CACvF,CAACF,KAAOhE,aAAagE;QAEvB,IAAI,CAACH,IAAIM,MAAM,EAAE,OAAO;QACxB,MAAMxB,KAAKvC,oBAAAA,YAAaF;QACxB,MAAMkE,UAAUzB,GAAGE,UAAU,CAAC,SAASC,GAAG,CAACnC,QAAQkC,UAAU,CAACa;QAC9D,MAAMW,QAAQC,GAAG,CACfT,IAAIE,GAAG,CAAC,CAACtC,aACP2C,QAAQtB,GAAG,CAACrB,YAAYyB,GAAG,CACzB;gBACEqB,WAAW;oBAAE,CAAC7D,QAAQ+C,OAAO,CAAC,EAAEpE,WAAW+D,SAAS,CAAC;gBAAG;eACpDtC,OAAOI,QAAQ,CAACH,SAASA,OAAO,IAAI;gBAAEyD,aAAazD;YAAK,IAAI,CAAC;gBACjEsC,WAAWhE,WAAW4D,eAAe;gBAEvC;gBAAEK,OAAO;YAAK;QAIpB,OAAOO,IAAIM,MAAM;IACnB,EAAE,OAAO/B,OAAO;QACdC,QAAQD,KAAK,CAAC,wCAAwCA;QACtD,OAAO;IACT;AACF"}
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 parseCampaignTouch,\n type CampaignTouch,\n} from '@aglyn/aglyn/app-utils/campaign-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 (`campaign-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: CampaignTouch | null = parseCampaignTouch(\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","parseCampaignTouch","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,kBAAkB,QAEb,wCAAuC;AAC9C;;;;;;;;CAQC,GACD,SACEC,2BAA2BC,iBAAiB,EAC5CC,iCAAiCC,uBAAuB,EACxDC,oBAAoB,QACf,gDAA+C;AACtD,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SACEC,gCAAgC,EAChCC,qCAAqC,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as _extends } from "@swc/helpers/_/_extends";
16
16
  * limitations under the License.
17
17
  */ import { FieldValue } from "firebase-admin/firestore";
18
18
  import { EMAIL_ATTRIBUTION_MODEL, EMAIL_ATTRIBUTION_WINDOW_DAYS, EMAIL_ATTRIBUTION_WINDOW_MS, emailTouchIsInWindow } from "@aglyn/shared-util-email";
19
+ import { resolveCampaignSendRef } from "./campaign-conversion-attribution.js";
19
20
  import { readEmailCampaignTouch } from "./email-delivery-log.js";
20
21
  import { isDocumentId } from "./document-id.js";
21
22
  import firebaseAdmin from "./firebase-admin.js";
@@ -182,8 +183,19 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
182
183
  * proven to exist a moment ago, when its click wrote the touch.
183
184
  *
184
185
  * Every amount is an increment, so two orders settling at once both land.
186
+ *
187
+ * The send is found where it is — the org's `campaigns`, or the site's
188
+ * for a send the migration has not reached — and a send in neither
189
+ * place was discarded: the record above stands, and no report is
190
+ * conjured under nothing.
185
191
  */ const currency = record.currency;
186
- await hostRef.collection('campaigns').doc(touch.campaignId).collection('reports').doc(CAMPAIGN_REVENUE_REPORT_DOC).set({
192
+ const sendRef = await resolveCampaignSendRef({
193
+ hostId,
194
+ sendId: touch.campaignId,
195
+ firestore: db
196
+ });
197
+ if (!sendRef) return record;
198
+ await sendRef.collection('reports').doc(CAMPAIGN_REVENUE_REPORT_DOC).set({
187
199
  model: EMAIL_ATTRIBUTION_MODEL,
188
200
  windowDays: EMAIL_ATTRIBUTION_WINDOW_DAYS,
189
201
  byCurrency: {
@@ -261,7 +273,16 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
261
273
  * — which happens when the credit was the charge and the refund includes
262
274
  * something the credit did not. The stored pair keeps both true figures
263
275
  * and the reader clamps the net it prints.
264
- */ await hostRef.collection('campaigns').doc(campaignId).collection('reports').doc(CAMPAIGN_REVENUE_REPORT_DOC).set({
276
+ *
277
+ * The send is found where it is, as the credit found it; a send that
278
+ * has since been discarded has no rollup left to reverse, and the
279
+ * record below still takes the refund.
280
+ */ const sendRef = await resolveCampaignSendRef({
281
+ hostId,
282
+ sendId: campaignId,
283
+ firestore: db
284
+ });
285
+ await (sendRef == null ? void 0 : sendRef.collection('reports').doc(CAMPAIGN_REVENUE_REPORT_DOC).set({
265
286
  byCurrency: {
266
287
  [currency]: _extends({
267
288
  refundedCents: FieldValue.increment(amountCents)
@@ -272,7 +293,7 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
272
293
  updatedAt: FieldValue.serverTimestamp()
273
294
  }, {
274
295
  merge: true
275
- });
296
+ }));
276
297
  /*
277
298
  * Stamped on the record as well as counted in the rollup. The rollup is a
278
299
  * sum and cannot say WHICH orders came back; this is the per-order half
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/email-revenue-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 } from 'firebase-admin/firestore'\nimport {\n EMAIL_ATTRIBUTION_MODEL,\n EMAIL_ATTRIBUTION_WINDOW_DAYS,\n EMAIL_ATTRIBUTION_WINDOW_MS,\n emailTouchIsInWindow,\n} from '@aglyn/shared-util-email'\nimport { readEmailCampaignTouch } from './email-delivery-log'\nimport { isDocumentId } from './document-id'\nimport firebaseAdmin from './firebase-admin'\n\nconst defaultFirestore = () => firebaseAdmin.app().firestore()\n\n/**\n * THE COMMERCE↔EMAIL JOIN — an order, credited to the campaign that led to it.\n *\n * ## Why this is a join\n *\n * Every compared ESP attributes revenue through an integration into a store\n * it does not own: a catalog sync, an on-site tracking snippet, an identity\n * graph, and a window wide enough to absorb what the reconciliation misses.\n * Commerce here is first-party and runs on the merchant's own Stripe Connect\n * account, so the click and the order are two rows in one database keyed the\n * same way. The window is not a fudge factor here — it is the model, and\n * nothing else about the number is estimated.\n *\n * ## Three writes, and what each one is for\n *\n * - **The touch**, `emailDeliveries/{personKey}.campaignTouches[hostId]`,\n * written by the delivery webhook on a click. Owned by\n * `email-delivery-log.ts`, because it lives on the person's document and\n * the erasure path has to be able to remove it.\n * - **The attribution record**, `hosts/{hostId}/emailAttributions/{orderId}`,\n * written here when an order is credited. It is the audit trail — which\n * campaign, which click, which model, which window — and it is what the\n * refund path reads to find out which campaign to take the money back off.\n * - **The rollup**, `campaigns/{campaignId}/reports/revenue`, incremented\n * here. One document per campaign, so the report reads it whole.\n *\n * ## Why the record is a document and not a field on the order\n *\n * Three reasons, and the first is decisive. `create()` fails when the\n * document already exists, which is exact idempotency for free: webhook\n * delivery is at-least-once, and a redelivered purchase must not be able to\n * credit a campaign twice. Second, not every purchase door writes an order —\n * a booking is a sale with no order document — and a field would have had to\n * either skip those or conjure the document, and conjuring is the\n * phantom-document shape this codebase spent a sweep removing. Third, the\n * order document is read by the console list, the fulfilment path, the\n * supplier outbox and the CSV export, and none of them wants a field about\n * email.\n *\n * ## Never throws\n *\n * Same contract as `upsertHostContact`, which calls it, and for the same\n * reason: the money has already moved and the order already records it, so\n * nothing here may fail a sale. A lost attribution understates a campaign; a\n * thrown one loses a checkout.\n */\n\n/** The per-host collection of attribution records. */\nexport const EMAIL_ATTRIBUTIONS_COLLECTION = 'emailAttributions'\n\n/** The single rollup document under a campaign. */\nexport const CAMPAIGN_REVENUE_REPORT_DOC = 'revenue'\n\n/**\n * The currency an amount is recorded under when the caller does not say.\n *\n * Every checkout door in this repo — cart, buy-now, POS, draft orders,\n * reservations, subscriptions — writes `currency: 'usd'` onto the Stripe line\n * items, and no order document carries a currency field to read back. So this\n * is a statement about what the code charges rather than a guess about the\n * money. The parameter exists so a door that ever charges in something else\n * says so and lands in its own bucket, because the one thing the report may\n * never do is add two currencies together.\n */\nexport const DEFAULT_ATTRIBUTION_CURRENCY = 'usd'\n\n/** What one attribution record holds. */\nexport interface EmailAttributionRecord {\n campaignId: string\n /** When the credited click happened. */\n clickedAtMs: number\n /** When the order was placed. */\n orderedAtMs: number\n /** Minor units credited, gross — the amount the buyer was charged. */\n amountCents: number\n /** Lowercase currency code the amount is in. */\n currency: string\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/** Normalizes a currency code to the key its bucket is stored under. */\nfunction currencyKey(raw: unknown): string {\n const code = String(raw ?? '')\n .trim()\n .toLowerCase()\n // Letters only: the code becomes a MAP KEY, and a key carrying a dot would\n // be unreachable by any dotted field path a later reader wants to use.\n return /^[a-z]{3}$/.test(code) ? code : DEFAULT_ATTRIBUTION_CURRENCY\n}\n\n/** A positive integer number of minor units, or 0. */\nfunction minorUnits(raw: unknown): number {\n const value = Math.round(Number(raw))\n return Number.isFinite(value) && value > 0 ? value : 0\n}\n\n/**\n * Credits one order to the campaign whose link the buyer last clicked.\n *\n * ## What happens when there is nobody to credit\n *\n * Each case answers `null` and writes NOTHING, which is the whole design:\n *\n * - **No email on the order.** A guest checkout that never identified its\n * buyer cannot be joined to anybody's clicks. There is no fallback and\n * there deliberately is not one — the alternatives are an IP or a device\n * guess, which is the probabilistic attribution owning the checkout exists\n * to avoid.\n * - **A guest with an email but no contact record.** This is ATTRIBUTED\n * normally. The join keys on the address hash, exactly as the touch and\n * the suppression list do, so it never asks whether a contact document\n * exists — which matters, because contact creation is audience-band gated\n * and a Free org's dropped contact would otherwise silently drop the\n * revenue with it.\n * - **No touch, or a touch on another site.** Nobody clicked, so nobody is\n * credited. The touch map is keyed by host and the send path refuses\n * cross-site reach; the revenue join agrees with it.\n * - **A touch outside the window**, in either direction. See\n * {@link emailTouchIsInWindow} — a click AFTER the order is the receipt,\n * not the cause.\n *\n * None of these is counted anywhere. A miss costs no write, which is what\n * keeps the ordinary order — placed by somebody who is not on the mailing\n * list at all — at exactly one document read. What it means for the report is\n * stated on the report: the figure counts orders it could join, and is a\n * floor.\n *\n * @returns the record written, or `null` when nothing was credited.\n */\nexport async function attributeOrderToEmail(\n options: {\n hostId: string\n /** The order, booking or invoice the money came in on. */\n orderId: string\n /** The buyer as the sale recorded them, raw — normalized downstream. */\n email: unknown\n /** Gross minor units the buyer was charged. */\n amountCents: number\n /** Lowercase currency code, when the door knows one. */\n currency?: string\n /** When the order was placed. Defaults to now. */\n orderedAtMs?: number\n },\n firestore?: any,\n): Promise<EmailAttributionRecord | null> {\n try {\n const hostId = String(options.hostId ?? '')\n const orderId = String(options.orderId ?? '')\n const amountCents = minorUnits(options.amountCents)\n if (!isDocumentId(hostId) || !isDocumentId(orderId)) return null\n if (!amountCents) return null\n\n const orderedAtMs = Number(options.orderedAtMs ?? Date.now())\n const db = firestore ?? defaultFirestore()\n\n /*\n * `String()` on an `unknown`, then let `emailSuppressionKey` decide.\n *\n * The buyer's address arrives as the ORDER recorded it, which is not\n * consistently a string — the same rawness `recordContactRefund` takes\n * `email: unknown` for. The key derivation is the one place that knows\n * how an address becomes a document id, so nothing here tries to\n * pre-clean it; a value that is not an address answers `null` there and\n * the order is credited to nobody.\n */\n const rawEmail =\n typeof options.email === 'string' ? options.email : String(options.email ?? '')\n const touch = await readEmailCampaignTouch(rawEmail, hostId, db)\n if (!touch) return null\n if (!isDocumentId(touch.campaignId)) return null\n if (!emailTouchIsInWindow(touch.clickedAtMs, orderedAtMs)) return null\n\n const record: EmailAttributionRecord = {\n campaignId: touch.campaignId,\n clickedAtMs: touch.clickedAtMs,\n orderedAtMs,\n amountCents,\n currency: currencyKey(options.currency),\n model: EMAIL_ATTRIBUTION_MODEL,\n windowDays: EMAIL_ATTRIBUTION_WINDOW_DAYS,\n }\n\n const hostRef = db.collection('hosts').doc(hostId)\n /*\n * `create()`, never `set()`. It fails with ALREADY_EXISTS when this order\n * has been credited before, and that failure is the idempotency: a\n * webhook redelivery, a retried checkout completion and a replayed event\n * all land here a second time, and all three must leave the rollup where\n * they found it. The increment below is reached only when the create\n * succeeded, so the two can never disagree about whether this order was\n * counted.\n */\n try {\n await hostRef\n .collection(EMAIL_ATTRIBUTIONS_COLLECTION)\n .doc(orderId)\n .create({ ...record, createdAt: FieldValue.serverTimestamp() })\n } catch {\n return null\n }\n\n /*\n * A merge-set that CREATES, unlike the campaign counters the delivery\n * webhook writes through `updateExisting`.\n *\n * The distinction is which document is being conjured. Those counters\n * refuse to create because a merge-set against a DELETED CAMPAIGN\n * resurrects the campaign itself, as a husk holding a stats map and no\n * subject. This writes a subcollection document UNDER a campaign, so a\n * campaign that no longer exists gains an orphaned report rather than\n * coming back to life in the merchant's history — and the campaign was\n * proven to exist a moment ago, when its click wrote the touch.\n *\n * Every amount is an increment, so two orders settling at once both land.\n */\n const currency = record.currency\n await hostRef\n .collection('campaigns')\n .doc(touch.campaignId)\n .collection('reports')\n .doc(CAMPAIGN_REVENUE_REPORT_DOC)\n .set(\n {\n model: EMAIL_ATTRIBUTION_MODEL,\n windowDays: EMAIL_ATTRIBUTION_WINDOW_DAYS,\n byCurrency: {\n [currency]: {\n grossCents: FieldValue.increment(amountCents),\n orders: FieldValue.increment(1),\n },\n },\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n\n return record\n } catch (error) {\n console.error('attributeOrderToEmail failed', error)\n return null\n }\n}\n\n/**\n * Takes back revenue a campaign was credited with, when it is refunded.\n *\n * ## Recorded beside the gross, never subtracted from it\n *\n * `grossCents` is left exactly as it is and the reversal lands in\n * `refundedCents` next to it. This is the shape `contact-refund.ts` chose for\n * `ltvCents`/`refundedCents` and the orders CSV chose for\n * `amountUsd`/`refundedUsd`, and it is chosen a third time here so all three\n * answer \"what did this earn, net\" identically. Decrementing would make a\n * stored number mean one thing for rollups written before a refund and\n * another after, with nothing on the document to tell them apart — and would\n * put the question \"can it go negative\" onto storage, where the answer cannot\n * be clamped without destroying evidence. Both stored figures are monotonic\n * counters of money that really moved in one direction; the derived net is\n * clamped at the point of display and nowhere else.\n *\n * ## The currency comes from the RECORD, not from the caller\n *\n * A refund reverses a specific sale, and the bucket it comes out of has to be\n * the bucket it went into. Reading the currency back off the attribution\n * record is what guarantees that, and it is the second thing the record is\n * for.\n *\n * ## Chargebacks come through here too\n *\n * Money reversed is money reversed, whichever door it left by, so a lost\n * dispute reverses the credit the same way a refund does. `kind` exists for\n * the caller's clarity and changes nothing about the arithmetic — the same\n * choice `recordContactRefund` made one field along.\n *\n * @returns whether a reversal was recorded.\n */\nexport async function reverseEmailAttributedRevenue(\n options: {\n hostId: string\n orderId: string\n /** Minor units reversed by THIS attempt, never the order total. */\n amountCents: number\n /** True only for the write that moved the order into `refunded`. */\n closedTheOrder: boolean\n kind?: 'refund' | 'chargeback'\n },\n firestore?: any,\n): Promise<boolean> {\n try {\n const hostId = String(options.hostId ?? '')\n const orderId = String(options.orderId ?? '')\n const amountCents = minorUnits(options.amountCents)\n if (!isDocumentId(hostId) || !isDocumentId(orderId)) return false\n if (!amountCents) return false\n\n const db = firestore ?? defaultFirestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const snapshot = await hostRef\n .collection(EMAIL_ATTRIBUTIONS_COLLECTION)\n .doc(orderId)\n .get()\n // The ordinary case, and not an error: most orders were never credited to\n // a campaign, so most refunds have nothing to reverse.\n if (!snapshot.exists) return false\n\n const record = snapshot.data() ?? {}\n const campaignId = String(record.campaignId ?? '')\n if (!isDocumentId(campaignId)) return false\n const currency = currencyKey(record.currency)\n\n /*\n * NOT capped against what was credited, and that is deliberate. The\n * caller already caps each attempt against what is left on the ORDER, so\n * several partials sum to at most the order total; capping again here\n * against the attributed amount would silently discard the reversal of an\n * order refunded for more than the amount the campaign was credited with\n * — which happens when the credit was the charge and the refund includes\n * something the credit did not. The stored pair keeps both true figures\n * and the reader clamps the net it prints.\n */\n await hostRef\n .collection('campaigns')\n .doc(campaignId)\n .collection('reports')\n .doc(CAMPAIGN_REVENUE_REPORT_DOC)\n .set(\n {\n byCurrency: {\n [currency]: {\n refundedCents: FieldValue.increment(amountCents),\n ...(options.closedTheOrder\n ? { refundedOrders: FieldValue.increment(1) }\n : {}),\n },\n },\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n\n /*\n * Stamped on the record as well as counted in the rollup. The rollup is a\n * sum and cannot say WHICH orders came back; this is the per-order half\n * of the same fact, and it is what a merchant asking \"why did this\n * campaign's revenue drop\" is eventually going to need. Increments, so\n * two partials on one order both land.\n */\n await snapshot.ref\n .set(\n {\n refundedCents: FieldValue.increment(amountCents),\n lastRefundAtMs: Date.now(),\n ...(options.kind === 'chargeback' ? { chargedBack: true } : {}),\n ...(options.closedTheOrder ? { fullyRefunded: true } : {}),\n },\n { merge: true },\n )\n .catch(() => undefined)\n\n return true\n } catch (error) {\n console.error('reverseEmailAttributedRevenue failed', error)\n return false\n }\n}\n\n/** The window, re-exported so a caller needs one import for the whole join. */\nexport { EMAIL_ATTRIBUTION_WINDOW_MS }\n"],"names":["FieldValue","EMAIL_ATTRIBUTION_MODEL","EMAIL_ATTRIBUTION_WINDOW_DAYS","EMAIL_ATTRIBUTION_WINDOW_MS","emailTouchIsInWindow","readEmailCampaignTouch","isDocumentId","firebaseAdmin","defaultFirestore","app","firestore","EMAIL_ATTRIBUTIONS_COLLECTION","CAMPAIGN_REVENUE_REPORT_DOC","DEFAULT_ATTRIBUTION_CURRENCY","currencyKey","raw","code","String","trim","toLowerCase","test","minorUnits","value","Math","round","Number","isFinite","attributeOrderToEmail","options","hostId","orderId","amountCents","orderedAtMs","Date","now","db","rawEmail","email","touch","campaignId","clickedAtMs","record","currency","model","windowDays","hostRef","collection","doc","create","createdAt","serverTimestamp","set","byCurrency","grossCents","increment","orders","updatedAt","merge","error","console","reverseEmailAttributedRevenue","snapshot","get","exists","data","refundedCents","closedTheOrder","refundedOrders","ref","lastRefundAtMs","kind","chargedBack","fullyRefunded","catch","undefined"],"mappings":";AAAA;;;;;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AAS,CAACvB;mBAChCH,QAAQsC,cAAc,GACtB;oBAAEC,gBAAgBnE,WAAWsD,SAAS,CAAC;gBAAG,IAC1C,CAAC;YAET;YACAE,WAAWxD,WAAWkD,eAAe;QACvC,GACA;YAAEO,OAAO;QAAK;QAGlB;;;;;;KAMC,GACD,MAAMI,SAASO,GAAG,CACfjB,GAAG,CACF;YACEc,eAAejE,WAAWsD,SAAS,CAACvB;YACpCsC,gBAAgBpC,KAAKC,GAAG;WACpBN,QAAQ0C,IAAI,KAAK,eAAe;YAAEC,aAAa;QAAK,IAAI,CAAC,GACzD3C,QAAQsC,cAAc,GAAG;YAAEM,eAAe;QAAK,IAAI,CAAC,IAE1D;YAAEf,OAAO;QAAK,GAEfgB,KAAK,CAAC,IAAMC;QAEf,OAAO;IACT,EAAE,OAAOhB,OAAO;QACdC,QAAQD,KAAK,CAAC,wCAAwCA;QACtD,OAAO;IACT;AACF;AAEA,6EAA6E,GAC7E,SAASvD,2BAA2B,GAAE"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/email-revenue-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 } from 'firebase-admin/firestore'\nimport {\n EMAIL_ATTRIBUTION_MODEL,\n EMAIL_ATTRIBUTION_WINDOW_DAYS,\n EMAIL_ATTRIBUTION_WINDOW_MS,\n emailTouchIsInWindow,\n} from '@aglyn/shared-util-email'\nimport { resolveCampaignSendRef } from './campaign-conversion-attribution'\nimport { readEmailCampaignTouch } from './email-delivery-log'\nimport { isDocumentId } from './document-id'\nimport firebaseAdmin from './firebase-admin'\n\nconst defaultFirestore = () => firebaseAdmin.app().firestore()\n\n/**\n * THE COMMERCE↔EMAIL JOIN — an order, credited to the campaign that led to it.\n *\n * ## Why this is a join\n *\n * Every compared ESP attributes revenue through an integration into a store\n * it does not own: a catalog sync, an on-site tracking snippet, an identity\n * graph, and a window wide enough to absorb what the reconciliation misses.\n * Commerce here is first-party and runs on the merchant's own Stripe Connect\n * account, so the click and the order are two rows in one database keyed the\n * same way. The window is not a fudge factor here — it is the model, and\n * nothing else about the number is estimated.\n *\n * ## Three writes, and what each one is for\n *\n * - **The touch**, `emailDeliveries/{personKey}.campaignTouches[hostId]`,\n * written by the delivery webhook on a click. Owned by\n * `email-delivery-log.ts`, because it lives on the person's document and\n * the erasure path has to be able to remove it.\n * - **The attribution record**, `hosts/{hostId}/emailAttributions/{orderId}`,\n * written here when an order is credited. It is the audit trail — which\n * campaign, which click, which model, which window — and it is what the\n * refund path reads to find out which campaign to take the money back off.\n * - **The rollup**, `campaigns/{campaignId}/reports/revenue`, incremented\n * here. One document per campaign, so the report reads it whole.\n *\n * ## Why the record is a document and not a field on the order\n *\n * Three reasons, and the first is decisive. `create()` fails when the\n * document already exists, which is exact idempotency for free: webhook\n * delivery is at-least-once, and a redelivered purchase must not be able to\n * credit a campaign twice. Second, not every purchase door writes an order —\n * a booking is a sale with no order document — and a field would have had to\n * either skip those or conjure the document, and conjuring is the\n * phantom-document shape this codebase spent a sweep removing. Third, the\n * order document is read by the console list, the fulfilment path, the\n * supplier outbox and the CSV export, and none of them wants a field about\n * email.\n *\n * ## Never throws\n *\n * Same contract as `upsertHostContact`, which calls it, and for the same\n * reason: the money has already moved and the order already records it, so\n * nothing here may fail a sale. A lost attribution understates a campaign; a\n * thrown one loses a checkout.\n */\n\n/** The per-host collection of attribution records. */\nexport const EMAIL_ATTRIBUTIONS_COLLECTION = 'emailAttributions'\n\n/** The single rollup document under a campaign. */\nexport const CAMPAIGN_REVENUE_REPORT_DOC = 'revenue'\n\n/**\n * The currency an amount is recorded under when the caller does not say.\n *\n * Every checkout door in this repo — cart, buy-now, POS, draft orders,\n * reservations, subscriptions — writes `currency: 'usd'` onto the Stripe line\n * items, and no order document carries a currency field to read back. So this\n * is a statement about what the code charges rather than a guess about the\n * money. The parameter exists so a door that ever charges in something else\n * says so and lands in its own bucket, because the one thing the report may\n * never do is add two currencies together.\n */\nexport const DEFAULT_ATTRIBUTION_CURRENCY = 'usd'\n\n/** What one attribution record holds. */\nexport interface EmailAttributionRecord {\n campaignId: string\n /** When the credited click happened. */\n clickedAtMs: number\n /** When the order was placed. */\n orderedAtMs: number\n /** Minor units credited, gross — the amount the buyer was charged. */\n amountCents: number\n /** Lowercase currency code the amount is in. */\n currency: string\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/** Normalizes a currency code to the key its bucket is stored under. */\nfunction currencyKey(raw: unknown): string {\n const code = String(raw ?? '')\n .trim()\n .toLowerCase()\n // Letters only: the code becomes a MAP KEY, and a key carrying a dot would\n // be unreachable by any dotted field path a later reader wants to use.\n return /^[a-z]{3}$/.test(code) ? code : DEFAULT_ATTRIBUTION_CURRENCY\n}\n\n/** A positive integer number of minor units, or 0. */\nfunction minorUnits(raw: unknown): number {\n const value = Math.round(Number(raw))\n return Number.isFinite(value) && value > 0 ? value : 0\n}\n\n/**\n * Credits one order to the campaign whose link the buyer last clicked.\n *\n * ## What happens when there is nobody to credit\n *\n * Each case answers `null` and writes NOTHING, which is the whole design:\n *\n * - **No email on the order.** A guest checkout that never identified its\n * buyer cannot be joined to anybody's clicks. There is no fallback and\n * there deliberately is not one — the alternatives are an IP or a device\n * guess, which is the probabilistic attribution owning the checkout exists\n * to avoid.\n * - **A guest with an email but no contact record.** This is ATTRIBUTED\n * normally. The join keys on the address hash, exactly as the touch and\n * the suppression list do, so it never asks whether a contact document\n * exists — which matters, because contact creation is audience-band gated\n * and a Free org's dropped contact would otherwise silently drop the\n * revenue with it.\n * - **No touch, or a touch on another site.** Nobody clicked, so nobody is\n * credited. The touch map is keyed by host and the send path refuses\n * cross-site reach; the revenue join agrees with it.\n * - **A touch outside the window**, in either direction. See\n * {@link emailTouchIsInWindow} — a click AFTER the order is the receipt,\n * not the cause.\n *\n * None of these is counted anywhere. A miss costs no write, which is what\n * keeps the ordinary order — placed by somebody who is not on the mailing\n * list at all — at exactly one document read. What it means for the report is\n * stated on the report: the figure counts orders it could join, and is a\n * floor.\n *\n * @returns the record written, or `null` when nothing was credited.\n */\nexport async function attributeOrderToEmail(\n options: {\n hostId: string\n /** The order, booking or invoice the money came in on. */\n orderId: string\n /** The buyer as the sale recorded them, raw — normalized downstream. */\n email: unknown\n /** Gross minor units the buyer was charged. */\n amountCents: number\n /** Lowercase currency code, when the door knows one. */\n currency?: string\n /** When the order was placed. Defaults to now. */\n orderedAtMs?: number\n },\n firestore?: any,\n): Promise<EmailAttributionRecord | null> {\n try {\n const hostId = String(options.hostId ?? '')\n const orderId = String(options.orderId ?? '')\n const amountCents = minorUnits(options.amountCents)\n if (!isDocumentId(hostId) || !isDocumentId(orderId)) return null\n if (!amountCents) return null\n\n const orderedAtMs = Number(options.orderedAtMs ?? Date.now())\n const db = firestore ?? defaultFirestore()\n\n /*\n * `String()` on an `unknown`, then let `emailSuppressionKey` decide.\n *\n * The buyer's address arrives as the ORDER recorded it, which is not\n * consistently a string — the same rawness `recordContactRefund` takes\n * `email: unknown` for. The key derivation is the one place that knows\n * how an address becomes a document id, so nothing here tries to\n * pre-clean it; a value that is not an address answers `null` there and\n * the order is credited to nobody.\n */\n const rawEmail =\n typeof options.email === 'string' ? options.email : String(options.email ?? '')\n const touch = await readEmailCampaignTouch(rawEmail, hostId, db)\n if (!touch) return null\n if (!isDocumentId(touch.campaignId)) return null\n if (!emailTouchIsInWindow(touch.clickedAtMs, orderedAtMs)) return null\n\n const record: EmailAttributionRecord = {\n campaignId: touch.campaignId,\n clickedAtMs: touch.clickedAtMs,\n orderedAtMs,\n amountCents,\n currency: currencyKey(options.currency),\n model: EMAIL_ATTRIBUTION_MODEL,\n windowDays: EMAIL_ATTRIBUTION_WINDOW_DAYS,\n }\n\n const hostRef = db.collection('hosts').doc(hostId)\n /*\n * `create()`, never `set()`. It fails with ALREADY_EXISTS when this order\n * has been credited before, and that failure is the idempotency: a\n * webhook redelivery, a retried checkout completion and a replayed event\n * all land here a second time, and all three must leave the rollup where\n * they found it. The increment below is reached only when the create\n * succeeded, so the two can never disagree about whether this order was\n * counted.\n */\n try {\n await hostRef\n .collection(EMAIL_ATTRIBUTIONS_COLLECTION)\n .doc(orderId)\n .create({ ...record, createdAt: FieldValue.serverTimestamp() })\n } catch {\n return null\n }\n\n /*\n * A merge-set that CREATES, unlike the campaign counters the delivery\n * webhook writes through `updateExisting`.\n *\n * The distinction is which document is being conjured. Those counters\n * refuse to create because a merge-set against a DELETED CAMPAIGN\n * resurrects the campaign itself, as a husk holding a stats map and no\n * subject. This writes a subcollection document UNDER a campaign, so a\n * campaign that no longer exists gains an orphaned report rather than\n * coming back to life in the merchant's history — and the campaign was\n * proven to exist a moment ago, when its click wrote the touch.\n *\n * Every amount is an increment, so two orders settling at once both land.\n *\n * The send is found where it is — the org's `campaigns`, or the site's\n * for a send the migration has not reached — and a send in neither\n * place was discarded: the record above stands, and no report is\n * conjured under nothing.\n */\n const currency = record.currency\n const sendRef = await resolveCampaignSendRef({ hostId, sendId: touch.campaignId, firestore: db })\n if (!sendRef) return record\n await sendRef\n .collection('reports')\n .doc(CAMPAIGN_REVENUE_REPORT_DOC)\n .set(\n {\n model: EMAIL_ATTRIBUTION_MODEL,\n windowDays: EMAIL_ATTRIBUTION_WINDOW_DAYS,\n byCurrency: {\n [currency]: {\n grossCents: FieldValue.increment(amountCents),\n orders: FieldValue.increment(1),\n },\n },\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n\n return record\n } catch (error) {\n console.error('attributeOrderToEmail failed', error)\n return null\n }\n}\n\n/**\n * Takes back revenue a campaign was credited with, when it is refunded.\n *\n * ## Recorded beside the gross, never subtracted from it\n *\n * `grossCents` is left exactly as it is and the reversal lands in\n * `refundedCents` next to it. This is the shape `contact-refund.ts` chose for\n * `ltvCents`/`refundedCents` and the orders CSV chose for\n * `amountUsd`/`refundedUsd`, and it is chosen a third time here so all three\n * answer \"what did this earn, net\" identically. Decrementing would make a\n * stored number mean one thing for rollups written before a refund and\n * another after, with nothing on the document to tell them apart — and would\n * put the question \"can it go negative\" onto storage, where the answer cannot\n * be clamped without destroying evidence. Both stored figures are monotonic\n * counters of money that really moved in one direction; the derived net is\n * clamped at the point of display and nowhere else.\n *\n * ## The currency comes from the RECORD, not from the caller\n *\n * A refund reverses a specific sale, and the bucket it comes out of has to be\n * the bucket it went into. Reading the currency back off the attribution\n * record is what guarantees that, and it is the second thing the record is\n * for.\n *\n * ## Chargebacks come through here too\n *\n * Money reversed is money reversed, whichever door it left by, so a lost\n * dispute reverses the credit the same way a refund does. `kind` exists for\n * the caller's clarity and changes nothing about the arithmetic — the same\n * choice `recordContactRefund` made one field along.\n *\n * @returns whether a reversal was recorded.\n */\nexport async function reverseEmailAttributedRevenue(\n options: {\n hostId: string\n orderId: string\n /** Minor units reversed by THIS attempt, never the order total. */\n amountCents: number\n /** True only for the write that moved the order into `refunded`. */\n closedTheOrder: boolean\n kind?: 'refund' | 'chargeback'\n },\n firestore?: any,\n): Promise<boolean> {\n try {\n const hostId = String(options.hostId ?? '')\n const orderId = String(options.orderId ?? '')\n const amountCents = minorUnits(options.amountCents)\n if (!isDocumentId(hostId) || !isDocumentId(orderId)) return false\n if (!amountCents) return false\n\n const db = firestore ?? defaultFirestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const snapshot = await hostRef\n .collection(EMAIL_ATTRIBUTIONS_COLLECTION)\n .doc(orderId)\n .get()\n // The ordinary case, and not an error: most orders were never credited to\n // a campaign, so most refunds have nothing to reverse.\n if (!snapshot.exists) return false\n\n const record = snapshot.data() ?? {}\n const campaignId = String(record.campaignId ?? '')\n if (!isDocumentId(campaignId)) return false\n const currency = currencyKey(record.currency)\n\n /*\n * NOT capped against what was credited, and that is deliberate. The\n * caller already caps each attempt against what is left on the ORDER, so\n * several partials sum to at most the order total; capping again here\n * against the attributed amount would silently discard the reversal of an\n * order refunded for more than the amount the campaign was credited with\n * — which happens when the credit was the charge and the refund includes\n * something the credit did not. The stored pair keeps both true figures\n * and the reader clamps the net it prints.\n *\n * The send is found where it is, as the credit found it; a send that\n * has since been discarded has no rollup left to reverse, and the\n * record below still takes the refund.\n */\n const sendRef = await resolveCampaignSendRef({ hostId, sendId: campaignId, firestore: db })\n await sendRef\n ?.collection('reports')\n .doc(CAMPAIGN_REVENUE_REPORT_DOC)\n .set(\n {\n byCurrency: {\n [currency]: {\n refundedCents: FieldValue.increment(amountCents),\n ...(options.closedTheOrder\n ? { refundedOrders: FieldValue.increment(1) }\n : {}),\n },\n },\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n\n /*\n * Stamped on the record as well as counted in the rollup. The rollup is a\n * sum and cannot say WHICH orders came back; this is the per-order half\n * of the same fact, and it is what a merchant asking \"why did this\n * campaign's revenue drop\" is eventually going to need. Increments, so\n * two partials on one order both land.\n */\n await snapshot.ref\n .set(\n {\n refundedCents: FieldValue.increment(amountCents),\n lastRefundAtMs: Date.now(),\n ...(options.kind === 'chargeback' ? { chargedBack: true } : {}),\n ...(options.closedTheOrder ? { fullyRefunded: true } : {}),\n },\n { merge: true },\n )\n .catch(() => undefined)\n\n return true\n } catch (error) {\n console.error('reverseEmailAttributedRevenue failed', error)\n return false\n }\n}\n\n/** The window, re-exported so a caller needs one import for the whole join. */\nexport { EMAIL_ATTRIBUTION_WINDOW_MS }\n"],"names":["FieldValue","EMAIL_ATTRIBUTION_MODEL","EMAIL_ATTRIBUTION_WINDOW_DAYS","EMAIL_ATTRIBUTION_WINDOW_MS","emailTouchIsInWindow","resolveCampaignSendRef","readEmailCampaignTouch","isDocumentId","firebaseAdmin","defaultFirestore","app","firestore","EMAIL_ATTRIBUTIONS_COLLECTION","CAMPAIGN_REVENUE_REPORT_DOC","DEFAULT_ATTRIBUTION_CURRENCY","currencyKey","raw","code","String","trim","toLowerCase","test","minorUnits","value","Math","round","Number","isFinite","attributeOrderToEmail","options","hostId","orderId","amountCents","orderedAtMs","Date","now","db","rawEmail","email","touch","campaignId","clickedAtMs","record","currency","model","windowDays","hostRef","collection","doc","create","createdAt","serverTimestamp","sendRef","sendId","set","byCurrency","grossCents","increment","orders","updatedAt","merge","error","console","reverseEmailAttributedRevenue","snapshot","get","exists","data","refundedCents","closedTheOrder","refundedOrders","ref","lastRefundAtMs","kind","chargedBack","fullyRefunded","catch","undefined"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,2BAA0B;AACrD,SACEC,uBAAuB,EACvBC,6BAA6B,EAC7BC,2BAA2B,EAC3BC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,uCAAmC;AAC1E,SAASC,sBAAsB,QAAQ,0BAAsB;AAC7D,SAASC,YAAY,QAAQ,mBAAe;AAC5C,OAAOC,mBAAmB,sBAAkB;AAE5C,MAAMC,mBAAmB,IAAMD,cAAcE,GAAG,GAAGC,SAAS;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6CC,GAED,oDAAoD,GACpD,OAAO,MAAMC,gCAAgC,oBAAmB;AAEhE,iDAAiD,GACjD,OAAO,MAAMC,8BAA8B,UAAS;AAEpD;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,+BAA+B,MAAK;AAmBjD,sEAAsE,GACtE,SAASC,YAAYC,GAAY;IAC/B,MAAMC,OAAOC,OAAOF,cAAAA,MAAO,IACxBG,IAAI,GACJC,WAAW;IACd,2EAA2E;IAC3E,uEAAuE;IACvE,OAAO,aAAaC,IAAI,CAACJ,QAAQA,OAAOH;AAC1C;AAEA,oDAAoD,GACpD,SAASQ,W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AC7E,SAAS1D,2BAA2B,GAAE"}
@@ -28,6 +28,7 @@ import { removeOrgMember } from "./organizations.js";
28
28
  import { runPluginUserErasers } from "@aglyn/aglyn/plugin-manager/plugin-user-erasure";
29
29
  import { runPluginOrgErasers } from "@aglyn/aglyn/plugin-manager/plugin-org-erasure";
30
30
  import { isBillingSubscription } from "@aglyn/aglyn/server";
31
+ import { listPluginOrgCollections } from "@aglyn/aglyn/plugin-manager/plugin-host-collections";
31
32
  import { readOrgBilling } from "./org-billing.js";
32
33
  import { disposeHostSendingDomain, readSendingDomainTeardownByLabel } from "./sending-domain-debt.js";
33
34
  /** The reversible hold before a requested erasure is executed (AGL-485). */ export const ERASURE_HOLD_MS = 7 * 24 * 60 * 60 * 1000;
@@ -120,6 +121,42 @@ import { disposeHostSendingDomain, readSendingDomainTeardownByLabel } from "./se
120
121
  return 0;
121
122
  }
122
123
  }
124
+ /**
125
+ * Destroy the org documents that belong to the site (AGL-3273).
126
+ *
127
+ * Some plugin storage is the organization's and names the site each document
128
+ * belongs to — Marketing's email sends, `orgs/{orgId}/campaigns`, each naming
129
+ * the site it was sent as. The `recursiveDelete(hosts/{hostId})` below does
130
+ * not reach them, and they are still the site's: a send's sender, unsubscribe
131
+ * page and the consent it relied on were that site's, and a send addressed to
132
+ * a hand-typed list carries those addresses.
133
+ *
134
+ * Which collections, and which field names the site, is each plugin's own
135
+ * declaration (`orgCollections` in `plugins.config.json`, read through
136
+ * `listPluginOrgCollections`): a declaration with a `siteField` is a
137
+ * collection whose documents belong to one site. One without — a campaign
138
+ * container, placed on sites rather than owned by one — is left alone. Each
139
+ * document goes with its subcollections, which is why this is a recursive
140
+ * delete per document.
141
+ *
142
+ * Best-effort, like every other trailing cleanup in `eraseHost`, and per
143
+ * collection, so one failed query leaves the others' cleanup standing.
144
+ */ async function eraseHostOwnedOrgDocuments(orgId, hostId) {
145
+ if (!orgId || !hostId) return 0;
146
+ const firestore = firebaseAdmin.app().firestore();
147
+ let erased = 0;
148
+ for (const declared of listPluginOrgCollections()){
149
+ if (!declared.siteField) continue;
150
+ try {
151
+ const rows = await firestore.collection('orgs').doc(orgId).collection(declared.name).where(declared.siteField, '==', hostId).get();
152
+ for (const doc of rows.docs)await firestore.recursiveDelete(doc.ref);
153
+ erased += rows.size;
154
+ } catch (error) {
155
+ console.error(`eraseHost: ${declared.name} cleanup failed for ${hostId}`, error);
156
+ }
157
+ }
158
+ return erased;
159
+ }
123
160
  export async function eraseHost(hostId, options = {}) {
124
161
  var _hostSnapshot_get;
125
162
  const firestore = firebaseAdmin.app().firestore();
@@ -191,6 +228,7 @@ export async function eraseHost(hostId, options = {}) {
191
228
  // Drop every member's reverse-index row for this host (AGL-844); the
192
229
  // members still exist here (recursiveDelete of the org, if any, is later).
193
230
  await deleteHostProjectionForAllMembers(orgId, hostId).catch(()=>undefined);
231
+ await eraseHostOwnedOrgDocuments(orgId, hostId);
194
232
  }
195
233
  // The host document tree (screens/layouts/versions/counters/products/…).
196
234
  await firestore.recursiveDelete(hostRef);