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>
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>
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>
The Patients link in the admin sidebar now shows an amber badge with the
count of patients whose stored signal is 'critical' or 'attention'. This
gives Manuel instant visibility without opening the patient list.
Uses lastKnownSignal from profiles (written by the nightly cron) — a
single fast table scan, no signal recomputation on every page load.
Badge color is var(--warn) amber to distinguish from the teal
messages/bookings badges.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When Manuel looks at a patient's detail page, unread messages from that patient now show a dot indicator on the thread row — same visual language as the admin messages list. No new data fetching: the messages are already loaded with senderId and readAt columns.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Patients write 'Notes for Manuel' and referral source in their profile, but these were never displayed in the admin patient view — Manuel had no way to read them. Now shown in a Notes section at the bottom of the profile card, conditional on the fields being non-empty.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Manuel now sees a badge on Bookings whenever there are pending booking requests — same pattern as the unread messages badge, same data freshness on each navigation.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Dynamic hrefs like /admin/messages/:id and /admin/patients/:id now use
ADMIN_ROUTES.messages and ADMIN_ROUTES.patients as prefixes, consistent
with the static route SSOT pattern applied across the codebase.
Affected: messages/page (portal), admin messages list, admin messages thread,
admin patients list, admin documents, InlineMessageCompose, PatientMessagesCard.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
"overallScore" was hardcoded in PatientGoalsCard, goals/page, and cron/signals.
Now imported from lib/config/portal.ts as ASSESSMENT_GOAL_METRIC_KEY — one change point if the key ever changes.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
PatientBookingsCard now renders bookingType + machineType label. PATCH route email subjects use actual booking type label (not hardcoded "consultation"). Portal type toggle uses BOOKING_TYPE_VALUES instead of inline array.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Goals have a metric field that the cron/signals job uses to auto-update
the 'current' value from check-in averages or assessment scores. The
form had no UI for it (metric was always null), so Manuel couldn't link
a goal to auto-update without direct DB edits.
Added a select dropdown (None / Assessment overall / Check-in: sleep/energy/
mood/focus/stress) derived from CHECKIN_METRICS SSOT. Active goals now
show "Auto-updated from: X" when metric is set.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Error boundaries (Next.js App Router error.tsx) were missing across the
entire app — a DB failure or uncaught exception during page rendering
would show a blank screen instead of a recoverable error state.
- app/(portal)/error.tsx: catches errors thrown by portal pages; shows
"Something went wrong" with Try again + Go to dashboard actions
- app/(admin)/error.tsx: same for admin pages; links back to /admin/patients
- app/global-error.tsx: root-level boundary for layout-level failures
(must render its own <html> since root layout is bypassed)
- portal.module.css / admin.module.css: errorPage styles for boundaries
- PatientGoalsCard: replace "Please refresh" with inline Retry button,
consistent with messages and bookings error state pattern
- admin.module.css: add goalRetryBtn style
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Wrap db.insert in bookings POST with try-catch → 500 on failure (was
unhandled bubble-up, last API route missing error handling)
- DocumentAddForm: add maxLength={DOCUMENT_TITLE_MAX_LENGTH} to title
input; replace hardcoded 3000 timeout with SAVED_FEEDBACK_MS constant
- PatientGoalsCard: add aria-labels to Cancel (add form) and Save/Cancel
(inline score edit row) buttons — each now names the goal being edited
- InlineMessageCompose: add aria-label to Cancel button
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Screen readers navigating lists of repeated buttons ("Confirm", "Cancel",
"✓ Done", "✕") had no way to distinguish which item each button acted on.
- PatientGoalsCard: "Mark complete", "Delete", "Reopen", and "Delete"
(completed section) now include the goal title in aria-label
- admin/bookings: "Confirm" and "Cancel" per-row buttons now include
the patient name/email in aria-label
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Both admin note fields lacked maxLength enforcement on the client despite
server Zod schemas using PATIENT_NOTE_MAX_LENGTH. Now consistent.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Client-side maxLength was missing on 11 inputs across 5 files despite
server schemas already having .max() limits via portal.ts constants.
Users could type past the limit and only discover the error on submit.
- ProfileForm: 6 textareas (mainConcern, goals, diagnosisHistory,
currentMedications, currentSupplements, notes) → PATIENT_NOTE_MAX_LENGTH
- checkin/page: notes textarea → CHECKIN_NOTES_MAX_LENGTH
- bookings/page: notes textarea → BOOKING_NOTES_MAX_LENGTH
- messages/page: subject input + body textarea → MESSAGE_*_MAX_LENGTH
- InlineMessageCompose: subject input + body textarea → MESSAGE_*_MAX_LENGTH
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
GOAL_TITLE_MAX_LENGTH (300) and GOAL_NOTES_MAX_LENGTH (2000) added to
lib/config/portal.ts. goals.ts Zod schema and PatientGoalsCard.tsx
inputs now import from there — client maxLength and server validation
stay in sync automatically.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Network error handling:
- DocumentAddForm, ProgrammeAssignmentForm, InlineMessageCompose,
AdminNotesForm all lacked try/catch — buttons stuck on network failure
SSOT fix:
- Added DOCUMENT_MAX_FILE_SIZE_MB = 20 to lib/config/portal.ts
- Upload route now derives MAX_BYTES from the constant instead of
hardcoding 20 * 1024 * 1024
- DocumentAddForm label now reads the constant instead of 'max 20 MB'
— changing the limit in one place updates validation + UI label
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Goal add form (5 inputs/textarea) and inline score edit input relied
solely on placeholder text — not accessible to screen readers. Each
now has an explicit aria-label.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- handleAdd/handleUpdateCurrent/handleToggleComplete/handleDelete now
show actionError on network failure instead of silently doing nothing
- setSaving(false) moved to finally block in handleAdd (was missing on error path)
- admin/patients: last-checkin cell colour uses conditional className instead
of inline style={{}} (default td colour is already var(--ink2))
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Was only calling setLoading(false) on success path — network errors
would leave the component stuck in loading state forever.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Eliminated 2 local AssessmentResult type definitions with divergent shapes
(portal version allowed Date|string, admin version required Date with id).
Canonical AssessmentRow — supporting both Drizzle (Date) and API (string)
completedAt — now lives alongside the assessment constants and scoring logic.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Eliminated hardcoded route string literals ("/dashboard", "/checkin", etc.)
scattered across 14 files. PORTAL_ROUTES and ADMIN_ROUTES constants are now
the single source of truth for all URL paths.
Benefit: renaming a portal route now requires 1 file change (routes.ts) instead
of hunting string literals across navigation, breadcrumbs, dashboard cards,
assessment pages, and marketing CTAs.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Eliminated 2 local Goal type definitions in GoalsCard and PatientGoalsCard.
Canonical API-serialised shape now lives in lib/config/portal.ts alongside
existing goal-progress threshold constants.
GoalsCard uses Pick<GoalRow,...> (id/title/baseline/current/target) so the
server-component caller can pass Drizzle results directly without date-type
mismatches.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Three hardcoded numeric literals removed from components and pages:
- 5000ms booking success banner → BOOKING_SUCCESS_MS in portal config
- 30_000ms message polling interval → MESSAGE_POLL_INTERVAL_MS in portal config
- 99 badge overflow threshold → BADGE_MAX_COUNT in portal config (used in
both PortalNav and AdminNav, eliminating the duplication)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Eliminated 4 local `type Booking` definitions that duplicated the same
shape across portal, admin, and component files. Canonical serialised
types now live in lib/config/booking-status.ts alongside BookingStatus.
PatientBookingsCard uses Omit<BookingRow,'createdAt'> so it accepts both
server-side Drizzle results (Date) and API responses (string) without a
cast, since the component never renders the date field.
AssessmentSection.status cast removed — now typed as BookingStatus.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Remove unused imports/variables across API routes and admin/portal pages
- Wrap async data-load functions in useCallback to satisfy exhaustive-deps
- Fix ref mutation during render in Assessment (move to useEffect)
- Fix raw anchors to Next.js Link for portal routes in Nav and checkin page
- Extract Date.now() to const in dashboard page
- Disable react-hooks/set-state-in-effect and react-hooks/purity (v7 rules
too aggressive for async useCallback+useEffect data-loading pattern)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
These three helpers were defined locally in 8 separate files with subtle
inconsistencies (different fallbacks, different null handling). They now
live once in lib/assessment/data.ts and are imported everywhere.
Also moves ACTIVE_CHECKIN_DAYS from a local const in the weekly-digest
cron route into lib/config/admin.ts where all other thresholds live.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
/en/dashboard, /de/profile, etc. now redirect to /dashboard, /profile
instead of 404ing. The intlMiddleware only handles marketing pages;
portal routes must be stripped of their locale prefix first.
Also refactors DocumentAddForm, InlineMessageCompose, AdminNotesForm
to replace all inline styles with admin.module.css classes.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Eliminates ~40 inline style objects across PatientGoalsCard including
goal form, progress bar, edit controls, and completed goals section.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Install @vercel/blob. New POST /api/documents/upload accepts FormData
(file + title + patientId), uploads to Vercel Blob at
documents/{patientId}/{timestamp}_{filename}, creates document record.
DocumentAddForm now has a file picker (PDF, images, Office docs, CSV, max 20 MB)
instead of a URL text field.
Requires BLOB_READ_WRITE_TOKEN env var (Vercel Storage -> Blob -> project token).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Mark messages as read on thread open (GET sets readAt for other party's messages)
- lib/domain/messages.ts: getUnreadThreadCount() and getAdminUnreadThreadCount()
- PortalNav + BottomNav: accept unreadMessages prop, show teal badge
- AdminNav: new client component with active state + unread badge
- CSS: .navBadge and .bottomNavBadge added to portal/admin modules
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Portal:
- Dashboard shows verdict tier name + interpretation text from VERDICT_TIERS
- Score delta between assessments (↑/↓ since last)
- Lowest dimension surfaced as key intervention area
- Clean empty state when no assessment taken — no fake steps
Assessments:
- Dimension interpretation text now visible below each score
- Uses INTERPRETATIONS from data.ts (was unused)
Admin:
- /admin/patients — patient list with verdict tier name alongside score
- /admin/patients/[id] — full detail: profile, verdict + interpretation, all dimensions, bookings, messages, documents
- /admin/bookings — all bookings with filter tabs, inline confirm/cancel
- /admin/messages — all threads; /admin/messages/[threadId] — admin reply view
- /admin/documents — add documents for patients with patient selector
- Messages nav item added to admin sidebar
Fixes:
- scoreColor defined in 4 places → imported from lib/assessment/data.ts everywhere
- Portal layout fetches name from DB (not stale JWT) — fixes "Welcome, there"
- Hardcoded "Patient" role → session.user.role
- Admin users see "Admin Panel ↗" link in portal sidebar
- Message notification links to /admin/messages/[threadId] not patient list
- documents relation added to schema (bookingsRelations, documentsRelations)
- Booking form shows success/error feedback after submit
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>