@venturekit/notify 0.0.37 → 0.0.39

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 CHANGED
@@ -380,6 +380,57 @@ Available helpers:
380
380
  - `listUserPreferences(client, userId)` / `upsertUserPreference(client, ...)` — per-user opt-in management
381
381
  - `listNotificationsForUser(client, userId, options)` — buyer-portal inbox view
382
382
 
383
+ ## In-app inbox (the bell)
384
+
385
+ `@venturekit/notify/inbox` is the notification centre: rows a user reads and
386
+ dismisses, in their own table (`vk_inbox_notifications`), independent of the
387
+ delivery outbox above. Rows carry a stored `title`/`body` plus
388
+ `messageKey` + `messageParams` so the client can re-render in the reader's
389
+ locale; `groupKey` collapses repeats ("3 new comments") into one entry.
390
+
391
+ ```ts
392
+ import { createInboxNotification, listInbox, unreadInboxCount, markInboxRead, markAllInboxRead } from '@venturekit/notify/inbox';
393
+
394
+ // fan-out, in the same transaction as the change
395
+ await createInboxNotification(tx.query, {
396
+ userId: post.authorId, type: 'post_comment',
397
+ title: `${actor.name} commented on your post`,
398
+ messageKey: 'post_comment', messageParams: { name: actor.name },
399
+ referenceKind: 'post', referenceId: post.id,
400
+ });
401
+
402
+ // GET /notifications?before=… GET /activity POST /notifications/read
403
+ const page = await listInbox(query, { userId, unreadOnly: false, limit: 20, before });
404
+ const unread = await unreadInboxCount(query, { userId, types: enabledTypes });
405
+ await markInboxRead(query, { userId, ids }); // always user-scoped
406
+ await markAllInboxRead(query, { userId, before: seenAt });
407
+ ```
408
+
409
+ `pruneInbox(query, { olderThanDays: 90 })` is the retention sweep for a cron.
410
+ Per-type preferences and realtime badge pushes stay in the app — the module
411
+ owns the rows, not the policy.
412
+
413
+ **Digests.** Real-time in-app, e-mail only when the user was away:
414
+
415
+ ```ts
416
+ // src/crons/inbox-digest.ts (schedules: rate 1 hour)
417
+ export const main = taskHandler(() =>
418
+ runInboxDigest(query, {
419
+ enqueue: (input) => notify.enqueue(input), // your client → templates, preferences, suppression apply
420
+ templateKey: 'inbox_digest',
421
+ minAgeMinutes: 30, maxPerUserPerDay: 1,
422
+ shouldSend: (userId) => prefs.emailDigestsEnabled(userId),
423
+ }),
424
+ );
425
+ ```
426
+
427
+ One e-mail per user with their unread rows since the last digest; a per-user
428
+ cursor (`vk_inbox_digest_cursor`) makes retries idempotent.
429
+
430
+ **Frequency caps** (`@venturekit/notify/policy`): `checkFrequencyCap(query, { userId, channel: 'email', max: 3, windowDays: 7, excludeTemplateKeys: ['password_reset'] })`
431
+ answers `{ allowed, remaining, windowResetsAt }` against the outbox — apply it to
432
+ the categories a user may opt out of; transactional templates are never asked.
433
+
383
434
  ## Local dev (`vk dev`)
384
435
 
385
436
  Declaring a notify intent with the `email` channel adds a **MailHog** service to `~/.vk/docker-compose.yml`:
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Inbox digests — turn what a user has NOT read into one e-mail instead of
3
+ * one per event.
4
+ *
5
+ * The rule most products settle on: real-time in-app, e-mail only when the
6
+ * user was away. A cron (hourly or daily) calls {@link runInboxDigest}:
7
+ * it finds users with unread inbox rows created since their last digest,
8
+ * groups the rows per user, applies the frequency cap the caller chooses,
9
+ * enqueues ONE notification per user through the caller's `enqueue`
10
+ * (the notify client's, so templates / preferences / suppression apply
11
+ * as usual), and stamps `vk_inbox_digest_cursor` so the next run starts
12
+ * where this one ended — idempotent across retries.
13
+ *
14
+ * ```ts
15
+ * // src/crons/inbox-digest.ts (schedule: rate 1 hour)
16
+ * export const main = taskHandler(async () =>
17
+ * runInboxDigest(query, {
18
+ * enqueue: (input) => notify.enqueue(input),
19
+ * templateKey: 'inbox_digest',
20
+ * minAgeMinutes: 30, // give the user a chance to read in-app first
21
+ * maxPerUserPerDay: 1,
22
+ * }),
23
+ * );
24
+ * ```
25
+ *
26
+ * Table: `vk_inbox_digest_cursor` (migration `vk_notify_004`).
27
+ */
28
+ import type { InboxNotification, Querier } from './inbox.js';
29
+ export interface DigestEnqueueInput {
30
+ recipientUserId: string;
31
+ channel: 'email';
32
+ templateKey: string;
33
+ payload: {
34
+ /** Unread rows in the digest, newest first. */
35
+ items: Array<Pick<InboxNotification, 'id' | 'type' | 'title' | 'body' | 'messageKey' | 'messageParams' | 'referenceKind' | 'referenceId' | 'createdAt'>>;
36
+ /** Total unread for the user (may exceed `items` when capped by `maxItems`). */
37
+ unreadCount: number;
38
+ };
39
+ relatedKind: 'inbox_digest';
40
+ relatedId: string;
41
+ }
42
+ export interface RunInboxDigestOptions {
43
+ /** Typically `(input) => notify.enqueue(input)`. */
44
+ enqueue: (input: DigestEnqueueInput) => Promise<unknown>;
45
+ /** Template rendered by the notify client. */
46
+ templateKey: string;
47
+ /** Tenant scope; omit for all. */
48
+ tenantId?: string | null;
49
+ /**
50
+ * Only rows older than this are eligible — the user may still read them
51
+ * in-app. Default 30.
52
+ */
53
+ minAgeMinutes?: number;
54
+ /** Rows per digest (newest first). Default 20. */
55
+ maxItems?: number;
56
+ /** At most this many digests per user per rolling day. Default 1. */
57
+ maxPerUserPerDay?: number;
58
+ /** Users per run (the cron's batch). Default 200. */
59
+ maxUsers?: number;
60
+ /** Only these inbox types are digested (e.g. the ones the user has e-mail enabled for). */
61
+ types?: string[];
62
+ /** Skip a user (preferences, suppressed address, …). */
63
+ shouldSend?: (userId: string) => Promise<boolean> | boolean;
64
+ now?: () => Date;
65
+ }
66
+ export interface InboxDigestResult {
67
+ usersConsidered: number;
68
+ digestsSent: number;
69
+ skippedByCap: number;
70
+ skippedByCallback: number;
71
+ }
72
+ /** One cron tick. Safe to re-run: the cursor makes an already-digested window empty. */
73
+ export declare function runInboxDigest(querier: Querier, options: RunInboxDigestOptions): Promise<InboxDigestResult>;
74
+ //# sourceMappingURL=digest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"digest.d.ts","sourceRoot":"","sources":["../../src/inbox/digest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,KAAK,EAAE,iBAAiB,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,YAAY,EAAE,MAAM,CAAC;IACrB,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AASD,wFAAwF;AACxF,wBAAsB,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CA+FjH"}
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Inbox digests — turn what a user has NOT read into one e-mail instead of
3
+ * one per event.
4
+ *
5
+ * The rule most products settle on: real-time in-app, e-mail only when the
6
+ * user was away. A cron (hourly or daily) calls {@link runInboxDigest}:
7
+ * it finds users with unread inbox rows created since their last digest,
8
+ * groups the rows per user, applies the frequency cap the caller chooses,
9
+ * enqueues ONE notification per user through the caller's `enqueue`
10
+ * (the notify client's, so templates / preferences / suppression apply
11
+ * as usual), and stamps `vk_inbox_digest_cursor` so the next run starts
12
+ * where this one ended — idempotent across retries.
13
+ *
14
+ * ```ts
15
+ * // src/crons/inbox-digest.ts (schedule: rate 1 hour)
16
+ * export const main = taskHandler(async () =>
17
+ * runInboxDigest(query, {
18
+ * enqueue: (input) => notify.enqueue(input),
19
+ * templateKey: 'inbox_digest',
20
+ * minAgeMinutes: 30, // give the user a chance to read in-app first
21
+ * maxPerUserPerDay: 1,
22
+ * }),
23
+ * );
24
+ * ```
25
+ *
26
+ * Table: `vk_inbox_digest_cursor` (migration `vk_notify_004`).
27
+ */
28
+ /** One cron tick. Safe to re-run: the cursor makes an already-digested window empty. */
29
+ export async function runInboxDigest(querier, options) {
30
+ const minAge = options.minAgeMinutes ?? 30;
31
+ const maxItems = Math.min(Math.max(1, options.maxItems ?? 20), 100);
32
+ const maxPerDay = Math.max(1, options.maxPerUserPerDay ?? 1);
33
+ const maxUsers = Math.min(Math.max(1, options.maxUsers ?? 200), 1000);
34
+ const now = options.now ?? (() => new Date());
35
+ const params = [minAge];
36
+ const where = ['n.read_at IS NULL', 'n.created_at <= now() - make_interval(mins => $1)', 'n.created_at > COALESCE(c.last_digest_at, to_timestamp(0))'];
37
+ if (options.tenantId !== undefined) {
38
+ if (options.tenantId === null)
39
+ where.push('n.tenant_id IS NULL');
40
+ else {
41
+ params.push(options.tenantId);
42
+ where.push(`n.tenant_id = $${params.length}`);
43
+ }
44
+ }
45
+ if (options.types && options.types.length > 0) {
46
+ params.push(options.types);
47
+ where.push(`n.type = ANY($${params.length}::text[])`);
48
+ }
49
+ params.push(maxUsers);
50
+ const candidates = await querier(`SELECT n.user_id AS "userId",
51
+ count(*)::int AS "unreadCount",
52
+ max(c.last_digest_at) AS "lastDigestAt",
53
+ COALESCE(max(c.sent_today), 0)::int AS "digestsToday"
54
+ FROM vk_inbox_notifications n
55
+ LEFT JOIN vk_inbox_digest_cursor c ON c.user_id = n.user_id
56
+ WHERE ${where.join(' AND ')}
57
+ GROUP BY n.user_id
58
+ ORDER BY min(n.created_at)
59
+ LIMIT $${params.length}`, params);
60
+ const result = { usersConsidered: candidates.length, digestsSent: 0, skippedByCap: 0, skippedByCallback: 0 };
61
+ for (const c of candidates) {
62
+ const lastAt = c.lastDigestAt ? new Date(c.lastDigestAt) : null;
63
+ const withinDay = lastAt !== null && now().getTime() - lastAt.getTime() < 86_400_000;
64
+ const sentToday = withinDay ? Number(c.digestsToday) : 0;
65
+ if (sentToday >= maxPerDay) {
66
+ result.skippedByCap++;
67
+ continue;
68
+ }
69
+ if (options.shouldSend && !(await options.shouldSend(c.userId))) {
70
+ result.skippedByCallback++;
71
+ continue;
72
+ }
73
+ const itemParams = [c.userId, minAge];
74
+ const itemWhere = ['user_id = $1', 'read_at IS NULL', 'created_at <= now() - make_interval(mins => $2)'];
75
+ if (options.types && options.types.length > 0) {
76
+ itemParams.push(options.types);
77
+ itemWhere.push(`type = ANY($${itemParams.length}::text[])`);
78
+ }
79
+ itemParams.push(maxItems);
80
+ const items = await querier(`SELECT id, type, title, body, message_key AS "messageKey", message_params AS "messageParams",
81
+ reference_kind AS "referenceKind", reference_id AS "referenceId", created_at AS "createdAt"
82
+ FROM vk_inbox_notifications
83
+ WHERE ${itemWhere.join(' AND ')}
84
+ ORDER BY created_at DESC
85
+ LIMIT $${itemParams.length}`, itemParams);
86
+ if (items.length === 0)
87
+ continue;
88
+ const digestId = `digest_${c.userId}_${now().getTime()}`;
89
+ await options.enqueue({
90
+ recipientUserId: c.userId,
91
+ channel: 'email',
92
+ templateKey: options.templateKey,
93
+ payload: { items, unreadCount: Number(c.unreadCount) },
94
+ relatedKind: 'inbox_digest',
95
+ relatedId: digestId,
96
+ });
97
+ // Advance the cursor to the newest row included, so a row created
98
+ // during this run is picked up next time rather than lost.
99
+ const newest = items.reduce((max, i) => (new Date(i.createdAt) > max ? new Date(i.createdAt) : max), new Date(0));
100
+ await querier(`INSERT INTO vk_inbox_digest_cursor (user_id, last_digest_at, sent_today)
101
+ VALUES ($1, $2, 1)
102
+ ON CONFLICT (user_id) DO UPDATE SET
103
+ sent_today = CASE WHEN vk_inbox_digest_cursor.last_digest_at > now() - interval '1 day'
104
+ THEN vk_inbox_digest_cursor.sent_today + 1 ELSE 1 END,
105
+ last_digest_at = GREATEST(vk_inbox_digest_cursor.last_digest_at, EXCLUDED.last_digest_at)`, [c.userId, newest]);
106
+ result.digestsSent++;
107
+ }
108
+ return result;
109
+ }
110
+ //# sourceMappingURL=digest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"digest.js","sourceRoot":"","sources":["../../src/inbox/digest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAyDH,wFAAwF;AACxF,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,OAAgB,EAAE,OAA8B;IACnF,MAAM,MAAM,GAAG,OAAO,CAAC,aAAa,IAAI,EAAE,CAAC;IAC3C,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,QAAQ,IAAI,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;IACpE,MAAM,SAAS,GAAG,IAAI,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,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC1B,MAAM,KAAK,GAAG,MAAM,OAAO,CACzB;;;eAGS,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC;;gBAEtB,UAAU,CAAC,MAAM,EAAE,EAC7B,UAAU,CACX,CAAC;QACF,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QAEjC,MAAM,QAAQ,GAAG,UAAU,CAAC,CAAC,MAAM,IAAI,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC;QACzD,MAAM,OAAO,CAAC,OAAO,CAAC;YACpB,eAAe,EAAE,CAAC,CAAC,MAAM;YACzB,OAAO,EAAE,OAAO;YAChB,WAAW,EAAE,OAAO,CAAC,WAAW;YAChC,OAAO,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE;YACtD,WAAW,EAAE,cAAc;YAC3B,SAAS,EAAE,QAAQ;SACpB,CAAC,CAAC;QAEH,kEAAkE;QAClE,2DAA2D;QAC3D,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QAClH,MAAM,OAAO,CACX;;;;;mGAK6F,EAC7F,CAAC,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CACnB,CAAC;QACF,MAAM,CAAC,WAAW,EAAE,CAAC;IACvB,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,125 @@
1
+ /**
2
+ * In-app inbox — the notification centre behind the bell icon.
3
+ *
4
+ * Separate from the delivery outbox (`vk_notifications`): an inbox row is
5
+ * state the user reads and dismisses, not a message that reaches a
6
+ * terminal status. Nothing here goes through a provider or the dispatcher.
7
+ *
8
+ * ```ts
9
+ * import { createInboxNotification, listInbox, unreadInboxCount, markInboxRead } from '@venturekit/notify/inbox';
10
+ *
11
+ * // Fan-out from your domain code (same transaction as the change)
12
+ * await createInboxNotification(tx.query, {
13
+ * userId: post.authorId,
14
+ * type: 'post_comment',
15
+ * title: `${commenter.name} commented on your post`,
16
+ * messageKey: 'post_comment', messageParams: { name: commenter.name },
17
+ * referenceKind: 'post', referenceId: post.id,
18
+ * });
19
+ *
20
+ * // GET /notifications, GET /activity, POST /notifications/read
21
+ * const page = await listInbox(query, { userId, unreadOnly: true, limit: 20 });
22
+ * const unread = await unreadInboxCount(query, { userId });
23
+ * await markInboxRead(query, { userId, ids: ['notif_…'] });
24
+ * ```
25
+ *
26
+ * Typical companions the app keeps for itself: a per-type preference matrix
27
+ * (mute `post_comment` in-app), a realtime push of `{ unread }` to open
28
+ * tabs, and e-mail digests for what stayed unread.
29
+ *
30
+ * Table: `vk_inbox_notifications` (this package's migrations).
31
+ */
32
+ /** `@venturekit/data`'s `query` / `tx.query` shape. Rows are aliased to camelCase in SQL. */
33
+ export type Querier = <T = Record<string, unknown>[]>(sql: string, params?: unknown[]) => Promise<T>;
34
+ export interface InboxNotification {
35
+ id: string;
36
+ userId: string;
37
+ tenantId: string | null;
38
+ type: string;
39
+ title: string;
40
+ body: string | null;
41
+ messageKey: string | null;
42
+ messageParams: Record<string, unknown>;
43
+ referenceKind: string | null;
44
+ referenceId: string | null;
45
+ data: Record<string, unknown>;
46
+ groupKey: string | null;
47
+ readAt: Date | null;
48
+ createdAt: Date;
49
+ updatedAt: Date;
50
+ }
51
+ export interface CreateInboxNotificationInput {
52
+ userId: string;
53
+ tenantId?: string | null;
54
+ type: string;
55
+ /** Complete sentence in the sender's locale — the fallback rendition. */
56
+ title: string;
57
+ body?: string | null;
58
+ /** Catalog key + data-only params so the client renders in the reader's locale. */
59
+ messageKey?: string | null;
60
+ messageParams?: Record<string, unknown>;
61
+ referenceKind?: string | null;
62
+ referenceId?: string | null;
63
+ data?: Record<string, unknown>;
64
+ /**
65
+ * Collapse key. A new notification with the same key for the same user
66
+ * replaces the existing one (content refreshed, `read_at` reset,
67
+ * `created_at` moved to now) instead of piling up.
68
+ */
69
+ groupKey?: string | null;
70
+ }
71
+ export interface ListInboxOptions {
72
+ userId: string;
73
+ tenantId?: string | null;
74
+ unreadOnly?: boolean;
75
+ /** Restrict to these types (e.g. the ones the user has not muted). */
76
+ types?: string[];
77
+ /** Keyset cursor: rows created strictly before this instant. */
78
+ before?: Date;
79
+ /** 1..100, default 20. */
80
+ limit?: number;
81
+ }
82
+ /** `notif_` + UUID without dashes — recognisable in logs and URLs. */
83
+ export declare function generateInboxId(): string;
84
+ /**
85
+ * Write one inbox row. With `groupKey`, an existing row for the same user
86
+ * and key is replaced (upsert) so repeated events collapse into one entry.
87
+ */
88
+ export declare function createInboxNotification(querier: Querier, input: CreateInboxNotificationInput): Promise<InboxNotification>;
89
+ /** A user's inbox, newest first, keyset-paginated on `createdAt`. */
90
+ export declare function listInbox(querier: Querier, options: ListInboxOptions): Promise<InboxNotification[]>;
91
+ /** Badge count. `types` lets the app exclude muted types. */
92
+ export declare function unreadInboxCount(querier: Querier, options: {
93
+ userId: string;
94
+ tenantId?: string | null;
95
+ types?: string[];
96
+ }): Promise<number>;
97
+ /**
98
+ * Mark rows read. Scoped to `userId` so a client can never flip someone
99
+ * else's rows by guessing ids. Returns the number of rows changed.
100
+ */
101
+ export declare function markInboxRead(querier: Querier, options: {
102
+ userId: string;
103
+ ids: string[];
104
+ }): Promise<number>;
105
+ /** "Mark all as read" — optionally only rows created up to `before` (what the user has seen). */
106
+ export declare function markAllInboxRead(querier: Querier, options: {
107
+ userId: string;
108
+ tenantId?: string | null;
109
+ before?: Date;
110
+ }): Promise<number>;
111
+ /** Remove one row (user-scoped). */
112
+ export declare function deleteInboxNotification(querier: Querier, options: {
113
+ userId: string;
114
+ id: string;
115
+ }): Promise<boolean>;
116
+ /**
117
+ * Retention sweep for a cron: delete READ rows older than `olderThanDays`
118
+ * (default 90) and, optionally, unread rows older than `unreadOlderThanDays`.
119
+ * Returns the number removed.
120
+ */
121
+ export declare function pruneInbox(querier: Querier, options?: {
122
+ olderThanDays?: number;
123
+ unreadOlderThanDays?: number;
124
+ }): Promise<number>;
125
+ //# sourceMappingURL=inbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inbox.d.ts","sourceRoot":"","sources":["../../src/inbox/inbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAIH,6FAA6F;AAC7F,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EAClD,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,OAAO,EAAE,KACf,OAAO,CAAC,CAAC,CAAC,CAAC;AAEhB,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACvC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9B,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,EAAE,IAAI,GAAG,IAAI,CAAC;IACpB,SAAS,EAAE,IAAI,CAAC;IAChB,SAAS,EAAE,IAA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A6D;AAC7D,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,GACtE,OAAO,CAAC,MAAM,CAAC,CAmBjB;AAED;;;GAGG;AACH,wBAAsB,aAAa,CACjC,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,EAAE,CAAA;CAAE,GACzC,OAAO,CAAC,MAAM,CAAC,CASjB;AAED,iGAAiG;AACjG,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,MAAM,CAAC,EAAE,IAAI,CAAA;CAAE,GACnE,OAAO,CAAC,MAAM,CAAC,CAqBjB;AAED,oCAAoC;AACpC,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GACtC,OAAO,CAAC,OAAO,CAAC,CAMlB;AAED;;;;GAIG;AACH,wBAAsB,UAAU,CAC9B,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAC;IAAC,mBAAmB,CAAC,EAAE,MAAM,CAAA;CAAO,GACrE,OAAO,CAAC,MAAM,CAAC,CAajB"}
@@ -0,0 +1,202 @@
1
+ /**
2
+ * In-app inbox — the notification centre behind the bell icon.
3
+ *
4
+ * Separate from the delivery outbox (`vk_notifications`): an inbox row is
5
+ * state the user reads and dismisses, not a message that reaches a
6
+ * terminal status. Nothing here goes through a provider or the dispatcher.
7
+ *
8
+ * ```ts
9
+ * import { createInboxNotification, listInbox, unreadInboxCount, markInboxRead } from '@venturekit/notify/inbox';
10
+ *
11
+ * // Fan-out from your domain code (same transaction as the change)
12
+ * await createInboxNotification(tx.query, {
13
+ * userId: post.authorId,
14
+ * type: 'post_comment',
15
+ * title: `${commenter.name} commented on your post`,
16
+ * messageKey: 'post_comment', messageParams: { name: commenter.name },
17
+ * referenceKind: 'post', referenceId: post.id,
18
+ * });
19
+ *
20
+ * // GET /notifications, GET /activity, POST /notifications/read
21
+ * const page = await listInbox(query, { userId, unreadOnly: true, limit: 20 });
22
+ * const unread = await unreadInboxCount(query, { userId });
23
+ * await markInboxRead(query, { userId, ids: ['notif_…'] });
24
+ * ```
25
+ *
26
+ * Typical companions the app keeps for itself: a per-type preference matrix
27
+ * (mute `post_comment` in-app), a realtime push of `{ unread }` to open
28
+ * tabs, and e-mail digests for what stayed unread.
29
+ *
30
+ * Table: `vk_inbox_notifications` (this package's migrations).
31
+ */
32
+ import { randomUUID } from 'node:crypto';
33
+ const COLUMNS = `
34
+ id,
35
+ user_id AS "userId",
36
+ tenant_id AS "tenantId",
37
+ type,
38
+ title,
39
+ body,
40
+ message_key AS "messageKey",
41
+ message_params AS "messageParams",
42
+ reference_kind AS "referenceKind",
43
+ reference_id AS "referenceId",
44
+ data,
45
+ group_key AS "groupKey",
46
+ read_at AS "readAt",
47
+ created_at AS "createdAt",
48
+ updated_at AS "updatedAt"`;
49
+ /** `notif_` + UUID without dashes — recognisable in logs and URLs. */
50
+ export function generateInboxId() {
51
+ return `notif_${randomUUID().replace(/-/g, '')}`;
52
+ }
53
+ /**
54
+ * Write one inbox row. With `groupKey`, an existing row for the same user
55
+ * and key is replaced (upsert) so repeated events collapse into one entry.
56
+ */
57
+ export async function createInboxNotification(querier, input) {
58
+ if (!input.userId)
59
+ throw new Error('[venturekit/notify] createInboxNotification: userId is required');
60
+ if (!input.type)
61
+ throw new Error('[venturekit/notify] createInboxNotification: type is required');
62
+ if (!input.title?.trim())
63
+ throw new Error('[venturekit/notify] createInboxNotification: title is required');
64
+ const params = [
65
+ generateInboxId(),
66
+ input.userId,
67
+ input.tenantId ?? null,
68
+ input.type,
69
+ input.title,
70
+ input.body ?? null,
71
+ input.messageKey ?? null,
72
+ JSON.stringify(input.messageParams ?? {}),
73
+ input.referenceKind ?? null,
74
+ input.referenceId ?? null,
75
+ JSON.stringify(input.data ?? {}),
76
+ input.groupKey ?? null,
77
+ ];
78
+ const insert = `INSERT INTO vk_inbox_notifications
79
+ (id, user_id, tenant_id, type, title, body, message_key, message_params,
80
+ reference_kind, reference_id, data, group_key)
81
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9, $10, $11::jsonb, $12)`;
82
+ const sql = input.groupKey
83
+ ? `${insert}
84
+ ON CONFLICT (user_id, group_key) WHERE group_key IS NOT NULL DO UPDATE SET
85
+ type = EXCLUDED.type,
86
+ title = EXCLUDED.title,
87
+ body = EXCLUDED.body,
88
+ message_key = EXCLUDED.message_key,
89
+ message_params = EXCLUDED.message_params,
90
+ reference_kind = EXCLUDED.reference_kind,
91
+ reference_id = EXCLUDED.reference_id,
92
+ data = EXCLUDED.data,
93
+ read_at = NULL,
94
+ created_at = now(),
95
+ updated_at = now()
96
+ RETURNING ${COLUMNS}`
97
+ : `${insert} RETURNING ${COLUMNS}`;
98
+ const rows = await querier(sql, params);
99
+ return rows[0];
100
+ }
101
+ /** A user's inbox, newest first, keyset-paginated on `createdAt`. */
102
+ export async function listInbox(querier, options) {
103
+ const params = [options.userId];
104
+ const where = ['user_id = $1'];
105
+ if (options.tenantId !== undefined) {
106
+ if (options.tenantId === null)
107
+ where.push('tenant_id IS NULL');
108
+ else {
109
+ params.push(options.tenantId);
110
+ where.push(`tenant_id = $${params.length}`);
111
+ }
112
+ }
113
+ if (options.unreadOnly)
114
+ where.push('read_at IS NULL');
115
+ if (options.types && options.types.length > 0) {
116
+ params.push(options.types);
117
+ where.push(`type = ANY($${params.length}::text[])`);
118
+ }
119
+ if (options.before) {
120
+ params.push(options.before);
121
+ where.push(`created_at < $${params.length}`);
122
+ }
123
+ params.push(Math.min(Math.max(1, options.limit ?? 20), 100));
124
+ return querier(`SELECT ${COLUMNS} FROM vk_inbox_notifications
125
+ WHERE ${where.join(' AND ')}
126
+ ORDER BY created_at DESC, id DESC
127
+ LIMIT $${params.length}`, params);
128
+ }
129
+ /** Badge count. `types` lets the app exclude muted types. */
130
+ export async function unreadInboxCount(querier, options) {
131
+ const params = [options.userId];
132
+ const where = ['user_id = $1', 'read_at IS NULL'];
133
+ if (options.tenantId !== undefined) {
134
+ if (options.tenantId === null)
135
+ where.push('tenant_id IS NULL');
136
+ else {
137
+ params.push(options.tenantId);
138
+ where.push(`tenant_id = $${params.length}`);
139
+ }
140
+ }
141
+ if (options.types && options.types.length > 0) {
142
+ params.push(options.types);
143
+ where.push(`type = ANY($${params.length}::text[])`);
144
+ }
145
+ const rows = await querier(`SELECT count(*)::int AS count FROM vk_inbox_notifications WHERE ${where.join(' AND ')}`, params);
146
+ return Number(rows[0]?.count ?? 0);
147
+ }
148
+ /**
149
+ * Mark rows read. Scoped to `userId` so a client can never flip someone
150
+ * else's rows by guessing ids. Returns the number of rows changed.
151
+ */
152
+ export async function markInboxRead(querier, options) {
153
+ if (options.ids.length === 0)
154
+ return 0;
155
+ const rows = await querier(`UPDATE vk_inbox_notifications SET read_at = now(), updated_at = now()
156
+ WHERE user_id = $1 AND id = ANY($2::text[]) AND read_at IS NULL
157
+ RETURNING id`, [options.userId, options.ids]);
158
+ return rows.length;
159
+ }
160
+ /** "Mark all as read" — optionally only rows created up to `before` (what the user has seen). */
161
+ export async function markAllInboxRead(querier, options) {
162
+ const params = [options.userId];
163
+ const where = ['user_id = $1', 'read_at IS NULL'];
164
+ if (options.tenantId !== undefined) {
165
+ if (options.tenantId === null)
166
+ where.push('tenant_id IS NULL');
167
+ else {
168
+ params.push(options.tenantId);
169
+ where.push(`tenant_id = $${params.length}`);
170
+ }
171
+ }
172
+ if (options.before) {
173
+ params.push(options.before);
174
+ where.push(`created_at <= $${params.length}`);
175
+ }
176
+ const rows = await querier(`UPDATE vk_inbox_notifications SET read_at = now(), updated_at = now()
177
+ WHERE ${where.join(' AND ')}
178
+ RETURNING id`, params);
179
+ return rows.length;
180
+ }
181
+ /** Remove one row (user-scoped). */
182
+ export async function deleteInboxNotification(querier, options) {
183
+ const rows = await querier(`DELETE FROM vk_inbox_notifications WHERE user_id = $1 AND id = $2 RETURNING id`, [options.userId, options.id]);
184
+ return rows.length > 0;
185
+ }
186
+ /**
187
+ * Retention sweep for a cron: delete READ rows older than `olderThanDays`
188
+ * (default 90) and, optionally, unread rows older than `unreadOlderThanDays`.
189
+ * Returns the number removed.
190
+ */
191
+ export async function pruneInbox(querier, options = {}) {
192
+ const readDays = options.olderThanDays ?? 90;
193
+ const conditions = [`(read_at IS NOT NULL AND created_at < now() - make_interval(days => $1))`];
194
+ const params = [readDays];
195
+ if (options.unreadOlderThanDays !== undefined) {
196
+ params.push(options.unreadOlderThanDays);
197
+ conditions.push(`(read_at IS NULL AND created_at < now() - make_interval(days => $${params.length}))`);
198
+ }
199
+ const rows = await querier(`DELETE FROM vk_inbox_notifications WHERE ${conditions.join(' OR ')} RETURNING id`, params);
200
+ return rows.length;
201
+ }
202
+ //# sourceMappingURL=inbox.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inbox.js","sourceRoot":"","sources":["../../src/inbox/inbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AA2DzC,MAAM,OAAO,GAAG;;;;;;;;;;;;;;;gCAegB,CAAC;AAEjC,sEAAsE;AACtE,MAAM,UAAU,eAAe;IAC7B,OAAO,SAAS,UAAU,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC;AACnD,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB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EAChB,UAAoE,EAAE;IAEtE,MAAM,QAAQ,GAAG,OAAO,CAAC,aAAa,IAAI,EAAE,CAAC;IAC7C,MAAM,UAAU,GAAG,CAAC,0EAA0E,CAAC,CAAC;IAChG,MAAM,MAAM,GAAc,CAAC,QAAQ,CAAC,CAAC;IACrC,IAAI,OAAO,CAAC,mBAAmB,KAAK,SAAS,EAAE,CAAC;QAC9C,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC;QACzC,UAAU,CAAC,IAAI,CAAC,oEAAoE,MAAM,CAAC,MAAM,IAAI,CAAC,CAAC;IACzG,CAAC;IACD,MAAM,IAAI,GAAG,MAAM,OAAO,CACxB,4CAA4C,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe,EAClF,MAAM,CACP,CAAC;IACF,OAAO,IAAI,CAAC,MAAM,CAAC;AACrB,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { createInboxNotification, listInbox, unreadInboxCount, markInboxRead, markAllInboxRead, deleteInboxNotification, pruneInbox, generateInboxId, } from './inbox.js';
2
+ export type { Querier as InboxQuerier, InboxNotification, CreateInboxNotificationInput, ListInboxOptions, } from './inbox.js';
3
+ export { runInboxDigest } from './digest.js';
4
+ export type { RunInboxDigestOptions, InboxDigestResult, DigestEnqueueInput } from './digest.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/inbox/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,SAAS,EACT,gBAAgB,EAChB,aAAa,EACb,gBAAgB,EAChB,uBAAuB,EACvB,UAAU,EACV,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,OAAO,IAAI,YAAY,EACvB,iBAAiB,EACjB,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,YAAY,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { createInboxNotification, listInbox, unreadInboxCount, markInboxRead, markAllInboxRead, deleteInboxNotification, pruneInbox, generateInboxId, } from './inbox.js';
2
+ export { runInboxDigest } from './digest.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/inbox/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,SAAS,EACT,gBAAgB,EAChB,aAAa,EACb,gBAAgB,EAChB,uBAAuB,EACvB,UAAU,EACV,eAAe,GAChB,MAAM,YAAY,CAAC;AAOpB,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,59 @@
1
+ -- @venturekit/notify — in-app inbox.
2
+ --
3
+ -- The bell / notification centre every product ends up with. Deliberately a
4
+ -- SEPARATE table from `vk_notifications`: that one is a delivery OUTBOX
5
+ -- (rows are claimed, sent through a provider, and reach a terminal status),
6
+ -- whereas an inbox row is state the user reads and dismisses over time.
7
+ -- Keeping them apart also leaves the `notify_channel` enum and the
8
+ -- dispatcher untouched.
9
+ --
10
+ -- Copy: `title` / `body` are the stored rendition (a complete sentence in
11
+ -- the sender's locale) and `message_key` + `message_params` let a client
12
+ -- re-render in the READER's locale from its own catalog, falling back to
13
+ -- the stored text when a key is unknown — the contract the consumer apps
14
+ -- converged on.
15
+ --
16
+ -- `tenant_id` is nullable TEXT; multi-tenant apps add their RLS policy on
17
+ -- top. `user_id` is whatever identifies the recipient (Cognito sub,
18
+ -- membership id) — the app decides, consistently with its other tables.
19
+
20
+ CREATE TABLE IF NOT EXISTS vk_inbox_notifications (
21
+ id TEXT PRIMARY KEY,
22
+ user_id TEXT NOT NULL,
23
+ tenant_id TEXT,
24
+ -- App-defined type, e.g. `comment_reply`; drives icons, grouping and the
25
+ -- per-type preference matrix.
26
+ type TEXT NOT NULL,
27
+ title TEXT NOT NULL,
28
+ body TEXT,
29
+ message_key TEXT,
30
+ message_params JSONB NOT NULL DEFAULT '{}'::jsonb,
31
+ -- Where the click goes: a kind + id the client maps to a route.
32
+ reference_kind TEXT,
33
+ reference_id TEXT,
34
+ -- Free-form extras (actor id, preview image, …).
35
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
36
+ -- Optional collapse key: a second notification with the same key for
37
+ -- the same user REPLACES the first (e.g. "3 new comments on your post").
38
+ group_key TEXT,
39
+ read_at TIMESTAMPTZ,
40
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
41
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
42
+ );
43
+
44
+ -- Inbox listing, newest first.
45
+ CREATE INDEX IF NOT EXISTS vk_inbox_user_created_idx
46
+ ON vk_inbox_notifications (user_id, created_at DESC);
47
+
48
+ -- Badge count.
49
+ CREATE INDEX IF NOT EXISTS vk_inbox_user_unread_idx
50
+ ON vk_inbox_notifications (user_id)
51
+ WHERE read_at IS NULL;
52
+
53
+ -- Collapse key upsert target.
54
+ CREATE UNIQUE INDEX IF NOT EXISTS vk_inbox_user_group_key_uidx
55
+ ON vk_inbox_notifications (user_id, group_key)
56
+ WHERE group_key IS NOT NULL;
57
+
58
+ COMMENT ON TABLE vk_inbox_notifications IS
59
+ 'In-app notification centre rows (read / unread per user). Structure owned by @venturekit/notify; written through its inbox helpers.';
@@ -0,0 +1,15 @@
1
+ -- @venturekit/notify — inbox digest cursor.
2
+ --
3
+ -- One row per user the digest cron has e-mailed: where the last digest
4
+ -- stopped (`last_digest_at`, the newest inbox row it included) and how
5
+ -- many digests went out in the current rolling day. `runInboxDigest`
6
+ -- reads it to pick up only what is new and to honour `maxPerUserPerDay`.
7
+
8
+ CREATE TABLE IF NOT EXISTS vk_inbox_digest_cursor (
9
+ user_id TEXT PRIMARY KEY,
10
+ last_digest_at TIMESTAMPTZ NOT NULL,
11
+ sent_today INTEGER NOT NULL DEFAULT 0
12
+ );
13
+
14
+ COMMENT ON TABLE vk_inbox_digest_cursor IS
15
+ 'Per-user cursor for the in-app inbox e-mail digest (runInboxDigest). Owned by @venturekit/notify.';
@@ -0,0 +1,80 @@
1
+ /**
2
+ * @venturekit/notify — frequency caps.
3
+ *
4
+ * "At most N routine messages per recipient per window" — the rule that
5
+ * keeps a helpful product from becoming a noisy one, and that every
6
+ * consumer wrote against its own notification table. Two pieces:
7
+ *
8
+ * - {@link decideFrequencyCap} — the pure rule: given how many messages
9
+ * already went out in the window, is one more allowed, and if not,
10
+ * when does the window open again.
11
+ * - {@link countSentInWindow} — the count against `vk_notifications`
12
+ * (this package's outbox), for callers that keep their outbox here.
13
+ * Callers with their own table run their own count and feed it to
14
+ * the pure rule.
15
+ *
16
+ * Critical messages (password resets, security alerts, payment failures)
17
+ * bypass the cap by NOT being asked — the cap is a policy the caller
18
+ * applies to the categories it chooses, typically everything the
19
+ * preferences matrix lets a user opt out of.
20
+ *
21
+ * ```ts
22
+ * const sent = await countSentInWindow(query, { userId, channel: 'email', windowDays: 7, excludeTemplateKeys: ['password_reset'] });
23
+ * const decision = decideFrequencyCap({ sent, max: 3 });
24
+ * if (!decision.allowed) return { skipped: 'frequency_cap', retryAt: decision.windowResetsAt };
25
+ * ```
26
+ */
27
+ /** `@venturekit/data`'s `query` / `tx.query` shape. */
28
+ export type Querier = <T = Record<string, unknown>[]>(sql: string, params?: unknown[]) => Promise<T>;
29
+ export interface FrequencyCapDecision {
30
+ allowed: boolean;
31
+ /** Messages already sent in the window. */
32
+ sent: number;
33
+ /** The cap. */
34
+ max: number;
35
+ /** Sends left in the window (0 when blocked). */
36
+ remaining: number;
37
+ /**
38
+ * When the oldest counted message leaves the window — i.e. the earliest
39
+ * instant another send would be allowed. Only meaningful when blocked
40
+ * and when `oldestSentAt` was supplied.
41
+ */
42
+ windowResetsAt?: Date;
43
+ }
44
+ /** The pure rule. `sent` counts messages in the trailing window. */
45
+ export declare function decideFrequencyCap(input: {
46
+ sent: number;
47
+ max: number;
48
+ /** Timestamp of the oldest message in the window, to compute `windowResetsAt`. */
49
+ oldestSentAt?: Date | null;
50
+ windowDays?: number;
51
+ now?: Date;
52
+ }): FrequencyCapDecision;
53
+ export interface CountSentInWindowOptions {
54
+ userId: string;
55
+ /** Restrict to one channel (`email`, `whatsapp`, …). Omit for all channels. */
56
+ channel?: string;
57
+ /** Trailing window length. Default 7. */
58
+ windowDays?: number;
59
+ /** Templates that never count against the cap (transactional / security). */
60
+ excludeTemplateKeys?: string[];
61
+ /** Only these templates count. */
62
+ includeTemplateKeys?: string[];
63
+ }
64
+ /**
65
+ * Count messages `sent` (or `delivered`) to a user within the trailing
66
+ * window in `vk_notifications`, and the oldest one's `sent_at`, so the
67
+ * caller can tell the user when the next one may go out.
68
+ */
69
+ export declare function countSentInWindow(querier: Querier, options: CountSentInWindowOptions): Promise<{
70
+ sent: number;
71
+ oldestSentAt: Date | null;
72
+ }>;
73
+ /**
74
+ * One call for callers whose outbox is this package's: count, then decide.
75
+ */
76
+ export declare function checkFrequencyCap(querier: Querier, options: CountSentInWindowOptions & {
77
+ max: number;
78
+ now?: Date;
79
+ }): Promise<FrequencyCapDecision>;
80
+ //# sourceMappingURL=frequency-cap.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frequency-cap.d.ts","sourceRoot":"","sources":["../../src/policy/frequency-cap.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,uDAAuD;AACvD,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EAClD,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,OAAO,EAAE,KACf,OAAO,CAAC,CAAC,CAAC,CAAC;AAEhB,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,OAAO,CAAC;IACjB,2CAA2C;IAC3C,IAAI,EAAE,MAAM,CAAC;IACb,eAAe;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,iDAAiD;IACjD,SAAS,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,cAAc,CAAC,EAAE,IAAI,CAAC;CACvB;AAED,oEAAoE;AACpE,wBAAgB,kBAAkB,CAAC,KAAK,EAAE;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ,kFAAkF;IAClF,YAAY,CAAC,EAAE,IAAI,GAAG,IAAI,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,GAAG,CAAC,EAAE,IAAI,CAAC;CACZ,GAAG,oBAAoB,CASvB;AAED,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,+EAA+E;IAC/E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yCAAyC;IACzC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,6EAA6E;IAC7E,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC/B,kCAAkC;IAClC,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC;CAChC;AAED;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,IAAI,GAAG,IAAI,CAAA;CAAE,CAAC,CAkCtD;AAED;;GAEG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,wBAAwB,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,IAAI,CAAA;CAAE,GAC9D,OAAO,CAAC,oBAAoB,CAAC,CAG/B"}
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @venturekit/notify — frequency caps.
3
+ *
4
+ * "At most N routine messages per recipient per window" — the rule that
5
+ * keeps a helpful product from becoming a noisy one, and that every
6
+ * consumer wrote against its own notification table. Two pieces:
7
+ *
8
+ * - {@link decideFrequencyCap} — the pure rule: given how many messages
9
+ * already went out in the window, is one more allowed, and if not,
10
+ * when does the window open again.
11
+ * - {@link countSentInWindow} — the count against `vk_notifications`
12
+ * (this package's outbox), for callers that keep their outbox here.
13
+ * Callers with their own table run their own count and feed it to
14
+ * the pure rule.
15
+ *
16
+ * Critical messages (password resets, security alerts, payment failures)
17
+ * bypass the cap by NOT being asked — the cap is a policy the caller
18
+ * applies to the categories it chooses, typically everything the
19
+ * preferences matrix lets a user opt out of.
20
+ *
21
+ * ```ts
22
+ * const sent = await countSentInWindow(query, { userId, channel: 'email', windowDays: 7, excludeTemplateKeys: ['password_reset'] });
23
+ * const decision = decideFrequencyCap({ sent, max: 3 });
24
+ * if (!decision.allowed) return { skipped: 'frequency_cap', retryAt: decision.windowResetsAt };
25
+ * ```
26
+ */
27
+ /** The pure rule. `sent` counts messages in the trailing window. */
28
+ export function decideFrequencyCap(input) {
29
+ const max = Math.max(0, Math.floor(input.max));
30
+ const sent = Math.max(0, Math.floor(input.sent));
31
+ const allowed = sent < max;
32
+ const decision = { allowed, sent, max, remaining: Math.max(0, max - sent) };
33
+ if (!allowed && input.oldestSentAt && input.windowDays) {
34
+ decision.windowResetsAt = new Date(new Date(input.oldestSentAt).getTime() + input.windowDays * 86_400_000);
35
+ }
36
+ return decision;
37
+ }
38
+ /**
39
+ * Count messages `sent` (or `delivered`) to a user within the trailing
40
+ * window in `vk_notifications`, and the oldest one's `sent_at`, so the
41
+ * caller can tell the user when the next one may go out.
42
+ */
43
+ export async function countSentInWindow(querier, options) {
44
+ const windowDays = options.windowDays ?? 7;
45
+ const params = [options.userId, windowDays];
46
+ // `status` is the `notify_status` enum; compared as text so a status
47
+ // value a future migration adds (e.g. `delivered`) counts without a
48
+ // change here, and an unknown literal never errors the query.
49
+ const where = [
50
+ 'recipient_user_id = $1',
51
+ "status::text IN ('sent', 'delivered')",
52
+ 'sent_at >= now() - make_interval(days => $2)',
53
+ ];
54
+ if (options.channel) {
55
+ params.push(options.channel);
56
+ where.push(`channel::text = $${params.length}`);
57
+ }
58
+ if (options.excludeTemplateKeys && options.excludeTemplateKeys.length > 0) {
59
+ params.push(options.excludeTemplateKeys);
60
+ where.push(`NOT (template_key = ANY($${params.length}::text[]))`);
61
+ }
62
+ if (options.includeTemplateKeys && options.includeTemplateKeys.length > 0) {
63
+ params.push(options.includeTemplateKeys);
64
+ where.push(`template_key = ANY($${params.length}::text[])`);
65
+ }
66
+ const rows = await querier(`SELECT count(*)::int AS sent, min(sent_at) AS "oldestSentAt"
67
+ FROM vk_notifications
68
+ WHERE ${where.join(' AND ')}`, params);
69
+ const row = rows[0];
70
+ return {
71
+ sent: Number(row?.sent ?? 0),
72
+ oldestSentAt: row?.oldestSentAt ? new Date(row.oldestSentAt) : null,
73
+ };
74
+ }
75
+ /**
76
+ * One call for callers whose outbox is this package's: count, then decide.
77
+ */
78
+ export async function checkFrequencyCap(querier, options) {
79
+ const { sent, oldestSentAt } = await countSentInWindow(querier, options);
80
+ return decideFrequencyCap({ sent, max: options.max, oldestSentAt, windowDays: options.windowDays ?? 7, now: options.now });
81
+ }
82
+ //# sourceMappingURL=frequency-cap.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frequency-cap.js","sourceRoot":"","sources":["../../src/policy/frequency-cap.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAwBH,oEAAoE;AACpE,MAAM,UAAU,kBAAkB,CAAC,KAOlC;IACC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IAC/C,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IACjD,MAAM,OAAO,GAAG,IAAI,GAAG,GAAG,CAAC;IAC3B,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,mBAAmB,IAAI,OAAO,CAAC,mBAAmB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC1E,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC;QACzC,KAAK,CAAC,IAAI,CAAC,uBAAuB,MAAM,CAAC,MAAM,WAAW,CAAC,CAAC;IAC9D,CAAC;IACD,MAAM,IAAI,GAAG,MAAM,OAAO,CACxB;;aAES,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,EAC9B,MAAM,CACP,CAAC;IACF,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,OAAO;QACL,IAAI,EAAE,MAAM,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,CAAC;QAC5B,YAAY,EAAE,GAAG,EAAE,YAAY,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI;KACpE,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,OAAgB,EAChB,OAA+D;IAE/D,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,MAAM,iBAAiB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACzE,OAAO,kBAAkB,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,YAAY,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;AAC7H,CAAC"}
@@ -11,6 +11,7 @@
11
11
  * stays with the consumer, because it is the part that differs per product.
12
12
  */
13
13
  export { inQuietHours, quietHoursEnd, type QuietHours, } from './quiet-hours.js';
14
+ export { decideFrequencyCap, countSentInWindow, checkFrequencyCap, type FrequencyCapDecision, type CountSentInWindowOptions, type Querier as FrequencyCapQuerier, } from './frequency-cap.js';
14
15
  export { buildChannelChain, nextChannel, type ChannelChainOptions, type ChannelReachability, type ChainStep, type NextChannelOptions, } from './channel-chain.js';
15
- export { placeholdersOf, undeclaredPlaceholders, renderStringTemplate, resolveLocale, type StringTemplate, type RenderOutcome, type ResolveLocaleOptions, } from './string-templates.js';
16
+ export { placeholdersOf, undeclaredPlaceholders, renderStringTemplate, escapeHtml, resolveLocale, type StringTemplate, type RenderOutcome, type RenderStringTemplateOptions, type ResolveLocaleOptions, } from './string-templates.js';
16
17
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/policy/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EACL,YAAY,EACZ,aAAa,EACb,KAAK,UAAU,GAChB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,iBAAiB,EACjB,WAAW,EACX,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,SAAS,EACd,KAAK,kBAAkB,GACxB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,oBAAoB,EACpB,aAAa,EACb,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,oBAAoB,GAC1B,MAAM,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/policy/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EACL,YAAY,EACZ,aAAa,EACb,KAAK,UAAU,GAChB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,KAAK,oBAAoB,EACzB,KAAK,wBAAwB,EAC7B,KAAK,OAAO,IAAI,mBAAmB,GACpC,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,iBAAiB,EACjB,WAAW,EACX,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,SAAS,EACd,KAAK,kBAAkB,GACxB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,oBAAoB,EACpB,UAAU,EACV,aAAa,EACb,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,2BAA2B,EAChC,KAAK,oBAAoB,GAC1B,MAAM,uBAAuB,CAAC"}
@@ -11,6 +11,7 @@
11
11
  * stays with the consumer, because it is the part that differs per product.
12
12
  */
13
13
  export { inQuietHours, quietHoursEnd, } from './quiet-hours.js';
14
+ export { decideFrequencyCap, countSentInWindow, checkFrequencyCap, } from './frequency-cap.js';
14
15
  export { buildChannelChain, nextChannel, } from './channel-chain.js';
15
- export { placeholdersOf, undeclaredPlaceholders, renderStringTemplate, resolveLocale, } from './string-templates.js';
16
+ export { placeholdersOf, undeclaredPlaceholders, renderStringTemplate, escapeHtml, resolveLocale, } from './string-templates.js';
16
17
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/policy/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EACL,YAAY,EACZ,aAAa,GAEd,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,iBAAiB,EACjB,WAAW,GAKZ,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,oBAAoB,EACpB,aAAa,GAId,MAAM,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/policy/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EACL,YAAY,EACZ,aAAa,GAEd,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,GAIlB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,iBAAiB,EACjB,WAAW,GAKZ,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,oBAAoB,EACpB,UAAU,EACV,aAAa,GAKd,MAAM,uBAAuB,CAAC"}
@@ -53,6 +53,23 @@ export type RenderOutcome = {
53
53
  ok: false;
54
54
  missing: string[];
55
55
  };
56
+ export interface RenderStringTemplateOptions {
57
+ /**
58
+ * Applied to every substituted VALUE (never to the template text) before
59
+ * it is spliced in. Pass {@link escapeHtml} when the rendered body ends
60
+ * up inside an HTML e-mail, a web push payload rendered as markup, or
61
+ * anything else that interprets tags: the values are typically
62
+ * user-supplied (a parent's name, a free-text note) and a template that
63
+ * is safe as plain text becomes markup injection the moment it is
64
+ * rendered as HTML. Plain-text channels (SMS, WhatsApp) leave this unset.
65
+ */
66
+ escape?: (value: string) => string;
67
+ }
68
+ /**
69
+ * HTML-escape a value for interpolation into an HTML document.
70
+ * Escapes `& < > " '` — enough for element content and quoted attributes.
71
+ */
72
+ export declare function escapeHtml(value: string): string;
56
73
  /**
57
74
  * Substitute values, or refuse.
58
75
  *
@@ -60,8 +77,11 @@ export type RenderOutcome = {
60
77
  * never a deliberate value for a name or a time, and rendering it produces a
61
78
  * message with a hole where the fact should be — which reads as a bug to the
62
79
  * recipient and is invisible to the sender.
80
+ *
81
+ * Values are substituted VERBATIM unless {@link RenderStringTemplateOptions.escape}
82
+ * is given — the renderer does not know which channel the text is bound for.
63
83
  */
64
- export declare function renderStringTemplate(template: StringTemplate, values: Record<string, string | number | null | undefined>): RenderOutcome;
84
+ export declare function renderStringTemplate(template: StringTemplate, values: Record<string, string | number | null | undefined>, options?: RenderStringTemplateOptions): RenderOutcome;
65
85
  export interface ResolveLocaleOptions {
66
86
  /**
67
87
  * Preferred locales, most specific first — typically the recipient's, then the
@@ -1 +1 @@
1
- {"version":3,"file":"string-templates.d.ts","sourceRoot":"","sources":["../../src/policy/string-templates.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,kDAAkD;AAClD,MAAM,WAAW,cAAc;IAC7B,yBAAyB;IACzB,GAAG,EAAE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B;;;OAGG;IACH,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC/B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,MAAM,GAAG,IAAI,CAY1E"}
@@ -46,6 +46,18 @@ export function undeclaredPlaceholders(template) {
46
46
  ]),
47
47
  ].filter((name) => !declared.has(name));
48
48
  }
49
+ /**
50
+ * HTML-escape a value for interpolation into an HTML document.
51
+ * Escapes `& < > " '` — enough for element content and quoted attributes.
52
+ */
53
+ export function escapeHtml(value) {
54
+ return value
55
+ .replace(/&/g, '&amp;')
56
+ .replace(/</g, '&lt;')
57
+ .replace(/>/g, '&gt;')
58
+ .replace(/"/g, '&quot;')
59
+ .replace(/'/g, '&#39;');
60
+ }
49
61
  /**
50
62
  * Substitute values, or refuse.
51
63
  *
@@ -53,8 +65,11 @@ export function undeclaredPlaceholders(template) {
53
65
  * never a deliberate value for a name or a time, and rendering it produces a
54
66
  * message with a hole where the fact should be — which reads as a bug to the
55
67
  * recipient and is invisible to the sender.
68
+ *
69
+ * Values are substituted VERBATIM unless {@link RenderStringTemplateOptions.escape}
70
+ * is given — the renderer does not know which channel the text is bound for.
56
71
  */
57
- export function renderStringTemplate(template, values) {
72
+ export function renderStringTemplate(template, values, options = {}) {
58
73
  const used = [
59
74
  ...new Set([
60
75
  ...placeholdersOf(template.title),
@@ -67,7 +82,8 @@ export function renderStringTemplate(template, values) {
67
82
  });
68
83
  if (missing.length > 0)
69
84
  return { ok: false, missing };
70
- const fill = (text) => text.replace(PLACEHOLDER, (_match, name) => String(values[name]));
85
+ const escape = options.escape ?? ((v) => v);
86
+ const fill = (text) => text.replace(PLACEHOLDER, (_match, name) => escape(String(values[name])));
71
87
  return { ok: true, title: fill(template.title), body: fill(template.body) };
72
88
  }
73
89
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"string-templates.js","sourceRoot":"","sources":["../../src/policy/string-templates.ts"],"names":[],"mappings":"AAAA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zB,MAAM,GAAG,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAChC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC,SAAS,CAAC,CAC3C,CAAC;QACF,IAAI,GAAG;YAAE,OAAO,GAAG,CAAC;IACtB,CAAC;IACD,OAAO,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;AACtC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venturekit/notify",
3
- "version": "0.0.37",
3
+ "version": "0.0.39",
4
4
  "description": "Transactional notifications for VentureKit — email (SES), WhatsApp (Meta Cloud), with a Postgres outbox + cron dispatcher.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -68,6 +68,10 @@
68
68
  "types": "./dist/policy/index.d.ts",
69
69
  "import": "./dist/policy/index.js"
70
70
  },
71
+ "./inbox": {
72
+ "types": "./dist/inbox/index.d.ts",
73
+ "import": "./dist/inbox/index.js"
74
+ },
71
75
  "./store/postgres": {
72
76
  "types": "./dist/store/postgres.d.ts",
73
77
  "import": "./dist/store/postgres.js"
@@ -92,11 +96,11 @@
92
96
  "outbox"
93
97
  ],
94
98
  "dependencies": {
95
- "@venturekit/core": "0.0.37"
99
+ "@venturekit/core": "0.0.39"
96
100
  },
97
101
  "peerDependencies": {
98
- "@venturekit/data": "0.0.37",
99
- "@venturekit/runtime": "0.0.37",
102
+ "@venturekit/data": "0.0.39",
103
+ "@venturekit/runtime": "0.0.39",
100
104
  "@aws-sdk/client-sesv2": "^3.1126.0",
101
105
  "@aws-sdk/client-secrets-manager": "^3.1126.0"
102
106
  },
@@ -115,8 +119,8 @@
115
119
  }
116
120
  },
117
121
  "devDependencies": {
118
- "@venturekit/data": "0.0.37",
119
- "@venturekit/runtime": "0.0.37",
122
+ "@venturekit/data": "0.0.39",
123
+ "@venturekit/runtime": "0.0.39",
120
124
  "@aws-sdk/client-sesv2": "^3.1126.0",
121
125
  "@aws-sdk/client-secrets-manager": "^3.1126.0",
122
126
  "@types/aws-lambda": "^8.10.163",
@@ -0,0 +1,59 @@
1
+ -- @venturekit/notify — in-app inbox.
2
+ --
3
+ -- The bell / notification centre every product ends up with. Deliberately a
4
+ -- SEPARATE table from `vk_notifications`: that one is a delivery OUTBOX
5
+ -- (rows are claimed, sent through a provider, and reach a terminal status),
6
+ -- whereas an inbox row is state the user reads and dismisses over time.
7
+ -- Keeping them apart also leaves the `notify_channel` enum and the
8
+ -- dispatcher untouched.
9
+ --
10
+ -- Copy: `title` / `body` are the stored rendition (a complete sentence in
11
+ -- the sender's locale) and `message_key` + `message_params` let a client
12
+ -- re-render in the READER's locale from its own catalog, falling back to
13
+ -- the stored text when a key is unknown — the contract the consumer apps
14
+ -- converged on.
15
+ --
16
+ -- `tenant_id` is nullable TEXT; multi-tenant apps add their RLS policy on
17
+ -- top. `user_id` is whatever identifies the recipient (Cognito sub,
18
+ -- membership id) — the app decides, consistently with its other tables.
19
+
20
+ CREATE TABLE IF NOT EXISTS vk_inbox_notifications (
21
+ id TEXT PRIMARY KEY,
22
+ user_id TEXT NOT NULL,
23
+ tenant_id TEXT,
24
+ -- App-defined type, e.g. `comment_reply`; drives icons, grouping and the
25
+ -- per-type preference matrix.
26
+ type TEXT NOT NULL,
27
+ title TEXT NOT NULL,
28
+ body TEXT,
29
+ message_key TEXT,
30
+ message_params JSONB NOT NULL DEFAULT '{}'::jsonb,
31
+ -- Where the click goes: a kind + id the client maps to a route.
32
+ reference_kind TEXT,
33
+ reference_id TEXT,
34
+ -- Free-form extras (actor id, preview image, …).
35
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
36
+ -- Optional collapse key: a second notification with the same key for
37
+ -- the same user REPLACES the first (e.g. "3 new comments on your post").
38
+ group_key TEXT,
39
+ read_at TIMESTAMPTZ,
40
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
41
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
42
+ );
43
+
44
+ -- Inbox listing, newest first.
45
+ CREATE INDEX IF NOT EXISTS vk_inbox_user_created_idx
46
+ ON vk_inbox_notifications (user_id, created_at DESC);
47
+
48
+ -- Badge count.
49
+ CREATE INDEX IF NOT EXISTS vk_inbox_user_unread_idx
50
+ ON vk_inbox_notifications (user_id)
51
+ WHERE read_at IS NULL;
52
+
53
+ -- Collapse key upsert target.
54
+ CREATE UNIQUE INDEX IF NOT EXISTS vk_inbox_user_group_key_uidx
55
+ ON vk_inbox_notifications (user_id, group_key)
56
+ WHERE group_key IS NOT NULL;
57
+
58
+ COMMENT ON TABLE vk_inbox_notifications IS
59
+ 'In-app notification centre rows (read / unread per user). Structure owned by @venturekit/notify; written through its inbox helpers.';
@@ -0,0 +1,15 @@
1
+ -- @venturekit/notify — inbox digest cursor.
2
+ --
3
+ -- One row per user the digest cron has e-mailed: where the last digest
4
+ -- stopped (`last_digest_at`, the newest inbox row it included) and how
5
+ -- many digests went out in the current rolling day. `runInboxDigest`
6
+ -- reads it to pick up only what is new and to honour `maxPerUserPerDay`.
7
+
8
+ CREATE TABLE IF NOT EXISTS vk_inbox_digest_cursor (
9
+ user_id TEXT PRIMARY KEY,
10
+ last_digest_at TIMESTAMPTZ NOT NULL,
11
+ sent_today INTEGER NOT NULL DEFAULT 0
12
+ );
13
+
14
+ COMMENT ON TABLE vk_inbox_digest_cursor IS
15
+ 'Per-user cursor for the in-app inbox e-mail digest (runInboxDigest). Owned by @venturekit/notify.';