@hogsend/engine 0.65.0 → 0.67.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 -12
- package/src/account-links/battlenet.ts +84 -0
- package/src/account-links/epic.ts +87 -0
- package/src/account-links/index.ts +12 -5
- package/src/account-links/riot.ts +82 -0
- package/src/account-links/xbox.ts +92 -0
- package/src/app.ts +9 -1
- package/src/container.ts +77 -0
- package/src/env.ts +18 -2
- package/src/index.ts +84 -0
- package/src/lib/account-links-from-env.ts +94 -30
- package/src/lib/contacts.ts +94 -2
- package/src/lib/ingestion.ts +61 -0
- package/src/lib/links.ts +94 -11
- package/src/lib/outbound.ts +94 -0
- package/src/lib/referral-intent.ts +723 -0
- package/src/lib/referral-link.ts +200 -0
- package/src/lib/referral-registry.ts +83 -0
- package/src/lib/referral-report.ts +739 -0
- package/src/lib/referral-runtime.ts +49 -0
- package/src/lib/referrals-no-emit.test.ts +109 -0
- package/src/lib/referrals.ts +712 -0
- package/src/lib/snippet.ts +76 -0
- package/src/lib/webhook-signing.ts +10 -0
- package/src/routes/admin/api-keys.ts +5 -0
- package/src/routes/admin/index.ts +2 -0
- package/src/routes/admin/links.ts +14 -5
- package/src/routes/admin/referrals.ts +565 -0
- package/src/routes/contacts/index.ts +78 -0
- package/src/routes/index.ts +45 -0
- package/src/routes/referrals/index.ts +41 -0
- package/src/routes/referrals/me.ts +123 -0
- package/src/routes/referrals/report.ts +285 -0
- package/src/routes/referrals/shared.ts +34 -0
- package/src/routes/referrals/touch.ts +313 -0
- package/src/routes/snippet.test.ts +70 -0
- package/src/routes/snippet.ts +58 -0
- package/src/routes/tracking/arrive.ts +90 -0
- package/src/routes/tracking/click-pipeline.ts +8 -0
- package/src/workflows/import-contacts.ts +6 -0
|
@@ -0,0 +1,565 @@
|
|
|
1
|
+
import { type DefinedReferral, durationToMs } from "@hogsend/core";
|
|
2
|
+
import type { Database } from "@hogsend/db";
|
|
3
|
+
import { contacts, links, referralTouches, trackedLinks } from "@hogsend/db";
|
|
4
|
+
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
|
|
5
|
+
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
|
|
6
|
+
import type { AppEnv } from "../../app.js";
|
|
7
|
+
import { canonicalTrackedRowFilter, vanityUrlFor } from "../../lib/links.js";
|
|
8
|
+
import {
|
|
9
|
+
getReferralOverview,
|
|
10
|
+
getReferralReport,
|
|
11
|
+
getReferralTree,
|
|
12
|
+
InvalidWindowError,
|
|
13
|
+
parseWindowMs,
|
|
14
|
+
REFERRAL_MODELS,
|
|
15
|
+
REFERRAL_REPORT_MAX_DEPTH,
|
|
16
|
+
resolveLevelWeights,
|
|
17
|
+
} from "../../lib/referral-report.js";
|
|
18
|
+
import { resolveNamedContactId } from "../referrals/shared.js";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Read-only admin surface over the referral ledger - the two endpoints the
|
|
22
|
+
* Studio OBSERVE views consume. It adds no reporting semantics of its own: the
|
|
23
|
+
* leaderboard is `getReferralReport()` and the drill-in is `getReferralTree()`,
|
|
24
|
+
* the same functions `/v1/referrals/report` and `/v1/referrals/tree/:id` call,
|
|
25
|
+
* so an operator and an API caller can never read two different numbers.
|
|
26
|
+
*
|
|
27
|
+
* What it DOES add is contact identity (email / external id), which the data
|
|
28
|
+
* plane deliberately omits: `/v1/referrals/*` answers in contact ids because it
|
|
29
|
+
* is machine-facing, while a leaderboard a human reads needs a name. The
|
|
30
|
+
* router inherits `requireAdmin` from the admin router, so it never re-auths.
|
|
31
|
+
*
|
|
32
|
+
* Model, depth, window and weights stay REQUEST parameters here too (PRD 05
|
|
33
|
+
* §5.3). The Studio picker just re-queries; nothing is persisted per model.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
const DEFAULT_WINDOW = "30d";
|
|
37
|
+
const DEFAULT_TREE_DEPTH = 3;
|
|
38
|
+
const MAX_TREE_NODES = 1000;
|
|
39
|
+
|
|
40
|
+
const currencyValueSchema = z.object({
|
|
41
|
+
currency: z.string(),
|
|
42
|
+
value: z.number(),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const contactSchema = z.object({
|
|
46
|
+
id: z.string(),
|
|
47
|
+
email: z.string().nullable(),
|
|
48
|
+
externalId: z.string().nullable(),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const errorSchema = z.object({ error: z.string() });
|
|
52
|
+
|
|
53
|
+
const beneficiarySchema = z.object({
|
|
54
|
+
contactId: z.string(),
|
|
55
|
+
contact: contactSchema.nullable(),
|
|
56
|
+
direct: z.object({
|
|
57
|
+
touched: z.number(),
|
|
58
|
+
bound: z.number(),
|
|
59
|
+
qualified: z.number(),
|
|
60
|
+
}),
|
|
61
|
+
tree: z.array(
|
|
62
|
+
z.object({
|
|
63
|
+
level: z.number(),
|
|
64
|
+
referees: z.number(),
|
|
65
|
+
conversions: z.number(),
|
|
66
|
+
value: z.array(currencyValueSchema),
|
|
67
|
+
}),
|
|
68
|
+
),
|
|
69
|
+
value: z.array(currencyValueSchema),
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
const treeNodeSchema = z.object({
|
|
73
|
+
contactId: z.string(),
|
|
74
|
+
contact: contactSchema.nullable(),
|
|
75
|
+
level: z.number(),
|
|
76
|
+
viaContactId: z.string(),
|
|
77
|
+
status: z.string(),
|
|
78
|
+
touchedAt: z.string(),
|
|
79
|
+
boundAt: z.string().nullable(),
|
|
80
|
+
qualifiedAt: z.string().nullable(),
|
|
81
|
+
conversions: z.number(),
|
|
82
|
+
value: z.array(currencyValueSchema),
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
const touchSchema = z.object({
|
|
86
|
+
id: z.string(),
|
|
87
|
+
referralId: z.string(),
|
|
88
|
+
refereeKey: z.string(),
|
|
89
|
+
refereeContactId: z.string().nullable(),
|
|
90
|
+
referee: contactSchema.nullable(),
|
|
91
|
+
source: z.string(),
|
|
92
|
+
status: z.string(),
|
|
93
|
+
rejectedReason: z.string().nullable(),
|
|
94
|
+
touchedAt: z.string(),
|
|
95
|
+
boundAt: z.string().nullable(),
|
|
96
|
+
qualifiedAt: z.string().nullable(),
|
|
97
|
+
linkId: z.string().nullable(),
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const definitionSchema = z.object({
|
|
101
|
+
id: z.string(),
|
|
102
|
+
name: z.string().nullable(),
|
|
103
|
+
description: z.string().nullable(),
|
|
104
|
+
/** The qualify event, or null when bind IS qualify. */
|
|
105
|
+
qualifyEvent: z.string().nullable(),
|
|
106
|
+
qualifyHasConditions: z.boolean(),
|
|
107
|
+
bindWindowMs: z.number(),
|
|
108
|
+
/** A fixed destination URL, or null when it is computed per referrer. */
|
|
109
|
+
destination: z.string().nullable(),
|
|
110
|
+
campaign: z.string().nullable(),
|
|
111
|
+
hooks: z.array(z.string()),
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
const currencyValueList = z.array(currencyValueSchema);
|
|
115
|
+
|
|
116
|
+
const overviewSchema = z.object({
|
|
117
|
+
referral: z.string(),
|
|
118
|
+
referrals: z.array(z.string()),
|
|
119
|
+
/** Null when the ledger holds a referral id no longer authored in code. */
|
|
120
|
+
definition: definitionSchema.nullable(),
|
|
121
|
+
from: z.string().nullable(),
|
|
122
|
+
to: z.string().nullable(),
|
|
123
|
+
referrers: z.number(),
|
|
124
|
+
links: z.number(),
|
|
125
|
+
funnel: z.object({
|
|
126
|
+
touched: z.number(),
|
|
127
|
+
bound: z.number(),
|
|
128
|
+
qualified: z.number(),
|
|
129
|
+
converted: z.number(),
|
|
130
|
+
}),
|
|
131
|
+
rejected: z.object({
|
|
132
|
+
total: z.number(),
|
|
133
|
+
byReason: z.array(z.object({ reason: z.string(), count: z.number() })),
|
|
134
|
+
}),
|
|
135
|
+
sources: z.array(z.object({ source: z.string(), count: z.number() })),
|
|
136
|
+
refereeValue: currencyValueList,
|
|
137
|
+
granularity: z.enum(["day", "week"]),
|
|
138
|
+
series: z.array(
|
|
139
|
+
z.object({
|
|
140
|
+
date: z.string(),
|
|
141
|
+
touched: z.number(),
|
|
142
|
+
bound: z.number(),
|
|
143
|
+
qualified: z.number(),
|
|
144
|
+
}),
|
|
145
|
+
),
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
const referrerLinkSchema = z.object({
|
|
149
|
+
id: z.string(),
|
|
150
|
+
slug: z.string().nullable(),
|
|
151
|
+
vanityUrl: z.string().nullable(),
|
|
152
|
+
url: z.string(),
|
|
153
|
+
originalUrl: z.string(),
|
|
154
|
+
campaign: z.string().nullable(),
|
|
155
|
+
clickCount: z.number(),
|
|
156
|
+
createdAt: z.string(),
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
/** What of a `defineReferral` an operator can read back. No functions cross. */
|
|
160
|
+
function serializeDefinition(
|
|
161
|
+
def: DefinedReferral,
|
|
162
|
+
): z.infer<typeof definitionSchema> {
|
|
163
|
+
const hooks = (
|
|
164
|
+
["beforeTouch", "beforeBind", "beforeQualify"] as const
|
|
165
|
+
).filter((h) => typeof def.meta[h] === "function");
|
|
166
|
+
return {
|
|
167
|
+
id: def.id,
|
|
168
|
+
name: def.meta.name ?? null,
|
|
169
|
+
description: def.meta.description ?? null,
|
|
170
|
+
qualifyEvent: def.meta.qualify?.event ?? null,
|
|
171
|
+
qualifyHasConditions: (def.qualifyWhere?.length ?? 0) > 0,
|
|
172
|
+
bindWindowMs: durationToMs(def.bindWindow),
|
|
173
|
+
destination:
|
|
174
|
+
typeof def.meta.link.destination === "string"
|
|
175
|
+
? def.meta.link.destination
|
|
176
|
+
: null,
|
|
177
|
+
campaign: def.meta.link.campaign ?? null,
|
|
178
|
+
hooks,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** `"1,0.5,0.25"` -> `[1, 0.5, 0.25]`. Throws on anything else. */
|
|
183
|
+
function parseWeights(input: string | undefined, depth: number): number[] {
|
|
184
|
+
if (!input) return [];
|
|
185
|
+
const parts = input.split(",").map((p) => p.trim());
|
|
186
|
+
if (parts.length > depth) {
|
|
187
|
+
throw new RangeError(
|
|
188
|
+
`weights has ${parts.length} entries but depth is ${depth}`,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
return parts.map((part) => {
|
|
192
|
+
const value = Number(part);
|
|
193
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
194
|
+
throw new RangeError(`weight "${part}" is not a non-negative number`);
|
|
195
|
+
}
|
|
196
|
+
return value;
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function parseDate(input: string | undefined, label: string): Date | undefined {
|
|
201
|
+
if (!input) return undefined;
|
|
202
|
+
const date = new Date(input);
|
|
203
|
+
if (Number.isNaN(date.getTime())) {
|
|
204
|
+
throw new RangeError(`invalid ${label} date "${input}"`);
|
|
205
|
+
}
|
|
206
|
+
return date;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Identity for a set of contact ids, so a leaderboard can show a name. */
|
|
210
|
+
async function contactsById(
|
|
211
|
+
db: Database,
|
|
212
|
+
ids: string[],
|
|
213
|
+
): Promise<Map<string, z.infer<typeof contactSchema>>> {
|
|
214
|
+
const unique = [...new Set(ids)];
|
|
215
|
+
if (unique.length === 0) return new Map();
|
|
216
|
+
const rows = await db
|
|
217
|
+
.select({
|
|
218
|
+
id: contacts.id,
|
|
219
|
+
email: contacts.email,
|
|
220
|
+
externalId: contacts.externalId,
|
|
221
|
+
})
|
|
222
|
+
.from(contacts)
|
|
223
|
+
.where(inArray(contacts.id, unique));
|
|
224
|
+
return new Map(rows.map((r) => [r.id, r]));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const listRoute = createRoute({
|
|
228
|
+
method: "get",
|
|
229
|
+
path: "/",
|
|
230
|
+
tags: ["Admin — Referrals"],
|
|
231
|
+
summary: "Referral leaderboard",
|
|
232
|
+
request: {
|
|
233
|
+
query: z.object({
|
|
234
|
+
referral: z.string().min(1).optional(),
|
|
235
|
+
model: z.enum(REFERRAL_MODELS).default("first_touch"),
|
|
236
|
+
window: z.string().default(DEFAULT_WINDOW),
|
|
237
|
+
depth: z.coerce
|
|
238
|
+
.number()
|
|
239
|
+
.int()
|
|
240
|
+
.min(1)
|
|
241
|
+
.max(REFERRAL_REPORT_MAX_DEPTH)
|
|
242
|
+
.default(1),
|
|
243
|
+
weights: z.string().optional(),
|
|
244
|
+
from: z.string().optional(),
|
|
245
|
+
to: z.string().optional(),
|
|
246
|
+
limit: z.coerce.number().int().min(1).max(100).default(50),
|
|
247
|
+
offset: z.coerce.number().int().min(0).default(0),
|
|
248
|
+
}),
|
|
249
|
+
},
|
|
250
|
+
responses: {
|
|
251
|
+
200: {
|
|
252
|
+
content: {
|
|
253
|
+
"application/json": {
|
|
254
|
+
schema: z.object({
|
|
255
|
+
referral: z.string(),
|
|
256
|
+
referrals: z.array(z.string()),
|
|
257
|
+
model: z.enum(REFERRAL_MODELS),
|
|
258
|
+
window: z.string(),
|
|
259
|
+
depth: z.number(),
|
|
260
|
+
weights: z.array(z.number()),
|
|
261
|
+
beneficiaries: z.array(beneficiarySchema),
|
|
262
|
+
limit: z.number(),
|
|
263
|
+
offset: z.number(),
|
|
264
|
+
nextOffset: z.number().nullable(),
|
|
265
|
+
}),
|
|
266
|
+
},
|
|
267
|
+
},
|
|
268
|
+
description:
|
|
269
|
+
"Referrers ranked by tree value under the requested model, with the registered referral ids for the picker",
|
|
270
|
+
},
|
|
271
|
+
400: {
|
|
272
|
+
content: { "application/json": { schema: errorSchema } },
|
|
273
|
+
description: "Invalid window, weights or date",
|
|
274
|
+
},
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
const overviewRoute = createRoute({
|
|
279
|
+
method: "get",
|
|
280
|
+
path: "/overview",
|
|
281
|
+
tags: ["Admin — Referrals"],
|
|
282
|
+
summary: "Program overview: definition, funnel, sources, rejections, series",
|
|
283
|
+
request: {
|
|
284
|
+
query: z.object({
|
|
285
|
+
referral: z.string().min(1).optional(),
|
|
286
|
+
from: z.string().optional(),
|
|
287
|
+
to: z.string().optional(),
|
|
288
|
+
}),
|
|
289
|
+
},
|
|
290
|
+
responses: {
|
|
291
|
+
200: {
|
|
292
|
+
content: { "application/json": { schema: overviewSchema } },
|
|
293
|
+
description:
|
|
294
|
+
"Ledger counts for one referral over the period; the same from/to the leaderboard takes",
|
|
295
|
+
},
|
|
296
|
+
400: {
|
|
297
|
+
content: { "application/json": { schema: errorSchema } },
|
|
298
|
+
description: "Invalid date",
|
|
299
|
+
},
|
|
300
|
+
},
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
const detailRoute = createRoute({
|
|
304
|
+
method: "get",
|
|
305
|
+
path: "/{contactId}",
|
|
306
|
+
tags: ["Admin — Referrals"],
|
|
307
|
+
summary: "One referrer's tree and touch log",
|
|
308
|
+
request: {
|
|
309
|
+
params: z.object({ contactId: z.string().min(1) }),
|
|
310
|
+
query: z.object({
|
|
311
|
+
referral: z.string().min(1).optional(),
|
|
312
|
+
depth: z.coerce
|
|
313
|
+
.number()
|
|
314
|
+
.int()
|
|
315
|
+
.min(1)
|
|
316
|
+
.max(REFERRAL_REPORT_MAX_DEPTH)
|
|
317
|
+
.default(DEFAULT_TREE_DEPTH),
|
|
318
|
+
limit: z.coerce.number().int().min(1).max(200).default(100),
|
|
319
|
+
}),
|
|
320
|
+
},
|
|
321
|
+
responses: {
|
|
322
|
+
200: {
|
|
323
|
+
content: {
|
|
324
|
+
"application/json": {
|
|
325
|
+
schema: z.object({
|
|
326
|
+
referral: z.string(),
|
|
327
|
+
referrals: z.array(z.string()),
|
|
328
|
+
contactId: z.string(),
|
|
329
|
+
contact: contactSchema.nullable(),
|
|
330
|
+
depth: z.number(),
|
|
331
|
+
links: z.array(referrerLinkSchema),
|
|
332
|
+
nodes: z.array(treeNodeSchema),
|
|
333
|
+
touches: z.array(touchSchema),
|
|
334
|
+
}),
|
|
335
|
+
},
|
|
336
|
+
},
|
|
337
|
+
description:
|
|
338
|
+
"The descendants of this referrer plus their own touch log, including rejected touches and the reason",
|
|
339
|
+
},
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
export const adminReferralsRouter = new OpenAPIHono<AppEnv>()
|
|
344
|
+
.openapi(listRoute, async (c) => {
|
|
345
|
+
const { db, referrals } = c.get("container");
|
|
346
|
+
const query = c.req.valid("query");
|
|
347
|
+
// The registry lists the AUTHORED programs; the ledger may still hold rows
|
|
348
|
+
// for one that was deleted from code, so the picker's default is whatever
|
|
349
|
+
// the caller asked for, then the first registered id, then "default".
|
|
350
|
+
const registered = referrals.ids();
|
|
351
|
+
const referralId = query.referral ?? registered[0] ?? "default";
|
|
352
|
+
|
|
353
|
+
let windowMs: number;
|
|
354
|
+
let weights: number[];
|
|
355
|
+
let from: Date | undefined;
|
|
356
|
+
let to: Date | undefined;
|
|
357
|
+
try {
|
|
358
|
+
windowMs = parseWindowMs(query.window);
|
|
359
|
+
weights = parseWeights(query.weights, query.depth);
|
|
360
|
+
from = parseDate(query.from, "from");
|
|
361
|
+
to = parseDate(query.to, "to");
|
|
362
|
+
} catch (err) {
|
|
363
|
+
if (err instanceof InvalidWindowError || err instanceof RangeError) {
|
|
364
|
+
return c.json({ error: err.message }, 400);
|
|
365
|
+
}
|
|
366
|
+
throw err;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const levelWeights = resolveLevelWeights(query.depth, weights);
|
|
370
|
+
const report = await getReferralReport({
|
|
371
|
+
db,
|
|
372
|
+
referralId,
|
|
373
|
+
model: query.model,
|
|
374
|
+
windowMs,
|
|
375
|
+
depth: query.depth,
|
|
376
|
+
levelWeights,
|
|
377
|
+
...(from ? { from } : {}),
|
|
378
|
+
...(to ? { to } : {}),
|
|
379
|
+
limit: query.limit,
|
|
380
|
+
offset: query.offset,
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
const identity = await contactsById(
|
|
384
|
+
db,
|
|
385
|
+
report.beneficiaries.map((b) => b.contactId),
|
|
386
|
+
);
|
|
387
|
+
|
|
388
|
+
return c.json(
|
|
389
|
+
{
|
|
390
|
+
referral: referralId,
|
|
391
|
+
referrals: registered,
|
|
392
|
+
model: query.model,
|
|
393
|
+
window: query.window,
|
|
394
|
+
depth: query.depth,
|
|
395
|
+
weights: levelWeights,
|
|
396
|
+
beneficiaries: report.beneficiaries.map((b) => ({
|
|
397
|
+
...b,
|
|
398
|
+
contact: identity.get(b.contactId) ?? null,
|
|
399
|
+
})),
|
|
400
|
+
limit: query.limit,
|
|
401
|
+
offset: query.offset,
|
|
402
|
+
nextOffset: report.nextOffset,
|
|
403
|
+
},
|
|
404
|
+
200,
|
|
405
|
+
);
|
|
406
|
+
})
|
|
407
|
+
.openapi(overviewRoute, async (c) => {
|
|
408
|
+
const { db, referrals } = c.get("container");
|
|
409
|
+
const query = c.req.valid("query");
|
|
410
|
+
const registered = referrals.ids();
|
|
411
|
+
const referralId = query.referral ?? registered[0] ?? "default";
|
|
412
|
+
let from: Date | undefined;
|
|
413
|
+
let to: Date | undefined;
|
|
414
|
+
try {
|
|
415
|
+
from = parseDate(query.from, "from");
|
|
416
|
+
to = parseDate(query.to, "to");
|
|
417
|
+
} catch (err) {
|
|
418
|
+
if (err instanceof RangeError) return c.json({ error: err.message }, 400);
|
|
419
|
+
throw err;
|
|
420
|
+
}
|
|
421
|
+
const overview = await getReferralOverview({
|
|
422
|
+
db,
|
|
423
|
+
referralId,
|
|
424
|
+
...(from ? { from } : {}),
|
|
425
|
+
...(to ? { to } : {}),
|
|
426
|
+
});
|
|
427
|
+
const def = referrals.get(referralId);
|
|
428
|
+
return c.json(
|
|
429
|
+
{
|
|
430
|
+
referral: referralId,
|
|
431
|
+
referrals: registered,
|
|
432
|
+
definition: def ? serializeDefinition(def) : null,
|
|
433
|
+
from: from ? from.toISOString() : null,
|
|
434
|
+
to: to ? to.toISOString() : null,
|
|
435
|
+
...overview,
|
|
436
|
+
},
|
|
437
|
+
200,
|
|
438
|
+
);
|
|
439
|
+
})
|
|
440
|
+
.openapi(detailRoute, async (c) => {
|
|
441
|
+
const { db, env, referrals } = c.get("container");
|
|
442
|
+
const { contactId } = c.req.valid("param");
|
|
443
|
+
const query = c.req.valid("query");
|
|
444
|
+
const registered = referrals.ids();
|
|
445
|
+
const referralId = query.referral ?? registered[0] ?? "default";
|
|
446
|
+
|
|
447
|
+
// Studio addresses a referrer by contact id, but an operator pasting an
|
|
448
|
+
// external key must not 500 on a failed uuid cast. An unknown key is an
|
|
449
|
+
// empty tree, matching `/v1/referrals/tree/:contactId`.
|
|
450
|
+
const resolved = await resolveNamedContactId(db, contactId);
|
|
451
|
+
if (!resolved) {
|
|
452
|
+
return c.json(
|
|
453
|
+
{
|
|
454
|
+
referral: referralId,
|
|
455
|
+
referrals: registered,
|
|
456
|
+
contactId,
|
|
457
|
+
contact: null,
|
|
458
|
+
depth: query.depth,
|
|
459
|
+
links: [],
|
|
460
|
+
nodes: [],
|
|
461
|
+
touches: [],
|
|
462
|
+
},
|
|
463
|
+
200,
|
|
464
|
+
);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const [nodes, touchRows, linkRows] = await Promise.all([
|
|
468
|
+
getReferralTree({
|
|
469
|
+
db,
|
|
470
|
+
referralId,
|
|
471
|
+
contactId: resolved,
|
|
472
|
+
depth: query.depth,
|
|
473
|
+
limit: MAX_TREE_NODES,
|
|
474
|
+
}),
|
|
475
|
+
db
|
|
476
|
+
.select()
|
|
477
|
+
.from(referralTouches)
|
|
478
|
+
.where(
|
|
479
|
+
and(
|
|
480
|
+
eq(referralTouches.referralId, referralId),
|
|
481
|
+
eq(referralTouches.referrerContactId, resolved),
|
|
482
|
+
),
|
|
483
|
+
)
|
|
484
|
+
.orderBy(desc(referralTouches.touchedAt))
|
|
485
|
+
.limit(query.limit),
|
|
486
|
+
// The referrer's own share links: what they were given to send around.
|
|
487
|
+
db
|
|
488
|
+
.select({
|
|
489
|
+
id: links.id,
|
|
490
|
+
slug: links.slug,
|
|
491
|
+
originalUrl: links.originalUrl,
|
|
492
|
+
campaign: links.campaign,
|
|
493
|
+
createdAt: links.createdAt,
|
|
494
|
+
trackedLinkId: sql<
|
|
495
|
+
string | null
|
|
496
|
+
>`min(${trackedLinks.id}::text) filter (where ${canonicalTrackedRowFilter()})`,
|
|
497
|
+
clickCount:
|
|
498
|
+
sql<number>`coalesce(sum(${trackedLinks.clickCount}), 0)`.mapWith(
|
|
499
|
+
Number,
|
|
500
|
+
),
|
|
501
|
+
})
|
|
502
|
+
.from(links)
|
|
503
|
+
.leftJoin(trackedLinks, eq(trackedLinks.linkId, links.id))
|
|
504
|
+
.where(
|
|
505
|
+
and(
|
|
506
|
+
eq(links.referralId, referralId),
|
|
507
|
+
eq(links.ownerContactId, resolved),
|
|
508
|
+
isNull(links.archivedAt),
|
|
509
|
+
),
|
|
510
|
+
)
|
|
511
|
+
.groupBy(links.id)
|
|
512
|
+
.orderBy(desc(links.createdAt)),
|
|
513
|
+
]);
|
|
514
|
+
|
|
515
|
+
// One identity lookup covers the referrer, every tree node and every
|
|
516
|
+
// touch's referee.
|
|
517
|
+
const identity = await contactsById(db, [
|
|
518
|
+
resolved,
|
|
519
|
+
...nodes.map((n) => n.contactId),
|
|
520
|
+
...touchRows.flatMap((t) =>
|
|
521
|
+
t.refereeContactId ? [t.refereeContactId] : [],
|
|
522
|
+
),
|
|
523
|
+
]);
|
|
524
|
+
|
|
525
|
+
return c.json(
|
|
526
|
+
{
|
|
527
|
+
referral: referralId,
|
|
528
|
+
referrals: registered,
|
|
529
|
+
contactId: resolved,
|
|
530
|
+
contact: identity.get(resolved) ?? null,
|
|
531
|
+
depth: query.depth,
|
|
532
|
+
links: linkRows.map((l) => ({
|
|
533
|
+
id: l.id,
|
|
534
|
+
slug: l.slug,
|
|
535
|
+
vanityUrl: l.slug ? vanityUrlFor(env.API_PUBLIC_URL, l.slug) : null,
|
|
536
|
+
url: `${env.API_PUBLIC_URL}/v1/t/c/${l.trackedLinkId ?? ""}`,
|
|
537
|
+
originalUrl: l.originalUrl,
|
|
538
|
+
campaign: l.campaign,
|
|
539
|
+
clickCount: l.clickCount,
|
|
540
|
+
createdAt: l.createdAt.toISOString(),
|
|
541
|
+
})),
|
|
542
|
+
nodes: nodes.map((n) => ({
|
|
543
|
+
...n,
|
|
544
|
+
contact: identity.get(n.contactId) ?? null,
|
|
545
|
+
})),
|
|
546
|
+
touches: touchRows.map((t) => ({
|
|
547
|
+
id: t.id,
|
|
548
|
+
referralId: t.referralId,
|
|
549
|
+
refereeKey: t.refereeKey,
|
|
550
|
+
refereeContactId: t.refereeContactId,
|
|
551
|
+
referee: t.refereeContactId
|
|
552
|
+
? (identity.get(t.refereeContactId) ?? null)
|
|
553
|
+
: null,
|
|
554
|
+
source: t.source,
|
|
555
|
+
status: t.status,
|
|
556
|
+
rejectedReason: t.rejectedReason,
|
|
557
|
+
touchedAt: t.touchedAt.toISOString(),
|
|
558
|
+
boundAt: t.boundAt ? t.boundAt.toISOString() : null,
|
|
559
|
+
qualifiedAt: t.qualifiedAt ? t.qualifiedAt.toISOString() : null,
|
|
560
|
+
linkId: t.linkId,
|
|
561
|
+
})),
|
|
562
|
+
},
|
|
563
|
+
200,
|
|
564
|
+
);
|
|
565
|
+
});
|
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
ALL_IDENTITY_KINDS,
|
|
5
5
|
findContacts,
|
|
6
6
|
PublishableAnonymousMergeError,
|
|
7
|
+
projectPublicContact,
|
|
7
8
|
resolveContact,
|
|
8
9
|
resolveOrCreateContact,
|
|
9
10
|
serializeContact,
|
|
@@ -17,6 +18,7 @@ import {
|
|
|
17
18
|
listMembershipError,
|
|
18
19
|
requireIdentity,
|
|
19
20
|
} from "../_shared.js";
|
|
21
|
+
import { resolveFeedRecipient } from "../feed/recipient.js";
|
|
20
22
|
|
|
21
23
|
// The public, serialized contact shape (§2.5). `externalId` is nullable (D1 —
|
|
22
24
|
// email-only / anonymous contacts) and timestamps are ISO strings.
|
|
@@ -128,6 +130,58 @@ const findRoute = createRoute({
|
|
|
128
130
|
},
|
|
129
131
|
});
|
|
130
132
|
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
// GET /v1/contacts/me — the BROWSER read of the identified contact's traits
|
|
135
|
+
// (publishable OR secret-ingest tier; guarded as a LITERAL in routes/index.ts).
|
|
136
|
+
// Identity is recipient-scoped SERVER-SIDE via `resolveFeedRecipient`, the same
|
|
137
|
+
// leak boundary as `GET /v1/flags` and the in-app feed: a userToken-verified
|
|
138
|
+
// userId, a secret key's trusted userId/email, or a publishable caller's OWN
|
|
139
|
+
// anon id (a pk_ `anonymousId` colliding with an IDENTIFIED contact's canonical
|
|
140
|
+
// key is rejected 403). A request-supplied contact key is NEVER honored.
|
|
141
|
+
//
|
|
142
|
+
// What comes back is an operator ALLOWLIST projection, not the contact row: only
|
|
143
|
+
// exact `contacts.publicProperties` keys, plus `email` when `exposeEmail`. The
|
|
144
|
+
// default config is empty, so a deploy that configures nothing exposes nothing.
|
|
145
|
+
// No contact / empty allowlist answers 200 `{ identified: false, traits: {} }` —
|
|
146
|
+
// never 404, so the response does not confirm whether a contact exists.
|
|
147
|
+
// ---------------------------------------------------------------------------
|
|
148
|
+
const meQuerySchema = z.object({
|
|
149
|
+
userToken: z.string().optional(),
|
|
150
|
+
anonymousId: z.string().optional(),
|
|
151
|
+
userId: z.string().optional(),
|
|
152
|
+
email: z.string().optional(),
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
const publicContactSchema = z.object({
|
|
156
|
+
identified: z.boolean(),
|
|
157
|
+
traits: z.record(z.string(), z.unknown()),
|
|
158
|
+
email: z.string().nullable().optional(),
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
const meRoute = createRoute({
|
|
162
|
+
method: "get",
|
|
163
|
+
path: "/me",
|
|
164
|
+
tags: ["Contacts"],
|
|
165
|
+
summary: "Read the resolved recipient's public traits",
|
|
166
|
+
description:
|
|
167
|
+
"Recipient-scoped server-side. Returns only the operator-allowlisted contact properties (client option `contacts.publicProperties`), plus the email when `contacts.exposeEmail` is on. Empty allowlist or no contact returns an empty projection, never 404.",
|
|
168
|
+
request: { query: meQuerySchema },
|
|
169
|
+
responses: {
|
|
170
|
+
200: {
|
|
171
|
+
content: { "application/json": { schema: publicContactSchema } },
|
|
172
|
+
description: "The recipient's allowlisted traits",
|
|
173
|
+
},
|
|
174
|
+
400: {
|
|
175
|
+
content: { "application/json": { schema: errorSchema } },
|
|
176
|
+
description: "Missing identity",
|
|
177
|
+
},
|
|
178
|
+
403: {
|
|
179
|
+
content: { "application/json": { schema: errorSchema } },
|
|
180
|
+
description: "Invalid userToken or non-addressable anonymousId",
|
|
181
|
+
},
|
|
182
|
+
},
|
|
183
|
+
});
|
|
184
|
+
|
|
131
185
|
const deleteRoute = createRoute({
|
|
132
186
|
method: "delete",
|
|
133
187
|
path: "/",
|
|
@@ -275,6 +329,30 @@ export const contactsRouter = new OpenAPIHono<AppEnv>()
|
|
|
275
329
|
|
|
276
330
|
return c.json({ contacts: rows.map((row) => serializeContact(row)) }, 200);
|
|
277
331
|
})
|
|
332
|
+
.openapi(meRoute, async (c) => {
|
|
333
|
+
const { db, contactsConfig } = c.get("container");
|
|
334
|
+
const query = c.req.valid("query");
|
|
335
|
+
const rec = await resolveFeedRecipient(c, query);
|
|
336
|
+
if (!rec.ok) return c.json({ error: rec.error }, rec.status);
|
|
337
|
+
// `resolveFeedRecipient` already did the trust work; the only remaining
|
|
338
|
+
// read is the row it pinned. No `contactId` means no contact exists for
|
|
339
|
+
// this recipient yet, which projects to the same empty answer as a
|
|
340
|
+
// configured-closed allowlist.
|
|
341
|
+
const row = rec.contactId
|
|
342
|
+
? await resolveContact({ db, id: rec.contactId })
|
|
343
|
+
: null;
|
|
344
|
+
// pk_ is ANON-ONLY; identity is a server-minted userToken. On the token-less
|
|
345
|
+
// publishable arm the resolver pins whatever live row holds this browser's
|
|
346
|
+
// anon id in its `anonymous_id` COLUMN — and that row may be an IDENTIFIED
|
|
347
|
+
// contact (a server-side stitch, or a pre-logout id that leaked), because
|
|
348
|
+
// `collidesWithIdentified` only rejects a value that IS a canonical key.
|
|
349
|
+
// Flags tolerate that (booleans); traits are PII, so an identified row is
|
|
350
|
+
// only readable through a token (or a secret key). Project it as empty.
|
|
351
|
+
const tokenless = c.get("publishable") === true && !query.userToken;
|
|
352
|
+
const identifiedRow = Boolean(row && (row.externalId || row.email));
|
|
353
|
+
const visible = tokenless && identifiedRow ? null : row;
|
|
354
|
+
return c.json(projectPublicContact(visible, contactsConfig), 200);
|
|
355
|
+
})
|
|
278
356
|
.openapi(deleteRoute, async (c) => {
|
|
279
357
|
const { db, hatchet, logger } = c.get("container");
|
|
280
358
|
const { email, userId } = c.req.valid("json");
|