notifkit 0.1.15 → 0.1.16
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/dashboard/dist/assets/index-C-DJYu0_.css +1 -0
- package/dashboard/dist/assets/index-CzFZcEon.js +318 -0
- package/dashboard/dist/index.html +2 -2
- package/dist/{bootstrap-BOmT69OH.mjs → bootstrap-BMDRPjgp.mjs} +1 -1
- package/dist/{bulk-ZPiOJRx-.mjs → bulk-CJ5QXiPa.mjs} +1 -1
- package/dist/index.d.mts +71 -27
- package/dist/index.mjs +2 -2
- package/dist/{main-CCqcFDDe.mjs → main-6_bXQBDH.mjs} +21 -41
- package/dist/{main-BdZvBgV7.mjs → main-8nP3qmCT.mjs} +22 -48
- package/dist/{main-C0m9-Eos.mjs → main-B82bsFoy.mjs} +183 -334
- package/dist/{main-CTjaZ7ZD.mjs → main-CpaHF1Zw.mjs} +13 -15
- package/dist/{main-JEXBLP2A.mjs → main-DULD8-th.mjs} +8 -6
- package/dist/{main-C6S3EsJ3.mjs → main-ZW5RaiOK.mjs} +77 -64
- package/dist/{main-g33jpia4.mjs → main-g1KEcXXp.mjs} +676 -582
- package/dist/{main-24J4U8yP.mjs → main-mGIT8jv4.mjs} +4 -4
- package/dist/schedule-or-dispatch-Cd7GLfc3.mjs +52 -0
- package/dist/{src-9LXITcNi.mjs → src-BE_EUpZ6.mjs} +93 -93
- package/package.json +1 -1
- package/scripts/create-project.mjs +6 -2
- package/src/client.ts +3 -3
- package/src/config/index.ts +1 -0
- package/src/contracts/common.ts +2 -0
- package/src/contracts/envelope.ts +1 -1
- package/src/contracts/events/notification-created.ts +2 -0
- package/src/contracts/events/notification-delivered.ts +1 -1
- package/src/contracts/events/notification-failed.ts +1 -1
- package/src/contracts/events/notification-requested.ts +3 -2
- package/src/contracts/helpers.ts +1 -2
- package/src/contracts/index.ts +1 -0
- package/src/contracts/registry.ts +1 -0
- package/src/contracts/sdk.ts +8 -37
- package/src/db/schema.ts +8 -13
- package/src/idempotency/index.ts +6 -8
- package/src/metrics/index.ts +2 -0
- package/src/rate-limiter/api-rate-limiter.ts +208 -0
- package/src/rate-limiter/index.ts +3 -411
- package/src/rate-limiter/project-settings-cache.ts +99 -0
- package/src/rate-limiter/user-throttle.ts +100 -0
- package/src/redis/index.ts +10 -3
- package/src/repositories/admin-user.ts +83 -0
- package/src/repositories/contact.ts +359 -0
- package/src/repositories/index.ts +9 -1416
- package/src/repositories/preference.ts +35 -0
- package/src/repositories/project.ts +110 -0
- package/src/repositories/segment.ts +16 -0
- package/src/repositories/template.ts +72 -0
- package/src/repositories/types.ts +49 -0
- package/src/repositories/user.ts +644 -0
- package/src/repositories/workflow.ts +64 -0
- package/src/services/ai/main.ts +29 -71
- package/src/services/api/admin-static.ts +4 -1
- package/src/services/api/handlers/auth.ts +109 -0
- package/src/services/api/handlers/campaigns.ts +191 -0
- package/src/services/api/handlers/events.ts +99 -0
- package/src/services/api/handlers/notifications.ts +356 -0
- package/src/services/api/handlers/projects.ts +116 -0
- package/src/services/api/handlers/shared.ts +262 -0
- package/src/services/api/handlers/suppressions.ts +95 -0
- package/src/services/api/handlers/system.ts +314 -0
- package/src/services/api/handlers/templates.ts +97 -0
- package/src/services/api/handlers/unsubscribe.ts +215 -0
- package/src/services/api/handlers/users.ts +262 -0
- package/src/services/api/handlers/workflows.ts +150 -0
- package/src/services/api/handlers.ts +25 -2190
- package/src/services/api/health.ts +133 -0
- package/src/services/api/http.ts +12 -0
- package/src/services/api/main.ts +32 -322
- package/src/services/api/router.ts +1 -1
- package/src/services/api/webhooks.ts +172 -0
- package/src/services/delivery/main.ts +256 -498
- package/src/services/engine/main.ts +31 -247
- package/src/services/engine/quiet-hours.ts +151 -0
- package/src/services/engine/schedule-or-dispatch.ts +104 -0
- package/src/services/enricher/main.ts +9 -21
- package/src/services/events/main.ts +2 -2
- package/src/services/scheduler/main.ts +16 -25
- package/src/services/workflow/duration.ts +24 -0
- package/src/services/workflow/main.ts +6 -164
- package/src/services/workflow/timers.ts +157 -0
- package/src/shared/events.ts +3 -2
- package/src/templates/render.ts +1 -0
- package/src/workers/index.ts +7 -4
- package/src/workflows/sdk.ts +1 -0
- package/dashboard/dist/assets/index-ggpJKZqZ.js +0 -315
- package/dashboard/dist/assets/index-s-SXGIwv.css +0 -1
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
import { eq, and, sql as drizzleSql, inArray, desc } from "drizzle-orm";
|
|
2
|
+
import { LRUCache } from "@/shared/index.js";
|
|
3
|
+
import type { Db } from "@/index.js";
|
|
4
|
+
import type { Preferences, ContactChannel } from "@/contracts/index.js";
|
|
5
|
+
import {
|
|
6
|
+
users,
|
|
7
|
+
userSegments,
|
|
8
|
+
userContacts,
|
|
9
|
+
userChannelPreferences,
|
|
10
|
+
userTopicPreferences,
|
|
11
|
+
quietHours,
|
|
12
|
+
} from "@/db/schema.js";
|
|
13
|
+
import type { UserProfile, UserRecord } from "./types.js";
|
|
14
|
+
|
|
15
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Applied when a profile is read, not when it is written: an upsert that
|
|
19
|
+
* leaves a field out must keep the stored value rather than reset it.
|
|
20
|
+
*/
|
|
21
|
+
const DEFAULT_LANGUAGE = "en";
|
|
22
|
+
const DEFAULT_TIMEZONE = "UTC";
|
|
23
|
+
|
|
24
|
+
export class UserRepository {
|
|
25
|
+
private readonly recordCache = new LRUCache<string, UserRecord>(5000, 30_000);
|
|
26
|
+
|
|
27
|
+
constructor(private readonly db: Db) {}
|
|
28
|
+
|
|
29
|
+
/** A repository that runs its queries inside `tx`. */
|
|
30
|
+
withTx(tx: Db): UserRepository {
|
|
31
|
+
return new UserRepository(tx);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async findById(projectId: string, userId: string): Promise<UserProfile | null> {
|
|
35
|
+
const rows = await this.db
|
|
36
|
+
.select()
|
|
37
|
+
.from(users)
|
|
38
|
+
.where(and(eq(users.externalId, userId), eq(users.projectId, projectId)))
|
|
39
|
+
.limit(1);
|
|
40
|
+
|
|
41
|
+
if (!rows[0]) return null;
|
|
42
|
+
const attrs = rows[0].attributes as any;
|
|
43
|
+
return {
|
|
44
|
+
userId: rows[0].externalId,
|
|
45
|
+
language: attrs.language ?? DEFAULT_LANGUAGE,
|
|
46
|
+
timezone: attrs.timezone ?? DEFAULT_TIMEZONE,
|
|
47
|
+
email: attrs.email,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async findRecordById(projectId: string, userId: string): Promise<UserRecord | null> {
|
|
52
|
+
const cacheKey = `${projectId}:${userId}`;
|
|
53
|
+
const cached = this.recordCache.get(cacheKey);
|
|
54
|
+
if (cached !== undefined) return cached;
|
|
55
|
+
|
|
56
|
+
const records = await this.findRecordsByIds(projectId, [userId]);
|
|
57
|
+
return records[0] ?? null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async findRecordsByIds(projectId: string, userIds: string[]): Promise<UserRecord[]> {
|
|
61
|
+
if (userIds.length === 0) return [];
|
|
62
|
+
|
|
63
|
+
const results: UserRecord[] = [];
|
|
64
|
+
const missingIds: string[] = [];
|
|
65
|
+
|
|
66
|
+
for (const id of userIds) {
|
|
67
|
+
const cacheKey = `${projectId}:${id}`;
|
|
68
|
+
const cached = this.recordCache.get(cacheKey);
|
|
69
|
+
if (cached !== undefined) {
|
|
70
|
+
results.push(cached);
|
|
71
|
+
} else {
|
|
72
|
+
missingIds.push(id);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (missingIds.length === 0) {
|
|
77
|
+
return results;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const usersRows = await this.db
|
|
81
|
+
.select()
|
|
82
|
+
.from(users)
|
|
83
|
+
.where(and(inArray(users.externalId, missingIds), eq(users.projectId, projectId)));
|
|
84
|
+
|
|
85
|
+
if (usersRows.length === 0) return results;
|
|
86
|
+
|
|
87
|
+
const internalIds = usersRows.map((r) => r.id);
|
|
88
|
+
|
|
89
|
+
const [segmentRows, topicRows, channelRows, qhRows] = await Promise.all([
|
|
90
|
+
this.db.select().from(userSegments).where(inArray(userSegments.userId, internalIds)),
|
|
91
|
+
this.db
|
|
92
|
+
.select()
|
|
93
|
+
.from(userTopicPreferences)
|
|
94
|
+
.where(inArray(userTopicPreferences.userId, internalIds)),
|
|
95
|
+
this.db
|
|
96
|
+
.select()
|
|
97
|
+
.from(userChannelPreferences)
|
|
98
|
+
.where(inArray(userChannelPreferences.userId, internalIds)),
|
|
99
|
+
this.db.select().from(quietHours).where(inArray(quietHours.userId, internalIds)),
|
|
100
|
+
]);
|
|
101
|
+
|
|
102
|
+
const segmentsByUserId = new Map<string, string[]>();
|
|
103
|
+
for (const r of segmentRows) {
|
|
104
|
+
if (!segmentsByUserId.has(r.userId)) segmentsByUserId.set(r.userId, []);
|
|
105
|
+
segmentsByUserId.get(r.userId)!.push(r.segment);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const topicsByUserId = new Map<string, Record<string, boolean>>();
|
|
109
|
+
for (const r of topicRows) {
|
|
110
|
+
if (!topicsByUserId.has(r.userId)) topicsByUserId.set(r.userId, {});
|
|
111
|
+
topicsByUserId.get(r.userId)![r.topic] = r.enabled;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const channelsByUserId = new Map<string, Record<string, boolean>>();
|
|
115
|
+
for (const r of channelRows) {
|
|
116
|
+
if (!channelsByUserId.has(r.userId)) channelsByUserId.set(r.userId, {});
|
|
117
|
+
channelsByUserId.get(r.userId)![r.channel] = r.enabled;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const qhByUserId = new Map<string, any[]>();
|
|
121
|
+
for (const r of qhRows) {
|
|
122
|
+
if (r.userId == null) continue;
|
|
123
|
+
if (!qhByUserId.has(r.userId)) qhByUserId.set(r.userId, []);
|
|
124
|
+
qhByUserId
|
|
125
|
+
.get(r.userId)!
|
|
126
|
+
.push({ start: r.startTime.slice(0, 5), end: r.endTime.slice(0, 5) });
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
for (const userRow of usersRows) {
|
|
130
|
+
const attrs = userRow.attributes as any;
|
|
131
|
+
const internalId = userRow.id;
|
|
132
|
+
|
|
133
|
+
const record: UserRecord = {
|
|
134
|
+
userId: userRow.externalId,
|
|
135
|
+
language: attrs.language ?? DEFAULT_LANGUAGE,
|
|
136
|
+
timezone: attrs.timezone ?? DEFAULT_TIMEZONE,
|
|
137
|
+
email: attrs.email,
|
|
138
|
+
segments: segmentsByUserId.get(internalId) || [],
|
|
139
|
+
preferences: {
|
|
140
|
+
channels: channelsByUserId.get(internalId) || {},
|
|
141
|
+
topics: topicsByUserId.get(internalId) || {},
|
|
142
|
+
quietHours: qhByUserId.get(internalId),
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
this.recordCache.set(`${projectId}:${record.userId}`, record);
|
|
147
|
+
results.push(record);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return results;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async upsertFull(
|
|
154
|
+
projectId: string,
|
|
155
|
+
user: {
|
|
156
|
+
userId: string;
|
|
157
|
+
language?: string;
|
|
158
|
+
timezone?: string;
|
|
159
|
+
email?: string | null;
|
|
160
|
+
segments: string[];
|
|
161
|
+
preferences: Preferences;
|
|
162
|
+
},
|
|
163
|
+
): Promise<void> {
|
|
164
|
+
await this.db.transaction(async (tx) => {
|
|
165
|
+
await tx
|
|
166
|
+
.insert(users)
|
|
167
|
+
.values({
|
|
168
|
+
projectId,
|
|
169
|
+
externalId: user.userId,
|
|
170
|
+
attributes: {
|
|
171
|
+
language: user.language,
|
|
172
|
+
timezone: user.timezone,
|
|
173
|
+
email: user.email,
|
|
174
|
+
},
|
|
175
|
+
})
|
|
176
|
+
.onConflictDoUpdate({
|
|
177
|
+
target: [users.projectId, users.externalId],
|
|
178
|
+
set: {
|
|
179
|
+
attributes: {
|
|
180
|
+
language: user.language,
|
|
181
|
+
timezone: user.timezone,
|
|
182
|
+
email: user.email,
|
|
183
|
+
},
|
|
184
|
+
updatedAt: new Date(),
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
const internalIdRows = await tx
|
|
189
|
+
.select({ id: users.id })
|
|
190
|
+
.from(users)
|
|
191
|
+
.where(and(eq(users.externalId, user.userId), eq(users.projectId, projectId)));
|
|
192
|
+
const internalId = internalIdRows[0]?.id;
|
|
193
|
+
if (!internalId) return;
|
|
194
|
+
|
|
195
|
+
if (user.segments && user.segments.length > 0) {
|
|
196
|
+
await tx
|
|
197
|
+
.insert(userSegments)
|
|
198
|
+
.values(user.segments.map((s) => ({ userId: internalId, segment: s })))
|
|
199
|
+
.onConflictDoNothing();
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (user.preferences && user.preferences.topics) {
|
|
203
|
+
const topicInserts = Object.entries(user.preferences.topics).map(([topic, enabled]) => ({
|
|
204
|
+
userId: internalId,
|
|
205
|
+
topic,
|
|
206
|
+
enabled,
|
|
207
|
+
}));
|
|
208
|
+
if (topicInserts.length > 0) {
|
|
209
|
+
await tx
|
|
210
|
+
.insert(userTopicPreferences)
|
|
211
|
+
.values(topicInserts)
|
|
212
|
+
.onConflictDoUpdate({
|
|
213
|
+
target: [userTopicPreferences.userId, userTopicPreferences.topic],
|
|
214
|
+
set: { enabled: drizzleSql`excluded.enabled` },
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (user.preferences?.channels) {
|
|
220
|
+
const channelInserts = Object.entries(user.preferences.channels).map(
|
|
221
|
+
([channel, enabled]) => ({
|
|
222
|
+
userId: internalId,
|
|
223
|
+
channel: channel as ContactChannel,
|
|
224
|
+
enabled,
|
|
225
|
+
}),
|
|
226
|
+
);
|
|
227
|
+
if (channelInserts.length > 0) {
|
|
228
|
+
await tx
|
|
229
|
+
.insert(userChannelPreferences)
|
|
230
|
+
.values(channelInserts)
|
|
231
|
+
.onConflictDoUpdate({
|
|
232
|
+
target: [userChannelPreferences.userId, userChannelPreferences.channel],
|
|
233
|
+
set: { enabled: drizzleSql`excluded.enabled` },
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (user.preferences?.quietHours !== undefined) {
|
|
239
|
+
await tx.delete(quietHours).where(eq(quietHours.userId, internalId));
|
|
240
|
+
if (user.preferences.quietHours.length > 0) {
|
|
241
|
+
await tx.insert(quietHours).values(
|
|
242
|
+
user.preferences.quietHours.map((window) => ({
|
|
243
|
+
userId: internalId,
|
|
244
|
+
startTime: window.start,
|
|
245
|
+
endTime: window.end,
|
|
246
|
+
})),
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
this.recordCache.delete(`${projectId}:${user.userId}`);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async upsertManyFull(
|
|
255
|
+
projectId: string,
|
|
256
|
+
usersList: Array<{
|
|
257
|
+
userId: string;
|
|
258
|
+
language?: string;
|
|
259
|
+
timezone?: string;
|
|
260
|
+
email?: string | null;
|
|
261
|
+
segments: string[];
|
|
262
|
+
preferences: Preferences;
|
|
263
|
+
}>,
|
|
264
|
+
): Promise<void> {
|
|
265
|
+
if (usersList.length === 0) return;
|
|
266
|
+
|
|
267
|
+
// ON CONFLICT DO UPDATE rejects the whole statement when two proposed rows
|
|
268
|
+
// hit the same key, so an import naming one user twice failed outright.
|
|
269
|
+
// The last occurrence wins, as it would had they been sent one by one.
|
|
270
|
+
const uniqueUsers = [...new Map(usersList.map((u) => [u.userId, u])).values()];
|
|
271
|
+
const winners = new Set(uniqueUsers);
|
|
272
|
+
|
|
273
|
+
let attempts = 0;
|
|
274
|
+
while (attempts < 3) {
|
|
275
|
+
try {
|
|
276
|
+
await this.db.transaction(async (tx) => {
|
|
277
|
+
await tx
|
|
278
|
+
.insert(users)
|
|
279
|
+
.values(
|
|
280
|
+
uniqueUsers.map((u) => ({
|
|
281
|
+
projectId,
|
|
282
|
+
externalId: u.userId,
|
|
283
|
+
attributes: {
|
|
284
|
+
language: u.language,
|
|
285
|
+
timezone: u.timezone,
|
|
286
|
+
email: u.email,
|
|
287
|
+
},
|
|
288
|
+
})),
|
|
289
|
+
)
|
|
290
|
+
.onConflictDoUpdate({
|
|
291
|
+
target: [users.projectId, users.externalId],
|
|
292
|
+
set: {
|
|
293
|
+
// Merged, not replaced: a field the caller left out (absent
|
|
294
|
+
// from the JSON) keeps its stored value.
|
|
295
|
+
attributes: drizzleSql`${users.attributes} || excluded.attributes`,
|
|
296
|
+
updatedAt: new Date(),
|
|
297
|
+
},
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
const internalIdRows = await tx
|
|
301
|
+
.select({ id: users.id, externalId: users.externalId })
|
|
302
|
+
.from(users)
|
|
303
|
+
.where(
|
|
304
|
+
and(
|
|
305
|
+
inArray(
|
|
306
|
+
users.externalId,
|
|
307
|
+
usersList.map((u) => u.userId),
|
|
308
|
+
),
|
|
309
|
+
eq(users.projectId, projectId),
|
|
310
|
+
),
|
|
311
|
+
);
|
|
312
|
+
|
|
313
|
+
const idMap = new Map(internalIdRows.map((r) => [r.externalId, r.id]));
|
|
314
|
+
|
|
315
|
+
const segmentInserts: any[] = [];
|
|
316
|
+
const topicInserts: any[] = [];
|
|
317
|
+
const channelInserts: any[] = [];
|
|
318
|
+
const quietHoursInserts: any[] = [];
|
|
319
|
+
|
|
320
|
+
for (const u of usersList) {
|
|
321
|
+
const internalId = idMap.get(u.userId);
|
|
322
|
+
if (!internalId) continue;
|
|
323
|
+
|
|
324
|
+
if (u.segments && u.segments.length > 0) {
|
|
325
|
+
for (const s of u.segments) {
|
|
326
|
+
segmentInserts.push({ userId: internalId, segment: s });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (u.preferences?.topics) {
|
|
331
|
+
for (const [topic, enabled] of Object.entries(u.preferences.topics)) {
|
|
332
|
+
topicInserts.push({ userId: internalId, topic, enabled });
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (u.preferences?.channels) {
|
|
337
|
+
for (const [channel, enabled] of Object.entries(u.preferences.channels)) {
|
|
338
|
+
channelInserts.push({
|
|
339
|
+
userId: internalId,
|
|
340
|
+
channel: channel as ContactChannel,
|
|
341
|
+
enabled,
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// Quiet hours are replaced, not merged, so only the winning row counts.
|
|
347
|
+
if (
|
|
348
|
+
winners.has(u) &&
|
|
349
|
+
u.preferences?.quietHours &&
|
|
350
|
+
u.preferences.quietHours.length > 0
|
|
351
|
+
) {
|
|
352
|
+
for (const window of u.preferences.quietHours) {
|
|
353
|
+
quietHoursInserts.push({
|
|
354
|
+
userId: internalId,
|
|
355
|
+
startTime: window.start,
|
|
356
|
+
endTime: window.end,
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const segmentSet = new Set<string>();
|
|
363
|
+
const dedupedSegmentInserts: any[] = [];
|
|
364
|
+
for (const s of segmentInserts) {
|
|
365
|
+
const key = `${s.userId}:${s.segment}`;
|
|
366
|
+
if (!segmentSet.has(key)) {
|
|
367
|
+
segmentSet.add(key);
|
|
368
|
+
dedupedSegmentInserts.push(s);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const topicMap = new Map<string, any>();
|
|
373
|
+
for (const t of topicInserts) {
|
|
374
|
+
topicMap.set(`${t.userId}:${t.topic}`, t);
|
|
375
|
+
}
|
|
376
|
+
const dedupedTopicInserts = Array.from(topicMap.values());
|
|
377
|
+
|
|
378
|
+
const channelMap = new Map<string, any>();
|
|
379
|
+
for (const c of channelInserts) {
|
|
380
|
+
channelMap.set(`${c.userId}:${c.channel}`, c);
|
|
381
|
+
}
|
|
382
|
+
const dedupedChannelInserts = Array.from(channelMap.values());
|
|
383
|
+
|
|
384
|
+
if (dedupedSegmentInserts.length > 0) {
|
|
385
|
+
await tx.insert(userSegments).values(dedupedSegmentInserts).onConflictDoNothing();
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
if (dedupedTopicInserts.length > 0) {
|
|
389
|
+
await tx
|
|
390
|
+
.insert(userTopicPreferences)
|
|
391
|
+
.values(dedupedTopicInserts)
|
|
392
|
+
.onConflictDoUpdate({
|
|
393
|
+
target: [userTopicPreferences.userId, userTopicPreferences.topic],
|
|
394
|
+
set: { enabled: drizzleSql`excluded.enabled` },
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
if (dedupedChannelInserts.length > 0) {
|
|
399
|
+
await tx
|
|
400
|
+
.insert(userChannelPreferences)
|
|
401
|
+
.values(dedupedChannelInserts)
|
|
402
|
+
.onConflictDoUpdate({
|
|
403
|
+
target: [userChannelPreferences.userId, userChannelPreferences.channel],
|
|
404
|
+
set: { enabled: drizzleSql`excluded.enabled` },
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const usersWithQuietHours = uniqueUsers.filter(
|
|
409
|
+
(u) => u.preferences?.quietHours !== undefined,
|
|
410
|
+
);
|
|
411
|
+
const internalIdsToClearQuietHours = usersWithQuietHours
|
|
412
|
+
.map((u) => idMap.get(u.userId))
|
|
413
|
+
.filter(Boolean) as string[];
|
|
414
|
+
|
|
415
|
+
if (internalIdsToClearQuietHours.length > 0) {
|
|
416
|
+
await tx
|
|
417
|
+
.delete(quietHours)
|
|
418
|
+
.where(inArray(quietHours.userId, internalIdsToClearQuietHours));
|
|
419
|
+
}
|
|
420
|
+
if (quietHoursInserts.length > 0) {
|
|
421
|
+
await tx.insert(quietHours).values(quietHoursInserts);
|
|
422
|
+
}
|
|
423
|
+
});
|
|
424
|
+
for (const u of usersList) {
|
|
425
|
+
this.recordCache.delete(`${projectId}:${u.userId}`);
|
|
426
|
+
}
|
|
427
|
+
return;
|
|
428
|
+
} catch (err: any) {
|
|
429
|
+
attempts++;
|
|
430
|
+
if (attempts >= 3 || (err.code !== "40001" && err.code !== "40P01")) {
|
|
431
|
+
throw err;
|
|
432
|
+
}
|
|
433
|
+
await new Promise((resolve) => setTimeout(resolve, Math.pow(2, attempts) * 100));
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
async updatePartial(
|
|
439
|
+
projectId: string,
|
|
440
|
+
userId: string,
|
|
441
|
+
patch: {
|
|
442
|
+
language?: string;
|
|
443
|
+
timezone?: string;
|
|
444
|
+
email?: string | null;
|
|
445
|
+
segments?: string[];
|
|
446
|
+
preferences?: Preferences;
|
|
447
|
+
},
|
|
448
|
+
): Promise<boolean> {
|
|
449
|
+
const existing = await this.findById(projectId, userId);
|
|
450
|
+
if (!existing) return false;
|
|
451
|
+
|
|
452
|
+
const attrs = {
|
|
453
|
+
language: patch.language ?? existing.language,
|
|
454
|
+
timezone: patch.timezone ?? existing.timezone,
|
|
455
|
+
// `null` clears the email; only an absent field keeps the old one.
|
|
456
|
+
email: patch.email !== undefined ? patch.email : existing.email,
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
await this.db.transaction(async (tx) => {
|
|
460
|
+
await tx
|
|
461
|
+
.update(users)
|
|
462
|
+
.set({ attributes: attrs, updatedAt: new Date() })
|
|
463
|
+
.where(and(eq(users.externalId, userId), eq(users.projectId, projectId)));
|
|
464
|
+
|
|
465
|
+
const internalIdRows = await tx
|
|
466
|
+
.select({ id: users.id })
|
|
467
|
+
.from(users)
|
|
468
|
+
.where(and(eq(users.externalId, userId), eq(users.projectId, projectId)));
|
|
469
|
+
const internalId = internalIdRows[0]?.id;
|
|
470
|
+
if (!internalId) return;
|
|
471
|
+
|
|
472
|
+
if (patch.segments) {
|
|
473
|
+
await tx.delete(userSegments).where(eq(userSegments.userId, internalId));
|
|
474
|
+
if (patch.segments.length > 0) {
|
|
475
|
+
await tx
|
|
476
|
+
.insert(userSegments)
|
|
477
|
+
.values(patch.segments.map((s) => ({ userId: internalId, segment: s })))
|
|
478
|
+
.onConflictDoNothing();
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
if (patch.preferences && patch.preferences.topics) {
|
|
483
|
+
const topicInserts = Object.entries(patch.preferences.topics).map(([topic, enabled]) => ({
|
|
484
|
+
userId: internalId,
|
|
485
|
+
topic,
|
|
486
|
+
enabled,
|
|
487
|
+
}));
|
|
488
|
+
if (topicInserts.length > 0) {
|
|
489
|
+
await tx
|
|
490
|
+
.insert(userTopicPreferences)
|
|
491
|
+
.values(topicInserts)
|
|
492
|
+
.onConflictDoUpdate({
|
|
493
|
+
target: [userTopicPreferences.userId, userTopicPreferences.topic],
|
|
494
|
+
set: { enabled: drizzleSql`excluded.enabled` },
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
if (patch.preferences?.channels) {
|
|
500
|
+
const channelInserts = Object.entries(patch.preferences.channels).map(
|
|
501
|
+
([channel, enabled]) => ({
|
|
502
|
+
userId: internalId,
|
|
503
|
+
channel: channel as ContactChannel,
|
|
504
|
+
enabled,
|
|
505
|
+
}),
|
|
506
|
+
);
|
|
507
|
+
if (channelInserts.length > 0) {
|
|
508
|
+
await tx
|
|
509
|
+
.insert(userChannelPreferences)
|
|
510
|
+
.values(channelInserts)
|
|
511
|
+
.onConflictDoUpdate({
|
|
512
|
+
target: [userChannelPreferences.userId, userChannelPreferences.channel],
|
|
513
|
+
set: { enabled: drizzleSql`excluded.enabled` },
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
if (patch.preferences?.quietHours !== undefined) {
|
|
519
|
+
await tx.delete(quietHours).where(eq(quietHours.userId, internalId));
|
|
520
|
+
if (patch.preferences.quietHours.length > 0) {
|
|
521
|
+
await tx.insert(quietHours).values(
|
|
522
|
+
patch.preferences.quietHours.map((window) => ({
|
|
523
|
+
userId: internalId,
|
|
524
|
+
startTime: window.start,
|
|
525
|
+
endTime: window.end,
|
|
526
|
+
})),
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
this.recordCache.delete(`${projectId}:${userId}`);
|
|
533
|
+
return true;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async delete(projectId: string, userId: string): Promise<boolean> {
|
|
537
|
+
this.recordCache.delete(`${projectId}:${userId}`);
|
|
538
|
+
const result = await this.db
|
|
539
|
+
.delete(users)
|
|
540
|
+
.where(and(eq(users.externalId, userId), eq(users.projectId, projectId)))
|
|
541
|
+
.returning();
|
|
542
|
+
return result.length > 0;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
async list(
|
|
546
|
+
projectId: string,
|
|
547
|
+
limit: number,
|
|
548
|
+
cursor?: string,
|
|
549
|
+
filters?: {
|
|
550
|
+
search?: string;
|
|
551
|
+
segment?: string;
|
|
552
|
+
language?: string;
|
|
553
|
+
timezone?: string;
|
|
554
|
+
channel?: string;
|
|
555
|
+
},
|
|
556
|
+
): Promise<{ users: UserProfile[]; nextCursor: string | null }> {
|
|
557
|
+
const conditions = [eq(users.projectId, projectId)];
|
|
558
|
+
|
|
559
|
+
// The cursor is the id of the last row returned. Paging on created_at
|
|
560
|
+
// alone skipped rows: a bulk import writes every user in one transaction,
|
|
561
|
+
// so they share one created_at, and the millisecond cursor could not tell
|
|
562
|
+
// them apart. (created_at, id) is unique and ordered.
|
|
563
|
+
if (cursor && UUID_RE.test(cursor)) {
|
|
564
|
+
conditions.push(
|
|
565
|
+
drizzleSql`(${users.createdAt}, ${users.id}) < (SELECT c.created_at, c.id FROM ${users} c WHERE c.id = ${cursor})`,
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
if (filters?.language) {
|
|
570
|
+
conditions.push(drizzleSql`(${users.attributes}->>'language') = ${filters.language}`);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
if (filters?.timezone) {
|
|
574
|
+
conditions.push(drizzleSql`(${users.attributes}->>'timezone') = ${filters.timezone}`);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
if (filters?.search) {
|
|
578
|
+
// `%`, `_` and `\` in the search are literal, not wildcards.
|
|
579
|
+
const term = `%${filters.search.trim().replace(/[\\%_]/g, "\\$&")}%`;
|
|
580
|
+
conditions.push(
|
|
581
|
+
drizzleSql`(${users.externalId} ILIKE ${term} OR (${users.attributes}->>'email') ILIKE ${term})`,
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
if (filters?.segment) {
|
|
586
|
+
conditions.push(
|
|
587
|
+
drizzleSql`EXISTS (SELECT 1 FROM ${userSegments} WHERE ${userSegments.userId} = ${users.id} AND ${userSegments.segment} = ${filters.segment})`,
|
|
588
|
+
);
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
if (filters?.channel) {
|
|
592
|
+
conditions.push(
|
|
593
|
+
drizzleSql`EXISTS (SELECT 1 FROM ${userContacts} WHERE ${userContacts.userId} = ${users.id} AND ${userContacts.channel} = ${filters.channel})`,
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const rows = await this.db
|
|
598
|
+
.select()
|
|
599
|
+
.from(users)
|
|
600
|
+
.where(and(...conditions))
|
|
601
|
+
.orderBy(desc(users.createdAt), desc(users.id))
|
|
602
|
+
.limit(limit);
|
|
603
|
+
|
|
604
|
+
const items = rows.map((r) => {
|
|
605
|
+
const attrs = r.attributes as any;
|
|
606
|
+
return {
|
|
607
|
+
userId: r.externalId,
|
|
608
|
+
language: attrs.language ?? DEFAULT_LANGUAGE,
|
|
609
|
+
timezone: attrs.timezone ?? DEFAULT_TIMEZONE,
|
|
610
|
+
email: attrs.email,
|
|
611
|
+
createdAt: r.createdAt.getTime(),
|
|
612
|
+
};
|
|
613
|
+
});
|
|
614
|
+
|
|
615
|
+
const nextCursor = rows.length === limit ? rows[rows.length - 1]!.id : null;
|
|
616
|
+
return { users: items, nextCursor };
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
async findUsersBySegment(projectId: string, segmentName: string): Promise<string[]> {
|
|
620
|
+
const rows = await this.db
|
|
621
|
+
.select({ externalId: users.externalId })
|
|
622
|
+
.from(users)
|
|
623
|
+
.innerJoin(userSegments, eq(users.id, userSegments.userId))
|
|
624
|
+
.where(and(eq(userSegments.segment, segmentName), eq(users.projectId, projectId)));
|
|
625
|
+
|
|
626
|
+
return rows.map((r) => r.externalId);
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
async findUsersByTopic(projectId: string, topicName: string): Promise<string[]> {
|
|
630
|
+
const rows = await this.db
|
|
631
|
+
.select({ externalId: users.externalId })
|
|
632
|
+
.from(users)
|
|
633
|
+
.innerJoin(userTopicPreferences, eq(users.id, userTopicPreferences.userId))
|
|
634
|
+
.where(
|
|
635
|
+
and(
|
|
636
|
+
eq(userTopicPreferences.topic, topicName),
|
|
637
|
+
eq(userTopicPreferences.enabled, true),
|
|
638
|
+
eq(users.projectId, projectId),
|
|
639
|
+
),
|
|
640
|
+
);
|
|
641
|
+
|
|
642
|
+
return rows.map((r) => r.externalId);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { eq, and, inArray, desc } from "drizzle-orm";
|
|
2
|
+
import type { Db } from "@/index.js";
|
|
3
|
+
import {
|
|
4
|
+
workflowInstances,
|
|
5
|
+
workflowSteps,
|
|
6
|
+
workflowWaiters,
|
|
7
|
+
workflowDefinitions,
|
|
8
|
+
} from "@/db/schema.js";
|
|
9
|
+
|
|
10
|
+
export class WorkflowRepository {
|
|
11
|
+
constructor(private readonly db: Db) {}
|
|
12
|
+
|
|
13
|
+
async listDefinitions(projectId: string): Promise<any[]> {
|
|
14
|
+
return this.db
|
|
15
|
+
.select()
|
|
16
|
+
.from(workflowDefinitions)
|
|
17
|
+
.where(eq(workflowDefinitions.projectId, projectId))
|
|
18
|
+
.orderBy(desc(workflowDefinitions.createdAt));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async getInstance(projectId: string, instanceId: string): Promise<any | null> {
|
|
22
|
+
const instances = await this.db
|
|
23
|
+
.select()
|
|
24
|
+
.from(workflowInstances)
|
|
25
|
+
.where(and(eq(workflowInstances.id, instanceId), eq(workflowInstances.projectId, projectId)))
|
|
26
|
+
.limit(1);
|
|
27
|
+
if (!instances[0]) return null;
|
|
28
|
+
|
|
29
|
+
const steps = await this.db
|
|
30
|
+
.select()
|
|
31
|
+
.from(workflowSteps)
|
|
32
|
+
.where(eq(workflowSteps.instanceId, instanceId))
|
|
33
|
+
.orderBy(workflowSteps.createdAt);
|
|
34
|
+
const waiters = await this.db
|
|
35
|
+
.select()
|
|
36
|
+
.from(workflowWaiters)
|
|
37
|
+
.where(eq(workflowWaiters.instanceId, instanceId));
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
...instances[0],
|
|
41
|
+
steps,
|
|
42
|
+
waiters,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async cancelInstance(projectId: string, instanceId: string): Promise<boolean> {
|
|
47
|
+
return await this.db.transaction(async (tx) => {
|
|
48
|
+
const result = await tx
|
|
49
|
+
.update(workflowInstances)
|
|
50
|
+
.set({ status: "canceled" })
|
|
51
|
+
.where(
|
|
52
|
+
and(
|
|
53
|
+
eq(workflowInstances.id, instanceId),
|
|
54
|
+
eq(workflowInstances.projectId, projectId),
|
|
55
|
+
inArray(workflowInstances.status, ["pending", "running"]),
|
|
56
|
+
),
|
|
57
|
+
)
|
|
58
|
+
.returning();
|
|
59
|
+
if (result.length === 0) return false;
|
|
60
|
+
await tx.delete(workflowWaiters).where(eq(workflowWaiters.instanceId, instanceId));
|
|
61
|
+
return true;
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
}
|