User drawer — data flow and cost
The portal shows a user through two drawers, opened from the Users table (decision: 0014-separate-user-details.md):
- the athlete drawer — how a training subject is doing: a glance row above two tabs, Training and Wellness, over four independent data sources;
- the details drawer — the account form: identity, role, body data, tags, photo and assignments, for creating a user and editing any user.
This page records what one open costs, what the client computes from what, and which layer each computation belongs in.
Companion reading: athlete-summary-backend-response.md
describes the HistoryStatsReturnDtoV2 aggregate the Summary tab renders;
state-management.md describes the store pattern the drawers'
caches follow.
The athlete drawer
AthleteDrawer in apps/portal/src/app/dashboard/users/athlete-drawer.tsx renders an
AvatarHeroDrawer inside a shared DrawerStack. It is rendered unconditionally with a
nullable target; useDrawerHost (apps/portal/src/components/use-drawer-host.ts) keeps
the panel mounted through its slide-out and hands back a sessionKey that remounts the
view per open. It opens for training subjects only (athlete role, or trainable —
isEffectivelyTrainable).
- Hero: the read-only photo, and on its lower edge the name, email · weight · height and the tags. These are the facts a coach used to open Details for.
- The pencil ("Edit details", or "View details" for a viewer without write
access) turns this same drawer into the account form (
UserForm); Save or the back chevron in its header (closeAs="back") turn it back. The view stays mounted underneath, so its open view, its scroll and an unsaved targets draft survive. Escape and Back leave the form first (asking when it has unsaved changes), then close the drawer. After a save the hero follows the profile cache, and the Goals save's base is re-read (see "Goals save on their own"). - "…" holds Recalculate training data, Unassign, Archive/Unarchive and Delete
(
useUserAccountActionsinusers/user-account-actions.tsx).
The details drawer
UserDrawer in apps/portal/src/app/dashboard/users/user-drawer.tsx is the account
form (UserForm) in the same chrome, with no tabs. It has three modes:
create— a new user, with the role cards, a managing coach (athletes) and assignments (managers).edit— any existing user. Assignments are a section of the form, saved with it. The "…" holds Unassign, Archive/Unarchive and Delete — except when opened from the athlete drawer, whose own "…" offers them right behind.draft—UserFormreused outsideUserDrawer, persisting to local state instead of the API. Used by the roster review (users/roster/draft-user-drawer.tsx) and the migration flow (migration/migration-user-drawer.tsx).
The form's state, seeding and update payload are pure (users/user-form-model.ts); the
API writes and cache upkeep are shared with the athlete drawer (users/user-persistence.ts).
How each drawer opens
| Entry point (Users page) | Training subject | Anyone else |
|---|---|---|
| Table row / mobile card tap | athlete drawer | details drawer |
| Row "…" → Open profile | athlete drawer | — |
| Row "…" → Edit details | details drawer | details drawer |
| Athlete drawer → pencil | the form, in the same drawer | — |
?user=<userId> | athlete drawer | details drawer |
?edit=<userId> (Performance "Edit") | details drawer | details drawer |
| "New user" (toolbar, empty state, tour) | details drawer, create |
The planner's athlete picker (planner/schedule-drawer.tsx) opens the details drawer in
create mode.
Requirement: POR-USERS-02 in requirements/portal.md. System tests: POR-ST-5.2 and POR-ST-5.6 in testing/portal-system-tests.md.
Athlete drawer layout
There is no Summary tab and no separate tab bar: three tiles are the
views. Each shows its answer and opens its detail below (role="tab"; the
chosen tile is outlined in ink, the others light up on hover).
| Where | Shows | Component |
|---|---|---|
| Hero | the photo (or a plain surface) fading into the drawer at its lower edge, where the name, email · weight · height, the tags and a pencil sit | users/athlete-drawer.tsx, @enode/ui/avatar-hero-drawer (caption) |
| Tile "This week" | the weekly goal's share and pace verdict | WeeklyGoalGlanceTile in a GlanceTabSlot |
| Tile "Targets" | the weekly target sets and the goal's name | TargetsGlanceTile (athlete-summary-panel.tsx) |
| Tile "Readiness" | today's readiness — opens Wellness | WellnessGlanceTile in a GlanceTabSlot |
| This week | the default — one week navigator; the week card (sets done of the target with the pace verdict; the muscle quality — strongest zone, split bar, the three shares, the goal's split; the body map in progress steps, where a picked muscle is outlined and hatched and shows its sets and split, otherwise the three muscles furthest behind); then the day-by-day log | week-targets-card.tsx via athlete-summary-panel.tsx (section="training", onOpenTargets), users/week-tab.tsx (hideNavigator) |
| Targets | training goal + per-muscle targets, with their own save | muscle-goals-panel.tsx |
| Wellness | the readiness and training-load trends | athlete-summary-panel.tsx with section="wellness" |
| Tile "1RM" | how many 1RMs / PBs are entered — "—" until the view was opened, because the entries are read only then; the row has four tiles | GlanceTile in a GlanceTabSlot (rm1EnteredCount), GlanceRow columns={4} |
| 1RM | the athlete's exercises a 1RM (strength, not on a flywheel) or a PB (weightlifting) can be entered on, as two tables with the entry edited in place — see "The 1RM view" below | users/athlete-rm1-tab.tsx, users/use-athlete-rm1-exercises.ts |
The tiles are GlanceTiles; inside a GlanceTabSlot (a context) a tile renders
as a tab and its own tooltip or action gives way. The session-rating tile is not
a view: its chart is part of Wellness.
The 1RM view. The one place in the portal where 1RMs and weightlifting PBs
are entered, also for an athlete without a session. Data → Profiles shows the
value read-only (ExerciseRm1Readout in data/performance/exercise-rm1.tsx:
"1RM" / "PB", the value, "Entered" / "Estimated" / "Tracked").
- Read, when the view is first opened:
GET /exercises/exercise_for_user/all/{athleteID}— every exercise instance of the athlete, trained or not. For the signed-in user's own drawerGET /exercises(the per-user route answers only for a user the caller is the parent of). - Rows (
buildAthleteExerciseRm1Rowsinexercise-rm1-table-model.ts): the athlete's own instances that take an entry, 1RM rows before PB rows, each by name (the Exercises table's row name). For someone who may write the entry, the coach's own exercises (the Exercises page's catalogue) the athlete has no instance of follow, muted, behind "Show all" while the athlete has rows of their own. - Columns: exercise · the entry · source ("Entered" / "Estimated" /
"Tracked") · for strength the server's estimate when its confidence is above
0.75. A weightlifting row shows the server's
valueas "Tracked" only when its confidence is at least 1 (exerciseRm1Tracked); that column is there only while a row has such a value. - Write, per cell on blur / Enter (
ExerciseRm1Cell,useExerciseRm1CellSaveinexercise-rm1-cell.tsx;saveExerciseRm1Cellinexercise-rm1-cell-save.ts):PUT /exercises/{instanceID}with the onerm1measurement, confirmed against the response. An emptied cell resets the entry. A row without an instance first callsPOST /exercises/exercise_for_user/workoutfor that definition and athlete — the get-or-create a session assignment uses — and then writes onto the instance it returns. - Who may edit:
writeExercise, and for another userwriteUserAthlete(useCanEditExerciseRm1); otherwise the table is read-only and lists only the athlete's own rows. - The cell, its state rules and its save are not tied to this drawer: they live
in
app/dashboard/exercise-rm1-*.ts(x)so a table "one exercise × all athletes" can reuse them.
Week usage rows name muscles by the athlete's own muscle id. The week
card resolves a row to its map key through the catalogue (getMuscle) and, when
that finds nothing, through the profile's muscles — on backdev the usage ids
match the profile's rows, not the catalogue's.
AthleteSummaryPanel renders one part per instance (section); the instances
share the stores, so the split costs no extra request. Without section it is
the whole summary in one column, glance row included (the debug view).
The name lives in the hero. With a caption, the pinned header shows the
title only after the hero has scrolled away. Without a photo (hasImage === false on the list row) the hero is a plain surface instead of the "add image"
frame; older backends omit hasImage, and the upload field's frame stays.
Tags are read-only in this drawer. They change in the table row and in the details drawer.
One shared week. The two week-scoped parts of "This week" — the Training
section and the log below it (still called the Activity tab in the code) — show
the same calendar week, held by the athlete drawer (weekStart,
Monday 00:00 local; helpers in users/drawer-week.ts). Both carry the same
WeekNavigator (‹ This week 22.9 – 28.9 ›, "Today" to jump back); stepping it
in one moves the other. It opens on the current week and steps back without
limit. Only the Activity tab can step ahead (up to 4 weeks, for planned workouts;
it requests no sessions there). The Training section never shows a future
week: its control stops at the current week, and while the Activity tab is on a
future week, Training stays on the current one. The glance row, Wellness and Session RPE are about now and do
not follow it; the muscle rows' pace badges show only for the current week.
The Activity tab is a log (users/week-tab.tsx, view model
users/week-log.ts; the tab's internal id is still week): a summary line
("5 sessions · 3 training days · 2 planned ahead", and the week's sets and
volume), then one compact row per day — date, a status chip, a title, "3
exercises · 12 sets" and the day's session RPE. Today's row starts expanded.
- The past shows only what happened. A past day lists its sessions and is Trained, or Rest without any — whatever was planned for it. Plans are not matched to sessions (sessions carry no workout id), so there is no done / partly / missed.
- Today and later show the plan. Today is Today: its planned workouts (exercise names, no ticks) and, listed separately under "Sessions", what was recorded so far. A later day is Upcoming with a plan, Rest without.
- Actions: "Open" on a planned workout opens it in the schedule drawer (edit it, or move it by changing its date); a session line opens the session in the session drawer (stacked above); "Schedule a workout" opens the schedule drawer with the athlete preselected.
- Session RPE per day comes from one read of the week's
sessionRpe+trainingLoad(a day past the week, as ratings can come the next morning), paired bypairRatingsWithLoads.
Account actions live in a header "…" menu of either drawer (see above): Recalculate training data (athlete drawer only; same grant as saving the profile), then Unassign · Archive/Unarchive · Delete — gated identically in both, with the same confirmation dialogs.
The Goals tab has two shapes. Until an athlete has either a training goal or a non-zero per-muscle target, it renders a single centred call to action to choose a goal — no goal card, no muscle map, no editors. The goal is what produces the targets, so there is nothing to fine-tune before one exists. Everything below is the populated shape.
Choose a goal, adjust the exceptions. The populated tab is two cards
(muscle-goals-panel.tsx, weekly-targets-card.tsx):
- Training goal — name, the backend's description (clamped to two lines),
and the goal's split as one stacked bar (power · hypertrophy · strength) with
its three values. "Change" opens the goal picker
(
training-goal-picker-drawer.tsx), which compares the goals by split bar, description, sets per muscle and per week. - Weekly targets — the body map in Target mode beside (from the
smbreakpoint) or above the list of regions. A region opens to its muscles; a muscle row opens its editor — one at a time. Rows show the target sets only, plus chips for what differs from the goal: "Focus", "+4" (sets against the goal), "Own split". A status line names the adjusted muscles and offers "Reset all to the goal".
Regions are the muscle catalogue's groups. muscleRegions groups by
groupNameTextContentID / groupName — Chest, Shoulder, Arms, Back, Thigh,
Calves, Core on today's catalogue — rather than by a table of muscle keys in the
portal: the names are translated with the muscles, the iOS app groups the same
way, and a new muscle needs no release. A group of one muscle is shown as that
muscle's own row.
The map selects, it never edits. Hovering a muscle shows its name and
target; clicking it selects it — opens its region and row and scrolls the row
into view. The selected or hovered muscle is outlined and the others dimmed
(selectedKeys on MuscleMap). No click on the map changes a number.
The map's colour is an absolute scale. muscleTargetSetStep
(packages/core/src/muscle-map/coloring.ts) bands the weekly target sets into
0 · 1–5 · 6–10 · 11–15 · 16+ and muscleRampColor maps the step to one of five
single-hue tokens (--illustration-musclehuman-0 … -4). The legend renders
from the same MUSCLE_TARGET_SET_BANDS, so it is fixed. Only the Goals map uses
this ramp; the session drawer, the exercise detail and the tracking app still
use the three usage tiers (muscleFillFor).
The row editor. A stepper for sets per week (0–30) with "Goal: 10 · Reset"
when it differs; the "Focus muscle" switch (focused); and the split, which
follows the goal until "Customise" shows one bar with two handles
(ZoneSplitSlider, 5 % steps, pointer or arrow keys) and "Use the goal's
split". What focused does is the backend's: its workout solver weighs a focus
muscle's distance from its target sets and split more heavily than the other
muscles'.
One staged save. Choosing another goal, changing sets, focus or a split all
edit a local draft; nothing is written. The panel compares the draft with what
is saved (goalsChanges) and, when they differ, shows a sticky bar with the
change list, "Save targets" and "Discard". Choosing a goal applies the goal's
values to the draft (applyGoalDefaults), and the picker says what that
replaces. The panel reports the draft to the athlete drawer (onDraftChange),
which writes it in ONE PUT /users/v2/{id}: the saved profile — the
drawer's own fetch-before-edit read (useFreshUser) — with the draft's
muscles (buildUserDto in users/user-form-model.ts) and, only when the goal
changed, trainingGoalID. The user update switches the goal without rescaling
the targets, so what is stored is exactly the draft. A save in the details
drawer re-runs the fresh read, so the Goals save can't write the pre-edit
details back; it is blocked until the read lands. An unsaved draft asks before
the athlete drawer closes. The details form round-trips the targets unchanged.
Without a host save the tab is read-only. On the debug page, or for a viewer
who may change the goal (writeTrainingGoal) but not write the profile, the
rows have no editor and a goal change is written at once through
PUT /users/{id}/training_goal/{goalID}. That endpoint does not copy the goal's
values: the backend gives every muscle the goal's split and scales the existing
weekly sets by the ratio of the two goals — the picker's confirmation says so.
Progress while writing. "Save targets" reads "Saving…" and both cards are dimmed and locked until the write returns. The immediate goal change of the read-only mode keeps the picker open with a busy "Use …" button.
The profile drawer (users/profile-drawer-view.tsx) is no longer opened from the athlete
drawer: the Activity tab opens sessions in the session drawer instead, and the Summary tab
links to the Profiles page for the athlete.
Tab panels mount on first activation
A tab's panel mounts the first time that tab is opened, and stays mounted after
— hidden with className="hidden" rather than unmounted — so switching tabs
costs nothing and in-progress edits (the Goals tab's draft targets) survive.
The panels used to mount all at once on open, to warm their data in the
background. The athlete drawer now does the warming directly, without the DOM:
one effect calls loadWeekStats, loadUserActivity and
prefetchUpcomingWorkouts on open, and the header's useUserProfile loads the
profile. The details drawer warms nothing beyond its own fresh read.
One consequence of the old approach survives on purpose: weekly-targets-card.tsx
scopes its muscle-rect lookup to a local mapRef, because the Summary tab's map
can still be mounted-and-hidden once both tabs have been visited, and a global
[data-muscle] query would match its 0×0 rect and pin the hover tooltip to the
corner.
Data sources per tab
| Tab | Reads | Endpoint | Cached |
|---|---|---|---|
| Header / form | the full user profile | GET /users/{id} | yes — users/profile-store.ts |
| Header avatar | the profile image | GET /users/profileImage/{id} | yes — permanent module cache |
| Summary | weekly history stats | POST /history/v2/week | yes — users/week-stats-store.ts |
| Summary | whether the athlete has a login (email) | the same cached profile | shared |
| Summary | daily wellness score, last 56 days | GET /measurements/user/{id}/metric/{wellnessScore} | yes — users/metric-measurements-store.ts |
| Summary | session RPE + training load, last 28 days | GET /measurements/user/{id}/metric/{sessionRpe} and …/{trainingLoad} | yes — users/metric-measurements-store.ts |
| Goals | training goal + per-muscle goals | the same cached profile | shared |
| Goals | the goal catalogue (on picker open) | GET /training_goals | one-shot ref |
| Activity | scheduled + recurring workouts | GET /workouts/schedules, GET /workouts/recurring | yes — workouts store |
| Activity | completed sessions of the shared week | POST /workout_sessions/search | yes — users/activity-store.ts |
| Summary | next planned workout (this + next week) | the same workouts store | shared |
| Details drawer | role catalogue, user catalogue, privileges | GET /user_roles, GET /users/all_roles, GET /users/{me} | yes — module stores |
| Details drawer | one avatar per assignee | GET /users/profileImage/{id} × N | yes — permanent module cache |
The details drawer runs its own fetch-before-edit read (useFreshUser, row 1 below)
each time it opens and gates Save on it. Inside the athlete drawer the form uses
the athlete drawer's own read instead.
Request timeline on opening an athlete
Every row is deduped by id/key and cached, so a reopen inside the freshness
window (REVALIDATE_MIN_AGE_MS, 15 s) issues nothing.
| # | Request | Fired by | Trigger | Cache | Payload | Blocks |
|---|---|---|---|---|---|---|
| 1 | GET /users/{id} | useFreshUser → loadUserProfile(id, { force: true }) | drawer host mount | users/profile-store.ts, keyed by id. force skips the freshness window — this is fetch-before-edit | full UserReturnDto, embeds recursive accessToUsers, muscles, trainingGoal | Save goals (athlete drawer); Save (details drawer) |
| 2 | POST /history/v2/week {userIDs:[id],from,to} | the athlete drawer's warm effect, then useWeekStats | drawer open (athlete) | users/week-stats-store.ts, keyed userID:from:to | one HistoryStatsReturnDtoV2 | the Summary cards |
| 3 | POST /workout_sessions/search?per=100 | the athlete drawer's warm effect, then useUserActivity | drawer open (athlete) | users/activity-store.ts, keyed userID:weekStart | up to 100 full SessionReturnDto trees | the Activity tab (done) |
| 4 | workouts month(s) + recurring | prefetchUpcomingWorkouts() | drawer open, and Users-page enter | workouts/store.ts | usually free | the Activity tab (planned) |
| 5 | GET /users/profileImage/{id} × N | AvatarUploadField, AthleteAvatar | hero + each Assignments row | permanent module cache | one per distinct user rendered | avatars |
| 7 | GET /measurements/user/{id}/metric/{wellnessScoreId}?from&to (56 days) | useUserMetricMeasurements via useWellnessTrend | first Summary open (not warmed) | users/metric-measurements-store.ts, keyed userID:metricID:from:to | one row per check-in (several per day possible) | wellness tile + section |
| 8 | GET /measurements/user/{id}/metric/{sessionRpeId} + …/{trainingLoadId} (28 days) | useUserMetricMeasurements × 2 in session-rpe-card.tsx | first Summary open (not warmed) | users/metric-measurements-store.ts | one rating + one load per workout | the Session RPE section |
| 6 | /user_roles, /users/all_roles, /users/{me}, /metrics, /exercises, /exercise_bases, /muscles | useRoles, useUsers, useHasPrivilege × 4, useSessionMetrics; /muscles via the Summary panel | drawer mount; /muscles on the first Summary open | store-cached (15 s min-age or load-once) | — | cold-cache first open only |
The Summary and Goals tabs read the same cached profile as row 1 rather than
fetching their own. Before the profile store they each issued a raw getUser,
so one open cost three identical reads of the heaviest user payload in the API —
and a training-goal change made it four.
Rows 2 and 3 are registered for focus / visibilitychange / reconnect
revalidation, so a drawer left open catches up when the admin returns. The
profile store deliberately is not: refetching the record currently being
edited risks clobbering in-progress input.
Invalidation on write
Caching only holds while nothing rewrites the data behind it, and one dependency is easy to miss: an athlete's per-muscle goals are what the backend computes the Summary tab's per-muscle targets from. A goals save, or a training-goal change, therefore makes the cached week stats wrong without ever writing to them.
| Write | Site | Effect |
|---|---|---|
| User save (create / update), Goals save | persistUser in user-persistence.ts | refresh profile + week stats |
| Training-goal change without a host save (read-only mode) | writeGoalNow in muscle-goals-panel.tsx | refresh week stats (it force-reloads the profile itself) |
| Archive / unarchive | setUserArchived in user-persistence.ts | refresh profile + week stats + activity |
| Unassign | unassignFromMe in user-persistence.ts | forget profile + week stats + activity + measurements; force-reload the signed-in user + the user list |
| Delete | deleteUserEverywhere in user-persistence.ts | forget profile + week stats + activity + measurements |
Unassign is the odd one out: it writes the signed-in user's roster
(DELETE /users/{myID}/assigned_users), not the user in the drawer, so it also
force-reloads the current-user profile — its accessToUsers is what gates the
button — and re-reads /users/all_roles rather than dropping the row locally,
because whether the user stays visible depends on the manager's tier.
It forgets rather than invalidates, for a reason worth stating: a successful
GET /users/{id} folds the row back into the users catalogue via upsertUser
(see loadUserProfile). invalidateUserProfile refetches, so on a write that
takes the user out of your scope it races the list refresh and re-inserts the
row you just removed. Refresh is for a user you still manage; forget is for one
who has left — deleted, or unassigned.
invalidateX refreshes the cached entry in place; it does not drop it. That
distinction is load-bearing: every consumer loads from an effect keyed on the id
(and window), so a dropped entry has nothing left to re-trigger its fetch and the
view waits on a skeleton forever — which is exactly what a training-goal change
used to do to the Summary tab. The cached numbers keep rendering until the fresh
ones land. forgetX is the drop, used only where the entity is gone and a
refetch would 404.
Session completions are not invalidated: the portal has no signal for them. The focus revalidation above covers the realistic case — a coach tabbing back after an athlete trains.
The activity search is keyed by name, then re-filtered by id
user-activity-tab.tsx searches { searchItems: [{ tableId: "user", searchTerm: name }] }
and then keeps only s.user?.id === userId. This is a correctness fact, not only a cost
one. Three consequences:
- Two athletes sharing a name split one 100-row page between them, so either can be silently truncated.
- An athlete with a blank or whitespace-only name sends
searchItems: []— a search across the whole account's week. - The client pays to download every row it then discards.
The per: 100 page size cannot be reduced while the filter is name-based: a smaller page
would truncate the target athlete's rows in exactly the collision case above.
Transformation inventory
What the client computes, from what, for whom.
Summary tab transformations
| Input | Transformation | Result | Rendered by |
|---|---|---|---|
muscleUsage.values[] | weeklySetTotals + daysElapsedInWeek + weeklyGoalState (weekly-goal-banner.tsx) | a WeeklyGoalState, percent, days left | useWeeklyGoalSummary → the glance row's goal tile; WeeklyGoalBadge on muscle rows |
muscleUsage.values[] + the /muscles catalogue | buildMuscleUsageVm → sortMusclesByCategory, bar scaleMax, completion percent (no icons) | MuscleUsageVm | MuscleUsageCard |
volumeCompletion + zoneDistribution | zone entries + zoneColorVar + tonnage formatting via useUnits | ring segments + centre label | VolumeCompletionCard |
gridMetrics[] | summaryGridTiles drops the two duration tiles (Time, Rest avg.), leaving Sets + Volume; then useMetricCategory(metric.metricCategoryID) for the icon; units.formatAggregate(value, metric) (by dimension — a weekly roll-up is never a "6+" overflow measurement); round(trend × 100) | the Sets + Volume glance tiles | GridMetricGlanceTile |
The week's muscleMapVolume is still returned but not rendered in the Summary
tab: the muscle map card was removed from it, as were the Time and Rest avg.
tiles. The session drawer's Details tab reads the same week's muscleUsage
(POST /history/v2/week, same cache entry) for its "Sets per muscle" card —
see history-feature-plan.md.
Summary tab layout
Top to bottom (athlete-summary-panel.tsx):
- At a glance (
summary-glance.tsx) — three tiles side by side: Wellness (latest score + verdict), Session RPE (the latest rated workout,8 / 10+ its step name, or "Notably hard" when that day's load stood out; dimmed with "No rating for N days" after 7 days) and Weekly goal (percent + pace verdict; the full sentence is the hover title). A tile's hover text is also revealed under it on tap (touch has no hover), and labels/verdicts wrap to two lines instead of being cut off. The old weekly-goal banner, the "Metrics" tiles, the goal badge and the outer "target volume completion" ring of the volume card were removed as duplicates; the Sets and Volume totals moved into the volume card. - Next workout (
summary-next-up.tsx) — "Next: Lower body · tomorrow" (this week and next), or "Nothing planned in the next 2 weeks"; tapping it opens the Activity tab on that week. - Trend window — a 4 / 8 / 12-week switch shared by the two trend sections, so they always show the same days.
- Wellness · last N weeks — the chart section (below).
- Session RPE · last N weeks — the training-load chart (below), on the same days as wellness. Hovering (or tapping) a day in either chart highlights the same day in the other, with a guide line.
- Training · the shared week (its header carries the drawer's week control; see "One shared week" above) — Volume (the week's set count beside the title, the zone ring with the tonnage in its centre, plus the zone legend) and Muscle usage (no per-muscle icons), which shows its first 5 rows until "Show all".
- Links out — "Open in Profiles →" (the Profiles page's
?athlete=<id>deep link) and "All sessions in History →" (History's?athlete=<name>deep link,data/history/history-link.ts; History matches athletes by name).
The section headers exist because the sections cover different time scopes.
Empty and partial states of the glance row and the sections:
- No training goal (the backend only computes set targets with a goal):
the goal tile reads "Set a goal" and opens the Goals tab when the viewer can
change it (
writeTrainingGoal+ write access to the profile), otherwise a muted "No set goal". The volume card looks the same with or without a goal. - Check-ins off, no data: the wellness tile reads "Turn on check-ins"
(opens Settings) only for holders of
canWriteCheckInSetting— the switch is the owner's, coaches inherit it — and a muted "Check-ins off" for everyone else. The section shows the matching explainer (questionnaire-off-note.tsx) in full the first time a viewer sees it, then as a single line with "Learn more" (remembered per browser, like the dashboard hints). Session RPE off works the same way. - Week stats failed or empty: the goal tile says "Not available" rather than "No set goal".
- Check-ins off, older data in range: the tile keeps the last score but says "Check-ins off" once it is stale, rather than "No check-in for N days".
- Stale score (last check-in 3+ days ago): the value is dimmed.
- Fewer than 7 check-ins: the tile says
{n} of 7 check-insinstead of a verdict. - No check-ins, check-ins on: the "athletes without a login…" hint shows only for an athlete without an email.
The wellness card
useWellnessTrend (apps/portal/src/app/dashboard/wellness-trend-card.tsx) is
called once by the panel and feeds both the glance tile and WellnessSection:
the athlete's daily wellness over the last 28 days against their own usual
range. The section has its own <RequireData> gate, so a failed or slow
wellness read never holds up the training figures below it.
- Source: the server-derived
wellnessScoremetric (the sum of a complete check-in's five answers). One request covers 56 days: the 28 shown plus the 28 before them, so the first shown day has a full baseline. - Measure picker: a dropdown above the chart switches between Overall (the default) and the five measures (fatigue, sleep, soreness, stress, mood). A measure is fetched on first pick — the same metric route and cache, one more request — and plotted on its own 1–5 scale with a usual-range spread floored at half a point. The glance tile always stays on Overall. The picker only appears once there is an overall check-in in the window.
- Method:
buildWellnessTrendinpackages/core/src/wellness/trend.ts. The latest check-in of a day counts. Each day is compared with the mean ± one standard deviation of the 28 days before it (floored at one point), which needs at least 7 check-ins; below that there is no range yet. - Layout (after the research branch's "Wellness trends" scene, but daily
instead of weekly): the latest score (
19 / 25) and its status in words ("Usual", "Lower than usual", "Much lower than usual") sit in the glance tile; the section header carries "Checked in N of M days"; the chart (WellnessTrendChartin@enode/ui/charts, 3:1) has a 5–25 value axis, and hovering a day shows its date, score and status. - Why it dropped: when the latest overall score is lower than usual (and recent), a line under the chart names the answers that were lower than their usual that day ("Lower than usual: sleep and soreness"), or — when none fell outside its own range — the one furthest below its average ("Mostly sleep"). The five measures are loaded only then (five reads).
- States: check-ins off and no data → an explainer with "Turn on in
Settings" + the questionnaires walkthrough (holders of
canWriteCheckInSetting), or "Ask your account owner" (everyone else); check-ins off with old data → the chart plus a "turned off" note; on with no data → "No check-ins … in the last 4 weeks"; a catalogue without thewellnessScoremetric reads as no data. "Check-ins on" is the viewer'suserCheckinEnabled.
The session RPE card
useSessionLoadTrend (apps/portal/src/app/dashboard/session-rpe-card.tsx) is
called once by the panel and feeds both the Session RPE glance tile and
SessionRpeSection, which charts the athlete's training load per day over the
last 28 days, each day coloured by how hard it felt, against their own average.
Chart after the research branch's "Session RPE trends" scene (dashed average
line with an "Average" legend chip, notably hard days ringed), drawn in the
wellness chart's style (SessionLoadChart in @enode/ui/charts). The scene's
headline is left out — the glance tile carries the summary.
- Source: the backend's
sessionRpe(0–10, one per workout) andtrainingLoad(RPE × volume, one per workout; volume is the workout's set count, else reps, else seconds) measurements. - Method:
buildSessionLoadTrendinpackages/core/src/training-load/trend.ts. Loads are summed per local day; the dot colour follows the day's highest rating. A day is notably hard at or above the athlete's average training-day load + 1 SD over the window, which needs at least 7 training days. - Week vs usual week: above the chart, "This week so far: 350 · usual
week: 520" (
weeklyLoad) — the current calendar week's load against the average of the complete earlier weeks in the window (rest weeks count as 0; needs two of them). - Pairing is by time. A measurement read carries no session id, and the rating is stamped when it was given while the load is stamped at workout start. Each rating is paired with the latest load that started within the 24 hours before it — the backend's own attach rule. An unpaired load is drawn neutral ("not rated"); ratings with no load are counted in a note, never drawn as zero. TODO: pair exactly once the backend returns the session id.
- States: session RPE off (the owner's
sessionRpeEnabled) and no data → an explainer with "Turn on in Settings" / "How it works" for holders ofcanWriteSessionRPESetting, "Ask your account owner" otherwise; off with old data → the chart plus a "turned off" note; on with no data → "No rated workouts … in the last 4 weeks"; fewer than 7 training days → no average line and "Building their usual load".
Goals tab transformations
| Input | Transformation | Result | Rendered by |
|---|---|---|---|
UserReturnDto.{trainingGoal,muscles[]} | hasMuscleTargets — is any target non-zero? | whether the tab shows its setup CTA or its cards | MuscleGoalsPanel |
UserReturnDto.{trainingGoal,muscles[]} | seedMuscleGoals, once per athlete | the saved GoalsState and an equal draft | MuscleGoalsPanel |
trainingGoal.muscleGoals[] | goalSplit → splitPercents (whole percentages that add up to 100) | the goal's one split bar and its three values | the goal card, the picker |
trainingGoal.muscleGoals[] | goalSetsSummary | sets per muscle (when uniform) and per week | the picker, the status line |
draft muscles[] | muscleRegions — the catalogue's groups, sets summed | the region rows | WeeklyTargetsCard |
draft muscles[].volume | targetSets (whole sets) → muscleTargetSetStep → muscleRampColor | the map's fill on the absolute scale | WeeklyTargetsCard |
draft muscles[].volume | totalTargetSets | "N sets per week" | the card header |
draft muscle + trainingGoal.muscleGoals[] | muscleDeviation, compared as displayed | the row chips ("+4", "Own split"), the editor's ways back | MuscleRow, MuscleEditor |
draft + trainingGoal.muscleGoals[] | adjustedMuscles | the status line, "N adjusted" on a closed region, the picker's "go back to the goal's standard" | WeeklyTargetsCard, the picker |
| a row edit | setMuscleVolume / setMuscleFocused / setMuscleZones / resetMuscleVolumeToGoal / resetMuscleSplitToGoal — all ID-keyed, all returning a new draft | the draft | MuscleGoalsPanel |
| a chosen goal, "Reset all to the goal" | applyGoalDefaults, matched by muscleKey | the draft | MuscleGoalsPanel |
| saved + draft | goalsChanges | the save bar's change list; empty = nothing to save | MuscleGoalsPanel |
| draft | toMuscleUpdate per muscle, plus the goal's id when it changed | GoalsDraft, the write payload | the athlete drawer's save |
muscle.nameTextContentID, groupNameTextContentID | getTextContent behind useMuscleName / useTextContentsVersion | localized names | rows, tooltip, change list |
Activity tab transformations — done (completed sessions)
| Input | Transformation | Result | Rendered by |
|---|---|---|---|
SessionReturnDto | buildActivityRows → useSessionMetrics().resolve — definitionID → catalogue exercise → exerciseBaseID → displayBaseExerciseGroupID, plus the equipment group, plus a scan of every set's measurements to find the loading metric's dimension | SessionMetricInfo (focus metric ids, mass vs inertia, dimensions) | SessionLine (sets, reps, top load) |
SessionReturnDto | buildActivityRows → summarizeSession (packages/core/src/training/exercise-overview.ts) — sort sets, Σ load × reps over working sets, highest load, Σ reps, mean set-start gap, first/last rep timestamps, per-set rows | SessionSummary | SessionLine |
pagedEntities[] | filtered by user.id in the activity store, then buildActivityRows sorts by summary.date desc | ActivityRow[], then grouped by local day | WeekTab |
Activity tab transformations — planned (workouts)
| Input | Transformation | Result | Rendered by |
|---|---|---|---|
| the workouts store | useWeekWorkouts: weekState(weekStart), utcMonths, isMine(participants), recurringDate(weekday) | DayWorkout[] (past days flagged) | WeekTab |
DayWorkout[] + ActivityRow[] + RPE by day | buildWeekLog: per local day, sessions (oldest first) and — from today on — planned workouts, never matched; day status against today; week summary | DayLog[] + WeekSummary | DayRow, WeekSummaryLine |
Details and Assignments transformations
| Input | Transformation | Result | Rendered by |
|---|---|---|---|
accessToUsers[] | .map(u => u.id), cross-joined against the useUsers({includeArchived:true}) catalogue, split by role.key | per-role assignee rows | assignmentSections() |
bodyHeight (m) / bodyWeight (kg) | useUnits inside HeightField / WeightField | the admin's unit system | the Details form |
birthdate (Unix ms) | msToDateInput / dateInputToMs | yyyy-mm-dd | DatePicker |
Cost hot spots, and what they cost now
The by-id user read embeds a recursive user tree
UserReturnDto (packages/core/src/api/dtos/users.ts) carries
accessToUsers?: UserReturnDto[] — each element itself a full UserReturnDto.
For a facility user this is their whole hierarchy, on a request whose only use in
the drawer is to derive a list of ids. Nothing client-side can trim the response,
so the mitigation is to read it once per open instead of three times, and to
serve reopens from cache.
The session search returns full session trees to render summary cards
per: 100 sessions, each with its sets and each set with its measurements (reps
are not included), to display roughly eight numbers per card. Now cached per
athlete-week, so it is paid once rather than on every open — but the payload
itself is unchanged, and the page size can't shrink while the filter is by name
(see the section above).
Derivation is per data change, not per render
The tab panels used to be children of the account form, so every keystroke in its Details tab re-rendered them. That re-ran, in the hidden tabs, the whole Activity reduction over up to 100 sessions, the muscle-usage sort, both heatmap normalizations and two tier passes — none of it memoized. The form now lives in its own drawer, so typing no longer reaches the panels at all; the memoization below still keeps the athlete drawer's own re-renders (a goal draft, the shared week) cheap:
- Every tab panel is wrapped in
React.memo, so a keystroke that doesn't change its props doesn't reach it at all. - Each derivation runs inside
useMemoover the fetched data. useSessionMetrics()memoizes itsresolveclosure and its return object. It used to return a fresh closure per render, which would have made the Activity memo a permanent miss. Becauseresolvereads the exercise-base and metric catalogues synchronously,useExerciseBasesVersion()/useMetricsVersion()are explicit dependencies — otherwise it would keep serving results derived from an empty catalogue.
MuscleGoalRow is memoized too, which is what stops N useTextContent
subscriptions and N Lottie players re-rendering. That required moving its edit
handlers from array-index to muscle-ID keyed — an index-keyed callback is a fresh
closure per row per render, and is also wrong once the list re-sorts.
The muscles catalogue is fetched to order rows that already carry an order
The Summary panel loads /muscles and subscribes to useMusclesVersion() purely
to resolve groupNameTextContentID and order for the usage-row sort. The DTO's
own order is only a fallback for muscles missing from the catalogue.
One avatar request per assignee
The details drawer's Assignments section renders an AthleteAvatar per row, each resolving through
GET /users/profileImage/{id}. The profile-image store caches permanently and
reconciles against the user list, so this is N once per session, not N per open.
Where each transformation belongs
The drawer's data flows through three layers, each with one job:
| Layer | Location | Job |
|---|---|---|
| Transport + cache | packages/core/src/users/{profile,week-stats,activity,metric-measurements}-store.ts | fetch each DTO once, cache it, dedupe concurrent callers |
| Preparation (pure) | athlete-summary-view-model.ts, muscle-goals-view-model.ts, users/user-activity-view-model.ts | DTO → render-ready view model; no hooks, no store reads, no t() |
| Rendering | the panels and cards, all React.memo | formatting, translation, interaction |
A computation belongs in the preparation layer when it is a pure function of fetched data: sorting, normalizing, tiering, summing, ranking, bar arithmetic, session reduction. These are the rows in the transformation inventory above that name a function.
A computation stays in the component when it depends on something the data doesn't carry:
| Concern | Why it stays |
|---|---|
| Unit conversion and formatting | metric/imperial is a per-admin preference read through useUnits at render time |
App-static copy via t(...) | only literal first arguments are extractable; a builder passing strings through would break extraction |
Server-entity names via useTextContent(uuid) | resolved by id against the text-content store so an over-the-air translation applies without a refetch |
| Local week bounds, "today", day headings | the browser owns the admin's timezone and the Monday-start week |
| Interaction state | hover key and tooltip rect, the usage card's collapse, the sets input's raw editing string, the active tab |
| Staged edits | the panel's draft GoalsState → onDraftChange → the athlete drawer's GoalsDraft, held until "Save targets" |
| Colors | zoneColorVar and the muscle-map tokens (usage tiers, target ramp) are design tokens, resolved light/dark at render |
| Privilege gating | useHasPrivilege decides which affordances render |
Backend-supplied display copy (title, detail on the history-stats blocks) passes
through the preparation layer raw. The component applies its own translated fallback —
muscleUsage?.title?.trim() || t("Muscle usage") — so an absent or empty server string
never reaches the screen untranslated.
An editable surface derives from its draft, not from the fetched DTO. The Goals tab's map, totals, chips and save bar all recompute from the draft as a stepper or a split handle moves, so they react without a round trip while the underlying profile stays untouched until Save.
How these numbers were measured
Reproduce before re-dating this section — do not carry the figures forward on trust.
- Request counts and payload sizes: DevTools Network, filtered to the API base, opening one athlete cold (hard reload) and warm (second open).
- Endpoint latency: the portal's benchmark harness at
/dashboard/debug/benchmark, whose catalogue andbudgetMsbands live inapps/portal/src/app/dashboard/debug/benchmark/endpoints.ts. - Payload shape: the "Log data model" buttons on the Summary and Goals tabs.
- Render cost: React Profiler, recording while editing goal targets.
TODO: record Measured on: <date>, <environment>, <athlete with N sessions> and fill the
table below. Left empty deliberately — figures are only useful if they were observed.
| Request | Bytes | p50 | p95 |
|---|---|---|---|
GET /users/{id} | TODO: | TODO: | TODO: |
POST /history/v2/week | TODO: | TODO: | TODO: |
POST /workout_sessions/search?per=100 | TODO: | TODO: | TODO: |
Known limitations of the current API
Facts about what the client has to live with, not requests.
The session search has no id filter
POST /workout_sessions/search filters by search term against a table id, so the Activity
tab searches by the athlete's name and re-filters by id client-side. The client
contains the leak by storing only the filtered list, and keeps per: 100 because a smaller
page would truncate a name collision.
The by-id user read carries the caller's user hierarchy
accessToUsers is a recursive array of full users. The drawer reduces it to ids
immediately. Nothing client-side can trim the response, so the mitigation is to read it
once per open rather than three times.
Two analysis calls are unbounded from this drawer
POST /analysis/volume_over_time/data and POST /analysis/intensity_over_time/data are
sent from apps/portal/src/app/dashboard/data/performance/pair-charts.tsx. They start on
ALL_TIME, which sends from: null, to: null — the athlete's entire history. The drawer
now carries the Profiles page's own timeframe picker (PairChartsColumn), so a coach can
narrow them from here; pass a chartRange to ProfileDrawerView to start somewhere else.
They fire only behind the Activity tab's explicit "Inspect Profile" action, so they are
outside the per-open budget.
One drawn shape is not always one muscle
The map draws the obliques (sideCore) as their own shape, but the backend
models the whole core as a single abdominals muscle. MUSCLE_PART_SOURCE in
packages/core/src/muscle-map/keys.ts declares that relationship, and anything
turning a map part into data goes through muscleDataKey. Skip it and the part
goes inert silently — an absent usage value tints exactly like a zero one, so
the shape just sits grey. coloring.test.ts guards against a new part arriving
with no muscle behind it.
Workout completion is not readable
Sessions carry no workout id and workouts no per-participant state, so the Schedule tab dims past workouts and says nothing about whether they happened. An earlier day-level inference from the session search was removed for claiming more than the data supports.
Related documents
- athlete-summary-backend-response.md — the
HistoryStatsReturnDtoV2aggregate and its batch endpoints - athlete-summary-backend-handoff.md — the request that produced them
- state-management.md — the external-store pattern the caches follow
- error-handling.md — dispositions, presenters,
RequireData - requirements/portal.md — POR-USERS-02
- testing/portal-system-tests.md — POR-ST-5.2, POR-ST-5.6
Training for several athletes
Selecting athletes in the Users table offers "Edit goal" first in the
selection bar. It opens users/bulk-training-drawer.tsx:
- Goal: the selection's goals with their counts ("No goal · 2 · General fitness · 1"); "Set for all" picks one goal for everyone, whose template every athlete's targets then start from.
- Weekly targets: the muscles by region. Where the athletes differ a row shows the range ("0–10"). + / − change each athlete's own value; tapping the number sets one value for all. A row opens to the focus switch and the muscle qualities, which a change sets for all.
- Model: the edit is stored as intent (
users/bulk-training-model.ts: goal, per muscledelta/set/focused/zones/reset) and applied to each athlete's own current values — on screen to show the ranges, on save to write them. - Read and save:
POST /users/training/readfor the selection, then onePUT /users/training/batchwith the edit as per-muscle changes (batchMuscleChanges) andifUnmodifiedSince; the server answers per athlete (ok/conflict/forbidden/error). On a backend without these routes (404): one athlete after the other, each from a freshGET /users/{id}and a whole-userPUT /users/v2/{id}. Either way the result names who could not be saved; those stay selected in the table, and the table's figures reload. Endpoints: users-table-backend-handoff.md.
The Users selection bar
The Users table uses the slim form of TableSelectionBar
(data-table.tsx): one line,
no effect lines (they move into each button's tooltip).
- Order: "n selected ×" (clears) · Edit goal · Schedule workout · Add
tags · More. The ✓ that commits picked tags appears only once tags are
picked, right after "Add tags"; "More" is an
enditem, so it stays last. - Schedule workout opens the planner's
ScheduleDrawerwith the selected athletes as participants. - More (
components/selection-more-menu.tsx, opens upward) holds the less frequent actions, each with a line on what it does to the selection: Edit details… (see below), Assign coach… (users/assign-coach-drawer.tsx, additiveassignUsers; disabled while the account has no coaches), Send invitation again (only the users who haven't joined and have an email address — the line says how many can't be invited), Export data, Archive (toast with Undo; in the Archived view it is Restore), and Delete users, set apart at the bottom. - Search and filters trim the selection to the rows still shown, so a bulk action never reaches a hidden row.
- The account actions run one request per user
(
users/bulk-account-actions.ts); every user is tried and the toast reports how many went through. - The phone pill keeps the
compactform: Add tags · More. Its menu adds Edit goal and Schedule workout on top and leaves out Export (the export drawer is desktop-only).
Details for several users
"Edit details…" in the More menu opens users/bulk-details-drawer.tsx: one row
per selected user with name, email, weight and height (body data for trainable
users only), and a line on where each stands with the app.
- Only an email address invites. The backend sends an invitation when a user
gets a new address on update (
UserServiceUpdate), and an update without one removes the address and signs the user out. So the drawer lets an address be added, or corrected while the invitation is open — the row then reads "Gets an invitation when you save" and Save becomes "Save and invite" — but never removed, and a user who joined keeps theirs (shown, not editable). - Model:
users/bulk-details-model.ts(pure, tested): changed fields, invitation state per row, validation (address format, the same address twice, removal, body ranges for what was edited). - Save: the changed users one after the other, each from a fresh
GET /users/{id}and a whole-userPUT /users/v2/{id}; per-user result as in the training editor. - The Invitation column reads "No email" for users without an address.
Not in plan (blocked athletes)
The backend marks an athlete blocked when the account's plan has no room for
them: they can't be picked for training. The portal treats it as a plan limit,
not a fault — a warning-tone pill "Not in plan" in the Account column and the
Status chip, a notice at the top of the athlete drawer — and always says what it
means with two ways on: "See plans" (pricing page) and "Contact support"
(users/plan-limit.tsx). Inside a tappable phone card the pill is a plain label
(the card's drawer explains it).
How full the plan is comes from GET /users/plan_capacity (usePlanCapacity
in the same file, read once per visit and again after create, archive, restore
and delete): the Users page subtitle says "plan full · n not in plan" or "n places
free in your plan", the explainer says how many people the plan holds and that a
freed place goes to the longest-registered user not in the plan, and Create user
and the roster review warn before a user would arrive "Not in plan". A backend
without the route (404) or an unlimited plan shows none of it.
Not having joined is not flagged in Status: an athlete without a login of their own still trains through a coach's account. The Invitation column shows it.
Safety edges of the bulk actions
- Asked first: Archive and "Send invitation again" open a confirmation
that names the people (
users/confirm-parts.tsx); Restore runs at once. - Delete (single and bulk) says what is lost — sessions, sets and measurements, check-ins, goals and targets — names the people, and offers "Archive instead".
- Failures name the first reason and offer "Try again" for the failed users
only. While a selection bar is shown, toasts rise above it (
--toast-lift, set byTableSelectionBar, read by theToaster). - Not in plan and training: the schedule drawer's athlete picker shows such
athletes but can't pick them (
UserPickerView excludeNotInPlan); a bulk "Schedule workout" leaves them out and names them; the athlete drawer offers no "Schedule a workout" for them; "Send invitation again" skips them. - Escape closes an open menu or popover only (capture phase), never the drawer around it.