Commit Graph
123 Commits
Author SHA1 Message Date
CatoandClaude Opus 5 614722b817 refactor(documents): one upload, whoever is uploading
A patient uploads their own lab results; a clinician uploads a report onto a
patient's record. Two forms, two skins — and two copies of the same upload: the
size pre-check, the FormData, the `data.success` handling, the "Uploaded ✓"
that fades after SAVED_FEEDBACK_MS, the reset of the file input, and a long
`accept=".pdf,.png,…"` literal typed out twice.

The pre-check is what made this worth doing. Refusing a file over
DOCUMENT_MAX_FILE_SIZE_MB *before* sending it is what stops a patient on a
phone pushing 40 MB up a mobile connection to be told no; a stale copy of that
rule would be invisible until someone's upload hung. The server enforces the
same limit — the client check is the courtesy, not the gate.

lib/hooks/useDocumentUpload.ts now owns all of it, and `patientId` is the whole
difference between the callers: the patient form omits it and the server files
the document against the signed-in user, which is why a patient cannot upload
onto someone else's record by editing a form. The portal's `router.refresh()`
rides along as `onUploaded`, since only its list is server-rendered.

DOCUMENT_ACCEPT moves to lib/config/portal.ts beside the other DOCUMENT_*
constants — it is configuration, not hook state.

Both forms keep their own markup, wording and placeholders; nothing rendered or
requested changes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
2026-09-15 11:52:00 +02:00
CatoandClaude Opus 5 3cd05b13e4 refactor(nav): one navigation, worn two ways
The patient portal and the clinician admin are the same product seen from two
sides, and their navigation was written out twice — right down to seven SVG
glyphs that were byte-identical copies (calendar, chat bubble, document,
person, bar chart, grid, two figures) and four near-identical render blocks.

That cost more than lines. Admin's overflow sheet once shipped without
`aria-current`, so exactly the destinations that fell behind "More" were the
ones a screen-reader user could not locate themselves in — a fix that had to
be remembered on one side only. A clinician who is also a patient crosses
between the two areas daily; an icon or an affordance that drifts on one side
reads as a different product on that side.

Now:
- components/nav/icons.tsx — one glyph per shape, named for the shape rather
  than the destination (IcoGrid, not IcoToday), and one shared 16px/1.5-stroke
  frame instead of eighteen copies of the same <svg> attributes.
- components/nav/NavSurfaces.tsx — NavSidebar and NavBottomBar render the
  anchor, the icon/label/badge order and the aria contract once. What actually
  differs stays with the caller: which routes, what they are called, which CSS
  module paints them, the portal's check-in dot, admin's urgent patient count
  and its "More" sheet (passed in as the bar's trailing slot).
- Admin's overflow sheet now builds its items from the same entries() as the
  sidebar, so the three surfaces cannot disagree about a label or a badge.

Behaviour and markup are unchanged — same classes, same aria-labels, same
wording on both sides.

CSS modules are typed as a plain string map, so the shared renderer reading a
misspelt class would have shipped `class="undefined"` rather than failing to
compile. components/nav/nav-styles.test.ts closes that: every class name the
renderer reads must exist in BOTH modules, neither nav may re-roll its own
<nav>, and neither may define an inline SVG icon again.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
2026-09-15 11:42:05 +02: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 Fable 5 8f8ca7076f fix(a11y): footer fine print above the AA floor (#67)
The footer's contact links measured 3.82:1 (white-40 on the dark
footer) at 12px — under the 4.5:1 floor for small text. The address
block and the emergency numbers share the same color on the same
background; emergency contact info is the last text that should sit
below the floor. All three move to --white-55 (existing token, ~6:1
here); hover states (white-80/90) stay distinct.

Found by the fleet-wide contrast sweep (dotfiles ui-defect-audit.mjs).
Other white-40 usages sit on unmeasured backgrounds and are left alone.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 13:18:55 +00:00
GandClaude Fable 5 83b87fd7aa feat(messages): consent-at-click for the assistant, one shared AskAssistant component (#66)
The 451 gate now says whose consent is missing (consentIsYours, decided
server-side — only the server knows whose consent it checked). The patient
gets an 'I consent — ask anyway' button; a clinician gets honest copy
(no_patient_consent) instead of a button that would record the wrong
person's consent and look broken.

Third call site of the ask-AI-handle-451 pattern → one shared component,
rendered outside the compose form so Enter never summons the assistant.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 12:30:16 +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 Sonnet 5 28107ba62a refactor(portal): shared page-header + dark-banner primitives, sharper type scale, split two god-files (#60)
UI/UX pass toward the SpaceX.ai reference (extreme type-scale contrast,
confident whitespace, high-contrast minimal chrome) while keeping the
existing Cormorant/teal/off-white brand character:

- .pageTitle sized up (2.2rem -> 2.6rem) with tighter line-height and
  letter-spacing; micro-labels (.pageEyebrow, .breadcrumb) tracked wider
  for sharper contrast against it.
- .btnSecondary's border strengthened from --border (a pale beige, barely
  visible until hover) to --ink2 — a ghost button needs an edge the eye
  registers.

Code-debt fixes (audited first, not guessed at):

- New PortalPageHeader component replaces ~11 hand-rolled title/subtitle/
  action blocks across every portal page. Two of them (goals, documents)
  were duplicating the block twice in the same file for their error vs.
  loaded state; goals' error-state title had also silently dropped the
  teal-italic-emphasis convention every other page uses. Both pages now
  render the header once, unconditionally.
- New shared darkBanner primitive family in shared.module.css consolidates
  dashboard's heroCard and assessments' savedBanner — two independent
  definitions of the same ink-card-with-eyebrow-title-body-links idea that
  had drifted (2rem vs 1.75rem/2rem padding, 1.8rem vs 1.6rem title). Also
  fixes a real contrast bug picked up in the merge: dashboard's link used
  --teal (3.50:1 on dark, below AA) instead of --teal-on-dark (5.01:1).
- New --gradient-ink token kills a hardcoded gradient literal duplicated
  identically in portal.module.css's sidebar and profile's hero card.
- dashboard/page.tsx imported portal.module.css as `shared`, colliding
  conceptually with the real app/shared.module.css one directory up while
  dashboard.module.css was `styles` — renamed to `portalStyles`.
- bookings/page.tsx (636 lines) split into ClinicianPicker, BookingHistoryList,
  and RequestBookingForm — the slot-picker/reschedule state machine (the
  riskiest part to move) stays in the page.
- ProfileForm.tsx (416 lines) split into PersonalFields, ClinicalContextFields,
  LifestyleFields and EmailPreferencesFields — pure renderers over the
  parent's single `form` state and `set()` helper, so there's still exactly
  one source of truth and one submit.

pnpm verify (1266 tests) and pnpm build both green.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 09:34:30 +00:00
GandClaude Sonnet 5 15a9f574f9 fix(brand): the actual wordmark still read VitaReBa (#59)
The rename to Vita covered config, copy and translations, but missed the
one hardcoded literal that renders on every page: Logo.tsx spelled out
"Vita" + accented "Re" + "Ba" directly, bypassing COMPANY.shortName
entirely. Caught live in the browser after the previous PR deployed.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 10:15:43 +02:00
GandClaude Sonnet 5 6504e6d65e feat(portal): a Care Team home, brand rename to Vita, and a blog (#58)
Patients had no dedicated place to see who treats them, switch clinicians,
or jump straight into messaging or booking with a specific doctor — that
lived as a small card buried on the profile page with no message/book
actions. New /care-team page (+ nav tab) centralizes it; the old profile
card is now a one-line link-out so the feature has a single home.

Message and booking pages accept ?to=/?clinicianId= so Care Team's
actions land pre-addressed instead of on whatever the picker defaults to.

Brand renamed VitaReBa -> Vita across all user-facing copy, config and
translations (de/en/fr). Left the live domain (vitareba.orangecat.ch),
the real HIN mailbox (vitareba@hin.ch) and deploy identifiers untouched —
those are infrastructure, not brand text, and renaming them is a separate,
riskier change.

Team roster: removed Jonas Montagna, added George as Chief Engineer.

assessment_results gains an additive assessmentType column (default
'inflection_edge') so a second instrument is a config entry, not a
migration.

New minimal blog (lib/blog/posts.ts SSOT, list + post pages, nav link)
with one post on why the platform is built the way it is.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 10:07:50 +02: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 0e354d4c3c fix(bookings): a booking card that answers "when", and a late rule that is fair (#55)
Five things, all of them the same underlying problem: the booking flow was built
for date-only requests and never revisited when real appointments arrived.

THE CARD BURIED THE ONLY THING ANYONE OPENS IT FOR. It read as one flat
sentence — "Consultation · Mon 17 Aug, 17:00 · George" — so WHEN had the same
weight as the word "Consultation", followed by "Requested 16/08/2026", a date
nobody has ever needed, in a different format, directly under the one that
mattered. It is now when → what and who → where, with the time set in the
display face, and the requested date is gone.

THE DASHBOARD DROPPED THE TIME ENTIRELY. It said "17 August 2026" for a 17:00
consultation, because the card's props were Pick<"status" | "preferredDate"> —
it could not see scheduledAt even when one existed, and no type error was
possible because the field was not in scope. Widening it made the compiler
point at the query, which had never fetched the clinician either.

THE DASHBOARD SHOWED THE WRONG BOOKING. It ordered by createdAt, so a patient
with a consultation on Monday and a vague request typed yesterday was shown the
request. "Your next appointment" now means the next appointment.

THREE DATE FORMATS ON TWO SCREENS. "17 August 2026", "Mon 17 Aug, 17:00" and
"16/08/2026", all describing the same kind of thing. formatAppointment() is now
the one way to write an appointment, and it formats in CLINIC time — the general
date helpers use the runtime's zone, which on the box is UTC, so a late
appointment rendered on the previous day.

"LESS THAN 24H AWAY · CANCELLING NOW IS RECORDED AS LATE" — permanently, under a
confirmed appointment, at a patient who had not asked to cancel anything. Two
separate faults:

  • It was NOISE. The policy belongs where the decision is made: it is already
    beside the confirm button when booking, and in the confirmation step when
    cancelling. A standing warning is just an alarm nobody switched on.
  • It was UNFAIR, and this is the real bug. Slots open 12 hours ahead while the
    notice window is 24, so an appointment booked for tomorrow evening is
    ALREADY inside the window the moment it is created. The patient books it and
    is immediately told cancelling would count against them, having never been
    offered a way to do better. "Late" now also requires that the booking existed
    long enough to have been cancelled in time. A rule that marks someone down
    for a choice the software never gave them is a bug wearing a policy.

MOVING AN APPOINTMENT COULD SILENTLY CHANGE THE DOCTOR. "Move" opened the picker
on whichever clinician it happened to be showing, not the one the appointment is
with — so moving a consultation with George could reassign it to Manuel the
moment a time was picked. It now opens on the right clinician, and says that
changing clinician is something you may do here, which the picker always allowed
and nothing ever mentioned.

+6 tests. 1243 passing; build green.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 18:42:39 +00:00
GandClaude Opus 5 07d2066c7f fix(a11y): teal as text on the dark band was 3.50:1 (#54)
The outlined CTA "DISCOVERY CALL BUCHEN" renders --teal on the dark page
at 3.50:1, below the 4.5 AA floor — and at 12px uppercase with 0.14em
tracking, which is the hardest thing on the site to read already.

--teal itself is not wrong. It is tuned to carry WHITE on top of it
(4.94:1) and works as a fill. The same colour AS text on dark is the
failing case. Lightening --teal would have fixed the text and broken the
fill: white-on-teal drops to 3.45:1 at the lightness the text needs.

Two roles, two tokens. --teal-on-dark (#3796a8) is 5.01:1 on the dark
page and is used only where teal has to be read rather than sat on.

Found by the fleet UI audit (dotfiles scripts/ci/ui-defect-audit.mjs).

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-16 16:46:10 +00:00
GandClaude Opus 5 43fdded9f3 fix(ux): what a walkthrough found that no test could (#49)
Six things, all found by using the product as a patient and then as a clinician,
none of them visible to a type checker or a test suite.

CONFIRMING A BOOKING SHOWED YOU NOTHING. The success banner and the new
appointment render below the picker, so on a laptop the only visible effect of
pressing "Confirm appointment" was a time quietly disappearing from the list —
which reads as a failure, not a booking. It now scrolls to the confirmation.

"CLINICIAN AREA" LANDED ON THE PATIENT LIST. Today exists now and is the first
thing in the nav; a list of every patient, most of whom are fine, answers "how
is everyone" when the question on arriving is "what needs me". Both switches —
the sidebar link and the user menu — now land on Today.

EMPTY URGENT SECTIONS STILL SHOUTED. "Results to review" rendered in red above
the words "No result is outside the range that can wait". A screen whose
alarming colour is present on a quiet morning is a screen whose alarming colour
means nothing. An answered section is muted.

"PREFERRED DATE" ABOVE AN AGREED TIME. That column header was true when every
booking was a date-only request. It now shows "Mon 17 Aug, 17:00" for real
appointments, so it says "When".

"1 OF THEM ARE READ AGAINST A SEX-SPECIFIC INTERVAL". Pluralised unconditionally.
Small, and it costs credibility on a page full of clinical numbers.

Verified live in the browser at each step, on both sides: booked a real
appointment, watched the slot disappear from availability, recorded a ferritin
of 20 µg/L and saw it render as "In range" with the honest caveat that the
sex-specific interval is not set, then removed it again.

STILL OPEN, deliberately not rushed here: a clinician can cancel an appointment
from the bookings table but cannot MOVE one — the Move control needs a slot
picker, which that page does not have. Building one hastily is how the last two
outages happened. It wants its own change.

1213 passing; build green.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 14:14:09 +00:00
GandClaude Opus 5 afec888102 fix(portal): one missing icon took down every page in the patient portal (#47)
The whole patient portal has been answering "Something went wrong" since #45.
Dashboard, check-in, messages, bookings, labs — all of it, for every patient.

PortalNav looks up an icon per route:

    const Icon = ROUTE_ICONS[href];
    ...
    <Icon />

ROUTE_ICONS was typed `Record<string, React.ComponentType>`. A Record keyed by
`string` accepts every key, and therefore PROMISES a component for keys it does
not contain. When #45 added /labs to PORTAL_NAV_GROUPS, the lookup returned
undefined, React was handed `<undefined />`, and answered "Element type is
invalid". PortalNav lives in the portal LAYOUT, so a single missing entry took
out every page beneath it at once.

Nothing caught it. tsc was satisfied — the type said any string was fine. The
1205 tests passed, because not one of them renders a component: there is no DOM
test environment in this project at all. The build succeeded, because the
failure only exists at render time. Adding a route to the nav was a one-line
config change that could not fail, right up until it took down the product.

The fix is the type. ROUTE_ICONS is now keyed by PortalRoute — the union of
PORTAL_ROUTES values — so a nav route with no icon is a compile error. Verified
by deleting the labs entry again: tsc now fails where it previously passed.

ROUTE_BADGE_KEYS gets the same treatment as Partial<Record<PortalRoute, …>>.
It is genuinely partial — most routes carry no badge — and saying so in the type
is different from leaving the key loose and hoping.

Also gives /regulation an icon. It has been in PORTAL_ROUTES the whole time and
would have crashed the portal identically the day anyone put it in the nav.

The remaining gap is honest and not closed here: NOTHING in this repo renders a
component, so "does the portal actually load" is not a question the test suite
can answer. That needs a DOM environment and a layout smoke test, and it wants
its own change rather than being bolted onto an outage fix.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 13:29:45 +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 7c7ef1cc8d feat(bookings): a patient can get out, and an appointment can move (#42)
Two things were true before this and neither should have been.

A PATIENT COULD NOT CANCEL A BOOKED APPOINTMENT. The self-cancel path accepted
only bookings still in `pending`, and every slot booking is created `confirmed`.
So the moment picking a time started working, everyone who picked one was stuck
with it — with no way out in the product at all. The same gate existed twice, in
the API and again in the button, which is why nobody noticed one of them.

NOTHING COULD BE MOVED, BY ANYBODY. There was no reschedule anywhere. The only
way to change a time was to cancel and rebook, which loses the appointment's
history and sends a patient two contradictory emails.

Both sides can now cancel and move. The rules are one pure function that the
API enforces and the button reads, so a control cannot offer something the
server will refuse.

THE POLICY: 24 hours' notice, and a late cancellation is RECORDED, NEVER
REFUSED. The reasoning is in lib/config/cancellation.ts and worth stating here.
A late fee needs stored card details and turns "I woke up unable to function"
into a bill — at a metabolic-psychiatry practice, the patients most likely to
cancel late are the ones it exists to help. Removing the button inside the
window does not produce attendance, it produces a NO-SHOW: the clinic finds out
at the appointment instead of the night before, and the patient learns the
portal is a thing that traps them. So cancelling is always possible, it says
plainly that it is late and that there is no charge, and the clinician sees it
flagged. A pattern of late cancellations is clinical information, not just an
accounting one.

The window is stated next to the confirm button when booking, not first met
while trying to cancel. A rule you discover at the moment it costs you is
experienced as a trap however reasonable it is.

RESCHEDULING NEEDED A REAL CALENDAR COUNTER. The .ics SEQUENCE was derived from
the booking's status, and moving an appointment does not change its status — so
the patient's calendar would have kept the old time forever and they would have
arrived on the wrong day having done everything right. bookings.revision is now
the counter, bumped on every change, with the old status table kept only as a
floor so nothing already published can appear to go backwards.

Details that matter:
  • Someone else's appointment answers 404, never 403 — a 403 confirms the id
    is real, which is a disclosure about another patient at this kind of clinic.
  • An appointment does not block its own move; the naive re-check treats the
    booking being moved as busy and refuses every reschedule.
  • Cancelling through the admin status button records the same shape as the
    patient's cancel button. One act, one kind of history.
  • Cancellation sends an .ics CANCEL. An email alone leaves a ghost entry that
    still buzzes the patient's phone on the day.
  • lateCancellation is STORED, not derived: it is a judgement made against the
    policy in force at that moment, and re-deriving it against a changed window
    would rewrite whether someone did the right thing two years ago.

+46 tests. 1130 passing; build green. Migration 0008 is additive-only.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 11:48:35 +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 1fd5e016ed refactor(design): one shared visual SSOT for portal + admin, config-driven nav (#22)
An audit found ~160 duplicated CSS rules across 11 module files: 8 re-
implementations of the card surface, 11 primary-button variants, 7
progress bars at 4 heights, the message thread byte-copied between
portal and admin, and eyebrow labels at 5 letter-spacings. Plus one real
bug: .booking-status-pending referenced --warn-12, which was never
defined — the badge background silently rendered transparent.

Now:

- app/shared.module.css — SSOT for every primitive portal and admin
  share: shell, page header, cards + variants, buttons, pills, Cormorant
  stat scale, progress bars, empty states, form basics, message thread,
  doc lists, error boundary. portal.module.css and admin.module.css
  re-export via cross-file composes (the forms.module.css precedent);
  page modules keep deltas only. Net -195 lines with the new layer
  included; every duplicated geometry now has exactly one definition.
- Design uplift riding on the shared layer: grouped sidebar with
  eyebrow labels + gradient, teal wash under a blurred sticky header,
  serif stat numerals on one scale, uniform tracked-uppercase buttons,
  one pill geometry, message bubbles as "mine = teal accent right,
  other = neutral left" on both portal and admin.
- Nav structure is config: PORTAL_NAV_GROUPS / PORTAL_BOTTOM_NAV /
  PORTAL_ROUTE_SHORT_LABELS in lib/config/routes.ts — PortalNav renders
  both navs from it; bottom-bar labels no longer hardcode copies.
- Tokens: --warn-12 defined (pending-badge bug), --shadow-xs,
  --z-sticky; raw z-indexes replaced with scale vars; the last inline
  scoreColor() style replaced by scoreClass + currentColor.
- design-discipline test: new globals.css self-check so an undefined
  var() referenced by a utility class can never ship silently again.

Verified in-browser at 1280px and 390px: all 8 portal pages, message
thread both roles, admin patients + thread; zero horizontal overflow on
mobile. pnpm verify green (905 tests) + production build green.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 12:21:02 +00:00
GandClaude 265d9a7013 feat(ux): mobile nav menu + above-the-fold hero CTA (#20)
On phones the marketing nav hid every action — no menu, no sign-in, no
CTA — and the hero filled the first screen with text alone. Now:

- Hamburger menu (<768px) with section links, the Inflection Edge CTA
  and Sign in / Dashboard; Escape closes it and body scroll locks while
  open.
- Hero dark panel gains mobile-only CTA pair (Take the Inflection Edge /
  Book Consultation) so the primary action sits in the first viewport.
- Hero subtitle tightened to one sentence in all four locales to cut
  reading load before the CTA.

Verified in-browser at 390x844: menu open/close, sign-in from menu,
login, forgot/reset password round-trip (old password rejected, new
accepted), and the guest assessment through to results + lead capture.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-12 12:40:52 +02: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
GandClaude Fable 5 433de2f8a9 One-shot usability: unbreak login, admin patient view, mobile admin (#16)
* fix(auth): unblock the public API surface — login was unreachable in prod

The middleware session-gated ALL of /api, so every anonymous endpoint
307-redirected to the login page: the NextAuth session + credentials
callback (login itself), registration, password reset, the assessment-
leads funnel, and the Calendly webhook. Signed-in traffic looked healthy,
so nothing caught it.

- PUBLIC_API_PREFIXES in lib/config/routes.ts (SSOT) — each listed
  prefix authenticates itself (NextAuth, HMAC signature, CRON_SECRET,
  or Zod-validated no-PII writes)
- gated /api paths now answer 401 JSON instead of an HTML login page
- new /api/health (fleet convention): 200 = app up + DB reachable
- route-auth-invariant.test.ts pins the class: every route under a
  public prefix must self-authenticate; every gated route must import
  a guard

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

* refactor: delete the dead unlocalized auth tree + audit fixes

next-intl (localePrefix: always) redirects /login -> /de/login, so the
app/(auth) tree never rendered — a full duplicate of the localized auth
pages, drifting separately (hardcoded English, stale styles). Deleted.
Its stylesheet WAS live (portal forms imported it): the shared form
primitives now live once in app/forms.module.css; auth.module.css
re-exports them via composes.

Also from the audit sweep:
- public/robots.txt deleted — it shadowed app/robots.ts, so the
  portal/admin/api disallow rules never shipped
- portal nav labels: one SSOT (PORTAL_ROUTE_LABELS) for PortalNav and
  NavBreadcrumb — breadcrumb was silently blank on /goals and
  /documents because the two copies had drifted
- global 404 now links to the public homepage, not the auth-gated
  dashboard
- manifest icons existed only as references: generated icon-192/512.png
  from the brand mark (404'd on every page load before)
- Google auth provider only registers when its env is configured
- dead SignOutButton component + create-next-app template SVGs removed
- drop package.json pnpm.onlyBuiltDependencies (moved to
  pnpm-workspace.yaml allowBuilds long ago; pnpm warned on every run)

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

* fix(ui): admin patient page 500, dead mobile CSS, and portal polish

- schema: documents<->users is doubly connected (owner + uploader); the
  unnamed primary relation made Drizzle throw at query time and the
  admin patient-detail page — the core clinical view — 500'd in prod.
  Both sides now carry relationName. lib/db/relations.test.ts plans a
  query over EVERY declared relation so the next misconfigured relation
  (this was the second) fails in CI, not in prod.
- admin.module.css: the entire mobile @media block sat BEFORE the base
  rules it overrides (appended later), so phones got the desktop layout
  — 4-across stat tiles clipping their labels, oversized title, no
  form-grid collapse. Block moved after its base rules;
  lib/css-order.test.ts now fails any stylesheet where a base rule
  shadows an earlier @media override.
- proxy: admins landing on /dashboard (post-login default, PWA
  start_url) are redirected to /admin/patients — they were dropped into
  the empty patient portal.
- check-in scale: hovering the button just clicked painted the number
  teal-on-teal (.scaleBtn:hover outranked .scaleBtnActive)
- admin assessment-trend chart plotted newest-first — time axis read
  right-to-left; reversed to chronological
- sidebar wordmark was ink-on-ink (only 'Re' visible): Logo gains a
  'bright' on-dark variant, used by portal + admin sidebars

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 20:06:17 +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 47791754f1 refactor(css): centralise all design tokens — eliminate color/shadow/font SSOT violations
• Expanded globals.css :root with full opacity scales:
  - White (--white-3 through --white-97) for dark-background sections
  - Primary/teal (--teal-6 through --teal-70) via color-mix so --teal cascades
  - Gold (--gold-6 through --gold-70), danger, warn, muted opacity scales
  - Shadow scale (--shadow-sm/md/lg)
  - Border radius (--radius-xs through --radius-full)
  - Transition timing (--transition-fast/normal/slow)
  - Z-index scale (--z-nav, --z-overlay, --z-overlay-pb, --z-overlay-close)
• Replaced every #fff → var(--white) across 28 CSS module files
• Replaced every rgba(255,255,255,X) → var(--white-X) across all dark-context files
• Replaced every rgba(42,122,138,X) teal → var(--teal-X) across all section/portal files
• Replaced every inline color-mix() in admin/portal/section files → named tokens
• Fixed hardcoded "DM Sans" font in not-found.module.css → var(--font-dm-sans)
• Replaced box-shadow rgba(0,0,0) values with --shadow-* tokens in Nav, UserDropdown, LanguageSwitcher
• global-error.module.css left intentionally self-sufficient (renders outside root layout)

Changing --teal to any colour now cascades to all opacity variants site-wide.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 11:52:32 +02:00
g-butandClaude Sonnet 4.6 8991034445 feat(nav): goals badge shows count of new goals added since patient last visited
Adds a goals_seen_at timestamp to the profiles table. The layout fetches
active goals created after that timestamp to compute a badge count passed
to PortalNav and BottomNav. Visiting the goals page upserts goalsSeenAt
to clear the badge. Badge is suppressed client-side while already on
the goals route.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 22:03:47 +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 b5e457877c refactor(ssot): centralize sessionStorage keys and fix magic strings
- New lib/utils/storage.ts: STORAGE_KEYS constant + safe safeSessionGet/Set/Remove wrappers (eliminates scattered try/catch blocks)
- Add COMPANY.partnerBrand for "Surf Your Life" brand name — Footer.tsx uses it instead of hardcoded string
- Fix email plural grammar: password reset expiry now renders "hour"/"hours" correctly
- All 5 consumers (Assessment, ResultsScreen, PendingAssessmentSaver, both register pages) import from the single SSOT

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 19:12:11 +02:00
g-butandClaude Sonnet 4.6 05922c29ed feat(assessment): fully translate Inflection Edge overlay into de/fr/it
All 30 questions, 5 dimension names, 15 interpretation tiers, 4 verdict
tiers, and all UI strings now live in messages/*.json (SSOT for i18n).

The Assessment components use useMessages() from next-intl so the overlay
renders in the visitor's marketing-site locale (de/en/fr/it). The portal
/assessment page gets an English-only NextIntlClientProvider via a new
nested layout — portal has no locale routing; English is the safe default.

data.ts gains i18nKey on VerdictTier and getInterpretationKey() helper;
existing English fields and getInterpretation() stay intact for portal
pages, admin, and cron/email routes that don't need translation.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 18:22:24 +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 bc866de55d fix(i18n): locale-preserving navigation across marketing nav & auth flow
Same class of bug as the prior ResultsScreen fix, three more places:

  1. components/sections/Nav.tsx — the marketing "Sign in" link used
     NextLink (raw next/link) so /de/ → /login (English) instead of
     /de/login. Switched to the locale-aware Link (next-intl).

  2 & 3. app/[locale]/(auth)/login & register — both pages imported
     useRouter from next/navigation (raw) but useSearchParams + Link
     from next/navigation + @/lib/i18n/navigation respectively. Inside
     /de/login, router.push(`${AUTH_ROUTES.login}?returnTo=...`)
     pushed to /login (English) on the post-register sign-in nudge.
     Switched useRouter to @/lib/i18n/navigation so it stays inside
     /de/.

  4. app/[locale]/(auth)/reset-password — same useRouter swap so the
     post-reset push to /login keeps the visitor on /de/login.

Together with c8a430d (auth-page footer tagline), 1519877 (per-locale
title/description), c6dff54 (per-locale OG image), 5d77d3a (<html lang>
from URL not cookie) and the ResultsScreen fix, the marketing-site
visitor's chosen locale now survives every step from /de/ through to
account creation without dropping into English.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 11:05:47 +02:00
g-butandClaude Opus 4.7 e3edf4a4f2 fix(assessment): preserve marketing locale on the post-overlay register CTA
ResultsScreen's "Save results + book a call" CTA used a raw <a href=
"/register">, so a German visitor on /de/ who completed the overlay
landed on the English /register page instead of /de/register —
breaking language context exactly when the conversion is most fragile
(score on screen, intent peaking, decision being made).

Now reads the current locale from usePathname() — if the first
segment matches a routing.locales entry, the CTA targets
/${locale}${AUTH_ROUTES.register}; otherwise falls through to the
canonical AUTH_ROUTES.register (covers the portal /assessment context
where there's no locale prefix). Marked the file "use client"
explicitly since it now holds a hook.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 10:55:27 +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 ed51e1c4e5 feat(portal): check-in reminder dot in sidebar and mobile nav
Show a pulsing teal dot on the Check-in nav item (both sidebar and mobile
bottom bar) when the patient hasn't logged a check-in today. Dot hides
when already on the check-in page or when today's entry exists.

Adds one lightweight DB query (findFirst with two equality filters) to
the portal layout, which runs on every portal page load regardless.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 13:44:50 +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