Spaces:
Sleeping

gymco / src /modules /coaches /coaches.controller.js
moustafa7's picture
fix: Gap analysis — tenant isolation, memory leak, pagination
8eee19e
Raw History Blame Contribute Delete
2.75 kB
import { ApiError } from '../../common/errors/ApiError.js';
import { asyncHandler } from '../../common/middleware/asyncHandler.js';
import { ok } from '../../common/utils/response.js';
import { getPagination, paginated } from '../../common/utils/pagination.js';
import { coachesRepository } from './coaches.repository.js';
const assertCoachAccess = (req, coachId) => {
if (req.user.role === 'coach' && req.user.sub !== coachId) {
throw ApiError.forbidden('Coach can only access own data');
}
};
const startOfMonth = () => {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), 1);
};
export const coachesController = {
members: asyncHandler(async (req, res) => {
assertCoachAccess(req, req.params.id);
const pagination = getPagination(req.query);
const [items, total] = await coachesRepository.getMembers(req.gymId, req.params.id, pagination.skip, pagination.take);
ok(res, paginated(items, total, pagination.page, pagination.limit));
}),
memberDetail: asyncHandler(async (req, res) => {
assertCoachAccess(req, req.params.id);
const member = await coachesRepository.getMemberDetail(req.gymId, req.params.id, req.params.memberId);
if (!member) throw ApiError.notFound('Member not found');
const since = new Date();
since.setDate(since.getDate() - 30);
const [progress, notes, attendance] = await Promise.all([
coachesRepository.getMemberProgress(req.gymId, member.id),
coachesRepository.getMemberNotes(req.gymId, member.id),
coachesRepository.getMemberAttendance(req.gymId, member.id, since),
]);
ok(res, { member, progress, notes, attendance });
}),
stats: asyncHandler(async (req, res) => {
assertCoachAccess(req, req.params.id);
const [totalMembers, activeMembers, monthSessions, attendanceCount] = await Promise.all([
coachesRepository.countMembers(req.gymId, req.params.id),
coachesRepository.countActiveMembers(req.gymId, req.params.id),
coachesRepository.countMonthSessions(req.gymId, req.params.id, startOfMonth()),
coachesRepository.countAttendance(req.gymId, req.params.id),
]);
ok(res, {
totalMembers,
activeMembers,
avgAttendanceRate: totalMembers ? Math.round((attendanceCount / Math.max(totalMembers * 30, 1)) * 100) : 0,
thisMonthSessions: monthSessions,
});
}),
availability: asyncHandler(async (req, res) => {
ok(res, await coachesRepository.getAvailability(req.gymId, req.params.id));
}),
updateAvailability: asyncHandler(async (req, res) => {
assertCoachAccess(req, req.params.id);
const result = await coachesRepository.upsertAvailability(req.gymId, req.params.id, req.body);
ok(res, result, 'Availability updated');
}),
};