@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
package/src/routes/index.ts
CHANGED
|
@@ -17,6 +17,8 @@ import { flagsRouter } from "./flags/index.js";
|
|
|
17
17
|
import { groupsRouter } from "./groups/index.js";
|
|
18
18
|
import { healthRouter } from "./health.js";
|
|
19
19
|
import { listsRouter } from "./lists/index.js";
|
|
20
|
+
import { createReferralsRouter } from "./referrals/index.js";
|
|
21
|
+
import { createSnippetRouter } from "./snippet.js";
|
|
20
22
|
import { trackingRouter } from "./tracking/index.js";
|
|
21
23
|
import { shortLinkRouter } from "./tracking/short.js";
|
|
22
24
|
import { vanityRouter } from "./tracking/vanity.js";
|
|
@@ -137,6 +139,13 @@ export function registerRoutes(
|
|
|
137
139
|
v1.use(`${base}/*`, requireApiKey, requireScope("ingest"));
|
|
138
140
|
}
|
|
139
141
|
v1.use("/contacts/find", requireApiKey, requireScope("ingest"));
|
|
142
|
+
// `GET /v1/contacts/me` is the BROWSER read of the allowlisted contact
|
|
143
|
+
// projection — publishable OR secret-ingest, exactly like `GET /v1/flags`.
|
|
144
|
+
// Registered as a LITERAL for the reason spelled out above: a
|
|
145
|
+
// `/contacts/*` wildcard would ALSO match the bare `/contacts` upsert and
|
|
146
|
+
// re-run on top of its method-branch guard. Identity is resolved
|
|
147
|
+
// server-side inside the handler, so this guard only sets the key tier.
|
|
148
|
+
v1.use("/contacts/me", requirePublishableOrIngest);
|
|
140
149
|
// `POST /v1/flags/evaluate` is the SERVER SDK read — secret-only, exactly like
|
|
141
150
|
// the other secret data-plane routes. The bare `/flags` (browser GET) is
|
|
142
151
|
// guarded separately above; guard ONLY the `/evaluate` path here so the two
|
|
@@ -223,6 +232,37 @@ export function registerRoutes(
|
|
|
223
232
|
|
|
224
233
|
v1.route("/accounts", createAccountsRouter());
|
|
225
234
|
|
|
235
|
+
// ---- Referrals (PRD 05 §7.2) ----
|
|
236
|
+
//
|
|
237
|
+
// TWO TIERS on one prefix, every path enumerated EXPLICITLY. There is
|
|
238
|
+
// deliberately NO `/referrals/*` catch-all: a `/<prefix>/*` `use` in Hono
|
|
239
|
+
// also matches the bare `/<prefix>` path AND every literal sibling, so one
|
|
240
|
+
// would 401 the browser-reachable `/referrals/me`, the same trap documented
|
|
241
|
+
// for `/contacts/*`, `/lists/*` and `/accounts/*` above.
|
|
242
|
+
//
|
|
243
|
+
// Tier 1: the browser-reachable literal, `userToken`-gated INSIDE its
|
|
244
|
+
// handler and non-confirming on every token failure.
|
|
245
|
+
v1.use("/referrals/me", requirePublishableOrIngest);
|
|
246
|
+
// Tier 2: secret-only. `referrals` is an ORTHOGONAL scope exactly like
|
|
247
|
+
// `accounts`: an explicit grant or `full-admin`, and no SCOPE_HIERARCHY edit
|
|
248
|
+
// (`middleware/api-key.ts` `hasScope`). A `pk_` key holds only
|
|
249
|
+
// `["ingest-public"]`, so it 403s here rather than escalating.
|
|
250
|
+
//
|
|
251
|
+
// `/tree/*` is the ONLY parameterised path and it is GET-only, so it needs no
|
|
252
|
+
// method branch: nothing browser-reachable lives under it, unlike the
|
|
253
|
+
// `/accounts/:provider/:providerUserId` shape.
|
|
254
|
+
for (const path of [
|
|
255
|
+
"/referrals",
|
|
256
|
+
"/referrals/report",
|
|
257
|
+
"/referrals/touch",
|
|
258
|
+
"/referrals/import",
|
|
259
|
+
"/referrals/tree/*",
|
|
260
|
+
]) {
|
|
261
|
+
v1.use(path, requireApiKey, requireScope("referrals"));
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
v1.route("/referrals", createReferralsRouter());
|
|
265
|
+
|
|
226
266
|
v1.route("/contacts", contactsRouter);
|
|
227
267
|
v1.route("/events", eventsRouter);
|
|
228
268
|
v1.route("/feed", feedRouter);
|
|
@@ -244,6 +284,11 @@ export function registerRoutes(
|
|
|
244
284
|
// against the GSM-7 segment budget. Unauthenticated like /l.
|
|
245
285
|
app.route("/", shortLinkRouter);
|
|
246
286
|
|
|
287
|
+
// Drop-in browser SDK — root-mounted so the pasted tag is
|
|
288
|
+
// `${API_PUBLIC_URL}/hogsend.js`. Public; 404s when @hogsend/js is not
|
|
289
|
+
// installed next to the engine (best-effort, like the Studio SPA).
|
|
290
|
+
app.route("/", createSnippetRouter());
|
|
291
|
+
|
|
247
292
|
// Generic connector dispatch (oauth/interactions/ingress) — the static
|
|
248
293
|
// `connectors/` prefix is registered BEFORE the `:sourceId` webhook catch-all
|
|
249
294
|
// so it wins path matching. These routes self-authenticate (oauth state +
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { OpenAPIHono } from "@hono/zod-openapi";
|
|
2
|
+
import type { AppEnv } from "../../app.js";
|
|
3
|
+
import { registerReferralMeRoute } from "./me.js";
|
|
4
|
+
import {
|
|
5
|
+
registerReferralReportRoute,
|
|
6
|
+
registerReferralTreeRoute,
|
|
7
|
+
} from "./report.js";
|
|
8
|
+
import {
|
|
9
|
+
registerReferralImportRoute,
|
|
10
|
+
registerReferralTouchRoute,
|
|
11
|
+
} from "./touch.js";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The `/v1/referrals/*` router (PRD 05 §7.2). TWO TIERS on one prefix:
|
|
15
|
+
*
|
|
16
|
+
* - `/me` is browser-reachable (publishable OR secret-ingest) and gated INSIDE
|
|
17
|
+
* its handler by a server-minted `userToken`;
|
|
18
|
+
* - `/report`, `/tree/:contactId`, `/touch` and `/import` are secret-key only
|
|
19
|
+
* under the ORTHOGONAL `referrals` scope.
|
|
20
|
+
*
|
|
21
|
+
* The guards live in `routes/index.ts` and BRANCH rather than stack, for the
|
|
22
|
+
* reason `routes/accounts/index.ts` documents at length: Hono runs EVERY
|
|
23
|
+
* matching `use` and `route("/v1", v1)` flattens the middleware, so a blanket
|
|
24
|
+
* `/referrals/*` guard would 401 the browser `/me` route. This router
|
|
25
|
+
* re-applies NO auth of its own.
|
|
26
|
+
*
|
|
27
|
+
* Registration order is LITERALS FIRST. `/me` is a literal and `/tree/{...}`
|
|
28
|
+
* is the only parameterised path, so they cannot collide today - but the order
|
|
29
|
+
* is kept explicit so a future `/referrals/{id}` cannot capture `/me`.
|
|
30
|
+
*/
|
|
31
|
+
export function createReferralsRouter(): OpenAPIHono<AppEnv> {
|
|
32
|
+
const router = new OpenAPIHono<AppEnv>();
|
|
33
|
+
|
|
34
|
+
registerReferralMeRoute(router);
|
|
35
|
+
registerReferralReportRoute(router);
|
|
36
|
+
registerReferralTouchRoute(router);
|
|
37
|
+
registerReferralImportRoute(router);
|
|
38
|
+
registerReferralTreeRoute(router);
|
|
39
|
+
|
|
40
|
+
return router;
|
|
41
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { referralTouches } from "@hogsend/db";
|
|
2
|
+
import { createRoute, type OpenAPIHono, z } from "@hono/zod-openapi";
|
|
3
|
+
import { and, eq, sql } from "drizzle-orm";
|
|
4
|
+
import type { AppEnv } from "../../app.js";
|
|
5
|
+
import { getReferralLink } from "../../lib/referral-link.js";
|
|
6
|
+
import {
|
|
7
|
+
InvalidUserTokenError,
|
|
8
|
+
verifyUserToken,
|
|
9
|
+
} from "../../lib/user-token.js";
|
|
10
|
+
import { resolveTokenContactId } from "../accounts/resolve.js";
|
|
11
|
+
import { referralIdQuery, resolveReferralId } from "./shared.js";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* `GET /v1/referrals/me` (PRD 05 §7.2) - the CALLER's own share link and
|
|
15
|
+
* counts, `userToken`-gated, and NON-CONFIRMING exactly like
|
|
16
|
+
* `GET /v1/accounts/me` (DECISIONS §6.9).
|
|
17
|
+
*
|
|
18
|
+
* An absent, malformed, expired or forged token takes the SAME code path as
|
|
19
|
+
* "no referral is registered": `200 { link: null, stats: null }`. Anything else
|
|
20
|
+
* would let a caller enumerate which of a customer's users exist.
|
|
21
|
+
*
|
|
22
|
+
* The mint is LAZY and idempotent: a signed-in user who has never shared gets a
|
|
23
|
+
* link on first ask, and `getReferralLink` recovers it on every ask after.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
const meRoute = createRoute({
|
|
27
|
+
method: "get",
|
|
28
|
+
path: "/me",
|
|
29
|
+
tags: ["Referrals"],
|
|
30
|
+
summary: "The signed-in user's referral link and counts",
|
|
31
|
+
description:
|
|
32
|
+
"Publishable OR secret key, plus a server-minted `userToken` in the query string. Mints the caller's shared link lazily (idempotent). NON-CONFIRMING: an absent, forged, expired or unknown-user token returns `200 { link: null, stats: null }`, byte-identical to a deploy with no referral registered.",
|
|
33
|
+
request: {
|
|
34
|
+
query: z.object({
|
|
35
|
+
userToken: z.string().optional(),
|
|
36
|
+
referral: referralIdQuery,
|
|
37
|
+
}),
|
|
38
|
+
},
|
|
39
|
+
responses: {
|
|
40
|
+
200: {
|
|
41
|
+
content: {
|
|
42
|
+
"application/json": {
|
|
43
|
+
schema: z.object({
|
|
44
|
+
link: z
|
|
45
|
+
.object({ url: z.string(), slug: z.string().nullable() })
|
|
46
|
+
.nullable(),
|
|
47
|
+
stats: z
|
|
48
|
+
.object({
|
|
49
|
+
touched: z.number(),
|
|
50
|
+
bound: z.number(),
|
|
51
|
+
qualified: z.number(),
|
|
52
|
+
})
|
|
53
|
+
.nullable(),
|
|
54
|
+
}),
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
description: "The caller's link + counts, or two nulls",
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const EMPTY = { link: null, stats: null } as const;
|
|
63
|
+
|
|
64
|
+
export function registerReferralMeRoute(router: OpenAPIHono<AppEnv>) {
|
|
65
|
+
router.openapi(meRoute, async (c) => {
|
|
66
|
+
const container = c.get("container");
|
|
67
|
+
const { db, env, referrals } = container;
|
|
68
|
+
const query = c.req.valid("query");
|
|
69
|
+
const referralId = resolveReferralId(query.referral);
|
|
70
|
+
|
|
71
|
+
if (!query.userToken) return c.json(EMPTY, 200);
|
|
72
|
+
if (!referrals.get(referralId)) return c.json(EMPTY, 200);
|
|
73
|
+
|
|
74
|
+
let contactId: string | null = null;
|
|
75
|
+
try {
|
|
76
|
+
const { userId } = verifyUserToken({
|
|
77
|
+
token: query.userToken,
|
|
78
|
+
secret: env.BETTER_AUTH_SECRET,
|
|
79
|
+
});
|
|
80
|
+
contactId = await resolveTokenContactId(db, userId);
|
|
81
|
+
} catch (err) {
|
|
82
|
+
if (!(err instanceof InvalidUserTokenError)) throw err;
|
|
83
|
+
contactId = null;
|
|
84
|
+
}
|
|
85
|
+
if (!contactId) return c.json(EMPTY, 200);
|
|
86
|
+
|
|
87
|
+
const link = await getReferralLink({
|
|
88
|
+
referral: referralId,
|
|
89
|
+
contactId,
|
|
90
|
+
container: {
|
|
91
|
+
db,
|
|
92
|
+
env: { API_PUBLIC_URL: env.API_PUBLIC_URL },
|
|
93
|
+
referrals,
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
const [counts] = await db
|
|
98
|
+
.select({
|
|
99
|
+
touched: sql<number>`count(*) filter (where ${referralTouches.status} <> 'rejected')::int`,
|
|
100
|
+
bound: sql<number>`count(*) filter (where ${referralTouches.status} in ('bound', 'qualified'))::int`,
|
|
101
|
+
qualified: sql<number>`count(*) filter (where ${referralTouches.status} = 'qualified')::int`,
|
|
102
|
+
})
|
|
103
|
+
.from(referralTouches)
|
|
104
|
+
.where(
|
|
105
|
+
and(
|
|
106
|
+
eq(referralTouches.referralId, referralId),
|
|
107
|
+
eq(referralTouches.referrerContactId, contactId),
|
|
108
|
+
),
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
return c.json(
|
|
112
|
+
{
|
|
113
|
+
link: { url: link.url, slug: link.slug },
|
|
114
|
+
stats: {
|
|
115
|
+
touched: Number(counts?.touched ?? 0),
|
|
116
|
+
bound: Number(counts?.bound ?? 0),
|
|
117
|
+
qualified: Number(counts?.qualified ?? 0),
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
200,
|
|
121
|
+
);
|
|
122
|
+
});
|
|
123
|
+
}
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import { createRoute, type OpenAPIHono, z } from "@hono/zod-openapi";
|
|
2
|
+
import type { AppEnv } from "../../app.js";
|
|
3
|
+
import {
|
|
4
|
+
getReferralReport,
|
|
5
|
+
getReferralTree,
|
|
6
|
+
InvalidWindowError,
|
|
7
|
+
parseWindowMs,
|
|
8
|
+
REFERRAL_MODELS,
|
|
9
|
+
REFERRAL_REPORT_MAX_DEPTH,
|
|
10
|
+
resolveLevelWeights,
|
|
11
|
+
} from "../../lib/referral-report.js";
|
|
12
|
+
import { errorSchema } from "../../lib/schemas.js";
|
|
13
|
+
import {
|
|
14
|
+
referralIdQuery,
|
|
15
|
+
resolveNamedContactId,
|
|
16
|
+
resolveReferralId,
|
|
17
|
+
} from "./shared.js";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* `GET /v1/referrals/report` and `GET /v1/referrals/tree/:contactId` (PRD 05
|
|
21
|
+
* §5.3). Model, window, depth and level weights are REQUEST parameters, so
|
|
22
|
+
* these two routes are the entire "reporting feature": nothing is persisted
|
|
23
|
+
* per model and nothing is backfilled when the reader changes their mind.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
const DEFAULT_WINDOW = "30d";
|
|
27
|
+
const DEFAULT_LIMIT = 50;
|
|
28
|
+
const MAX_LIMIT = 200;
|
|
29
|
+
const DEFAULT_TREE_DEPTH = 3;
|
|
30
|
+
const MAX_TREE_NODES = 1000;
|
|
31
|
+
|
|
32
|
+
const currencyValueSchema = z.object({
|
|
33
|
+
currency: z.string(),
|
|
34
|
+
value: z.number(),
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const reportRoute = createRoute({
|
|
38
|
+
method: "get",
|
|
39
|
+
path: "/report",
|
|
40
|
+
tags: ["Referrals"],
|
|
41
|
+
summary: "Referral revenue and tree report",
|
|
42
|
+
description:
|
|
43
|
+
"Secret key + the `referrals` scope. Picks each referee's effective edge(s) under `model` within `window` (the touch-to-bind gap), walks the referrer chain to `depth`, and credits `weights[level] * edgeWeight * conversion value`. VALUES ARE NEVER CONVERTED BETWEEN CURRENCIES: every monetary field is a list of `{ currency, value }`.",
|
|
44
|
+
request: {
|
|
45
|
+
query: z.object({
|
|
46
|
+
referral: referralIdQuery,
|
|
47
|
+
model: z.enum(REFERRAL_MODELS).optional(),
|
|
48
|
+
window: z.string().optional(),
|
|
49
|
+
depth: z.coerce
|
|
50
|
+
.number()
|
|
51
|
+
.int()
|
|
52
|
+
.min(1)
|
|
53
|
+
.max(REFERRAL_REPORT_MAX_DEPTH)
|
|
54
|
+
.optional(),
|
|
55
|
+
weights: z.string().optional(),
|
|
56
|
+
from: z.string().optional(),
|
|
57
|
+
to: z.string().optional(),
|
|
58
|
+
limit: z.coerce.number().int().min(1).max(MAX_LIMIT).optional(),
|
|
59
|
+
cursor: z.string().optional(),
|
|
60
|
+
}),
|
|
61
|
+
},
|
|
62
|
+
responses: {
|
|
63
|
+
200: {
|
|
64
|
+
content: {
|
|
65
|
+
"application/json": {
|
|
66
|
+
schema: z.object({
|
|
67
|
+
referral: z.string(),
|
|
68
|
+
model: z.enum(REFERRAL_MODELS),
|
|
69
|
+
window: z.string(),
|
|
70
|
+
depth: z.number(),
|
|
71
|
+
weights: z.array(z.number()),
|
|
72
|
+
from: z.string().nullable(),
|
|
73
|
+
to: z.string().nullable(),
|
|
74
|
+
beneficiaries: z.array(
|
|
75
|
+
z.object({
|
|
76
|
+
contactId: z.string(),
|
|
77
|
+
direct: z.object({
|
|
78
|
+
touched: z.number(),
|
|
79
|
+
bound: z.number(),
|
|
80
|
+
qualified: z.number(),
|
|
81
|
+
}),
|
|
82
|
+
tree: z.array(
|
|
83
|
+
z.object({
|
|
84
|
+
level: z.number(),
|
|
85
|
+
referees: z.number(),
|
|
86
|
+
conversions: z.number(),
|
|
87
|
+
value: z.array(currencyValueSchema),
|
|
88
|
+
}),
|
|
89
|
+
),
|
|
90
|
+
value: z.array(currencyValueSchema),
|
|
91
|
+
}),
|
|
92
|
+
),
|
|
93
|
+
nextCursor: z.string().nullable(),
|
|
94
|
+
}),
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
description: "The report",
|
|
98
|
+
},
|
|
99
|
+
400: {
|
|
100
|
+
content: { "application/json": { schema: errorSchema } },
|
|
101
|
+
description: "Invalid window, weights, cursor or date",
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
const treeRoute = createRoute({
|
|
107
|
+
method: "get",
|
|
108
|
+
path: "/tree/{contactId}",
|
|
109
|
+
tags: ["Referrals"],
|
|
110
|
+
summary: "One referrer's descendants",
|
|
111
|
+
description:
|
|
112
|
+
"Secret key + the `referrals` scope. Walks DOWN from `contactId` to `depth` (default 3, cap 5) over every non-rejected edge. This is a ledger view, not a model: no window, no weights.",
|
|
113
|
+
request: {
|
|
114
|
+
params: z.object({ contactId: z.string().min(1) }),
|
|
115
|
+
query: z.object({
|
|
116
|
+
referral: referralIdQuery,
|
|
117
|
+
depth: z.coerce
|
|
118
|
+
.number()
|
|
119
|
+
.int()
|
|
120
|
+
.min(1)
|
|
121
|
+
.max(REFERRAL_REPORT_MAX_DEPTH)
|
|
122
|
+
.optional(),
|
|
123
|
+
}),
|
|
124
|
+
},
|
|
125
|
+
responses: {
|
|
126
|
+
200: {
|
|
127
|
+
content: {
|
|
128
|
+
"application/json": {
|
|
129
|
+
schema: z.object({
|
|
130
|
+
referral: z.string(),
|
|
131
|
+
contactId: z.string(),
|
|
132
|
+
depth: z.number(),
|
|
133
|
+
nodes: z.array(
|
|
134
|
+
z.object({
|
|
135
|
+
contactId: z.string(),
|
|
136
|
+
level: z.number(),
|
|
137
|
+
viaContactId: z.string(),
|
|
138
|
+
status: z.string(),
|
|
139
|
+
touchedAt: z.string(),
|
|
140
|
+
boundAt: z.string().nullable(),
|
|
141
|
+
qualifiedAt: z.string().nullable(),
|
|
142
|
+
conversions: z.number(),
|
|
143
|
+
value: z.array(currencyValueSchema),
|
|
144
|
+
}),
|
|
145
|
+
),
|
|
146
|
+
}),
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
description: "The descendant nodes",
|
|
150
|
+
},
|
|
151
|
+
400: {
|
|
152
|
+
content: { "application/json": { schema: errorSchema } },
|
|
153
|
+
description: "Unresolvable contact key",
|
|
154
|
+
},
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
/** `"1,0.5,0.25"` -> `[1, 0.5, 0.25]`. Throws on anything else. */
|
|
159
|
+
function parseWeights(input: string | undefined, depth: number): number[] {
|
|
160
|
+
if (!input) return [];
|
|
161
|
+
const parts = input.split(",").map((p) => p.trim());
|
|
162
|
+
if (parts.length > depth) {
|
|
163
|
+
throw new RangeError(
|
|
164
|
+
`weights has ${parts.length} entries but depth is ${depth}`,
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
return parts.map((part) => {
|
|
168
|
+
const value = Number(part);
|
|
169
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
170
|
+
throw new RangeError(`weight "${part}" is not a non-negative number`);
|
|
171
|
+
}
|
|
172
|
+
return value;
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** The cursor is an opaque decimal offset; a non-offset value is a 400. */
|
|
177
|
+
function parseCursor(input: string | undefined): number {
|
|
178
|
+
if (!input) return 0;
|
|
179
|
+
const offset = Number(input);
|
|
180
|
+
if (!Number.isInteger(offset) || offset < 0) {
|
|
181
|
+
throw new RangeError(`invalid cursor "${input}"`);
|
|
182
|
+
}
|
|
183
|
+
return offset;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function parseDate(input: string | undefined, label: string): Date | undefined {
|
|
187
|
+
if (!input) return undefined;
|
|
188
|
+
const date = new Date(input);
|
|
189
|
+
if (Number.isNaN(date.getTime())) {
|
|
190
|
+
throw new RangeError(`invalid ${label} date "${input}"`);
|
|
191
|
+
}
|
|
192
|
+
return date;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function registerReferralReportRoute(router: OpenAPIHono<AppEnv>) {
|
|
196
|
+
router.openapi(reportRoute, async (c) => {
|
|
197
|
+
const { db } = c.get("container");
|
|
198
|
+
const query = c.req.valid("query");
|
|
199
|
+
|
|
200
|
+
const referralId = resolveReferralId(query.referral);
|
|
201
|
+
const model = query.model ?? "first_touch";
|
|
202
|
+
const windowInput = query.window ?? DEFAULT_WINDOW;
|
|
203
|
+
const depth = query.depth ?? 1;
|
|
204
|
+
const limit = query.limit ?? DEFAULT_LIMIT;
|
|
205
|
+
|
|
206
|
+
let windowMs: number;
|
|
207
|
+
let weights: number[];
|
|
208
|
+
let offset: number;
|
|
209
|
+
let from: Date | undefined;
|
|
210
|
+
let to: Date | undefined;
|
|
211
|
+
try {
|
|
212
|
+
windowMs = parseWindowMs(windowInput);
|
|
213
|
+
weights = parseWeights(query.weights, depth);
|
|
214
|
+
offset = parseCursor(query.cursor);
|
|
215
|
+
from = parseDate(query.from, "from");
|
|
216
|
+
to = parseDate(query.to, "to");
|
|
217
|
+
} catch (err) {
|
|
218
|
+
if (err instanceof InvalidWindowError || err instanceof RangeError) {
|
|
219
|
+
return c.json({ error: err.message }, 400);
|
|
220
|
+
}
|
|
221
|
+
throw err;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const levelWeights = resolveLevelWeights(depth, weights);
|
|
225
|
+
const report = await getReferralReport({
|
|
226
|
+
db,
|
|
227
|
+
referralId,
|
|
228
|
+
model,
|
|
229
|
+
windowMs,
|
|
230
|
+
depth,
|
|
231
|
+
levelWeights,
|
|
232
|
+
...(from ? { from } : {}),
|
|
233
|
+
...(to ? { to } : {}),
|
|
234
|
+
limit,
|
|
235
|
+
offset,
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
return c.json(
|
|
239
|
+
{
|
|
240
|
+
referral: referralId,
|
|
241
|
+
model,
|
|
242
|
+
window: windowInput,
|
|
243
|
+
depth,
|
|
244
|
+
weights: levelWeights,
|
|
245
|
+
from: from ? from.toISOString() : null,
|
|
246
|
+
to: to ? to.toISOString() : null,
|
|
247
|
+
beneficiaries: report.beneficiaries,
|
|
248
|
+
nextCursor:
|
|
249
|
+
report.nextOffset === null ? null : String(report.nextOffset),
|
|
250
|
+
},
|
|
251
|
+
200,
|
|
252
|
+
);
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function registerReferralTreeRoute(router: OpenAPIHono<AppEnv>) {
|
|
257
|
+
router.openapi(treeRoute, async (c) => {
|
|
258
|
+
const { db } = c.get("container");
|
|
259
|
+
const { contactId } = c.req.valid("param");
|
|
260
|
+
const query = c.req.valid("query");
|
|
261
|
+
const referralId = resolveReferralId(query.referral);
|
|
262
|
+
const depth = query.depth ?? DEFAULT_TREE_DEPTH;
|
|
263
|
+
|
|
264
|
+
// A tree is addressed by the CONTACT, so an external key resolves the same
|
|
265
|
+
// way every other operator route resolves one. An unknown key is an empty
|
|
266
|
+
// tree, not a 404: "this person referred nobody" is the same answer.
|
|
267
|
+
const resolved = await resolveNamedContactId(db, contactId);
|
|
268
|
+
if (!resolved) {
|
|
269
|
+
return c.json({ referral: referralId, contactId, depth, nodes: [] }, 200);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const nodes = await getReferralTree({
|
|
273
|
+
db,
|
|
274
|
+
referralId,
|
|
275
|
+
contactId: resolved,
|
|
276
|
+
depth,
|
|
277
|
+
limit: MAX_TREE_NODES,
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
return c.json(
|
|
281
|
+
{ referral: referralId, contactId: resolved, depth, nodes },
|
|
282
|
+
200,
|
|
283
|
+
);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { DEFAULT_REFERRAL_ID } from "@hogsend/core";
|
|
2
|
+
import type { Database } from "@hogsend/db";
|
|
3
|
+
import { z } from "@hono/zod-openapi";
|
|
4
|
+
import { resolveContact } from "../../lib/contacts.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Helpers shared by the `/v1/referrals` routes. Nothing here creates a
|
|
8
|
+
* contact: an operator naming a key is asking a QUESTION, and minting a row to
|
|
9
|
+
* answer it is the ghost-contact case PRD 02 forbade.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** Every route takes the same optional `referral` selector. */
|
|
13
|
+
export const referralIdQuery = z
|
|
14
|
+
.string()
|
|
15
|
+
.min(1)
|
|
16
|
+
.optional()
|
|
17
|
+
.describe(`The defineReferral id. Default "${DEFAULT_REFERRAL_ID}".`);
|
|
18
|
+
|
|
19
|
+
export function resolveReferralId(input: string | undefined): string {
|
|
20
|
+
return input ?? DEFAULT_REFERRAL_ID;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Resolve a contact an operator named by uuid or external key. `null` = no
|
|
25
|
+
* such contact; the caller decides whether that is a 404 or a skipped row.
|
|
26
|
+
*/
|
|
27
|
+
export async function resolveNamedContactId(
|
|
28
|
+
db: Database,
|
|
29
|
+
key: string | undefined,
|
|
30
|
+
): Promise<string | null> {
|
|
31
|
+
if (!key) return null;
|
|
32
|
+
const row = await resolveContact({ db, id: key });
|
|
33
|
+
return row?.id ?? null;
|
|
34
|
+
}
|