@hogsend/engine 0.46.0 → 0.50.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/README.md +6 -0
- package/package.json +13 -10
- package/src/connectors/presets/index.ts +8 -2
- package/src/container.ts +149 -7
- package/src/destinations/presets/posthog.ts +7 -0
- package/src/destinations/presets/segment.ts +5 -0
- package/src/env.ts +38 -0
- package/src/flags/reconcile.ts +195 -0
- package/src/index.ts +79 -0
- package/src/journeys/authoring.ts +32 -0
- package/src/journeys/define-journey.ts +45 -40
- package/src/journeys/execute-journey-run.ts +73 -32
- package/src/journeys/journey-boundary.ts +76 -0
- package/src/journeys/journey-context.ts +128 -70
- package/src/journeys/journey-task-factory.ts +31 -0
- package/src/journeys/journey-task-runtime.ts +31 -0
- package/src/journeys/journey-version.test.ts +236 -0
- package/src/journeys/journey-version.ts +158 -0
- package/src/journeys/record-once.ts +28 -2
- package/src/lib/connector-actions.test.ts +36 -0
- package/src/lib/connector-actions.ts +42 -4
- package/src/lib/contacts.ts +49 -0
- package/src/lib/conversions.test.ts +33 -0
- package/src/lib/conversions.ts +8 -0
- package/src/lib/email.ts +23 -2
- package/src/lib/enrollment-policy.ts +51 -0
- package/src/lib/feed.ts +55 -3
- package/src/lib/flags-registry.ts +48 -0
- package/src/lib/flags.ts +498 -0
- package/src/lib/fx.ts +374 -0
- package/src/lib/global-control-readout.ts +166 -0
- package/src/lib/groups.ts +362 -0
- package/src/lib/ingestion.ts +38 -0
- package/src/lib/journey-lift.ts +142 -0
- package/src/lib/operator-settings.ts +71 -0
- package/src/lib/outbound.ts +147 -0
- package/src/lib/preferences.ts +6 -80
- package/src/lib/recipient-preferences.ts +53 -0
- package/src/lib/sms.ts +21 -2
- package/src/lib/stable-stringify.test.ts +42 -0
- package/src/lib/stable-stringify.ts +23 -0
- package/src/lib/variant.ts +99 -0
- package/src/lib/webhook-signing.ts +16 -1
- package/src/lists/registry.ts +6 -2
- package/src/lists/subscription.ts +13 -0
- package/src/routes/admin/contacts.ts +53 -4
- package/src/routes/admin/conversions.ts +137 -0
- package/src/routes/admin/flags.ts +369 -0
- package/src/routes/admin/groups.ts +866 -0
- package/src/routes/admin/impact-schemas.ts +44 -0
- package/src/routes/admin/impact-wire.test.ts +181 -0
- package/src/routes/admin/impact.ts +486 -0
- package/src/routes/admin/index.ts +12 -0
- package/src/routes/admin/journey-impact.ts +446 -0
- package/src/routes/admin/journeys.ts +70 -100
- package/src/routes/admin/readiness.ts +8 -8
- package/src/routes/admin/settings.ts +145 -0
- package/src/routes/admin/targeting.ts +256 -0
- package/src/routes/events/index.ts +11 -0
- package/src/routes/flags/index.ts +120 -0
- package/src/routes/groups/index.ts +417 -0
- package/src/routes/index.ts +23 -1
- package/src/testing.ts +25 -0
- package/src/webhook-sources/presets/index.ts +5 -1
- package/src/webhook-sources/presets/intercom.ts +230 -0
- package/src/webhook-sources/presets/segment.ts +56 -4
- package/src/worker.ts +3 -0
- package/src/workflows/bucket-backfill.ts +1 -14
- package/src/workflows/impact-digest.ts +761 -0
- package/src/workflows/journey-blueprint-interpreter.ts +18 -1
|
@@ -25,7 +25,16 @@ import {
|
|
|
25
25
|
import type { AppEnv } from "../../app.js";
|
|
26
26
|
import { buildJourneyGraph } from "../../journeys/graph/build-graph.js";
|
|
27
27
|
import { ingestEvent } from "../../lib/ingestion.js";
|
|
28
|
-
import {
|
|
28
|
+
import {
|
|
29
|
+
computeJourneyLift,
|
|
30
|
+
computeLiftValues,
|
|
31
|
+
} from "../../lib/journey-lift.js";
|
|
32
|
+
import {
|
|
33
|
+
cohortSchema,
|
|
34
|
+
type DefinitionSource,
|
|
35
|
+
definitionSourceSchema,
|
|
36
|
+
liftVerdictSchema,
|
|
37
|
+
} from "./impact-schemas.js";
|
|
29
38
|
|
|
30
39
|
/**
|
|
31
40
|
* Per-process cache of the built {@link JourneyGraph}. A journey's `runSource`
|
|
@@ -43,6 +52,16 @@ const journeySchema = z.object({
|
|
|
43
52
|
event: z.string(),
|
|
44
53
|
}),
|
|
45
54
|
entryLimit: z.enum(["once", "once_per_period", "unlimited"]),
|
|
55
|
+
/** Display-only author label (JourneyMeta.version) of the CURRENT
|
|
56
|
+
* deployed definition. */
|
|
57
|
+
version: z.string().optional(),
|
|
58
|
+
/** Engine-computed content fingerprint (12 hex) of the CURRENT deployed
|
|
59
|
+
* definition — what a fresh enrollment would stamp. Treat a NEW hash as
|
|
60
|
+
* "possible new version": toolchain bumps can fork it (D1). */
|
|
61
|
+
versionHash: z.string().optional(),
|
|
62
|
+
/** Conversion definition id (JourneyMeta.goal) — boot-validated; the
|
|
63
|
+
* /lift + /impact readouts default to it. */
|
|
64
|
+
goal: z.string().optional(),
|
|
46
65
|
counts: z.object({
|
|
47
66
|
active: z.number(),
|
|
48
67
|
waiting: z.number(),
|
|
@@ -64,6 +83,10 @@ export const stateSchema = z.object({
|
|
|
64
83
|
currentNodeId: z.string(),
|
|
65
84
|
status: z.string(),
|
|
66
85
|
hatchetRunId: z.string().nullable(),
|
|
86
|
+
/** Impact experiments (D1): definition fingerprint + label stamped at
|
|
87
|
+
* this row's INSERT. Null = pre-versioning ("unversioned") row. */
|
|
88
|
+
journeyVersionHash: z.string().nullable(),
|
|
89
|
+
journeyVersionLabel: z.string().nullable(),
|
|
67
90
|
context: z.record(z.string(), z.unknown()),
|
|
68
91
|
errorMessage: z.string().nullable(),
|
|
69
92
|
entryCount: z.number(),
|
|
@@ -485,19 +508,12 @@ const graphRoute = createRoute({
|
|
|
485
508
|
* Holdout lift (impact plan §4.2) — the ONLY surface allowed causal
|
|
486
509
|
* language. Treatment = entered enrollments in the window; control =
|
|
487
510
|
* held_out diversions (§4.1). Outcome = the contact fired ≥1 conversion
|
|
488
|
-
* AFTER their state row was created.
|
|
489
|
-
*
|
|
511
|
+
* AFTER their state row was created. Cohort math + verdict live in the
|
|
512
|
+
* shared computeJourneyLift/computeLiftValues helpers (lib/journey-lift.ts
|
|
513
|
+
* — also the engine of the phase-2b /impact route and the 3b digest);
|
|
514
|
+
* this route merges the per-currency values into the cohorts to keep its
|
|
515
|
+
* original wire shape.
|
|
490
516
|
*/
|
|
491
|
-
const liftCohortSchema = z.object({
|
|
492
|
-
contacts: z.number(),
|
|
493
|
-
converters: z.number(),
|
|
494
|
-
rate: z.number(),
|
|
495
|
-
/** Qualifying conversion value per currency (full, not fractional). */
|
|
496
|
-
value: z.array(
|
|
497
|
-
z.object({ currency: z.string().nullable(), value: z.number() }),
|
|
498
|
-
),
|
|
499
|
-
});
|
|
500
|
-
|
|
501
517
|
const liftRoute = createRoute({
|
|
502
518
|
method: "get",
|
|
503
519
|
path: "/{id}/lift",
|
|
@@ -507,7 +523,8 @@ const liftRoute = createRoute({
|
|
|
507
523
|
params: z.object({ id: z.string() }),
|
|
508
524
|
query: z.object({
|
|
509
525
|
days: z.coerce.number().min(1).max(365).default(90),
|
|
510
|
-
/** Scope the outcome to one conversion point
|
|
526
|
+
/** Scope the outcome to one conversion point. Default: the
|
|
527
|
+
* journey's meta.goal; else any conversion. */
|
|
511
528
|
definitionId: z.string().optional(),
|
|
512
529
|
}),
|
|
513
530
|
},
|
|
@@ -518,14 +535,16 @@ const liftRoute = createRoute({
|
|
|
518
535
|
schema: z.object({
|
|
519
536
|
journeyId: z.string(),
|
|
520
537
|
days: z.number(),
|
|
538
|
+
/** The EFFECTIVE definition scoping the outcome (query param,
|
|
539
|
+
* else the journey's meta.goal); null = any conversion. */
|
|
521
540
|
definitionId: z.string().nullable(),
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
541
|
+
/** Where the effective definitionId came from — the single
|
|
542
|
+
* source enum shared with /impact (phase 2b) and the Studio
|
|
543
|
+
* mirror (phase 3a). */
|
|
544
|
+
definitionSource: definitionSourceSchema,
|
|
545
|
+
treatment: cohortSchema,
|
|
546
|
+
control: cohortSchema,
|
|
547
|
+
...liftVerdictSchema.shape,
|
|
529
548
|
}),
|
|
530
549
|
},
|
|
531
550
|
},
|
|
@@ -587,6 +606,9 @@ export const journeysRouter = new OpenAPIHono<AppEnv>()
|
|
|
587
606
|
enabled: effectiveEnabled,
|
|
588
607
|
trigger: { event: j.trigger.event },
|
|
589
608
|
entryLimit: j.entryLimit,
|
|
609
|
+
version: j.version,
|
|
610
|
+
versionHash: j.versionHash,
|
|
611
|
+
goal: j.goal,
|
|
590
612
|
counts: countsMap.get(j.id) ?? { ...emptyCounts },
|
|
591
613
|
};
|
|
592
614
|
});
|
|
@@ -656,6 +678,9 @@ export const journeysRouter = new OpenAPIHono<AppEnv>()
|
|
|
656
678
|
where: meta.trigger.where as Record<string, unknown>[] | undefined,
|
|
657
679
|
},
|
|
658
680
|
entryLimit: meta.entryLimit,
|
|
681
|
+
version: meta.version,
|
|
682
|
+
versionHash: meta.versionHash,
|
|
683
|
+
goal: meta.goal,
|
|
659
684
|
exitOn: meta.exitOn?.map((e) => ({
|
|
660
685
|
event: e.event,
|
|
661
686
|
where: e.where as Record<string, unknown>[] | undefined,
|
|
@@ -1112,94 +1137,39 @@ export const journeysRouter = new OpenAPIHono<AppEnv>()
|
|
|
1112
1137
|
);
|
|
1113
1138
|
})
|
|
1114
1139
|
.openapi(liftRoute, async (c) => {
|
|
1115
|
-
const { db } = c.get("container");
|
|
1140
|
+
const { db, registry } = c.get("container");
|
|
1116
1141
|
const { id } = c.req.valid("param");
|
|
1117
|
-
const { days, definitionId } = c.req.valid("query");
|
|
1118
|
-
const since = new Date(
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
//
|
|
1124
|
-
//
|
|
1125
|
-
const
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
? eq(journeyStates.status, "held_out")
|
|
1137
|
-
: sql`${journeyStates.status} != 'held_out'`;
|
|
1138
|
-
const [row] = await db
|
|
1139
|
-
.select({
|
|
1140
|
-
contacts: sql<number>`count(distinct ${journeyStates.userId})::int`,
|
|
1141
|
-
converters: sql<number>`(count(distinct ${journeyStates.userId}) filter (where ${convertedSql}))::int`,
|
|
1142
|
-
})
|
|
1143
|
-
.from(journeyStates)
|
|
1144
|
-
.where(
|
|
1145
|
-
and(
|
|
1146
|
-
eq(journeyStates.journeyId, id),
|
|
1147
|
-
gteCreated(sinceTs),
|
|
1148
|
-
statusFilter,
|
|
1149
|
-
),
|
|
1150
|
-
);
|
|
1151
|
-
// Full qualifying conversion value per currency (secondary read-out —
|
|
1152
|
-
// the rate is the primary lift instrument).
|
|
1153
|
-
const valueRows = await db.execute<{
|
|
1154
|
-
currency: string | null;
|
|
1155
|
-
value: number;
|
|
1156
|
-
}>(sql`
|
|
1157
|
-
select c.currency, coalesce(sum(c.value), 0)::float8 as value
|
|
1158
|
-
from conversions c
|
|
1159
|
-
where c.value is not null
|
|
1160
|
-
and exists (
|
|
1161
|
-
select 1 from journey_states js
|
|
1162
|
-
where js.journey_id = ${id}
|
|
1163
|
-
and js.created_at >= ${sinceTs}
|
|
1164
|
-
and ${control ? sql`js.status = 'held_out'` : sql`js.status != 'held_out'`}
|
|
1165
|
-
and js.user_id = c.user_key
|
|
1166
|
-
and c.occurred_at >= js.created_at
|
|
1167
|
-
)${definitionId ? sql` and c.definition_id = ${definitionId}` : sql``}
|
|
1168
|
-
group by c.currency
|
|
1169
|
-
`);
|
|
1170
|
-
const contacts = Number(row?.contacts ?? 0);
|
|
1171
|
-
const converters = row?.converters ?? 0;
|
|
1172
|
-
return {
|
|
1173
|
-
contacts,
|
|
1174
|
-
converters,
|
|
1175
|
-
rate: contacts > 0 ? converters / contacts : 0,
|
|
1176
|
-
value: [...valueRows].map((r) => ({
|
|
1177
|
-
currency: r.currency,
|
|
1178
|
-
value: Number(r.value),
|
|
1179
|
-
})),
|
|
1180
|
-
};
|
|
1181
|
-
};
|
|
1182
|
-
|
|
1183
|
-
const [treatment, control] = await Promise.all([
|
|
1184
|
-
cohort(false),
|
|
1185
|
-
cohort(true),
|
|
1142
|
+
const { days, definitionId: queryDefinitionId } = c.req.valid("query");
|
|
1143
|
+
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
|
1144
|
+
|
|
1145
|
+
// definitionId resolution: explicit query param > journey meta.goal >
|
|
1146
|
+
// any conversion. registry.get(id) is undefined for (a) deleted/renamed
|
|
1147
|
+
// journeys with historical states and (b) DEFINED journeys excluded by
|
|
1148
|
+
// the ENABLED_JOURNEYS csv — both keep the pre-goal "any" behavior and
|
|
1149
|
+
// report source "none". The route still never 404s.
|
|
1150
|
+
const goal = registry.get(id)?.goal;
|
|
1151
|
+
const definitionId = queryDefinitionId ?? goal;
|
|
1152
|
+
const definitionSource: DefinitionSource = queryDefinitionId
|
|
1153
|
+
? "query"
|
|
1154
|
+
: goal
|
|
1155
|
+
? "goal"
|
|
1156
|
+
: "none";
|
|
1157
|
+
|
|
1158
|
+
const [result, values] = await Promise.all([
|
|
1159
|
+
computeJourneyLift({ db, journeyId: id, since, definitionId }),
|
|
1160
|
+
computeLiftValues({ db, journeyId: id, since, definitionId }),
|
|
1186
1161
|
]);
|
|
1187
|
-
const verdict = computeLift({ treatment, control });
|
|
1188
1162
|
|
|
1189
1163
|
return c.json(
|
|
1190
1164
|
{
|
|
1191
1165
|
journeyId: id,
|
|
1192
1166
|
days,
|
|
1193
1167
|
definitionId: definitionId ?? null,
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
...
|
|
1168
|
+
definitionSource,
|
|
1169
|
+
treatment: { ...result.treatment, value: values.treatment },
|
|
1170
|
+
control: { ...result.control, value: values.control },
|
|
1171
|
+
...result.verdict,
|
|
1197
1172
|
},
|
|
1198
1173
|
200,
|
|
1199
1174
|
);
|
|
1200
1175
|
});
|
|
1201
|
-
|
|
1202
|
-
/** `created_at >= since` as a reusable fragment (lift cohort windows). */
|
|
1203
|
-
function gteCreated(sinceTs: ReturnType<typeof sql>) {
|
|
1204
|
-
return sql`${journeyStates.createdAt} >= ${sinceTs}`;
|
|
1205
|
-
}
|
|
@@ -78,7 +78,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
78
78
|
detail: env.HATCHET_CLIENT_TOKEN
|
|
79
79
|
? `Connected (${env.HATCHET_CLIENT_HOST_PORT}).`
|
|
80
80
|
: "Set HATCHET_CLIENT_TOKEN so the worker can run your journeys.",
|
|
81
|
-
docsUrl: DOCS
|
|
81
|
+
docsUrl: `${DOCS}/docs/getting-started/hatchet`,
|
|
82
82
|
});
|
|
83
83
|
|
|
84
84
|
// 3. Email provider key — sends fail without it.
|
|
@@ -98,7 +98,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
98
98
|
detail: providerKeyPresent
|
|
99
99
|
? `${providerId} key configured.`
|
|
100
100
|
: `No ${providerId} API key yet — sends will fail until one is set.`,
|
|
101
|
-
docsUrl: DOCS
|
|
101
|
+
docsUrl: `${DOCS}/docs/guides/email`,
|
|
102
102
|
});
|
|
103
103
|
|
|
104
104
|
// 4. Data-plane API key — any non-revoked key lets your app code ingest.
|
|
@@ -120,7 +120,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
120
120
|
dataPlaneKeys > 0
|
|
121
121
|
? `${dataPlaneKeys} active key${dataPlaneKeys === 1 ? "" : "s"}.`
|
|
122
122
|
: "Mint one (run bootstrap, or POST /v1/admin/api-keys) so your app can send events.",
|
|
123
|
-
docsUrl: DOCS
|
|
123
|
+
docsUrl: `${DOCS}/docs/data-api/authentication`,
|
|
124
124
|
});
|
|
125
125
|
|
|
126
126
|
// 5. Sending domain — derive from the (now graceful) domain status. A bad
|
|
@@ -134,7 +134,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
134
134
|
status: "optional",
|
|
135
135
|
detail:
|
|
136
136
|
"No EMAIL_DOMAIN set — sends use the provider default. Configure one to send from your own domain.",
|
|
137
|
-
docsUrl: DOCS
|
|
137
|
+
docsUrl: `${DOCS}/docs/operating/production-email`,
|
|
138
138
|
});
|
|
139
139
|
} else if (dom.status?.state === "verified") {
|
|
140
140
|
checks.push({
|
|
@@ -152,7 +152,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
152
152
|
dom.status === null
|
|
153
153
|
? `${dom.domain}: can't read status — confirm your ${providerId} key can read domains.`
|
|
154
154
|
: `${dom.domain} is ${dom.status.state.replace("_", " ")} — verify it below.`,
|
|
155
|
-
docsUrl: DOCS
|
|
155
|
+
docsUrl: `${DOCS}/docs/operating/production-email`,
|
|
156
156
|
});
|
|
157
157
|
}
|
|
158
158
|
} catch {
|
|
@@ -161,7 +161,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
161
161
|
label: "Sending domain",
|
|
162
162
|
status: "action",
|
|
163
163
|
detail: "Couldn't read domain status — check your email provider key.",
|
|
164
|
-
docsUrl: DOCS
|
|
164
|
+
docsUrl: `${DOCS}/docs/operating/production-email`,
|
|
165
165
|
});
|
|
166
166
|
}
|
|
167
167
|
|
|
@@ -175,7 +175,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
175
175
|
detail: analyticsConfigured
|
|
176
176
|
? "Connected."
|
|
177
177
|
: "Optional — connect PostHog to capture events and person properties.",
|
|
178
|
-
docsUrl: DOCS
|
|
178
|
+
docsUrl: `${DOCS}/docs/getting-started/posthog-setup`,
|
|
179
179
|
});
|
|
180
180
|
|
|
181
181
|
// 7–10. Attribution readiness (impact plan §5.4) — the "how's it doing"
|
|
@@ -234,7 +234,7 @@ export const readinessRouter = new OpenAPIHono<AppEnv>().openapi(
|
|
|
234
234
|
: seen
|
|
235
235
|
? okDetail
|
|
236
236
|
: missingDetail,
|
|
237
|
-
docsUrl: `${DOCS}/conversions/impact`,
|
|
237
|
+
docsUrl: `${DOCS}/docs/conversions/impact`,
|
|
238
238
|
});
|
|
239
239
|
checks.push(
|
|
240
240
|
probeCheck(
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
|
|
2
|
+
import type { AppEnv } from "../../app.js";
|
|
3
|
+
import type { HogsendClient } from "../../container.js";
|
|
4
|
+
import {
|
|
5
|
+
deleteOperatorSetting,
|
|
6
|
+
FX_SETTINGS_KEY,
|
|
7
|
+
type FxSetting,
|
|
8
|
+
getOperatorSetting,
|
|
9
|
+
putOperatorSetting,
|
|
10
|
+
} from "../../lib/operator-settings.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Operator settings — the Studio-facing surface over `operator_settings`.
|
|
14
|
+
* Mounted at `/v1/admin/settings`, inheriting `requireAdmin` + `rateLimit` +
|
|
15
|
+
* `auditMiddleware` from the admin router root.
|
|
16
|
+
*
|
|
17
|
+
* Today: `/fx`, the base-currency choice behind the FX lens. The precedence
|
|
18
|
+
* the response makes explicit (mirroring the container's resolver):
|
|
19
|
+
*
|
|
20
|
+
* - a setting ROW with a currency → that currency ("set here")
|
|
21
|
+
* - a setting ROW with null → lens explicitly OFF (beats env)
|
|
22
|
+
* - NO row → env `BASE_CURRENCY`, else off
|
|
23
|
+
*
|
|
24
|
+
* PUT writes/updates the row (a null body value = the explicit off); DELETE
|
|
25
|
+
* removes the row entirely, falling back to env. Every mutation returns the
|
|
26
|
+
* same full state as GET so the Studio card never needs a second fetch.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
const fxStateSchema = z.object({
|
|
30
|
+
// The stored operator choice, or null when no row exists.
|
|
31
|
+
setting: z.object({ baseCurrency: z.string().nullable() }).nullable(),
|
|
32
|
+
// The env bootstrap default (`BASE_CURRENCY`), shown so the card can say
|
|
33
|
+
// where the effective value comes from — and name the static sheet's
|
|
34
|
+
// quoted base when it can't serve the effective one.
|
|
35
|
+
env: z.object({ baseCurrency: z.string().nullable() }),
|
|
36
|
+
// What the lens actually resolves right now (setting ?? env; null = off).
|
|
37
|
+
effective: z.object({ baseCurrency: z.string().nullable() }),
|
|
38
|
+
// The resolved rate source probed against the effective base — null when
|
|
39
|
+
// no provider is configured at all. `servesEffectiveBase: false` with a
|
|
40
|
+
// base set = converted figures will NOT appear (e.g. a USD-quoted static
|
|
41
|
+
// sheet asked for EUR — the honesty rule).
|
|
42
|
+
provider: z
|
|
43
|
+
.object({
|
|
44
|
+
id: z.string(),
|
|
45
|
+
asOf: z.string().nullable(),
|
|
46
|
+
servesEffectiveBase: z.boolean(),
|
|
47
|
+
})
|
|
48
|
+
.nullable(),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const putFxBodySchema = z.object({
|
|
52
|
+
baseCurrency: z
|
|
53
|
+
.string()
|
|
54
|
+
.regex(/^[A-Za-z]{3}$/, "must be a 3-letter ISO-4217 code")
|
|
55
|
+
.transform((v) => v.toUpperCase())
|
|
56
|
+
.nullable(),
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
const getFxRoute = createRoute({
|
|
60
|
+
method: "get",
|
|
61
|
+
path: "/fx",
|
|
62
|
+
tags: ["Admin — Settings"],
|
|
63
|
+
summary: "Get the base-currency (FX lens) setting",
|
|
64
|
+
responses: {
|
|
65
|
+
200: {
|
|
66
|
+
content: { "application/json": { schema: fxStateSchema } },
|
|
67
|
+
description:
|
|
68
|
+
"The stored setting, the env default, the effective base, and the rate source probed against it",
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const putFxRoute = createRoute({
|
|
74
|
+
method: "put",
|
|
75
|
+
path: "/fx",
|
|
76
|
+
tags: ["Admin — Settings"],
|
|
77
|
+
summary: "Set (or explicitly turn off) the base currency",
|
|
78
|
+
description:
|
|
79
|
+
"Upserts the operator's base-currency choice. `baseCurrency: null` is the EXPLICIT off — it beats an env BASE_CURRENCY. To fall back to env instead, DELETE the setting.",
|
|
80
|
+
request: {
|
|
81
|
+
body: {
|
|
82
|
+
content: { "application/json": { schema: putFxBodySchema } },
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
responses: {
|
|
86
|
+
200: {
|
|
87
|
+
content: { "application/json": { schema: fxStateSchema } },
|
|
88
|
+
description: "The updated state (same shape as GET)",
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const deleteFxRoute = createRoute({
|
|
94
|
+
method: "delete",
|
|
95
|
+
path: "/fx",
|
|
96
|
+
tags: ["Admin — Settings"],
|
|
97
|
+
summary: "Clear the base-currency setting (fall back to env)",
|
|
98
|
+
responses: {
|
|
99
|
+
200: {
|
|
100
|
+
content: { "application/json": { schema: fxStateSchema } },
|
|
101
|
+
description:
|
|
102
|
+
"The state after removing the override (idempotent — 200 even when no row existed)",
|
|
103
|
+
},
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
/** Assemble the full GET-shape state the card needs to be honest. */
|
|
108
|
+
async function fxStateOf(container: HogsendClient) {
|
|
109
|
+
const setting = await getOperatorSetting<FxSetting>(
|
|
110
|
+
container.db,
|
|
111
|
+
FX_SETTINGS_KEY,
|
|
112
|
+
);
|
|
113
|
+
const effective = await container.fx.getBaseCurrency();
|
|
114
|
+
// The probe IS getRatesToBase(): it resolves the same effective base per
|
|
115
|
+
// call, so a null sheet with a base set means the source cannot serve it.
|
|
116
|
+
const sheet = effective ? await container.fx.getRatesToBase() : null;
|
|
117
|
+
return {
|
|
118
|
+
setting,
|
|
119
|
+
env: { baseCurrency: container.env.BASE_CURRENCY ?? null },
|
|
120
|
+
effective: { baseCurrency: effective },
|
|
121
|
+
provider: container.fx.providerId
|
|
122
|
+
? {
|
|
123
|
+
id: container.fx.providerId,
|
|
124
|
+
asOf: sheet?.asOf ?? null,
|
|
125
|
+
servesEffectiveBase: sheet !== null,
|
|
126
|
+
}
|
|
127
|
+
: null,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export const settingsRouter = new OpenAPIHono<AppEnv>()
|
|
132
|
+
.openapi(getFxRoute, async (c) => {
|
|
133
|
+
return c.json(await fxStateOf(c.get("container")), 200);
|
|
134
|
+
})
|
|
135
|
+
.openapi(putFxRoute, async (c) => {
|
|
136
|
+
const container = c.get("container");
|
|
137
|
+
const { baseCurrency } = c.req.valid("json");
|
|
138
|
+
await putOperatorSetting(container.db, FX_SETTINGS_KEY, { baseCurrency });
|
|
139
|
+
return c.json(await fxStateOf(container), 200);
|
|
140
|
+
})
|
|
141
|
+
.openapi(deleteFxRoute, async (c) => {
|
|
142
|
+
const container = c.get("container");
|
|
143
|
+
await deleteOperatorSetting(container.db, FX_SETTINGS_KEY);
|
|
144
|
+
return c.json(await fxStateOf(container), 200);
|
|
145
|
+
});
|