Fill the remaining coverage gaps in src/routes/admin-users.ts and add the
domain lifecycle test, bringing the file to 100% stmts/branch/funcs/lines.
New tests (apps/api/test/admin-users.test.ts):
- password route: 404 unknown id; 400 when better-auth setUserPassword throws
(driven via a spy so the catch path is deterministic).
- toListItem: a null DB role lists as 'worker' (nullish-coalescing fallback).
- role route: 400 on an invalid role body; 404 on an unknown id.
- reactivate route: 404 on an unknown id.
Lifecycle (apps/api/test/integration/user-lifecycle.test.ts): admin creates a
worker -> worker signs in and the bearer authorizes /api/me -> admin deactivates
(session rows deleted, so the pre-issued token 401s and fresh sign-in is blocked)
-> admin reactivates -> sign-in works again.
The two last-admin guards (role + deactivate routes) are unreachable over HTTP
(the self-demote / self-deactivate guards above already handle caller===target,
so any caller reaching them is a distinct active admin and
activeAdminsExcluding(target) >= 1). Annotated with /* c8 ignore */ + reasons
rather than left as silent gaps; the guard logic is unit-tested via
activeAdminsExcluding.
No production behavior changed; no bugs found.
Drives the report/export parts of src/routes/admin.ts to 100%
stmts/branch/funcs/lines. Adds one lifecycle test plus gap tests for the
previously-uncovered branches; no production behavior changed.
Tests added (apps/api/test):
- report.test.ts: invalid insole_type / non-numeric activity_id → 400;
activity filter narrows; null insole_type bucketed "Onbekend"; null
duration counts as 0 worked; export 400 on missing/inverted range.
Migrated the report + export describes to resetDb(beforeEach) so exact
totals are order-independent (removed the activity_id isolation
workaround in the all-users export test).
- integration/report-aggregation.test.ts: lifecycle — 2 workers × 2
activities × 2 types → exact totals + every by_worker/by_activity/
by_type row (values and worked-desc order) → user_id filter narrows.
Defensive annotations in admin.ts report loop (behavior unchanged):
- pausedSeconds/pairCount ?? 0 — NOT NULL columns, DB-impossible nulls.
- user_name/activity_name ?? 'Onbekend' — unreachable; userId FK cascades
on delete and activityId FK is enforced (libsql enforces FKs), so every
session always joins to a real user and activity.
No bugs found; the code was already correct.
Fills the session-part coverage gaps in src/routes/admin.ts (cross-user list,
active list, manual create/edit, admin stop/discard) and adds the admin↔worker
lifecycle test.
New route-level tests (apps/api/test/admin.test.ts):
- manual create: 400 on schema-invalid body; 400 when paused_seconds > span.
- edit: 404 non-numeric id; 400 schema-invalid body; 400 unparseable start_time;
400 paused_seconds > span; 404 unknown activity.
- stop: 404 non-numeric/unknown id; folds an open pause into paused_seconds.
- discard: 404 non-numeric/unknown id; 409 when already closed.
Lifecycle (apps/api/test/integration/admin-worker-session.test.ts): worker
starts → admin stops via the admin endpoint → session lands in /api/admin/report
and /api/admin/export with matching totals (uses resetDb for exact counts).
admin.ts session parts now at 100% stmts/lines; every session-part branch
covered. The one remaining session-part branch (row.pausedSeconds ?? 0 in the
stop route) is c8-ignored — paused_seconds is NOT NULL DEFAULT 0, so the null
branch is DB-impossible. The remaining uncovered branches in admin.ts are the
report/export parts, owned by the Reports domain (B-A6).
No behavior-changing bugs found; all session-part code was already correct.
Drives src/routes/sessions.ts and src/lib/work-session.ts to 100%
stmts/branch/funcs/lines (branch was 84.12% / 83.33%).
- sessions.test.ts: added error/edge branch tests — malformed-JSON start
(400), non-numeric id on pause/resume/stop/discard (404), pause/resume of a
no-longer-active session (409), discard missing (404) + already-closed (409),
stop missing (404), and discard ownership scoping (user B → 404).
- work-session.test.ts: mapper unit tests — null insoleType, nullish
pausedSeconds → 0, null durationSeconds/notes, full-field shape with
activity/user opts, and opts defaulting to undefined.
- test/integration/worker-session-lifecycle.test.ts: the anchor lifecycle test
(start→pause→resume→stop→history→export).
No bugs found — the code was correct. The two remaining uncovered branches were
the defensive `row.pausedSeconds ?? 0` guards in resume/stop; pausedSeconds is
NOT NULL DEFAULT 0 in the schema, so the null branch is unreachable via any
route. Annotated both with `/* c8 ignore next -- reason */` (comment only, no
behavior change).
Drives all infra src files to 100% (env.ts, db/client.ts, db/ensure-dir.ts,
db/migrate.ts, db/seed.ts, routes/health.ts).
- env.test.ts: dev defaults when unset, overrides when set (PORT coerced),
CORS_ORIGINS parsing (trim + drop empties) and empty-fallback.
- db.test.ts: runMigrations idempotency; ensureDbDir no-op for non-file URLs
and bare filenames (branch coverage).
- seed.test.ts: production guard — no dev users seeded when NODE_ENV=production.
- c8-ignore the migrate.ts/seed.ts CLI direct-run blocks (unreachable under vitest).
No lifecycle test (infra domain, per plan). No bugs found — infra code correct;
only coverage gaps. All 112 API tests green; typecheck + oxlint clean.
Sub
Phase 3b.1 needs admin-side write paths so an admin can hand-create a
session for a worker, correct any session, and stop/cancel a worker's
stuck active session — duration always derived server-side.
Adds under the existing /api/admin/* admin guard:
- GET /api/admin/users — {id,name,email} roster ordered by name (worker picker)
- POST /api/admin/sessions — manual create -> completed, source=manual,
duration = max(0, round((end-start)/1000) - paused)
- PUT /api/admin/sessions/:id — edit any session (no user reassignment);
recomputes duration when end_time present, else duration null
- POST /api/admin/sessions/:id/stop — fold open pause, end=now, completed
- POST /api/admin/sessions/:id/discard — status=discarded, end=now
Validates end>=start, pair_count>=1, paused<=span, activity/user exist
(400/404); stop/discard on an already-closed session -> 409. Responses
reuse toWorkSession.
Products affected: SoleLog backend (apps/api)
The repo was authored prettier-style (trailing-comma 'all') but .oxfmtrc.json
was set to 'es5', so every formatted file diverged. Switch the config to 'all'
to match the existing code, ignore docs/** and **/drizzle/** (prose + generated
snapshots the formatter should not own), and reformat the source tree once for
consistency. No behavioural change; all suites green (api 60, worker 28, admin 21).
Add user-scoped POST /api/sessions/:id/pause and /resume endpoints,
mirroring the stop handler's ownership/lookup and 401/404/409 guards.
Pause sets paused_at (status stays active); resume folds the open span
into paused_seconds and clears paused_at.
Change stop to fold any open pause span into paused_seconds, then set
duration_seconds = max(0, round((end-start)/1000) - paused_seconds) so
saved duration is worked time, and clear paused_at.
Add a "Paused Duration" column to /api/export (after "Total Duration")
using formatDuration(paused_seconds).
Products affected: SoleLog backend (apps/api)
Add `role: Role` to the shared `PublicUser` contract and return it from
`GET /api/me` (defaulting to 'worker' when the session user has no role).
This lets the planned admin app gate access by role.
Also add the admin dev origin `http://localhost:5174` to the default
`WEB_ORIGINS` (env.ts) and to `.env.example`, so the admin SPA on :5174 can
reach the API at :3000 cross-origin (drives both hono/cors and better-auth
trustedOrigins).
db:seed now also creates a ready-made dev account via better-auth (properly
hashed), idempotent, and SKIPPED when NODE_ENV=production so no known-password
account ships to prod. Credentials: worker@solelog.local / werkplaats123.
Documented in the worker README. API tests 37/37 green; verified live (sign-in
returns a bearer token; /api/me returns the user).
Phone/LAN testing previously required editing both app.ts (cors origin) and
auth.ts (better-auth trustedOrigins). Now both read env.WEB_ORIGINS, parsed from
a comma-separated CORS_ORIGINS env var (default http://localhost:5173). To test
from a phone, set CORS_ORIGINS to include the LAN origin and restart the API — no
code edit. Documented in .env.example. Also fixed the worker README (db:migrate
creates ./data/app.db, not ./.tmp; phone step now uses CORS_ORIGINS). API tests
36/36 green; typecheck clean.
A fresh local `yarn db:migrate`/`yarn dev` failed with SQLITE_CANTOPEN (14)
because libsql does not create the parent directory for a file: URL and the
gitignored apps/api/data/ does not exist on checkout. Added ensureDbDir() and
call it before createClient in both the client and the migrator. No-op for
non-file URLs and for the Docker /data volume. Verified: fresh db:migrate now
creates data/ and all tables; tests + typecheck still green; live round-trip
(/health, sign-up, sign-in, /api/me, 401) works.
The guard compared import.meta.url against `file://${process.argv[1]}`, which
never matches on Windows (argv[1] is a drive-letter/backslash path), so
`yarn db:migrate` silently no-opped for local non-Docker dev. Use
pathToFileURL(process.argv[1]).href instead, which is correct on Windows and
Linux alike. Verified `yarn db:migrate` now creates all tables on Windows; the
Docker start path is unaffected.
The Task 3 schema drifted from what better-auth@1.6.18's CLI generates: it used
mode:'timestamp' (epoch seconds) instead of 'timestamp_ms', left verification
timestamps nullable, and omitted the default expressions and helper indexes.
Regenerated src/db/schema.ts from `@better-auth/cli generate` (authoritative per
the plan's version-drift rule) and rebuilt migration 0000 from scratch (no data
exists yet). Converted the index callbacks from the CLI's array form to the
object form required by drizzle-orm@0.36.4's types. Adds session_userId_idx,
account_userId_idx, verification_identifier_idx and the unixepoch defaults.
Tests (health, db, auth sign-up/sign-in, /api/me round-trip) all pass; typecheck
clean; db:generate reports no pending changes.