Commit Graph
23 Commits
Author SHA1 Message Date
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 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 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 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 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 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 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 2fb657105a fix(api): validate UUID route params to prevent 500 on malformed IDs
Adds UUID_RE check at the top of every dynamic route handler ([id],
[goalId], [threadId]) so invalid param values return 400 instead of
causing a PostgreSQL type error (500). Adds badRequest() helper to
lib/utils/api-response.ts alongside the existing serviceUnavailable().
Test PARAMS fixtures updated to use valid UUIDs so all 798 tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 08:44:32 +02:00
g-butandClaude Sonnet 4.6 7ee94c9ace refactor(ssot): extract serviceUnavailable() helper and standardise displayName usage
- Add lib/utils/api-response.ts with serviceUnavailable() — replaces 17
  identical NextResponse.json({error: "Service unavailable..."}) call sites
- Replace all patient.name ?? "there" / patient.name ?? patient.email fallbacks
  with displayName() — the existing utility already handles these cases
- Merge duplicate @/lib/config/routes imports in bookings/route.ts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 19:39:56 +02:00
g-butandClaude Sonnet 4.6 4cbdd5ffaa refactor(api): extract cron logic to lib/workflows, standardise fire-and-forget
- Move all business logic out of the 5 cron route handlers into pure,
  injectable lib/workflows/* functions so they can be unit-tested without
  spinning up a Next.js server
- Add runAfterResponse() util (wraps next/server `after`) to replace the
  ad-hoc .then().catch() fire-and-forget pattern used across 9 API routes;
  errors are now logged consistently and work is not dropped at request
  lifecycle end
- Add 540 tests (5 new suites) covering cron workflows; fix vi.hoisted()
  pattern so vi.mock factories don't hit the temporal dead zone
- Replace magic signal strings in patients page with PATIENT_SIGNAL constants
- Replace magic "pending" string in bookings page with BOOKING_STATUS.pending
- Replace hardcoded 30-day window in reports page with CHECKIN_DISPLAY_DAYS
- Extract duplicate streak-message inline IIFE in email templates to the
  streakMessage() helper already in lib/domain/checkin (DRY)
- Add `pnpm typecheck` script to package.json

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 17:05:46 +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 a579c237e3 test(domain): add tests for normalizeCheckinMetric, streakMessage, relativeDate, sparkLevel
Cover the four functions extracted from components in the prior commit:
- normalizeCheckinMetric: boundary values (1→0, 5→100), midpoint, fractional rounding
- streakMessage: each milestone tier (0/1, 2, 3-6, 7-13, 14-29, 30+)
- relativeDate: today, yesterday, N-days-ago cases
- sparkLevel: low / mid / high threshold boundaries per SPARKLINE config

Test count: 133 → 153 (+20)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 09:31:38 +02:00
g-butandClaude Sonnet 4.6 ea4a5fe43b refactor(domain): move business logic out of components into canonical homes
- lib/domain/checkin.ts: add streakMessage() — milestone thresholds (30/14/7/3/2
  days) are domain decisions, not UI copy; page now imports instead of defining
- lib/utils/format.ts: add relativeDate() — was duplicated in admin/patients page;
  formatting utilities belong here alongside other date helpers
- lib/domain/signals.ts: add sparkLevel() — wellness categorisation using
  SPARKLINE thresholds belongs in signals domain next to wellnessAvg()
- admin/patients page: remove all three local function defs, clean unused imports
- admin/reports page: replace magic -7 with SIGNAL_CHECKIN_WINDOW_DAYS

No behaviour change — same logic, now in testable, single-homed modules.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 09:26:40 +02:00
g-butandClaude Sonnet 4.6 09ef9dfa55 refactor(config): eliminate magic numbers and duplicate UUID regex
- lib/config/auth.ts: add PASSWORD_RESET_TOKEN_MAX_LENGTH and
  RESET_TOKEN_IDENTIFIER_PREFIX ("reset:") so the token schema cap and
  identifier prefix have a single source of truth
- auth routes: import and use both new constants (4 occurrences of
  hardcoded "reset:" prefix replaced)
- lib/utils/validate.ts: export UUID_RE so routes don't each define their
  own copy of the same regex
- documents routes (GET + upload): import UUID_RE instead of local re-def

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 09:06:37 +02:00
g-butandClaude Sonnet 4.6 999a3045ce test(format): add 6 tests for displayName utility
Covers name priority, email-local-part fallback, null/undefined name,
null email with default fallback, and custom fallback string.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 02:06:37 +02:00
g-butandClaude Sonnet 4.6 41506a3363 refactor(dry): extract displayName() utility, replace 5 inline fallbacks
The pattern `name ?? email.split("@")[0]` appeared in 5 cron routes
with slight variations (optional chaining, different fallbacks). Extracted
to lib/utils/format.ts displayName(name, email, fallback="there") and
replaced all occurrences.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 02:05:17 +02:00
g-butandClaude Sonnet 4.6 5d19bae7ac fix(config): last VitaReBa strings in email templates; add format.ts tests
lib/email/templates.ts: 4 remaining hardcoded "VitaReBa" text strings in
email body copy (password-reset, welcome, weekly-digest, checkin-reminder)
now use COMPANY.shortName. Every non-HTML-design brand reference now derives
from lib/config/company.ts.

lib/utils/format.test.ts: 19 tests covering all 6 exported date utilities
(formatDateShort, formatDateLong, formatDateNumeric, formatDateTime,
formatDateMonthDay, formatDateISO) plus HOUR_MS and DAY_MS constants.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 23:51:25 +02:00
g-butandClaude Sonnet 4.6 99fac8df4f refactor(format): add formatDateMonthDay utility; eliminate all inline toLocaleDateString calls
Add formatDateMonthDay() to lib/utils/format.ts for compact chart axis labels
("2 Apr"). Replace inline toLocaleDateString in assessments page, checkin page,
admin patient detail page, and admin documents page with the shared utility.
Also fix remaining USER_ROLE string literals in portal/admin layouts and
message thread pages.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 22:36:07 +02:00
g-butandClaude Sonnet 4.6 c4dbf247d7 refactor(utils): centralize formatDateISO, DAY_MS, HOUR_MS in lib/utils/format.ts
- Add formatDateISO(), DAY_MS, HOUR_MS exports to lib/utils/format.ts
- Remove 10+ inline .toISOString().slice(0,10) expressions across 8 files
- Remove 4 inline (24*60*60*1000) magic numbers across 5 files
- Remove local dateStr() function from weekly-digest/route.ts
- Remove local dayMs constant from lib/domain/signals.ts
- Remove private HOUR_MS/DAY_MS from lib/config/email-sequences.ts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 14:52:29 +02:00
g-butandClaude Sonnet 4.6 785b923e25 feat(ui): portal nav overhaul, clinical goals UI, check-in, accessibility + readability fixes
Navigation & layout:
- PortalNav: icon sidebar with 4 groups, active state with teal left border
- BottomNav: fixed mobile bottom tab bar (5 items, safe-area-inset-bottom)
- NavBreadcrumb: route-aware header breadcrumb
- UserDropdown: escape key close, aria-expanded ring, quick check-in link

Portal features:
- Check-in page: 1-10 scale for mood/energy/sleep/stress
- PatientGoalsCard: admin goal CRUD with progress bars
- Dashboard: active clinical goals section
- ProfileCompletenessBar uses profileCompletenessColor()
- Admin patient detail decomposed into card components

Accessibility & readability:
- html font-size 112% - raises all rem values ~12% site-wide
- --muted darkened to #71727c (WCAG AA 4.5:1 on white)
- Hero eyebrow 0.6rem to 0.72rem, pill 0.58 to 0.68rem, sub contrast fixed
- Nav links 0.68 to 0.75rem
- LanguageSwitcher: pill container, mobile visible (was hidden), 0.62 to 0.72rem
- scaleBtn min-height 2.75rem (44px touch target)

Hero fix: .heroR justify-content flex-end (was center) aligns both columns

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-15 11:00:05 +02:00