Racks, notes and to-do, OS support, suggested dependencies, Nginx Proxy Manager and Home Assistant

- Racks page and a network diagram (UniFi tree with servers, printable)
- Notes on servers and devices; To do list shown in Coming up and My work
- Agents report the operating system (Linux 7, Windows 6); end-of-life badge and alert
- Suggested dependencies from where a service is reached
- Nginx Proxy Manager integration: proxy hosts page, certificate and host alerts, suggested checks
- Home Assistant integration: watch chosen entities, history chart, limit and unavailable alerts
- TimeChart gets a "value" scale that fits negatives; docs updated

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-20 21:47:56 +02:00
1 parent 68b41b5586
commit 18ceed62e8
77 files changed
+20432 -35

No files matched your search

+38
View File
@@ -8,6 +8,7 @@ import { recordAudit } from "../services/audit.js";
import { invalidateAlertsCache } from "../services/alerts.js";
import { dependentsOf, impactOf, loadGraph, nodeKey, nodeTypes, wouldLoop } from "../services/dependencies.js";
import { getSettings } from "../services/settingsStore.js";
import { loadDependencySuggestions, loadDismissedDependencies, saveDismissedDependencies } from "../services/dependencySuggestions.js";
import { getSourceStatus } from "../services/integrationHealthMonitor.js";
import { serverStatus, type MapStatus } from "../services/topology.js";
import { asyncHandler } from "../utils/asyncHandler.js";
@@ -44,6 +45,43 @@ dependenciesRouter.get("/", asyncHandler(async (_req, res) => {
});
}));
// Dependencies worth writing, from what the app already knows (an integration reached at a server's own address). Everyone signed in can see them; operators
// add or dismiss them, as they would any dependency.
dependenciesRouter.get("/suggestions", asyncHandler(async (_req, res) => {
res.json(await loadDependencySuggestions());
}));
const keysSchema = z.object({ keys: z.array(z.string().min(1).max(100)).min(1).max(200) });
dependenciesRouter.post("/suggestions/add", requireRole("operator"), asyncHandler(async (req, res) => {
const parsed = keysSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body" });
const { suggestions } = await loadDependencySuggestions();
const wanted = new Set(parsed.data.keys);
const added: { id: number; from: string; to: string }[] = [];
for (const s of suggestions.filter((x) => wanted.has(x.key))) {
const [row] = await db.insert(dependencies).values({ fromType: "integration", fromId: s.from.id, toType: "server", toId: s.to.id }).returning();
await recordAudit({ actor: req.currentUser!, category: "dependency", action: "create", targetType: "dependency", targetId: row.id, detail: { from: s.from.name, to: s.to.name, fromKey: `integration:${s.from.id}`, toKey: `server:${s.to.id}`, suggested: true } });
added.push({ id: row.id, from: s.from.name, to: s.to.name });
}
if (added.length > 0) invalidateAlertsCache();
res.json({ added, ...(await loadDependencySuggestions()) });
}));
dependenciesRouter.post("/suggestions/dismiss", requireRole("operator"), asyncHandler(async (req, res) => {
const parsed = keysSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body" });
const dismissed = await loadDismissedDependencies();
for (const k of parsed.data.keys) dismissed.add(k);
await saveDismissedDependencies(dismissed);
res.json(await loadDependencySuggestions());
}));
dependenciesRouter.post("/suggestions/restore", requireRole("operator"), asyncHandler(async (_req, res) => {
await saveDismissedDependencies(new Set());
res.json(await loadDependencySuggestions());
}));
// What a thing would take with it, and what it needs itself: for the maintenance and update pages, which say so before it is done.
dependenciesRouter.get("/impact", asyncHandler(async (req, res) => {
const type = nodeTypes.find((t) => t === req.query.type);
+137
View File
@@ -0,0 +1,137 @@
import { Router } from "express";
import { and, eq, gte } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { haEntities, haReadings, haWatched, integrations } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { invalidateAlertsCache } from "../services/alerts.js";
import { createHomeAssistantAdapter } from "../integrations/homeassistant/adapter.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { haProblems, haSyncStatuses, isHaFresh, READING_KEEP_DAYS, syncAllHomeAssistants, syncHomeAssistant } from "../services/homeAssistantSync.js";
import { bucketPoints } from "../services/serverMetrics.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const homeAssistantRouter = Router();
homeAssistantRouter.use(requireAuth);
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
const DAY_MS = 86_400_000;
async function haIntegration(id: number) {
const [row] = await db.select({ id: integrations.id, name: integrations.name, type: integrations.type }).from(integrations).where(eq(integrations.id, id)).limit(1);
return row && row.type === "homeassistant" ? row : null;
}
/** What is watched in each Home Assistant, with what the last read said; everyone signed in can see it. */
homeAssistantRouter.get("/", asyncHandler(async (_req, res) => {
const [intRows, watched, entities, statuses] = await Promise.all([
db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled }).from(integrations).where(eq(integrations.type, "homeassistant")),
db.select().from(haWatched),
db.select().from(haEntities),
haSyncStatuses(),
]);
const now = new Date();
res.json({
integrations: intRows.map((i) => {
const status = statuses[i.id] ?? null;
const mine = watched.filter((w) => w.integrationId === i.id).sort((a, b) => (a.name ?? a.entityId).localeCompare(b.name ?? b.entityId));
const rows = new Map(entities.filter((e) => e.integrationId === i.id).map((e) => [e.entityId, e]));
return {
id: i.id,
name: i.name,
enabled: i.enabled,
status,
fresh: isHaFresh(status ?? undefined, now.getTime()),
watched: mine.map((w) => {
const e = rows.get(w.entityId);
return {
entityId: w.entityId,
name: w.name,
above: w.above,
below: w.below,
entity: e ? { friendlyName: e.friendlyName, state: e.state, value: e.value, unit: e.unit, deviceClass: e.deviceClass, lastChanged: e.lastChanged, unavailableSince: e.unavailableSince, updatedAt: e.updatedAt } : null,
};
}),
problems: isHaFresh(status ?? undefined, now.getTime()) ? haProblems(i.id, i.name, mine, rows, now) : [],
};
}),
});
}));
// Every entity Home Assistant has, to pick from: read live, so only those who may change what is watched see them.
homeAssistantRouter.get("/:id/entities", requireRole("operator"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id) || !(await haIntegration(id))) return res.status(404).json({ error: "not_found" });
const loaded = await loadIntegrationConfig(id);
if (!loaded) return res.status(404).json({ error: "not_found" });
const q = typeof req.query.q === "string" ? req.query.q.trim().toLowerCase() : "";
try {
const all = await createHomeAssistantAdapter(loaded.config as never).listEntities();
const watched = new Set((await db.select({ entityId: haWatched.entityId }).from(haWatched).where(eq(haWatched.integrationId, id))).map((w) => w.entityId));
const found = all.filter((e) => !q || e.entityId.toLowerCase().includes(q) || e.name.toLowerCase().includes(q)).sort((a, b) => a.entityId.localeCompare(b.entityId)).slice(0, 60);
res.json({ total: all.length, entities: found.map((e) => ({ entityId: e.entityId, name: e.name, state: e.state, unit: e.unit, deviceClass: e.deviceClass, watched: watched.has(e.entityId) })) });
} catch (err) {
res.status(502).json({ error: "unreachable", message: err instanceof Error ? err.message : String(err) });
}
}));
const watchSchema = z.object({
entityId: z.string().regex(/^[a-z_]+\.[A-Za-z0-9_]+$/, "Not an entity id, like sensor.ups_battery").max(120),
name: z.string().trim().max(80).nullable().optional(),
above: z.number().finite().nullable().optional(),
below: z.number().finite().nullable().optional(),
});
// Watch an entity, or change what is said about one already watched (its name, its limits).
homeAssistantRouter.put("/:id/watched", requireRole("operator"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
const parsed = watchSchema.safeParse(req.body);
if (!Number.isInteger(id) || !(await haIntegration(id))) return res.status(404).json({ error: "not_found" });
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "Not an entity." });
const d = parsed.data;
if (d.above != null && d.below != null && d.below >= d.above) return res.status(400).json({ error: "invalid_limits", message: "The lower limit has to be below the upper one." });
const [count] = [(await db.select({ id: haWatched.id }).from(haWatched).where(eq(haWatched.integrationId, id))).length];
const existing = (await db.select().from(haWatched).where(and(eq(haWatched.integrationId, id), eq(haWatched.entityId, d.entityId))).limit(1))[0];
if (!existing && count >= 60) return res.status(400).json({ error: "too_many", message: "That is as many as can be watched on one Home Assistant (60)." });
const values = { name: d.name?.trim() || null, above: d.above ?? null, below: d.below ?? null };
if (existing) await db.update(haWatched).set(values).where(eq(haWatched.id, existing.id));
else await db.insert(haWatched).values({ integrationId: id, entityId: d.entityId, ...values, createdAt: new Date().toISOString() });
await recordAudit({ actor: req.currentUser!, category: "integration", action: existing ? "ha_watch_changed" : "ha_watch", targetType: "integration", targetId: id, detail: { entity: d.entityId, above: values.above, below: values.below } });
const status = await syncHomeAssistant(id);
invalidateAlertsCache();
res.json({ ok: true, status });
}));
homeAssistantRouter.delete("/:id/watched/:entityId", requireRole("operator"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
const entityId = req.params.entityId;
if (!Number.isInteger(id) || !(await haIntegration(id))) return res.status(404).json({ error: "not_found" });
const [row] = await db.select().from(haWatched).where(and(eq(haWatched.integrationId, id), eq(haWatched.entityId, entityId))).limit(1);
if (!row) return res.status(404).json({ error: "not_found" });
await db.delete(haWatched).where(eq(haWatched.id, row.id));
await db.delete(haEntities).where(and(eq(haEntities.integrationId, id), eq(haEntities.entityId, entityId)));
await db.delete(haReadings).where(and(eq(haReadings.integrationId, id), eq(haReadings.entityId, entityId)));
await recordAudit({ actor: req.currentUser!, category: "integration", action: "ha_unwatch", targetType: "integration", targetId: id, detail: { entity: entityId } });
invalidateAlertsCache();
res.status(204).end();
}));
// The chart of a watched number: up to the 35 days that are kept.
homeAssistantRouter.get("/:id/history", asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
const entity = typeof req.query.entity === "string" ? req.query.entity : "";
if (!Number.isInteger(id) || !entity) return res.status(400).json({ error: "invalid_query" });
const requested = Number(req.query.days);
const days = Number.isFinite(requested) ? Math.min(READING_KEEP_DAYS, Math.max(1, Math.round(requested))) : 7;
const to = Date.now();
const from = to - days * DAY_MS;
const rows = await db.select({ at: haReadings.at, value: haReadings.value }).from(haReadings).where(and(eq(haReadings.integrationId, id), eq(haReadings.entityId, entity), gte(haReadings.at, new Date(from).toISOString()))).orderBy(haReadings.at);
res.json({ days, points: bucketPoints(rows.map((r) => ({ t: Date.parse(r.at), v: r.value })), from, to, 96) });
}));
homeAssistantRouter.post("/sync", requireRole("operator"), asyncHandler(async (_req, res) => {
const statuses = await syncAllHomeAssistants();
invalidateAlertsCache();
res.json({ statuses });
}));
+4
View File
@@ -26,6 +26,7 @@ import { createOsTicketAdapter } from "../integrations/osticket/adapter.js";
import { attachMatchedServers, summarizeMonitors, toMatchableServers } from "../services/uptimeKumaMatch.js";
import { getSourceStatus } from "../services/integrationHealthMonitor.js";
import { removeIntegrationData, syncUnifiIntegration } from "../services/unifiSync.js";
import { removeHomeAssistantData, syncHomeAssistant } from "../services/homeAssistantSync.js";
import { invalidateAlertsCache } from "../services/alerts.js";
import { asyncHandler } from "../utils/asyncHandler.js";
import { ID_PATTERNS, isValidId } from "../utils/pathSegment.js";
@@ -125,6 +126,7 @@ integrationsRouter.post("/", requireRole("admin"), asyncHandler(async (req, res)
// A new UniFi controller is read at once, so its equipment is there when the person opens the page (not waited for: a slow controller must not slow this).
if (type === "unifi") void syncUnifiIntegration(created.id).then(() => invalidateAlertsCache());
if (type === "homeassistant") void syncHomeAssistant(created.id).then(() => invalidateAlertsCache());
res.status(201).json({
integration: {
@@ -226,6 +228,7 @@ integrationsRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req,
});
if (updated.type === "unifi" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncUnifiIntegration(updated.id).then(() => invalidateAlertsCache());
if (updated.type === "homeassistant" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncHomeAssistant(updated.id).then(() => invalidateAlertsCache());
res.json({
integration: {
@@ -303,6 +306,7 @@ integrationsRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req,
.returning({ id: servers.id });
if (existing.type === "unifi") await removeIntegrationData(id);
if (existing.type === "homeassistant") await removeHomeAssistantData(id);
await db.delete(integrations).where(eq(integrations.id, id));
if (existing.credentialId) {
await db.delete(integrationCredentials).where(eq(integrationCredentials.id, existing.credentialId));
+7
View File
@@ -6,6 +6,7 @@ import { assetKinds, assets, servers } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { isRealDate, lifecycleReport } from "../services/inventory.js";
import { buildRacks } from "../services/racks.js";
import { blanksToFill, differences, hardwareOf } from "../services/inventoryAutofill.js";
import { getSettings, updateSettings } from "../services/settingsStore.js";
import { asyncHandler } from "../utils/asyncHandler.js";
@@ -88,6 +89,12 @@ inventoryRouter.get("/", asyncHandler(async (_req, res) => {
}));
// What ages out when, for planning what to replace: this year, the next few, later, and what has no date.
// The racks, drawn from the hardware that says which unit it sits in and where. Everyone signed in can see it, as they can the hardware.
inventoryRouter.get("/racks", asyncHandler(async (_req, res) => {
const rows = await db.select().from(assets);
res.json({ racks: buildRacks(rows) });
}));
inventoryRouter.get("/lifecycle", asyncHandler(async (req, res) => {
const asked = Number(req.query.years);
const years = Number.isInteger(asked) && asked >= 1 && asked <= 10 ? asked : 5;
+47
View File
@@ -0,0 +1,47 @@
import { Router } from "express";
import { db } from "../db/client.js";
import { servers } from "../db/schema.js";
import { requireAuth } from "../auth/middleware.js";
import { npmIntegrationIds, npmProblems, readNpm } from "../services/npmReader.js";
import { matchServerForTarget } from "../services/uptimeKumaMatch.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const npmRouter = Router();
npmRouter.use(requireAuth);
/**
* What Nginx Proxy Manager proxies: each host with where it forwards to (and which server that is, when the address is one the app knows), its certificate and how it is
* doing. Everyone signed in can see it (it is the same picture the alerts and suggested checks draw on). \`?refresh=1\` asks NPM again instead of using the last minute.
*/
npmRouter.get("/", asyncHandler(async (req, res) => {
const force = req.query.refresh === "1";
const rows = await db.select({ id: servers.id, name: servers.name, hostname: servers.hostname, ipAddresses: servers.ipAddresses }).from(servers);
const matchable = rows.map((s) => {
let ips: string[] = [];
try {
const v = s.ipAddresses ? JSON.parse(s.ipAddresses) : [];
ips = Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
} catch {
// none
}
return { id: s.id, name: s.name, hostname: s.hostname, ips };
});
const out = [];
for (const i of await npmIntegrationIds()) {
const read = await readNpm(i.id, force);
out.push({
id: i.id,
name: i.name,
readAt: read.at,
error: read.error,
version: read.snapshot?.version ?? null,
hosts: (read.snapshot?.hosts ?? []).map((h) => {
const server = matchServerForTarget(h.forwardHost, matchable);
return { ...h, server: server ? { id: server.id, name: server.name } : null };
}),
certificates: read.snapshot?.certificates ?? [],
problems: read.snapshot ? npmProblems(i.id, i.name, read.snapshot, new Date()) : [],
});
}
res.json({ integrations: out });
}));
+3 -1
View File
@@ -24,6 +24,7 @@ import { buildServerSummary } from "../services/serverSummary.js";
import { activeSubjects } from "../services/maintenance.js";
import { invalidateAlertsCache } from "../services/alerts.js";
import { getSettings, updateSettings } from "../services/settingsStore.js";
import { osSummary } from "../services/osLifecycle.js";
export const serversRouter = Router();
@@ -397,7 +398,8 @@ serversRouter.get("/:id/detail", asyncHandler(async (req, res) => {
children: [...links2.entries()].filter(([, l]) => l.parentId === id).map(([childId, l]) => ({ id: childId, name: nameOf.get(childId) ?? "", auto: l.auto })).sort((a, b) => a.name.localeCompare(b.name)),
};
res.json({ server: { ...serverOut, tags: parseTags(rawTags), pendingUpdates: parsePendingUpdates(rawUpdates), hostHealth: markIgnoredServices(parseHostHealth(rawHealth), parseThresholds(rawThresholds)?.ignoreServices), thresholds: parseThresholds(rawThresholds) }, diagnostics: describeDiagnostics(parseDiagnostics(rawDiagnostics), { osType: server.osType, lastSeenAt: server.lastSeenAt, agentVersion: server.agentVersion, latest: latestAgentVersions() }), thresholdDefaults: (await getSettings()).healthChecks, ipAddresses, hardware, dnsMatches, links, relations, agentLatest: latestAgentVersions() });
const settings = await getSettings();
res.json({ os: osSummary(server, new Date(), settings.healthChecks.osSupportWarnDays), server: { ...serverOut, tags: parseTags(rawTags), pendingUpdates: parsePendingUpdates(rawUpdates), hostHealth: markIgnoredServices(parseHostHealth(rawHealth), parseThresholds(rawThresholds)?.ignoreServices), thresholds: parseThresholds(rawThresholds) }, diagnostics: describeDiagnostics(parseDiagnostics(rawDiagnostics), { osType: server.osType, lastSeenAt: server.lastSeenAt, agentVersion: server.agentVersion, latest: latestAgentVersions() }), thresholdDefaults: (await getSettings()).healthChecks, ipAddresses, hardware, dnsMatches, links, relations, agentLatest: latestAgentVersions() });
}));
const tagsSchema = z.object({ tags: z.array(z.string().max(100)).max(50) });
+1 -1
View File
@@ -144,7 +144,7 @@ const updateSchema = z.object({
.partial()
.optional(),
healthChecks: z
.object({ serverOfflineMinutes: z.number().int().min(15).max(10080), diskUsagePercent: z.number().int().min(50).max(99), domainWarnDays: z.number().int().min(1).max(365), diskForecastDays: z.number().int().min(0).max(90), backupStaleHours: z.number().int().min(0).max(2160), restoreTestDays: z.number().int().min(0).max(730), newPortAlerts: z.boolean(), flapRaises: z.number().int().min(0).max(20), deviceOfflineMinutes: z.number().int().min(5).max(1440) })
.object({ serverOfflineMinutes: z.number().int().min(15).max(10080), diskUsagePercent: z.number().int().min(50).max(99), domainWarnDays: z.number().int().min(1).max(365), diskForecastDays: z.number().int().min(0).max(90), backupStaleHours: z.number().int().min(0).max(2160), restoreTestDays: z.number().int().min(0).max(730), newPortAlerts: z.boolean(), flapRaises: z.number().int().min(0).max(20), deviceOfflineMinutes: z.number().int().min(5).max(1440), osSupportWarnDays: z.number().int().min(0).max(365) })
.partial()
.optional(),
quietHours: z
+92
View File
@@ -0,0 +1,92 @@
import { Router } from "express";
import { z } from "zod";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { assignableUsers } from "../services/alertAcks.js";
import { createTodo, getNote, listTodos, removeTodo, setNote, TARGET_TYPES, TodoError, updateTodo } from "../services/todos.js";
import { asyncHandler } from "../utils/asyncHandler.js";
/** The to-do list: everyone signed in reads it; operators write. */
export const todosRouter = Router();
todosRouter.use(requireAuth);
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
const label = (u: { name: string | null; email: string | null; oidcSub: string }) => u.name ?? u.email ?? u.oidcSub;
const fields = {
title: z.string(),
detail: z.string().nullable().optional(),
dueDate: z.string().nullable().optional(),
assigneeId: z.number().int().positive().nullable().optional(),
targetType: z.enum(TARGET_TYPES).nullable().optional(),
targetId: z.number().int().positive().nullable().optional(),
};
todosRouter.get("/", asyncHandler(async (_req, res) => {
res.json({ todos: await listTodos(), people: await assignableUsers() });
}));
todosRouter.post("/", requireRole("operator"), asyncHandler(async (req, res) => {
const parsed = z.object(fields).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Say what is to be done." });
try {
const actor = req.currentUser!;
const item = await createTodo(parsed.data, label(actor));
await recordAudit({ actor, category: "todo", action: "create", targetType: "todo", targetId: item.id, detail: { title: item.title, dueDate: item.dueDate, assignee: item.assignee?.name ?? null, about: item.target?.name ?? null } });
res.status(201).json({ todo: item });
} catch (err) {
if (err instanceof TodoError) return res.status(err.status).json({ error: err.code, message: err.message });
throw err;
}
}));
todosRouter.patch("/:id", requireRole("operator"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
const parsed = z.object({ ...fields, title: z.string().optional(), done: z.boolean().optional() }).safeParse(req.body);
if (!Number.isInteger(id) || !parsed.success) return res.status(400).json({ error: "invalid_body" });
try {
const actor = req.currentUser!;
const result = await updateTodo(id, parsed.data, label(actor));
if (!result) return res.status(404).json({ error: "not_found" });
const action = parsed.data.done === true && !result.before.doneAt ? "done" : parsed.data.done === false && result.before.doneAt ? "reopen" : "update";
await recordAudit({ actor, category: "todo", action, targetType: "todo", targetId: id, detail: { title: result.after.title } });
res.json({ todo: result.after });
} catch (err) {
if (err instanceof TodoError) return res.status(err.status).json({ error: err.code, message: err.message });
throw err;
}
}));
todosRouter.delete("/:id", requireRole("operator"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const removed = await removeTodo(id);
if (!removed) return res.status(404).json({ error: "not_found" });
await recordAudit({ actor: req.currentUser!, category: "todo", action: "delete", targetType: "todo", targetId: id, detail: { title: removed.title } });
res.status(204).end();
}));
/** The notes on servers and devices: everyone reads; operators write. */
export const notesRouter = Router();
notesRouter.use(requireAuth);
notesRouter.get("/", asyncHandler(async (req, res) => {
const type = z.enum(TARGET_TYPES).safeParse(req.query.targetType);
const id = idOf(String(req.query.targetId ?? ""));
if (!type.success || !Number.isInteger(id)) return res.status(400).json({ error: "invalid_target" });
res.json({ note: await getNote(type.data, id) });
}));
notesRouter.put("/", requireRole("operator"), asyncHandler(async (req, res) => {
const parsed = z.object({ targetType: z.enum(TARGET_TYPES), targetId: z.number().int().positive(), body: z.string() }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body" });
try {
const actor = req.currentUser!;
const note = await setNote(parsed.data.targetType, parsed.data.targetId, parsed.data.body, label(actor));
await recordAudit({ actor, category: "note", action: note ? "save" : "delete", targetType: parsed.data.targetType, targetId: parsed.data.targetId });
res.json({ note });
} catch (err) {
if (err instanceof TodoError) return res.status(err.status).json({ error: err.code, message: err.message });
throw err;
}
}));