@hogsend/engine 0.36.1 → 0.37.1

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hogsend/engine",
3
- "version": "0.36.1",
3
+ "version": "0.37.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -42,14 +42,14 @@
42
42
  "svix": "^1.95.1",
43
43
  "winston": "^3.19.0",
44
44
  "zod": "^4.4.3",
45
- "@hogsend/core": "^0.36.1",
46
- "@hogsend/db": "^0.36.1",
47
- "@hogsend/email": "^0.36.1",
48
- "@hogsend/plugin-posthog": "^0.36.1",
49
- "@hogsend/plugin-resend": "^0.36.1"
45
+ "@hogsend/core": "^0.37.1",
46
+ "@hogsend/db": "^0.37.1",
47
+ "@hogsend/email": "^0.37.1",
48
+ "@hogsend/plugin-posthog": "^0.37.1",
49
+ "@hogsend/plugin-resend": "^0.37.1"
50
50
  },
51
51
  "optionalDependencies": {
52
- "@hogsend/plugin-postmark": "^0.36.1"
52
+ "@hogsend/plugin-postmark": "^0.37.1"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@types/node": "^22.15.3",
package/src/index.ts CHANGED
@@ -435,6 +435,8 @@ export {
435
435
  SEMANTIC_BURST_WINDOW_MS,
436
436
  } from "./lib/semantic-click.js";
437
437
  export { type MountStudioResult, mountStudio } from "./lib/studio.js";
438
+ // --- In-app survey/rating (sendSurvey — producer sugar over sendFeedItem) ---
439
+ export { type SendSurveyOptions, sendSurvey } from "./lib/survey.js";
438
440
  export {
439
441
  type ResolveTimezoneInput,
440
442
  type ResolveTimezoneResult,
@@ -0,0 +1,50 @@
1
+ import type { FeedBlock } from "@hogsend/db";
2
+ import { type SendFeedItemResult, sendFeedItem } from "./feed.js";
3
+
4
+ /** The survey block's own fields (event/mode/property/…), minus the discriminant. */
5
+ type SurveyBlockFields = Omit<Extract<FeedBlock, { type: "survey" }>, "type">;
6
+
7
+ /**
8
+ * Options for {@link sendSurvey} — the producer sugar that drops a `survey`
9
+ * feed block into a recipient's in-app feed. Thin over {@link sendFeedItem}, so
10
+ * it inherits the full pipeline (recipient resolution, `in_app` suppression,
11
+ * replay-safe idempotency, Redis realtime publish).
12
+ */
13
+ export interface SendSurveyOptions extends SurveyBlockFields {
14
+ recipient: { userId?: string; email?: string; anonymousId?: string };
15
+ title?: string;
16
+ category?: string;
17
+ idempotencyKey?: string;
18
+ idempotencyLabel?: string;
19
+ }
20
+
21
+ /**
22
+ * Journey-callable in-app survey send — producer sugar over {@link sendFeedItem}.
23
+ * Builds a single `survey` feed block from `opts` and delegates, so the in-app
24
+ * survey/rating primitive gets the SAME exactly-once replay-safety and `in_app`
25
+ * suppression as any other feed send. The answer the recipient picks is captured
26
+ * onto the spine by `<SurveyBlockView>` and lands in `user_events` — readable by
27
+ * a journey via `ctx.waitForEvent → properties` and by
28
+ * `GET /v1/admin/reporting/breakdown`.
29
+ */
30
+ export function sendSurvey(
31
+ opts: SendSurveyOptions,
32
+ ): Promise<SendFeedItemResult> {
33
+ const {
34
+ recipient,
35
+ title,
36
+ category,
37
+ idempotencyKey,
38
+ idempotencyLabel,
39
+ ...survey
40
+ } = opts;
41
+ return sendFeedItem({
42
+ recipient,
43
+ type: "survey",
44
+ ...(title !== undefined ? { title } : {}),
45
+ blocks: [{ type: "survey", ...survey }],
46
+ ...(category !== undefined ? { category } : {}),
47
+ ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),
48
+ ...(idempotencyLabel !== undefined ? { idempotencyLabel } : {}),
49
+ });
50
+ }
@@ -1,4 +1,4 @@
1
- import { emailSends } from "@hogsend/db";
1
+ import { emailSends, userEvents } from "@hogsend/db";
2
2
  import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
3
3
  import {
4
4
  and,
@@ -143,6 +143,47 @@ const contactActivityRoute = createRoute({
143
143
  },
144
144
  });
145
145
 
146
+ // ---------------------------------------------------------------------------
147
+ // GET /breakdown — aggregate ANY event by a scalar property value (count,
148
+ // average, optional NPS) over user_events.properties. Surveys are one caller.
149
+ // ---------------------------------------------------------------------------
150
+
151
+ const breakdownRoute = createRoute({
152
+ method: "get",
153
+ path: "/breakdown",
154
+ tags: ["Admin — Reporting"],
155
+ summary:
156
+ "Aggregate any event by a property value (count, average, optional NPS)",
157
+ request: {
158
+ query: z.object({
159
+ event: z.string().min(1),
160
+ property: z.string().default("value"),
161
+ from: z.string().datetime().optional(),
162
+ to: z.string().datetime().optional(),
163
+ metric: z.enum(["nps"]).optional(),
164
+ }),
165
+ },
166
+ responses: {
167
+ 200: {
168
+ content: {
169
+ "application/json": {
170
+ schema: z.object({
171
+ event: z.string(),
172
+ property: z.string(),
173
+ total: z.number(),
174
+ breakdown: z.array(
175
+ z.object({ answer: z.string(), count: z.number() }),
176
+ ),
177
+ average: z.number().nullable(),
178
+ nps: z.number().nullable(),
179
+ }),
180
+ },
181
+ },
182
+ description: "Per-answer counts plus computed average / NPS",
183
+ },
184
+ },
185
+ });
186
+
146
187
  const MAX_EXPORT_ROWS = 50_000;
147
188
 
148
189
  function csvCell(value: unknown): string {
@@ -282,6 +323,78 @@ export const reportingRouter = new OpenAPIHono<AppEnv>()
282
323
  },
283
324
  200,
284
325
  );
326
+ })
327
+ .openapi(breakdownRoute, async (c) => {
328
+ const { db } = c.get("container");
329
+ const { event, property, from, to, metric } = c.req.valid("query");
330
+
331
+ // GROUP BY user_events.properties ->> '<property>'. The property key is a
332
+ // bound parameter (never interpolated); the `::text` cast disambiguates
333
+ // `->>` from its integer (array-index) overload so Postgres can resolve it.
334
+ const answerExpr = sql<string>`${userEvents.properties} ->> ${property}::text`;
335
+
336
+ const conditions = [
337
+ eq(userEvents.event, event),
338
+ sql`${answerExpr} is not null`,
339
+ ];
340
+ if (from) conditions.push(gte(userEvents.occurredAt, new Date(from)));
341
+ if (to) conditions.push(lte(userEvents.occurredAt, new Date(to)));
342
+
343
+ // GROUP BY / ORDER BY the first output column by ordinal (the spec's
344
+ // `GROUP BY 1 ORDER BY 1`) — matching the grouped expression by position
345
+ // avoids Postgres treating the repeated `->>` param as a distinct column.
346
+ const rows = await db
347
+ .select({ answer: answerExpr, count: count() })
348
+ .from(userEvents)
349
+ .where(and(...conditions))
350
+ .groupBy(sql`1`)
351
+ .orderBy(sql`1`);
352
+
353
+ const breakdown = rows.map((r) => ({
354
+ answer: String(r.answer),
355
+ count: Number(r.count),
356
+ }));
357
+ const total = breakdown.reduce((sum, b) => sum + b.count, 0);
358
+
359
+ // average = Σ(numeric(answer) * count) / total — only when EVERY answer
360
+ // parses numeric (else null). NaN/empty short-circuits to non-numeric.
361
+ let numericSum = 0;
362
+ let allNumeric = breakdown.length > 0;
363
+ for (const b of breakdown) {
364
+ const n = Number(b.answer);
365
+ if (b.answer === "" || Number.isNaN(n)) {
366
+ allNumeric = false;
367
+ break;
368
+ }
369
+ numericSum += n * b.count;
370
+ }
371
+ const average =
372
+ allNumeric && total > 0
373
+ ? Math.round((numericSum / total) * 100) / 100
374
+ : null;
375
+
376
+ // nps = %(answer ∈ 9..10) − %(answer ∈ 0..6), when metric === "nps" or the
377
+ // answers look like a 0..10 integer scale (else null).
378
+ const looks0to10 =
379
+ allNumeric &&
380
+ breakdown.length > 0 &&
381
+ breakdown.every((b) => {
382
+ const n = Number(b.answer);
383
+ return Number.isInteger(n) && n >= 0 && n <= 10;
384
+ });
385
+ let nps: number | null = null;
386
+ if ((metric === "nps" || looks0to10) && allNumeric && total > 0) {
387
+ let promoters = 0;
388
+ let detractors = 0;
389
+ for (const b of breakdown) {
390
+ const n = Number(b.answer);
391
+ if (n >= 9 && n <= 10) promoters += b.count;
392
+ else if (n >= 0 && n <= 6) detractors += b.count;
393
+ }
394
+ nps = Math.round(((promoters - detractors) / total) * 100);
395
+ }
396
+
397
+ return c.json({ event, property, total, breakdown, average, nps }, 200);
285
398
  });
286
399
 
287
400
  // CSV export — plain route (non-JSON response) under the same auth as the rest
@@ -26,6 +26,21 @@ const listSummarySchema = z.object({
26
26
  name: z.string(),
27
27
  description: z.string().optional(),
28
28
  defaultOptIn: z.boolean(),
29
+ // The resolved opt-in state for the identity in the query (`categories[id] ??
30
+ // defaultOptIn`). An anon / publishable / no-identity read degrades to
31
+ // `defaultOptIn` (never leaks another contact's state — mirrors the
32
+ // `/preferences` gate). This makes ONE catalog call power a preference matrix.
33
+ subscribed: z.boolean(),
34
+ });
35
+
36
+ // `GET /` accepts the SAME identity query as `/preferences` so a single call can
37
+ // return the catalog WITH each list's resolved `subscribed`. Identity is
38
+ // OPTIONAL here (the catalog itself is always returned); when absent (or on a
39
+ // publishable key) every `subscribed` falls back to `defaultOptIn`.
40
+ const listQuerySchema = z.object({
41
+ userId: z.string().optional(),
42
+ email: z.string().optional(),
43
+ anonymousId: z.string().optional(),
29
44
  });
30
45
 
31
46
  const bodySchema = z.object({
@@ -41,7 +56,8 @@ const listRoute = createRoute({
41
56
  tags: ["Lists"],
42
57
  summary: "List defined email lists",
43
58
  description:
44
- "Returns the enabled, code-defined email lists (D3). Membership lives in `email_preferences.categories`; this only enumerates the catalog.",
59
+ "Returns the enabled, code-defined email lists (D3) with each list's resolved `subscribed` state for the (optional) identity in the query. Membership lives in `email_preferences.categories`; this enumerates the catalog and folds in the contact's opt-in map in one call.",
60
+ request: { query: listQuerySchema },
45
61
  responses: {
46
62
  200: {
47
63
  content: {
@@ -251,15 +267,44 @@ async function applyListSubscription(opts: {
251
267
  // `requireScope("ingest")` to `/v1/lists` (bare + `/*`) before requests reach
252
268
  // this router. Mounting auth here too would double the middleware.
253
269
  export const listsRouter = new OpenAPIHono<AppEnv>()
254
- .openapi(listRoute, (c) => {
255
- const lists = getListRegistry()
256
- .getEnabled()
257
- .map((l) => ({
258
- id: l.id,
259
- name: l.name,
260
- ...(l.description !== undefined ? { description: l.description } : {}),
261
- defaultOptIn: l.defaultOptIn,
262
- }));
270
+ .openapi(listRoute, async (c) => {
271
+ const { db } = c.get("container");
272
+ const { userId, email } = c.req.valid("query");
273
+ const enabled = getListRegistry().getEnabled();
274
+
275
+ // Best-effort subscription enrichment. ONLY a secret key with a concrete
276
+ // identity (email/userId) reads another contact's category map; a
277
+ // publishable key — or an anon / no-identity read — degrades to
278
+ // `defaultOptIn` (no leak, mirroring the `/preferences` 403 on a publishable
279
+ // concrete read). Reuses the same `resolveRecipient` + `extId` lookup so the
280
+ // catalog and the matrix stay one call.
281
+ let categories: Record<string, boolean> = {};
282
+ if ((userId || email) && !c.get("publishable")) {
283
+ const recipient = await resolveRecipient({ db, userId, email });
284
+ if (recipient) {
285
+ const extId = recipient.externalId ?? recipient.contactId;
286
+ const rows = await db
287
+ .select()
288
+ .from(emailPreferences)
289
+ .where(
290
+ and(
291
+ eq(emailPreferences.userId, extId),
292
+ eq(emailPreferences.email, recipient.email),
293
+ ),
294
+ )
295
+ .limit(1);
296
+ const row = rows[0];
297
+ if (row) categories = serializePrefs(row).categories;
298
+ }
299
+ }
300
+
301
+ const lists = enabled.map((l) => ({
302
+ id: l.id,
303
+ name: l.name,
304
+ ...(l.description !== undefined ? { description: l.description } : {}),
305
+ defaultOptIn: l.defaultOptIn,
306
+ subscribed: categories[l.id] ?? l.defaultOptIn,
307
+ }));
263
308
 
264
309
  return c.json({ lists }, 200);
265
310
  })