@hogsend/engine 0.43.0 → 0.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +12 -9
- package/src/container.ts +289 -13
- package/src/destinations/define-destination.ts +7 -3
- package/src/destinations/presets/posthog.ts +31 -0
- package/src/index.ts +99 -0
- package/src/journeys/execute-journey-run.ts +93 -0
- package/src/journeys/journey-context.ts +4 -0
- package/src/lib/analytics-providers-from-env.ts +106 -43
- package/src/lib/attribution-backfill.ts +285 -0
- package/src/lib/attribution.ts +239 -0
- package/src/lib/contacts.ts +71 -0
- package/src/lib/conversion-dispatch.ts +326 -0
- package/src/lib/conversions.ts +197 -0
- package/src/lib/crm-deals.ts +320 -0
- package/src/lib/crm-ingest.ts +341 -0
- package/src/lib/crm-provider-registry.ts +41 -0
- package/src/lib/crm-registry-singleton.ts +22 -0
- package/src/lib/deal-money-events.ts +85 -0
- package/src/lib/email-service-types.ts +16 -1
- package/src/lib/event-names.ts +1 -1
- package/src/lib/funnel-progress.ts +76 -0
- package/src/lib/funnel-registry.ts +108 -0
- package/src/lib/funnel-transitions.ts +280 -0
- package/src/lib/holdout.ts +62 -0
- package/src/lib/ingestion.ts +218 -9
- package/src/lib/lift-stats.ts +125 -0
- package/src/lib/mailer.ts +1 -0
- package/src/lib/operator.ts +31 -0
- package/src/lib/outbound.ts +51 -0
- package/src/lib/posthog-scopes.ts +30 -6
- package/src/lib/revenue.ts +116 -0
- package/src/lib/sms-service-types.ts +7 -1
- package/src/lib/sms-tracked.ts +35 -0
- package/src/lib/tracked.ts +40 -0
- package/src/lib/tracking-events.ts +26 -0
- package/src/lib/unconfigured-email-provider.ts +45 -0
- package/src/lib/webhook-signing.ts +7 -0
- package/src/routes/admin/analytics.ts +14 -5
- package/src/routes/admin/attribution.ts +414 -0
- package/src/routes/admin/contacts.ts +71 -11
- package/src/routes/admin/conversions.ts +247 -0
- package/src/routes/admin/deals.ts +472 -0
- package/src/routes/admin/funnels.ts +228 -0
- package/src/routes/admin/index.ts +8 -0
- package/src/routes/admin/journeys.ts +158 -1
- package/src/routes/admin/readiness.ts +97 -2
- package/src/routes/admin/templates.ts +28 -1
- package/src/routes/events/index.ts +12 -0
- package/src/routes/tracking/click-pipeline.ts +26 -18
- package/src/routes/webhooks/crm-provider.ts +117 -0
- package/src/routes/webhooks/index.ts +5 -1
- package/src/sources/define-contact-source.ts +159 -0
- package/src/sources/registry.ts +71 -0
- package/src/sources/webhook-source.ts +109 -0
- package/src/worker.ts +4 -0
- package/src/workflows/crm-reconcile.ts +129 -0
- package/src/workflows/dispatch-conversion.ts +31 -0
- package/src/workflows/send-campaign.ts +5 -0
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type {
|
|
3
|
+
ConversionDestination,
|
|
4
|
+
ConversionDispatchInput,
|
|
5
|
+
} from "@hogsend/core";
|
|
6
|
+
import { CLICK_ID_PARAM_NAMES } from "@hogsend/core";
|
|
7
|
+
import {
|
|
8
|
+
contacts,
|
|
9
|
+
conversionDispatches,
|
|
10
|
+
conversions,
|
|
11
|
+
type Database,
|
|
12
|
+
userEvents,
|
|
13
|
+
} from "@hogsend/db";
|
|
14
|
+
import { and, desc, eq, inArray, lte } from "drizzle-orm";
|
|
15
|
+
import type { Logger } from "./logger.js";
|
|
16
|
+
import { createOptionalSingleton } from "./singleton.js";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Conversion dispatch (plan §5.2): fired conversions → destination providers,
|
|
20
|
+
* durably. The ingest hook creates `conversion_dispatches` rows (idempotent
|
|
21
|
+
* on (destination, event_id)) and enqueues the durable task per row; the task
|
|
22
|
+
* assembles the enriched payload (contact identifiers + recovered click
|
|
23
|
+
* context) and calls the provider, retrying with the SAME deterministic
|
|
24
|
+
* event_id so the platform dedups.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
export class ConversionDestinationRegistry {
|
|
28
|
+
private byId = new Map<string, ConversionDestination>();
|
|
29
|
+
|
|
30
|
+
constructor(destinations: ConversionDestination[] = []) {
|
|
31
|
+
for (const destination of destinations) {
|
|
32
|
+
this.byId.set(destination.meta.id, destination);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
get(id: string): ConversionDestination | undefined {
|
|
37
|
+
return this.byId.get(id);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const singleton = createOptionalSingleton<ConversionDestinationRegistry>();
|
|
42
|
+
export const setConversionDestinations = singleton.set;
|
|
43
|
+
export const getConversionDestinations = singleton.get;
|
|
44
|
+
/** Reset the singleton — only for test cleanup. */
|
|
45
|
+
export const resetConversionDestinations = singleton.reset;
|
|
46
|
+
|
|
47
|
+
/** Deterministic dedup id — stable across retries AND re-evaluations. */
|
|
48
|
+
export function conversionEventId(opts: {
|
|
49
|
+
contactId: string;
|
|
50
|
+
definitionId: string;
|
|
51
|
+
eventRowId: string;
|
|
52
|
+
}): string {
|
|
53
|
+
return createHash("sha256")
|
|
54
|
+
.update(`${opts.contactId}:${opts.definitionId}:${opts.eventRowId}`)
|
|
55
|
+
.digest("hex");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Create the dispatch rows for a fired conversion (idempotent) and return the
|
|
60
|
+
* ids that were FRESHLY created (the caller enqueues the task for those).
|
|
61
|
+
*/
|
|
62
|
+
export async function createConversionDispatches(opts: {
|
|
63
|
+
db: Database;
|
|
64
|
+
conversionId: string;
|
|
65
|
+
eventId: string;
|
|
66
|
+
destinationIds: string[];
|
|
67
|
+
}): Promise<string[]> {
|
|
68
|
+
const { db, conversionId, eventId, destinationIds } = opts;
|
|
69
|
+
if (destinationIds.length === 0) return [];
|
|
70
|
+
const inserted = await db
|
|
71
|
+
.insert(conversionDispatches)
|
|
72
|
+
.values(
|
|
73
|
+
destinationIds.map((destinationId) => ({
|
|
74
|
+
conversionId,
|
|
75
|
+
destinationId,
|
|
76
|
+
eventId,
|
|
77
|
+
})),
|
|
78
|
+
)
|
|
79
|
+
.onConflictDoNothing({
|
|
80
|
+
target: [
|
|
81
|
+
conversionDispatches.destinationId,
|
|
82
|
+
conversionDispatches.eventId,
|
|
83
|
+
],
|
|
84
|
+
})
|
|
85
|
+
.returning({ id: conversionDispatches.id });
|
|
86
|
+
return inserted.map((row) => row.id);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Recover the contact's click context: the most recent `campaign.arrived`
|
|
91
|
+
* touchpoint at-or-before the conversion carrying at least one allowlisted
|
|
92
|
+
* click ID. A later click-ID-less arrival (a `utm_*`-only newsletter landing)
|
|
93
|
+
* must not shadow a real ad click, so we scan back past it; only when NO
|
|
94
|
+
* arrival carries a click ID does the latest one stand (for `landingPage`).
|
|
95
|
+
* The chosen arrival's `occurredAt` doubles as the click timestamp (`fbc`
|
|
96
|
+
* needs the real one).
|
|
97
|
+
*/
|
|
98
|
+
export async function recoverClickContext(opts: {
|
|
99
|
+
db: Database;
|
|
100
|
+
userKey: string;
|
|
101
|
+
before: Date;
|
|
102
|
+
}): Promise<ConversionDispatchInput["clicks"]> {
|
|
103
|
+
const rows = await opts.db
|
|
104
|
+
.select({
|
|
105
|
+
properties: userEvents.properties,
|
|
106
|
+
occurredAt: userEvents.occurredAt,
|
|
107
|
+
})
|
|
108
|
+
.from(userEvents)
|
|
109
|
+
.where(
|
|
110
|
+
and(
|
|
111
|
+
eq(userEvents.userId, opts.userKey),
|
|
112
|
+
eq(userEvents.event, "campaign.arrived"),
|
|
113
|
+
lte(userEvents.occurredAt, opts.before),
|
|
114
|
+
),
|
|
115
|
+
)
|
|
116
|
+
.orderBy(desc(userEvents.occurredAt))
|
|
117
|
+
.limit(25);
|
|
118
|
+
if (rows.length === 0) return { clickIds: {} };
|
|
119
|
+
|
|
120
|
+
const extractClickIds = (row: (typeof rows)[number]) => {
|
|
121
|
+
const properties = (row.properties ?? {}) as Record<string, unknown>;
|
|
122
|
+
const clickIds: Record<string, string> = {};
|
|
123
|
+
for (const param of CLICK_ID_PARAM_NAMES) {
|
|
124
|
+
const value = properties[param];
|
|
125
|
+
if (typeof value === "string" && value) clickIds[param] = value;
|
|
126
|
+
}
|
|
127
|
+
return clickIds;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
let chosen = rows[0] as (typeof rows)[number];
|
|
131
|
+
let clickIds = extractClickIds(chosen);
|
|
132
|
+
if (Object.keys(clickIds).length === 0) {
|
|
133
|
+
for (const row of rows.slice(1)) {
|
|
134
|
+
const candidate = extractClickIds(row);
|
|
135
|
+
if (Object.keys(candidate).length > 0) {
|
|
136
|
+
chosen = row;
|
|
137
|
+
clickIds = candidate;
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const landingPage = (chosen.properties as Record<string, unknown> | null)
|
|
144
|
+
?.landing_page;
|
|
145
|
+
return {
|
|
146
|
+
clickIds,
|
|
147
|
+
clickAt: chosen.occurredAt.getTime(),
|
|
148
|
+
...(typeof landingPage === "string" ? { landingPage } : {}),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Deliver ONE dispatch row: load, enrich, send, record. Called by the durable
|
|
154
|
+
* task (which owns retry/backoff); a throw here signals Hatchet to retry.
|
|
155
|
+
* `maxAttempts` marks the row failed instead of throwing once exhausted.
|
|
156
|
+
*/
|
|
157
|
+
export async function deliverConversionDispatch(opts: {
|
|
158
|
+
db: Database;
|
|
159
|
+
logger: Logger;
|
|
160
|
+
dispatchId: string;
|
|
161
|
+
registry?: ConversionDestinationRegistry;
|
|
162
|
+
maxAttempts?: number;
|
|
163
|
+
}): Promise<{ status: "delivered" | "failed" | "skipped" }> {
|
|
164
|
+
const { db, logger, dispatchId } = opts;
|
|
165
|
+
const registry = opts.registry ?? getConversionDestinations();
|
|
166
|
+
const maxAttempts = opts.maxAttempts ?? 5;
|
|
167
|
+
|
|
168
|
+
const rows = await db
|
|
169
|
+
.select({
|
|
170
|
+
dispatch: conversionDispatches,
|
|
171
|
+
conversion: conversions,
|
|
172
|
+
contact: contacts,
|
|
173
|
+
})
|
|
174
|
+
.from(conversionDispatches)
|
|
175
|
+
.innerJoin(
|
|
176
|
+
conversions,
|
|
177
|
+
eq(conversionDispatches.conversionId, conversions.id),
|
|
178
|
+
)
|
|
179
|
+
.innerJoin(contacts, eq(conversions.contactId, contacts.id))
|
|
180
|
+
.where(
|
|
181
|
+
and(
|
|
182
|
+
eq(conversionDispatches.id, dispatchId),
|
|
183
|
+
inArray(conversionDispatches.status, ["pending"]),
|
|
184
|
+
),
|
|
185
|
+
)
|
|
186
|
+
.limit(1);
|
|
187
|
+
const row = rows[0];
|
|
188
|
+
if (!row) return { status: "skipped" };
|
|
189
|
+
|
|
190
|
+
const destination = registry?.get(row.dispatch.destinationId);
|
|
191
|
+
if (!destination) {
|
|
192
|
+
await db
|
|
193
|
+
.update(conversionDispatches)
|
|
194
|
+
.set({ status: "failed", lastError: "destination not registered" })
|
|
195
|
+
.where(eq(conversionDispatches.id, dispatchId));
|
|
196
|
+
logger.warn("conversion dispatch: destination not registered", {
|
|
197
|
+
destinationId: row.dispatch.destinationId,
|
|
198
|
+
});
|
|
199
|
+
return { status: "failed" };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Need the triggering event's name for platform event mapping.
|
|
203
|
+
const eventRows = await db
|
|
204
|
+
.select({ event: userEvents.event })
|
|
205
|
+
.from(userEvents)
|
|
206
|
+
.where(eq(userEvents.id, row.conversion.eventId))
|
|
207
|
+
.limit(1);
|
|
208
|
+
|
|
209
|
+
const clicks = await recoverClickContext({
|
|
210
|
+
db,
|
|
211
|
+
userKey: row.conversion.userKey,
|
|
212
|
+
before: row.conversion.occurredAt,
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
const input: ConversionDispatchInput = {
|
|
216
|
+
eventId: row.dispatch.eventId,
|
|
217
|
+
definitionId: row.conversion.definitionId,
|
|
218
|
+
triggerEvent: eventRows[0]?.event ?? "",
|
|
219
|
+
value: row.conversion.value,
|
|
220
|
+
currency: row.conversion.currency,
|
|
221
|
+
occurredAt: row.conversion.occurredAt.getTime(),
|
|
222
|
+
contact: {
|
|
223
|
+
...(row.contact.email ? { email: row.contact.email } : {}),
|
|
224
|
+
...(row.contact.externalId ? { externalId: row.contact.externalId } : {}),
|
|
225
|
+
...(row.contact.anonymousId
|
|
226
|
+
? { anonymousId: row.contact.anonymousId }
|
|
227
|
+
: {}),
|
|
228
|
+
...(typeof row.contact.properties?.phone === "string"
|
|
229
|
+
? { phone: row.contact.properties.phone }
|
|
230
|
+
: {}),
|
|
231
|
+
},
|
|
232
|
+
clicks,
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
const attempt = row.dispatch.attempts + 1;
|
|
236
|
+
try {
|
|
237
|
+
const result = await destination.send(input);
|
|
238
|
+
await db
|
|
239
|
+
.update(conversionDispatches)
|
|
240
|
+
.set({
|
|
241
|
+
status: "delivered",
|
|
242
|
+
attempts: attempt,
|
|
243
|
+
response: result.response ?? null,
|
|
244
|
+
lastError: null,
|
|
245
|
+
deliveredAt: new Date(),
|
|
246
|
+
})
|
|
247
|
+
.where(eq(conversionDispatches.id, dispatchId));
|
|
248
|
+
logger.info("conversion dispatched", {
|
|
249
|
+
destination: destination.meta.id,
|
|
250
|
+
definition: row.conversion.definitionId,
|
|
251
|
+
value: row.conversion.value,
|
|
252
|
+
});
|
|
253
|
+
return { status: "delivered" };
|
|
254
|
+
} catch (err) {
|
|
255
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
256
|
+
const exhausted = attempt >= maxAttempts;
|
|
257
|
+
await db
|
|
258
|
+
.update(conversionDispatches)
|
|
259
|
+
.set({
|
|
260
|
+
attempts: attempt,
|
|
261
|
+
lastError: message,
|
|
262
|
+
...(exhausted ? { status: "failed" as const } : {}),
|
|
263
|
+
})
|
|
264
|
+
.where(eq(conversionDispatches.id, dispatchId));
|
|
265
|
+
logger.warn("conversion dispatch attempt failed", {
|
|
266
|
+
destination: destination.meta.id,
|
|
267
|
+
attempt,
|
|
268
|
+
exhausted,
|
|
269
|
+
error: message,
|
|
270
|
+
});
|
|
271
|
+
if (exhausted) return { status: "failed" };
|
|
272
|
+
throw err; // let the durable task retry
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Narrow structural type so the ingest hook can enqueue without importing the
|
|
277
|
+
// full Hatchet client type.
|
|
278
|
+
export interface ConversionDispatchTask {
|
|
279
|
+
runNoWait(input: { dispatchId: string }): unknown;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// The durable task reference, set by `createHogsendClient` (the composition
|
|
283
|
+
// root imports the workflow module; this lib cannot — it would cycle).
|
|
284
|
+
// Deliberately UNSET when the container runs with a hatchet override (tests):
|
|
285
|
+
// dispatch rows stay pending and tests drive delivery directly.
|
|
286
|
+
const taskSingleton = createOptionalSingleton<ConversionDispatchTask>();
|
|
287
|
+
export const setConversionDispatchTask = taskSingleton.set;
|
|
288
|
+
export const getConversionDispatchTask = taskSingleton.get;
|
|
289
|
+
/** Reset the singleton — only for test cleanup. */
|
|
290
|
+
export const resetConversionDispatchTask = taskSingleton.reset;
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Ingest-side fan-out: create dispatch rows for a fired conversion and
|
|
294
|
+
* enqueue the durable task for each fresh row. Best-effort — the conversion
|
|
295
|
+
* row is already durable; a failed enqueue is retriable via the row's
|
|
296
|
+
* pending status (a future reaper can re-drive).
|
|
297
|
+
*/
|
|
298
|
+
export async function enqueueConversionDispatches(opts: {
|
|
299
|
+
db: Database;
|
|
300
|
+
logger: Logger;
|
|
301
|
+
task?: ConversionDispatchTask;
|
|
302
|
+
conversionId: string;
|
|
303
|
+
eventId: string;
|
|
304
|
+
destinationIds: string[];
|
|
305
|
+
}): Promise<void> {
|
|
306
|
+
const task = opts.task ?? getConversionDispatchTask();
|
|
307
|
+
const created = await createConversionDispatches({
|
|
308
|
+
db: opts.db,
|
|
309
|
+
conversionId: opts.conversionId,
|
|
310
|
+
eventId: opts.eventId,
|
|
311
|
+
destinationIds: opts.destinationIds,
|
|
312
|
+
});
|
|
313
|
+
for (const dispatchId of created) {
|
|
314
|
+
try {
|
|
315
|
+
await task?.runNoWait({ dispatchId });
|
|
316
|
+
} catch (err) {
|
|
317
|
+
opts.logger.warn(
|
|
318
|
+
"conversion dispatch enqueue failed (row stays pending)",
|
|
319
|
+
{
|
|
320
|
+
dispatchId,
|
|
321
|
+
error: err instanceof Error ? err.message : String(err),
|
|
322
|
+
},
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import type { DefinedConversion } from "@hogsend/core";
|
|
2
|
+
import {
|
|
3
|
+
conversionSourceAllowed,
|
|
4
|
+
defineConversion,
|
|
5
|
+
evaluatePropertyConditions,
|
|
6
|
+
overlayEventMoney,
|
|
7
|
+
resolveConversionValue,
|
|
8
|
+
} from "@hogsend/core";
|
|
9
|
+
import { conversions, type Database } from "@hogsend/db";
|
|
10
|
+
import type { Logger } from "./logger.js";
|
|
11
|
+
import { REVENUE_EXCLUDED_EVENTS } from "./revenue.js";
|
|
12
|
+
import { createOptionalSingleton } from "./singleton.js";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Conversion evaluation at ingest (docs/revenue-attribution-plan.md §5.1) —
|
|
16
|
+
* the hook `ingestEvent` calls after a FRESH event insert. Definitions are
|
|
17
|
+
* code-first (`createHogsendClient({ conversions })`); a fired instance is
|
|
18
|
+
* recorded once per (definition, event row) — the unique index makes a
|
|
19
|
+
* replayed evaluation a no-op, so this inherits the spine's idempotency.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export interface FiredConversion {
|
|
23
|
+
conversionId: string;
|
|
24
|
+
definition: DefinedConversion;
|
|
25
|
+
value: number | null;
|
|
26
|
+
currency: string | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Registry: definitions indexed by trigger event name. `trigger.event: "*"`
|
|
31
|
+
* is a WILDCARD (impact plan §5.2): the definition is a candidate for EVERY
|
|
32
|
+
* ingested event, narrowed only by its `where`/`sources` gates — how the
|
|
33
|
+
* built-in zero-config `revenue` conversion matches any trusted valued
|
|
34
|
+
* event without naming it.
|
|
35
|
+
*/
|
|
36
|
+
export class ConversionRegistry {
|
|
37
|
+
private byEvent = new Map<string, DefinedConversion[]>();
|
|
38
|
+
private wildcard: DefinedConversion[] = [];
|
|
39
|
+
private all: DefinedConversion[] = [];
|
|
40
|
+
|
|
41
|
+
constructor(definitions: DefinedConversion[] = []) {
|
|
42
|
+
for (const def of definitions) {
|
|
43
|
+
if (def.meta.trigger.event === "*") {
|
|
44
|
+
this.wildcard.push(def);
|
|
45
|
+
} else {
|
|
46
|
+
const list = this.byEvent.get(def.meta.trigger.event) ?? [];
|
|
47
|
+
list.push(def);
|
|
48
|
+
this.byEvent.set(def.meta.trigger.event, list);
|
|
49
|
+
}
|
|
50
|
+
this.all.push(def);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
forEvent(event: string): DefinedConversion[] {
|
|
55
|
+
const named = this.byEvent.get(event);
|
|
56
|
+
if (this.wildcard.length === 0) return named ?? [];
|
|
57
|
+
return [...(named ?? []), ...this.wildcard];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
getAll(): DefinedConversion[] {
|
|
61
|
+
return [...this.all];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
count(): number {
|
|
65
|
+
return this.all.length;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const singleton = createOptionalSingleton<ConversionRegistry>();
|
|
70
|
+
export const setConversionRegistry = singleton.set;
|
|
71
|
+
export const getConversionRegistry = singleton.get;
|
|
72
|
+
/** Reset the singleton — only for test cleanup. */
|
|
73
|
+
export const resetConversionRegistry = singleton.reset;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The built-in zero-config revenue conversion (impact plan §5.2): any
|
|
77
|
+
* TRUSTED valued event fires it — a fresh adopter who points one Stripe /
|
|
78
|
+
* order webhook at a source sees the Impact tab populate with no
|
|
79
|
+
* configuration. Seeded by `createHogsendClient` unless the consumer
|
|
80
|
+
* authors their own `id: "revenue"` definition or sets
|
|
81
|
+
* `HOGSEND_DEFAULT_REVENUE_CONVERSION=false`.
|
|
82
|
+
*
|
|
83
|
+
* Guards, matching the revenue-rollup semantics (lib/revenue.ts):
|
|
84
|
+
* - `value > 0` — valueless events never fire it;
|
|
85
|
+
* - quote-shaped events excluded (`crm.stage_changed` re-carries a deal's
|
|
86
|
+
* value on every change; a quote is unrealized money) — only
|
|
87
|
+
* `crm.deal_sold` and genuine order/subscription events count;
|
|
88
|
+
* - browser (`inapp`) events excluded by the default `sources` gate
|
|
89
|
+
* (forged-value guard).
|
|
90
|
+
*/
|
|
91
|
+
export const defaultRevenueConversion: DefinedConversion = defineConversion({
|
|
92
|
+
id: "revenue",
|
|
93
|
+
name: "Revenue",
|
|
94
|
+
description:
|
|
95
|
+
'Built-in: any trusted valued event (orders, subscriptions, crm.deal_sold). Author your own id:"revenue" definition to replace it.',
|
|
96
|
+
trigger: {
|
|
97
|
+
event: "*",
|
|
98
|
+
where: [
|
|
99
|
+
{ type: "property", property: "value", operator: "gt", value: 0 },
|
|
100
|
+
...REVENUE_EXCLUDED_EVENTS.map((event) => ({
|
|
101
|
+
type: "property" as const,
|
|
102
|
+
property: "event",
|
|
103
|
+
operator: "neq" as const,
|
|
104
|
+
value: event,
|
|
105
|
+
})),
|
|
106
|
+
],
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
export async function evaluateConversionsAtIngest(opts: {
|
|
111
|
+
db: Database;
|
|
112
|
+
logger: Logger;
|
|
113
|
+
registry: ConversionRegistry | undefined;
|
|
114
|
+
event: {
|
|
115
|
+
name: string;
|
|
116
|
+
source: string | null;
|
|
117
|
+
properties: Record<string, unknown>;
|
|
118
|
+
value: number | null;
|
|
119
|
+
currency: string | null;
|
|
120
|
+
occurredAt: Date;
|
|
121
|
+
};
|
|
122
|
+
eventRowId: string;
|
|
123
|
+
contactId: string;
|
|
124
|
+
userKey: string;
|
|
125
|
+
}): Promise<FiredConversion[]> {
|
|
126
|
+
const { db, logger, registry, event, eventRowId, contactId, userKey } = opts;
|
|
127
|
+
if (!registry) return [];
|
|
128
|
+
const candidates = registry.forEvent(event.name);
|
|
129
|
+
if (candidates.length === 0) return [];
|
|
130
|
+
|
|
131
|
+
const fired: FiredConversion[] = [];
|
|
132
|
+
for (const def of candidates) {
|
|
133
|
+
if (!conversionSourceAllowed(def, event.source)) {
|
|
134
|
+
logger.debug("conversion skipped: source not allowed", {
|
|
135
|
+
definition: def.meta.id,
|
|
136
|
+
source: event.source,
|
|
137
|
+
});
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
// `where` sees the event's first-class value/currency (overlayEventMoney)
|
|
141
|
+
// AND the event NAME as `event` — lets wildcard definitions carve out
|
|
142
|
+
// exclusions, e.g. the built-in revenue conversion skipping quote
|
|
143
|
+
// events. The injected keys win a name collision.
|
|
144
|
+
if (
|
|
145
|
+
def.where &&
|
|
146
|
+
!evaluatePropertyConditions({
|
|
147
|
+
conditions: def.where,
|
|
148
|
+
properties: {
|
|
149
|
+
...overlayEventMoney(event.properties, event.value, event.currency),
|
|
150
|
+
event: event.name,
|
|
151
|
+
},
|
|
152
|
+
})
|
|
153
|
+
) {
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const { value, currency } = resolveConversionValue(def, {
|
|
158
|
+
value: event.value,
|
|
159
|
+
currency: event.currency,
|
|
160
|
+
properties: event.properties,
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
const inserted = await db
|
|
164
|
+
.insert(conversions)
|
|
165
|
+
.values({
|
|
166
|
+
definitionId: def.meta.id,
|
|
167
|
+
contactId,
|
|
168
|
+
userKey,
|
|
169
|
+
eventId: eventRowId,
|
|
170
|
+
value,
|
|
171
|
+
currency,
|
|
172
|
+
scopeJourneyId: def.meta.scope?.journeyId ?? null,
|
|
173
|
+
scopeCampaignId: def.meta.scope?.campaignId ?? null,
|
|
174
|
+
occurredAt: event.occurredAt,
|
|
175
|
+
})
|
|
176
|
+
.onConflictDoNothing({
|
|
177
|
+
target: [conversions.definitionId, conversions.eventId],
|
|
178
|
+
})
|
|
179
|
+
.returning({ id: conversions.id });
|
|
180
|
+
|
|
181
|
+
if (inserted[0]) {
|
|
182
|
+
fired.push({
|
|
183
|
+
conversionId: inserted[0].id,
|
|
184
|
+
definition: def,
|
|
185
|
+
value,
|
|
186
|
+
currency,
|
|
187
|
+
});
|
|
188
|
+
logger.info("conversion fired", {
|
|
189
|
+
definition: def.meta.id,
|
|
190
|
+
value,
|
|
191
|
+
currency,
|
|
192
|
+
userKey,
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return fired;
|
|
197
|
+
}
|