r2
This commit is contained in:
@@ -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');
|
||||
},
|
||||
};
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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');
|
||||
},
|
||||
};
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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;
|
||||
@@ -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 };
|
||||
@@ -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');
|
||||
},
|
||||
};
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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(() => {});
|
||||
},
|
||||
};
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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;
|
||||
@@ -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');
|
||||
},
|
||||
};
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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;
|
||||
@@ -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 };
|
||||
@@ -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(() => {});
|
||||
},
|
||||
};
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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;
|
||||
@@ -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 };
|
||||
@@ -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(() => {});
|
||||
},
|
||||
};
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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(() => {});
|
||||
},
|
||||
};
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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;
|
||||
@@ -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(() => {});
|
||||
},
|
||||
};
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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;
|
||||
@@ -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 };
|
||||
Reference in New Issue
Block a user