Patient administration system tutorial
Appointments, a waiting list, and reminders that never leave a silent patient behind. You finish with a small working app, and the way to the full project.
What you'll build
A small patient administration system: a clinic calendar, a waiting list, reminders that end with a person picking up the phone, and a link by which a patient confirms or cancels. It is administrative: it holds no diagnosis and no result. About 90 minutes.
It leads to the open-source Patient Administration System, whose site is patient-administration-system.github.io. That project is built for the NHS in Wales, is tested, and is not yet in use with real patients.
For learning only. Use invented people, never a real person's details.
Before you start
You need Node 26, pnpm, and a little Svelte: the Svelte tutorial is enough. Make the app, then add Lily:
npx sv create pas --template minimal --types ts --no-add-ons --install pnpm
cd pas
pnpm add @lilydesignsystem/svelte-headless @lilydesignsystem/themes \
@lilydesignsystem/svelte-calendar @lilydesignsystem/svelte-kanban-board \
@lilydesignsystem/svelte-locale-translations
pnpm add -D vitest @types/node Each code block below is one whole file, under the path shown above it. Copy it as it is, replacing the file if the new app already has one.
Step 1: Choose a theme
src/routes/+layout.svelte
<script lang="ts">
import "@lilydesignsystem/themes/light.css";
import type { LayoutProps } from "./$types";
let { children }: LayoutProps = $props();
</script>
{@render children()} Step 2: Describe the work
src/lib/types.ts
// Administrative data only: no diagnosis, no result, no medicine. A person is an opaque id; who they
// are belongs to the identity service.
export interface Appointment {
id: string;
personId: string;
service: string;
/** An instant, in UTC. */
start: string;
status: "booked" | "confirmed" | "cancelled" | "held";
/** On an urgent pathway a cancellation is held for a person, never done by a link. */
urgent: boolean;
}
export interface Wait {
id: string;
personId: string;
service: string;
priority: "urgent" | "routine";
status: "waiting" | "booked" | "treated" | "removed";
}
export interface Contact {
optedOut: boolean;
/** Reminders already sent for the appointment, as days before it. */
sent: number[];
replied: boolean;
}
export type Role = "staff" | "patient"; A person is an id and nothing more. Who they are belongs to another service, so a copy of this database names nobody.
Step 3: Decide the next step
src/lib/reminders.ts
import type { Appointment, Contact } from "./types.js";
export type Step =
| { kind: "send"; daysBefore: number }
| { kind: "phone" }
| { kind: "nothing"; why: "cancelled" | "replied" | "opted-out" | "past" | "quiet" | "not-yet" };
const DAY = 86_400_000;
const LADDER = [7, 4, 3, 1];
/** The hour in the clinic's own time zone, not the server's. */
const hourIn = (timeZone: string, now: Date) =>
Number(new Intl.DateTimeFormat("en-GB", { timeZone, hour: "2-digit", hourCycle: "h23" }).format(now));
/** What to do next about one appointment. Pure: the clock is an argument, so every case is a test. */
export function nextStep(
appointment: Appointment,
contact: Contact,
now: Date,
timeZone: string,
): Step {
if (appointment.status === "cancelled") return { kind: "nothing", why: "cancelled" };
const daysLeft = (Date.parse(appointment.start) - now.getTime()) / DAY;
if (daysLeft <= 0) return { kind: "nothing", why: "past" };
// The patient was told that someone will phone, so someone is asked to.
if (appointment.status === "held") return { kind: "phone" };
if (contact.replied) return { kind: "nothing", why: "replied" };
const due = LADDER.filter((days) => daysLeft <= days);
const step = due.at(-1);
if (step === undefined) return { kind: "nothing", why: "not-yet" };
// An opt-out stops messages. It never stops a person from being looked after.
if (contact.optedOut) return step === 1 ? { kind: "phone" } : { kind: "nothing", why: "opted-out" };
if (!contact.sent.includes(step)) {
const hour = hourIn(timeZone, now);
if (hour < 8 || hour >= 20) return { kind: "nothing", why: "quiet" };
return { kind: "send", daysBefore: step };
}
// Every message has gone unanswered, so a person phones. Silence is never a reason to discharge.
return step === 1 ? { kind: "phone" } : { kind: "nothing", why: "not-yet" };
} Read it as policy, because it is:
- Silence goes to a person. When every message is unanswered, someone phones. A missed message never removes anyone from a list.
- An opt-out stops messages, not care.
- Quiet hours are the clinic's, in its time zone, and not the server's.
- A held cancellation asks for a call, even though the patient replied, because the patient was told that someone would phone.
Step 4: Test the policy
The clock is an argument, so every case is one line.
src/lib/reminders.test.ts
import { describe, expect, it } from "vitest";
import { nextStep } from "./reminders.js";
import type { Appointment, Contact } from "./types.js";
const appointment: Appointment = {
id: "a1",
personId: "p1",
service: "Physiotherapy",
start: "2026-12-10T10:00:00Z",
status: "booked",
urgent: false,
};
const contact: Contact = { optedOut: false, sent: [], replied: false };
const on = (now: string, c: Partial<Contact> = {}, a: Partial<Appointment> = {}) =>
nextStep({ ...appointment, ...a }, { ...contact, ...c }, new Date(now), "Europe/London");
describe("nextStep", () => {
it("waits, then sends the first reminder at seven days", () => {
expect(on("2026-12-01T10:00:00Z")).toEqual({ kind: "nothing", why: "not-yet" });
expect(on("2026-12-03T12:00:00Z")).toEqual({ kind: "send", daysBefore: 7 });
});
it("does not send one twice, and sends only the newest after a gap", () => {
expect(on("2026-12-03T12:00:00Z", { sent: [7] })).toEqual({ kind: "nothing", why: "not-yet" });
expect(on("2026-12-07T12:00:00Z", { sent: [7] })).toEqual({ kind: "send", daysBefore: 3 });
});
it("asks a person to phone when every message goes unanswered", () => {
expect(on("2026-12-09T12:00:00Z", { sent: [7, 4, 3, 1] })).toEqual({ kind: "phone" });
});
it("stops when the patient replies, cancels or has been seen", () => {
expect(on("2026-12-09T12:00:00Z", { replied: true })).toMatchObject({ why: "replied" });
expect(on("2026-12-09T12:00:00Z", {}, { status: "cancelled" })).toMatchObject({ why: "cancelled" });
expect(on("2026-12-10T10:00:00Z")).toMatchObject({ why: "past" });
});
it("asks a person to phone when a cancellation is held, though the patient replied", () => {
expect(on("2026-12-03T22:00:00Z", { replied: true }, { status: "held" })).toEqual({ kind: "phone" });
});
it("never messages someone who opted out, and still has a person phone", () => {
expect(on("2026-12-03T12:00:00Z", { optedOut: true })).toMatchObject({ why: "opted-out" });
expect(on("2026-12-09T12:00:00Z", { optedOut: true })).toEqual({ kind: "phone" });
});
it("keeps quiet hours in the clinic's time zone", () => {
expect(on("2026-12-03T22:00:00Z")).toMatchObject({ why: "quiet" });
const tokyo = nextStep(appointment, contact, new Date("2026-12-03T12:00:00Z"), "Asia/Tokyo");
expect(tokyo).toMatchObject({ why: "quiet" });
});
}); npx vitest run Step 5: Make safe reply links
src/lib/server/links.ts
import { createHash, randomBytes } from "node:crypto";
interface Link {
appointmentId: string;
expires: number;
used: boolean;
}
const hash = (token: string) => createHash("sha256").update(token).digest("hex");
/** Reply links. Only the hash is kept, so a copy of the table opens nobody's appointment. */
export class Links {
#links = new Map<string, Link>();
issue(appointmentId: string, expires: Date): string {
const token = randomBytes(32).toString("base64url");
this.#links.set(hash(token), { appointmentId, expires: expires.getTime(), used: false });
return token;
}
/** Look, without using it up: a mail scanner that opens the link changes nothing. */
peek(token: string, now: Date): string | undefined {
const link = this.#links.get(hash(token));
return link && !link.used && now.getTime() < link.expires ? link.appointmentId : undefined;
}
/** Use it, once. */
use(token: string, now: Date): string | undefined {
const appointmentId = this.peek(token, now);
if (appointmentId) this.#links.get(hash(token))!.used = true;
return appointmentId;
}
} Only a hash is stored, so a copy of the table opens nobody's appointment. A link works once, and it expires.
Step 6: Keep the appointments
src/lib/server/pas.ts
import type { Appointment, Contact, Wait } from "../types.js";
import { Links } from "./links.js";
const DAY = 86_400_000;
const NOON = Math.floor(Date.now() / DAY) * DAY + DAY / 2;
const inDays = (days: number) => new Date(NOON + days * DAY).toISOString();
export type Outcome = "confirmed" | "cancelled" | "held";
/** In memory, for learning: everything is lost when the server stops. */
export class Pas {
links = new Links();
#appointments = new Map<string, Appointment>();
#contacts = new Map<string, Contact>();
waits: Wait[] = [];
audit: { at: string; what: string; id: string }[] = [];
book(appointment: Appointment, contact: Partial<Contact> = {}) {
this.#appointments.set(appointment.id, appointment);
this.#contacts.set(appointment.id, { optedOut: false, sent: [], replied: false, ...contact });
}
appointments(): Appointment[] {
return [...this.#appointments.values()];
}
appointment(id: string): Appointment | undefined {
return this.#appointments.get(id);
}
contact(id: string): Contact | undefined {
return this.#contacts.get(id);
}
/** A patient's reply, through a link that works once. */
reply(token: string, answer: "confirm" | "cancel", now: Date): Outcome | undefined {
const id = this.links.use(token, now);
const appointment = id ? this.#appointments.get(id) : undefined;
if (!appointment) return undefined;
const outcome: Outcome =
answer === "confirm" ? "confirmed" : appointment.urgent ? "held" : "cancelled";
this.#appointments.set(appointment.id, { ...appointment, status: outcome });
this.#contacts.set(appointment.id, { ...this.#contacts.get(appointment.id)!, replied: true });
this.audit.push({ at: now.toISOString(), what: `reply: ${outcome}`, id: appointment.id });
return outcome;
}
}
export const pas = new Pas();
pas.book({ id: "a1", personId: "7d1f0c3a", service: "Physiotherapy", start: inDays(3), status: "booked", urgent: false });
pas.book({ id: "a2", personId: "b52e9410", service: "Breast clinic", start: inDays(1), status: "booked", urgent: true }, { sent: [7, 4, 3, 1] });
pas.waits = [
{ id: "w1", personId: "7d1f0c3a", service: "Audiology", priority: "routine", status: "waiting" },
{ id: "w2", personId: "c90a77e1", service: "Cardiology", priority: "urgent", status: "waiting" },
{ id: "w3", personId: "b52e9410", service: "Dermatology", priority: "routine", status: "booked" },
]; src/lib/server/pas.test.ts
import { beforeEach, describe, expect, it } from "vitest";
import { Pas } from "./pas.js";
const now = new Date("2026-12-03T12:00:00Z");
const later = new Date("2026-12-10T10:00:00Z");
const appointment = {
id: "a1",
personId: "p1",
service: "Physiotherapy",
start: later.toISOString(),
status: "booked" as const,
urgent: false,
};
let pas: Pas;
let token: string;
beforeEach(() => {
pas = new Pas();
pas.book(appointment);
token = pas.links.issue("a1", later);
});
describe("reply links", () => {
it("look without acting", () => {
expect(pas.links.peek(token, now)).toBe("a1");
expect(pas.links.peek(token, now)).toBe("a1");
expect(pas.appointment("a1")?.status).toBe("booked");
});
it("work once", () => {
expect(pas.reply(token, "cancel", now)).toBe("cancelled");
expect(pas.reply(token, "confirm", now)).toBeUndefined();
expect(pas.appointment("a1")?.status).toBe("cancelled");
expect(pas.contact("a1")?.replied).toBe(true);
});
it("expire, and cannot be guessed", () => {
expect(pas.reply(token, "confirm", later)).toBeUndefined();
expect(pas.reply("a1", "confirm", now)).toBeUndefined();
expect(pas.appointment("a1")?.status).toBe("booked");
});
it("hold a cancellation on an urgent pathway for a person", () => {
pas.book({ ...appointment, id: "a2", urgent: true });
const urgent = pas.links.issue("a2", later);
expect(pas.reply(urgent, "cancel", now)).toBe("held");
expect(pas.appointment("a2")?.status).toBe("held");
});
it("leave a trace", () => {
pas.reply(token, "confirm", now);
expect(pas.audit).toEqual([{ at: now.toISOString(), what: "reply: confirmed", id: "a1" }]);
});
}); Check your work: twelve tests pass in two files. Make reply cancel an urgent appointment outright and run them again: one fails. On an urgent pathway a wrong tap must not cancel a cancer clinic.
Step 7: Write the words, and turn data into views
src/lib/words.ts
import type { Step } from "./reminders.js";
import type { Appointment, Wait } from "./types.js";
export const locale = "en-GB";
/** The clinic's time zone: every time on every page is the clinic's, never the reader's. */
export const timeZone = "Europe/London";
export const appointmentStatus: Record<Appointment["status"], string> = {
booked: "Booked",
confirmed: "Confirmed",
cancelled: "Cancelled",
held: "Cancellation asked for: waiting for a person",
};
export const waitColumns: { id: Wait["status"]; title: string }[] = [
{ id: "waiting", title: "Waiting" },
{ id: "booked", title: "Booked" },
{ id: "treated", title: "Treated" },
{ id: "removed", title: "Removed" },
];
export const priority: Record<Wait["priority"], string> = { urgent: "Urgent", routine: "Routine" };
const why: Record<Extract<Step, { kind: "nothing" }>["why"], string> = {
cancelled: "Nothing: cancelled",
replied: "Nothing: the patient replied",
"opted-out": "Nothing yet: opted out of messages",
past: "Nothing: the time has passed",
quiet: "Wait: quiet hours",
"not-yet": "Nothing yet",
};
export function stepWords(step: Step): string {
if (step.kind === "phone") return "Phone the patient";
if (step.kind === "nothing") return why[step.why];
return `Send the reminder for day ${step.daysBefore}`;
}
export const when = (iso: string) =>
new Intl.DateTimeFormat(locale, { dateStyle: "full", timeStyle: "short", timeZone }).format(new Date(iso)); src/lib/views.ts
import type { CalendarEvent } from "@lilydesignsystem/svelte-calendar";
import type { KanbanCard } from "@lilydesignsystem/svelte-kanban-board";
import type { Appointment, Wait } from "./types.js";
import { appointmentStatus, locale, priority, timeZone } from "./words.js";
/** The clinic's calendar day of an instant, as YYYY-MM-DD. */
export function clinicDay(iso: string): string {
const parts = new Intl.DateTimeFormat("en-GB", {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(new Date(iso));
const part = (type: string) => parts.find((p) => p.type === type)!.value;
return `${part("year")}-${part("month")}-${part("day")}`;
}
const clinicTime = (iso: string) =>
new Intl.DateTimeFormat(locale, { timeZone, timeStyle: "short" }).format(new Date(iso));
export const appointmentEvents = (rows: Appointment[]): CalendarEvent[] =>
rows.map((a) => ({
id: a.id,
date: clinicDay(a.start),
title: `${clinicTime(a.start)} ${a.service}`,
values: { status: appointmentStatus[a.status] },
}));
/** Urgent first. The priority is a word on the card, so it never depends on colour. */
export const waitCards = (rows: Wait[]): KanbanCard[] =>
[...rows]
.sort((a, b) => Number(b.priority === "urgent") - Number(a.priority === "urgent"))
.map((w) => ({
id: w.id,
columnId: w.status,
title: w.service,
subtitle: `Patient ${w.personId}`,
badges: [priority[w.priority]],
})); src/lib/views.test.ts
import { expect, it } from "vitest";
import { clinicDay, waitCards } from "./views.js";
it("puts an appointment on the clinic's day, not the UTC one", () => {
// Half past midnight in London in June is the evening before, in UTC.
expect(clinicDay("2026-06-09T23:30:00Z")).toBe("2026-06-10");
expect(clinicDay("2026-12-09T23:30:00Z")).toBe("2026-12-09");
});
it("shows urgent waits first, in words", () => {
const wait = { personId: "p1", service: "Audiology", status: "waiting" } as const;
const cards = waitCards([
{ ...wait, id: "1", priority: "routine" },
{ ...wait, id: "2", priority: "urgent" },
]);
expect(cards.map((c) => [c.id, c.badges])).toEqual([
["2", ["Urgent"]],
["1", ["Routine"]],
]);
}); An appointment belongs to the clinic's day. Half past midnight in London in summer is still yesterday in UTC, and cutting the date from the text would show it on the wrong day.
Step 8: Load the labels
The calendar and the board need many short strings. Lily has them in 64 languages, as drafts: only English has been reviewed.
src/lib/labels.ts
import { labelsFor, type LabelPack } from "@lilydesignsystem/svelte-locale-translations";
import en from "@lilydesignsystem/svelte-locale-translations/en-001";
const pack = en as LabelPack;
export const calendarLabels = labelsFor("calendar", pack);
export const boardLabels = labelsFor("kanban-board", pack); Step 9: Guard the staff pages
src/app.d.ts
import type { Role } from "#lib/types.js";
declare global {
namespace App {
interface Locals {
role: Role | null;
}
}
}
export {}; src/lib/server/sessions.ts
import { randomBytes } from "node:crypto";
import type { Role } from "../types.js";
// A stand-in for OpenID Connect. The browser holds a random id and the server holds the role, so
// nobody can make themselves staff by editing a cookie.
const sessions = new Map<string, Role>();
export function signIn(role: Role): string {
const id = randomBytes(32).toString("base64url");
sessions.set(id, role);
return id;
}
export const roleOf = (id: string | undefined): Role | null => sessions.get(id ?? "") ?? null; src/lib/server/guard.ts
import { error, redirect } from "@sveltejs/kit";
/** Every staff page calls this in its own load. Hiding a link protects nothing. */
export function requireStaff(locals: App.Locals) {
if (!locals.role) redirect(303, "/signin");
if (locals.role !== "staff") error(403, "Staff only");
} src/hooks.server.ts
import type { Handle } from "@sveltejs/kit/hooks";
import { roleOf } from "#lib/server/sessions.js";
export const handle: Handle = async ({ event, resolve }) => {
event.locals.role = roleOf(event.cookies.get("session"));
const response = await resolve(event);
response.headers.set("cache-control", "no-store");
// A reply link is a secret: never send its address to another site.
response.headers.set("referrer-policy", "no-referrer");
return response;
}; src/routes/signin/+page.server.ts
import { redirect } from "@sveltejs/kit";
import { dev } from "$app/env";
import { signIn } from "#lib/server/sessions.js";
import type { Actions } from "./$types";
export const actions: Actions = {
default: async ({ request, cookies }) => {
const role = (await request.formData()).get("role") === "staff" ? "staff" : "patient";
cookies.set("session", signIn(role), {
path: "/",
httpOnly: true,
sameSite: "lax",
secure: !dev,
});
redirect(303, "/");
},
}; src/routes/signin/+page.svelte
<svelte:head><title>Sign in</title></svelte:head>
<main>
<h1>Sign in</h1>
<p>For learning: there is no password. Use an identity provider for anything real.</p>
<form method="POST">
<button class="button" name="role" value="staff">Sign in as staff</button>
<button class="button" name="role" value="patient">Sign in as a patient</button>
</form>
</main> src/routes/+page.svelte
<svelte:head><title>Patient administration</title></svelte:head>
<main>
<h1>Patient administration</h1>
<p>For learning. Never enter a real person's details.</p>
<nav aria-label="Staff pages">
<ul>
<li><a href="/appointments">Appointments</a></li>
<li><a href="/waitlist">Waiting list</a></li>
<li><a href="/reminders">Reminders</a></li>
</ul>
</nav>
<p><a href="/signin">Sign in</a></p>
</main> Step 10: Show the calendar
src/routes/appointments/+page.server.ts
import { requireStaff } from "#lib/server/guard.js";
import { pas } from "#lib/server/pas.js";
import { clinicDay } from "#lib/views.js";
import type { PageServerLoad } from "./$types";
export const load: PageServerLoad = ({ locals }) => {
requireStaff(locals);
return { appointments: pas.appointments(), today: clinicDay(new Date().toISOString()) };
}; src/routes/appointments/+page.svelte
<script lang="ts">
import { CalendarView, type CalendarViewMode } from "@lilydesignsystem/svelte-calendar";
import { untrack } from "svelte";
import { calendarLabels } from "#lib/labels.js";
import { appointmentEvents } from "#lib/views.js";
import { locale } from "#lib/words.js";
import type { PageProps } from "./$types";
let { data }: PageProps = $props();
let view = $state<CalendarViewMode>("month");
let anchorDate = $state(untrack(() => data.today));
// Words from the label pack; weekday and month names from Intl.
const name = (options: Intl.DateTimeFormatOptions, date: Date) =>
new Intl.DateTimeFormat(locale, { ...options, timeZone: "UTC" }).format(date);
// 2023-01-01 was a Sunday, which the calendar numbers 0.
const weekday = (n: number) => new Date(Date.UTC(2023, 0, 1 + n));
const labels = {
...calendarLabels,
weekday: (n: number) => name({ weekday: "long" }, weekday(n)),
weekdayAbbr: (n: number) => name({ weekday: "short" }, weekday(n)),
periodTitle: (_view: string, _start: string, _end: string, anchor: string) =>
name({ month: "long", year: "numeric" }, new Date(`${anchor}T00:00:00Z`)),
};
</script>
<svelte:head><title>Appointments</title></svelte:head>
<main>
<h1>Appointments</h1>
<!-- svelte-ignore a11y_no_noninteractive_tabindex (a region that scrolls must take the keyboard) -->
<div class="calendar" role="region" tabindex="0" aria-label="Appointment calendar">
<CalendarView
label="Clinic appointments"
bind:view
bind:anchorDate
today={data.today}
{locale}
{labels}
events={appointmentEvents(data.appointments)}
eventFields={[{ id: "status", header: "Status", type: "text" }]}
>
<!-- The calendar draws the days; what an appointment looks like is yours. Without this, only the agenda shows any. -->
{#snippet day({ events, fieldText })}
{#each events as event (event.id)}
<p>{event.title}: {fieldText(event, "status")}</p>
{/each}
{/snippet}
</CalendarView>
</div>
</main>
<style>
.calendar {
overflow-x: auto;
}
</style> The calendar draws the days, and you draw what is in them, in the day snippet. Leave it out and the week and month views show none, with no error: only the agenda lists them by itself.
Step 11: Show the waiting list
src/routes/waitlist/+page.server.ts
import { requireStaff } from "#lib/server/guard.js";
import { pas } from "#lib/server/pas.js";
import type { PageServerLoad } from "./$types";
export const load: PageServerLoad = ({ locals }) => {
requireStaff(locals);
return { waits: pas.waits };
}; src/routes/waitlist/+page.svelte
<script lang="ts">
import { KanbanBoard } from "@lilydesignsystem/svelte-kanban-board";
import { boardLabels } from "#lib/labels.js";
import { waitCards } from "#lib/views.js";
import { waitColumns } from "#lib/words.js";
import type { PageProps } from "./$types";
let { data }: PageProps = $props();
</script>
<svelte:head><title>Waiting list</title></svelte:head>
<main>
<h1>Waiting list</h1>
<!-- Read only: a wait ends when someone books, treats or removes the patient, not when a card is dragged. -->
<!-- svelte-ignore a11y_no_noninteractive_tabindex (a region that scrolls must take the keyboard) -->
<div class="board" role="region" tabindex="0" aria-label="Waiting list board">
<KanbanBoard
label="Waiting list"
columns={waitColumns}
cards={waitCards(data.waits)}
labels={boardLabels}
readonly
/>
</div>
</main>
<style>
.board {
overflow-x: auto;
}
</style> Step 12: Work through the reminders
src/routes/reminders/+page.server.ts
import { error } from "@sveltejs/kit";
import { nextStep } from "#lib/reminders.js";
import { requireStaff } from "#lib/server/guard.js";
import { pas } from "#lib/server/pas.js";
import { stepWords, timeZone } from "#lib/words.js";
import type { Actions, PageServerLoad } from "./$types";
export const load: PageServerLoad = ({ locals }) => {
requireStaff(locals);
const now = new Date();
return {
rows: pas.appointments().map((a) => ({
...a,
step: stepWords(nextStep(a, pas.contact(a.id)!, now, timeZone)),
})),
};
};
export const actions: Actions = {
// A real service texts this link and never shows it to staff.
link: async ({ request, locals }) => {
requireStaff(locals);
const appointment = pas.appointment(String((await request.formData()).get("id")));
if (!appointment) error(404, "No such appointment");
return { link: `/r/${pas.links.issue(appointment.id, new Date(appointment.start))}` };
},
}; src/routes/reminders/+page.svelte
<script lang="ts">
import { appointmentStatus, when } from "#lib/words.js";
import type { PageProps } from "./$types";
let { data, form }: PageProps = $props();
</script>
<svelte:head><title>Reminders</title></svelte:head>
<main>
<h1>Reminders</h1>
{#if form?.link}<p role="status">Reply link: <a href={form.link}>open it as the patient</a></p>{/if}
<ul>
{#each data.rows as row (row.id)}
<li>
{row.service}, <time datetime={row.start}>{when(row.start)}</time>.
{appointmentStatus[row.status]}. <strong>{row.step}</strong>
<form method="POST" action="?/link">
<input type="hidden" name="id" value={row.id} />
<button class="button">Make a reply link for {row.service}</button>
</form>
</li>
{/each}
</ul>
</main> Step 13: Let the patient reply
src/routes/r/[token]/+page.server.ts
import { error } from "@sveltejs/kit";
import { pas } from "#lib/server/pas.js";
import type { Actions, PageServerLoad } from "./$types";
// Reads only. Opening the link, or a mail scanner opening it, changes nothing.
export const load: PageServerLoad = ({ params }) => {
const id = pas.links.peek(params.token, new Date());
const appointment = id ? pas.appointment(id) : undefined;
// The date and time, and no more: whoever holds the phone may not be the patient.
return { start: appointment?.start ?? null };
};
export const actions: Actions = {
default: async ({ request, params }) => {
const answer = (await request.formData()).get("answer");
if (answer !== "confirm" && answer !== "cancel") error(400, "Unknown answer");
return { outcome: pas.reply(params.token, answer, new Date()) ?? null };
},
}; src/routes/r/[token]/+page.svelte
<script lang="ts">
import { when } from "#lib/words.js";
import type { PageProps } from "./$types";
let { data, form }: PageProps = $props();
const outcomes = {
confirmed: "Thank you. Your appointment is confirmed.",
cancelled: "Your appointment is cancelled.",
held: "Please do not worry: someone will phone you about this before anything is cancelled.",
};
</script>
<svelte:head><title>Your appointment</title></svelte:head>
<main>
<h1>Your appointment</h1>
{#if form?.outcome}
<p role="status">{outcomes[form.outcome]}</p>
{:else if data.start}
<p><time datetime={data.start}>{when(data.start)}</time></p>
<form method="POST">
<button class="button" name="answer" value="confirm">I will come</button>
<button class="button" name="answer" value="cancel">I cannot come</button>
</form>
{:else}
<p>This link has been used or is out of date. Please phone the clinic.</p>
{/if}
</main> Opening the link reads, and only the button acts. Mail scanners open every link they see: if opening one cancelled, they would cancel your clinic.
Check your work: run pnpm dev. Open the appointments: you are sent to sign in. Sign in as a patient: you are refused. Sign in as staff: two appointments are on the calendar. On the reminders page make a link for the breast clinic, open it, and choose "I cannot come": nothing is cancelled, you are told that someone will phone, and the reminders page now says "Phone the patient". Open the link again: it has been used.
What this does not do yet
- It keeps everything in memory, and signing in has no password.
- It sends nothing. A real service texts the link and never shows it to staff.
- The built version marks its cookie as secure, so it needs https.
From here to the full project
- What it must do: the functional requirements, each with the test that proves it.
- Views: views.ts maps the service's data to the calendar, the board and the chart.
- Who may see what: access.ts and guard.ts.
- Signing in: oidc.ts, with Keycloak.
- Reply links: token-link.ts.
- The service: the API, in Rust, with PostgreSQL.
- Misuse: chaos testing sends hostile input to every route.
- Fairness: the no-show model is off until named people approve it, and may only ever add a phone call.
- Running it: the runbook and the path to production.
A good next step is to offer another time when someone cancels, with a test first.
Next steps
- Electronic patient record tutorial: record what happens at the appointment.
- International Patient Summary tutorial: share it.
- A form that works worldwide: names, addresses, dates and direction.