diff --git a/V2/app/.dockerignore b/V2/app/.dockerignore new file mode 100644 index 0000000..8b0e4c6 --- /dev/null +++ b/V2/app/.dockerignore @@ -0,0 +1,9 @@ +node_modules +.env +*.sqlite +uploads/ +tmp/ +pino-*.log +coverage/ +.git +.gitignore diff --git a/V2/app/.env.example b/V2/app/.env.example new file mode 100644 index 0000000..051956f --- /dev/null +++ b/V2/app/.env.example @@ -0,0 +1,25 @@ +PORT=3000 +NODE_ENV=development + +# REQUIRED — app will refuse to start without this +JWT_SECRET=change-me-to-a-long-random-string + +# Database (relative paths work on both Windows and Linux) +DB_PATH=./vitfit.sqlite + +# File storage +UPLOADS_DIR=./uploads +UPLOAD_TEMP_DIR=./tmp +UPLOAD_MAX_BYTES=524288000 + +# Disk warning threshold (5 GB) +STORAGE_WARN_BYTES=5368709120 + +# CORS — set to your domain in production +CORS_ORIGIN=https://yourdomain.com + +# Logging — trace | debug | info | warn | error | fatal +LOG_LEVEL=info + +# Backup (used by scripts/backup-uploads.sh) +BACKUP_UPLOADS_DEST=/mnt/backup/uploads diff --git a/V2/app/.gitignore b/V2/app/.gitignore new file mode 100644 index 0000000..3ce3825 --- /dev/null +++ b/V2/app/.gitignore @@ -0,0 +1,8 @@ +node_modules/ +.env +*.sqlite +uploads/ +/tmp/ +pino-*.log +coverage/ +.sequelizerc diff --git a/V2/app/Dockerfile b/V2/app/Dockerfile new file mode 100644 index 0000000..d7ada03 --- /dev/null +++ b/V2/app/Dockerfile @@ -0,0 +1,41 @@ +# ── Stage 1: install production dependencies ────────────────────────────────── +FROM node:20-alpine AS deps +WORKDIR /app +COPY package*.json ./ +RUN npm ci --omit=dev && npm cache clean --force + +# ── Stage 2: runtime image ──────────────────────────────────────────────────── +FROM node:20-alpine + +# tini: PID 1 signal forwarding + zombie reaping +RUN apk add --no-cache tini + +WORKDIR /app + +# Copy production node_modules from deps stage +COPY --from=deps /app/node_modules ./node_modules + +# Copy application source (respects .dockerignore) +COPY . . + +# Runtime data directories — overridden by volume mounts in production. +# The 'node' user already exists in the official node image. +RUN mkdir -p /data/uploads /data/tmp \ + && chown -R node:node /app /data + +USER node + +ENV NODE_ENV=production \ + PORT=3000 \ + DB_PATH=/data/vitfit.sqlite \ + UPLOADS_DIR=/data/uploads \ + UPLOAD_TEMP_DIR=/data/tmp + +EXPOSE 3000 + +# /health is unauthenticated and checks DB connectivity + disk +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD wget -qO- http://localhost:3000/health || exit 1 + +ENTRYPOINT ["/sbin/tini", "--"] +CMD ["node", "app.js"] diff --git a/V2/app/app.js b/V2/app/app.js new file mode 100644 index 0000000..0abd1bf --- /dev/null +++ b/V2/app/app.js @@ -0,0 +1,148 @@ +'use strict'; + +require('dotenv').config(); + +const http = require('http'); +const express = require('express'); +const helmet = require('helmet'); +const cors = require('cors'); +const rateLimit = require('express-rate-limit'); +const path = require('path'); + +const logger = require('./core/logger'); +const { initDb, runMigrations } = require('./core/db'); +const { init: initSocket } = require('./core/socket'); +const { errorHandler } = require('./core/errors'); + +if (!process.env.JWT_SECRET) { + console.error('FATAL: JWT_SECRET environment variable is required'); + process.exit(1); +} + +const app = express(); +const server = http.createServer(app); + +// Trust the first proxy hop (nginx / k8s ingress) so req.ip is the real client IP +app.set('trust proxy', 1); + +// ── Security headers ────────────────────────────────────────────────────────── +app.use(helmet({ + contentSecurityPolicy: { + directives: { + defaultSrc: ["'self'"], + scriptSrc: ["'self'", "'unsafe-inline'"], + styleSrc: ["'self'", "'unsafe-inline'"], + imgSrc: ["'self'", "data:"], + mediaSrc: ["'self'"], + connectSrc: ["'self'", "wss:"], + fontSrc: ["'self'"], + frameSrc: ["'none'"], + objectSrc: ["'none'"], + baseUri: ["'none'"], + formAction: ["'none'"], + }, + }, +})); + +// ── CORS ────────────────────────────────────────────────────────────────────── +app.use(cors({ + origin: process.env.NODE_ENV === 'production' + ? process.env.CORS_ORIGIN + : true, + credentials: true, +})); + +// ── Body parsing ────────────────────────────────────────────────────────────── +app.use(express.json({ limit: '64kb' })); + +// ── Static frontend ─────────────────────────────────────────────────────────── +app.use(express.static(path.join(__dirname, 'public'))); + +// ── Auth rate limiter (shared by login + device-login) ──────────────────────── +const authRateLimiter = rateLimit({ + windowMs: 15 * 60 * 1000, + max: 10, + standardHeaders: true, + legacyHeaders: false, + message: { error: { code: 'RATE_LIMITED', message: 'Too many attempts, please try again later.' } }, +}); + +// ── Health endpoint (no auth) ───────────────────────────────────────────────── +app.get('/health', async (req, res) => { + const { getStorageInfo } = require('./core/storage'); + const { sequelize } = require('./core/db'); + let dbStatus = 'ok'; + let diskAvailableGB = null; + let diskWarnActive = false; + try { + await sequelize.authenticate(); + const storage = await getStorageInfo(); + diskAvailableGB = parseFloat((storage.disk.free / 1e9).toFixed(1)); + diskWarnActive = storage.warning; + } catch { + dbStatus = 'error'; + } + res.json({ + status: dbStatus === 'ok' && !diskWarnActive ? 'ok' : 'degraded', + version: require('./package.json').version, + uptime: Math.floor(process.uptime()), + db: dbStatus, + diskAvailableGB, + diskWarnActive, + }); +}); + +// ── Auto-load modules ───────────────────────────────────────────────────────── +const fs = require('fs'); +const MODULES_DIR = path.join(__dirname, 'modules'); + +// Collect all route files: routes.js + any *-routes.js in each module dir +function loadRouteFiles(dir) { + const entries = []; + fs.readdirSync(dir).sort().forEach(name => { + const moduleDir = path.join(dir, name); + if (!fs.statSync(moduleDir).isDirectory()) return; + fs.readdirSync(moduleDir).filter(f => f.endsWith('-routes.js') || f === 'routes.js').forEach(file => { + entries.push(path.join(moduleDir, file)); + }); + }); + return entries; +} + +// Auth routes get the per-IP rate limiter; all others just use authenticateToken per-route +const authLimitedRoutes = ['/api/v1/auth']; + +loadRouteFiles(MODULES_DIR).forEach(routesPath => { + const router = require(routesPath); + if (!router.prefix) return; // skip files that don't export a router with prefix + const mountPath = `/api/v1/${router.prefix}`; + if (authLimitedRoutes.some(p => mountPath.startsWith(p))) { + app.use(mountPath, authRateLimiter, router); + } else { + app.use(mountPath, router); + } + logger.info(`Mounted: ${mountPath}`); +}); + +// ── Global error handler ────────────────────────────────────────────────────── +app.use(errorHandler); + +// ── Boot ────────────────────────────────────────────────────────────────────── +async function boot() { + await initDb(); + await runMigrations(); + initSocket(server); + + const port = parseInt(process.env.PORT || '3000', 10); + server.listen(port, () => { + logger.info(`VitFit v${require('./package.json').version} listening on port ${port}`); + if (process.send) process.send('ready'); // PM2 ready signal + }); +} + +boot().catch(err => { + logger.error(err, 'Failed to start server'); + process.exit(1); +}); + +module.exports = { app, server }; diff --git a/V2/app/core/audit.js b/V2/app/core/audit.js new file mode 100644 index 0000000..e52c1a8 --- /dev/null +++ b/V2/app/core/audit.js @@ -0,0 +1,24 @@ +'use strict'; + +const logger = require('./logger'); + +async function log(req, action, entityType, entityId, details = {}) { + try { + const { models } = require('./db'); + await models.AuditLog.create({ + organizationId: req.user?.organizationId ?? null, + userId: req.user?.id ?? null, + userRole: req.user?.role ?? null, + action, + entityType: entityType ?? null, + entityId: entityId ?? null, + details, + ipAddress: req.ip, + userAgent: req.get('User-Agent'), + }); + } catch (err) { + logger.warn({ err, action }, 'Audit log write failed'); + } +} + +module.exports = { log }; diff --git a/V2/app/core/auth.js b/V2/app/core/auth.js new file mode 100644 index 0000000..5893c6e --- /dev/null +++ b/V2/app/core/auth.js @@ -0,0 +1,94 @@ +'use strict'; + +const jwt = require('jsonwebtoken'); +const { AppError } = require('./errors'); + +// Feature flag cache: orgId → { features: string[], fetchedAt: number } +const featureCache = new Map(); +const FEATURE_CACHE_TTL = 5 * 60 * 1000; // 5 minutes + +function authenticateToken(req, res, next) { + const header = req.headers.authorization; + if (!header || !header.startsWith('Bearer ')) { + return next(new AppError('AUTH_REQUIRED', 'Authentication required.', 401)); + } + + const token = header.slice(7); + + jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }, async (err, decoded) => { + if (err) { + return next(new AppError('AUTH_INVALID', 'Invalid or expired token.', 401)); + } + + try { + const { models } = require('./db'); + const user = await models.User.findByPk(decoded.id, { + attributes: ['id', 'username', 'role', 'organizationId', 'isActive', 'passwordChangedAt'], + }); + + if (!user || !user.isActive) { + return next(new AppError('AUTH_INVALID', 'User not found or inactive.', 401)); + } + + if (user.passwordChangedAt && decoded.iat * 1000 < user.passwordChangedAt.getTime()) { + return next(new AppError('AUTH_INVALID', 'Token issued before last password change.', 401)); + } + + req.user = { + id: user.id, + username: user.username, + role: user.role, + organizationId: user.organizationId, + }; + + next(); + } catch (dbErr) { + next(dbErr); + } + }); +} + +function authenticateRole(roles) { + return (req, res, next) => { + if (!req.user) { + return next(new AppError('AUTH_REQUIRED', 'Authentication required.', 401)); + } + if (!roles.includes(req.user.role)) { + return next(new AppError('AUTH_FORBIDDEN', 'You do not have permission to perform this action.', 403)); + } + next(); + }; +} + +function requireFeature(feature) { + return async (req, res, next) => { + if (!req.user) { + return next(new AppError('AUTH_REQUIRED', 'Authentication required.', 401)); + } + + const orgId = req.user.organizationId; + const cached = featureCache.get(orgId); + if (cached && Date.now() - cached.fetchedAt < FEATURE_CACHE_TTL) { + if (!cached.features.includes(feature)) { + return next(new AppError('FEATURE_DISABLED', 'This feature is not enabled for your organization.', 403)); + } + return next(); + } + + try { + const { models } = require('./db'); + const org = await models.Organization.findByPk(orgId, { attributes: ['features'] }); + const features = org ? org.features : []; + featureCache.set(orgId, { features, fetchedAt: Date.now() }); + + if (!features.includes(feature)) { + return next(new AppError('FEATURE_DISABLED', 'This feature is not enabled for your organization.', 403)); + } + next(); + } catch (err) { + next(err); + } + }; +} + +module.exports = { authenticateToken, authenticateRole, requireFeature }; diff --git a/V2/app/core/db.js b/V2/app/core/db.js new file mode 100644 index 0000000..c0e33b8 --- /dev/null +++ b/V2/app/core/db.js @@ -0,0 +1,91 @@ +'use strict'; + +const { Sequelize, DataTypes } = require('sequelize'); +const path = require('path'); +const fs = require('fs'); +const logger = require('./logger'); + +let sequelize; +let models = {}; + +function initDb() { + const dbPath = process.env.DB_PATH || path.join(__dirname, '..', 'database.sqlite'); + + sequelize = new Sequelize({ + dialect: 'sqlite', + storage: dbPath, + logging: (sql) => logger.trace({ sql }, 'SQL'), + }); + + // Required SQLite pragmas + sequelize.query('PRAGMA journal_mode = WAL;'); + sequelize.query('PRAGMA busy_timeout = 5000;'); + sequelize.query('PRAGMA foreign_keys = ON;'); + + // Register all models by scanning module directories + const modulesDir = path.join(__dirname, '..', 'modules'); + fs.readdirSync(modulesDir).forEach(name => { + const modelPath = path.join(modulesDir, name, 'model.js'); + if (fs.existsSync(modelPath)) { + const moduleModels = require(modelPath)(sequelize, DataTypes); + Object.assign(models, moduleModels); + } + }); + + // Run associations after all models are loaded + Object.values(models).forEach(model => { + if (typeof model.associate === 'function') { + model.associate(models); + } + }); + + logger.info({ dbPath }, 'Database initialized'); + return sequelize.authenticate(); +} + +async function runMigrations() { + const { Umzug, SequelizeStorage } = require('umzug'); + + // Collect all migration files from modules/*/migrations/ + const modulesDir = path.join(__dirname, '..', 'modules'); + const migrationFiles = []; + + fs.readdirSync(modulesDir).sort().forEach(moduleName => { + const migrationsDir = path.join(modulesDir, moduleName, 'migrations'); + if (fs.existsSync(migrationsDir)) { + fs.readdirSync(migrationsDir).sort().forEach(file => { + if (file.endsWith('.js')) { + migrationFiles.push(path.join(migrationsDir, file)); + } + }); + } + }); + + // Sort globally by filename prefix (001, 002, ...) + migrationFiles.sort((a, b) => path.basename(a).localeCompare(path.basename(b))); + + const umzug = new Umzug({ + migrations: migrationFiles.map(filePath => ({ + name: path.basename(filePath, '.js'), + path: filePath, + up: async ({ context }) => require(filePath).up(context, Sequelize), + down: async ({ context }) => require(filePath).down(context, Sequelize), + })), + context: sequelize.getQueryInterface(), + storage: new SequelizeStorage({ sequelize }), + logger, + }); + + const pending = await umzug.pending(); + if (pending.length > 0) { + logger.info({ count: pending.length }, 'Running pending migrations'); + await umzug.up(); + logger.info('Migrations complete'); + } +} + +function getSequelize() { + return sequelize; +} + +module.exports = { initDb, runMigrations, getSequelize, get sequelize() { return sequelize; }, get models() { return models; } }; diff --git a/V2/app/core/errors.js b/V2/app/core/errors.js new file mode 100644 index 0000000..0cbd506 --- /dev/null +++ b/V2/app/core/errors.js @@ -0,0 +1,42 @@ +'use strict'; + +const logger = require('./logger'); + +class AppError extends Error { + constructor(code, message, status = 500, field = null) { + super(message); + this.name = 'AppError'; + this.code = code; + this.status = status; + this.field = field; + } +} + +function errorHandler(err, req, res, next) { + if (err instanceof AppError) { + return res.status(err.status).json({ + error: { + code: err.code, + message: err.message, + ...(err.field ? { field: err.field } : {}), + }, + }); + } + + // Multer errors + if (err.code === 'LIMIT_FILE_SIZE') { + return res.status(400).json({ + error: { code: 'UPLOAD_SIZE_EXCEEDED', message: 'File exceeds the maximum allowed size.' }, + }); + } + + logger.error({ err, req: { method: req.method, url: req.url } }, 'Unhandled error'); + + const message = process.env.NODE_ENV === 'production' + ? 'An unexpected error occurred.' + : err.message; + + res.status(500).json({ error: { code: 'INTERNAL_ERROR', message } }); +} + +module.exports = { AppError, errorHandler }; diff --git a/V2/app/core/logger.js b/V2/app/core/logger.js new file mode 100644 index 0000000..74d81d6 --- /dev/null +++ b/V2/app/core/logger.js @@ -0,0 +1,13 @@ +'use strict'; + +const pino = require('pino'); + +const logger = pino({ + level: process.env.LOG_LEVEL || 'info', + transport: process.env.NODE_ENV !== 'production' + ? { target: 'pino-pretty', options: { colorize: true, ignore: 'pid,hostname' } } + : undefined, + redact: ['req.headers.authorization', 'body.password', 'body.currentPassword', 'body.newPassword'], +}); + +module.exports = logger; diff --git a/V2/app/core/respond.js b/V2/app/core/respond.js new file mode 100644 index 0000000..61c9d12 --- /dev/null +++ b/V2/app/core/respond.js @@ -0,0 +1,33 @@ +'use strict'; + +function ok(res, data) { + res.status(200).json({ data }); +} + +function created(res, data) { + res.status(201).json({ data }); +} + +function collection(res, data, total, page, limit) { + res.status(200).json({ + data, + meta: { + total, + page, + limit, + totalPages: Math.ceil(total / limit), + }, + }); +} + +function noContent(res) { + res.status(204).end(); +} + +function err(res, code, message, status, field) { + res.status(status).json({ + error: { code, message, ...(field ? { field } : {}) }, + }); +} + +module.exports = { ok, created, collection, noContent, err }; diff --git a/V2/app/core/schemas/auth.js b/V2/app/core/schemas/auth.js new file mode 100644 index 0000000..444339c --- /dev/null +++ b/V2/app/core/schemas/auth.js @@ -0,0 +1,22 @@ +'use strict'; + +const { z } = require('zod'); + +const login = z.object({ + username: z.string().min(1).max(64), + password: z.string().min(1).max(128), + rememberDevice: z.boolean().optional().default(false), + deviceName: z.string().max(200).optional(), + deviceType: z.enum(['kiosk', 'personal']).optional().default('personal'), +}); + +const deviceLogin = z.object({ + deviceToken: z.string().min(1), +}); + +const changeOwnPassword = z.object({ + currentPassword: z.string().min(1).max(128), + newPassword: z.string().min(8).max(128), +}); + +module.exports = { login, deviceLogin, changeOwnPassword }; diff --git a/V2/app/core/schemas/clients.js b/V2/app/core/schemas/clients.js new file mode 100644 index 0000000..5640b06 --- /dev/null +++ b/V2/app/core/schemas/clients.js @@ -0,0 +1,54 @@ +'use strict'; + +const { z } = require('zod'); + +const createClient = z.object({ + username: z.string().min(1).max(64).regex(/^[a-zA-Z0-9_.-]+$/), + firstName: z.string().max(100).optional(), + lastName: z.string().max(100).optional(), + email: z.string().email().optional(), + password: z.string().min(8).max(128), + coachId: z.number().int().positive().optional(), +}); + +const assignCoach = z.object({ + coachId: z.number().int().positive(), +}); + +const workoutItem = z.discriminatedUnion('type', [ + z.object({ + type: z.literal('video'), + videoId: z.number().int().positive(), + reps: z.number().int().min(0).optional(), + sets: z.number().int().min(0).optional(), + notes: z.string().max(500).optional(), + }), + z.object({ + type: z.literal('text'), + text: z.string().min(1).max(1000), + }), +]); + +const createClientWorkout = z.object({ + name: z.string().min(1).max(200), + scheduledDate: z.string().datetime().optional(), + notes: z.string().max(2000).optional(), + items: z.array(workoutItem).min(1).max(100), +}); + +const updateClientWorkout = createClientWorkout.partial(); + +const createSession = z.object({ + title: z.string().min(1).max(200), + sessionType: z.enum(['personal', 'group', 'assessment', 'other']).default('personal'), + startAt: z.string().datetime(), + endAt: z.string().datetime(), + locationNotes: z.string().max(500).optional(), + coachNotes: z.string().max(2000).optional(), + sharedNotes: z.string().max(2000).optional(), + linkedWorkoutId: z.number().int().positive().optional(), +}); + +const updateSession = createSession.partial(); + +module.exports = { createClient, assignCoach, createClientWorkout, updateClientWorkout, createSession, updateSession }; diff --git a/V2/app/core/schemas/crossfit.js b/V2/app/core/schemas/crossfit.js new file mode 100644 index 0000000..1540b17 --- /dev/null +++ b/V2/app/core/schemas/crossfit.js @@ -0,0 +1,11 @@ +'use strict'; + +const { z } = require('zod'); + +const createCrossfitWorkout = z.object({ + name: z.string().min(1).max(200), + workoutDate: z.string().datetime().optional(), + workoutItems: z.array(z.string().min(1).max(500)).min(1).max(50), +}); + +module.exports = { createCrossfitWorkout }; diff --git a/V2/app/core/schemas/org.js b/V2/app/core/schemas/org.js new file mode 100644 index 0000000..408e6aa --- /dev/null +++ b/V2/app/core/schemas/org.js @@ -0,0 +1,23 @@ +'use strict'; + +const { z } = require('zod'); + +const hexColor = z.string().regex(/^#[0-9A-Fa-f]{6}$/, 'Must be a valid hex color (e.g. #00FF88)'); + +const updateOrg = z.object({ + name: z.string().min(1).max(200).optional(), + timezone: z.string().max(100).optional(), + licenseOwner: z.string().max(200).optional(), + licenseEmail: z.string().email().optional(), +}).strict(); + +const updateBranding = z.object({ + appName: z.string().min(1).max(200).optional(), + primaryColor: hexColor.optional(), + secondaryColor: hexColor.optional(), + workColor: hexColor.optional(), + restColor: hexColor.optional(), + moveColor: hexColor.optional(), +}).strict(); + +module.exports = { updateOrg, updateBranding }; diff --git a/V2/app/core/schemas/timers.js b/V2/app/core/schemas/timers.js new file mode 100644 index 0000000..b403ef9 --- /dev/null +++ b/V2/app/core/schemas/timers.js @@ -0,0 +1,19 @@ +'use strict'; + +const { z } = require('zod'); + +const positiveInt = z.number().int().positive(); +const nonNegInt = z.number().int().min(0); + +const createTimer = z.object({ + name: z.string().min(1).max(200), + totalTime: positiveInt, + setTime: positiveInt, + restTime: nonNegInt.default(0), + moveTime: nonNegInt.default(0), + setCount: positiveInt, + exerciseCount: positiveInt, + lapCount: positiveInt.default(1), +}); + +module.exports = { createTimer }; diff --git a/V2/app/core/schemas/users.js b/V2/app/core/schemas/users.js new file mode 100644 index 0000000..c10755f --- /dev/null +++ b/V2/app/core/schemas/users.js @@ -0,0 +1,28 @@ +'use strict'; + +const { z } = require('zod'); + +const createUser = z.object({ + username: z.string().min(1).max(64).regex(/^[a-zA-Z0-9_.-]+$/, 'Username may only contain letters, numbers, underscores, dots, and hyphens'), + email: z.string().email().optional(), + firstName: z.string().max(100).optional(), + lastName: z.string().max(100).optional(), + password: z.string().min(8).max(128), + role: z.enum(['Owner', 'Coach', 'Client']), +}); + +const updateProfile = z.object({ + firstName: z.string().max(100).optional(), + lastName: z.string().max(100).optional(), + email: z.string().email().optional(), +}).strict(); + +const resetPassword = z.object({ + newPassword: z.string().min(8).max(128), +}); + +const changeRole = z.object({ + role: z.enum(['Owner', 'Coach', 'Client']), +}); + +module.exports = { createUser, updateProfile, resetPassword, changeRole }; diff --git a/V2/app/core/schemas/videos.js b/V2/app/core/schemas/videos.js new file mode 100644 index 0000000..4706bb5 --- /dev/null +++ b/V2/app/core/schemas/videos.js @@ -0,0 +1,14 @@ +'use strict'; + +const { z } = require('zod'); + +const uploadVideo = z.object({ + description: z.string().max(500).optional().default(''), + category: z.string().min(1).max(100), +}); + +const createCategory = z.object({ + name: z.string().min(1).max(100), +}); + +module.exports = { uploadVideo, createCategory }; diff --git a/V2/app/core/schemas/workouts.js b/V2/app/core/schemas/workouts.js new file mode 100644 index 0000000..1f65126 --- /dev/null +++ b/V2/app/core/schemas/workouts.js @@ -0,0 +1,18 @@ +'use strict'; + +const { z } = require('zod'); + +const createWorkout = z.object({ + name: z.string().min(1).max(200), + workoutDate: z.string().datetime().optional(), + video1: z.number().int().positive().nullable().optional(), + video2: z.number().int().positive().nullable().optional(), + video3: z.number().int().positive().nullable().optional(), + video4: z.number().int().positive().nullable().optional(), + number1: z.number().int().min(0).nullable().optional(), + number2: z.number().int().min(0).nullable().optional(), + number3: z.number().int().min(0).nullable().optional(), + number4: z.number().int().min(0).nullable().optional(), +}); + +module.exports = { createWorkout }; diff --git a/V2/app/core/socket.js b/V2/app/core/socket.js new file mode 100644 index 0000000..849a27e --- /dev/null +++ b/V2/app/core/socket.js @@ -0,0 +1,49 @@ +'use strict'; + +const { Server } = require('socket.io'); +const jwt = require('jsonwebtoken'); +const logger = require('./logger'); + +let io; + +function init(httpServer) { + io = new Server(httpServer, { + cors: { + origin: process.env.NODE_ENV === 'production' + ? process.env.CORS_ORIGIN + : true, + credentials: true, + }, + }); + + io.use((socket, next) => { + const token = socket.handshake.auth?.token; + if (!token) { + return next(new Error('Authentication required')); + } + + jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }, (err, decoded) => { + if (err) return next(new Error('Invalid token')); + socket.data.user = decoded; + next(); + }); + }); + + io.on('connection', (socket) => { + logger.debug({ userId: socket.data.user?.id }, 'Socket connected'); + + socket.on('disconnect', (reason) => { + logger.debug({ userId: socket.data.user?.id, reason }, 'Socket disconnected'); + }); + }); + + logger.info('Socket.io initialized'); + return io; +} + +function getIo() { + if (!io) throw new Error('Socket.io not initialized — call init() first'); + return io; +} + +module.exports = { init, getIo }; diff --git a/V2/app/core/storage.js b/V2/app/core/storage.js new file mode 100644 index 0000000..0381eae --- /dev/null +++ b/V2/app/core/storage.js @@ -0,0 +1,74 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const checkDiskSpace = require('check-disk-space').default; +const { AppError } = require('./errors'); + +const UPLOADS_DIR = () => process.env.UPLOADS_DIR || path.join(__dirname, '..', 'uploads'); +const WARN_BYTES = () => parseInt(process.env.STORAGE_WARN_BYTES || String(5 * 1024 ** 3), 10); + +let cache = null; +let cacheTime = 0; +let inflightPromise = null; + +async function getUploadsSize() { + const dir = UPLOADS_DIR(); + let total = 0; + let count = 0; + try { + const files = fs.readdirSync(dir); + for (const f of files) { + try { + const stat = fs.statSync(path.join(dir, f)); + if (stat.isFile()) { total += stat.size; count++; } + } catch {} + } + } catch {} + return { size: total, fileCount: count }; +} + +async function getStorageInfo() { + if (cache && Date.now() - cacheTime < 60_000) return cache; + if (inflightPromise) return inflightPromise; + + inflightPromise = (async () => { + const [disk, uploads] = await Promise.all([ + checkDiskSpace(UPLOADS_DIR()), + getUploadsSize(), + ]); + + const result = { + disk: { + total: disk.size, + used: disk.size - disk.free, + free: disk.free, + usedPercent: Math.round(((disk.size - disk.free) / disk.size) * 100), + }, + uploads, + warning: disk.free < WARN_BYTES(), + warnThresholdBytes: WARN_BYTES(), + }; + + cache = result; + cacheTime = Date.now(); + inflightPromise = null; + return result; + })(); + + return inflightPromise; +} + +async function checkUploadAllowed(req, res, next) { + try { + const info = await getStorageInfo(); + if (info.warning) { + return next(new AppError('STORAGE_INSUFFICIENT', 'Not enough disk space to upload. Contact your administrator.', 507)); + } + next(); + } catch (err) { + next(err); + } +} + +module.exports = { getStorageInfo, checkUploadAllowed }; diff --git a/V2/app/modules/admin/routes.js b/V2/app/modules/admin/routes.js new file mode 100644 index 0000000..7d89cd4 --- /dev/null +++ b/V2/app/modules/admin/routes.js @@ -0,0 +1,21 @@ +'use strict'; + +const express = require('express'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole } = require('../../core/auth'); +const { ok } = require('../../core/respond'); +const { getStorageInfo } = require('../../core/storage'); + +const router = express.Router(); +router.prefix = 'admin'; + +const OWNERS = ['Owner', 'SystemAdmin']; + +router.get('/storage', authenticateToken, authenticateRole(OWNERS), async (req, res, next) => { + try { + const info = await getStorageInfo(); + ok(res, info); + } catch (err) { next(err); } +}); + +module.exports = router; diff --git a/V2/app/modules/audit/migrations/013-audit-logs.js b/V2/app/modules/audit/migrations/013-audit-logs.js new file mode 100644 index 0000000..c6bf843 --- /dev/null +++ b/V2/app/modules/audit/migrations/013-audit-logs.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable('AuditLogs', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: Sequelize.INTEGER }, + userId: { type: Sequelize.INTEGER }, + userRole: { type: Sequelize.STRING }, + action: { type: Sequelize.STRING, allowNull: false }, + entityType: { type: Sequelize.STRING }, + entityId: { type: Sequelize.INTEGER }, + details: { type: Sequelize.TEXT }, + ipAddress: { type: Sequelize.STRING }, + userAgent: { type: Sequelize.STRING }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + }); + + await queryInterface.addIndex('AuditLogs', ['organizationId', 'createdAt']); + await queryInterface.addIndex('AuditLogs', ['userId']); + await queryInterface.addIndex('AuditLogs', ['action']); + await queryInterface.addIndex('AuditLogs', ['entityType', 'entityId']); + }, + + async down(queryInterface) { + await queryInterface.dropTable('AuditLogs'); + }, +}; diff --git a/V2/app/modules/audit/model.js b/V2/app/modules/audit/model.js new file mode 100644 index 0000000..79f4d5d --- /dev/null +++ b/V2/app/modules/audit/model.js @@ -0,0 +1,25 @@ +'use strict'; + +module.exports = (sequelize, DataTypes) => { + const AuditLog = sequelize.define('AuditLog', { + id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: DataTypes.INTEGER }, + userId: { type: DataTypes.INTEGER }, + 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, + createdAt: 'createdAt', + }); + + return { AuditLog }; +}; diff --git a/V2/app/modules/audit/routes.js b/V2/app/modules/audit/routes.js new file mode 100644 index 0000000..f35a8c9 --- /dev/null +++ b/V2/app/modules/audit/routes.js @@ -0,0 +1,60 @@ +'use strict'; + +const express = require('express'); +const { Op } = require('sequelize'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole } = require('../../core/auth'); +const { collection } = require('../../core/respond'); +const { DateTime } = require('luxon'); + +const router = express.Router(); +router.prefix = 'audit-logs'; + +const OWNERS = ['Owner', 'SystemAdmin']; + +router.get('/', authenticateToken, authenticateRole(OWNERS), async (req, res, next) => { + try { + const { action, userId, entityType, from, to, page = 1, limit = 50 } = req.query; + const where = { organizationId: req.user.organizationId }; + if (action) where.action = action; + if (userId) where.userId = parseInt(userId, 10); + if (entityType) where.entityType = entityType; + if (from) where.createdAt = { [Op.gte]: new Date(from) }; + if (to) where.createdAt = { ...where.createdAt, [Op.lte]: new Date(to) }; + + const offset = (parseInt(page, 10) - 1) * parseInt(limit, 10); + const { rows, count } = await models.AuditLog.findAndCountAll({ + where, limit: +limit, offset, order: [['createdAt', 'DESC']], + }); + collection(res, rows, count, +page, +limit); + } catch (err) { next(err); } +}); + +router.get('/export', authenticateToken, authenticateRole(OWNERS), async (req, res, next) => { + try { + const { action, userId, entityType, from, to } = req.query; + const where = { organizationId: req.user.organizationId }; + if (action) where.action = action; + if (userId) where.userId = parseInt(userId, 10); + if (entityType) where.entityType = entityType; + if (from) where.createdAt = { [Op.gte]: new Date(from) }; + if (to) where.createdAt = { ...where.createdAt, [Op.lte]: new Date(to) }; + + const rows = await models.AuditLog.findAll({ where, order: [['createdAt', 'DESC']] }); + + const date = DateTime.now().toISODate(); + res.setHeader('Content-Type', 'text/csv'); + res.setHeader('Content-Disposition', `attachment; filename="audit-log-${date}.csv"`); + + const header = 'id,createdAt,userId,userRole,action,entityType,entityId,ipAddress,details\n'; + res.write(header); + + for (const row of rows) { + const details = JSON.stringify(row.details || {}).replace(/"/g, '""'); + res.write(`${row.id},"${row.createdAt}",${row.userId},"${row.userRole}","${row.action}","${row.entityType}",${row.entityId},"${row.ipAddress}","${details}"\n`); + } + res.end(); + } catch (err) { next(err); } +}); + +module.exports = router; diff --git a/V2/app/modules/auth/migrations/009-device-tokens.js b/V2/app/modules/auth/migrations/009-device-tokens.js new file mode 100644 index 0000000..969e052 --- /dev/null +++ b/V2/app/modules/auth/migrations/009-device-tokens.js @@ -0,0 +1,26 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable('DeviceTokens', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + userId: { type: Sequelize.INTEGER, allowNull: false }, + organizationId: { type: Sequelize.INTEGER, allowNull: false }, + token: { type: Sequelize.STRING, allowNull: false, unique: true }, + deviceName: { type: Sequelize.STRING }, + deviceType: { type: Sequelize.ENUM('kiosk', 'personal'), defaultValue: 'personal' }, + lastUsedAt: { type: Sequelize.DATE }, + expiresAt: { type: Sequelize.DATE, allowNull: false }, + isRevoked: { type: Sequelize.BOOLEAN, defaultValue: false }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false }, + }); + + await queryInterface.addIndex('DeviceTokens', ['token']); + await queryInterface.addIndex('DeviceTokens', ['userId', 'isRevoked']); + }, + + async down(queryInterface) { + await queryInterface.dropTable('DeviceTokens'); + }, +}; diff --git a/V2/app/modules/auth/model.js b/V2/app/modules/auth/model.js new file mode 100644 index 0000000..f22f6ba --- /dev/null +++ b/V2/app/modules/auth/model.js @@ -0,0 +1,21 @@ +'use strict'; + +module.exports = (sequelize, DataTypes) => { + const 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 }, + 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 }, + }); + + DeviceToken.associate = (models) => { + DeviceToken.belongsTo(models.User, { foreignKey: 'userId' }); + }; + + return { DeviceToken }; +}; diff --git a/V2/app/modules/auth/routes.js b/V2/app/modules/auth/routes.js new file mode 100644 index 0000000..7f1a1eb --- /dev/null +++ b/V2/app/modules/auth/routes.js @@ -0,0 +1,55 @@ +'use strict'; + +const express = require('express'); +const { models } = require('../../core/db'); +const { authenticateToken } = require('../../core/auth'); +const { ok, noContent } = require('../../core/respond'); +const { AppError } = require('../../core/errors'); +const { login, deviceLogin, refreshToken } = require('./service'); +const { login: loginSchema, deviceLogin: deviceLoginSchema } = require('../../core/schemas/auth'); +const { log: auditLog } = require('../../core/audit'); + +const router = express.Router(); +router.prefix = 'auth'; + +function validate(schema) { + return (req, res, next) => { + const result = schema.safeParse(req.body); + if (!result.success) { + const field = result.error.errors[0]?.path[0]; + return next(new AppError('VALIDATION_FAILED', result.error.errors[0].message, 400, field)); + } + req.body = result.data; + next(); + }; +} + +router.post('/login', validate(loginSchema), async (req, res, next) => { + try { + const result = await login(models, req, req.body); + ok(res, result); + } catch (err) { next(err); } +}); + +router.post('/device-login', validate(deviceLoginSchema), async (req, res, next) => { + try { + const result = await deviceLogin(models, req, req.body.deviceToken); + ok(res, result); + } catch (err) { next(err); } +}); + +router.post('/refresh-token', authenticateToken, async (req, res, next) => { + try { + const result = await refreshToken(models, req.user.id); + ok(res, result); + } catch (err) { next(err); } +}); + +router.post('/logout', authenticateToken, async (req, res, next) => { + try { + await auditLog(req, 'auth.logout', 'user', req.user.id, {}); + noContent(res); + } catch (err) { next(err); } +}); + +module.exports = router; diff --git a/V2/app/modules/auth/service.js b/V2/app/modules/auth/service.js new file mode 100644 index 0000000..0304628 --- /dev/null +++ b/V2/app/modules/auth/service.js @@ -0,0 +1,138 @@ +'use strict'; + +const bcrypt = require('bcryptjs'); +const jwt = require('jsonwebtoken'); +const crypto = require('crypto'); +const { AppError } = require('../../core/errors'); +const { log: auditLog } = require('../../core/audit'); + +// Per-username brute force tracking (process memory) +const failureMap = new Map(); // username → { count, resetAt } +const MAX_FAILURES = 10; +const LOCKOUT_MS = 15 * 60 * 1000; + +function checkLockout(username) { + const entry = failureMap.get(username); + if (!entry) return; + if (Date.now() > entry.resetAt) { failureMap.delete(username); return; } + if (entry.count >= MAX_FAILURES) { + throw new AppError('LOGIN_FAILED', 'Invalid username or password.', 401); + } +} + +function recordFailure(username) { + const entry = failureMap.get(username) || { count: 0, resetAt: Date.now() + LOCKOUT_MS }; + entry.count++; + failureMap.set(username, entry); +} + +function clearFailures(username) { + failureMap.delete(username); +} + +function signJwt(user) { + return jwt.sign( + { id: user.id, username: user.username, role: user.role, organizationId: user.organizationId }, + process.env.JWT_SECRET, + { algorithm: 'HS256', expiresIn: '7d' } + ); +} + +function hashToken(rawToken) { + return crypto.createHash('sha256').update(rawToken).digest('hex'); +} + +async function createDeviceToken(models, userId, orgId, deviceName, deviceType) { + const rawToken = crypto.randomBytes(32).toString('hex'); + const ttlDays = deviceType === 'kiosk' ? 90 : 30; + const expiresAt = new Date(Date.now() + ttlDays * 24 * 60 * 60 * 1000); + + const record = await models.DeviceToken.create({ + userId, + organizationId: orgId, + token: hashToken(rawToken), + deviceName: deviceName || 'Unknown device', + deviceType: deviceType || 'personal', + expiresAt, + lastUsedAt: new Date(), + }); + + return { rawToken, record }; +} + +async function login(models, req, { username, password, rememberDevice, deviceName, deviceType }) { + checkLockout(username); + + const user = await models.User.findOne({ + where: { username }, + attributes: ['id', 'username', 'email', 'role', 'organizationId', 'isActive', 'password'], + }); + + const valid = user && user.isActive && await bcrypt.compare(password, user.password); + + if (!valid) { + recordFailure(username); + throw new AppError('LOGIN_FAILED', 'Invalid username or password.', 401); + } + + clearFailures(username); + + await user.update({ lastLoginAt: new Date() }); + + const token = signJwt(user); + let deviceToken; + + if (rememberDevice) { + const { rawToken } = await createDeviceToken(models, user.id, user.organizationId, deviceName, deviceType); + deviceToken = rawToken; + } + + const userPublic = { id: user.id, username: user.username, role: user.role, organizationId: user.organizationId }; + + await auditLog(req, 'auth.login.success', 'user', user.id, { username }); + + return { jwt: token, user: userPublic, ...(deviceToken ? { deviceToken } : {}) }; +} + +async function deviceLogin(models, req, rawToken) { + const hash = hashToken(rawToken); + const record = await models.DeviceToken.findOne({ where: { token: hash } }); + + if (!record || record.isRevoked || record.expiresAt < new Date()) { + throw new AppError('AUTH_DEVICE_TOKEN_INVALID', 'Device token is invalid or expired.', 401); + } + + const user = await models.User.findByPk(record.userId, { + attributes: ['id', 'username', 'role', 'organizationId', 'isActive'], + }); + + if (!user || !user.isActive) { + throw new AppError('AUTH_DEVICE_TOKEN_INVALID', 'Device token is invalid or expired.', 401); + } + + // Rotate token + await record.update({ isRevoked: true }); + const { rawToken: newRaw } = await createDeviceToken( + models, user.id, user.organizationId, record.deviceName, record.deviceType + ); + + await user.update({ lastLoginAt: new Date() }); + + const token = signJwt(user); + await auditLog(req, 'auth.token.refreshed', 'user', user.id, {}); + + const userPublic = { id: user.id, username: user.username, role: user.role, organizationId: user.organizationId }; + return { jwt: token, deviceToken: newRaw, user: userPublic }; +} + +async function refreshToken(models, userId) { + const user = await models.User.findByPk(userId, { + attributes: ['id', 'username', 'role', 'organizationId', 'isActive'], + }); + if (!user || !user.isActive) { + throw new AppError('AUTH_INVALID', 'User not found.', 401); + } + return { jwt: signJwt(user) }; +} + +module.exports = { login, deviceLogin, refreshToken }; diff --git a/V2/app/modules/clients/calendar-routes.js b/V2/app/modules/clients/calendar-routes.js new file mode 100644 index 0000000..b49ff62 --- /dev/null +++ b/V2/app/modules/clients/calendar-routes.js @@ -0,0 +1,22 @@ +'use strict'; + +const express = require('express'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole, requireFeature } = require('../../core/auth'); +const { collection } = require('../../core/respond'); +const svc = require('./service'); + +const router = express.Router(); +router.prefix = 'calendar'; + +const CALENDAR = requireFeature('calendar'); +const COACH_PLUS = ['Owner', 'Coach', 'SystemAdmin']; + +router.get('/', authenticateToken, CALENDAR, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const { rows, count } = await svc.getSessions(models, req.query, req.user.organizationId, req.user.id, req.user.role); + collection(res, rows, count, +(req.query.page || 1), +(req.query.limit || 50)); + } catch (err) { next(err); } +}); + +module.exports = router; diff --git a/V2/app/modules/clients/migrations/010-coach-client-links.js b/V2/app/modules/clients/migrations/010-coach-client-links.js new file mode 100644 index 0000000..d9a266d --- /dev/null +++ b/V2/app/modules/clients/migrations/010-coach-client-links.js @@ -0,0 +1,24 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable('CoachClientLinks', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: Sequelize.INTEGER, allowNull: false }, + coachId: { type: Sequelize.INTEGER, allowNull: false }, + clientId: { type: Sequelize.INTEGER, allowNull: false }, + isActive: { type: Sequelize.BOOLEAN, defaultValue: true }, + assignedAt: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }, + assignedByUserId: { type: Sequelize.INTEGER }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false }, + }); + + await queryInterface.addIndex('CoachClientLinks', ['coachId', 'clientId', 'isActive']); + await queryInterface.addIndex('CoachClientLinks', ['clientId', 'isActive']); + }, + + async down(queryInterface) { + await queryInterface.dropTable('CoachClientLinks'); + }, +}; diff --git a/V2/app/modules/clients/migrations/011-client-workouts.js b/V2/app/modules/clients/migrations/011-client-workouts.js new file mode 100644 index 0000000..8d33aef --- /dev/null +++ b/V2/app/modules/clients/migrations/011-client-workouts.js @@ -0,0 +1,26 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable('ClientWorkouts', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: Sequelize.INTEGER, allowNull: false }, + clientId: { type: Sequelize.INTEGER, allowNull: false }, + coachId: { type: Sequelize.INTEGER, allowNull: false }, + name: { type: Sequelize.STRING }, + scheduledDate: { type: Sequelize.DATE }, + notes: { type: Sequelize.TEXT }, + items: { type: Sequelize.TEXT, defaultValue: '[]' }, + completedAt: { type: Sequelize.DATE }, + deletedAt: { type: Sequelize.DATE }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false }, + }); + + await queryInterface.addIndex('ClientWorkouts', ['clientId', 'deletedAt', 'scheduledDate']); + }, + + async down(queryInterface) { + await queryInterface.dropTable('ClientWorkouts'); + }, +}; diff --git a/V2/app/modules/clients/migrations/012-calendar-sessions.js b/V2/app/modules/clients/migrations/012-calendar-sessions.js new file mode 100644 index 0000000..ad07801 --- /dev/null +++ b/V2/app/modules/clients/migrations/012-calendar-sessions.js @@ -0,0 +1,30 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable('CalendarSessions', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: Sequelize.INTEGER, allowNull: false }, + coachId: { type: Sequelize.INTEGER, allowNull: false }, + clientId: { type: Sequelize.INTEGER }, + title: { type: Sequelize.STRING }, + sessionType: { type: Sequelize.ENUM('personal', 'group', 'assessment', 'other'), defaultValue: 'personal' }, + startAt: { type: Sequelize.DATE, allowNull: false }, + endAt: { type: Sequelize.DATE, allowNull: false }, + locationNotes: { type: Sequelize.STRING }, + coachNotes: { type: Sequelize.TEXT }, + sharedNotes: { type: Sequelize.TEXT }, + status: { type: Sequelize.ENUM('scheduled', 'completed', 'cancelled', 'no-show'), defaultValue: 'scheduled' }, + linkedWorkoutId: { type: Sequelize.INTEGER }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false }, + }); + + await queryInterface.addIndex('CalendarSessions', ['coachId', 'startAt']); + await queryInterface.addIndex('CalendarSessions', ['clientId', 'startAt']); + }, + + async down(queryInterface) { + await queryInterface.dropTable('CalendarSessions'); + }, +}; diff --git a/V2/app/modules/clients/model.js b/V2/app/modules/clients/model.js new file mode 100644 index 0000000..bd9c395 --- /dev/null +++ b/V2/app/modules/clients/model.js @@ -0,0 +1,51 @@ +'use strict'; + +module.exports = (sequelize, DataTypes) => { + const 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 }, + }); + + const 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, + defaultValue: '[]', + get() { try { return JSON.parse(this.getDataValue('items') || '[]'); } catch { return []; } }, + set(v) { this.setDataValue('items', JSON.stringify(v)); }, + }, + completedAt: { type: DataTypes.DATE }, + deletedAt: { type: DataTypes.DATE }, + }); + + ClientWorkout.addScope('active', { where: { deletedAt: null } }); + + const 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 }, + 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 }, + }); + + return { CoachClientLink, ClientWorkout, CalendarSession }; +}; diff --git a/V2/app/modules/clients/my-routes.js b/V2/app/modules/clients/my-routes.js new file mode 100644 index 0000000..f09aaa4 --- /dev/null +++ b/V2/app/modules/clients/my-routes.js @@ -0,0 +1,28 @@ +'use strict'; + +const express = require('express'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole, requireFeature } = require('../../core/auth'); +const { ok, collection } = require('../../core/respond'); +const svc = require('./service'); + +const router = express.Router(); +// These are mounted under /my by app.js via a separate prefix registration +router.prefix = 'my/client'; + +router.get('/workouts', authenticateToken, authenticateRole(['Client']), async (req, res, next) => { + try { + const { page = 1, limit = 20, includeCompleted } = req.query; + const { rows, count } = await svc.getClientWorkouts(models, req.user.id, req.user.id, req.user.organizationId, 'Client', { page: +page, limit: +limit, includeCompleted }); + collection(res, rows, count, +page, +limit); + } catch (err) { next(err); } +}); + +router.get('/sessions', authenticateToken, authenticateRole(['Client']), async (req, res, next) => { + try { + const { rows, count } = await svc.getSessions(models, req.query, req.user.organizationId, req.user.id, 'Client'); + collection(res, rows, count, +(req.query.page || 1), +(req.query.limit || 20)); + } catch (err) { next(err); } +}); + +module.exports = router; diff --git a/V2/app/modules/clients/routes.js b/V2/app/modules/clients/routes.js new file mode 100644 index 0000000..a39b52b --- /dev/null +++ b/V2/app/modules/clients/routes.js @@ -0,0 +1,152 @@ +'use strict'; + +const express = require('express'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole, requireFeature } = require('../../core/auth'); +const { ok, created, collection, noContent } = require('../../core/respond'); +const { AppError } = require('../../core/errors'); +const { createClient, assignCoach: assignCoachSchema, createClientWorkout, updateClientWorkout, createSession, updateSession } = require('../../core/schemas/clients'); +const { createUser: createUserSchema } = require('../../core/schemas/users'); +const svc = require('./service'); +const userSvc = require('../users/service'); + +const router = express.Router(); +router.prefix = 'clients'; + +const COACH_PLUS = ['Owner', 'Coach', 'SystemAdmin']; +const OWNERS = ['Owner', 'SystemAdmin']; +const ALL_AUTHENTICATED = ['Owner', 'Coach', 'Client', 'SystemAdmin']; + +const CLIENT_MGMT = requireFeature('client-management'); + +function validate(schema) { + return (req, res, next) => { + const result = schema.safeParse(req.body); + if (!result.success) { + const e = result.error.errors[0]; + return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0])); + } + req.body = result.data; + next(); + }; +} + +// GET /clients +router.get('/', authenticateToken, CLIENT_MGMT, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const clients = await svc.getClients(models, req.user.id, req.user.organizationId, req.user.role); + ok(res, clients.map(c => c.toPublic())); + } catch (err) { next(err); } +}); + +// POST /clients +router.post('/', authenticateToken, CLIENT_MGMT, authenticateRole(OWNERS), validate(createClient), async (req, res, next) => { + try { + const { coachId, ...userData } = req.body; + userData.role = 'Client'; + const user = await userSvc.createUser(models, req, req.user.organizationId, userData); + if (coachId) await svc.assignCoach(models, req, user.id, coachId, req.user.organizationId); + ok(res, user); + } catch (err) { next(err); } +}); + +// GET /clients/:id +router.get('/:id', authenticateToken, CLIENT_MGMT, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const client = await svc.getClientById(models, parseInt(req.params.id, 10), req.user.id, req.user.organizationId, req.user.role); + ok(res, client.toPublic()); + } catch (err) { next(err); } +}); + +// POST /clients/:id/assign +router.post('/:id/assign', authenticateToken, CLIENT_MGMT, authenticateRole(OWNERS), validate(assignCoachSchema), async (req, res, next) => { + try { + const link = await svc.assignCoach(models, req, parseInt(req.params.id, 10), req.body.coachId, req.user.organizationId); + ok(res, link); + } catch (err) { next(err); } +}); + +// DELETE /clients/:id/assign +router.delete('/:id/assign', authenticateToken, CLIENT_MGMT, authenticateRole(OWNERS), async (req, res, next) => { + try { + const { linkId } = req.body; + if (!linkId) return next(new AppError('VALIDATION_FAILED', 'linkId required.', 400)); + await svc.unassignCoach(models, req, linkId, req.user.organizationId); + noContent(res); + } catch (err) { next(err); } +}); + +// GET /clients/:id/workouts +router.get('/:id/workouts', authenticateToken, CLIENT_MGMT, authenticateRole([...COACH_PLUS, 'Client']), async (req, res, next) => { + try { + const { page = 1, limit = 20, includeCompleted } = req.query; + const { rows, count } = await svc.getClientWorkouts(models, parseInt(req.params.id, 10), req.user.id, req.user.organizationId, req.user.role, { page: +page, limit: +limit, includeCompleted }); + collection(res, rows, count, +page, +limit); + } catch (err) { next(err); } +}); + +// POST /clients/:id/workouts +router.post('/:id/workouts', authenticateToken, CLIENT_MGMT, authenticateRole(COACH_PLUS), validate(createClientWorkout), async (req, res, next) => { + try { + const workout = await svc.createClientWorkout(models, req, req.user.organizationId, { clientId: parseInt(req.params.id, 10), ...req.body }); + created(res, workout); + } catch (err) { next(err); } +}); + +// PATCH /clients/:id/workouts/:workoutId +router.patch('/:id/workouts/:workoutId', authenticateToken, CLIENT_MGMT, authenticateRole(COACH_PLUS), validate(updateClientWorkout), async (req, res, next) => { + try { + const workout = await svc.updateClientWorkout(models, req, parseInt(req.params.workoutId, 10), req.user.organizationId, req.body); + ok(res, workout); + } catch (err) { next(err); } +}); + +// DELETE /clients/:id/workouts/:workoutId +router.delete('/:id/workouts/:workoutId', authenticateToken, CLIENT_MGMT, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + await svc.deleteClientWorkout(models, req, parseInt(req.params.workoutId, 10), req.user.organizationId); + noContent(res); + } catch (err) { next(err); } +}); + +// POST /clients/:id/workouts/:workoutId/complete +router.post('/:id/workouts/:workoutId/complete', authenticateToken, CLIENT_MGMT, authenticateRole([...COACH_PLUS, 'Client']), async (req, res, next) => { + try { + const workout = await svc.completeClientWorkout(models, req, parseInt(req.params.workoutId, 10), req.user.organizationId); + ok(res, { completedAt: workout.completedAt }); + } catch (err) { next(err); } +}); + +// GET /clients/:id/sessions +router.get('/:id/sessions', authenticateToken, CLIENT_MGMT, authenticateRole([...COACH_PLUS, 'Client']), async (req, res, next) => { + try { + const { rows, count } = await svc.getSessions(models, { clientId: req.params.id, ...req.query }, req.user.organizationId, req.user.id, req.user.role); + collection(res, rows, count, +(req.query.page || 1), +(req.query.limit || 20)); + } catch (err) { next(err); } +}); + +// POST /clients/:id/sessions +router.post('/:id/sessions', authenticateToken, CLIENT_MGMT, authenticateRole(COACH_PLUS), validate(createSession), async (req, res, next) => { + try { + const session = await svc.createSession(models, req, req.user.organizationId, { clientId: parseInt(req.params.id, 10), ...req.body }); + created(res, session); + } catch (err) { next(err); } +}); + +// PATCH /clients/:id/sessions/:sessionId +router.patch('/:id/sessions/:sessionId', authenticateToken, CLIENT_MGMT, authenticateRole([...COACH_PLUS, 'Client']), validate(updateSession), async (req, res, next) => { + try { + const session = await svc.updateSession(models, req, parseInt(req.params.sessionId, 10), req.user.organizationId, req.body); + ok(res, session); + } catch (err) { next(err); } +}); + +// POST /clients/:id/sessions/:sessionId/cancel +router.post('/:id/sessions/:sessionId/cancel', authenticateToken, CLIENT_MGMT, authenticateRole([...COACH_PLUS, 'Client']), async (req, res, next) => { + try { + const session = await svc.cancelSession(models, req, parseInt(req.params.sessionId, 10), req.user.organizationId, req.user.role); + ok(res, { status: session.status }); + } catch (err) { next(err); } +}); + +module.exports = router; diff --git a/V2/app/modules/clients/service.js b/V2/app/modules/clients/service.js new file mode 100644 index 0000000..cb41d93 --- /dev/null +++ b/V2/app/modules/clients/service.js @@ -0,0 +1,186 @@ +'use strict'; + +const { Op } = require('sequelize'); +const { AppError } = require('../../core/errors'); +const { log: auditLog } = require('../../core/audit'); + +const STREAM_BASE = '/api/v1/videos/stream/'; + +async function getClients(models, requesterId, orgId, requesterRole) { + if (requesterRole === 'Owner' || requesterRole === 'SystemAdmin') { + return models.User.findAll({ where: { organizationId: orgId, role: 'Client', isActive: true } }); + } + // Coach — only assigned clients + const links = await models.CoachClientLink.findAll({ where: { coachId: requesterId, organizationId: orgId, isActive: true } }); + const clientIds = links.map(l => l.clientId); + if (!clientIds.length) return []; + return models.User.findAll({ where: { id: clientIds, isActive: true } }); +} + +async function getClientById(models, clientId, requesterId, orgId, requesterRole) { + if (requesterRole === 'Coach') { + const link = await models.CoachClientLink.findOne({ where: { coachId: requesterId, clientId, organizationId: orgId, isActive: true } }); + if (!link) throw new AppError('NOT_FOUND', 'Client not found.', 404); + } + const user = await models.User.findOne({ where: { id: clientId, organizationId: orgId, role: 'Client' } }); + if (!user) throw new AppError('NOT_FOUND', 'Client not found.', 404); + return user; +} + +async function assignCoach(models, req, clientId, coachId, orgId) { + const [client, coach] = await Promise.all([ + models.User.findOne({ where: { id: clientId, organizationId: orgId, role: 'Client' } }), + models.User.findOne({ where: { id: coachId, organizationId: orgId, role: { [Op.in]: ['Coach', 'Owner'] } } }), + ]); + if (!client) throw new AppError('NOT_FOUND', 'Client not found.', 404); + if (!coach) throw new AppError('NOT_FOUND', 'Coach not found.', 404); + + await models.CoachClientLink.update({ isActive: false }, { where: { clientId, organizationId: orgId, isActive: true } }); + const link = await models.CoachClientLink.create({ organizationId: orgId, coachId, clientId, assignedByUserId: req.user.id }); + await auditLog(req, 'coach.client.assign', 'coach_client_link', link.id, { coachId, clientId }); + return link; +} + +async function unassignCoach(models, req, linkId, orgId) { + const link = await models.CoachClientLink.findOne({ where: { id: linkId, organizationId: orgId } }); + if (!link) throw new AppError('NOT_FOUND', 'Link not found.', 404); + await link.update({ isActive: false }); + await auditLog(req, 'coach.client.unassign', 'coach_client_link', linkId, {}); +} + +async function getClientWorkouts(models, clientId, requesterId, orgId, requesterRole, { page = 1, limit = 20, includeCompleted = false } = {}) { + if (requesterRole === 'Coach') { + const link = await models.CoachClientLink.findOne({ where: { coachId: requesterId, clientId, organizationId: orgId, isActive: true } }); + if (!link) throw new AppError('NOT_FOUND', 'Client not found.', 404); + } else if (requesterRole === 'Client' && requesterId !== clientId) { + throw new AppError('AUTH_FORBIDDEN', 'Forbidden.', 403); + } + + const where = { clientId, organizationId: orgId, deletedAt: null }; + if (!includeCompleted || includeCompleted === 'false') where.completedAt = null; + + const offset = (page - 1) * limit; + const { rows, count } = await models.ClientWorkout.findAndCountAll({ + where, limit, offset, order: [['scheduledDate', 'ASC']], + }); + + const isClient = requesterRole === 'Client'; + return { + rows: rows.map(w => { + const obj = w.toJSON(); + if (isClient) delete obj.notes; // strip coach notes + // Attach streamUrl to video items + obj.items = obj.items.map(item => { + if (item.type === 'video') return { ...item, streamUrl: STREAM_BASE + (item.filename || '') }; + return item; + }); + return obj; + }), + count, + }; +} + +async function createClientWorkout(models, req, orgId, { clientId, name, scheduledDate, notes, items }) { + const link = await models.CoachClientLink.findOne({ where: { coachId: req.user.id, clientId, organizationId: orgId, isActive: true } }); + if (!link) throw new AppError('NOT_FOUND', 'Client not found or not assigned to you.', 404); + + // Validate video items + for (const item of items.filter(i => i.type === 'video')) { + const video = await models.Video.findOne({ where: { id: item.videoId, organizationId: orgId } }); + if (!video) throw new AppError('VALIDATION_FAILED', `Video ${item.videoId} not found in your library.`, 400); + } + + const workout = await models.ClientWorkout.create({ organizationId: orgId, clientId, coachId: req.user.id, name, scheduledDate, notes, items }); + await auditLog(req, 'client_workout.create', 'client_workout', workout.id, { clientId, name }); + return workout; +} + +async function updateClientWorkout(models, req, id, orgId, data) { + const workout = await models.ClientWorkout.scope('active').findOne({ where: { id, organizationId: orgId, coachId: req.user.id } }); + if (!workout) throw new AppError('NOT_FOUND', 'Workout not found.', 404); + + const before = workout.toJSON(); + await workout.update(data); + await auditLog(req, 'client_workout.update', 'client_workout', id, { before, after: data }); + return workout; +} + +async function deleteClientWorkout(models, req, id, orgId) { + const workout = await models.ClientWorkout.scope('active').findOne({ where: { id, organizationId: orgId, coachId: req.user.id } }); + if (!workout) throw new AppError('NOT_FOUND', 'Workout not found.', 404); + await workout.update({ deletedAt: new Date() }); + await auditLog(req, 'client_workout.delete', 'client_workout', id, {}); +} + +async function completeClientWorkout(models, req, id, orgId) { + const where = { id, organizationId: orgId, deletedAt: null }; + if (req.user.role === 'Client') where.clientId = req.user.id; + if (req.user.role === 'Coach') where.coachId = req.user.id; + + const workout = await models.ClientWorkout.findOne({ where }); + if (!workout) throw new AppError('NOT_FOUND', 'Workout not found.', 404); + + await workout.update({ completedAt: new Date() }); + await auditLog(req, 'client_workout.complete', 'client_workout', id, {}); + return workout; +} + +async function getSessions(models, filters, orgId, requesterId, requesterRole) { + const { clientId, startAfter, endBefore, status, page = 1, limit = 20 } = filters; + const where = { organizationId: orgId }; + + if (requesterRole === 'Coach') where.coachId = requesterId; + else if (requesterRole === 'Client') where.clientId = requesterId; + if (clientId) where.clientId = clientId; + if (status) where.status = status; + if (startAfter) where.startAt = { [Op.gte]: new Date(startAfter) }; + if (endBefore) where.endAt = { ...where.endAt, [Op.lte]: new Date(endBefore) }; + + const offset = (page - 1) * limit; + const { rows, count } = await models.CalendarSession.findAndCountAll({ where, limit, offset, order: [['startAt', 'ASC']] }); + + return { + rows: rows.map(s => { + const obj = s.toJSON(); + if (requesterRole === 'Client') delete obj.coachNotes; + return obj; + }), + count, + }; +} + +async function createSession(models, req, orgId, data) { + if (new Date(data.endAt) <= new Date(data.startAt)) { + throw new AppError('VALIDATION_FAILED', 'endAt must be after startAt.', 400, 'endAt'); + } + const session = await models.CalendarSession.create({ ...data, organizationId: orgId, coachId: req.user.id }); + await auditLog(req, 'session.create', 'calendar_session', session.id, { title: data.title }); + return session; +} + +async function updateSession(models, req, id, orgId, data) { + const session = await models.CalendarSession.findOne({ where: { id, organizationId: orgId } }); + if (!session) throw new AppError('NOT_FOUND', 'Session not found.', 404); + const before = session.toJSON(); + await session.update(data); + await auditLog(req, 'session.update', 'calendar_session', id, { before, after: data }); + return session; +} + +async function cancelSession(models, req, id, orgId, actorRole) { + const session = await models.CalendarSession.findOne({ where: { id, organizationId: orgId } }); + if (!session) throw new AppError('NOT_FOUND', 'Session not found.', 404); + + if (actorRole === 'Client') { + const hoursUntil = (new Date(session.startAt) - Date.now()) / 3_600_000; + if (hoursUntil < 24) { + throw new AppError('CANCELLATION_TOO_LATE', 'Sessions must be cancelled at least 24 hours in advance.', 400); + } + } + + await session.update({ status: 'cancelled' }); + await auditLog(req, 'session.cancel', 'calendar_session', id, { cancelledBy: actorRole }); + return session; +} + +module.exports = { getClients, getClientById, assignCoach, unassignCoach, getClientWorkouts, createClientWorkout, updateClientWorkout, deleteClientWorkout, completeClientWorkout, getSessions, createSession, updateSession, cancelSession }; diff --git a/V2/app/modules/crossfit/migrations/008-crossfit-v2.js b/V2/app/modules/crossfit/migrations/008-crossfit-v2.js new file mode 100644 index 0000000..44b43ca --- /dev/null +++ b/V2/app/modules/crossfit/migrations/008-crossfit-v2.js @@ -0,0 +1,32 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const tableDesc = await queryInterface.describeTable('CrossfitWorkouts').catch(() => null); + + if (!tableDesc) { + await queryInterface.createTable('CrossfitWorkouts', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: Sequelize.INTEGER, allowNull: false }, + name: { type: Sequelize.STRING }, + workoutDate: { type: Sequelize.DATE }, + workoutItems: { type: Sequelize.TEXT, defaultValue: '[]' }, + createdByUserId: { type: Sequelize.INTEGER }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false }, + }); + return; + } + + const addIfMissing = async (col, def) => { + if (!tableDesc[col]) await queryInterface.addColumn('CrossfitWorkouts', col, def); + }; + + await addIfMissing('organizationId', { type: Sequelize.INTEGER }); + await addIfMissing('createdByUserId', { type: Sequelize.INTEGER }); + }, + + async down(queryInterface) { + await queryInterface.dropTable('CrossfitWorkouts').catch(() => {}); + }, +}; diff --git a/V2/app/modules/crossfit/model.js b/V2/app/modules/crossfit/model.js new file mode 100644 index 0000000..4dbd0f0 --- /dev/null +++ b/V2/app/modules/crossfit/model.js @@ -0,0 +1,19 @@ +'use strict'; + +module.exports = (sequelize, DataTypes) => { + const 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, + defaultValue: '[]', + get() { try { return JSON.parse(this.getDataValue('workoutItems') || '[]'); } catch { return []; } }, + set(v) { this.setDataValue('workoutItems', JSON.stringify(v)); }, + }, + createdByUserId: { type: DataTypes.INTEGER }, + }); + + return { CrossfitWorkout }; +}; diff --git a/V2/app/modules/crossfit/routes.js b/V2/app/modules/crossfit/routes.js new file mode 100644 index 0000000..4e22446 --- /dev/null +++ b/V2/app/modules/crossfit/routes.js @@ -0,0 +1,58 @@ +'use strict'; + +const express = require('express'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole } = require('../../core/auth'); +const { ok, created, collection, noContent } = require('../../core/respond'); +const { AppError } = require('../../core/errors'); +const { createCrossfitWorkout: createCrossfitSchema } = require('../../core/schemas/crossfit'); +const svc = require('./service'); + +const router = express.Router(); +router.prefix = 'crossfit-workouts'; + +const COACH_PLUS = ['Owner', 'Coach', 'SystemAdmin']; +const OWNERS = ['Owner', 'SystemAdmin']; + +function validate(schema) { + return (req, res, next) => { + const result = schema.safeParse(req.body); + if (!result.success) { + const e = result.error.errors[0]; + return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0])); + } + req.body = result.data; + next(); + }; +} + +router.get('/', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const { page = 1, limit = 20 } = req.query; + const { rows, count } = await svc.getCrossfitWorkouts(models, req.user.organizationId, { page: +page, limit: +limit }); + collection(res, rows, count, +page, +limit); + } catch (err) { next(err); } +}); + +router.post('/', authenticateToken, authenticateRole(COACH_PLUS), validate(createCrossfitSchema), async (req, res, next) => { + try { + const workout = await svc.createCrossfitWorkout(models, req, req.user.organizationId, req.body); + created(res, workout); + } catch (err) { next(err); } +}); + +router.get('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const workout = await svc.getCrossfitWorkoutById(models, parseInt(req.params.id, 10), req.user.organizationId); + ok(res, workout); + } catch (err) { next(err); } +}); + +router.delete('/:id', authenticateToken, authenticateRole(OWNERS), async (req, res, next) => { + try { + await svc.deleteCrossfitWorkout(models, req, parseInt(req.params.id, 10), req.user.organizationId); + noContent(res); + } catch (err) { next(err); } +}); + +module.exports = router; diff --git a/V2/app/modules/crossfit/service.js b/V2/app/modules/crossfit/service.js new file mode 100644 index 0000000..f462423 --- /dev/null +++ b/V2/app/modules/crossfit/service.js @@ -0,0 +1,37 @@ +'use strict'; + +const { AppError } = require('../../core/errors'); +const { log: auditLog } = require('../../core/audit'); + +async function getCrossfitWorkouts(models, orgId, { page = 1, limit = 20 } = {}) { + const offset = (page - 1) * limit; + const { rows, count } = await models.CrossfitWorkout.findAndCountAll({ + where: { organizationId: orgId }, + limit, offset, order: [['workoutDate', 'DESC'], ['createdAt', 'DESC']], + }); + return { rows, count }; +} + +async function getCrossfitWorkoutById(models, id, orgId) { + const w = await models.CrossfitWorkout.findOne({ where: { id, organizationId: orgId } }); + if (!w) throw new AppError('NOT_FOUND', 'CrossFit workout not found.', 404); + return w; +} + +async function createCrossfitWorkout(models, req, orgId, data) { + const workout = await models.CrossfitWorkout.create({ + ...data, + organizationId: orgId, + createdByUserId: req.user.id, + }); + await auditLog(req, 'crossfit.create', 'crossfit_workout', workout.id, { name: data.name }); + return workout; +} + +async function deleteCrossfitWorkout(models, req, id, orgId) { + const workout = await getCrossfitWorkoutById(models, id, orgId); + await auditLog(req, 'crossfit.delete', 'crossfit_workout', id, { name: workout.name }); + await workout.destroy(); +} + +module.exports = { getCrossfitWorkouts, getCrossfitWorkoutById, createCrossfitWorkout, deleteCrossfitWorkout }; diff --git a/V2/app/modules/org/migrations/002-organizations.js b/V2/app/modules/org/migrations/002-organizations.js new file mode 100644 index 0000000..8dd794f --- /dev/null +++ b/V2/app/modules/org/migrations/002-organizations.js @@ -0,0 +1,37 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable('Organizations', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + name: { type: Sequelize.STRING, allowNull: false }, + slug: { type: Sequelize.STRING, unique: true }, + timezone: { type: Sequelize.STRING, defaultValue: 'UTC' }, + features: { type: Sequelize.TEXT, defaultValue: '[]' }, + isActive: { type: Sequelize.BOOLEAN, defaultValue: true }, + licenseOwner: { type: Sequelize.STRING }, + licenseEmail: { type: Sequelize.STRING }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false }, + }); + + await queryInterface.createTable('Brandings', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: Sequelize.INTEGER, allowNull: false, unique: true }, + appName: { type: Sequelize.STRING, defaultValue: 'VitFit' }, + logoPath: { type: Sequelize.STRING }, + primaryColor: { type: Sequelize.STRING, defaultValue: '#00FF88' }, + secondaryColor: { type: Sequelize.STRING, defaultValue: '#4488FF' }, + workColor: { type: Sequelize.STRING, defaultValue: '#00FF88' }, + restColor: { type: Sequelize.STRING, defaultValue: '#4488FF' }, + moveColor: { type: Sequelize.STRING, defaultValue: '#FF4444' }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false }, + }); + }, + + async down(queryInterface) { + await queryInterface.dropTable('Brandings'); + await queryInterface.dropTable('Organizations'); + }, +}; diff --git a/V2/app/modules/org/model.js b/V2/app/modules/org/model.js new file mode 100644 index 0000000..afd174b --- /dev/null +++ b/V2/app/modules/org/model.js @@ -0,0 +1,43 @@ +'use strict'; + +module.exports = (sequelize, DataTypes) => { + const 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() { try { return JSON.parse(this.getDataValue('features') || '[]'); } catch { return []; } }, + set(v) { this.setDataValue('features', JSON.stringify(v)); }, + }, + isActive: { type: DataTypes.BOOLEAN, defaultValue: true }, + licenseOwner: { type: DataTypes.STRING }, + licenseEmail: { type: DataTypes.STRING }, + }); + + Organization.beforeCreate(org => { + if (!org.slug) { + org.slug = org.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); + } + }); + + const 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' }, + }); + + Organization.associate = (models) => { + Organization.hasOne(models.Branding, { foreignKey: 'organizationId' }); + }; + + return { Organization, Branding }; +}; diff --git a/V2/app/modules/org/routes.js b/V2/app/modules/org/routes.js new file mode 100644 index 0000000..d2390de --- /dev/null +++ b/V2/app/modules/org/routes.js @@ -0,0 +1,87 @@ +'use strict'; + +const express = require('express'); +const multer = require('multer'); +const path = require('path'); +const fs = require('fs'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole } = require('../../core/auth'); +const { ok, noContent } = require('../../core/respond'); +const { AppError } = require('../../core/errors'); +const { updateOrg: updateOrgSchema, updateBranding: updateBrandingSchema } = require('../../core/schemas/org'); +const svc = require('./service'); + +const router = express.Router(); +router.prefix = 'org'; + +const OWNERS = ['Owner', 'SystemAdmin']; + +const upload = multer({ + dest: process.env.UPLOAD_TEMP_DIR || '/tmp/vitfit-uploads', + limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB for logos +}); + +function validate(schema) { + return (req, res, next) => { + const result = schema.safeParse(req.body); + if (!result.success) { + const e = result.error.errors[0]; + return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0])); + } + req.body = result.data; + next(); + }; +} + +router.get('/', authenticateToken, async (req, res, next) => { + try { + const org = await svc.getOrg(models, req.user.organizationId); + ok(res, org); + } catch (err) { next(err); } +}); + +router.patch('/', authenticateToken, authenticateRole(OWNERS), validate(updateOrgSchema), async (req, res, next) => { + try { + const org = await svc.updateOrg(models, req, req.user.organizationId, req.body); + ok(res, org); + } catch (err) { next(err); } +}); + +router.get('/branding', authenticateToken, async (req, res, next) => { + try { + const branding = await svc.getBranding(models, req.user.organizationId); + ok(res, branding); + } catch (err) { next(err); } +}); + +router.patch('/branding', authenticateToken, authenticateRole(OWNERS), validate(updateBrandingSchema), async (req, res, next) => { + try { + const branding = await svc.updateBranding(models, req, req.user.organizationId, req.body); + ok(res, branding); + } catch (err) { next(err); } +}); + +router.post('/logo', authenticateToken, authenticateRole(OWNERS), upload.single('logo'), async (req, res, next) => { + try { + if (!req.file) return next(new AppError('VALIDATION_FAILED', 'No logo file provided.', 400)); + const branding = await svc.uploadLogo(models, req, req.user.organizationId, req.file); + ok(res, { logoPath: branding.logoPath }); + } catch (err) { next(err); } +}); + +router.get('/logo', authenticateToken, async (req, res, next) => { + try { + const branding = await svc.getBranding(models, req.user.organizationId); + if (!branding.logoPath) return next(new AppError('NOT_FOUND', 'No custom logo set.', 404)); + + // Find logo file in uploads dir + const uploadsDir = process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads'); + const files = fs.readdirSync(uploadsDir).filter(f => f.startsWith(`logo_${req.user.organizationId}_`)); + if (!files.length) return next(new AppError('NOT_FOUND', 'Logo file not found.', 404)); + + const logoFile = files.sort().pop(); // latest + res.sendFile(path.join(uploadsDir, logoFile)); + } catch (err) { next(err); } +}); + +module.exports = router; diff --git a/V2/app/modules/org/service.js b/V2/app/modules/org/service.js new file mode 100644 index 0000000..020d1bf --- /dev/null +++ b/V2/app/modules/org/service.js @@ -0,0 +1,115 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { AppError } = require('../../core/errors'); +const { log: auditLog } = require('../../core/audit'); + +const UPLOADS_DIR = () => process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads'); + +function contrastRatio(hex, bgHex = '#1a1a1a') { + const toLuminance = (h) => { + const r = parseInt(h.slice(1, 3), 16) / 255; + const g = parseInt(h.slice(3, 5), 16) / 255; + const b = parseInt(h.slice(5, 7), 16) / 255; + const chan = (c) => c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); + return 0.2126 * chan(r) + 0.7152 * chan(g) + 0.0722 * chan(b); + }; + const L1 = toLuminance(hex); + const L2 = toLuminance(bgHex); + const lighter = Math.max(L1, L2); + const darker = Math.min(L1, L2); + return (lighter + 0.05) / (darker + 0.05); +} + +async function getOrg(models, orgId) { + const org = await models.Organization.findByPk(orgId); + if (!org) throw new AppError('NOT_FOUND', 'Organization not found.', 404); + return org; +} + +async function updateOrg(models, req, orgId, data) { + if (data.timezone) { + const valid = Intl.supportedValuesOf('timeZone'); + if (!valid.includes(data.timezone)) { + throw new AppError('VALIDATION_FAILED', 'Invalid timezone.', 400, 'timezone'); + } + } + const org = await getOrg(models, orgId); + await org.update(data); + await auditLog(req, 'org.update', 'organization', orgId, data); + return org; +} + +async function getBranding(models, orgId) { + let branding = await models.Branding.findOne({ where: { organizationId: orgId } }); + if (!branding) { + branding = await models.Branding.create({ organizationId: orgId }); + } + return branding; +} + +async function updateBranding(models, req, orgId, data) { + const colorFields = ['primaryColor', 'secondaryColor', 'workColor', 'restColor', 'moveColor']; + const failures = []; + + for (const field of colorFields) { + if (data[field]) { + const ratio = contrastRatio(data[field]); + if (ratio < 4.5) { + failures.push({ field, color: data[field], ratio: ratio.toFixed(2) }); + } + } + } + + if (failures.length > 0) { + throw new AppError('VALIDATION_FAILED', `Colors fail minimum contrast ratio (4.5:1) against display background: ${failures.map(f => `${f.field} (${f.ratio}:1)`).join(', ')}`, 400); + } + + const branding = await getBranding(models, orgId); + await branding.update(data); + await auditLog(req, 'branding.update', 'branding', branding.id, data); + return branding; +} + +async function uploadLogo(models, req, orgId, file) { + const { fileTypeFromBuffer } = await import('file-type'); + const ALLOWED = ['image/png', 'image/jpeg', 'image/gif', 'image/webp']; + const EXT_MAP = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif', 'image/webp': '.webp' }; + + let detectedMime; + try { + const fd = fs.openSync(file.path, 'r'); + const buf = Buffer.alloc(12); + fs.readSync(fd, buf, 0, 12, 0); + fs.closeSync(fd); + const result = await fileTypeFromBuffer(buf); + detectedMime = result?.mime; + } finally { + await fs.promises.unlink(file.path).catch(() => {}); + } + + if (!detectedMime || !ALLOWED.includes(detectedMime)) { + throw new AppError('UPLOAD_TYPE_INVALID', 'Only PNG, JPG, GIF, and WebP images are supported.', 400); + } + + const ext = EXT_MAP[detectedMime]; + const safeName = `logo_${orgId}_${Date.now()}${ext}`; + const destPath = path.join(UPLOADS_DIR(), safeName); + + const branding = await getBranding(models, orgId); + + // Delete old logo + if (branding.logoPath) { + const oldFile = path.join(UPLOADS_DIR(), path.basename(branding.logoPath)); + await fs.promises.unlink(oldFile).catch(() => {}); + } + + await fs.promises.rename(file.path, destPath); + await branding.update({ logoPath: `/api/v1/org/logo` }); + await auditLog(req, 'logo.upload', 'branding', branding.id, { filename: safeName }); + + return branding; +} + +module.exports = { getOrg, updateOrg, getBranding, updateBranding, uploadLogo, contrastRatio }; diff --git a/V2/app/modules/sysadmin/routes.js b/V2/app/modules/sysadmin/routes.js new file mode 100644 index 0000000..b1cfee1 --- /dev/null +++ b/V2/app/modules/sysadmin/routes.js @@ -0,0 +1,84 @@ +'use strict'; + +const express = require('express'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole } = require('../../core/auth'); +const { ok, collection } = require('../../core/respond'); +const { AppError } = require('../../core/errors'); +const { getStorageInfo } = require('../../core/storage'); +const { getActiveSession } = require('../timers/service'); + +const router = express.Router(); +router.prefix = 'sysadmin'; + +const SA = ['SystemAdmin']; + +router.get('/orgs', authenticateToken, authenticateRole(SA), async (req, res, next) => { + try { + const orgs = await models.Organization.findAll({ + include: [{ model: models.Branding, required: false }], + order: [['createdAt', 'DESC']], + }); + + const result = await Promise.all(orgs.map(async org => { + const counts = await models.User.findAll({ + where: { organizationId: org.id }, + attributes: ['role', [models.User.sequelize.fn('COUNT', models.User.sequelize.col('id')), 'count']], + group: ['role'], + raw: true, + }); + return { ...org.toJSON(), userCounts: counts }; + })); + + ok(res, result); + } catch (err) { next(err); } +}); + +router.get('/orgs/:id', authenticateToken, authenticateRole(SA), async (req, res, next) => { + try { + const org = await models.Organization.findByPk(req.params.id, { + include: [{ model: models.Branding, required: false }], + }); + if (!org) return next(new AppError('NOT_FOUND', 'Organization not found.', 404)); + + const users = await models.User.findAll({ where: { organizationId: org.id } }); + ok(res, { ...org.toJSON(), users: users.map(u => u.toPublic()) }); + } catch (err) { next(err); } +}); + +router.patch('/orgs/:id', authenticateToken, authenticateRole(SA), async (req, res, next) => { + try { + const org = await models.Organization.findByPk(req.params.id); + if (!org) return next(new AppError('NOT_FOUND', 'Organization not found.', 404)); + await org.update(req.body); + ok(res, org); + } catch (err) { next(err); } +}); + +router.get('/health', authenticateToken, authenticateRole(SA), async (req, res, next) => { + try { + const storage = await getStorageInfo(); + const orgCount = await models.Organization.count(); + + // Count active timer sessions across all orgs + // (getActiveSession checks per-org; do a rough count via the activeSessions map) + let activeTimerSessions = 0; + const allOrgs = await models.Organization.findAll({ attributes: ['id'] }); + for (const org of allOrgs) { + if (getActiveSession(org.id)) activeTimerSessions++; + } + + ok(res, { + status: 'ok', + version: require('../../package.json').version, + nodeVersion: process.version, + uptime: Math.floor(process.uptime()), + db: { status: 'ok' }, + disk: { free: storage.disk.free, usedPercent: storage.disk.usedPercent }, + activeTimerSessions, + orgCount, + }); + } catch (err) { next(err); } +}); + +module.exports = router; diff --git a/V2/app/modules/timers/migrations/007-timers-v2.js b/V2/app/modules/timers/migrations/007-timers-v2.js new file mode 100644 index 0000000..43f0295 --- /dev/null +++ b/V2/app/modules/timers/migrations/007-timers-v2.js @@ -0,0 +1,38 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const tableDesc = await queryInterface.describeTable('Timers').catch(() => null); + + if (!tableDesc) { + await queryInterface.createTable('Timers', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: Sequelize.INTEGER, allowNull: false }, + name: { type: Sequelize.STRING, allowNull: false }, + totalTime: { type: Sequelize.INTEGER, allowNull: false }, + setTime: { type: Sequelize.INTEGER, allowNull: false }, + restTime: { type: Sequelize.INTEGER, defaultValue: 0 }, + moveTime: { type: Sequelize.INTEGER, defaultValue: 0 }, + setCount: { type: Sequelize.INTEGER, allowNull: false }, + exerciseCount: { type: Sequelize.INTEGER, allowNull: false }, + lapCount: { type: Sequelize.INTEGER, defaultValue: 1 }, + createdByUserId: { type: Sequelize.INTEGER }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false }, + }); + return; + } + + const addIfMissing = async (col, def) => { + if (!tableDesc[col]) await queryInterface.addColumn('Timers', col, def); + }; + + await addIfMissing('organizationId', { type: Sequelize.INTEGER }); + await addIfMissing('name', { type: Sequelize.STRING, allowNull: false, defaultValue: 'Timer' }); + await addIfMissing('createdByUserId', { type: Sequelize.INTEGER }); + }, + + async down(queryInterface) { + await queryInterface.dropTable('Timers').catch(() => {}); + }, +}; diff --git a/V2/app/modules/timers/model.js b/V2/app/modules/timers/model.js new file mode 100644 index 0000000..a7e7cc6 --- /dev/null +++ b/V2/app/modules/timers/model.js @@ -0,0 +1,19 @@ +'use strict'; + +module.exports = (sequelize, DataTypes) => { + const 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 }, + }); + + return { Timer }; +}; diff --git a/V2/app/modules/timers/routes.js b/V2/app/modules/timers/routes.js new file mode 100644 index 0000000..164776e --- /dev/null +++ b/V2/app/modules/timers/routes.js @@ -0,0 +1,75 @@ +'use strict'; + +const express = require('express'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole } = require('../../core/auth'); +const { ok, created, collection, noContent } = require('../../core/respond'); +const { AppError } = require('../../core/errors'); +const { createTimer: createTimerSchema } = require('../../core/schemas/timers'); +const svc = require('./service'); + +const router = express.Router(); +router.prefix = 'timers'; + +const COACH_PLUS = ['Owner', 'Coach', 'SystemAdmin']; + +function validate(schema) { + return (req, res, next) => { + const result = schema.safeParse(req.body); + if (!result.success) { + const e = result.error.errors[0]; + return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0])); + } + req.body = result.data; + next(); + }; +} + +router.get('/', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const timers = await svc.getTimers(models, req.user.organizationId); + ok(res, timers); + } catch (err) { next(err); } +}); + +router.post('/', authenticateToken, authenticateRole(COACH_PLUS), validate(createTimerSchema), async (req, res, next) => { + try { + const timer = await svc.createTimer(models, req, req.user.organizationId, req.body); + created(res, timer); + } catch (err) { next(err); } +}); + +router.get('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const timer = await svc.getTimerById(models, parseInt(req.params.id, 10), req.user.organizationId); + ok(res, timer); + } catch (err) { next(err); } +}); + +router.delete('/session', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const { sessionId } = req.body; + if (!sessionId) return next(new AppError('VALIDATION_FAILED', 'sessionId required.', 400)); + await svc.stopTimer(req, sessionId, req.user.organizationId); + noContent(res); + } catch (err) { next(err); } +}); + +router.delete('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + await svc.deleteTimer(models, req, parseInt(req.params.id, 10), req.user.organizationId); + noContent(res); + } catch (err) { next(err); } +}); + +router.post('/:id/launch', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const result = await svc.launchTimer(models, req, parseInt(req.params.id, 10), req.user.organizationId); + ok(res, result); + } catch (err) { next(err); } +}); + +// Socket.io timer:join handler — registered when client connects +// see core/socket.js for connection handler; timer join logic is in the page JS + +module.exports = router; diff --git a/V2/app/modules/timers/service.js b/V2/app/modules/timers/service.js new file mode 100644 index 0000000..95fe52f --- /dev/null +++ b/V2/app/modules/timers/service.js @@ -0,0 +1,83 @@ +'use strict'; + +const { AppError } = require('../../core/errors'); +const { log: auditLog } = require('../../core/audit'); +const { getIo } = require('../../core/socket'); +const TimerEngine = require('./timer-engine'); + +// Active sessions: sessionId → { engine, orgId } +const activeSessions = new Map(); + +async function getTimers(models, orgId) { + return models.Timer.findAll({ where: { organizationId: orgId }, order: [['createdAt', 'DESC']] }); +} + +async function getTimerById(models, id, orgId) { + const timer = await models.Timer.findOne({ where: { id, organizationId: orgId } }); + if (!timer) throw new AppError('NOT_FOUND', 'Timer not found.', 404); + return timer; +} + +async function createTimer(models, req, orgId, data) { + const timer = await models.Timer.create({ ...data, organizationId: orgId, createdByUserId: req.user.id }); + await auditLog(req, 'timer.create', 'timer', timer.id, { name: data.name }); + return timer; +} + +async function deleteTimer(models, req, id, orgId) { + const timer = await getTimerById(models, id, orgId); + + if (req.user.role === 'Coach' && timer.createdByUserId !== req.user.id) { + throw new AppError('AUTH_FORBIDDEN', 'You can only delete your own timers.', 403); + } + + // Stop active session if one exists for this timer + for (const [sessionId, session] of activeSessions) { + if (session.orgId === orgId && sessionId.startsWith(`timer_${id}_`)) { + session.engine.stop(); + activeSessions.delete(sessionId); + } + } + + await auditLog(req, 'timer.delete', 'timer', id, { name: timer.name }); + await timer.destroy(); +} + +async function launchTimer(models, req, timerId, orgId) { + const timer = await getTimerById(models, timerId, orgId); + const io = getIo(); + + const sessionId = `timer_${timerId}_${Date.now()}`; + const engine = new TimerEngine(timer.toJSON(), io, sessionId); + + activeSessions.set(sessionId, { engine, orgId }); + engine.start(); + + await auditLog(req, 'timer.launch', 'timer', timerId, { sessionId }); + return { sessionId }; +} + +async function stopTimer(req, sessionId, orgId) { + const session = activeSessions.get(sessionId); + if (!session || session.orgId !== orgId) { + throw new AppError('NOT_FOUND', 'Active timer session not found.', 404); + } + session.engine.stop(); + activeSessions.delete(sessionId); + await auditLog(req, 'timer.stop', null, null, { sessionId }); +} + +function getActiveSession(orgId) { + for (const [sessionId, session] of activeSessions) { + if (session.orgId === orgId) { + return { sessionId, state: session.engine.getState() }; + } + } + return null; +} + +function getSessionEngine(sessionId) { + return activeSessions.get(sessionId)?.engine ?? null; +} + +module.exports = { getTimers, getTimerById, createTimer, deleteTimer, launchTimer, stopTimer, getActiveSession, getSessionEngine }; diff --git a/V2/app/modules/timers/timer-engine.js b/V2/app/modules/timers/timer-engine.js new file mode 100644 index 0000000..7e77c70 --- /dev/null +++ b/V2/app/modules/timers/timer-engine.js @@ -0,0 +1,169 @@ +'use strict'; + +const NS_PER_MS = BigInt(1_000_000); + +class TimerEngine { + constructor(config, io, roomId) { + this.config = config; + this.io = io; + this.roomId = roomId; + + this.status = 'idle'; + this.phase = 'set'; + this.currentLap = 1; + this.currentExercise = 1; + this.currentSet = 1; + this.phaseEndTime = BigInt(0); + this.sessionEndTime = BigInt(0); + this.elapsedSeconds = 0; + + this._interval = null; + this._lastEmittedSecond = -1; + } + + start() { + this.status = 'running'; + const now = process.hrtime.bigint(); + this.phaseEndTime = now + BigInt(this.config.setTime) * NS_PER_MS * BigInt(1000); + this.sessionEndTime = now + BigInt(this.config.totalTime) * NS_PER_MS * BigInt(1000); + + this.io.to(this.roomId).emit('timer:state', this._snapshot()); + this._interval = setInterval(() => this._tick(), 100); + } + + stop() { + this._clearInterval(); + this.status = 'stopped'; + this.io.to(this.roomId).emit('timer:stopped', { sessionId: this.roomId }); + } + + getState() { + return this._snapshot(); + } + + _snapshot() { + const now = process.hrtime.bigint(); + const phaseRemainingMs = Number((this.phaseEndTime - now) / NS_PER_MS); + const totalRemainingMs = Number((this.sessionEndTime - now) / NS_PER_MS); + return { + status: this.status, + phase: this.phase, + currentLap: this.currentLap, + currentExercise:this.currentExercise, + currentSet: this.currentSet, + lapCount: this.config.lapCount, + exerciseCount: this.config.exerciseCount, + setCount: this.config.setCount, + phaseRemainingMs: Math.max(0, phaseRemainingMs), + totalRemainingMs: Math.max(0, totalRemainingMs), + phaseEndTime: Number(this.phaseEndTime / NS_PER_MS), // ms epoch + }; + } + + _tick() { + if (this.status !== 'running') return; + + const now = process.hrtime.bigint(); + const phaseRemainingMs = Number((this.phaseEndTime - now) / NS_PER_MS); + const totalRemainingMs = Number((this.sessionEndTime - now) / NS_PER_MS); + + const currentSecond = Math.ceil(phaseRemainingMs / 1000); + if (currentSecond !== this._lastEmittedSecond) { + this._lastEmittedSecond = currentSecond; + this.io.to(this.roomId).emit('timer:tick', { + phaseRemainingMs: Math.max(0, phaseRemainingMs), + totalRemainingMs: Math.max(0, totalRemainingMs), + phase: this.phase, + currentLap: this.currentLap, + currentExercise: this.currentExercise, + currentSet: this.currentSet, + }); + } + + if (phaseRemainingMs <= 0) { + this._advancePhase(); + } + } + + _advancePhase() { + const { setTime, restTime, moveTime, setCount, exerciseCount, lapCount } = this.config; + const now = process.hrtime.bigint(); + + // State machine + if (this.phase === 'set') { + if (restTime > 0) { + this.phase = 'rest'; + this.phaseEndTime = now + BigInt(restTime) * NS_PER_MS * BigInt(1000); + this.io.to(this.roomId).emit('timer:phase-change', this._snapshot()); + return; + } + // fall through to move/next-set logic + } + + if (this.phase === 'rest' || (this.phase === 'set' && restTime === 0)) { + // Check if this was the last set + const isLastSet = this.currentSet >= setCount; + const isLastExercise = this.currentExercise >= exerciseCount; + const isLastLap = this.currentLap >= lapCount; + + if (isLastSet && isLastExercise && isLastLap) { + this._complete(); + return; + } + + if (moveTime > 0 && !isLastSet) { + this.phase = 'move'; + this.phaseEndTime = now + BigInt(moveTime) * NS_PER_MS * BigInt(1000); + this.io.to(this.roomId).emit('timer:phase-change', this._snapshot()); + return; + } + + // Advance counters + this._advance(); + return; + } + + if (this.phase === 'move') { + this._advance(); + } + } + + _advance() { + const { setCount, exerciseCount, lapCount, setTime } = this.config; + const now = process.hrtime.bigint(); + + if (this.currentSet < setCount) { + this.currentSet++; + } else if (this.currentExercise < exerciseCount) { + this.currentSet = 1; + this.currentExercise++; + } else if (this.currentLap < lapCount) { + this.currentSet = 1; + this.currentExercise = 1; + this.currentLap++; + } else { + this._complete(); + return; + } + + this.phase = 'set'; + this.phaseEndTime = now + BigInt(setTime) * NS_PER_MS * BigInt(1000); + this._lastEmittedSecond = -1; + this.io.to(this.roomId).emit('timer:phase-change', this._snapshot()); + } + + _complete() { + this._clearInterval(); + this.status = 'complete'; + this.io.to(this.roomId).emit('timer:complete', { sessionId: this.roomId }); + } + + _clearInterval() { + if (this._interval) { + clearInterval(this._interval); + this._interval = null; + } + } +} + +module.exports = TimerEngine; diff --git a/V2/app/modules/users/migrations/003-users-v2.js b/V2/app/modules/users/migrations/003-users-v2.js new file mode 100644 index 0000000..d5c9c94 --- /dev/null +++ b/V2/app/modules/users/migrations/003-users-v2.js @@ -0,0 +1,47 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + // Create Users table if it doesn't exist (new installs) + const tableDesc = await queryInterface.describeTable('Users').catch(() => null); + + if (!tableDesc) { + await queryInterface.createTable('Users', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: Sequelize.INTEGER }, + username: { type: Sequelize.STRING, allowNull: false, unique: true }, + email: { type: Sequelize.STRING, unique: true }, + password: { type: Sequelize.STRING, allowNull: false }, + role: { type: Sequelize.ENUM('SystemAdmin', 'Owner', 'Coach', 'Client'), allowNull: false, defaultValue: 'Coach' }, + firstName: { type: Sequelize.STRING }, + lastName: { type: Sequelize.STRING }, + isActive: { type: Sequelize.BOOLEAN, defaultValue: true }, + lastLoginAt: { type: Sequelize.DATE }, + passwordChangedAt: { type: Sequelize.DATE }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false }, + }); + return; + } + + // V1 upgrade path: add missing columns + const addIfMissing = async (col, def) => { + if (!tableDesc[col]) { + await queryInterface.addColumn('Users', col, def); + } + }; + + await addIfMissing('organizationId', { type: Sequelize.INTEGER }); + await addIfMissing('email', { type: Sequelize.STRING }); + await addIfMissing('firstName', { type: Sequelize.STRING }); + await addIfMissing('lastName', { type: Sequelize.STRING }); + await addIfMissing('isActive', { type: Sequelize.BOOLEAN, defaultValue: true }); + await addIfMissing('lastLoginAt', { type: Sequelize.DATE }); + await addIfMissing('passwordChangedAt', { type: Sequelize.DATE }); + }, + + async down(queryInterface) { + // No-op for V1 upgrade path; would need to be more specific for rollback + await queryInterface.dropTable('Users').catch(() => {}); + }, +}; diff --git a/V2/app/modules/users/migrations/014-users-password-changed-at.js b/V2/app/modules/users/migrations/014-users-password-changed-at.js new file mode 100644 index 0000000..4d961bc --- /dev/null +++ b/V2/app/modules/users/migrations/014-users-password-changed-at.js @@ -0,0 +1,20 @@ +'use strict'; + +// passwordChangedAt was added in 003 for new installs; this migration ensures +// it exists on V1 upgrades where 003 ran the addIfMissing path but may have +// been using an older column list. +module.exports = { + async up(queryInterface, Sequelize) { + const tableDesc = await queryInterface.describeTable('Users').catch(() => null); + if (tableDesc && !tableDesc['passwordChangedAt']) { + await queryInterface.addColumn('Users', 'passwordChangedAt', { + type: Sequelize.DATE, + allowNull: true, + }); + } + }, + + async down(queryInterface) { + await queryInterface.removeColumn('Users', 'passwordChangedAt').catch(() => {}); + }, +}; diff --git a/V2/app/modules/users/model.js b/V2/app/modules/users/model.js new file mode 100644 index 0000000..b1b8d10 --- /dev/null +++ b/V2/app/modules/users/model.js @@ -0,0 +1,32 @@ +'use strict'; + +module.exports = (sequelize, DataTypes) => { + const User = sequelize.define('User', { + id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: DataTypes.INTEGER }, + 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 }, + }, { + defaultScope: { + attributes: { exclude: ['password', 'passwordChangedAt'] }, + }, + }); + + User.prototype.toPublic = function () { + const { password, passwordChangedAt, ...rest } = this.toJSON(); + return rest; + }; + + User.associate = (models) => { + User.hasMany(models.DeviceToken, { foreignKey: 'userId' }); + }; + + return { User }; +}; diff --git a/V2/app/modules/users/my-routes.js b/V2/app/modules/users/my-routes.js new file mode 100644 index 0000000..47be2fe --- /dev/null +++ b/V2/app/modules/users/my-routes.js @@ -0,0 +1,41 @@ +'use strict'; + +const express = require('express'); +const { models } = require('../../core/db'); +const { authenticateToken } = require('../../core/auth'); +const { ok, noContent } = require('../../core/respond'); +const { AppError } = require('../../core/errors'); +const { changeOwnPassword: changeOwnPasswordSchema } = require('../../core/schemas/auth'); +const svc = require('./service'); + +const router = express.Router(); +router.prefix = 'my'; + +function validate(schema) { + return (req, res, next) => { + const result = schema.safeParse(req.body); + if (!result.success) { + const e = result.error.errors[0]; + return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0])); + } + req.body = result.data; + next(); + }; +} + +router.get('/profile', authenticateToken, async (req, res, next) => { + try { + const user = await models.User.findByPk(req.user.id); + if (!user) return next(new AppError('NOT_FOUND', 'User not found.', 404)); + ok(res, user.toPublic()); + } catch (err) { next(err); } +}); + +router.put('/password', authenticateToken, validate(changeOwnPasswordSchema), async (req, res, next) => { + try { + await svc.changeOwnPassword(models, req, req.user.id, req.body.currentPassword, req.body.newPassword); + noContent(res); + } catch (err) { next(err); } +}); + +module.exports = router; diff --git a/V2/app/modules/users/routes.js b/V2/app/modules/users/routes.js new file mode 100644 index 0000000..2912d31 --- /dev/null +++ b/V2/app/modules/users/routes.js @@ -0,0 +1,122 @@ +'use strict'; + +const express = require('express'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole } = require('../../core/auth'); +const { ok, created, collection, noContent } = require('../../core/respond'); +const { AppError } = require('../../core/errors'); +const { createUser: createUserSchema, updateProfile, resetPassword: resetPasswordSchema, changeRole: changeRoleSchema } = require('../../core/schemas/users'); +const { changeOwnPassword: changeOwnPasswordSchema } = require('../../core/schemas/auth'); +const svc = require('./service'); + +const router = express.Router(); +router.prefix = 'users'; + +const OWNERS = ['Owner', 'SystemAdmin']; + +function validate(schema) { + return (req, res, next) => { + const result = schema.safeParse(req.body); + if (!result.success) { + const e = result.error.errors[0]; + return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0])); + } + req.body = result.data; + next(); + }; +} + +// GET /users +router.get('/', authenticateToken, authenticateRole(OWNERS), async (req, res, next) => { + try { + const { role, isActive, page = 1, limit = 50 } = req.query; + const { rows, count } = await svc.getUsers(models, req.user.organizationId, { role, isActive, page: +page, limit: +limit }); + collection(res, rows.map(u => u.toPublic()), count, +page, +limit); + } catch (err) { next(err); } +}); + +// POST /users +router.post('/', authenticateToken, authenticateRole(OWNERS), validate(createUserSchema), async (req, res, next) => { + try { + const user = await svc.createUser(models, req, req.user.organizationId, req.body); + created(res, user); + } catch (err) { next(err); } +}); + +// GET /users/:id +router.get('/:id', authenticateToken, async (req, res, next) => { + try { + const targetId = parseInt(req.params.id, 10); + // Own profile: any role. Other profiles: Owner+ + if (req.user.id !== targetId && !OWNERS.includes(req.user.role)) { + return next(new AppError('AUTH_FORBIDDEN', 'Forbidden.', 403)); + } + const user = await svc.getUserById(models, targetId, req.user.organizationId); + const tokens = await svc.getDeviceTokens(models, targetId, req.user.organizationId); + ok(res, { ...user.toPublic(), deviceTokens: tokens }); + } catch (err) { next(err); } +}); + +// PATCH /users/:id +router.patch('/:id', authenticateToken, validate(updateProfile), async (req, res, next) => { + try { + const targetId = parseInt(req.params.id, 10); + if (req.user.id !== targetId && !OWNERS.includes(req.user.role)) { + return next(new AppError('AUTH_FORBIDDEN', 'Forbidden.', 403)); + } + const user = await svc.updateProfile(models, req, targetId, req.body); + ok(res, user); + } catch (err) { next(err); } +}); + +// DELETE /users/:id (soft deactivate) +router.delete('/:id', authenticateToken, authenticateRole(OWNERS), async (req, res, next) => { + try { + await svc.deactivateUser(models, req, parseInt(req.params.id, 10), req.user.organizationId); + noContent(res); + } catch (err) { next(err); } +}); + +// PUT /users/:id/role +router.put('/:id/role', authenticateToken, authenticateRole(OWNERS), validate(changeRoleSchema), async (req, res, next) => { + try { + const user = await svc.changeRole(models, req, parseInt(req.params.id, 10), req.body.role, req.user.organizationId, req.user.id); + ok(res, user); + } catch (err) { next(err); } +}); + +// PUT /users/:id/password (admin reset — no current password required) +router.put('/:id/password', authenticateToken, authenticateRole(OWNERS), validate(resetPasswordSchema), async (req, res, next) => { + try { + await svc.resetPassword(models, req, parseInt(req.params.id, 10), req.body.newPassword, req.user.organizationId); + noContent(res); + } catch (err) { next(err); } +}); + +// GET /users/:id/devices +router.get('/:id/devices', authenticateToken, async (req, res, next) => { + try { + const targetId = parseInt(req.params.id, 10); + if (req.user.id !== targetId && !OWNERS.includes(req.user.role)) { + return next(new AppError('AUTH_FORBIDDEN', 'Forbidden.', 403)); + } + const tokens = await svc.getDeviceTokens(models, targetId, req.user.organizationId); + ok(res, tokens); + } catch (err) { next(err); } +}); + +// DELETE /users/:id/devices/:tokenId +router.delete('/:id/devices/:tokenId', authenticateToken, async (req, res, next) => { + try { + const targetId = parseInt(req.params.id, 10); + if (req.user.id !== targetId && !OWNERS.includes(req.user.role)) { + return next(new AppError('AUTH_FORBIDDEN', 'Forbidden.', 403)); + } + await svc.revokeDeviceToken(models, req, parseInt(req.params.tokenId, 10), targetId, req.user.organizationId); + noContent(res); + } catch (err) { next(err); } +}); + +// PUT /my/password (own password change with current password verification) +// Note: registered here but mounted under /users; the /my prefix is handled by a separate router +module.exports = router; diff --git a/V2/app/modules/users/service.js b/V2/app/modules/users/service.js new file mode 100644 index 0000000..9cc04e7 --- /dev/null +++ b/V2/app/modules/users/service.js @@ -0,0 +1,131 @@ +'use strict'; + +const bcrypt = require('bcryptjs'); +const { Op } = require('sequelize'); +const { AppError } = require('../../core/errors'); +const { log: auditLog } = require('../../core/audit'); + +const BCRYPT_ROUNDS = 12; + +async function getUsers(models, orgId, { role, isActive, page = 1, limit = 50 } = {}) { + const where = { organizationId: orgId }; + if (role) where.role = role; + if (isActive != null) where.isActive = isActive === 'true' || isActive === true; + + const offset = (page - 1) * limit; + const { rows, count } = await models.User.findAndCountAll({ where, limit, offset, order: [['createdAt', 'ASC']] }); + return { rows, count }; +} + +async function getUserById(models, id, orgId) { + const user = await models.User.findOne({ where: { id, organizationId: orgId } }); + if (!user) throw new AppError('NOT_FOUND', 'User not found.', 404); + return user; +} + +async function createUser(models, req, orgId, { username, email, firstName, lastName, password, role }) { + if (role === 'SystemAdmin') { + throw new AppError('AUTH_FORBIDDEN', 'Cannot create SystemAdmin accounts via this endpoint.', 403); + } + + const hash = await bcrypt.hash(password, BCRYPT_ROUNDS); + + let user; + try { + user = await models.User.create({ organizationId: orgId, username, email, firstName, lastName, password: hash, role }); + } catch (err) { + if (err.name === 'SequelizeUniqueConstraintError') { + throw new AppError('CONFLICT', 'Username already exists.', 409, 'username'); + } + throw err; + } + + await auditLog(req, 'user.create', 'user', user.id, { username, role }); + return user.toPublic(); +} + +async function deactivateUser(models, req, targetId, orgId) { + const user = await getUserById(models, targetId, orgId); + + if (user.role === 'Owner') { + const ownerCount = await models.User.count({ where: { organizationId: orgId, role: 'Owner', isActive: true } }); + if (ownerCount <= 1) throw new AppError('LAST_OWNER_PROTECTED', 'Cannot deactivate the last Owner.', 400); + } + + await user.update({ isActive: false }); + await models.DeviceToken.update({ isRevoked: true }, { where: { userId: targetId } }); + await auditLog(req, 'user.deactivate', 'user', targetId, {}); +} + +async function changeRole(models, req, targetId, newRole, orgId, actorId) { + const user = await getUserById(models, targetId, orgId); + + if (actorId === targetId) { + throw new AppError('AUTH_FORBIDDEN', 'You cannot change your own role.', 403); + } + + if (user.role === 'Owner' && newRole !== 'Owner') { + const ownerCount = await models.User.count({ where: { organizationId: orgId, role: 'Owner', isActive: true } }); + if (ownerCount <= 1) throw new AppError('LAST_OWNER_PROTECTED', 'Cannot change the role of the last Owner.', 400); + } + + await user.update({ role: newRole }); + await auditLog(req, 'user.role.change', 'user', targetId, { from: user.role, to: newRole }); + return user.toPublic(); +} + +async function resetPassword(models, req, targetId, newPassword, orgId) { + await getUserById(models, targetId, orgId); // 404 guard + + const hash = await bcrypt.hash(newPassword, BCRYPT_ROUNDS); + await models.User.update( + { password: hash, passwordChangedAt: new Date() }, + { where: { id: targetId } } + ); + await models.DeviceToken.update({ isRevoked: true }, { where: { userId: targetId } }); + await auditLog(req, 'user.password.reset', 'user', targetId, {}); +} + +async function updateProfile(models, req, userId, data) { + const user = await models.User.findByPk(userId); + if (!user) throw new AppError('NOT_FOUND', 'User not found.', 404); + + const before = { firstName: user.firstName, lastName: user.lastName, email: user.email }; + await user.update(data); + await auditLog(req, 'user.profile.update', 'user', userId, { before, after: data }); + return user.toPublic(); +} + +async function changeOwnPassword(models, req, userId, currentPassword, newPassword) { + const user = await models.User.unscoped().findByPk(userId, { + attributes: ['id', 'password', 'organizationId'], + }); + + const valid = await bcrypt.compare(currentPassword, user.password); + if (!valid) throw new AppError('AUTH_FORBIDDEN', 'Current password is incorrect.', 401); + + const hash = await bcrypt.hash(newPassword, BCRYPT_ROUNDS); + await models.User.update( + { password: hash, passwordChangedAt: new Date() }, + { where: { id: userId } } + ); + await models.DeviceToken.update({ isRevoked: true }, { where: { userId } }); + await auditLog(req, 'user.password.change', 'user', userId, {}); +} + +async function getDeviceTokens(models, userId, orgId) { + return models.DeviceToken.findAll({ + where: { userId, organizationId: orgId, isRevoked: false }, + attributes: ['id', 'deviceName', 'deviceType', 'lastUsedAt', 'expiresAt'], + order: [['createdAt', 'DESC']], + }); +} + +async function revokeDeviceToken(models, req, tokenId, userId, orgId) { + const token = await models.DeviceToken.findOne({ where: { id: tokenId, userId, organizationId: orgId } }); + if (!token) throw new AppError('NOT_FOUND', 'Device token not found.', 404); + await token.update({ isRevoked: true }); + await auditLog(req, 'auth.device.revoked', 'device_token', tokenId, {}); +} + +module.exports = { getUsers, getUserById, createUser, deactivateUser, changeRole, resetPassword, updateProfile, changeOwnPassword, getDeviceTokens, revokeDeviceToken }; diff --git a/V2/app/modules/videos/categories-routes.js b/V2/app/modules/videos/categories-routes.js new file mode 100644 index 0000000..9374443 --- /dev/null +++ b/V2/app/modules/videos/categories-routes.js @@ -0,0 +1,49 @@ +'use strict'; + +const express = require('express'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole } = require('../../core/auth'); +const { ok, created, noContent } = require('../../core/respond'); +const { AppError } = require('../../core/errors'); +const { createCategory: createCategorySchema } = require('../../core/schemas/videos'); +const svc = require('./service'); + +const router = express.Router(); +router.prefix = 'categories'; + +const COACH_PLUS = ['Owner', 'Coach', 'SystemAdmin']; + +function validate(schema) { + return (req, res, next) => { + const result = schema.safeParse(req.body); + if (!result.success) { + const e = result.error.errors[0]; + return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0])); + } + req.body = result.data; + next(); + }; +} + +router.get('/', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const cats = await svc.getCategories(models, req.user.organizationId); + ok(res, cats); + } catch (err) { next(err); } +}); + +router.post('/', authenticateToken, authenticateRole(COACH_PLUS), validate(createCategorySchema), async (req, res, next) => { + try { + const cat = await svc.createCategory(models, req, req.user.organizationId, req.body.name); + created(res, cat); + } catch (err) { next(err); } +}); + +router.delete('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + await svc.deleteCategory(models, req, parseInt(req.params.id, 10), req.user.organizationId); + noContent(res); + } catch (err) { next(err); } +}); + +module.exports = router; diff --git a/V2/app/modules/videos/migrations/004-videos-v2.js b/V2/app/modules/videos/migrations/004-videos-v2.js new file mode 100644 index 0000000..1f53703 --- /dev/null +++ b/V2/app/modules/videos/migrations/004-videos-v2.js @@ -0,0 +1,34 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const tableDesc = await queryInterface.describeTable('Videos').catch(() => null); + + if (!tableDesc) { + await queryInterface.createTable('Videos', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: Sequelize.INTEGER, allowNull: false }, + filename: { type: Sequelize.STRING, allowNull: false }, + description: { type: Sequelize.STRING }, + category: { type: Sequelize.STRING }, + mimeType: { type: Sequelize.STRING }, + fileSizeBytes: { type: Sequelize.INTEGER }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false }, + }); + return; + } + + const addIfMissing = async (col, def) => { + if (!tableDesc[col]) await queryInterface.addColumn('Videos', col, def); + }; + + await addIfMissing('organizationId', { type: Sequelize.INTEGER }); + await addIfMissing('mimeType', { type: Sequelize.STRING }); + await addIfMissing('fileSizeBytes', { type: Sequelize.INTEGER }); + }, + + async down(queryInterface) { + await queryInterface.dropTable('Videos').catch(() => {}); + }, +}; diff --git a/V2/app/modules/videos/migrations/005-categories-v2.js b/V2/app/modules/videos/migrations/005-categories-v2.js new file mode 100644 index 0000000..0ff2376 --- /dev/null +++ b/V2/app/modules/videos/migrations/005-categories-v2.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const tableDesc = await queryInterface.describeTable('Categories').catch(() => null); + + if (!tableDesc) { + await queryInterface.createTable('Categories', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: Sequelize.INTEGER, allowNull: false }, + name: { type: Sequelize.STRING, allowNull: false }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false }, + }); + + await queryInterface.addIndex('Categories', ['organizationId', 'name'], { unique: true }); + return; + } + + if (!tableDesc['organizationId']) { + await queryInterface.addColumn('Categories', 'organizationId', { type: Sequelize.INTEGER }); + } + }, + + async down(queryInterface) { + await queryInterface.dropTable('Categories').catch(() => {}); + }, +}; diff --git a/V2/app/modules/videos/model.js b/V2/app/modules/videos/model.js new file mode 100644 index 0000000..21019f8 --- /dev/null +++ b/V2/app/modules/videos/model.js @@ -0,0 +1,21 @@ +'use strict'; + +module.exports = (sequelize, DataTypes) => { + const 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 }, + }); + + const Category = sequelize.define('Category', { + id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: DataTypes.INTEGER, allowNull: false }, + name: { type: DataTypes.STRING, allowNull: false }, + }); + + return { Video, Category }; +}; diff --git a/V2/app/modules/videos/routes.js b/V2/app/modules/videos/routes.js new file mode 100644 index 0000000..384ba92 --- /dev/null +++ b/V2/app/modules/videos/routes.js @@ -0,0 +1,71 @@ +'use strict'; + +const express = require('express'); +const multer = require('multer'); +const path = require('path'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole } = require('../../core/auth'); +const { ok, created, collection, noContent } = require('../../core/respond'); +const { AppError } = require('../../core/errors'); +const { checkUploadAllowed } = require('../../core/storage'); +const { uploadVideo: uploadVideoSchema, createCategory: createCategorySchema } = require('../../core/schemas/videos'); +const svc = require('./service'); + +const router = express.Router(); +router.prefix = 'videos'; + +const COACH_PLUS = ['Owner', 'Coach', 'SystemAdmin']; + +const upload = multer({ + dest: process.env.UPLOAD_TEMP_DIR || '/tmp/vitfit-uploads', + limits: { fileSize: parseInt(process.env.UPLOAD_MAX_BYTES || '524288000', 10) }, +}); + +function validate(schema) { + return (req, res, next) => { + const result = schema.safeParse(req.body); + if (!result.success) { + const e = result.error.errors[0]; + return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0])); + } + req.body = result.data; + next(); + }; +} + +// GET /videos +router.get('/', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const { category, page = 1, limit = 50 } = req.query; + const { rows, count } = await svc.getVideos(models, req.user.organizationId, { category, page: +page, limit: +limit }); + collection(res, rows, count, +page, +limit); + } catch (err) { next(err); } +}); + +// POST /videos (upload) +router.post('/', authenticateToken, authenticateRole(COACH_PLUS), checkUploadAllowed, upload.single('video'), validate(uploadVideoSchema), async (req, res, next) => { + try { + if (!req.file) return next(new AppError('VALIDATION_FAILED', 'No video file provided.', 400)); + const video = await svc.uploadVideo(models, req, req.user.organizationId, req.file, req.body); + created(res, video); + } catch (err) { next(err); } +}); + +// GET /videos/stream/:filename (must come before /:id to avoid conflict) +router.get('/stream/:filename', authenticateToken, async (req, res, next) => { + try { + await svc.streamVideo(models, req.user.organizationId, req.params.filename, req.headers.range, res); + } catch (err) { next(err); } +}); + +// DELETE /videos/:id +router.delete('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + await svc.deleteVideo(models, req, parseInt(req.params.id, 10), req.user.organizationId); + noContent(res); + } catch (err) { next(err); } +}); + +// GET /videos/categories → mounted under /categories prefix but exported from here +// These are registered separately in categories-routes.js +module.exports = router; diff --git a/V2/app/modules/videos/service.js b/V2/app/modules/videos/service.js new file mode 100644 index 0000000..7e83371 --- /dev/null +++ b/V2/app/modules/videos/service.js @@ -0,0 +1,161 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const { AppError } = require('../../core/errors'); +const { log: auditLog } = require('../../core/audit'); + +const UPLOADS_DIR = () => process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads'); +const ALLOWED_MIMES = ['video/mp4', 'video/quicktime', 'video/x-m4v']; +const EXT_MAP = { 'video/mp4': '.mp4', 'video/quicktime': '.mov', 'video/x-m4v': '.m4v' }; + +async function validateMimeType(filePath, allowedMimes) { + const { fileTypeFromBuffer } = await import('file-type'); + const fd = fs.openSync(filePath, 'r'); + const buf = Buffer.alloc(12); + fs.readSync(fd, buf, 0, 12, 0); + fs.closeSync(fd); + const result = await fileTypeFromBuffer(buf); + const mime = result?.mime; + if (!mime || !allowedMimes.includes(mime)) { + throw new AppError('UPLOAD_TYPE_INVALID', 'Only MP4, MOV, and M4V video files are supported.', 400); + } + return mime; +} + +async function getVideos(models, orgId, { category, page = 1, limit = 50 } = {}) { + const where = { organizationId: orgId }; + if (category) where.category = category; + + const offset = (page - 1) * limit; + const { rows, count } = await models.Video.findAndCountAll({ + where, limit, offset, order: [['createdAt', 'DESC']], + }); + + const base = '/api/v1/videos/stream/'; + return { + rows: rows.map(v => ({ ...v.toJSON(), streamUrl: base + v.filename })), + count, + }; +} + +async function uploadVideo(models, req, orgId, file, { description, category }) { + const uploadsDir = UPLOADS_DIR(); + await fs.promises.mkdir(uploadsDir, { recursive: true }); + + let detectedMime; + try { + detectedMime = await validateMimeType(file.path, ALLOWED_MIMES); + const ext = EXT_MAP[detectedMime]; + const safeName = `${Date.now()}_${crypto.randomBytes(8).toString('hex')}${ext}`; + await fs.promises.rename(file.path, path.join(uploadsDir, safeName)); + + const video = await models.Video.create({ + organizationId: orgId, + filename: safeName, + description: description || '', + category, + mimeType: detectedMime, + fileSizeBytes: file.size, + }); + + await auditLog(req, 'video.upload', 'video', video.id, { filename: safeName, category, fileSizeBytes: file.size }); + return { ...video.toJSON(), streamUrl: '/api/v1/videos/stream/' + safeName }; + } finally { + await fs.promises.unlink(file.path).catch(() => {}); + } +} + +async function deleteVideo(models, req, videoId, orgId) { + const video = await models.Video.findOne({ where: { id: videoId, organizationId: orgId } }); + if (!video) throw new AppError('NOT_FOUND', 'Video not found.', 404); + + const filePath = path.join(UPLOADS_DIR(), video.filename); + await fs.promises.unlink(filePath).catch(() => {}); // ignore ENOENT + + const snapshot = video.toJSON(); + await video.destroy(); + await auditLog(req, 'video.delete', 'video', videoId, snapshot); +} + +async function streamVideo(models, orgId, filename, rangeHeader, res) { + const safeName = path.basename(filename); + if (safeName !== filename) { + throw new AppError('NOT_FOUND', 'Invalid filename.', 404); + } + + const video = await models.Video.findOne({ where: { filename: safeName, organizationId: orgId } }); + if (!video) throw new AppError('NOT_FOUND', 'Video not found.', 404); + + const filePath = path.join(UPLOADS_DIR(), safeName); + const resolvedPath = path.resolve(filePath); + const resolvedDir = path.resolve(UPLOADS_DIR()); + if (!resolvedPath.startsWith(resolvedDir + path.sep)) { + throw new AppError('NOT_FOUND', 'Invalid filename.', 404); + } + + let stat; + try { + stat = fs.statSync(filePath); + } catch { + throw new AppError('NOT_FOUND', 'Video file not found on disk.', 404); + } + + const fileSize = stat.size; + const mimeType = video.mimeType || 'video/mp4'; + + if (rangeHeader) { + const [startStr, endStr] = rangeHeader.replace(/bytes=/, '').split('-'); + const start = parseInt(startStr, 10); + const end = endStr ? parseInt(endStr, 10) : Math.min(start + 1024 * 1024, fileSize - 1); + + res.writeHead(206, { + 'Content-Range': `bytes ${start}-${end}/${fileSize}`, + 'Accept-Ranges': 'bytes', + 'Content-Length': end - start + 1, + 'Content-Type': mimeType, + }); + fs.createReadStream(filePath, { start, end }).pipe(res); + } else { + res.writeHead(200, { + 'Content-Length': fileSize, + 'Content-Type': mimeType, + 'Accept-Ranges': 'bytes', + }); + fs.createReadStream(filePath).pipe(res); + } +} + +async function getCategories(models, orgId) { + return models.Category.findAll({ where: { organizationId: orgId }, order: [['name', 'ASC']] }); +} + +async function createCategory(models, req, orgId, name) { + let category; + try { + category = await models.Category.create({ organizationId: orgId, name }); + } catch (err) { + if (err.name === 'SequelizeUniqueConstraintError') { + throw new AppError('CONFLICT', 'Category already exists.', 409, 'name'); + } + throw err; + } + await auditLog(req, 'category.create', 'category', category.id, { name }); + return category; +} + +async function deleteCategory(models, req, categoryId, orgId) { + const category = await models.Category.findOne({ where: { id: categoryId, organizationId: orgId } }); + if (!category) throw new AppError('NOT_FOUND', 'Category not found.', 404); + + const videoCount = await models.Video.count({ where: { organizationId: orgId, category: category.name } }); + if (videoCount > 0) { + throw new AppError('CONFLICT', 'This category has videos. Move or delete the videos first.', 409); + } + + await auditLog(req, 'category.delete', 'category', categoryId, { name: category.name }); + await category.destroy(); +} + +module.exports = { getVideos, uploadVideo, deleteVideo, streamVideo, getCategories, createCategory, deleteCategory }; diff --git a/V2/app/modules/workouts/migrations/006-workouts-v2.js b/V2/app/modules/workouts/migrations/006-workouts-v2.js new file mode 100644 index 0000000..8c39be4 --- /dev/null +++ b/V2/app/modules/workouts/migrations/006-workouts-v2.js @@ -0,0 +1,41 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const tableDesc = await queryInterface.describeTable('Workouts').catch(() => null); + + if (!tableDesc) { + await queryInterface.createTable('Workouts', { + id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + organizationId: { type: Sequelize.INTEGER, allowNull: false }, + name: { type: Sequelize.STRING }, + workoutDate: { type: Sequelize.DATE }, + video1: { type: Sequelize.INTEGER }, + video2: { type: Sequelize.INTEGER }, + video3: { type: Sequelize.INTEGER }, + video4: { type: Sequelize.INTEGER }, + number1: { type: Sequelize.INTEGER }, + number2: { type: Sequelize.INTEGER }, + number3: { type: Sequelize.INTEGER }, + number4: { type: Sequelize.INTEGER }, + createdByUserId: { type: Sequelize.INTEGER }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false }, + }); + + await queryInterface.addIndex('Workouts', ['organizationId', 'workoutDate']); + return; + } + + const addIfMissing = async (col, def) => { + if (!tableDesc[col]) await queryInterface.addColumn('Workouts', col, def); + }; + + await addIfMissing('organizationId', { type: Sequelize.INTEGER }); + await addIfMissing('createdByUserId', { type: Sequelize.INTEGER }); + }, + + async down(queryInterface) { + await queryInterface.dropTable('Workouts').catch(() => {}); + }, +}; diff --git a/V2/app/modules/workouts/model.js b/V2/app/modules/workouts/model.js new file mode 100644 index 0000000..130ce75 --- /dev/null +++ b/V2/app/modules/workouts/model.js @@ -0,0 +1,28 @@ +'use strict'; + +module.exports = (sequelize, DataTypes) => { + const 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 }, + }); + + Workout.associate = (models) => { + Workout.belongsTo(models.Video, { foreignKey: 'video1', as: 'VideoOne', constraints: false }); + Workout.belongsTo(models.Video, { foreignKey: 'video2', as: 'VideoTwo', constraints: false }); + Workout.belongsTo(models.Video, { foreignKey: 'video3', as: 'VideoThree', constraints: false }); + Workout.belongsTo(models.Video, { foreignKey: 'video4', as: 'VideoFour', constraints: false }); + }; + + return { Workout }; +}; diff --git a/V2/app/modules/workouts/routes.js b/V2/app/modules/workouts/routes.js new file mode 100644 index 0000000..3e76892 --- /dev/null +++ b/V2/app/modules/workouts/routes.js @@ -0,0 +1,64 @@ +'use strict'; + +const express = require('express'); +const { models } = require('../../core/db'); +const { authenticateToken, authenticateRole } = require('../../core/auth'); +const { ok, created, collection, noContent } = require('../../core/respond'); +const { AppError } = require('../../core/errors'); +const { createWorkout: createWorkoutSchema } = require('../../core/schemas/workouts'); +const svc = require('./service'); + +const router = express.Router(); +router.prefix = 'workouts'; + +const COACH_PLUS = ['Owner', 'Coach', 'SystemAdmin']; + +function validate(schema) { + return (req, res, next) => { + const result = schema.safeParse(req.body); + if (!result.success) { + const e = result.error.errors[0]; + return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0])); + } + req.body = result.data; + next(); + }; +} + +router.get('/today', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const workouts = await svc.getTodayWorkouts(models, req.user.organizationId); + ok(res, workouts); + } catch (err) { next(err); } +}); + +router.get('/', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const { page = 1, limit = 20 } = req.query; + const { rows, count } = await svc.getWorkouts(models, req.user.organizationId, { page: +page, limit: +limit }); + collection(res, rows, count, +page, +limit); + } catch (err) { next(err); } +}); + +router.post('/', authenticateToken, authenticateRole(COACH_PLUS), validate(createWorkoutSchema), async (req, res, next) => { + try { + const workout = await svc.createWorkout(models, req, req.user.organizationId, req.body); + created(res, workout); + } catch (err) { next(err); } +}); + +router.get('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + const workout = await svc.getWorkoutById(models, parseInt(req.params.id, 10), req.user.organizationId); + ok(res, workout); + } catch (err) { next(err); } +}); + +router.delete('/:id', authenticateToken, authenticateRole(COACH_PLUS), async (req, res, next) => { + try { + await svc.deleteWorkout(models, req, parseInt(req.params.id, 10), req.user.organizationId); + noContent(res); + } catch (err) { next(err); } +}); + +module.exports = router; diff --git a/V2/app/modules/workouts/service.js b/V2/app/modules/workouts/service.js new file mode 100644 index 0000000..1bd3353 --- /dev/null +++ b/V2/app/modules/workouts/service.js @@ -0,0 +1,92 @@ +'use strict'; + +const { Op } = require('sequelize'); +const { DateTime } = require('luxon'); +const { AppError } = require('../../core/errors'); +const { log: auditLog } = require('../../core/audit'); + +const STREAM_BASE = '/api/v1/videos/stream/'; + +function videoIncludes(models) { + return [ + { model: models.Video, as: 'VideoOne', required: false, attributes: ['id', 'description', 'filename', 'category'] }, + { model: models.Video, as: 'VideoTwo', required: false, attributes: ['id', 'description', 'filename', 'category'] }, + { model: models.Video, as: 'VideoThree', required: false, attributes: ['id', 'description', 'filename', 'category'] }, + { model: models.Video, as: 'VideoFour', required: false, attributes: ['id', 'description', 'filename', 'category'] }, + ]; +} + +function formatWorkout(w) { + const obj = w.toJSON(); + obj.videos = [ + { slot: 1, video: obj.VideoOne ? { ...obj.VideoOne, streamUrl: STREAM_BASE + obj.VideoOne.filename } : null, reps: obj.number1 }, + { slot: 2, video: obj.VideoTwo ? { ...obj.VideoTwo, streamUrl: STREAM_BASE + obj.VideoTwo.filename } : null, reps: obj.number2 }, + { slot: 3, video: obj.VideoThree ? { ...obj.VideoThree, streamUrl: STREAM_BASE + obj.VideoThree.filename } : null, reps: obj.number3 }, + { slot: 4, video: obj.VideoFour ? { ...obj.VideoFour, streamUrl: STREAM_BASE + obj.VideoFour.filename } : null, reps: obj.number4 }, + ].filter(s => s.video || s.reps); + delete obj.VideoOne; delete obj.VideoTwo; delete obj.VideoThree; delete obj.VideoFour; + return obj; +} + +async function getWorkouts(models, orgId, { page = 1, limit = 20 } = {}) { + const offset = (page - 1) * limit; + const { rows, count } = await models.Workout.findAndCountAll({ + where: { organizationId: orgId }, + include: videoIncludes(models), + limit, offset, order: [['workoutDate', 'DESC'], ['createdAt', 'DESC']], + }); + return { rows: rows.map(formatWorkout), count }; +} + +async function getWorkoutById(models, id, orgId) { + const w = await models.Workout.findOne({ + where: { id, organizationId: orgId }, + include: videoIncludes(models), + }); + if (!w) throw new AppError('NOT_FOUND', 'Workout not found.', 404); + return formatWorkout(w); +} + +async function getTodayWorkouts(models, orgId) { + const org = await models.Organization.findByPk(orgId, { attributes: ['timezone'] }); + const tz = org?.timezone || 'UTC'; + const now = DateTime.now().setZone(tz); + const start = now.startOf('day').toUTC().toJSDate(); + const end = now.endOf('day').toUTC().toJSDate(); + + const rows = await models.Workout.findAll({ + where: { organizationId: orgId, workoutDate: { [Op.between]: [start, end] } }, + include: videoIncludes(models), + order: [['workoutDate', 'ASC']], + }); + return rows.map(formatWorkout); +} + +async function createWorkout(models, req, orgId, data) { + // Validate video IDs belong to org + for (const slot of [1, 2, 3, 4]) { + const vid = data[`video${slot}`]; + if (vid) { + const exists = await models.Video.findOne({ where: { id: vid, organizationId: orgId } }); + if (!exists) throw new AppError('VALIDATION_FAILED', `Video ${vid} not found in your library.`, 400, `video${slot}`); + } + } + + const workout = await models.Workout.create({ ...data, organizationId: orgId, createdByUserId: req.user.id }); + await auditLog(req, 'workout.create', 'workout', workout.id, { name: data.name }); + return getWorkoutById(models, workout.id, orgId); +} + +async function deleteWorkout(models, req, id, orgId) { + const workout = await models.Workout.findOne({ where: { id, organizationId: orgId } }); + if (!workout) throw new AppError('NOT_FOUND', 'Workout not found.', 404); + + if (req.user.role === 'Coach' && workout.createdByUserId !== req.user.id) { + throw new AppError('AUTH_FORBIDDEN', 'You can only delete your own workouts.', 403); + } + + await auditLog(req, 'workout.delete', 'workout', id, { name: workout.name }); + await workout.destroy(); +} + +module.exports = { getWorkouts, getWorkoutById, getTodayWorkouts, createWorkout, deleteWorkout }; diff --git a/V2/app/package.json b/V2/app/package.json new file mode 100644 index 0000000..d25e0d2 --- /dev/null +++ b/V2/app/package.json @@ -0,0 +1,46 @@ +{ + "name": "vitfit", + "version": "2.0.0", + "description": "VitFit gym management and coaching platform", + "main": "app.js", + "scripts": { + "start": "node app.js", + "dev": "node --watch app.js", + "setup": "node scripts/setup.js", + "migrate": "node_modules/.bin/sequelize db:migrate", + "test": "node --experimental-vm-modules node_modules/.bin/jest --runInBand", + "test:unit": "jest tests/unit --runInBand", + "test:integration": "jest tests/integration --runInBand", + "test:socket": "jest tests/socket --runInBand", + "test:burnin": "npx playwright test tests/e2e/display-burn-in.test.js" + }, + "dependencies": { + "bcryptjs": "^2.4.3", + "check-disk-space": "^3.4.0", + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "express": "^4.19.2", + "express-rate-limit": "^7.3.1", + "file-type": "^19.4.0", + "helmet": "^7.1.0", + "jsonwebtoken": "^9.0.2", + "luxon": "^3.4.4", + "multer": "^1.4.5-lts.1", + "pino": "^9.2.0", + "pino-pretty": "^11.2.1", + "sequelize": "^6.37.3", + "sequelize-cli": "^6.6.2", + "umzug": "^3.8.1", + "socket.io": "^4.7.5", + "sqlite3": "^5.1.7", + "zod": "^3.23.8" + }, + "devDependencies": { + "jest": "^29.7.0", + "socket.io-client": "^4.7.5", + "supertest": "^7.0.0" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/V2/app/public/audit-log.html b/V2/app/public/audit-log.html new file mode 100644 index 0000000..873579c --- /dev/null +++ b/V2/app/public/audit-log.html @@ -0,0 +1,113 @@ + + + + + + Audit Log — VitFit + + + + + + + +
+ + +
+ + +
+ + +
+ +
+

Loading…

+
+ + +
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/calendar.html b/V2/app/public/calendar.html new file mode 100644 index 0000000..c6ca1a9 --- /dev/null +++ b/V2/app/public/calendar.html @@ -0,0 +1,162 @@ + + + + + + Calendar — VitFit + + + + + + + +
+ + +
+ + +
+ + + +
+ +
+

Loading…

+
+ + + +
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/categories.html b/V2/app/public/categories.html new file mode 100644 index 0000000..e79e1ad --- /dev/null +++ b/V2/app/public/categories.html @@ -0,0 +1,106 @@ + + + + + + Categories — VitFit + + + + + + + +
+ + +
+ + +
+
+
+ +
+ + +
+
+ +
+
+ +
+

Loading…

+
+
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/client-profile.html b/V2/app/public/client-profile.html new file mode 100644 index 0000000..3cf40ec --- /dev/null +++ b/V2/app/public/client-profile.html @@ -0,0 +1,180 @@ + + + + + + Client Profile — VitFit + + + + + + + +
+ + +
+ + +
+ + +
+ + +
+ +
+

Loading…

+
+
+ + + + + + +
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/clients.html b/V2/app/public/clients.html new file mode 100644 index 0000000..63f2702 --- /dev/null +++ b/V2/app/public/clients.html @@ -0,0 +1,93 @@ + + + + + + Clients — VitFit + + + + + + + +
+ + +
+ + +
+ +
+ +
+

Loading…

+
+ + +
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/create-crossfit.html b/V2/app/public/create-crossfit.html new file mode 100644 index 0000000..ca79eba --- /dev/null +++ b/V2/app/public/create-crossfit.html @@ -0,0 +1,144 @@ + + + + + + Create CrossFit WOD — VitFit + + + + + + + +
+ + +
+ + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+

Workout Items

+ +
+

Each item is one line shown on the display (e.g. "21 Thrusters 95/65 lb").

+
+
+ + + +
+
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/create-timer.html b/V2/app/public/create-timer.html new file mode 100644 index 0000000..0aac451 --- /dev/null +++ b/V2/app/public/create-timer.html @@ -0,0 +1,179 @@ + + + + + + Create Timer — VitFit + + + + + + + +
+ + +
+ + +
+
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +

Time between exercises to transition.

+
+
+ + +
+
+
+ + + + + + + + + + + + +
+
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/create-workout.html b/V2/app/public/create-workout.html new file mode 100644 index 0000000..19947ef --- /dev/null +++ b/V2/app/public/create-workout.html @@ -0,0 +1,179 @@ + + + + + + Create Workout — VitFit + + + + + + + +
+ + +
+ + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+

Exercises

+ +
+
+
+ + + +
+ + + +
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/crossfit-display.html b/V2/app/public/crossfit-display.html new file mode 100644 index 0000000..92c994d --- /dev/null +++ b/V2/app/public/crossfit-display.html @@ -0,0 +1,58 @@ + + + + + + WOD Display — VitFit + + + + +
+
+ Loading… + +
+ +
+ +
+ +
+
+
+ +
Offline — last known data shown
+ + + + + + diff --git a/V2/app/public/crossfit.html b/V2/app/public/crossfit.html new file mode 100644 index 0000000..b0ac644 --- /dev/null +++ b/V2/app/public/crossfit.html @@ -0,0 +1,94 @@ + + + + + + CrossFit WODs — VitFit + + + + + + + +
+ + +
+ + +
+

Loading…

+
+ + +
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/dashboard.html b/V2/app/public/dashboard.html new file mode 100644 index 0000000..6589f6e --- /dev/null +++ b/V2/app/public/dashboard.html @@ -0,0 +1,119 @@ + + + + + + Dashboard — VitFit + + + + + + + + +
+ + +
+

Dashboard

+ +
+
+

Today's Workout

+ View All +
+
+
+

No workout scheduled for today.

+ Create Workout +
+
+
+ +
+
+
+

Active Timer

+ View All +
+
+
+

No timer running.

+
+
+
+ + +
+
+ +
+
+

Your session has expired.

+ Sign In Again +
+
+ + + + + diff --git a/V2/app/public/index.html b/V2/app/public/index.html new file mode 100644 index 0000000..869c2eb --- /dev/null +++ b/V2/app/public/index.html @@ -0,0 +1,109 @@ + + + + + + VitFit — Sign In + + + + + + +
+
+ + +
+
+ + +
+
+ + +
+ + +
+
+
+ + + + + diff --git a/V2/app/public/js/core.js b/V2/app/public/js/core.js new file mode 100644 index 0000000..a8ede69 --- /dev/null +++ b/V2/app/public/js/core.js @@ -0,0 +1,256 @@ +/* VitFit core.js — loaded on every page */ +'use strict'; + +// ── Auth ────────────────────────────────────────────────────────────────────── +const Auth = (() => { + const JWT_KEY = 'vf_jwt'; + const DEVICE_KEY = 'vf_device'; + + function getJwt() { return localStorage.getItem(JWT_KEY); } + function setJwt(t) { localStorage.setItem(JWT_KEY, t); } + function getDeviceToken() { return localStorage.getItem(DEVICE_KEY); } + function setDeviceToken(t) { localStorage.setItem(DEVICE_KEY, t); } + function clearSession() { localStorage.removeItem(JWT_KEY); localStorage.removeItem(DEVICE_KEY); } + + function decodeJwt(token) { + try { + return JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))); + } catch { return null; } + } + + function isTokenExpiringSoon(token) { + const payload = decodeJwt(token); + if (!payload?.exp) return false; + return (payload.exp * 1000 - Date.now()) < 60 * 60 * 1000; // < 1 hour + } + + async function tryDeviceLogin() { + const deviceToken = getDeviceToken(); + if (!deviceToken) return false; + try { + const res = await fetch('/api/v1/auth/device-login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ deviceToken }), + }); + if (!res.ok) return false; + const { data } = await res.json(); + setJwt(data.jwt); + if (data.deviceToken) setDeviceToken(data.deviceToken); + return true; + } catch { return false; } + } + + async function autoRefreshIfNeeded() { + const token = getJwt(); + if (!token || !isTokenExpiringSoon(token)) return; + try { + const res = await fetch('/api/v1/auth/refresh-token', { + method: 'POST', + headers: { Authorization: `Bearer ${token}` }, + }); + if (res.ok) { + const { data } = await res.json(); + setJwt(data.jwt); + } + } catch {} + } + + return { getJwt, setJwt, getDeviceToken, setDeviceToken, clearSession, decodeJwt, isTokenExpiringSoon, tryDeviceLogin, autoRefreshIfNeeded }; +})(); + +// ── Api ─────────────────────────────────────────────────────────────────────── +const Api = (() => { + async function _fetch(url, options = {}, retry = true) { + await Auth.autoRefreshIfNeeded(); + const jwt = Auth.getJwt(); + const headers = { ...(options.headers || {}) }; + if (jwt) headers['Authorization'] = `Bearer ${jwt}`; + if (!(options.body instanceof FormData) && options.body) { + headers['Content-Type'] = 'application/json'; + } + + const res = await fetch(url, { ...options, headers }); + + if (res.status === 401 && retry) { + // Try device login once + const refreshed = await Auth.tryDeviceLogin(); + if (refreshed) return _fetch(url, options, false); + Page.showSessionExpiredOverlay(); + throw new Error('Session expired'); + } + + return res; + } + + const get = (url, params) => _fetch(url + (params ? '?' + new URLSearchParams(params) : '')); + const post = (url, body) => _fetch(url, { method: 'POST', body: JSON.stringify(body) }); + const patch = (url, body) => _fetch(url, { method: 'PATCH', body: JSON.stringify(body) }); + const put = (url, body) => _fetch(url, { method: 'PUT', body: JSON.stringify(body) }); + const del = (url) => _fetch(url, { method: 'DELETE' }); + const upload = (url, formData) => _fetch(url, { method: 'POST', body: formData }); + + return { fetch: _fetch, get, post, patch, put, del, upload }; +})(); + +// ── Nav ─────────────────────────────────────────────────────────────────────── +const Nav = (() => { + 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', 'SystemAdmin'] }, + { label: 'Log Out', href: '#', action: 'logout', roles: ['Owner', 'Coach', 'Client', 'SystemAdmin'] }, + ]; + + function init(currentPage) { + const drawer = document.getElementById('nav-drawer'); + const scrim = document.getElementById('drawer-scrim'); + const hamb = document.getElementById('nav-hamburger'); + const navList = document.getElementById('nav-list'); + if (!drawer || !navList) return; + + const user = Page.currentUser(); + const orgFeatures = (window._orgFeatures || []); + + navList.innerHTML = ''; + NAV_LINKS.forEach(link => { + if (!link.roles.includes(user?.role)) return; + if (link.feature && !orgFeatures.includes(link.feature)) return; + + const li = document.createElement('li'); + const a = document.createElement('a'); + a.textContent = link.label; + a.href = link.href; + if (link.href === currentPage || window.location.pathname.endsWith(link.href)) { + a.classList.add('active'); + } + if (link.action === 'logout') { + a.addEventListener('click', async (e) => { + e.preventDefault(); + await Api.post('/api/v1/auth/logout', {}).catch(() => {}); + Auth.clearSession(); + window.location.href = '/'; + }); + } + li.appendChild(a); + navList.appendChild(li); + }); + + hamb?.addEventListener('click', toggle); + scrim?.addEventListener('click', close); + } + + function toggle() { + const drawer = document.getElementById('nav-drawer'); + const scrim = document.getElementById('drawer-scrim'); + drawer?.classList.toggle('open'); + scrim?.classList.toggle('open'); + } + + function close() { + document.getElementById('nav-drawer')?.classList.remove('open'); + document.getElementById('drawer-scrim')?.classList.remove('open'); + } + + return { init, toggle, close }; +})(); + +// ── Branding ────────────────────────────────────────────────────────────────── +const Branding = (() => { + async function load() { + try { + const res = await Api.get('/api/v1/org/branding'); + if (!res.ok) return; + const { data } = await res.json(); + apply(data); + window._orgFeatures = data.features || []; + // Set app name in banner + const titleEl = document.getElementById('app-name'); + if (titleEl && data.appName) titleEl.textContent = data.appName; + // Set logo if present + const logoEl = document.getElementById('banner-logo'); + if (logoEl && data.logoPath) { logoEl.src = data.logoPath; logoEl.style.display = ''; } + } catch {} + } + + function apply(branding) { + const root = document.documentElement.style; + if (branding.primaryColor) root.setProperty('--color-primary', branding.primaryColor); + if (branding.secondaryColor) root.setProperty('--color-secondary', branding.secondaryColor); + if (branding.workColor) root.setProperty('--color-work', branding.workColor); + if (branding.restColor) root.setProperty('--color-rest', branding.restColor); + if (branding.moveColor) root.setProperty('--color-move', branding.moveColor); + } + + return { load, apply }; +})(); + +// ── Page ────────────────────────────────────────────────────────────────────── +const Page = (() => { + function currentUser() { + const token = Auth.getJwt(); + if (!token) return null; + return Auth.decodeJwt(token); + } + + async function init(allowedRoles) { + let user = currentUser(); + + if (!user) { + const refreshed = await Auth.tryDeviceLogin(); + if (refreshed) { user = currentUser(); } + } + + if (!user) { + window.location.href = '/'; + return; + } + + if (allowedRoles && !allowedRoles.includes(user.role)) { + window.location.href = '/dashboard.html'; + return; + } + + await Branding.load(); + Nav.init(window.location.pathname); + } + + function showSessionExpiredOverlay() { + document.getElementById('session-expired-overlay')?.classList.add('visible'); + } + + return { init, currentUser, showSessionExpiredOverlay }; +})(); + +// ── Toast ───────────────────────────────────────────────────────────────────── +function toast(message, type = 'info', duration = 3000) { + let container = document.getElementById('toast-container'); + if (!container) { + container = document.createElement('div'); + container.id = 'toast-container'; + document.body.appendChild(container); + } + const el = document.createElement('div'); + el.className = `toast toast-${type}`; + el.textContent = message; + container.appendChild(el); + setTimeout(() => el.remove(), duration); +} + +// ── Back-forward cache (bfcache) re-init ────────────────────────────────────── +window.addEventListener('pageshow', (e) => { + if (e.persisted && window._socketClient) { + // Re-connect socket on bfcache restore + window._socketClient.connect?.(); + } +}); diff --git a/V2/app/public/js/display.js b/V2/app/public/js/display.js new file mode 100644 index 0000000..8f3fea0 --- /dev/null +++ b/V2/app/public/js/display.js @@ -0,0 +1,68 @@ +/* VitFit display.js — used by workout-display.html and crossfit-display.html */ +'use strict'; + +const Display = (() => { + let _keepAliveEl = null; + + function renderWorkout(workout) { + const nameEl = document.getElementById('display-workout-name'); + const dateEl = document.getElementById('display-workout-date'); + const listEl = document.getElementById('display-workout-list'); + + if (nameEl) nameEl.textContent = workout.name || ''; + if (dateEl && workout.workoutDate) { + dateEl.textContent = new Date(workout.workoutDate).toLocaleDateString('en-US', { month: 'long', day: 'numeric' }); + } + + if (listEl) { + listEl.innerHTML = ''; + (workout.videos || []).filter(s => s.video).forEach(slot => { + const li = document.createElement('li'); + li.className = 'display-workout-item'; + li.innerHTML = ` + ${slot.video.description || 'Exercise'} + ${slot.reps ? `${slot.reps} reps` : ''} + `; + listEl.appendChild(li); + }); + } + } + + function renderCrossfit(workout) { + const nameEl = document.getElementById('display-cf-name'); + const dateEl = document.getElementById('display-cf-date'); + const listEl = document.getElementById('display-cf-list'); + + if (nameEl) nameEl.textContent = workout.name || ''; + if (dateEl && workout.workoutDate) { + dateEl.textContent = new Date(workout.workoutDate).toLocaleDateString('en-US', { month: 'long', day: 'numeric' }); + } + + if (listEl) { + listEl.innerHTML = ''; + (workout.workoutItems || []).forEach(item => { + const li = document.createElement('li'); + li.className = 'display-crossfit-item'; + li.textContent = item; + listEl.appendChild(li); + }); + } + } + + function setOffline(isOffline) { + document.getElementById('display-offline-banner')?.classList.toggle('visible', isOffline); + } + + function startKeepAlive() { + if (_keepAliveEl) return; + _keepAliveEl = document.createElement('div'); + _keepAliveEl.className = 'keep-alive'; + document.body.appendChild(_keepAliveEl); + } + + function applyBranding(branding) { + Branding.apply(branding); + } + + return { renderWorkout, renderCrossfit, setOffline, startKeepAlive, applyBranding }; +})(); diff --git a/V2/app/public/js/socket-client.js b/V2/app/public/js/socket-client.js new file mode 100644 index 0000000..498aff9 --- /dev/null +++ b/V2/app/public/js/socket-client.js @@ -0,0 +1,66 @@ +/* VitFit socket-client.js */ +'use strict'; + +class SocketClient { + constructor() { + this._socket = null; + this._reconnectHandlers = []; + this._disconnectHandlers = []; + this._handlers = {}; + this._currentRoom = null; + } + + connect() { + if (this._socket?.connected) return; + + const jwt = Auth.getJwt(); + this._socket = io({ auth: { token: jwt }, reconnectionDelay: 1000, reconnectionDelayMax: 10000 }); + + this._socket.on('connect', () => { + if (this._currentRoom) this._socket.emit('timer:join', { sessionId: this._currentRoom }); + this._reconnectHandlers.forEach(cb => cb()); + }); + + this._socket.on('disconnect', (reason) => { + this._disconnectHandlers.forEach(cb => cb(reason)); + }); + + // Re-bind registered handlers to new socket + Object.entries(this._handlers).forEach(([event, handler]) => { + this._socket.on(event, handler); + }); + + window._socketClient = this; + } + + on(event, handler) { + this._handlers[event] = handler; + this._socket?.on(event, handler); + } + + emit(event, data) { + this._socket?.emit(event, data); + } + + joinRoom(sessionId) { + this._currentRoom = sessionId; + this._socket?.emit('timer:join', { sessionId }); + } + + leaveRoom(sessionId) { + this._currentRoom = null; + this._socket?.emit('timer:leave', { sessionId }); + } + + onDisconnect(cb) { this._disconnectHandlers.push(cb); } + onReconnect(cb) { this._reconnectHandlers.push(cb); } + + destroy() { + this._socket?.disconnect(); + this._socket = null; + this._handlers = {}; + this._reconnectHandlers = []; + this._disconnectHandlers = []; + window._socketClient = null; + } +} diff --git a/V2/app/public/js/timer-display.js b/V2/app/public/js/timer-display.js new file mode 100644 index 0000000..f550fae --- /dev/null +++ b/V2/app/public/js/timer-display.js @@ -0,0 +1,164 @@ +/* VitFit timer-display.js — used by timer-display.html */ +'use strict'; + +const TimerDisplay = (() => { + let _socket = null; + let _sessionId = null; + let _localFallbackRaf = null; + let _localEndTime = null; + let _keepAliveEl = null; + + const containerEl = () => document.getElementById('timer-container'); + const timerEl = () => document.getElementById('timer-countdown'); + const totalEl = () => document.getElementById('timer-total'); + const phaseEl = () => document.getElementById('timer-phase-label'); + const lapEl = () => document.getElementById('timer-lap'); + const exerciseEl = () => document.getElementById('timer-exercise'); + const setEl = () => document.getElementById('timer-set'); + const overlayEl = () => document.getElementById('timer-overlay'); + const overlayTitleEl = () => document.getElementById('timer-overlay-title'); + const offlineBanner = () => document.getElementById('display-offline-banner'); + const localIndicator = () => document.getElementById('display-local-indicator'); + + function init(sessionId) { + _sessionId = sessionId; + _socket = new SocketClient(); + + _socket.onDisconnect(() => { + offlineBanner()?.classList.add('visible'); + if (_localEndTime) startLocalFallback(_localEndTime); + }); + + _socket.onReconnect(async () => { + offlineBanner()?.classList.remove('visible'); + localIndicator()?.classList.remove('visible'); + stopLocalFallback(); + // Re-sync state from server + const res = await Api.get(`/api/v1/timers/session/${_sessionId}`).catch(() => null); + if (res?.ok) { + const { data } = await res.json(); + if (data) handleState(data); + } + }); + + _socket.on('timer:state', handleState); + _socket.on('timer:tick', handleTick); + _socket.on('timer:phase-change', handlePhaseChange); + _socket.on('timer:complete', handleComplete); + _socket.on('timer:stopped', handleStopped); + + _socket.connect(); + _socket.joinRoom(sessionId); + + // AirPlay keep-alive + _keepAliveEl = document.createElement('div'); + _keepAliveEl.className = 'keep-alive'; + document.body.appendChild(_keepAliveEl); + + // Cleanup on unload + window.addEventListener('beforeunload', () => { + _socket.leaveRoom(sessionId); + _socket.destroy(); + stopLocalFallback(); + }); + } + + function handleState(state) { + _localEndTime = state.phaseEndTime; // ms epoch from server + setPhaseColor(state.phase, state.phaseRemainingMs); + updateCounters(state); + if (timerEl()) timerEl().textContent = formatTime(state.phaseRemainingMs); + if (totalEl()) totalEl().textContent = 'Total ' + formatTime(state.totalRemainingMs); + } + + function handleTick(data) { + _localEndTime = data.phaseEndTime || _localEndTime; + setPhaseColor(data.phase, data.phaseRemainingMs); + if (timerEl()) timerEl().textContent = formatTime(data.phaseRemainingMs); + if (totalEl()) totalEl().textContent = 'Total ' + formatTime(data.totalRemainingMs); + updateCounters(data); + stopLocalFallback(); + } + + function handlePhaseChange(data) { + setPhaseColor(data.phase, data.phaseRemainingMs); + updateCounters(data); + _localEndTime = data.phaseEndTime; + } + + function handleComplete() { + stopLocalFallback(); + if (timerEl()) timerEl().textContent = '00:00'; + if (overlayTitleEl()) overlayTitleEl().textContent = 'DONE'; + overlayEl()?.classList.add('visible'); + containerEl()?.classList.add('phase-complete'); + } + + function handleStopped() { + stopLocalFallback(); + if (overlayTitleEl()) overlayTitleEl().textContent = 'STOPPED'; + overlayEl()?.classList.add('visible'); + } + + function startLocalFallback(endTimeMs) { + stopLocalFallback(); + localIndicator()?.classList.add('visible'); + + function tick() { + const remaining = Math.max(0, endTimeMs - Date.now()); + if (timerEl()) timerEl().textContent = formatTime(remaining); + if (remaining > 0) { + _localFallbackRaf = requestAnimationFrame(tick); + } else { + localIndicator()?.classList.remove('visible'); + } + } + _localFallbackRaf = requestAnimationFrame(tick); + } + + function stopLocalFallback() { + if (_localFallbackRaf) { + cancelAnimationFrame(_localFallbackRaf); + _localFallbackRaf = null; + } + localIndicator()?.classList.remove('visible'); + } + + function updateCounters(state) { + if (phaseEl()) phaseEl().textContent = (state.phase || '').toUpperCase(); + if (lapEl()) lapEl().textContent = `LAP ${state.currentLap}/${state.lapCount}`; + if (exerciseEl()) exerciseEl().textContent = `${state.currentExercise}/${state.exerciseCount} EX`; + if (setEl()) setEl().textContent = `SET ${state.currentSet}/${state.setCount}`; + } + + function setPhaseColor(phase, remainingMs) { + const container = containerEl(); + if (!container) return; + container.className = 'display-container'; + + const isWarning = typeof remainingMs === 'number' && remainingMs <= 10000 && remainingMs > 0; + if (isWarning) { + container.classList.add('phase-warning'); + } else { + container.classList.add(`phase-${phase || 'idle'}`); + } + } + + function formatTime(ms) { + if (typeof ms !== 'number' || isNaN(ms)) return '--:--'; + const totalSec = Math.max(0, Math.ceil(ms / 1000)); + const min = String(Math.floor(totalSec / 60)).padStart(2, '0'); + const sec = String(totalSec % 60).padStart(2, '0'); + return `${min}:${sec}`; + } + + function formatHMS(ms) { + const totalSec = Math.max(0, Math.ceil(ms / 1000)); + const h = Math.floor(totalSec / 3600); + const m = Math.floor((totalSec % 3600) / 60); + const s = totalSec % 60; + return `${h}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`; + } + + return { init, handleState, handleTick, handlePhaseChange, handleComplete, handleStopped, startLocalFallback, stopLocalFallback, formatTime, formatHMS, setPhaseColor }; +})(); diff --git a/V2/app/public/manifest.json b/V2/app/public/manifest.json new file mode 100644 index 0000000..43566a1 --- /dev/null +++ b/V2/app/public/manifest.json @@ -0,0 +1,15 @@ +{ + "name": "VitFit", + "short_name": "VitFit", + "description": "Fitness coaching platform", + "start_url": "/dashboard.html", + "display": "standalone", + "background_color": "#1a1a1a", + "theme_color": "#1a1a1a", + "orientation": "any", + "icons": [ + { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" }, + { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" }, + { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" } + ] +} diff --git a/V2/app/public/my-schedule.html b/V2/app/public/my-schedule.html new file mode 100644 index 0000000..5718f66 --- /dev/null +++ b/V2/app/public/my-schedule.html @@ -0,0 +1,77 @@ + + + + + + My Schedule — VitFit + + + + + + + +
+ + +
+

My Schedule

+ +
+

Loading…

+
+
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/my-workouts.html b/V2/app/public/my-workouts.html new file mode 100644 index 0000000..854c481 --- /dev/null +++ b/V2/app/public/my-workouts.html @@ -0,0 +1,94 @@ + + + + + + My Workouts — VitFit + + + + + + + +
+ + +
+

My Workouts

+ +
+ + +
+ +
+

Loading…

+
+
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/profile.html b/V2/app/public/profile.html new file mode 100644 index 0000000..cee9b96 --- /dev/null +++ b/V2/app/public/profile.html @@ -0,0 +1,125 @@ + + + + + + Profile — VitFit + + + + + + + +
+ + +
+

My Profile

+ +
+ +
+

Account Details

+
+
+ + +
+
+ + +
+ + +
+
+ + +
+

Change Password

+
+
+ + +
+
+ + +
+
+ + +
+ + +
+
+
+
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/settings.html b/V2/app/public/settings.html new file mode 100644 index 0000000..aa84749 --- /dev/null +++ b/V2/app/public/settings.html @@ -0,0 +1,262 @@ + + + + + + Settings — VitFit + + + + + + + +
+ + +
+

Settings

+ +
+ + + +
+ + +
+
+

Organisation Details

+
+
+ + +
+
+ + +
+ + +
+
+
+ + + + + + +
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/styles/base.css b/V2/app/public/styles/base.css new file mode 100644 index 0000000..e65411e --- /dev/null +++ b/V2/app/public/styles/base.css @@ -0,0 +1,146 @@ +/* ── Reset ────────────────────────────────────────────────────────────────── */ +*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } +html { -webkit-text-size-adjust: 100%; } +body { -webkit-font-smoothing: antialiased; } +img, video { max-width: 100%; display: block; } +button, input, select, textarea { font: inherit; } +a { color: inherit; text-decoration: none; } + +/* ── Brand tokens (overridable per org via Branding.apply()) ────────────── */ +:root { + --color-primary: #00FF88; + --color-secondary: #4488FF; + --color-work: #00FF88; + --color-rest: #4488FF; + --color-move: #FF4444; + --color-warning: #FFAA00; + --color-complete: #FFFFFF; + --color-idle: #FFFFFF; +} + +/* ── Surface & text tokens (not overridable) ────────────────────────────── */ +:root { + --surface-bg: #0f0f0f; + --surface-card: #1a1a1a; + --surface-raised: #242424; + --surface-border: #2e2e2e; + --surface-hover: #2a2a2a; + + --text-primary: #f0f0f0; + --text-secondary: #a0a0a0; + --text-muted: #606060; + --text-inverse: #0f0f0f; + --text-on-primary: #0f0f0f; + + --color-success: #00FF88; + --color-danger: #FF4444; + --color-info: #4488FF; + --color-warning-ui: #FFAA00; + + --display-bg: #1a1a1a; + --display-text: #ffffff; +} + +/* ── Spacing ────────────────────────────────────────────────────────────── */ +:root { + --space-1: 4px; --space-2: 8px; --space-3: 12px; + --space-4: 16px; --space-5: 20px; --space-6: 24px; + --space-8: 32px; --space-10: 40px; --space-12: 48px; + --space-16: 64px; --space-20: 80px; --space-24: 96px; +} + +/* ── Radii ──────────────────────────────────────────────────────────────── */ +:root { + --radius-sm: 6px; + --radius-md: 10px; + --radius-lg: 16px; + --radius-full: 9999px; +} + +/* ── Typography ─────────────────────────────────────────────────────────── */ +:root { + --font-family: system-ui, -apple-system, "Segoe UI", sans-serif; + + --text-xs: 12px; --text-sm: 14px; --text-base: 16px; + --text-lg: 18px; --text-xl: 22px; --text-2xl: 28px; + + --weight-normal: 400; --weight-medium: 500; + --weight-semibold: 600; --weight-bold: 700; --weight-black: 900; + + --line-height-tight: 1.2; + --line-height-normal: 1.5; + --line-height-loose: 1.75; +} + +/* ── Transitions ────────────────────────────────────────────────────────── */ +:root { + --transition-fast: 100ms ease; + --transition-base: 200ms ease; + --transition-slow: 400ms ease; + --transition-phase: 600ms ease; +} + +/* ── Z-index ────────────────────────────────────────────────────────────── */ +:root { + --z-base: 1; --z-sticky: 10; --z-drawer: 100; + --z-modal: 200; --z-overlay: 300; --z-toast: 400; +} + +/* ── Base styles ────────────────────────────────────────────────────────── */ +html, body { + height: 100%; + background: var(--surface-bg); + color: var(--text-primary); + font-family: var(--font-family); + font-size: var(--text-base); + line-height: var(--line-height-normal); +} + +/* ── Focus ──────────────────────────────────────────────────────────────── */ +:focus-visible { + outline: 2px solid var(--color-primary); + outline-offset: 2px; +} + +/* ── Reduced motion ─────────────────────────────────────────────────────── */ +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + transition-duration: 0ms !important; + animation-duration: 0ms !important; + } +} + +/* ── Typography utilities ───────────────────────────────────────────────── */ +.text-primary { color: var(--text-primary); } +.text-secondary { color: var(--text-secondary); } +.text-muted { color: var(--text-muted); } +.text-danger { color: var(--color-danger); } +.text-success { color: var(--color-success); } + +.text-xs { font-size: var(--text-xs); } +.text-sm { font-size: var(--text-sm); } +.text-lg { font-size: var(--text-lg); } +.text-xl { font-size: var(--text-xl); } +.text-2xl { font-size: var(--text-2xl); } + +.font-medium { font-weight: var(--weight-medium); } +.font-semibold { font-weight: var(--weight-semibold); } +.font-bold { font-weight: var(--weight-bold); } + +/* ── Utility ─────────────────────────────────────────────────────────────── */ +.sr-only { + position: absolute; width: 1px; height: 1px; + padding: 0; margin: -1px; overflow: hidden; + clip: rect(0,0,0,0); white-space: nowrap; border: 0; +} +.hidden { display: none !important; } +.flex { display: flex; } +.flex-col { flex-direction: column; } +.items-center { align-items: center; } +.justify-between { justify-content: space-between; } +.gap-2 { gap: var(--space-2); } +.gap-4 { gap: var(--space-4); } +.gap-6 { gap: var(--space-6); } +.mt-4 { margin-top: var(--space-4); } +.mt-6 { margin-top: var(--space-6); } +.mb-4 { margin-bottom: var(--space-4); } diff --git a/V2/app/public/styles/components.css b/V2/app/public/styles/components.css new file mode 100644 index 0000000..535403f --- /dev/null +++ b/V2/app/public/styles/components.css @@ -0,0 +1,307 @@ +/* ── Buttons ─────────────────────────────────────────────────────────────── */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: var(--space-2); + height: 44px; + padding: 0 var(--space-5); + border-radius: var(--radius-md); + font-size: var(--text-base); + font-weight: var(--weight-semibold); + border: none; + cursor: pointer; + transition: opacity var(--transition-fast); + white-space: nowrap; + text-decoration: none; +} +.btn:active { opacity: 0.75; } +.btn:disabled { opacity: 0.4; cursor: not-allowed; } + +.btn-primary { background: var(--color-primary); color: var(--text-on-primary); } +.btn-secondary { background: var(--surface-raised); color: var(--text-primary); } +.btn-danger { background: var(--color-danger); color: #fff; } +.btn-ghost { background: transparent; color: var(--color-primary); border: 1px solid var(--surface-border); } + +.btn-sm { height: 36px; padding: 0 var(--space-4); font-size: var(--text-sm); } +.btn-lg { height: 52px; padding: 0 var(--space-6); font-size: var(--text-lg); } +.btn-full { width: 100%; } + +/* ── Cards ───────────────────────────────────────────────────────────────── */ +.card { + background: var(--surface-card); + border-radius: var(--radius-md); + border: 1px solid var(--surface-border); + padding: var(--space-5); +} +.card-header { + font-size: var(--text-lg); + font-weight: var(--weight-semibold); + color: var(--text-primary); + margin-bottom: var(--space-4); +} +.card-meta { + font-size: var(--text-sm); + color: var(--text-secondary); +} +.card-actions { + display: flex; + gap: var(--space-3); + margin-top: var(--space-4); +} +.card + .card { margin-top: var(--space-4); } + +/* ── Forms ───────────────────────────────────────────────────────────────── */ +.form-field { margin-bottom: var(--space-5); } +.form-label { + display: block; + font-size: var(--text-sm); + font-weight: var(--weight-medium); + color: var(--text-secondary); + margin-bottom: var(--space-2); +} +.form-input, +.form-select, +.form-textarea { + width: 100%; + height: 44px; + padding: 0 var(--space-4); + background: var(--surface-raised); + border: 1px solid var(--surface-border); + border-radius: var(--radius-sm); + color: var(--text-primary); + font-size: var(--text-base); + transition: border-color var(--transition-fast); +} +.form-textarea { + height: auto; + padding: var(--space-3) var(--space-4); + resize: vertical; + min-height: 100px; +} +.form-input:focus, +.form-select:focus, +.form-textarea:focus { + border-color: var(--color-primary); + outline: none; +} +.form-input::placeholder, +.form-textarea::placeholder { color: var(--text-muted); } +.form-error { + font-size: var(--text-sm); + color: var(--color-danger); + margin-top: var(--space-2); +} +.form-hint { + font-size: var(--text-sm); + color: var(--text-muted); + margin-top: var(--space-2); +} +.form-row { + display: grid; + grid-template-columns: 1fr 1fr; + gap: var(--space-4); +} +@media (max-width: 480px) { .form-row { grid-template-columns: 1fr; } } + +/* ── Color input ─────────────────────────────────────────────────────────── */ +.form-input[type="color"] { + height: 44px; + padding: var(--space-1) var(--space-2); + cursor: pointer; +} + +/* ── Badges ──────────────────────────────────────────────────────────────── */ +.badge { + display: inline-flex; + align-items: center; + padding: 2px var(--space-2); + border-radius: var(--radius-full); + font-size: var(--text-xs); + font-weight: var(--weight-semibold); + text-transform: uppercase; + letter-spacing: 0.04em; + white-space: nowrap; +} +.badge-success { background: color-mix(in srgb, var(--color-success) 15%, transparent); color: var(--color-success); } +.badge-danger { background: color-mix(in srgb, var(--color-danger) 15%, transparent); color: var(--color-danger); } +.badge-info { background: color-mix(in srgb, var(--color-info) 15%, transparent); color: var(--color-info); } +.badge-warning { background: color-mix(in srgb, var(--color-warning-ui) 15%, transparent); color: var(--color-warning-ui); } +.badge-neutral { background: var(--surface-raised); color: var(--text-secondary); } + +/* ── Modal ───────────────────────────────────────────────────────────────── */ +.modal-scrim { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.7); + z-index: calc(var(--z-modal) - 1); + display: flex; + align-items: center; + justify-content: center; + padding: var(--space-4); + opacity: 0; + pointer-events: none; + transition: opacity var(--transition-base); +} +.modal-scrim.open { + opacity: 1; + pointer-events: all; +} + +.modal { + background: var(--surface-raised); + border-radius: var(--radius-lg); + border: 1px solid var(--surface-border); + width: 100%; + max-width: 480px; + max-height: 90dvh; + overflow-y: auto; + display: flex; + flex-direction: column; +} +.modal-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: var(--space-5) var(--space-6) var(--space-4); + border-bottom: 1px solid var(--surface-border); +} +.modal-title { font-size: var(--text-lg); font-weight: var(--weight-semibold); } +.modal-close { + width: 36px; height: 36px; + display: flex; align-items: center; justify-content: center; + background: none; border: none; cursor: pointer; + color: var(--text-secondary); font-size: 20px; + border-radius: var(--radius-sm); + transition: background var(--transition-fast); +} +.modal-close:hover { background: var(--surface-hover); color: var(--text-primary); } + +.modal-body { padding: var(--space-6); flex: 1; } +.modal-footer { + padding: var(--space-4) var(--space-6); + border-top: 1px solid var(--surface-border); + display: flex; + justify-content: flex-end; + gap: var(--space-3); +} + +/* ── Toast ───────────────────────────────────────────────────────────────── */ +#toast-container { + position: fixed; + bottom: var(--space-6); + left: 50%; + transform: translateX(-50%); + z-index: var(--z-toast); + display: flex; + flex-direction: column; + align-items: center; + gap: var(--space-3); + pointer-events: none; + width: max-content; + max-width: min(360px, calc(100vw - 32px)); +} +.toast { + padding: var(--space-3) var(--space-5); + border-radius: var(--radius-md); + font-size: var(--text-sm); + font-weight: var(--weight-medium); + box-shadow: 0 4px 16px rgba(0,0,0,0.4); + pointer-events: all; + animation: toastIn 200ms ease forwards; +} +@keyframes toastIn { + from { opacity: 0; transform: translateY(8px); } + to { opacity: 1; transform: translateY(0); } +} +.toast-success { background: var(--surface-raised); border-left: 3px solid var(--color-success); color: var(--text-primary); } +.toast-error { background: var(--surface-raised); border-left: 3px solid var(--color-danger); color: var(--text-primary); } +.toast-warning { background: var(--surface-raised); border-left: 3px solid var(--color-warning-ui); color: var(--text-primary); } +.toast-info { background: var(--surface-raised); border-left: 3px solid var(--color-info); color: var(--text-primary); } + +/* ── Progress bar ────────────────────────────────────────────────────────── */ +.progress-bar { + height: 8px; + background: var(--surface-border); + border-radius: var(--radius-full); + overflow: hidden; +} +.progress-fill { + height: 100%; + border-radius: var(--radius-full); + background: var(--color-primary); + transition: width var(--transition-slow); +} +.progress-fill.warning { background: var(--color-warning-ui); } +.progress-fill.danger { background: var(--color-danger); } + +/* ── Table ───────────────────────────────────────────────────────────────── */ +.table-wrap { overflow-x: auto; } +table { width: 100%; border-collapse: collapse; } +th, td { + padding: var(--space-3) var(--space-4); + text-align: left; + border-bottom: 1px solid var(--surface-border); + font-size: var(--text-sm); +} +th { + font-weight: var(--weight-semibold); + color: var(--text-secondary); + white-space: nowrap; +} +tr:last-child td { border-bottom: none; } +tr:hover td { background: var(--surface-hover); } + +/* ── Video card ──────────────────────────────────────────────────────────── */ +.video-card { overflow: hidden; } +.video-card video { + width: 100%; + aspect-ratio: 16/9; + background: #000; + border-radius: var(--radius-sm); + margin-bottom: var(--space-3); +} + +/* ── Upload progress ─────────────────────────────────────────────────────── */ +.upload-progress { display: none; margin-top: var(--space-4); } +.upload-progress.visible { display: block; } + +/* ── Empty state ─────────────────────────────────────────────────────────── */ +.empty-state { + text-align: center; + padding: var(--space-16) var(--space-6); + color: var(--text-muted); +} +.empty-state-title { font-size: var(--text-lg); margin-bottom: var(--space-2); color: var(--text-secondary); } + +/* ── Warning banner ──────────────────────────────────────────────────────── */ +.warning-banner { + background: color-mix(in srgb, var(--color-warning-ui) 12%, transparent); + border: 1px solid var(--color-warning-ui); + border-radius: var(--radius-md); + padding: var(--space-3) var(--space-5); + font-size: var(--text-sm); + color: var(--color-warning-ui); + margin-bottom: var(--space-5); +} + +/* ── Session expired overlay ─────────────────────────────────────────────── */ +#session-expired-overlay { + position: fixed; + inset: 0; + background: rgba(0,0,0,0.8); + z-index: var(--z-overlay); + display: flex; + align-items: center; + justify-content: center; + display: none; +} +#session-expired-overlay.visible { display: flex; } +.session-expired-card { + background: var(--surface-card); + border-radius: var(--radius-lg); + padding: var(--space-8); + text-align: center; + max-width: 320px; +} +.session-expired-card h2 { margin-bottom: var(--space-4); } diff --git a/V2/app/public/styles/display.css b/V2/app/public/styles/display.css new file mode 100644 index 0000000..0f45560 --- /dev/null +++ b/V2/app/public/styles/display.css @@ -0,0 +1,231 @@ +/* Display mode — full-screen TV layout. Replaces layout.css + components.css entirely. */ + +/* ── Display mode typography scale ──────────────────────────────────────── */ +:root { + --display-font-primary: 96px; + --display-font-secondary: 48px; + --display-font-label: 32px; + --display-font-body: 28px; +} + +/* ── Full-screen shell ────────────────────────────────────────────────────── */ +html, body { + width: 100vw; + height: 100dvh; + overflow: hidden; + background: var(--display-bg); + color: var(--display-text); + cursor: none; + user-select: none; + -webkit-user-select: none; +} + +.display-container { + width: 100vw; + height: 100dvh; + display: flex; + flex-direction: column; + position: relative; +} + +/* ── Status bar (top strip) ───────────────────────────────────────────────── */ +.display-status-bar { + display: flex; + align-items: center; + justify-content: space-between; + padding: var(--space-4) var(--space-8); + height: 64px; + flex-shrink: 0; +} +.display-status-label { + font-size: var(--display-font-label); + font-weight: var(--weight-bold); + text-transform: uppercase; + letter-spacing: 0.06em; + transition: color var(--transition-phase); +} +.display-status-right { + display: flex; + gap: var(--space-8); + font-size: var(--display-font-label); + font-weight: var(--weight-medium); + color: var(--text-secondary); +} + +/* ── Main timer display ───────────────────────────────────────────────────── */ +.display-main { + flex: 1; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 0 var(--space-8); + text-align: center; +} + +.display-timer { + font-size: var(--display-font-primary); + font-weight: var(--weight-black); + line-height: 1; + letter-spacing: -2px; + transition: color var(--transition-phase); + font-variant-numeric: tabular-nums; +} + +.display-exercise { + font-size: var(--display-font-label); + font-weight: var(--weight-bold); + text-transform: uppercase; + letter-spacing: 0.08em; + margin-top: var(--space-6); + color: var(--text-secondary); + transition: color var(--transition-phase); +} + +.display-total-time { + font-size: var(--display-font-body); + color: var(--text-muted); + margin-top: var(--space-8); +} + +/* ── Phase colors ─────────────────────────────────────────────────────────── */ +.phase-work .display-timer { color: var(--color-work); } +.phase-rest .display-timer { color: var(--color-rest); } +.phase-move .display-timer { color: var(--color-move); } +.phase-idle .display-timer { color: var(--color-idle); } +.phase-warning .display-timer { color: var(--color-warning); } +.phase-complete .display-timer { color: var(--display-text); } + +.phase-work .display-status-label { color: var(--color-work); } +.phase-rest .display-status-label { color: var(--color-rest); } +.phase-move .display-status-label { color: var(--color-move); } +.phase-idle .display-status-label { color: var(--color-idle); } +.phase-warning .display-status-label { color: var(--color-warning); } + +/* ── Workout display ─────────────────────────────────────────────────────── */ +.display-workout-list { + width: 100%; + max-width: 800px; + list-style: none; +} +.display-workout-item { + display: flex; + align-items: baseline; + justify-content: space-between; + padding: var(--space-5) 0; + border-bottom: 1px solid rgba(255,255,255,0.08); + font-size: var(--display-font-body); + font-weight: var(--weight-medium); +} +.display-workout-item:last-child { border-bottom: none; } +.display-workout-item-name { flex: 1; } +.display-workout-item-reps { + font-size: var(--display-font-label); + font-weight: var(--weight-bold); + color: var(--color-primary); + margin-left: var(--space-8); +} + +/* ── CrossFit display ────────────────────────────────────────────────────── */ +.display-crossfit-list { + width: 100%; + max-width: 760px; + list-style: none; + counter-reset: cf-counter; +} +.display-crossfit-item { + display: flex; + gap: var(--space-5); + padding: var(--space-4) 0; + font-size: var(--display-font-body); + font-weight: var(--weight-medium); + border-bottom: 1px solid rgba(255,255,255,0.08); + counter-increment: cf-counter; +} +.display-crossfit-item:last-child { border-bottom: none; } +.display-crossfit-item::before { + content: counter(cf-counter) "."; + font-weight: var(--weight-bold); + color: var(--color-primary); + min-width: 32px; +} + +/* ── Coach touch zones (invisible on TV) ────────────────────────────────── */ +.touch-zone { + position: absolute; + top: 0; + bottom: 0; + width: 80px; + opacity: 0; + cursor: pointer; + -webkit-tap-highlight-color: transparent; +} +.touch-zone-left { left: 0; } +.touch-zone-right { right: 0; } + +/* ── Done / stopped overlay ─────────────────────────────────────────────── */ +.display-overlay { + position: absolute; + inset: 0; + background: rgba(26,26,26,0.92); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: var(--space-6); + display: none; +} +.display-overlay.visible { display: flex; } +.display-overlay-title { + font-size: var(--display-font-primary); + font-weight: var(--weight-black); + color: var(--color-complete); +} +.display-overlay-sub { + font-size: var(--display-font-label); + color: var(--text-secondary); +} + +/* ── Offline banners ─────────────────────────────────────────────────────── */ +.display-offline-banner { + position: fixed; + top: 0; + left: 50%; + transform: translateX(-50%); + background: rgba(26,26,26,0.85); + border: 1px solid var(--color-warning-ui); + border-radius: 0 0 var(--radius-md) var(--radius-md); + padding: var(--space-2) var(--space-6); + font-size: var(--display-font-body); + color: var(--color-warning-ui); + z-index: var(--z-overlay); + pointer-events: none; + display: none; +} +.display-offline-banner.visible { display: block; } + +.display-local-indicator { + position: fixed; + bottom: var(--space-4); + right: var(--space-6); + font-size: 18px; + color: var(--color-warning-ui); + opacity: 0.7; + z-index: var(--z-overlay); + pointer-events: none; + display: none; +} +.display-local-indicator.visible { display: block; } + +/* ── AirPlay keep-alive (imperceptible pulse) ────────────────────────────── */ +@keyframes keepAlive { + 0%, 100% { opacity: 0.995; } + 50% { opacity: 1.0; } +} +.keep-alive { + position: fixed; + inset: 0; + pointer-events: none; + animation: keepAlive 4s ease-in-out infinite; + z-index: -1; +} diff --git a/V2/app/public/styles/layout.css b/V2/app/public/styles/layout.css new file mode 100644 index 0000000..2ffcb02 --- /dev/null +++ b/V2/app/public/styles/layout.css @@ -0,0 +1,195 @@ +/* Management shell — banner + nav drawer + content */ + +/* ── Banner ──────────────────────────────────────────────────────────────── */ +.banner { + position: sticky; + top: 0; + z-index: var(--z-sticky); + height: 56px; + background: var(--surface-card); + border-bottom: 1px solid var(--surface-border); + display: flex; + align-items: center; + padding: 0 var(--space-4); + gap: var(--space-4); +} + +.banner-hamburger { + width: 44px; + height: 44px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 5px; + background: none; + border: none; + cursor: pointer; + flex-shrink: 0; +} +.banner-hamburger span { + display: block; + width: 22px; + height: 2px; + background: var(--text-primary); + border-radius: 2px; + transition: transform var(--transition-base), opacity var(--transition-base); +} + +.banner-logo { + height: 32px; + width: auto; +} +.banner-title { + font-size: var(--text-lg); + font-weight: var(--weight-semibold); + color: var(--text-primary); +} + +/* ── Nav Drawer ──────────────────────────────────────────────────────────── */ +.drawer-scrim { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.6); + z-index: calc(var(--z-drawer) - 1); + opacity: 0; + pointer-events: none; + transition: opacity var(--transition-base); +} +.drawer-scrim.open { + opacity: 1; + pointer-events: all; +} + +.drawer { + position: fixed; + top: 0; + left: 0; + width: 280px; + height: 100dvh; + background: var(--surface-card); + border-right: 1px solid var(--surface-border); + z-index: var(--z-drawer); + transform: translateX(-280px); + transition: transform var(--transition-base); + display: flex; + flex-direction: column; + overflow-y: auto; +} +.drawer.open { transform: translateX(0); } + +.drawer-header { + padding: var(--space-5) var(--space-5) var(--space-4); + border-bottom: 1px solid var(--surface-border); +} +.drawer-logo { + height: 36px; + margin-bottom: var(--space-2); +} +.drawer-org { + font-size: var(--text-sm); + color: var(--text-secondary); +} + +.drawer-nav { + flex: 1; + padding: var(--space-3) 0; + list-style: none; +} +.drawer-nav a { + display: flex; + align-items: center; + height: 48px; + padding: 0 var(--space-5); + font-size: var(--text-base); + color: var(--text-secondary); + transition: background var(--transition-fast), color var(--transition-fast); + cursor: pointer; +} +.drawer-nav a:hover, +.drawer-nav a:focus-visible { background: var(--surface-hover); color: var(--text-primary); } +.drawer-nav a.active { + color: var(--color-primary); + background: color-mix(in srgb, var(--color-primary) 8%, transparent); + font-weight: var(--weight-medium); +} + +.drawer-footer { + border-top: 1px solid var(--surface-border); + padding: var(--space-3) 0; +} + +/* ── Main content ────────────────────────────────────────────────────────── */ +.page-content { + padding: var(--space-6); + max-width: 960px; + margin: 0 auto; + min-height: calc(100dvh - 56px); +} + +.page-title { + font-size: var(--text-xl); + font-weight: var(--weight-semibold); + margin-bottom: var(--space-6); +} + +.page-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: var(--space-6); +} + +/* ── Grid helpers ────────────────────────────────────────────────────────── */ +.grid-2 { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: var(--space-5); +} +.grid-3 { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: var(--space-5); +} + +@media (max-width: 767px) { + .grid-2, .grid-3 { grid-template-columns: 1fr; } + .page-content { padding: var(--space-4); } +} + +/* ── Tabs ────────────────────────────────────────────────────────────────── */ +.tabs { + display: flex; + gap: 2px; + border-bottom: 1px solid var(--surface-border); + margin-bottom: var(--space-6); +} +.tab-btn { + padding: var(--space-3) var(--space-5); + background: none; + border: none; + border-bottom: 2px solid transparent; + color: var(--text-secondary); + font-size: var(--text-base); + cursor: pointer; + transition: color var(--transition-fast), border-color var(--transition-fast); + margin-bottom: -1px; +} +.tab-btn:hover { color: var(--text-primary); } +.tab-btn.active { + color: var(--color-primary); + border-bottom-color: var(--color-primary); + font-weight: var(--weight-medium); +} +.tab-panel { display: none; } +.tab-panel.active { display: block; } + +/* ── Pagination ──────────────────────────────────────────────────────────── */ +.pagination { + display: flex; + align-items: center; + justify-content: center; + gap: var(--space-3); + margin-top: var(--space-8); +} +.pagination-info { font-size: var(--text-sm); color: var(--text-secondary); } diff --git a/V2/app/public/sw.js b/V2/app/public/sw.js new file mode 100644 index 0000000..140c90c --- /dev/null +++ b/V2/app/public/sw.js @@ -0,0 +1,51 @@ +/* VitFit Service Worker — shell-only caching for PWA install */ +'use strict'; + +const CACHE_NAME = 'vitfit-v2'; +const SHELL_ASSETS = [ + '/', + '/index.html', + '/dashboard.html', + '/styles/base.css', + '/styles/layout.css', + '/styles/components.css', + '/js/core.js', + '/js/socket-client.js', + '/manifest.json', +]; + +self.addEventListener('install', (e) => { + e.waitUntil( + caches.open(CACHE_NAME).then(cache => cache.addAll(SHELL_ASSETS)) + ); + self.skipWaiting(); +}); + +self.addEventListener('activate', (e) => { + e.waitUntil( + caches.keys().then(keys => + Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k))) + ) + ); + self.clients.claim(); +}); + +self.addEventListener('fetch', (e) => { + const url = new URL(e.request.url); + + // API and socket: always network + if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/socket.io')) return; + + // Navigation: network-first, fallback to cached index + if (e.request.mode === 'navigate') { + e.respondWith( + fetch(e.request).catch(() => caches.match('/index.html')) + ); + return; + } + + // Static assets: cache-first + e.respondWith( + caches.match(e.request).then(cached => cached || fetch(e.request)) + ); +}); diff --git a/V2/app/public/sysadmin.html b/V2/app/public/sysadmin.html new file mode 100644 index 0000000..82273dd --- /dev/null +++ b/V2/app/public/sysadmin.html @@ -0,0 +1,143 @@ + + + + + + System Admin — VitFit + + + + + + + +
+ + +
+

System Admin

+ +
+ + + +
+ + +
+
+

System Health

+
+

Loading…

+
+
+
+ + + + + + +
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/timer-display.html b/V2/app/public/timer-display.html new file mode 100644 index 0000000..a9d31c3 --- /dev/null +++ b/V2/app/public/timer-display.html @@ -0,0 +1,67 @@ + + + + + + Timer Display — VitFit + + + + +
+ +
+ READY +
+ LAP 1/1 + 1/1 EX + SET 1/1 +
+
+ + +
+
--:--
+
+
+
+ + +
+
DONE
+
Great work!
+
+ + +
+
+
+ +
Offline — running on local clock
+
⌛ local
+ + + + + + + + diff --git a/V2/app/public/timers.html b/V2/app/public/timers.html new file mode 100644 index 0000000..9350b53 --- /dev/null +++ b/V2/app/public/timers.html @@ -0,0 +1,134 @@ + + + + + + Timers — VitFit + + + + + + + +
+ + +
+ + + + + +
+

Loading…

+
+
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/upload-video.html b/V2/app/public/upload-video.html new file mode 100644 index 0000000..d4f7d66 --- /dev/null +++ b/V2/app/public/upload-video.html @@ -0,0 +1,148 @@ + + + + + + Upload Video — VitFit + + + + + + + +
+ + +
+ + +
+
+
+ + +

MP4 recommended. Max 2GB.

+
+
+ + +
+
+ + +
+
+ + +
+ + + + + + +
+
+
+ +
+
+

Your session has expired.

+ Sign In Again +
+
+ + + + + diff --git a/V2/app/public/videos.html b/V2/app/public/videos.html new file mode 100644 index 0000000..068f660 --- /dev/null +++ b/V2/app/public/videos.html @@ -0,0 +1,119 @@ + + + + + + Videos — VitFit + + + + + + + +
+ + +
+ + + +
+ + +
+ +
+

Loading…

+
+ + +
+ +
+
+

Your session has expired.

+ Sign In Again +
+
+ + + + + diff --git a/V2/app/public/workout-display.html b/V2/app/public/workout-display.html new file mode 100644 index 0000000..ab174af --- /dev/null +++ b/V2/app/public/workout-display.html @@ -0,0 +1,60 @@ + + + + + + Workout Display — VitFit + + + + +
+
+ Loading… + +
+ +
+ +
+ +
+
+
+ +
Offline — last known data shown
+ + + + + + diff --git a/V2/app/public/workout-view.html b/V2/app/public/workout-view.html new file mode 100644 index 0000000..5362c15 --- /dev/null +++ b/V2/app/public/workout-view.html @@ -0,0 +1,98 @@ + + + + + + Workout — VitFit + + + + + + + +
+ + +
+ + +
+ +
+

Exercises

+
+

Loading…

+
+
+
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/public/workouts.html b/V2/app/public/workouts.html new file mode 100644 index 0000000..5e36166 --- /dev/null +++ b/V2/app/public/workouts.html @@ -0,0 +1,95 @@ + + + + + + Workouts — VitFit + + + + + + + +
+ + +
+ + +
+ +
+ +
+

Loading…

+
+ + +
+ +
+

Your session has expired.

Sign In Again
+
+ + + + + diff --git a/V2/app/scripts/backup-uploads.sh b/V2/app/scripts/backup-uploads.sh new file mode 100644 index 0000000..d3e33c6 --- /dev/null +++ b/V2/app/scripts/backup-uploads.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# Weekly uploads rsync backup — call via cron +# crontab: 0 2 * * 0 /home/ubuntu/site/scripts/backup-uploads.sh >> /var/log/vitfit-uploads-backup.log 2>&1 + +set -e + +source "$(dirname "$0")/../.env" 2>/dev/null || true + +UPLOADS_DIR="${UPLOADS_DIR:-/home/ubuntu/site/uploads}" +BACKUP_UPLOADS_DEST="${BACKUP_UPLOADS_DEST:-/mnt/backup/uploads}" + +if [ -z "$BACKUP_UPLOADS_DEST" ]; then + echo "[$(date)] BACKUP_UPLOADS_DEST not set — skipping uploads backup" + exit 0 +fi + +mkdir -p "$BACKUP_UPLOADS_DEST" + +rsync -av --checksum "$UPLOADS_DIR/" "$BACKUP_UPLOADS_DEST/" +echo "[$(date)] Uploads backup complete: $UPLOADS_DIR → $BACKUP_UPLOADS_DEST" diff --git a/V2/app/scripts/backup.sh b/V2/app/scripts/backup.sh new file mode 100644 index 0000000..6cfcc84 --- /dev/null +++ b/V2/app/scripts/backup.sh @@ -0,0 +1,21 @@ +#!/bin/bash +# SQLite daily backup — call via cron +# crontab: 0 3 * * * /home/ubuntu/site/scripts/backup.sh >> /var/log/vitfit-backup.log 2>&1 + +set -e + +source "$(dirname "$0")/../.env" 2>/dev/null || true + +DB_PATH="${DB_PATH:-/home/ubuntu/site/database.sqlite}" +BACKUP_DIR="${BACKUP_DIR:-/home/ubuntu/backups}" +TIMESTAMP=$(date +%Y%m%d_%H%M%S) +BACKUP_FILE="$BACKUP_DIR/vitfit_$TIMESTAMP.sqlite" + +mkdir -p "$BACKUP_DIR" + +sqlite3 "$DB_PATH" ".backup '$BACKUP_FILE'" +echo "[$(date)] Backup created: $BACKUP_FILE" + +# Remove backups older than 14 days +find "$BACKUP_DIR" -name "vitfit_*.sqlite" -mtime +14 -delete +echo "[$(date)] Old backups purged" diff --git a/V2/app/scripts/setup.js b/V2/app/scripts/setup.js new file mode 100644 index 0000000..5bc7ea2 --- /dev/null +++ b/V2/app/scripts/setup.js @@ -0,0 +1,90 @@ +#!/usr/bin/env node +'use strict'; + +require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') }); + +const readline = require('readline'); +const bcrypt = require('bcryptjs'); + +const rl = rl_create(); + +function rl_create() { + return readline.createInterface({ input: process.stdin, output: process.stdout }); +} + +function ask(question) { + return new Promise(resolve => rl.question(question, resolve)); +} + +async function main() { + console.log('\nVitFit V2 — First-Time Setup\n'); + + const { initDb, runMigrations, models } = require('../core/db'); + + await initDb(); + await runMigrations(); + + // Refuse if any org exists + const orgCount = await models.Organization.count(); + if (orgCount > 0) { + console.error('ERROR: An organization already exists. Setup can only run on a fresh install.'); + process.exit(1); + } + + const orgName = await ask('Organization name (e.g. CrossFit Downtown): '); + const timezone = await ask('Timezone (e.g. America/New_York) [UTC]: ') || 'UTC'; + const ownerUser = await ask('Owner username: '); + const ownerPass = await ask('Owner password (min 8 chars): '); + const ownerEmail = await ask('Owner email (optional): '); + const saUser = await ask('SystemAdmin username: '); + const saPass = await ask('SystemAdmin password (min 8 chars): '); + + rl.close(); + + if (ownerPass.length < 8 || saPass.length < 8) { + console.error('ERROR: Passwords must be at least 8 characters.'); + process.exit(1); + } + + const { sequelize } = require('../core/db'); + const transaction = await sequelize.transaction(); + + try { + const org = await models.Organization.create({ name: orgName, timezone }, { transaction }); + await models.Branding.create({ organizationId: org.id }, { transaction }); + + const ownerHash = await bcrypt.hash(ownerPass, 12); + await models.User.create({ + organizationId: org.id, + username: ownerUser, + email: ownerEmail || null, + password: ownerHash, + role: 'Owner', + isActive: true, + }, { transaction }); + + const saHash = await bcrypt.hash(saPass, 12); + await models.User.create({ + organizationId: null, + username: saUser, + password: saHash, + role: 'SystemAdmin', + isActive: true, + }, { transaction }); + + await transaction.commit(); + + console.log('\n✓ Setup complete.'); + console.log(` Organization: ${orgName} (id: ${org.id})`); + console.log(` Owner: ${ownerUser}`); + console.log(` SystemAdmin: ${saUser}`); + console.log('\nStart the app with: npm start\n'); + process.exit(0); + } catch (err) { + await transaction.rollback(); + console.error('Setup failed:', err.message); + process.exit(1); + } +} + +main().catch(err => { console.error(err); process.exit(1); }); diff --git a/V2/deploy/docker-compose.yml b/V2/deploy/docker-compose.yml new file mode 100644 index 0000000..070742d --- /dev/null +++ b/V2/deploy/docker-compose.yml @@ -0,0 +1,39 @@ +services: + app: + build: + context: ../app + dockerfile: Dockerfile + image: vitfit:latest + container_name: vitfit-app + restart: unless-stopped + + # Load .env from the app directory; values below override specific keys + env_file: + - ../app/.env + environment: + NODE_ENV: production + DB_PATH: /data/vitfit.sqlite + UPLOADS_DIR: /data/uploads + UPLOAD_TEMP_DIR: /data/tmp + + volumes: + # Bind-mount host directory so DB + uploads survive container rebuilds. + # Create on first deploy: sudo mkdir -p /var/vitfit/data && sudo chown 1000:1000 /var/vitfit/data + - /var/vitfit/data:/data + + # Only expose to localhost — nginx proxies inbound HTTPS traffic + ports: + - "127.0.0.1:3000:3000" + + healthcheck: + test: ["CMD", "wget", "-qO-", "http://localhost:3000/health"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 20s + + logging: + driver: json-file + options: + max-size: "20m" + max-file: "5" diff --git a/V2/deploy/k8s/00-namespace.yaml b/V2/deploy/k8s/00-namespace.yaml new file mode 100644 index 0000000..316e4cd --- /dev/null +++ b/V2/deploy/k8s/00-namespace.yaml @@ -0,0 +1,4 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: vitfit diff --git a/V2/deploy/k8s/01-pvc.yaml b/V2/deploy/k8s/01-pvc.yaml new file mode 100644 index 0000000..24f186d --- /dev/null +++ b/V2/deploy/k8s/01-pvc.yaml @@ -0,0 +1,18 @@ +# Persistent storage for SQLite database + uploaded videos. +# SQLite requires ReadWriteOnce — this limits the Deployment to a single replica. +# If you need horizontal scaling in the future, migrate to PostgreSQL and use +# a separate object store (S3-compatible) for uploads. +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: vitfit-data + namespace: vitfit +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 20Gi + # Set storageClassName to match your cluster's provisioner. + # Leave blank to use the default StorageClass. + # storageClassName: standard diff --git a/V2/deploy/k8s/02-configmap.yaml b/V2/deploy/k8s/02-configmap.yaml new file mode 100644 index 0000000..8369829 --- /dev/null +++ b/V2/deploy/k8s/02-configmap.yaml @@ -0,0 +1,19 @@ +# Non-sensitive environment variables. +# Sensitive values (JWT_SECRET, etc.) go in 03-secret.yaml. +apiVersion: v1 +kind: ConfigMap +metadata: + name: vitfit-config + namespace: vitfit +data: + NODE_ENV: "production" + PORT: "3000" + DB_PATH: "/data/vitfit.sqlite" + UPLOADS_DIR: "/data/uploads" + UPLOAD_TEMP_DIR: "/data/tmp" + LOG_LEVEL: "info" + # Set to your domain: https://your.domain.com + CORS_ORIGIN: "https://your.domain.com" + # Storage warning threshold in bytes (default 10 GB) + STORAGE_WARN_BYTES: "10737418240" + UPLOAD_MAX_BYTES: "2147483648" diff --git a/V2/deploy/k8s/03-secret.yaml b/V2/deploy/k8s/03-secret.yaml new file mode 100644 index 0000000..2b16ea5 --- /dev/null +++ b/V2/deploy/k8s/03-secret.yaml @@ -0,0 +1,18 @@ +# TEMPLATE — do not commit real values. +# Generate and apply this manually: +# +# kubectl create secret generic vitfit-secrets \ +# --namespace=vitfit \ +# --from-literal=JWT_SECRET="$(openssl rand -hex 64)" \ +# --dry-run=client -o yaml | kubectl apply -f - +# +# Or fill in base64-encoded values below (echo -n 'value' | base64): +apiVersion: v1 +kind: Secret +metadata: + name: vitfit-secrets + namespace: vitfit +type: Opaque +data: + # base64-encoded values — replace before applying + JWT_SECRET: REPLACE_WITH_BASE64_ENCODED_SECRET diff --git a/V2/deploy/k8s/04-deployment.yaml b/V2/deploy/k8s/04-deployment.yaml new file mode 100644 index 0000000..6e99fb3 --- /dev/null +++ b/V2/deploy/k8s/04-deployment.yaml @@ -0,0 +1,76 @@ +# Single replica required — SQLite (ReadWriteOnce PVC) cannot be shared across pods. +apiVersion: apps/v1 +kind: Deployment +metadata: + name: vitfit + namespace: vitfit + labels: + app: vitfit +spec: + replicas: 1 + selector: + matchLabels: + app: vitfit + # Recreate ensures the old pod releases the PVC before the new one starts. + strategy: + type: Recreate + template: + metadata: + labels: + app: vitfit + spec: + securityContext: + runAsNonRoot: true + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + + containers: + - name: app + image: vitfit:latest # replace with your registry path + imagePullPolicy: Always + + ports: + - containerPort: 3000 + name: http + + envFrom: + - configMapRef: + name: vitfit-config + - secretRef: + name: vitfit-secrets + + volumeMounts: + - name: data + mountPath: /data + + resources: + requests: + cpu: "250m" + memory: "256Mi" + limits: + cpu: "1000m" + memory: "512Mi" + + livenessProbe: + httpGet: + path: /health + port: 3000 + initialDelaySeconds: 20 + periodSeconds: 30 + timeoutSeconds: 5 + failureThreshold: 3 + + readinessProbe: + httpGet: + path: /health + port: 3000 + initialDelaySeconds: 10 + periodSeconds: 10 + timeoutSeconds: 3 + failureThreshold: 3 + + volumes: + - name: data + persistentVolumeClaim: + claimName: vitfit-data diff --git a/V2/deploy/k8s/05-service.yaml b/V2/deploy/k8s/05-service.yaml new file mode 100644 index 0000000..f1a0ff5 --- /dev/null +++ b/V2/deploy/k8s/05-service.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + name: vitfit + namespace: vitfit + labels: + app: vitfit +spec: + type: ClusterIP + selector: + app: vitfit + ports: + - name: http + port: 80 + targetPort: 3000 diff --git a/V2/deploy/k8s/06-cluster-issuer.yaml b/V2/deploy/k8s/06-cluster-issuer.yaml new file mode 100644 index 0000000..8219429 --- /dev/null +++ b/V2/deploy/k8s/06-cluster-issuer.yaml @@ -0,0 +1,42 @@ +# cert-manager ClusterIssuers — requires cert-manager to be installed in the cluster. +# Install cert-manager: https://cert-manager.io/docs/installation/ +# +# Apply staging first to verify ACME account + DNS, then switch Ingress to prod. +# +# Usage: +# kubectl apply -f 06-cluster-issuer.yaml +# # verify: kubectl describe clusterissuer letsencrypt-staging + +--- +# Staging — safe for testing (not trusted by browsers, no rate limits) +apiVersion: cert-manager.io/v1 +kind: ClusterIssuer +metadata: + name: letsencrypt-staging +spec: + acme: + server: https://acme-staging-v02.api.letsencrypt.org/directory + email: admin@your.domain.com # replace with your email + privateKeySecretRef: + name: letsencrypt-staging-key + solvers: + - http01: + ingress: + ingressClassName: nginx + +--- +# Production — real trusted certs, rate-limited (5 failures/hour per domain) +apiVersion: cert-manager.io/v1 +kind: ClusterIssuer +metadata: + name: letsencrypt-prod +spec: + acme: + server: https://acme-v02.api.letsencrypt.org/directory + email: admin@your.domain.com # replace with your email + privateKeySecretRef: + name: letsencrypt-prod-key + solvers: + - http01: + ingress: + ingressClassName: nginx diff --git a/V2/deploy/k8s/07-ingress.yaml b/V2/deploy/k8s/07-ingress.yaml new file mode 100644 index 0000000..b035f30 --- /dev/null +++ b/V2/deploy/k8s/07-ingress.yaml @@ -0,0 +1,54 @@ +# Nginx Ingress with TLS. +# +# ── Option A: Let's Encrypt (cert-manager) ──────────────────────────────────── +# Requires cert-manager + ClusterIssuer from 06-cluster-issuer.yaml. +# Switch between staging and prod by changing the annotation value. +# cert-manager will auto-create the Secret named in tls.secretName. +# +# ── Option B: Custom / uploaded certificate ─────────────────────────────────── +# 1. Remove (or comment out) the cert-manager annotation. +# 2. Pre-create the TLS Secret: +# kubectl create secret tls vitfit-tls \ +# --namespace=vitfit \ +# --cert=/path/to/your.crt \ +# --key=/path/to/your.key +# 3. The tls.secretName below stays the same — no other changes needed. + +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: vitfit + namespace: vitfit + annotations: + # ── [LE] cert-manager — comment out for custom cert (Option B) + cert-manager.io/cluster-issuer: "letsencrypt-prod" + + # WebSocket support (socket.io) + nginx.ingress.kubernetes.io/proxy-read-timeout: "3600" + nginx.ingress.kubernetes.io/proxy-send-timeout: "3600" + nginx.ingress.kubernetes.io/proxy-buffering: "off" + + # Video upload size — match UPLOAD_MAX_BYTES + nginx.ingress.kubernetes.io/proxy-body-size: "2100m" + + # Force HTTPS + nginx.ingress.kubernetes.io/force-ssl-redirect: "true" + nginx.ingress.kubernetes.io/ssl-redirect: "true" + +spec: + ingressClassName: nginx + tls: + - hosts: + - your.domain.com # replace with your domain + secretName: vitfit-tls # cert-manager creates this (LE) or you create it (custom) + rules: + - host: your.domain.com # replace with your domain + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: vitfit + port: + name: http diff --git a/V2/deploy/nginx/certbot-renew.sh b/V2/deploy/nginx/certbot-renew.sh new file mode 100644 index 0000000..24c9ce2 --- /dev/null +++ b/V2/deploy/nginx/certbot-renew.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Renew Let's Encrypt certificates and reload nginx only when a cert was renewed. +# Run via cron or systemd timer twice daily (certbot skips certs with >30 days left). +# +# Recommended cron entry (as root): +# 0 3,15 * * * /path/to/vitfit/deploy/nginx/certbot-renew.sh >> /var/log/certbot-renew.log 2>&1 + +set -euo pipefail + +certbot renew --quiet --deploy-hook "nginx -s reload" diff --git a/V2/deploy/nginx/nginx-http-snippet.conf b/V2/deploy/nginx/nginx-http-snippet.conf new file mode 100644 index 0000000..74a4c06 --- /dev/null +++ b/V2/deploy/nginx/nginx-http-snippet.conf @@ -0,0 +1,8 @@ +# Add this block to the http{} section of your main nginx.conf +# (typically /etc/nginx/nginx.conf), NOT inside vitfit.conf. +# It enables WebSocket upgrade pass-through for socket.io. + +map $http_upgrade $connection_upgrade { + default upgrade; + '' close; +} diff --git a/V2/deploy/nginx/vitfit.conf b/V2/deploy/nginx/vitfit.conf new file mode 100644 index 0000000..116405e --- /dev/null +++ b/V2/deploy/nginx/vitfit.conf @@ -0,0 +1,91 @@ +# VitFit — Nginx reverse proxy +# Replace 'your.domain.com' with your actual domain before deploying. +# +# TLS mode — only one block should be active at a time: +# Option A (Let's Encrypt via certbot) → lines marked [LE] — ACTIVE by default +# Option B (custom / uploaded cert) → lines marked [CUSTOM] — commented out +# +# To switch to Option B: +# 1. Comment out all [LE] lines +# 2. Uncomment all [CUSTOM] lines +# 3. Copy your cert to /etc/nginx/ssl/vitfit.crt and key to /etc/nginx/ssl/vitfit.key +# 4. nginx -t && nginx -s reload + +# ── HTTP: ACME challenge pass-through + redirect ─────────────────────────────── +server { + listen 80; + listen [::]:80; + server_name your.domain.com; + + # [LE] certbot HTTP-01 challenge files + location /.well-known/acme-challenge/ { + root /var/www/certbot; + } + + location / { + return 301 https://$host$request_uri; + } +} + +# ── HTTPS ────────────────────────────────────────────────────────────────────── +server { + listen 443 ssl; + listen [::]:443 ssl; + http2 on; + server_name your.domain.com; + + # ── [LE] Let's Encrypt certificate (managed by certbot) ─────────────────── + ssl_certificate /etc/letsencrypt/live/your.domain.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/your.domain.com/privkey.pem; + include /etc/letsencrypt/options-ssl-nginx.conf; + ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; + + # ── [CUSTOM] Uploaded / self-signed certificate ─────────────────────────── + # ssl_certificate /etc/nginx/ssl/vitfit.crt; + # ssl_certificate_key /etc/nginx/ssl/vitfit.key; + # ssl_protocols TLSv1.2 TLSv1.3; + # ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384; + # ssl_prefer_server_ciphers off; + # ssl_session_cache shared:SSL:10m; + # ssl_session_timeout 1d; + + # ── Security headers ────────────────────────────────────────────────────── + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; + add_header X-Frame-Options SAMEORIGIN always; + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + + # ── Video upload size — match UPLOAD_MAX_BYTES in .env ─────────────────── + client_max_body_size 2100m; + + # ── Proxy to Node app ───────────────────────────────────────────────────── + location / { + proxy_pass http://127.0.0.1:3000; + proxy_http_version 1.1; + + # WebSocket upgrade (required for socket.io) + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # Long timeouts keep socket.io connections alive through the proxy + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + + # Disable buffering for streaming video responses (Range requests) + proxy_buffering off; + } +} + +# ── WebSocket connection upgrade map ────────────────────────────────────────── +# Place this in the http{} block of your nginx.conf (not inside server{}). +# If you're using a separate conf.d include, add a map-only file instead. +# +# map $http_upgrade $connection_upgrade { +# default upgrade; +# '' close; +# } diff --git a/site/public/uploads/1720846248903.mp4 b/site/public/uploads/1720846248903.mp4 new file mode 100644 index 0000000..d3af971 Binary files /dev/null and b/site/public/uploads/1720846248903.mp4 differ diff --git a/site/public/uploads/1720846257173.mp4 b/site/public/uploads/1720846257173.mp4 new file mode 100644 index 0000000..489f13b Binary files /dev/null and b/site/public/uploads/1720846257173.mp4 differ diff --git a/site/public/uploads/1720846266371.mp4 b/site/public/uploads/1720846266371.mp4 new file mode 100644 index 0000000..0196a3c Binary files /dev/null and b/site/public/uploads/1720846266371.mp4 differ diff --git a/site/public/uploads/1720846274231.mp4 b/site/public/uploads/1720846274231.mp4 new file mode 100644 index 0000000..c621d89 Binary files /dev/null and b/site/public/uploads/1720846274231.mp4 differ