forked from ramfam101/Checkmate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapply-escalation.ps1
More file actions
636 lines (549 loc) · 31.6 KB
/
Copy pathapply-escalation.ps1
File metadata and controls
636 lines (549 loc) · 31.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
# =============================================================
# Checkmate – Escalation Notifications patch
# Run from: C:\Users\tyler\Checkmate
# powershell -ExecutionPolicy Bypass -File apply-escalation.ps1
# =============================================================
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $root
Write-Host "Applying Escalation Notifications patch..." -ForegroundColor Cyan
# ── 1. server/src/types/monitor.ts ───────────────────────────
$monitorTypes = Get-Content "server\src\types\monitor.ts" -Raw
$oldInterface = @'
export interface Monitor {
id: string;
userId: string;
teamId: string;
'@
$newInterface = @'
export interface EscalationRule {
notification: string; // notification ID (DB shape)
delayMinutes: number;
}
export interface Monitor {
id: string;
userId: string;
teamId: string;
'@
if ($monitorTypes -notlike "*EscalationRule*") {
$monitorTypes = $monitorTypes.Replace($oldInterface, $newInterface)
# Add escalationRules field before closing brace of Monitor interface
$monitorTypes = $monitorTypes.Replace(
" createdAt: string;`r`n updatedAt: string;`r`n}",
" escalationRules?: EscalationRule[];`r`n createdAt: string;`r`n updatedAt: string;`r`n}"
)
$monitorTypes = $monitorTypes.Replace(
" createdAt: string;`n updatedAt: string;`n}",
" escalationRules?: EscalationRule[];`n createdAt: string;`n updatedAt: string;`n}"
)
Set-Content "server\src\types\monitor.ts" $monitorTypes -NoNewline
Write-Host " [OK] server/src/types/monitor.ts" -ForegroundColor Green
} else {
Write-Host " [SKIP] server/src/types/monitor.ts already patched" -ForegroundColor Yellow
}
# ── 2. server/src/db/models/Monitor.ts ───────────────────────
$monitorModel = Get-Content "server\src\db\models\Monitor.ts" -Raw
$oldRecentChecks = @'
recentChecks: {
type: [checkSnapshotSchema],
default: [],
},
},
{
timestamps: true,
}
'@
$newRecentChecks = @'
recentChecks: {
type: [checkSnapshotSchema],
default: [],
},
escalationRules: {
type: [
{
notification: { type: Schema.Types.ObjectId, ref: "Notification", required: true },
delayMinutes: { type: Number, required: true, min: 1 },
},
],
default: [],
},
},
{
timestamps: true,
}
'@
if ($monitorModel -notlike "*escalationRules*") {
$monitorModel = $monitorModel.Replace($oldRecentChecks, $newRecentChecks)
Set-Content "server\src\db\models\Monitor.ts" $monitorModel -NoNewline
Write-Host " [OK] server/src/db/models/Monitor.ts" -ForegroundColor Green
} else {
Write-Host " [SKIP] server/src/db/models/Monitor.ts already patched" -ForegroundColor Yellow
}
# ── 3. server/src/repositories/monitors/MongoMonitorsRepository.ts ──
$repo = Get-Content "server\src\repositories\monitors\MongoMonitorsRepository.ts" -Raw
$oldToEntity = " geoCheckInterval: doc.geoCheckInterval ?? 300000,`r`n createdAt: toDateString(doc.createdAt),`r`n updatedAt: toDateString(doc.updatedAt),`r`n };`r`n };`r`n`r`n private toEntityWithChecks"
$newToEntity = " geoCheckInterval: doc.geoCheckInterval ?? 300000,`r`n escalationRules: (doc.escalationRules ?? []).map((r: { notification: unknown; delayMinutes: number }) => ({`r`n notification: toStringId(r.notification),`r`n delayMinutes: r.delayMinutes,`r`n })),`r`n createdAt: toDateString(doc.createdAt),`r`n updatedAt: toDateString(doc.updatedAt),`r`n };`r`n };`r`n`r`n private toEntityWithChecks"
$oldToEntityLF = " geoCheckInterval: doc.geoCheckInterval ?? 300000,`n createdAt: toDateString(doc.createdAt),`n updatedAt: toDateString(doc.updatedAt),`n };`n };`n`n private toEntityWithChecks"
$newToEntityLF = " geoCheckInterval: doc.geoCheckInterval ?? 300000,`n escalationRules: (doc.escalationRules ?? []).map((r: { notification: unknown; delayMinutes: number }) => ({`n notification: toStringId(r.notification),`n delayMinutes: r.delayMinutes,`n })),`n createdAt: toDateString(doc.createdAt),`n updatedAt: toDateString(doc.updatedAt),`n };`n };`n`n private toEntityWithChecks"
if ($repo -notlike "*escalationRules*") {
if ($repo -like "*`r`n*") {
$repo = $repo.Replace($oldToEntity, $newToEntity)
} else {
$repo = $repo.Replace($oldToEntityLF, $newToEntityLF)
}
Set-Content "server\src\repositories\monitors\MongoMonitorsRepository.ts" $repo -NoNewline
Write-Host " [OK] server/src/repositories/monitors/MongoMonitorsRepository.ts" -ForegroundColor Green
} else {
Write-Host " [SKIP] MongoMonitorsRepository.ts already patched" -ForegroundColor Yellow
}
# ── 4. server/src/validation/monitorValidation.ts ────────────
$validation = Get-Content "server\src\validation\monitorValidation.ts" -Raw
$escalationRuleSchema = @'
const escalationRuleSchema = z.object({
notificationId: z.string().min(1),
delayMinutes: z.number().int().min(1),
});
'@
$oldCreate = "export const createMonitorBodyValidation = z.object({"
$newCreate = $escalationRuleSchema + "export const createMonitorBodyValidation = z.object({"
$addEscalationCreate = " geoCheckInterval: z.number().min(300000).optional(),`r`n});"
$addEscalationCreateNew = " geoCheckInterval: z.number().min(300000).optional(),`r`n escalationRules: z.array(escalationRuleSchema).optional(),`r`n});"
$addEscalationCreateLF = " geoCheckInterval: z.number().min(300000).optional(),`n});"
$addEscalationCreateNewLF = " geoCheckInterval: z.number().min(300000).optional(),`n escalationRules: z.array(escalationRuleSchema).optional(),`n});"
if ($validation -notlike "*escalationRuleSchema*") {
$validation = $validation.Replace($oldCreate, $newCreate)
# Add to createMonitorBodyValidation (first occurrence)
$firstIdx = $validation.IndexOf($addEscalationCreate)
if ($firstIdx -ge 0) {
$validation = $validation.Substring(0, $firstIdx) + $addEscalationCreateNew + $validation.Substring($firstIdx + $addEscalationCreate.Length)
} else {
$firstIdx = $validation.IndexOf($addEscalationCreateLF)
if ($firstIdx -ge 0) {
$validation = $validation.Substring(0, $firstIdx) + $addEscalationCreateNewLF + $validation.Substring($firstIdx + $addEscalationCreateLF.Length)
}
}
# Add to editMonitorBodyValidation (second occurrence)
$secondIdx = $validation.IndexOf($addEscalationCreate)
if ($secondIdx -ge 0) {
$validation = $validation.Substring(0, $secondIdx) + $addEscalationCreateNew + $validation.Substring($secondIdx + $addEscalationCreate.Length)
} else {
$secondIdx = $validation.IndexOf($addEscalationCreateLF)
if ($secondIdx -ge 0) {
$validation = $validation.Substring(0, $secondIdx) + $addEscalationCreateNewLF + $validation.Substring($secondIdx + $addEscalationCreateLF.Length)
}
}
Set-Content "server\src\validation\monitorValidation.ts" $validation -NoNewline
Write-Host " [OK] server/src/validation/monitorValidation.ts" -ForegroundColor Green
} else {
Write-Host " [SKIP] server/src/validation/monitorValidation.ts already patched" -ForegroundColor Yellow
}
# ── 5. server/src/controllers/monitorController.ts ───────────
$controller = Get-Content "server\src\controllers\monitorController.ts" -Raw
$oldCreate = @'
createMonitor = async (req: Request, res: Response, next: NextFunction) => {
try {
const validatedBody = createMonitorBodyValidation.parse(req.body);
const userId = requireUserId(req.user?.id);
const teamId = requireTeamId(req.user?.teamId);
const monitor = await this.monitorService.createMonitor(teamId, userId, validatedBody);
'@
$newCreate = @'
createMonitor = async (req: Request, res: Response, next: NextFunction) => {
try {
const validatedBody = createMonitorBodyValidation.parse(req.body);
const userId = requireUserId(req.user?.id);
const teamId = requireTeamId(req.user?.teamId);
// Validate escalation notification IDs belong to this team
if (validatedBody.escalationRules && validatedBody.escalationRules.length > 0) {
const teamNotifications = await this.notificationsService.findNotificationsByTeamId(teamId);
const validIds = teamNotifications.map((n) => n.id);
const invalidIds = validatedBody.escalationRules
.map((r) => r.notificationId)
.filter((id) => !validIds.includes(id));
if (invalidIds.length > 0) {
throw new AppError({
message: `Invalid escalation notification IDs: ${invalidIds.join(", ")}`,
status: 403,
});
}
// Transform frontend shape { notificationId, delayMinutes } -> DB shape { notification, delayMinutes }
(validatedBody as Record<string, unknown>).escalationRules = validatedBody.escalationRules.map((r) => ({
notification: r.notificationId,
delayMinutes: r.delayMinutes,
}));
}
const monitor = await this.monitorService.createMonitor(teamId, userId, validatedBody);
'@
$oldEdit = @'
editMonitor = async (req: Request, res: Response, next: NextFunction) => {
try {
const validatedParams = getMonitorByIdParamValidation.parse(req.params);
const validatedBody = editMonitorBodyValidation.parse(req.body);
const monitorId = validatedParams.monitorId;
const teamId = requireTeamId(req.user?.teamId);
const editedMonitor = await this.monitorService.editMonitor({ teamId, monitorId, body: validatedBody });
'@
$newEdit = @'
editMonitor = async (req: Request, res: Response, next: NextFunction) => {
try {
const validatedParams = getMonitorByIdParamValidation.parse(req.params);
const validatedBody = editMonitorBodyValidation.parse(req.body);
const monitorId = validatedParams.monitorId;
const teamId = requireTeamId(req.user?.teamId);
// Validate escalation notification IDs belong to this team
if (validatedBody.escalationRules && validatedBody.escalationRules.length > 0) {
const teamNotifications = await this.notificationsService.findNotificationsByTeamId(teamId);
const validIds = teamNotifications.map((n) => n.id);
const invalidIds = validatedBody.escalationRules
.map((r) => r.notificationId)
.filter((id) => !validIds.includes(id));
if (invalidIds.length > 0) {
throw new AppError({
message: `Invalid escalation notification IDs: ${invalidIds.join(", ")}`,
status: 403,
});
}
// Transform frontend shape { notificationId, delayMinutes } -> DB shape { notification, delayMinutes }
(validatedBody as Record<string, unknown>).escalationRules = validatedBody.escalationRules.map((r) => ({
notification: r.notificationId,
delayMinutes: r.delayMinutes,
}));
}
const editedMonitor = await this.monitorService.editMonitor({ teamId, monitorId, body: validatedBody });
'@
if ($controller -notlike "*escalationRules*") {
$controller = $controller.Replace($oldCreate, $newCreate)
$controller = $controller.Replace($oldEdit, $newEdit)
Set-Content "server\src\controllers\monitorController.ts" $controller -NoNewline
Write-Host " [OK] server/src/controllers/monitorController.ts" -ForegroundColor Green
} else {
Write-Host " [SKIP] server/src/controllers/monitorController.ts already patched" -ForegroundColor Yellow
}
# ── 6. server/src/service/infrastructure/notificationsService.ts ──
$notifService = Get-Content "server\src\service\infrastructure\notificationsService.ts" -Raw
$oldInterface = @'
export interface INotificationsService {
createNotification: (notificationData: Partial<Notification>, userId: string, teamId: string) => Promise<Notification>;
findById: (id: string, teamId: string) => Promise<Notification>;
findNotificationsByTeamId: (teamId: string) => Promise<Notification[]>;
updateById(id: string, teamId: string, updateData: Partial<Notification>): Promise<Notification>;
deleteById: (id: string, teamId: string) => Promise<Notification>;
handleNotifications: (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse, decision: MonitorActionDecision) => Promise<boolean>;
sendTestNotification: (notification: Partial<Notification>) => Promise<boolean>;
testAllNotifications: (notificationIds: string[]) => Promise<boolean>;
}
'@
$newInterface = @'
export interface INotificationsService {
createNotification: (notificationData: Partial<Notification>, userId: string, teamId: string) => Promise<Notification>;
findById: (id: string, teamId: string) => Promise<Notification>;
findNotificationsByTeamId: (teamId: string) => Promise<Notification[]>;
updateById(id: string, teamId: string, updateData: Partial<Notification>): Promise<Notification>;
deleteById: (id: string, teamId: string) => Promise<Notification>;
handleNotifications: (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse, decision: MonitorActionDecision) => Promise<boolean>;
scheduleEscalationNotifications: (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse, decision: MonitorActionDecision) => void;
cancelEscalationNotifications: (monitorId: string) => void;
sendTestNotification: (notification: Partial<Notification>) => Promise<boolean>;
testAllNotifications: (notificationIds: string[]) => Promise<boolean>;
}
'@
$oldDeleteById = @'
deleteById = async (id: string, teamId: string): Promise<Notification> => {
const deleted = await this.notificationsRepository.deleteById(id, teamId);
await this.monitorsRepository.removeNotificationFromMonitors(id);
return deleted;
};
}
'@
$newDeleteById = @'
deleteById = async (id: string, teamId: string): Promise<Notification> => {
const deleted = await this.notificationsRepository.deleteById(id, teamId);
await this.monitorsRepository.removeNotificationFromMonitors(id);
return deleted;
};
// ── Escalation scheduling ─────────────────────────────────────
// In-memory map: monitorId -> array of NodeJS.Timeout handles
private escalationTimers: Map<string, ReturnType<typeof setTimeout>[]> = new Map();
scheduleEscalationNotifications = (
monitor: Monitor,
monitorStatusResponse: MonitorStatusResponse,
decision: MonitorActionDecision
): void => {
const rules = (monitor as unknown as { escalationRules?: { notification: string; delayMinutes: number }[] }).escalationRules;
if (!rules || rules.length === 0) return;
// Cancel any existing timers for this monitor first
this.cancelEscalationNotifications(monitor.id);
const timers: ReturnType<typeof setTimeout>[] = [];
for (const rule of rules) {
const delayMs = rule.delayMinutes * 60 * 1000;
const timer = setTimeout(async () => {
try {
// Re-fetch monitor to confirm it is still down
const current = await this.monitorsRepository.findById(monitor.id, monitor.teamId);
if (current.status !== "down") return;
const notification = await this.notificationsRepository.findById(rule.notification, monitor.teamId);
if (!notification) return;
const settings = this.settingsService.getSettings();
const clientHost = settings.clientHost || "Host not defined";
const message = this.notificationMessageBuilder.buildMessage(
monitor,
monitorStatusResponse,
decision,
clientHost
);
// Mark as escalation so email provider can prefix subject
if (message?.metadata) {
(message.metadata as Record<string, unknown>).escalation = true;
}
await this.emailProvider.sendMessage!(notification, message!);
this.logger.info({
message: `Escalation email sent for monitor ${monitor.id} after ${rule.delayMinutes} min`,
service: SERVICE_NAME,
method: "scheduleEscalationNotifications",
});
} catch (err) {
this.logger.error({
message: `Escalation send failed for monitor ${monitor.id}: ${err instanceof Error ? err.message : String(err)}`,
service: SERVICE_NAME,
method: "scheduleEscalationNotifications",
});
}
}, delayMs);
timers.push(timer);
}
this.escalationTimers.set(monitor.id, timers);
this.logger.info({
message: `Scheduled ${timers.length} escalation timer(s) for monitor ${monitor.id}`,
service: SERVICE_NAME,
method: "scheduleEscalationNotifications",
});
};
cancelEscalationNotifications = (monitorId: string): void => {
const timers = this.escalationTimers.get(monitorId);
if (timers && timers.length > 0) {
timers.forEach((t) => clearTimeout(t));
this.escalationTimers.delete(monitorId);
this.logger.info({
message: `Cancelled escalation timers for monitor ${monitorId}`,
service: SERVICE_NAME,
method: "cancelEscalationNotifications",
});
}
};
}
'@
if ($notifService -notlike "*scheduleEscalationNotifications*") {
$notifService = $notifService.Replace($oldInterface, $newInterface)
$notifService = $notifService.Replace($oldDeleteById, $newDeleteById)
Set-Content "server\src\service\infrastructure\notificationsService.ts" $notifService -NoNewline
Write-Host " [OK] server/src/service/infrastructure/notificationsService.ts" -ForegroundColor Green
} else {
Write-Host " [SKIP] notificationsService.ts already patched" -ForegroundColor Yellow
}
# ── 7. SuperSimpleQueueHelper.ts – hook escalation into heartbeat ──
$queueHelper = Get-Content "server\src\service\infrastructure\SuperSimpleQueue\SuperSimpleQueueHelper.ts" -Raw
$oldStep6 = @'
// Step 6. Handle notifications (best effort, continue even in event of failure, don't wait)
if (decision.shouldSendNotification) {
this.notificationsService.handleNotifications(statusChangeResult.monitor, status, decision).catch((error: unknown) => {
this.logger.error({
message: `Error sending notifications for job ${statusChangeResult.monitor.id}: ${error instanceof Error ? error.message : "Unknown error"}`,
service: SERVICE_NAME,
method: "getMonitorJob",
stack: error instanceof Error ? error.stack : undefined,
});
});
}
'@
$newStep6 = @'
// Step 6. Handle notifications (best effort, continue even in event of failure, don't wait)
if (decision.shouldSendNotification) {
this.notificationsService.handleNotifications(statusChangeResult.monitor, status, decision).catch((error: unknown) => {
this.logger.error({
message: `Error sending notifications for job ${statusChangeResult.monitor.id}: ${error instanceof Error ? error.message : "Unknown error"}`,
service: SERVICE_NAME,
method: "getMonitorJob",
stack: error instanceof Error ? error.stack : undefined,
});
});
// Step 6b. Handle escalation scheduling
if (statusChangeResult.monitor.status === "down") {
// Monitor just went down – schedule escalation alerts
this.notificationsService.scheduleEscalationNotifications(statusChangeResult.monitor, status, decision);
} else if (
statusChangeResult.monitor.status === "up" &&
(statusChangeResult.prevStatus === "down" || statusChangeResult.prevStatus === "breached")
) {
// Monitor recovered – cancel any pending escalation alerts
this.notificationsService.cancelEscalationNotifications(statusChangeResult.monitor.id);
}
}
'@
if ($queueHelper -notlike "*scheduleEscalationNotifications*") {
$queueHelper = $queueHelper.Replace($oldStep6, $newStep6)
Set-Content "server\src\service\infrastructure\SuperSimpleQueue\SuperSimpleQueueHelper.ts" $queueHelper -NoNewline
Write-Host " [OK] SuperSimpleQueueHelper.ts" -ForegroundColor Green
} else {
Write-Host " [SKIP] SuperSimpleQueueHelper.ts already patched" -ForegroundColor Yellow
}
# ── 8. client/src/Components/EscalationRulesEditor.tsx (new file) ──
$escalationEditor = @'
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import IconButton from "@mui/material/IconButton";
import MenuItem from "@mui/material/MenuItem";
import { Trash2, Plus } from "lucide-react";
import { useTheme } from "@mui/material/styles";
import { Select, TextField, Button } from "@/Components/inputs";
import type { Notification } from "@/Types/Notification";
export interface EscalationRule {
notificationId: string;
delayMinutes: number;
}
interface Props {
value: EscalationRule[];
onChange: (rules: EscalationRule[]) => void;
notifications: Notification[];
}
export const EscalationRulesEditor = ({ value, onChange, notifications }: Props) => {
const theme = useTheme();
const addRule = () => {
onChange([...value, { notificationId: "", delayMinutes: 30 }]);
};
const removeRule = (index: number) => {
onChange(value.filter((_, i) => i !== index));
};
const updateRule = (index: number, patch: Partial<EscalationRule>) => {
onChange(value.map((r, i) => (i === index ? { ...r, ...patch } : r)));
};
return (
<Stack spacing={theme.spacing(3)}>
{value.map((rule, index) => (
<Stack
key={index}
direction="row"
alignItems="flex-end"
spacing={theme.spacing(2)}
>
<Select
value={rule.notificationId}
onChange={(e) => updateRule(index, { notificationId: e.target.value as string })}
fieldLabel={index === 0 ? "Notification" : undefined}
placeholder="Select notification"
sx={{ minWidth: 200, flexGrow: 1 }}
>
{notifications.map((n) => (
<MenuItem key={n.id} value={n.id}>
{n.notificationName}
</MenuItem>
))}
</Select>
<TextField
type="number"
value={rule.delayMinutes}
onChange={(e) =>
updateRule(index, { delayMinutes: Math.max(1, Number(e.target.value)) })
}
fieldLabel={index === 0 ? "Delay (minutes)" : undefined}
sx={{ width: 140 }}
inputProps={{ min: 1 }}
/>
<IconButton
size="small"
onClick={() => removeRule(index)}
aria-label="Remove escalation rule"
sx={{ mb: 0.5 }}
>
<Trash2 size={16} />
</IconButton>
</Stack>
))}
<Stack direction="row">
<Button
variant="outlined"
onClick={addRule}
startIcon={<Plus size={16} />}
>
Add escalation rule
</Button>
</Stack>
{value.length === 0 && (
<Typography variant="body2" color="text.secondary">
No escalation rules configured. Add a rule to send follow-up alerts if the monitor stays down.
</Typography>
)}
</Stack>
);
};
'@
if (-not (Test-Path "client\src\Components\EscalationRulesEditor.tsx")) {
Set-Content "client\src\Components\EscalationRulesEditor.tsx" $escalationEditor -NoNewline
Write-Host " [OK] client/src/Components/EscalationRulesEditor.tsx (created)" -ForegroundColor Green
} else {
Write-Host " [SKIP] EscalationRulesEditor.tsx already exists" -ForegroundColor Yellow
}
# ── 9. Inject EscalationRulesEditor into CreateMonitor/index.tsx ──
$createMonitor = Get-Content "client\src\Pages\CreateMonitor\index.tsx" -Raw
$oldImports = 'import type { MonitorFormData } from "@/Validation/monitor";'
$newImports = @'
import type { MonitorFormData } from "@/Validation/monitor";
import { EscalationRulesEditor } from "@/Components/EscalationRulesEditor";
'@
$oldSaveButton = @'
<Stack
direction="row"
justifyContent="flex-end"
>
<Button
loading={isSubmitting}
type="submit"
variant="contained"
color="primary"
>
{t("common.buttons.save")}
</Button>
</Stack>
'@
$newSaveButton = @'
<ConfigBox
title="Escalation Alerts"
subtitle="Send follow-up email alerts if the monitor stays down for a specified duration."
rightContent={
<Controller
name="escalationRules"
control={control}
render={({ field }) => (
<EscalationRulesEditor
value={field.value ?? []}
onChange={field.onChange}
notifications={notifications ?? []}
/>
)}
/>
}
/>
<Stack
direction="row"
justifyContent="flex-end"
>
<Button
loading={isSubmitting}
type="submit"
variant="contained"
color="primary"
>
{t("common.buttons.save")}
</Button>
</Stack>
'@
if ($createMonitor -notlike "*EscalationRulesEditor*") {
$createMonitor = $createMonitor.Replace($oldImports, $newImports)
$createMonitor = $createMonitor.Replace($oldSaveButton, $newSaveButton)
Set-Content "client\src\Pages\CreateMonitor\index.tsx" $createMonitor -NoNewline
Write-Host " [OK] client/src/Pages/CreateMonitor/index.tsx" -ForegroundColor Green
} else {
Write-Host " [SKIP] CreateMonitor/index.tsx already patched" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "All done! Restart your server and client:" -ForegroundColor Cyan
Write-Host " cd server && npm run dev" -ForegroundColor White
Write-Host " cd client && npm run dev" -ForegroundColor White