Conventions in depth¶
The full text of the conventions that the repo-root CLAUDE.md states as one short rule each: the permission gates, the real-time broadcast tiers, the own-booking approval workflow, change notifications and booking segments behind those rules, the metric matrix, the store split, the lazy Dashboards view, the What-If exemption list, the error and confirmation protocol, the icon, overlay and form-field conventions, the shared test helpers, and the documentation-screenshot pipeline. Each section is the original convention, moved verbatim; CLAUDE.md links here from the matching rule. When a convention changes, change the rule in CLAUDE.md and its detail here together.
Code described: app/middleware/auth.py, app/middleware/broadcast.py, app/services/approvals.py, app/services/change_notifications.py, app/services/booking_segments.py, app/services/metrics.py, frontend/src/stores/, frontend/src/api/client.ts, frontend/src/utils/permissions.ts, frontend/src/utils/confirmDialog.ts, frontend/src/components/common/ (Notice, ConfirmDialog, Icon, AnchoredPanel, Input, Select, SearchableSelect, DateRangeField, ErrorBoundary), the test helpers in tests/ and frontend/src/test/, and scripts/screenshots/.
Backend¶
Permission gates on the backend¶
Gate on permission keys, never on role names. Routes use the dependencies from app/middleware/auth.py: get_current_user (any authenticated user), require_permission(key) / require_any_permission(*keys) (403 Permission required: <key>), require_project_permission(key) (adds the PM bundle; the path parameter must be named project_id); require_admin is only for the lockout-proof surface (roles and approval-policy writes). Every key comes from the catalogue in app/services/permissions.py. Rules that need the entity live in the access services: project_access.py (can_on_project/require_on_project, editor-first resolve_self_booking), approvals.py (own-booking approval requests, see Approval workflow), card_access.py, site_access.py (async ensure_site_access(request, db, user, site_ids, detail) on the live visible sites), user_access.py (edit target, escalation and last-admin guards). Never define a local role check in a router; admin-ness is role == 'admin' (the one admin role), and no role literal is left in a router (staff.py lists people by users.is_resource, not by role). Admin-portal routes use get_current_admin / require_superadmin from app/routers/admin/auth.py against the master DB. The is_system flag on users protects the provisioned admin from deletion.
One session per request¶
A request uses one database session and holds at most one pooled connection (2.5.1). get_db (app/database.py) is that session: FastAPI caches a dependency per request, so the auth dependencies (get_current_user), the handler and get_db_readonly — which since 2.5.1 simply returns get_db's session; it used to open its own — all share it. get_db keeps it on request.state for release_request_connection(request).
Two sessions on one pool deadlock under load: with more requests in flight than the pool holds, every request holds its first connection and waits for a second, until DB_POOL_TIMEOUT (30 s) fails them with 500s. In 2.5.0 every authenticated get_db_readonly read did exactly that (QueuePool limit of size 20 overflow 10 reached, connection timed out in the log).
The derived tiers that need a session of their own — audit_log.record_detached (behind broadcast_change and BroadcastMiddleware) and change_notifications.deliver — first call release_request_connection(request): a route that re-read after its commit (db.refresh, a reload select) has begun a new transaction that holds a connection again, and the helper commits it (a commit keeps the loaded objects usable under expire_on_commit=False, a rollback would expire them) before the second session is opened. BroadcastMiddleware runs after the response, when FastAPI has already closed the request's session. Sessions on another pool (the master DB, another tenant's pool) do not count.
Rules: never open a second session (get_session_factory()(), async with factory(), engine.connect()) while the request's session may hold a connection — release it first, or do the work on the request's session; load a list in one request (a bulk route like GET /projects/details), never one request per item; and run the load test when you touch the session dependencies or a detached tier.
Real-time broadcast tiers¶
Real-time broadcast is two-tier. For user-facing mutations on projects/phases/subphases/assignments, call broadcast_change(...) (app/websocket/broadcast.py) with rich attribution (entity, action, summary). Everything else is covered automatically: BroadcastMiddleware (app/middleware/broadcast.py) fires a coarse change:<entity> on any successful 2xx write, and its SKIP_PATTERNS list suppresses the paths that already do rich broadcasts (now including /api/kanban and /api/notifications). When you add rich broadcasting to a new path, add it to SKIP_PATTERNS too — otherwise clients receive double events. SKIP_PATTERNS also holds the two POST reads /api/dashboards/query and /api/dashboards/{id}/data (a builder preview or a viewer's data load must never broadcast — two open viewers would reload each other forever); dashboard writes broadcast change:dashboard.
Audit log tiers¶
The audit log is written in three places (app/services/audit_log.py; rows are immutable, keys are past tense: auth.login.failed, admin.user.updated, project.created):
- Explicit rows — categories
auth,admin,access— in the routes, throughaudit_log.record(db, request, *, action, category, ...)on the route's own session: the sign-in events (app/routers/auth.py), the diff-carrying admin writes (users, roles and their permission matrix, approval policies,PUT /settings/{key}, the three SSO config routes, the SSO test, sites, teams;changes = audit_log.diff(before, after, keys=...), nothing recorded when nothing changed) and the exports.recordadds and flushes, never commits:get_dbcommits at the end of the request and rolls back on a raise, so a failure path (a failed or locked sign-in) records its row and commits before it raises; the SSO callback's failure branches return a redirect instead of raising and commit onactive_db(the organization-SSO session never commits by itself). Updates and deletes record before the route's commit; creates (users, roles, teams, sites) after a flush for the id, inside the create's own transaction. Failed password sign-ins are capped per (tenant, client ip): pastMAX_FAILURES_PER_IPin the window oneauth.login.failedrow carriescontext.suppressed(at most one per window), then nothing is written for that address while the count stays past the cap (login_throttle.audit_failure_mode).tests/test_audit_recording.pywalks the route table: every write matched by an explicit pattern must callaudit_log.record(or a recorder helper (EXPLICIT_RECORDERS), and no write the middleware records may call it too. Their paths areAUDIT_EXPLICIT_PATTERNS(app/middleware/broadcast.py, anchored) so tier 2b never doubles them. - Derived tier 2a —
broadcast_change(...)(every rich call site, after its commit) also writes achangerowchange_action(entity_type, action)(project+create→project.created), target(entity_type, entity_id, summary),project_id(0 → none);audit=Falseonly for the ws-debug ping. - Derived tier 2b —
BroadcastMiddleware, afterself.appreturned and the coarse broadcast went out, awaits the row inline (nocreate_task) for every other 2xx write it maps:audit_action_for(method, path)classifies everyENTITY_PATTERNSentity (AUDIT_ENTITY_CATEGORIES: Settings entities →admin.<entity>.<verb>, user content →<entity>.<verb>) and returns None forSKIP_PATTERNSandAUDIT_EXPLICIT_PATTERNS; the target id is the path's trailing segment when numeric (a create or import under a site —/api/sites/3/holidays— has none), the actor thecurrent_userstash (id, email, name)get_current_userwrites.
Both derived tiers go through audit_log.record_detached(request, ...): its own session (resolve_tenant_session_factory(request) or get_session_factory()), committed at once, and it never raises — a failed row is logged and dropped, never failing the change. Credentials never reach a row: details passes through redact() (keys matching password|secret|token|api_key|... → ***), and the SSO routes report the client secret as set / not set only. Tests: the autouse audit_calls fixture (tests/conftest.py) stubs record and record_detached and collects (name, kwargs); the service's own tests use the real functions captured at import.
Approval workflow¶
Approval workflow for own bookings (app/services/approvals.py, routes app/routers/approvals.py). The eleven self-booking decision points (POST /projects/{id}/staff, /phases/{id}/staff, /subphases/{id}/staff, PUT/DELETE /assignments/{id}, /phase-staff/{id}, /subphase-staff/{id}, Kanban POST/DELETE assignees) all go one way: resolve_self_booking (creates) or approvals.resolve_row_write (existing rows) decides editor first; an "approval" outcome goes to approvals.submit_request, which answers 202 {success: true, pending: true, request_id, id} — never decide it on the client. A pending create is a real row (approval_status = 'pending', approval_request_id), excluded from availability, card access (card_access) and assignee notifications (card_assignee_ids); a pending update/removal leaves the row untouched and stores requested/previous on the request. Request statuses: pending → approved / rejected / cancelled / superseded / expired (close_reason: target_deleted, requester_inactive, permission_lost, overtaken, duplicate); a decision on a closed request is 409 {detail, status}. A create request whose requester is no longer bookable (users.is_resource false) expires permission_lost on approve; their update/removal requests stay approvable (existing bookings are kept). At phase/subphase level the request values carry the segment dates (booking_values; a relink is explicit null dates): _values_valid(level, values, context) checks them inside the card (load_context exposes target_start / target_end), _new_row / _write_values write them, _revalidate re-checks overlap for a create and for an update whose dates changed (expired(duplicate)) — an auto-placed create (requested.placement == "auto") is re-planned instead (plan_placement(..., approved_only=True); approve applies the shrink and the landed dates, keeps the marker and extends the effects, never assigns them) —, and a card move fits the dates stored in open requests (requested / previous) along with the rows (fit_card_bookings). Approvers are resolved live (approver_user_ids / can_decide: admins always, the PM when the policy's pm_approves, holders of the policy's roles — active, seeing the project's site, never the requester); approve re-validates in its transaction and closes the request expired(<reason>) with a 409 when the booking can no longer apply; stored values no longer valid for the request's level answer 409 INVALID_VALUES_DETAIL and leave it pending (reject it instead). Direct writes keep the workflow consistent: a second booking of the same person on a target is 409 at project level (pending included); on a phase/subphase explicit dates overlapping one of theirs are 409 ALREADY_BOOKED_OVERLAP_DETAIL, while a dateless create is placed (plan_placement → PlannedBooking, the card row then the person's rows on it locked FOR UPDATE, so placements on one card run one after another; requested carries placement: "auto"): no row → linked (PlannedBooking.first) — or, with link_first=False (the Kanban assignee POST: Join / Request to join / Assign; the phase / subphase staff POST with unpinned: true, the resource-panel drop), the card's own dates read from the locked card row, an unpinned first booking filed without the marker, so approve re-checks its overlap like the dialog's dated create instead of re-planning it into a linked row —, else the largest free stretch, else the one full-span row is halved (apply_shrink, response adjusted), else 409 CARD_FULL_DETAIL (ALREADY_PENDING_DETAIL when that full-span row is pending). In approval mode the request carries the planned dates and the full-span row is left alone until approve — in that window the half overlaps it; an editor's PUT/DELETE on a pending-create row is 409 "This booking awaits approval — approve or reject it instead"; a direct write on a row with an open request calls expire_overtaken; phase/subphase/project deletes call cancel_for_entity first; deactivating or deleting a requester (users.py PUT active=0, toggle-active, DELETE) calls expire_for_requester (requester_inactive). The to_decide list (My Work → My Approvals) holds the eligibility rule in SQL (decider_clause), so a page is never cut short. Every transition notifies (approval_requested / approval_decided), broadcasts change:approval_request (approve/reject also change:staff_assignment) and pushes approval:changed per user (publish, after the commit). Request note: the staff create routes' optional comment becomes the request's note in approval mode (no kanban.comment needed; the approvers' approval_requested body is mentions.comment_preview(note) — tokens stripped, then cut to 200). Approving a create posts a non-blank note to the booking's thread (card_comments.booking_thread: the card's, or ('project', project_id)) as the requester's comment inside the approval's transaction (_post_request_note) — only while the requester holds kanban.comment, else it stays on the request; mentions are re-derived at that moment (card_comments.validate_mention_ids, existing users), mention goes out with the requester as actor and never to the approver, no comment notifications. ApprovalEffects.comments makes publish broadcast change:card_comment, ApprovalEffects.notified_ids joins the requester in deliver's already_notified (one notification per person). Change requests, reject, cancel and expiry never post the note. A direct create with a comment needs kanban.comment (403 right after the 202 return, before apply_shrink or any write) and posts it in the booking's transaction (card_comments.stage_booking_comment): mention / comment without the actor, the booked person and the PM, whose change-notification bodies end with the preview (change_notifications.booking_intents(note=…) / with_note), and the staged recipients are deliver's already_notified.
Change notifications¶
Change notifications are delivered after the commit (app/services/change_notifications.py). When someone else adds, changes or removes a person's approved booking, moves or deletes the card it is on, or changes a project (fields name/dates/customer/confirmed/volume/archived/pm_id, phases/subphases added/moved/removed, equipment bookings, delete, an approval applied), the booked person gets assignment_changed and the project manager project_changed — nobody else, never the actor, never inactive users, never broadcast. Routes build plain-data ChangeIntents with the module's builders (old values captured before mutating, names of deleted things before the delete; {project} / {target} / {person} placeholders are filled by deliver) and call await change_notifications.deliver(db, request, actor_id, intents, already_notified=…) after their db.commit(). deliver merges to one row per recipient (assignment_changed outranks project_changed), then per row takes pg_advisory_xact_lock(hashtext("{user}|{type}|{project}|{actor}")) in sorted key order and folds it into the newest unread row with that key from the last 10 minutes (read FOR UPDATE: the recipient may delete that row, or the 30-day purge of GET /notifications remove it, between the read and the flushed UPDATE, which would then match nothing and roll the whole batch back — locked, their DELETE waits) (COALESCE_WINDOW, a sliding window: the merged row's created_at moves to the latest change; title N changes by <Actor> on <Project>, body the latest change) or inserts, commits its own short transaction, and pushes notification:new per row. A project delete has project_id = NULL and is never coalesced. This departs on purpose from the same-transaction rule of notifications.py (the lock must stay short, and the Gantt saves one drag as parallel PUTs whose notifications must merge); deliver works on its own session from the request's tenant factory and never touches the caller's db (a rollback there would expire the rows the route still reads for its response → MissingGreenlet 500 on a committed change); a failure is rolled back on that session and logged with its traceback, never fails the change. Only approved rows are bookings; 202 paths, no-op PUTs and reorders produce no intents. Route tests: the autouse change_intents fixture (tests/conftest.py) replaces deliver with a recorder of (actor_id, intents, already_notified) per call; tests/test_change_notifications.py tests the real function.
Booking segments¶
Booking segments are a mirror contract too. How unlinked phase/subphase bookings follow their card lives in app/services/booking_segments.py (fit_segments_to_card, segments_overlap, effective_dates), mirrored by fitSegmentsToCard / segmentsOverlap in frontend/src/utils/bookingSegments.ts: a move with the same duration translates every segment, any other change clamps (a segment fully outside goes against the nearest edge, length kept, capped to the card), unchanged dates are the identity; overlap is inclusive days (adjacent days do not overlap). A weekday move (2.7.0) is the third case, and it is asked for, never inferred: fit_segments_to_card(..., weekday_move=True) / fitSegmentsToCard(..., { weekdayMove: true }) moves each segment by as many Monday-to-Friday days as the card's start (shift_span_by_weekdays), keeps the weekdays it covers and then clamps it into the card. The Gantt drag sends it as weekday_move on the card PUT when the weekends are hidden and are not working days (a card there keeps its weekdays, so Monday-to-Friday becomes Tuesday-to-Monday and the calendar rule would read a resize); the dates alone cannot tell — Thursday-to-Tuesday moved to Friday-to-Wednesday is both a calendar and a weekday move, and a Friday segment goes to Saturday in one, to Monday in the other. The server applies the rule in the card PUT (approvals.fit_card_bookings, same transaction) and the client mirrors it locally without sending segment PUTs; tests/test_booking_segments.py / src/utils/__tests__/bookingSegmentsMirror.test.ts hold the same FIT_CASES / WEEKDAY_FIT_CASES / OVERLAP_CASES — change one, change both. clampToCard (a dragged segment kept inside its card, by calendar length or { weekdays: true }) is client-only: the server refuses a segment outside its card. A shrink may leave two segments of one person overlapping; that is stored as is (no merge, no refusal) until one of them is edited (409 then). New bookings are unpinned by default (2.1.0): AssignmentModal opens a first phase/subphase booking with the switch off and the card's dates prefilled and sent (the switch's default is reactive until touched: followCard = followCardChoice ?? secondBooking, so picking someone already on the card flips it on and the booking goes dateless to plan_placement), and the Kanban assignee POST and the resource-panel drop (a dateless phase / subphase staff POST with unpinned: true, 2.2.0; unpinned with dates is a 422) place a first booking with link_first=False; an unpinned booking is fitted (clipped / translated), never stretched, when its card moves — pinning (null dates) is the Gantt pin or the dialog switch. place_booking (where a dateless second booking goes: largest free stretch, ties earliest, else halve the one full-span booking, else None; PLACE_CASES) lives in the same module but is server-only, no mirror on purpose — the client never predicts a placement, it reloads after the POST.
Number field rounding¶
A number project field's decimals (0–3, NULL = as typed) is a small mirror contract (2.1.0). The server rounds a new value on write (project_field_rules.round_field_number, in validate_field_values; the site export rounds a stored value the same way), the client drafts and sends values the same way (roundFieldNumber in frontend/src/utils/projectFields.ts, used by draftFromValue / valueFromDraft and the number input's blur). Both round half-up, away from zero, on the value's shortest decimal string (Python Decimal(repr(v)).quantize(..., ROUND_HALF_UP), the client on String(v) with a BigInt carry) — never Python's round (half-to-even on the binary double) nor toFixed (1.005 → 1.00); doubles from 2^53 up are left as they are. tests/test_project_field_rules.py and src/utils/__tests__/projectFields.test.ts hold the same ROUNDING_CASES — change one, change both. Stored values are never rewritten when an admin changes decimals: readers round (formatFieldNumber for read-only display), and a value only shown rounded in the dialog is not re-sent unless edited.
Metric matrix¶
The metric matrix is a generated mirror (2.3.0), like shared/permission-keys.json: shared/metric-matrix.json (per measure {unit, dimensions, needs, filters, dimension_needs, filter_needs} in family order — the last two the family-specific keys of FAMILY_DIMENSION_NEEDS / FAMILY_FILTER_NEEDS, capacity person / person_ids → absences.view_others (a capacity per person shows that person's absence days), {} elsewhere; a top-level needs map — dimension kinds and filters → permission key, e.g. person / person_ids → views.staff, equipment / equipment_type / equipment_ids / equipment_types → views.equipment, archived → views.archived —; no_percent; term_measures and formula (2.6.0: the measures a calculated widget's terms may use and its limits, TERM_MEASURES / MAX_FORMULA_TERMS ↔ TERM_MEASURES / isTermMeasure / MAX_FORMULA_TERMS / MAX_FORMULA_LENGTH); relative periods; grains; measure_labels / dimension_labels / filter_labels / period_labels) is written by metrics.metric_matrix_json() (tests/test_metric_matrix.py fails when stale and prints the regeneration command); the hand-written MEASURES / MATRIX / MEASURE_FILTERS (Utilisation's project filters included, 2.6.0) / NEEDS / FAMILY_DIMENSION_NEEDS / FAMILY_FILTER_NEEDS / NO_PERCENT_MEASURES / TERM_MEASURES and the label lists (MEASURES, DIMENSION_KINDS, FILTER_LABELS, RELATIVE_PERIODS) in frontend/src/utils/metrics.ts are compared with it by src/utils/__tests__/metrics.test.ts (imported by the test, never at runtime). Change a measure, dimension or filter → regenerate the file and update utils/metrics.ts. The formula language of calculated widgets is a mirror too (2.6.0): app/services/formula.py (parse, canonical; evaluation is server-only) ↔ frontend/src/utils/formula.ts (parseFormula, canonical), the same FORMULA_CASES (expression → canonical form and names, or the exact error, a length pin on both sides) in tests/test_formula.py and src/utils/__tests__/formula.test.ts — change one, change both. The editor's formula field (utils/formulaField.ts) builds the expression from its measure pills and words the parser's refusals in its own terms; the server stays the judge. The recurring-absence parser is a mirror too: app/services/absence_patterns.py (parse_recurring_days, [R:d,…], 0 = Sunday) ↔ parseRecurringPattern in frontend/src/utils/recurringVacation.ts, the same PATTERN_CASES in tests/test_absence_patterns.py and recurringVacation.test.ts — change one, change both.
The working-day rule is a mirror too (2.5.0): app/services/working_days.py (is_working_day, count_working_days — arithmetic, never a walk over the range — and WORKING_DAYS_PER_WEEK, 5 or 7) ↔ frontend/src/utils/workingDays.ts (isWorkingDay, countWorkingDays, workingDaysPerWeek), the same WORKING_DAY_CASES (a day, the setting, a holiday → counts or not) and COUNT_CASES (a range with off days → its count) in tests/test_working_days.py and src/utils/__tests__/workingDayMirror.test.ts, each side asserting the tables' lengths — change one, change both. The same pair holds the weekday arithmetic (2.7.0) — add_weekdays / weekdays_between / shift_span_by_weekdays ↔ addWeekdays / weekdaysBetween / shiftSpanByWeekdays, with WEEKDAY_ADD_CASES, WEEKDAYS_BETWEEN_CASES and WEEKDAY_SHIFT_CASES — which is a separate rule: always Monday to Friday, with no weekend_working_days parameter, because it describes the columns of a Gantt whose weekends are hidden (a weekend day counts as the Monday after, where it is drawn; a span keeps the weekdays it covers, at least one). Don't give these helpers the flag, and don't use them to count working days. The drag uses them only when the weekend cells are hidden and weekend_working_days is off: with weekends working, the calendar length is the working days, so the Gantt keeps the calendar move. Day numbers on the client are calendar components in UTC (Date.UTC(y, m, d)), never elapsed local milliseconds, which are a day short in a zone that skipped a date (Pacific/Apia, 2011-12-30; workingDays.apia.test.ts). A working day is Monday to Friday, or every day when the instance setting weekend_working_days (Weekends are working days, off by default) is on; it is not a switch — instance_settings.weekends_working_from reads value.strip().lower() == "true", the client's selectWeekendsWorking a case-insensitive true (.trim().toLowerCase() === 'true'), so a missing or stray row keeps Monday to Friday (never flag_enabled / isSettingOn, which read "on unless false"). The server applies it once, in metrics.load_facts (Facts.weekends_working, passed keyword-only with default False to expand_holidays, person_off_days, equipment_off_days and absence_weekdays, then to WorkingCalendar), so with the setting off every dashboard number is the Monday-to-Friday one and the direct callers in the tests need no argument. The client applies it in calculateWorkloadCells (a non-working day is nonworking before an absence, a closure or a booking), the Weekend badges of StaffView / ResourceCard (staff cards), the Shift-hover work days (tooltipData; a weekend holiday counts only when weekends are working days, like the server) and the Gantt's absence markers at day zoom. show_weekends stays display only.
People you may name¶
One definition of "people you may name": app/services/people_lists.shareable_users_statement(site_ids) (active members of the given sites + every active user whose role sees every site — admins and roles allowing sites.view_all; None = every active user; IN subqueries, so each person once) feeds the Kanban @-mention picker (GET /kanban/sites/{id}/mentionable-users, one site) and the dashboard people picker (GET /dashboards/shareable-users) plus its PUT/POST check (the caller's visible sites). Callers add their own columns and ordering; don't open-code another "members + all-sites roles" query.
Frontend¶
Store ownership¶
Store ownership: domain data (sites/projects/staff/equipment/vacations/absence types/holidays/skills/tags/project fields/teams/roles + approval policies/settings) → appStore; view state (mode, zoom, expansion, scroll, current view, per-site project filter, Gantt group-by / colour-by, Kanban board preferences) → viewStore; transient UI (modals, drag/resize, dependency linking, context menus) → uiStore; What-If sandbox → whatIfStore; undo/redo snapshots → undoStore; custom-column data/filters/visibility → customColumnStore; admin portal → adminStore; notification inbox → notificationStore; My Work (requests to decide, own requests; My Assignments is derived from appStore.projects) → workStore; dashboards (list, the open dashboard, its widget data, the editing flag) → dashboardStore. Don't put domain data in uiStore or UI state in appStore. Selectors must not return a freshly allocated array or object (Zustand 5 re-renders forever — the old selectSiteProjects-style array selectors were removed for this): select the raw slice and filter with useMemo, or wrap the selector in useShallow.
Lazy Dashboards view¶
The Dashboards view is the one lazy-loaded view (2.3.0): MainLayout renders it through lazy(() => import('@/components/views/DashboardsView')) inside Suspense (LoadingScreen compact) and ErrorBoundary (src/components/common/ErrorBoundary, the app's first: a Notice plus Retry, which remounts the children), so ECharts and react-grid-layout stay in the DashboardsView-*.js chunk (named by the chunkFileNames rule in vite.config.ts). Never re-export it from the components/views/index.ts barrel or import echarts / react-grid-layout outside components/views/DashboardsView/ — the main chunk would pull them in. charts/EChart.tsx registers exactly what the nine widget kinds draw — BarChart, LineChart, PieChart, GaugeChart, HeatmapChart, TreemapChart, SankeyChart and GridComponent, TooltipComponent, LegendComponent, VisualMapComponent (the heatmap's colour scale, which ECharts 6 requires), DatasetComponent, AriaComponent, CanvasRenderer; a new series or component goes into that use([...]) list and into the echarts/charts / echarts/components mocks of EChart.test.tsx (Vitest throws on a missing named export). Tests mock echarts/core with a fake instance (charts/__tests__/EChart.test.tsx); charts/__tests__/realECharts.test.ts renders the gauge, heatmap, treemap and sankey options through the real ECharts (SSR SVG, no warning logged) — the only test that imports echarts itself; src/test/setup.ts stubs ResizeObserver.
What-If exemptions¶
New write endpoints are What-If-intercepted by default. The API client queues every POST/PUT/PATCH/DELETE while What-If mode is active, except URLs under /api/auth/, /api/settings/, /api/admin/, /api/notifications, the comment paths (/api/kanban/cards/{phase|subphase|project}/{id}/comments, /api/kanban/comments/{id}), the RBAC endpoints /api/roles, /api/permissions, /api/approval-policies (configuration), /api/dashboards (reports, never plan data — the builder preview POST must answer for real) and /api/approval-requests (a decision is a message to a person and cannot be rolled back — own bookings stay queued and a 202 on Apply becomes a request), and the configuration endpoints /api/tags, /api/project-fields, /api/teams, /api/absence-types, /api/skills, /api/equipment-types, /api/predefined-phases, /api/users, plus site and equipment definitions only (/api/sites, /api/sites/{id}, /api/equipment, /api/equipment/{id} — their calendar and booking sub-resources /api/sites/{id}/holidays|events, /api/events, /api/equipment-blocks, /api/equipment-assignments stay queued, they are plan data). Configuration is never part of the What-If snapshot, so queuing it only makes edits vanish and deletes fail on Apply; isWhatIfExempt() in src/api/client.ts is the one list (card moves and assignments stay queued — they are plan operations; comments are not, and a queued comment cannot be rolled back on Discard and would be duplicated on Apply). If a new endpoint must bypass What-If (rare), extend the exemption list in src/api/client.ts deliberately — and if it must be queued, ensure the local optimistic update is complete since the server won't respond for real.
Errors and confirmations¶
Errors show in place, never in alert(). A form or panel renders its message with the shared Notice (src/components/common/Notice, tone error/warning/info/success, role="alert" for errors); an action with no form of its own reports through uiStore.showFlash() (rendered by layout/FlashNotice). Confirmations go through confirmAction() (src/utils/confirmDialog.ts): await confirmAction({ message, title?, destructive?, confirmLabel?, cancelLabel?, confirmWord? }) resolves true/false; the one host ConfirmDialog (src/components/common/ConfirmDialog, mounted in App.tsx so the admin portal is covered too) renders it on the shared Modal with a danger Delete button when destructive; with confirmWord the confirm button stays disabled until that word is typed (Enter confirms once it matches). Never call window.confirm — a handler that confirms must be async and await the result, and confirm before taking a submit guard. Tests stub the service with stubConfirm(result) from src/test/confirmDialog.ts (restored after each test by test/setup.ts) and assert expect.objectContaining({ message }), never vi.spyOn(window, 'confirm'). A popup's destructive button that is itself the deliberate second step needs no confirmation: the dependency popup's Delete Dependency (click the arrow, then the button) deletes at once — a link is re-created by one drag.
Icons¶
Every icon is a Material icon from @mui/icons-material, drawn through src/components/common/Icon (icons.ts binds each app name — EditIcon, PlusIcon, … — to its Material component by deep path; <Icon icon={EditIcon} size={15} />, aria-hidden unless given a title, colour currentColor, outlined variants by default). size is the compact px: Icon renders calc(<size>px * var(--icon-scale)), 1.125 across the app and 1 inside .compact-ui, the rows and timelines of the Gantt, Staff & Calendar, Equipment, Cross-site and Archived views (their title strips take the app scale), which keep the compact text scale too. Add a new icon as one line in icons.ts, never an inline <svg>: src/components/__tests__/noInlineIcons.test.ts fails on any <svg> outside noInlineIconsAllowlist.json (Gantt dependency arrows, the Microsoft logo). No other MUI component, theme provider or sx — CSS Modules stay the rule; IconStyles in main.tsx (an Emotion cache with prepend) is the one Emotion setting, so a module rule on the svg wins a tie. See UI_GUIDELINES.md §3.14.
Dropdowns, popovers and menus¶
Dropdowns, popovers and menus dismiss through useDismissableOverlay (src/hooks/useDismissableOverlay.ts): outside mousedown, Tab out, capture-phase Escape with focus back on the trigger. Don't hand-roll a click-outside effect; the panel is a role="dialog" (checkbox/radio panels), role="menu" (ContextMenu) or a role="listbox" (MultiSelectDropdown, the dialog's multi-select field and Teams → members; SearchableSelect) with a name, and its trigger carries aria-expanded + aria-haspopup. A panel that must escape a clipping pane renders through AnchoredPanel (src/components/common/AnchoredPanel: portal to <body>, fixed, below or flipped above its trigger, measured max-height, focus sentinels) and passes its ref as the hook's panelRef; never inside a Modal (its Tab trap).
Form fields and date fields¶
Form fields are the shared Input / Select (src/components/common/Input|Select): every text-like <input> (text, email, password, number, …) and every <select> in a dialog, Settings panel, admin modal or login screen, with the visible label passed as label (or an aria-label); a list of people, or any list longer than a handful, is a SearchableSelect (src/components/common/SearchableSelect: a Select-looking trigger whose panel opens with a focused search Input as an ARIA combobox over the listbox, filtering label + hint from the first character; onChange only on a real change; Enter never submits the host form; test helpers in src/test/searchableSelect.ts), several people a MultiSelectDropdown searchable. The only raw ones left are documented exceptions (inline row-rename editors, the two ARIA comboboxes, the Gantt cell editor, the header SiteSelector, the phone-only Settings section picker, the credentials copy fields); src/components/__tests__/rawFormControls.test.ts counts raw controls per component against rawFormControlsAllowlist.json and fails when a count rises or the allowlist names a file that no longer needs it. A number with a format (a number project field, the built-in Volume) is a NumberFieldInput (src/components/modals/ProjectFieldInputs.tsx): type="number", step = the last kept decimal, and a controlled onChange gated by acceptsNumberText so a keystroke adding decimals past the format never lands; blur pads (12 → 12.0) and the server rounds as the guard. Dates are entered through DateRangeField / DateField (src/components/common/DateRangeField: a start/end pair on one two-month calendar, or a single date) — never a type="date" input. Values are YYYY-MM-DD strings ('' = none), the field text is formatMediumDate, the end can never precede the start (onChange({start, end}) once per click), weekends are muted and the header site's bank holidays and closures are marked from appStore; the Settings holiday/event forms pass markSiteCalendar={false} (they may edit another site). color-scheme is set once per theme in styles/variables.css / themes.css — never set it in a component stylesheet.
Permission gates on the frontend¶
Gate on permission keys, never on role names. Every check goes through src/utils/permissions.ts — can(user, key, project?) (a held key, or a PM_BUNDLE key on a project whose pm_id is the user while projects.manage_as_pm is held), canSelf / needsApproval (own bookings: allow or approval mode counts as "may"; the server decides the 202), canEditProject(ById), canEditAssignment(user, project, staffId, selfKey?), canBookSelf (also requires isBookable: is_resource !== false), canBookEquipment(ById/OnAny) (equipment_bookings.manage), canManageAbsencesOf, canManageAnyProject, isSelf — or the hooks useHasPermission / useNeedsApproval / useCan (src/hooks/useCan.ts); the helpers mirror app/services/project_access.py. The user's keys come from /auth/me (permissions = allow keys, approval_required, can_see_all_sites, role_name, mapped by transformUser); a user object without permissions is denied — there is no role fallback. Key spellings live in src/types/permissions.ts, mirrored from shared/permission-keys.json (permissions.catalogue.test.ts fails on drift). Visible sites come from useVisibleSites(), view access from useAllowedViews() (VIEW_PERMISSIONS), Settings sections from their permission field. The role literals left are in UsersPanel (ADMIN_ROLE_KEY): the "target is an admin" check (the backend's admin-ness rule) and the create default of Bookable as a resource (off for an admin role, like the backend's POST default).
Testing¶
Shared test helpers¶
Shared test helpers: frontend/src/test/factories.ts (makeProject, makePhase, makeSubphase, makeUser, makeStaff, makeSite, makeTeam, makeEquipment, makeVacation, makeTag, makeProjectField, makeProjectFieldOption, makeCustomColumn, makeRole / makeSystemRoles, makeApprovalRequest — each takes a Partial<T> override; makeUser derives permissions, role_name and can_see_all_sites from role unless given), frontend/src/test/permissionFixtures.ts (USER_DEFAULTS / SUPERUSER_DEFAULTS / ALL_PERMISSIONS, permissionsForRole, asSignedIn, makeCatalogue), frontend/src/test/datePicker.ts (pickRange / pickDate / pickEnd, openDateField, dateValue — assert a date field's data-value, never its locale text), frontend/src/test/searchableSelect.ts (pickOption / pickerOptions / pickerSearch / openPicker — a picker is found by a name regex, label + chosen value), tests/sqlite_support.py (an AsyncSession facade over a sync in-memory SQLite Session with every tenant table, CHECKs dropped — the dashboards route and loader tests override mock_db_session with it; aiosqlite is not a dependency), tests/conftest.py (FakeUser(role, permissions=…, site_ids=…) — permissions takes keys, a {key: mode} dict or a PermissionSet, default the role's shipped defaults; permissive_user(); the site_links fixture placing people, projects and equipment at sites) and tests/support.py (scalar_result, scalars_result, unique_scalar_result mock Result builders, fake_websocket(), the approval fakes ApprovalFakeDB / approval_request / pending_phase_row). Use them instead of redeclaring fixtures per file.
Schema-source tests (tests/test_dashboards_schema.py and its copy tests/test_dashboard_sharing_schema.py, like the teams / project-fields / notification-types ones) assert each DDL statement verbatim in every fresh source and the migration file, the parents-first order, the README row, the ORM matching the DDL, and the auto-migration step through a fake connection — a new auto-migration step means teaching the other steps' fakes its probe (or they ROLLBACK as "another step"). A self-gated DO block that SQLite cannot run is tested textually (two $$, no :word binds, its statements in order).
Load testing¶
scripts/loadtest/ (2.5.1, README) loads a real server the way browsers do: seed.py builds the pilot (5 sites, 33 projects, 50 equipment, 28 users) or stress (15 sites, 100 projects, 150 equipment, 90 users) workspace through the API; run.py signs every simulated browser in as its own user and replays the frontend's loadAllData startup (its Promise.all, the site calendar and custom columns, projects through GET /projects/details, or --projects detail for the pre-2.5.1 per-project loading), a writer during the startup, then a write burst with each browser's WebSocket refetch (slicesForEntity); journey.py runs one user's reads and writes against a server with DB_POOL_SIZE=1 DB_POOL_MAX_OVERFLOW=0 DB_POOL_TIMEOUT=5, where any code path needing two connections at once fails or stalls deterministically. The report has one line per endpoint (requests, non-2xx, median, p95, max); any non-2xx, a request over the ceiling (20 s under load, 3 s in the journey) or QueuePool limit / could not be written in the server log fails the run. scripts/loadtest/ci.sh runs all of it, locally or as the Load test job of backend.yml. No retries anywhere: under overload a retry only multiplies the load.
Documentation Screenshots¶
When asked to add, update, or refresh screenshots in the MkDocs docs (docs/), use the canonical capture pipeline in scripts/screenshots/ — do not capture by hand.
Pipeline: 1. Spin up the demo instance (self-contained Postgres + app on port 8486):
cp .env.example .env # if missing — generate SESSION_SECRET and TENANT_ENCRYPTION_KEY (64-char hex each)
docker compose -f docker-compose.fresh.yml up -d --build
docker exec milestone-fresh python -m app.scripts.seed_demo
demo (Demo Company) with the canonical projects (Bioprocess Scale-Up, Catalyst Optimization, Analytical Method Transfer, Quality System Upgrade) and everything the screenshots show: two dropdown project fields (Project type, Area), tags, subphases, dependencies, staff and equipment bookings, blocks, Swiss and German bank holidays, a site closure, every absence type, custom columns, Kanban comments and notifications, a Team Lead custom role, the User role booking itself with approval, Diana's pending request to join Bob's Bioprocess Scale-Up and a few tasks. The data is one Python module, app/scripts/demo_data.py (dates relative to the day you seed); the same seed runs in Codespaces, so there is no second SQL step. Login: admin@demo.local / demo1234 (and bob.brown@demo.local for multi-user collab shots). .env must set MULTI_TENANT=true, a TENANT_ENCRYPTION_KEY, and INIT_ADMIN_PASSWORD (deterministic admin-portal login for capture_admin.py) — see scripts/screenshots/README.md.
2. Install Playwright once:
python3 -m venv /tmp/pw-venv
/tmp/pw-venv/bin/pip install playwright
/tmp/pw-venv/bin/playwright install chromium
docs/assets/screenshots/, and must run in this order (capture_admin.py temporarily attaches the demo tenant to an SSO org and cleans up after itself):
/tmp/pw-venv/bin/python scripts/screenshots/capture.py # single-user shots
/tmp/pw-venv/bin/python scripts/screenshots/capture_collab.py # multi-user collab shots
INIT_ADMIN_PASSWORD=... /tmp/pw-venv/bin/python scripts/screenshots/capture_admin.py # admin portal
mkdocs build --strict (catches broken image refs).
All three capture scripts default to http://localhost:8486; set SCREENSHOT_BASE_URL (e.g. http://localhost:8487) to capture from another instance.
Without the Docker image (cloud sessions, where the image build cannot trust the session proxy's CA): run PostgreSQL alone in a container, the backend from a Python venv with uvicorn on 8485, build and deploy-react.sh the frontend before starting uvicorn, seed with python -m app.scripts.init_db then seed_demo, and capture with SCREENSHOT_BASE_URL=http://localhost:8485. Playwright must match the preinstalled Chromium (never playwright install). The step list is in scripts/screenshots/README.md → "Capturing without the Docker image".
Conventions the scripts enforce:
- Viewport 1440×900, light theme, en-US locale (pinned on the browser context), Gantt Q (Quarter) zoom — matches the existing screenshots' visual style.
- Capture against the demo tenant only — project names and dates are referenced in alt text and prose.
- Multi-user shots use two Playwright BrowserContexts in one browser (independent cookies, real WebSockets); User B drives events through ctx_b.request.* API calls so the WS broadcast fires naturally.
Adding a new shot: add a shot_<key> function to capture.py or capture_collab.py, register it in the targets map, reference the new PNG from a markdown page, then re-run capture + mkdocs build --strict. See scripts/screenshots/README.md for full details.
The scripts/screenshots/ Python scripts run their own Chromium and are always headless — they do not depend on the Claude Code Playwright MCP plugin. (If the user asks to make that plugin headless-by-default, edit both copies of .mcp.json under ~/.claude/plugins/.../playwright/ to add "--headless" to the args list and reload Claude Code.)