64 Commits
Author SHA1 Message Date
CatoandClaude ed5359a242 feat: every prose field is chatkit's DictationField (#190)
One app wrapper, components/shared/TextBox.tsx, around chatkit's
DictationField. Every textarea in the portal and the admin now uses it:
profile, clinical context, check-in notes, new message, booking notes,
cancellation reason, clinician bio, programme notes, clinical notes,
goal notes and admin profile edits. The two thread reply boxes (patient
and clinician) are now chatkit's Composer.

The microphone is off (voice={false}). These fields hold health data.
Without a transcribeUrl, chatkit falls back to the browser's speech
recogniser, which sends audio to the browser vendor, and AGENTS.md lets
health data go only to an EU/CH provider under a DPA. Turn it on in
TextBox once a consent-gated transcription route exists.

Textarea, compose-row and send-button CSS that nothing uses any more
is removed.


Claude-Session: https://claude.ai/code/session_019MDtmrZVd3q4PDcqQwfLT9

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-15 18:46:11 +01:00
d538a775b0 fix(nav): the admin overflow sheet was the one surface that stayed silent (#84)
The sidebar and the bottom bar both set aria-current. The "More" sheet did
not — so the destinations that happened to land behind the overflow were
precisely the ones a screen-reader user could not locate themselves in.
`isActive` and `pathname` were already in scope; the call was simply missing.

Two more defects on the same surface, both of which the rest of the app
already gets right:

- `.moreSheetItem` came out near 41px tall — 0.65rem of padding around
  0.85rem text at this root size. `.bottomNavItem` states `min-height: 44px`
  explicitly; the overflow sheet is the same kind of touch surface, so it now
  says the minimum instead of arriving near it by arithmetic.

- Hover and focus were one rule ending in `outline: none`, so keyboard focus
  was indicated by a 7%-white wash and nothing else: the weakest possible
  signal, on the surface where a keyboard user most needs to know where they
  are. Focus now gets a real ring; hover keeps the wash.

Found by a fleet-wide navigation audit across 20 repos, which found the same
one-straggler shape in aoz-housing, fleetcrown and evig — four teams applying
a rule correctly on every surface but one.

Typecheck clean; 1306 tests pass.


Claude-Session: https://claude.ai/code/session_01XeELB8b3N4JrT2asYL9WvE

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 07:29:45 +00:00
GandClaude Opus 5 3e059f0818 chore: add a formatter (#83)
* 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>
2026-08-29 10:48:01 +00:00
GandClaude Sonnet 5 0cd2d59723 fix(admin): clinician onboarding is owner-only now, and /admin/profile is two screens instead of five stacked cards (#65)
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>
2026-08-17 21:10:07 +00:00
GandClaude Sonnet 5 6fc4ac7086 feat(shell): notifications, grouped admin nav, admin mobile tabs, a working mega menu, and a real footer (#64)
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>
2026-08-17 20:19:48 +00:00
GandClaude Sonnet 5 0e04ec25e6 fix(admin): patient-facing copy shown to clinicians, a booking with no visible signal, and two real gaps in the patient record (#63)
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>
2026-08-17 14:05:23 +00:00
GandClaude Sonnet 5 9811bad941 feat(scheduling): real clinician profiles, working hours, calendar sync surfacing, and a clinician-application process (#62)
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>
2026-08-17 11:44:32 +00:00
GandClaude Opus 5 aef5071908 feat(bookings): a doctor who can close intake, and an assistant that can join a patient's own thread (#56)
Two real gaps, both already half-built.

DOCTOR CHOICE ALREADY EXISTED — CareTeamCard on the profile page, and
/api/care-team already let a patient pick without an admin round trip. What
was missing was the other half of that sentence: the doctor's own say. A
clinician could not signal "I am full right now", so the only way to protect
a calendar from new patients was for Manuel to manually turn people away.

profiles.acceptingPatients is self-service — a clinician sets their own,
nobody sets it for them, and there is no admin override route. Enforcement is
ONE function, canPatientChooseClinician(), called at both places a patient
actually chooses a doctor: adding them to the care team, and booking a first
slot with them. Two different doors, one rule, so "not accepting" means the
same thing at both.

The rule is deliberately narrow: closing intake protects a calendar from NEW
patients, and must never look like a doctor dropping someone mid-treatment.
An existing relationship — care-team membership, or ANY prior booking, even
one still pending — always continues. A dual-role clinician can always choose
themselves. A closed clinician is never hidden from the roster; hiding a
person reads as the clinic disowning them, and an existing patient must still
be able to find their own doctor in the list. Staff booking on a patient's
behalf may override — the clinic picking up the phone is the exception being
made, not a patient finding a workaround.

Surfaced everywhere the roster already renders: a "Not accepting new
patients" badge in warn tone (never danger — this is a normal practice state,
not a fault) in the care-team picker and the booking picker, the Choose
button disabled with the server's own reason as its tooltip, and the Confirm
button on a closed doctor's slot honestly relabelled rather than left to fail
after the fact.

THE AI ASSISTANT ALREADY EXISTED, on one side. #53 wired threadkit's model
seam into thread conversations — consent-gated, participant-visibility-scoped,
prompted to defer every clinical question — and put an "Ask assistant" button
on the ADMIN thread view. The API route was already generic (requireSession,
any participant may call it); only the patient's own thread page never grew
the button. "They all can brainstorm solutions together" needed the same
control on both sides of the same thread, not a new capability.

Mirrors the admin handler exactly: on demand only, posts into the shared
thread so the clinician sees precisely what the patient saw, and turns the
451 legal-gate response into an actionable note ("turn on AI in your privacy
settings") rather than a dead button.

Also: two definitions of "the clinician roster" existed (care-team.ts and
scheduling-data.ts) for different reasons — one needs email for availability
rules and orders by account age, the other doesn't. Not merged; both note the
duplication and the rule that would trigger unifying them (a third caller).
The checkbox-toggle CSS pattern DID have two definitions with no reason
(portal-only, needed on admin too) — moved to shared.module.css, both sides
compose from it now.

+19 tests. 1264 passing; build green. Migration 0011 is additive-only, one
boolean column.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 22:34:31 +00:00
GandClaude Opus 5 aafe0a7d41 feat(portal): patients can see their own numbers, and what to do if one frightens them (#45)
Labs and vitals existed only on the clinician's side. A patient could not see a
single measured value about themselves — which makes the whole measurement layer
something done TO them rather than with them, and quietly teaches that their
record is a thing kept from them.

/labs shows them the same rendering their clinician sees: the same intervals,
the same trend arrows, the same words. Deliberately the same component, because
a softened patient view would eventually disagree with the clinical one about
what a number means, and the one place that must never happen is a page showing
someone their own blood results.

They can add their own vitals, and only their own. A home blood-pressure cuff
produces better data than one reading taken in a consulting room by someone who
is nervous — that is real clinical value, not a toy. Laboratory results stay
read-only so the record always says who vouched for a number. The API already
enforced both; this page just renders the result.

EMERGENCY_CONTACTS FINALLY EXISTS SOMEWHERE. It has sat in config since the
regulatory work, rendered on no page at all, which is the same as not having it.
It now appears in two places chosen on purpose: beside a patient's own results,
where a number can frighten someone at eleven at night, and on the messages
page, where a patient in distress is most likely to be sitting. Saying plainly
that nobody is reading that inbox at 2am is not a disclaimer — it is the
difference between waiting for a reply and calling 144.

The same notice states the scope: this platform records and displays, it does
not diagnose, and a value outside an interval is not a diagnosis while one
inside it is not proof of health. That is the honest description of what the
software is, and it is also the thing that keeps a portal page from being
treated as a clinician on call.

Also: a subscribed calendar can correctly find NOTHING, and it looks exactly
like a broken parser. Google's holiday feeds mark every event TRANSP:TRANSPARENT
— holidays are informational and are not meant to block anyone's diary — so
subscribing one and seeing zero busy periods is right. Verified against the real
Swiss holiday feed: 160 KB, every VEVENT transparent, zero intervals; strip the
TRANSP lines from the same bytes and the parser finds them all. The UI now says
so instead of leaving a working subscription looking dead, and the parser
carries the note so nobody "fixes" it by ignoring TRANSP.

1217 passing; build green.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 12:55:02 +00:00
GandClaude Opus 5 3592f814f5 feat(bookings): the clinician's real calendar blocks slots here (#44)
Slot generation only knew about appointments booked inside VitaReBa. Anything
in a clinician's actual life — a school concert, a hospital rota, a conference —
was invisible, so the picker cheerfully offered patients hours their doctor was
already committed to. The first person to find out would have been the patient,
at the door.

A clinician pastes the private "secret address in iCal format" URL their
calendar app already publishes, and their real commitments start blocking slots.
No OAuth application to register, no vendor to depend on, nothing to pay, and it
works identically for Google, Apple, Outlook and Nextcloud.

READ-ONLY BY CONSTRUCTION. Nothing here can write to anyone's calendar.
VitaReBa's own appointments travel the other way, through the .ics invites
already attached to confirmation emails.

ONLY THE TIMES ARE STORED. Not titles, not guests, not descriptions. A
psychiatric clinic should not hold a mirror of its doctors' private lives in
order to avoid double-booking them, and the parser is written so it cannot.

THE DANGEROUS PART IS THE FETCH, and it looks like nothing. "The server fetches
a URL the user typed" is server-side request forgery: the request originates
inside the box, so it reaches the Postgres port, the cloud metadata service and
every other app on the host — none of which the internet can reach. An attacker
need not even see a reply; a calendar that "fails to parse" with 800 events has
already answered. So: https only (webcal is https wearing a hat), every resolved
address must be publicly routable, redirects followed by hand and re-checked at
every hop because a public host is free to redirect to 127.0.0.1, bounded bytes,
bounded time. 32 tests cover the closed side — loopback, all three private
ranges and their off-by-one edges, link-local metadata, CGNAT, IPv6 loopback and
IPv4-mapped IPv6, file:// and gopher://.

Busy time is CACHED, not fetched during slot generation. A network call on every
page load makes the picker slow, and a calendar host that is down would make the
clinic look completely free. A stale cache offers one slot that is taken; no
cache offers every slot that is taken.

Failure is per-calendar and fails SAFE: an unreachable feed keeps its previous
busy times rather than emptying them, because not reaching a calendar is not
evidence its owner is free. The error is recorded and shown, since a feed that
broke last week looks exactly like having no calendar at all.

The parser handles what real calendars actually contain: folded lines, TZID
wall-clock times, floating times (read in the clinic's zone, not UTC — reading
them as UTC frees hours nobody is free), all-day events, RRULE with INTERVAL /
COUNT / UNTIL / BYDAY, EXDATE, and the two properties that legitimately mean
free — TRANSP:TRANSPARENT and STATUS:CANCELLED. Unbounded rules are expanded
only within the horizon; a daily rule with no end is genuinely infinite. One
malformed event never costs the rest of the year.

Where the parser is unsure it errs toward BUSY. The asymmetry is the whole
design: a missed busy hour sends a patient to an empty room, an invented one
costs an unbooked slot.

External busy time is used without the appointment buffer. That buffer is time
the clinic reserves after its own consultations; someone's dentist appointment
already has whatever margin they gave it, and padding it would silently delete
two further bookable slots around every event in their life.

+75 tests. 1217 passing; build green. Migration 0009 is additive-only, two new
tables. Needs a systemd timer for cron/calendar-sync every 15 minutes.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 12:24:09 +00:00
GandClaude Opus 5 909c2b2896 feat(admin): the first screen answers the first question (#39)
/admin redirected to the patient list. A list sorted by a badge answers "how is
everyone" — a fine second question. The first one, at 08:00 on a Tuesday, is
"what needs me", and the product's own stated goal is that Manuel opens the
admin and knows without calling anyone. Most patients are fine; a page listing
all of them buries the four who are not.

Today is that page. Five sections, and the order IS the design:

  Results to review   urgent     a value past a recognised action threshold
  Patients to contact urgent     a critical signal
  Waiting on a reply  attention  a thread the patient wrote last
  Bookings to confirm attention  a request nobody has answered
  Next steps          routine    an attention signal — assessed but not booked

Anything routine placed above something urgent teaches the reader to scroll past
the urgent one, so only two sections are allowed to shout.

Decisions worth stating:

IT INVENTS NO SECOND OPINION. Who is critical is computePatientSignal, the same
function the patient list uses. Two definitions of critical in one product means
the list and the dashboard eventually disagree and the clinician trusts neither.
The only things added are the two questions the signal cannot answer: has a
measured value crossed a line that should not wait, and is a person sitting
there waiting for a reply.

OLDEST FIRST, EVERYWHERE. The newest item is still fresh in mind; the oldest is
the one already forgotten. Sorting newest-first buries exactly the wrong thing.

A STALE VALUE IS NOT AN ALERT. A blood pressure of 186 this week is today's
problem; the same reading from eighteen months ago is history, and shouting it
every morning is how the top of the screen stops being read. Results older than
180 days do not raise anything — if that is still the newest value, what is
needed is a repeat measurement, not an alert.

NOTHING IS TRUNCATED SILENTLY. Sections cap at eight and say how many more
there are. "8 shown" and "8 in total" must not look the same to someone deciding
whether they are done for the day.

AN EMPTY INBOX IS THE GOAL, NOT A BUG, and is designed as such rather than
rendered as a blank page.

Also fixed while here: getAdminUnreadThreadIds selected messages by
role=patient. A clinician who is also somebody's patient has role=admin, so
their messages were dropped from the badge entirely — undercounting exactly the
dual-role people care_team exists to support. It now asks the same question as
getAdminUnreadPatientIds: was the sender this thread's own patient.

+24 tests over the pure builder. 1092 passing.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 10:17:22 +00:00
GandClaude Opus 5 9b83539eab feat(clinical): a lab result you can watch move (#36)
A blood test could only enter this system as an uploaded PDF. That meant the
single most valuable thing a clinician does — watch a number move — was
invisible to the software. Ferritin from 18 to 62 looked exactly like two files
in a list.

Measured values are now first-class: typed, unitful, dated to when the sample
was TAKEN rather than typed, and comparable to a published reference interval.
39 markers, in the SI units Swiss laboratories report, from the blood pressure
and resting heart rate that stimulant treatment turns on to ApoB, hs-CRP,
ferritin, vitamin D and the omega-3 index.

Three judgements the software now makes, and the reasoning behind each:

REFERENCE INTERVAL IS NOT A TARGET, AND NEITHER IS A DIAGNOSIS. `ref` is where
most healthy adults sit; `optimal` is a narrower, guideline-backed goal, kept
separate and rendered separately. Presenting a target as a normal range would
mark healthy people abnormal at scale. Every interval states its source, and CI
fails if one does not — an interval printed beside a patient's own result is a
medical claim, and an unsourced one is an unsourced medical claim.

SEX CHANGES THE INTERVAL WHERE IT ACTUALLY CHANGES IT. Ferritin 20 µg/L is
unremarkable against the male interval and worth a conversation against the
female one. profiles.biological_sex is recorded for that one purpose, asked with
a label that says so, and when it is absent the range says it was not tailored
rather than guessing. Testosterone, whose intervals do not overlap at all,
declines to rate rather than merge them.

DOWN IS NOT ALWAYS BETTER. A TSH falling from 8 to 5 is a patient improving; one
falling from 2 to 0.2 is a patient getting worse. Markers judged by distance
from the interval are computed that way, and movement smaller than the assay's
own noise reads as "steady" instead of an arrow that means nothing.

Alerts stay rare on purpose: only where a recognised action threshold exists
(hypertensive crisis, resting HR outside 40–120, eGFR <30, ALT >3× ULN). A
signal that fires on ordinary findings is one nobody reads.

Access is one definition, not one per surface: patient, admin, or a clinician on
the care team. Anything else answers 404, never 403 — a 403 would confirm which
people are patients at a psychiatric clinic. A patient records their own vitals;
laboratory results enter under a clinician, so the record always says who
vouched for a number. Enforced in the API, because a form is a suggestion and an
API is the actual door.

Gates, all mutation-tested (a gate that has never failed is decoration):
  • interval with no source, optimal wider than normal, alert firing inside the
    reference interval, one-sided sex interval — 8 defects injected, 8 caught
  • profile-discipline: a schema field absent from a form. This exact defect
    (zod field never reaching the form, silently unsaved) has hit sibling repos
    three times; fixing it a fourth was not the job — ending the class was.

+69 tests, 1058 passing.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 08:49:18 +00:00
GandClaude Opus 5 d3ef867471 fix(db): erasure was still blocked — by the message the patient sent (#33)
Correction to the previous commit. It claimed documents.uploaded_by was the
only thing vetoing a patient's deletion. It was only the FIRST veto: Postgres
reports one constraint and stops, so fixing that one revealed the next.

  ERROR: update or delete on table "users" violates foreign key constraint
         "thread_messages_sender_id_users_id_fk"

I had put sender_id in the retained-authorship list, reasoning that a medical
record must keep its author. That reasoning is right for a note, a programme
assignment and a goal — only staff can write those, so they can never block a
patient's own erasure. It is wrong for a message, because a PATIENT is a sender
too. The rule ended up protecting the patient's data from the patient.

sender_id becomes nullable with SET NULL. Erasing a patient still removes their
messages — threads cascade on patient_id, messages on thread_id — so the null
case only arises for a deleted clinician's reply in a thread that survives,
where keeping the text with an unknown author beats deleting a patient's
clinical history. Membership in RETAINED_AUTHORSHIP now requires that only
staff can write the column, which is the property that actually matters.

Both thread views dereferenced msg.sender.role directly. Drizzle still types
the relation as non-null, so the compiler did not catch it — a deleted sender
would have thrown at render. Both now treat an authorless message as staff-side,
which is the only case that can reach a reader.

Verified on production rather than assumed: a throwaway patient that had
checked in, messaged, booked and uploaded a document now deletes cleanly.

pnpm verify green: lint, typecheck, 978 tests.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 11:11:09 +00:00
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
GandClaude Opus 5 be52705aa8 feat(clinic): book a named doctor, choose your provider, calendars that actually sync (#27)
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>
2026-08-14 01:26:32 +00:00
GandClaude Fable 5 2b10a18392 fix(ux): portal shell survives assessment, dual-role switching, tabbed patient record (#26)
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>
2026-08-13 20:31:55 +00:00
GandClaude Fable 5 5f3c21e5d1 feat(clinic): multi-doctor care, AI everywhere with legal warning labels, GDPR surface (#24)
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>
2026-08-13 15:06:41 +00:00
GandClaude Fable 5 daff9e2273 feat(bookings): native conflict-free slot booking — no Calendly, no paid SaaS (#23)
Patients can now book Manuel directly in the portal: pick a free slot,
instantly confirmed, double-booking structurally impossible. Fully
open-source and self-hosted — the dormant Calendly rail is removed.

- lib/config/scheduling.ts — SSOT for availability: weekly working
  windows (clinic wall time), slot length, buffer, lead time, horizon,
  per-day cap. Changing Manuel's hours = editing this file only.
- lib/domain/scheduling.ts — pure, injectable slot engine; timezone-
  correct via CLINIC_TIMEZONE (two-pass wall-time→UTC conversion, DST
  fall-back day-dedupe). 9 unit tests incl. CET/CEST regimes.
- bookings.scheduled_at + partial unique index on active bookings —
  the race between two patients picking the same slot is settled by the
  database, not application logic (23505 → 409 slot_taken). Additive
  migration drizzle/0001, auto-applied on deploy.
- GET /api/bookings/slots + slot path on POST /api/bookings: engine
  re-check → confirmed insert → patient confirmation + admin
  notification emails with the exact Zürich time.
- Bookings page: day tabs + slot grid picker (design-system native,
  44px touch targets), booked slot vanishes from the feed, 409 refreshes
  the list with a friendly message; manual request flow stays as
  fallback. Admin bookings + patient card show exact scheduled times.
- Calendly fully removed: webhook route + signature lib + tests,
  CALENDLY_URL config, banner. External calendar free/busy (CalDAV /
  Google) plugs into the engine's busy-interval input later.
- shared.module.css: mainWrap min-width:0 — first nowrap scroll row
  exposed the classic grid-track blowout on mobile.

Verified in-browser at 1280px and 390px: slot pick → confirm → banner →
list row; slot disappears; same-instant rebook returns 409; admin sees
"Mon 17 Aug, 09:45" under Confirmed; zero mobile overflow after fix.
pnpm verify green (886 tests) + production build green.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 13:42:55 +00:00
GandClaude Fable 5 45966a8e86 Design-token discipline with CI teeth + clinic-timezone dates + skeleton loading (#19)
* fix(ui): mobile patient table fits a 390px card

Walkthrough at 390px showed the triage table still ~50px wider than its
card: desktop cell padding, and the email ellipsis targeting a <p> that
is actually a <div> — plus max-width on the td, which auto table layout
ignores; the cap now sits on the inner divs.

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

* feat(design): token discipline with CI teeth, clinic-timezone dates, skeleton loading

Design discipline (SSOT enforced, not aspirational):
- Normalize every raw border-radius, transition duration, rgba() and hex
  in *.module.css to the globals.css token scale (26 files); add
  --radius-2xs (2px bars) and --radius-pill (2rem pills)
- lib/design-discipline.test.ts: 8 CI rules — no raw colors in css modules,
  radius/transition must use tokens, every var() must resolve in
  globals.css, no hex in TSX, style={{}} only in a data-driven allowlist
  (with staleness check)

UX intuition:
- formatDateISO now uses Europe/Zurich (CLINIC_TIMEZONE SSOT in
  lib/config/company.ts) instead of UTC: a 00:30 check-in no longer lands
  on yesterday's date, overwriting it and killing the streak; client and
  server now agree on 'today' even when the patient travels
- Shared <LoadingState/> shimmer skeleton (reduced-motion aware) replaces
  nine bare 'Loading…' strings across portal and admin

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 16:51:53 +00:00
g-butandClaude Sonnet 4.6 e46a28e441 refactor(css): move booking status badge colors fully into CSS
Replaces inline style={{ color: s.color, background: s.bg }} across 4 badge
callsites with className={s.badgeClass} referencing .booking-status-* globals.
Removes color/bg fields from BOOKING_STATUS_CONFIG — the JS config now has
no knowledge of colors. Status badge appearance is changed purely in globals.css.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 13:30:53 +02:00
g-butandClaude Sonnet 4.6 de145e3b38 refactor(css): replace scoreColor/profileCompletenessColor inline styles with global utility classes
Adds scoreClass() and profileCompletenessClass() helpers that return CSS
class names (.score-good/warn/bad, .pct-good/warn/bad) so color logic lives
in CSS, not scattered inline style props. Also fixes BOOKING_STATUS_CONFIG
to reference CSS variable tokens (--warn-12, --teal-12, etc.) instead of
inline color-mix() strings.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 12:17:08 +02:00
g-butandClaude Sonnet 4.6 65fb1e8a48 fix(ux): validate document file size client-side before upload
Previously, selecting a file larger than DOCUMENT_MAX_FILE_SIZE_MB
would silently start the upload and only fail after sending data to
the server. Now the onChange handler checks size immediately using the
SSOT constant, clears the input, and surfaces the error before any
network request is made.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 23:12:34 +02:00
g-butandClaude Sonnet 4.6 5d9f014988 test(storage): add 15 unit tests for safeSession* utilities + fix aria-labels
- lib/utils/storage.test.ts: 15 tests covering STORAGE_KEYS values, all
  three safe wrappers for happy path, missing key, and throw/unavailable
  cases (vi.stubGlobal for Node env compatibility)
- All four unread-dot spans gain role="img" + aria-label so screen readers
  announce them (title= alone is not announced by most AT)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 20:06:53 +02:00
g-butandClaude Sonnet 4.6 826fcfd606 fix(admin): strip empty name from patient profile PATCH to prevent Zod min(1) rejection
Same bug as the patient form — sending name: "" with z.string().min(1).optional()
blocks the entire PATCH. Strip it before sending so Zod's .optional() accepts it.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 13:07:11 +02:00
g-butandClaude Sonnet 4.6 b435d8aab9 feat(admin): allow admin to edit patient profile from patient detail page
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>
2026-04-27 09:30:54 +02:00
g-butandClaude Opus 4.7 9ad8e7bc08 fix(booking-status): show human label, not raw enum, on badges & in digest
Patient bookings page, admin PatientBookingsCard, and the weekly-digest
email all rendered b.status directly — the lowercase enum value
("pending" / "confirmed" / "attended" / "cancelled") instead of a
proper UI label. Patients saw "Your next consultation is pending" in
the email and "pending" badges in the portal.

Added a label field to BOOKING_STATUS_CONFIG (alongside the existing
color/bg) so labels stay in the same SSOT and never drift from
status values. Both card components read s.label; the weekly-digest
cron now resolves the label before passing it to the template.
Extended booking-status.test.ts with a regression that asserts no
label equals the raw enum and every label starts uppercase.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:36:06 +02:00
g-butandClaude Opus 4.7 4d8dbf9d9a fix(admin): goal progress bar fills correctly for descending goals
The admin patient-detail GoalProgressBar computed fill width as
max(0, currentPct − baselinePct), which renders zero width when
current < baseline — exactly the case for descending goals
("reduce stress 70 → 30"). Manuel saw a baseline marker and a
target dot but no fill, even when the patient was making real
progress.

Extracted the geometry to a pure goalBarGeometry() helper in
lib/domain/goals.ts that branches on direction:
  ascending  → fill from baseline → min(current, target)
  descending → fill from max(current, target) → baseline
Component is now a thin wrapper. 12 new unit tests cover both
directions + overshoot, regression, no-target, and null-baseline
fallback cases.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 17:57:15 +02:00
g-butandClaude Sonnet 4.6 f74310828a feat(admin): log manual bookings from patient detail page
Manuel had no way to record phone/in-person consultations in the system.
Without this, the signal engine would show 'attention — no booking' for
patients who actually have upcoming appointments, producing false alerts.

Changes:
- adminBookingCreateSchema: extends bookingCreateSchema with patientId
  (required) + optional status (defaults to confirmed)
- POST /api/bookings: admin branch uses patientId from body, defaults
  status to confirmed, skips admin notification, notifies patient with
  bookingConfirmedEmail (fire-and-forget); patient branch unchanged
- AdminBookingForm: inline form on patient detail — type, machine (if
  applicable), date, status (confirmed/attended), notes; toggles open
  behind "+ Log booking" button, resets on success
- Patient detail page: Log booking section between the grid and check-in
  trend

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 15:15:19 +02:00
g-butandClaude Sonnet 4.6 a0515a4921 refactor(ssot): centralize assessment goal metric label + rename stale variable
- Add ASSESSMENT_GOAL_METRIC_LABEL to lib/config/portal.ts alongside the key
- Remove duplicate string literal from goals/page.tsx and PatientGoalsCard.tsx
- Rename sixtyDaysAgoISO → historyStartISO in dashboard/page.tsx (110-day window)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 12:17:11 +02:00
g-butandClaude Sonnet 4.6 c641bf7e42 feat(admin): urgent patients badge on nav Patients link
The Patients link in the admin sidebar now shows an amber badge with the
count of patients whose stored signal is 'critical' or 'attention'. This
gives Manuel instant visibility without opening the patient list.

Uses lastKnownSignal from profiles (written by the nightly cron) — a
single fast table scan, no signal recomputation on every page load.
Badge color is var(--warn) amber to distinguish from the teal
messages/bookings badges.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 06:35:31 +02:00
g-butandClaude Sonnet 4.6 e7d6ac349a feat(admin): unread message indicators in patient detail messages card
When Manuel looks at a patient's detail page, unread messages from that patient now show a dot indicator on the thread row — same visual language as the admin messages list. No new data fetching: the messages are already loaded with senderId and readAt columns.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 02:40:43 +02:00
g-butandClaude Sonnet 4.6 f5a8e52194 fix(admin): show patient notes and referral source in profile card
Patients write 'Notes for Manuel' and referral source in their profile, but these were never displayed in the admin patient view — Manuel had no way to read them. Now shown in a Notes section at the bottom of the profile card, conditional on the fields being non-empty.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 02:38:32 +02:00
g-butandClaude Sonnet 4.6 9afed9de64 feat(admin): pending bookings badge in admin nav
Manuel now sees a badge on Bookings whenever there are pending booking requests — same pattern as the unread messages badge, same data freshness on each navigation.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 02:31:21 +02:00
g-butandClaude Sonnet 4.6 f33816f466 refactor(routes): use PORTAL/ADMIN_ROUTES prefix for all dynamic route links
Dynamic hrefs like /admin/messages/:id and /admin/patients/:id now use
ADMIN_ROUTES.messages and ADMIN_ROUTES.patients as prefixes, consistent
with the static route SSOT pattern applied across the codebase.

Affected: messages/page (portal), admin messages list, admin messages thread,
admin patients list, admin documents, InlineMessageCompose, PatientMessagesCard.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 01:02:34 +02:00
g-butandClaude Sonnet 4.6 b265c1062a refactor(goals): extract ASSESSMENT_GOAL_METRIC_KEY to SSOT in portal.ts
"overallScore" was hardcoded in PatientGoalsCard, goals/page, and cron/signals.
Now imported from lib/config/portal.ts as ASSESSMENT_GOAL_METRIC_KEY — one change point if the key ever changes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 21:50:45 +02:00
g-butandClaude Sonnet 4.6 a89b7b3705 fix(bookings): show booking type in PatientBookingsCard; fix email subjects for non-consultation bookings
PatientBookingsCard now renders bookingType + machineType label. PATCH route email subjects use actual booking type label (not hardcoded "consultation"). Portal type toggle uses BOOKING_TYPE_VALUES instead of inline array.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 21:36:34 +02:00
g-butandClaude Sonnet 4.6 fe844cf62c feat(admin): add metric select to goal form + display auto-update source
Goals have a metric field that the cron/signals job uses to auto-update
the 'current' value from check-in averages or assessment scores. The
form had no UI for it (metric was always null), so Manuel couldn't link
a goal to auto-update without direct DB edits.

Added a select dropdown (None / Assessment overall / Check-in: sleep/energy/
mood/focus/stress) derived from CHECKIN_METRICS SSOT. Active goals now
show "Auto-updated from: X" when metric is set.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 11:34:44 +02:00
g-butandClaude Sonnet 4.6 acecee4b4b feat(ux): add error boundaries + retry button to goals card
Error boundaries (Next.js App Router error.tsx) were missing across the
entire app — a DB failure or uncaught exception during page rendering
would show a blank screen instead of a recoverable error state.

- app/(portal)/error.tsx: catches errors thrown by portal pages; shows
  "Something went wrong" with Try again + Go to dashboard actions
- app/(admin)/error.tsx: same for admin pages; links back to /admin/patients
- app/global-error.tsx: root-level boundary for layout-level failures
  (must render its own <html> since root layout is bypassed)
- portal.module.css / admin.module.css: errorPage styles for boundaries
- PatientGoalsCard: replace "Please refresh" with inline Retry button,
  consistent with messages and bookings error state pattern
- admin.module.css: add goalRetryBtn style

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 09:48:01 +02:00
g-butandClaude Sonnet 4.6 8a1209ab32 fix(api): try-catch on bookings insert + SSOT/a11y polish
- Wrap db.insert in bookings POST with try-catch → 500 on failure (was
  unhandled bubble-up, last API route missing error handling)
- DocumentAddForm: add maxLength={DOCUMENT_TITLE_MAX_LENGTH} to title
  input; replace hardcoded 3000 timeout with SAVED_FEEDBACK_MS constant
- PatientGoalsCard: add aria-labels to Cancel (add form) and Save/Cancel
  (inline score edit row) buttons — each now names the goal being edited
- InlineMessageCompose: add aria-label to Cancel button

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 04:06:30 +02:00
g-butandClaude Sonnet 4.6 e5669386db fix(a11y): add context-specific aria-labels to list action buttons
Screen readers navigating lists of repeated buttons ("Confirm", "Cancel",
"✓ Done", "✕") had no way to distinguish which item each button acted on.

- PatientGoalsCard: "Mark complete", "Delete", "Reopen", and "Delete"
  (completed section) now include the goal title in aria-label
- admin/bookings: "Confirm" and "Cancel" per-row buttons now include
  the patient name/email in aria-label

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 03:33:29 +02:00
g-butandClaude Sonnet 4.6 e79a329aff fix(admin): add maxLength to AdminNotesForm and ProgrammeAssignmentForm textareas
Both admin note fields lacked maxLength enforcement on the client despite
server Zod schemas using PATIENT_NOTE_MAX_LENGTH. Now consistent.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 03:18:56 +02:00
g-butandClaude Sonnet 4.6 517bd65858 fix(forms): add maxLength to all text inputs matching server Zod bounds
Client-side maxLength was missing on 11 inputs across 5 files despite
server schemas already having .max() limits via portal.ts constants.
Users could type past the limit and only discover the error on submit.

- ProfileForm: 6 textareas (mainConcern, goals, diagnosisHistory,
  currentMedications, currentSupplements, notes) → PATIENT_NOTE_MAX_LENGTH
- checkin/page: notes textarea → CHECKIN_NOTES_MAX_LENGTH
- bookings/page: notes textarea → BOOKING_NOTES_MAX_LENGTH
- messages/page: subject input + body textarea → MESSAGE_*_MAX_LENGTH
- InlineMessageCompose: subject input + body textarea → MESSAGE_*_MAX_LENGTH

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 03:14:32 +02:00
g-butandClaude Sonnet 4.6 e27e4b033c refactor(goals): centralize title/notes max lengths as SSOT constants
GOAL_TITLE_MAX_LENGTH (300) and GOAL_NOTES_MAX_LENGTH (2000) added to
lib/config/portal.ts. goals.ts Zod schema and PatientGoalsCard.tsx
inputs now import from there — client maxLength and server validation
stay in sync automatically.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 03:05:35 +02:00
g-butandClaude Sonnet 4.6 d694067f43 fix(network,ssot): try/catch admin components + DOCUMENT_MAX_FILE_SIZE_MB constant
Network error handling:
- DocumentAddForm, ProgrammeAssignmentForm, InlineMessageCompose,
  AdminNotesForm all lacked try/catch — buttons stuck on network failure

SSOT fix:
- Added DOCUMENT_MAX_FILE_SIZE_MB = 20 to lib/config/portal.ts
- Upload route now derives MAX_BYTES from the constant instead of
  hardcoding 20 * 1024 * 1024
- DocumentAddForm label now reads the constant instead of 'max 20 MB'
  — changing the limit in one place updates validation + UI label

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 02:43:56 +02:00
g-butandClaude Sonnet 4.6 b17c55d724 a11y(admin): add aria-label to all unlabelled inputs in PatientGoalsCard
Goal add form (5 inputs/textarea) and inline score edit input relied
solely on placeholder text — not accessible to screen readers. Each
now has an explicit aria-label.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 01:51:47 +02:00
g-butandClaude Sonnet 4.6 3e2478a480 fix(admin): error feedback for PatientGoalsCard mutations + inline style → class
- handleAdd/handleUpdateCurrent/handleToggleComplete/handleDelete now
  show actionError on network failure instead of silently doing nothing
- setSaving(false) moved to finally block in handleAdd (was missing on error path)
- admin/patients: last-checkin cell colour uses conditional className instead
  of inline style={{}} (default td colour is already var(--ink2))

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 01:50:17 +02:00
g-butandClaude Sonnet 4.6 09524dac1a fix(a11y): add htmlFor/id pairs and aria-labels to unlabelled form inputs
- ProgrammeAssignmentForm: 4 standalone labels missing htmlFor — added id
  to all inputs/selects (prog-programme, prog-phase, prog-start-date, prog-notes)
- AdminNotesForm: textarea missing label — added aria-label="Clinical note"
- InlineMessageCompose: subject input and body textarea missing labels —
  added aria-label; also fixed missing type="button" on expand button
- portal messages/[threadId]: reply textarea — added aria-label="Message"
- admin messages/[threadId]: reply textarea — added aria-label="Reply"

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 01:27:45 +02:00
g-butandClaude Sonnet 4.6 5b3dfc66f7 fix(reliability): add try/catch/finally to PatientGoalsCard load
Was only calling setLoading(false) on success path — network errors
would leave the component stuck in loading state forever.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 01:20:37 +02:00
g-butandClaude Sonnet 4.6 a13a5fc5c7 refactor(types): centralise AssessmentRow type in lib/assessment/data.ts
Eliminated 2 local AssessmentResult type definitions with divergent shapes
(portal version allowed Date|string, admin version required Date with id).
Canonical AssessmentRow — supporting both Drizzle (Date) and API (string)
completedAt — now lives alongside the assessment constants and scoring logic.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 00:38:52 +02:00
g-butandClaude Sonnet 4.6 c8b95a1b1b refactor(routes): centralise portal and admin route strings in lib/config/routes.ts
Eliminated hardcoded route string literals ("/dashboard", "/checkin", etc.)
scattered across 14 files. PORTAL_ROUTES and ADMIN_ROUTES constants are now
the single source of truth for all URL paths.

Benefit: renaming a portal route now requires 1 file change (routes.ts) instead
of hunting string literals across navigation, breadcrumbs, dashboard cards,
assessment pages, and marketing CTAs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 00:29:28 +02:00