@hogsend/engine 0.66.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/container.ts +77 -0
- package/src/index.ts +78 -0
- package/src/lib/contacts.ts +70 -0
- 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/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 +39 -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/tracking/arrive.ts +90 -0
- package/src/routes/tracking/click-pipeline.ts +8 -0
|
@@ -118,6 +118,16 @@ export const WEBHOOK_EVENT_TYPES = [
|
|
|
118
118
|
"account.linked",
|
|
119
119
|
"account.unlinked",
|
|
120
120
|
"account.link_failed",
|
|
121
|
+
// Referrals (`defineReferral`, PRD 05). Emitted from the referral INTENT
|
|
122
|
+
// layer only (`lib/referral-intent.ts`), never from the store, which never
|
|
123
|
+
// emits. `level` on `referral.tree_converted` is a FACT on the event, not
|
|
124
|
+
// program config: depth and weights stay report-time parameters.
|
|
125
|
+
"referral.touched",
|
|
126
|
+
"referral.bound",
|
|
127
|
+
"referral.qualified",
|
|
128
|
+
"referral.converted",
|
|
129
|
+
"referral.tree_converted",
|
|
130
|
+
"referral.rejected",
|
|
121
131
|
// Weekly impact digest (impact experiments D5). Self-referential: the
|
|
122
132
|
// cron watermarks off its own delivery rows.
|
|
123
133
|
"impact.digest",
|
|
@@ -120,6 +120,11 @@ const createKeyRoute = createRoute({
|
|
|
120
120
|
// SCOPE_HIERARCHY edit and no migration (`api_keys.scopes`
|
|
121
121
|
// is a jsonb string array).
|
|
122
122
|
"accounts",
|
|
123
|
+
// The referral data plane (`/v1/referrals` report, tree,
|
|
124
|
+
// touch, import). ORTHOGONAL for the same reason
|
|
125
|
+
// `accounts` is; `/v1/referrals/me` is NOT covered by it
|
|
126
|
+
// (that one is publishable + userToken).
|
|
127
|
+
"referrals",
|
|
123
128
|
]),
|
|
124
129
|
)
|
|
125
130
|
.min(1)
|
|
@@ -37,6 +37,7 @@ import { openEditorRouter } from "./open-editor.js";
|
|
|
37
37
|
import { preferencesRouter } from "./preferences.js";
|
|
38
38
|
import { providerCredentialsRouter } from "./provider-credentials.js";
|
|
39
39
|
import { readinessRouter } from "./readiness.js";
|
|
40
|
+
import { adminReferralsRouter } from "./referrals.js";
|
|
40
41
|
import { reportingRouter } from "./reporting.js";
|
|
41
42
|
import { settingsRouter } from "./settings.js";
|
|
42
43
|
import { suppressionsRouter } from "./suppressions.js";
|
|
@@ -67,6 +68,7 @@ adminRouter.route("/conversions", adminConversionsRouter);
|
|
|
67
68
|
adminRouter.route("/attribution", adminAttributionRouter);
|
|
68
69
|
adminRouter.route("/funnels", adminFunnelsRouter);
|
|
69
70
|
adminRouter.route("/groups", groupsRouter);
|
|
71
|
+
adminRouter.route("/referrals", adminReferralsRouter);
|
|
70
72
|
adminRouter.route("/flags", adminFlagsRouter);
|
|
71
73
|
adminRouter.route("/targeting", targetingRouter);
|
|
72
74
|
adminRouter.route("/events", eventsRouter);
|
|
@@ -67,7 +67,10 @@ const linkSchema = z.object({
|
|
|
67
67
|
// link somehow has no tracked row — kept nullable to stay total.
|
|
68
68
|
trackedLinkId: z.string().nullable(),
|
|
69
69
|
originalUrl: z.string(),
|
|
70
|
-
type: z.enum(["personal", "public"]),
|
|
70
|
+
type: z.enum(["personal", "public", "shared"]),
|
|
71
|
+
// The credited owner of a "shared" (referral) link; null otherwise. An
|
|
72
|
+
// ATTRIBUTION field, never an identity one - a shared link stitches nobody.
|
|
73
|
+
ownerContactId: z.string().nullable(),
|
|
71
74
|
// Vanity slug (normalized lowercase, unique per instance) + its short URL
|
|
72
75
|
// (`${API_PUBLIC_URL}/l/:slug`). Both null when no slug is set.
|
|
73
76
|
slug: z.string().nullable(),
|
|
@@ -157,8 +160,10 @@ function serializeLink(
|
|
|
157
160
|
id: row.id,
|
|
158
161
|
trackedLinkId,
|
|
159
162
|
originalUrl: row.originalUrl,
|
|
160
|
-
// The column is
|
|
161
|
-
type:
|
|
163
|
+
// The column is free text; mintLink only ever writes these three values.
|
|
164
|
+
type:
|
|
165
|
+
row.type === "personal" || row.type === "shared" ? row.type : "public",
|
|
166
|
+
ownerContactId: row.ownerContactId,
|
|
162
167
|
slug: row.slug,
|
|
163
168
|
vanityUrl: row.slug ? vanityUrlFor(baseUrl, row.slug) : null,
|
|
164
169
|
label: row.label,
|
|
@@ -193,7 +198,10 @@ const createLinkRoute = createRoute({
|
|
|
193
198
|
schema: z
|
|
194
199
|
.object({
|
|
195
200
|
url: z.string().url(),
|
|
196
|
-
type: z.enum(["personal", "public"]).default("public"),
|
|
201
|
+
type: z.enum(["personal", "public", "shared"]).default("public"),
|
|
202
|
+
// REQUIRED for type "shared", rejected on personal/public
|
|
203
|
+
// (mintLink's ownership invariant -> 400).
|
|
204
|
+
ownerContactId: z.string().uuid().optional(),
|
|
197
205
|
// Optional vanity slug (`/l/:slug`). Normalized lowercase; 409 if
|
|
198
206
|
// already taken by a different destination (same destination +
|
|
199
207
|
// type recovers the existing link — see idempotencyKey).
|
|
@@ -252,7 +260,7 @@ const listLinksRoute = createRoute({
|
|
|
252
260
|
query: z.object({
|
|
253
261
|
limit: z.coerce.number().min(1).max(200).default(50),
|
|
254
262
|
offset: z.coerce.number().min(0).default(0),
|
|
255
|
-
type: z.enum(["personal", "public"]).optional(),
|
|
263
|
+
type: z.enum(["personal", "public", "shared"]).optional(),
|
|
256
264
|
includeArchived: z.coerce.boolean().default(false),
|
|
257
265
|
// true = only links whose QR scan row exists — the "QR codes" lens
|
|
258
266
|
// (a QR code IS a managed link whose QR row has been minted).
|
|
@@ -448,6 +456,7 @@ export const linksRouter = new OpenAPIHono<AppEnv>()
|
|
|
448
456
|
appendRef: body.appendRef,
|
|
449
457
|
campaign: body.campaign,
|
|
450
458
|
distinctId: body.distinctId,
|
|
459
|
+
ownerContactId: body.ownerContactId,
|
|
451
460
|
createdBy: resolveActor(c) ?? undefined,
|
|
452
461
|
idempotencyKey: body.idempotencyKey,
|
|
453
462
|
});
|
|
@@ -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
|
+
});
|