@aglyn/plugins-marketing 1.0.0-beta.222 → 1.0.0-beta.223
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 +15 -15
- package/src/lib/components/campaign-detail-card.js +17 -3
- package/src/lib/components/campaign-detail-card.js.map +1 -1
- package/src/lib/components/campaign-edit-drawer.d.ts +6 -0
- package/src/lib/components/campaign-edit-drawer.js +13 -2
- package/src/lib/components/campaign-edit-drawer.js.map +1 -1
- package/src/lib/components/campaign-queries.d.ts +5 -0
- package/src/lib/components/campaign-queries.js +7 -0
- package/src/lib/components/campaign-queries.js.map +1 -1
- package/src/lib/components/campaign-reach-sections.d.ts +28 -0
- package/src/lib/components/campaign-reach-sections.js +95 -4
- package/src/lib/components/campaign-reach-sections.js.map +1 -1
- package/src/lib/components/conversion-attribution.component.d.ts +18 -0
- package/src/lib/components/conversion-attribution.component.js +177 -39
- package/src/lib/components/conversion-attribution.component.js.map +1 -1
- package/src/lib/components/record-attribution-widget.d.ts +5 -0
- package/src/lib/components/record-attribution-widget.js +6 -3
- package/src/lib/components/record-attribution-widget.js.map +1 -1
- package/src/lib/components/site-runtime.d.ts +5 -0
- package/src/lib/components/site-runtime.js +101 -2
- package/src/lib/components/site-runtime.js.map +1 -1
- package/src/lib/declarations.server.js +17 -1
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/model/campaign-container.d.ts +28 -0
- package/src/lib/model/campaign-container.js +34 -0
- package/src/lib/model/campaign-container.js.map +1 -1
- package/src/lib/model/campaign-conversions.d.ts +47 -3
- package/src/lib/model/campaign-conversions.js +49 -4
- package/src/lib/model/campaign-conversions.js.map +1 -1
- package/src/lib/model/campaign-visits.d.ts +74 -0
- package/src/lib/model/campaign-visits.js +65 -0
- package/src/lib/model/campaign-visits.js.map +1 -0
- package/src/lib/server/campaign-conversion-attribution.d.ts +34 -3
- package/src/lib/server/campaign-conversion-attribution.js +126 -24
- package/src/lib/server/campaign-conversion-attribution.js.map +1 -1
- package/src/lib/server/campaign-touch-targets.d.ts +61 -0
- package/src/lib/server/campaign-touch-targets.js +162 -0
- package/src/lib/server/campaign-touch-targets.js.map +1 -0
- package/src/lib/server/campaign-visit-beacon.d.ts +44 -0
- package/src/lib/server/campaign-visit-beacon.js +125 -0
- package/src/lib/server/campaign-visit-beacon.js.map +1 -0
- package/src/lib/server/conversion-creditor.js +109 -2
- package/src/lib/server/conversion-creditor.js.map +1 -1
- package/src/lib/server/email-events.js +24 -25
- package/src/lib/server/email-events.js.map +1 -1
- package/src/lib/server/site-page-enricher.js +18 -2
- package/src/lib/server/site-page-enricher.js.map +1 -1
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ /**
|
|
17
|
+
* WHO A CAMPAIGN REACHED ON THE SITE (AGL-3461) — first visits and views of
|
|
18
|
+
* the pages filed under it.
|
|
19
|
+
*
|
|
20
|
+
* ## One document per campaign, keyed by the campaign's id
|
|
21
|
+
*
|
|
22
|
+
* `orgs/{orgId}/campaignVisitReports/{campaignId}`, beside the sequence
|
|
23
|
+
* rollup and on the same footing: counts, never a person, written only on the
|
|
24
|
+
* Admin SDK by the site collector's `campaignVisit` beacon, readable by
|
|
25
|
+
* whoever may open the campaign. Keyed by the campaign DOCUMENT, so the
|
|
26
|
+
* collection is bounded by the campaigns that exist — never by a label or a
|
|
27
|
+
* path a visitor's URL could mint.
|
|
28
|
+
*
|
|
29
|
+
* ## What each figure counts
|
|
30
|
+
*
|
|
31
|
+
* - **Page views** — views of the pages filed under the campaign, one per
|
|
32
|
+
* pageview, whoever the visitor is. It needs nothing from the visitor's
|
|
33
|
+
* device, so every view counts.
|
|
34
|
+
* - **First visits** — visitors whose first campaign touch in the
|
|
35
|
+
* attribution window was this campaign: a page filed under it, or a link
|
|
36
|
+
* carrying a `utm_campaign` label it declares. The device answers from the
|
|
37
|
+
* touch it already remembers (`claimFirstCampaignTouch` in
|
|
38
|
+
* `utm-touch.ts`): one held from the last seven days means this visit is
|
|
39
|
+
* not a first. A visitor whose consent posture keeps nothing on their
|
|
40
|
+
* device cannot be told from the next one and is not counted at all, so
|
|
41
|
+
* the figure is a floor, and the page says so.
|
|
42
|
+
*
|
|
43
|
+
* Both are also kept per month, under `byMonth`, so a campaign with dates can
|
|
44
|
+
* be read for its own window. Twelve keys a year is the bound.
|
|
45
|
+
*/ /** The org collection the rollups live in. */ export const CAMPAIGN_VISIT_REPORTS_COLLECTION = 'campaignVisitReports';
|
|
46
|
+
function count(raw) {
|
|
47
|
+
const value = Math.floor(Number(raw != null ? raw : 0));
|
|
48
|
+
return Number.isFinite(value) && value > 0 ? value : 0;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The rollup as the page reads it. `since` is the earliest month on record,
|
|
52
|
+
* so the figures say how far back they reach: they start when counting
|
|
53
|
+
* started, not when the campaign did.
|
|
54
|
+
*/ export function campaignVisitsReport(rollup) {
|
|
55
|
+
var _ref, _months_;
|
|
56
|
+
const months = Object.keys((_ref = rollup == null ? void 0 : rollup.byMonth) != null ? _ref : {}).filter((month)=>/^\d{4}-\d{2}$/.test(month)).sort();
|
|
57
|
+
return {
|
|
58
|
+
recorded: Boolean(rollup),
|
|
59
|
+
views: count(rollup == null ? void 0 : rollup.views),
|
|
60
|
+
firstVisits: count(rollup == null ? void 0 : rollup.firstVisits),
|
|
61
|
+
since: (_months_ = months[0]) != null ? _months_ : ''
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
//# sourceMappingURL=campaign-visits.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/model/campaign-visits.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * WHO A CAMPAIGN REACHED ON THE SITE (AGL-3461) — first visits and views of\n * the pages filed under it.\n *\n * ## One document per campaign, keyed by the campaign's id\n *\n * `orgs/{orgId}/campaignVisitReports/{campaignId}`, beside the sequence\n * rollup and on the same footing: counts, never a person, written only on the\n * Admin SDK by the site collector's `campaignVisit` beacon, readable by\n * whoever may open the campaign. Keyed by the campaign DOCUMENT, so the\n * collection is bounded by the campaigns that exist — never by a label or a\n * path a visitor's URL could mint.\n *\n * ## What each figure counts\n *\n * - **Page views** — views of the pages filed under the campaign, one per\n * pageview, whoever the visitor is. It needs nothing from the visitor's\n * device, so every view counts.\n * - **First visits** — visitors whose first campaign touch in the\n * attribution window was this campaign: a page filed under it, or a link\n * carrying a `utm_campaign` label it declares. The device answers from the\n * touch it already remembers (`claimFirstCampaignTouch` in\n * `utm-touch.ts`): one held from the last seven days means this visit is\n * not a first. A visitor whose consent posture keeps nothing on their\n * device cannot be told from the next one and is not counted at all, so\n * the figure is a floor, and the page says so.\n *\n * Both are also kept per month, under `byMonth`, so a campaign with dates can\n * be read for its own window. Twelve keys a year is the bound.\n */\n\n/** The org collection the rollups live in. */\nexport const CAMPAIGN_VISIT_REPORTS_COLLECTION = 'campaignVisitReports'\n\n/** One month's figures, under `byMonth['YYYY-MM']`. */\nexport interface CampaignVisitMonth {\n views?: number\n firstVisits?: number\n}\n\n/** The stored shape of `orgs/{orgId}/campaignVisitReports/{campaignId}`. */\nexport interface CampaignVisitRollup {\n views?: number\n firstVisits?: number\n byMonth?: Record<string, CampaignVisitMonth>\n}\n\n/** What the campaign's page draws. */\nexport interface CampaignVisitsReport {\n /** Whether anything has been counted at all. */\n recorded: boolean\n views: number\n firstVisits: number\n /** The first month anything was counted, `YYYY-MM`, or `''`. */\n since: string\n}\n\nfunction count(raw: unknown): number {\n const value = Math.floor(Number(raw ?? 0))\n return Number.isFinite(value) && value > 0 ? value : 0\n}\n\n/**\n * The rollup as the page reads it. `since` is the earliest month on record,\n * so the figures say how far back they reach: they start when counting\n * started, not when the campaign did.\n */\nexport function campaignVisitsReport(\n rollup: CampaignVisitRollup | null | undefined,\n): CampaignVisitsReport {\n const months = Object.keys(rollup?.byMonth ?? {})\n .filter((month) => /^\\d{4}-\\d{2}$/.test(month))\n .sort()\n return {\n recorded: Boolean(rollup),\n views: count(rollup?.views),\n firstVisits: count(rollup?.firstVisits),\n since: months[0] ?? '',\n }\n}\n"],"names":["CAMPAIGN_VISIT_REPORTS_COLLECTION","count","raw","value","Math","floor","Number","isFinite","campaignVisitsReport","rollup","months","Object","keys","byMonth","filter","month","test","sort","recorded","Boolean","views","firstVisits","since"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BC,GAED,4CAA4C,GAC5C,OAAO,MAAMA,oCAAoC,uBAAsB;AAyBvE,SAASC,MAAMC,GAAY;IACzB,MAAMC,QAAQC,KAAKC,KAAK,CAACC,OAAOJ,cAAAA,MAAO;IACvC,OAAOI,OAAOC,QAAQ,CAACJ,UAAUA,QAAQ,IAAIA,QAAQ;AACvD;AAEA;;;;CAIC,GACD,OAAO,SAASK,qBACdC,MAA8C;cASrCC;IAPT,MAAMA,SAASC,OAAOC,IAAI,SAACH,0BAAAA,OAAQI,OAAO,mBAAI,CAAC,GAC5CC,MAAM,CAAC,CAACC,QAAU,gBAAgBC,IAAI,CAACD,QACvCE,IAAI;IACP,OAAO;QACLC,UAAUC,QAAQV;QAClBW,OAAOnB,MAAMQ,0BAAAA,OAAQW,KAAK;QAC1BC,aAAapB,MAAMQ,0BAAAA,OAAQY,WAAW;QACtCC,KAAK,GAAEZ,WAAAA,MAAM,CAAC,EAAE,YAATA,WAAa;IACtB;AACF"}
|
|
@@ -55,6 +55,17 @@ import { CAMPAIGN_ATTRIBUTIONS_COLLECTION, eraseCampaignAttributionsForPersonKey
|
|
|
55
55
|
* produces a figure nobody can check. One outcome, one campaign, and a rule
|
|
56
56
|
* stated on the record.
|
|
57
57
|
*
|
|
58
|
+
* ## And a page filed under a campaign (AGL-3461)
|
|
59
|
+
*
|
|
60
|
+
* A third touch needs no label and no click: the visitor viewed a page the
|
|
61
|
+
* merchant filed under a campaign. The device carries it beside the labels
|
|
62
|
+
* (`utm-touch.ts`), the server credits it only while the campaign exists and
|
|
63
|
+
* the page is still filed under it (`campaign-touch-targets.ts`), and it
|
|
64
|
+
* competes with the winning click under {@link pickCampaignTouch}. A label a
|
|
65
|
+
* campaign declares as its own (`utmCampaigns` on the container) names that
|
|
66
|
+
* campaign the same way. Both are recorded with the CONTAINER's id as
|
|
67
|
+
* `campaignId`, under the `last-touch` model.
|
|
68
|
+
*
|
|
58
69
|
* ## No campaign touch means NO RECORD
|
|
59
70
|
*
|
|
60
71
|
* Direct traffic writes nothing at all, and there is deliberately no fallback
|
|
@@ -110,16 +121,21 @@ export type CampaignConversionKind = 'form' | 'lead' | 'contact' | 'booking';
|
|
|
110
121
|
* every other booking, and nothing in this join has to know what a
|
|
111
122
|
* sequence is.
|
|
112
123
|
*/
|
|
113
|
-
export type CampaignTouchChannel = 'email' | 'web' | 'sequence';
|
|
114
|
-
/** The touch a conversion is credited to, once
|
|
124
|
+
export type CampaignTouchChannel = 'email' | 'web' | 'sequence' | 'page';
|
|
125
|
+
/** The touch a conversion is credited to, once every channel has been asked. */
|
|
115
126
|
export interface ResolvedCampaignTouch {
|
|
116
127
|
channel: CampaignTouchChannel;
|
|
117
128
|
/**
|
|
118
129
|
* The campaign document, when the touch was a click on our own mail — or
|
|
119
130
|
* the campaign CONTAINER (`emailCampaigns/{id}`) a sequence is in, for a
|
|
120
|
-
* sequence touch
|
|
131
|
+
* sequence touch, the page was filed under, for a page touch, or that
|
|
132
|
+
* declares the label, for a web touch whose label one does (AGL-3461).
|
|
121
133
|
*/
|
|
122
134
|
campaignId?: string;
|
|
135
|
+
/** The screen the visitor viewed, for a `page` touch. */
|
|
136
|
+
screenId?: string;
|
|
137
|
+
/** That page's path, for a `page` touch. */
|
|
138
|
+
path?: string;
|
|
123
139
|
/** The sequence the touch came through, for a `sequence` touch. */
|
|
124
140
|
sequenceId?: string;
|
|
125
141
|
/** The enrollment the touch came through, for a `sequence` touch. */
|
|
@@ -184,6 +200,21 @@ export declare function resolveCampaignTouch(options: {
|
|
|
184
200
|
/** When they identified themselves. Defaults to now. */
|
|
185
201
|
atMs?: number;
|
|
186
202
|
}, firestore?: any): Promise<ResolvedCampaignTouch | null>;
|
|
203
|
+
/**
|
|
204
|
+
* THE RULE, between a click and a page (AGL-3461) — `CAMPAIGN_TOUCH_MODEL`
|
|
205
|
+
* says it in words.
|
|
206
|
+
*
|
|
207
|
+
* Within one visit a click that names a campaign keeps the credit for the
|
|
208
|
+
* page it landed on: the visitor clicked a campaign's mail or a link labeled
|
|
209
|
+
* for a campaign and READ the page because of it, and handing the credit to
|
|
210
|
+
* the page would take every landing page's conversions away from the email
|
|
211
|
+
* that sent the reader there. A bare label yields to the page, because the
|
|
212
|
+
* page names a campaign and the label names nothing anybody can open.
|
|
213
|
+
*
|
|
214
|
+
* Further apart, the later wins, which is the last-touch rule every other
|
|
215
|
+
* pair already follows.
|
|
216
|
+
*/
|
|
217
|
+
export declare function pickCampaignTouch(click: ResolvedCampaignTouch | null, page: ResolvedCampaignTouch | null): ResolvedCampaignTouch | null;
|
|
187
218
|
/**
|
|
188
219
|
* Credits one conversion to the campaign the visitor last came from.
|
|
189
220
|
*
|
|
@@ -15,7 +15,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { FieldValue } from "firebase-admin/firestore";
|
|
18
|
-
import { parseUtmTouch } from "@aglyn/aglyn/app-utils/utm-touch";
|
|
18
|
+
import { parsePageTouch, parseUtmTouch } from "@aglyn/aglyn/app-utils/utm-touch";
|
|
19
19
|
/*
|
|
20
20
|
* Stamped from the REVENUE join's constants, aliased at the import.
|
|
21
21
|
*
|
|
@@ -24,13 +24,19 @@ import { parseUtmTouch } from "@aglyn/aglyn/app-utils/utm-touch";
|
|
|
24
24
|
* platform's one answer to how long a touch may be credited. Reading them
|
|
25
25
|
* from there is what makes a lead's record and an order's record carry the
|
|
26
26
|
* same rule rather than two that happen to agree.
|
|
27
|
-
*/ import {
|
|
27
|
+
*/ import { EMAIL_ATTRIBUTION_WINDOW_DAYS as ATTRIBUTION_WINDOW_DAYS, emailTouchIsInWindow } from "@aglyn/shared-util-email/email-revenue-window";
|
|
28
|
+
/*
|
|
29
|
+
* The identify moment's own rule (AGL-3461): a page filed under a campaign is
|
|
30
|
+
* a touch here, and it is not a click, so these records say `last-touch` where
|
|
31
|
+
* an order's say `last-click`. The window above is still the one both share.
|
|
32
|
+
*/ import { CAMPAIGN_TOUCH_MODEL as ATTRIBUTION_MODEL, CAMPAIGN_VISIT_MS } from "../model/campaign-conversions.js";
|
|
28
33
|
import { personKey } from "@aglyn/aglyn/app-utils/person-key";
|
|
29
34
|
import { CAMPAIGN_ATTRIBUTIONS_COLLECTION, eraseCampaignAttributionsForPersonKey } from "./campaign-attribution-store.js";
|
|
30
35
|
import { isDocumentId } from "@aglyn/tenant-data-admin/server/document-id";
|
|
31
36
|
import firebaseAdmin from "@aglyn/tenant-data-admin/server/firebase-admin";
|
|
32
37
|
import { resolveOrgIdForHost } from "@aglyn/tenant-data-admin/server/organizations";
|
|
33
38
|
import { readEmailCampaignTouch } from "./email-campaign-touch.js";
|
|
39
|
+
import { campaignForUtmLabel, filedCampaignForPage } from "./campaign-touch-targets.js";
|
|
34
40
|
const defaultFirestore = ()=>firebaseAdmin.app().firestore();
|
|
35
41
|
/**
|
|
36
42
|
* THE IDENTIFY-MOMENT JOIN — a form, a lead, a contact or a booking, credited
|
|
@@ -71,6 +77,17 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
|
|
|
71
77
|
* produces a figure nobody can check. One outcome, one campaign, and a rule
|
|
72
78
|
* stated on the record.
|
|
73
79
|
*
|
|
80
|
+
* ## And a page filed under a campaign (AGL-3461)
|
|
81
|
+
*
|
|
82
|
+
* A third touch needs no label and no click: the visitor viewed a page the
|
|
83
|
+
* merchant filed under a campaign. The device carries it beside the labels
|
|
84
|
+
* (`utm-touch.ts`), the server credits it only while the campaign exists and
|
|
85
|
+
* the page is still filed under it (`campaign-touch-targets.ts`), and it
|
|
86
|
+
* competes with the winning click under {@link pickCampaignTouch}. A label a
|
|
87
|
+
* campaign declares as its own (`utmCampaigns` on the container) names that
|
|
88
|
+
* campaign the same way. Both are recorded with the CONTAINER's id as
|
|
89
|
+
* `campaignId`, under the `last-touch` model.
|
|
90
|
+
*
|
|
74
91
|
* ## No campaign touch means NO RECORD
|
|
75
92
|
*
|
|
76
93
|
* Direct traffic writes nothing at all, and there is deliberately no fallback
|
|
@@ -127,28 +144,45 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
|
|
|
127
144
|
if (!isDocumentId(hostId)) return null;
|
|
128
145
|
const convertedAtMs = Number((_options_atMs = options.atMs) != null ? _options_atMs : Date.now());
|
|
129
146
|
if (!Number.isFinite(convertedAtMs) || convertedAtMs <= 0) return null;
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
147
|
+
const db = firestore != null ? firestore : defaultFirestore();
|
|
148
|
+
/*
|
|
149
|
+
* The window is enforced inside the parsers, so an expired wire value
|
|
150
|
+
* answers null here exactly as it does in the browser that decided
|
|
151
|
+
* whether to send it.
|
|
152
|
+
*
|
|
153
|
+
* Both instants on the wire are the VISITOR'S clock, and a device running
|
|
154
|
+
* a few minutes fast would date the page it is reading after the
|
|
155
|
+
* conversion the server is recording — refused as "a touch after the
|
|
156
|
+
* conversion", which is the receipt rule, not a clock rule. So the parse
|
|
157
|
+
* allows {@link CLIENT_CLOCK_SKEW_MS} of future and clamps it to the
|
|
158
|
+
* conversion; the write re-checks the window against the server's own
|
|
159
|
+
* instant either way.
|
|
160
|
+
*/ const web = clampToConversion(parseUtmTouch(options.wire, convertedAtMs + CLIENT_CLOCK_SKEW_MS), convertedAtMs);
|
|
161
|
+
const page = clampToConversion(parsePageTouch(options.wire, convertedAtMs + CLIENT_CLOCK_SKEW_MS), convertedAtMs);
|
|
134
162
|
const key = personKey(options.email);
|
|
135
163
|
/*
|
|
136
164
|
* The email channel is only askable of somebody who named an address, and
|
|
137
165
|
* that is the whole reason this join needs the web channel at all. No
|
|
138
166
|
* address means no keyed read: the ordinary anonymous conversion costs
|
|
139
167
|
* nothing here.
|
|
140
|
-
*/ const emailTouch = key ? await readEmailCampaignTouch(String((_options_email = options.email) != null ? _options_email : ''), hostId,
|
|
168
|
+
*/ const emailTouch = key ? await readEmailCampaignTouch(String((_options_email = options.email) != null ? _options_email : ''), hostId, db) : null;
|
|
141
169
|
const emailInWindow = emailTouch && isDocumentId(emailTouch.campaignId) && emailTouchIsInWindow(emailTouch.clickedAtMs, convertedAtMs) ? emailTouch : null;
|
|
142
170
|
/*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
|
|
147
|
-
|
|
171
|
+
* The org owns the campaigns a page or a label can name. Asked only when
|
|
172
|
+
* the visitor carried one of those, so the ordinary conversion pays
|
|
173
|
+
* nothing for it — and the lookup is request-cached besides.
|
|
174
|
+
*/ const orgId = page || (web == null ? void 0 : web.campaign) ? await resolveOrgIdForHost(hostId).catch(()=>null) : null;
|
|
175
|
+
/*
|
|
176
|
+
* A CLICK first — the later of the campaign email and the labeled link,
|
|
177
|
+
* and a tie goes to email. A tie is only reachable when the two instants
|
|
178
|
+
* are the same millisecond, and in that case the email touch is the better
|
|
179
|
+
* evidence: it was recorded by the provider's own click event on the
|
|
180
|
+
* server, while the web touch is a value the visitor's device supplied.
|
|
148
181
|
*/ const emailWins = emailInWindow && (!web || emailInWindow.clickedAtMs >= web.atMs);
|
|
182
|
+
let click = null;
|
|
149
183
|
if (emailWins) {
|
|
150
184
|
const viaSequence = emailInWindow.sequenceId && emailInWindow.enrollmentId;
|
|
151
|
-
|
|
185
|
+
click = _extends({
|
|
152
186
|
channel: viaSequence ? 'sequence' : 'email',
|
|
153
187
|
campaignId: emailInWindow.campaignId
|
|
154
188
|
}, viaSequence ? {
|
|
@@ -159,26 +193,90 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
|
|
|
159
193
|
}, key ? {
|
|
160
194
|
personKey: key
|
|
161
195
|
} : {});
|
|
196
|
+
} else if (web) {
|
|
197
|
+
// A label a campaign declares names that campaign (AGL-3461); any other
|
|
198
|
+
// label stays the text it is.
|
|
199
|
+
const declared = orgId && web.campaign ? await campaignForUtmLabel({
|
|
200
|
+
orgId,
|
|
201
|
+
hostId,
|
|
202
|
+
label: web.campaign
|
|
203
|
+
}, db) : null;
|
|
204
|
+
click = _extends({
|
|
205
|
+
channel: 'web'
|
|
206
|
+
}, declared ? {
|
|
207
|
+
campaignId: declared.id
|
|
208
|
+
} : {}, web.source ? {
|
|
209
|
+
source: web.source
|
|
210
|
+
} : {}, web.medium ? {
|
|
211
|
+
medium: web.medium
|
|
212
|
+
} : {}, web.campaign ? {
|
|
213
|
+
campaign: web.campaign
|
|
214
|
+
} : {}, {
|
|
215
|
+
touchedAtMs: web.atMs
|
|
216
|
+
}, key ? {
|
|
217
|
+
personKey: key
|
|
218
|
+
} : {});
|
|
162
219
|
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
220
|
+
/*
|
|
221
|
+
* THEN THE PAGE (AGL-3461), checked against what is stored: the campaign
|
|
222
|
+
* still exists and the page is still filed under it. Read only when there
|
|
223
|
+
* is one — and never when the click it would compete with is in the same
|
|
224
|
+
* visit and names a campaign, because that click wins without it.
|
|
225
|
+
*/ const pageCouldWin = page && orgId && !((click == null ? void 0 : click.campaignId) && Math.abs(page.atMs - click.touchedAtMs) <= CAMPAIGN_VISIT_MS);
|
|
226
|
+
const filed = pageCouldWin ? await filedCampaignForPage({
|
|
227
|
+
orgId,
|
|
228
|
+
hostId,
|
|
229
|
+
screenId: page.screenId,
|
|
230
|
+
campaignIds: page.containerIds
|
|
231
|
+
}, db) : null;
|
|
232
|
+
const pageTouch = page && filed ? _extends({
|
|
233
|
+
channel: 'page',
|
|
234
|
+
campaignId: filed.id,
|
|
235
|
+
screenId: page.screenId
|
|
236
|
+
}, page.path ? {
|
|
237
|
+
path: page.path
|
|
172
238
|
} : {}, {
|
|
173
|
-
touchedAtMs:
|
|
239
|
+
touchedAtMs: page.atMs
|
|
174
240
|
}, key ? {
|
|
175
241
|
personKey: key
|
|
176
|
-
} : {});
|
|
242
|
+
} : {}) : null;
|
|
243
|
+
return pickCampaignTouch(click, pageTouch);
|
|
177
244
|
} catch (error) {
|
|
178
245
|
console.error('resolveCampaignTouch failed', error);
|
|
179
246
|
return null;
|
|
180
247
|
}
|
|
181
248
|
}
|
|
249
|
+
/**
|
|
250
|
+
* How far ahead of the server a visitor's clock may run before the touch it
|
|
251
|
+
* dates is refused as after the conversion.
|
|
252
|
+
*/ const CLIENT_CLOCK_SKEW_MS = 5 * 60 * 1000;
|
|
253
|
+
/** A parsed touch with an instant no later than the conversion. */ function clampToConversion(touch, convertedAtMs) {
|
|
254
|
+
if (!touch) return null;
|
|
255
|
+
return touch.atMs > convertedAtMs ? _extends({}, touch, {
|
|
256
|
+
atMs: convertedAtMs
|
|
257
|
+
}) : touch;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* THE RULE, between a click and a page (AGL-3461) — `CAMPAIGN_TOUCH_MODEL`
|
|
261
|
+
* says it in words.
|
|
262
|
+
*
|
|
263
|
+
* Within one visit a click that names a campaign keeps the credit for the
|
|
264
|
+
* page it landed on: the visitor clicked a campaign's mail or a link labeled
|
|
265
|
+
* for a campaign and READ the page because of it, and handing the credit to
|
|
266
|
+
* the page would take every landing page's conversions away from the email
|
|
267
|
+
* that sent the reader there. A bare label yields to the page, because the
|
|
268
|
+
* page names a campaign and the label names nothing anybody can open.
|
|
269
|
+
*
|
|
270
|
+
* Further apart, the later wins, which is the last-touch rule every other
|
|
271
|
+
* pair already follows.
|
|
272
|
+
*/ export function pickCampaignTouch(click, page) {
|
|
273
|
+
if (!page) return click;
|
|
274
|
+
if (!click) return page;
|
|
275
|
+
if (Math.abs(page.touchedAtMs - click.touchedAtMs) <= CAMPAIGN_VISIT_MS) {
|
|
276
|
+
return click.campaignId ? click : page;
|
|
277
|
+
}
|
|
278
|
+
return page.touchedAtMs > click.touchedAtMs ? page : click;
|
|
279
|
+
}
|
|
182
280
|
/**
|
|
183
281
|
* Credits one conversion to the campaign the visitor last came from.
|
|
184
282
|
*
|
|
@@ -236,6 +334,10 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
|
|
|
236
334
|
medium: touch.medium
|
|
237
335
|
} : {}, touch.campaign ? {
|
|
238
336
|
campaign: touch.campaign
|
|
337
|
+
} : {}, touch.screenId ? {
|
|
338
|
+
screenId: touch.screenId
|
|
339
|
+
} : {}, touch.path ? {
|
|
340
|
+
path: touch.path
|
|
239
341
|
} : {}, {
|
|
240
342
|
touchedAtMs: touch.touchedAtMs,
|
|
241
343
|
convertedAtMs,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/src/lib/server/campaign-conversion-attribution.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue, type DocumentReference, type Firestore } from 'firebase-admin/firestore'\nimport {\n parseUtmTouch,\n type UtmTouch,\n} from '@aglyn/aglyn/app-utils/utm-touch'\n/*\n * Stamped from the REVENUE join's constants, aliased at the import.\n *\n * They are spelled `EMAIL_` because that is where both halves of that join\n * could reach them, not because the window is an email fact — it is the\n * platform's one answer to how long a touch may be credited. Reading them\n * from there is what makes a lead's record and an order's record carry the\n * same rule rather than two that happen to agree.\n */\nimport {\n EMAIL_ATTRIBUTION_MODEL as ATTRIBUTION_MODEL,\n EMAIL_ATTRIBUTION_WINDOW_DAYS as ATTRIBUTION_WINDOW_DAYS,\n emailTouchIsInWindow,\n} from '@aglyn/shared-util-email/email-revenue-window'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport {\n CAMPAIGN_ATTRIBUTIONS_COLLECTION,\n eraseCampaignAttributionsForPersonKey,\n} from './campaign-attribution-store'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { readEmailCampaignTouch } from './email-campaign-touch'\n\nconst defaultFirestore = () => firebaseAdmin.app().firestore()\n\n/**\n * THE IDENTIFY-MOMENT JOIN — a form, a lead, a contact or a booking, credited\n * to the campaign that led to it.\n *\n * ## Why there is a second join at all, and why it is not a second SCHEME\n *\n * `email-revenue-attribution.ts` credits an ORDER by looking the buyer's\n * address up in the touch map a click wrote. That works because an order\n * names its buyer. Every other outcome a campaign causes is produced by\n * somebody who was anonymous until the instant they produced it: they arrive\n * from a campaign link, browse, and only become identifiable when they submit\n * a form, sign up, book or check out. There is no address to look up until\n * the very moment being attributed.\n *\n * So the touch is carried on the VISITOR (`utm-touch.ts`) and attached\n * here, at each moment they become somebody. What is NOT rebuilt is the\n * model: the same seven-day window, the same last-click rule, the same\n * `model`/`windowDays` stamped onto every record so a report can say what it\n * counted. The email channel is not re-derived either — it is READ from the\n * touch the delivery webhook already wrote, so a campaign email and a\n * campaign ad are two inputs to one comparison rather than two schemes with\n * two answers.\n *\n * ## Last touch, across both channels\n *\n * At the identify moment there can be two candidate touches:\n *\n * - the WEB touch the visitor's device carried, from an ad, a partner link\n * or a social post; and\n * - the EMAIL touch on `emailDeliveries/{personKey}.campaignTouches[hostId]`\n * (`email-campaign-touch.ts`), written server-side when they clicked a\n * 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 — see\n * `campaign-attribution-store.ts` for why.\n */\nexport {\n CAMPAIGN_ATTRIBUTIONS_COLLECTION,\n eraseCampaignAttributionsForPersonKey,\n}\n\n/** The single conversion rollup document under an email campaign. */\nexport const CAMPAIGN_CONVERSIONS_REPORT_DOC = 'conversions'\n\n/**\n * Which identify moment a record credits.\n *\n * Kept apart rather than summed, which is the whole reason the kind is on the\n * record. One form submission by a new person creates a submission, a contact\n * and possibly a lead — three true statements about one visitor action — and\n * a report that added them would treble every campaign's conversions. A\n * reader asks for one kind at a time, exactly as the revenue rollup buckets\n * by currency and never totals across them.\n */\nexport type CampaignConversionKind = 'form' | 'lead' | 'contact' | 'booking'\n\n/**\n * Which channel the credited touch arrived through.\n *\n * `sequence` (AGL-3254) is a click on, or the sending of, a one-to-one\n * email a rep's sequence sent. It is read off the same touch map as the\n * email channel — the Outreach click route stamps it there with the\n * sequence and the enrollment beside the campaign the sequence is in — so\n * a booking made from a sequence link is credited by the door that credits\n * every other booking, and nothing in this join has to know what a\n * sequence is.\n */\nexport type CampaignTouchChannel = 'email' | 'web' | 'sequence'\n\n/** The touch a conversion is credited to, once both channels have been asked. */\nexport interface ResolvedCampaignTouch {\n channel: CampaignTouchChannel\n /**\n * The campaign document, when the touch was a click on our own mail — or\n * the campaign CONTAINER (`emailCampaigns/{id}`) a sequence is in, for a\n * sequence touch.\n */\n campaignId?: string\n /** The sequence the touch came through, for a `sequence` touch. */\n sequenceId?: string\n /** The enrollment the touch came through, for a `sequence` touch. */\n enrollmentId?: string\n /** `utm_source`, when the touch was a link on the web. */\n source?: string\n /** `utm_medium`, when the touch was a link on the web. */\n medium?: string\n /** `utm_campaign`, when the touch was a link on the web. */\n campaign?: string\n /** When the visitor followed the campaign link, epoch ms. */\n touchedAtMs: number\n /**\n * `sha256` of the normalized address the touch was resolved against, when\n * the visitor gave one. The handle an erasure erases by — see\n * {@link eraseCampaignAttributionsForPersonKey}.\n */\n personKey?: string\n}\n\n/** What one conversion attribution record holds. */\nexport interface CampaignConversionRecord extends ResolvedCampaignTouch {\n kind: CampaignConversionKind\n /** The submission, lead, contact or booking this credits. */\n refId: string\n /** When the visitor became identifiable. */\n convertedAtMs: number\n /** The model this credit was decided under. */\n model: string\n /** The window, in days, it was decided inside. */\n windowDays: number\n}\n\n/**\n * The document id for one conversion.\n *\n * `{kind}:{refId}`, so the same submission credited twice is the same\n * document — which is what makes {@link attributeCampaignConversion}'s\n * `create()` idempotent. Scoped by kind because the ids come from different\n * collections and a booking id has no reason to be distinct from a form\n * submission's.\n */\nexport function campaignConversionId(\n kind: CampaignConversionKind,\n refId: string,\n): string {\n return `${kind}:${refId}`\n}\n\n/**\n * The campaign touch to credit a conversion happening now, or `null`.\n *\n * Called ONCE per conversion request, at the door, and the result handed to\n * every writer beneath it. See the module docblock for the cost argument.\n *\n * @returns the winning touch, or `null` when neither channel has one inside\n * the window — which is the ordinary case and writes nothing.\n */\nexport async function resolveCampaignTouch(\n options: {\n hostId: string\n /**\n * The wire form the conversion request carried, when the door reports\n * one. Re-parsed through the allowlist that wrote it rather than trusted:\n * it arrives from the visitor's browser, so it may claim no more than an\n * inbound URL could.\n */\n wire?: unknown\n /** The address the visitor identified with, raw. */\n email?: unknown\n /** When they identified themselves. Defaults to now. */\n atMs?: number\n },\n firestore?: any,\n): Promise<ResolvedCampaignTouch | null> {\n try {\n const hostId = String(options.hostId ?? '')\n if (!isDocumentId(hostId)) return null\n const convertedAtMs = Number(options.atMs ?? Date.now())\n if (!Number.isFinite(convertedAtMs) || convertedAtMs <= 0) return null\n\n // The window is enforced inside the parser, so an expired or\n // future-dated wire value answers null here exactly as it does in the\n // browser that decided whether to send it.\n const web: UtmTouch | null = parseUtmTouch(\n options.wire,\n convertedAtMs,\n )\n\n const key = personKey(options.email)\n /*\n * The email channel is only askable of somebody who named an address, and\n * that is the whole reason this join needs the web channel at all. No\n * address means no keyed read: the ordinary anonymous conversion costs\n * nothing here.\n */\n const emailTouch = key\n ? await readEmailCampaignTouch(\n String(options.email ?? ''),\n hostId,\n firestore ?? defaultFirestore(),\n )\n : null\n const emailInWindow =\n emailTouch &&\n isDocumentId(emailTouch.campaignId) &&\n emailTouchIsInWindow(emailTouch.clickedAtMs, convertedAtMs)\n ? emailTouch\n : null\n\n /*\n * LAST TOUCH decides, and a tie goes to email. A tie is only reachable\n * when the two instants are the same millisecond, and in that case the\n * email touch is the better evidence: it was recorded by the provider's\n * own click event on the server, while the web touch is a value the\n * visitor's device supplied.\n */\n const emailWins =\n emailInWindow && (!web || emailInWindow.clickedAtMs >= web.atMs)\n if (emailWins) {\n const viaSequence = emailInWindow.sequenceId && emailInWindow.enrollmentId\n return {\n channel: viaSequence ? 'sequence' : 'email',\n campaignId: emailInWindow.campaignId,\n ...(viaSequence\n ? { sequenceId: emailInWindow.sequenceId, enrollmentId: emailInWindow.enrollmentId }\n : {}),\n touchedAtMs: emailInWindow.clickedAtMs,\n ...(key ? { personKey: key } : {}),\n }\n }\n if (!web) return null\n return {\n channel: 'web',\n ...(web.source ? { source: web.source } : {}),\n ...(web.medium ? { medium: web.medium } : {}),\n ...(web.campaign ? { campaign: web.campaign } : {}),\n touchedAtMs: web.atMs,\n ...(key ? { personKey: key } : {}),\n }\n } catch (error) {\n console.error('resolveCampaignTouch failed', error)\n return null\n }\n}\n\n/**\n * Credits one conversion to the campaign the visitor last came from.\n *\n * ## Why the record is a document and not a field\n *\n * The revenue join's three reasons, and the first is decisive here too.\n * `create()` fails when the document already exists, which is exact\n * idempotency for free: a retried form POST, a redelivered booking webhook\n * and a re-run capture all land here a second time and must all leave the\n * rollup where they found it. Second, the four kinds live in four different\n * collections — a contact is org-scoped and shared across every site in the\n * org — so there is no one document a field could go on. Third, the\n * submission, the lead and the booking are read by the inbox, the export and\n * the fulfilment path, and none of them wants a field about marketing.\n *\n * ## The rollup exists for the EMAIL channel only\n *\n * A campaign document is a real entity with a real id, so its conversions\n * roll up under it beside the revenue the same join already credits it with.\n * A web campaign is a LABEL the marketer typed into a URL, with no document,\n * no id and no bound on how many distinct values exist — the same unbounded\n * key space the analytics collector caps its per-day label map against. A\n * rollup keyed on it would be a map anybody who can vary a query string can\n * grow. So the web channel's records stand on their own and a report reads\n * them; see the module's report seam note.\n *\n * @returns the record written, or `null` when nothing was credited.\n */\nexport async function attributeCampaignConversion(\n options: {\n hostId: string\n kind: CampaignConversionKind\n /** The submission, lead, contact or booking being credited. */\n refId: string\n /** The touch {@link resolveCampaignTouch} picked, or `null` for direct. */\n touch: ResolvedCampaignTouch | null | undefined\n /** When the visitor became identifiable. Defaults to now. */\n convertedAtMs?: number\n },\n firestore?: any,\n): Promise<CampaignConversionRecord | null> {\n try {\n const { touch } = options\n if (!touch) return null\n const hostId = String(options.hostId ?? '')\n const refId = String(options.refId ?? '')\n if (!isDocumentId(hostId) || !isDocumentId(refId)) return null\n const convertedAtMs = Number(options.convertedAtMs ?? Date.now())\n if (!Number.isFinite(convertedAtMs) || convertedAtMs <= 0) return null\n // Re-checked at the write rather than trusted from the resolve. The two\n // are separated by the writes that produced the thing being credited, and\n // a touch that has aged out between them is a touch outside the window.\n if (!emailTouchIsInWindow(touch.touchedAtMs, convertedAtMs)) return null\n\n const record: CampaignConversionRecord = {\n kind: options.kind,\n refId,\n channel: touch.channel,\n ...(touch.campaignId ? { campaignId: touch.campaignId } : {}),\n ...(touch.sequenceId ? { sequenceId: touch.sequenceId } : {}),\n ...(touch.enrollmentId ? { enrollmentId: touch.enrollmentId } : {}),\n ...(touch.source ? { source: touch.source } : {}),\n ...(touch.medium ? { medium: touch.medium } : {}),\n ...(touch.campaign ? { campaign: touch.campaign } : {}),\n touchedAtMs: touch.touchedAtMs,\n convertedAtMs,\n model: ATTRIBUTION_MODEL,\n windowDays: ATTRIBUTION_WINDOW_DAYS,\n ...(touch.personKey ? { personKey: touch.personKey } : {}),\n }\n\n const db = firestore ?? defaultFirestore()\n const hostRef = db.collection('hosts').doc(hostId)\n /*\n * `create()`, never `set()` — the revenue join's argument, unchanged. The\n * ALREADY_EXISTS failure IS the idempotency, and the rollup below is\n * reached only when the create succeeded, so the two can never disagree\n * about whether this conversion was counted.\n */\n try {\n await hostRef\n .collection(CAMPAIGN_ATTRIBUTIONS_COLLECTION)\n .doc(campaignConversionId(options.kind, refId))\n .create({ ...record, createdAt: FieldValue.serverTimestamp() })\n } catch {\n return null\n }\n\n /*\n * The send the touch names (`touch.campaignId` is a SEND id on the email\n * channel), wherever it is: the org's `campaigns` collection, or the\n * site's for a send the migration has not reached. A send in neither\n * place was discarded, and its rollup is skipped — the record above\n * already says what was credited.\n */\n const sendRef =\n touch.channel === 'email' && touch.campaignId && isDocumentId(touch.campaignId)\n ? await resolveCampaignSendRef({ hostId, sendId: touch.campaignId, firestore: db })\n : null\n if (sendRef) {\n /*\n * A merge-set that CREATES, for the reason `reports/revenue` gives: this\n * writes a document UNDER a campaign, so a campaign that no longer\n * exists gains an orphaned report rather than being resurrected as a\n * husk in the merchant's history — and the campaign was proven to exist\n * when its click wrote the touch.\n *\n * Every figure is an increment, so two conversions settling at once\n * both land.\n */\n await sendRef\n .collection('reports')\n .doc(CAMPAIGN_CONVERSIONS_REPORT_DOC)\n .set(\n {\n model: ATTRIBUTION_MODEL,\n windowDays: ATTRIBUTION_WINDOW_DAYS,\n byKind: { [options.kind]: FieldValue.increment(1) },\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n }\n\n /*\n * A SEQUENCE touch rolls up under the campaign's sequences report, and\n * only a booking does: \"meetings booked from a sequence link\" is the one\n * identify moment a sequence's own outcomes do not already count. The\n * form, lead and contact kinds stand as records — visible on the record\n * they credit and on the site's conversions list — and never in\n * `byKind`, whose caveat promises the reader campaign emails only.\n */\n if (touch.channel === 'sequence' && touch.campaignId && options.kind === 'booking') {\n await creditCampaignSequenceOutcome(\n { hostId, campaignIds: [touch.campaignId], outcome: 'meetings', atMs: convertedAtMs },\n db,\n )\n }\n\n return record\n } catch (error) {\n console.error('attributeCampaignConversion failed', error)\n return null\n }\n}\n\n/*==========================================\n * WHAT A CAMPAIGN'S SEQUENCES PRODUCED (AGL-3254).\n *\n * A sequence joins a campaign the way a form does, and the Outreach runtime\n * credits what each enrollment produced — enrolled, first email sent, a\n * reply, a meeting booked from a sequence link, an enrolled lead converted\n * — to every campaign the sequence was in when the person was enrolled. The\n * counts live in `orgs/{orgId}/campaignSequenceReports/{campaignId}`, beside\n * the org's containers: one document per campaign, server-only like every\n * other report here, and never inside the campaign container, which the\n * history list reads.\n *\n * Idempotency is the CALLER's: a plugin credits an outcome once per\n * enrollment from a state change that happens once — the enrollment is\n * created once, its first email is the first, its status moves to replied\n * once, its lead converts once — so this writer is a plain increment and\n * keeps no per-enrollment record of its own.\n *=========================================*/\n\n/**\n * The per-org collection of sequence rollups. Restated from the reader\n * (`model/campaign-report.ts`) and asserted equal by\n * 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, beside the join that is this\n * lookup's first reader; `campaign-container.ts` documents the same strings.\n */\n\nconst sendRefFirestore = (): Firestore => firebaseAdmin.app().firestore()\n\n/** `orgs/{orgId}/campaigns` — one document per email send. */\nconst ORG_SENDS = 'campaigns'\n\n/** `orgs/{orgId}/campaignSequenceReports` — keyed by the container id. */\nconst ORG_SEQUENCE_REPORTS = 'campaignSequenceReports'\n\n/** `orgs/{orgId}/campaigns/{sendId}`. */\nexport function orgCampaignSendRef(\n orgId: string,\n sendId: string,\n firestore: Firestore = sendRefFirestore(),\n): DocumentReference {\n return firestore.collection('orgs').doc(orgId).collection(ORG_SENDS).doc(sendId)\n}\n\n/** `orgs/{orgId}/campaignSequenceReports/{campaignId}`. */\nexport function orgCampaignSequenceReportRef(\n orgId: string,\n campaignId: string,\n firestore: Firestore = sendRefFirestore(),\n): DocumentReference {\n return firestore\n .collection('orgs')\n .doc(orgId)\n .collection(ORG_SEQUENCE_REPORTS)\n .doc(campaignId)\n}\n\n/** The pre-AGL-3273 location, read only as the fallback described above. */\nfunction legacySiteSendRef(\n hostId: string,\n sendId: string,\n firestore: Firestore,\n): DocumentReference {\n return firestore.collection('hosts').doc(hostId).collection(ORG_SENDS).doc(sendId)\n}\n\nexport interface ResolveCampaignSendRefInput {\n /** The site the link or the message tag names. */\n hostId: string\n /** The send id (`cid` on a link, `campaignId` on a message tag). */\n sendId: string\n /**\n * The org, when the caller already has it — a message tag minted since\n * AGL-3273 carries it. Saves the `hostIndex` read.\n */\n orgId?: string | null\n firestore?: Firestore\n}\n\n/**\n * The send's document, wherever it currently is. Null when neither location\n * holds it — a send id from a link whose send was discarded, or a forged one.\n *\n * Costs one read after the migration (the org document), plus the\n * `hostIndex` lookup when the caller has no org id; that lookup is\n * request-cached.\n */\nexport async function resolveCampaignSendRef(\n input: ResolveCampaignSendRefInput,\n): Promise<DocumentReference | null> {\n const { hostId, sendId } = input\n if (!hostId || !sendId || sendId.includes('/') || hostId.includes('/')) return null\n const firestore = input.firestore ?? sendRefFirestore()\n const orgId = input.orgId || (await resolveOrgIdForHost(hostId))\n if (orgId) {\n const orgRef = orgCampaignSendRef(orgId, sendId, firestore)\n if ((await orgRef.get()).exists) return orgRef\n }\n const siteRef = legacySiteSendRef(hostId, sendId, firestore)\n if ((await siteRef.get()).exists) return siteRef\n return null\n}\n"],"names":["FieldValue","parseUtmTouch","EMAIL_ATTRIBUTION_MODEL","ATTRIBUTION_MODEL","EMAIL_ATTRIBUTION_WINDOW_DAYS","ATTRIBUTION_WINDOW_DAYS","emailTouchIsInWindow","personKey","CAMPAIGN_ATTRIBUTIONS_COLLECTION","eraseCampaignAttributionsForPersonKey","isDocumentId","firebaseAdmin","resolveOrgIdForHost","readEmailCampaignTouch","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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BT,OAAOpB,QAAQhD;QACjD,IAAI,AAAC,CAAA,MAAMgF,OAAOC,GAAG,EAAC,EAAGC,MAAM,EAAE,OAAOF;IAC1C;IACA,MAAMG,UAAUL,kBAAkBvE,QAAQyC,QAAQhD;IAClD,IAAI,AAAC,CAAA,MAAMmF,QAAQF,GAAG,EAAC,EAAGC,MAAM,EAAE,OAAOC;IACzC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketing/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 parsePageTouch,\n parseUtmTouch,\n type PageTouch,\n type UtmTouch,\n} from '@aglyn/aglyn/app-utils/utm-touch'\n/*\n * Stamped from the REVENUE join's constants, aliased at the import.\n *\n * They are spelled `EMAIL_` because that is where both halves of that join\n * could reach them, not because the window is an email fact — it is the\n * platform's one answer to how long a touch may be credited. Reading them\n * from there is what makes a lead's record and an order's record carry the\n * same rule rather than two that happen to agree.\n */\nimport {\n EMAIL_ATTRIBUTION_WINDOW_DAYS as ATTRIBUTION_WINDOW_DAYS,\n emailTouchIsInWindow,\n} from '@aglyn/shared-util-email/email-revenue-window'\n/*\n * The identify moment's own rule (AGL-3461): a page filed under a campaign is\n * a touch here, and it is not a click, so these records say `last-touch` where\n * an order's say `last-click`. The window above is still the one both share.\n */\nimport {\n CAMPAIGN_TOUCH_MODEL as ATTRIBUTION_MODEL,\n CAMPAIGN_VISIT_MS,\n} from '../model/campaign-conversions'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport {\n CAMPAIGN_ATTRIBUTIONS_COLLECTION,\n eraseCampaignAttributionsForPersonKey,\n} from './campaign-attribution-store'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport firebaseAdmin from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { readEmailCampaignTouch } from './email-campaign-touch'\nimport { campaignForUtmLabel, filedCampaignForPage } from './campaign-touch-targets'\n\nconst defaultFirestore = () => firebaseAdmin.app().firestore()\n\n/**\n * THE IDENTIFY-MOMENT JOIN — a form, a lead, a contact or a booking, credited\n * to the campaign that led to it.\n *\n * ## Why there is a second join at all, and why it is not a second SCHEME\n *\n * `email-revenue-attribution.ts` credits an ORDER by looking the buyer's\n * address up in the touch map a click wrote. That works because an order\n * names its buyer. Every other outcome a campaign causes is produced by\n * somebody who was anonymous until the instant they produced it: they arrive\n * from a campaign link, browse, and only become identifiable when they submit\n * a form, sign up, book or check out. There is no address to look up until\n * the very moment being attributed.\n *\n * So the touch is carried on the VISITOR (`utm-touch.ts`) and attached\n * here, at each moment they become somebody. What is NOT rebuilt is the\n * model: the same seven-day window, the same last-click rule, the same\n * `model`/`windowDays` stamped onto every record so a report can say what it\n * counted. The email channel is not re-derived either — it is READ from the\n * touch the delivery webhook already wrote, so a campaign email and a\n * campaign ad are two inputs to one comparison rather than two schemes with\n * two answers.\n *\n * ## Last touch, across both channels\n *\n * At the identify moment there can be two candidate touches:\n *\n * - the WEB touch the visitor's device carried, from an ad, a partner link\n * or a social post; and\n * - the EMAIL touch on `emailDeliveries/{personKey}.campaignTouches[hostId]`\n * (`email-campaign-touch.ts`), written server-side when they clicked a\n * 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 * ## And a page filed under a campaign (AGL-3461)\n *\n * A third touch needs no label and no click: the visitor viewed a page the\n * merchant filed under a campaign. The device carries it beside the labels\n * (`utm-touch.ts`), the server credits it only while the campaign exists and\n * the page is still filed under it (`campaign-touch-targets.ts`), and it\n * competes with the winning click under {@link pickCampaignTouch}. A label a\n * campaign declares as its own (`utmCampaigns` on the container) names that\n * campaign the same way. Both are recorded with the CONTAINER's id as\n * `campaignId`, under the `last-touch` model.\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 — see\n * `campaign-attribution-store.ts` for why.\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' | 'page'\n\n/** The touch a conversion is credited to, once every channel has 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, the page was filed under, for a page touch, or that\n * declares the label, for a web touch whose label one does (AGL-3461).\n */\n campaignId?: string\n /** The screen the visitor viewed, for a `page` touch. */\n screenId?: string\n /** That page's path, for a `page` touch. */\n path?: 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 const db = firestore ?? defaultFirestore()\n\n /*\n * The window is enforced inside the parsers, so an expired wire value\n * answers null here exactly as it does in the browser that decided\n * whether to send it.\n *\n * Both instants on the wire are the VISITOR'S clock, and a device running\n * a few minutes fast would date the page it is reading after the\n * conversion the server is recording — refused as \"a touch after the\n * conversion\", which is the receipt rule, not a clock rule. So the parse\n * allows {@link CLIENT_CLOCK_SKEW_MS} of future and clamps it to the\n * conversion; the write re-checks the window against the server's own\n * instant either way.\n */\n const web = clampToConversion(\n parseUtmTouch(options.wire, convertedAtMs + CLIENT_CLOCK_SKEW_MS),\n convertedAtMs,\n )\n const page = clampToConversion(\n parsePageTouch(options.wire, convertedAtMs + CLIENT_CLOCK_SKEW_MS),\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(String(options.email ?? ''), hostId, db)\n : null\n const emailInWindow =\n emailTouch &&\n isDocumentId(emailTouch.campaignId) &&\n emailTouchIsInWindow(emailTouch.clickedAtMs, convertedAtMs)\n ? emailTouch\n : null\n\n /*\n * The org owns the campaigns a page or a label can name. Asked only when\n * the visitor carried one of those, so the ordinary conversion pays\n * nothing for it — and the lookup is request-cached besides.\n */\n const orgId =\n page || web?.campaign\n ? await resolveOrgIdForHost(hostId).catch(() => null)\n : null\n\n /*\n * A CLICK first — the later of the campaign email and the labeled link,\n * and a tie goes to email. A tie is only reachable when the two instants\n * are the same millisecond, and in that case the email touch is the better\n * evidence: it was recorded by the provider's own click event on the\n * server, while the web touch is a value the visitor's device supplied.\n */\n const emailWins =\n emailInWindow && (!web || emailInWindow.clickedAtMs >= web.atMs)\n let click: ResolvedCampaignTouch | null = null\n if (emailWins) {\n const viaSequence = emailInWindow.sequenceId && emailInWindow.enrollmentId\n click = {\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 } else if (web) {\n // A label a campaign declares names that campaign (AGL-3461); any other\n // label stays the text it is.\n const declared =\n orgId && web.campaign\n ? await campaignForUtmLabel({ orgId, hostId, label: web.campaign }, db)\n : null\n click = {\n channel: 'web',\n ...(declared ? { campaignId: declared.id } : {}),\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 }\n\n /*\n * THEN THE PAGE (AGL-3461), checked against what is stored: the campaign\n * still exists and the page is still filed under it. Read only when there\n * is one — and never when the click it would compete with is in the same\n * visit and names a campaign, because that click wins without it.\n */\n const pageCouldWin =\n page &&\n orgId &&\n !(\n click?.campaignId &&\n Math.abs(page.atMs - click.touchedAtMs) <= CAMPAIGN_VISIT_MS\n )\n const filed = pageCouldWin\n ? await filedCampaignForPage(\n {\n orgId,\n hostId,\n screenId: page.screenId,\n campaignIds: page.containerIds,\n },\n db,\n )\n : null\n const pageTouch: ResolvedCampaignTouch | null =\n page && filed\n ? {\n channel: 'page',\n campaignId: filed.id,\n screenId: page.screenId,\n ...(page.path ? { path: page.path } : {}),\n touchedAtMs: page.atMs,\n ...(key ? { personKey: key } : {}),\n }\n : null\n\n return pickCampaignTouch(click, pageTouch)\n } catch (error) {\n console.error('resolveCampaignTouch failed', error)\n return null\n }\n}\n\n/**\n * How far ahead of the server a visitor's clock may run before the touch it\n * dates is refused as after the conversion.\n */\nconst CLIENT_CLOCK_SKEW_MS = 5 * 60 * 1000\n\n/** A parsed touch with an instant no later than the conversion. */\nfunction clampToConversion<T extends UtmTouch | PageTouch>(\n touch: T | null,\n convertedAtMs: number,\n): T | null {\n if (!touch) return null\n return touch.atMs > convertedAtMs ? { ...touch, atMs: convertedAtMs } : touch\n}\n\n/**\n * THE RULE, between a click and a page (AGL-3461) — `CAMPAIGN_TOUCH_MODEL`\n * says it in words.\n *\n * Within one visit a click that names a campaign keeps the credit for the\n * page it landed on: the visitor clicked a campaign's mail or a link labeled\n * for a campaign and READ the page because of it, and handing the credit to\n * the page would take every landing page's conversions away from the email\n * that sent the reader there. A bare label yields to the page, because the\n * page names a campaign and the label names nothing anybody can open.\n *\n * Further apart, the later wins, which is the last-touch rule every other\n * pair already follows.\n */\nexport function pickCampaignTouch(\n click: ResolvedCampaignTouch | null,\n page: ResolvedCampaignTouch | null,\n): ResolvedCampaignTouch | null {\n if (!page) return click\n if (!click) return page\n if (Math.abs(page.touchedAtMs - click.touchedAtMs) <= CAMPAIGN_VISIT_MS) {\n return click.campaignId ? click : page\n }\n return page.touchedAtMs > click.touchedAtMs ? page : click\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 ...(touch.screenId ? { screenId: touch.screenId } : {}),\n ...(touch.path ? { path: touch.path } : {}),\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 * (`model/campaign-report.ts`) and asserted equal by\n * 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, beside the join that is this\n * lookup's first reader; `campaign-container.ts` documents the same strings.\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","parsePageTouch","parseUtmTouch","EMAIL_ATTRIBUTION_WINDOW_DAYS","ATTRIBUTION_WINDOW_DAYS","emailTouchIsInWindow","CAMPAIGN_TOUCH_MODEL","ATTRIBUTION_MODEL","CAMPAIGN_VISIT_MS","personKey","CAMPAIGN_ATTRIBUTIONS_COLLECTION","eraseCampaignAttributionsForPersonKey","isDocumentId","firebaseAdmin","resolveOrgIdForHost","readEmailCampaignTouch","campaignForUtmLabel","filedCampaignForPage","defaultFirestore","app","firestore","CAMPAIGN_CONVERSIONS_REPORT_DOC","campaignConversionId","kind","refId","resolveCampaignTouch","options","hostId","String","convertedAtMs","Number","atMs","Date","now","isFinite","db","web","clampToConversion","wire","CLIENT_CLOCK_SKEW_MS","page","key","email","emailTouch","emailInWindow","campaignId","clickedAtMs","orgId","campaign","catch","emailWins","click","viaSequence","sequenceId","enrollmentId","channel","touchedAtMs","declared","label","id","source","medium","pageCouldWin","Math","abs","filed","screenId","campaignIds","containerIds","pageTouch","path","pickCampaignTouch","error","console","touch","attributeCampaignConversion","record","model","windowDays","hostRef","collection","doc","create","createdAt","serverTimestamp","sendRef","resolveCampaignSendRef","sendId","set","byKind","increment","updatedAt","merge","creditCampaignSequenceOutcome","outcome","CAMPAIGN_SEQUENCE_REPORTS_COLLECTION","CAMPAIGN_SEQUENCE_OUTCOMES","includes","ids","Set","map","trim","filter","length","given","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,cAAc,EACdC,aAAa,QAGR,mCAAkC;AACzC;;;;;;;;CAQC,GACD,SACEC,iCAAiCC,uBAAuB,EACxDC,oBAAoB,QACf,gDAA+C;AACtD;;;;CAIC,GACD,SACEC,wBAAwBC,iBAAiB,EACzCC,iBAAiB,QACZ,mCAA+B;AACtC,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SACEC,gCAAgC,EAChCC,qCAAqC,QAChC,kCAA8B;AACrC,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,OAAOC,mBAAmB,iDAAgD;AAC1E,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,sBAAsB,QAAQ,4BAAwB;AAC/D,SAASC,mBAAmB,EAAEC,oBAAoB,QAAQ,8BAA0B;AAEpF,MAAMC,mBAAmB,IAAML,cAAcM,GAAG,GAAGC,SAAS;AAE5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0EC,GAED;;;;CAIC,GACD,SACEV,gCAAgC,EACh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ASH,mBAAmBlE,OAAOwC,QAAQnE;QACjD,IAAI,AAAC,CAAA,MAAMgG,OAAOC,GAAG,EAAC,EAAGC,MAAM,EAAE,OAAOF;IAC1C;IACA,MAAMG,UAAUL,kBAAkBvF,QAAQ4D,QAAQnE;IAClD,IAAI,AAAC,CAAA,MAAMmG,QAAQF,GAAG,EAAC,EAAGC,MAAM,EAAE,OAAOC;IACzC,OAAO;AACT"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/** A campaign container, as much of it as a touch's credit needs. */
|
|
18
|
+
export interface LiveCampaign {
|
|
19
|
+
id: string;
|
|
20
|
+
name: string;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The campaign at `orgs/{orgId}/emailCampaigns/{campaignId}`, or `null` when
|
|
24
|
+
* it does not exist or its owner retired it.
|
|
25
|
+
*/
|
|
26
|
+
export declare function readLiveCampaign(options: {
|
|
27
|
+
orgId: string;
|
|
28
|
+
campaignId: string;
|
|
29
|
+
}, firestore: any): Promise<LiveCampaign | null>;
|
|
30
|
+
/**
|
|
31
|
+
* The campaigns a site's screen is filed under right now, or `null` when the
|
|
32
|
+
* screen does not exist.
|
|
33
|
+
*/
|
|
34
|
+
export declare function readScreenCampaignIds(options: {
|
|
35
|
+
hostId: string;
|
|
36
|
+
screenId: string;
|
|
37
|
+
}, firestore: any): Promise<string[] | null>;
|
|
38
|
+
/**
|
|
39
|
+
* Of the campaigns a page touch carries, the first that the page is STILL
|
|
40
|
+
* filed under and that still exists — or `null`.
|
|
41
|
+
*
|
|
42
|
+
* The touch carries the screen's campaigns in the screen's own order, so a
|
|
43
|
+
* page filed under two campaigns credits the one it names first. One
|
|
44
|
+
* outcome, one campaign: crediting both would count one visitor's form twice
|
|
45
|
+
* across the org's campaigns.
|
|
46
|
+
*/
|
|
47
|
+
export declare function filedCampaignForPage(options: {
|
|
48
|
+
orgId: string;
|
|
49
|
+
hostId: string;
|
|
50
|
+
screenId: string;
|
|
51
|
+
campaignIds: readonly string[];
|
|
52
|
+
}, firestore: any): Promise<LiveCampaign | null>;
|
|
53
|
+
/**
|
|
54
|
+
* The one live campaign placed on this site that declares `label` among its
|
|
55
|
+
* `utmCampaigns`, or `null` — for no such campaign, and for two.
|
|
56
|
+
*/
|
|
57
|
+
export declare function campaignForUtmLabel(options: {
|
|
58
|
+
orgId: string;
|
|
59
|
+
hostId: string;
|
|
60
|
+
label: string | null | undefined;
|
|
61
|
+
}, firestore: any): Promise<LiveCampaign | null>;
|