This commit is contained in:
Ccjcarkbla
2026-06-13 08:03:45 -04:00
parent cfcd6ae11e
commit a2c300678b
121 changed files with 8639 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
node_modules
.env
*.sqlite
uploads/
tmp/
pino-*.log
coverage/
.git
.gitignore
+25
View File
@@ -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
+8
View File
@@ -0,0 +1,8 @@
node_modules/
.env
*.sqlite
uploads/
/tmp/
pino-*.log
coverage/
.sequelizerc
+41
View File
@@ -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"]
+148
View File
@@ -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 };
+24
View File
@@ -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 };
+94
View File
@@ -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 };
+91
View File
@@ -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; } };
+42
View File
@@ -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 };
+13
View File
@@ -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;
+33
View File
@@ -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 };
+22
View File
@@ -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 };
+54
View File
@@ -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 };
+11
View File
@@ -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 };
+23
View File
@@ -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 };
+19
View File
@@ -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 };
+28
View File
@@ -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 };
+14
View File
@@ -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 };
+18
View File
@@ -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 };
+49
View File
@@ -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 };
+74
View File
@@ -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 };
+21
View File
@@ -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;
@@ -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');
},
};
+25
View File
@@ -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 };
};
+60
View File
@@ -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;
@@ -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');
},
};
+21
View File
@@ -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 };
};
+55
View File
@@ -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;
+138
View File
@@ -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 };
+22
View File
@@ -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;
@@ -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');
},
};
@@ -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');
},
};
@@ -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');
},
};
+51
View File
@@ -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 };
};
+28
View File
@@ -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;
+152
View File
@@ -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;
+186
View File
@@ -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 };
@@ -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(() => {});
},
};
+19
View File
@@ -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 };
};
+58
View File
@@ -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;
+37
View File
@@ -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 };
@@ -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');
},
};
+43
View File
@@ -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 };
};
+87
View File
@@ -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;
+115
View File
@@ -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 };
+84
View File
@@ -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;
@@ -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(() => {});
},
};
+19
View File
@@ -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 };
};
+75
View File
@@ -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;
+83
View File
@@ -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 };
+169
View File
@@ -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;
@@ -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(() => {});
},
};
@@ -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(() => {});
},
};
+32
View File
@@ -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 };
};
+41
View File
@@ -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;
+122
View File
@@ -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;
+131
View File
@@ -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 };
@@ -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;
@@ -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(() => {});
},
};
@@ -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(() => {});
},
};
+21
View File
@@ -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 };
};
+71
View File
@@ -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;
+161
View File
@@ -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 };
@@ -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(() => {});
},
};
+28
View File
@@ -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 };
};
+64
View File
@@ -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;
+92
View File
@@ -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 };
+46
View File
@@ -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"
}
}
+113
View File
@@ -0,0 +1,113 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audit Log — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">Audit Log</h1>
<a id="export-btn" href="/api/v1/audit-logs/export" class="btn btn-ghost">Export CSV</a>
</div>
<div class="filter-bar">
<input class="form-input" type="text" id="action-filter" placeholder="Filter by action…" style="max-width:200px;">
<input class="form-input" type="text" id="entity-filter" placeholder="Entity type…" style="max-width:200px;">
</div>
<div id="log-list">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
<div id="pagination" class="pagination"></div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
let _page = 1;
async function loadLogs() {
const el = document.getElementById('log-list');
const action = document.getElementById('action-filter').value.trim();
const entity = document.getElementById('entity-filter').value.trim();
try {
const res = await Api.get('/api/v1/audit-logs', { page: _page, limit: 50, action: action || undefined, entityType: entity || undefined });
if (!res.ok) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; return; }
const { data, meta } = await res.json();
if (!data.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No log entries.</p></div>'; return; }
el.innerHTML = `<table class="table"><thead><tr><th>Time</th><th>User</th><th>Action</th><th>Entity</th><th>ID</th></tr></thead><tbody>
${data.map(l => `<tr>
<td style="white-space:nowrap;">${new Date(l.createdAt).toLocaleString()}</td>
<td>${l.user?.name || l.userId || '—'}</td>
<td><code>${l.action}</code></td>
<td>${l.entityType || '—'}</td>
<td>${l.entityId || '—'}</td>
</tr>`).join('')}
</tbody></table>`;
renderPagination(meta);
} catch {
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Error loading log.</p></div>';
}
}
function renderPagination(meta) {
const el = document.getElementById('pagination');
if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; }
el.innerHTML = `
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} onclick="changePage(${_page - 1})">Previous</button>
<span class="pagination-info">Page ${meta.page} of ${meta.totalPages}</span>
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} onclick="changePage(${_page + 1})">Next</button>`;
}
function changePage(p) { _page = p; loadLogs(); }
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner']);
// Add Bearer to export link
const jwt = Auth.getJwt();
if (jwt) {
document.getElementById('export-btn').addEventListener('click', async (e) => {
e.preventDefault();
const res = await Api.get('/api/v1/audit-logs/export');
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = 'audit-log.csv'; a.click();
URL.revokeObjectURL(url);
});
}
loadLogs();
let debounce;
['action-filter', 'entity-filter'].forEach(id => {
document.getElementById(id).addEventListener('input', () => {
clearTimeout(debounce);
debounce = setTimeout(() => { _page = 1; loadLogs(); }, 400);
});
});
});
</script>
</body>
</html>
+162
View File
@@ -0,0 +1,162 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calendar — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">Calendar</h1>
<button class="btn btn-primary" id="new-session-btn">+ Book Session</button>
</div>
<div class="filter-bar">
<input class="form-input" type="date" id="date-from" title="From">
<input class="form-input" type="date" id="date-to" title="To">
<button class="btn btn-ghost" id="filter-btn">Filter</button>
</div>
<div id="session-list">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
<!-- Book session modal -->
<div class="modal-overlay" id="book-modal" style="display:none;">
<div class="modal">
<div class="modal-header">
<h2 class="modal-title">Book Session</h2>
<button class="modal-close" id="book-modal-close">&times;</button>
</div>
<div class="form-group">
<label class="form-label" for="book-client">Client</label>
<select class="form-select" id="book-client">
<option value="">Select client…</option>
</select>
</div>
<div class="form-group">
<label class="form-label" for="book-start">Start</label>
<input class="form-input" type="datetime-local" id="book-start">
</div>
<div class="form-group">
<label class="form-label" for="book-end">End</label>
<input class="form-input" type="datetime-local" id="book-end">
</div>
<div class="form-group">
<label class="form-label" for="book-notes">Notes</label>
<textarea class="form-input" id="book-notes" rows="2"></textarea>
</div>
<div id="book-error" class="form-error" style="display:none;"></div>
<button class="btn btn-primary" id="book-confirm-btn">Book</button>
</div>
</div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
async function loadSessions() {
const el = document.getElementById('session-list');
const from = document.getElementById('date-from').value;
const to = document.getElementById('date-to').value;
const params = {};
if (from) params.from = from;
if (to) params.to = to;
try {
const res = await Api.get('/api/v1/calendar', params);
if (!res.ok) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; return; }
const { data } = await res.json();
if (!data.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No sessions in this range.</p></div>'; return; }
el.innerHTML = `<table class="table"><thead><tr><th>Client</th><th>Start</th><th>End</th><th>Status</th><th></th></tr></thead><tbody>
${data.map(s => `<tr>
<td>${s.client?.name || '—'}</td>
<td>${new Date(s.startAt).toLocaleString()}</td>
<td>${new Date(s.endAt).toLocaleString()}</td>
<td><span class="badge badge-${s.status === 'scheduled' ? 'default' : s.status === 'completed' ? 'success' : 'danger'}">${s.status}</span></td>
<td class="table-actions">
${s.status === 'scheduled' ? `<button class="btn btn-danger btn-sm" onclick="cancelSession(${s.id})">Cancel</button>` : ''}
</td>
</tr>`).join('')}
</tbody></table>`;
} catch {
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Error loading sessions.</p></div>';
}
}
async function cancelSession(id) {
if (!confirm('Cancel this session?')) return;
try {
const res = await Api.patch(`/api/v1/calendar/${id}/cancel`, {});
if (res.ok) { toast('Session cancelled.', 'success'); loadSessions(); }
else { const b = await res.json(); toast(b.message || 'Cannot cancel — may be within 24h window.', 'error'); }
} catch { toast('Network error.', 'error'); }
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
// Default date range: today + 30 days
const today = new Date();
const future = new Date(today); future.setDate(future.getDate() + 30);
document.getElementById('date-from').value = today.toISOString().slice(0,10);
document.getElementById('date-to').value = future.toISOString().slice(0,10);
loadSessions();
document.getElementById('filter-btn').addEventListener('click', loadSessions);
document.getElementById('new-session-btn').addEventListener('click', async () => {
try {
const res = await Api.get('/api/v1/clients', { limit: 100 });
if (res.ok) {
const { data } = await res.json();
const sel = document.getElementById('book-client');
sel.innerHTML = '<option value="">Select client…</option>' +
data.map(c => `<option value="${c.clientId}">${c.client?.name || c.clientId}</option>`).join('');
}
} catch {}
document.getElementById('book-modal').style.display = 'flex';
});
document.getElementById('book-modal-close').addEventListener('click', () => {
document.getElementById('book-modal').style.display = 'none';
});
document.getElementById('book-confirm-btn').addEventListener('click', async () => {
const errEl = document.getElementById('book-error');
errEl.style.display = 'none';
const clientId = document.getElementById('book-client').value;
const startAt = document.getElementById('book-start').value;
const endAt = document.getElementById('book-end').value;
if (!clientId || !startAt || !endAt) { errEl.textContent = 'All fields required.'; errEl.style.display = 'block'; return; }
try {
const res = await Api.post('/api/v1/calendar', { clientId, startAt, endAt, notes: document.getElementById('book-notes').value || null });
if (res.ok) {
toast('Session booked.', 'success');
document.getElementById('book-modal').style.display = 'none';
loadSessions();
} else { const b = await res.json(); errEl.textContent = b.message || 'Failed.'; errEl.style.display = 'block'; }
} catch { errEl.textContent = 'Network error.'; errEl.style.display = 'block'; }
});
});
</script>
</body>
</html>
+106
View File
@@ -0,0 +1,106 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Categories — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">Video Categories</h1>
</div>
<div class="card" style="max-width:480px;margin-bottom:var(--space-8);">
<form id="add-form" novalidate>
<div class="form-group">
<label class="form-label" for="new-name">New Category</label>
<div class="input-row">
<input class="form-input" type="text" id="new-name" placeholder="e.g. Upper Body" maxlength="60" required>
<button class="btn btn-primary" type="submit">Add</button>
</div>
</div>
<div id="add-error" class="form-error" style="display:none;"></div>
</form>
</div>
<div id="cat-list">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
let _categories = [];
async function loadCategories() {
const el = document.getElementById('cat-list');
try {
const res = await Api.get('/api/v1/categories');
if (!res.ok) throw new Error();
const { data } = await res.json();
_categories = data;
if (!data.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No categories yet.</p></div>'; return; }
el.innerHTML = `<table class="table"><thead><tr><th>Name</th><th>Videos</th><th></th></tr></thead><tbody>
${data.map(c => `<tr>
<td>${c.name}</td>
<td>${c.videoCount ?? '—'}</td>
<td><button class="btn btn-danger btn-sm" onclick="deleteCategory(${c.id})">Delete</button></td>
</tr>`).join('')}
</tbody></table>`;
} catch {
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>';
}
}
async function deleteCategory(id) {
if (!confirm('Delete this category? Videos will be uncategorised.')) return;
try {
const res = await Api.del(`/api/v1/categories/${id}`);
if (res.ok) { toast('Category deleted.', 'success'); loadCategories(); }
else { const b = await res.json(); toast(b.message || 'Failed.', 'error'); }
} catch { toast('Network error.', 'error'); }
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
loadCategories();
document.getElementById('add-form').addEventListener('submit', async (e) => {
e.preventDefault();
const errEl = document.getElementById('add-error');
errEl.style.display = 'none';
const name = document.getElementById('new-name').value.trim();
if (!name) return;
try {
const res = await Api.post('/api/v1/categories', { name });
if (res.ok) {
document.getElementById('new-name').value = '';
toast('Category added.', 'success');
loadCategories();
} else {
const b = await res.json();
errEl.textContent = b.message || 'Failed.'; errEl.style.display = 'block';
}
} catch { errEl.textContent = 'Network error.'; errEl.style.display = 'block'; }
});
});
</script>
</body>
</html>
+180
View File
@@ -0,0 +1,180 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Client Profile — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title" id="client-name">Client</h1>
<a href="/clients.html" class="btn btn-ghost">Back</a>
</div>
<div class="tabs" style="margin-bottom:var(--space-6);">
<button class="tab active" data-tab="workouts">Workouts</button>
<button class="tab" data-tab="notes">Coach Notes</button>
</div>
<!-- Workouts tab -->
<div id="tab-workouts">
<div class="page-header" style="margin-bottom:var(--space-4);">
<h2 class="card-title">Assigned Workouts</h2>
<button class="btn btn-primary btn-sm" id="assign-btn">Assign Workout</button>
</div>
<div id="client-workouts">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
</div>
<!-- Notes tab -->
<div id="tab-notes" style="display:none;">
<div class="card" style="max-width:600px;">
<div class="form-group">
<label class="form-label" for="coach-notes">Coach Notes (private)</label>
<textarea class="form-input" id="coach-notes" rows="8" maxlength="5000"></textarea>
</div>
<button class="btn btn-primary" id="save-notes-btn">Save Notes</button>
</div>
</div>
<!-- Assign workout modal -->
<div class="modal-overlay" id="assign-modal" style="display:none;">
<div class="modal">
<div class="modal-header">
<h2 class="modal-title">Assign Workout</h2>
<button class="modal-close" id="assign-modal-close">&times;</button>
</div>
<select class="form-select" id="assign-workout-select" style="margin-bottom:var(--space-4);">
<option value="">Select a workout…</option>
</select>
<div class="form-group">
<label class="form-label" for="assign-due">Due Date</label>
<input class="form-input" type="date" id="assign-due">
</div>
<button class="btn btn-primary" id="assign-confirm-btn">Assign</button>
</div>
</div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
const params = new URLSearchParams(window.location.search);
const clientId = params.get('id');
async function loadClientWorkouts() {
const el = document.getElementById('client-workouts');
try {
const res = await Api.get(`/api/v1/clients/${clientId}/workouts`);
if (!res.ok) throw new Error();
const { data } = await res.json();
if (!data.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No workouts assigned.</p></div>'; return; }
el.innerHTML = `<table class="table"><thead><tr><th>Workout</th><th>Status</th><th>Due</th><th></th></tr></thead><tbody>
${data.map(cw => `<tr>
<td>${cw.workout?.name || '—'}</td>
<td><span class="badge badge-${cw.status === 'completed' ? 'success' : 'default'}">${cw.status}</span></td>
<td>${cw.dueDate ? new Date(cw.dueDate).toLocaleDateString() : '—'}</td>
<td><button class="btn btn-danger btn-sm" onclick="removeWorkout(${cw.id})">Remove</button></td>
</tr>`).join('')}
</tbody></table>`;
} catch { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; }
}
async function removeWorkout(cwId) {
if (!confirm('Remove this workout assignment?')) return;
try {
const res = await Api.del(`/api/v1/clients/workouts/${cwId}`);
if (res.ok) { toast('Removed.', 'success'); loadClientWorkouts(); }
else { const b = await res.json(); toast(b.message || 'Failed.', 'error'); }
} catch { toast('Network error.', 'error'); }
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
if (!clientId) { window.location.href = '/clients.html'; return; }
// Load client info
try {
const res = await Api.get(`/api/v1/clients/${clientId}`);
if (res.ok) {
const { data } = await res.json();
document.getElementById('client-name').textContent = data.client?.name || 'Client';
document.title = `${data.client?.name || 'Client'} — VitFit`;
if (data.coachNotes) document.getElementById('coach-notes').value = data.coachNotes;
}
} catch {}
loadClientWorkouts();
// Tabs
document.querySelectorAll('.tab').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
btn.classList.add('active');
document.getElementById('tab-workouts').style.display = btn.dataset.tab === 'workouts' ? '' : 'none';
document.getElementById('tab-notes').style.display = btn.dataset.tab === 'notes' ? '' : 'none';
});
});
// Save notes
document.getElementById('save-notes-btn').addEventListener('click', async () => {
const notes = document.getElementById('coach-notes').value.trim();
try {
const res = await Api.patch(`/api/v1/clients/${clientId}`, { coachNotes: notes });
if (res.ok) toast('Notes saved.', 'success');
else { const b = await res.json(); toast(b.message || 'Failed.', 'error'); }
} catch { toast('Network error.', 'error'); }
});
// Assign workout
document.getElementById('assign-btn').addEventListener('click', async () => {
try {
const res = await Api.get('/api/v1/workouts', { limit: 100 });
if (res.ok) {
const { data } = await res.json();
const sel = document.getElementById('assign-workout-select');
sel.innerHTML = '<option value="">Select a workout…</option>' +
data.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
}
} catch {}
document.getElementById('assign-modal').style.display = 'flex';
});
document.getElementById('assign-modal-close').addEventListener('click', () => {
document.getElementById('assign-modal').style.display = 'none';
});
document.getElementById('assign-confirm-btn').addEventListener('click', async () => {
const workoutId = document.getElementById('assign-workout-select').value;
const dueDate = document.getElementById('assign-due').value;
if (!workoutId) { toast('Select a workout.', 'error'); return; }
try {
const res = await Api.post(`/api/v1/clients/${clientId}/workouts`, { workoutId, dueDate: dueDate || null });
if (res.ok) {
toast('Workout assigned.', 'success');
document.getElementById('assign-modal').style.display = 'none';
loadClientWorkouts();
} else { const b = await res.json(); toast(b.message || 'Failed.', 'error'); }
} catch { toast('Network error.', 'error'); }
});
});
</script>
</body>
</html>
+93
View File
@@ -0,0 +1,93 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clients — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">Clients</h1>
</div>
<div class="filter-bar">
<input class="form-input filter-search" type="search" id="search" placeholder="Search clients…">
</div>
<div id="client-list">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
<div id="pagination" class="pagination"></div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
let _page = 1, _search = '';
async function loadClients() {
const el = document.getElementById('client-list');
try {
const res = await Api.get('/api/v1/clients', { page: _page, limit: 20, search: _search });
if (!res.ok) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; return; }
const { data, meta } = await res.json();
if (!data.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No clients yet.</p></div>'; return; }
el.innerHTML = `<table class="table"><thead><tr><th>Name</th><th>Email</th><th>Since</th><th></th></tr></thead><tbody>
${data.map(c => `<tr>
<td><a href="/client-profile.html?id=${c.clientId}">${c.client?.name || '—'}</a></td>
<td>${c.client?.email || '—'}</td>
<td>${c.createdAt ? new Date(c.createdAt).toLocaleDateString() : '—'}</td>
<td class="table-actions">
<a href="/client-profile.html?id=${c.clientId}" class="btn btn-ghost btn-sm">Profile</a>
</td>
</tr>`).join('')}
</tbody></table>`;
renderPagination(meta);
} catch {
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Error loading clients.</p></div>';
}
}
function renderPagination(meta) {
const el = document.getElementById('pagination');
if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; }
el.innerHTML = `
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} onclick="changePage(${_page - 1})">Previous</button>
<span class="pagination-info">Page ${meta.page} of ${meta.totalPages}</span>
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} onclick="changePage(${_page + 1})">Next</button>`;
}
function changePage(p) { _page = p; loadClients(); }
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
loadClients();
let debounce;
document.getElementById('search').addEventListener('input', (e) => {
clearTimeout(debounce);
debounce = setTimeout(() => { _search = e.target.value; _page = 1; loadClients(); }, 300);
});
});
</script>
</body>
</html>
+144
View File
@@ -0,0 +1,144 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create CrossFit WOD — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">Create CrossFit WOD</h1>
<a href="/crossfit.html" class="btn btn-ghost">Back</a>
</div>
<form id="wod-form" novalidate style="max-width:600px;">
<div class="card" style="margin-bottom:var(--space-6);">
<div class="form-group">
<label class="form-label" for="name">WOD Name <span class="required">*</span></label>
<input class="form-input" type="text" id="name" maxlength="120" required>
</div>
<div class="form-group">
<label class="form-label" for="workout-date">Date</label>
<input class="form-input" type="date" id="workout-date">
</div>
<div class="form-group">
<label class="form-label" for="wod-type">WOD Type</label>
<select class="form-select" id="wod-type">
<option value="">— select —</option>
<option value="amrap">AMRAP</option>
<option value="fortime">For Time</option>
<option value="emom">EMOM</option>
<option value="chipper">Chipper</option>
<option value="ladder">Ladder</option>
<option value="custom">Custom</option>
</select>
</div>
<div class="form-group" id="duration-group">
<label class="form-label" for="duration">Duration (minutes)</label>
<input class="form-input" type="number" id="duration" min="1" placeholder="e.g. 20">
</div>
<div class="form-group">
<label class="form-label" for="notes">Notes / Scaling</label>
<textarea class="form-input" id="notes" rows="3" maxlength="2000"></textarea>
</div>
</div>
<div class="card" style="margin-bottom:var(--space-6);">
<div class="card-header">
<h2 class="card-title">Workout Items</h2>
<button class="btn btn-secondary btn-sm" type="button" id="add-item-btn">+ Add Item</button>
</div>
<p class="form-hint" style="margin-bottom:var(--space-4);">Each item is one line shown on the display (e.g. "21 Thrusters 95/65 lb").</p>
<div id="items-list"></div>
</div>
<div id="form-error" class="form-error" style="display:none;"></div>
<button class="btn btn-primary" type="submit" id="save-btn">Save WOD</button>
</form>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
let _items = [];
function renderItems() {
const el = document.getElementById('items-list');
if (!_items.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No items yet.</p></div>'; return; }
el.innerHTML = _items.map((item, i) => `
<div class="slot-row" data-idx="${i}">
<input class="form-input" type="text" value="${item.text?.replace(/"/g, '&quot;') || ''}" placeholder="e.g. 21 Thrusters 95/65 lb" maxlength="200"
onchange="_items[${i}].text = this.value" style="flex:1;">
<button class="btn btn-danger btn-sm" type="button" onclick="removeItem(${i})">Remove</button>
</div>`).join('');
}
function removeItem(idx) { _items.splice(idx, 1); renderItems(); }
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
renderItems();
document.getElementById('add-item-btn').addEventListener('click', () => {
_items.push({ type: 'text', text: '' });
renderItems();
// Focus last input
const inputs = document.querySelectorAll('#items-list .form-input');
inputs[inputs.length - 1]?.focus();
});
document.getElementById('wod-form').addEventListener('submit', async (e) => {
e.preventDefault();
const errEl = document.getElementById('form-error');
errEl.style.display = 'none';
const btn = document.getElementById('save-btn');
const name = document.getElementById('name').value.trim();
if (!name) { errEl.textContent = 'Name is required.'; errEl.style.display = 'block'; return; }
// Sync any open inputs
document.querySelectorAll('#items-list .form-input').forEach((inp, i) => { if (_items[i]) _items[i].text = inp.value.trim(); });
const filteredItems = _items.filter(it => it.text);
const payload = {
name,
workoutDate: document.getElementById('workout-date').value || null,
wodType: document.getElementById('wod-type').value || null,
durationMin: document.getElementById('duration').value ? +document.getElementById('duration').value : null,
notes: document.getElementById('notes').value.trim() || null,
workoutItems: filteredItems,
};
btn.disabled = true; btn.textContent = 'Saving…';
try {
const res = await Api.post('/api/v1/crossfit-workouts', payload);
if (res.ok) {
toast('WOD saved!', 'success');
setTimeout(() => window.location.href = '/crossfit.html', 800);
} else {
const b = await res.json();
errEl.textContent = b.message || 'Failed.'; errEl.style.display = 'block';
}
} catch { errEl.textContent = 'Network error.'; errEl.style.display = 'block'; }
finally { btn.disabled = false; btn.textContent = 'Save WOD'; }
});
});
</script>
</body>
</html>
+179
View File
@@ -0,0 +1,179 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Timer — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">Create Timer</h1>
<a href="/timers.html" class="btn btn-ghost">Back</a>
</div>
<form id="timer-form" novalidate style="max-width:560px;">
<div class="card" style="margin-bottom:var(--space-6);">
<div class="form-group">
<label class="form-label" for="name">Timer Name <span class="required">*</span></label>
<input class="form-input" type="text" id="name" maxlength="80" required>
</div>
<div class="form-group">
<label class="form-label" for="timer-type">Type <span class="required">*</span></label>
<select class="form-select" id="timer-type">
<option value="interval">Interval (Work / Rest)</option>
<option value="amrap">AMRAP</option>
<option value="emom">EMOM</option>
<option value="tabata">Tabata</option>
</select>
</div>
</div>
<!-- Interval -->
<div class="card timer-config" id="config-interval" style="margin-bottom:var(--space-6);">
<div class="grid-2">
<div class="form-group">
<label class="form-label">Exercises per Set</label>
<input class="form-input" type="number" id="exerciseCount" min="1" value="1">
</div>
<div class="form-group">
<label class="form-label">Sets</label>
<input class="form-input" type="number" id="sets" min="1" value="3">
</div>
<div class="form-group">
<label class="form-label">Work (seconds)</label>
<input class="form-input" type="number" id="workSec" min="1" value="40">
</div>
<div class="form-group">
<label class="form-label">Rest (seconds)</label>
<input class="form-input" type="number" id="restSec" min="0" value="20">
</div>
<div class="form-group">
<label class="form-label">Move time (seconds)</label>
<input class="form-input" type="number" id="moveSec" min="0" value="10">
<p class="form-hint">Time between exercises to transition.</p>
</div>
<div class="form-group">
<label class="form-label">Laps</label>
<input class="form-input" type="number" id="laps" min="1" value="1">
</div>
</div>
</div>
<!-- AMRAP -->
<div class="card timer-config" id="config-amrap" style="margin-bottom:var(--space-6);display:none;">
<div class="form-group">
<label class="form-label">Duration (minutes)</label>
<input class="form-input" type="number" id="amrapDuration" min="1" value="10">
</div>
</div>
<!-- EMOM -->
<div class="card timer-config" id="config-emom" style="margin-bottom:var(--space-6);display:none;">
<div class="grid-2">
<div class="form-group">
<label class="form-label">Rounds</label>
<input class="form-input" type="number" id="emomRounds" min="1" value="10">
</div>
<div class="form-group">
<label class="form-label">Exercises per round</label>
<input class="form-input" type="number" id="emomExercises" min="1" value="1">
</div>
</div>
</div>
<!-- Tabata -->
<div class="card timer-config" id="config-tabata" style="margin-bottom:var(--space-6);display:none;">
<div class="grid-2">
<div class="form-group">
<label class="form-label">Rounds</label>
<input class="form-input" type="number" id="tabataRounds" min="1" value="8">
</div>
<div class="form-group">
<label class="form-label">Work (seconds)</label>
<input class="form-input" type="number" id="tabataWork" min="1" value="20">
</div>
<div class="form-group">
<label class="form-label">Rest (seconds)</label>
<input class="form-input" type="number" id="tabataRest" min="0" value="10">
</div>
</div>
</div>
<div id="form-error" class="form-error" style="display:none;"></div>
<button class="btn btn-primary" type="submit" id="save-btn">Save Timer</button>
</form>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
function showConfig(type) {
document.querySelectorAll('.timer-config').forEach(el => el.style.display = 'none');
const el = document.getElementById(`config-${type}`);
if (el) el.style.display = '';
}
function buildConfig(type) {
if (type === 'interval') return {
exerciseCount: +document.getElementById('exerciseCount').value,
sets: +document.getElementById('sets').value,
workSec: +document.getElementById('workSec').value,
restSec: +document.getElementById('restSec').value,
moveSec: +document.getElementById('moveSec').value,
laps: +document.getElementById('laps').value,
};
if (type === 'amrap') return { durationMin: +document.getElementById('amrapDuration').value };
if (type === 'emom') return { rounds: +document.getElementById('emomRounds').value, exercisesPerRound: +document.getElementById('emomExercises').value };
if (type === 'tabata') return { rounds: +document.getElementById('tabataRounds').value, workSec: +document.getElementById('tabataWork').value, restSec: +document.getElementById('tabataRest').value };
return {};
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
const typeEl = document.getElementById('timer-type');
typeEl.addEventListener('change', () => showConfig(typeEl.value));
showConfig(typeEl.value);
document.getElementById('timer-form').addEventListener('submit', async (e) => {
e.preventDefault();
const errEl = document.getElementById('form-error');
errEl.style.display = 'none';
const btn = document.getElementById('save-btn');
const type = typeEl.value;
const name = document.getElementById('name').value.trim();
if (!name) { errEl.textContent = 'Name is required.'; errEl.style.display = 'block'; return; }
btn.disabled = true; btn.textContent = 'Saving…';
try {
const res = await Api.post('/api/v1/timers', { name, timerType: type, config: buildConfig(type) });
if (res.ok) {
toast('Timer saved!', 'success');
setTimeout(() => window.location.href = '/timers.html', 800);
} else {
const b = await res.json();
errEl.textContent = b.message || 'Failed.'; errEl.style.display = 'block';
}
} catch { errEl.textContent = 'Network error.'; errEl.style.display = 'block'; }
finally { btn.disabled = false; btn.textContent = 'Save Timer'; }
});
});
</script>
</body>
</html>
+179
View File
@@ -0,0 +1,179 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Workout — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">Create Workout</h1>
<a href="/workouts.html" class="btn btn-ghost">Back</a>
</div>
<form id="workout-form" novalidate style="max-width:640px;">
<div class="card" style="margin-bottom:var(--space-6);">
<div class="form-group">
<label class="form-label" for="name">Workout Name <span class="required">*</span></label>
<input class="form-input" type="text" id="name" maxlength="120" required>
</div>
<div class="form-group">
<label class="form-label" for="workout-date">Date</label>
<input class="form-input" type="date" id="workout-date">
</div>
<div class="form-group">
<label class="form-label" for="notes">Notes</label>
<textarea class="form-input" id="notes" rows="3" maxlength="2000"></textarea>
</div>
</div>
<div class="card" style="margin-bottom:var(--space-6);">
<div class="card-header">
<h2 class="card-title">Exercises</h2>
<button class="btn btn-secondary btn-sm" type="button" id="add-slot-btn">+ Add Exercise</button>
</div>
<div id="slots-list"></div>
</div>
<div id="form-error" class="form-error" style="display:none;"></div>
<button class="btn btn-primary" type="submit" id="save-btn">Save Workout</button>
</form>
<!-- Video picker modal -->
<div class="modal-overlay" id="video-modal" style="display:none;">
<div class="modal">
<div class="modal-header">
<h2 class="modal-title">Pick a Video</h2>
<button class="modal-close" id="modal-close">&times;</button>
</div>
<input class="form-input" type="search" id="modal-search" placeholder="Search videos…" style="margin-bottom:var(--space-4);">
<div id="modal-video-list" class="modal-scroll"></div>
</div>
</div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
let _slots = [];
let _videos = [];
let _pickingSlotIdx = null;
function renderSlots() {
const el = document.getElementById('slots-list');
if (!_slots.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No exercises yet.</p></div>'; return; }
el.innerHTML = _slots.map((s, i) => `
<div class="slot-row" data-idx="${i}">
<div class="slot-pick">
${s.video
? `<span class="slot-video-name">${s.video.description}</span>`
: `<button class="btn btn-ghost btn-sm" type="button" onclick="openPicker(${i})">Pick Video</button>`}
</div>
<input class="form-input slot-reps" type="number" placeholder="Reps" min="1" value="${s.reps || ''}" onchange="updateReps(${i}, this.value)" style="width:90px;">
<input class="form-input slot-sets" type="number" placeholder="Sets" min="1" value="${s.sets || ''}" onchange="updateSets(${i}, this.value)" style="width:90px;">
<button class="btn btn-danger btn-sm" type="button" onclick="removeSlot(${i})">Remove</button>
</div>`).join('');
}
function openPicker(idx) {
_pickingSlotIdx = idx;
document.getElementById('video-modal').style.display = 'flex';
loadModalVideos('');
}
async function loadModalVideos(search) {
const el = document.getElementById('modal-video-list');
el.innerHTML = '<p class="text-secondary">Loading…</p>';
try {
const res = await Api.get('/api/v1/videos', { limit: 50, search });
if (!res.ok) throw new Error();
const { data } = await res.json();
if (!data.length) { el.innerHTML = '<p class="text-secondary">No videos found.</p>'; return; }
el.innerHTML = data.map(v => `
<div class="modal-video-item" onclick="selectVideo(${v.id}, '${v.description?.replace(/'/g, "\\'")}')">
${v.description || 'Untitled'}
</div>`).join('');
} catch { el.innerHTML = '<p class="text-secondary">Failed to load.</p>'; }
}
function selectVideo(id, description) {
if (_pickingSlotIdx === null) return;
_slots[_pickingSlotIdx].video = { id, description };
document.getElementById('video-modal').style.display = 'none';
renderSlots();
}
function updateReps(idx, val) { _slots[idx].reps = val ? parseInt(val) : null; }
function updateSets(idx, val) { _slots[idx].sets = val ? parseInt(val) : null; }
function removeSlot(idx) { _slots.splice(idx, 1); renderSlots(); }
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
renderSlots();
document.getElementById('add-slot-btn').addEventListener('click', () => {
_slots.push({ video: null, reps: null, sets: null });
renderSlots();
});
document.getElementById('modal-close').addEventListener('click', () => {
document.getElementById('video-modal').style.display = 'none';
});
let debounce;
document.getElementById('modal-search').addEventListener('input', (e) => {
clearTimeout(debounce);
debounce = setTimeout(() => loadModalVideos(e.target.value), 300);
});
document.getElementById('workout-form').addEventListener('submit', async (e) => {
e.preventDefault();
const errEl = document.getElementById('form-error');
errEl.style.display = 'none';
const btn = document.getElementById('save-btn');
const name = document.getElementById('name').value.trim();
if (!name) { errEl.textContent = 'Name is required.'; errEl.style.display = 'block'; return; }
const payload = {
name,
workoutDate: document.getElementById('workout-date').value || null,
notes: document.getElementById('notes').value.trim() || null,
slots: _slots.filter(s => s.video).map((s, i) => ({
videoId: s.video.id, order: i, reps: s.reps, sets: s.sets
})),
};
btn.disabled = true; btn.textContent = 'Saving…';
try {
const res = await Api.post('/api/v1/workouts', payload);
if (res.ok) {
toast('Workout created!', 'success');
setTimeout(() => { window.location.href = '/workouts.html'; }, 1000);
} else {
const b = await res.json();
errEl.textContent = b.message || 'Failed to save.'; errEl.style.display = 'block';
}
} catch { errEl.textContent = 'Network error.'; errEl.style.display = 'block'; }
finally { btn.disabled = false; btn.textContent = 'Save Workout'; }
});
});
</script>
</body>
</html>
+58
View File
@@ -0,0 +1,58 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WOD Display — VitFit</title>
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/display.css">
</head>
<body>
<div class="display-container phase-idle" id="timer-container">
<div class="display-status-bar">
<span class="display-status-label" id="display-cf-name">Loading…</span>
<span class="display-status-right" id="display-cf-date"></span>
</div>
<div class="display-main">
<ul class="display-crossfit-list" id="display-cf-list"></ul>
</div>
<div class="touch-zone touch-zone-left"></div>
<div class="touch-zone touch-zone-right"></div>
</div>
<div id="display-offline-banner" class="display-offline-banner">Offline — last known data shown</div>
<script src="/js/core.js"></script>
<script src="/js/display.js"></script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
const params = new URLSearchParams(window.location.search);
const id = params.get('id');
if (!id) { document.getElementById('display-cf-name').textContent = 'No WOD selected.'; return; }
Display.startKeepAlive();
try {
const res = await fetch('/api/v1/org/branding/public');
if (res.ok) { const { data } = await res.json(); Display.applyBranding(data); }
} catch {}
async function load() {
try {
const jwt = Auth.getJwt();
const headers = jwt ? { Authorization: `Bearer ${jwt}` } : {};
const res = await fetch(`/api/v1/crossfit-workouts/${id}`, { headers });
if (!res.ok) return;
const { data } = await res.json();
Display.renderCrossfit(data);
} catch { Display.setOffline(true); }
}
load();
setInterval(load, 30000);
});
</script>
</body>
</html>
+94
View File
@@ -0,0 +1,94 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CrossFit WODs — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">CrossFit WODs</h1>
<a href="/create-crossfit.html" class="btn btn-primary">Create WOD</a>
</div>
<div id="wod-list">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
<div id="pagination" class="pagination"></div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
let _page = 1;
async function loadWods() {
const el = document.getElementById('wod-list');
try {
const res = await Api.get('/api/v1/crossfit-workouts', { page: _page, limit: 20 });
if (!res.ok) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; return; }
const { data, meta } = await res.json();
if (!data.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No WODs yet.</p><a href="/create-crossfit.html" class="btn btn-primary">Create one</a></div>'; return; }
el.innerHTML = `<table class="table"><thead><tr><th>Name</th><th>Date</th><th>Type</th><th></th></tr></thead><tbody>
${data.map(w => `<tr>
<td>${w.name}</td>
<td>${w.workoutDate ? new Date(w.workoutDate).toLocaleDateString() : '—'}</td>
<td>${w.wodType || '—'}</td>
<td class="table-actions">
<a href="/crossfit-display.html?id=${w.id}" class="btn btn-ghost btn-sm" target="_blank">Display</a>
<button class="btn btn-danger btn-sm" onclick="deleteWod(${w.id})">Delete</button>
</td>
</tr>`).join('')}
</tbody></table>`;
renderPagination(meta);
} catch {
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Error loading WODs.</p></div>';
}
}
function renderPagination(meta) {
const el = document.getElementById('pagination');
if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; }
el.innerHTML = `
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} onclick="changePage(${_page - 1})">Previous</button>
<span class="pagination-info">Page ${meta.page} of ${meta.totalPages}</span>
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} onclick="changePage(${_page + 1})">Next</button>`;
}
function changePage(p) { _page = p; loadWods(); }
async function deleteWod(id) {
if (!confirm('Delete this WOD?')) return;
try {
const res = await Api.del(`/api/v1/crossfit-workouts/${id}`);
if (res.ok) { toast('WOD deleted.', 'success'); loadWods(); }
else { const b = await res.json(); toast(b.message || 'Failed.', 'error'); }
} catch { toast('Network error.', 'error'); }
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
loadWods();
});
</script>
</body>
</html>
+119
View File
@@ -0,0 +1,119 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer" aria-label="Navigation">
<ul class="nav-list" id="nav-list"></ul>
</nav>
<main class="main-content">
<h1 class="page-title">Dashboard</h1>
<div id="today-workout" class="card" style="margin-bottom:var(--space-6);">
<div class="card-header">
<h2 class="card-title">Today's Workout</h2>
<a href="/workouts.html" class="btn btn-ghost btn-sm">View All</a>
</div>
<div id="today-workout-body">
<div class="empty-state">
<p class="empty-state-text">No workout scheduled for today.</p>
<a href="/create-workout.html" class="btn btn-primary">Create Workout</a>
</div>
</div>
</div>
<div class="grid-2">
<div class="card">
<div class="card-header">
<h2 class="card-title">Active Timer</h2>
<a href="/timers.html" class="btn btn-ghost btn-sm">View All</a>
</div>
<div id="active-timer-body">
<div class="empty-state">
<p class="empty-state-text">No timer running.</p>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h2 class="card-title">Quick Links</h2>
</div>
<ul class="quick-links">
<li><a href="/upload-video.html" class="btn btn-secondary btn-full">Upload Video</a></li>
<li><a href="/create-workout.html" class="btn btn-secondary btn-full">Create Workout</a></li>
<li><a href="/create-timer.html" class="btn btn-secondary btn-full">Create Timer</a></li>
<li><a href="/create-crossfit.html" class="btn btn-secondary btn-full">Create CrossFit WOD</a></li>
</ul>
</div>
</div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box">
<p>Your session has expired.</p>
<a href="/" class="btn btn-primary">Sign In Again</a>
</div>
</div>
<script src="/js/core.js"></script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
// Load today's workout
try {
const res = await Api.get('/api/v1/workouts/today');
if (res.ok) {
const { data } = await res.json();
if (data?.length) {
const w = data[0];
document.getElementById('today-workout-body').innerHTML = `
<div class="card-body">
<p class="text-lg font-bold">${w.name}</p>
<p class="text-secondary">${w.videos?.length ?? 0} exercises</p>
<div class="mt-4 flex gap-3">
<a href="/workout-view.html?id=${w.id}" class="btn btn-primary btn-sm">View</a>
<a href="/workout-display.html?id=${w.id}" class="btn btn-ghost btn-sm" target="_blank">Display</a>
</div>
</div>`;
}
}
} catch {}
// Load active timer session
try {
const res = await Api.get('/api/v1/timers/session/active');
if (res.ok) {
const { data } = await res.json();
if (data) {
document.getElementById('active-timer-body').innerHTML = `
<div class="card-body">
<p class="text-lg font-bold">${data.timerName || 'Timer'}</p>
<p class="badge badge-success">Running</p>
<div class="mt-4 flex gap-3">
<a href="/timer-display.html?session=${data.sessionId}" class="btn btn-primary btn-sm" target="_blank">Display</a>
</div>
</div>`;
}
}
} catch {}
});
</script>
</body>
</html>
+109
View File
@@ -0,0 +1,109 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VitFit — Sign In</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<div class="login-page">
<div class="card login-card">
<div class="login-logo">
<img id="banner-logo" src="/icons/icon-192.png" alt="VitFit" style="width:64px;height:64px;" onerror="this.style.display='none'">
<h1 id="app-name" class="login-title">VitFit</h1>
</div>
<form id="login-form" novalidate>
<div class="form-group">
<label class="form-label" for="email">Email</label>
<input class="form-input" type="email" id="email" name="email" autocomplete="email" required>
</div>
<div class="form-group">
<label class="form-label" for="password">Password</label>
<input class="form-input" type="password" id="password" name="password" autocomplete="current-password" required>
</div>
<div id="login-error" class="form-error" style="display:none;"></div>
<button class="btn btn-primary btn-full" type="submit" id="login-btn">Sign In</button>
</form>
</div>
</div>
<script src="/js/core.js"></script>
<script>
(async () => {
// If already authenticated, skip to dashboard
const user = Page.currentUser();
if (user) {
window.location.href = user.role === 'Client' ? '/my-workouts.html' : '/dashboard.html';
return;
}
// Try kiosk device token
const ok = await Auth.tryDeviceLogin();
if (ok) {
const u = Page.currentUser();
window.location.href = u?.role === 'Client' ? '/my-workouts.html' : '/dashboard.html';
return;
}
// Load org branding without auth
try {
const res = await fetch('/api/v1/org/branding/public');
if (res.ok) {
const { data } = await res.json();
Branding.apply(data);
const titleEl = document.getElementById('app-name');
if (titleEl && data.appName) titleEl.textContent = data.appName;
const logoEl = document.getElementById('banner-logo');
if (logoEl && data.logoPath) { logoEl.src = data.logoPath; logoEl.style.display = ''; }
}
} catch {}
const form = document.getElementById('login-form');
const errEl = document.getElementById('login-error');
const loginBtn = document.getElementById('login-btn');
form.addEventListener('submit', async (e) => {
e.preventDefault();
errEl.style.display = 'none';
loginBtn.disabled = true;
loginBtn.textContent = 'Signing in…';
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value;
try {
const res = await fetch('/api/v1/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const body = await res.json();
if (!res.ok) {
errEl.textContent = body.message || 'Sign in failed.';
errEl.style.display = 'block';
return;
}
Auth.setJwt(body.data.jwt);
if (body.data.deviceToken) Auth.setDeviceToken(body.data.deviceToken);
const u = Page.currentUser();
window.location.href = u?.role === 'Client' ? '/my-workouts.html' : '/dashboard.html';
} catch {
errEl.textContent = 'Network error. Please try again.';
errEl.style.display = 'block';
} finally {
loginBtn.disabled = false;
loginBtn.textContent = 'Sign In';
}
});
})();
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').catch(() => {});
}
</script>
</body>
</html>
+256
View File
@@ -0,0 +1,256 @@
/* VitFit core.js — loaded on every page */
'use strict';
// ── Auth ──────────────────────────────────────────────────────────────────────
const Auth = (() => {
const JWT_KEY = 'vf_jwt';
const DEVICE_KEY = 'vf_device';
function getJwt() { return localStorage.getItem(JWT_KEY); }
function setJwt(t) { localStorage.setItem(JWT_KEY, t); }
function getDeviceToken() { return localStorage.getItem(DEVICE_KEY); }
function setDeviceToken(t) { localStorage.setItem(DEVICE_KEY, t); }
function clearSession() { localStorage.removeItem(JWT_KEY); localStorage.removeItem(DEVICE_KEY); }
function decodeJwt(token) {
try {
return JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));
} catch { return null; }
}
function isTokenExpiringSoon(token) {
const payload = decodeJwt(token);
if (!payload?.exp) return false;
return (payload.exp * 1000 - Date.now()) < 60 * 60 * 1000; // < 1 hour
}
async function tryDeviceLogin() {
const deviceToken = getDeviceToken();
if (!deviceToken) return false;
try {
const res = await fetch('/api/v1/auth/device-login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ deviceToken }),
});
if (!res.ok) return false;
const { data } = await res.json();
setJwt(data.jwt);
if (data.deviceToken) setDeviceToken(data.deviceToken);
return true;
} catch { return false; }
}
async function autoRefreshIfNeeded() {
const token = getJwt();
if (!token || !isTokenExpiringSoon(token)) return;
try {
const res = await fetch('/api/v1/auth/refresh-token', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
});
if (res.ok) {
const { data } = await res.json();
setJwt(data.jwt);
}
} catch {}
}
return { getJwt, setJwt, getDeviceToken, setDeviceToken, clearSession, decodeJwt, isTokenExpiringSoon, tryDeviceLogin, autoRefreshIfNeeded };
})();
// ── Api ───────────────────────────────────────────────────────────────────────
const Api = (() => {
async function _fetch(url, options = {}, retry = true) {
await Auth.autoRefreshIfNeeded();
const jwt = Auth.getJwt();
const headers = { ...(options.headers || {}) };
if (jwt) headers['Authorization'] = `Bearer ${jwt}`;
if (!(options.body instanceof FormData) && options.body) {
headers['Content-Type'] = 'application/json';
}
const res = await fetch(url, { ...options, headers });
if (res.status === 401 && retry) {
// Try device login once
const refreshed = await Auth.tryDeviceLogin();
if (refreshed) return _fetch(url, options, false);
Page.showSessionExpiredOverlay();
throw new Error('Session expired');
}
return res;
}
const get = (url, params) => _fetch(url + (params ? '?' + new URLSearchParams(params) : ''));
const post = (url, body) => _fetch(url, { method: 'POST', body: JSON.stringify(body) });
const patch = (url, body) => _fetch(url, { method: 'PATCH', body: JSON.stringify(body) });
const put = (url, body) => _fetch(url, { method: 'PUT', body: JSON.stringify(body) });
const del = (url) => _fetch(url, { method: 'DELETE' });
const upload = (url, formData) => _fetch(url, { method: 'POST', body: formData });
return { fetch: _fetch, get, post, patch, put, del, upload };
})();
// ── Nav ───────────────────────────────────────────────────────────────────────
const Nav = (() => {
const NAV_LINKS = [
{ label: 'Dashboard', href: '/dashboard.html', roles: ['Owner', 'Coach'] },
{ label: 'Videos', href: '/videos.html', roles: ['Owner', 'Coach'] },
{ label: 'Workouts', href: '/workouts.html', roles: ['Owner', 'Coach'] },
{ label: 'Timers', href: '/timers.html', roles: ['Owner', 'Coach'] },
{ label: 'CrossFit', href: '/crossfit.html', roles: ['Owner', 'Coach'] },
{ label: 'Clients', href: '/clients.html', roles: ['Owner', 'Coach'], feature: 'client-management' },
{ label: 'Calendar', href: '/calendar.html', roles: ['Owner', 'Coach'], feature: 'calendar' },
{ label: 'My Workouts', href: '/my-workouts.html', roles: ['Client'] },
{ label: 'My Schedule', href: '/my-schedule.html', roles: ['Client'], feature: 'calendar' },
{ label: 'Settings', href: '/settings.html', roles: ['Owner'] },
{ label: 'Audit Log', href: '/audit-log.html', roles: ['Owner'] },
{ label: 'System Admin',href: '/sysadmin.html', roles: ['SystemAdmin'] },
{ label: 'Profile', href: '/profile.html', roles: ['Owner', 'Coach', 'Client', 'SystemAdmin'] },
{ label: 'Log Out', href: '#', action: 'logout', roles: ['Owner', 'Coach', 'Client', 'SystemAdmin'] },
];
function init(currentPage) {
const drawer = document.getElementById('nav-drawer');
const scrim = document.getElementById('drawer-scrim');
const hamb = document.getElementById('nav-hamburger');
const navList = document.getElementById('nav-list');
if (!drawer || !navList) return;
const user = Page.currentUser();
const orgFeatures = (window._orgFeatures || []);
navList.innerHTML = '';
NAV_LINKS.forEach(link => {
if (!link.roles.includes(user?.role)) return;
if (link.feature && !orgFeatures.includes(link.feature)) return;
const li = document.createElement('li');
const a = document.createElement('a');
a.textContent = link.label;
a.href = link.href;
if (link.href === currentPage || window.location.pathname.endsWith(link.href)) {
a.classList.add('active');
}
if (link.action === 'logout') {
a.addEventListener('click', async (e) => {
e.preventDefault();
await Api.post('/api/v1/auth/logout', {}).catch(() => {});
Auth.clearSession();
window.location.href = '/';
});
}
li.appendChild(a);
navList.appendChild(li);
});
hamb?.addEventListener('click', toggle);
scrim?.addEventListener('click', close);
}
function toggle() {
const drawer = document.getElementById('nav-drawer');
const scrim = document.getElementById('drawer-scrim');
drawer?.classList.toggle('open');
scrim?.classList.toggle('open');
}
function close() {
document.getElementById('nav-drawer')?.classList.remove('open');
document.getElementById('drawer-scrim')?.classList.remove('open');
}
return { init, toggle, close };
})();
// ── Branding ──────────────────────────────────────────────────────────────────
const Branding = (() => {
async function load() {
try {
const res = await Api.get('/api/v1/org/branding');
if (!res.ok) return;
const { data } = await res.json();
apply(data);
window._orgFeatures = data.features || [];
// Set app name in banner
const titleEl = document.getElementById('app-name');
if (titleEl && data.appName) titleEl.textContent = data.appName;
// Set logo if present
const logoEl = document.getElementById('banner-logo');
if (logoEl && data.logoPath) { logoEl.src = data.logoPath; logoEl.style.display = ''; }
} catch {}
}
function apply(branding) {
const root = document.documentElement.style;
if (branding.primaryColor) root.setProperty('--color-primary', branding.primaryColor);
if (branding.secondaryColor) root.setProperty('--color-secondary', branding.secondaryColor);
if (branding.workColor) root.setProperty('--color-work', branding.workColor);
if (branding.restColor) root.setProperty('--color-rest', branding.restColor);
if (branding.moveColor) root.setProperty('--color-move', branding.moveColor);
}
return { load, apply };
})();
// ── Page ──────────────────────────────────────────────────────────────────────
const Page = (() => {
function currentUser() {
const token = Auth.getJwt();
if (!token) return null;
return Auth.decodeJwt(token);
}
async function init(allowedRoles) {
let user = currentUser();
if (!user) {
const refreshed = await Auth.tryDeviceLogin();
if (refreshed) { user = currentUser(); }
}
if (!user) {
window.location.href = '/';
return;
}
if (allowedRoles && !allowedRoles.includes(user.role)) {
window.location.href = '/dashboard.html';
return;
}
await Branding.load();
Nav.init(window.location.pathname);
}
function showSessionExpiredOverlay() {
document.getElementById('session-expired-overlay')?.classList.add('visible');
}
return { init, currentUser, showSessionExpiredOverlay };
})();
// ── Toast ─────────────────────────────────────────────────────────────────────
function toast(message, type = 'info', duration = 3000) {
let container = document.getElementById('toast-container');
if (!container) {
container = document.createElement('div');
container.id = 'toast-container';
document.body.appendChild(container);
}
const el = document.createElement('div');
el.className = `toast toast-${type}`;
el.textContent = message;
container.appendChild(el);
setTimeout(() => el.remove(), duration);
}
// ── Back-forward cache (bfcache) re-init ──────────────────────────────────────
window.addEventListener('pageshow', (e) => {
if (e.persisted && window._socketClient) {
// Re-connect socket on bfcache restore
window._socketClient.connect?.();
}
});
+68
View File
@@ -0,0 +1,68 @@
/* VitFit display.js — used by workout-display.html and crossfit-display.html */
'use strict';
const Display = (() => {
let _keepAliveEl = null;
function renderWorkout(workout) {
const nameEl = document.getElementById('display-workout-name');
const dateEl = document.getElementById('display-workout-date');
const listEl = document.getElementById('display-workout-list');
if (nameEl) nameEl.textContent = workout.name || '';
if (dateEl && workout.workoutDate) {
dateEl.textContent = new Date(workout.workoutDate).toLocaleDateString('en-US', { month: 'long', day: 'numeric' });
}
if (listEl) {
listEl.innerHTML = '';
(workout.videos || []).filter(s => s.video).forEach(slot => {
const li = document.createElement('li');
li.className = 'display-workout-item';
li.innerHTML = `
<span class="display-workout-item-name">${slot.video.description || 'Exercise'}</span>
${slot.reps ? `<span class="display-workout-item-reps">${slot.reps} reps</span>` : ''}
`;
listEl.appendChild(li);
});
}
}
function renderCrossfit(workout) {
const nameEl = document.getElementById('display-cf-name');
const dateEl = document.getElementById('display-cf-date');
const listEl = document.getElementById('display-cf-list');
if (nameEl) nameEl.textContent = workout.name || '';
if (dateEl && workout.workoutDate) {
dateEl.textContent = new Date(workout.workoutDate).toLocaleDateString('en-US', { month: 'long', day: 'numeric' });
}
if (listEl) {
listEl.innerHTML = '';
(workout.workoutItems || []).forEach(item => {
const li = document.createElement('li');
li.className = 'display-crossfit-item';
li.textContent = item;
listEl.appendChild(li);
});
}
}
function setOffline(isOffline) {
document.getElementById('display-offline-banner')?.classList.toggle('visible', isOffline);
}
function startKeepAlive() {
if (_keepAliveEl) return;
_keepAliveEl = document.createElement('div');
_keepAliveEl.className = 'keep-alive';
document.body.appendChild(_keepAliveEl);
}
function applyBranding(branding) {
Branding.apply(branding);
}
return { renderWorkout, renderCrossfit, setOffline, startKeepAlive, applyBranding };
})();
+66
View File
@@ -0,0 +1,66 @@
/* VitFit socket-client.js */
'use strict';
class SocketClient {
constructor() {
this._socket = null;
this._reconnectHandlers = [];
this._disconnectHandlers = [];
this._handlers = {};
this._currentRoom = null;
}
connect() {
if (this._socket?.connected) return;
const jwt = Auth.getJwt();
this._socket = io({ auth: { token: jwt }, reconnectionDelay: 1000, reconnectionDelayMax: 10000 });
this._socket.on('connect', () => {
if (this._currentRoom) this._socket.emit('timer:join', { sessionId: this._currentRoom });
this._reconnectHandlers.forEach(cb => cb());
});
this._socket.on('disconnect', (reason) => {
this._disconnectHandlers.forEach(cb => cb(reason));
});
// Re-bind registered handlers to new socket
Object.entries(this._handlers).forEach(([event, handler]) => {
this._socket.on(event, handler);
});
window._socketClient = this;
}
on(event, handler) {
this._handlers[event] = handler;
this._socket?.on(event, handler);
}
emit(event, data) {
this._socket?.emit(event, data);
}
joinRoom(sessionId) {
this._currentRoom = sessionId;
this._socket?.emit('timer:join', { sessionId });
}
leaveRoom(sessionId) {
this._currentRoom = null;
this._socket?.emit('timer:leave', { sessionId });
}
onDisconnect(cb) { this._disconnectHandlers.push(cb); }
onReconnect(cb) { this._reconnectHandlers.push(cb); }
destroy() {
this._socket?.disconnect();
this._socket = null;
this._handlers = {};
this._reconnectHandlers = [];
this._disconnectHandlers = [];
window._socketClient = null;
}
}
+164
View File
@@ -0,0 +1,164 @@
/* VitFit timer-display.js — used by timer-display.html */
'use strict';
const TimerDisplay = (() => {
let _socket = null;
let _sessionId = null;
let _localFallbackRaf = null;
let _localEndTime = null;
let _keepAliveEl = null;
const containerEl = () => document.getElementById('timer-container');
const timerEl = () => document.getElementById('timer-countdown');
const totalEl = () => document.getElementById('timer-total');
const phaseEl = () => document.getElementById('timer-phase-label');
const lapEl = () => document.getElementById('timer-lap');
const exerciseEl = () => document.getElementById('timer-exercise');
const setEl = () => document.getElementById('timer-set');
const overlayEl = () => document.getElementById('timer-overlay');
const overlayTitleEl = () => document.getElementById('timer-overlay-title');
const offlineBanner = () => document.getElementById('display-offline-banner');
const localIndicator = () => document.getElementById('display-local-indicator');
function init(sessionId) {
_sessionId = sessionId;
_socket = new SocketClient();
_socket.onDisconnect(() => {
offlineBanner()?.classList.add('visible');
if (_localEndTime) startLocalFallback(_localEndTime);
});
_socket.onReconnect(async () => {
offlineBanner()?.classList.remove('visible');
localIndicator()?.classList.remove('visible');
stopLocalFallback();
// Re-sync state from server
const res = await Api.get(`/api/v1/timers/session/${_sessionId}`).catch(() => null);
if (res?.ok) {
const { data } = await res.json();
if (data) handleState(data);
}
});
_socket.on('timer:state', handleState);
_socket.on('timer:tick', handleTick);
_socket.on('timer:phase-change', handlePhaseChange);
_socket.on('timer:complete', handleComplete);
_socket.on('timer:stopped', handleStopped);
_socket.connect();
_socket.joinRoom(sessionId);
// AirPlay keep-alive
_keepAliveEl = document.createElement('div');
_keepAliveEl.className = 'keep-alive';
document.body.appendChild(_keepAliveEl);
// Cleanup on unload
window.addEventListener('beforeunload', () => {
_socket.leaveRoom(sessionId);
_socket.destroy();
stopLocalFallback();
});
}
function handleState(state) {
_localEndTime = state.phaseEndTime; // ms epoch from server
setPhaseColor(state.phase, state.phaseRemainingMs);
updateCounters(state);
if (timerEl()) timerEl().textContent = formatTime(state.phaseRemainingMs);
if (totalEl()) totalEl().textContent = 'Total ' + formatTime(state.totalRemainingMs);
}
function handleTick(data) {
_localEndTime = data.phaseEndTime || _localEndTime;
setPhaseColor(data.phase, data.phaseRemainingMs);
if (timerEl()) timerEl().textContent = formatTime(data.phaseRemainingMs);
if (totalEl()) totalEl().textContent = 'Total ' + formatTime(data.totalRemainingMs);
updateCounters(data);
stopLocalFallback();
}
function handlePhaseChange(data) {
setPhaseColor(data.phase, data.phaseRemainingMs);
updateCounters(data);
_localEndTime = data.phaseEndTime;
}
function handleComplete() {
stopLocalFallback();
if (timerEl()) timerEl().textContent = '00:00';
if (overlayTitleEl()) overlayTitleEl().textContent = 'DONE';
overlayEl()?.classList.add('visible');
containerEl()?.classList.add('phase-complete');
}
function handleStopped() {
stopLocalFallback();
if (overlayTitleEl()) overlayTitleEl().textContent = 'STOPPED';
overlayEl()?.classList.add('visible');
}
function startLocalFallback(endTimeMs) {
stopLocalFallback();
localIndicator()?.classList.add('visible');
function tick() {
const remaining = Math.max(0, endTimeMs - Date.now());
if (timerEl()) timerEl().textContent = formatTime(remaining);
if (remaining > 0) {
_localFallbackRaf = requestAnimationFrame(tick);
} else {
localIndicator()?.classList.remove('visible');
}
}
_localFallbackRaf = requestAnimationFrame(tick);
}
function stopLocalFallback() {
if (_localFallbackRaf) {
cancelAnimationFrame(_localFallbackRaf);
_localFallbackRaf = null;
}
localIndicator()?.classList.remove('visible');
}
function updateCounters(state) {
if (phaseEl()) phaseEl().textContent = (state.phase || '').toUpperCase();
if (lapEl()) lapEl().textContent = `LAP ${state.currentLap}/${state.lapCount}`;
if (exerciseEl()) exerciseEl().textContent = `${state.currentExercise}/${state.exerciseCount} EX`;
if (setEl()) setEl().textContent = `SET ${state.currentSet}/${state.setCount}`;
}
function setPhaseColor(phase, remainingMs) {
const container = containerEl();
if (!container) return;
container.className = 'display-container';
const isWarning = typeof remainingMs === 'number' && remainingMs <= 10000 && remainingMs > 0;
if (isWarning) {
container.classList.add('phase-warning');
} else {
container.classList.add(`phase-${phase || 'idle'}`);
}
}
function formatTime(ms) {
if (typeof ms !== 'number' || isNaN(ms)) return '--:--';
const totalSec = Math.max(0, Math.ceil(ms / 1000));
const min = String(Math.floor(totalSec / 60)).padStart(2, '0');
const sec = String(totalSec % 60).padStart(2, '0');
return `${min}:${sec}`;
}
function formatHMS(ms) {
const totalSec = Math.max(0, Math.ceil(ms / 1000));
const h = Math.floor(totalSec / 3600);
const m = Math.floor((totalSec % 3600) / 60);
const s = totalSec % 60;
return `${h}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
}
return { init, handleState, handleTick, handlePhaseChange, handleComplete, handleStopped, startLocalFallback, stopLocalFallback, formatTime, formatHMS, setPhaseColor };
})();
+15
View File
@@ -0,0 +1,15 @@
{
"name": "VitFit",
"short_name": "VitFit",
"description": "Fitness coaching platform",
"start_url": "/dashboard.html",
"display": "standalone",
"background_color": "#1a1a1a",
"theme_color": "#1a1a1a",
"orientation": "any",
"icons": [
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" },
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
]
}
+77
View File
@@ -0,0 +1,77 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Schedule — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<h1 class="page-title">My Schedule</h1>
<div id="schedule-list">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
async function loadSchedule() {
const el = document.getElementById('schedule-list');
try {
const res = await Api.get('/api/v1/my/client/sessions');
if (!res.ok) throw new Error();
const { data } = await res.json();
if (!data.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No upcoming sessions.</p></div>'; return; }
el.innerHTML = data.map(s => `
<div class="card" style="margin-bottom:var(--space-4);">
<div class="card-body flex justify-between align-center">
<div>
<p class="text-lg font-bold">${new Date(s.startAt).toLocaleString()}</p>
<p class="text-secondary">${new Date(s.endAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} · ${s.coach?.name || 'Coach'}</p>
${s.notes ? `<p class="text-secondary mt-1">${s.notes}</p>` : ''}
</div>
<div class="flex gap-3 align-center">
<span class="badge badge-${s.status === 'scheduled' ? 'default' : s.status === 'completed' ? 'success' : 'danger'}">${s.status}</span>
${s.status === 'scheduled' ? `<button class="btn btn-danger btn-sm" onclick="cancelSession(${s.id})">Cancel</button>` : ''}
</div>
</div>
</div>`).join('');
} catch {
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load schedule.</p></div>';
}
}
async function cancelSession(id) {
if (!confirm('Cancel this session?')) return;
try {
const res = await Api.patch(`/api/v1/calendar/${id}/cancel`, {});
if (res.ok) { toast('Session cancelled.', 'success'); loadSchedule(); }
else { const b = await res.json(); toast(b.message || 'Cannot cancel — within 24h window.', 'error'); }
} catch { toast('Network error.', 'error'); }
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Client']);
loadSchedule();
});
</script>
</body>
</html>
+94
View File
@@ -0,0 +1,94 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Workouts — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<h1 class="page-title">My Workouts</h1>
<div class="tabs" style="margin-bottom:var(--space-6);">
<button class="tab active" data-status="assigned">Assigned</button>
<button class="tab" data-status="completed">Completed</button>
</div>
<div id="workout-list">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
let _status = 'assigned';
async function loadMyWorkouts() {
const el = document.getElementById('workout-list');
try {
const res = await Api.get('/api/v1/my/client/workouts', { status: _status });
if (!res.ok) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; return; }
const { data } = await res.json();
if (!data.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No workouts here yet.</p></div>'; return; }
el.innerHTML = data.map(cw => `
<div class="card" style="margin-bottom:var(--space-4);">
<div class="card-body">
<div class="flex justify-between align-center">
<div>
<p class="text-lg font-bold">${cw.workout?.name || '—'}</p>
${cw.dueDate ? `<p class="text-secondary">Due: ${new Date(cw.dueDate).toLocaleDateString()}</p>` : ''}
</div>
<div class="flex gap-3">
<span class="badge badge-${cw.status === 'completed' ? 'success' : 'default'}">${cw.status}</span>
${cw.status !== 'completed' ? `<button class="btn btn-primary btn-sm" onclick="markComplete(${cw.id})">Mark Done</button>` : ''}
</div>
</div>
${cw.workout?.videos?.length ? `<p class="text-secondary mt-2">${cw.workout.videos.length} exercises</p>` : ''}
</div>
</div>`).join('');
} catch {
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Error loading workouts.</p></div>';
}
}
async function markComplete(cwId) {
try {
const res = await Api.patch(`/api/v1/my/client/workouts/${cwId}`, { status: 'completed' });
if (res.ok) { toast('Marked as complete!', 'success'); loadMyWorkouts(); }
else { const b = await res.json(); toast(b.message || 'Failed.', 'error'); }
} catch { toast('Network error.', 'error'); }
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Client']);
loadMyWorkouts();
document.querySelectorAll('.tab').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
btn.classList.add('active');
_status = btn.dataset.status;
loadMyWorkouts();
});
});
});
</script>
</body>
</html>
+125
View File
@@ -0,0 +1,125 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Profile — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<h1 class="page-title">My Profile</h1>
<div class="grid-2">
<!-- Update info -->
<div class="card">
<h2 class="card-title" style="margin-bottom:var(--space-6);">Account Details</h2>
<form id="profile-form" novalidate>
<div class="form-group">
<label class="form-label" for="name">Name</label>
<input class="form-input" type="text" id="name" maxlength="80">
</div>
<div class="form-group">
<label class="form-label" for="email">Email</label>
<input class="form-input" type="email" id="email" maxlength="200">
</div>
<div id="profile-error" class="form-error" style="display:none;"></div>
<button class="btn btn-primary" type="submit" id="profile-btn">Save Changes</button>
</form>
</div>
<!-- Change password -->
<div class="card">
<h2 class="card-title" style="margin-bottom:var(--space-6);">Change Password</h2>
<form id="password-form" novalidate>
<div class="form-group">
<label class="form-label" for="current-password">Current Password</label>
<input class="form-input" type="password" id="current-password" autocomplete="current-password">
</div>
<div class="form-group">
<label class="form-label" for="new-password">New Password</label>
<input class="form-input" type="password" id="new-password" autocomplete="new-password" minlength="8">
</div>
<div class="form-group">
<label class="form-label" for="confirm-password">Confirm New Password</label>
<input class="form-input" type="password" id="confirm-password" autocomplete="new-password">
</div>
<div id="password-error" class="form-error" style="display:none;"></div>
<button class="btn btn-primary" type="submit" id="password-btn">Change Password</button>
</form>
</div>
</div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach', 'Client', 'SystemAdmin']);
// Load current user
try {
const res = await Api.get('/api/v1/my/profile');
if (res.ok) {
const { data } = await res.json();
document.getElementById('name').value = data.name || '';
document.getElementById('email').value = data.email || '';
}
} catch {}
document.getElementById('profile-form').addEventListener('submit', async (e) => {
e.preventDefault();
const errEl = document.getElementById('profile-error');
errEl.style.display = 'none';
const btn = document.getElementById('profile-btn');
btn.disabled = true; btn.textContent = 'Saving…';
try {
const res = await Api.patch('/api/v1/my/profile', {
name: document.getElementById('name').value.trim(),
email: document.getElementById('email').value.trim(),
});
if (res.ok) toast('Profile updated.', 'success');
else { const b = await res.json(); errEl.textContent = b.message || 'Failed.'; errEl.style.display = 'block'; }
} catch { errEl.textContent = 'Network error.'; errEl.style.display = 'block'; }
finally { btn.disabled = false; btn.textContent = 'Save Changes'; }
});
document.getElementById('password-form').addEventListener('submit', async (e) => {
e.preventDefault();
const errEl = document.getElementById('password-error');
errEl.style.display = 'none';
const newPw = document.getElementById('new-password').value;
const conf = document.getElementById('confirm-password').value;
if (newPw !== conf) { errEl.textContent = 'Passwords do not match.'; errEl.style.display = 'block'; return; }
const btn = document.getElementById('password-btn');
btn.disabled = true; btn.textContent = 'Changing…';
try {
const res = await Api.post('/api/v1/my/change-password', {
currentPassword: document.getElementById('current-password').value,
newPassword: newPw,
});
if (res.ok) {
toast('Password changed. Please sign in again.', 'success');
setTimeout(() => { Auth.clearSession(); window.location.href = '/'; }, 2000);
} else { const b = await res.json(); errEl.textContent = b.message || 'Failed.'; errEl.style.display = 'block'; }
} catch { errEl.textContent = 'Network error.'; errEl.style.display = 'block'; }
finally { btn.disabled = false; btn.textContent = 'Change Password'; }
});
});
</script>
</body>
</html>
+262
View File
@@ -0,0 +1,262 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Settings — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<h1 class="page-title">Settings</h1>
<div class="tabs" style="margin-bottom:var(--space-6);">
<button class="tab active" data-tab="org">Organisation</button>
<button class="tab" data-tab="branding">Branding</button>
<button class="tab" data-tab="users">Users</button>
</div>
<!-- Org tab -->
<div id="tab-org">
<div class="card" style="max-width:560px;">
<h2 class="card-title" style="margin-bottom:var(--space-6);">Organisation Details</h2>
<form id="org-form" novalidate>
<div class="form-group">
<label class="form-label" for="org-name">Name</label>
<input class="form-input" type="text" id="org-name" maxlength="120">
</div>
<div class="form-group">
<label class="form-label" for="org-timezone">Timezone</label>
<input class="form-input" type="text" id="org-timezone" placeholder="e.g. America/Chicago">
</div>
<div id="org-error" class="form-error" style="display:none;"></div>
<button class="btn btn-primary" type="submit" id="org-btn">Save</button>
</form>
</div>
</div>
<!-- Branding tab -->
<div id="tab-branding" style="display:none;">
<div class="card" style="max-width:560px;">
<h2 class="card-title" style="margin-bottom:var(--space-6);">Branding</h2>
<form id="branding-form" novalidate>
<div class="form-group">
<label class="form-label" for="app-name-input">App Name</label>
<input class="form-input" type="text" id="app-name-input" maxlength="60">
</div>
<div class="form-group">
<label class="form-label" for="primary-color">Primary Color</label>
<div class="input-row">
<input class="form-input" type="text" id="primary-color" placeholder="#3a86ff" maxlength="7" pattern="^#[0-9A-Fa-f]{6}$">
<input type="color" id="primary-color-pick" style="width:44px;height:44px;border:none;cursor:pointer;">
</div>
</div>
<div class="form-group">
<label class="form-label" for="logo-file">Logo (PNG/JPG, max 2MB)</label>
<input class="form-input" type="file" id="logo-file" accept="image/*">
<img id="logo-preview" style="display:none;max-height:60px;margin-top:var(--space-2);">
</div>
<div id="branding-error" class="form-error" style="display:none;"></div>
<button class="btn btn-primary" type="submit" id="branding-btn">Save Branding</button>
</form>
</div>
</div>
<!-- Users tab -->
<div id="tab-users" style="display:none;">
<div class="page-header" style="margin-bottom:var(--space-4);">
<h2 class="card-title">Users</h2>
<button class="btn btn-primary btn-sm" id="invite-btn">Invite User</button>
</div>
<div id="user-list">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
<div class="modal-overlay" id="invite-modal" style="display:none;">
<div class="modal">
<div class="modal-header">
<h2 class="modal-title">Invite User</h2>
<button class="modal-close" id="invite-modal-close">&times;</button>
</div>
<div class="form-group">
<label class="form-label" for="invite-name">Name</label>
<input class="form-input" type="text" id="invite-name" maxlength="80">
</div>
<div class="form-group">
<label class="form-label" for="invite-email">Email</label>
<input class="form-input" type="email" id="invite-email">
</div>
<div class="form-group">
<label class="form-label" for="invite-role">Role</label>
<select class="form-select" id="invite-role">
<option value="Coach">Coach</option>
<option value="Client">Client</option>
</select>
</div>
<div class="form-group">
<label class="form-label" for="invite-password">Temporary Password</label>
<input class="form-input" type="text" id="invite-password" autocomplete="off">
</div>
<div id="invite-error" class="form-error" style="display:none;"></div>
<button class="btn btn-primary" id="invite-confirm-btn">Create User</button>
</div>
</div>
</div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
async function loadUsers() {
const el = document.getElementById('user-list');
try {
const res = await Api.get('/api/v1/users');
if (!res.ok) throw new Error();
const { data } = await res.json();
el.innerHTML = `<table class="table"><thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Status</th><th></th></tr></thead><tbody>
${data.map(u => `<tr>
<td>${u.name}</td>
<td>${u.email}</td>
<td>${u.role}</td>
<td><span class="badge badge-${u.isActive ? 'success' : 'danger'}">${u.isActive ? 'Active' : 'Inactive'}</span></td>
<td class="table-actions">
${u.isActive
? `<button class="btn btn-danger btn-sm" onclick="toggleUser(${u.id}, false)">Deactivate</button>`
: `<button class="btn btn-secondary btn-sm" onclick="toggleUser(${u.id}, true)">Activate</button>`}
</td>
</tr>`).join('')}
</tbody></table>`;
} catch { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; }
}
async function toggleUser(id, active) {
try {
const res = await Api.patch(`/api/v1/users/${id}`, { isActive: active });
if (res.ok) { toast(active ? 'User activated.' : 'User deactivated.', 'success'); loadUsers(); }
else { const b = await res.json(); toast(b.message || 'Failed.', 'error'); }
} catch { toast('Network error.', 'error'); }
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner']);
// Tab switching
document.querySelectorAll('.tab').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
btn.classList.add('active');
['org', 'branding', 'users'].forEach(t => {
document.getElementById(`tab-${t}`).style.display = btn.dataset.tab === t ? '' : 'none';
});
if (btn.dataset.tab === 'users') loadUsers();
});
});
// Load org data
try {
const res = await Api.get('/api/v1/org');
if (res.ok) {
const { data } = await res.json();
document.getElementById('org-name').value = data.name || '';
document.getElementById('org-timezone').value = data.timezone || '';
}
} catch {}
document.getElementById('org-form').addEventListener('submit', async (e) => {
e.preventDefault();
const errEl = document.getElementById('org-error'); errEl.style.display = 'none';
const btn = document.getElementById('org-btn'); btn.disabled = true; btn.textContent = 'Saving…';
try {
const res = await Api.patch('/api/v1/org', { name: document.getElementById('org-name').value.trim(), timezone: document.getElementById('org-timezone').value.trim() });
if (res.ok) toast('Saved.', 'success');
else { const b = await res.json(); errEl.textContent = b.message || 'Failed.'; errEl.style.display = 'block'; }
} catch { errEl.textContent = 'Network error.'; errEl.style.display = 'block'; }
finally { btn.disabled = false; btn.textContent = 'Save'; }
});
// Load branding
try {
const res = await Api.get('/api/v1/org/branding');
if (res.ok) {
const { data } = await res.json();
document.getElementById('app-name-input').value = data.appName || '';
if (data.primaryColor) { document.getElementById('primary-color').value = data.primaryColor; document.getElementById('primary-color-pick').value = data.primaryColor; }
if (data.logoPath) { const img = document.getElementById('logo-preview'); img.src = data.logoPath; img.style.display = ''; }
}
} catch {}
document.getElementById('primary-color-pick').addEventListener('input', (e) => {
document.getElementById('primary-color').value = e.target.value;
});
document.getElementById('primary-color').addEventListener('input', (e) => {
if (/^#[0-9A-Fa-f]{6}$/.test(e.target.value)) document.getElementById('primary-color-pick').value = e.target.value;
});
document.getElementById('branding-form').addEventListener('submit', async (e) => {
e.preventDefault();
const errEl = document.getElementById('branding-error'); errEl.style.display = 'none';
const btn = document.getElementById('branding-btn'); btn.disabled = true; btn.textContent = 'Saving…';
const logoFile = document.getElementById('logo-file').files[0];
try {
if (logoFile) {
const fd = new FormData();
fd.append('logo', logoFile);
fd.append('appName', document.getElementById('app-name-input').value.trim());
fd.append('primaryColor', document.getElementById('primary-color').value.trim());
const res = await Api.upload('/api/v1/org/branding/logo', fd);
if (!res.ok) { const b = await res.json(); errEl.textContent = b.message || 'Failed.'; errEl.style.display = 'block'; return; }
} else {
const res = await Api.patch('/api/v1/org/branding', {
appName: document.getElementById('app-name-input').value.trim(),
primaryColor: document.getElementById('primary-color').value.trim() || undefined,
});
if (!res.ok) { const b = await res.json(); errEl.textContent = b.message || 'Failed.'; errEl.style.display = 'block'; return; }
}
toast('Branding updated.', 'success');
Branding.load();
} catch { errEl.textContent = 'Network error.'; errEl.style.display = 'block'; }
finally { btn.disabled = false; btn.textContent = 'Save Branding'; }
});
// Users tab
document.getElementById('invite-btn').addEventListener('click', () => {
document.getElementById('invite-modal').style.display = 'flex';
});
document.getElementById('invite-modal-close').addEventListener('click', () => {
document.getElementById('invite-modal').style.display = 'none';
});
document.getElementById('invite-confirm-btn').addEventListener('click', async () => {
const errEl = document.getElementById('invite-error'); errEl.style.display = 'none';
const name = document.getElementById('invite-name').value.trim();
const email = document.getElementById('invite-email').value.trim();
const role = document.getElementById('invite-role').value;
const password = document.getElementById('invite-password').value;
if (!name || !email || !password) { errEl.textContent = 'All fields required.'; errEl.style.display = 'block'; return; }
try {
const res = await Api.post('/api/v1/users', { name, email, role, password });
if (res.ok) {
toast('User created.', 'success');
document.getElementById('invite-modal').style.display = 'none';
loadUsers();
} else { const b = await res.json(); errEl.textContent = b.message || 'Failed.'; errEl.style.display = 'block'; }
} catch { errEl.textContent = 'Network error.'; errEl.style.display = 'block'; }
});
});
</script>
</body>
</html>
+146
View File
@@ -0,0 +1,146 @@
/* ── Reset ────────────────────────────────────────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html { -webkit-text-size-adjust: 100%; }
body { -webkit-font-smoothing: antialiased; }
img, video { max-width: 100%; display: block; }
button, input, select, textarea { font: inherit; }
a { color: inherit; text-decoration: none; }
/* ── Brand tokens (overridable per org via Branding.apply()) ────────────── */
:root {
--color-primary: #00FF88;
--color-secondary: #4488FF;
--color-work: #00FF88;
--color-rest: #4488FF;
--color-move: #FF4444;
--color-warning: #FFAA00;
--color-complete: #FFFFFF;
--color-idle: #FFFFFF;
}
/* ── Surface & text tokens (not overridable) ────────────────────────────── */
:root {
--surface-bg: #0f0f0f;
--surface-card: #1a1a1a;
--surface-raised: #242424;
--surface-border: #2e2e2e;
--surface-hover: #2a2a2a;
--text-primary: #f0f0f0;
--text-secondary: #a0a0a0;
--text-muted: #606060;
--text-inverse: #0f0f0f;
--text-on-primary: #0f0f0f;
--color-success: #00FF88;
--color-danger: #FF4444;
--color-info: #4488FF;
--color-warning-ui: #FFAA00;
--display-bg: #1a1a1a;
--display-text: #ffffff;
}
/* ── Spacing ────────────────────────────────────────────────────────────── */
:root {
--space-1: 4px; --space-2: 8px; --space-3: 12px;
--space-4: 16px; --space-5: 20px; --space-6: 24px;
--space-8: 32px; --space-10: 40px; --space-12: 48px;
--space-16: 64px; --space-20: 80px; --space-24: 96px;
}
/* ── Radii ──────────────────────────────────────────────────────────────── */
:root {
--radius-sm: 6px;
--radius-md: 10px;
--radius-lg: 16px;
--radius-full: 9999px;
}
/* ── Typography ─────────────────────────────────────────────────────────── */
:root {
--font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
--text-xs: 12px; --text-sm: 14px; --text-base: 16px;
--text-lg: 18px; --text-xl: 22px; --text-2xl: 28px;
--weight-normal: 400; --weight-medium: 500;
--weight-semibold: 600; --weight-bold: 700; --weight-black: 900;
--line-height-tight: 1.2;
--line-height-normal: 1.5;
--line-height-loose: 1.75;
}
/* ── Transitions ────────────────────────────────────────────────────────── */
:root {
--transition-fast: 100ms ease;
--transition-base: 200ms ease;
--transition-slow: 400ms ease;
--transition-phase: 600ms ease;
}
/* ── Z-index ────────────────────────────────────────────────────────────── */
:root {
--z-base: 1; --z-sticky: 10; --z-drawer: 100;
--z-modal: 200; --z-overlay: 300; --z-toast: 400;
}
/* ── Base styles ────────────────────────────────────────────────────────── */
html, body {
height: 100%;
background: var(--surface-bg);
color: var(--text-primary);
font-family: var(--font-family);
font-size: var(--text-base);
line-height: var(--line-height-normal);
}
/* ── Focus ──────────────────────────────────────────────────────────────── */
:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
/* ── Reduced motion ─────────────────────────────────────────────────────── */
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
transition-duration: 0ms !important;
animation-duration: 0ms !important;
}
}
/* ── Typography utilities ───────────────────────────────────────────────── */
.text-primary { color: var(--text-primary); }
.text-secondary { color: var(--text-secondary); }
.text-muted { color: var(--text-muted); }
.text-danger { color: var(--color-danger); }
.text-success { color: var(--color-success); }
.text-xs { font-size: var(--text-xs); }
.text-sm { font-size: var(--text-sm); }
.text-lg { font-size: var(--text-lg); }
.text-xl { font-size: var(--text-xl); }
.text-2xl { font-size: var(--text-2xl); }
.font-medium { font-weight: var(--weight-medium); }
.font-semibold { font-weight: var(--weight-semibold); }
.font-bold { font-weight: var(--weight-bold); }
/* ── Utility ─────────────────────────────────────────────────────────────── */
.sr-only {
position: absolute; width: 1px; height: 1px;
padding: 0; margin: -1px; overflow: hidden;
clip: rect(0,0,0,0); white-space: nowrap; border: 0;
}
.hidden { display: none !important; }
.flex { display: flex; }
.flex-col { flex-direction: column; }
.items-center { align-items: center; }
.justify-between { justify-content: space-between; }
.gap-2 { gap: var(--space-2); }
.gap-4 { gap: var(--space-4); }
.gap-6 { gap: var(--space-6); }
.mt-4 { margin-top: var(--space-4); }
.mt-6 { margin-top: var(--space-6); }
.mb-4 { margin-bottom: var(--space-4); }
+307
View File
@@ -0,0 +1,307 @@
/* ── Buttons ─────────────────────────────────────────────────────────────── */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: var(--space-2);
height: 44px;
padding: 0 var(--space-5);
border-radius: var(--radius-md);
font-size: var(--text-base);
font-weight: var(--weight-semibold);
border: none;
cursor: pointer;
transition: opacity var(--transition-fast);
white-space: nowrap;
text-decoration: none;
}
.btn:active { opacity: 0.75; }
.btn:disabled { opacity: 0.4; cursor: not-allowed; }
.btn-primary { background: var(--color-primary); color: var(--text-on-primary); }
.btn-secondary { background: var(--surface-raised); color: var(--text-primary); }
.btn-danger { background: var(--color-danger); color: #fff; }
.btn-ghost { background: transparent; color: var(--color-primary); border: 1px solid var(--surface-border); }
.btn-sm { height: 36px; padding: 0 var(--space-4); font-size: var(--text-sm); }
.btn-lg { height: 52px; padding: 0 var(--space-6); font-size: var(--text-lg); }
.btn-full { width: 100%; }
/* ── Cards ───────────────────────────────────────────────────────────────── */
.card {
background: var(--surface-card);
border-radius: var(--radius-md);
border: 1px solid var(--surface-border);
padding: var(--space-5);
}
.card-header {
font-size: var(--text-lg);
font-weight: var(--weight-semibold);
color: var(--text-primary);
margin-bottom: var(--space-4);
}
.card-meta {
font-size: var(--text-sm);
color: var(--text-secondary);
}
.card-actions {
display: flex;
gap: var(--space-3);
margin-top: var(--space-4);
}
.card + .card { margin-top: var(--space-4); }
/* ── Forms ───────────────────────────────────────────────────────────────── */
.form-field { margin-bottom: var(--space-5); }
.form-label {
display: block;
font-size: var(--text-sm);
font-weight: var(--weight-medium);
color: var(--text-secondary);
margin-bottom: var(--space-2);
}
.form-input,
.form-select,
.form-textarea {
width: 100%;
height: 44px;
padding: 0 var(--space-4);
background: var(--surface-raised);
border: 1px solid var(--surface-border);
border-radius: var(--radius-sm);
color: var(--text-primary);
font-size: var(--text-base);
transition: border-color var(--transition-fast);
}
.form-textarea {
height: auto;
padding: var(--space-3) var(--space-4);
resize: vertical;
min-height: 100px;
}
.form-input:focus,
.form-select:focus,
.form-textarea:focus {
border-color: var(--color-primary);
outline: none;
}
.form-input::placeholder,
.form-textarea::placeholder { color: var(--text-muted); }
.form-error {
font-size: var(--text-sm);
color: var(--color-danger);
margin-top: var(--space-2);
}
.form-hint {
font-size: var(--text-sm);
color: var(--text-muted);
margin-top: var(--space-2);
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--space-4);
}
@media (max-width: 480px) { .form-row { grid-template-columns: 1fr; } }
/* ── Color input ─────────────────────────────────────────────────────────── */
.form-input[type="color"] {
height: 44px;
padding: var(--space-1) var(--space-2);
cursor: pointer;
}
/* ── Badges ──────────────────────────────────────────────────────────────── */
.badge {
display: inline-flex;
align-items: center;
padding: 2px var(--space-2);
border-radius: var(--radius-full);
font-size: var(--text-xs);
font-weight: var(--weight-semibold);
text-transform: uppercase;
letter-spacing: 0.04em;
white-space: nowrap;
}
.badge-success { background: color-mix(in srgb, var(--color-success) 15%, transparent); color: var(--color-success); }
.badge-danger { background: color-mix(in srgb, var(--color-danger) 15%, transparent); color: var(--color-danger); }
.badge-info { background: color-mix(in srgb, var(--color-info) 15%, transparent); color: var(--color-info); }
.badge-warning { background: color-mix(in srgb, var(--color-warning-ui) 15%, transparent); color: var(--color-warning-ui); }
.badge-neutral { background: var(--surface-raised); color: var(--text-secondary); }
/* ── Modal ───────────────────────────────────────────────────────────────── */
.modal-scrim {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.7);
z-index: calc(var(--z-modal) - 1);
display: flex;
align-items: center;
justify-content: center;
padding: var(--space-4);
opacity: 0;
pointer-events: none;
transition: opacity var(--transition-base);
}
.modal-scrim.open {
opacity: 1;
pointer-events: all;
}
.modal {
background: var(--surface-raised);
border-radius: var(--radius-lg);
border: 1px solid var(--surface-border);
width: 100%;
max-width: 480px;
max-height: 90dvh;
overflow-y: auto;
display: flex;
flex-direction: column;
}
.modal-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: var(--space-5) var(--space-6) var(--space-4);
border-bottom: 1px solid var(--surface-border);
}
.modal-title { font-size: var(--text-lg); font-weight: var(--weight-semibold); }
.modal-close {
width: 36px; height: 36px;
display: flex; align-items: center; justify-content: center;
background: none; border: none; cursor: pointer;
color: var(--text-secondary); font-size: 20px;
border-radius: var(--radius-sm);
transition: background var(--transition-fast);
}
.modal-close:hover { background: var(--surface-hover); color: var(--text-primary); }
.modal-body { padding: var(--space-6); flex: 1; }
.modal-footer {
padding: var(--space-4) var(--space-6);
border-top: 1px solid var(--surface-border);
display: flex;
justify-content: flex-end;
gap: var(--space-3);
}
/* ── Toast ───────────────────────────────────────────────────────────────── */
#toast-container {
position: fixed;
bottom: var(--space-6);
left: 50%;
transform: translateX(-50%);
z-index: var(--z-toast);
display: flex;
flex-direction: column;
align-items: center;
gap: var(--space-3);
pointer-events: none;
width: max-content;
max-width: min(360px, calc(100vw - 32px));
}
.toast {
padding: var(--space-3) var(--space-5);
border-radius: var(--radius-md);
font-size: var(--text-sm);
font-weight: var(--weight-medium);
box-shadow: 0 4px 16px rgba(0,0,0,0.4);
pointer-events: all;
animation: toastIn 200ms ease forwards;
}
@keyframes toastIn {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
.toast-success { background: var(--surface-raised); border-left: 3px solid var(--color-success); color: var(--text-primary); }
.toast-error { background: var(--surface-raised); border-left: 3px solid var(--color-danger); color: var(--text-primary); }
.toast-warning { background: var(--surface-raised); border-left: 3px solid var(--color-warning-ui); color: var(--text-primary); }
.toast-info { background: var(--surface-raised); border-left: 3px solid var(--color-info); color: var(--text-primary); }
/* ── Progress bar ────────────────────────────────────────────────────────── */
.progress-bar {
height: 8px;
background: var(--surface-border);
border-radius: var(--radius-full);
overflow: hidden;
}
.progress-fill {
height: 100%;
border-radius: var(--radius-full);
background: var(--color-primary);
transition: width var(--transition-slow);
}
.progress-fill.warning { background: var(--color-warning-ui); }
.progress-fill.danger { background: var(--color-danger); }
/* ── Table ───────────────────────────────────────────────────────────────── */
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; }
th, td {
padding: var(--space-3) var(--space-4);
text-align: left;
border-bottom: 1px solid var(--surface-border);
font-size: var(--text-sm);
}
th {
font-weight: var(--weight-semibold);
color: var(--text-secondary);
white-space: nowrap;
}
tr:last-child td { border-bottom: none; }
tr:hover td { background: var(--surface-hover); }
/* ── Video card ──────────────────────────────────────────────────────────── */
.video-card { overflow: hidden; }
.video-card video {
width: 100%;
aspect-ratio: 16/9;
background: #000;
border-radius: var(--radius-sm);
margin-bottom: var(--space-3);
}
/* ── Upload progress ─────────────────────────────────────────────────────── */
.upload-progress { display: none; margin-top: var(--space-4); }
.upload-progress.visible { display: block; }
/* ── Empty state ─────────────────────────────────────────────────────────── */
.empty-state {
text-align: center;
padding: var(--space-16) var(--space-6);
color: var(--text-muted);
}
.empty-state-title { font-size: var(--text-lg); margin-bottom: var(--space-2); color: var(--text-secondary); }
/* ── Warning banner ──────────────────────────────────────────────────────── */
.warning-banner {
background: color-mix(in srgb, var(--color-warning-ui) 12%, transparent);
border: 1px solid var(--color-warning-ui);
border-radius: var(--radius-md);
padding: var(--space-3) var(--space-5);
font-size: var(--text-sm);
color: var(--color-warning-ui);
margin-bottom: var(--space-5);
}
/* ── Session expired overlay ─────────────────────────────────────────────── */
#session-expired-overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.8);
z-index: var(--z-overlay);
display: flex;
align-items: center;
justify-content: center;
display: none;
}
#session-expired-overlay.visible { display: flex; }
.session-expired-card {
background: var(--surface-card);
border-radius: var(--radius-lg);
padding: var(--space-8);
text-align: center;
max-width: 320px;
}
.session-expired-card h2 { margin-bottom: var(--space-4); }
+231
View File
@@ -0,0 +1,231 @@
/* Display mode — full-screen TV layout. Replaces layout.css + components.css entirely. */
/* ── Display mode typography scale ──────────────────────────────────────── */
:root {
--display-font-primary: 96px;
--display-font-secondary: 48px;
--display-font-label: 32px;
--display-font-body: 28px;
}
/* ── Full-screen shell ────────────────────────────────────────────────────── */
html, body {
width: 100vw;
height: 100dvh;
overflow: hidden;
background: var(--display-bg);
color: var(--display-text);
cursor: none;
user-select: none;
-webkit-user-select: none;
}
.display-container {
width: 100vw;
height: 100dvh;
display: flex;
flex-direction: column;
position: relative;
}
/* ── Status bar (top strip) ───────────────────────────────────────────────── */
.display-status-bar {
display: flex;
align-items: center;
justify-content: space-between;
padding: var(--space-4) var(--space-8);
height: 64px;
flex-shrink: 0;
}
.display-status-label {
font-size: var(--display-font-label);
font-weight: var(--weight-bold);
text-transform: uppercase;
letter-spacing: 0.06em;
transition: color var(--transition-phase);
}
.display-status-right {
display: flex;
gap: var(--space-8);
font-size: var(--display-font-label);
font-weight: var(--weight-medium);
color: var(--text-secondary);
}
/* ── Main timer display ───────────────────────────────────────────────────── */
.display-main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 0 var(--space-8);
text-align: center;
}
.display-timer {
font-size: var(--display-font-primary);
font-weight: var(--weight-black);
line-height: 1;
letter-spacing: -2px;
transition: color var(--transition-phase);
font-variant-numeric: tabular-nums;
}
.display-exercise {
font-size: var(--display-font-label);
font-weight: var(--weight-bold);
text-transform: uppercase;
letter-spacing: 0.08em;
margin-top: var(--space-6);
color: var(--text-secondary);
transition: color var(--transition-phase);
}
.display-total-time {
font-size: var(--display-font-body);
color: var(--text-muted);
margin-top: var(--space-8);
}
/* ── Phase colors ─────────────────────────────────────────────────────────── */
.phase-work .display-timer { color: var(--color-work); }
.phase-rest .display-timer { color: var(--color-rest); }
.phase-move .display-timer { color: var(--color-move); }
.phase-idle .display-timer { color: var(--color-idle); }
.phase-warning .display-timer { color: var(--color-warning); }
.phase-complete .display-timer { color: var(--display-text); }
.phase-work .display-status-label { color: var(--color-work); }
.phase-rest .display-status-label { color: var(--color-rest); }
.phase-move .display-status-label { color: var(--color-move); }
.phase-idle .display-status-label { color: var(--color-idle); }
.phase-warning .display-status-label { color: var(--color-warning); }
/* ── Workout display ─────────────────────────────────────────────────────── */
.display-workout-list {
width: 100%;
max-width: 800px;
list-style: none;
}
.display-workout-item {
display: flex;
align-items: baseline;
justify-content: space-between;
padding: var(--space-5) 0;
border-bottom: 1px solid rgba(255,255,255,0.08);
font-size: var(--display-font-body);
font-weight: var(--weight-medium);
}
.display-workout-item:last-child { border-bottom: none; }
.display-workout-item-name { flex: 1; }
.display-workout-item-reps {
font-size: var(--display-font-label);
font-weight: var(--weight-bold);
color: var(--color-primary);
margin-left: var(--space-8);
}
/* ── CrossFit display ────────────────────────────────────────────────────── */
.display-crossfit-list {
width: 100%;
max-width: 760px;
list-style: none;
counter-reset: cf-counter;
}
.display-crossfit-item {
display: flex;
gap: var(--space-5);
padding: var(--space-4) 0;
font-size: var(--display-font-body);
font-weight: var(--weight-medium);
border-bottom: 1px solid rgba(255,255,255,0.08);
counter-increment: cf-counter;
}
.display-crossfit-item:last-child { border-bottom: none; }
.display-crossfit-item::before {
content: counter(cf-counter) ".";
font-weight: var(--weight-bold);
color: var(--color-primary);
min-width: 32px;
}
/* ── Coach touch zones (invisible on TV) ────────────────────────────────── */
.touch-zone {
position: absolute;
top: 0;
bottom: 0;
width: 80px;
opacity: 0;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
.touch-zone-left { left: 0; }
.touch-zone-right { right: 0; }
/* ── Done / stopped overlay ─────────────────────────────────────────────── */
.display-overlay {
position: absolute;
inset: 0;
background: rgba(26,26,26,0.92);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: var(--space-6);
display: none;
}
.display-overlay.visible { display: flex; }
.display-overlay-title {
font-size: var(--display-font-primary);
font-weight: var(--weight-black);
color: var(--color-complete);
}
.display-overlay-sub {
font-size: var(--display-font-label);
color: var(--text-secondary);
}
/* ── Offline banners ─────────────────────────────────────────────────────── */
.display-offline-banner {
position: fixed;
top: 0;
left: 50%;
transform: translateX(-50%);
background: rgba(26,26,26,0.85);
border: 1px solid var(--color-warning-ui);
border-radius: 0 0 var(--radius-md) var(--radius-md);
padding: var(--space-2) var(--space-6);
font-size: var(--display-font-body);
color: var(--color-warning-ui);
z-index: var(--z-overlay);
pointer-events: none;
display: none;
}
.display-offline-banner.visible { display: block; }
.display-local-indicator {
position: fixed;
bottom: var(--space-4);
right: var(--space-6);
font-size: 18px;
color: var(--color-warning-ui);
opacity: 0.7;
z-index: var(--z-overlay);
pointer-events: none;
display: none;
}
.display-local-indicator.visible { display: block; }
/* ── AirPlay keep-alive (imperceptible pulse) ────────────────────────────── */
@keyframes keepAlive {
0%, 100% { opacity: 0.995; }
50% { opacity: 1.0; }
}
.keep-alive {
position: fixed;
inset: 0;
pointer-events: none;
animation: keepAlive 4s ease-in-out infinite;
z-index: -1;
}
+195
View File
@@ -0,0 +1,195 @@
/* Management shell — banner + nav drawer + content */
/* ── Banner ──────────────────────────────────────────────────────────────── */
.banner {
position: sticky;
top: 0;
z-index: var(--z-sticky);
height: 56px;
background: var(--surface-card);
border-bottom: 1px solid var(--surface-border);
display: flex;
align-items: center;
padding: 0 var(--space-4);
gap: var(--space-4);
}
.banner-hamburger {
width: 44px;
height: 44px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 5px;
background: none;
border: none;
cursor: pointer;
flex-shrink: 0;
}
.banner-hamburger span {
display: block;
width: 22px;
height: 2px;
background: var(--text-primary);
border-radius: 2px;
transition: transform var(--transition-base), opacity var(--transition-base);
}
.banner-logo {
height: 32px;
width: auto;
}
.banner-title {
font-size: var(--text-lg);
font-weight: var(--weight-semibold);
color: var(--text-primary);
}
/* ── Nav Drawer ──────────────────────────────────────────────────────────── */
.drawer-scrim {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.6);
z-index: calc(var(--z-drawer) - 1);
opacity: 0;
pointer-events: none;
transition: opacity var(--transition-base);
}
.drawer-scrim.open {
opacity: 1;
pointer-events: all;
}
.drawer {
position: fixed;
top: 0;
left: 0;
width: 280px;
height: 100dvh;
background: var(--surface-card);
border-right: 1px solid var(--surface-border);
z-index: var(--z-drawer);
transform: translateX(-280px);
transition: transform var(--transition-base);
display: flex;
flex-direction: column;
overflow-y: auto;
}
.drawer.open { transform: translateX(0); }
.drawer-header {
padding: var(--space-5) var(--space-5) var(--space-4);
border-bottom: 1px solid var(--surface-border);
}
.drawer-logo {
height: 36px;
margin-bottom: var(--space-2);
}
.drawer-org {
font-size: var(--text-sm);
color: var(--text-secondary);
}
.drawer-nav {
flex: 1;
padding: var(--space-3) 0;
list-style: none;
}
.drawer-nav a {
display: flex;
align-items: center;
height: 48px;
padding: 0 var(--space-5);
font-size: var(--text-base);
color: var(--text-secondary);
transition: background var(--transition-fast), color var(--transition-fast);
cursor: pointer;
}
.drawer-nav a:hover,
.drawer-nav a:focus-visible { background: var(--surface-hover); color: var(--text-primary); }
.drawer-nav a.active {
color: var(--color-primary);
background: color-mix(in srgb, var(--color-primary) 8%, transparent);
font-weight: var(--weight-medium);
}
.drawer-footer {
border-top: 1px solid var(--surface-border);
padding: var(--space-3) 0;
}
/* ── Main content ────────────────────────────────────────────────────────── */
.page-content {
padding: var(--space-6);
max-width: 960px;
margin: 0 auto;
min-height: calc(100dvh - 56px);
}
.page-title {
font-size: var(--text-xl);
font-weight: var(--weight-semibold);
margin-bottom: var(--space-6);
}
.page-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: var(--space-6);
}
/* ── Grid helpers ────────────────────────────────────────────────────────── */
.grid-2 {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: var(--space-5);
}
.grid-3 {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: var(--space-5);
}
@media (max-width: 767px) {
.grid-2, .grid-3 { grid-template-columns: 1fr; }
.page-content { padding: var(--space-4); }
}
/* ── Tabs ────────────────────────────────────────────────────────────────── */
.tabs {
display: flex;
gap: 2px;
border-bottom: 1px solid var(--surface-border);
margin-bottom: var(--space-6);
}
.tab-btn {
padding: var(--space-3) var(--space-5);
background: none;
border: none;
border-bottom: 2px solid transparent;
color: var(--text-secondary);
font-size: var(--text-base);
cursor: pointer;
transition: color var(--transition-fast), border-color var(--transition-fast);
margin-bottom: -1px;
}
.tab-btn:hover { color: var(--text-primary); }
.tab-btn.active {
color: var(--color-primary);
border-bottom-color: var(--color-primary);
font-weight: var(--weight-medium);
}
.tab-panel { display: none; }
.tab-panel.active { display: block; }
/* ── Pagination ──────────────────────────────────────────────────────────── */
.pagination {
display: flex;
align-items: center;
justify-content: center;
gap: var(--space-3);
margin-top: var(--space-8);
}
.pagination-info { font-size: var(--text-sm); color: var(--text-secondary); }
+51
View File
@@ -0,0 +1,51 @@
/* VitFit Service Worker — shell-only caching for PWA install */
'use strict';
const CACHE_NAME = 'vitfit-v2';
const SHELL_ASSETS = [
'/',
'/index.html',
'/dashboard.html',
'/styles/base.css',
'/styles/layout.css',
'/styles/components.css',
'/js/core.js',
'/js/socket-client.js',
'/manifest.json',
];
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(SHELL_ASSETS))
);
self.skipWaiting();
});
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys().then(keys =>
Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
)
);
self.clients.claim();
});
self.addEventListener('fetch', (e) => {
const url = new URL(e.request.url);
// API and socket: always network
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/socket.io')) return;
// Navigation: network-first, fallback to cached index
if (e.request.mode === 'navigate') {
e.respondWith(
fetch(e.request).catch(() => caches.match('/index.html'))
);
return;
}
// Static assets: cache-first
e.respondWith(
caches.match(e.request).then(cached => cached || fetch(e.request))
);
});
+143
View File
@@ -0,0 +1,143 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>System Admin — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<h1 class="page-title">System Admin</h1>
<div class="tabs" style="margin-bottom:var(--space-6);">
<button class="tab active" data-tab="health">Health</button>
<button class="tab" data-tab="orgs">Organisations</button>
<button class="tab" data-tab="storage">Storage</button>
</div>
<!-- Health tab -->
<div id="tab-health">
<div class="card" style="max-width:480px;">
<h2 class="card-title" style="margin-bottom:var(--space-4);">System Health</h2>
<div id="health-body">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
</div>
</div>
<!-- Orgs tab -->
<div id="tab-orgs" style="display:none;">
<div id="orgs-body">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
</div>
<!-- Storage tab -->
<div id="tab-storage" style="display:none;">
<div class="card" style="max-width:480px;">
<h2 class="card-title" style="margin-bottom:var(--space-4);">Disk Usage</h2>
<div id="storage-body">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
</div>
</div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
async function loadHealth() {
const el = document.getElementById('health-body');
try {
const res = await Api.get('/api/v1/sysadmin/health');
if (!res.ok) throw new Error();
const { data } = await res.json();
el.innerHTML = `
<table class="table">
<tr><td><strong>Status</strong></td><td><span class="badge badge-success">${data.status}</span></td></tr>
<tr><td><strong>Uptime</strong></td><td>${Math.floor(data.uptimeSeconds / 3600)}h ${Math.floor((data.uptimeSeconds % 3600) / 60)}m</td></tr>
<tr><td><strong>Memory RSS</strong></td><td>${Math.round(data.memoryMb?.rss ?? 0)} MB</td></tr>
<tr><td><strong>Node</strong></td><td>${data.nodeVersion || '—'}</td></tr>
<tr><td><strong>Timestamp</strong></td><td>${new Date(data.timestamp).toLocaleTimeString()}</td></tr>
</table>`;
} catch { el.innerHTML = '<p class="text-secondary">Failed to load.</p>'; }
}
async function loadOrgs() {
const el = document.getElementById('orgs-body');
try {
const res = await Api.get('/api/v1/sysadmin/orgs');
if (!res.ok) throw new Error();
const { data } = await res.json();
if (!data.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No organisations.</p></div>'; return; }
el.innerHTML = `<table class="table"><thead><tr><th>Name</th><th>Slug</th><th>Created</th><th>Features</th></tr></thead><tbody>
${data.map(o => `<tr>
<td>${o.name}</td>
<td><code>${o.slug}</code></td>
<td>${new Date(o.createdAt).toLocaleDateString()}</td>
<td>${(o.features || []).join(', ') || '—'}</td>
</tr>`).join('')}
</tbody></table>`;
} catch { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; }
}
async function loadStorage() {
const el = document.getElementById('storage-body');
try {
const res = await Api.get('/api/v1/admin/storage');
if (!res.ok) throw new Error();
const { data } = await res.json();
const pct = data.total ? Math.round(data.used / data.total * 100) : 0;
el.innerHTML = `
<div class="progress-bar-track" style="margin-bottom:var(--space-4);">
<div class="progress-bar-fill" style="width:${pct}%;background:${pct > 85 ? 'var(--color-danger)' : 'var(--color-primary)'}"></div>
</div>
<table class="table">
<tr><td><strong>Used</strong></td><td>${formatBytes(data.used)}</td></tr>
<tr><td><strong>Free</strong></td><td>${formatBytes(data.free)}</td></tr>
<tr><td><strong>Total</strong></td><td>${formatBytes(data.total)}</td></tr>
<tr><td><strong>Used %</strong></td><td>${pct}%</td></tr>
</table>`;
} catch { el.innerHTML = '<p class="text-secondary">Failed to load.</p>'; }
}
function formatBytes(b) {
if (!b) return '—';
const gb = b / 1_073_741_824;
return gb >= 1 ? `${gb.toFixed(1)} GB` : `${(b / 1_048_576).toFixed(0)} MB`;
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['SystemAdmin']);
loadHealth();
document.querySelectorAll('.tab').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
btn.classList.add('active');
['health', 'orgs', 'storage'].forEach(t => {
document.getElementById(`tab-${t}`).style.display = btn.dataset.tab === t ? '' : 'none';
});
if (btn.dataset.tab === 'orgs') loadOrgs();
if (btn.dataset.tab === 'storage') loadStorage();
});
});
});
</script>
</body>
</html>
+67
View File
@@ -0,0 +1,67 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Timer Display — VitFit</title>
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/display.css">
</head>
<body>
<div class="display-container phase-idle" id="timer-container">
<!-- Status bar: phase label + counters -->
<div class="display-status-bar">
<span class="display-status-label" id="timer-phase-label">READY</span>
<div class="display-status-right">
<span id="timer-lap">LAP 1/1</span>
<span id="timer-exercise">1/1 EX</span>
<span id="timer-set">SET 1/1</span>
</div>
</div>
<!-- Main countdown -->
<div class="display-main">
<div class="display-timer" id="timer-countdown">--:--</div>
<div class="display-exercise" id="timer-exercise-name"></div>
<div class="display-total-time" id="timer-total"></div>
</div>
<!-- Done/stopped overlay -->
<div class="display-overlay" id="timer-overlay">
<div class="display-overlay-title" id="timer-overlay-title">DONE</div>
<div class="display-overlay-sub">Great work!</div>
</div>
<!-- Coach invisible touch zones -->
<div class="touch-zone touch-zone-left"></div>
<div class="touch-zone touch-zone-right"></div>
</div>
<div id="display-offline-banner" class="display-offline-banner">Offline — running on local clock</div>
<div id="display-local-indicator" class="display-local-indicator">&#8987; local</div>
<script src="/js/core.js"></script>
<script src="/js/socket-client.js"></script>
<script src="/js/timer-display.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
const params = new URLSearchParams(window.location.search);
const sessionId = params.get('session');
if (!sessionId) {
document.getElementById('timer-phase-label').textContent = 'NO SESSION';
return;
}
// Apply branding
try {
const res = await fetch('/api/v1/org/branding/public');
if (res.ok) { const { data } = await res.json(); Branding.apply(data); }
} catch {}
TimerDisplay.init(sessionId);
});
</script>
</body>
</html>
+134
View File
@@ -0,0 +1,134 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Timers — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">Timers</h1>
<a href="/create-timer.html" class="btn btn-primary">Create Timer</a>
</div>
<!-- Active session banner -->
<div id="active-session-banner" style="display:none;" class="warning-banner">
<span id="active-session-label">Timer running</span>
<div class="flex gap-3">
<a id="active-session-display-link" href="#" class="btn btn-secondary btn-sm" target="_blank">Open Display</a>
<button id="stop-timer-btn" class="btn btn-danger btn-sm">Stop Timer</button>
</div>
</div>
<div id="timer-list">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box"><p>Your session has expired.</p><a href="/" class="btn btn-primary">Sign In Again</a></div>
</div>
<script src="/js/core.js"></script>
<script>
let _activeSession = null;
async function loadActiveSession() {
try {
const res = await Api.get('/api/v1/timers/session/active');
if (res.ok) {
const { data } = await res.json();
_activeSession = data;
const banner = document.getElementById('active-session-banner');
if (data) {
document.getElementById('active-session-label').textContent = `Running: ${data.timerName || 'Timer'}`;
document.getElementById('active-session-display-link').href = `/timer-display.html?session=${data.sessionId}`;
banner.style.display = 'flex';
} else {
banner.style.display = 'none';
}
}
} catch {}
}
async function loadTimers() {
const el = document.getElementById('timer-list');
try {
const res = await Api.get('/api/v1/timers');
if (!res.ok) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; return; }
const { data } = await res.json();
if (!data.length) { el.innerHTML = '<div class="empty-state"><p class="empty-state-text">No timers yet.</p><a href="/create-timer.html" class="btn btn-primary">Create one</a></div>'; return; }
el.innerHTML = `<table class="table"><thead><tr><th>Name</th><th>Type</th><th>Config</th><th></th></tr></thead><tbody>
${data.map(t => `<tr>
<td>${t.name}</td>
<td>${t.timerType}</td>
<td>${timerSummary(t)}</td>
<td class="table-actions">
<button class="btn btn-primary btn-sm" onclick="launchTimer(${t.id}, '${t.name.replace(/'/g, "\\'")}')">Launch</button>
</td>
</tr>`).join('')}
</tbody></table>`;
} catch {
el.innerHTML = '<div class="empty-state"><p class="empty-state-text">Error loading timers.</p></div>';
}
}
function timerSummary(t) {
const c = t.config || {};
if (t.timerType === 'interval') return `${c.sets ?? '?'}×${c.exerciseCount ?? '?'} ex | ${c.workSec ?? '?'}s work / ${c.restSec ?? '?'}s rest`;
if (t.timerType === 'amrap') return `${c.durationMin ?? '?'} min`;
if (t.timerType === 'emom') return `${c.rounds ?? '?'} rounds`;
if (t.timerType === 'tabata') return `${c.rounds ?? '?'} rounds`;
return '';
}
async function launchTimer(id, name) {
if (_activeSession) {
if (!confirm('A timer is already running. Stop it and launch this one?')) return;
await Api.del('/api/v1/timers/session').catch(() => {});
}
try {
const res = await Api.post(`/api/v1/timers/${id}/launch`, {});
if (res.ok) {
const { data } = await res.json();
toast(`${name} launched!`, 'success');
window.open(`/timer-display.html?session=${data.sessionId}`, '_blank');
loadActiveSession();
} else {
const b = await res.json();
toast(b.message || 'Failed to launch.', 'error');
}
} catch { toast('Network error.', 'error'); }
}
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
loadActiveSession();
loadTimers();
document.getElementById('stop-timer-btn').addEventListener('click', async () => {
if (!confirm('Stop the running timer?')) return;
try {
const res = await Api.del('/api/v1/timers/session');
if (res.ok) { toast('Timer stopped.', 'success'); loadActiveSession(); }
else { const b = await res.json(); toast(b.message || 'Failed.', 'error'); }
} catch { toast('Network error.', 'error'); }
});
});
</script>
</body>
</html>
+148
View File
@@ -0,0 +1,148 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Video — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">Upload Video</h1>
<a href="/videos.html" class="btn btn-ghost">Back to Videos</a>
</div>
<div class="card" style="max-width:600px;">
<form id="upload-form" novalidate>
<div class="form-group">
<label class="form-label" for="video-file">Video File <span class="required">*</span></label>
<input class="form-input" type="file" id="video-file" accept="video/*" required>
<p class="form-hint">MP4 recommended. Max 2GB.</p>
</div>
<div class="form-group">
<label class="form-label" for="description">Description <span class="required">*</span></label>
<input class="form-input" type="text" id="description" maxlength="200" required>
</div>
<div class="form-group">
<label class="form-label" for="category-id">Category</label>
<select class="form-select" id="category-id">
<option value="">None</option>
</select>
</div>
<div class="form-group">
<label class="form-label" for="thumbnail">Thumbnail (optional)</label>
<input class="form-input" type="file" id="thumbnail" accept="image/*">
</div>
<div id="progress-wrap" style="display:none;" class="form-group">
<div class="progress-bar-track">
<div class="progress-bar-fill" id="progress-bar" style="width:0%"></div>
</div>
<p id="progress-label" class="form-hint">0%</p>
</div>
<div id="upload-error" class="form-error" style="display:none;"></div>
<button class="btn btn-primary" type="submit" id="upload-btn">Upload</button>
</form>
</div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box">
<p>Your session has expired.</p>
<a href="/" class="btn btn-primary">Sign In Again</a>
</div>
</div>
<script src="/js/core.js"></script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
// Load categories
try {
const res = await Api.get('/api/v1/categories');
if (res.ok) {
const { data } = await res.json();
const sel = document.getElementById('category-id');
data.forEach(c => {
const opt = document.createElement('option');
opt.value = c.id; opt.textContent = c.name;
sel.appendChild(opt);
});
}
} catch {}
document.getElementById('upload-form').addEventListener('submit', async (e) => {
e.preventDefault();
const errEl = document.getElementById('upload-error');
const btn = document.getElementById('upload-btn');
const progWrap = document.getElementById('progress-wrap');
const progBar = document.getElementById('progress-bar');
const progLabel = document.getElementById('progress-label');
errEl.style.display = 'none';
const file = document.getElementById('video-file').files[0];
if (!file) { errEl.textContent = 'Please select a video.'; errEl.style.display = 'block'; return; }
const fd = new FormData();
fd.append('video', file);
fd.append('description', document.getElementById('description').value.trim());
const catId = document.getElementById('category-id').value;
if (catId) fd.append('categoryId', catId);
const thumb = document.getElementById('thumbnail').files[0];
if (thumb) fd.append('thumbnail', thumb);
btn.disabled = true; btn.textContent = 'Uploading…';
progWrap.style.display = 'block';
// Use XHR for progress
const jwt = Auth.getJwt();
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/v1/videos');
if (jwt) xhr.setRequestHeader('Authorization', `Bearer ${jwt}`);
xhr.upload.addEventListener('progress', (ev) => {
if (ev.lengthComputable) {
const pct = Math.round(ev.loaded / ev.total * 100);
progBar.style.width = pct + '%';
progLabel.textContent = pct + '%';
}
});
xhr.addEventListener('load', () => {
if (xhr.status >= 200 && xhr.status < 300) {
toast('Video uploaded successfully!', 'success');
setTimeout(() => { window.location.href = '/videos.html'; }, 1200);
} else {
let msg = 'Upload failed.';
try { msg = JSON.parse(xhr.responseText).message || msg; } catch {}
errEl.textContent = msg; errEl.style.display = 'block';
btn.disabled = false; btn.textContent = 'Upload';
}
});
xhr.addEventListener('error', () => {
errEl.textContent = 'Network error during upload.'; errEl.style.display = 'block';
btn.disabled = false; btn.textContent = 'Upload';
});
xhr.send(fd);
});
});
</script>
</body>
</html>
+119
View File
@@ -0,0 +1,119 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Videos — VitFit</title>
<link rel="manifest" href="/manifest.json">
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/layout.css">
<link rel="stylesheet" href="/styles/components.css">
</head>
<body>
<header class="banner">
<button class="banner-hamburger" id="nav-hamburger" aria-label="Menu">&#9776;</button>
<img id="banner-logo" alt="Logo" style="display:none;height:36px;">
<span id="app-name" class="banner-title">VitFit</span>
</header>
<div class="drawer-scrim" id="drawer-scrim"></div>
<nav class="nav-drawer" id="nav-drawer"><ul class="nav-list" id="nav-list"></ul></nav>
<main class="main-content">
<div class="page-header">
<h1 class="page-title">Videos</h1>
<a href="/upload-video.html" class="btn btn-primary">Upload Video</a>
</div>
<!-- Search + filter -->
<div class="filter-bar">
<input class="form-input filter-search" type="search" id="search" placeholder="Search videos…">
<select class="form-select" id="category-filter">
<option value="">All Categories</option>
</select>
</div>
<div id="video-grid" class="video-grid">
<div class="empty-state"><p class="empty-state-text">Loading…</p></div>
</div>
<div id="pagination" class="pagination"></div>
</main>
<div id="session-expired-overlay" class="session-expired-overlay">
<div class="session-expired-box">
<p>Your session has expired.</p>
<a href="/" class="btn btn-primary">Sign In Again</a>
</div>
</div>
<script src="/js/core.js"></script>
<script>
let _page = 1, _search = '', _category = '';
async function loadVideos() {
const grid = document.getElementById('video-grid');
try {
const res = await Api.get('/api/v1/videos', { page: _page, limit: 20, search: _search, categoryId: _category });
if (!res.ok) { grid.innerHTML = '<div class="empty-state"><p class="empty-state-text">Failed to load.</p></div>'; return; }
const { data, meta } = await res.json();
if (!data.length) { grid.innerHTML = '<div class="empty-state"><p class="empty-state-text">No videos found.</p></div>'; return; }
grid.innerHTML = data.map(v => `
<div class="video-card">
<div class="video-card-thumb">
${v.thumbnailPath ? `<img src="${v.thumbnailPath}" alt="">` : '<div class="video-card-thumb-placeholder"></div>'}
</div>
<div class="video-card-body">
<p class="video-card-title">${v.description || 'Untitled'}</p>
${v.category ? `<span class="badge">${v.category.name}</span>` : ''}
</div>
</div>`).join('');
renderPagination(meta);
} catch {
grid.innerHTML = '<div class="empty-state"><p class="empty-state-text">Error loading videos.</p></div>';
}
}
function renderPagination(meta) {
const el = document.getElementById('pagination');
if (!meta || meta.totalPages <= 1) { el.innerHTML = ''; return; }
el.innerHTML = `
<button class="btn btn-ghost btn-sm" ${_page <= 1 ? 'disabled' : ''} onclick="changePage(${_page - 1})">Previous</button>
<span class="pagination-info">Page ${meta.page} of ${meta.totalPages}</span>
<button class="btn btn-ghost btn-sm" ${_page >= meta.totalPages ? 'disabled' : ''} onclick="changePage(${_page + 1})">Next</button>`;
}
function changePage(p) { _page = p; loadVideos(); }
document.addEventListener('DOMContentLoaded', async () => {
await Page.init(['Owner', 'Coach']);
// Load categories
try {
const res = await Api.get('/api/v1/categories');
if (res.ok) {
const { data } = await res.json();
const sel = document.getElementById('category-filter');
data.forEach(c => {
const opt = document.createElement('option');
opt.value = c.id; opt.textContent = c.name;
sel.appendChild(opt);
});
}
} catch {}
const search = document.getElementById('search');
const catFilter = document.getElementById('category-filter');
let debounce;
search.addEventListener('input', () => {
clearTimeout(debounce);
debounce = setTimeout(() => { _search = search.value; _page = 1; loadVideos(); }, 300);
});
catFilter.addEventListener('change', () => { _category = catFilter.value; _page = 1; loadVideos(); });
loadVideos();
});
</script>
</body>
</html>
+60
View File
@@ -0,0 +1,60 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Workout Display — VitFit</title>
<link rel="stylesheet" href="/styles/base.css">
<link rel="stylesheet" href="/styles/display.css">
</head>
<body>
<div class="display-container phase-idle" id="timer-container">
<div class="display-status-bar">
<span class="display-status-label" id="display-workout-name">Loading…</span>
<span class="display-status-right" id="display-workout-date"></span>
</div>
<div class="display-main">
<ul class="display-workout-list" id="display-workout-list"></ul>
</div>
<div class="touch-zone touch-zone-left" id="touch-left"></div>
<div class="touch-zone touch-zone-right" id="touch-right"></div>
</div>
<div id="display-offline-banner" class="display-offline-banner">Offline — last known data shown</div>
<script src="/js/core.js"></script>
<script src="/js/display.js"></script>
<script>
document.addEventListener('DOMContentLoaded', async () => {
const params = new URLSearchParams(window.location.search);
const id = params.get('id');
if (!id) { document.getElementById('display-workout-name').textContent = 'No workout selected.'; return; }
Display.startKeepAlive();
// Load branding without full auth gate
try {
const res = await fetch('/api/v1/org/branding/public');
if (res.ok) { const { data } = await res.json(); Display.applyBranding(data); }
} catch {}
async function load() {
try {
const jwt = Auth.getJwt();
const headers = jwt ? { Authorization: `Bearer ${jwt}` } : {};
const res = await fetch(`/api/v1/workouts/${id}`, { headers });
if (!res.ok) return;
const { data } = await res.json();
Display.renderWorkout(data);
} catch { Display.setOffline(true); }
}
load();
// Refresh every 30s to stay in sync
setInterval(load, 30000);
});
</script>
</body>
</html>

Some files were not shown because too many files have changed in this diff Show More