File size: 5,547 Bytes
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import Notification from "../models/NotificationModel.js";
import WhatsAppService from "../utils/whatsappService.js";
import { catchAsync } from "../utils/catchAsync.js";

// Get all notifications
export const getAllNotifications = catchAsync(async (req, res) => {
  const { tenantId } = req.params;
  const { status, invoiceId, page = 1, limit = 20 } = req.query;  

  const filter = { tenant: tenantId };
  if (status) filter.status = status;
  if (invoiceId) filter.invoice = invoiceId;

  const skip = (page - 1) * limit;

  const notifications = await Notification.find(filter)
    .populate("invoice", "invoiceNumber totalAmount status")
    .sort({ createdAt: -1 })
    .skip(skip)
    .limit(Number(limit));

  const total = await Notification.countDocuments(filter);

  res.status(200).json({
    status: "success",
    data: notifications,
    pagination: {
      total,
      page: Number(page),
      pages: Math.ceil(total / limit),
    },
  });
});

// Get notification by ID
export const getNotificationById = catchAsync(async (req, res) => {
  const { id } = req.params;

  const notification = await Notification.findById(id).populate("invoice");

  if (!notification) {
    return res.status(404).json({
      status: "error",
      message: "الإشعار غير موجود",
    });
  }

  res.status(200).json({
    status: "success",
    data: notification,
  });
});

// Send notification manually
export const sendNotification = catchAsync(async (req, res) => {
  const { id } = req.params;

  const notification = await Notification.findById(id);

  if (!notification) {
    return res.status(404).json({
      status: "error",
      message: "الإشعار غير موجود",
    });
  }

  if (notification.status !== "queued") {
    return res.status(400).json({
      status: "error",
      message: "يمكن فقط إرسال الإشعارات المعلقة",
    });
  }

  try {
    await WhatsAppService.sendWhatsAppMessage(notification);

    res.status(200).json({
      status: "success",
      message: "تم إرسال الإشعار بنجاح",
      data: notification,
    });
  } catch (error) {
    console.error("Send notification error:", error);
    res.status(500).json({
      status: "error",
      message: "فشل إرسال الإشعار",
    });
  }
});

// Send all queued notifications
export const sendQueuedNotifications = catchAsync(async (req, res) => {
  try {
    const result = await WhatsAppService.sendQueuedNotifications();

    res.status(200).json({
      status: "success",
      message: `تم معالجة ${result.processed} إشعار`,
      data: result,
    });
  } catch (error) {
    console.error("Send queued notifications error:", error);
    res.status(500).json({
      status: "error",
      message: "فشلت معالجة الإشعارات",
    });
  }
});

// Get order notifications
export const getInvoiceNotifications = catchAsync(async (req, res) => {
  const { tenantId, invoiceId } = req.params;  

  const notifications = await Notification.find({
    tenant: tenantId,
    invoice: invoiceId,    
  }).sort({ createdAt: -1 });

  res.status(200).json({
    status: "success",
    data: notifications,
  });
});

// Delete notification
export const deleteNotification = catchAsync(async (req, res) => {
  const { id } = req.params;

  const notification = await Notification.findByIdAndDelete(id);

  if (!notification) {
    return res.status(404).json({
      status: "error",
      message: "الإشعار غير موجود",
    });
  }

  res.status(200).json({
    status: "success",
    message: "تم حذف الإشعار بنجاح",
  });
});

// Retry failed notification
export const retryNotification = catchAsync(async (req, res) => {
  const { id } = req.params;

  const notification = await Notification.findById(id);

  if (!notification) {
    return res.status(404).json({
      status: "error",
      message: "الإشعار غير موجود",
    });
  }

  if (notification.status !== "failed") {
    return res.status(400).json({
      status: "error",
      message: "يمكن فقط إعادة محاولة الإشعارات الفاشلة",
    });
  }

  // Reset for retry
  notification.status = "queued";
  notification.retryCount = 0;
  notification.errorMessage = null;
  await notification.save();

  try {
    await WhatsAppService.sendWhatsAppMessage(notification);

    res.status(200).json({
      status: "success",
      message: "تم إعادة محاولة الإشعار",
      data: notification,
    });
  } catch (error) {
    console.error("Retry notification error:", error);
    res.status(500).json({
      status: "error",
      message: "فشلت إعادة المحاولة",
    });
  }
});

// Get notification statistics
export const getNotificationStats = catchAsync(async (req, res) => {
  const { tenantId } = req.params;

  const stats = await Notification.aggregate([
    { $match: { tenant: tenantId } },
    {
      $group: {
        _id: "$status",
        count: { $sum: 1 },
      },
    },
  ]);

  const formattedStats = {
    queued: 0,
    sent: 0,
    delivered: 0,
    failed: 0,
  };

  stats.forEach((stat) => {
    formattedStats[stat._id] = stat.count;
  });

  res.status(200).json({
    status: "success",
    data: formattedStats,
  });
});