Commit Graph
300 Commits
Author SHA1 Message Date
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 ca12b1de21 fix(account): close check-then-insert race in registration
POST /api/account looked up the email, then inserted — two concurrent
requests with the same new email both passed the findFirst, then one
won the unique-constraint race and the other returned a generic 500
"Registration failed". The user behind the losing request couldn't
tell their email was just registered (e.g. by themselves on another
device) vs a real backend issue.

Kept the up-front check (so we avoid the bcrypt cost in the common
case where the email is already known to exist), but hardened the
insert with onConflictDoNothing({ target: users.email }) and check
inserted.length === 0 — the racing loser now surfaces as the same 409
the up-front check returns, with the same { email: ["Email already
registered"] } error body the form already handles.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 10:45:02 +02:00
g-butandClaude Opus 4.7 58654c2de6 fix(auth): apply brute-force lockout to change-password currentPassword check
/api/auth/change-password verified the current password but had no
counter and no lockout — an attacker with session access (XSS, stolen
cookie) could enumerate the current password against this endpoint
forever and use it for credential stuffing on other sites, even though
they already had session access locally.

Now the endpoint loads the user's failedLoginAttempts + lockedUntil,
short-circuits with 429 if locked, and on a wrong currentPassword
runs the same nextLoginAttemptState() transition that gates /login —
so the same 5-attempt threshold and 15-min cooldown apply uniformly
to every credential-verification surface in the app. The success path
already cleared the lockout (earlier commit) so legitimate change
flow is unaffected.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 10:37:27 +02:00
g-butandClaude Opus 4.7 3e83d32df2 fix(cron/signals): count alerts per patient transition, not per admin recipient
cron/signals incremented `alerts++` inside the per-admin Promise.allSettled
result loop, so 1 patient going critical with 3 admins reported
{ alerts: 3 } in the response body. Made the cron's observability
number meaningless — Manuel checking the day's run could not
distinguish "3 patients went critical" from "1 patient with our 3
admins on the distribution list".

Now the per-admin loop logs failures only; alerts increments once
per critical-transition iff at least one admin send succeeded.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 10:27:06 +02:00
g-butandClaude Opus 4.7 db27e398d1 fix(company): lowercase + dedupe ADMIN_EMAILS to stop double-emailing
getAdminEmails() trimmed entries but did not lowercase or dedupe. A
misconfigured env var like "manuel@x.com, MANUEL@x.com" would send
two copies of every admin notification (booking request, dip alert,
critical signal, profile completion) to the same person. It also
left case-sensitive entries that drifted from the new lowercase-on-
input policy applied to user records by emailField().

Now: lowercase each entry then deduplicate via Set while preserving
first-occurrence order. 9 new unit tests cover unset / empty / single
/ list / whitespace / empty-entries / case-mixed / dedupe / order.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 10:18:04 +02:00
g-butandClaude Opus 4.7 dfce84317c chore(ssot): replace magic 110/0/100 in cron & leads with named constants
cron/checkin-reminder hardcoded `setDate(now - 110)` for the streak
look-back window — same value as CHECKIN_HISTORY_DAYS in lib/config/portal.
A future change to that constant on the dashboard would silently drift
from the cron, leading to mismatched streak counts in the reminder
email vs the patient's portal view. Wired to the SSOT.

assessment-leads/route.ts validated overallScore with min(0).max(100) —
matches ASSESSMENT_SCORE_MIN/MAX from lib/assessment/data.ts. Same
problem if the score range ever changes (e.g. 0–10 normalisation).
Wired to the SSOT.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 10:09:10 +02:00
g-butandClaude Opus 4.7 4f4e3504b8 fix(dashboard): keep pendingAssessment on transient API failure
PendingAssessmentSaver removed sessionStorage.pendingAssessment in
both .then() and .catch(), so any 5xx response or network blip on the
new patient's first dashboard load silently destroyed the assessment
scores they had just produced as a guest. From their perspective:
"I took the assessment, registered, and now my results are gone."

Now: clear only on success or on a permanent 4xx (validation/auth —
retry won't help). Keep on 5xx and network errors so the next dashboard
mount gets another shot.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:58:02 +02:00
g-butandClaude Opus 4.7 91d40ead81 fix(auth): lowercase emails on input so case differences can't fork accounts
users.email is unique but case-sensitive at the DB level. Without a
normalisation step, registering as "Alice@x.com" and "alice@x.com"
created two distinct accounts, and a user who registered as
"Alice@x.com" couldn't log in as "alice@x.com" (or vice versa).

Added a reusable emailField() Zod schema in lib/domain/auth.ts that
validates RFC format, enforces EMAIL_MAX_LENGTH, and .transform()s
to lowercase. Wired into loginSchema, registerSchema, and the
forgot-password / reset-password schemas. The Calendly webhook now
also lowercases the inbound invitee email before lookup so a patient
registered as "alice@x.com" still matches a Calendly booking
submitted as "Alice@x.com".

8 new unit tests pin the lowercase transform across local part,
domain, and combined cases plus loginSchema/registerSchema flow.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:48:05 +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 2af49c6c4c fix(assessment): validate scores against the SSOT dimension list
POST /api/assessment used z.record(string, number) for the scores
payload, which accepted any object with arbitrary string keys. A
client could submit { "garbage_key": 50 } or only one of the five
dimensions, polluting the JSONB column and breaking downstream
renderers (charts and the assessmentResultsEmail template loop over
DIMENSIONS — missing keys would render as undefined).

Extracted the schema to lib/domain/assessment.ts where it builds itself
from the SSOT DIMENSIONS list and is .strict() (rejects unknown keys).
Adding or renaming a dimension in lib/assessment/data.ts now
automatically updates the validator. Removed the now-unused
ASSESSMENT_SCORE_KEY_MAX_LENGTH constant. 16 new unit tests cover
boundary scores, missing dimension, unknown key (regression), wrong
type, only-one-dimension, plus full assessmentSaveSchema flow.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:21:19 +02:00
g-butandClaude Opus 4.7 aa98691b0a fix(auth): clear brute-force lockout on password reset & change
A user who tripped the 5-failed-login lockout (15-min window) and then
recovered via the password-reset flow would still be denied on their
next sign-in, with no explanation. From their perspective: "I just
reset my password, why doesn't it work?"

Both reset-password and change-password now also zero failedLoginAttempts
and clear lockedUntil in the same UPDATE — knowing the new password
proves the user is the account owner, so any prior failed-attempt
streak shouldn't follow them into the next session.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 18:54:47 +02:00
g-butandClaude Opus 4.7 6d73efc290 fix(bookings): return 404 instead of 500 when patching unknown booking ID
PATCH /api/bookings/[id] declared `updated` as `typeof bookings.$inferSelect`
(non-nullable) and assumed Drizzle's .returning() always yielded a row.
When the WHERE matched nothing (stale ID, deleted booking), .returning()
returned [] → updated became undefined → the email-notification block
crashed on `updated.userId` and surfaced as an opaque 500.

Same pattern as app/api/admin/goals/[goalId]/route.ts: type the var
as `| undefined`, check `!updated` after the try/catch, return 404.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 18:44:44 +02:00
g-butandClaude Opus 4.7 b6bfaeb4d8 fix(checkin): reject future dates and guard streak from existing future rows
The checkinSchema only validated date *format* (YYYY-MM-DD), not range.
A POST with a future date would silently succeed, then computeStreak()
— which sorts DESC and short-circuits on the first non-match against
"today" — would see the future row first and report streak = 0,
wiping the patient's real streak for clinical reporting.

Two-layer fix: schema-level refine() rejects any date past today
(server-side UTC), and computeStreak() filters future-dated records
before its scan as defense in depth against any pre-existing rows
that bypassed the (newer) guard. UI never sends future dates so
this costs nothing UX-wise.

8 new unit tests: 3 for the streak filter (future row above today,
only-future, mixed past/future) and 5 for the schema (today,
yesterday/backfill OK; tomorrow, far-future, malformed rejected).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 18:35:04 +02:00
g-butandClaude Opus 4.7 d3af4b1aaa fix(webhooks): reject stale Calendly signatures (replay protection)
The Calendly webhook computed HMAC over "<timestamp>.<rawBody>" but
never validated the timestamp itself. An attacker who captured one
valid webhook (leaked log, MITM on a misconfigured edge, etc.) could
replay it indefinitely to create duplicate booking rows or revive
canceled state.

Extracted verifyCalendlySignature() to lib/webhooks/calendly-signature.ts
so it is testable without spinning up an HTTP request, and added a
±5-minute timestamp tolerance check (matches Stripe's default and
Calendly's own documentation). Stale-future timestamps are also
rejected as a clock-skew abuse mitigation. The expensive HMAC
computation now runs only after the cheap timestamp check.

17 new unit tests cover every reject path (missing key, missing
header, malformed header, wrong body, wrong key, malformed hex,
stale, far-future) and every accept path (fresh, within tolerance,
small clock skew, exact boundary).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 18:24:17 +02:00
g-butandClaude Opus 4.7 b15f42fd0e fix(auth): close open-redirect via returnTo in login & register
All four auth pages — (auth)/login, (auth)/register and their locale
variants — read ?returnTo from the URL and pass it directly to
router.push(). An attacker could craft
https://vitareba.ch/login?returnTo=https://evil.com/phish so that a
user who signs in is silently sent to a phishing site under
attacker control.

Centralised parsing into sanitizeReturnTo() in lib/domain/auth.ts.
Allows only same-origin paths starting with a single `/`; rejects
absolute URLs, protocol-relative `//evil.com`, Windows backslash
`/\evil.com`, `javascript:` / `data:` schemes, bare relative paths
and empty/null/undefined. Fallback is the route caller already
intended (PORTAL_ROUTES.dashboard).

15 new unit tests pin every attack vector and the legitimate
relative-path / nested-path / query-string / hash-fragment /
locale-prefixed cases.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 18:13:11 +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 Opus 4.7 5ff2f700f9 fix(cron/signals): correct goal-achievement detection for descending goals
The signals cron used liveValue >= goal.target to detect first-time
goal achievement. That works for ascending goals (focus 30 → 75) but
incorrectly fires at the baseline for descending goals (stress 70 → 30,
where 70 >= 30 trivially). The result would be a false "Goal achieved"
email to admin and patient on the very first cron run after the goal
was set.

Switched to computeGoalProgress() which already handles both directions
correctly via the ((current − baseline) / (target − baseline)) * 100
formula, then checks progress >= GOAL_PROGRESS_COMPLETE_PCT. Added 5
new unit tests pinning down descending-goal behavior across baseline,
midpoint, target-reached, overshoot, and worsened cases.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 17:45:27 +02:00
g-butandClaude Opus 4.7 59dcabc5ce feat(i18n): localized 404 page for /[locale]/* unmatched routes
German visitors hitting a broken /de/* URL now see "Seite nicht
gefunden" with a "Zurück zur Startseite" link routed back to /de
(not the global English "Page not found" → /dashboard which made no
sense for an unauth marketing visitor).

Implementation: app/[locale]/not-found.tsx + a [locale]/[...rest]
catch-all that calls notFound() (next-intl's recommended pattern —
without the catch-all, Next.js bubbles unmatched routes up to the
global root not-found.tsx). New notFound.{title,body,cta} keys in
all four locale message files. Verified via curl across de/en/fr/it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 17:30:02 +02:00
g-butandClaude Opus 4.7 c6dff54a7b feat(seo): per-locale OpenGraph image
When German visitors share a /de/ page on social media, the preview
card now shows the German tagline ("Metabolische Psychiatrie &
Systemische Longevity") instead of English. Same for French and
Italian.

Extracted the shared OG render to lib/og/element.tsx (so both the root
English fallback and the new per-locale image render the same layout
with only the tagline string differing). The new app/[locale]/
opengraph-image.tsx generates on demand at the edge from the existing
meta.tagline translation key.

Verified via curl: each locale emits a distinct PNG (file sizes differ
by tagline length); /de page metadata correctly references
/de/opengraph-image; Next.js auto-emits hreflang link headers across
locales with x-default pointing to the root.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 17:14:57 +02:00
g-butandClaude Opus 4.7 c8a430d5d6 fix(i18n): localize auth-page footer tagline
The locale-prefixed auth pages (/de/login, /fr/login, etc.) were
showing the English tagline "Metabolic Psychiatry & Systemic
Longevity · Zürich" below a localized form — visibly wrong for
German visitors arriving from the marketing nav. Now reads from the
existing meta.tagline translation key per locale.

Verified via curl on /de, /en, /fr, /it /login pages: each renders
its own tagline.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 16:56:30 +02:00
g-butandClaude Opus 4.7 8fc0a1018c chore(seo): drop dead keywords meta, noindex portal & admin layouts
The keywords meta tag has been ignored by Google since 2009 and was
hardcoded English regardless of locale. Drop it. In its place add
robots: noindex,nofollow to the portal and admin layouts as defense
in depth alongside the existing robots.txt disallow — so accidental
indexing (Vercel preview URLs, leaked links) is prevented at the
page-meta level too.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 16:48:41 +02:00
g-butandClaude Opus 4.7 5d77d3a9e5 fix(seo): set <html lang> from URL locale, not from cookie
Cookies are absent on first visit and never sent by crawlers, so the
old cookie-based locale read in app/layout.tsx caused every search-
indexed /en, /fr and /it page to advertise lang="de". Middleware now
extracts the locale from the URL pathname and injects it as the
x-vita-locale request header (post-processing the next-intl response
so it survives both NextResponse.next and rewrite paths). Root layout
reads that header and validates it against routing.locales.

Verified end-to-end via curl: /de/, /en/, /fr/, /it/ (and locale-
prefixed auth pages) now each return the correct <html lang>.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 16:37:13 +02:00
g-butandClaude Opus 4.7 1519877e59 feat(seo): localized title, description and OG metadata per locale
Generates locale-specific <title>, <meta description>, openGraph and
twitter tags from new meta.tagline + meta.description translation keys
in de/en/fr/it. German visitors (default locale, primary market) now
get German meta tags instead of the hardcoded English fallback in the
root layout. OG locale is mapped to Swiss variants (de_CH, fr_CH, it_CH)
where applicable. Brand name and city stay in COMPANY config (SSOT).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 16:17:17 +02:00
g-butandClaude Opus 4.7 20acfb9126 feat(auth): lock account after 5 failed login attempts
Adds users.failed_login_attempts + users.locked_until columns and
enforces a 15-min lockout in the Credentials authorize() handler.
Counter resets on successful login or when the lockout fires. Locked
accounts are denied silently (same null return as a bad password) to
prevent enumeration. Pure helpers in lib/domain/auth.ts cover state
transitions; 9 new unit tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 16:08:03 +02:00
g-butandClaude Opus 4.7 3662d978f2 refactor(email): extract pure row-builders for testability
Split enqueueAssessmentEmails/enqueueWelcomeEmails into pure
buildAssessmentEmailRows/buildWelcomeEmailRows + thin DB wrappers.
Adds 16 unit tests covering sequence ordering, delays, payload shape,
and first-vs-retake branching — no DB required.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 15:58:54 +02:00
g-butandClaude Sonnet 4.6 dd1915dcab feat(admin): add KPI overview cards to patient list page
Manuel now sees 4 at-a-glance stat cards above the patient table:
- Critical (red when non-zero) — patients needing immediate attention
- Attention (amber when non-zero) — patients worth a follow-up
- Checked in today — N/total + adherence % for the day
- Unread messages (amber when non-zero) — patient replies waiting

Data is derived from the existing patient query with one extra parallel
call for unreadThreadCount — zero additional DB round-trips for signal
counts and today's adherence (computed in a single O(n) pass).
Accent CSS classes (.statCardValueDanger, .statCardValueWarn) added to
admin.module.css.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 20:31:50 +02:00
g-butandClaude Sonnet 4.6 f878f4ab2c fix(ux): add progress indicator to check-in form when not all metrics filled
Previously the submit button silently disabled (opacity 0.45) when any
metric was unset, giving patients no signal about what was blocking them.

- Track filledCount alongside allFilled; derive inProgress (some but not all)
- While in-progress, unfilled metric labels get a trailing · in warn colour
  so patients can spot the missing rows at a glance
- Below the submit button, show "N / 5 metrics filled — select a value for
  each one above" when not all done; disappears once complete

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 20:09:49 +02:00
g-butandClaude Sonnet 4.6 3770c021da feat(admin): show programme assignment in patient list
Add programme + phase column to /admin/patients table:
- Fetch programmeAssignment relation alongside existing patient data
- Display programme name (Edge Diagnostic / Riding the Wave / Full Ocean)
  with phase pill badge (Intake / Assessment / Planning / Active / Review /
  Completed) — colour-coded by phase significance
- Patients without an assignment show — consistent with score column
- Add .progName and .phasePill[data-phase] CSS classes to admin.module.css

Manuel can now see each patient's clinical programme status at a glance
without navigating to the detail page.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 19:55:05 +02:00
g-butandClaude Sonnet 4.6 d3f947403b feat(admin): unread message dot on patient list
Adds getAdminUnreadPatientIds() — a single JOIN query that returns all
patient IDs with unread messages. Shown as a teal dot in a new "Msg"
column on the admin patients table, so Manuel sees at a glance who needs
a reply without navigating to the messages page.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 17:38:51 +02:00
g-butandClaude Sonnet 4.6 19e795bec2 fix(auth): rate-limit forgot-password to prevent email bombing
Uses the existing verificationTokens table to infer token creation time
(created ≈ expires − EXPIRY_MS). If a token exists and was created within
RESET_RATE_LIMIT_MS (2 min), silently returns OK without resending.
No new infrastructure required — works across all Vercel instances.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 17:21:43 +02:00
g-butandClaude Sonnet 4.6 7a67db3821 test(domain): add adminBookingCreateSchema tests
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 15:50:13 +02:00
g-butandClaude Sonnet 4.6 8782f9d014 feat(digest): include active clinical goal progress in weekly email
The weekly patient digest now includes a goal progress table alongside
check-in averages. Each active goal with current + target values is shown
with a named title, percentage bar, and current→target values. This closes
the feedback loop — patients see that their daily check-ins are directly
moving their clinical goals forward.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 15:46:43 +02:00
g-butandClaude Sonnet 4.6 86f81c67b7 feat(cron): notify patient on clinical goal achievement
When cron/signals detects a first-time goal achievement it now fires two
emails: the existing admin alert (goalAchievedAdminEmail) and a new
patient-facing congratulation (goalAchievedPatientEmail). The patient
email closes the feedback loop — their daily check-ins and assessments
moved the metric, and they hear about it directly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 15:36:40 +02:00
g-butandClaude Sonnet 4.6 711d30f71c feat(cron): auto-complete goals and notify Manuel on first achievement
When the daily signals cron auto-updates a goal's current value and it
reaches or exceeds the target for the first time (completedAt IS NULL),
the cron now:
  1. Merges completedAt = now into the same DB write (one round-trip)
  2. Fires a goalAchievedAdminEmail to all ADMIN_EMAILS (fire-and-forget)

The guard (completedAt IS NULL) ensures the notification fires exactly
once per goal — subsequent cron runs see the goal as already completed
and the clinicalGoals query already filters them out (WHERE completedAt
IS NULL). The response payload gains a goalsCompleted counter.

Adds goalAchievedAdminEmail template with escaping + 4 tests (364 total).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 15:25:10 +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 39cd9238ab fix(messages): notify on new thread creation, not just on replies
POST /api/messages created threads silently with no email notification.
A patient opening a new thread would not reach Manuel unless he happened
to check the admin panel; admin opening a thread for a patient left the
patient unaware.

Now mirrors the existing reply-notification pattern in /api/messages/[threadId]:
- Patient → admin: notifies all ADMIN_EMAILS with sender name + subject
- Admin → patient: notifies the patient with clinician name + deep link to thread

Both sends are fire-and-forget (.catch(console.error)) so the API response
is never blocked. No new templates needed — reuses newMessageEmail.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 14:59:17 +02:00
g-butandClaude Sonnet 4.6 08854eadcd feat(notifications): email patients when document uploaded or programme assigned
Two UX gaps where patients had no signal that something happened:
- Document upload: admin POSTs to /api/documents → patient now gets
  "New document shared: <title>" email linking to /documents
- Programme assignment: admin PATCHes programme → patient gets enrolment
  email with programme name, phase label, and phase description; fires
  only on first insert, not on subsequent updates

Both sends are fire-and-forget (.catch logged) so API response is never
blocked. Adds newDocumentEmail + programmeAssignedEmail templates with
escaping and 8 new tests (360 total, 0 failures).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 14:39:41 +02:00
g-butandClaude Sonnet 4.6 8cedccc8b8 perf: use count() for assessmentLeads funnel and thread count queries
Replace findMany/select-id-then-length patterns with SQL count() in
reports (assessmentLeads conversion funnel) and dashboard (threadCount).
Consistent with earlier count() fixes for nav badges and community stats.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 14:26:32 +02:00
g-butandClaude Sonnet 4.6 ed07e19b1d feat(admin): urgency-based secondary sort within signal tiers
Within each signal tier, patients are sub-sorted by urgency so Manuel
sees the most time-sensitive cases first. Urgency values: critical silent
= days since last check-in, critical declining = 50, critical score drop
= magnitude of drop, attention no assessment = days since registration,
attention no booking = 10, attention follow-up = days since attended.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 14:16:32 +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 949bf105e4 perf(admin): use count() for nav badge queries + remove redundant checkin empty state
- Replace findMany+length with count() for pending bookings and urgent
  patient badges in admin layout — fires on every admin page load, so
  avoiding full row hydration matters
- Remove redundant "Complete your first check-in" empty state card on the
  checkin page; the form is already visible above it, making the card
  pure noise for new patients

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 13:31:40 +02:00
g-butandClaude Sonnet 4.6 79bcd2055e fix(dashboard): filter stale bookings + use count() for community stats
- latestBooking now only returns pending/confirmed — patients whose last
  booking was attended/cancelled would see stale status in the consultation
  card with no prompt to rebook (same fix applied to weekly-digest in 2fa7290)
- replace findMany+.length for community check-in counts with count()
  — avoids fetching full rows just to measure cardinality
- fix <a> → <Link> for patient navigation in admin bookings page

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 13:23:06 +02:00
g-butandClaude Sonnet 4.6 6debcf155f feat(portal): no-dead-end UX for bookings empty state + consolidate empty action CTA
Bookings page empty state now has "Request a booking →" that opens the form
inline — completing the flow for patients arriving via Goals/Documents CTAs.

Consolidates four near-identical emptyCta/emptyBtn CSS definitions into a
single .emptyAction class in portal.module.css (works for both <a> and <button>).
Removes the duplicated definitions from goals, documents, messages, and bookings
module CSS files.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 13:08:03 +02:00
g-butandClaude Sonnet 4.6 40c1259e96 perf(reports): run all DB queries in parallel with Promise.all
Five of the six DB queries on the reports page were executing sequentially
despite being entirely independent. Wrapping them in a single Promise.all
cuts page latency by the sum of the four slowest serialised round-trips.
Post-query computation (signalCounts, tierCounts, populationTrend, etc.)
is unchanged — moved to after all data is available.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 13:00:43 +02:00
g-butandClaude Sonnet 4.6 e41b08f250 feat(portal): add booking CTA to empty states on Goals, Documents, Messages
No dead ends — every empty state now has a clear next step.

Goals: "Book a consultation →" since goals are set after first consultation.
Documents: "Book a consultation →" since docs accumulate as work progresses.
Messages: "Send a message →" button opens the compose form inline, surfacing
the existing + New message flow directly from the empty state.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 12:54:13 +02:00
g-butandClaude Sonnet 4.6 2fa7290976 fix(weekly-digest): only show pending/confirmed bookings as next consultation
Bookings query was fetching the most recent booking regardless of status.
Patients who had completed or cancelled their latest booking would see
"Your next consultation is attended" in the weekly digest email — confusing
and inaccurate. Filter to pending/confirmed only so the booking section
is omitted when there is no upcoming appointment.

Also replace raw <a href="/admin/patients/..."> in reports page adherence
table with <Link> + ADMIN_ROUTES.patients for SSOT consistency (same URL
was already using ADMIN_ROUTES on line 332 of the same file).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 12:46:56 +02:00
g-butandClaude Sonnet 4.6 a3add5b5ad fix(security): escape HTML in email templates to prevent injection
User-supplied strings (patientName, patientEmail, senderName, subject,
notes) were interpolated directly into HTML email bodies without escaping.
A patient with a name or thread subject containing < > & could inject
arbitrary HTML into admin email clients.

Added escapeHtml() helper and applied it to all user-controlled inputs
across all 16 template functions. Added 13 tests verifying that <script>,
<b>, & and similar characters are correctly escaped in output.

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

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 12:17:11 +02:00
g-butandClaude Sonnet 4.6 14008dfef9 fix(cron): rename stale sixtyDaysAgoISO → historyStartISO in checkin-reminder
Variable was named for the old 60-day window; renamed to reflect the current
110-day history fetch. Logic unchanged — just removes misleading name.

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