feat: org-scoped appointments backend, wire appointments page

Add the appointments table, validation, service and CRUD routes
(/api/appointments, RBAC-gated) and the matching frontend data module.
The appointments page now loads and persists real data; KPIs are computed
from it and the schedule/calendar anchor to the real current date.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Khalid Abdi
2026-06-07 19:33:37 +03:00
parent 128ce36df2
commit dec04ec506
14 changed files with 2004 additions and 142 deletions
+19
View File
@@ -0,0 +1,19 @@
CREATE TABLE "appointments" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"organization_id" text NOT NULL,
"patient_file_number" text DEFAULT '' NOT NULL,
"patient_name" text NOT NULL,
"patient_initials" text NOT NULL,
"date" text NOT NULL,
"time" text NOT NULL,
"type" text NOT NULL,
"provider" text NOT NULL,
"status" text NOT NULL,
"created_by" text,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "appointments" ADD CONSTRAINT "appointments_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "appointments" ADD CONSTRAINT "appointments_created_by_user_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "appointments_org_date_idx" ON "appointments" USING btree ("organization_id","date");
File diff suppressed because it is too large Load Diff
+7
View File
@@ -15,6 +15,13 @@
"when": 1780591375930,
"tag": "0001_boring_puck",
"breakpoints": true
},
{
"idx": 2,
"version": "7",
"when": 1780849813505,
"tag": "0002_fluffy_longshot",
"breakpoints": true
}
]
}
+35
View File
@@ -0,0 +1,35 @@
import { index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import type { AppointmentStatus } from "../../types/appointment.js";
import { organization, user } from "./auth.js";
// One row per scheduled visit, scoped to a clinic (organization). Patient
// identity is denormalized (name/initials/file number) so the schedule renders
// without joining; `date`/`time` are stored as plain strings to match the UI's
// local-date model exactly (no timezone drift).
export const appointments = pgTable(
"appointments",
{
id: uuid("id").primaryKey().defaultRandom(),
organizationId: text("organization_id")
.notNull()
.references(() => organization.id, { onDelete: "cascade" }),
patientFileNumber: text("patient_file_number").notNull().default(""),
patientName: text("patient_name").notNull(),
patientInitials: text("patient_initials").notNull(),
date: text("date").notNull(), // YYYY-MM-DD
time: text("time").notNull(), // HH:mm
type: text("type").notNull(),
provider: text("provider").notNull(),
status: text("status").$type<AppointmentStatus>().notNull(),
createdBy: text("created_by").references(() => user.id, {
onDelete: "set null",
}),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.defaultNow()
.$onUpdate(() => new Date())
.notNull(),
},
(t) => [index("appointments_org_date_idx").on(t.organizationId, t.date)],
);
+1
View File
@@ -1,3 +1,4 @@
export * from "./auth.js";
export * from "./patients.js";
export * from "./notes.js";
export * from "./appointments.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 { appointmentsRouter } from "./routes/appointments.js";
import { notesRouter } from "./routes/notes.js";
import { patientsRouter } from "./routes/patients.js";
@@ -45,6 +46,7 @@ app.get("/health", (_req, res) => {
app.use("/api/patients", patientsRouter);
app.use("/api/notes", notesRouter);
app.use("/api/appointments", appointmentsRouter);
app.use(notFound);
app.use(errorHandler);
@@ -54,4 +56,5 @@ app.listen(env.PORT, () => {
console.log(` • auth: /api/auth/* (frontend origin: ${env.FRONTEND_URL})`);
console.log(` • patients: /api/patients`);
console.log(` • notes: /api/notes`);
console.log(` • appts: /api/appointments`);
});
+20
View File
@@ -0,0 +1,20 @@
import { z } from "zod";
// Payload accepted by POST/PUT /api/appointments. Mirrors the frontend
// `NewAppointment` shape; `status` defaults to "confirmed" on create.
export const appointmentInputSchema = z.object({
fileNumber: z.string().trim().default(""),
name: z.string().trim().min(1, "Patient name is required.").max(200),
initials: z.string().trim().min(1).max(4),
date: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, "Date must be YYYY-MM-DD."),
time: z.string().regex(/^\d{2}:\d{2}$/, "Time must be HH:mm."),
type: z.string().trim().min(1, "Type is required.").max(120),
provider: z.string().trim().min(1, "Provider is required.").max(200),
status: z
.enum(["confirmed", "checked-in", "completed", "cancelled"])
.default("confirmed"),
});
export type AppointmentInput = z.infer<typeof appointmentInputSchema>;
+81
View File
@@ -0,0 +1,81 @@
import { Router } from "express";
import { appointmentInputSchema } from "../lib/appointment-validation.js";
import { HttpError } from "../lib/http-error.js";
import {
requireAuth,
requireOrg,
requirePermission,
} from "../middleware/auth.js";
import * as service from "../services/appointments.js";
export const appointmentsRouter = Router();
// Appointments are clinic-wide records, gated by the caller's role like patients.
appointmentsRouter.use(requireAuth, requireOrg);
appointmentsRouter.get(
"/",
requirePermission({ appointment: ["read"] }),
async (req, res, next) => {
try {
res.json(await service.listAppointments(req.organizationId!));
} catch (err) {
next(err);
}
},
);
appointmentsRouter.post(
"/",
requirePermission({ appointment: ["write"] }),
async (req, res, next) => {
try {
const input = appointmentInputSchema.parse(req.body);
const created = await service.createAppointment(
req.organizationId!,
req.user!.id,
input,
);
res.status(201).json(created);
} catch (err) {
next(err);
}
},
);
appointmentsRouter.put(
"/:id",
requirePermission({ appointment: ["write"] }),
async (req, res, next) => {
try {
const input = appointmentInputSchema.parse(req.body);
const updated = await service.updateAppointment(
req.organizationId!,
req.params.id as string,
input,
);
if (!updated) throw new HttpError(404, "Appointment not found.");
res.json(updated);
} catch (err) {
next(err);
}
},
);
appointmentsRouter.delete(
"/:id",
requirePermission({ appointment: ["delete"] }),
async (req, res, next) => {
try {
const ok = await service.deleteAppointment(
req.organizationId!,
req.params.id as string,
);
if (!ok) throw new HttpError(404, "Appointment not found.");
res.status(204).end();
} catch (err) {
next(err);
}
},
);
+94
View File
@@ -0,0 +1,94 @@
import { and, asc, eq } from "drizzle-orm";
import { db } from "../db/index.js";
import { appointments } from "../db/schema/appointments.js";
import type { AppointmentInput } from "../lib/appointment-validation.js";
import type { Appointment } from "../types/appointment.js";
type AppointmentRow = typeof appointments.$inferSelect;
// Postgres throws on a malformed uuid; treat non-uuid ids as "not found".
const UUID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function toAppointment(row: AppointmentRow): Appointment {
return {
id: row.id,
fileNumber: row.patientFileNumber,
name: row.patientName,
initials: row.patientInitials,
date: row.date,
time: row.time,
type: row.type,
provider: row.provider,
status: row.status,
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
}
function columns(orgId: string, input: AppointmentInput, createdBy?: string) {
return {
organizationId: orgId,
patientFileNumber: input.fileNumber,
patientName: input.name,
patientInitials: input.initials,
date: input.date,
time: input.time,
type: input.type,
provider: input.provider,
status: input.status,
...(createdBy ? { createdBy } : {}),
};
}
export async function listAppointments(orgId: string): Promise<Appointment[]> {
const rows = await db
.select()
.from(appointments)
.where(eq(appointments.organizationId, orgId))
.orderBy(asc(appointments.date), asc(appointments.time));
return rows.map(toAppointment);
}
export async function createAppointment(
orgId: string,
userId: string,
input: AppointmentInput,
): Promise<Appointment> {
const [row] = await db
.insert(appointments)
.values(columns(orgId, input, userId))
.returning();
return toAppointment(row!);
}
export async function updateAppointment(
orgId: string,
id: string,
input: AppointmentInput,
): Promise<Appointment | null> {
if (!UUID_RE.test(id)) return null;
const [row] = await db
.update(appointments)
.set(columns(orgId, input))
.where(
and(eq(appointments.id, id), eq(appointments.organizationId, orgId)),
)
.returning();
return row ? toAppointment(row) : null;
}
export async function deleteAppointment(
orgId: string,
id: string,
): Promise<boolean> {
if (!UUID_RE.test(id)) return false;
const deleted = await db
.delete(appointments)
.where(
and(eq(appointments.id, id), eq(appointments.organizationId, orgId)),
)
.returning({ id: appointments.id });
return deleted.length > 0;
}
+22
View File
@@ -0,0 +1,22 @@
// The canonical Appointment shape returned by the API. Mirrors the frontend
// `lib/appointments.ts` Appointment type. Patient fields are denormalized for
// display; `fileNumber` links back to a patient record when set.
export type AppointmentStatus =
| "confirmed"
| "checked-in"
| "completed"
| "cancelled";
export type Appointment = {
id: string;
fileNumber: string;
name: string;
initials: string;
date: string; // ISO YYYY-MM-DD
time: string; // HH:mm
type: string;
provider: string;
status: AppointmentStatus;
createdAt: string;
updatedAt: string;
};
@@ -58,8 +58,8 @@ function Field({ label, children }: { label: string; children: ReactNode }) {
}
// Compact "New appointment" dialog. The patient is chosen via a quick search by
// name or file number; the rest is the slot. Appointments are mock-only, so a
// confirmed entry is handed back to the page via onAdd.
// name or file number; the rest is the slot. The new entry is handed back to the
// page via onAdd, which persists it through the appointments API.
export function AddAppointmentDialog({
open,
onOpenChange,
@@ -9,7 +9,7 @@ import {
Stethoscope,
Users,
} from "lucide-react";
import { type ReactNode, useMemo, useState } from "react";
import { type ReactNode, useEffect, useMemo, useState } from "react";
import {
AddAppointmentDialog,
@@ -21,25 +21,34 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
type Appointment,
createAppointment,
listAppointments,
} from "@/lib/appointments";
import { notify } from "@/lib/toast";
// All figures here are mock/placeholder data — there is no scheduling backend.
// They illustrate the Appointments & Schedule layout.
export type { Appointment } from "@/lib/appointments";
// Anchor "today" to a fixed date so the mock copy ("Wednesday, June 5") lines up
// across the page, the calendar dialog, and the add dialog. ISO YYYY-MM-DD.
export const TODAY = "2026-06-05";
// Local-date ISO key (avoids UTC drift from toISOString).
const keyOf = (d: Date) =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(
d.getDate(),
).padStart(2, "0")}`;
type ApptStatus = "confirmed" | "checked-in" | "completed" | "cancelled";
// "Today" is the real current date — appointments are persisted, not seeded, so
// the schedule and calendar anchor to now. ISO YYYY-MM-DD.
export const TODAY = keyOf(new Date());
export type Appointment = {
date: string; // ISO YYYY-MM-DD
time: string;
name: string;
initials: string;
type: string;
provider: string;
status: ApptStatus;
};
// Sunday-anchored week window [start, end] as ISO keys, for the "This week" KPI.
function weekRange(): { start: string; end: string } {
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay());
const end = new Date(start.getFullYear(), start.getMonth(), start.getDate() + 6);
return { start: keyOf(start), end: keyOf(end) };
}
type ApptStatus = Appointment["status"];
const statusVariant: Record<
ApptStatus,
@@ -58,116 +67,6 @@ const statusLabel: Record<ApptStatus, string> = {
cancelled: "Cancelled",
};
const kpis = [
{ label: "Today", value: "12", icon: CalendarClock },
{ label: "This week", value: "146", icon: Users },
{ label: "Avg. visit", value: "22 min", icon: Clock },
{ label: "Utilization", value: "87%", icon: Stethoscope },
];
// Mock schedule spread across June 2026 so the month calendar looks populated.
const seed: Appointment[] = [
{
date: TODAY,
time: "09:00",
name: "Amina Yusuf",
initials: "AY",
type: "Follow-up",
provider: "Dr. Okafor",
status: "completed",
},
{
date: TODAY,
time: "09:30",
name: "Daniel Mensah",
initials: "DM",
type: "New patient",
provider: "Dr. Okafor",
status: "checked-in",
},
{
date: TODAY,
time: "10:15",
name: "Leila Haddad",
initials: "LH",
type: "Lab review",
provider: "Dr. Stein",
status: "confirmed",
},
{
date: TODAY,
time: "11:00",
name: "Carlos Rivera",
initials: "CR",
type: "Consultation",
provider: "Dr. Okafor",
status: "confirmed",
},
{
date: TODAY,
time: "13:30",
name: "Priya Nair",
initials: "PN",
type: "Follow-up",
provider: "Dr. Stein",
status: "cancelled",
},
{
date: TODAY,
time: "14:45",
name: "Tom Becker",
initials: "TB",
type: "Vaccination",
provider: "Dr. Okafor",
status: "confirmed",
},
{
date: "2026-06-06",
time: "08:45",
name: "Grace Lin",
initials: "GL",
type: "Follow-up",
provider: "Dr. Stein",
status: "confirmed",
},
{
date: "2026-06-06",
time: "10:00",
name: "Omar Farouk",
initials: "OF",
type: "New patient",
provider: "Dr. Okafor",
status: "confirmed",
},
{
date: "2026-06-09",
time: "11:30",
name: "Sofia Marin",
initials: "SM",
type: "Consultation",
provider: "Dr. Stein",
status: "confirmed",
},
{
date: "2026-06-12",
time: "15:00",
name: "Henry Adeyemi",
initials: "HA",
type: "Lab review",
provider: "Dr. Okafor",
status: "confirmed",
},
{
date: "2026-06-18",
time: "09:15",
name: "Nadia Petrova",
initials: "NP",
type: "Follow-up",
provider: "Dr. Stein",
status: "confirmed",
},
];
// "2026-06-05" -> "Wednesday, June 5"
function formatDayKey(key: string): string {
return new Date(`${key}T00:00:00`).toLocaleDateString("en-US", {
@@ -231,7 +130,7 @@ export function ScheduleList({ items }: { items: Appointment[] }) {
return (
<div className="divide-y divide-border overflow-hidden rounded-2xl border bg-card/30">
{items.map((appt) => (
<ApptRow appt={appt} key={appt.time + appt.name} />
<ApptRow appt={appt} key={appt.id} />
))}
</div>
);
@@ -262,25 +161,61 @@ function Section({
export function AppointmentsView() {
const [addOpen, setAddOpen] = useState(false);
const [calendarOpen, setCalendarOpen] = useState(false);
const [appointments, setAppointments] = useState<Appointment[]>(seed);
const [appointments, setAppointments] = useState<Appointment[]>([]);
const [query, setQuery] = useState("");
// Insert a new (mock) appointment at the date/time chosen in the dialog.
const addAppointment = (appt: NewAppointment) => {
setAppointments((prev) => [
...prev,
{
date: appt.date,
time: appt.time,
useEffect(() => {
let active = true;
listAppointments()
.then((data) => {
if (active) setAppointments(data);
})
.catch(() => {
/* api-client redirects on 401; otherwise leave the list empty */
});
return () => {
active = false;
};
}, []);
// Persist a new appointment, then add the saved record to the list.
const addAppointment = async (appt: NewAppointment) => {
try {
const created = await createAppointment({
fileNumber: appt.fileNumber,
name: appt.name,
initials: appt.initials,
date: appt.date,
time: appt.time,
type: appt.type,
provider: appt.provider,
status: "confirmed" as const,
},
]);
});
setAppointments((prev) => [...prev, created]);
} catch {
notify.error("Couldn't add appointment", "Please try again.");
}
};
const kpis = useMemo(() => {
const { start, end } = weekRange();
const today = appointments.filter((a) => a.date === TODAY);
const week = appointments.filter((a) => a.date >= start && a.date <= end);
return [
{ label: "Today", value: String(today.length), icon: CalendarClock },
{ label: "This week", value: String(week.length), icon: Users },
{
label: "Checked in",
value: String(today.filter((a) => a.status === "checked-in").length),
icon: Stethoscope,
},
{
label: "Completed",
value: String(today.filter((a) => a.status === "completed").length),
icon: Clock,
},
];
}, [appointments]);
const todayItems = useMemo(
() => appointments.filter((a) => a.date === TODAY).sort(byTime),
[appointments],
@@ -324,7 +259,7 @@ export function AppointmentsView() {
Appointments &amp; Schedule
</h1>
<p className="text-muted-foreground text-sm">
Today&apos;s clinic schedule and what&apos;s coming up. Sample data.
Today&apos;s clinic schedule and what&apos;s coming up.
</p>
</div>
<div className="flex items-center gap-2">
@@ -47,7 +47,7 @@ const chipClass: Record<Appointment["status"], string> = {
// A Google-Calendar-style month grid in a dialog: a 6×7 grid of day cells with
// color-coded event chips; navigate months and click a day to list its
// appointments. Mock-only — there's no per-date scheduling backend.
// appointments. Reads the appointments passed down from the page.
export function CalendarDialog({
open,
onOpenChange,
+61
View File
@@ -0,0 +1,61 @@
import { apiFetch } from "@/lib/api-client";
// An appointment. Mirrors the backend `src/types/appointment.ts`. Scoped to the
// active clinic. `fileNumber` links back to a patient record when set.
export type AppointmentStatus =
| "confirmed"
| "checked-in"
| "completed"
| "cancelled";
export type Appointment = {
id: string;
fileNumber: string;
name: string;
initials: string;
date: string; // ISO YYYY-MM-DD
time: string; // HH:mm
type: string;
provider: string;
status: AppointmentStatus;
createdAt: string;
updatedAt: string;
};
export type AppointmentInput = {
fileNumber: string;
name: string;
initials: string;
date: string;
time: string;
type: string;
provider: string;
status?: AppointmentStatus;
};
export function listAppointments(): Promise<Appointment[]> {
return apiFetch<Appointment[]>("/api/appointments");
}
export function createAppointment(
input: AppointmentInput,
): Promise<Appointment> {
return apiFetch<Appointment>("/api/appointments", {
method: "POST",
body: JSON.stringify(input),
});
}
export function updateAppointment(
id: string,
input: AppointmentInput,
): Promise<Appointment> {
return apiFetch<Appointment>(`/api/appointments/${id}`, {
method: "PUT",
body: JSON.stringify(input),
});
}
export function deleteAppointment(id: string): Promise<void> {
return apiFetch<void>(`/api/appointments/${id}`, { method: "DELETE" });
}