Commit Graph
13 Commits
Author SHA1 Message Date
CatoandClaude Opus 5 4802fe02df chore(lint): hold warnings at zero and ban stray console.log
Three small guards, one theme: a rule the repo already follows should be
enforced rather than remembered.

- `pnpm run lint` now runs with `--max-warnings 0`, so a warning fails the
  build instead of accumulating. The one outstanding warning is fixed first:
  /api/calendar/subscribe took a `Request` it deliberately never reads (the
  whole point of that route is that nothing on the request may decide where a
  calendar token is sent), so the parameter is gone and the comment says why.
- ESLint `no-console`, allowing `warn` and `error` — those are how a degraded
  state reaches the systemd journal on the box. The two existing `console.log`
  calls are genuine operator output (email provider unconfigured; orphaned
  files deleted) and move to `console.warn`, which is where an operator looks.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
2026-09-15 11:30:47 +02:00
ab2c2b0397 refactor(email): migrate transport to @bitbaum/mail-kit (#91)
Replace the bespoke Resend-SDK transport in lib/email/index.ts with the
fleet's shared @bitbaum/mail-kit. The app keeps its public seam
(sendEmail/isEmailConfigured/SendResult) and clinic defaults (reply-to
clinic inbox, DEFAULT_FROM_EMAIL fallback); the sandbox-sender and
placeholder-key guards now live in mail-kit. Email-queue cron sends pass
an idempotency key so a retried run cannot double-send. Removes the
resend dependency.


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

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-05 10:08:09 +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 Opus 5 721c30a177 fix(cron): say which thing is actually broken (#82)
/api/cron/emails returned {"error":"Database unavailable"} while the database
was fine — psql connects with the app's own DATABASE_URL and the schema has 25
tables. The route hardcoded one of the workflow's two possible errors, so an
email-configuration failure was reported as a database failure.

The log line beside it made the same mistake in the other direction: it said
"RESEND_API_KEY not configured" while the key was present, 36 characters and
correctly prefixed re_. isEmailConfigured() is false for TWO reasons, and the
second one — a sandbox sender, which is exactly the case the guard was written
for — announced the first.

Both now name the reason that applies. The guard itself is correct and stays:
refusing to mark a queue sent when the sender reaches nobody is the whole point
of it.

The underlying condition is unchanged and is an operator decision: RESEND_FROM
is a sandbox address, so no patient email can be delivered until a verified
domain is set.


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 09:40:49 +02: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 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 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 c7e5688e00 feat(cron): erase the file, not just the row (#34)
After deleting a probe patient on production, `documents` held 0 rows and the
box still held 2 medical files. delLocal() has existed since the local-storage
migration and was never called from anywhere — there is no delete route, so no
uploaded file has ever been removed under any circumstance.

Erasing a patient removes their document ROWS through the database cascade,
and a cascade cannot call application code. So the record disappears while the
medical file it named stays on disk forever. That is not erasure (GDPR Art. 17),
it is bookkeeping — and it is invisible, because the DB looks correct.

A reconciler is the only thing that can close this: it is the only part that
runs after the database has already decided what no longer exists. Daily at
03:00 it deletes stored files that no document row points at.

Direction is deliberate — it deletes files with no row, never rows with no
file. A row whose file is missing is a restore artefact, already handled at
read time with a 410; deleting that row would destroy the patient's history
instead of a leftover byte.

It also fails CLOSED: if the document read throws, it deletes nothing and
reports failure. An unreachable database returns zero rows, which reads as
"nothing is referenced" — the naive version would wipe every patient document
on the box. That case is the test I care most about in this commit.

pnpm verify green: lint, typecheck, 985 tests.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 13:33:41 +02: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 Fable 5 6c530594f8 fix(auth): honest email-failure handling — no more silent password-reset lockout (#21)
An unconfigured or failing email provider used to be invisible: forgot-
password answered "sent" with nothing sent (permanent lockout for the
user), cron marked queued emails as delivered, and reset-password errors
surfaced as raw English strings on localized pages. Now:

- lib/email: sendEmail never throws, returns { sent } | { sent, error },
  checks the Resend SDK's error return (it doesn't throw); new
  isEmailConfigured() gate.
- /api/auth/forgot-password: 503 with a translated "contact us at
  {email}" message when the provider is unconfigured — checked before
  any user lookup, so no account enumeration.
- /api/auth/reset-password: machine-readable error codes; the page maps
  invalid_token to a localized message plus a "request a new link"
  recovery action instead of echoing API English.
- cron-emails: unconfigured provider leaves the queue pending (retried
  next run); a provider send error marks the row failed instead of sent.
- messages/{de,en,fr,it}: unavailable + expiredError keys.

Verified in-browser at 390px and 1280px: forgot-password honest 503,
reset flow with bad token shows localized error + recovery link.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 11:19:32 +00:00
g-butandClaude Sonnet 4.6 626a0914b1 refactor(ssot): replace magic numbers with named constants
- Add DAYS_PER_WEEK and WEEKLY_DIGEST_STREAK_WINDOW_DAYS to lib/config/portal.ts
- Replace raw 7/14/90 offsets in cron-weekly-digest with those constants
- Replace hardcoded >= 100 in cron-emails with GOAL_PROGRESS_COMPLETE_PCT
- Replace streak threshold literals in email templates with CHECKIN_STREAK_MILESTONES

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 19:00:11 +02:00
g-butandClaude Sonnet 4.6 934c0a24e4 test(workflows): comprehensive coverage for cron-signals and cron-checkin-dip-alert
cron-signals (14 tests):
- DB failure returns error immediately
- Zero counts for empty patient list
- Alert on null→critical and active→critical transitions
- Alert suppressed when patient already known critical
- Profile updated on non-critical transitions, skipped when unchanged
- Multi-admin partial delivery still counts as alerted
- No admin emails: profile still updated, no alert sent
- Goal check-in metric: current updated but not marked complete below target
- Goal check-in metric: marked complete + patient+admin emails at 100%
- Goal assessment metric: marked complete at target score
- Goal skipped when current value unchanged
- Goal skipped when metric field is null
- Goal skipped when no assessment data exists for assessment metric
- Multiple patients processed independently

cron-checkin-dip-alert (10 tests):
- DB failure returns error immediately
- All patients skipped when no admin emails configured
- Patient skipped with fewer than CHECKIN_DIP_ALERT_DAYS check-ins
- Patient skipped when any check-in avg exceeds threshold
- Patient skipped when alert sent within cooldown window
- Alert fires and dipAlertSentAt persisted on first qualifying dip
- Alert re-fires after cooldown window expires
- All admin inboxes receive alert
- dipAlertSentAt not persisted when all emails fail
- Partial delivery counts as alerted

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 17:37:05 +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