r2
This commit is contained in:
@@ -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