Phase 3 planning
This commit is contained in:
@@ -0,0 +1,982 @@
|
||||
# VitFit V2 — API Routes
|
||||
|
||||
All routes prefixed `/api/v1/`. Auth header: `Authorization: Bearer <jwt>`.
|
||||
Response envelopes: see `API_STANDARDS.md`. Dates: ISO 8601 UTC strings.
|
||||
|
||||
Legend: `[T]` = requires authenticateToken `[O]` = Owner+ `[SA]` = SystemAdmin only `[F:x]` = requires feature flag
|
||||
|
||||
---
|
||||
|
||||
## Auth — /api/v1/auth
|
||||
|
||||
### POST /api/v1/auth/login
|
||||
No auth required.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"username": "coach1",
|
||||
"password": "secret",
|
||||
"rememberDevice": true,
|
||||
"deviceName": "Gym iPad",
|
||||
"deviceType": "kiosk"
|
||||
}
|
||||
```
|
||||
`rememberDevice`, `deviceName`, `deviceType` are optional (default: no device token).
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"jwt": "eyJ...",
|
||||
"deviceToken": "a3f9...",
|
||||
"user": { "id": 1, "username": "coach1", "role": "Coach", "firstName": "Jason", "organizationId": 1 }
|
||||
}
|
||||
}
|
||||
```
|
||||
`deviceToken` only present when `rememberDevice: true`. Store in localStorage as `deviceToken`.
|
||||
|
||||
Errors: `LOGIN_FAILED` (401), rate-limited after 10 attempts/15 min (429).
|
||||
|
||||
Two independent rate limits apply:
|
||||
- **Per-IP** — `express-rate-limit` middleware, 10 req/15 min per source IP.
|
||||
- **Per-username** — tracked in process memory by auth service. 10 failed attempts for the
|
||||
same `username` string within 15 minutes triggers immediate `LOGIN_FAILED` regardless of IP.
|
||||
Resets automatically on success or after 15 minutes. Prevents targeted account brute-force
|
||||
from rotating IPs.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/auth/device-login
|
||||
No auth required. Used on page load to silently re-authenticate.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{ "deviceToken": "a3f9..." }
|
||||
```
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"jwt": "eyJ...",
|
||||
"deviceToken": "b7e2...",
|
||||
"user": { "id": 1, "username": "coach1", "role": "Coach", "organizationId": 1 }
|
||||
}
|
||||
}
|
||||
```
|
||||
Old token is invalidated. New token replaces it in localStorage.
|
||||
|
||||
Errors: `AUTH_DEVICE_TOKEN_INVALID` (401).
|
||||
|
||||
Rate limited: same 10 req/15 min per-IP limiter as `/auth/login`. The token search space
|
||||
(32-byte random = 2²⁵⁶) makes brute force computationally infeasible; rate limiting prevents
|
||||
server load abuse and probing.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/auth/refresh-token
|
||||
`[T]`
|
||||
|
||||
No request body. Called by `core.js` when token is within 1 hour of expiry.
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{ "data": { "jwt": "eyJ..." } }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/auth/logout
|
||||
`[T]`
|
||||
|
||||
No request body. Logs audit event. JWT invalidation is client-side (delete from localStorage).
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
## Users — /api/v1/users
|
||||
|
||||
### GET /api/v1/users
|
||||
`[T]` `[O]`
|
||||
|
||||
Query: `?role=Coach&isActive=true&page=1&limit=50`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 2, "username": "jsmith", "email": "j@gym.com", "firstName": "John", "lastName": "Smith",
|
||||
"role": "Coach", "isActive": true, "lastLoginAt": "2025-06-10T14:22:00.000Z" }
|
||||
],
|
||||
"meta": { "total": 4, "page": 1, "limit": 50, "totalPages": 1 }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/users
|
||||
`[T]` `[O]`
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"username": "newcoach",
|
||||
"email": "coach@gym.com",
|
||||
"firstName": "Mike",
|
||||
"lastName": "Jones",
|
||||
"password": "initialPass123",
|
||||
"role": "Coach"
|
||||
}
|
||||
```
|
||||
`email`, `firstName`, `lastName` optional. `role` must be `Owner`, `Coach`, or `Client`.
|
||||
|
||||
Response 201: `{ "data": { ...user } }`
|
||||
|
||||
Errors: `CONFLICT` (409 duplicate username), `VALIDATION_FAILED` (400).
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/users/:id
|
||||
`[T]` `[O]`
|
||||
|
||||
Response 200: `{ "data": { ...user, deviceTokens: [ { id, deviceName, deviceType, lastUsedAt, expiresAt } ] } }`
|
||||
|
||||
Errors: `NOT_FOUND` (404).
|
||||
|
||||
---
|
||||
|
||||
### PATCH /api/v1/users/:id
|
||||
`[T]` Own profile only (any role) OR `[O]` for any user in org.
|
||||
|
||||
Request (any subset):
|
||||
```json
|
||||
{ "firstName": "Jason", "lastName": "A", "email": "new@email.com" }
|
||||
```
|
||||
|
||||
Response 200: `{ "data": { ...updatedUser } }`
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/users/:id
|
||||
`[T]` `[O]`
|
||||
|
||||
Soft deactivate. Not a true delete.
|
||||
|
||||
Response 204.
|
||||
|
||||
Errors: `LAST_OWNER_PROTECTED` (400), `NOT_FOUND` (404).
|
||||
|
||||
---
|
||||
|
||||
### PUT /api/v1/users/:id/role
|
||||
`[T]` `[O]`
|
||||
|
||||
Request: `{ "role": "Owner" }`
|
||||
|
||||
Response 200: `{ "data": { ...user } }`
|
||||
|
||||
Errors: `LAST_OWNER_PROTECTED` (400), `AUTH_FORBIDDEN` (403 if Owner tries to self-change).
|
||||
|
||||
---
|
||||
|
||||
### PUT /api/v1/users/:id/password
|
||||
`[T]` `[O]`
|
||||
|
||||
Request: `{ "newPassword": "newPass456" }`
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/users/:id/devices
|
||||
`[T]` Own devices (any role) OR `[O]` for any user in org.
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 3, "deviceName": "Gym iPad", "deviceType": "kiosk",
|
||||
"lastUsedAt": "2025-06-11T08:00:00.000Z", "expiresAt": "2025-09-09T08:00:00.000Z" }
|
||||
]
|
||||
}
|
||||
```
|
||||
Token hash is never returned.
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/users/:id/devices/:tokenId
|
||||
`[T]` Own devices (any role) OR `[O]`.
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
## Organization — /api/v1/org
|
||||
|
||||
### GET /api/v1/org
|
||||
`[T]`
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": 1, "name": "CrossFit Downtown", "slug": "crossfit-downtown",
|
||||
"timezone": "America/New_York", "features": ["client-management", "calendar"],
|
||||
"licenseOwner": "Jason A", "licenseEmail": "jason@gym.com"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### PATCH /api/v1/org
|
||||
`[T]` `[O]`
|
||||
|
||||
Request (any subset): `{ "name": "CrossFit Uptown", "timezone": "America/Chicago" }`
|
||||
|
||||
Response 200: `{ "data": { ...org } }`
|
||||
|
||||
Errors: `VALIDATION_FAILED` (400 invalid timezone).
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/org/branding
|
||||
`[T]`
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"appName": "CrossFit Downtown",
|
||||
"logoPath": "/api/v1/org/logo",
|
||||
"primaryColor": "#00FF88",
|
||||
"secondaryColor": "#4488FF",
|
||||
"workColor": "#00FF88",
|
||||
"restColor": "#4488FF",
|
||||
"moveColor": "#FF4444"
|
||||
}
|
||||
}
|
||||
```
|
||||
`logoPath` is `null` if no custom logo.
|
||||
|
||||
---
|
||||
|
||||
### PATCH /api/v1/org/branding
|
||||
`[T]` `[O]`
|
||||
|
||||
Request (any subset):
|
||||
```json
|
||||
{ "appName": "My Gym", "primaryColor": "#FF0066", "workColor": "#FF0066" }
|
||||
```
|
||||
|
||||
Response 200: `{ "data": { ...branding } }`
|
||||
|
||||
Errors: `VALIDATION_FAILED` (400, lists each color that fails contrast check).
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/org/logo
|
||||
`[T]` `[O]`
|
||||
|
||||
Body: `multipart/form-data`, field `logo` (image file).
|
||||
|
||||
Response 200: `{ "data": { "logoPath": "/api/v1/org/logo" } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/org/logo
|
||||
`[T]`
|
||||
|
||||
Streams logo file. Returns 404 if no custom logo set.
|
||||
|
||||
---
|
||||
|
||||
## Videos — /api/v1/videos
|
||||
|
||||
### GET /api/v1/videos
|
||||
`[T]` Coaches and above.
|
||||
|
||||
Query: `?category=Arm+Exercises&page=1&limit=50`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 5, "filename": "1718000000_abc123.mp4", "description": "Barbell curl",
|
||||
"category": "Arm Exercises", "mimeType": "video/mp4",
|
||||
"fileSizeBytes": 45020000, "createdAt": "2025-06-01T12:00:00.000Z",
|
||||
"streamUrl": "/api/v1/videos/stream/1718000000_abc123.mp4" }
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
`streamUrl` is included so the frontend doesn't need to construct URLs.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/videos
|
||||
`[T]` Coach+.
|
||||
|
||||
Body: `multipart/form-data`. Fields: `video` (file), `description` (string), `category` (string).
|
||||
|
||||
Pre-upload middleware: `checkUploadAllowed` (507 if disk low), multer file size limit.
|
||||
|
||||
Response 201: `{ "data": { ...video, streamUrl } }`
|
||||
|
||||
Errors: `UPLOAD_TYPE_INVALID` (400), `UPLOAD_SIZE_EXCEEDED` (400), `STORAGE_INSUFFICIENT` (507).
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/videos/:id
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 204.
|
||||
|
||||
Errors: `NOT_FOUND` (404).
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/videos/stream/:filename
|
||||
`[T]`
|
||||
|
||||
Streams video file. Supports `Range` header for seek (required by Safari).
|
||||
|
||||
Response 200 (full) or 206 (partial/range).
|
||||
Headers include `Accept-Ranges: bytes`, `Content-Type` from stored mimeType.
|
||||
|
||||
Errors: `NOT_FOUND` (404 — file not in DB for this org, or doesn't exist on disk).
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/categories
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 200: `{ "data": [ { "id": 1, "name": "Arm Exercises" }, ... ] }`
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/categories
|
||||
`[T]` Coach+.
|
||||
|
||||
Request: `{ "name": "Mobility" }`
|
||||
|
||||
Response 201: `{ "data": { "id": 7, "name": "Mobility" } }`
|
||||
|
||||
Errors: `CONFLICT` (409).
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/categories/:id
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 204.
|
||||
|
||||
Errors: `CONFLICT` (409 if videos exist in this category), `NOT_FOUND` (404).
|
||||
|
||||
---
|
||||
|
||||
## Workouts (Group Display) — /api/v1/workouts
|
||||
|
||||
### GET /api/v1/workouts
|
||||
`[T]` Coach+.
|
||||
|
||||
Query: `?page=1&limit=20`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": 10, "name": "Tuesday WOD", "workoutDate": "2025-06-11T00:00:00.000Z",
|
||||
"createdByUserId": 2,
|
||||
"videos": [
|
||||
{ "slot": 1, "video": { "id": 5, "description": "Barbell curl", "streamUrl": "..." }, "reps": 10 },
|
||||
{ "slot": 2, "video": null, "reps": null }
|
||||
]
|
||||
}
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
`video: null` when the referenced video has been deleted.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/workouts
|
||||
`[T]` Coach+.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"name": "Tuesday WOD",
|
||||
"workoutDate": "2025-06-11T00:00:00.000Z",
|
||||
"video1": 5, "number1": 10,
|
||||
"video2": 8, "number2": 12,
|
||||
"video3": null, "number3": null,
|
||||
"video4": null, "number4": null
|
||||
}
|
||||
```
|
||||
|
||||
Response 201: `{ "data": { ...workout with videos } }`
|
||||
|
||||
Errors: `VALIDATION_FAILED` (400, video IDs not in org).
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/workouts/today
|
||||
`[T]` Coach+.
|
||||
|
||||
No query params. Uses org timezone for "today" calculation.
|
||||
|
||||
Response 200 (collection — same shape as GET /workouts).
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/workouts/:id
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 200: `{ "data": { ...workout with videos } }`
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/workouts/:id
|
||||
`[T]` Coach (own only) or Owner (any).
|
||||
|
||||
Response 204.
|
||||
|
||||
Errors: `AUTH_FORBIDDEN` (403 if Coach tries to delete another's workout), `NOT_FOUND` (404).
|
||||
|
||||
---
|
||||
|
||||
## Timers — /api/v1/timers
|
||||
|
||||
### GET /api/v1/timers
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 3, "name": "HIIT 30/10", "totalTime": 1800, "setTime": 30, "restTime": 10,
|
||||
"moveTime": 15, "setCount": 3, "exerciseCount": 5, "lapCount": 2 }
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/timers
|
||||
`[T]` Coach+.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"name": "HIIT 30/10",
|
||||
"totalTime": 1800, "setTime": 30, "restTime": 10, "moveTime": 15,
|
||||
"setCount": 3, "exerciseCount": 5, "lapCount": 2
|
||||
}
|
||||
```
|
||||
|
||||
Response 201: `{ "data": { ...timer } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/timers/:id
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 200: `{ "data": { ...timer } }`
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/timers/:id
|
||||
`[T]` Coach (own) or Owner.
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/timers/:id/launch
|
||||
`[T]` Coach+.
|
||||
|
||||
No request body.
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{ "data": { "sessionId": "timer_3_1718273400000" } }
|
||||
```
|
||||
Client uses `sessionId` to join the Socket.io room.
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/timers/session
|
||||
`[T]` Coach+.
|
||||
|
||||
Request: `{ "sessionId": "timer_3_1718273400000" }`
|
||||
|
||||
Stops the active timer session.
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
## CrossFit Workouts — /api/v1/crossfit-workouts
|
||||
|
||||
### GET /api/v1/crossfit-workouts
|
||||
`[T]` Coach+.
|
||||
|
||||
Query: `?page=1&limit=20`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 7, "name": "Hero WOD Murph", "workoutDate": "2025-06-11T00:00:00.000Z",
|
||||
"workoutItems": ["1 mile run", "100 pull-ups", "200 push-ups", "300 squats", "1 mile run"],
|
||||
"createdByUserId": 2 }
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/crossfit-workouts
|
||||
`[T]` Coach+.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"name": "Hero WOD Murph",
|
||||
"workoutDate": "2025-06-11T00:00:00.000Z",
|
||||
"workoutItems": ["1 mile run", "100 pull-ups", "200 push-ups"]
|
||||
}
|
||||
```
|
||||
|
||||
Response 201: `{ "data": { ...crossfitWorkout } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/crossfit-workouts/:id
|
||||
`[T]` Coach+.
|
||||
|
||||
Response 200: `{ "data": { ...crossfitWorkout } }`
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/crossfit-workouts/:id
|
||||
`[T]` `[O]`
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
## Clients — /api/v1/clients
|
||||
|
||||
`[F:client-management]` All client endpoints require this feature flag.
|
||||
|
||||
### GET /api/v1/clients
|
||||
`[T]` Coach (own clients) or Owner (all).
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 9, "username": "athlete1", "firstName": "Sara", "lastName": "Kim",
|
||||
"email": "sara@email.com", "isActive": true,
|
||||
"coach": { "id": 2, "firstName": "John", "lastName": "Smith" } }
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/clients
|
||||
`[T]` `[O]` or Coach if org allows self-assign.
|
||||
|
||||
Creates a new Client user and optionally assigns a coach.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"username": "athlete2",
|
||||
"firstName": "Tom",
|
||||
"lastName": "Brady",
|
||||
"email": "tom@email.com",
|
||||
"password": "initialPass",
|
||||
"coachId": 2
|
||||
}
|
||||
```
|
||||
`coachId` optional.
|
||||
|
||||
Response 201: `{ "data": { ...user, coachLink? } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/clients/:id
|
||||
`[T]` Coach (own clients only) or Owner.
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"id": 9, "username": "athlete1", "firstName": "Sara", "lastName": "Kim",
|
||||
"coach": { "id": 2, "firstName": "John" },
|
||||
"upcomingSessionsCount": 3,
|
||||
"pendingWorkoutsCount": 2
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/clients/:id/assign
|
||||
`[T]` `[O]`
|
||||
|
||||
Request: `{ "coachId": 3 }`
|
||||
|
||||
Response 200: `{ "data": { "linkId": 14, "coachId": 3, "clientId": 9, "assignedAt": "..." } }`
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/clients/:id/assign
|
||||
`[T]` `[O]`
|
||||
|
||||
Request: `{ "linkId": 14 }`
|
||||
|
||||
Response 204.
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/clients/:id/workouts
|
||||
`[T]` Coach (own clients) or Client (own) or Owner.
|
||||
|
||||
Query: `?page=1&limit=20&includeCompleted=false`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 22, "name": "Monday Strength", "scheduledDate": "2025-06-12T00:00:00.000Z",
|
||||
"completedAt": null, "coachId": 2,
|
||||
"items": [
|
||||
{ "type": "video", "videoId": 5, "reps": 10, "sets": 3, "notes": "Full ROM",
|
||||
"streamUrl": "/api/v1/videos/stream/..." },
|
||||
{ "type": "text", "text": "Rest 2 min between sets" }
|
||||
]
|
||||
}
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/clients/:id/workouts
|
||||
`[T]` Coach (own clients only).
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"name": "Monday Strength",
|
||||
"scheduledDate": "2025-06-12T00:00:00.000Z",
|
||||
"notes": "Focus on form today.",
|
||||
"items": [
|
||||
{ "type": "video", "videoId": 5, "reps": 10, "sets": 3, "notes": "Full ROM" },
|
||||
{ "type": "text", "text": "Rest 2 min" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Response 201: `{ "data": { ...clientWorkout } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/clients/:id/workouts/:workoutId
|
||||
`[T]` Coach (own clients) or Client (own) or Owner.
|
||||
|
||||
Response 200: `{ "data": { ...clientWorkout with items } }`
|
||||
|
||||
---
|
||||
|
||||
### PATCH /api/v1/clients/:id/workouts/:workoutId
|
||||
`[T]` Coach (own clients only).
|
||||
|
||||
Request: any subset of `{ name, scheduledDate, notes, items }`.
|
||||
|
||||
Response 200: `{ "data": { ...updated } }`
|
||||
|
||||
---
|
||||
|
||||
### DELETE /api/v1/clients/:id/workouts/:workoutId
|
||||
`[T]` Coach (own clients only).
|
||||
|
||||
Soft delete. Response 204.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/clients/:id/workouts/:workoutId/complete
|
||||
`[T]` Coach (own clients) or Client (own).
|
||||
|
||||
No request body.
|
||||
|
||||
Response 200: `{ "data": { "completedAt": "2025-06-12T09:30:00.000Z" } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/clients/:id/sessions
|
||||
`[T]` Coach (own clients) or Client (own) or Owner.
|
||||
|
||||
Query: `?startAfter=2025-06-01&endBefore=2025-06-30&status=Scheduled&page=1&limit=20`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 31, "title": "Weekly Check-in", "sessionType": "Personal",
|
||||
"startAt": "2025-06-12T09:00:00.000Z", "endAt": "2025-06-12T10:00:00.000Z",
|
||||
"status": "Scheduled", "locationNotes": "Gym Floor B",
|
||||
"sharedNotes": "Bring your training log",
|
||||
"linkedWorkoutId": 22 }
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
`coachNotes` is stripped when requester is the Client.
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/clients/:id/sessions
|
||||
`[T]` Coach (own clients).
|
||||
|
||||
Request:
|
||||
```json
|
||||
{
|
||||
"title": "Weekly Check-in",
|
||||
"sessionType": "personal",
|
||||
"startAt": "2025-06-12T09:00:00.000Z",
|
||||
"endAt": "2025-06-12T10:00:00.000Z",
|
||||
"locationNotes": "Gym Floor B",
|
||||
"coachNotes": "Client struggling with squat depth",
|
||||
"sharedNotes": "Bring your training log",
|
||||
"linkedWorkoutId": 22
|
||||
}
|
||||
```
|
||||
|
||||
Response 201: `{ "data": { ...session } }`
|
||||
|
||||
---
|
||||
|
||||
### PATCH /api/v1/clients/:id/sessions/:sessionId
|
||||
`[T]` Coach (own) or Client (limited fields only).
|
||||
|
||||
Response 200: `{ "data": { ...updated } }`
|
||||
|
||||
---
|
||||
|
||||
### POST /api/v1/clients/:id/sessions/:sessionId/cancel
|
||||
`[T]` Coach or Client.
|
||||
|
||||
Response 200: `{ "data": { "status": "Cancelled" } }`
|
||||
|
||||
Errors: `CANCELLATION_TOO_LATE` (400) — Client attempting to cancel a session that starts in
|
||||
less than 24 hours. Coaches and Owners are not subject to this restriction.
|
||||
|
||||
---
|
||||
|
||||
## My (Client Self-Service) — /api/v1/my
|
||||
|
||||
### GET /api/v1/my/workouts
|
||||
`[T]` Client role only.
|
||||
|
||||
Alias for `GET /api/v1/clients/:ownId/workouts` scoped to the requesting client.
|
||||
|
||||
Response: same collection shape as client workouts.
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/my/sessions
|
||||
`[T]` Client role only.
|
||||
|
||||
Alias for `GET /api/v1/clients/:ownId/sessions`.
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/my/profile
|
||||
`[T]` Any role.
|
||||
|
||||
Returns own user record. Alias for `GET /api/v1/users/:ownId`.
|
||||
|
||||
---
|
||||
|
||||
### PUT /api/v1/my/password
|
||||
`[T]` Any role.
|
||||
|
||||
Allows any authenticated user to change their own password after verifying the current one.
|
||||
Owner-managed `PUT /api/v1/users/:id/password` does not require the current password;
|
||||
this endpoint does.
|
||||
|
||||
Request:
|
||||
```json
|
||||
{ "currentPassword": "oldPass123", "newPassword": "newPass456" }
|
||||
```
|
||||
|
||||
Response 204.
|
||||
|
||||
Errors: `AUTH_FORBIDDEN` (401 if `currentPassword` does not match stored hash), `VALIDATION_FAILED` (400).
|
||||
|
||||
---
|
||||
|
||||
## Calendar (Coach View) — /api/v1/calendar
|
||||
|
||||
### GET /api/v1/calendar
|
||||
`[T]` Coach+. `[F:calendar]`
|
||||
|
||||
Query: `?startAfter=2025-06-01&endBefore=2025-06-30`
|
||||
|
||||
Returns all sessions for the coach across all their clients, aggregated.
|
||||
|
||||
Response 200 (collection of CalendarSession).
|
||||
|
||||
**Phase 2 deferrals:** Conflict detection (overlapping sessions for same coach) and recurring
|
||||
sessions (RRULE / weekly repeat) are not implemented in V2 MVP. Every session is a standalone
|
||||
record. The API accepts overlapping bookings without error.
|
||||
|
||||
---
|
||||
|
||||
## Admin — /api/v1/admin
|
||||
|
||||
### GET /api/v1/admin/storage
|
||||
`[T]` `[O]`
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"disk": { "total": 53687091200, "used": 21474836480, "free": 32212254720, "usedPercent": 40 },
|
||||
"uploads": { "size": 4831838208, "fileCount": 47 },
|
||||
"warning": false,
|
||||
"warnThresholdBytes": 5368709120
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Audit Logs — /api/v1/audit-logs
|
||||
|
||||
### GET /api/v1/audit-logs
|
||||
`[T]` `[O]`
|
||||
|
||||
Query: `?action=video.upload&userId=2&entityType=video&from=2025-06-01&to=2025-06-30&page=1&limit=50`
|
||||
|
||||
Response 200 (collection):
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{ "id": 204, "userId": 2, "userRole": "Coach", "action": "video.upload",
|
||||
"entityType": "video", "entityId": 15,
|
||||
"details": { "filename": "1718...", "category": "Arm Exercises", "fileSizeBytes": 45020000 },
|
||||
"ipAddress": "192.168.1.5", "createdAt": "2025-06-11T14:23:00.000Z" }
|
||||
],
|
||||
"meta": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/audit-logs/export
|
||||
`[T]` `[O]`
|
||||
|
||||
Same query params as GET. Returns CSV stream.
|
||||
|
||||
Response headers:
|
||||
```
|
||||
Content-Type: text/csv
|
||||
Content-Disposition: attachment; filename="audit-log-2025-06-11.csv"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## System Admin — /api/v1/sysadmin
|
||||
|
||||
### GET /api/v1/sysadmin/orgs
|
||||
`[T]` `[SA]`
|
||||
|
||||
Response 200: All organizations with user count summary.
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/sysadmin/orgs/:id
|
||||
`[T]` `[SA]`
|
||||
|
||||
Response 200: Full org detail, branding, user list.
|
||||
|
||||
---
|
||||
|
||||
### PATCH /api/v1/sysadmin/orgs/:id
|
||||
`[T]` `[SA]`
|
||||
|
||||
Request: any subset of `{ name, timezone, features, isActive, licenseOwner, licenseEmail }`.
|
||||
|
||||
Response 200: `{ "data": { ...org } }`
|
||||
|
||||
---
|
||||
|
||||
### GET /api/v1/sysadmin/health
|
||||
`[T]` `[SA]`
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"status": "ok",
|
||||
"version": "1.0.0",
|
||||
"nodeVersion": "v20.11.0",
|
||||
"uptime": 86423,
|
||||
"db": { "status": "ok", "lastMigration": "005-add-video-mime-type" },
|
||||
"disk": { "free": 32212254720, "usedPercent": 40 },
|
||||
"activeTimerSessions": 0,
|
||||
"orgCount": 1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Health (No Auth)
|
||||
|
||||
### GET /health
|
||||
|
||||
Response 200:
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"version": "1.0.0",
|
||||
"uptime": 86423,
|
||||
"db": "ok",
|
||||
"diskAvailableGB": 30.0,
|
||||
"diskWarnActive": false
|
||||
}
|
||||
```
|
||||
Returns `"status": "degraded"` (still HTTP 200) if DB unreachable or disk in warning state.
|
||||
|
||||
---
|
||||
|
||||
## OpenAPI Spec
|
||||
|
||||
### GET /api/v1/openapi.yaml
|
||||
No auth required.
|
||||
|
||||
Returns the OpenAPI 3.0 spec for this API as a YAML file.
|
||||
Generated from code comments or a hand-maintained `openapi.yaml` in the project root.
|
||||
|
||||
Response headers:
|
||||
```
|
||||
Content-Type: application/yaml
|
||||
```
|
||||
|
||||
This endpoint is mentioned in `API_STANDARDS.md` as the authoritative spec location.
|
||||
@@ -0,0 +1,887 @@
|
||||
# VitFit V2 — Backend Method Maps
|
||||
|
||||
TypeScript-style signatures are used for clarity. The implementation is JavaScript (CommonJS).
|
||||
`Promise<T>` return types indicate async functions. All service functions throw `AppError` on failure.
|
||||
|
||||
---
|
||||
|
||||
## core/db.js
|
||||
|
||||
```js
|
||||
initDb(): Promise<Sequelize>
|
||||
```
|
||||
Creates Sequelize instance. Runs PRAGMAs. Returns sequelize.
|
||||
```
|
||||
PRAGMA journal_mode = WAL
|
||||
PRAGMA busy_timeout = 5000
|
||||
PRAGMA foreign_keys = ON
|
||||
```
|
||||
|
||||
```js
|
||||
runMigrations(): Promise<void>
|
||||
```
|
||||
Programmatically runs all pending sequelize-cli migrations in `modules/*/migrations/`.
|
||||
|
||||
```js
|
||||
models: {
|
||||
Organization, Branding,
|
||||
User, DeviceToken,
|
||||
Video, Category,
|
||||
Workout,
|
||||
Timer,
|
||||
CrossfitWorkout,
|
||||
CoachClientLink, ClientWorkout, CalendarSession,
|
||||
AuditLog
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## core/auth.js
|
||||
|
||||
```js
|
||||
authenticateToken(req, res, next): void
|
||||
```
|
||||
Reads `Authorization: Bearer <token>`. Verifies JWT against `JWT_SECRET` with algorithm
|
||||
pinned to `HS256`:
|
||||
```js
|
||||
jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }, (err, decoded) => { ... });
|
||||
```
|
||||
Algorithm pinning prevents RS256/none algorithm confusion attacks.
|
||||
|
||||
After signature verification, fetches the user row to check `passwordChangedAt`:
|
||||
```js
|
||||
if (user.passwordChangedAt && decoded.iat * 1000 < user.passwordChangedAt.getTime()) {
|
||||
return next(new AppError('AUTH_INVALID', 'Token issued before last password change.', 401));
|
||||
}
|
||||
```
|
||||
This ensures that tokens issued before a password change are rejected, even within their 7-day TTL.
|
||||
|
||||
Sets `req.user = { id, username, role, organizationId }` on success.
|
||||
Calls `next()` on success. Returns `AppError('AUTH_REQUIRED', ..., 401)` if no token,
|
||||
`AppError('AUTH_INVALID', ..., 401)` on invalid or pre-password-change token.
|
||||
|
||||
```js
|
||||
authenticateRole(roles: string[]): Middleware
|
||||
```
|
||||
Returns middleware. Checks `req.user.role` is in `roles`.
|
||||
Returns `AppError('AUTH_FORBIDDEN', ..., 403)` if not.
|
||||
Usage: `router.delete('/:id', authenticateToken, authenticateRole(['Owner', 'SystemAdmin']), handler)`
|
||||
|
||||
```js
|
||||
requireFeature(feature: string): Middleware
|
||||
```
|
||||
Returns middleware. Fetches org features from DB (cached 5 min per orgId).
|
||||
Returns `AppError('FEATURE_DISABLED', ..., 403)` if feature not in org's features array.
|
||||
Usage: `router.post('/', authenticateToken, requireFeature('client-management'), handler)`
|
||||
|
||||
---
|
||||
|
||||
## core/audit.js
|
||||
|
||||
```js
|
||||
log(
|
||||
req: Request,
|
||||
action: string,
|
||||
entityType: string | null,
|
||||
entityId: number | null,
|
||||
details: object
|
||||
): Promise<void>
|
||||
```
|
||||
Creates one AuditLog row. `req.user` provides userId, userRole, organizationId.
|
||||
`req.ip` and `req.get('User-Agent')` provide client info.
|
||||
On DB error: logs via pino at `warn` level and swallows — audit failure must never break the request.
|
||||
|
||||
---
|
||||
|
||||
## core/storage.js
|
||||
|
||||
```js
|
||||
getStorageInfo(): Promise<StorageInfo>
|
||||
```
|
||||
Returns:
|
||||
```js
|
||||
{
|
||||
disk: { total: number, used: number, free: number, usedPercent: number },
|
||||
uploads: { size: number, fileCount: number },
|
||||
warning: boolean // true when free < STORAGE_WARN_BYTES
|
||||
}
|
||||
```
|
||||
Result is cached for 60 seconds. Thread-safe: subsequent calls while in-flight share the same Promise.
|
||||
|
||||
```js
|
||||
checkUploadAllowed(req, res, next): Promise<void>
|
||||
```
|
||||
Middleware. Calls `getStorageInfo()`. Throws `AppError('STORAGE_INSUFFICIENT', ..., 507)` if `warning`.
|
||||
Applied to all upload routes before multer.
|
||||
|
||||
```js
|
||||
getUploadsSize(): Promise<{ size: number, fileCount: number }>
|
||||
```
|
||||
Internal. Reads `UPLOADS_DIR` synchronously (blocking but fast for < 1000 files),
|
||||
sums `stat.size` of each file. Returns totals.
|
||||
|
||||
---
|
||||
|
||||
## core/socket.js
|
||||
|
||||
```js
|
||||
init(httpServer: HttpServer): SocketIoServer
|
||||
```
|
||||
Attaches Socket.io to the HTTP server. Configures CORS. Registers `connection` handler.
|
||||
On `connection`: authenticates socket via JWT passed in `auth.token` handshake data.
|
||||
If auth fails, disconnects with error. Sets `socket.data.user` on success.
|
||||
Returns the `io` instance.
|
||||
|
||||
```js
|
||||
getIo(): SocketIoServer
|
||||
```
|
||||
Returns the singleton `io`. Throws if `init()` has not been called.
|
||||
|
||||
---
|
||||
|
||||
## core/errors.js
|
||||
|
||||
```js
|
||||
class AppError extends Error {
|
||||
constructor(code: string, message: string, status: number, field?: string)
|
||||
code: string
|
||||
status: number
|
||||
field: string | null
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
errorHandler(err, req, res, next): void
|
||||
```
|
||||
Express `(err, req, res, next)` middleware. Last middleware in `app.js`.
|
||||
If `err instanceof AppError`: responds with standard error envelope at `err.status`.
|
||||
Otherwise: logs at `error` level, responds 500 with generic message (hides internals in production).
|
||||
|
||||
---
|
||||
|
||||
## core/respond.js
|
||||
|
||||
```js
|
||||
ok(res: Response, data: object): void
|
||||
```
|
||||
Sends `200 { "data": data }`.
|
||||
|
||||
```js
|
||||
created(res: Response, data: object): void
|
||||
```
|
||||
Sends `201 { "data": data }`.
|
||||
|
||||
```js
|
||||
collection(res: Response, data: any[], total: number, page: number, limit: number): void
|
||||
```
|
||||
Sends `200 { "data": [...], "meta": { total, page, limit, totalPages } }`.
|
||||
|
||||
```js
|
||||
noContent(res: Response): void
|
||||
```
|
||||
Sends `204` with no body.
|
||||
|
||||
```js
|
||||
err(res: Response, code: string, message: string, status: number, field?: string): void
|
||||
```
|
||||
Sends `status { "error": { code, message, field } }`.
|
||||
|
||||
---
|
||||
|
||||
## modules/auth/service.js
|
||||
|
||||
```js
|
||||
login(
|
||||
username: string,
|
||||
password: string,
|
||||
rememberDevice: boolean,
|
||||
deviceName: string,
|
||||
deviceType: 'kiosk' | 'personal'
|
||||
): Promise<{ jwt: string, deviceToken?: string, user: UserPublic }>
|
||||
```
|
||||
**Per-username lockout (in addition to per-IP rate limit on the route):**
|
||||
Maintains a `Map<username, { count, resetAt }>` in process memory. On each failed attempt,
|
||||
increments the counter for that username. If `count >= 10` and `resetAt > Date.now()`, throws
|
||||
`AppError('LOGIN_FAILED', ..., 401)` immediately without hitting the DB. Resets automatically
|
||||
after 15 minutes. This prevents targeted account brute-force from IPs that rotate.
|
||||
|
||||
Finds User by username. Checks `isActive`. Compares password with bcrypt.
|
||||
On any failure: throws `AppError('LOGIN_FAILED', ..., 401)` — same error for unknown username,
|
||||
wrong password, and inactive account (no enumeration).
|
||||
On success: clears per-username failure counter. Signs JWT (7-day), creates DeviceToken if
|
||||
`rememberDevice`. Updates `lastLoginAt`. Logs `auth.login.success` audit event.
|
||||
|
||||
```js
|
||||
deviceLogin(
|
||||
rawToken: string,
|
||||
ipAddress: string,
|
||||
userAgent: string
|
||||
): Promise<{ jwt: string, newDeviceToken: string }>
|
||||
```
|
||||
Route-level rate limiter applied to `POST /auth/device-login` — same 10 req/15 min per-IP
|
||||
limiter as `/auth/login`. The token search space (32-byte random hex = 2²⁵⁶) makes brute force
|
||||
computationally infeasible, but rate limiting prevents this endpoint from being used as an
|
||||
amplification vector or server load probe.
|
||||
|
||||
Hashes `rawToken`. Finds DeviceToken by hash. Validates not revoked, not expired.
|
||||
Issues new JWT. Rotates device token (old revoked, new created with same TTL).
|
||||
Logs `auth.token.refreshed`. Returns new JWT + new raw device token.
|
||||
|
||||
```js
|
||||
refreshToken(userId: number): Promise<{ jwt: string }>
|
||||
```
|
||||
Signs a fresh JWT for the given userId. Called automatically when token < 1 hour from expiry.
|
||||
|
||||
```js
|
||||
createDeviceToken(
|
||||
userId: number,
|
||||
orgId: number,
|
||||
deviceName: string,
|
||||
deviceType: 'kiosk' | 'personal'
|
||||
): Promise<{ rawToken: string, record: DeviceToken }>
|
||||
```
|
||||
Generates `crypto.randomBytes(32).toString('hex')` as raw token.
|
||||
Stores bcrypt hash in DB. TTL: 90 days for kiosk, 30 days for personal.
|
||||
Returns raw token (only time it's in plaintext — not stored anywhere else).
|
||||
|
||||
```js
|
||||
hashToken(rawToken: string): string
|
||||
```
|
||||
Returns `crypto.createHash('sha256').update(rawToken).digest('hex')`.
|
||||
SHA-256 (not bcrypt) for token lookup — device tokens are long random strings, no need for bcrypt cost.
|
||||
|
||||
---
|
||||
|
||||
## modules/users/service.js
|
||||
|
||||
```js
|
||||
getUsers(
|
||||
orgId: number,
|
||||
filters: { role?: string, isActive?: boolean, page?: number, limit?: number }
|
||||
): Promise<{ rows: User[], count: number }>
|
||||
```
|
||||
Returns paginated users for the org. SystemAdmin can pass `orgId = null` to query across orgs.
|
||||
|
||||
```js
|
||||
getUserById(id: number, orgId: number): Promise<User>
|
||||
```
|
||||
Finds user by id within orgId. Throws `AppError('NOT_FOUND', ..., 404)` if not found.
|
||||
|
||||
```js
|
||||
createUser(
|
||||
orgId: number,
|
||||
data: { username, email?, firstName?, lastName?, password, role },
|
||||
actorId: number
|
||||
): Promise<User>
|
||||
```
|
||||
Validates role is not `SystemAdmin` (only setup script can create SystemAdmin).
|
||||
Password validated by Zod schema before reaching this method: minimum 8 characters,
|
||||
at most 128 characters. Bcrypt work factor: 12 rounds.
|
||||
Hashes password. Creates user. Logs `user.create` audit.
|
||||
Throws `AppError('CONFLICT', ..., 409)` on duplicate username.
|
||||
|
||||
```js
|
||||
deactivateUser(targetId: number, orgId: number, actorId: number): Promise<void>
|
||||
```
|
||||
Last Owner check: counts active Owners in org. If target is last Owner, throws `AppError('LAST_OWNER_PROTECTED', ..., 400)`.
|
||||
Sets `isActive = false`. Deactivates all DeviceTokens for the user. Logs `user.deactivate` audit.
|
||||
|
||||
```js
|
||||
changeRole(
|
||||
targetId: number,
|
||||
newRole: string,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<void>
|
||||
```
|
||||
Last Owner check if current role is `Owner` and new role is not `Owner`.
|
||||
Self-role-change check: actorId === targetId throws if actor is Owner.
|
||||
Updates role. Logs `user.role.change` audit.
|
||||
|
||||
```js
|
||||
resetPassword(
|
||||
targetId: number,
|
||||
newPassword: string,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<void>
|
||||
```
|
||||
Password validated by Zod schema: minimum 8, maximum 128 characters.
|
||||
Hashes new password (12 bcrypt rounds). Sets `passwordChangedAt = now()` alongside the hash
|
||||
update — this invalidates all JWTs issued before this moment (enforced by `authenticateToken`).
|
||||
Revokes all DeviceTokens for target user.
|
||||
Logs `user.password.reset` audit (no password in log).
|
||||
|
||||
```js
|
||||
changeOwnPassword(
|
||||
userId: number,
|
||||
currentPassword: string,
|
||||
newPassword: string
|
||||
): Promise<void>
|
||||
```
|
||||
`newPassword` validated by Zod schema: minimum 8, maximum 128 characters.
|
||||
Fetches user with password included (bypasses defaultScope). Verifies `currentPassword` against
|
||||
stored bcrypt hash — throws `AppError('AUTH_FORBIDDEN', 'Current password is incorrect.', 401)`
|
||||
on mismatch. Hashes new password (12 bcrypt rounds). Sets `passwordChangedAt = now()` — this
|
||||
invalidates all JWTs and device tokens issued before this moment. Revokes all DeviceTokens for
|
||||
the user (the calling session's JWT is still valid until it next hits `authenticateToken`, at
|
||||
which point it is rejected and the user re-authenticates). Logs `user.password.change` audit
|
||||
(no passwords in log).
|
||||
|
||||
```js
|
||||
updateProfile(
|
||||
userId: number,
|
||||
data: { firstName?, lastName?, email? }
|
||||
): Promise<User>
|
||||
```
|
||||
Updates own profile fields. Logs `user.profile.update` audit with before/after.
|
||||
|
||||
```js
|
||||
getDeviceTokens(userId: number, orgId: number): Promise<DeviceToken[]>
|
||||
```
|
||||
Returns non-revoked device tokens for a user. Returns metadata only — token hash never returned.
|
||||
|
||||
```js
|
||||
revokeDeviceToken(tokenId: number, userId: number, orgId: number): Promise<void>
|
||||
```
|
||||
Sets `isRevoked = true`. Validates token belongs to userId + orgId before revoking.
|
||||
Logs `auth.device.revoked` audit.
|
||||
|
||||
---
|
||||
|
||||
## modules/org/service.js
|
||||
|
||||
```js
|
||||
getOrg(orgId: number): Promise<Organization>
|
||||
```
|
||||
Returns org record. Includes Branding via eager load.
|
||||
|
||||
```js
|
||||
updateOrg(
|
||||
orgId: number,
|
||||
data: { name?, timezone?, licenseOwner?, licenseEmail? },
|
||||
actorId: number
|
||||
): Promise<Organization>
|
||||
```
|
||||
Validates timezone is a valid IANA string (check against `Intl.supportedValuesOf('timeZone')`).
|
||||
Logs `org.update` audit.
|
||||
|
||||
```js
|
||||
getBranding(orgId: number): Promise<Branding>
|
||||
```
|
||||
Returns branding for org. Creates default branding if not exists.
|
||||
|
||||
```js
|
||||
updateBranding(
|
||||
orgId: number,
|
||||
data: { appName?, primaryColor?, secondaryColor?, workColor?, restColor?, moveColor? },
|
||||
actorId: number
|
||||
): Promise<Branding>
|
||||
```
|
||||
Validates each color is a valid CSS hex (`/^#[0-9A-Fa-f]{6}$/`).
|
||||
Validates contrast ratio of each color against `#1a1a1a` (display background) is >= 4.5:1.
|
||||
Throws `AppError('VALIDATION_FAILED', ..., 400)` listing each failing color.
|
||||
Logs `branding.update` audit.
|
||||
|
||||
```js
|
||||
validateContrastRatio(hex: string, background: string): number
|
||||
```
|
||||
Internal. Converts hex to relative luminance, calculates WCAG contrast ratio.
|
||||
Returns ratio (e.g., `7.2`).
|
||||
|
||||
```js
|
||||
uploadLogo(orgId: number, file: MulterFile, actorId: number): Promise<Branding>
|
||||
```
|
||||
Validates MIME type via magic bytes (reads first 12 bytes from `file.path`).
|
||||
Allowed types: `image/png`, `image/jpeg`, `image/gif`, `image/webp`.
|
||||
Wraps in `try/finally` to clean up the multer temp file regardless of outcome:
|
||||
```js
|
||||
try {
|
||||
// validate, derive ext from detected MIME, save to UPLOADS_DIR
|
||||
} finally {
|
||||
await fs.promises.unlink(file.path).catch(() => {});
|
||||
}
|
||||
```
|
||||
Deletes old logo file if one existed. Updates `Branding.logoPath`.
|
||||
Logs `logo.upload` audit.
|
||||
|
||||
---
|
||||
|
||||
## modules/videos/service.js
|
||||
|
||||
```js
|
||||
getVideos(
|
||||
orgId: number,
|
||||
filters: { category?: string, page?: number, limit?: number }
|
||||
): Promise<{ rows: Video[], count: number }>
|
||||
```
|
||||
Paginated. Filters by category if provided. Orders by `createdAt DESC`.
|
||||
|
||||
```js
|
||||
uploadVideo(
|
||||
orgId: number,
|
||||
file: MulterFile,
|
||||
data: { description: string, category: string },
|
||||
actorId: number
|
||||
): Promise<Video>
|
||||
```
|
||||
Wraps upload logic in `try/finally` to guarantee temp file cleanup:
|
||||
```js
|
||||
try {
|
||||
const detectedMime = await validateMimeType(file.path);
|
||||
const ext = { 'video/mp4': '.mp4', 'video/quicktime': '.mov', 'video/x-m4v': '.m4v' }[detectedMime];
|
||||
// ext is derived from detected MIME — original filename extension is ignored
|
||||
const safeName = `${Date.now()}_${crypto.randomBytes(8).toString('hex')}${ext}`;
|
||||
await fs.promises.rename(file.path, path.join(UPLOADS_DIR, safeName));
|
||||
// create DB record ...
|
||||
} finally {
|
||||
await fs.promises.unlink(file.path).catch(() => {}); // clean up temp if rename failed
|
||||
}
|
||||
```
|
||||
`validateMimeType(file.path)` — opens the temp file with `fs.openSync`, reads exactly the
|
||||
first 12 bytes via `fs.readSync`, closes the file handle, then runs `fileTypeFromBuffer` on
|
||||
those 12 bytes. Throws `UPLOAD_TYPE_INVALID` if result is not `video/mp4`, `video/quicktime`,
|
||||
or `video/x-m4v`. Never loads the full file into memory. Multer must use disk storage
|
||||
(`multer({ dest: process.env.UPLOAD_TEMP_DIR })`) — NOT `memoryStorage()`.
|
||||
File extension is derived from the detected MIME type — the original uploaded filename
|
||||
extension is discarded to prevent serving a valid video file with a `.php` or `.html` extension.
|
||||
Creates Video record with `fileSizeBytes = file.size`.
|
||||
Logs `video.upload` audit.
|
||||
|
||||
```js
|
||||
deleteVideo(videoId: number, orgId: number, actorId: number): Promise<void>
|
||||
```
|
||||
Finds video (throws 404 if not found or wrong org).
|
||||
Deletes file from `UPLOADS_DIR` (ignores ENOENT — file already gone is fine).
|
||||
Deletes DB record.
|
||||
Logs `video.delete` audit with before snapshot.
|
||||
|
||||
```js
|
||||
getCategories(orgId: number): Promise<Category[]>
|
||||
```
|
||||
Returns all categories for org, ordered by name.
|
||||
|
||||
```js
|
||||
createCategory(
|
||||
orgId: number,
|
||||
name: string,
|
||||
actorId: number
|
||||
): Promise<Category>
|
||||
```
|
||||
Throws `CONFLICT` on duplicate. Logs `category.create` audit.
|
||||
|
||||
```js
|
||||
deleteCategory(
|
||||
categoryId: number,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<void>
|
||||
```
|
||||
Throws `CONFLICT` if any Video in this org has `category = category.name`.
|
||||
Deletes. Logs `category.delete` audit.
|
||||
|
||||
```js
|
||||
validateMimeType(filePath: string, allowedMimes: string[]): Promise<string>
|
||||
```
|
||||
Opens `filePath` with `fs.openSync`, reads exactly 12 bytes via `fs.readSync`, closes the
|
||||
file descriptor, then passes the 12-byte Buffer to `fileTypeFromBuffer` from the `file-type`
|
||||
package. Never loads the whole file into memory.
|
||||
`allowedMimes` is passed by the caller — video uploads use `['video/mp4', 'video/quicktime',
|
||||
'video/x-m4v']`; logo uploads use `['image/png', 'image/jpeg', 'image/gif', 'image/webp']`.
|
||||
Throws `AppError('UPLOAD_TYPE_INVALID', ..., 400)` if detected type is not in `allowedMimes`
|
||||
or is undetectable. Returns the detected MIME type string.
|
||||
|
||||
```js
|
||||
streamVideo(
|
||||
filename: string,
|
||||
orgId: number,
|
||||
rangeHeader: string | undefined,
|
||||
res: Response
|
||||
): Promise<void>
|
||||
```
|
||||
Validates `path.basename(filename) === filename` (path traversal guard).
|
||||
Verifies a Video record with this filename exists in orgId (throws 404 if not).
|
||||
Resolves full path, checks it starts with `path.resolve(UPLOADS_DIR)` (double-check).
|
||||
If `rangeHeader`: parses range, opens `fs.createReadStream(start, end)`, sends 206.
|
||||
Otherwise: sends 200 with full file stream.
|
||||
Sets `Content-Type` from `video.mimeType` stored in DB.
|
||||
|
||||
---
|
||||
|
||||
## modules/workouts/service.js
|
||||
|
||||
```js
|
||||
getWorkouts(
|
||||
orgId: number,
|
||||
filters: { page?: number, limit?: number }
|
||||
): Promise<{ rows: Workout[], count: number }>
|
||||
```
|
||||
Uses LEFT JOIN on all four video slots. Each slot may return null if video was deleted.
|
||||
Returns `[Video removed]` sentinel values handled by the model association.
|
||||
|
||||
```js
|
||||
getWorkoutById(id: number, orgId: number): Promise<Workout>
|
||||
```
|
||||
LEFT JOINs all four video associations. Throws 404 if not found in org.
|
||||
|
||||
```js
|
||||
getTodayWorkouts(orgId: number): Promise<Workout[]>
|
||||
```
|
||||
Fetches org timezone. Uses luxon to compute UTC start/end for today in org's local time.
|
||||
Queries `workoutDate BETWEEN todayStart AND todayEnd`.
|
||||
|
||||
```js
|
||||
createWorkout(
|
||||
orgId: number,
|
||||
data: { name, workoutDate, video1?, video2?, video3?, video4?, number1?, number2?, number3?, number4? },
|
||||
actorId: number
|
||||
): Promise<Workout>
|
||||
```
|
||||
Validates each non-null videoN ID belongs to orgId.
|
||||
Creates Workout. Logs `workout.create` audit.
|
||||
|
||||
```js
|
||||
deleteWorkout(id: number, orgId: number, actorId: number): Promise<void>
|
||||
```
|
||||
Ownership check: if `req.user.role === 'Coach'`, verifies `createdByUserId === actorId`.
|
||||
Owners can delete any workout. Deletes. Logs `workout.delete` audit.
|
||||
|
||||
---
|
||||
|
||||
## modules/timers/service.js
|
||||
|
||||
```js
|
||||
getTimers(orgId: number): Promise<Timer[]>
|
||||
```
|
||||
Returns all timers for org, ordered by `createdAt DESC`.
|
||||
|
||||
```js
|
||||
getTimerById(id: number, orgId: number): Promise<Timer>
|
||||
```
|
||||
Throws 404 if not found in org.
|
||||
|
||||
```js
|
||||
createTimer(
|
||||
orgId: number,
|
||||
data: { name, totalTime, setTime, restTime, moveTime, setCount, exerciseCount, lapCount },
|
||||
actorId: number
|
||||
): Promise<Timer>
|
||||
```
|
||||
Validates all time values are positive integers.
|
||||
Validates `totalTime >= setTime * setCount * exerciseCount * lapCount` (rough sanity check).
|
||||
Creates. Logs `timer.create` audit.
|
||||
|
||||
```js
|
||||
deleteTimer(id: number, orgId: number, actorId: number): Promise<void>
|
||||
```
|
||||
Ownership check (same as workouts). Stops active session if one exists for this timer.
|
||||
Deletes. Logs `timer.delete` audit.
|
||||
|
||||
```js
|
||||
launchTimer(timerId: number, orgId: number, actorId: number): Promise<{ sessionId: string }>
|
||||
```
|
||||
Fetches timer config. Generates `sessionId = 'timer_' + timerId + '_' + Date.now()`.
|
||||
Creates `TimerEngine` instance. Stores in active sessions Map under `sessionId`.
|
||||
Calls `engine.start()`. Logs `timer.launch` audit.
|
||||
Returns `{ sessionId }` — clients join this Socket.io room.
|
||||
|
||||
```js
|
||||
stopTimer(sessionId: string, orgId: number, actorId: number): Promise<void>
|
||||
```
|
||||
Finds engine by sessionId. Calls `engine.stop()`. Removes from Map. Logs `timer.stop` audit.
|
||||
|
||||
```js
|
||||
getActiveSession(orgId: number): Promise<{ sessionId, state } | null>
|
||||
```
|
||||
Returns the currently running timer session for the org, or null. One active session per org.
|
||||
|
||||
---
|
||||
|
||||
## modules/timers/timer-engine.js
|
||||
|
||||
```js
|
||||
class TimerEngine {
|
||||
constructor(config: TimerConfig, io: SocketIoServer, roomId: string)
|
||||
}
|
||||
```
|
||||
|
||||
**State:**
|
||||
```js
|
||||
{
|
||||
status: 'idle' | 'running' | 'paused' | 'complete',
|
||||
phase: 'set' | 'rest' | 'move',
|
||||
currentLap: number, // 1-indexed
|
||||
currentExercise: number, // 1-indexed
|
||||
currentSet: number, // 1-indexed
|
||||
phaseEndTime: bigint, // process.hrtime.bigint() target for phase end
|
||||
sessionEndTime: bigint, // process.hrtime.bigint() target for session end
|
||||
elapsedSeconds: number
|
||||
}
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
|
||||
```js
|
||||
start(): void
|
||||
```
|
||||
Sets initial state. Records `sessionStartHrTime`. Begins `_tick()` interval (every 100ms for responsiveness).
|
||||
Emits `timer:state` to room with full state snapshot.
|
||||
|
||||
```js
|
||||
stop(): void
|
||||
```
|
||||
Clears interval. Sets `status = 'complete'`. Emits `timer:stopped` to room. Cleans up.
|
||||
|
||||
```js
|
||||
getState(): TimerState
|
||||
```
|
||||
Returns current state snapshot. Called when a client reconnects to re-sync.
|
||||
|
||||
```js
|
||||
_tick(): void [private]
|
||||
```
|
||||
Called every 100ms. Computes `remaining = phaseEndTime - process.hrtime.bigint()` in nanoseconds.
|
||||
Emits `timer:tick` with `{ phaseRemainingMs, totalRemainingMs, ...state }` at most once per second
|
||||
(tracks last-emitted second to avoid flooding).
|
||||
Calls `_advancePhase()` when `phaseRemaining <= 0`.
|
||||
|
||||
```js
|
||||
_advancePhase(): void [private]
|
||||
```
|
||||
State machine transitions:
|
||||
```
|
||||
set → rest (if restTime > 0, else skip to move)
|
||||
rest → move (if moveTime > 0 and not last set, else skip)
|
||||
move → set (increment set counter; if set > setCount, increment exercise; if exercise > exerciseCount, increment lap)
|
||||
last lap + last exercise + last set → complete()
|
||||
```
|
||||
Sets new `phaseEndTime`. Emits `timer:phase-change` with `{ phase, lap, exercise, set }`.
|
||||
|
||||
```js
|
||||
complete(): void [private]
|
||||
```
|
||||
Clears the `setInterval`. Removes this engine from the active sessions `Map` in `service.js`.
|
||||
Sets `status = 'complete'`. Emits `timer:complete` to the room.
|
||||
Does NOT call `stop()` — natural completion and manual stop are distinct paths.
|
||||
`stop()` is only ever called by an explicit coach/owner stop request.
|
||||
|
||||
---
|
||||
|
||||
## modules/crossfit/service.js
|
||||
|
||||
```js
|
||||
getCrossfitWorkouts(
|
||||
orgId: number,
|
||||
filters: { page?: number, limit?: number }
|
||||
): Promise<{ rows: CrossfitWorkout[], count: number }>
|
||||
```
|
||||
Parses `workoutItems` JSON on each row before returning.
|
||||
|
||||
```js
|
||||
createCrossfitWorkout(
|
||||
orgId: number,
|
||||
data: { name, workoutDate, workoutItems: string[] },
|
||||
actorId: number
|
||||
): Promise<CrossfitWorkout>
|
||||
```
|
||||
Validates `workoutItems` via Zod: non-empty array, max 50 items, each item a non-empty
|
||||
string max 500 characters. Stores as JSON. Logs `crossfit.create` audit.
|
||||
|
||||
```js
|
||||
deleteCrossfitWorkout(
|
||||
id: number,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<void>
|
||||
```
|
||||
Owner-only (checked by route). Logs `crossfit.delete` audit.
|
||||
|
||||
---
|
||||
|
||||
## modules/clients/service.js
|
||||
|
||||
```js
|
||||
getClients(
|
||||
requesterId: number,
|
||||
orgId: number,
|
||||
requesterRole: string
|
||||
): Promise<User[]>
|
||||
```
|
||||
If `Owner | SystemAdmin`: returns all Client-role users in org.
|
||||
If `Coach`: returns only clients with an active CoachClientLink to requesterId.
|
||||
|
||||
```js
|
||||
getClientById(
|
||||
clientId: number,
|
||||
requesterId: number,
|
||||
orgId: number,
|
||||
requesterRole: string
|
||||
): Promise<User>
|
||||
```
|
||||
Includes active coach assignment. Access check: Coach can only get their own clients.
|
||||
Throws 404 if not found or not accessible.
|
||||
|
||||
```js
|
||||
assignCoach(
|
||||
clientId: number,
|
||||
coachId: number,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<CoachClientLink>
|
||||
```
|
||||
Validates both users exist in org and have correct roles.
|
||||
Deactivates any existing active link for this client+coach pair (idempotent upsert).
|
||||
Creates new link. Logs `coach.client.assign` audit.
|
||||
|
||||
```js
|
||||
unassignCoach(
|
||||
linkId: number,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<void>
|
||||
```
|
||||
Sets `isActive = false`. Logs `coach.client.unassign` audit.
|
||||
|
||||
```js
|
||||
getClientWorkouts(
|
||||
clientId: number,
|
||||
requesterId: number,
|
||||
orgId: number,
|
||||
requesterRole: string,
|
||||
filters: { page?, limit?, includeCompleted?: boolean }
|
||||
): Promise<{ rows: ClientWorkout[], count: number }>
|
||||
```
|
||||
Access check: Client sees only their own workouts. Coach sees only their clients' workouts.
|
||||
Parses `items` JSON on each row.
|
||||
**coachNotes stripping (server-enforced):** When `requesterRole === 'Client'`, the `notes`
|
||||
field (coach notes on the workout record) is deleted from each row before returning. Item-level
|
||||
`notes` within the `items` array are coaching instructions and remain visible to the client.
|
||||
|
||||
```js
|
||||
createClientWorkout(
|
||||
orgId: number,
|
||||
data: { clientId, name, scheduledDate, notes?, items },
|
||||
actorId: number
|
||||
): Promise<ClientWorkout>
|
||||
```
|
||||
Validates `items` via Zod: max 100 items; each `video` item must have a valid `videoId` in org;
|
||||
each `text` item must have a non-empty string max 1000 characters; item-level `notes` max 500
|
||||
characters. Validates coach has active link to client. Logs `client_workout.create` audit.
|
||||
|
||||
```js
|
||||
updateClientWorkout(
|
||||
id: number,
|
||||
orgId: number,
|
||||
data: Partial<ClientWorkoutData>,
|
||||
actorId: number
|
||||
): Promise<ClientWorkout>
|
||||
```
|
||||
Validates ownership (same coach). Logs `client_workout.update` audit with before/after.
|
||||
|
||||
```js
|
||||
deleteClientWorkout(
|
||||
id: number,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<void>
|
||||
```
|
||||
Soft delete: sets `deletedAt = now()`. Logs `client_workout.delete` audit.
|
||||
|
||||
```js
|
||||
completeClientWorkout(
|
||||
id: number,
|
||||
orgId: number,
|
||||
actorId: number
|
||||
): Promise<ClientWorkout>
|
||||
```
|
||||
Sets `completedAt = now()`. Both coach and client can call this. Logs `client_workout.complete` audit.
|
||||
|
||||
```js
|
||||
getSessions(
|
||||
filters: { clientId?, startAfter?, endBefore?, status?, page?, limit? },
|
||||
orgId: number,
|
||||
requesterId: number,
|
||||
requesterRole: string
|
||||
): Promise<{ rows: CalendarSession[], count: number }>
|
||||
```
|
||||
Scope: Coach sees own sessions. Client sees own sessions. Owner sees all.
|
||||
Strips `coachNotes` from response when requester is a Client.
|
||||
|
||||
```js
|
||||
createSession(
|
||||
orgId: number,
|
||||
data: { clientId?, title, sessionType, startAt, endAt, locationNotes?, coachNotes?, sharedNotes?, linkedWorkoutId? },
|
||||
actorId: number
|
||||
): Promise<CalendarSession>
|
||||
```
|
||||
Validates `endAt > startAt`. Validates linkedWorkoutId belongs to clientId if provided.
|
||||
Logs `session.create` audit.
|
||||
|
||||
```js
|
||||
updateSession(
|
||||
id: number,
|
||||
orgId: number,
|
||||
data: Partial<SessionData>,
|
||||
actorId: number
|
||||
): Promise<CalendarSession>
|
||||
```
|
||||
Validates ownership. Logs `session.update` audit with before/after.
|
||||
|
||||
```js
|
||||
cancelSession(
|
||||
id: number,
|
||||
orgId: number,
|
||||
actorId: number,
|
||||
actorRole: string
|
||||
): Promise<CalendarSession>
|
||||
```
|
||||
Sets `status = 'cancelled'`. Both coach and client can cancel.
|
||||
**24-hour rule (server-enforced):** If `actorRole === 'Client'` and
|
||||
`(new Date(session.startAt) - Date.now()) / 3600000 < 24`, throws
|
||||
`AppError('CANCELLATION_TOO_LATE', 'Sessions must be cancelled at least 24 hours in advance.', 400)`.
|
||||
Coaches and Owners bypass the 24-hour check.
|
||||
Client cancellation logs `session.cancel` with `cancelledBy: 'client'`.
|
||||
Logs `session.cancel` audit.
|
||||
|
||||
---
|
||||
|
||||
## modules/audit/routes.js
|
||||
|
||||
No service.js — reads directly from AuditLog model. Writes are via `core/audit.js`.
|
||||
|
||||
```js
|
||||
GET /api/v1/audit-logs
|
||||
→ authenticateToken, authenticateRole(['Owner', 'SystemAdmin'])
|
||||
→ Queries AuditLog with filters: action, userId, entityType, from, to
|
||||
→ Returns paginated collection
|
||||
|
||||
GET /api/v1/audit-logs/export
|
||||
→ authenticateToken, authenticateRole(['Owner', 'SystemAdmin'])
|
||||
→ Streams CSV response
|
||||
→ Sets Content-Disposition: attachment; filename="audit-log-<date>.csv"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## modules/sysadmin/routes.js
|
||||
|
||||
No service.js — uses models directly with cross-org queries (no orgId filter).
|
||||
|
||||
```js
|
||||
GET /api/v1/sysadmin/orgs
|
||||
→ authenticateToken, authenticateRole(['SystemAdmin'])
|
||||
→ Returns all orgs with user counts
|
||||
|
||||
GET /api/v1/sysadmin/orgs/:id
|
||||
→ authenticateToken, authenticateRole(['SystemAdmin'])
|
||||
→ Returns org detail with branding, user list summary
|
||||
|
||||
PATCH /api/v1/sysadmin/orgs/:id
|
||||
→ authenticateToken, authenticateRole(['SystemAdmin'])
|
||||
→ Updates timezone, features, isActive, licenseOwner, licenseEmail
|
||||
|
||||
GET /api/v1/sysadmin/health
|
||||
→ authenticateToken, authenticateRole(['SystemAdmin'])
|
||||
→ Returns full health details: version, DB migrations, storage, uptime, active timer sessions
|
||||
```
|
||||
@@ -0,0 +1,426 @@
|
||||
# VitFit V2 — Database Schema
|
||||
|
||||
Sequelize model definitions. Every model is defined in its module's `model.js` file
|
||||
and registered via `core/db.js`. Primary keys, `createdAt`, `updatedAt` are generated
|
||||
by Sequelize unless noted. `timestamps: false` is only used on AuditLog (no `updatedAt`).
|
||||
|
||||
---
|
||||
|
||||
## Associations Summary
|
||||
|
||||
```
|
||||
Organization hasOne Branding (via organizationId)
|
||||
Organization hasMany User (via organizationId)
|
||||
Organization hasMany Video (via organizationId)
|
||||
Organization hasMany Category (via organizationId)
|
||||
Organization hasMany Workout (via organizationId)
|
||||
Organization hasMany Timer (via organizationId)
|
||||
Organization hasMany CrossfitWorkout (via organizationId)
|
||||
Organization hasMany CoachClientLink (via organizationId)
|
||||
Organization hasMany ClientWorkout (via organizationId)
|
||||
Organization hasMany CalendarSession (via organizationId)
|
||||
|
||||
User hasMany DeviceToken (via userId)
|
||||
User hasMany CoachClientLink (as coach, via coachId)
|
||||
User hasMany CoachClientLink (as client, via clientId)
|
||||
User hasMany ClientWorkout (as coach, via coachId)
|
||||
User hasMany ClientWorkout (as client, via clientId)
|
||||
User hasMany CalendarSession (as coach, via coachId)
|
||||
User hasMany CalendarSession (as client, via clientId)
|
||||
|
||||
Workout belongsTo Video (as VideoOne, via video1)
|
||||
Workout belongsTo Video (as VideoTwo, via video2)
|
||||
Workout belongsTo Video (as VideoThree, via video3)
|
||||
Workout belongsTo Video (as VideoFour, via video4)
|
||||
|
||||
ClientWorkout belongsTo CalendarSession (via linkedWorkoutId, optional)
|
||||
```
|
||||
|
||||
AuditLog has no enforced FK associations (see DATA_MODEL.md rationale).
|
||||
|
||||
---
|
||||
|
||||
## Organizations
|
||||
|
||||
```js
|
||||
// modules/org/model.js
|
||||
Organization = sequelize.define('Organization', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
name: { type: DataTypes.STRING, allowNull: false },
|
||||
slug: { type: DataTypes.STRING, unique: true },
|
||||
timezone: { type: DataTypes.STRING, defaultValue: 'UTC' },
|
||||
features: { type: DataTypes.TEXT, defaultValue: '[]',
|
||||
get() { return JSON.parse(this.getDataValue('features') || '[]'); },
|
||||
set(v) { this.setDataValue('features', JSON.stringify(v)); } },
|
||||
isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
|
||||
licenseOwner: { type: DataTypes.STRING },
|
||||
licenseEmail: { type: DataTypes.STRING },
|
||||
});
|
||||
```
|
||||
|
||||
Hooks:
|
||||
```js
|
||||
Organization.beforeCreate(org => {
|
||||
if (!org.slug) {
|
||||
org.slug = org.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Brandings
|
||||
|
||||
```js
|
||||
// modules/org/model.js
|
||||
Branding = sequelize.define('Branding', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false, unique: true },
|
||||
appName: { type: DataTypes.STRING, defaultValue: 'VitFit' },
|
||||
logoPath: { type: DataTypes.STRING },
|
||||
primaryColor: { type: DataTypes.STRING, defaultValue: '#00FF88' },
|
||||
secondaryColor: { type: DataTypes.STRING, defaultValue: '#4488FF' },
|
||||
workColor: { type: DataTypes.STRING, defaultValue: '#00FF88' },
|
||||
restColor: { type: DataTypes.STRING, defaultValue: '#4488FF' },
|
||||
moveColor: { type: DataTypes.STRING, defaultValue: '#FF4444' },
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Users
|
||||
|
||||
```js
|
||||
// modules/users/model.js
|
||||
User = sequelize.define('User', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER }, // nullable for SystemAdmin
|
||||
username: { type: DataTypes.STRING, allowNull: false, unique: true },
|
||||
email: { type: DataTypes.STRING, unique: true },
|
||||
password: { type: DataTypes.STRING, allowNull: false },
|
||||
role: { type: DataTypes.ENUM('SystemAdmin', 'Owner', 'Coach', 'Client'),
|
||||
allowNull: false, defaultValue: 'Coach' },
|
||||
firstName: { type: DataTypes.STRING },
|
||||
lastName: { type: DataTypes.STRING },
|
||||
isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
|
||||
lastLoginAt: { type: DataTypes.DATE },
|
||||
passwordChangedAt: { type: DataTypes.DATE }, // set on every password change/reset; null for new accounts
|
||||
});
|
||||
```
|
||||
|
||||
Instance method:
|
||||
```js
|
||||
User.prototype.toPublic = function() {
|
||||
const { password, ...rest } = this.toJSON();
|
||||
return rest; // password never sent in responses
|
||||
};
|
||||
```
|
||||
|
||||
Default scope (always applied):
|
||||
```js
|
||||
User.addScope('defaultScope', { attributes: { exclude: ['password', 'passwordChangedAt'] } });
|
||||
```
|
||||
Both `password` and `passwordChangedAt` are excluded from all normal queries.
|
||||
`authenticateToken` and `changeOwnPassword` explicitly select these fields when needed.
|
||||
|
||||
---
|
||||
|
||||
## DeviceTokens
|
||||
|
||||
```js
|
||||
// modules/auth/model.js
|
||||
DeviceToken = sequelize.define('DeviceToken', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
userId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
token: { type: DataTypes.STRING, allowNull: false, unique: true }, // SHA-256 hash
|
||||
deviceName: { type: DataTypes.STRING },
|
||||
deviceType: { type: DataTypes.ENUM('kiosk', 'personal'), defaultValue: 'personal' },
|
||||
lastUsedAt: { type: DataTypes.DATE },
|
||||
expiresAt: { type: DataTypes.DATE, allowNull: false },
|
||||
isRevoked: { type: DataTypes.BOOLEAN, defaultValue: false },
|
||||
});
|
||||
```
|
||||
|
||||
Index:
|
||||
```js
|
||||
DeviceToken.addIndex(['token']); // lookup by hash
|
||||
DeviceToken.addIndex(['userId', 'isRevoked']); // list user's active tokens
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Videos
|
||||
|
||||
```js
|
||||
// modules/videos/model.js
|
||||
Video = sequelize.define('Video', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
filename: { type: DataTypes.STRING, allowNull: false },
|
||||
description: { type: DataTypes.STRING },
|
||||
category: { type: DataTypes.STRING },
|
||||
mimeType: { type: DataTypes.STRING },
|
||||
fileSizeBytes: { type: DataTypes.INTEGER },
|
||||
});
|
||||
```
|
||||
|
||||
Virtual field appended in service layer (not stored):
|
||||
```js
|
||||
// In service.getVideos() — appended after DB query:
|
||||
video.streamUrl = `/api/v1/videos/stream/${video.filename}`;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Categories
|
||||
|
||||
```js
|
||||
// modules/videos/model.js
|
||||
Category = sequelize.define('Category', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
name: { type: DataTypes.STRING, allowNull: false },
|
||||
});
|
||||
|
||||
Category.addIndex(['organizationId', 'name'], { unique: true });
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Workouts
|
||||
|
||||
```js
|
||||
// modules/workouts/model.js
|
||||
Workout = sequelize.define('Workout', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
name: { type: DataTypes.STRING },
|
||||
workoutDate: { type: DataTypes.DATE },
|
||||
video1: { type: DataTypes.INTEGER },
|
||||
video2: { type: DataTypes.INTEGER },
|
||||
video3: { type: DataTypes.INTEGER },
|
||||
video4: { type: DataTypes.INTEGER },
|
||||
number1: { type: DataTypes.INTEGER },
|
||||
number2: { type: DataTypes.INTEGER },
|
||||
number3: { type: DataTypes.INTEGER },
|
||||
number4: { type: DataTypes.INTEGER },
|
||||
createdByUserId: { type: DataTypes.INTEGER },
|
||||
});
|
||||
|
||||
// Associations (using aliases to resolve 4x FK to same table)
|
||||
Workout.belongsTo(Video, { foreignKey: 'video1', as: 'VideoOne', constraints: false });
|
||||
Workout.belongsTo(Video, { foreignKey: 'video2', as: 'VideoTwo', constraints: false });
|
||||
Workout.belongsTo(Video, { foreignKey: 'video3', as: 'VideoThree', constraints: false });
|
||||
Workout.belongsTo(Video, { foreignKey: 'video4', as: 'VideoFour', constraints: false });
|
||||
// constraints: false — allows hard-deleted videos without FK violation
|
||||
```
|
||||
|
||||
Index:
|
||||
```js
|
||||
Workout.addIndex(['organizationId', 'workoutDate']); // used by today-workouts query
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Timers
|
||||
|
||||
```js
|
||||
// modules/timers/model.js
|
||||
Timer = sequelize.define('Timer', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
name: { type: DataTypes.STRING, allowNull: false },
|
||||
totalTime: { type: DataTypes.INTEGER, allowNull: false },
|
||||
setTime: { type: DataTypes.INTEGER, allowNull: false },
|
||||
restTime: { type: DataTypes.INTEGER, defaultValue: 0 },
|
||||
moveTime: { type: DataTypes.INTEGER, defaultValue: 0 },
|
||||
setCount: { type: DataTypes.INTEGER, allowNull: false },
|
||||
exerciseCount: { type: DataTypes.INTEGER, allowNull: false },
|
||||
lapCount: { type: DataTypes.INTEGER, defaultValue: 1 },
|
||||
createdByUserId: { type: DataTypes.INTEGER },
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CrossfitWorkouts
|
||||
|
||||
```js
|
||||
// modules/crossfit/model.js
|
||||
CrossfitWorkout = sequelize.define('CrossfitWorkout', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
name: { type: DataTypes.STRING },
|
||||
workoutDate: { type: DataTypes.DATE },
|
||||
workoutItems: {
|
||||
type: DataTypes.TEXT,
|
||||
get() { return JSON.parse(this.getDataValue('workoutItems') || '[]'); },
|
||||
set(v) { this.setDataValue('workoutItems', JSON.stringify(v)); },
|
||||
},
|
||||
createdByUserId: { type: DataTypes.INTEGER },
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CoachClientLinks
|
||||
|
||||
```js
|
||||
// modules/clients/model.js
|
||||
CoachClientLink = sequelize.define('CoachClientLink', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
coachId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
clientId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
|
||||
assignedAt: { type: DataTypes.DATE, defaultValue: DataTypes.NOW },
|
||||
assignedByUserId:{ type: DataTypes.INTEGER },
|
||||
});
|
||||
|
||||
CoachClientLink.addIndex(['coachId', 'clientId', 'isActive']);
|
||||
CoachClientLink.addIndex(['clientId', 'isActive']); // find active coach for a client
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ClientWorkouts
|
||||
|
||||
```js
|
||||
// modules/clients/model.js
|
||||
ClientWorkout = sequelize.define('ClientWorkout', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
clientId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
coachId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
name: { type: DataTypes.STRING },
|
||||
scheduledDate: { type: DataTypes.DATE },
|
||||
notes: { type: DataTypes.TEXT },
|
||||
items: {
|
||||
type: DataTypes.TEXT,
|
||||
get() { return JSON.parse(this.getDataValue('items') || '[]'); },
|
||||
set(v) { this.setDataValue('items', JSON.stringify(v)); },
|
||||
},
|
||||
completedAt: { type: DataTypes.DATE },
|
||||
deletedAt: { type: DataTypes.DATE }, // soft delete
|
||||
});
|
||||
|
||||
ClientWorkout.addScope('active', { where: { deletedAt: null } });
|
||||
// All queries use: ClientWorkout.scope('active').findAll(...)
|
||||
```
|
||||
|
||||
Index:
|
||||
```js
|
||||
ClientWorkout.addIndex(['clientId', 'deletedAt', 'scheduledDate']);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CalendarSessions
|
||||
|
||||
```js
|
||||
// modules/clients/model.js
|
||||
CalendarSession = sequelize.define('CalendarSession', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
coachId: { type: DataTypes.INTEGER, allowNull: false },
|
||||
clientId: { type: DataTypes.INTEGER }, // nullable = group session
|
||||
title: { type: DataTypes.STRING },
|
||||
sessionType: { type: DataTypes.ENUM('personal', 'group', 'assessment', 'other'),
|
||||
defaultValue: 'personal' },
|
||||
startAt: { type: DataTypes.DATE, allowNull: false },
|
||||
endAt: { type: DataTypes.DATE, allowNull: false },
|
||||
locationNotes: { type: DataTypes.STRING },
|
||||
coachNotes: { type: DataTypes.TEXT },
|
||||
sharedNotes: { type: DataTypes.TEXT },
|
||||
status: { type: DataTypes.ENUM('scheduled', 'completed', 'cancelled', 'no-show'),
|
||||
defaultValue: 'scheduled' },
|
||||
linkedWorkoutId: { type: DataTypes.INTEGER },
|
||||
});
|
||||
```
|
||||
|
||||
Index:
|
||||
```js
|
||||
CalendarSession.addIndex(['coachId', 'startAt']);
|
||||
CalendarSession.addIndex(['clientId', 'startAt']);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## AuditLogs
|
||||
|
||||
```js
|
||||
// modules/audit/model.js
|
||||
AuditLog = sequelize.define('AuditLog', {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
organizationId: { type: DataTypes.INTEGER }, // no FK constraint — intentional
|
||||
userId: { type: DataTypes.INTEGER }, // no FK constraint — intentional
|
||||
userRole: { type: DataTypes.STRING },
|
||||
action: { type: DataTypes.STRING, allowNull: false },
|
||||
entityType: { type: DataTypes.STRING },
|
||||
entityId: { type: DataTypes.INTEGER },
|
||||
details: {
|
||||
type: DataTypes.TEXT,
|
||||
get() { try { return JSON.parse(this.getDataValue('details') || '{}'); } catch { return {}; } },
|
||||
set(v) { this.setDataValue('details', JSON.stringify(v)); },
|
||||
},
|
||||
ipAddress: { type: DataTypes.STRING },
|
||||
userAgent: { type: DataTypes.STRING },
|
||||
}, {
|
||||
updatedAt: false, // audit logs have no updatedAt
|
||||
createdAt: 'createdAt',
|
||||
});
|
||||
```
|
||||
|
||||
Indexes:
|
||||
```js
|
||||
AuditLog.addIndex(['organizationId', 'createdAt']); // paginate by org
|
||||
AuditLog.addIndex(['userId']); // filter by user
|
||||
AuditLog.addIndex(['action']); // filter by action type
|
||||
AuditLog.addIndex(['entityType', 'entityId']); // find all logs for a specific record
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Migration Numbering
|
||||
|
||||
```
|
||||
modules/*/migrations/
|
||||
├── 001-baseline.js V1 tables (idempotent — skips if tables exist)
|
||||
├── 002-organizations.js Create Organizations, Brandings tables; seed one org + branding
|
||||
├── 003-users-v2.js Add organizationId, email, firstName, lastName, isActive, lastLoginAt to Users
|
||||
├── 004-videos-v2.js Add organizationId, mimeType, fileSizeBytes to Videos
|
||||
├── 005-categories-v2.js Add organizationId to Categories
|
||||
├── 006-workouts-v2.js Add organizationId, createdByUserId to Workouts
|
||||
├── 007-timers-v2.js Add organizationId, name, createdByUserId to Timers
|
||||
├── 008-crossfit-v2.js Add organizationId, createdByUserId to CrossfitWorkouts
|
||||
├── 009-device-tokens.js Create DeviceTokens table
|
||||
├── 010-coach-client-links.js Create CoachClientLinks table
|
||||
├── 011-client-workouts.js Create ClientWorkouts table (with deletedAt)
|
||||
├── 012-calendar-sessions.js Create CalendarSessions table
|
||||
├── 013-audit-logs.js Create AuditLogs table
|
||||
└── 014-users-password-changed-at.js Add passwordChangedAt column to Users (nullable, no default)
|
||||
```
|
||||
|
||||
Migration 001 checks table existence before creating — safe to run against the populated V1 database.
|
||||
Migrations 002+ are additive only (addColumn, createTable) — no data destroyed.
|
||||
|
||||
---
|
||||
|
||||
## Soft Delete vs. Hard Delete Reference
|
||||
|
||||
| Entity | Delete behavior | Restorable? | Notes |
|
||||
|---|---|---|---|
|
||||
| User | Soft — `isActive = false` | Yes (Owner can reactivate) | Record preserved; history intact |
|
||||
| Organization | Soft — `isActive = false` | Yes (SystemAdmin only) | |
|
||||
| CoachClientLink | Soft — `isActive = false` | Yes (reassign flow) | Old link deactivated, new link created |
|
||||
| ClientWorkout | Soft — `deletedAt` timestamp | Yes (no UI, but data recoverable by DB) | `scope('active')` hides it |
|
||||
| CalendarSession | Soft — `status = 'cancelled'` | No (status change, not hidden) | Remains in history |
|
||||
| Video | Hard — DB record + file removed | No | File on disk is deleted immediately |
|
||||
| Workout | Hard — DB record removed | No | Video FKs use `constraints: false` so video deletion doesn't cascade |
|
||||
| Timer | Hard — DB record removed | No | In-memory sessions already gone if server restarted |
|
||||
| CrossfitWorkout | Hard — DB record removed | No | |
|
||||
| Category | Hard — blocked if videos exist in it | N/A (blocked, not deleted) | Returns `CONFLICT` |
|
||||
| DeviceToken | Hard — DB record removed | No (user must re-login to get new token) | |
|
||||
| AuditLog | Never deleted | N/A | Append-only; no delete endpoint |
|
||||
| Branding | Never deleted | N/A | Updated in-place; one per org |
|
||||
@@ -0,0 +1,394 @@
|
||||
# VitFit V2 — File Structure
|
||||
|
||||
Every file in the deployed application with its purpose and primary exports.
|
||||
|
||||
---
|
||||
|
||||
## Root
|
||||
|
||||
```
|
||||
/home/ubuntu/site/
|
||||
├── app.js
|
||||
├── .env
|
||||
├── package.json
|
||||
├── openapi.yaml
|
||||
├── CHANGELOG.md
|
||||
├── scripts/
|
||||
├── core/
|
||||
├── modules/
|
||||
├── public/
|
||||
├── tests/
|
||||
└── uploads/
|
||||
```
|
||||
|
||||
### CHANGELOG.md
|
||||
|
||||
Human-readable release notes for the gym owner/operator.
|
||||
Not a git log — describes user-visible changes in plain language.
|
||||
Template per release:
|
||||
```markdown
|
||||
## [1.x.x] — YYYY-MM-DD
|
||||
### What's new
|
||||
- ...
|
||||
### Fixed
|
||||
- ...
|
||||
### Notes for update
|
||||
- Run `npm install` if listed
|
||||
- Run `node_modules/.bin/sequelize db:migrate` if listed
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## app.js — Main Entry Point
|
||||
|
||||
Boots the application. Does not export anything — side effect only.
|
||||
|
||||
Responsibilities:
|
||||
1. Load `.env`
|
||||
2. Initialize pino logger
|
||||
3. Run database migrations via `core/db.js`
|
||||
4. Create Express app, apply global middleware
|
||||
5. Auto-load all modules from `modules/*/routes.js`
|
||||
6. Attach Socket.io via `core/socket.js`
|
||||
7. Register the global error handler
|
||||
8. Start HTTP server on `PORT`
|
||||
9. Signal PM2 ready (`process.send('ready')`)
|
||||
|
||||
Global middleware stack (in order):
|
||||
1. `helmet()` — security headers (including CSP — see ARCHITECTURE.md)
|
||||
2. `cors()` — CORS (restrict origin in production via `CORS_ORIGIN` env)
|
||||
3. `express.json({ limit: '64kb' })` — JSON body parser with explicit size cap; prevents DoS via large payloads
|
||||
4. `express.static('public')` — serve frontend HTML/JS/CSS
|
||||
5. `authRateLimiter` applied to both `POST /api/v1/auth/login` AND `POST /api/v1/auth/device-login` — 10 req/15 min per IP
|
||||
|
||||
**Static HTML security model:** HTML files are served publicly — no server-side auth gate
|
||||
on the HTML delivery itself. Auth is enforced on every API call: `core.js` runs on every
|
||||
page load, checks localStorage for a valid JWT, and redirects to `/` if missing or expired.
|
||||
This is the standard SPA/MPA pattern: the server trusts the client to request only data the
|
||||
user is authorized for, and the API enforces that boundary. Sensitive data (workouts, videos,
|
||||
client records) is never embedded in static HTML.
|
||||
|
||||
**Multer disk storage:** All file upload routes use `multer({ dest: process.env.UPLOAD_TEMP_DIR })`.
|
||||
`UPLOAD_TEMP_DIR` defaults to `/tmp/vitfit-uploads`. The service reads magic bytes from the temp
|
||||
file path (not `file.buffer`) and then moves the file to `UPLOADS_DIR`. `memoryStorage()` is
|
||||
never used — loading a 500 MB video into memory on a 4 GB server would be unsafe.
|
||||
|
||||
---
|
||||
|
||||
## .env — Environment Variables
|
||||
|
||||
```
|
||||
PORT=3000
|
||||
JWT_SECRET=<long random string>
|
||||
DB_PATH=/home/ubuntu/site/database.sqlite
|
||||
UPLOADS_DIR=/home/ubuntu/site/uploads
|
||||
UPLOAD_TEMP_DIR=/tmp/vitfit-uploads # multer disk storage temp dir
|
||||
BACKUP_UPLOADS_DEST=/mnt/backup/uploads
|
||||
CORS_ORIGIN=https://yourdomain.com
|
||||
UPLOAD_MAX_BYTES=524288000 # 500 MB
|
||||
STORAGE_WARN_BYTES=5368709120 # 5 GB
|
||||
NODE_ENV=production
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## scripts/
|
||||
|
||||
```
|
||||
scripts/
|
||||
├── setup.js First-run bootstrap: create org, branding, owner, sysadmin
|
||||
├── support-bundle.js Print diagnostic info for support (redacted of PII)
|
||||
├── backup.sh SQLite backup script (called by cron)
|
||||
└── backup-uploads.sh Weekly rsync of uploads/ to off-server backup location
|
||||
```
|
||||
|
||||
### scripts/setup.js
|
||||
|
||||
Interactive CLI. Reads `.env`, connects to DB, refuses to run if any Organization exists.
|
||||
Creates: Organization, Branding (defaults), Owner user, SystemAdmin user in one transaction.
|
||||
Exits with code 1 on any error.
|
||||
|
||||
### scripts/support-bundle.js
|
||||
|
||||
Non-interactive. Prints JSON/text summary to stdout: app version, Node version,
|
||||
migration status, DB size, uploads size, disk available, org count, user counts, PM2 status,
|
||||
last 5 error log lines (redacted). Safe to share.
|
||||
|
||||
### scripts/backup.sh
|
||||
|
||||
Called by cron. Runs `sqlite3 $DB_PATH ".backup '$BACKUP_PATH'"`.
|
||||
Cleans backups older than 14 days in the backup directory.
|
||||
|
||||
### scripts/backup-uploads.sh
|
||||
|
||||
Called by weekly cron. Runs `rsync -av --checksum $UPLOADS_DIR/ $BACKUP_UPLOADS_DEST/`.
|
||||
`BACKUP_UPLOADS_DEST` is a separate directory or mount (configure in `.env`).
|
||||
Logs output to `/var/log/vitfit-uploads-backup.log`. Does not delete from source.
|
||||
|
||||
---
|
||||
|
||||
## core/
|
||||
|
||||
```
|
||||
core/
|
||||
├── db.js Sequelize instance, PRAGMA config, model registry, migration runner
|
||||
├── auth.js Middleware: authenticateToken, authenticateRole, requireFeature
|
||||
├── audit.js Audit log helper: log()
|
||||
├── storage.js Disk stats, upload size cache, upload guard middleware
|
||||
├── socket.js Socket.io server init and io accessor
|
||||
├── logger.js Pino logger instance (exported as singleton)
|
||||
├── errors.js AppError class and global Express error handler
|
||||
├── respond.js Response helper functions: ok, created, collection, err
|
||||
└── schemas/
|
||||
├── auth.js Zod schemas for /auth/* request bodies
|
||||
├── users.js Zod schemas for /users/* request bodies
|
||||
├── org.js Zod schemas for /org/* request bodies
|
||||
├── videos.js Zod schemas for /videos/* request bodies
|
||||
├── workouts.js Zod schemas for /workouts/* request bodies
|
||||
├── timers.js Zod schemas for /timers/* request bodies
|
||||
├── crossfit.js Zod schemas for /crossfit-workouts/* request bodies
|
||||
└── clients.js Zod schemas for /clients/* request bodies
|
||||
```
|
||||
|
||||
`core/schemas/` — All Zod validation schemas. Each route imports its schema and runs
|
||||
`schema.safeParse(req.body)`, throwing `AppError('VALIDATION_FAILED', ...)` if invalid.
|
||||
Centralizing schemas here keeps routes thin and makes schemas testable in isolation.
|
||||
|
||||
### core/db.js
|
||||
Exports: `{ sequelize, models, initDb, runMigrations }`
|
||||
|
||||
`initDb()` — Creates Sequelize instance pointed at `DB_PATH`. Applies PRAGMAs.
|
||||
`runMigrations()` — Programmatically runs sequelize-cli pending migrations.
|
||||
`models` — Object keyed by model name containing all Sequelize model classes.
|
||||
|
||||
### core/auth.js
|
||||
Exports: `{ authenticateToken, authenticateRole, requireFeature }`
|
||||
|
||||
Middleware functions used as route-level Express middleware.
|
||||
|
||||
### core/audit.js
|
||||
Exports: `{ log }`
|
||||
|
||||
`log(req, action, entityType, entityId, details)` — Inserts one AuditLog row.
|
||||
Does not throw; errors are caught and logged via pino (audit failure must not break the request).
|
||||
|
||||
### core/storage.js
|
||||
Exports: `{ getStorageInfo, checkUploadAllowed }`
|
||||
|
||||
`getStorageInfo()` — Returns `{ disk, uploads, warning }`. Disk result cached 60 seconds.
|
||||
`checkUploadAllowed` — Express middleware. Calls `getStorageInfo()`, returns 507 if `warning`.
|
||||
|
||||
### core/socket.js
|
||||
Exports: `{ init, getIo }`
|
||||
|
||||
`init(httpServer)` — Attaches Socket.io. Registers connection/disconnect handlers.
|
||||
`getIo()` — Returns the `io` singleton. Used by timer-engine.js.
|
||||
|
||||
### core/logger.js
|
||||
Exports: pino logger instance with `level` set from `LOG_LEVEL` env (default `'info'`).
|
||||
|
||||
### core/errors.js
|
||||
Exports: `{ AppError, errorHandler }`
|
||||
|
||||
`AppError` — extends Error. Fields: `code`, `message`, `status`, `field`.
|
||||
`errorHandler` — Express `(err, req, res, next)` middleware. Converts AppError to standard
|
||||
response shape. Logs 5xx errors via pino.
|
||||
|
||||
### core/respond.js
|
||||
Exports: `{ ok, created, collection, err }`
|
||||
|
||||
Thin wrappers that produce the standard response envelopes from `API_STANDARDS.md`.
|
||||
|
||||
---
|
||||
|
||||
## modules/
|
||||
|
||||
Each module is a self-contained feature unit. Structure:
|
||||
|
||||
```
|
||||
modules/<name>/
|
||||
├── routes.js Express Router. Composes middleware + service calls.
|
||||
├── service.js Business logic. DB queries + validation + audit calls.
|
||||
└── model.js Sequelize model definition(s).
|
||||
```
|
||||
|
||||
Some modules have an additional file:
|
||||
- `timers/timer-engine.js` — in-memory timer state machine
|
||||
|
||||
```
|
||||
modules/
|
||||
├── auth/
|
||||
│ ├── routes.js
|
||||
│ ├── service.js
|
||||
│ └── model.js (DeviceToken)
|
||||
├── users/
|
||||
│ ├── routes.js
|
||||
│ ├── service.js
|
||||
│ └── model.js (User)
|
||||
├── org/
|
||||
│ ├── routes.js
|
||||
│ ├── service.js
|
||||
│ └── model.js (Organization, Branding)
|
||||
├── videos/
|
||||
│ ├── routes.js
|
||||
│ ├── service.js
|
||||
│ └── model.js (Video, Category)
|
||||
├── workouts/
|
||||
│ ├── routes.js
|
||||
│ ├── service.js
|
||||
│ └── model.js (Workout)
|
||||
├── timers/
|
||||
│ ├── routes.js
|
||||
│ ├── service.js
|
||||
│ ├── timer-engine.js (TimerEngine class)
|
||||
│ └── model.js (Timer)
|
||||
├── crossfit/
|
||||
│ ├── routes.js
|
||||
│ ├── service.js
|
||||
│ └── model.js (CrossfitWorkout)
|
||||
├── clients/
|
||||
│ ├── routes.js
|
||||
│ ├── service.js
|
||||
│ └── model.js (CoachClientLink, ClientWorkout, CalendarSession)
|
||||
├── audit/
|
||||
│ ├── routes.js (read-only: GET /audit-logs, GET /audit-logs/export)
|
||||
│ └── model.js (AuditLog — writes via core/audit.js only)
|
||||
└── sysadmin/
|
||||
└── routes.js (cross-org views, health, org management)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## public/
|
||||
|
||||
All files in `public/` are served as static files by Express or Nginx.
|
||||
`uploads/` is NOT inside `public/` — it is a sibling directory.
|
||||
|
||||
```
|
||||
public/
|
||||
├── manifest.json PWA manifest
|
||||
├── sw.js Service worker (cache app shell)
|
||||
├── styles/
|
||||
│ ├── base.css Reset, CSS custom properties (:root vars), typography
|
||||
│ ├── layout.css Banner, nav drawer, page shell grid
|
||||
│ ├── components.css Buttons, forms, cards, tables, badges, overlays
|
||||
│ └── display.css TV display mode (full-screen, no chrome, large type)
|
||||
├── js/
|
||||
│ ├── core.js Auth bootstrap, fetch wrapper, nav drawer, branding loader
|
||||
│ ├── socket-client.js Socket.io client with auto-reconnect wrapper
|
||||
│ ├── display.js Display mode controller (workout / crossfit views)
|
||||
│ └── timer-display.js Timer countdown UI, phase state, local-fallback mode
|
||||
├── icons/
|
||||
│ ├── icon-180.png Apple touch icon
|
||||
│ ├── icon-192.png PWA maskable icon
|
||||
│ └── icon-512.png PWA splash icon
|
||||
├── index.html Login page
|
||||
├── dashboard.html Home (Owner/Coach)
|
||||
├── videos.html Video library browse/manage
|
||||
├── upload-video.html Upload video form
|
||||
├── categories.html Manage video categories
|
||||
├── workouts.html Group workout list
|
||||
├── create-workout.html Create/edit group workout
|
||||
├── workout-view.html Single workout detail
|
||||
├── workout-display.html Full-screen TV display — group workout
|
||||
├── timers.html Timer list
|
||||
├── create-timer.html Create/edit timer config
|
||||
├── timer-display.html Full-screen TV display — timer running
|
||||
├── crossfit.html CrossFit workout list
|
||||
├── create-crossfit.html Create CrossFit workout
|
||||
├── crossfit-display.html Full-screen TV display — CrossFit workout
|
||||
├── clients.html Client roster (Coach/Owner)
|
||||
├── client-profile.html Individual client detail, workouts, sessions
|
||||
├── calendar.html Coach calendar view
|
||||
├── my-workouts.html Client: own assigned workouts
|
||||
├── my-schedule.html Client: own upcoming sessions
|
||||
├── profile.html Own profile / change password
|
||||
├── settings.html Owner: users, branding, storage, device tokens
|
||||
├── audit-log.html Owner: audit log viewer
|
||||
└── sysadmin.html SystemAdmin panel
|
||||
```
|
||||
|
||||
### public/js/core.js
|
||||
|
||||
Loaded on every page. Provides:
|
||||
- `Auth` — token read/write, device token refresh, session expired overlay
|
||||
- `Api` — fetch wrapper that injects Authorization header, handles 401, retries after token refresh
|
||||
- `Nav` — drawer open/close, mark active link, role-based link visibility
|
||||
- `Branding` — fetches `/api/v1/org/branding` on load, applies CSS custom properties to `:root`
|
||||
- `Page.init(rolesAllowed)` — called by every page; redirects to `/` if not logged in or wrong role
|
||||
|
||||
### public/js/socket-client.js
|
||||
|
||||
Exports `SocketClient` class:
|
||||
- Wraps `io()` with reconnect event handling
|
||||
- Emits `client:ready` when connected
|
||||
- Exposes `on(event, handler)` and `emit(event, data)` proxies
|
||||
- On reconnect: calls a registered `onReconnect` callback so pages can re-sync state
|
||||
|
||||
### public/js/display.js
|
||||
|
||||
Used by `workout-display.html` and `crossfit-display.html`.
|
||||
- Renders workout/CrossFit data in full-screen TV layout
|
||||
- Applies branding colors from CSS custom properties
|
||||
- Keeps a constant low-opacity pulse animation to prevent AirPlay freeze
|
||||
- Shows offline overlay when server unreachable (content remains visible underneath)
|
||||
|
||||
### public/js/timer-display.js
|
||||
|
||||
Used by `timer-display.html`.
|
||||
- Connects to Socket.io and joins the timer room
|
||||
- Handles `timer:tick`, `timer:phase-change`, `timer:complete` events
|
||||
- Falls back to local countdown using received `endTime` if Socket.io disconnects
|
||||
- `localFallback(endTime)` — runs `Date.now()` diff per animationFrame, no drift
|
||||
- Manages phase colors by reading CSS custom properties from branding
|
||||
|
||||
---
|
||||
|
||||
## uploads/
|
||||
|
||||
```
|
||||
uploads/
|
||||
└── <timestamp>_<random>.<ext> Video files — never served statically
|
||||
```
|
||||
|
||||
Filenames are generated as `Date.now() + '_' + crypto.randomBytes(8).toString('hex') + ext`
|
||||
to prevent name collisions and enumeration.
|
||||
|
||||
Files in this directory are accessed only through `GET /api/v1/videos/stream/:filename`,
|
||||
which enforces JWT auth and handles HTTP Range requests.
|
||||
|
||||
---
|
||||
|
||||
## tests/
|
||||
|
||||
See [TESTING.md](TESTING.md) for the full test plan, case lists, and helper API.
|
||||
|
||||
```
|
||||
tests/
|
||||
├── helpers/
|
||||
│ ├── db.js In-memory SQLite setup/teardown; runs migrations before each suite
|
||||
│ ├── auth.js makeJwt(), authHeader() — no DB needed
|
||||
│ ├── factories.js seedOrg(), seedUser(), seedVideo(), seedTimer() — minimal DB seeds
|
||||
│ └── socket.js Create real Socket.io server + test client bound to random port
|
||||
├── unit/
|
||||
│ ├── timer-engine.test.js TimerEngine state machine (mocked io)
|
||||
│ ├── validate-mime.test.js Magic-byte validation reads from file, not buffer
|
||||
│ ├── storage.test.js 60s cache, checkUploadAllowed 507 behavior
|
||||
│ ├── contrast.test.js Branding WCAG contrast ratio pass/fail
|
||||
│ └── respond.test.js ok/created/collection/err envelope shapes
|
||||
├── integration/
|
||||
│ ├── migrations.test.js All 13 migrations run in order against :memory:
|
||||
│ ├── auth.test.js
|
||||
│ ├── users.test.js
|
||||
│ ├── videos.test.js
|
||||
│ ├── workouts.test.js
|
||||
│ ├── timers.test.js
|
||||
│ ├── crossfit.test.js
|
||||
│ ├── clients.test.js
|
||||
│ ├── audit.test.js
|
||||
│ └── org.test.js
|
||||
├── socket/
|
||||
│ └── timer-engine.socket.test.js
|
||||
└── e2e/
|
||||
└── display-burn-in.test.js Manual only (npm run test:burnin); Playwright/WebKit
|
||||
```
|
||||
@@ -0,0 +1,650 @@
|
||||
# VitFit V2 — Frontend Page Map
|
||||
|
||||
Every HTML page: purpose, access control, API calls, socket events, and key JS behavior.
|
||||
|
||||
All pages load `core.js` which calls `Page.init(allowedRoles)` on DOMContentLoaded.
|
||||
`Page.init` checks localStorage for a JWT (or attempts device-token re-auth), redirects to `/` if
|
||||
not authenticated or role not in `allowedRoles`. It also fetches branding and applies CSS vars.
|
||||
|
||||
CSS loaded on every page: `base.css`, `layout.css`, `components.css`.
|
||||
Display-mode pages also load: `display.css` (replaces layout, not combined with it).
|
||||
|
||||
---
|
||||
|
||||
## Shared JS Modules
|
||||
|
||||
### public/js/core.js
|
||||
|
||||
Loaded on every page.
|
||||
|
||||
```
|
||||
Auth
|
||||
- getJwt() read from localStorage
|
||||
- setJwt(token) write to localStorage
|
||||
- getDeviceToken() read from localStorage
|
||||
- setDeviceToken(token) write to localStorage
|
||||
- clearSession() remove jwt + deviceToken from localStorage
|
||||
- tryDeviceLogin() POST /auth/device-login with stored device token
|
||||
- isTokenExpiringSoon(jwt) true if exp < now + 1h
|
||||
- autoRefreshIfNeeded() call /auth/refresh-token if expiring soon
|
||||
|
||||
Api
|
||||
- fetch(url, options?) wraps window.fetch; injects Auth header; on 401 → tries
|
||||
autoRefreshIfNeeded then retries once; on 2nd 401 → shows
|
||||
session-expired overlay
|
||||
- get(url, params?) Api.fetch with method GET
|
||||
- post(url, body) Api.fetch with method POST, JSON body
|
||||
- patch(url, body) Api.fetch with method PATCH, JSON body
|
||||
- put(url, body) Api.fetch with method PUT, JSON body
|
||||
- del(url) Api.fetch with method DELETE
|
||||
- upload(url, formData) Api.fetch with method POST, FormData body (no Content-Type header)
|
||||
|
||||
Nav
|
||||
- init(currentPage) build nav drawer from config, highlight active item
|
||||
- roleVisibility(role) filter nav links by role
|
||||
- toggle() open/close drawer on hamburger tap
|
||||
|
||||
Branding
|
||||
- load() GET /api/v1/org/branding → apply to :root CSS vars
|
||||
- apply(branding) set --color-primary, --color-work, --app-name, etc.
|
||||
|
||||
Page
|
||||
- init(allowedRoles) auth check + branding load + nav init
|
||||
- currentUser() decode jwt, return { id, username, role, organizationId }
|
||||
- showSessionExpiredOverlay() shows tap-to-re-login overlay (non-blocking)
|
||||
```
|
||||
|
||||
### public/js/socket-client.js
|
||||
|
||||
```
|
||||
SocketClient
|
||||
- connect() create io() with auth token; bind internal events
|
||||
- on(event, handler) register event handler
|
||||
- emit(event, data) emit to server
|
||||
- joinRoom(roomId) emit timer:join
|
||||
- leaveRoom(roomId) emit timer:leave
|
||||
- onDisconnect(cb) register disconnect callback
|
||||
- onReconnect(cb) register reconnect callback (re-joins room automatically)
|
||||
- destroy() disconnect and remove all listeners (called on page unload)
|
||||
```
|
||||
|
||||
### public/js/display.js
|
||||
|
||||
Used by `workout-display.html` and `crossfit-display.html`.
|
||||
|
||||
```
|
||||
Display
|
||||
- renderWorkout(workout) populate full-screen workout layout
|
||||
- renderCrossfit(crossfit) populate full-screen CrossFit layout
|
||||
- setOffline(true|false) show/hide reconnecting banner (content stays)
|
||||
- startKeepAlive() begin 30s low-opacity CSS animation to prevent AirPlay freeze
|
||||
- applyBranding(branding) set display-mode CSS vars (colors, font)
|
||||
```
|
||||
|
||||
### public/js/timer-display.js
|
||||
|
||||
```
|
||||
TimerDisplay
|
||||
- init(sessionId) join socket room, register event handlers
|
||||
- handleState(state) render full timer state from timer:state event
|
||||
- handleTick(data) update phase countdown display
|
||||
- handlePhaseChange(data) update phase label, color, reset countdown, play sound
|
||||
- handleComplete(data) show completion overlay
|
||||
- handleStopped(data) show stopped overlay
|
||||
- startLocalFallback(endTime) animationFrame loop using Date.now() diff
|
||||
- stopLocalFallback() cancel animationFrame loop
|
||||
- formatTime(ms) returns "MM:SS" string
|
||||
- formatHMS(ms) returns "H:MM:SS" string for total time
|
||||
- setPhaseColor(phase) read CSS var for phase, apply to display elements
|
||||
- setOffline(true|false) show/hide reconnecting indicator (timer continues)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pages — Unauthenticated
|
||||
|
||||
### index.html — Login
|
||||
|
||||
Access: Public (unauthenticated only — redirects to dashboard if already logged in).
|
||||
|
||||
On load:
|
||||
- Check for stored JWT; if valid, redirect to `/dashboard.html`
|
||||
- Check for stored deviceToken; if present, `POST /api/v1/auth/device-login` → redirect on success
|
||||
|
||||
Form submit:
|
||||
```
|
||||
POST /api/v1/auth/login
|
||||
body: { username, password, rememberDevice, deviceName, deviceType }
|
||||
on 200: store jwt (+ deviceToken if present), redirect to /dashboard.html
|
||||
on 401: show "Invalid username or password" inline error
|
||||
on 429: show "Too many attempts, please wait" inline error
|
||||
```
|
||||
|
||||
Key behavior:
|
||||
- "Remember this device" checkbox (default checked on iPad-sized screens)
|
||||
- `deviceName` defaults to `navigator.userAgent` parsed to a readable string
|
||||
- `deviceType` defaults to `kiosk` if screen width >= 768px (iPad), else `personal`
|
||||
- Password field: toggle show/hide button
|
||||
|
||||
---
|
||||
|
||||
## Pages — Coach / Owner (Standard Management UI)
|
||||
|
||||
CSS: `base.css`, `layout.css`, `components.css`
|
||||
Shell: banner + hamburger, nav drawer, main content area.
|
||||
|
||||
### dashboard.html — Home
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/workouts/today → render "Today's Workouts" card list
|
||||
GET /api/v1/org → show org name in header
|
||||
GET /api/v1/admin/storage → (Owner only) show disk usage bar in quick-stats
|
||||
```
|
||||
|
||||
Quick-stats cards:
|
||||
- Today's workouts count (link to workouts.html)
|
||||
- Active timers: count of timers defined (link to timers.html)
|
||||
- (Owner only) Disk used %
|
||||
|
||||
---
|
||||
|
||||
### videos.html — Video Library
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/categories → populate filter dropdown
|
||||
GET /api/v1/videos?page=1 → render video grid
|
||||
```
|
||||
|
||||
Actions:
|
||||
- Category filter dropdown → `GET /api/v1/videos?category=X` → re-render grid
|
||||
- Pagination controls → `GET /api/v1/videos?page=N`
|
||||
- Each video card: inline `<video>` element using `streamUrl` as `src`
|
||||
- Delete button: confirm modal → `DELETE /api/v1/videos/:id` → remove card from DOM
|
||||
|
||||
---
|
||||
|
||||
### upload-video.html — Upload Video
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/categories → populate category select
|
||||
```
|
||||
|
||||
Form submit:
|
||||
```
|
||||
POST /api/v1/videos (multipart)
|
||||
fields: video (file), description, category
|
||||
on 201: show success toast, reset form
|
||||
on 400 UPLOAD_TYPE_INVALID: "Only MP4, MOV, and M4V files are supported."
|
||||
on 507: "Not enough disk space to upload. Contact your administrator."
|
||||
```
|
||||
|
||||
Progress indicator: `XMLHttpRequest.upload.onprogress` for upload progress bar.
|
||||
|
||||
---
|
||||
|
||||
### categories.html — Manage Categories
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/categories → render list
|
||||
```
|
||||
|
||||
Actions:
|
||||
- Create form: `POST /api/v1/categories` → append to list
|
||||
- Delete button: `DELETE /api/v1/categories/:id`
|
||||
- On CONFLICT 409: "This category has videos. Move or delete the videos first."
|
||||
|
||||
---
|
||||
|
||||
### workouts.html — Group Workouts
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/workouts?page=1 → render paginated workout cards
|
||||
```
|
||||
|
||||
Each workout card shows: name, date, video thumbnails (or "[Video removed]"), video descriptions.
|
||||
|
||||
Actions:
|
||||
- "View" link → `workout-view.html?id=X`
|
||||
- "Display" button → open `workout-display.html?id=X` in same window (full-screen takes over)
|
||||
- Delete button (own workouts for Coach, any for Owner):
|
||||
`DELETE /api/v1/workouts/:id` → remove card
|
||||
|
||||
---
|
||||
|
||||
### create-workout.html — Create Workout
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/categories → populate category dropdowns (one per slot)
|
||||
```
|
||||
|
||||
Slot 1 category change:
|
||||
```
|
||||
GET /api/v1/videos?category=X → populate video select for slot 1
|
||||
```
|
||||
Repeated for slots 2–4 (each has its own category+video selects, initially hidden, revealed by "Add Exercise" button).
|
||||
|
||||
Form submit:
|
||||
```
|
||||
POST /api/v1/workouts
|
||||
on 201: redirect to workouts.html
|
||||
on 400: show validation errors inline
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### workout-view.html — Single Workout Detail
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
Query param: `?id=<workoutId>`
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/workouts/:id → render workout detail + video players
|
||||
```
|
||||
|
||||
Each video slot renders a `<video>` element with `src = streamUrl`.
|
||||
"Display on TV" button → navigate to `workout-display.html?id=X`.
|
||||
|
||||
---
|
||||
|
||||
### timers.html — Timer List
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/timers → render timer cards
|
||||
```
|
||||
|
||||
Each card: name, summary (e.g. "30s work / 10s rest × 3 sets × 5 exercises × 2 laps").
|
||||
|
||||
Actions:
|
||||
- "Launch" button → `POST /api/v1/timers/:id/launch` → navigate to `timer-display.html?session=<sessionId>`
|
||||
- Delete button → `DELETE /api/v1/timers/:id`
|
||||
|
||||
---
|
||||
|
||||
### create-timer.html — Create Timer
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load: no API calls.
|
||||
|
||||
Form submit:
|
||||
```
|
||||
POST /api/v1/timers
|
||||
on 201: redirect to timers.html
|
||||
```
|
||||
|
||||
Live preview: calculated total time shown as user fills in fields.
|
||||
Formula: `totalTime = setTime * setCount * exerciseCount * lapCount + restTime * ... + moveTime * ...`
|
||||
|
||||
---
|
||||
|
||||
### crossfit.html — CrossFit Workouts
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/crossfit-workouts?page=1 → render workout cards
|
||||
```
|
||||
|
||||
Each card: name, date, bullet list of items.
|
||||
|
||||
Actions:
|
||||
- "Display" button → open `crossfit-display.html?id=X`
|
||||
- Delete button (Owner only): `DELETE /api/v1/crossfit-workouts/:id`
|
||||
|
||||
---
|
||||
|
||||
### create-crossfit.html — Create CrossFit Workout
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
Form: name, date, textarea (one item per line).
|
||||
|
||||
Submit:
|
||||
```
|
||||
POST /api/v1/crossfit-workouts
|
||||
body: { name, workoutDate, workoutItems: textarea.value.split('\n').filter(Boolean) }
|
||||
on 201: redirect to crossfit.html
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### clients.html — Client Roster
|
||||
|
||||
Access: Owner (all clients), Coach (own clients only).
|
||||
|
||||
Feature flag: `client-management`.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/clients → render client cards
|
||||
```
|
||||
|
||||
Each card: name, username, assigned coach name, pending workout count.
|
||||
|
||||
Actions:
|
||||
- Click card → `client-profile.html?id=X`
|
||||
- "Add Client" button (Owner) → modal with create-user form → `POST /api/v1/clients`
|
||||
|
||||
---
|
||||
|
||||
### client-profile.html — Client Detail
|
||||
|
||||
Access: Owner, Coach (own clients only).
|
||||
|
||||
Query param: `?id=<clientId>`
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/clients/:id → render profile header
|
||||
GET /api/v1/clients/:id/workouts?includeCompleted=false → render upcoming workouts
|
||||
GET /api/v1/clients/:id/sessions?status=scheduled → render upcoming sessions
|
||||
```
|
||||
|
||||
Tabs: Workouts | Sessions | History
|
||||
|
||||
Actions:
|
||||
- "Assign New Workout" → modal form → `POST /api/v1/clients/:id/workouts`
|
||||
- "Schedule Session" → modal form → `POST /api/v1/clients/:id/sessions`
|
||||
- Workout "Complete" → `POST /api/v1/clients/:id/workouts/:workoutId/complete`
|
||||
- Workout delete → `DELETE /api/v1/clients/:id/workouts/:workoutId`
|
||||
- Session cancel → `POST /api/v1/clients/:id/sessions/:sessionId/cancel`
|
||||
|
||||
---
|
||||
|
||||
### calendar.html — Coach Calendar
|
||||
|
||||
Access: Owner, Coach.
|
||||
|
||||
Feature flag: `calendar`.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/calendar?startAfter=<monthStart>&endBefore=<monthEnd> → render calendar grid
|
||||
```
|
||||
|
||||
Month navigation recalculates date range and re-fetches.
|
||||
Click on session → expand detail inline.
|
||||
|
||||
**Phase 2 deferrals (not in V2 MVP):**
|
||||
- Conflict detection: overlapping sessions for the same coach are not flagged. The API accepts
|
||||
overlapping bookings. Visual collision awareness is a Phase 2 enhancement.
|
||||
- Recurring sessions: no recurrence rules (RRULE, daily, weekly, etc.). Each session is a
|
||||
standalone record. Repeating a session means creating copies manually. Recurrence engine
|
||||
is Phase 2.
|
||||
|
||||
---
|
||||
|
||||
### profile.html — Own Profile
|
||||
|
||||
Access: All roles.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/my/profile → populate form
|
||||
GET /api/v1/users/:id/devices → list device tokens
|
||||
```
|
||||
|
||||
Actions:
|
||||
- Save profile: `PATCH /api/v1/users/:id` with `{ firstName, lastName, email }`
|
||||
- Change password: form with current + new password → `PUT /api/v1/my/password`
|
||||
- Revoke device: `DELETE /api/v1/users/:id/devices/:tokenId`
|
||||
|
||||
---
|
||||
|
||||
### settings.html — Owner Settings
|
||||
|
||||
Access: Owner only.
|
||||
|
||||
Tabs: Users | Branding | Storage | Devices
|
||||
|
||||
**Users tab:**
|
||||
```
|
||||
GET /api/v1/users → render user table
|
||||
```
|
||||
- Create user: inline form → `POST /api/v1/users`
|
||||
- Deactivate: `DELETE /api/v1/users/:id` (soft)
|
||||
- Change role: inline select → `PUT /api/v1/users/:id/role`
|
||||
- Reset password: inline form → `PUT /api/v1/users/:id/password`
|
||||
|
||||
**Branding tab:**
|
||||
```
|
||||
GET /api/v1/org/branding → populate color inputs + logo preview
|
||||
```
|
||||
- Color pickers (HTML `<input type="color">`) with live preview of timer phase colors
|
||||
- Save colors: `PATCH /api/v1/org/branding`
|
||||
- Logo upload: `POST /api/v1/org/logo`
|
||||
|
||||
**Storage tab:**
|
||||
```
|
||||
GET /api/v1/admin/storage → render disk usage bar + breakdown
|
||||
```
|
||||
Auto-refreshes every 5 minutes. Shows warning banner if `data.warning === true`.
|
||||
|
||||
**Devices tab:**
|
||||
All device tokens across all users in the org.
|
||||
```
|
||||
GET /api/v1/users → for each user, GET /api/v1/users/:id/devices
|
||||
```
|
||||
Revoke: `DELETE /api/v1/users/:id/devices/:tokenId`
|
||||
|
||||
---
|
||||
|
||||
### audit-log.html — Audit Log
|
||||
|
||||
Access: Owner only.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/audit-logs?page=1&limit=50 → render table
|
||||
```
|
||||
|
||||
Filter controls: action (dropdown), date range (from/to), user (dropdown), entity type.
|
||||
Any filter change: re-fetches with new params.
|
||||
|
||||
Expandable rows: click row → show full `details` JSON formatted.
|
||||
|
||||
"Export CSV" button: navigates to `GET /api/v1/audit-logs/export?<same filters>` (browser download).
|
||||
|
||||
---
|
||||
|
||||
### sysadmin.html — System Admin Panel
|
||||
|
||||
Access: SystemAdmin only.
|
||||
|
||||
Tabs: Organizations | Health
|
||||
|
||||
**Organizations tab:**
|
||||
```
|
||||
GET /api/v1/sysadmin/orgs → render org table
|
||||
```
|
||||
- Click org → expand detail: name, slug, timezone, features, user counts, license info
|
||||
- Edit org: inline form → `PATCH /api/v1/sysadmin/orgs/:id`
|
||||
|
||||
**Health tab:**
|
||||
```
|
||||
GET /api/v1/sysadmin/health → render health dashboard
|
||||
```
|
||||
Shows: version, uptime, DB migration status, disk stats, active timer sessions.
|
||||
Manual refresh button.
|
||||
|
||||
---
|
||||
|
||||
## Pages — Display Mode (Full-Screen TV)
|
||||
|
||||
These pages use `display.css` instead of `layout.css`. No nav drawer, no banner.
|
||||
They are opened from the management pages when a coach taps "Display" or "Launch".
|
||||
Full-screen API is requested on load: `document.documentElement.requestFullscreen()`.
|
||||
|
||||
### workout-display.html
|
||||
|
||||
Query param: `?id=<workoutId>`
|
||||
|
||||
CSS: `base.css`, `display.css`
|
||||
JS: `core.js`, `display.js`
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/workouts/:id → pass to Display.renderWorkout()
|
||||
```
|
||||
|
||||
Layout:
|
||||
```
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ WORKOUT NAME DATE │ small top bar
|
||||
│ │
|
||||
│ [slot 1 description] 10 reps │ large text
|
||||
│ [slot 2 description] 12 reps │
|
||||
│ [slot 3 description] 8 reps │
|
||||
│ │
|
||||
│ [touch: back] [touch: close] │ invisible coach controls
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
`Display.startKeepAlive()` runs on load to prevent AirPlay stream freeze.
|
||||
|
||||
---
|
||||
|
||||
### timer-display.html
|
||||
|
||||
Query param: `?session=<sessionId>`
|
||||
|
||||
CSS: `base.css`, `display.css`
|
||||
JS: `core.js`, `socket-client.js`, `timer-display.js`
|
||||
|
||||
On load:
|
||||
```
|
||||
SocketClient.connect()
|
||||
TimerDisplay.init(sessionId) → joins socket room, registers event handlers
|
||||
```
|
||||
|
||||
Layout:
|
||||
```
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ SET LAP 1/2 EXERCISE 2/5 SET 1/3 │ small status bar (phase label left)
|
||||
│ │
|
||||
│ 00:28 │ giant phase countdown
|
||||
│ │
|
||||
│ Total 14:32 │ smaller total time
|
||||
│ │
|
||||
│ [touch: stop — left edge, invisible] │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Background color changes with phase (reads `--color-work`, `--color-rest`, `--color-move` CSS vars).
|
||||
10-second warning: countdown turns amber (`--color-warning`).
|
||||
|
||||
On `timer:complete`: background fades to dark, "DONE" displayed in center.
|
||||
On disconnect: `TimerDisplay.startLocalFallback(phaseEndTime)` continues countdown locally.
|
||||
|
||||
---
|
||||
|
||||
### crossfit-display.html
|
||||
|
||||
Query param: `?id=<crossfitWorkoutId>`
|
||||
|
||||
CSS: `base.css`, `display.css`
|
||||
JS: `core.js`, `display.js`
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/crossfit-workouts/:id → pass to Display.renderCrossfit()
|
||||
```
|
||||
|
||||
Layout:
|
||||
```
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ HERO WOD MURPH June 11 │ small top bar
|
||||
│ │
|
||||
│ 1. 1 mile run │ large numbered list
|
||||
│ 2. 100 pull-ups │
|
||||
│ 3. 200 push-ups │
|
||||
│ 4. 300 air squats │
|
||||
│ 5. 1 mile run │
|
||||
│ │
|
||||
│ [touch: close — right edge, invisible] │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pages — Client Portal
|
||||
|
||||
CSS: `base.css`, `layout.css`, `components.css` (same shell, different nav links).
|
||||
|
||||
### my-workouts.html
|
||||
|
||||
Access: Client only.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/my/workouts?includeCompleted=false&page=1 → render workout cards
|
||||
```
|
||||
|
||||
Each card: workout name, scheduled date, item summary (exercise count), completion status.
|
||||
"Mark Complete" button: `POST /api/v1/clients/:ownId/workouts/:workoutId/complete`
|
||||
"View" button: expand inline to show full items list (including video players via streamUrl).
|
||||
|
||||
---
|
||||
|
||||
### my-schedule.html
|
||||
|
||||
Access: Client only.
|
||||
|
||||
On load:
|
||||
```
|
||||
GET /api/v1/my/sessions?status=scheduled&startAfter=<today> → render session list
|
||||
```
|
||||
|
||||
Each card: title, coach name, date/time, location, shared notes.
|
||||
"Cancel" button (if session > 24h away): `POST /api/v1/clients/:ownId/sessions/:id/cancel`
|
||||
|
||||
---
|
||||
|
||||
## Navigation Config (core.js)
|
||||
|
||||
Nav links are defined in a config array in `core.js`. Role-based visibility is enforced client-side
|
||||
(cosmetic only — server enforces real access control).
|
||||
|
||||
```js
|
||||
const NAV_LINKS = [
|
||||
{ label: 'Dashboard', href: '/dashboard.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Videos', href: '/videos.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Workouts', href: '/workouts.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Timers', href: '/timers.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'CrossFit', href: '/crossfit.html', roles: ['Owner', 'Coach'] },
|
||||
{ label: 'Clients', href: '/clients.html', roles: ['Owner', 'Coach'], feature: 'client-management' },
|
||||
{ label: 'Calendar', href: '/calendar.html', roles: ['Owner', 'Coach'], feature: 'calendar' },
|
||||
{ label: 'My Workouts', href: '/my-workouts.html', roles: ['Client'] },
|
||||
{ label: 'My Schedule', href: '/my-schedule.html', roles: ['Client'], feature: 'calendar' },
|
||||
{ label: 'Settings', href: '/settings.html', roles: ['Owner'] },
|
||||
{ label: 'Audit Log', href: '/audit-log.html', roles: ['Owner'] },
|
||||
{ label: 'System Admin', href: '/sysadmin.html', roles: ['SystemAdmin'] },
|
||||
{ label: 'Profile', href: '/profile.html', roles: ['Owner', 'Coach', 'Client'] },
|
||||
{ label: 'Log Out', href: '#', roles: ['Owner', 'Coach', 'Client', 'SystemAdmin'],
|
||||
action: 'logout' },
|
||||
];
|
||||
```
|
||||
@@ -0,0 +1,46 @@
|
||||
# VitFit V2 — Structure Index
|
||||
|
||||
Implementation blueprints. Read planning docs first, then these structure docs before writing code.
|
||||
|
||||
## Documents
|
||||
|
||||
| Document | What it covers |
|
||||
|----------|---------------|
|
||||
| [FILE_STRUCTURE.md](FILE_STRUCTURE.md) | Every file in the project with purpose, exports, and key behavior |
|
||||
| [BACKEND_METHODS.md](BACKEND_METHODS.md) | Method signatures for all core/ and module service files |
|
||||
| [API_ROUTES.md](API_ROUTES.md) | Every endpoint: method, path, auth, request body, response shape, errors |
|
||||
| [DATABASE_SCHEMA.md](DATABASE_SCHEMA.md) | Sequelize model definitions, associations, indexes, migration order |
|
||||
| [SOCKET_EVENTS.md](SOCKET_EVENTS.md) | Timer engine Socket.io events (server→client and client→server) |
|
||||
| [FRONTEND_MAP.md](FRONTEND_MAP.md) | Every HTML page: access roles, API calls on load, user actions, key JS behavior |
|
||||
| [TESTING.md](TESTING.md) | Test structure, unit/integration/socket/e2e test cases, helpers, scripts |
|
||||
|
||||
## Reading Order
|
||||
|
||||
1. `FILE_STRUCTURE.md` — get the big picture of what exists
|
||||
2. `DATABASE_SCHEMA.md` — understand the data shapes before reading services
|
||||
3. `BACKEND_METHODS.md` — understand what each service function does
|
||||
4. `API_ROUTES.md` — understand the contract between frontend and backend
|
||||
5. `SOCKET_EVENTS.md` — understand the timer real-time system
|
||||
6. `FRONTEND_MAP.md` — understand how each page uses the API
|
||||
7. `TESTING.md` — understand what must be tested and how
|
||||
|
||||
## Module Count
|
||||
|
||||
| Layer | Count |
|
||||
|-------|-------|
|
||||
| Backend modules | 10 (auth, users, org, videos, workouts, timers, crossfit, clients, audit, sysadmin) |
|
||||
| API endpoints | 55 |
|
||||
| Database tables | 13 |
|
||||
| Socket.io events | 8 |
|
||||
| Frontend pages | 22 |
|
||||
| Shared JS modules | 4 (core, socket-client, display, timer-display) |
|
||||
| CSS files | 4 (base, layout, components, display) |
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
- All modules are auto-loaded by `app.js` scanning `modules/*/routes.js`
|
||||
- All service functions throw `AppError` — routes never construct error responses directly
|
||||
- All routes call `core/audit.js log()` after successful mutations
|
||||
- `organizationId` is added to every DB query by the service layer, not the route layer
|
||||
- Display-mode pages (`*-display.html`) are the TV-facing views; all others are coach-facing
|
||||
- `core.js` runs on every page; `socket-client.js` only on display and timer pages
|
||||
@@ -0,0 +1,269 @@
|
||||
# VitFit V2 — Socket.io Event System
|
||||
|
||||
Socket.io is used exclusively for the timer engine. No other feature uses real-time events in V2.
|
||||
|
||||
---
|
||||
|
||||
## Connection and Authentication
|
||||
|
||||
Socket.io clients must authenticate at connection time by passing the JWT in the handshake:
|
||||
|
||||
```js
|
||||
// Client-side (socket-client.js)
|
||||
const socket = io('/', {
|
||||
auth: { token: localStorage.getItem('jwt') },
|
||||
reconnectionDelay: 1000,
|
||||
reconnectionDelayMax: 10000,
|
||||
reconnectionAttempts: Infinity
|
||||
});
|
||||
```
|
||||
|
||||
Server-side (core/socket.js):
|
||||
```js
|
||||
io.use((socket, next) => {
|
||||
const token = socket.handshake.auth.token;
|
||||
if (!token) return next(new Error('AUTH_REQUIRED'));
|
||||
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
|
||||
if (err) return next(new Error('AUTH_INVALID'));
|
||||
socket.data.user = user;
|
||||
next();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
On auth failure the socket is disconnected immediately. The client retries with exponential backoff using the reconnect config above.
|
||||
|
||||
---
|
||||
|
||||
## Rooms
|
||||
|
||||
Each active timer session gets its own Socket.io room named by `sessionId`:
|
||||
```
|
||||
timer_<timerId>_<timestamp>
|
||||
e.g. timer_3_1718273400000
|
||||
```
|
||||
|
||||
Clients join a room to receive events for that specific timer session.
|
||||
Multiple clients can join the same room (e.g., the coach's iPad + the display page both watching the same timer).
|
||||
|
||||
---
|
||||
|
||||
## Events: Client → Server
|
||||
|
||||
### `timer:join`
|
||||
Client requests to join a timer session room.
|
||||
|
||||
```js
|
||||
// Emit
|
||||
socket.emit('timer:join', { sessionId: 'timer_3_1718273400000' });
|
||||
```
|
||||
|
||||
Server handler (order of checks):
|
||||
1. Looks up the engine by `sessionId` in the active sessions Map.
|
||||
2. If not found: emits `timer:error { code: 'SESSION_NOT_FOUND' }` and returns.
|
||||
3. **Verifies `engine.orgId === socket.data.user.organizationId`.**
|
||||
If mismatch: emits `timer:error { code: 'SESSION_NOT_FOUND' }` — same error as missing,
|
||||
so cross-org probing cannot distinguish "exists but not yours" from "doesn't exist."
|
||||
4. Joins the socket to the room. Emits `timer:state` back to this socket only.
|
||||
|
||||
```js
|
||||
socket.emit('timer:state', engine.getState());
|
||||
```
|
||||
|
||||
This org check is required because sessionId format (`timer_<timerId>_<timestamp>`) is
|
||||
guessable by anyone who knows a timerId. Without it, a user from Org B could observe
|
||||
Org A's timer state.
|
||||
|
||||
---
|
||||
|
||||
### `timer:leave`
|
||||
Client leaves a timer room. Server removes from room.
|
||||
|
||||
```js
|
||||
socket.emit('timer:leave', { sessionId: 'timer_3_1718273400000' });
|
||||
```
|
||||
|
||||
No server response.
|
||||
|
||||
---
|
||||
|
||||
## Events: Server → Client
|
||||
|
||||
### `timer:state`
|
||||
Full state snapshot. Sent on `timer:join` to the joining socket, and when a client reconnects.
|
||||
|
||||
```js
|
||||
{
|
||||
sessionId: 'timer_3_1718273400000',
|
||||
status: 'running', // 'idle' | 'running' | 'paused' | 'complete'
|
||||
phase: 'set', // 'set' | 'rest' | 'move'
|
||||
currentLap: 1,
|
||||
currentExercise: 2,
|
||||
currentSet: 1,
|
||||
phaseEndTime: 1718273430000, // Unix ms — client uses Date.now() diff
|
||||
sessionEndTime: 1718275200000, // Unix ms — total session end
|
||||
phaseRemainingMs: 28500,
|
||||
totalRemainingMs: 1725000,
|
||||
config: {
|
||||
lapCount: 2, exerciseCount: 5, setCount: 3,
|
||||
setTime: 30, restTime: 10, moveTime: 15, totalTime: 1800
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Client uses `phaseEndTime` (absolute timestamp) to drive local countdown. If the socket goes quiet, the client can continue using `Date.now() - phaseEndTime` without server involvement.
|
||||
|
||||
---
|
||||
|
||||
### `timer:tick`
|
||||
Emitted once per second while timer is running. Lightweight — only changing fields.
|
||||
|
||||
```js
|
||||
{
|
||||
sessionId: 'timer_3_1718273400000',
|
||||
phaseRemainingMs: 27500,
|
||||
totalRemainingMs: 1724000
|
||||
}
|
||||
```
|
||||
|
||||
Client uses this to keep displays in sync. If ticks stop arriving (disconnect), client falls back to computing from `phaseEndTime` received in the last `timer:state`.
|
||||
|
||||
---
|
||||
|
||||
### `timer:phase-change`
|
||||
Emitted when phase transitions (set→rest, rest→move, move→set).
|
||||
|
||||
```js
|
||||
{
|
||||
sessionId: 'timer_3_1718273400000',
|
||||
phase: 'rest',
|
||||
currentLap: 1,
|
||||
currentExercise: 2,
|
||||
currentSet: 1,
|
||||
phaseEndTime: 1718273440000, // new phase end time
|
||||
phaseRemainingMs: 10000
|
||||
}
|
||||
```
|
||||
|
||||
Client uses this to update the display color, label, and reset the phase countdown.
|
||||
Phase colors are read from CSS custom properties (set by branding loader) — no color data in the event.
|
||||
|
||||
---
|
||||
|
||||
### `timer:complete`
|
||||
Emitted when all laps/exercises/sets are done.
|
||||
|
||||
```js
|
||||
{
|
||||
sessionId: 'timer_3_1718273400000',
|
||||
totalElapsedSeconds: 1798
|
||||
}
|
||||
```
|
||||
|
||||
Client shows completion state. No further tick events will arrive.
|
||||
Timer engine is cleaned up server-side after emitting this.
|
||||
|
||||
---
|
||||
|
||||
### `timer:stopped`
|
||||
Emitted when a coach or owner manually stops the timer via `DELETE /api/v1/timers/session`.
|
||||
|
||||
```js
|
||||
{
|
||||
sessionId: 'timer_3_1718273400000',
|
||||
elapsedSeconds: 342,
|
||||
stoppedByUserId: 2
|
||||
}
|
||||
```
|
||||
|
||||
Client shows stopped state. Distinct from `timer:complete` — the timer did not finish naturally.
|
||||
|
||||
---
|
||||
|
||||
### `timer:error`
|
||||
Emitted when client attempts an invalid operation.
|
||||
|
||||
```js
|
||||
{
|
||||
code: 'SESSION_NOT_FOUND',
|
||||
message: 'No active timer session with that ID.'
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Client-Side Event Handling (timer-display.js)
|
||||
|
||||
```
|
||||
socket connects
|
||||
→ socket.emit('timer:join', { sessionId })
|
||||
→ receives timer:state → render full display state
|
||||
→ store phaseEndTime for local fallback
|
||||
|
||||
socket receives timer:tick
|
||||
→ update phaseRemainingMs display (smooth update, no flicker)
|
||||
|
||||
socket receives timer:phase-change
|
||||
→ update phase label, color, new phaseEndTime, reset phase countdown
|
||||
→ play phase-change sound (if audio unlocked by prior coach tap)
|
||||
|
||||
socket receives timer:complete
|
||||
→ show completion state
|
||||
→ stop local fallback interval if running
|
||||
|
||||
socket receives timer:stopped
|
||||
→ show stopped state
|
||||
|
||||
socket disconnects
|
||||
→ start localFallback(phaseEndTime):
|
||||
every animationFrame: remaining = phaseEndTime - Date.now()
|
||||
if remaining <= 0: show phase-change estimate (cannot know new phase without server)
|
||||
show "Offline - running locally" indicator
|
||||
→ Socket.io reconnects automatically (exponential backoff, infinite attempts)
|
||||
|
||||
socket reconnects
|
||||
→ stop localFallback
|
||||
→ socket.emit('timer:join', { sessionId }) again to re-sync
|
||||
→ receives fresh timer:state → updates display with authoritative state
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Disconnect / Reconnect Protocol
|
||||
|
||||
The client's `socket-client.js` wraps the Socket.io client with:
|
||||
|
||||
1. On `disconnect`: call registered `onDisconnect()` callback (page shows offline indicator)
|
||||
2. On `connect`: call registered `onReconnect()` callback — page re-joins its room and re-syncs
|
||||
3. Socket is created once per page load, not recreated
|
||||
|
||||
For the display pages (timer-display.html, workout-display.html, crossfit-display.html):
|
||||
- Offline indicator is a slim banner at top of screen: `⚠ Reconnecting...`
|
||||
- Content remains fully visible underneath — gym display does not go dark
|
||||
- Indicator disappears automatically when reconnected
|
||||
|
||||
---
|
||||
|
||||
## Active Session Registry (server-side)
|
||||
|
||||
Timer sessions live in a `Map<sessionId, TimerEngine>` in `modules/timers/service.js`.
|
||||
This is in-process memory — sessions do not survive a server restart.
|
||||
|
||||
Consequence: if the server restarts while a timer is running, the session is gone.
|
||||
Clients will receive a `timer:error SESSION_NOT_FOUND` when they reconnect and try to re-join.
|
||||
The display page shows a "Session ended — reconnect to start a new timer" message.
|
||||
The coach starts a new timer session from the timers list page.
|
||||
|
||||
For the current use case (single gym, single timer at a time) this is acceptable.
|
||||
A persistent session store (Redis or DB-backed) is a future enhancement if needed.
|
||||
|
||||
---
|
||||
|
||||
## One Active Session Per Org
|
||||
|
||||
Only one timer session can be running per organization at a time.
|
||||
|
||||
`launchTimer()` checks for an existing active session before creating a new one.
|
||||
If one exists: `AppError('CONFLICT', 'A timer is already running. Stop it before launching another.', 409)`.
|
||||
|
||||
The active session for an org is determined by scanning the in-memory Map for entries matching `orgId`.
|
||||
@@ -0,0 +1,344 @@
|
||||
# VitFit V2 — Test Structure
|
||||
|
||||
---
|
||||
|
||||
## Directory Layout
|
||||
|
||||
```
|
||||
/home/ubuntu/site/
|
||||
└── tests/
|
||||
├── helpers/
|
||||
│ ├── db.js In-memory SQLite setup/teardown for unit + integration tests
|
||||
│ ├── auth.js Generate test JWTs for any role
|
||||
│ ├── factories.js Seeders: makeOrg(), makeUser(role), makeVideo(), makeTimer(), etc.
|
||||
│ └── socket.js Create test Socket.io server + client pairs
|
||||
├── unit/
|
||||
│ ├── timer-engine.test.js
|
||||
│ ├── validate-mime.test.js
|
||||
│ ├── storage.test.js
|
||||
│ ├── contrast.test.js
|
||||
│ └── respond.test.js
|
||||
├── integration/
|
||||
│ ├── auth.test.js
|
||||
│ ├── users.test.js
|
||||
│ ├── videos.test.js
|
||||
│ ├── workouts.test.js
|
||||
│ ├── timers.test.js
|
||||
│ ├── crossfit.test.js
|
||||
│ ├── clients.test.js
|
||||
│ ├── audit.test.js
|
||||
│ ├── org.test.js
|
||||
│ └── migrations.test.js
|
||||
├── socket/
|
||||
│ └── timer-engine.socket.test.js
|
||||
└── e2e/
|
||||
└── display-burn-in.test.js
|
||||
```
|
||||
|
||||
Test runner: **Jest** with `--forceExit` flag (cleans up open DB handles).
|
||||
|
||||
---
|
||||
|
||||
## helpers/db.js
|
||||
|
||||
```js
|
||||
createTestDb(): Promise<{ sequelize, models }>
|
||||
```
|
||||
Creates an in-memory SQLite DB (`:memory:`), runs all migrations, returns sequelize instance.
|
||||
Each test file calls this in `beforeAll` and calls `sequelize.close()` in `afterAll`.
|
||||
Migrations run against in-memory DB, validating that the migration chain is complete and idempotent.
|
||||
|
||||
```js
|
||||
seedOrg(sequelize): Promise<{ org, branding }>
|
||||
seedUser(sequelize, orgId, role, overrides?): Promise<User>
|
||||
seedVideo(sequelize, orgId, overrides?): Promise<Video>
|
||||
```
|
||||
Minimal seed helpers. `factories.js` builds on these with realistic defaults.
|
||||
|
||||
---
|
||||
|
||||
## helpers/auth.js
|
||||
|
||||
```js
|
||||
makeJwt(user: Partial<User>): string
|
||||
```
|
||||
Signs a short-lived (5-minute) test JWT. Does not hit the DB.
|
||||
Usage: `const token = makeJwt({ id: 1, role: 'Coach', organizationId: 1 });`
|
||||
|
||||
```js
|
||||
authHeader(token: string): { Authorization: string }
|
||||
```
|
||||
Returns `{ Authorization: 'Bearer <token>' }` for use in supertest requests.
|
||||
|
||||
---
|
||||
|
||||
## Unit Tests
|
||||
|
||||
### tests/unit/timer-engine.test.js
|
||||
|
||||
Tests the `TimerEngine` state machine in isolation (no real Socket.io).
|
||||
|
||||
```
|
||||
✓ starts in 'idle' status
|
||||
✓ transitions to 'running' on start()
|
||||
✓ phase advances set → rest after setTime elapses
|
||||
✓ phase advances rest → move after restTime elapses
|
||||
✓ phase advances move → set, increments currentSet
|
||||
✓ increments currentExercise after all sets complete
|
||||
✓ increments currentLap after all exercises complete
|
||||
✓ emits timer:complete (not timer:stopped) on natural completion
|
||||
✓ emits timer:stopped (not timer:complete) on manual stop()
|
||||
✓ complete() does NOT call stop() — no double-event emission
|
||||
✓ getState() returns correct snapshot mid-run
|
||||
✓ skips rest phase when restTime = 0
|
||||
✓ skips move phase when moveTime = 0
|
||||
✓ phaseEndTime is an absolute timestamp (not a delta)
|
||||
```
|
||||
|
||||
Uses a mock `io` object that records emitted events.
|
||||
|
||||
### tests/unit/validate-mime.test.js
|
||||
|
||||
```
|
||||
✓ accepts first 12 bytes of a real MP4 file (ftyp magic bytes)
|
||||
✓ accepts first 12 bytes of a MOV file
|
||||
✓ accepts first 12 bytes of an M4V file
|
||||
✓ rejects a WebM file
|
||||
✓ rejects a text file renamed to .mp4
|
||||
✓ rejects an empty buffer
|
||||
✓ throws UPLOAD_TYPE_INVALID (not a generic error)
|
||||
✓ reads only from file path, does NOT load whole file into memory
|
||||
```
|
||||
|
||||
Uses real minimal binary fixtures (12-byte magic byte sequences only).
|
||||
|
||||
### tests/unit/storage.test.js
|
||||
|
||||
```
|
||||
✓ returns warning: false when free > STORAGE_WARN_BYTES
|
||||
✓ returns warning: true when free < STORAGE_WARN_BYTES
|
||||
✓ caches result for 60 seconds (second call within 60s returns cached value)
|
||||
✓ returns fresh result after 60 second cache expiry
|
||||
✓ checkUploadAllowed middleware returns 507 when warning: true
|
||||
✓ checkUploadAllowed middleware calls next() when warning: false
|
||||
```
|
||||
|
||||
Mocks `check-disk-space` to return controlled values.
|
||||
|
||||
### tests/unit/contrast.test.js
|
||||
|
||||
Tests `validateContrastRatio()` in org service.
|
||||
|
||||
```
|
||||
✓ #00FF88 on #1a1a1a passes (>= 4.5:1)
|
||||
✓ #000000 on #1a1a1a fails (ratio too low)
|
||||
✓ #FFFFFF on #1a1a1a passes
|
||||
✓ #777777 on #1a1a1a fails
|
||||
✓ invalid hex throws VALIDATION_FAILED
|
||||
✓ empty string throws VALIDATION_FAILED
|
||||
```
|
||||
|
||||
### tests/unit/respond.test.js
|
||||
|
||||
```
|
||||
✓ ok() sends 200 with { data }
|
||||
✓ created() sends 201 with { data }
|
||||
✓ collection() sends 200 with { data, meta } including correct totalPages
|
||||
✓ noContent() sends 204 with no body
|
||||
✓ err() sends correct status with { error: { code, message, field } }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration Tests
|
||||
|
||||
All integration tests use `supertest` against a real Express app with an in-memory SQLite DB.
|
||||
No network calls. No real files written to disk (multer storage overridden to use `/tmp`).
|
||||
|
||||
### tests/integration/migrations.test.js
|
||||
|
||||
**Critical test — run before all others.**
|
||||
|
||||
```
|
||||
✓ migration 001 (baseline) is idempotent — runs twice without error
|
||||
✓ migration 002+ run in order without error
|
||||
✓ all expected tables exist after full migration
|
||||
✓ all expected columns exist on each table
|
||||
✓ running db:migrate on already-migrated DB makes no changes
|
||||
✓ V1-compatible data inserted before migrations is preserved after
|
||||
```
|
||||
|
||||
### tests/integration/auth.test.js
|
||||
|
||||
```
|
||||
✓ POST /auth/login returns jwt on valid credentials
|
||||
✓ POST /auth/login returns LOGIN_FAILED on bad password
|
||||
✓ POST /auth/login returns LOGIN_FAILED on inactive user
|
||||
✓ POST /auth/login rate-limits after 10 attempts
|
||||
✓ POST /auth/login with rememberDevice returns deviceToken
|
||||
✓ POST /auth/device-login returns new jwt + rotated token
|
||||
✓ POST /auth/device-login returns AUTH_DEVICE_TOKEN_INVALID on revoked token
|
||||
✓ POST /auth/device-login returns AUTH_DEVICE_TOKEN_INVALID on expired token
|
||||
✓ POST /auth/refresh-token returns new jwt
|
||||
✓ POST /auth/logout returns 204 and logs audit event
|
||||
✓ Authenticated request with valid jwt returns 200
|
||||
✓ Authenticated request with no jwt returns 401
|
||||
✓ Authenticated request with expired jwt returns 401
|
||||
```
|
||||
|
||||
### tests/integration/users.test.js
|
||||
|
||||
```
|
||||
✓ GET /users returns paginated list for Owner
|
||||
✓ GET /users returns 403 for Coach
|
||||
✓ POST /users creates user with hashed password
|
||||
✓ POST /users returns 409 on duplicate username
|
||||
✓ DELETE /users/:id deactivates user (does not hard delete)
|
||||
✓ DELETE /users/:id returns LAST_OWNER_PROTECTED if last Owner
|
||||
✓ DELETE /users/:id revokes all device tokens for the user
|
||||
✓ PUT /users/:id/role returns LAST_OWNER_PROTECTED when demoting last Owner
|
||||
✓ PUT /users/:id/role returns AUTH_FORBIDDEN when Owner tries to change own role
|
||||
✓ PUT /users/:id/password re-hashes password
|
||||
✓ PUT /api/v1/my/password succeeds with correct currentPassword
|
||||
✓ PUT /api/v1/my/password returns 401 with wrong currentPassword
|
||||
✓ Cross-org: user from org B cannot be found by org A
|
||||
```
|
||||
|
||||
### tests/integration/videos.test.js
|
||||
|
||||
```
|
||||
✓ GET /videos returns only videos for requesting org
|
||||
✓ GET /videos filters by category
|
||||
✓ POST /videos accepts valid MP4 (multer disk + magic-byte check)
|
||||
✓ POST /videos rejects non-video file (UPLOAD_TYPE_INVALID)
|
||||
✓ POST /videos returns 507 when disk below threshold
|
||||
✓ DELETE /videos/:id removes DB record and file
|
||||
✓ DELETE /videos/:id returns 404 for wrong org
|
||||
✓ GET /videos/stream/:filename returns 206 with Range header
|
||||
✓ GET /videos/stream/:filename returns 200 without Range header
|
||||
✓ GET /videos/stream/../secret.txt returns 400 (path traversal blocked)
|
||||
✓ GET /videos/stream/:filename returns 404 for filename not in org's DB
|
||||
```
|
||||
|
||||
### tests/integration/workouts.test.js
|
||||
|
||||
```
|
||||
✓ GET /workouts/today uses org timezone, not server local time
|
||||
✓ GET /workouts/today returns workouts for org's "today" across DST boundary
|
||||
✓ POST /workouts returns VALIDATION_FAILED if video ID belongs to different org
|
||||
✓ DELETE /workouts/:id blocks Coach from deleting another Coach's workout
|
||||
✓ DELETE /workouts/:id allows Owner to delete any workout
|
||||
✓ GET /workouts includes null for deleted video slots (LEFT JOIN)
|
||||
```
|
||||
|
||||
### tests/integration/timers.test.js
|
||||
|
||||
```
|
||||
✓ POST /timers/:id/launch creates session and returns sessionId
|
||||
✓ POST /timers/:id/launch returns 409 if a session already active for org
|
||||
✓ DELETE /timers/session stops active session
|
||||
✓ Timer session not found after server restart (in-memory, expected)
|
||||
```
|
||||
|
||||
### tests/integration/clients.test.js
|
||||
|
||||
```
|
||||
✓ Coach only sees own clients
|
||||
✓ Owner sees all clients in org
|
||||
✓ Client cannot access /clients route
|
||||
✓ POST /clients/:id/workouts validates videoId belongs to org
|
||||
✓ DELETE /clients/:id/workouts/:id soft-deletes (row remains, deletedAt set)
|
||||
✓ GET /clients/:id/workouts excludes coachNotes when requester is client
|
||||
✓ POST /clients/:id/sessions/cancel returns 400 if < 24h until session (client)
|
||||
✓ POST /clients/:id/sessions/cancel succeeds for coach regardless of time
|
||||
✓ Feature flag client-management: returns 403 when flag absent
|
||||
```
|
||||
|
||||
### tests/integration/audit.test.js
|
||||
|
||||
```
|
||||
✓ video.upload event recorded after successful upload
|
||||
✓ auth.login.failed recorded on bad password
|
||||
✓ user.create recorded when Owner creates user
|
||||
✓ Audit log failures do not break the parent request
|
||||
✓ GET /audit-logs returns 403 for Coach
|
||||
✓ GET /audit-logs/export returns CSV with correct headers
|
||||
✓ Audit records survive even if the referenced user is deactivated
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Socket Tests
|
||||
|
||||
### tests/socket/timer-engine.socket.test.js
|
||||
|
||||
Uses a real Socket.io server bound to a random port + a test client.
|
||||
|
||||
```
|
||||
✓ Client receives timer:state on timer:join
|
||||
✓ Client receives timer:tick events after start
|
||||
✓ tick events arrive at most once per second
|
||||
✓ Client receives timer:phase-change on phase transition
|
||||
✓ Client receives timer:complete on natural completion, NOT timer:stopped
|
||||
✓ Client receives timer:stopped on manual stop(), NOT timer:complete
|
||||
✓ Reconnected client receives timer:state after timer:join re-emit
|
||||
✓ timer:error SESSION_NOT_FOUND emitted for unknown sessionId
|
||||
✓ unauthenticated socket is disconnected immediately
|
||||
✓ socket from different org cannot join another org's timer room
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## E2E / Burn-In Test
|
||||
|
||||
### tests/e2e/display-burn-in.test.js
|
||||
|
||||
Long-running test. Only run manually (`npm run test:burnin`). Not in CI.
|
||||
|
||||
Uses Playwright (headless Safari via WebKit engine) to simulate the iPad kiosk scenario.
|
||||
|
||||
```
|
||||
✓ App loads and authenticates via device token
|
||||
✓ Timer display page opens and joins socket room
|
||||
✓ Timer runs for its full configured duration (uses a 60-second test timer)
|
||||
✓ phase:change events fire on schedule
|
||||
✓ timer:complete fires at end, NOT timer:stopped
|
||||
✓ DOM is not rebuilt during timer run (MutationObserver counts mutations < threshold)
|
||||
✓ Memory does not grow > 20 MB over 60-second run (page.metrics())
|
||||
✓ After simulated disconnect and reconnect, timer re-syncs correctly
|
||||
✓ AirPlay keep-alive animation is present in the DOM (CSS animation detected)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Test Scripts (package.json)
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"test": "jest tests/unit tests/integration tests/socket --forceExit",
|
||||
"test:unit": "jest tests/unit --forceExit",
|
||||
"test:int": "jest tests/integration --forceExit",
|
||||
"test:socket": "jest tests/socket --forceExit",
|
||||
"test:burnin": "jest tests/e2e/display-burn-in.test.js --forceExit --testTimeout=300000",
|
||||
"test:ci": "jest tests/unit tests/integration tests/socket --forceExit --ci --coverage"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`test:burnin` is excluded from `test` and `test:ci` — it's a manual check, not a gate.
|
||||
|
||||
---
|
||||
|
||||
## Test Dependencies (devDependencies only)
|
||||
|
||||
```json
|
||||
{
|
||||
"jest": "^29",
|
||||
"supertest": "^6",
|
||||
"playwright": "^1"
|
||||
}
|
||||
```
|
||||
|
||||
No test framework is added to `dependencies` — tests only run in the dev environment.
|
||||
Playwright is installed separately for the burn-in test: `npx playwright install webkit`.
|
||||
Reference in New Issue
Block a user