@terreno/comms 57.2.0 → 57.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -0
- package/dist/adapters/expoPush.d.ts +54 -0
- package/dist/adapters/expoPush.js +400 -0
- package/dist/adapters/sendgrid.d.ts +3 -0
- package/dist/adapters/sendgrid.js +7 -1
- package/dist/adapters/twilioSms.d.ts +36 -0
- package/dist/adapters/twilioSms.js +232 -0
- package/dist/adapters/twilioVerify.d.ts +44 -0
- package/dist/adapters/twilioVerify.js +212 -0
- package/dist/commsApp.d.ts +4 -1
- package/dist/commsApp.js +28 -2
- package/dist/commsQuery.d.ts +30 -0
- package/dist/commsQuery.js +134 -0
- package/dist/commsRetry.d.ts +16 -0
- package/dist/commsRetry.js +79 -0
- package/dist/commsService.d.ts +11 -4
- package/dist/commsService.js +217 -47
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -1
- package/dist/routes/commsDashboard.d.ts +11 -0
- package/dist/routes/commsDashboard.js +414 -0
- package/dist/templates.d.ts +9 -0
- package/dist/templates.js +34 -1
- package/dist/types.d.ts +11 -0
- package/dist/webhooks/sendgridWebhooks.d.ts +16 -0
- package/dist/webhooks/sendgridWebhooks.js +251 -0
- package/dist/webhooks/twilioWebhooks.d.ts +18 -0
- package/dist/webhooks/twilioWebhooks.js +175 -0
- package/package.json +26 -5
- package/src/adapters/expoPush.test.ts +585 -0
- package/src/adapters/expoPush.ts +304 -0
- package/src/adapters/sendgrid.ts +8 -0
- package/src/adapters/twilioSms.test.ts +374 -0
- package/src/adapters/twilioSms.ts +237 -0
- package/src/adapters/twilioVerify.test.ts +207 -0
- package/src/adapters/twilioVerify.ts +227 -0
- package/src/commsApp.test.ts +13 -0
- package/src/commsApp.ts +38 -3
- package/src/commsQuery.test.ts +165 -0
- package/src/commsQuery.ts +162 -0
- package/src/commsRetry.ts +87 -0
- package/src/commsService.test.ts +68 -0
- package/src/commsService.ts +177 -20
- package/src/index.ts +9 -2
- package/src/routes/commsDashboard.test.ts +310 -0
- package/src/routes/commsDashboard.ts +327 -0
- package/src/templates.test.ts +63 -1
- package/src/templates.ts +47 -0
- package/src/tests/bunSetup.ts +8 -0
- package/src/types.ts +13 -0
- package/src/webhooks/sendgridWebhooks.test.ts +520 -0
- package/src/webhooks/sendgridWebhooks.ts +166 -0
- package/src/webhooks/twilioWebhooks.test.ts +352 -0
- package/src/webhooks/twilioWebhooks.ts +154 -0
- package/dist/routes/commsExplorer.d.ts +0 -7
- package/dist/routes/commsExplorer.js +0 -147
- package/src/routes/commsExplorer.ts +0 -114
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import {beforeEach, describe, it} from "bun:test";
|
|
2
|
+
import {
|
|
3
|
+
addAuthRoutes,
|
|
4
|
+
apiErrorMiddleware,
|
|
5
|
+
apiUnauthorizedMiddleware,
|
|
6
|
+
setupAuth,
|
|
7
|
+
type UserModel as UserModelType,
|
|
8
|
+
} from "@terreno/api";
|
|
9
|
+
import {authAsUser, getBaseServer, setupDb, UserModel} from "@terreno/api/testing";
|
|
10
|
+
import {assert} from "chai";
|
|
11
|
+
import type express from "express";
|
|
12
|
+
import {DateTime} from "luxon";
|
|
13
|
+
import mongoose from "mongoose";
|
|
14
|
+
|
|
15
|
+
import {CommsApp} from "../commsApp";
|
|
16
|
+
import {CommsMessage} from "../models/commsMessage";
|
|
17
|
+
import type {MailMessage, MailProvider, SendResult} from "../types";
|
|
18
|
+
|
|
19
|
+
const buildApp = (plugin = new CommsApp()): express.Application => {
|
|
20
|
+
const app = getBaseServer();
|
|
21
|
+
setupAuth(app, UserModel as unknown as UserModelType);
|
|
22
|
+
addAuthRoutes(app, UserModel as unknown as UserModelType);
|
|
23
|
+
plugin.register(app);
|
|
24
|
+
app.use(apiUnauthorizedMiddleware);
|
|
25
|
+
app.use(apiErrorMiddleware);
|
|
26
|
+
return app;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const seedMessage = async (overrides: Record<string, unknown> = {}): Promise<mongoose.Document> => {
|
|
30
|
+
const created = await CommsMessage.logSend({
|
|
31
|
+
attempts: [
|
|
32
|
+
{
|
|
33
|
+
at: DateTime.utc().toJSDate(),
|
|
34
|
+
provider: "console",
|
|
35
|
+
providerMessageId: "msg-1",
|
|
36
|
+
},
|
|
37
|
+
],
|
|
38
|
+
channel: "mail",
|
|
39
|
+
payload: {subject: "Welcome", text: "Hello", to: "person@example.com"},
|
|
40
|
+
payloadExpiresAt: DateTime.utc().plus({days: 7}).toJSDate(),
|
|
41
|
+
provider: "console",
|
|
42
|
+
status: "sent",
|
|
43
|
+
subject: "Welcome",
|
|
44
|
+
to: "[redacted]",
|
|
45
|
+
...overrides,
|
|
46
|
+
});
|
|
47
|
+
if (!created) {
|
|
48
|
+
throw new Error("Failed to seed CommsMessage");
|
|
49
|
+
}
|
|
50
|
+
return created;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
describe("comms dashboard routes", () => {
|
|
54
|
+
beforeEach(async (): Promise<void> => {
|
|
55
|
+
await setupDb();
|
|
56
|
+
await CommsMessage.deleteMany({});
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("filters list results by provider, error class, error code, template, recipient, and q", async (): Promise<void> => {
|
|
60
|
+
const app = buildApp();
|
|
61
|
+
const admin = await authAsUser(app, "admin");
|
|
62
|
+
const userId = new mongoose.Types.ObjectId();
|
|
63
|
+
await seedMessage({
|
|
64
|
+
error: "mailbox full",
|
|
65
|
+
errorClass: "transient",
|
|
66
|
+
errorCode: "421",
|
|
67
|
+
provider: "sendgrid",
|
|
68
|
+
status: "failed",
|
|
69
|
+
subject: "Invoice 99",
|
|
70
|
+
templateId: "d-invoice",
|
|
71
|
+
to: "****1234",
|
|
72
|
+
userId,
|
|
73
|
+
});
|
|
74
|
+
await seedMessage({
|
|
75
|
+
channel: "sms",
|
|
76
|
+
provider: "twilio",
|
|
77
|
+
status: "sent",
|
|
78
|
+
subject: undefined,
|
|
79
|
+
to: "****9999",
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
const byProvider = await admin.get("/comms/messages").query({provider: "sendgrid"}).expect(200);
|
|
83
|
+
assert.lengthOf(byProvider.body.data, 1);
|
|
84
|
+
assert.equal(byProvider.body.data[0].provider, "sendgrid");
|
|
85
|
+
|
|
86
|
+
const byErrorClass = await admin
|
|
87
|
+
.get("/comms/messages")
|
|
88
|
+
.query({errorClass: "transient"})
|
|
89
|
+
.expect(200);
|
|
90
|
+
assert.equal(byErrorClass.body.total, 1);
|
|
91
|
+
|
|
92
|
+
const byErrorCode = await admin.get("/comms/messages").query({errorCode: "421"}).expect(200);
|
|
93
|
+
assert.equal(byErrorCode.body.total, 1);
|
|
94
|
+
|
|
95
|
+
const byTemplate = await admin
|
|
96
|
+
.get("/comms/messages")
|
|
97
|
+
.query({templateId: "d-invoice"})
|
|
98
|
+
.expect(200);
|
|
99
|
+
assert.equal(byTemplate.body.total, 1);
|
|
100
|
+
|
|
101
|
+
const byTo = await admin.get("/comms/messages").query({to: "****1234"}).expect(200);
|
|
102
|
+
assert.equal(byTo.body.total, 1);
|
|
103
|
+
|
|
104
|
+
const byQ = await admin.get("/comms/messages").query({q: "Invoice"}).expect(200);
|
|
105
|
+
assert.equal(byQ.body.total, 1);
|
|
106
|
+
const byLast4 = await admin.get("/comms/messages").query({q: "1234"}).expect(200);
|
|
107
|
+
assert.equal(byLast4.body.total, 1);
|
|
108
|
+
const byErrorText = await admin.get("/comms/messages").query({q: "mailbox"}).expect(200);
|
|
109
|
+
assert.equal(byErrorText.body.total, 1);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("returns message detail with attempts, payload, metadata, and linked retries", async (): Promise<void> => {
|
|
113
|
+
const app = buildApp();
|
|
114
|
+
const admin = await authAsUser(app, "admin");
|
|
115
|
+
const original = await seedMessage({
|
|
116
|
+
metadata: {consoleUrl: "https://sendgrid.example/activity/1"},
|
|
117
|
+
status: "failed",
|
|
118
|
+
});
|
|
119
|
+
const retry = await seedMessage({
|
|
120
|
+
retriedFromId: original._id,
|
|
121
|
+
subject: "Welcome retry",
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
const response = await admin.get(`/comms/messages/${String(original._id)}`).expect(200);
|
|
125
|
+
assert.equal(response.body.data.subject, "Welcome");
|
|
126
|
+
assert.deepEqual(response.body.data.payload, {
|
|
127
|
+
subject: "Welcome",
|
|
128
|
+
text: "Hello",
|
|
129
|
+
to: "person@example.com",
|
|
130
|
+
});
|
|
131
|
+
assert.equal(response.body.data.metadata.consoleUrl, "https://sendgrid.example/activity/1");
|
|
132
|
+
assert.lengthOf(response.body.data.attempts, 1);
|
|
133
|
+
assert.equal(response.body.data.retries[0]._id, String(retry._id));
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("returns 404 for unknown message ids and 403 for non-admins on detail and stats", async (): Promise<void> => {
|
|
137
|
+
const app = buildApp();
|
|
138
|
+
const admin = await authAsUser(app, "admin");
|
|
139
|
+
const user = await authAsUser(app, "notAdmin");
|
|
140
|
+
const missing = "507f1f77bcf86cd799439011";
|
|
141
|
+
|
|
142
|
+
await user.get(`/comms/messages/${missing}`).expect(403);
|
|
143
|
+
await user.get("/comms/stats").expect(403);
|
|
144
|
+
await admin.get(`/comms/messages/${missing}`).expect(404);
|
|
145
|
+
await admin.get("/comms/messages/not-an-id").expect(404);
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
describe("comms retry and stats", () => {
|
|
150
|
+
beforeEach(async (): Promise<void> => {
|
|
151
|
+
await setupDb();
|
|
152
|
+
await CommsMessage.deleteMany({});
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
it("retries a failed mail through the facade and links the new row", async (): Promise<void> => {
|
|
156
|
+
let sent: MailMessage | undefined;
|
|
157
|
+
let sawRetry = false;
|
|
158
|
+
const mail: MailProvider = {
|
|
159
|
+
id: "memory-mail",
|
|
160
|
+
sendMail: async (message: MailMessage): Promise<SendResult> => {
|
|
161
|
+
sent = message;
|
|
162
|
+
return {accepted: true, providerMessageId: "retry-1"};
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
const plugin = new CommsApp({
|
|
166
|
+
mail,
|
|
167
|
+
onSend: async (context): Promise<void> => {
|
|
168
|
+
if (context.isRetry) {
|
|
169
|
+
sawRetry = true;
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
redactRecipients: false,
|
|
173
|
+
});
|
|
174
|
+
const app = buildApp(plugin);
|
|
175
|
+
const admin = await authAsUser(app, "admin");
|
|
176
|
+
const original = await seedMessage({
|
|
177
|
+
errorClass: "transient",
|
|
178
|
+
status: "failed",
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
const response = await admin.post(`/comms/messages/${String(original._id)}/retry`).expect(200);
|
|
182
|
+
|
|
183
|
+
assert.equal(sent?.subject, "Welcome");
|
|
184
|
+
assert.equal(sent?.to, "person@example.com");
|
|
185
|
+
assert.equal(response.body.data.retriedFromId, String(original._id));
|
|
186
|
+
assert.isTrue(sawRetry);
|
|
187
|
+
const reloaded = await CommsMessage.findExactlyOne({_id: original._id});
|
|
188
|
+
assert.equal(String(reloaded.retriedById), response.body.data._id);
|
|
189
|
+
assert.match(String(response.body.data.metadata.retriedByUserId), /^[a-f0-9]{24}$/);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it("does not return an earlier retry when this send created no log", async (): Promise<void> => {
|
|
193
|
+
const mail: MailProvider = {
|
|
194
|
+
id: "memory-mail",
|
|
195
|
+
sendMail: async (): Promise<SendResult> => ({accepted: true, providerMessageId: "ok"}),
|
|
196
|
+
};
|
|
197
|
+
const loggingApp = buildApp(new CommsApp({mail}));
|
|
198
|
+
const admin = await authAsUser(loggingApp, "admin");
|
|
199
|
+
const original = await seedMessage({status: "failed"});
|
|
200
|
+
const first = await admin.post(`/comms/messages/${String(original._id)}/retry`).expect(200);
|
|
201
|
+
const firstRetryId = first.body.data._id as string;
|
|
202
|
+
|
|
203
|
+
const silentApp = buildApp(new CommsApp({logMessages: false, mail}));
|
|
204
|
+
const silentAdmin = await authAsUser(silentApp, "admin");
|
|
205
|
+
const second = await silentAdmin
|
|
206
|
+
.post(`/comms/messages/${String(original._id)}/retry`)
|
|
207
|
+
.expect(500);
|
|
208
|
+
assert.equal(second.body.title, "Retry did not create a communication log");
|
|
209
|
+
const newest = await CommsMessage.find({retriedFromId: original._id}).sort("-created").limit(1);
|
|
210
|
+
assert.equal(String(newest[0]?._id), firstRetryId);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
it("returns stable codes for each non-retryable reason", async (): Promise<void> => {
|
|
214
|
+
const plugin = new CommsApp({
|
|
215
|
+
mail: {id: "memory-mail", sendMail: async () => ({accepted: true})},
|
|
216
|
+
});
|
|
217
|
+
const app = buildApp(plugin);
|
|
218
|
+
const admin = await authAsUser(app, "admin");
|
|
219
|
+
|
|
220
|
+
const verification = await seedMessage({channel: "verification", status: "failed"});
|
|
221
|
+
const permanent = await seedMessage({errorClass: "permanent", status: "failed"});
|
|
222
|
+
const sent = await seedMessage({status: "sent"});
|
|
223
|
+
const expired = await seedMessage({
|
|
224
|
+
payload: undefined,
|
|
225
|
+
payloadExpiresAt: undefined,
|
|
226
|
+
status: "failed",
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
const verificationRes = await admin
|
|
230
|
+
.post(`/comms/messages/${String(verification._id)}/retry`)
|
|
231
|
+
.expect(400);
|
|
232
|
+
assert.equal(verificationRes.body.code, "comms-retry-not-retryable");
|
|
233
|
+
|
|
234
|
+
const permanentRes = await admin
|
|
235
|
+
.post(`/comms/messages/${String(permanent._id)}/retry`)
|
|
236
|
+
.expect(400);
|
|
237
|
+
assert.equal(permanentRes.body.code, "comms-retry-not-retryable");
|
|
238
|
+
|
|
239
|
+
const sentRes = await admin.post(`/comms/messages/${String(sent._id)}/retry`).expect(400);
|
|
240
|
+
assert.equal(sentRes.body.code, "comms-retry-not-retryable");
|
|
241
|
+
|
|
242
|
+
const expiredRes = await admin.post(`/comms/messages/${String(expired._id)}/retry`).expect(400);
|
|
243
|
+
assert.equal(expiredRes.body.code, "comms-retry-payload-expired");
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
it("returns comms-retry-channel-unconfigured in production when mail is missing", async (): Promise<void> => {
|
|
247
|
+
const previous = process.env.NODE_ENV;
|
|
248
|
+
process.env.NODE_ENV = "production";
|
|
249
|
+
try {
|
|
250
|
+
const plugin = new CommsApp({});
|
|
251
|
+
const app = buildApp(plugin);
|
|
252
|
+
const admin = await authAsUser(app, "admin");
|
|
253
|
+
const original = await seedMessage({status: "failed"});
|
|
254
|
+
const response = await admin
|
|
255
|
+
.post(`/comms/messages/${String(original._id)}/retry`)
|
|
256
|
+
.expect(400);
|
|
257
|
+
assert.equal(response.body.code, "comms-retry-channel-unconfigured");
|
|
258
|
+
} finally {
|
|
259
|
+
process.env.NODE_ENV = previous;
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it("retryMany respects the cap and reports skipped reasons", async (): Promise<void> => {
|
|
264
|
+
const mail: MailProvider = {
|
|
265
|
+
id: "memory-mail",
|
|
266
|
+
sendMail: async (): Promise<SendResult> => ({accepted: true, providerMessageId: "ok"}),
|
|
267
|
+
};
|
|
268
|
+
const app = buildApp(new CommsApp({mail}));
|
|
269
|
+
const admin = await authAsUser(app, "admin");
|
|
270
|
+
const failed = await Promise.all([
|
|
271
|
+
seedMessage({status: "failed", subject: "one"}),
|
|
272
|
+
seedMessage({status: "failed", subject: "two"}),
|
|
273
|
+
seedMessage({status: "failed", subject: "three"}),
|
|
274
|
+
]);
|
|
275
|
+
await seedMessage({errorClass: "permanent", status: "failed", subject: "permanent"});
|
|
276
|
+
|
|
277
|
+
const response = await admin
|
|
278
|
+
.post("/comms/messages/retryMany")
|
|
279
|
+
.send({limit: 2, status: "failed"})
|
|
280
|
+
.expect(200);
|
|
281
|
+
|
|
282
|
+
assert.equal(response.body.retried.length + response.body.skipped.length, 2);
|
|
283
|
+
assert.isAtMost(response.body.retried.length, 2);
|
|
284
|
+
assert.isAtLeast(response.body.retried.length, 1);
|
|
285
|
+
assert.equal(failed.length, 3);
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it("stats totals match the filtered list for the same range", async (): Promise<void> => {
|
|
289
|
+
const app = buildApp();
|
|
290
|
+
const admin = await authAsUser(app, "admin");
|
|
291
|
+
const startDate = DateTime.utc().minus({hours: 1}).toISO();
|
|
292
|
+
const endDate = DateTime.utc().plus({hours: 1}).toISO();
|
|
293
|
+
await seedMessage({provider: "sendgrid", status: "sent"});
|
|
294
|
+
await seedMessage({provider: "sendgrid", status: "failed"});
|
|
295
|
+
await seedMessage({channel: "sms", provider: "twilio", status: "delivered"});
|
|
296
|
+
|
|
297
|
+
const list = await admin.get("/comms/messages").query({endDate, startDate}).expect(200);
|
|
298
|
+
const stats = await admin.get("/comms/stats").query({endDate, startDate}).expect(200);
|
|
299
|
+
|
|
300
|
+
assert.equal(stats.body.totals.total, list.body.total);
|
|
301
|
+
assert.equal(
|
|
302
|
+
stats.body.totals.sent + stats.body.totals.failed + stats.body.totals.delivered,
|
|
303
|
+
list.body.total
|
|
304
|
+
);
|
|
305
|
+
const sendgrid = stats.body.byProvider.find(
|
|
306
|
+
(row: {provider: string}) => row.provider === "sendgrid"
|
|
307
|
+
);
|
|
308
|
+
assert.equal(sendgrid.failureRate, 0.5);
|
|
309
|
+
});
|
|
310
|
+
});
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import {
|
|
2
|
+
APIError,
|
|
3
|
+
asyncHandler,
|
|
4
|
+
authenticateMiddleware,
|
|
5
|
+
createOpenApiBuilder,
|
|
6
|
+
isAPIError,
|
|
7
|
+
type OpenApiMiddleware,
|
|
8
|
+
} from "@terreno/api";
|
|
9
|
+
import type express from "express";
|
|
10
|
+
import mongoose from "mongoose";
|
|
11
|
+
import {
|
|
12
|
+
buildCommsMessageMatch,
|
|
13
|
+
parseCommsListFilters,
|
|
14
|
+
parseCommsListPagination,
|
|
15
|
+
parseRetryManyLimit,
|
|
16
|
+
} from "../commsQuery";
|
|
17
|
+
import {serializeCommsMessage} from "../commsRetry";
|
|
18
|
+
import type {CommsService} from "../commsService";
|
|
19
|
+
import {CommsMessage} from "../models/commsMessage";
|
|
20
|
+
import type {CommsChannel} from "../types";
|
|
21
|
+
|
|
22
|
+
interface CommsDashboardRouteOptions {
|
|
23
|
+
basePath?: string;
|
|
24
|
+
openApi?: unknown;
|
|
25
|
+
service: CommsService;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const requireAdmin = (req: express.Request): {id?: string} => {
|
|
29
|
+
const user = req.user as
|
|
30
|
+
| {admin?: boolean; id?: string; _id?: {toString: () => string}}
|
|
31
|
+
| undefined;
|
|
32
|
+
if (!user?.admin) {
|
|
33
|
+
throw new APIError({status: 403, title: "Admin access required"});
|
|
34
|
+
}
|
|
35
|
+
return {id: user.id ?? user._id?.toString()};
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const listQueryParameters = (
|
|
39
|
+
builder: ReturnType<typeof createOpenApiBuilder>
|
|
40
|
+
): ReturnType<typeof createOpenApiBuilder> =>
|
|
41
|
+
builder
|
|
42
|
+
.withQueryParameter("page", {type: "number"}, {required: false})
|
|
43
|
+
.withQueryParameter("limit", {type: "number"}, {required: false})
|
|
44
|
+
.withQueryParameter("channel", {type: "string"}, {required: false})
|
|
45
|
+
.withQueryParameter("provider", {type: "string"}, {required: false})
|
|
46
|
+
.withQueryParameter("status", {type: "string"}, {required: false})
|
|
47
|
+
.withQueryParameter("errorClass", {type: "string"}, {required: false})
|
|
48
|
+
.withQueryParameter("errorCode", {type: "string"}, {required: false})
|
|
49
|
+
.withQueryParameter("userId", {type: "string"}, {required: false})
|
|
50
|
+
.withQueryParameter("to", {type: "string"}, {required: false})
|
|
51
|
+
.withQueryParameter("templateId", {type: "string"}, {required: false})
|
|
52
|
+
.withQueryParameter("retriedFromId", {type: "string"}, {required: false})
|
|
53
|
+
.withQueryParameter("startDate", {type: "string"}, {required: false})
|
|
54
|
+
.withQueryParameter("endDate", {type: "string"}, {required: false})
|
|
55
|
+
.withQueryParameter("q", {type: "string"}, {required: false});
|
|
56
|
+
|
|
57
|
+
const filterBodyFields = {
|
|
58
|
+
channel: {type: "string"},
|
|
59
|
+
endDate: {type: "string"},
|
|
60
|
+
errorClass: {type: "string"},
|
|
61
|
+
errorCode: {type: "string"},
|
|
62
|
+
limit: {type: "number"},
|
|
63
|
+
provider: {type: "string"},
|
|
64
|
+
q: {type: "string"},
|
|
65
|
+
retriedFromId: {type: "string"},
|
|
66
|
+
startDate: {type: "string"},
|
|
67
|
+
status: {type: "string"},
|
|
68
|
+
templateId: {type: "string"},
|
|
69
|
+
to: {type: "string"},
|
|
70
|
+
userId: {type: "string"},
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const pathId = (value: string | string[] | undefined): string | undefined => {
|
|
74
|
+
if (Array.isArray(value)) {
|
|
75
|
+
return value[0];
|
|
76
|
+
}
|
|
77
|
+
return value;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const failureRate = (failed: number, total: number): number => {
|
|
81
|
+
if (total === 0) {
|
|
82
|
+
return 0;
|
|
83
|
+
}
|
|
84
|
+
return failed / total;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
export const addCommsDashboardRoutes = (
|
|
88
|
+
app: express.Application,
|
|
89
|
+
options: CommsDashboardRouteOptions
|
|
90
|
+
): void => {
|
|
91
|
+
const basePath = options.basePath ?? "/comms";
|
|
92
|
+
const routeOpenApi = options.openApi ? {openApi: options.openApi as OpenApiMiddleware} : {};
|
|
93
|
+
const {service} = options;
|
|
94
|
+
const isConfigured = (channel: CommsChannel): boolean => service.isChannelConfigured(channel);
|
|
95
|
+
|
|
96
|
+
app.get(
|
|
97
|
+
`${basePath}/messages`,
|
|
98
|
+
[
|
|
99
|
+
authenticateMiddleware(),
|
|
100
|
+
listQueryParameters(
|
|
101
|
+
createOpenApiBuilder(routeOpenApi)
|
|
102
|
+
.withTags(["admin", "comms"])
|
|
103
|
+
.withSummary("List communication delivery attempts")
|
|
104
|
+
)
|
|
105
|
+
.withResponse(200, {
|
|
106
|
+
data: {items: {type: "object"}, type: "array"},
|
|
107
|
+
limit: {type: "number"},
|
|
108
|
+
more: {type: "boolean"},
|
|
109
|
+
page: {type: "number"},
|
|
110
|
+
total: {type: "number"},
|
|
111
|
+
})
|
|
112
|
+
.build(),
|
|
113
|
+
],
|
|
114
|
+
asyncHandler(async (req: express.Request, res: express.Response) => {
|
|
115
|
+
requireAdmin(req);
|
|
116
|
+
const filters = parseCommsListFilters(req.query as Record<string, unknown>);
|
|
117
|
+
const {limit, page, skip} = parseCommsListPagination(req.query as Record<string, unknown>);
|
|
118
|
+
const match = buildCommsMessageMatch(filters);
|
|
119
|
+
const [messages, total] = await Promise.all([
|
|
120
|
+
CommsMessage.find(match).sort("-created").skip(skip).limit(limit),
|
|
121
|
+
CommsMessage.countDocuments(match),
|
|
122
|
+
]);
|
|
123
|
+
return res.json({
|
|
124
|
+
data: messages.map((message) => serializeCommsMessage(message, isConfigured)),
|
|
125
|
+
limit,
|
|
126
|
+
more: skip + limit < total,
|
|
127
|
+
page,
|
|
128
|
+
total,
|
|
129
|
+
});
|
|
130
|
+
})
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
app.post(
|
|
134
|
+
`${basePath}/messages/retryMany`,
|
|
135
|
+
[
|
|
136
|
+
authenticateMiddleware(),
|
|
137
|
+
createOpenApiBuilder(routeOpenApi)
|
|
138
|
+
.withTags(["admin", "comms"])
|
|
139
|
+
.withSummary("Retry matching failed communication messages")
|
|
140
|
+
.withRequestBody(filterBodyFields)
|
|
141
|
+
.withResponse(200, {
|
|
142
|
+
retried: {items: {type: "object"}, type: "array"},
|
|
143
|
+
skipped: {items: {type: "object"}, type: "array"},
|
|
144
|
+
})
|
|
145
|
+
.build(),
|
|
146
|
+
],
|
|
147
|
+
asyncHandler(async (req: express.Request, res: express.Response) => {
|
|
148
|
+
const admin = requireAdmin(req);
|
|
149
|
+
const body = (req.body ?? {}) as Record<string, unknown>;
|
|
150
|
+
const limit = parseRetryManyLimit(body.limit);
|
|
151
|
+
const match = buildCommsMessageMatch(parseCommsListFilters(body));
|
|
152
|
+
const candidates = await CommsMessage.find(match).sort("-created").limit(limit);
|
|
153
|
+
const retried: Record<string, unknown>[] = [];
|
|
154
|
+
const skipped: {id: string; reason: string}[] = [];
|
|
155
|
+
for (const candidate of candidates) {
|
|
156
|
+
try {
|
|
157
|
+
const created = await service.retryMessage({
|
|
158
|
+
messageId: String(candidate._id),
|
|
159
|
+
retriedByUserId: admin.id,
|
|
160
|
+
});
|
|
161
|
+
retried.push(serializeCommsMessage(created, isConfigured));
|
|
162
|
+
} catch (error: unknown) {
|
|
163
|
+
const title = isAPIError(error) ? error.title : "Message could not be retried";
|
|
164
|
+
skipped.push({id: String(candidate._id), reason: title});
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return res.json({retried, skipped});
|
|
168
|
+
})
|
|
169
|
+
);
|
|
170
|
+
|
|
171
|
+
app.get(
|
|
172
|
+
`${basePath}/messages/:id`,
|
|
173
|
+
[
|
|
174
|
+
authenticateMiddleware(),
|
|
175
|
+
createOpenApiBuilder(routeOpenApi)
|
|
176
|
+
.withTags(["admin", "comms"])
|
|
177
|
+
.withSummary("Read one communication delivery attempt")
|
|
178
|
+
.withPathParameter("id", {type: "string"})
|
|
179
|
+
.withResponse(200, {data: {type: "object"}})
|
|
180
|
+
.build(),
|
|
181
|
+
],
|
|
182
|
+
asyncHandler(async (req: express.Request, res: express.Response) => {
|
|
183
|
+
requireAdmin(req);
|
|
184
|
+
const id = pathId(req.params.id);
|
|
185
|
+
if (!id || !mongoose.isValidObjectId(id)) {
|
|
186
|
+
throw new APIError({status: 404, title: "Comms message not found"});
|
|
187
|
+
}
|
|
188
|
+
const message = await CommsMessage.findOneOrNone({_id: id});
|
|
189
|
+
if (!message) {
|
|
190
|
+
throw new APIError({status: 404, title: "Comms message not found"});
|
|
191
|
+
}
|
|
192
|
+
const retries = await CommsMessage.find({retriedFromId: message._id}).sort("-created");
|
|
193
|
+
return res.json({
|
|
194
|
+
data: {
|
|
195
|
+
...serializeCommsMessage(message, isConfigured),
|
|
196
|
+
retries: retries.map((row) => serializeCommsMessage(row, isConfigured)),
|
|
197
|
+
},
|
|
198
|
+
});
|
|
199
|
+
})
|
|
200
|
+
);
|
|
201
|
+
|
|
202
|
+
app.post(
|
|
203
|
+
`${basePath}/messages/:id/retry`,
|
|
204
|
+
[
|
|
205
|
+
authenticateMiddleware(),
|
|
206
|
+
createOpenApiBuilder(routeOpenApi)
|
|
207
|
+
.withTags(["admin", "comms"])
|
|
208
|
+
.withSummary("Retry a failed communication message")
|
|
209
|
+
.withPathParameter("id", {type: "string"})
|
|
210
|
+
.withResponse(200, {data: {type: "object"}})
|
|
211
|
+
.build(),
|
|
212
|
+
],
|
|
213
|
+
asyncHandler(async (req: express.Request, res: express.Response) => {
|
|
214
|
+
const admin = requireAdmin(req);
|
|
215
|
+
const id = pathId(req.params.id);
|
|
216
|
+
if (!id || !mongoose.isValidObjectId(id)) {
|
|
217
|
+
throw new APIError({status: 404, title: "Comms message not found"});
|
|
218
|
+
}
|
|
219
|
+
const created = await service.retryMessage({
|
|
220
|
+
messageId: id,
|
|
221
|
+
retriedByUserId: admin.id,
|
|
222
|
+
});
|
|
223
|
+
return res.json({
|
|
224
|
+
data: serializeCommsMessage(created, isConfigured),
|
|
225
|
+
});
|
|
226
|
+
})
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
app.get(
|
|
230
|
+
`${basePath}/stats`,
|
|
231
|
+
[
|
|
232
|
+
authenticateMiddleware(),
|
|
233
|
+
listQueryParameters(
|
|
234
|
+
createOpenApiBuilder(routeOpenApi)
|
|
235
|
+
.withTags(["admin", "comms"])
|
|
236
|
+
.withSummary("Aggregate communication delivery stats")
|
|
237
|
+
)
|
|
238
|
+
.withResponse(200, {
|
|
239
|
+
buckets: {items: {type: "object"}, type: "array"},
|
|
240
|
+
byProvider: {items: {type: "object"}, type: "array"},
|
|
241
|
+
totals: {type: "object"},
|
|
242
|
+
})
|
|
243
|
+
.build(),
|
|
244
|
+
],
|
|
245
|
+
asyncHandler(async (req: express.Request, res: express.Response) => {
|
|
246
|
+
requireAdmin(req);
|
|
247
|
+
const filters = parseCommsListFilters(req.query as Record<string, unknown>);
|
|
248
|
+
const match = buildCommsMessageMatch(filters, {applyDefaultStatsRange: true});
|
|
249
|
+
const grouped = await CommsMessage.aggregate([
|
|
250
|
+
{$match: match},
|
|
251
|
+
{
|
|
252
|
+
$group: {
|
|
253
|
+
_id: {
|
|
254
|
+
channel: "$channel",
|
|
255
|
+
day: {$dateToString: {date: "$created", format: "%Y-%m-%d"}},
|
|
256
|
+
provider: "$provider",
|
|
257
|
+
status: "$status",
|
|
258
|
+
},
|
|
259
|
+
count: {$sum: 1},
|
|
260
|
+
},
|
|
261
|
+
},
|
|
262
|
+
]);
|
|
263
|
+
|
|
264
|
+
const totals: Record<string, number> = {
|
|
265
|
+
bounced: 0,
|
|
266
|
+
cancelled: 0,
|
|
267
|
+
delivered: 0,
|
|
268
|
+
failed: 0,
|
|
269
|
+
sent: 0,
|
|
270
|
+
total: 0,
|
|
271
|
+
};
|
|
272
|
+
const providerTotals = new Map<
|
|
273
|
+
string,
|
|
274
|
+
{bounced: number; delivered: number; failed: number; sent: number; total: number}
|
|
275
|
+
>();
|
|
276
|
+
const buckets = grouped.map((row: {_id: Record<string, string>; count: number}) => {
|
|
277
|
+
const status = row._id.status;
|
|
278
|
+
const provider = row._id.provider;
|
|
279
|
+
totals.total += row.count;
|
|
280
|
+
if (status in totals) {
|
|
281
|
+
totals[status] = (totals[status] ?? 0) + row.count;
|
|
282
|
+
}
|
|
283
|
+
const existing = providerTotals.get(provider) ?? {
|
|
284
|
+
bounced: 0,
|
|
285
|
+
delivered: 0,
|
|
286
|
+
failed: 0,
|
|
287
|
+
sent: 0,
|
|
288
|
+
total: 0,
|
|
289
|
+
};
|
|
290
|
+
existing.total += row.count;
|
|
291
|
+
if (
|
|
292
|
+
status === "bounced" ||
|
|
293
|
+
status === "delivered" ||
|
|
294
|
+
status === "failed" ||
|
|
295
|
+
status === "sent"
|
|
296
|
+
) {
|
|
297
|
+
existing[status] += row.count;
|
|
298
|
+
}
|
|
299
|
+
providerTotals.set(provider, existing);
|
|
300
|
+
return {
|
|
301
|
+
channel: row._id.channel,
|
|
302
|
+
count: row.count,
|
|
303
|
+
day: row._id.day,
|
|
304
|
+
provider,
|
|
305
|
+
status,
|
|
306
|
+
};
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
const failedTotal = (totals.failed ?? 0) + (totals.bounced ?? 0);
|
|
310
|
+
return res.json({
|
|
311
|
+
buckets: buckets.sort((left, right) => left.day.localeCompare(right.day)),
|
|
312
|
+
byProvider: [...providerTotals.entries()].map(([provider, counts]) => ({
|
|
313
|
+
...counts,
|
|
314
|
+
failureRate: failureRate(counts.failed + counts.bounced, counts.total),
|
|
315
|
+
provider,
|
|
316
|
+
})),
|
|
317
|
+
totals: {
|
|
318
|
+
...totals,
|
|
319
|
+
failureRate: failureRate(failedTotal, totals.total),
|
|
320
|
+
},
|
|
321
|
+
});
|
|
322
|
+
})
|
|
323
|
+
);
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
/** @deprecated Use {@link addCommsDashboardRoutes}. */
|
|
327
|
+
export const addCommsExplorerRoute = addCommsDashboardRoutes;
|