Files
vitareba/components/admin/ProgrammeAssignmentForm.tsx
T
GandClaude Opus 5 ef293be78a fix: name each patient's own clinician, and stop trusting stale sessions (#30)
* fix(bookings): confirm bar only pins once there is something to confirm

At 390px the sticky confirm bar was pinned from the moment the picker
rendered, so an empty, disabled bar parked a white slab over "2 · Pick a
day" — covering the step the patient still had to reach. It now sticks
only after a slot is selected, which is when following the thumb is
actually worth the screen it costs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(clinic): every patient is told their own doctor's name, not one from config

COMPANY.clinicianName was a second source of truth for "who treats this
patient". care_team is the first. The config answer was wrong for every
patient who is not Manuel's — which is the whole point of signing up more
clinicians — and it appeared in 20+ places: every onboarding email, the
dashboard, the check-in page, the profile form, programme phase copy.

Killing the property makes the compiler enumerate every site. Each one now
resolves the real name via clinicianLabelFor(patientId), falling back to a
neutral "your clinician" when nobody treats them yet. Copy that says "your
clinician" is never wrong; copy that names the wrong doctor destroys trust
in a clinical product.

Where the actor is not the primary clinician, it now says who actually
acted: newDocumentEmail names the uploader, programmeAssignedEmail names
the admin who enrolled. Where the actor is unknowable — an unread reply
can come from any care-team member — the copy stays unattributed rather
than guessing.

Also fixed along the way:
- the public Inflection Edge results CTA interpolated an English name into
  German/French/Italian copy; the four message files now carry a localised
  "our clinical team" and the placeholder is gone
- phase descriptions said "you will hear from him"; now "from them"
- /checkin was a client route with no way to reach the database, so it is
  split into a thin server page + CheckinForm

Never-Twice: lib/domain/clinician-discipline.test.ts fails CI if config
regrows a clinician*Name key, or if any shared copy hardcodes a name from
TEAM_MEMBERS. It caught two leaks this sweep had missed (programmes.ts,
next-step.ts).

pnpm verify green: lint, typecheck, 940 tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(auth): a deleted or demoted account stops working within 5 minutes

JWT sessions are self-contained. The jwt callback only touched the database
at sign-in, so nothing afterwards knew the row it came from had changed:
deleting a user left their session fully working, and revoking an admin left
them admin — both until the cookie happened to expire.

The callback now re-reads the users row when the token is older than
SESSION_REVALIDATE_MS (5 min), and returns null when the row is gone, which
ends the session. Role and email verification are refreshed from the row on
the same pass, so a demotion also takes effect within one interval.

A failed lookup deliberately does NOT end the session: an unreachable
database is not evidence a user was deleted, and treating it that way would
sign the whole clinic out during a blip. The token is returned unstamped so
the check retries on the next request.

The decision logic is a pure function pair in lib/domain/auth.ts rather than
inline in the NextAuth factory, so it is testable: 10 cases cover deletion,
demotion, the promote-only ADMIN_EMAILS recovery path, a backwards clock,
and the database-down path.

Middleware (lib/auth/edge.ts) still reads the token without a database — it
cannot reach one from the Edge runtime. That is only coarse routing; every
data path goes through requireSession()/requireAdmin() in the Node runtime,
which is where this check now runs.

pnpm verify green: lint, typecheck, 950 tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 17:16:29 +02:00

145 lines
4.5 KiB
TypeScript

"use client";
import { useState } from "react";
import styles from "@/app/(admin)/admin.module.css";
import { SAVED_FEEDBACK_MS, PATIENT_NOTE_MAX_LENGTH } from "@/lib/config/portal";
import { PROGRAMME_CONFIG, PHASE_CONFIG, PROGRAMME_ENUM_VALUES, PHASE_ENUM_VALUES, phaseDescription } from "@/lib/config/programmes";
import type { ProgrammeKey, PhaseKey } from "@/lib/config/programmes";
type Assignment = {
programme: ProgrammeKey;
phase: PhaseKey;
startDate: string | null;
notes: string | null;
};
export function ProgrammeAssignmentForm({
patientId,
initial,
clinician,
}: {
patientId: string;
initial: Assignment | null;
/** This patient's clinician, so the preview shows the copy they will read. */
clinician: string;
}) {
const [programme, setProgramme] = useState<ProgrammeKey | "">(initial?.programme ?? "");
const [phase, setPhase] = useState<PhaseKey | "">(initial?.phase ?? "");
const [startDate, setStartDate] = useState(initial?.startDate ?? "");
const [notes, setNotes] = useState(initial?.notes ?? "");
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const [error, setError] = useState("");
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!programme || !phase) return;
setSaving(true);
setError("");
try {
const res = await fetch(`/api/admin/patients/${patientId}/programme`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
programme,
phase,
startDate: startDate || null,
notes: notes || null,
}),
});
const data = await res.json();
if (!data.success) {
setError("Failed to save assignment.");
return;
}
setSaved(true);
setTimeout(() => setSaved(false), SAVED_FEEDBACK_MS);
} catch {
setError("Failed to save assignment.");
} finally {
setSaving(false);
}
}
return (
<form onSubmit={handleSubmit} className={styles.formStack}>
<div className={styles.formGrid2}>
<div>
<label htmlFor="prog-programme" className={styles.assignLabel}>Programme</label>
<select
id="prog-programme"
value={programme}
onChange={(e) => setProgramme(e.target.value as ProgrammeKey)}
className={styles.assignField}
>
<option value="">Select programme…</option>
{PROGRAMME_ENUM_VALUES.map((key) => (
<option key={key} value={key}>{PROGRAMME_CONFIG[key].label}</option>
))}
</select>
</div>
<div>
<label htmlFor="prog-phase" className={styles.assignLabel}>Phase</label>
<select
id="prog-phase"
value={phase}
onChange={(e) => setPhase(e.target.value as PhaseKey)}
className={styles.assignField}
>
<option value="">Select phase…</option>
{PHASE_ENUM_VALUES.map((key) => (
<option key={key} value={key}>{PHASE_CONFIG[key].label}</option>
))}
</select>
</div>
</div>
<div>
<label htmlFor="prog-start-date" className={styles.assignLabel}>Start date (optional)</label>
<input
id="prog-start-date"
type="date"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
className={styles.assignField}
/>
</div>
<div>
<label htmlFor="prog-notes" className={styles.assignLabel}>Notes (optional)</label>
<textarea
id="prog-notes"
value={notes}
onChange={(e) => setNotes(e.target.value)}
rows={2}
maxLength={PATIENT_NOTE_MAX_LENGTH}
placeholder="Any notes about this assignment…"
className={styles.assignFieldTextarea}
/>
</div>
{programme && phase && (
<div className={styles.assignPreview}>
<strong className={styles.assignPreviewLabel}>{PROGRAMME_CONFIG[programme as ProgrammeKey]?.label}</strong>
{" — "}
{phaseDescription(phase as PhaseKey, clinician)}
</div>
)}
{error && <p className={styles.assignError}>{error}</p>}
<button
type="submit"
disabled={saving || !programme || !phase}
className={styles.assignSubmit}
>
{saving ? "Saving…" : saved ? "Saved ✓" : initial ? "Update assignment" : "Assign programme"}
</button>
</form>
);
}