v2 Planning start
This commit is contained in:
@@ -414,3 +414,5 @@ FodyWeavers.xsd
|
||||
# JetBrains Rider
|
||||
*.sln.iml
|
||||
|
||||
.claude/
|
||||
.exclude/
|
||||
@@ -0,0 +1,370 @@
|
||||
# VitFit V2 — Architecture
|
||||
|
||||
## Guiding Principles
|
||||
|
||||
1. **Lean stack** — The server has 2 CPU / 4 GB RAM. No unnecessary processes.
|
||||
2. **Modular** — Each feature is a drop-in module. Core framework is untouched when adding features.
|
||||
3. **Safari-first** — All frontend decisions are validated against Safari on iPadOS.
|
||||
4. **24h session stability** — Long-running JS must not leak memory or drift. Server-authoritative state where possible.
|
||||
5. **API-clean** — REST responses are consistent now so a future iOS app requires no backend changes.
|
||||
|
||||
---
|
||||
|
||||
## Server Environment
|
||||
|
||||
| Item | Value |
|
||||
|------|-------|
|
||||
| OS | Ubuntu 24.04.1 LTS |
|
||||
| Access | PuTTY (SSH), WinSCP (SFTP) — no other access method |
|
||||
| App root | `/home/ubuntu/site/` |
|
||||
| Frontend pages | `/home/ubuntu/site/public/` |
|
||||
| Video uploads | `/home/ubuntu/site/uploads/` (outside public, **do not move**) |
|
||||
| Process manager | PM2 |
|
||||
| Reverse proxy | Nginx |
|
||||
|
||||
The `uploads/` directory is **outside** the `public/` static tree intentionally. All video files are served through an authenticated Express route, never as bare static files. This means gym videos are not publicly accessible without a valid JWT — a security improvement over V1.
|
||||
|
||||
---
|
||||
|
||||
## Backend
|
||||
|
||||
### Framework: Express.js (keep)
|
||||
|
||||
No reason to change. Lightweight, well-understood, sufficient for the load.
|
||||
|
||||
**Changes from V1:**
|
||||
- Routes split into module files, not one monolithic `app.js`
|
||||
- Middleware organized: auth, validation, error handling, logging — each in own file
|
||||
- `helmet` added for security headers
|
||||
- `express-rate-limit` on `/login`
|
||||
- `express-validator` or `zod` for request body validation on all routes
|
||||
|
||||
### Database: SQLite + Sequelize (keep, add migrations)
|
||||
|
||||
SQLite is appropriate for a single-gym install with < 10 concurrent users. Do not over-engineer.
|
||||
|
||||
**Changes from V1:**
|
||||
- Replace `sync({ alter: true })` with proper Sequelize migrations (`sequelize-cli`)
|
||||
- Every schema change ships as a numbered migration file
|
||||
- V1 → V2 migration script handles the initial data carry-over
|
||||
- DB file location configurable via `.env`
|
||||
|
||||
### Video File Serving
|
||||
|
||||
V1 stored uploads in `public/uploads/` and served them as static files — no auth required to access the video files if you knew the URL. V2 changes this.
|
||||
|
||||
**V2 approach: authenticated streaming route**
|
||||
|
||||
```
|
||||
GET /uploads/:filename
|
||||
→ authenticateToken middleware
|
||||
→ pipes file from /home/ubuntu/site/uploads/:filename
|
||||
→ sets correct Content-Type based on mime type stored in DB
|
||||
→ supports Range header for video seeking (required by Safari's <video> element)
|
||||
```
|
||||
|
||||
This is critical: **Safari's `<video>` element requires Range request support** to seek within a video. The route must respond to `Range` headers with a `206 Partial Content` response. A plain `fs.createReadStream` pipe without Range handling will break video playback in Safari.
|
||||
|
||||
Implementation sketch:
|
||||
```js
|
||||
// modules/videos/routes.js
|
||||
router.get('/stream/:filename', authenticateToken, (req, res) => {
|
||||
const filePath = path.join(UPLOADS_DIR, req.params.filename);
|
||||
const stat = fs.statSync(filePath);
|
||||
const fileSize = stat.size;
|
||||
const range = req.headers.range;
|
||||
|
||||
if (range) {
|
||||
const [start, end] = range.replace(/bytes=/, '').split('-').map(Number);
|
||||
const chunkEnd = end || Math.min(start + 1024 * 1024, fileSize - 1);
|
||||
res.writeHead(206, {
|
||||
'Content-Range': `bytes ${start}-${chunkEnd}/${fileSize}`,
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Content-Length': chunkEnd - start + 1,
|
||||
'Content-Type': 'video/mp4',
|
||||
});
|
||||
fs.createReadStream(filePath, { start, end: chunkEnd }).pipe(res);
|
||||
} else {
|
||||
res.writeHead(200, { 'Content-Length': fileSize, 'Content-Type': 'video/mp4' });
|
||||
fs.createReadStream(filePath).pipe(res);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
`UPLOADS_DIR` is set from `.env`: `UPLOADS_DIR=/home/ubuntu/site/uploads`
|
||||
|
||||
---
|
||||
|
||||
### Storage Monitoring
|
||||
|
||||
A new admin-only feature that shows disk usage in the admin panel.
|
||||
|
||||
**API endpoint:** `GET /admin/storage` (requires `authenticateToken` + `authenticateAdmin`)
|
||||
|
||||
Response shape:
|
||||
```json
|
||||
{
|
||||
"disk": {
|
||||
"total": 53687091200,
|
||||
"used": 21474836480,
|
||||
"available": 32212254720,
|
||||
"usedPercent": 40
|
||||
},
|
||||
"uploads": {
|
||||
"size": 4831838208,
|
||||
"fileCount": 47
|
||||
},
|
||||
"warning": false
|
||||
}
|
||||
```
|
||||
|
||||
`warning: true` when available disk space drops below `STORAGE_WARN_BYTES` (env var, default 5 GB).
|
||||
|
||||
**Implementation:** Use the `check-disk-space` npm package for cross-platform disk stats. For uploads folder size, use a recursive `fs` walk summing `stat.size` (fast enough for < 1000 files; cache the result for 60 seconds to avoid hammering the FS on every page load).
|
||||
|
||||
```js
|
||||
// core/storage.js
|
||||
const checkDiskSpace = require('check-disk-space').default;
|
||||
const UPLOADS_DIR = process.env.UPLOADS_DIR;
|
||||
const WARN_BYTES = parseInt(process.env.STORAGE_WARN_BYTES || String(5 * 1024 ** 3));
|
||||
|
||||
let uploadsCache = null;
|
||||
let uploadsCacheTime = 0;
|
||||
|
||||
async function getUploadsSize() {
|
||||
if (Date.now() - uploadsCacheTime < 60_000) return uploadsCache;
|
||||
let total = 0, count = 0;
|
||||
for (const f of fs.readdirSync(UPLOADS_DIR)) {
|
||||
try { const s = fs.statSync(path.join(UPLOADS_DIR, f)); total += s.size; count++; } catch {}
|
||||
}
|
||||
uploadsCache = { size: total, fileCount: count };
|
||||
uploadsCacheTime = Date.now();
|
||||
return uploadsCache;
|
||||
}
|
||||
|
||||
async function getStorageInfo() {
|
||||
const [disk, uploads] = await Promise.all([checkDiskSpace(UPLOADS_DIR), getUploadsSize()]);
|
||||
return { disk, uploads, warning: disk.free < WARN_BYTES };
|
||||
}
|
||||
```
|
||||
|
||||
**Upload guard:** Before accepting a new video upload, multer's `fileFilter` checks available space. If `disk.free < WARN_BYTES * 2` (double the warning threshold as the upload hard limit), reject with HTTP 507 (Insufficient Storage).
|
||||
|
||||
**Frontend display (admin panel):**
|
||||
- Progress bar: used / total, color-coded (green → yellow → red as disk fills)
|
||||
- Three stats: Total, Used, Available (human-readable: GB/MB)
|
||||
- Uploads folder: size + file count
|
||||
- Auto-refreshes every 5 minutes (not on every render)
|
||||
- Warning banner appears when `warning: true`
|
||||
|
||||
---
|
||||
|
||||
### Real-time: Socket.io
|
||||
|
||||
V1 timers are purely client-side — the server has no awareness of timer state. This works but is fragile over a 24h session.
|
||||
|
||||
**V2 approach:**
|
||||
- Timer state lives on the server (in memory, per active session)
|
||||
- Client connects via Socket.io and receives tick events
|
||||
- If the iPad briefly disconnects/reconnects, it re-syncs to server time
|
||||
- Server-side timer uses `process.hrtime()` for drift-free intervals, not `setInterval`
|
||||
- Room-based: each active timer run is a room; admin can see status from management UI
|
||||
|
||||
**Why not polling?** Polling every second from a 24h-running browser is noisy and wasteful. Socket.io with auto-reconnect is cleaner and more reliable.
|
||||
|
||||
### Process Management: PM2
|
||||
|
||||
```bash
|
||||
pm2 start app.js --name vitfit
|
||||
pm2 startup # auto-restart on server reboot
|
||||
pm2 save
|
||||
```
|
||||
|
||||
PM2 handles:
|
||||
- Auto-restart on crash
|
||||
- Log rotation
|
||||
- Memory limit restart (e.g., `--max-memory-restart 512M`)
|
||||
|
||||
### Reverse Proxy: Nginx + HTTPS
|
||||
|
||||
Nginx sits in front of Node:
|
||||
- Terminates TLS (Let's Encrypt / Certbot)
|
||||
- Proxies to `localhost:3000`
|
||||
- Serves static files directly (faster than Node for assets)
|
||||
- Buffers WebSocket upgrades for Socket.io
|
||||
|
||||
**This is required.** Safari on iPad will not allow persistent WebSocket connections or full-screen AirPlay over HTTP on a local network in some iPadOS versions.
|
||||
|
||||
---
|
||||
|
||||
## Frontend
|
||||
|
||||
### Approach: Vanilla JS + CSS Modules (no heavy framework)
|
||||
|
||||
The app is display-oriented, not a complex SPA. A full framework (React, Vue) adds build complexity and memory overhead for marginal benefit on this hardware profile.
|
||||
|
||||
**V2 approach:**
|
||||
- Each page is still an HTML file, but styles move to a shared `styles/` folder
|
||||
- A single `app.js` core handles: auth token management, nav drawer, shared fetch wrapper
|
||||
- Feature modules add their own `<script>` bundles — no bundler required for basic features
|
||||
- CSS custom properties (variables) for theming — one place to change colors/fonts
|
||||
|
||||
**If complexity grows:** Switch to Vite + vanilla JS or Svelte (lightweight, compiles to minimal JS). Avoid React for this use case.
|
||||
|
||||
### Two Distinct UI Modes
|
||||
|
||||
This is the most important structural change from V1.
|
||||
|
||||
**Control Mode (coach on iPad)**
|
||||
- Standard management UI: create workouts, manage videos, start timers
|
||||
- Touch-optimized
|
||||
- Normal nav drawer, forms, admin controls
|
||||
|
||||
**Display Mode (gym-facing, cast to TV)**
|
||||
- Triggered when a workout or timer is "launched" for display
|
||||
- Full-screen layout, no navigation chrome
|
||||
- Large text, high contrast, readable at 10+ feet
|
||||
- Minimal DOM updates (reduces jitter on AirPlay stream)
|
||||
- No cursor (CSS `cursor: none` when idle)
|
||||
- Designed for 16:9 aspect ratio (TV)
|
||||
|
||||
The iPad shows Display Mode. Coach interactions (start/stop/next) are touch targets on the edges of the display — invisible to the TV audience but accessible to the coach.
|
||||
|
||||
---
|
||||
|
||||
## Module System
|
||||
|
||||
### Structure
|
||||
|
||||
On the server, the deployed structure maps to `/home/ubuntu/site/`:
|
||||
|
||||
```
|
||||
/home/ubuntu/site/ (= V2/site/ in this repo)
|
||||
├── app.js # Core: Express init, middleware, module loader
|
||||
├── .env # Secrets + config (not in repo)
|
||||
├── package.json
|
||||
├── core/
|
||||
│ ├── auth.js # JWT middleware
|
||||
│ ├── db.js # Sequelize instance + migration runner
|
||||
│ ├── socket.js # Socket.io setup
|
||||
│ ├── storage.js # Disk/uploads storage helpers
|
||||
│ └── logger.js # Structured logger (pino)
|
||||
├── modules/
|
||||
│ ├── users/ # User management feature
|
||||
│ │ ├── routes.js
|
||||
│ │ ├── model.js
|
||||
│ │ └── migrations/
|
||||
│ ├── videos/ # Video upload + library + streaming
|
||||
│ │ ├── routes.js # Includes /stream/:filename with Range support
|
||||
│ │ ├── model.js
|
||||
│ │ └── migrations/
|
||||
│ ├── workouts/ # Video workouts
|
||||
│ │ ├── routes.js
|
||||
│ │ ├── model.js
|
||||
│ │ └── migrations/
|
||||
│ ├── timers/ # Interval timers
|
||||
│ │ ├── routes.js
|
||||
│ │ ├── model.js
|
||||
│ │ ├── timer-engine.js # Server-side timer state machine
|
||||
│ │ └── migrations/
|
||||
│ ├── crossfit/ # CrossFit workouts
|
||||
│ │ ├── routes.js
|
||||
│ │ ├── model.js
|
||||
│ │ └── migrations/
|
||||
│ └── admin/ # Admin panel: users, storage, logo
|
||||
│ └── routes.js # Includes GET /admin/storage
|
||||
├── public/ # Static frontend (served by Express or Nginx)
|
||||
│ ├── styles/
|
||||
│ │ ├── base.css # Reset, CSS variables, typography
|
||||
│ │ ├── layout.css # Nav, drawer, page shell
|
||||
│ │ └── display.css # TV display mode styles
|
||||
│ ├── js/
|
||||
│ │ ├── core.js # Token management, fetch wrapper, nav
|
||||
│ │ └── socket-client.js
|
||||
│ └── [feature pages]/ # HTML pages per feature
|
||||
└── uploads/ # ← VIDEO FILES LIVE HERE, never inside public/
|
||||
└── [timestamped video files] # Existing V1 files preserved in place
|
||||
```
|
||||
|
||||
**Critical:** `uploads/` is a sibling of `public/`, not inside it. Express does NOT serve this directory statically. All video access goes through `GET /videos/stream/:filename` which enforces JWT auth and handles Range requests.
|
||||
|
||||
### How to Add a Feature
|
||||
|
||||
1. Create `modules/<feature>/` with `routes.js`, `model.js`, and a `migrations/` subfolder
|
||||
2. Register the module in `app.js` with one line: `app.use('/feature', require('./modules/feature/routes'))`
|
||||
3. Add the frontend page(s) to `public/`
|
||||
4. Add a nav link to `public/js/core.js` nav config array
|
||||
5. Run the migration
|
||||
|
||||
Nothing else changes. Removing a feature reverses these steps — no orphaned code.
|
||||
|
||||
---
|
||||
|
||||
## Authentication
|
||||
|
||||
### Changes from V1
|
||||
|
||||
| Concern | V1 | V2 |
|
||||
|---------|----|----|
|
||||
| Token expiry | 7 days | 7 days (unchanged — 24h sessions need this) |
|
||||
| Secret source | `process.env.JWT_SECRET \|\| 'hardcoded'` | `process.env.JWT_SECRET` — fail to start if missing |
|
||||
| Registration | Open endpoint | Admin-only user creation |
|
||||
| Token storage | localStorage | localStorage (unchanged — httpOnly cookies would be better but Safari has restrictions with cross-context; localStorage is acceptable for this closed network use case) |
|
||||
| Password reset | Admin UI | Admin UI (unchanged) |
|
||||
|
||||
### Session Stability for 24h iPad
|
||||
|
||||
- Token TTL stays at 7 days — no mid-day expiry
|
||||
- A `/refresh-token` endpoint is added: before each fetch, if token is within 1 hour of expiry, silently refresh in the background
|
||||
- If token is somehow invalid (server restart with new secret, etc.), the app shows a "Session expired — tap to re-login" overlay rather than breaking silently
|
||||
|
||||
---
|
||||
|
||||
## Data Migration (V1 → V2)
|
||||
|
||||
See `MIGRATION_PLAN.md` for the full script approach.
|
||||
|
||||
Summary:
|
||||
- V1 `database.sqlite` is copied as the starting point
|
||||
- Migration scripts add any new columns/tables without dropping existing data
|
||||
- The V1 table structure maps cleanly to V2 models (no breaking schema changes planned at this stage)
|
||||
- If the workout model is expanded (e.g., more than 4 video slots), a migration adds a new `WorkoutItem` join table while the old 4-slot columns are kept temporarily for backward reads during transition
|
||||
|
||||
---
|
||||
|
||||
## Security Checklist
|
||||
|
||||
- [ ] `helmet()` middleware on all routes
|
||||
- [ ] `express-rate-limit` on `/login` (10 req/15 min)
|
||||
- [ ] Input validation on every POST/PUT route (`zod` or `express-validator`)
|
||||
- [ ] JWT secret from env, app refuses to start without it
|
||||
- [ ] MIME type validation on file uploads (not just extension)
|
||||
- [ ] File size limit on video uploads (configurable via env)
|
||||
- [ ] Upload rejected with HTTP 507 when available disk < 2× `STORAGE_WARN_BYTES`
|
||||
- [ ] Video files served through authenticated `/videos/stream/:filename` route, never static
|
||||
- [ ] Range request (seek) support in video streaming route (required for Safari)
|
||||
- [ ] Nginx enforces HTTPS, redirects HTTP
|
||||
- [ ] Admin-only registration (no open `/register`)
|
||||
- [ ] Database queries use Sequelize parameterized queries (already true in V1, maintain)
|
||||
- [ ] No sensitive data in logs (token values, passwords)
|
||||
- [ ] `.env` in `.gitignore`
|
||||
|
||||
---
|
||||
|
||||
## Dependency Plan
|
||||
|
||||
Keep from V1:
|
||||
- `express`, `sequelize`, `sqlite3`, `bcryptjs`, `jsonwebtoken`, `multer`, `cors`, `dotenv`
|
||||
|
||||
Add:
|
||||
- `socket.io` — real-time timer sync
|
||||
- `helmet` — security headers
|
||||
- `express-rate-limit` — login brute force protection
|
||||
- `zod` — schema validation (lighter than express-validator, works in browser too for future iOS)
|
||||
- `pino` — structured logging (replace raw `console.log`; lighter than winston)
|
||||
- `sequelize-cli` — migration management
|
||||
- `check-disk-space` — cross-platform disk stats for storage monitoring endpoint
|
||||
|
||||
Remove:
|
||||
- `body-parser` — built into Express 4.16+ (`express.json()`)
|
||||
- `node-schedule` — not used in V1; not needed in V2 (Socket.io timer replaces it)
|
||||
@@ -0,0 +1,348 @@
|
||||
# VitFit V2 — Data Model
|
||||
|
||||
## Entity Overview
|
||||
|
||||
```
|
||||
Organization
|
||||
├── Users (SystemAdmin | Owner | Coach | Client)
|
||||
│ ├── DeviceTokens (per user, for remember-me / iPad kiosk)
|
||||
│ └── CoachClientLinks (Coach ↔ Client many-to-many)
|
||||
├── Branding (1-to-1 with Organization)
|
||||
├── Videos
|
||||
│ └── Categories
|
||||
├── Workouts (group display workouts)
|
||||
│ └── WorkoutItems (future: replaces video1-4 columns)
|
||||
├── Timers
|
||||
├── CrossfitWorkouts
|
||||
├── ClientWorkouts (1-on-1 programming per client)
|
||||
├── CalendarSessions (scheduled coach/client sessions)
|
||||
└── AuditLogs
|
||||
```
|
||||
|
||||
All tables except `AuditLogs` and `DeviceTokens` have an `organizationId` foreign key. Every query filters by the requesting user's `organizationId`. This is the tenant isolation boundary.
|
||||
|
||||
---
|
||||
|
||||
## Model Definitions
|
||||
|
||||
### Organization
|
||||
|
||||
```
|
||||
Organizations
|
||||
├── id INTEGER PK
|
||||
├── name STRING NOT NULL "CrossFit Downtown"
|
||||
├── slug STRING UNIQUE "crossfit-downtown" (URL-safe, future subdomain use)
|
||||
├── features TEXT (JSON array) ["client-management", "calendar"]
|
||||
├── isActive BOOLEAN DEFAULT true
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
```
|
||||
|
||||
Notes:
|
||||
- `slug` is auto-generated from `name` on creation; can be edited by SystemAdmin
|
||||
- `features` controls which modules are accessible (see `PRODUCT_VISION.md`)
|
||||
- One Organization is seeded at install time (the gym that purchased this instance)
|
||||
|
||||
---
|
||||
|
||||
### User
|
||||
|
||||
Replaces V1's `Users` table. Extended with `organizationId`, expanded `role`, `isActive`, and profile fields.
|
||||
|
||||
```
|
||||
Users
|
||||
├── id INTEGER PK
|
||||
├── organizationId INTEGER FK → Organizations.id (nullable for SystemAdmin)
|
||||
├── username STRING UNIQUE NOT NULL
|
||||
├── email STRING UNIQUE (optional for now; required for client portal later)
|
||||
├── password STRING NOT NULL (bcrypt hash)
|
||||
├── role ENUM('SystemAdmin', 'Owner', 'Coach', 'Client')
|
||||
├── firstName STRING
|
||||
├── lastName STRING
|
||||
├── isActive BOOLEAN DEFAULT true (soft delete — deactivate, never hard delete)
|
||||
├── lastLoginAt DATE
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
```
|
||||
|
||||
Notes:
|
||||
- `organizationId` is NULL only for SystemAdmin accounts
|
||||
- Deactivated users (`isActive: false`) cannot log in; their data and audit trail are preserved
|
||||
- `email` is nullable in V2 but should be populated for clients who need a login/reset flow
|
||||
- V1 `username` + `password` + `role` columns are preserved exactly — migration just adds new columns
|
||||
|
||||
---
|
||||
|
||||
### DeviceToken
|
||||
|
||||
Supports the iPad kiosk "remember this device" feature and "remember me" on personal devices.
|
||||
|
||||
```
|
||||
DeviceTokens
|
||||
├── id INTEGER PK
|
||||
├── userId INTEGER FK → Users.id
|
||||
├── organizationId INTEGER FK → Organizations.id
|
||||
├── token STRING UNIQUE NOT NULL (UUID or cryptographic random, stored hashed)
|
||||
├── deviceName STRING "Gym iPad", "Jason's MacBook"
|
||||
├── deviceType ENUM('kiosk', 'personal') kiosk = 90-day TTL, personal = 30-day TTL
|
||||
├── lastUsedAt DATE
|
||||
├── expiresAt DATE
|
||||
├── isRevoked BOOLEAN DEFAULT false
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
```
|
||||
|
||||
Flow:
|
||||
1. Login with "Remember this device" → server creates DeviceToken, returns it in response
|
||||
2. Client stores token in localStorage as `deviceToken`
|
||||
3. On page load: if JWT missing/expired, call `POST /auth/device-login` with stored token
|
||||
4. Server finds non-revoked, non-expired token → issues fresh JWT → normal session
|
||||
5. Owner/SystemAdmin can revoke device tokens from the user management UI
|
||||
|
||||
---
|
||||
|
||||
### Branding
|
||||
|
||||
One-to-one with Organization. Stores per-org visual customization.
|
||||
|
||||
```
|
||||
Brandings
|
||||
├── id INTEGER PK
|
||||
├── organizationId INTEGER FK → Organizations.id UNIQUE
|
||||
├── appName STRING DEFAULT 'VitFit'
|
||||
├── logoPath STRING (path within uploads/ or null for default)
|
||||
├── primaryColor STRING DEFAULT '#00FF88' (CSS hex)
|
||||
├── secondaryColor STRING DEFAULT '#4488FF'
|
||||
├── workColor STRING DEFAULT '#00FF88' (timer work phase)
|
||||
├── restColor STRING DEFAULT '#4488FF' (timer rest phase)
|
||||
├── moveColor STRING DEFAULT '#FF4444' (timer move/transition phase)
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Category
|
||||
|
||||
Unchanged from V1, plus `organizationId`.
|
||||
|
||||
```
|
||||
Categories
|
||||
├── id INTEGER PK
|
||||
├── organizationId INTEGER FK → Organizations.id
|
||||
├── name STRING NOT NULL
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
UNIQUE (organizationId, name)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Video
|
||||
|
||||
Unchanged from V1, plus `organizationId` and `mimeType`.
|
||||
|
||||
```
|
||||
Videos
|
||||
├── id INTEGER PK
|
||||
├── organizationId INTEGER FK → Organizations.id
|
||||
├── filename STRING NOT NULL (stored in UPLOADS_DIR)
|
||||
├── description STRING
|
||||
├── category STRING (matches a Category.name — kept as string for V1 compat)
|
||||
├── mimeType STRING (e.g., 'video/mp4' — validated on upload)
|
||||
├── fileSizeBytes INTEGER (stored at upload time for storage reports)
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
```
|
||||
|
||||
Notes:
|
||||
- `category` kept as a string (not FK) to match V1 schema. A future migration can normalize this.
|
||||
- `fileSizeBytes` added so storage reports don't need to re-stat every file on disk
|
||||
|
||||
---
|
||||
|
||||
### Workout (Group Display)
|
||||
|
||||
V1 structure preserved + `organizationId`. The 4-slot columns stay for backward compat.
|
||||
|
||||
```
|
||||
Workouts
|
||||
├── id INTEGER PK
|
||||
├── organizationId INTEGER FK → Organizations.id
|
||||
├── name STRING
|
||||
├── workoutDate DATE
|
||||
├── video1 INTEGER FK → Videos.id (nullable)
|
||||
├── video2 INTEGER FK → Videos.id (nullable)
|
||||
├── video3 INTEGER FK → Videos.id (nullable)
|
||||
├── video4 INTEGER FK → Videos.id (nullable)
|
||||
├── number1 INTEGER
|
||||
├── number2 INTEGER
|
||||
├── number3 INTEGER
|
||||
├── number4 INTEGER
|
||||
├── createdByUserId INTEGER FK → Users.id (new — who created it)
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Timer
|
||||
|
||||
V1 structure preserved + `organizationId` + `name`.
|
||||
|
||||
```
|
||||
Timers
|
||||
├── id INTEGER PK
|
||||
├── organizationId INTEGER FK → Organizations.id
|
||||
├── name STRING NOT NULL (new — human-readable timer name)
|
||||
├── totalTime INTEGER (seconds)
|
||||
├── setTime INTEGER
|
||||
├── restTime INTEGER
|
||||
├── moveTime INTEGER
|
||||
├── setCount INTEGER
|
||||
├── exerciseCount INTEGER
|
||||
├── lapCount INTEGER
|
||||
├── createdByUserId INTEGER FK → Users.id
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### CrossfitWorkout
|
||||
|
||||
V1 structure preserved + `organizationId` + `createdByUserId`.
|
||||
|
||||
```
|
||||
CrossfitWorkouts
|
||||
├── id INTEGER PK
|
||||
├── organizationId INTEGER FK → Organizations.id
|
||||
├── name STRING
|
||||
├── workoutDate DATE
|
||||
├── workoutItems TEXT (JSON array of strings)
|
||||
├── createdByUserId INTEGER FK → Users.id
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### CoachClientLink
|
||||
|
||||
Many-to-many relationship between Coach users and Client users.
|
||||
|
||||
```
|
||||
CoachClientLinks
|
||||
├── id INTEGER PK
|
||||
├── organizationId INTEGER FK → Organizations.id
|
||||
├── coachId INTEGER FK → Users.id (must have role = 'Coach')
|
||||
├── clientId INTEGER FK → Users.id (must have role = 'Client')
|
||||
├── isActive BOOLEAN DEFAULT true
|
||||
├── assignedAt DATE
|
||||
├── assignedByUserId INTEGER FK → Users.id (Owner or SystemAdmin who made the assignment)
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
UNIQUE (coachId, clientId)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### ClientWorkout
|
||||
|
||||
A workout assigned to a specific client by their coach. Different from group Workouts — this is 1-on-1 programming.
|
||||
|
||||
```
|
||||
ClientWorkouts
|
||||
├── id INTEGER PK
|
||||
├── organizationId INTEGER FK → Organizations.id
|
||||
├── clientId INTEGER FK → Users.id
|
||||
├── coachId INTEGER FK → Users.id
|
||||
├── name STRING
|
||||
├── scheduledDate DATE
|
||||
├── notes TEXT (coach notes visible to client)
|
||||
├── items TEXT (JSON array) (flexible: [{type, videoId, reps, sets, notes}])
|
||||
├── completedAt DATE (nullable) (client or coach marks as done)
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
```
|
||||
|
||||
`items` is a flexible JSON structure rather than fixed video slots:
|
||||
```json
|
||||
[
|
||||
{ "type": "video", "videoId": 12, "reps": 10, "sets": 3, "notes": "Full ROM" },
|
||||
{ "type": "text", "text": "200m run between sets" },
|
||||
{ "type": "rest", "durationSeconds": 60 }
|
||||
]
|
||||
```
|
||||
|
||||
This avoids the 4-slot limitation of the group Workout model.
|
||||
|
||||
---
|
||||
|
||||
### CalendarSession
|
||||
|
||||
A scheduled session between a coach and client (or a group class).
|
||||
|
||||
```
|
||||
CalendarSessions
|
||||
├── id INTEGER PK
|
||||
├── organizationId INTEGER FK → Organizations.id
|
||||
├── coachId INTEGER FK → Users.id
|
||||
├── clientId INTEGER FK → Users.id (nullable — null = group/open session)
|
||||
├── title STRING "Weekly Check-in", "Leg Day"
|
||||
├── sessionType ENUM('personal', 'group', 'assessment', 'other')
|
||||
├── startAt DATETIME NOT NULL
|
||||
├── endAt DATETIME NOT NULL
|
||||
├── locationNotes STRING "Gym floor B", "Zoom link: ..."
|
||||
├── coachNotes TEXT (coach-only, client cannot see)
|
||||
├── sharedNotes TEXT (both coach and client can see)
|
||||
├── status ENUM('scheduled', 'completed', 'cancelled', 'no-show') DEFAULT 'scheduled'
|
||||
├── linkedWorkoutId INTEGER FK → ClientWorkouts.id (nullable — the workout for this session)
|
||||
├── createdAt DATE
|
||||
└── updatedAt DATE
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### AuditLog
|
||||
|
||||
Immutable record of all significant actions. Never updated or deleted. See `AUDIT_LOGS.md` for full event catalog.
|
||||
|
||||
```
|
||||
AuditLogs
|
||||
├── id INTEGER PK
|
||||
├── organizationId INTEGER FK → Organizations.id (nullable for SystemAdmin actions)
|
||||
├── userId INTEGER FK → Users.id (nullable for system-generated events)
|
||||
├── userRole STRING (role at time of action — denormalized for log integrity)
|
||||
├── action STRING NOT NULL e.g., 'video.upload', 'user.create', 'timer.delete'
|
||||
├── entityType STRING 'video', 'workout', 'user', etc.
|
||||
├── entityId INTEGER (nullable) ID of the affected record
|
||||
├── details TEXT (JSON) {before: {...}, after: {...}, metadata: {...}}
|
||||
├── ipAddress STRING
|
||||
├── userAgent STRING
|
||||
├── createdAt DATE (the only timestamp — audit logs have no updatedAt)
|
||||
```
|
||||
|
||||
Note: `organizationId` and `userId` on AuditLog are **not** FK-constrained (no `REFERENCES` clause). This ensures log records survive even if the user or org is deleted. They are informational, not relational.
|
||||
|
||||
---
|
||||
|
||||
## Migration from V1
|
||||
|
||||
| V1 Table | V2 Table | Changes |
|
||||
|----------|----------|---------|
|
||||
| Users | Users | + organizationId, email, firstName, lastName, isActive, lastLoginAt |
|
||||
| Videos | Videos | + organizationId, mimeType, fileSizeBytes |
|
||||
| Categories | Categories | + organizationId |
|
||||
| Workouts | Workouts | + organizationId, createdByUserId |
|
||||
| Timers | Timers | + organizationId, name, createdByUserId |
|
||||
| CrossfitWorkouts | CrossfitWorkouts | + organizationId, createdByUserId |
|
||||
| (none) | Organizations | New — one seeded row |
|
||||
| (none) | Brandings | New — one seeded row (default colors) |
|
||||
| (none) | DeviceTokens | New |
|
||||
| (none) | CoachClientLinks | New |
|
||||
| (none) | ClientWorkouts | New |
|
||||
| (none) | CalendarSessions | New |
|
||||
| (none) | AuditLogs | New |
|
||||
|
||||
All V1 data is preserved. New columns are nullable or have defaults so existing rows are valid without backfilling.
|
||||
@@ -0,0 +1,253 @@
|
||||
# VitFit V2 — Display Design (iPad + AirPlay + TV)
|
||||
|
||||
## The Runtime Environment
|
||||
|
||||
Understanding exactly how the display works is critical before writing a line of CSS.
|
||||
|
||||
```
|
||||
[iPad running Safari]
|
||||
└── AirPlay Screen Mirror ──► [VIZIO TV in gym]
|
||||
(1:1 mirror, no second-screen API)
|
||||
```
|
||||
|
||||
AirPlay screen mirroring sends the iPad's exact rendered output to the TV. What the iPad displays IS what the gym sees. There is no separate TV canvas or second-screen API involved.
|
||||
|
||||
**Implications:**
|
||||
- Design for the iPad screen size and aspect ratio — the TV scales it up
|
||||
- The coach and the gym members see the same content at the same time
|
||||
- Touch interactions on the iPad are NOT visible on the TV (no cursor shown)
|
||||
- Safari must stay full-screen — any native UI (address bar, status bar) showing on iPad appears on the TV
|
||||
|
||||
---
|
||||
|
||||
## iPad Full-Screen in Safari
|
||||
|
||||
On iPadOS, "full screen" in Safari means the page fills the viewport but the device is not truly in kiosk mode. To minimize Safari chrome:
|
||||
- Use the "Add to Home Screen" feature → launches as a standalone PWA (removes address bar entirely)
|
||||
- Set `<meta name="apple-mobile-web-app-capable" content="yes">` in the HTML head
|
||||
- Set `<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">`
|
||||
|
||||
**PWA approach is strongly recommended.** It eliminates the Safari address bar and tab bar from the mirrored image on the TV. Without it, the gym sees a browser UI on the TV.
|
||||
|
||||
Required manifest and meta tags:
|
||||
```html
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<link rel="apple-touch-icon" href="/icons/icon-180.png">
|
||||
```
|
||||
|
||||
Safe area insets must be handled for iPad models with rounded corners / notch:
|
||||
```css
|
||||
padding-top: env(safe-area-inset-top);
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## TV Readability Requirements
|
||||
|
||||
The TV is a standard gym display. Gym members view it from across the room (estimated 10–20 feet).
|
||||
|
||||
### Typography
|
||||
|
||||
| Element | Minimum Size | Notes |
|
||||
|---------|-------------|-------|
|
||||
| Primary display (current exercise, timer) | 96px+ | Must be visible at 15 feet |
|
||||
| Secondary info (lap count, set count) | 48px+ | Supporting info |
|
||||
| Labels | 32px+ | Category/phase labels |
|
||||
| Body text (workout list items) | 28px+ | CrossFit workout items |
|
||||
|
||||
Font choice: Use a system font with wide character support and high legibility — `system-ui`, `-apple-system`, or a loaded sans-serif like `Inter`. Avoid decorative fonts.
|
||||
|
||||
Font weight: Bold (700) or Black (900) for primary display numbers. High contrast is more important than style.
|
||||
|
||||
### Color and Contrast
|
||||
|
||||
Minimum WCAG AA contrast ratio (4.5:1) is the floor, not the target. Aim for 7:1+ given the viewing distance.
|
||||
|
||||
Recommended palette for display mode:
|
||||
|
||||
| State | Background | Foreground | Purpose |
|
||||
|-------|-----------|-----------|---------|
|
||||
| Work / Active | `#1a1a1a` dark | `#00FF88` bright green | Athlete is working |
|
||||
| Rest | `#1a1a1a` dark | `#4488FF` bright blue | Rest period |
|
||||
| Transition / Move | `#1a1a1a` dark | `#FF4444` bright red | Moving to next station |
|
||||
| Idle / Ready | `#1a1a1a` dark | `#FFFFFF` white | Waiting to start |
|
||||
| Warning (10s left) | `#1a1a1a` dark | `#FFAA00` amber | Time almost up |
|
||||
|
||||
Dark background is mandatory — it reduces TV backlight bleed and is more readable in a gym with mixed lighting.
|
||||
|
||||
### Layout for Display Mode
|
||||
|
||||
The display must work in landscape orientation (iPad landscape = standard TV aspect ratio).
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ PHASE LABEL LAP X / Y SET X / Y │ ← small, top bar
|
||||
│ │
|
||||
│ │
|
||||
│ 00:45 │ ← giant timer
|
||||
│ │
|
||||
│ BICEP CURLS │ ← exercise name
|
||||
│ │
|
||||
│ [touch zone: prev] [touch zone: next]│ ← invisible coach controls
|
||||
└─────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- Center the primary display number — this is what the athlete reads
|
||||
- Touch zones for coach are on the left/right edges — these are NOT visible on screen
|
||||
- No navigation drawer, no header, no admin UI in display mode
|
||||
- Transitions between phases: brief CSS animation (color change, not movement)
|
||||
|
||||
---
|
||||
|
||||
## 24-Hour Session Stability
|
||||
|
||||
### The Problem
|
||||
|
||||
The iPad browser runs for 24h without refresh. This creates several failure modes:
|
||||
|
||||
1. **Memory leaks** — detached DOM nodes, uncleaned intervals, zombie event listeners
|
||||
2. **Timer drift** — `setInterval` is not precise; over hours, seconds accumulate
|
||||
3. **AirPlay stream freeze** — if the page becomes visually static for too long, some AirPlay implementations freeze the stream
|
||||
4. **Network drops** — WebSocket disconnects; app must reconnect silently
|
||||
5. **JWT expiry** — if token expires during session, app breaks silently
|
||||
|
||||
### Mitigations
|
||||
|
||||
**Memory leaks:**
|
||||
- Every `setInterval` and `addEventListener` is stored in a reference and explicitly cleared when the component/page unmounts
|
||||
- Video elements: `video.src = ''` and `video.load()` before removing from DOM
|
||||
- No anonymous functions as event listeners (cannot be removed); always named references
|
||||
- Display mode DOM is kept minimal — only update `textContent`, never rebuild the DOM during a timer run
|
||||
|
||||
**Timer drift:**
|
||||
- Server-side timer using `process.hrtime.bigint()` for nanosecond precision
|
||||
- Client receives absolute `endTime` timestamp from server, not a countdown delta
|
||||
- Client calculates remaining time as `endTime - Date.now()` on each tick — any network lag is self-correcting
|
||||
- Even if the client's `setInterval` fires late, the displayed time is always accurate
|
||||
|
||||
**AirPlay stream freeze:**
|
||||
- Some AirPlay implementations pause the video stream if the content appears static
|
||||
- Mitigation: a subtle, imperceptible animation runs constantly in display mode (e.g., a 1px opacity pulse on a background element, or the seconds counter always changing)
|
||||
- This is a known AirPlay quirk; the animation must be present even during "rest" countdown
|
||||
|
||||
**Network drops (Socket.io):**
|
||||
- Socket.io has built-in reconnection with exponential backoff — use default config
|
||||
- On reconnect, client immediately requests current timer state from server
|
||||
- If server has no active timer (e.g., it restarted), client shows "Reconnecting..." overlay
|
||||
- No user action required; overlay disappears automatically on sync
|
||||
|
||||
**JWT expiry:**
|
||||
- Tokens are 7-day TTL
|
||||
- On every API call, if response is 401/403, show non-blocking "Session expired" overlay
|
||||
- Overlay has a single tap-to-refresh button (doesn't navigate away; re-auths in place)
|
||||
- Background token refresh: 1 hour before expiry, silently fetch a new token
|
||||
|
||||
---
|
||||
|
||||
## Safari-Specific Quirks
|
||||
|
||||
| Issue | Impact | Mitigation |
|
||||
|-------|--------|-----------|
|
||||
| Safari blocks autoplay audio/video | Timer sounds won't play unless user has interacted | Require a coach "Start Session" tap before any audio. Do not assume sounds will play automatically. |
|
||||
| `position: fixed` can scroll off-screen during Safari address bar hide animation | Layout jumps | Use `position: sticky` or recalculate after `visualViewport` resize events |
|
||||
| `100vh` includes Safari address bar height | Elements clipped at bottom | Use `window.innerHeight` or `100dvh` (dynamic viewport height) — supported in Safari 15.4+ on iPadOS 15.4+ |
|
||||
| WebSQL deprecated, IndexedDB quirks | Not relevant for this app | N/A — we use server-side storage only |
|
||||
| Back/Forward cache (bfcache) | Page may be served from cache on nav | Add `pageshow` event listener to detect bfcache restores and re-initialize Socket.io |
|
||||
|
||||
### `100dvh` Usage
|
||||
|
||||
Use `100dvh` everywhere instead of `100vh`:
|
||||
```css
|
||||
.display-container {
|
||||
height: 100dvh; /* respects Safari dynamic toolbar height */
|
||||
}
|
||||
```
|
||||
|
||||
Fallback for older iPadOS:
|
||||
```css
|
||||
.display-container {
|
||||
height: 100vh;
|
||||
height: 100dvh; /* overrides above if supported */
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## PWA Configuration
|
||||
|
||||
To run as a true kiosk-like experience (no browser chrome on TV):
|
||||
|
||||
### Required in every HTML page `<head>`
|
||||
|
||||
```html
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<link rel="manifest" href="/manifest.json">
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="/icons/icon-180.png">
|
||||
```
|
||||
|
||||
### `manifest.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "VitFit",
|
||||
"short_name": "VitFit",
|
||||
"display": "standalone",
|
||||
"orientation": "landscape",
|
||||
"background_color": "#1a1a1a",
|
||||
"theme_color": "#1a1a1a",
|
||||
"start_url": "/",
|
||||
"icons": [
|
||||
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
|
||||
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Service Worker (minimal)
|
||||
|
||||
A minimal service worker that caches the app shell (HTML, CSS, JS) so the page loads instantly after the 24h refresh, even on slow gym wifi:
|
||||
|
||||
```js
|
||||
// Cache the app shell on install
|
||||
self.addEventListener('install', event => {
|
||||
event.waitUntil(
|
||||
caches.open('vitfit-shell-v1').then(cache =>
|
||||
cache.addAll(['/', '/styles/base.css', '/styles/display.css', '/js/core.js'])
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
// Serve from cache, fall back to network
|
||||
self.addEventListener('fetch', event => {
|
||||
if (event.request.url.includes('/api/') || event.request.url.includes('/socket.io/')) return;
|
||||
event.respondWith(
|
||||
caches.match(event.request).then(r => r || fetch(event.request))
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
Note: API calls and Socket.io are never cached — always network.
|
||||
|
||||
---
|
||||
|
||||
## Orientation and Aspect Ratio
|
||||
|
||||
- iPad in landscape: 4:3 or 3:2 depending on iPad model (not 16:9)
|
||||
- VIZIO TV: 16:9
|
||||
- The TV will pillarbox (black bars on sides) or stretch — this depends on the TV's AirPlay display settings
|
||||
|
||||
**Design for 4:3 safe zone** — put critical content in the center 4:3 area. Decorative elements can extend to the edges that may be cropped on some TV settings.
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────┐
|
||||
│ │ │ │
|
||||
│ crop │ 4:3 SAFE ZONE (all content) │ crop │
|
||||
│ zone │ │ zone │
|
||||
└──────────────────────────────────────────────────┘
|
||||
↑ 16:9 full TV width
|
||||
```
|
||||
@@ -0,0 +1,154 @@
|
||||
# VitFit V2 — Migration Plan (V1 → V2)
|
||||
|
||||
## Goal
|
||||
|
||||
Move all existing data from V1's `database.sqlite` to V2 without data loss. V2 uses proper Sequelize migrations going forward — `sync()` is removed entirely.
|
||||
|
||||
---
|
||||
|
||||
## V1 Schema (what exists today)
|
||||
|
||||
| Table | Key Fields |
|
||||
|-------|-----------|
|
||||
| Users | id, username, password, role, createdAt, updatedAt |
|
||||
| Videos | id, filename, description, category, createdAt, updatedAt |
|
||||
| Categories | id, name, createdAt, updatedAt |
|
||||
| Workouts | id, video1, video2, video3, video4, number1, number2, number3, number4, name, workoutDate, createdAt, updatedAt |
|
||||
| Timers | id, totalTime, setTime, restTime, moveTime, setCount, exerciseCount, lapCount, createdAt, updatedAt |
|
||||
| CrossfitWorkouts | id, name, workoutDate, workoutItems (JSON string), createdAt, updatedAt |
|
||||
|
||||
---
|
||||
|
||||
## Migration Strategy
|
||||
|
||||
### Step 0 — Video Files
|
||||
|
||||
Video files at `/home/ubuntu/site/uploads/` do **not** move. V2's `uploads/` folder IS this directory — the new app is deployed alongside (or replacing) V1 at the same path `/home/ubuntu/site/`. The `UPLOADS_DIR` env var in V2's `.env` points to `/home/ubuntu/site/uploads`.
|
||||
|
||||
No file transfers. No re-uploads. The `filename` values already stored in the `Videos` table remain valid.
|
||||
|
||||
### Step 1 — Back Up V1 Database
|
||||
|
||||
Before deploying V2, back up the existing database:
|
||||
|
||||
```bash
|
||||
# On the server (via PuTTY)
|
||||
cp /home/ubuntu/site/database.sqlite /home/ubuntu/site/database.sqlite.v1-backup
|
||||
```
|
||||
|
||||
Then WinSCP a copy to your local machine as an additional backup. V2 will open the live file in place — the backup is the safety net.
|
||||
|
||||
This preserves all existing data. V2 will open this file and add to it — never recreate from scratch.
|
||||
|
||||
### Step 2 — Initialize Sequelize Migrations
|
||||
|
||||
```bash
|
||||
npx sequelize-cli init # creates migrations/, seeders/, config/
|
||||
```
|
||||
|
||||
Set `config/config.json` (or `config/config.js`) to point at the existing SQLite file.
|
||||
|
||||
### Step 3 — Create Baseline Migration (V1 Schema)
|
||||
|
||||
Generate a "baseline" migration that documents the V1 schema as-is. This migration checks if tables exist before creating them (idempotent), so it's safe to run against the already-populated database:
|
||||
|
||||
```js
|
||||
// migrations/001-baseline.js
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
// Only creates tables if they don't exist — existing data is untouched
|
||||
const tables = await queryInterface.showAllTables();
|
||||
if (!tables.includes('Users')) {
|
||||
await queryInterface.createTable('Users', { /* V1 schema */ });
|
||||
}
|
||||
// ... repeat for each table
|
||||
},
|
||||
down: async () => { /* no-op for baseline */ }
|
||||
};
|
||||
```
|
||||
|
||||
After this, `npx sequelize-cli db:migrate` will mark the baseline as done and all future migrations will apply cleanly.
|
||||
|
||||
### Step 4 — V2 Schema Additions
|
||||
|
||||
Each architectural change to the schema is a new numbered migration:
|
||||
|
||||
| Migration | Change | Reason |
|
||||
|-----------|--------|--------|
|
||||
| `002-add-timer-name.js` | Add `name` column to Timers | Timers need human-readable names in V2 UI |
|
||||
| `003-workout-items-table.js` | Add `WorkoutItems` join table | Future: more than 4 videos per workout |
|
||||
| `004-add-user-refresh-token.js` | Add `refreshToken` column to Users | Token refresh flow |
|
||||
| `005-add-video-mime-type.js` | Add `mimeType` column to Videos | Server-side MIME validation storage |
|
||||
|
||||
Migrations in `002+` use standard `addColumn` / `createTable` — they do not touch existing data.
|
||||
|
||||
---
|
||||
|
||||
## Data Compatibility Notes
|
||||
|
||||
### Workouts (4-slot model)
|
||||
|
||||
V1 stores workouts with `video1`–`video4` and `number1`–`number4` as direct columns. This is inflexible but the data is valid.
|
||||
|
||||
**V2 approach:** Keep the 4-column model as-is for V2. Do not break the schema on day one. The `WorkoutItems` join table migration (`003`) can be added later when the UI is ready to support it. Both models can coexist:
|
||||
- Old workouts: read from `video1`–`video4` columns
|
||||
- New workouts: read from `WorkoutItems` table
|
||||
- A compatibility layer in the API returns the same JSON shape for both
|
||||
|
||||
### CrossFit Workouts (`workoutItems` JSON)
|
||||
|
||||
V1 stores items as a JSON string (SQLite TEXT column). V2 reads it the same way — `JSON.parse()` on read, `JSON.stringify()` on write. No migration needed unless we want to normalize these into rows (not planned for V2).
|
||||
|
||||
### Categories
|
||||
|
||||
V1 seeds 6 categories on startup via `findOrCreate`. V2 migration `001-baseline` includes these as seed data. The seeder won't run if the categories already exist.
|
||||
|
||||
---
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
Since V2 copies (not moves) the V1 database, rollback is:
|
||||
|
||||
1. Stop V2 server
|
||||
2. Restart V1 server pointing at its original database file
|
||||
3. No data loss — V1 database was never touched
|
||||
|
||||
Additive migrations (columns added, tables created) are also reversible via `db:migrate:undo` on each migration's `down` function.
|
||||
|
||||
---
|
||||
|
||||
## Deployment Checklist (via PuTTY + WinSCP)
|
||||
|
||||
```bash
|
||||
# 1. On your local machine — transfer V2 files via WinSCP to /home/ubuntu/site/
|
||||
# (overwrite app.js, core/, modules/, public/ — do NOT touch uploads/ or database.sqlite)
|
||||
|
||||
# 2. SSH via PuTTY, then:
|
||||
cd /home/ubuntu/site
|
||||
|
||||
# 3. Install dependencies (first deploy only, or when package.json changes)
|
||||
npm install
|
||||
|
||||
# 4. Create/verify .env file (if not already there via WinSCP)
|
||||
# Required vars:
|
||||
# JWT_SECRET=<long random string>
|
||||
# DB_PATH=/home/ubuntu/site/database.sqlite
|
||||
# UPLOADS_DIR=/home/ubuntu/site/uploads
|
||||
# PORT=3000
|
||||
# STORAGE_WARN_BYTES=5368709120 (5 GB default)
|
||||
|
||||
# 5. Back up DB before first migration run
|
||||
cp database.sqlite database.sqlite.v1-backup
|
||||
|
||||
# 6. Run migrations
|
||||
npx sequelize-cli db:migrate
|
||||
|
||||
# 7. Verify DB is reachable
|
||||
node -e "require('./core/db').sequelize.authenticate().then(() => console.log('DB OK'))"
|
||||
|
||||
# 8. (Re)start with PM2
|
||||
pm2 restart vitfit # or: pm2 start app.js --name vitfit
|
||||
pm2 save # persist process list across reboots
|
||||
```
|
||||
|
||||
Verify in logs (`pm2 logs vitfit`) that all migrations completed and the server is listening before testing from the iPad.
|
||||
@@ -0,0 +1,210 @@
|
||||
# VitFit V2 — Product Vision & Resale Strategy
|
||||
|
||||
## What This Product Is
|
||||
|
||||
VitFit V2 is a gym management and coaching platform targeting two use cases simultaneously:
|
||||
|
||||
1. **Group gym display** — workouts, timers, and CrossFit content displayed on a TV via iPad + AirPlay (the current use case)
|
||||
2. **1-on-1 coaching** — a coach manages individual client programming, scheduling, and progress through a personal portal
|
||||
|
||||
The product is designed to be **white-labeled and resold** to gym owners, personal trainers, and fitness studios.
|
||||
|
||||
---
|
||||
|
||||
## Deployment Model Decision: Multi-Instance vs True SaaS
|
||||
|
||||
This is the most important architectural decision before writing code. The two options:
|
||||
|
||||
### Option A — Multi-Instance (Recommended for V2)
|
||||
|
||||
Each customer (gym/trainer) gets their own **separate deployment** of VitFit on their own server or a VPS provided as part of the sale.
|
||||
|
||||
```
|
||||
Customer A: vitfit.gymA.com → Server A (their own database, files, branding)
|
||||
Customer B: vitfit.gymB.com → Server B (completely separate)
|
||||
You (seller): deploy + maintain each instance
|
||||
```
|
||||
|
||||
**Pros:**
|
||||
- Complete data isolation — no cross-tenant risk
|
||||
- Each instance is self-contained; one customer's problem can't affect another
|
||||
- Simple: no multi-tenancy code, no subdomain routing
|
||||
- Customer owns their data/server — easier for compliance, white-labeling
|
||||
- Matches current architecture exactly — V1 already does this
|
||||
- SQLite scales fine for a single gym
|
||||
|
||||
**Cons:**
|
||||
- Manual work to deploy each new customer
|
||||
- Updates must be pushed to each instance separately
|
||||
- You maintain N servers instead of 1
|
||||
|
||||
### Option B — True SaaS Multi-Tenant
|
||||
|
||||
One platform, many gyms. Each gym signs up and gets a subdomain.
|
||||
|
||||
```
|
||||
gymA.vitfit.com ─┐
|
||||
gymB.vitfit.com ─┤─ One server, shared database (with tenant_id isolation)
|
||||
gymC.vitfit.com ─┘
|
||||
```
|
||||
|
||||
**Pros:**
|
||||
- One codebase to update
|
||||
- Automatic provisioning (self-serve signup)
|
||||
- Scales to many customers without proportional infrastructure work
|
||||
|
||||
**Cons:**
|
||||
- Requires Postgres (SQLite is not suitable for true multi-tenant SaaS)
|
||||
- Requires wildcard DNS, SSL, and subdomain routing
|
||||
- Data leakage risk if tenant isolation is imperfect
|
||||
- Billing/subscription integration required
|
||||
- Much higher development and operational complexity
|
||||
- Over-engineered for the current customer base
|
||||
|
||||
### Decision: Start with Multi-Instance, Design for SaaS
|
||||
|
||||
**V2 will be multi-instance.** One codebase, deployed separately per customer.
|
||||
|
||||
**However:** The data model will be designed as if it will be multi-tenant later:
|
||||
- Every table that belongs to an organization will have an `organizationId` column from day one
|
||||
- All queries will filter by `organizationId` even with only one org in the DB
|
||||
- When/if SaaS is needed, adding tenant routing is a surface-level change — the data model is already correct
|
||||
|
||||
This means V2 is "SaaS-ready without being SaaS."
|
||||
|
||||
---
|
||||
|
||||
## The Organization Model
|
||||
|
||||
Each deployed instance is owned by one **Organization** (a gym, a studio, a personal trainer's business).
|
||||
|
||||
Within that organization:
|
||||
- One or more **Owners** (the person who bought the license)
|
||||
- One or more **Coaches** (staff, trainers)
|
||||
- Zero or more **Clients** (members, athletes)
|
||||
- One **System Admin** (the platform operator — you)
|
||||
|
||||
See `ROLES_AND_PERMISSIONS.md` for the full role breakdown.
|
||||
|
||||
---
|
||||
|
||||
## Branding & White-Labeling
|
||||
|
||||
Each organization can customize the look and feel through the admin panel:
|
||||
|
||||
| Setting | Where Used |
|
||||
|---------|-----------|
|
||||
| Organization name | Page titles, login screen, emails |
|
||||
| Logo | Nav header, login screen, TV display |
|
||||
| Primary color | Buttons, active states, highlights |
|
||||
| Secondary color | Accents, secondary actions |
|
||||
| Timer display colors | Work/rest/move phase colors on TV |
|
||||
|
||||
Branding is stored per-organization in the database. The frontend reads branding settings on load and applies them via CSS custom properties:
|
||||
|
||||
```js
|
||||
// On page load, after auth
|
||||
const brand = await fetch('/api/branding').then(r => r.json());
|
||||
document.documentElement.style.setProperty('--color-primary', brand.primaryColor);
|
||||
document.documentElement.style.setProperty('--color-secondary', brand.secondaryColor);
|
||||
```
|
||||
|
||||
This means the entire app re-themes without a page rebuild. New organizations get default VitFit branding until they customize it.
|
||||
|
||||
**For resale:** The default branding can be set in `.env` at deploy time:
|
||||
```
|
||||
DEFAULT_BRAND_NAME=VitFit
|
||||
DEFAULT_BRAND_COLOR=#00FF88
|
||||
```
|
||||
When deployed for a specific gym, these are set to their brand before first launch. The gym owner then manages their own branding through the Owner panel.
|
||||
|
||||
---
|
||||
|
||||
## Feature Tiers (Future)
|
||||
|
||||
VitFit is structured so features can be enabled/disabled per organization via a `features` JSON column on the Organization model. This allows selling different tiers:
|
||||
|
||||
| Feature | Tier |
|
||||
|---------|------|
|
||||
| Group display (TV workouts, timers) | Base |
|
||||
| Video library + upload | Base |
|
||||
| CrossFit workouts | Base |
|
||||
| 1-on-1 client management | Plus |
|
||||
| Client calendar + scheduling | Plus |
|
||||
| Audit logs | Plus |
|
||||
| Custom branding | All tiers |
|
||||
|
||||
Feature flags are checked server-side (not just frontend):
|
||||
```js
|
||||
// middleware
|
||||
if (!req.organization.features.includes('client-management')) {
|
||||
return res.sendStatus(403);
|
||||
}
|
||||
```
|
||||
|
||||
This is implemented but not actively gated in V2 (all features on for all customers). The structure exists for future tiering.
|
||||
|
||||
---
|
||||
|
||||
## Current Customer Migration (V1 → V2)
|
||||
|
||||
The existing gym has:
|
||||
- Multiple user accounts (Admin + Coach roles) that are shared among staff — they log in as the same accounts
|
||||
- No individual client accounts
|
||||
- No branding customization applied (uses default)
|
||||
|
||||
**V2 migration path for current customer:**
|
||||
1. One Organization is created (seeded) representing their gym
|
||||
2. All existing V1 users are assigned to that Organization with their existing roles mapped (Admin → Owner/Coach, Coach → Coach)
|
||||
3. The existing single shared Admin account can continue to be used as-is
|
||||
4. Individual accounts are set up as staff start using their own logins
|
||||
5. Clients are added when the 1-on-1 features are ready to use
|
||||
|
||||
The gym does not need to change their workflow on day one. V2 is additive.
|
||||
|
||||
---
|
||||
|
||||
## Credential Saving (iPad Kiosk Use Case)
|
||||
|
||||
The iPad in the gym needs to:
|
||||
- Auto-login on page refresh (24h cycle) without anyone touching it
|
||||
- Not prompt for credentials unless explicitly logged out
|
||||
|
||||
### Device Token Approach
|
||||
|
||||
Standard JWT (7-day TTL) is used for session auth as today. Additionally, a **Device Token** mechanism is added for trusted devices:
|
||||
|
||||
1. On login, if "Remember this device" is checked (or always for the iPad), the server issues a `deviceToken` (a long-lived token, 90 days, stored in a `DeviceTokens` table)
|
||||
2. The `deviceToken` is stored in localStorage separately from the session JWT
|
||||
3. On page load, if the JWT is expired or missing, the app silently calls `POST /auth/device-login` with the `deviceToken`
|
||||
4. Server validates the device token and issues a fresh JWT — no username/password re-entry
|
||||
5. Device tokens can be revoked by an Owner/Admin (e.g., if an iPad is lost)
|
||||
|
||||
This means the iPad essentially never needs manual re-login as long as the device token is valid and not revoked.
|
||||
|
||||
For coach personal devices (phones, laptops) where they want to remember their credentials without a device token, a standard 30-day "remember me" JWT is offered on login.
|
||||
|
||||
---
|
||||
|
||||
## Roadmap Phases
|
||||
|
||||
### Phase 1 — V2 Core (current scope)
|
||||
- Multi-instance architecture with `organizationId` on all models
|
||||
- SystemAdmin, Owner, Coach roles
|
||||
- All V1 features rebuilt cleanly
|
||||
- Storage monitoring
|
||||
- Audit logs
|
||||
- Branding per org
|
||||
- Credential saving / device tokens
|
||||
|
||||
### Phase 2 — Client Features
|
||||
- Client role and portal
|
||||
- 1-on-1 workout assignment (coach → client)
|
||||
- Calendar and scheduling
|
||||
- Client-facing workout view
|
||||
|
||||
### Phase 3 — SaaS (if needed)
|
||||
- Multi-tenant routing (subdomain per org)
|
||||
- Postgres migration
|
||||
- Self-serve signup and billing
|
||||
- Automated provisioning
|
||||
@@ -0,0 +1,27 @@
|
||||
# VitFit V2 — Planning Index
|
||||
|
||||
This folder contains all planning documentation for the V2 redesign.
|
||||
|
||||
| Document | What it covers |
|
||||
|----------|---------------|
|
||||
| [REQUIREMENTS.md](REQUIREMENTS.md) | What V2 must do — functional features, stability, security, and platform constraints |
|
||||
| [ARCHITECTURE.md](ARCHITECTURE.md) | How to build it — stack decisions, module system, real-time strategy, dependency plan |
|
||||
| [DISPLAY_DESIGN.md](DISPLAY_DESIGN.md) | iPad + Safari + AirPlay + TV specifics — PWA config, 24h session stability, typography, Safari quirks |
|
||||
| [MIGRATION_PLAN.md](MIGRATION_PLAN.md) | How to move V1 data to V2 without loss — Sequelize migration strategy, rollback plan |
|
||||
|
||||
## Key Decisions at a Glance
|
||||
|
||||
- **Stack:** Express.js + SQLite (Sequelize with migrations) + Socket.io + Nginx
|
||||
- **Frontend:** Vanilla JS + shared CSS (no heavy framework)
|
||||
- **Timer:** Server-side state machine via Socket.io — drift-free, survives reconnects
|
||||
- **Display:** PWA (`apple-mobile-web-app-capable`) to remove Safari chrome from TV mirror
|
||||
- **Auth:** JWT 7-day TTL + silent background refresh, admin-only user creation
|
||||
- **Modules:** Drop-in feature folders — add/remove without touching core
|
||||
- **Process:** PM2 with memory limit restart, auto-start on server reboot
|
||||
- **Server access:** PuTTY (SSH) + WinSCP (SFTP) only — no other access method
|
||||
- **Video files:** Stay at `/home/ubuntu/site/uploads/` — served via authenticated streaming route with Range support (required by Safari), never as static files
|
||||
- **Storage monitoring:** Admin panel shows disk usage + uploads size; upload endpoint blocks new files when disk is low
|
||||
|
||||
## V1 Reference
|
||||
|
||||
The full V1 code walkthrough is at the repo root: [`CODEBASE_REFERENCE.md`](../../CODEBASE_REFERENCE.md)
|
||||
@@ -0,0 +1,118 @@
|
||||
# VitFit V2 — Requirements
|
||||
|
||||
## Context
|
||||
|
||||
VitFit is a gym coaching tool. The primary runtime environment is:
|
||||
- A dedicated iPad running Safari full-screen
|
||||
- That iPad's screen is AirPlay-mirrored to a VIZIO TV via AirPlay 24/7
|
||||
- The browser is only refreshed once every ~24 hours
|
||||
- iPads are never restarted; the app runs continuously
|
||||
|
||||
The server is a Linux machine (Ubuntu 24.04.1 LTS, 2 CPU, 4 GB RAM).
|
||||
Server is accessed remotely only — via **PuTTY** (SSH) and **WinSCP** (SFTP). There is no local terminal or file manager access.
|
||||
|
||||
**Server paths:**
|
||||
- App root: `/home/ubuntu/site/`
|
||||
- Frontend pages: `/home/ubuntu/site/public/`
|
||||
- Video uploads: `/home/ubuntu/site/uploads/` ← **outside public, must stay here**
|
||||
|
||||
---
|
||||
|
||||
## Functional Requirements
|
||||
|
||||
### Must Carry Over from V1
|
||||
|
||||
| Feature | Notes |
|
||||
|---------|-------|
|
||||
| Video workouts | Up to N videos with rep counts and a scheduled date |
|
||||
| Interval timers | Configurable work/rest/move phases, multiple sets/exercises/laps |
|
||||
| CrossFit workouts | Free-text workout items, ordered list |
|
||||
| Video library | Upload, categorize, browse, delete exercise videos |
|
||||
| User accounts | Admin and Coach roles |
|
||||
| Admin panel | User management, role changes, password reset, logo upload |
|
||||
| JWT authentication | Must survive a 24-hour session without expiry forcing re-login |
|
||||
|
||||
### New Requirements
|
||||
|
||||
- **Workout display mode** — A full-screen, high-contrast view designed to be read from across a gym on a TV. Separate from the management/control UI.
|
||||
- **Stable long-running timer** — Timer execution must not drift, stop, or glitch during a multi-hour session. Must survive the iPad going to sleep/wake if AirPlay connection is maintained.
|
||||
- **Session persistence** — If the page can't be refreshed for 24h, the app must not lose state. No forced logouts mid-session.
|
||||
- **Modular feature system** — New features can be added as self-contained modules without touching existing code. Deployed live.
|
||||
- **Secure by default** — No open registration endpoint. All user creation is admin-gated.
|
||||
- **Future iOS app compatibility** — API must be clean REST so a native iOS client can consume it without changes.
|
||||
- **Storage monitoring in admin panel** — Admin panel must display total disk space, used space, available space, and uploads folder size. Must prevent admins from filling the drive by showing a clear warning when storage is low. Upload endpoint must refuse new files when available space falls below a configurable threshold.
|
||||
|
||||
---
|
||||
|
||||
## Non-Functional Requirements
|
||||
|
||||
### Stability
|
||||
- The app must run continuously without memory leaks degrading performance over 24h+
|
||||
- All JavaScript intervals and event listeners must be properly cleaned up
|
||||
- WebSocket connections must auto-reconnect on drop (no user interaction needed)
|
||||
- Server process must be managed by PM2 with auto-restart on crash
|
||||
- Server must recover from reboot automatically (PM2 startup config)
|
||||
|
||||
### Performance
|
||||
- Page load (initial, after the 24h refresh) must be under 3 seconds on wifi
|
||||
- Timer UI must update at exactly 1-second intervals without drift
|
||||
- Server resource usage must stay well under the 4 GB RAM / 2 CPU ceiling
|
||||
- No memory bloat from video elements left in DOM — properly destroy players when not in view
|
||||
|
||||
### Security
|
||||
- JWT secret must come from an environment variable, never hardcoded
|
||||
- All user creation is admin-only (no open `/register`)
|
||||
- Passwords hashed with bcrypt (already in V1, maintain)
|
||||
- HTTPS required — use nginx + Let's Encrypt on the server
|
||||
- Input validation on all API routes (backend, not just frontend)
|
||||
- Rate limiting on login endpoint to prevent brute force
|
||||
- Security headers via helmet.js
|
||||
- Video uploads: validate MIME type server-side, not just file extension
|
||||
|
||||
### Reliability
|
||||
- Database writes must be transactional where multiple tables are affected
|
||||
- Soft deletes or confirmation guards for destructive actions (videos, workouts)
|
||||
- Health check endpoint (`/health`) for monitoring
|
||||
|
||||
### Browser/Platform Compatibility
|
||||
- Must work correctly in Safari on iPadOS (primary target)
|
||||
- Must work in Safari on macOS (admin use)
|
||||
- Chrome desktop support is a nice-to-have, not required
|
||||
- No features that require browser permissions Safari doesn't support (e.g., no background JS execution assumptions)
|
||||
|
||||
---
|
||||
|
||||
## Constraints
|
||||
|
||||
### Hardware
|
||||
- Server: Ubuntu 24.04.1 LTS, 2 vCPU, 4 GB RAM
|
||||
- SQLite is acceptable at this scale (single gym, small team)
|
||||
- No Redis, no Postgres required — keep the stack lean
|
||||
- Disk space is limited — storage monitoring is a first-class feature, not an afterthought
|
||||
|
||||
### Server Access
|
||||
- SSH only (PuTTY), SFTP only (WinSCP) — no control panel, no local access
|
||||
- All deployments are manual file transfers via WinSCP + SSH commands
|
||||
- No CI/CD pipeline; no automated deployment assumed
|
||||
|
||||
### Data
|
||||
- V1 database must be migrated, not abandoned
|
||||
- All existing workouts, videos, categories, timers, and users must survive the migration
|
||||
- Schema changes must go through migration scripts (not `sync({ force: true })`)
|
||||
- **Video files at `/home/ubuntu/site/uploads/` must not move** — re-uploading is not an option
|
||||
- V2 must serve video files from this path via an authenticated route (not static middleware)
|
||||
|
||||
### Development
|
||||
- Code must be modular: each feature is a self-contained unit (routes + frontend + migrations)
|
||||
- Adding a new feature = dropping in a new module folder + registering it; no other files changed
|
||||
- Removing a feature = removing the module folder; no orphaned code left behind
|
||||
|
||||
---
|
||||
|
||||
## Out of Scope for V2
|
||||
|
||||
- Native iOS app (future phase — but API compatibility must be maintained)
|
||||
- Push notifications
|
||||
- Multi-gym / multi-tenant support
|
||||
- Billing or subscriptions
|
||||
- Video streaming from external providers (YouTube, Vimeo)
|
||||
@@ -0,0 +1,244 @@
|
||||
# VitFit V2 — Roles & Permissions
|
||||
|
||||
## Role Hierarchy
|
||||
|
||||
```
|
||||
SystemAdmin ← Platform operator (you). Cross-org visibility. Not a gym user.
|
||||
│
|
||||
Organization
|
||||
├── Owner ← Gym owner/manager. Manages coaches and clients. Sees everything in their org.
|
||||
├── Coach ← Trainer. Manages workouts and their own clients. Cannot manage other coaches.
|
||||
└── Client ← Athlete/member. Views own workouts and schedule only.
|
||||
```
|
||||
|
||||
Roles are **scoped to an organization**. A user belongs to exactly one organization. SystemAdmin is the only cross-organization role.
|
||||
|
||||
---
|
||||
|
||||
## Role Definitions
|
||||
|
||||
### SystemAdmin
|
||||
- Platform-level administrator (the person who sells and deploys VitFit)
|
||||
- There is exactly one SystemAdmin per deployment (could be multiple accounts, all flagged as SystemAdmin)
|
||||
- Can access any organization's data for support purposes
|
||||
- Manages the Organization record itself (creates, suspends, configures feature flags)
|
||||
- Does NOT manage day-to-day gym operations — that is the Owner's job
|
||||
- Has a dedicated `/sysadmin` panel separate from the normal app UI
|
||||
- Actions are always audit-logged
|
||||
|
||||
### Owner
|
||||
- The gym owner or head administrator who purchased the license
|
||||
- Can do everything a Coach can do, plus:
|
||||
- Manage all user accounts in their organization (create, deactivate, change roles)
|
||||
- View all coaches' clients and workouts
|
||||
- Configure organization branding
|
||||
- View audit logs for their organization
|
||||
- Set up billing/license info (if applicable)
|
||||
- Grant Coach accounts
|
||||
- Manage the client roster
|
||||
- Cannot elevate their own account to SystemAdmin
|
||||
|
||||
### Coach
|
||||
- A trainer or staff member
|
||||
- Can manage workouts, timers, CrossFit workouts, the video library
|
||||
- Can be assigned clients (by Owner or by self-assignment if the org allows it)
|
||||
- Can view and manage their **own** clients' profiles and programming
|
||||
- Cannot see other coaches' clients (unless they are also an Owner)
|
||||
- Cannot manage other user accounts
|
||||
- Cannot view audit logs
|
||||
- Cannot change organization branding
|
||||
|
||||
### Client
|
||||
- An athlete or gym member
|
||||
- Read-only access to their own data
|
||||
- Can view workouts assigned to them by their coach
|
||||
- Can view their own calendar / upcoming sessions
|
||||
- Cannot upload videos, create workouts, or manage any content
|
||||
- Cannot see other clients' data
|
||||
- Cannot see coach-only content (full video library, timer configs, etc.)
|
||||
- Can update their own profile (name, password, preferences)
|
||||
- Does NOT have access to the group display features (TV display, timers) — those are coach-facing
|
||||
|
||||
---
|
||||
|
||||
## Permission Matrix
|
||||
|
||||
Legend: ✅ Full access | 🔶 Own/assigned only | ❌ No access | 👑 SystemAdmin only
|
||||
|
||||
### Organization Management
|
||||
|
||||
| Action | SystemAdmin | Owner | Coach | Client |
|
||||
|--------|------------|-------|-------|--------|
|
||||
| Create organization | 👑 | ❌ | ❌ | ❌ |
|
||||
| Edit organization name/settings | 👑 | ✅ | ❌ | ❌ |
|
||||
| View organization details | 👑 | ✅ | 🔶 (name/logo only) | 🔶 (name/logo only) |
|
||||
| Enable/disable feature flags | 👑 | ❌ | ❌ | ❌ |
|
||||
| Suspend/deactivate organization | 👑 | ❌ | ❌ | ❌ |
|
||||
|
||||
### User Management
|
||||
|
||||
| Action | SystemAdmin | Owner | Coach | Client |
|
||||
|--------|------------|-------|-------|--------|
|
||||
| Create Coach account | 👑 | ✅ | ❌ | ❌ |
|
||||
| Create Client account | 👑 | ✅ | ✅ (if org allows) | ❌ |
|
||||
| View all users in org | 👑 | ✅ | ❌ | ❌ |
|
||||
| View own profile | ✅ | ✅ | ✅ | ✅ |
|
||||
| Edit own profile / password | ✅ | ✅ | ✅ | ✅ |
|
||||
| Change any user's role | 👑 | ✅ | ❌ | ❌ |
|
||||
| Reset any user's password | 👑 | ✅ | ❌ | ❌ |
|
||||
| Deactivate a user | 👑 | ✅ | ❌ | ❌ |
|
||||
| Assign coach to client | 👑 | ✅ | 🔶 (self-assign if allowed) | ❌ |
|
||||
| View assigned clients | — | ✅ (all) | 🔶 (own clients) | ❌ |
|
||||
| Revoke device tokens | 👑 | ✅ | 🔶 (own devices) | 🔶 (own devices) |
|
||||
|
||||
### Branding
|
||||
|
||||
| Action | SystemAdmin | Owner | Coach | Client |
|
||||
|--------|------------|-------|-------|--------|
|
||||
| View branding settings | 👑 | ✅ | ❌ | ❌ |
|
||||
| Edit logo, colors, name | 👑 | ✅ | ❌ | ❌ |
|
||||
|
||||
### Video Library
|
||||
|
||||
| Action | SystemAdmin | Owner | Coach | Client |
|
||||
|--------|------------|-------|-------|--------|
|
||||
| Upload video | 👑 | ✅ | ✅ | ❌ |
|
||||
| View all videos | 👑 | ✅ | ✅ | ❌ |
|
||||
| View videos assigned to them | — | — | — | ✅ (via workouts) |
|
||||
| Delete video | 👑 | ✅ | ✅ | ❌ |
|
||||
| Manage categories | 👑 | ✅ | ✅ | ❌ |
|
||||
|
||||
### Workouts (Group / TV Display)
|
||||
|
||||
| Action | SystemAdmin | Owner | Coach | Client |
|
||||
|--------|------------|-------|-------|--------|
|
||||
| Create group workout | 👑 | ✅ | ✅ | ❌ |
|
||||
| Edit group workout | 👑 | ✅ | ✅ | ❌ |
|
||||
| Delete group workout | 👑 | ✅ | ✅ | ❌ |
|
||||
| Launch workout to TV display | 👑 | ✅ | ✅ | ❌ |
|
||||
| View group workouts | 👑 | ✅ | ✅ | ❌ |
|
||||
|
||||
### Client Workouts (1-on-1)
|
||||
|
||||
| Action | SystemAdmin | Owner | Coach | Client |
|
||||
|--------|------------|-------|-------|--------|
|
||||
| Create workout for a client | 👑 | ✅ | 🔶 (own clients) | ❌ |
|
||||
| Edit client workout | 👑 | ✅ | 🔶 (own clients) | ❌ |
|
||||
| Delete client workout | 👑 | ✅ | 🔶 (own clients) | ❌ |
|
||||
| View own assigned workouts | — | — | — | ✅ |
|
||||
| View all client workouts in org | 👑 | ✅ | ❌ | ❌ |
|
||||
|
||||
### Timers
|
||||
|
||||
| Action | SystemAdmin | Owner | Coach | Client |
|
||||
|--------|------------|-------|-------|--------|
|
||||
| Create / edit / delete timer | 👑 | ✅ | ✅ | ❌ |
|
||||
| Launch timer to TV display | 👑 | ✅ | ✅ | ❌ |
|
||||
| View timer list | 👑 | ✅ | ✅ | ❌ |
|
||||
|
||||
### CrossFit Workouts
|
||||
|
||||
| Action | SystemAdmin | Owner | Coach | Client |
|
||||
|--------|------------|-------|-------|--------|
|
||||
| Create CrossFit workout | 👑 | ✅ | ✅ | ❌ |
|
||||
| Delete CrossFit workout | 👑 | ✅ | ❌ | ❌ |
|
||||
| View CrossFit workouts | 👑 | ✅ | ✅ | ❌ |
|
||||
|
||||
### Calendar / Scheduling
|
||||
|
||||
| Action | SystemAdmin | Owner | Coach | Client |
|
||||
|--------|------------|-------|-------|--------|
|
||||
| Create session/appointment | 👑 | ✅ | 🔶 (own calendar) | ❌ |
|
||||
| Edit session | 👑 | ✅ | 🔶 (own sessions) | ❌ |
|
||||
| Cancel session | 👑 | ✅ | 🔶 (own sessions) | 🔶 (request cancellation) |
|
||||
| View own calendar | — | ✅ | ✅ | ✅ |
|
||||
| View all coaches' calendars | 👑 | ✅ | ❌ | ❌ |
|
||||
| View assigned coach's calendar | — | — | — | 🔶 (coach's availability only) |
|
||||
|
||||
### Audit Logs
|
||||
|
||||
| Action | SystemAdmin | Owner | Coach | Client |
|
||||
|--------|------------|-------|-------|--------|
|
||||
| View org audit log | 👑 | ✅ | ❌ | ❌ |
|
||||
| View cross-org audit log | 👑 | ❌ | ❌ | ❌ |
|
||||
| Export audit log | 👑 | ✅ | ❌ | ❌ |
|
||||
|
||||
### Storage
|
||||
|
||||
| Action | SystemAdmin | Owner | Coach | Client |
|
||||
|--------|------------|-------|-------|--------|
|
||||
| View storage usage | 👑 | ✅ | ❌ | ❌ |
|
||||
|
||||
---
|
||||
|
||||
## UI Navigation by Role
|
||||
|
||||
### SystemAdmin UI
|
||||
- `/sysadmin` — separate section
|
||||
- Organizations list + detail
|
||||
- Cross-org user lookup
|
||||
- Feature flag management
|
||||
- Full audit log (all orgs)
|
||||
- Server health / storage
|
||||
|
||||
### Owner UI
|
||||
Full app + additional Owner tabs in settings:
|
||||
- User management (create coaches + clients, manage roles)
|
||||
- Branding settings
|
||||
- Audit log (own org)
|
||||
- Client roster
|
||||
- All coaches' calendars (read)
|
||||
- Storage monitoring
|
||||
|
||||
### Coach UI
|
||||
Standard app (matches V1 functionality):
|
||||
- Group workouts, timers, CrossFit, video library
|
||||
- My Clients section: list of assigned clients, their programming, their calendar
|
||||
- Own calendar management
|
||||
|
||||
### Client UI
|
||||
Minimal, client-only:
|
||||
- My Workouts — workouts assigned by coach
|
||||
- My Schedule — upcoming sessions
|
||||
- My Profile — update name/password
|
||||
- No nav items for group workouts, video library, or admin functions
|
||||
|
||||
---
|
||||
|
||||
## Role Enforcement
|
||||
|
||||
### Backend
|
||||
Every route that touches org-specific data must:
|
||||
1. Verify JWT (authenticateToken)
|
||||
2. Verify role is sufficient (authenticateRole(['Owner', 'Coach']))
|
||||
3. Verify the resource being accessed belongs to `req.user.organizationId`
|
||||
|
||||
Rule 3 is the critical one — it prevents a Coach at Gym A from accessing Gym B's data even if they somehow get a valid token.
|
||||
|
||||
Pattern:
|
||||
```js
|
||||
// Every data-access query includes the org filter
|
||||
const workout = await Workout.findOne({
|
||||
where: {
|
||||
id: req.params.id,
|
||||
organizationId: req.user.organizationId // ALWAYS required
|
||||
}
|
||||
});
|
||||
if (!workout) return res.sendStatus(404); // 404 not 403 — don't reveal existence
|
||||
```
|
||||
|
||||
### Frontend
|
||||
Frontend hides UI elements based on role (stored in the decoded JWT payload). But hiding is cosmetic — all real enforcement is server-side. Frontend role checks are only for UX, never for security.
|
||||
|
||||
---
|
||||
|
||||
## Mapping V1 Roles → V2 Roles
|
||||
|
||||
| V1 Role | V2 Role | Notes |
|
||||
|---------|---------|-------|
|
||||
| Admin | Owner | The person managing the gym instance |
|
||||
| Coach | Coach | Staff/trainer |
|
||||
| (none) | Client | New in V2 |
|
||||
| (none) | SystemAdmin | New — platform operator only |
|
||||
|
||||
The existing V1 "Admin" user maps to "Owner" in V2. No data is lost. The migration script sets their role to `Owner` and assigns them to the seeded Organization.
|
||||
Reference in New Issue
Block a user