Files
vitfit-r2/V2/app/modules/clients/service.js
T
2026-06-13 08:03:45 -04:00

187 lines
8.6 KiB
JavaScript

'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 };