* chore: add a formatter, matching the style this repo already writes
singleQuote=false was chosen by counting this repo's own
imports, not by fleet decree. The fleet is genuinely split and the two repos
that already had a .prettierrc disagreed with each other, so there was no
standard to restore. Quote style does not cross repo boundaries; having a
gate does.
Markdown is ignored for now — prettier rewraps prose, which would bury the
real diff.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* style: format with prettier (304 files)
Mechanical. No behaviour change. This SHA is listed in
.git-blame-ignore-revs so `git blame` skips it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* chore: teach git blame to skip the reformat
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* style: format the two files the reformat pass missed
prettier --check flagged app/shared.module.css and lib/domain/clinicians.test.ts
on a branch whose whole point was that everything had been formatted. Re-running
the same command with the same version fixes both, so the rollout's write step
did not finish what it reported.
The rollout now runs --check straight after --write and refuses to open a PR
unless it comes back clean, so a partial reformat fails at the source instead of
in CI.
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
George's report, verbatim: "there should be a way to apply as a clinician.
doctors should not see the applications in their tools. registration as a
clinician should not be public" plus a pasted dump of the calendar-connect
copy calling it "too complicated," and the admin dashboard overall "awful."
Investigated before changing anything, because "grant clinician access" is
security-sensitive:
- The public "apply to become a clinician" flow (ClinicianApplicationCard on
every patient's profile page) was fully open — any registrant could submit
a request, no allowlist, no invite. That's the literal thing George said
shouldn't be public.
- Approval never actually worked end to end: approveApplication set
isClinician=true but never granted role=admin, and /admin/* is gated on
role=admin only. An approved applicant got booking/profile visibility but
had NO route to actually manage their own hours, bio, or calendar sync —
the feature was half-built.
- I considered fixing that by widening /admin/* to any isClinician account.
Investigated first and stopped: /admin/patients, /admin/patients/[id],
and app/api/bookings GET are ALL globally scoped today — any admin session
sees every patient's full clinical record and every clinician's bookings,
with zero per-clinician filtering (only /admin/messages is properly
participant-scoped, via threadkit). Widening access without building real
care_team-based scoping across those three surfaces first would hand a
newly-onboarded clinician read access to every other clinician's patients'
clinical notes — a privacy bug, not a UI nit. NOT doing that in this pass;
it's a separate, larger, security-critical project of its own.
What shipped instead, scoped to what's safe and concretely asked for:
- Removed the public self-apply flow entirely (ClinicianApplicationCard,
the public /api/clinician-applications submit route, the pending/approve/
decline review ceremony). Replaced with lib/domain/clinicians.ts: an owner
adds a clinician directly by email (grantClinicianByEmail) or removes one
(revokeClinicianStatus) — no public registration path exists any more.
Reuses the existing clinician_applications table as an audit row (who
granted it, when) rather than adding a new table for the same fact.
- New owner-only page at the same /admin/applications path, relabeled
"Clinicians": search-free, just an email field and a roster with Remove.
Moved out of the "Patients" nav group into "Practice" (alongside Reports)
— deliberately separated from the day-to-day clinical nav a working
clinician lives in, since who is staff is an owner decision, not part of
the patient pipeline. Dropped its nav badge: there's no pending queue
left to signal.
- Simplified the calendar-connect copy on /admin/profile: trimmed both
paragraphs, and collapsed the three-provider "Where to find it" block into
a closed-by-default <details> disclosure instead of always-visible text.
- Split /admin/profile from five stacked independent cards into two tabs
(Profile & hours / Calendar sync) via the existing SectionTabs component
(already used on the patient detail page) — added an ariaLabel prop to it
since it's now used in a second context, rather than hardcoding a label
that only made sense for the first caller.
pnpm verify (1297 tests, 0 lint errors) and pnpm build both green.
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Phase 1 of a full clinician/patient UI redesign George asked for after we
shipped the actor-aware cancellation copy fix (#63) — he judged the wider
nav/notification/mobile experience underneath it as poorly designed. This is
the shared foundation (nav, header, notifications, mobile, mega menu, footer)
that every individual page redesign in later phases will sit on top of.
In-app notifications (lib/domain/notifications.ts, app/api/notifications/*,
components/shared/NotificationBell.tsx): a companion to the existing email
sends, not a replacement — wired alongside sendEmail at 5 trigger sites
(new message, every booking lifecycle event, critical-signal + goal-achieved
in cron/signals, clinician application decisions, document uploads). One
shared bell component in both admin and portal headers, 30s polling reusing
the existing MESSAGE_POLL_INTERVAL_MS constant. Kept as an in-repo module,
not a published package — no second adopter yet to justify that (same
rule-of-three standard that produced threadkit, which vitareba already
imports for message read/write/unread — verified before starting, so no
messaging-domain work was needed here).
Admin nav (lib/config/routes.ts ADMIN_NAV_GROUPS, components/admin/AdminNav.tsx):
flat 8-item list replaced with grouped sections mirroring the portal's own
Care group, so the same clinician relationship reads the same shape from
either side. Fixed the "always-on badge" problem: urgentPatients and
pendingApplications were live state counts with no seen-at gate, so a
clinician who'd already reviewed everything still saw a nonzero badge
forever. Added profiles.patientsSeenAt/applicationsSeenAt (mirroring the
existing bookingsSeenAt/goalsSeenAt pattern) and profiles.lastKnownSignalAt
(there was no "when did this become urgent" timestamp at all) via one
generic mark-seen route instead of a 4th near-identical file.
Admin mobile (AdminBottomNav): replaced the fragile horizontal-scrolling
pill strip (flagged in its own code comment as tracking <th> order by hand)
with a bottom tab bar + "More" sheet, matching the portal's own BottomNav —
a clinician who is also a patient (the existing role-switch) shouldn't
relearn navigation switching sides.
Marketing mega menu (components/sections/Nav.tsx): was CSS :hover-only, no
keyboard access, no aria-expanded, unusable on a tablet or hybrid laptop.
Now click/focus-driven with proper button semantics, Escape + click-outside
(via the new shared useClickOutside hook — also used by the notification
bell and UserDropdown, its 3rd use). Extracted NavAuthActions to fix the
"future auth-state change needs editing two places" risk the desktop/mobile
duplication already had.
Marketing footer: was a logo and one copyright line, no links at all — now a
real sitemap footer (explore/account columns, address, emergency contacts).
EMERGENCY_CONTACTS existed in config but was wired into no authed screen
either; added to UserDropdown too.
New/changed columns: notifications (new table), profiles.patientsSeenAt,
profiles.applicationsSeenAt, profiles.lastKnownSignalAt — all additive,
drizzle/0015_loving_umar.sql.
pnpm verify (1299 tests, 0 lint errors) and pnpm build both green.
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
You caught this live: cancelling a patient's appointment from /admin/bookings
showed George (as the clinician) the PATIENT's own late-cancellation copy —
"...if you are unwell or something has happened, cancel anyway and message
your clinician" — telling him to message himself. BookingActions already had
an actorLabel prop that varied the reason-field wording, but the actual
warning banner was one hardcoded string used for both sides. Split into
lateWarningPatient/lateWarningClinic in lib/config/cancellation.ts.
Root-caused the other half of the same report: "he never received a
notification when a patient booked him." An email IS sent on every new
booking (already implemented) — the real gap is that admin's "Bookings" nav
badge only counts status=pending, but a native slot booking is born
status=confirmed and never touches pending. So a real booking landed with
zero visible change anywhere in George's own UI until he happened to open
the page. Mirrored the exact pattern the patient portal already uses for
"new goals" (profiles.goalsSeenAt): added profiles.bookingsSeenAt, an
/api/admin/bookings/mark-seen endpoint that clears it on page visit, and the
nav badge now counts pending+confirmed bookings created since last seen.
Then audited /admin/patients (list + detail) as asked. Two real bugs, not
vague dissatisfaction:
- Date of birth rendered the raw "1989-11-24" string straight from the
database — every other date on this exact page goes through
formatDateLong. Fixed, anchored to local midnight (not UTC) the same way
this file already handles check-in dates, so the displayed day can't
shift at a timezone boundary.
- PatientBookingsCard's own type declared a `clinician` field that the JSX
never rendered, and the query feeding it didn't even fetch the relation —
so an admin looking at any patient's booking history had no way to tell
which doctor a given appointment was with. Now fetched and shown.
- CareTeamCard's "Remove" and "Add to care team" buttons were the identical
bold primary style — detaching a clinician and adding one are not the same
weight of action. Remove is now the secondary/ghost treatment.
Scope note: this pass fixed the concrete bugs an audit surfaced rather than
re-skinning the whole admin patient record to match the portal's SpaceX-
influenced redesign — that's ~9 more components (assessment/messages/goals
cards, notes, programme assignment, booking log, measurements, profile edit)
and a genuinely separate initiative. Said so rather than silently scoping it
down.
pnpm verify (1293 tests) and pnpm build both green.
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Three complaints in one message, all rooted in the same gap: nothing about
"who is a clinician and when do they work" was ever real, self-service data.
## The fake availability
lib/config/scheduling.ts hardcoded a per-clinician-email override object.
One entry's own comment called it what it was: "evenings-and-Friday
product-testing window". Every patient booking against it was offered
times a developer had typed into source, not a real schedule.
Replaced with clinician_profiles (new table, additive migration): a
clinician's own bio, title, specialties and working hours, self-service via
a real day x window editor (not a JSON blob) at /admin/profile. The row is
optional per clinician — no row means DEFAULT_AVAILABILITY, the exact
fallback contract the old override map gave an unlisted clinician, now
backed by a database column instead of a source edit. All 5 call sites that
read a clinician's rules (booking, rescheduling, cancellation email,
calendar feed, slot listing) now read the real per-clinician row.
## The calendar-connect feature nobody found
lib/domain/calendar-sync.ts + the clinician_calendars table + a full
connect-a-real-ICS-feed UI (CalendarSubscriptions) already existed and
already worked — verified live: the DB had zero rows, meaning nobody, ever,
had connected a real calendar. It was buried at the top of /admin/bookings
next to two other calendar-shaped cards with similar names. Moved to a
dedicated /admin/profile settings page alongside the new bio/hours editor,
where "your calendar" and "your availability" live together instead of
being three cards stacked above a booking table.
## Clinician profiles, both directions
- Patients can now see a clinician's bio, title, specialties and working
hours (app/(portal)/care-team/[clinicianId], linked from the Care Team
card's name) — GET /api/clinicians/[id], a curated view that never
exposes booking-engine tuning (leadTimeHours, horizonDays, maxPerDay).
- Clinicians already see patient profiles via the existing admin patient
view — this pass didn't need to add that side.
## Clinician application process
users.isClinician defaults to false for every new account; there was no
path to becoming one except a developer flipping it by hand. New
clinician_applications table: a patient submits a message from their
profile page, an admin approves or declines from /admin/applications
(nav badge shows the pending count). Approval grants isClinician inside a
transaction with marking the application decided, so the two can't
half-apply. Declined applicants see the reviewer's note and may re-apply.
## Also
- Extracted requireClinician() into lib/auth/guards.ts (was duplicated
locally in accepting-patients/route.ts; this PR added a second real
need for it) — CLAUDE.md's "notice on the 2nd, extract by the 3rd" rule.
- Caught by clinician-profile.test.ts before it shipped: this Zod version's
z.record() with an enum/literal key schema validates as an EXHAUSTIVE
record (every key required), not partial — would have made the weekly-
hours editor reject any patch that left a day closed, i.e. every real
patch. Fixed with z.partialRecord().
- reviewed_by on clinician_applications added to schema-discipline's
RETAINED_AUTHORSHIP (deliberately no onDelete policy) — it's staff-only
authorship provenance, the same pattern as patient_notes.admin_id.
pnpm verify (1292 tests, up from 1266) and pnpm build both green.
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
GET /api/admin/patients and /api/admin/patients/[id] returned the Drizzle row
verbatim — `db.query.users.findMany(...)` with no `columns:` projection — so
every response carried each patient's bcrypt digest, plus failedLoginAttempts
and lockedUntil.
Confirmed live on prod before fixing: 2/2 rows in the list response and both
detail responses carried a `$2b$12$…` hash.
This is a worse shape than the FleetCrown /api/me case that prompted the sweep.
There the digest was the caller's own. Here an admin console shipped OTHER
people's credential material to a browser, in a clinic app, where those people
are patients. A digest is not a password, but it is the input to an offline
attack that costs the attacker nothing, and it moves the secret from a place
nothing can read it to a place everything can.
lib/db/user-view.ts is now the single answer to what may leave the server:
an ALLOW-list whose halves are exhaustive over the schema, so a new users
column fails the test until it is classified exposed or withheld. A deny-list
can only name what existed when it was written.
failedLoginAttempts and lockedUntil stay exposed deliberately — not secrets,
and an admin helping someone locked out needs to see them.
Negative-tested in both directions, because a gate that cannot fail is not a
gate: dropping `role` from the list fails with "users.role is in NEITHER list";
re-exposing `password` fails with "in BOTH lists" plus the projection and
serialization assertions.
Verified: tsc clean, eslint clean, 1100/1100 tests (8 new).
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
* 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>
Booking, messages and documents all needed the same missing fact — who treats
you — and none of them had a way to learn it. This adds one definition of the
care team and makes every surface read from it.
Choose your provider
- /profile gains a care-team picker: a patient chooses their own clinician
(previously only an admin could create the link, so a new patient had no way
to say "this is my doctor"). Self-pairs allowed by design: a dual-role
clinician can be their own patient and walk the patient path.
- lib/domain/care-team.ts is the SSOT — roster, "who treats me", primary
clinician — consumed by booking defaults, message recipients and document
notifications.
Booking
- Slot picker redesigned mobile-first as three explicit steps: who you'd like
to see (avatar cards, "Your clinician" badge), pick a day (scroll-snap date
rail with free-slot counts), choose a time (grouped morning/afternoon/
evening rather than a wall of times). Every control is a >=44px touch target
and the confirm bar sticks above the mobile nav.
- The default clinician is now the patient's OWN clinician, not whoever sorts
first. The confirm bar states the real appointment length, timezone and that
an invite is attached.
- The booking email now also reaches the clinician whose calendar it lands in,
deduplicated against ADMIN_EMAILS.
Calendars, without a paid SaaS
- Every confirmed booking ships an RFC 5545 invite (.ics) on both emails — one
tap adds it in Gmail, Apple Mail or Outlook, no integration to configure.
- Each clinician gets a subscribable feed at /api/calendar/<id>/<token>,
surfaced with copy-paste instructions on /admin/bookings. Cancelled bookings
are published as CANCELLED so they disappear rather than linger.
- The feed token is an HMAC of the user id (lib/domain/calendar-token.ts): no
column, no migration, rotatable for everyone by changing the secret. A wrong
token 404s — a 401 would confirm the id belongs to a real clinician.
- Fixed a bug this would have shipped with: the feed sat behind the middleware
session gate, and calendar clients send no cookies, so it could never have
worked in prod. route-auth-invariant.test.ts caught it.
Messages
- Threads are addressed to a clinician (threads.clinician_id, nullable for the
threads that predate multi-clinician care). Patients pick a recipient; the
server defaults to their primary clinician; replies follow the thread's
addressee instead of mailing every admin. Admin lists show "-> Dr X".
Documents
- Patients can upload their own documents. Ownership is decided server-side in
both upload routes — only an admin may name the owner — and who gets notified
follows who uploaded: clinician uploads notify the patient, patient uploads
notify their care team (falling back to ADMIN_EMAILS so nothing lands in a
mailbox nobody reads).
Also: --portal-bottom-nav-h hoisted to a token (the 60px was duplicated in two
files), slotParts() groups by CLINIC hour so a 09:30 Zürich slot reads as
morning from Tokyo, and h23 hour cycle so midnight is 0 and not 24.
pnpm verify green (932 tests, +18 new for ics/calendar-token/slotParts);
pnpm build green. Migration 0003 is additive (ADD COLUMN + FK, no new tables).
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Four coherence fixes from George's walkthrough:
- /assessment no longer hijacks the viewport: the instrument renders
embedded inside the portal shell (sidebar + header stay visible)
instead of mounting the marketing full-screen overlay on top of it.
- Dual-role switching is first-class: 'Clinician area →' in the portal
sidebar (admins only), '← Patient portal' in the admin sidebar, and
the user dropdown offers the OTHER side instead of the one you're in.
- Admins can actually reach the patient portal again: the middleware
rule bouncing /dashboard → /admin/patients predated dual-role care
and made the portal unreachable for Manuel and George. Post-login
'clinicians land in admin' now lives in the login page, where an
explicit returnTo still wins.
- Admin patient record is tabbed (Overview / Clinical / Activity /
Edit profile) instead of ~12 stacked cards; tab state survives
refresh via URL hash. Admin header gains the same breadcrumb the
portal has; admin messages list unread threads first.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
First-principles audit of the admin against the mission line ("Manuel
opens the admin and knows — without calling anyone — exactly who needs
attention today") surfaced two violations; both fixed:
- lib/domain/patients.ts patientScope() — THE definition of who counts
as a patient (role=patient OR treated in care_team), now used by the
patient list, the admin patients API and reports. Before, reports
still filtered role=patient only: it claimed 3 patients / 0 critical
while the list showed 5 / 1 critical — two admin pages contradicting
each other on the mission-critical number.
- Bookings admin defaults to a new "upcoming" view (active bookings with
a scheduled time, soonest first) and the subtitle answers the daily
question before the table loads: "Next: Fri 14 Aug, 09:00 — George ·
2 upcoming · 0 pending". The old default was "pending" — but slot
bookings are born confirmed, so a normal day showed an empty list and
the real schedule was buried in created-at order. Subtitle no longer
claims "0 total" while still loading.
Verified in dev browser: reports and patient list agree (critical = 1),
bookings opens on the sorted schedule. 898 tests + build green.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
One shot, per George's directives: dual roles, mutual care, per-clinician
booking, AI as a first-class feature — and where regulation would have
stopped a feature, it runs anyway with the law rendered as a warning at
the moment of use, never as a silent wall.
Roles & care:
- users.isClinician marks doctors; role stays the ACCESS level. Dual
roles by design: a clinician can be another clinician's patient
(care_team table, symmetric pairs). Patient lists include anyone
treated in care_team, so dual-role users appear.
- Roles are now DB-owned: resolveRole is promote-only (ADMIN_EMAILS
bootstraps/recovers admin, never demotes) — login used to silently
strip DB-granted admin, which cost an hour of "why am I a patient
again".
- Per-clinician booking: bookings.clinicianId, unique slot index becomes
(clinician_id, scheduled_at), availability rules per clinician email
in lib/config/scheduling.ts, clinician picker pills in the slot UI,
clinician named in confirmations/emails/admin views.
AI (lib/ai, OpenAI-compatible, env-configured):
- Patient "AI insight" on the dashboard; clinician "pre-consultation
brief" and "differential discussion aid" on the patient page —
the latter is the feature MDR would call a medical device if it
diagnosed, so it lawfully hypothesises instead and EVERY output
renders under the not-a-medical-device warning.
- Consent-at-click: missing GDPR Art. 9 consent doesn't block — the
warning explains the law and one click records timestamped consent
and runs. Providers without an EU DPA still run; each output carries
the Schrems II warning (AI_DPA_SIGNED=true silences it).
- HTTP 451 responses carry blockId into lib/config/regulation.ts.
GDPR surface:
- Profile "Privacy & data" card: AI consent toggle, one-click JSON
export of ALL user data (Art. 15/20), erasure request opening a
tracked thread + admin alert (Art. 17 vs the Swiss 10-year retention
duty — reconciled by a human, not a DELETE).
/regulation — the regulatory ledger: every gated feature with the exact
statutes, who passed them (institutions and named rapporteurs), what
they meant to protect, and who benefits in practice. Config-driven SSOT.
Verified in dev browser end-to-end both roles; 898 tests + build green.
Migration drizzle/0002 (additive + index swap, guard-compatible).
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Adds UUID_RE check at the top of every dynamic route handler ([id],
[goalId], [threadId]) so invalid param values return 400 instead of
causing a PostgreSQL type error (500). Adds badRequest() helper to
lib/utils/api-response.ts alongside the existing serviceUnavailable().
Test PARAMS fixtures updated to use valid UUIDs so all 798 tests pass.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Covers: /api/admin/patients/[id]/goals (GET + POST), /api/admin/patients/[id]/notes
(GET + POST, including admin-name lookup failure path), /api/admin/patients/[id]/profile
(PATCH with and without name — verifies users table update is skipped when no name
provided), /api/admin/goals/[goalId] (PATCH with completedAt set/clear logic, 404 on
empty returning, DELETE). All auth-guard, DB-failure, schema-validation, and success
branches covered.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
12 tests covering the three read-only admin and patient GET routes: auth guard
(401), DB failure (500), not-found (404 for the [id] route), empty-list, and
success with data. All three routes follow the same guard → query → respond
shape, so this completes the simple GET route coverage.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Move all business logic out of the 5 cron route handlers into pure,
injectable lib/workflows/* functions so they can be unit-tested without
spinning up a Next.js server
- Add runAfterResponse() util (wraps next/server `after`) to replace the
ad-hoc .then().catch() fire-and-forget pattern used across 9 API routes;
errors are now logged consistently and work is not dropped at request
lifecycle end
- Add 540 tests (5 new suites) covering cron workflows; fix vi.hoisted()
pattern so vi.mock factories don't hit the temporal dead zone
- Replace magic signal strings in patients page with PATIENT_SIGNAL constants
- Replace magic "pending" string in bookings page with BOOKING_STATUS.pending
- Replace hardcoded 30-day window in reports page with CHECKIN_DISPLAY_DAYS
- Extract duplicate streak-message inline IIFE in email templates to the
streakMessage() helper already in lib/domain/checkin (DRY)
- Add `pnpm typecheck` script to package.json
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Admin previously had a read-only view of patient profile data — no way
to correct or fill in clinical fields (medications, diagnoses, goals,
etc.) gathered during a consultation. Manuel had to ask patients to
update their own portal.
- New PATCH /api/admin/patients/[id]/profile endpoint: reuses
profileUpdateSchema and the same upsert pattern as the patient-side
/api/profile route; guarded with requireAdmin()
- New AdminProfileEditForm client component: pre-populated from current
profile; sections for Personal (name, DOB, phone, city, occupation,
referral), Clinical (concern, goals, diagnosis, medications,
supplements), and Lifestyle (sleep, exercise)
- Patient detail page: "Edit profile" section inserted between the
overview card grid and the log-booking form
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Two UX gaps where patients had no signal that something happened:
- Document upload: admin POSTs to /api/documents → patient now gets
"New document shared: <title>" email linking to /documents
- Programme assignment: admin PATCHes programme → patient gets enrolment
email with programme name, phase label, and phase description; fires
only on first insert, not on subsequent updates
Both sends are fire-and-forget (.catch logged) so API response is never
blocked. Adds newDocumentEmail + programmeAssignedEmail templates with
escaping and 8 new tests (360 total, 0 failures).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Completes the domain-schema consolidation pass:
- lib/domain/programmes.ts: new — programmeUpdateSchema (fixes magic 10
→ PROGRAMME_START_DATE_MAX_LENGTH constant added to lib/config/portal.ts)
- lib/domain/bookings.ts: new — bookingCreateSchema
- lib/domain/messages.ts: add replySchema alongside existing message utils
API routes now import from domain; no more inline z.object() definitions
in app/api/**. All routes thin; all validation logic has a single home.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
All 20 unprotected findFirst/findMany calls across API routes now return
structured { success: false, error } JSON on DB failure instead of
bubbling an unhandled rejection (which produces a raw 500 HTML page that
breaks JSON.parse on the client).
Security highlight: forgot-password user lookup now returns OK on DB
failure, preserving the anti-enumeration guarantee even when Neon is
unreachable.
Fire-and-forget reads (notification enrichment in bookings, messages,
notes) use .catch(()=>null) to stay non-blocking without crashing the
request. The mark-as-read update in messages/[threadId] GET is also
made fire-and-forget — a read-receipt failure shouldn't prevent the
thread from loading.
Also wraps the bookings/[id] PATCH mutation (was missing try-catch).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
DRY violation: wellnessAvg() (stress-inverted 5-metric average) was defined
identically in lib/domain/signals.ts and app/(admin)/admin/patients/page.tsx.
Now exported from signals.ts — its natural home — and imported in the admin page.
Magic numbers: max(5000) for patient note body and max(1000) for check-in notes
were hardcoded in API routes. Both now reference named constants
PATIENT_NOTE_MAX_LENGTH and CHECKIN_NOTES_MAX_LENGTH in lib/config/portal.ts.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Add USER_ROLE named-constants object and UserRole type to lib/config/auth.ts —
the SSOT for user role values. Replace every raw "patient" / "admin" string
comparison in auth, middleware, cron routes, API routes, admin pages, and the
UserDropdown component with typed USER_ROLE constants.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
goalCreateSchema and goalUpdateSchema were duplicated across two API routes.
Now both routes import from a single SSOT in lib/domain/goals.ts.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Remove unused imports/variables across API routes and admin/portal pages
- Wrap async data-load functions in useCallback to satisfy exhaustive-deps
- Fix ref mutation during render in Assessment (move to useEffect)
- Fix raw anchors to Next.js Link for portal routes in Nav and checkin page
- Extract Date.now() to const in dashboard page
- Disable react-hooks/set-state-in-effect and react-hooks/purity (v7 rules
too aggressive for async useCallback+useEffect data-loading pattern)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>