Compare commits
7 Commits
e2dcbe74d3
...
wisdom
| Author | SHA1 | Date | |
|---|---|---|---|
| 13ce1705fa | |||
| b4fe71ccc6 | |||
| a52efeceb5 | |||
| 1c56239fc8 | |||
| 84ba679b2e | |||
| e5a77f2f93 | |||
| 5112090a35 |
@@ -1,5 +1,8 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
|
const verifyToken = require("../middleware/verifyToken");
|
||||||
|
const verifyAccess = require("../middleware/verifyAccess");
|
||||||
const NotifikasiWaService = require('../services/notifikasi-wa.service');
|
const NotifikasiWaService = require('../services/notifikasi-wa.service');
|
||||||
|
|
||||||
router.post('/restart-wa', async (req, res) => {
|
router.post('/restart-wa', async (req, res) => {
|
||||||
@@ -11,10 +14,10 @@ router.post('/restart-wa', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/reminder-monthly/:id', async (req, res) => {
|
router.post('/reminder-monthly/:id', verifyToken.verifyAccessToken, verifyAccess(), async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const {reminder_at_monthly} = req.body
|
const { reminder_at_monthly } = req.body;
|
||||||
const result = await NotifikasiWaService.onMonthlyReminder(id, reminder_at_monthly);
|
const result = await NotifikasiWaService.onMonthlyReminder(id, reminder_at_monthly);
|
||||||
return res.status(200).json(result);
|
return res.status(200).json(result);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -22,10 +25,10 @@ router.post('/reminder-monthly/:id', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/reminder-custom/:id', async (req, res) => {
|
router.post('/reminder-custom/:id', verifyToken.verifyAccessToken, verifyAccess(), async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const {start_date, end_date} = req.body;
|
const { start_date, end_date } = req.body;
|
||||||
const result = await NotifikasiWaService.onCustomReminder(id, start_date, end_date);
|
const result = await NotifikasiWaService.onCustomReminder(id, start_date, end_date);
|
||||||
return res.status(200).json(result);
|
return res.status(200).json(result);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -33,52 +36,51 @@ router.post('/reminder-custom/:id', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/cron/jobs', async (req, res) => {
|
// router.get('/cron/jobs', async (req, res) => {
|
||||||
try {
|
// try {
|
||||||
const activeJobs = NotifikasiWaService.getActiveCronJobs();
|
// const activeJobs = NotifikasiWaService.getActiveCronJobs();
|
||||||
return res.status(200).json({
|
// return res.status(200).json({
|
||||||
success: true,
|
// success: true,
|
||||||
total: activeJobs.length,
|
// total: activeJobs.length,
|
||||||
jobs: activeJobs
|
// jobs: activeJobs
|
||||||
});
|
// });
|
||||||
} catch (error) {
|
// } catch (error) {
|
||||||
return res.status(500).json({
|
// return res.status(500).json({
|
||||||
success: false,
|
// success: false,
|
||||||
message: error.message
|
// message: error.message
|
||||||
});
|
// });
|
||||||
}
|
// }
|
||||||
});
|
// });
|
||||||
|
|
||||||
router.delete('/cron/jobs/:deviceId', async (req, res) => {
|
// router.delete('/cron/jobs/:deviceId', async (req, res) => {
|
||||||
try {
|
// try {
|
||||||
const { deviceId } = req.params;
|
// const { deviceId } = req.params;
|
||||||
NotifikasiWaService.stopCronJob(deviceId);
|
// NotifikasiWaService.stopCronJob(deviceId);
|
||||||
return res.status(200).json({
|
// return res.status(200).json({
|
||||||
success: true,
|
// success: true,
|
||||||
message: `Cron job untuk device ${deviceId} dihentikan`
|
// message: `Cron job untuk device ${deviceId} dihentikan`
|
||||||
});
|
// });
|
||||||
} catch (error) {
|
// } catch (error) {
|
||||||
return res.status(500).json({
|
// return res.status(500).json({
|
||||||
success: false,
|
// success: false,
|
||||||
message: error.message
|
// message: error.message
|
||||||
});
|
// });
|
||||||
}
|
// }
|
||||||
});
|
// });
|
||||||
|
|
||||||
// Endpoint untuk menghentikan semua cron job
|
// router.delete('/cron/jobs', async (req, res) => {
|
||||||
router.delete('/cron/jobs', async (req, res) => {
|
// try {
|
||||||
try {
|
// NotifikasiWaService.stopAllCronJobs();
|
||||||
NotifikasiWaService.stopAllCronJobs();
|
// return res.status(200).json({
|
||||||
return res.status(200).json({
|
// success: true,
|
||||||
success: true,
|
// message: 'Semua cron job dihentikan'
|
||||||
message: 'Semua cron job dihentikan'
|
// });
|
||||||
});
|
// } catch (error) {
|
||||||
} catch (error) {
|
// return res.status(500).json({
|
||||||
return res.status(500).json({
|
// success: false,
|
||||||
success: false,
|
// message: error.message
|
||||||
message: error.message
|
// });
|
||||||
});
|
// }
|
||||||
}
|
// });
|
||||||
});
|
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
@@ -616,7 +616,6 @@ class NotifikasiWaService {
|
|||||||
|
|
||||||
async onMonthlyReminder(deviceId, reminderMonthly) {
|
async onMonthlyReminder(deviceId, reminderMonthly) {
|
||||||
try {
|
try {
|
||||||
console.log(`🔄 Memulai onMonthlyReminder untuk device ID: ${deviceId}`);
|
|
||||||
|
|
||||||
const paramDb = {
|
const paramDb = {
|
||||||
limit: 100,
|
limit: 100,
|
||||||
@@ -625,12 +624,9 @@ class NotifikasiWaService {
|
|||||||
active: true,
|
active: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
// 1. Validasi device
|
|
||||||
console.log(`📡 Mengambil data device dengan ID: ${deviceId}`);
|
|
||||||
const devices = await getDeviceReminderMonthlyDb(deviceId);
|
const devices = await getDeviceReminderMonthlyDb(deviceId);
|
||||||
|
|
||||||
if (!devices || devices.length === 0) {
|
if (!devices || devices.length === 0) {
|
||||||
console.error(`❌ Device dengan ID ${deviceId} tidak ditemukan`);
|
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: `Device dengan ID ${deviceId} tidak ditemukan di database`
|
message: `Device dengan ID ${deviceId} tidak ditemukan di database`
|
||||||
@@ -641,19 +637,14 @@ class NotifikasiWaService {
|
|||||||
const deviceName = device.device_name;
|
const deviceName = device.device_name;
|
||||||
const currentDeviceId = device.device_id;
|
const currentDeviceId = device.device_id;
|
||||||
|
|
||||||
console.log(`✅ Device ditemukan: ${deviceName} (ID: ${currentDeviceId})`);
|
|
||||||
|
|
||||||
// 2. Validasi dan update reminder_at_monthly jika diperlukan
|
|
||||||
let targetReminderTime = device.reminder_at_monthly;
|
let targetReminderTime = device.reminder_at_monthly;
|
||||||
console.log(`📅 Reminder time dari DB: ${targetReminderTime}`);
|
|
||||||
|
|
||||||
if (reminderMonthly) {
|
if (reminderMonthly) {
|
||||||
console.log(`📝 Mengupdate reminder time ke: ${reminderMonthly}`);
|
|
||||||
const isValidDate = dayjs.tz(reminderMonthly, this.timeZone).isValid();
|
const isValidDate = dayjs.tz(reminderMonthly, this.timeZone).isValid();
|
||||||
if (!isValidDate) {
|
if (!isValidDate) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'Format reminderMonthly tidak valid. Gunakan format YYYY-MM-DD HH:mm:ss'
|
message: 'Format Reminder Monthly tidak valid. Gunakan format YYYY-MM-DD HH:mm:ss'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -661,40 +652,30 @@ class NotifikasiWaService {
|
|||||||
if (!updatedDevice) {
|
if (!updatedDevice) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'Gagal mengupdate reminder monthly.'
|
message: 'Gagal mengupdate Reminder Monthly.'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
targetReminderTime = reminderMonthly;
|
targetReminderTime = reminderMonthly;
|
||||||
console.log(`✅ Reminder time berhasil diupdate ke: ${targetReminderTime}`);
|
|
||||||
} else if (!targetReminderTime) {
|
} else if (!targetReminderTime) {
|
||||||
console.log(`⚠️ Tidak ada reminder time, setting default ke sekarang + 1 jam`);
|
|
||||||
const reminderTime = dayjs().tz(this.timeZone).add(1, 'hour').format('YYYY-MM-DD HH:mm:ss');
|
const reminderTime = dayjs().tz(this.timeZone).add(1, 'hour').format('YYYY-MM-DD HH:mm:ss');
|
||||||
const updatedDevice = await updateDeviceReminderMonthlyDb(deviceId, reminderTime);
|
const updatedDevice = await updateDeviceReminderMonthlyDb(deviceId, reminderTime);
|
||||||
|
|
||||||
if (!updatedDevice) {
|
if (!updatedDevice) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'Gagal mengupdate reminder monthly dengan default time.'
|
message: 'Gagal update Reminder Monthly dengan default time.'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
targetReminderTime = reminderTime;
|
targetReminderTime = reminderTime;
|
||||||
console.log(`✅ Default reminder time: ${targetReminderTime}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`📅 Target reminder time: ${targetReminderTime}`);
|
|
||||||
|
|
||||||
// 3. Parse target reminder time
|
|
||||||
const reminderAt = dayjs.tz(targetReminderTime, this.timeZone);
|
const reminderAt = dayjs.tz(targetReminderTime, this.timeZone);
|
||||||
const now = dayjs().tz(this.timeZone);
|
const now = dayjs().tz(this.timeZone);
|
||||||
|
|
||||||
console.log(`🕐 Waktu sekarang: ${now.format('YYYY-MM-DD HH:mm:ss')}`);
|
|
||||||
console.log(`🕐 Waktu reminder: ${reminderAt.format('YYYY-MM-DD HH:mm:ss')}`);
|
|
||||||
|
|
||||||
// 4. Jika sudah lewat atau sama, langsung kirim (sama seperti onCustomReminder)
|
|
||||||
const isEndDatePassed = now.isAfter(reminderAt) || now.isSame(reminderAt);
|
const isEndDatePassed = now.isAfter(reminderAt) || now.isSame(reminderAt);
|
||||||
|
|
||||||
if (isEndDatePassed) {
|
if (isEndDatePassed) {
|
||||||
console.log(`⏰ Reminder time sudah terlewati, mengirim reminder sekarang untuk ${deviceName}`);
|
|
||||||
const sendResult = await this.sendMonthlyReminderNow(
|
const sendResult = await this.sendMonthlyReminderNow(
|
||||||
currentDeviceId,
|
currentDeviceId,
|
||||||
deviceName,
|
deviceName,
|
||||||
@@ -703,13 +684,8 @@ class NotifikasiWaService {
|
|||||||
return sendResult;
|
return sendResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Jika belum waktunya, jadwalkan cron job (sama seperti onCustomReminder)
|
|
||||||
console.log(`⏰ Menjadwalkan reminder untuk ${deviceName} pada ${reminderAt.format('YYYY-MM-DD HH:mm:ss')}`);
|
|
||||||
|
|
||||||
// Stop cron job lama jika ada
|
|
||||||
this.stopCronJob(currentDeviceId);
|
this.stopCronJob(currentDeviceId);
|
||||||
|
|
||||||
// Schedule cron job
|
|
||||||
const scheduleResult = await this.scheduleMonthlyReminderJob(
|
const scheduleResult = await this.scheduleMonthlyReminderJob(
|
||||||
currentDeviceId,
|
currentDeviceId,
|
||||||
deviceName,
|
deviceName,
|
||||||
@@ -719,19 +695,11 @@ class NotifikasiWaService {
|
|||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: `Reminder berhasil dijadwalkan untuk device ${deviceName}`,
|
message: `Reminder berhasil dijadwalkan untuk device ${deviceName}`,
|
||||||
schedule: scheduleResult,
|
|
||||||
nextRun: scheduleResult.nextRun
|
|
||||||
};
|
};
|
||||||
|
|
||||||
} catch (error) {
|
} catch (err) {
|
||||||
console.error('❌ Error onMonthlyReminder:', error);
|
console.error('Error on Monthly Reminder:', err);
|
||||||
console.error('❌ Stack trace:', error.stack);
|
throw err
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
message: 'Error pada onMonthlyReminder: ' + error.message,
|
|
||||||
error: error,
|
|
||||||
stack: error.stack
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -820,7 +788,6 @@ class NotifikasiWaService {
|
|||||||
|
|
||||||
async sendMonthlyReminderNow(deviceId, deviceName, reminderAt) {
|
async sendMonthlyReminderNow(deviceId, deviceName, reminderAt) {
|
||||||
try {
|
try {
|
||||||
console.log(`Mengirim reminder untuk ${deviceName}`);
|
|
||||||
|
|
||||||
const paramDb = {
|
const paramDb = {
|
||||||
limit: 100,
|
limit: 100,
|
||||||
@@ -841,7 +808,6 @@ class NotifikasiWaService {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (checkNotifExist) {
|
if (checkNotifExist) {
|
||||||
console.log(`Reminder untuk ${deviceName} bulan ${currentMonth} sudah pernah dibuat`);
|
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: `Reminder untuk device ${deviceName} sudah pernah dibuat.`
|
message: `Reminder untuk device ${deviceName} sudah pernah dibuat.`
|
||||||
@@ -957,14 +923,12 @@ class NotifikasiWaService {
|
|||||||
|
|
||||||
this.stopCronJob(deviceId);
|
this.stopCronJob(deviceId);
|
||||||
|
|
||||||
console.log(`Reminder berhasil dikirim untuk ${deviceName}`);
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: "Reminder has been sent.",
|
message: "Reminder has been sent.",
|
||||||
};
|
};
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error sending monthly reminder now:', error);
|
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -981,7 +945,7 @@ class NotifikasiWaService {
|
|||||||
if (!inputStartDate || !inputEndDate) {
|
if (!inputStartDate || !inputEndDate) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'start_date dan end_date harus diisi. Format: YYYY-MM-DD HH:mm:ss'
|
message: 'Start Date dan End Date harus diisi. Format: YYYY-MM-DD HH:mm:ss'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -991,14 +955,14 @@ class NotifikasiWaService {
|
|||||||
if (!startDateObj.isValid() || !endDateObj.isValid()) {
|
if (!startDateObj.isValid() || !endDateObj.isValid()) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'Format tanggal tidak valid. Gunakan format: YYYY-MM-DD HH:mm:ss'
|
message: 'Format tanggal Start Date dan End Date tidak valid. Gunakan format: YYYY-MM-DD HH:mm:ss'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!endDateObj.isAfter(startDateObj)) {
|
if (!endDateObj.isAfter(startDateObj)) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'end_date harus lebih besar dari start_date'
|
message: 'End Date harus lebih besar dari Start Date'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1025,11 +989,9 @@ class NotifikasiWaService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`Berhasil update start_date dan end_date untuk device ${deviceName}`);
|
|
||||||
|
|
||||||
this.stopCronJob(currentDeviceId);
|
this.stopCronJob(currentDeviceId);
|
||||||
|
|
||||||
const scheduleResult = await this.scheduleReminderJob(
|
const scheduleResult = await this.scheduleCustomReminderJob(
|
||||||
currentDeviceId,
|
currentDeviceId,
|
||||||
deviceName,
|
deviceName,
|
||||||
startDateObj,
|
startDateObj,
|
||||||
@@ -1041,7 +1003,7 @@ class NotifikasiWaService {
|
|||||||
|
|
||||||
if (isEndDatePassed) {
|
if (isEndDatePassed) {
|
||||||
console.log(`⏰ End_date sudah terlewati, mengirim reminder sekarang untuk ${deviceName}`);
|
console.log(`⏰ End_date sudah terlewati, mengirim reminder sekarang untuk ${deviceName}`);
|
||||||
const sendResult = await this.sendReminderNow(
|
const sendResult = await this.sendCustomReminderNow(
|
||||||
currentDeviceId,
|
currentDeviceId,
|
||||||
deviceName,
|
deviceName,
|
||||||
startDateObj,
|
startDateObj,
|
||||||
@@ -1051,16 +1013,12 @@ class NotifikasiWaService {
|
|||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: 'Reminder berhasil dijadwalkan dan dikirim sekarang',
|
message: 'Reminder berhasil dijadwalkan dan dikirim sekarang',
|
||||||
schedule: scheduleResult,
|
|
||||||
sendResult: sendResult
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: `Reminder berhasil dijadwalkan untuk device ${deviceName}`,
|
message: `Reminder berhasil dijadwalkan untuk device ${deviceName}`,
|
||||||
schedule: scheduleResult,
|
|
||||||
nextRun: scheduleResult.nextRun
|
|
||||||
};
|
};
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -1069,7 +1027,7 @@ class NotifikasiWaService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async scheduleReminderJob(deviceId, deviceName, startDateObj, endDateObj) {
|
async scheduleCustomReminderJob(deviceId, deviceName, startDateObj, endDateObj) {
|
||||||
try {
|
try {
|
||||||
const now = dayjs().tz(this.timeZone);
|
const now = dayjs().tz(this.timeZone);
|
||||||
|
|
||||||
@@ -1079,10 +1037,6 @@ class NotifikasiWaService {
|
|||||||
|
|
||||||
const nextRun = targetTime.format('YYYY-MM-DD HH:mm:ss');
|
const nextRun = targetTime.format('YYYY-MM-DD HH:mm:ss');
|
||||||
|
|
||||||
console.log(`Reminder untuk ${deviceName} dijadwalkan pada ${nextRun}`);
|
|
||||||
console.log(`Start Date: ${startDateObj.format('YYYY-MM-DD HH:mm:ss')}`);
|
|
||||||
console.log(`End Date: ${endDateObj.format('YYYY-MM-DD HH:mm:ss')}`);
|
|
||||||
|
|
||||||
const timeoutId = setTimeout(async () => {
|
const timeoutId = setTimeout(async () => {
|
||||||
console.log(`Waktu pengiriman tiba untuk ${deviceName} pada ${dayjs().tz(this.timeZone).format('YYYY-MM-DD HH:mm:ss')}`);
|
console.log(`Waktu pengiriman tiba untuk ${deviceName} pada ${dayjs().tz(this.timeZone).format('YYYY-MM-DD HH:mm:ss')}`);
|
||||||
try {
|
try {
|
||||||
@@ -1090,13 +1044,11 @@ class NotifikasiWaService {
|
|||||||
const isEndDatePassed = now.isAfter(endDateObj) || now.isSame(endDateObj);
|
const isEndDatePassed = now.isAfter(endDateObj) || now.isSame(endDateObj);
|
||||||
|
|
||||||
if (isEndDatePassed) {
|
if (isEndDatePassed) {
|
||||||
await this.sendReminderNow(deviceId, deviceName, startDateObj, endDateObj);
|
await this.sendCustomReminderNow(deviceId, deviceName, startDateObj, endDateObj);
|
||||||
} else {
|
|
||||||
console.log(`End_date untuk ${deviceName} belum terlewati, menunggu...`);
|
|
||||||
this.rescheduleReminderCheck(deviceId, deviceName, startDateObj, endDateObj);
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
|
||||||
console.error(`Gagal mengirim reminder untuk ${deviceName}:`, error);
|
} catch (err) {
|
||||||
|
throw err
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1111,10 +1063,8 @@ class NotifikasiWaService {
|
|||||||
const endMinute = endDateObj.minute();
|
const endMinute = endDateObj.minute();
|
||||||
const cronExpression = `${endMinute} ${endHour} * * *`;
|
const cronExpression = `${endMinute} ${endHour} * * *`;
|
||||||
|
|
||||||
console.log(`Backup cron akan berjalan setiap hari pada ${endHour}:${endMinute}`);
|
|
||||||
|
|
||||||
const cronTask = cron.schedule(cronExpression, async () => {
|
const cronTask = cron.schedule(cronExpression, async () => {
|
||||||
console.log(`Backup cron job berjalan untuk ${deviceName} pada ${dayjs().tz(this.timeZone).format('YYYY-MM-DD HH:mm:ss')}`);
|
|
||||||
try {
|
try {
|
||||||
const now = dayjs().tz(this.timeZone);
|
const now = dayjs().tz(this.timeZone);
|
||||||
const isEndDatePassed = now.isAfter(endDateObj) || now.isSame(endDateObj);
|
const isEndDatePassed = now.isAfter(endDateObj) || now.isSame(endDateObj);
|
||||||
@@ -1128,20 +1078,23 @@ class NotifikasiWaService {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (!checkNotifExist) {
|
if (!checkNotifExist) {
|
||||||
await this.sendReminderNow(deviceId, deviceName, startDateObj, endDateObj);
|
await this.sendCustomReminderNow(deviceId, deviceName, startDateObj, endDateObj);
|
||||||
} else {
|
} else {
|
||||||
console.log(`Reminder untuk ${deviceName} sudah pernah dikirim`);
|
return {
|
||||||
|
success: false,
|
||||||
|
message: `Reminder untuk ${deviceName} sudah pernah dikirim`
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
cronTask.stop();
|
cronTask.stop();
|
||||||
this.cronJobs.delete(deviceId);
|
this.cronJobs.delete(deviceId);
|
||||||
this.cronJobs.delete(`cron_${deviceId}`);
|
this.cronJobs.delete(`cron_${deviceId}`);
|
||||||
} else {
|
|
||||||
console.log(`Menunggu end_date untuk ${deviceName}: ${endDateObj.format('YYYY-MM-DD HH:mm:ss')}`);
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
|
||||||
console.error(`Backup cron job gagal untuk ${deviceName}:`, error);
|
} catch (err) {
|
||||||
|
throw err
|
||||||
}
|
}
|
||||||
|
|
||||||
}, {
|
}, {
|
||||||
timezone: this.timeZone
|
timezone: this.timeZone
|
||||||
});
|
});
|
||||||
@@ -1166,30 +1119,15 @@ class NotifikasiWaService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async rescheduleReminderCheck(deviceId, deviceName, startDateObj, endDateObj) {
|
async sendCustomReminderNow(deviceId, deviceName, startDateObj, endDateObj) {
|
||||||
const checkInterval = setInterval(async () => {
|
|
||||||
const now = dayjs().tz(this.timeZone);
|
|
||||||
const isEndDatePassed = now.isAfter(endDateObj) || now.isSame(endDateObj);
|
|
||||||
|
|
||||||
if (isEndDatePassed) {
|
|
||||||
clearInterval(checkInterval);
|
|
||||||
console.log(`End_date terlewati untuk ${deviceName}, mengirim reminder...`);
|
|
||||||
try {
|
try {
|
||||||
await this.sendReminderNow(deviceId, deviceName, startDateObj, endDateObj);
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Gagal mengirim reminder untuk ${deviceName}:`, error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, 60000);
|
|
||||||
|
|
||||||
this.cronJobs.set(`interval_${deviceId}`, {
|
const paramDb = {
|
||||||
intervalId: checkInterval
|
limit: 100,
|
||||||
});
|
page: 1,
|
||||||
}
|
criteria: "",
|
||||||
|
active: true,
|
||||||
async sendReminderNow(deviceId, deviceName, startDateObj, endDateObj) {
|
};
|
||||||
try {
|
|
||||||
console.log(`Mengirim reminder untuk ${deviceName}`);
|
|
||||||
|
|
||||||
const now = dayjs().tz(this.timeZone);
|
const now = dayjs().tz(this.timeZone);
|
||||||
const currentMonth = now.month() + 1;
|
const currentMonth = now.month() + 1;
|
||||||
@@ -1202,7 +1140,6 @@ class NotifikasiWaService {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (checkNotifExist) {
|
if (checkNotifExist) {
|
||||||
console.log(`Reminder untuk ${deviceName} sudah pernah dibuat`);
|
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: `Reminder untuk device ${deviceName} sudah pernah dibuat.`
|
message: `Reminder untuk device ${deviceName} sudah pernah dibuat.`
|
||||||
@@ -1221,12 +1158,6 @@ class NotifikasiWaService {
|
|||||||
|
|
||||||
const resultNotificationError = await InsertNotificationErrorDb(data);
|
const resultNotificationError = await InsertNotificationErrorDb(data);
|
||||||
|
|
||||||
const paramDb = {
|
|
||||||
limit: 100,
|
|
||||||
page: 1,
|
|
||||||
criteria: "",
|
|
||||||
active: true,
|
|
||||||
};
|
|
||||||
const results = await getAllContactDb(paramDb);
|
const results = await getAllContactDb(paramDb);
|
||||||
const dataUsers = results.data;
|
const dataUsers = results.data;
|
||||||
|
|
||||||
@@ -1282,7 +1213,7 @@ class NotifikasiWaService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (resultSend.success) {
|
if (resultSend.success) {
|
||||||
isSendNotification = resultSend.success;
|
isSendNotification = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1313,12 +1244,11 @@ class NotifikasiWaService {
|
|||||||
|
|
||||||
this.stopCronJob(deviceId);
|
this.stopCronJob(deviceId);
|
||||||
|
|
||||||
console.log(`Reminder berhasil dikirim untuk ${deviceName}`);
|
|
||||||
return { success: true, message: "Reminder has been sent." };
|
return { success: true, message: "Reminder has been sent." };
|
||||||
|
|
||||||
} catch (error) {
|
} catch (err) {
|
||||||
console.error('Error sending reminder now:', error);
|
console.error('Error sending reminder now:', err);
|
||||||
throw error;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1346,39 +1276,6 @@ class NotifikasiWaService {
|
|||||||
this.cronJobs.delete(`interval_${deviceId}`);
|
this.cronJobs.delete(`interval_${deviceId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
getActiveCronJobs() {
|
|
||||||
const activeJobs = [];
|
|
||||||
for (const [key, value] of this.cronJobs) {
|
|
||||||
if (!key.startsWith('cron_') && !key.startsWith('interval_')) {
|
|
||||||
activeJobs.push({
|
|
||||||
deviceId: key,
|
|
||||||
nextRun: value.nextRun,
|
|
||||||
startDate: value.startDate,
|
|
||||||
endDate: value.endDate
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return activeJobs;
|
|
||||||
}
|
|
||||||
|
|
||||||
stopAllCronJobs() {
|
|
||||||
for (const [key, value] of this.cronJobs) {
|
|
||||||
if (value.timeoutId) {
|
|
||||||
clearTimeout(value.timeoutId);
|
|
||||||
}
|
|
||||||
if (value.intervalId) {
|
|
||||||
clearInterval(value.intervalId);
|
|
||||||
}
|
|
||||||
if (value.cronTask) {
|
|
||||||
value.cronTask.stop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.cronJobs.clear();
|
|
||||||
console.log('Semua cron job dihentikan');
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async restartWhatsapp() {
|
async restartWhatsapp() {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
@@ -1390,19 +1287,18 @@ class NotifikasiWaService {
|
|||||||
const endJSON = cleanJSON.lastIndexOf(']') + 1;
|
const endJSON = cleanJSON.lastIndexOf(']') + 1;
|
||||||
|
|
||||||
if (startJSON === -1 || endJSON === 0) {
|
if (startJSON === -1 || endJSON === 0) {
|
||||||
throw new Error(`Terminal tidak mengembalikan JSON yang valid. Output: ${stdout}`);
|
console.error(`Terminal tidak mengembalikan JSON yang valid. Output: ${stdout}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const index = cleanJSON.slice(startJSON, endJSON);
|
const index = cleanJSON.slice(startJSON, endJSON);
|
||||||
const processes = JSON.parse(index);
|
const processes = JSON.parse(index);
|
||||||
const waProcess = processes.find((p) => p.name === processName);
|
const waProcess = processes.find((p) => p.name === processName);
|
||||||
|
|
||||||
if (!waProcess) throw new Error(`PM2 proses dengan nama "${processName}" tidak ditemukan!`);
|
if (!waProcess) console.error(`PM2 proses dengan nama ${processName} tidak ditemukan`);
|
||||||
|
|
||||||
const waProcessId = waProcess.pm_id;
|
const waProcessId = waProcess.pm_id;
|
||||||
const pathDelete = waProcess.pm2_env.pm_cwd;
|
const pathDelete = waProcess.pm2_env.pm_cwd;
|
||||||
|
|
||||||
// console.log(`stop proses id: ${waProcessId}`);
|
|
||||||
await execPromise(`pm2 stop ${waProcessId}`);
|
await execPromise(`pm2 stop ${waProcessId}`);
|
||||||
|
|
||||||
const pathFolderDelete = [
|
const pathFolderDelete = [
|
||||||
@@ -1410,8 +1306,6 @@ class NotifikasiWaService {
|
|||||||
path.join(pathDelete, ".wwebjs_cache"),
|
path.join(pathDelete, ".wwebjs_cache"),
|
||||||
];
|
];
|
||||||
|
|
||||||
// console.log(`path: ${pathDelete}`);
|
|
||||||
|
|
||||||
for (const dir of pathFolderDelete) {
|
for (const dir of pathFolderDelete) {
|
||||||
try {
|
try {
|
||||||
await fs.access(dir);
|
await fs.access(dir);
|
||||||
@@ -1425,12 +1319,19 @@ class NotifikasiWaService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// console.log(`start proses id: ${waProcessId}`);
|
|
||||||
await execPromise(`pm2 start ${waProcessId}`);
|
await execPromise(`pm2 start ${waProcessId}`);
|
||||||
|
|
||||||
return { success: true, message: "WhatsApp has been restarted." };
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "WhatsApp has been restarted."
|
||||||
|
};
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return { success: false, error: err.message || err };
|
return {
|
||||||
|
success: false,
|
||||||
|
message: `Gagal mengirim Whatsapp`
|
||||||
|
};
|
||||||
|
throw err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,7 +28,10 @@ class SparepartService {
|
|||||||
throw new ErrorHandler(404, "Sparepart not found");
|
throw new ErrorHandler(404, "Sparepart not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
sparepart[0].sparepart_yearly = JSON.parse(sparepart[0].sparepart_yearly);
|
if (sparepart[0]) {
|
||||||
|
if (sparepart[0].sparepart_yearly) sparepart[0].sparepart_yearly = JSON.parse(sparepart[0].sparepart_yearly);
|
||||||
|
if (sparepart[0].sparepart_monthly) sparepart[0].sparepart_monthly = JSON.parse(sparepart[0].sparepart_monthly);
|
||||||
|
}
|
||||||
|
|
||||||
return sparepart[0];
|
return sparepart[0];
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -49,6 +52,10 @@ class SparepartService {
|
|||||||
data.sparepart_yearly = JSON.stringify(data.sparepart_yearly);
|
data.sparepart_yearly = JSON.stringify(data.sparepart_yearly);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (data.sparepart_monthly) {
|
||||||
|
data.sparepart_monthly = JSON.stringify(data.sparepart_monthly);
|
||||||
|
}
|
||||||
|
|
||||||
const created = await createSparepartDb(data);
|
const created = await createSparepartDb(data);
|
||||||
if (!created) throw new ErrorHandler(500, "Failed to create Sparepart");
|
if (!created) throw new ErrorHandler(500, "Failed to create Sparepart");
|
||||||
return created;
|
return created;
|
||||||
@@ -70,14 +77,17 @@ class SparepartService {
|
|||||||
data.sparepart_number,
|
data.sparepart_number,
|
||||||
id
|
id
|
||||||
);
|
);
|
||||||
if (exists)
|
|
||||||
throw new ErrorHandler(400, "Sparepart name already exists");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.sparepart_yearly) {
|
if (data.sparepart_yearly) {
|
||||||
data.sparepart_yearly = JSON.stringify(data.sparepart_yearly);
|
data.sparepart_yearly = JSON.stringify(data.sparepart_yearly);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (data.sparepart_monthly) {
|
||||||
|
data.sparepart_monthly = JSON.stringify(data.sparepart_monthly);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
const updated = await updateSparepartDb(id, data);
|
const updated = await updateSparepartDb(id, data);
|
||||||
if (!updated) throw new ErrorHandler(500, "Failed to update Sparepart");
|
if (!updated) throw new ErrorHandler(500, "Failed to update Sparepart");
|
||||||
return await this.getSparepartById(id);
|
return await this.getSparepartById(id);
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ const insertDeviceSchema = Joi.object({
|
|||||||
listen_channel: Joi.string().max(100).required(),
|
listen_channel: Joi.string().max(100).required(),
|
||||||
listen_channel_reminder: Joi.string().max(100).allow('', null),
|
listen_channel_reminder: Joi.string().max(100).allow('', null),
|
||||||
reminder_at: Joi.date().iso().allow('', null),
|
reminder_at: Joi.date().iso().allow('', null),
|
||||||
|
reminder_at_monthly: Joi.date().iso().allow('', null),
|
||||||
|
start_date: Joi.date().iso().allow('', null),
|
||||||
|
end_date: Joi.date().iso().allow('', null),
|
||||||
});
|
});
|
||||||
|
|
||||||
const updateDeviceSchema = Joi.object({
|
const updateDeviceSchema = Joi.object({
|
||||||
@@ -35,6 +38,9 @@ const updateDeviceSchema = Joi.object({
|
|||||||
listen_channel: Joi.string().max(100),
|
listen_channel: Joi.string().max(100),
|
||||||
listen_channel_reminder: Joi.string().max(100).allow('', null),
|
listen_channel_reminder: Joi.string().max(100).allow('', null),
|
||||||
reminder_at: Joi.date().iso().allow('', null),
|
reminder_at: Joi.date().iso().allow('', null),
|
||||||
|
reminder_at_monthly: Joi.date().iso().allow('', null),
|
||||||
|
start_date: Joi.date().iso().allow('', null),
|
||||||
|
end_date: Joi.date().iso().allow('', null),
|
||||||
|
|
||||||
}).min(1);
|
}).min(1);
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,11 @@ const insertSparepartSchema = Joi.object({
|
|||||||
sparepart_merk: Joi.string().max(255).optional(),
|
sparepart_merk: Joi.string().max(255).optional(),
|
||||||
sparepart_stok: Joi.string().max(255).optional(),
|
sparepart_stok: Joi.string().max(255).optional(),
|
||||||
sparepart_yearly: Joi.array()
|
sparepart_yearly: Joi.array()
|
||||||
|
.items(Joi.number().integer())
|
||||||
|
.min(0)
|
||||||
|
.allow(null)
|
||||||
|
.optional(),
|
||||||
|
sparepart_monthly: Joi.array()
|
||||||
.items(Joi.number().integer())
|
.items(Joi.number().integer())
|
||||||
.min(0)
|
.min(0)
|
||||||
.allow(null)
|
.allow(null)
|
||||||
@@ -33,11 +38,17 @@ const updateSparepartSchema = Joi.object({
|
|||||||
sparepart_merk: Joi.string().max(255).optional(),
|
sparepart_merk: Joi.string().max(255).optional(),
|
||||||
sparepart_stok: Joi.string().max(255).optional(),
|
sparepart_stok: Joi.string().max(255).optional(),
|
||||||
sparepart_yearly: Joi.array()
|
sparepart_yearly: Joi.array()
|
||||||
|
.items(Joi.number().integer())
|
||||||
|
.min(0)
|
||||||
|
.allow(null)
|
||||||
|
.optional(),
|
||||||
|
sparepart_monthly: Joi.array()
|
||||||
.items(Joi.number().integer())
|
.items(Joi.number().integer())
|
||||||
.min(0)
|
.min(0)
|
||||||
.allow(null)
|
.allow(null)
|
||||||
.optional()
|
.optional()
|
||||||
});
|
})
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
insertSparepartSchema,
|
insertSparepartSchema,
|
||||||
updateSparepartSchema,
|
updateSparepartSchema,
|
||||||
|
|||||||
Reference in New Issue
Block a user