This commit is contained in:
Ccjcarkbla
2026-06-13 08:03:45 -04:00
parent cfcd6ae11e
commit a2c300678b
121 changed files with 8639 additions and 0 deletions
+22
View File
@@ -0,0 +1,22 @@
'use strict';
const express = require('express');
const { models } = require('../../core/db');
const { authenticateToken, authenticateRole, requireFeature } = require('../../core/auth');
const { collection } = require('../../core/respond');
const svc = require('./service');
const router = express.Router();
router.prefix = 'calendar';
const CALENDAR = requireFeature('calendar');
const COACH_PLUS = ['Owner', 'Coach', 'SystemAdmin'];
router.get('/', authenticateToken, CALENDAR, authenticateRole(COACH_PLUS), async (req, res, next) => {
try {
const { rows, count } = await svc.getSessions(models, req.query, req.user.organizationId, req.user.id, req.user.role);
collection(res, rows, count, +(req.query.page || 1), +(req.query.limit || 50));
} catch (err) { next(err); }
});
module.exports = router;
@@ -0,0 +1,24 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('CoachClientLinks', {
id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: Sequelize.INTEGER, allowNull: false },
coachId: { type: Sequelize.INTEGER, allowNull: false },
clientId: { type: Sequelize.INTEGER, allowNull: false },
isActive: { type: Sequelize.BOOLEAN, defaultValue: true },
assignedAt: { type: Sequelize.DATE, defaultValue: Sequelize.NOW },
assignedByUserId: { type: Sequelize.INTEGER },
createdAt: { type: Sequelize.DATE, allowNull: false },
updatedAt: { type: Sequelize.DATE, allowNull: false },
});
await queryInterface.addIndex('CoachClientLinks', ['coachId', 'clientId', 'isActive']);
await queryInterface.addIndex('CoachClientLinks', ['clientId', 'isActive']);
},
async down(queryInterface) {
await queryInterface.dropTable('CoachClientLinks');
},
};
@@ -0,0 +1,26 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('ClientWorkouts', {
id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: Sequelize.INTEGER, allowNull: false },
clientId: { type: Sequelize.INTEGER, allowNull: false },
coachId: { type: Sequelize.INTEGER, allowNull: false },
name: { type: Sequelize.STRING },
scheduledDate: { type: Sequelize.DATE },
notes: { type: Sequelize.TEXT },
items: { type: Sequelize.TEXT, defaultValue: '[]' },
completedAt: { type: Sequelize.DATE },
deletedAt: { type: Sequelize.DATE },
createdAt: { type: Sequelize.DATE, allowNull: false },
updatedAt: { type: Sequelize.DATE, allowNull: false },
});
await queryInterface.addIndex('ClientWorkouts', ['clientId', 'deletedAt', 'scheduledDate']);
},
async down(queryInterface) {
await queryInterface.dropTable('ClientWorkouts');
},
};
@@ -0,0 +1,30 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('CalendarSessions', {
id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: Sequelize.INTEGER, allowNull: false },
coachId: { type: Sequelize.INTEGER, allowNull: false },
clientId: { type: Sequelize.INTEGER },
title: { type: Sequelize.STRING },
sessionType: { type: Sequelize.ENUM('personal', 'group', 'assessment', 'other'), defaultValue: 'personal' },
startAt: { type: Sequelize.DATE, allowNull: false },
endAt: { type: Sequelize.DATE, allowNull: false },
locationNotes: { type: Sequelize.STRING },
coachNotes: { type: Sequelize.TEXT },
sharedNotes: { type: Sequelize.TEXT },
status: { type: Sequelize.ENUM('scheduled', 'completed', 'cancelled', 'no-show'), defaultValue: 'scheduled' },
linkedWorkoutId: { type: Sequelize.INTEGER },
createdAt: { type: Sequelize.DATE, allowNull: false },
updatedAt: { type: Sequelize.DATE, allowNull: false },
});
await queryInterface.addIndex('CalendarSessions', ['coachId', 'startAt']);
await queryInterface.addIndex('CalendarSessions', ['clientId', 'startAt']);
},
async down(queryInterface) {
await queryInterface.dropTable('CalendarSessions');
},
};
+51
View File
@@ -0,0 +1,51 @@
'use strict';
module.exports = (sequelize, DataTypes) => {
const CoachClientLink = sequelize.define('CoachClientLink', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER, allowNull: false },
coachId: { type: DataTypes.INTEGER, allowNull: false },
clientId: { type: DataTypes.INTEGER, allowNull: false },
isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
assignedAt: { type: DataTypes.DATE, defaultValue: DataTypes.NOW },
assignedByUserId: { type: DataTypes.INTEGER },
});
const ClientWorkout = sequelize.define('ClientWorkout', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER, allowNull: false },
clientId: { type: DataTypes.INTEGER, allowNull: false },
coachId: { type: DataTypes.INTEGER, allowNull: false },
name: { type: DataTypes.STRING },
scheduledDate: { type: DataTypes.DATE },
notes: { type: DataTypes.TEXT },
items: {
type: DataTypes.TEXT,
defaultValue: '[]',
get() { try { return JSON.parse(this.getDataValue('items') || '[]'); } catch { return []; } },
set(v) { this.setDataValue('items', JSON.stringify(v)); },
},
completedAt: { type: DataTypes.DATE },
deletedAt: { type: DataTypes.DATE },
});
ClientWorkout.addScope('active', { where: { deletedAt: null } });
const CalendarSession = sequelize.define('CalendarSession', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER, allowNull: false },
coachId: { type: DataTypes.INTEGER, allowNull: false },
clientId: { type: DataTypes.INTEGER },
title: { type: DataTypes.STRING },
sessionType: { type: DataTypes.ENUM('personal', 'group', 'assessment', 'other'), defaultValue: 'personal' },
startAt: { type: DataTypes.DATE, allowNull: false },
endAt: { type: DataTypes.DATE, allowNull: false },
locationNotes: { type: DataTypes.STRING },
coachNotes: { type: DataTypes.TEXT },
sharedNotes: { type: DataTypes.TEXT },
status: { type: DataTypes.ENUM('scheduled', 'completed', 'cancelled', 'no-show'), defaultValue: 'scheduled' },
linkedWorkoutId: { type: DataTypes.INTEGER },
});
return { CoachClientLink, ClientWorkout, CalendarSession };
};
+28
View File
@@ -0,0 +1,28 @@
'use strict';
const express = require('express');
const { models } = require('../../core/db');
const { authenticateToken, authenticateRole, requireFeature } = require('../../core/auth');
const { ok, collection } = require('../../core/respond');
const svc = require('./service');
const router = express.Router();
// These are mounted under /my by app.js via a separate prefix registration
router.prefix = 'my/client';
router.get('/workouts', authenticateToken, authenticateRole(['Client']), async (req, res, next) => {
try {
const { page = 1, limit = 20, includeCompleted } = req.query;
const { rows, count } = await svc.getClientWorkouts(models, req.user.id, req.user.id, req.user.organizationId, 'Client', { page: +page, limit: +limit, includeCompleted });
collection(res, rows, count, +page, +limit);
} catch (err) { next(err); }
});
router.get('/sessions', authenticateToken, authenticateRole(['Client']), async (req, res, next) => {
try {
const { rows, count } = await svc.getSessions(models, req.query, req.user.organizationId, req.user.id, 'Client');
collection(res, rows, count, +(req.query.page || 1), +(req.query.limit || 20));
} catch (err) { next(err); }
});
module.exports = router;
+152
View File
@@ -0,0 +1,152 @@
'use strict';
const express = require('express');
const { models } = require('../../core/db');
const { authenticateToken, authenticateRole, requireFeature } = require('../../core/auth');
const { ok, created, collection, noContent } = require('../../core/respond');
const { AppError } = require('../../core/errors');
const { createClient, assignCoach: assignCoachSchema, createClientWorkout, updateClientWorkout, createSession, updateSession } = require('../../core/schemas/clients');
const { createUser: createUserSchema } = require('../../core/schemas/users');
const svc = require('./service');
const userSvc = require('../users/service');
const router = express.Router();
router.prefix = 'clients';
const COACH_PLUS = ['Owner', 'Coach', 'SystemAdmin'];
const OWNERS = ['Owner', 'SystemAdmin'];
const ALL_AUTHENTICATED = ['Owner', 'Coach', 'Client', 'SystemAdmin'];
const CLIENT_MGMT = requireFeature('client-management');
function validate(schema) {
return (req, res, next) => {
const result = schema.safeParse(req.body);
if (!result.success) {
const e = result.error.errors[0];
return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0]));
}
req.body = result.data;
next();
};
}
// GET /clients
router.get('/', authenticateToken, CLIENT_MGMT, authenticateRole(COACH_PLUS), async (req, res, next) => {
try {
const clients = await svc.getClients(models, req.user.id, req.user.organizationId, req.user.role);
ok(res, clients.map(c => c.toPublic()));
} catch (err) { next(err); }
});
// POST /clients
router.post('/', authenticateToken, CLIENT_MGMT, authenticateRole(OWNERS), validate(createClient), async (req, res, next) => {
try {
const { coachId, ...userData } = req.body;
userData.role = 'Client';
const user = await userSvc.createUser(models, req, req.user.organizationId, userData);
if (coachId) await svc.assignCoach(models, req, user.id, coachId, req.user.organizationId);
ok(res, user);
} catch (err) { next(err); }
});
// GET /clients/:id
router.get('/:id', authenticateToken, CLIENT_MGMT, authenticateRole(COACH_PLUS), async (req, res, next) => {
try {
const client = await svc.getClientById(models, parseInt(req.params.id, 10), req.user.id, req.user.organizationId, req.user.role);
ok(res, client.toPublic());
} catch (err) { next(err); }
});
// POST /clients/:id/assign
router.post('/:id/assign', authenticateToken, CLIENT_MGMT, authenticateRole(OWNERS), validate(assignCoachSchema), async (req, res, next) => {
try {
const link = await svc.assignCoach(models, req, parseInt(req.params.id, 10), req.body.coachId, req.user.organizationId);
ok(res, link);
} catch (err) { next(err); }
});
// DELETE /clients/:id/assign
router.delete('/:id/assign', authenticateToken, CLIENT_MGMT, authenticateRole(OWNERS), async (req, res, next) => {
try {
const { linkId } = req.body;
if (!linkId) return next(new AppError('VALIDATION_FAILED', 'linkId required.', 400));
await svc.unassignCoach(models, req, linkId, req.user.organizationId);
noContent(res);
} catch (err) { next(err); }
});
// GET /clients/:id/workouts
router.get('/:id/workouts', authenticateToken, CLIENT_MGMT, authenticateRole([...COACH_PLUS, 'Client']), async (req, res, next) => {
try {
const { page = 1, limit = 20, includeCompleted } = req.query;
const { rows, count } = await svc.getClientWorkouts(models, parseInt(req.params.id, 10), req.user.id, req.user.organizationId, req.user.role, { page: +page, limit: +limit, includeCompleted });
collection(res, rows, count, +page, +limit);
} catch (err) { next(err); }
});
// POST /clients/:id/workouts
router.post('/:id/workouts', authenticateToken, CLIENT_MGMT, authenticateRole(COACH_PLUS), validate(createClientWorkout), async (req, res, next) => {
try {
const workout = await svc.createClientWorkout(models, req, req.user.organizationId, { clientId: parseInt(req.params.id, 10), ...req.body });
created(res, workout);
} catch (err) { next(err); }
});
// PATCH /clients/:id/workouts/:workoutId
router.patch('/:id/workouts/:workoutId', authenticateToken, CLIENT_MGMT, authenticateRole(COACH_PLUS), validate(updateClientWorkout), async (req, res, next) => {
try {
const workout = await svc.updateClientWorkout(models, req, parseInt(req.params.workoutId, 10), req.user.organizationId, req.body);
ok(res, workout);
} catch (err) { next(err); }
});
// DELETE /clients/:id/workouts/:workoutId
router.delete('/:id/workouts/:workoutId', authenticateToken, CLIENT_MGMT, authenticateRole(COACH_PLUS), async (req, res, next) => {
try {
await svc.deleteClientWorkout(models, req, parseInt(req.params.workoutId, 10), req.user.organizationId);
noContent(res);
} catch (err) { next(err); }
});
// POST /clients/:id/workouts/:workoutId/complete
router.post('/:id/workouts/:workoutId/complete', authenticateToken, CLIENT_MGMT, authenticateRole([...COACH_PLUS, 'Client']), async (req, res, next) => {
try {
const workout = await svc.completeClientWorkout(models, req, parseInt(req.params.workoutId, 10), req.user.organizationId);
ok(res, { completedAt: workout.completedAt });
} catch (err) { next(err); }
});
// GET /clients/:id/sessions
router.get('/:id/sessions', authenticateToken, CLIENT_MGMT, authenticateRole([...COACH_PLUS, 'Client']), async (req, res, next) => {
try {
const { rows, count } = await svc.getSessions(models, { clientId: req.params.id, ...req.query }, req.user.organizationId, req.user.id, req.user.role);
collection(res, rows, count, +(req.query.page || 1), +(req.query.limit || 20));
} catch (err) { next(err); }
});
// POST /clients/:id/sessions
router.post('/:id/sessions', authenticateToken, CLIENT_MGMT, authenticateRole(COACH_PLUS), validate(createSession), async (req, res, next) => {
try {
const session = await svc.createSession(models, req, req.user.organizationId, { clientId: parseInt(req.params.id, 10), ...req.body });
created(res, session);
} catch (err) { next(err); }
});
// PATCH /clients/:id/sessions/:sessionId
router.patch('/:id/sessions/:sessionId', authenticateToken, CLIENT_MGMT, authenticateRole([...COACH_PLUS, 'Client']), validate(updateSession), async (req, res, next) => {
try {
const session = await svc.updateSession(models, req, parseInt(req.params.sessionId, 10), req.user.organizationId, req.body);
ok(res, session);
} catch (err) { next(err); }
});
// POST /clients/:id/sessions/:sessionId/cancel
router.post('/:id/sessions/:sessionId/cancel', authenticateToken, CLIENT_MGMT, authenticateRole([...COACH_PLUS, 'Client']), async (req, res, next) => {
try {
const session = await svc.cancelSession(models, req, parseInt(req.params.sessionId, 10), req.user.organizationId, req.user.role);
ok(res, { status: session.status });
} catch (err) { next(err); }
});
module.exports = router;
+186
View File
@@ -0,0 +1,186 @@
'use strict';
const { Op } = require('sequelize');
const { AppError } = require('../../core/errors');
const { log: auditLog } = require('../../core/audit');
const STREAM_BASE = '/api/v1/videos/stream/';
async function getClients(models, requesterId, orgId, requesterRole) {
if (requesterRole === 'Owner' || requesterRole === 'SystemAdmin') {
return models.User.findAll({ where: { organizationId: orgId, role: 'Client', isActive: true } });
}
// Coach — only assigned clients
const links = await models.CoachClientLink.findAll({ where: { coachId: requesterId, organizationId: orgId, isActive: true } });
const clientIds = links.map(l => l.clientId);
if (!clientIds.length) return [];
return models.User.findAll({ where: { id: clientIds, isActive: true } });
}
async function getClientById(models, clientId, requesterId, orgId, requesterRole) {
if (requesterRole === 'Coach') {
const link = await models.CoachClientLink.findOne({ where: { coachId: requesterId, clientId, organizationId: orgId, isActive: true } });
if (!link) throw new AppError('NOT_FOUND', 'Client not found.', 404);
}
const user = await models.User.findOne({ where: { id: clientId, organizationId: orgId, role: 'Client' } });
if (!user) throw new AppError('NOT_FOUND', 'Client not found.', 404);
return user;
}
async function assignCoach(models, req, clientId, coachId, orgId) {
const [client, coach] = await Promise.all([
models.User.findOne({ where: { id: clientId, organizationId: orgId, role: 'Client' } }),
models.User.findOne({ where: { id: coachId, organizationId: orgId, role: { [Op.in]: ['Coach', 'Owner'] } } }),
]);
if (!client) throw new AppError('NOT_FOUND', 'Client not found.', 404);
if (!coach) throw new AppError('NOT_FOUND', 'Coach not found.', 404);
await models.CoachClientLink.update({ isActive: false }, { where: { clientId, organizationId: orgId, isActive: true } });
const link = await models.CoachClientLink.create({ organizationId: orgId, coachId, clientId, assignedByUserId: req.user.id });
await auditLog(req, 'coach.client.assign', 'coach_client_link', link.id, { coachId, clientId });
return link;
}
async function unassignCoach(models, req, linkId, orgId) {
const link = await models.CoachClientLink.findOne({ where: { id: linkId, organizationId: orgId } });
if (!link) throw new AppError('NOT_FOUND', 'Link not found.', 404);
await link.update({ isActive: false });
await auditLog(req, 'coach.client.unassign', 'coach_client_link', linkId, {});
}
async function getClientWorkouts(models, clientId, requesterId, orgId, requesterRole, { page = 1, limit = 20, includeCompleted = false } = {}) {
if (requesterRole === 'Coach') {
const link = await models.CoachClientLink.findOne({ where: { coachId: requesterId, clientId, organizationId: orgId, isActive: true } });
if (!link) throw new AppError('NOT_FOUND', 'Client not found.', 404);
} else if (requesterRole === 'Client' && requesterId !== clientId) {
throw new AppError('AUTH_FORBIDDEN', 'Forbidden.', 403);
}
const where = { clientId, organizationId: orgId, deletedAt: null };
if (!includeCompleted || includeCompleted === 'false') where.completedAt = null;
const offset = (page - 1) * limit;
const { rows, count } = await models.ClientWorkout.findAndCountAll({
where, limit, offset, order: [['scheduledDate', 'ASC']],
});
const isClient = requesterRole === 'Client';
return {
rows: rows.map(w => {
const obj = w.toJSON();
if (isClient) delete obj.notes; // strip coach notes
// Attach streamUrl to video items
obj.items = obj.items.map(item => {
if (item.type === 'video') return { ...item, streamUrl: STREAM_BASE + (item.filename || '') };
return item;
});
return obj;
}),
count,
};
}
async function createClientWorkout(models, req, orgId, { clientId, name, scheduledDate, notes, items }) {
const link = await models.CoachClientLink.findOne({ where: { coachId: req.user.id, clientId, organizationId: orgId, isActive: true } });
if (!link) throw new AppError('NOT_FOUND', 'Client not found or not assigned to you.', 404);
// Validate video items
for (const item of items.filter(i => i.type === 'video')) {
const video = await models.Video.findOne({ where: { id: item.videoId, organizationId: orgId } });
if (!video) throw new AppError('VALIDATION_FAILED', `Video ${item.videoId} not found in your library.`, 400);
}
const workout = await models.ClientWorkout.create({ organizationId: orgId, clientId, coachId: req.user.id, name, scheduledDate, notes, items });
await auditLog(req, 'client_workout.create', 'client_workout', workout.id, { clientId, name });
return workout;
}
async function updateClientWorkout(models, req, id, orgId, data) {
const workout = await models.ClientWorkout.scope('active').findOne({ where: { id, organizationId: orgId, coachId: req.user.id } });
if (!workout) throw new AppError('NOT_FOUND', 'Workout not found.', 404);
const before = workout.toJSON();
await workout.update(data);
await auditLog(req, 'client_workout.update', 'client_workout', id, { before, after: data });
return workout;
}
async function deleteClientWorkout(models, req, id, orgId) {
const workout = await models.ClientWorkout.scope('active').findOne({ where: { id, organizationId: orgId, coachId: req.user.id } });
if (!workout) throw new AppError('NOT_FOUND', 'Workout not found.', 404);
await workout.update({ deletedAt: new Date() });
await auditLog(req, 'client_workout.delete', 'client_workout', id, {});
}
async function completeClientWorkout(models, req, id, orgId) {
const where = { id, organizationId: orgId, deletedAt: null };
if (req.user.role === 'Client') where.clientId = req.user.id;
if (req.user.role === 'Coach') where.coachId = req.user.id;
const workout = await models.ClientWorkout.findOne({ where });
if (!workout) throw new AppError('NOT_FOUND', 'Workout not found.', 404);
await workout.update({ completedAt: new Date() });
await auditLog(req, 'client_workout.complete', 'client_workout', id, {});
return workout;
}
async function getSessions(models, filters, orgId, requesterId, requesterRole) {
const { clientId, startAfter, endBefore, status, page = 1, limit = 20 } = filters;
const where = { organizationId: orgId };
if (requesterRole === 'Coach') where.coachId = requesterId;
else if (requesterRole === 'Client') where.clientId = requesterId;
if (clientId) where.clientId = clientId;
if (status) where.status = status;
if (startAfter) where.startAt = { [Op.gte]: new Date(startAfter) };
if (endBefore) where.endAt = { ...where.endAt, [Op.lte]: new Date(endBefore) };
const offset = (page - 1) * limit;
const { rows, count } = await models.CalendarSession.findAndCountAll({ where, limit, offset, order: [['startAt', 'ASC']] });
return {
rows: rows.map(s => {
const obj = s.toJSON();
if (requesterRole === 'Client') delete obj.coachNotes;
return obj;
}),
count,
};
}
async function createSession(models, req, orgId, data) {
if (new Date(data.endAt) <= new Date(data.startAt)) {
throw new AppError('VALIDATION_FAILED', 'endAt must be after startAt.', 400, 'endAt');
}
const session = await models.CalendarSession.create({ ...data, organizationId: orgId, coachId: req.user.id });
await auditLog(req, 'session.create', 'calendar_session', session.id, { title: data.title });
return session;
}
async function updateSession(models, req, id, orgId, data) {
const session = await models.CalendarSession.findOne({ where: { id, organizationId: orgId } });
if (!session) throw new AppError('NOT_FOUND', 'Session not found.', 404);
const before = session.toJSON();
await session.update(data);
await auditLog(req, 'session.update', 'calendar_session', id, { before, after: data });
return session;
}
async function cancelSession(models, req, id, orgId, actorRole) {
const session = await models.CalendarSession.findOne({ where: { id, organizationId: orgId } });
if (!session) throw new AppError('NOT_FOUND', 'Session not found.', 404);
if (actorRole === 'Client') {
const hoursUntil = (new Date(session.startAt) - Date.now()) / 3_600_000;
if (hoursUntil < 24) {
throw new AppError('CANCELLATION_TOO_LATE', 'Sessions must be cancelled at least 24 hours in advance.', 400);
}
}
await session.update({ status: 'cancelled' });
await auditLog(req, 'session.cancel', 'calendar_session', id, { cancelledBy: actorRole });
return session;
}
module.exports = { getClients, getClientById, assignCoach, unassignCoach, getClientWorkouts, createClientWorkout, updateClientWorkout, deleteClientWorkout, completeClientWorkout, getSessions, createSession, updateSession, cancelSession };