import { asyncHandler } from '../../common/middleware/asyncHandler.js'; import { prisma } from '../../config/prisma.js'; import { ApiError } from '../../common/errors/ApiError.js'; import { getPagination, paginated } from '../../common/utils/pagination.js'; import { created, ok } from '../../common/utils/response.js'; import { notificationsRepository } from './notifications.repository.js'; import { sendNotification } from '../../config/notificationProviders.js'; const sendOne = async (gymId, id) => { const notification = await prisma.notification.findFirst({ where: { id, gymId, deletedAt: null }, include: { member: true } }); if (!notification) throw ApiError.notFound('Notification not found'); try { const externalId = await sendNotification(notification, notification.member); return prisma.notification.update({ where: { id, gymId }, data: { status: 'sent', sentAt: new Date(), externalId, errorMessage: null }, include: { member: true }, }); } catch (error) { return prisma.notification.update({ where: { id, gymId }, data: { status: 'failed', retryCount: { increment: 1 }, errorMessage: error.message }, include: { member: true }, }); } }; export const notificationsController = { list: asyncHandler(async (req, res) => { const pagination = getPagination(req.query); const [items, total] = await notificationsRepository.list({ gymId: req.gymId, search: req.query.search, ...pagination }); ok(res, paginated(items, total, pagination.page, pagination.limit)); }), create: asyncHandler(async (req, res) => created(res, await notificationsRepository.create(req.gymId, req.body), 'Notification queued')), mine: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); ok(res, await notificationsRepository.listForMember(req.gymId, req.user.memberId)); }), generateSubscriptionReminders: asyncHandler(async (req, res) => { const subscriptions = await prisma.subscription.findMany({ where: { gymId: req.gymId, status: 'active', deletedAt: null }, include: { member: true, plan: true }, }); const now = Date.now(); const reminders = []; for (const subscription of subscriptions) { const start = new Date(subscription.startDate).getTime(); const end = new Date(subscription.endDate).getTime(); const total = end - start; const remaining = end - now; const points = [ { key: 'midpoint', shouldSend: now >= start + total / 2, message: `Your ${subscription.plan.name} subscription is halfway through.` }, { key: '3-days', shouldSend: remaining <= 3 * 24 * 60 * 60 * 1000 && remaining > 24 * 60 * 60 * 1000, message: `Your ${subscription.plan.name} subscription ends in 3 days.` }, { key: '1-day', shouldSend: remaining <= 24 * 60 * 60 * 1000 && remaining > 5 * 60 * 60 * 1000, message: `Your ${subscription.plan.name} subscription ends tomorrow.` }, { key: '5-hours', shouldSend: remaining <= 5 * 60 * 60 * 1000 && remaining > 0, message: `Your ${subscription.plan.name} subscription ends in 5 hours.` }, ]; for (const point of points) { if (!point.shouldSend) continue; const exists = await prisma.notification.findFirst({ where: { gymId: req.gymId, memberId: subscription.memberId, type: 'renewal', message: point.message, deletedAt: null }, }); if (!exists) { reminders.push(await notificationsRepository.create(req.gymId, { memberId: subscription.memberId, type: 'renewal', channel: 'whatsapp', message: point.message, status: 'pending', })); } const managerMessage = `${subscription.member.fullName}: ${point.message}`; const managerExists = await prisma.notification.findFirst({ where: { gymId: req.gymId, memberId: null, type: 'renewal', message: managerMessage, deletedAt: null }, }); if (!managerExists) { reminders.push(await notificationsRepository.create(req.gymId, { type: 'renewal', channel: 'email', message: managerMessage, status: 'pending', })); } } } ok(res, { created: reminders.length, reminders }, 'Subscription reminders generated'); }), update: asyncHandler(async (req, res) => ok(res, await notificationsRepository.update(req.gymId, req.params.id, req.body), 'Notification updated')), send: asyncHandler(async (req, res) => ok(res, await sendOne(req.gymId, req.params.id), 'Notification send attempted')), retry: asyncHandler(async (req, res) => ok(res, await sendOne(req.gymId, req.params.id), 'Notification retry attempted')), stats: asyncHandler(async (req, res) => { const grouped = await prisma.notification.groupBy({ by: ['status'], where: { gymId: req.gymId, deletedAt: null }, _count: true }); const stats = { sent: 0, failed: 0, pending: 0, total: 0 }; for (const item of grouped) { stats[item.status] = item._count; stats.total += item._count; } ok(res, stats); }), templates: asyncHandler(async (_req, res) => { ok(res, [ { type: 'renewal', channel: 'whatsapp', message: 'Your membership is about to expire. Renew now to keep training.' }, { type: 'payment', channel: 'email', message: 'Your payment has been received. Thank you.' }, { type: 'reminder', channel: 'sms', message: 'We miss you at the gym. Book your next session today.' }, ]); }), sendBulk: asyncHandler(async (req, res) => { const createdItems = await prisma.$transaction(req.body.memberIds.map((memberId) => prisma.notification.create({ data: { gymId: req.gymId, memberId, type: req.body.type, channel: req.body.channel, message: req.body.message, status: 'pending' }, include: { member: true }, }))); const sent = []; for (const item of createdItems) sent.push(await sendOne(req.gymId, item.id)); ok(res, sent, 'Bulk notifications queued'); }), requestRenewal: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); const member = await prisma.member.findFirst({ where: { id: req.user.memberId, gymId: req.gymId, deletedAt: null } }); if (!member) throw ApiError.notFound('Member profile not found'); created(res, await prisma.notification.create({ data: { gymId: req.gymId, memberId: req.user.memberId, type: 'renewal', channel: 'email', status: 'pending', message: `${member.fullName} requested membership renewal. Please review the membership request and payment status.`, }, include: { member: true }, }), 'Renewal request sent'); }), markRead: asyncHandler(async (req, res) => { if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); const notification = await prisma.notification.findFirst({ where: { id: req.params.id, gymId: req.gymId, memberId: req.user.memberId, deletedAt: null }, }); if (!notification) throw ApiError.notFound('Notification not found'); ok(res, await prisma.notification.update({ where: { id: notification.id, gymId: req.gymId }, data: { isRead: true } }), 'Notification marked read'); }), remove: asyncHandler(async (req, res) => { await notificationsRepository.softDelete(req.gymId, req.params.id); ok(res, null, 'Notification deleted'); }), };