File size: 7,589 Bytes
2b109bf
 
 
 
 
 
1615df8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b109bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1615df8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d31513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1615df8
4d31513
 
 
 
 
 
1615df8
2b109bf
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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');
  }),
};