feat: activity audit log written from all resource routes

Add the activity_log table, a best-effort recordActivity() service and a
GET /api/activity feed, and write entries on create/update/delete of
patients, notes, appointments, prescriptions and tasks. The Activity page
now shows the real audit trail (actor, action, patient context, time);
the fabricated signing hashes / approval badges are gone — that vision
stays deferred.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Khalid Abdi
2026-06-07 19:46:22 +03:00
parent 25254dd4c1
commit 75940313a4
16 changed files with 2436 additions and 142 deletions
+16
View File
@@ -0,0 +1,16 @@
CREATE TABLE "activity_log" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"organization_id" text NOT NULL,
"actor_id" text,
"actor_name" text NOT NULL,
"action" text NOT NULL,
"entity_type" text NOT NULL,
"entity_id" text,
"patient_name" text,
"patient_file_number" text,
"created_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "activity_log" ADD CONSTRAINT "activity_log_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "activity_log" ADD CONSTRAINT "activity_log_actor_id_user_id_fk" FOREIGN KEY ("actor_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "activity_org_created_idx" ON "activity_log" USING btree ("organization_id","created_at");
File diff suppressed because it is too large Load Diff
+7
View File
@@ -36,6 +36,13 @@
"when": 1780850364853,
"tag": "0004_dizzy_scarlet_spider",
"breakpoints": true
},
{
"idx": 5,
"version": "7",
"when": 1780850717058,
"tag": "0005_true_gwen_stacy",
"breakpoints": true
}
]
}
+29
View File
@@ -0,0 +1,29 @@
import { index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import type { ActivityEntityType } from "../../types/activity.js";
import { organization, user } from "./auth.js";
// One row per record change, scoped to a clinic (organization). Written
// best-effort from the resource routes (patients / notes / appointments /
// prescriptions / tasks). `actorName` is denormalized so the feed renders even
// after the user is removed (FK is set null).
export const activityLog = pgTable(
"activity_log",
{
id: uuid("id").primaryKey().defaultRandom(),
organizationId: text("organization_id")
.notNull()
.references(() => organization.id, { onDelete: "cascade" }),
actorId: text("actor_id").references(() => user.id, {
onDelete: "set null",
}),
actorName: text("actor_name").notNull(),
action: text("action").notNull(),
entityType: text("entity_type").$type<ActivityEntityType>().notNull(),
entityId: text("entity_id"),
patientName: text("patient_name"),
patientFileNumber: text("patient_file_number"),
createdAt: timestamp("created_at").defaultNow().notNull(),
},
(t) => [index("activity_org_created_idx").on(t.organizationId, t.createdAt)],
);
+1
View File
@@ -4,3 +4,4 @@ export * from "./notes.js";
export * from "./appointments.js";
export * from "./prescriptions.js";
export * from "./tasks.js";
export * from "./activity.js";
+3
View File
@@ -5,6 +5,7 @@ import express from "express";
import { auth } from "./auth.js";
import { env } from "./env.js";
import { errorHandler, notFound } from "./middleware/error.js";
import { activityRouter } from "./routes/activity.js";
import { appointmentsRouter } from "./routes/appointments.js";
import { notesRouter } from "./routes/notes.js";
import { patientsRouter } from "./routes/patients.js";
@@ -51,6 +52,7 @@ app.use("/api/notes", notesRouter);
app.use("/api/appointments", appointmentsRouter);
app.use("/api/prescriptions", prescriptionsRouter);
app.use("/api/tasks", tasksRouter);
app.use("/api/activity", activityRouter);
app.use(notFound);
app.use(errorHandler);
@@ -63,4 +65,5 @@ app.listen(env.PORT, () => {
console.log(` • appts: /api/appointments`);
console.log(` • rx: /api/prescriptions`);
console.log(` • tasks: /api/tasks`);
console.log(` • activity: /api/activity`);
});
+17
View File
@@ -0,0 +1,17 @@
import { Router } from "express";
import { requireAuth, requireOrg } from "../middleware/auth.js";
import * as service from "../services/activity.js";
export const activityRouter = Router();
// The audit feed is readable by any clinic member.
activityRouter.use(requireAuth, requireOrg);
activityRouter.get("/", async (req, res, next) => {
try {
res.json(await service.listActivity(req.organizationId!));
} catch (err) {
next(err);
}
});
+26
View File
@@ -7,6 +7,7 @@ import {
requireOrg,
requirePermission,
} from "../middleware/auth.js";
import { recordActivity } from "../services/activity.js";
import * as service from "../services/appointments.js";
export const appointmentsRouter = Router();
@@ -37,6 +38,15 @@ appointmentsRouter.post(
req.user!.id,
input,
);
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: `Scheduled appointment for ${created.name} on ${created.date}`,
entityType: "appointment",
entityId: created.id,
patientName: created.name,
patientFileNumber: created.fileNumber || null,
});
res.status(201).json(created);
} catch (err) {
next(err);
@@ -56,6 +66,15 @@ appointmentsRouter.put(
input,
);
if (!updated) throw new HttpError(404, "Appointment not found.");
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: `Updated appointment for ${updated.name}`,
entityType: "appointment",
entityId: updated.id,
patientName: updated.name,
patientFileNumber: updated.fileNumber || null,
});
res.json(updated);
} catch (err) {
next(err);
@@ -73,6 +92,13 @@ appointmentsRouter.delete(
req.params.id as string,
);
if (!ok) throw new HttpError(404, "Appointment not found.");
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: "Deleted appointment",
entityType: "appointment",
entityId: req.params.id as string,
});
res.status(204).end();
} catch (err) {
next(err);
+22
View File
@@ -3,6 +3,7 @@ import { Router } from "express";
import { HttpError } from "../lib/http-error.js";
import { noteInputSchema } from "../lib/note-validation.js";
import { requireAuth, requireOrg } from "../middleware/auth.js";
import { recordActivity } from "../services/activity.js";
import * as service from "../services/notes.js";
export const notesRouter = Router();
@@ -27,6 +28,13 @@ notesRouter.post("/", async (req, res, next) => {
req.user!.id,
input,
);
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: `Created note — ${created.title}`,
entityType: "note",
entityId: created.id,
});
res.status(201).json(created);
} catch (err) {
next(err);
@@ -57,6 +65,13 @@ notesRouter.put("/:id", async (req, res, next) => {
input,
);
if (!updated) throw new HttpError(404, "Note not found.");
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: `Updated note — ${updated.title}`,
entityType: "note",
entityId: updated.id,
});
res.json(updated);
} catch (err) {
next(err);
@@ -71,6 +86,13 @@ notesRouter.delete("/:id", async (req, res, next) => {
req.params.id as string,
);
if (!ok) throw new HttpError(404, "Note not found.");
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: "Deleted note",
entityType: "note",
entityId: req.params.id as string,
});
res.status(204).end();
} catch (err) {
next(err);
+27
View File
@@ -7,6 +7,7 @@ import {
requireOrg,
requirePermission,
} from "../middleware/auth.js";
import { recordActivity } from "../services/activity.js";
import * as service from "../services/patients.js";
export const patientsRouter = Router();
@@ -54,6 +55,15 @@ patientsRouter.post(
req.user!.id,
input,
);
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: `Created patient ${created.name}`,
entityType: "patient",
entityId: created.fileNumber,
patientName: created.name,
patientFileNumber: created.fileNumber,
});
res.status(201).json(created);
} catch (err) {
next(err);
@@ -73,6 +83,15 @@ patientsRouter.put(
input,
);
if (!updated) throw new HttpError(404, "Patient not found.");
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: `Updated patient ${updated.name}`,
entityType: "patient",
entityId: updated.fileNumber,
patientName: updated.name,
patientFileNumber: updated.fileNumber,
});
res.json(updated);
} catch (err) {
next(err);
@@ -90,6 +109,14 @@ patientsRouter.delete(
req.params.fileNumber as string,
);
if (!ok) throw new HttpError(404, "Patient not found.");
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: `Deleted patient #${req.params.fileNumber}`,
entityType: "patient",
entityId: req.params.fileNumber as string,
patientFileNumber: req.params.fileNumber as string,
});
res.status(204).end();
} catch (err) {
next(err);
+26
View File
@@ -7,6 +7,7 @@ import {
requireOrg,
requirePermission,
} from "../middleware/auth.js";
import { recordActivity } from "../services/activity.js";
import * as service from "../services/prescriptions.js";
export const prescriptionsRouter = Router();
@@ -38,6 +39,15 @@ prescriptionsRouter.post(
req.user!.id,
input,
);
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: `Prescribed ${created.medication} for ${created.name}`,
entityType: "prescription",
entityId: created.id,
patientName: created.name,
patientFileNumber: created.fileNumber || null,
});
res.status(201).json(created);
} catch (err) {
next(err);
@@ -58,6 +68,15 @@ prescriptionsRouter.put(
input,
);
if (!updated) throw new HttpError(404, "Prescription not found.");
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: `Updated prescription — ${updated.medication}`,
entityType: "prescription",
entityId: updated.id,
patientName: updated.name,
patientFileNumber: updated.fileNumber || null,
});
res.json(updated);
} catch (err) {
next(err);
@@ -75,6 +94,13 @@ prescriptionsRouter.delete(
req.params.id as string,
);
if (!ok) throw new HttpError(404, "Prescription not found.");
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: "Deleted prescription",
entityType: "prescription",
entityId: req.params.id as string,
});
res.status(204).end();
} catch (err) {
next(err);
+28
View File
@@ -7,6 +7,7 @@ import {
requireOrg,
requirePermission,
} from "../middleware/auth.js";
import { recordActivity } from "../services/activity.js";
import * as service from "../services/tasks.js";
export const tasksRouter = Router();
@@ -36,6 +37,13 @@ tasksRouter.post(
req.user!.id,
input,
);
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: `Created task — ${created.title}`,
entityType: "task",
entityId: created.id,
});
res.status(201).json(created);
} catch (err) {
next(err);
@@ -55,6 +63,19 @@ tasksRouter.patch(
patch,
);
if (!updated) throw new HttpError(404, "Task not found.");
const action =
patch.done === undefined
? `Updated task — ${updated.title}`
: patch.done
? `Completed task — ${updated.title}`
: `Reopened task — ${updated.title}`;
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action,
entityType: "task",
entityId: updated.id,
});
res.json(updated);
} catch (err) {
next(err);
@@ -72,6 +93,13 @@ tasksRouter.delete(
req.params.id as string,
);
if (!ok) throw new HttpError(404, "Task not found.");
await recordActivity({
orgId: req.organizationId!,
actor: { id: req.user!.id, name: req.user!.name },
action: "Deleted task",
entityType: "task",
entityId: req.params.id as string,
});
res.status(204).end();
} catch (err) {
next(err);
+68
View File
@@ -0,0 +1,68 @@
import { desc, eq } from "drizzle-orm";
import { db } from "../db/index.js";
import { activityLog } from "../db/schema/activity.js";
import type { ActivityEntityType, ActivityEntry } from "../types/activity.js";
type ActivityRow = typeof activityLog.$inferSelect;
// Up to two-letter initials from a display name (e.g. "Dr. Ada Okafor" -> "AO").
export function initialsOf(name: string): string {
const parts = name.trim().split(/\s+/).filter(Boolean);
if (parts.length === 0) return "?";
if (parts.length === 1) return parts[0]!.slice(0, 2).toUpperCase();
return (parts[0]![0]! + parts.at(-1)![0]!).toUpperCase();
}
function toEntry(row: ActivityRow): ActivityEntry {
return {
id: row.id,
actorName: row.actorName,
actorInitials: initialsOf(row.actorName),
action: row.action,
entityType: row.entityType,
entityId: row.entityId,
patientName: row.patientName,
patientFileNumber: row.patientFileNumber,
createdAt: row.createdAt.toISOString(),
};
}
// Best-effort: an audit entry must never fail the originating request.
export async function recordActivity(params: {
orgId: string;
actor: { id?: string | null; name?: string | null };
action: string;
entityType: ActivityEntityType;
entityId?: string | null;
patientName?: string | null;
patientFileNumber?: string | null;
}): Promise<void> {
try {
await db.insert(activityLog).values({
organizationId: params.orgId,
actorId: params.actor.id ?? null,
actorName: params.actor.name?.trim() || "Someone",
action: params.action,
entityType: params.entityType,
entityId: params.entityId ?? null,
patientName: params.patientName ?? null,
patientFileNumber: params.patientFileNumber ?? null,
});
} catch (err) {
console.error("Failed to record activity:", err);
}
}
export async function listActivity(
orgId: string,
limit = 100,
): Promise<ActivityEntry[]> {
const rows = await db
.select()
.from(activityLog)
.where(eq(activityLog.organizationId, orgId))
.orderBy(desc(activityLog.createdAt))
.limit(limit);
return rows.map(toEntry);
}
+21
View File
@@ -0,0 +1,21 @@
// The canonical activity-log entry returned by the API. A plain, tamper-evident
// audit trail of record changes within a clinic. (The blockchain-style signing /
// patient-approval flow from the product vision is separate and not built yet.)
export type ActivityEntityType =
| "patient"
| "note"
| "appointment"
| "prescription"
| "task";
export type ActivityEntry = {
id: string;
actorName: string;
actorInitials: string;
action: string;
entityType: ActivityEntityType;
entityId: string | null;
patientName: string | null;
patientFileNumber: string | null;
createdAt: string;
};
+118 -142
View File
@@ -1,109 +1,59 @@
"use client";
import {
Clock,
Activity as ActivityIcon,
CalendarClock,
CalendarDays,
FileText,
Hash,
ListChecks,
type LucideIcon,
NotebookPen,
Pill,
ShieldCheck,
Stethoscope,
TriangleAlert,
} from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import {
type ActivityEntityType,
type ActivityEntry,
listActivity,
} from "@/lib/activity";
import { cn } from "@/lib/utils";
// All entries here are mock/placeholder data — there is no signing/ledger
// backend yet. They illustrate temetro's patient-owned, signed-change vision:
// every record change is signed (blockchain-style) and awaits patient approval.
// A plain, tamper-evident audit log of record changes in the active clinic. (The
// blockchain-style signing / patient-approval flow from the product vision is
// separate and not built yet.)
type ActivityStatus = "signed" | "pending";
type ActivityEntry = {
id: string;
actor: string;
initials: string;
action: string;
patient: string;
fileNumber: string;
time: string;
hash: string;
status: ActivityStatus;
icon: LucideIcon;
const entityIcon: Record<ActivityEntityType, LucideIcon> = {
patient: Stethoscope,
note: NotebookPen,
appointment: CalendarClock,
prescription: Pill,
task: ListChecks,
};
const entries: ActivityEntry[] = [
{
id: "1",
actor: "Dr. Okafor",
initials: "DO",
action: "Updated vitals",
patient: "Amina Yusuf",
fileNumber: "10293",
time: "Today, 10:24",
hash: "0x9f3a…c21",
status: "pending",
icon: Stethoscope,
},
{
id: "2",
actor: "Dr. Okafor",
initials: "DO",
action: "Added prescription — Lisinopril 10mg",
patient: "Amina Yusuf",
fileNumber: "10293",
time: "Today, 10:21",
hash: "0x4b8e…7df",
status: "pending",
icon: Pill,
},
{
id: "3",
actor: "Dr. Stein",
initials: "DS",
action: "Created note — Lab review",
patient: "Leila Haddad",
fileNumber: "10342",
time: "Today, 09:48",
hash: "0x1c07…a90",
status: "signed",
icon: NotebookPen,
},
{
id: "4",
actor: "Dr. Stein",
initials: "DS",
action: "Edited allergies — added Penicillin",
patient: "Daniel Mensah",
fileNumber: "10311",
time: "Yesterday, 16:05",
hash: "0xab12…44e",
status: "signed",
icon: TriangleAlert,
},
{
id: "5",
actor: "Dr. Okafor",
initials: "DO",
action: "Imported prior records",
patient: "Carlos Rivera",
fileNumber: "10358",
time: "Yesterday, 14:30",
hash: "0x77f0…b3c",
status: "signed",
icon: FileText,
},
];
const kpis = [
{ label: "Pending approvals", value: "2", icon: Clock },
{ label: "Signed today", value: "1", icon: ShieldCheck },
{ label: "Changes this week", value: "37", icon: Hash },
];
// ISO timestamp -> "Today, 10:24" / "Yesterday, 16:05" / "Jun 3, 14:30".
function formatTime(iso: string): string {
const d = new Date(iso);
const time = d.toLocaleTimeString("en-US", {
hour: "2-digit",
minute: "2-digit",
hour12: false,
});
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);
const sameDay = (a: Date, b: Date) =>
a.getFullYear() === b.getFullYear() &&
a.getMonth() === b.getMonth() &&
a.getDate() === b.getDate();
if (sameDay(d, today)) return `Today, ${time}`;
if (sameDay(d, yesterday)) return `Yesterday, ${time}`;
return `${d.toLocaleDateString("en-US", { month: "short", day: "numeric" })}, ${time}`;
}
function Kpi({
label,
@@ -130,13 +80,46 @@ function Kpi({
}
export function ActivityView() {
const [entries, setEntries] = useState<ActivityEntry[]>([]);
useEffect(() => {
let active = true;
listActivity()
.then((data) => {
if (active) setEntries(data);
})
.catch(() => {
/* api-client redirects on 401; otherwise leave the feed empty */
});
return () => {
active = false;
};
}, []);
const kpis = useMemo(() => {
const now = new Date();
const startOfToday = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
);
const startOfWeek = new Date(startOfToday);
startOfWeek.setDate(startOfToday.getDate() - now.getDay());
const today = entries.filter((e) => new Date(e.createdAt) >= startOfToday);
const week = entries.filter((e) => new Date(e.createdAt) >= startOfWeek);
return [
{ label: "Changes today", value: String(today.length), icon: ActivityIcon },
{ label: "This week", value: String(week.length), icon: CalendarDays },
{ label: "Total recorded", value: String(entries.length), icon: Hash },
];
}, [entries]);
return (
<div className="mx-auto flex w-full max-w-3xl flex-col gap-10 px-6 py-10">
<div>
<h1 className="font-semibold text-2xl tracking-tight">Activity</h1>
<p className="text-muted-foreground text-sm">
A signed, tamper-evident log of record changes awaiting patient
approval. Sample data.
An audit log of record changes across the clinic.
</p>
</div>
@@ -146,66 +129,59 @@ export function ActivityView() {
))}
</div>
<ol className="flex flex-col">
{entries.map((entry, i) => {
const Icon = entry.icon;
const isLast = i === entries.length - 1;
return (
<li className="flex gap-4" key={entry.id}>
<div className="flex flex-col items-center">
<div className="flex size-9 shrink-0 items-center justify-center rounded-full border bg-card text-muted-foreground">
<Icon className="size-4" />
{entries.length === 0 ? (
<div className="rounded-2xl border border-dashed bg-card/20 px-4 py-12 text-center text-muted-foreground text-sm">
No activity yet. Changes to patients, notes, appointments,
prescriptions and tasks will appear here.
</div>
) : (
<ol className="flex flex-col">
{entries.map((entry, i) => {
const Icon = entityIcon[entry.entityType] ?? FileText;
const isLast = i === entries.length - 1;
const context = [
entry.actorName,
entry.patientName &&
`${entry.patientName}${
entry.patientFileNumber ? ` (#${entry.patientFileNumber})` : ""
}`,
]
.filter(Boolean)
.join(" · ");
return (
<li className="flex gap-4" key={entry.id}>
<div className="flex flex-col items-center">
<div className="flex size-9 shrink-0 items-center justify-center rounded-full border bg-card text-muted-foreground">
<Icon className="size-4" />
</div>
{!isLast && <div className="mt-1 w-px flex-1 bg-border" />}
</div>
{!isLast && <div className="mt-1 w-px flex-1 bg-border" />}
</div>
<div className={cn("flex-1", isLast ? "pb-0" : "pb-6")}>
<div className="flex items-start justify-between gap-2">
<div className={cn("flex-1", isLast ? "pb-0" : "pb-6")}>
<span className="font-medium text-foreground text-sm">
{entry.action}
</span>
{entry.status === "signed" ? (
<Badge
className="shrink-0 border-success/40 text-success"
variant="outline"
>
<ShieldCheck className="size-3" />
Signed
</Badge>
) : (
<Badge
className="shrink-0 border-warning/40 text-warning"
variant="outline"
>
<Clock className="size-3" />
Pending approval
</Badge>
)}
</div>
<div className="mt-1 flex items-center gap-2">
<Avatar className="size-5">
<AvatarFallback className="text-[10px]">
{entry.initials}
</AvatarFallback>
</Avatar>
<span className="text-muted-foreground text-xs">
{entry.actor} · {entry.patient} (#{entry.fileNumber})
</span>
</div>
<div className="mt-1 flex items-center gap-2">
<Avatar className="size-5">
<AvatarFallback className="text-[10px]">
{entry.actorInitials}
</AvatarFallback>
</Avatar>
<span className="text-muted-foreground text-xs">
{context}
</span>
</div>
<div className="mt-2 flex flex-wrap items-center gap-2 text-xs">
<span className="text-muted-foreground">{entry.time}</span>
<span className="inline-flex items-center gap-1 rounded-md border bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground">
<Hash className="size-3" />
{entry.hash}
</span>
<div className="mt-2 text-muted-foreground text-xs">
{formatTime(entry.createdAt)}
</div>
</div>
</div>
</li>
);
})}
</ol>
</li>
);
})}
</ol>
)}
</div>
);
}
+27
View File
@@ -0,0 +1,27 @@
import { apiFetch } from "@/lib/api-client";
// An audit-log entry. Mirrors the backend `src/types/activity.ts`. A plain,
// tamper-evident trail of record changes in the active clinic. (The signing /
// patient-approval vision is separate and not built yet.)
export type ActivityEntityType =
| "patient"
| "note"
| "appointment"
| "prescription"
| "task";
export type ActivityEntry = {
id: string;
actorName: string;
actorInitials: string;
action: string;
entityType: ActivityEntityType;
entityId: string | null;
patientName: string | null;
patientFileNumber: string | null;
createdAt: string;
};
export function listActivity(): Promise<ActivityEntry[]> {
return apiFetch<ActivityEntry[]>("/api/activity");
}