Audit Log
+ Export CSV +Loading…
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 @@ + + +
+ + +Loading…
Loading…
Loading…
Loading…
Loading…
Loading…
No workout scheduled for today.
+ Create Workout +No timer running.
+Loading…
Loading…
Loading…
Loading…
Loading…
Loading…
Loading…