112 lines
4.9 KiB
JavaScript
112 lines
4.9 KiB
JavaScript
'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';
|
|
// workoutDate is stored as UTC midnight when submitted as a date string ("YYYY-MM-DD"),
|
|
// so we compare against the UTC date range matching today's local date.
|
|
const todayStr = DateTime.now().setZone(tz).toFormat('yyyy-MM-dd');
|
|
const start = new Date(`${todayStr}T00:00:00.000Z`);
|
|
const end = new Date(`${todayStr}T23:59:59.999Z`);
|
|
|
|
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 updateWorkout(models, req, id, orgId, data) {
|
|
const workout = await models.Workout.findOne({ where: { id, organizationId: orgId } });
|
|
if (!workout) throw new AppError('NOT_FOUND', 'Workout not found.', 404);
|
|
|
|
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}`);
|
|
}
|
|
}
|
|
|
|
await workout.update(data);
|
|
await auditLog(req, 'workout.update', 'workout', id, { name: workout.name });
|
|
return getWorkoutById(models, 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, updateWorkout, deleteWorkout };
|