import { ApiError } from '../../common/errors/ApiError.js'; import { asyncHandler } from '../../common/middleware/asyncHandler.js'; import { getPagination, paginated } from '../../common/utils/pagination.js'; import { hashPassword } from '../../common/utils/password.js'; import { created, ok } from '../../common/utils/response.js'; import { prisma } from '../../config/prisma.js'; import { membersRepository } from './members.repository.js'; import { membersService } from './members.service.js'; export const membersController = { list: asyncHandler(async (req, res) => { const pagination = getPagination(req.query); const [items, total] = await membersRepository.list({ gymId: req.gymId, search: req.query.search, status: req.query.status, ...pagination, }); ok(res, paginated(items, total, pagination.page, pagination.limit)); }), get: asyncHandler(async (req, res) => { const member = await membersRepository.findById(req.gymId, req.params.id); if (!member) throw ApiError.notFound('Member not found'); ok(res, member); }), create: asyncHandler(async (req, res) => { if (req.body.coachId) { const coach = await prisma.user.findFirst({ where: { id: req.body.coachId, gymId: req.gymId, role: 'coach', deletedAt: null, isActive: true } }); if (!coach) throw ApiError.badRequest('Coach must belong to the same gym'); } const { accountPassword, ...memberPayload } = req.body; if (accountPassword && !memberPayload.email) throw ApiError.badRequest('Email is required to create member login'); const result = await prisma.$transaction(async (tx) => { const member = await tx.member.create({ data: { ...memberPayload, gymId: req.gymId }, select: { id: true, gymId: true, fullName: true, phone: true, nationalId: true, email: true, gender: true, birthDate: true, weight: true, height: true, photo: true, qrToken: true, discountPercent: true, discountAmount: true, coachId: true, coach: { select: { id: true, name: true, email: true } }, status: true, createdAt: true, updatedAt: true, }, }); let account = null; if (accountPassword) { account = await tx.user.create({ data: { gymId: req.gymId, memberId: member.id, name: member.fullName, email: member.email, phone: member.phone, nationalId: member.nationalId, password: await hashPassword(accountPassword), role: 'member', }, select: { id: true, gymId: true, memberId: true, name: true, email: true, role: true }, }); } return { ...member, account }; }); created(res, result, result.account ? 'Member and login account created' : 'Member created'); }), me: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); const member = await membersRepository.findProfile(req.gymId, req.user.memberId); if (!member) throw ApiError.notFound('Member profile not found'); ok(res, member); }), meDashboard: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); const now = new Date(); const monthStart = new Date(now.getFullYear(), now.getMonth(), 1); const [subscription, attendanceThisMonth, upcomingSessions, lastAttendance, member] = await Promise.all([ prisma.subscription.findFirst({ where: { gymId: req.gymId, memberId: req.user.memberId, status: 'active', endDate: { gte: now }, deletedAt: null }, orderBy: { endDate: 'desc' }, include: { plan: true } }), prisma.attendance.count({ where: { gymId: req.gymId, memberId: req.user.memberId, checkIn: { gte: monthStart }, deletedAt: null } }), prisma.coachSession.findMany({ where: { gymId: req.gymId, memberId: req.user.memberId, sessionDate: { gte: now }, deletedAt: null }, include: { coach: { select: { id: true, name: true } } }, orderBy: { sessionDate: 'asc' }, take: 5 }), prisma.attendance.findFirst({ where: { gymId: req.gymId, memberId: req.user.memberId, deletedAt: null }, orderBy: { checkIn: 'desc' } }), prisma.member.findFirst({ where: { id: req.user.memberId, gymId: req.gymId, deletedAt: null } }), ]); const daysRemaining = subscription ? Math.max(Math.ceil((subscription.endDate.getTime() - now.getTime()) / 86400000), 0) : 0; ok(res, { daysRemaining, attendanceThisMonth, currentStreak: attendanceThisMonth, longestStreak: attendanceThisMonth, upcomingSessions, lastAttendance: lastAttendance?.checkIn || null, memberSince: member ? Math.ceil((now.getTime() - member.createdAt.getTime()) / 86400000) : 0, }); }), meHeatmap: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); const year = Number(req.query.year || new Date().getFullYear()); const start = new Date(year, 0, 1); const end = new Date(year + 1, 0, 1); const rows = await prisma.attendance.findMany({ where: { gymId: req.gymId, memberId: req.user.memberId, checkIn: { gte: start, lt: end }, deletedAt: null } }); const byDate = new Map(rows.map((row) => [row.checkIn.toISOString().slice(0, 10), row])); const days = []; for (const day = new Date(start); day < end; day.setDate(day.getDate() + 1)) { const key = day.toISOString().slice(0, 10); days.push({ date: key, attended: byDate.has(key), hours: byDate.get(key)?.checkOut ? (byDate.get(key).checkOut.getTime() - byDate.get(key).checkIn.getTime()) / 3600000 : 1 }); } ok(res, days); }), mePayments: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); ok(res, await prisma.payment.findMany({ where: { gymId: req.gymId, memberId: req.user.memberId, deletedAt: null }, orderBy: { paymentDate: 'desc' }, take: Number(req.query.limit || 5), include: { subscription: { include: { plan: true } } } })); }), updateMyProfile: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); const allowed = (({ fullName, phone, birthDate, height, weight }) => ({ fullName, phone, birthDate, height, weight }))(req.body); ok(res, await membersRepository.update(req.gymId, req.user.memberId, allowed), 'Profile updated'); }), uploadMyAvatar: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); if (!req.file) throw ApiError.badRequest('Image file is required'); ok(res, await membersService.attachUploadedImage(req.gymId, req.user.memberId, req.file), 'Avatar uploaded'); }), myQr: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); ok(res, await membersService.generateQr(req.gymId, req.user.memberId), 'Member QR generated'); }), assignMyCoach: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); if (req.body.coachId) { const coach = await prisma.user.findFirst({ where: { id: req.body.coachId, gymId: req.gymId, role: 'coach', deletedAt: null, isActive: true } }); if (!coach) throw ApiError.badRequest('Coach must belong to the same gym'); } ok(res, await membersRepository.update(req.gymId, req.user.memberId, { coachId: req.body.coachId }), 'Coach selection updated'); }), availableCoaches: asyncHandler(async (req, res) => { const today = new Date(); today.setHours(0, 0, 0, 0); const tomorrow = new Date(today); tomorrow.setDate(tomorrow.getDate() + 1); const coaches = await prisma.user.findMany({ where: { gymId: req.gymId, role: 'coach', isActive: true, deletedAt: null }, select: { id: true, name: true, email: true, phone: true, nationalId: true, _count: { select: { coachedMembers: { where: { gymId: req.gymId, deletedAt: null } } } }, coachAttendance: { where: { gymId: req.gymId, attendanceDate: { gte: today, lt: tomorrow }, deletedAt: null }, select: { status: true, checkIn: true }, take: 1, }, }, orderBy: { name: 'asc' }, }); ok(res, coaches.map((coach) => { const todayAttendance = coach.coachAttendance[0]; const todayStatus = todayAttendance?.status || 'not_checked_in'; return { id: coach.id, name: coach.name, email: coach.email, phone: coach.phone, nationalId: coach.nationalId, assignedMembers: coach._count.coachedMembers, todayStatus, availableNow: todayStatus !== 'absent', checkedInAt: todayAttendance?.checkIn || null, }; })); }), scanPreview: asyncHandler(async (req, res) => { const member = await prisma.member.findFirst({ where: { gymId: req.gymId, deletedAt: null, OR: [{ qrToken: req.params.identifier }, { barcodeId: req.params.identifier }], }, include: { subscriptions: { where: { deletedAt: null }, orderBy: { endDate: 'desc' }, take: 1, include: { plan: true } }, attendance: { where: { deletedAt: null }, orderBy: { checkIn: 'desc' }, take: 1 }, }, }); if (!member) throw ApiError.notFound('Member not found'); ok(res, { member, activeSubscription: member.subscriptions.find((item) => item.status === 'active' && new Date(item.endDate) > new Date()) || null, lastAttendance: member.attendance[0] || null, }); }), setBarcode: asyncHandler(async (req, res) => { ok(res, await membersRepository.update(req.gymId, req.params.id, { barcodeId: req.body.barcodeId || null }), 'Member barcode updated'); }), assignedToMe: asyncHandler(async (req, res) => { ok(res, await prisma.member.findMany({ where: { gymId: req.gymId, coachId: req.user.sub, deletedAt: null }, select: { id: true, gymId: true, fullName: true, phone: true, nationalId: true, email: true, status: true, coachId: true, createdAt: true, }, orderBy: { fullName: 'asc' }, })); }), update: asyncHandler(async (req, res) => { if (req.body.coachId) { const coach = await prisma.user.findFirst({ where: { id: req.body.coachId, gymId: req.gymId, role: 'coach', deletedAt: null, isActive: true } }); if (!coach) throw ApiError.badRequest('Coach must belong to the same gym'); } ok(res, await membersRepository.update(req.gymId, req.params.id, req.body), 'Member updated'); }), applyDiscount: asyncHandler(async (req, res) => { const member = await membersRepository.findById(req.gymId, req.params.id); if (!member) throw ApiError.notFound('Member not found'); const updated = await prisma.$transaction(async (tx) => { const savedMember = await tx.member.update({ where: { id: req.params.id, gymId: req.gymId }, data: { discountPercent: req.body.discountPercent ?? null, discountAmount: req.body.discountAmount ?? null, }, select: { id: true, gymId: true, fullName: true, phone: true, nationalId: true, email: true, discountPercent: true, discountAmount: true, status: true, coachId: true, coach: { select: { id: true, name: true, email: true } }, createdAt: true, updatedAt: true, }, }); const activeSubscriptions = await tx.subscription.findMany({ where: { gymId: req.gymId, memberId: req.params.id, status: 'active', deletedAt: null }, include: { plan: true }, }); for (const subscription of activeSubscriptions) { const planPrice = Number(subscription.plan.price); const percentDiscount = req.body.discountPercent ? (planPrice * Number(req.body.discountPercent)) / 100 : 0; const fixedDiscount = Number(req.body.discountAmount || 0); const discountAmount = Math.min(planPrice, percentDiscount + fixedDiscount); await tx.subscription.update({ where: { id: subscription.id, gymId: req.gymId }, data: { discountAmount, finalPrice: Math.max(planPrice - discountAmount, 0) }, }); } const parts = []; if (req.body.discountPercent) parts.push(`${req.body.discountPercent}%`); if (req.body.discountAmount) parts.push(`EGP ${req.body.discountAmount}`); await tx.notification.create({ data: { gymId: req.gymId, memberId: req.params.id, type: 'payment', channel: 'email', status: 'pending', message: req.body.note || `A discount${parts.length ? ` (${parts.join(' + ')})` : ''} has been applied to your membership billing.`, }, }); return savedMember; }); ok(res, updated, 'Discount applied and member notified'); }), remove: asyncHandler(async (req, res) => { await membersRepository.softDelete(req.gymId, req.params.id); ok(res, null, 'Member deleted'); }), generateQr: asyncHandler(async (req, res) => { ok(res, await membersService.generateQr(req.gymId, req.params.id), 'Member QR generated'); }), uploadPhoto: asyncHandler(async (req, res) => { if (!req.file) throw ApiError.badRequest('Image file is required'); ok(res, await membersService.attachUploadedImage(req.gymId, req.params.id, req.file), 'Member photo uploaded'); }), };