|
|
|
|
@@ -24,17 +24,25 @@ const {
|
|
|
|
|
|
|
|
|
|
const { getErrorCodeByBrandAndCodeDb } = require("../db/brand_code.db");
|
|
|
|
|
|
|
|
|
|
const {
|
|
|
|
|
getDeviceReminderChanelDb,
|
|
|
|
|
getDeviceReminderMonthlyDb,
|
|
|
|
|
getDeviceReminderCustomDb,
|
|
|
|
|
updateDeviceReminderCustomDb,
|
|
|
|
|
updateDeviceReminderMonthlyDb
|
|
|
|
|
} = require("../db/device.db");
|
|
|
|
|
|
|
|
|
|
const {
|
|
|
|
|
getSparepartsByMonthlyDb,
|
|
|
|
|
getSparepartsByCustomDb
|
|
|
|
|
} = require("../db/sparepart.db");
|
|
|
|
|
|
|
|
|
|
const { exec } = require("child_process");
|
|
|
|
|
const util = require("util");
|
|
|
|
|
const execPromise = util.promisify(exec);
|
|
|
|
|
const fs = require('fs').promises;
|
|
|
|
|
const path = require("path");
|
|
|
|
|
const { getDeviceReminderChanelDb,
|
|
|
|
|
getDeviceReminderMonthlyDb,
|
|
|
|
|
getDeviceReminderCustomDb,
|
|
|
|
|
updateDeviceReminderCustomDb
|
|
|
|
|
} = require("../db/device.db");
|
|
|
|
|
const { getSparepartsByMonthlyDb, getSparepartsByCustomDb } = require("../db/sparepart.db");
|
|
|
|
|
|
|
|
|
|
const baseDir = path.resolve(__dirname, '../scheduler');
|
|
|
|
|
const filePath = path.join(baseDir, 'reminder.json');
|
|
|
|
|
// const filePathLog = path.join(baseDir, 'log.json');
|
|
|
|
|
@@ -605,8 +613,10 @@ class NotifikasiWaService {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async onMonthlyReminder(deviceId) {
|
|
|
|
|
|
|
|
|
|
async onMonthlyReminder(deviceId, reminderMonthly, period) {
|
|
|
|
|
try {
|
|
|
|
|
|
|
|
|
|
const paramDb = {
|
|
|
|
|
limit: 100,
|
|
|
|
|
page: 1,
|
|
|
|
|
@@ -614,154 +624,312 @@ class NotifikasiWaService {
|
|
|
|
|
active: true,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const allDeviceReminders = await getDeviceReminderMonthlyDb(deviceId);
|
|
|
|
|
const devices = await getDeviceReminderMonthlyDb(deviceId);
|
|
|
|
|
|
|
|
|
|
if (!allDeviceReminders || allDeviceReminders.length === 0) {
|
|
|
|
|
return { success: false, message: 'Tidak ada data device.' };
|
|
|
|
|
if (!devices || devices.length === 0) {
|
|
|
|
|
return {
|
|
|
|
|
success: false,
|
|
|
|
|
message: `Device dengan ID ${deviceId} tidak ditemukan di database`
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const now = dayjs().tz(timeZone);
|
|
|
|
|
const currentYear = dayjs().tz(timeZone).year();
|
|
|
|
|
const currentMonth = dayjs().tz(timeZone).month() + 1;
|
|
|
|
|
const device = devices[0];
|
|
|
|
|
const deviceName = device.device_name;
|
|
|
|
|
const currentDeviceId = device.device_id;
|
|
|
|
|
|
|
|
|
|
for (const deviceReminder of allDeviceReminders) {
|
|
|
|
|
let targetReminderTime = device.reminder_at_monthly;
|
|
|
|
|
|
|
|
|
|
if (deviceReminder?.reminder_at_monthly) {
|
|
|
|
|
const deviceName = deviceReminder.device_name ?? '-';
|
|
|
|
|
const currentDeviceId = deviceReminder.device_id;
|
|
|
|
|
if (reminderMonthly) {
|
|
|
|
|
const isValidDate = dayjs.tz(reminderMonthly, this.timeZone).isValid();
|
|
|
|
|
if (!isValidDate) {
|
|
|
|
|
return {
|
|
|
|
|
success: false,
|
|
|
|
|
message: 'Format Reminder Monthly tidak valid. Gunakan format YYYY-MM-DD HH:mm:ss'
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const reminderAt = dayjs.tz(
|
|
|
|
|
deviceReminder.reminder_at_monthly,
|
|
|
|
|
timeZone
|
|
|
|
|
const updatedDevice = await updateDeviceReminderMonthlyDb(deviceId, reminderMonthly);
|
|
|
|
|
if (!updatedDevice) {
|
|
|
|
|
return {
|
|
|
|
|
success: false,
|
|
|
|
|
message: 'Gagal mengupdate Reminder Monthly.'
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
targetReminderTime = reminderMonthly;
|
|
|
|
|
|
|
|
|
|
} else if (!targetReminderTime) {
|
|
|
|
|
const reminderTime = dayjs().tz(this.timeZone).add(1, 'hour').format('YYYY-MM-DD HH:mm:ss');
|
|
|
|
|
const updatedDevice = await updateDeviceReminderMonthlyDb(deviceId, reminderTime);
|
|
|
|
|
|
|
|
|
|
if (!updatedDevice) {
|
|
|
|
|
return {
|
|
|
|
|
success: false,
|
|
|
|
|
message: 'Gagal update Reminder Monthly dengan default time.'
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
targetReminderTime = reminderTime;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const reminderAt = dayjs.tz(targetReminderTime, this.timeZone);
|
|
|
|
|
const now = dayjs().tz(this.timeZone);
|
|
|
|
|
const isEndDatePassed = now.isAfter(reminderAt) || now.isSame(reminderAt);
|
|
|
|
|
|
|
|
|
|
if (isEndDatePassed) {
|
|
|
|
|
const sendResult = await this.sendMonthlyReminderNow(
|
|
|
|
|
currentDeviceId,
|
|
|
|
|
deviceName,
|
|
|
|
|
reminderAt
|
|
|
|
|
);
|
|
|
|
|
return sendResult;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
this.stopCronJob(currentDeviceId);
|
|
|
|
|
|
|
|
|
|
const scheduleResult = await this.scheduleMonthlyReminderJob(
|
|
|
|
|
currentDeviceId,
|
|
|
|
|
deviceName,
|
|
|
|
|
reminderAt
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
success: true,
|
|
|
|
|
message: `Reminder berhasil dijadwalkan untuk device ${deviceName}`,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error('Error on Monthly Reminder:', err);
|
|
|
|
|
throw err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async scheduleMonthlyReminderJob(deviceId, deviceName, reminderAt) {
|
|
|
|
|
try {
|
|
|
|
|
const now = dayjs().tz(this.timeZone);
|
|
|
|
|
|
|
|
|
|
const targetTime = reminderAt.clone()
|
|
|
|
|
.set('second', 0)
|
|
|
|
|
.set('millisecond', 0);
|
|
|
|
|
|
|
|
|
|
const nextRun = targetTime.format('YYYY-MM-DD HH:mm:ss');
|
|
|
|
|
|
|
|
|
|
console.log(`Reminder untuk ${deviceName} dijadwalkan pada ${nextRun}`);
|
|
|
|
|
console.log(`Reminder At: ${reminderAt.format('YYYY-MM-DD HH:mm:ss')}`);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const timeoutId = setTimeout(async () => {
|
|
|
|
|
console.log(`Waktu pengiriman tiba untuk ${deviceName} pada ${dayjs().tz(this.timeZone).format('YYYY-MM-DD HH:mm:ss')}`);
|
|
|
|
|
try {
|
|
|
|
|
await this.sendMonthlyReminderNow(deviceId, deviceName, reminderAt);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error(`Gagal mengirim reminder untuk ${deviceName}:`, error);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
this.cronJobs.set(deviceId, {
|
|
|
|
|
timeoutId,
|
|
|
|
|
nextRun,
|
|
|
|
|
reminderAt: reminderAt.format('YYYY-MM-DD HH:mm:ss')
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const cronExpression = `${reminderAt.minute()} ${reminderAt.hour()} * * *`;
|
|
|
|
|
console.log(`Backup cron akan berjalan setiap hari pada ${reminderAt.hour()}:${reminderAt.minute()}`);
|
|
|
|
|
|
|
|
|
|
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 {
|
|
|
|
|
const now = dayjs().tz(this.timeZone);
|
|
|
|
|
const isEndDatePassed = now.isAfter(reminderAt) || now.isSame(reminderAt);
|
|
|
|
|
|
|
|
|
|
if (isEndDatePassed) {
|
|
|
|
|
const currentMonth = now.month() + 1;
|
|
|
|
|
const checkNotifExist = await getReminderNotificationErrorByMonthlyDb(
|
|
|
|
|
parseInt(`${currentMonth}`),
|
|
|
|
|
currentMonth,
|
|
|
|
|
deviceId
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (!checkNotifExist) {
|
|
|
|
|
await this.sendMonthlyReminderNow(deviceId, deviceName, reminderAt);
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`Reminder untuk ${deviceName} sudah pernah dikirim`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
cronTask.stop();
|
|
|
|
|
this.cronJobs.delete(`cron_${deviceId}`);
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`Menunggu reminder untuk ${deviceName}: ${reminderAt.format('YYYY-MM-DD HH:mm:ss')}`);
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error(`Backup cron job gagal untuk ${deviceName}:`, error);
|
|
|
|
|
}
|
|
|
|
|
}, {
|
|
|
|
|
timezone: this.timeZone
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
this.cronJobs.set(`cron_${deviceId}`, {
|
|
|
|
|
cronTask,
|
|
|
|
|
nextRun,
|
|
|
|
|
reminderAt: reminderAt.format('YYYY-MM-DD HH:mm:ss')
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
nextRun,
|
|
|
|
|
targetDate: targetTime.format('YYYY-MM-DD HH:mm:ss'),
|
|
|
|
|
reminderAt: reminderAt.format('YYYY-MM-DD HH:mm:ss'),
|
|
|
|
|
cronExpression: cronExpression,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error scheduling monthly reminder:', error);
|
|
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async sendMonthlyReminderNow(deviceId, deviceName, reminderAt) {
|
|
|
|
|
try {
|
|
|
|
|
|
|
|
|
|
const paramDb = {
|
|
|
|
|
limit: 100,
|
|
|
|
|
page: 1,
|
|
|
|
|
criteria: "",
|
|
|
|
|
active: true,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const now = dayjs().tz(this.timeZone);
|
|
|
|
|
const currentMonth = now.month() + 1;
|
|
|
|
|
const currentYear = now.year();
|
|
|
|
|
const monthlyCode = parseInt(`${currentMonth}`);
|
|
|
|
|
|
|
|
|
|
const checkNotifExist = await getReminderNotificationErrorByMonthlyDb(
|
|
|
|
|
monthlyCode,
|
|
|
|
|
currentMonth,
|
|
|
|
|
deviceId
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (checkNotifExist) {
|
|
|
|
|
return {
|
|
|
|
|
success: false,
|
|
|
|
|
message: `Reminder untuk device ${deviceName} sudah pernah dibuat.`
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const spareparts = await getSparepartsByMonthlyDb(currentMonth);
|
|
|
|
|
const sparepartList = spareparts && spareparts.length > 0
|
|
|
|
|
? "\n\nDaftar sparepart yang perlu diperiksa:\n" +
|
|
|
|
|
spareparts.map((sp, idx) => `${idx + 1}. ${sp.sparepart_name || 'Sparepart'}`).join('\n')
|
|
|
|
|
: "";
|
|
|
|
|
|
|
|
|
|
const data = {
|
|
|
|
|
error_code_id: monthlyCode,
|
|
|
|
|
error_chanel: 0,
|
|
|
|
|
is_send: 0,
|
|
|
|
|
is_delivered: 0,
|
|
|
|
|
is_read: 0,
|
|
|
|
|
is_active: 1,
|
|
|
|
|
message_error_issue: `reminder monthly device ${deviceName} in month ${currentMonth}`,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const resultNotificationError = await InsertNotificationErrorDb(data);
|
|
|
|
|
if (!resultNotificationError) {
|
|
|
|
|
return {
|
|
|
|
|
success: false,
|
|
|
|
|
message: 'Gagal menyimpan notifikasi error'
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const results = await getAllContactDb(paramDb);
|
|
|
|
|
const dataUsers = results.data;
|
|
|
|
|
|
|
|
|
|
let isSendNotification = false;
|
|
|
|
|
let successCount = 0;
|
|
|
|
|
let failCount = 0;
|
|
|
|
|
|
|
|
|
|
for (const dataUser of dataUsers) {
|
|
|
|
|
if (dataUser.is_active) {
|
|
|
|
|
const tokenRedirect = await generateTokenRedirect(
|
|
|
|
|
dataUser.contact_phone,
|
|
|
|
|
dataUser.contact_name,
|
|
|
|
|
resultNotificationError.notification_error_id
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const nowKey = now.format('MM-DD HH:mm');
|
|
|
|
|
const reminderKey = reminderAt.format('MM-DD HH:mm');
|
|
|
|
|
const encodedToken = encodeURIComponent(tokenRedirect);
|
|
|
|
|
const shortUrl = await shortUrltiny(encodedToken);
|
|
|
|
|
|
|
|
|
|
const isTriggered = nowKey >= reminderKey;
|
|
|
|
|
const bodyMessage =
|
|
|
|
|
`Hai ${dataUser.contact_name || "-"},\n\n` +
|
|
|
|
|
`Diberitahukan bahwa terdapat sparepart pada device "${deviceName}" ` +
|
|
|
|
|
`yang telah memasuki jadwal perawatan bulanan untuk bulan ${currentMonth} pada tahun ${currentYear}.${sparepartList}\n\n` +
|
|
|
|
|
`Silakan segera lakukan pengecekan dan perawatan untuk memastikan kinerja tetap optimal.`
|
|
|
|
|
|
|
|
|
|
if (isTriggered) {
|
|
|
|
|
const monthlyCode = parseInt(`${currentMonth}`);
|
|
|
|
|
const param = {
|
|
|
|
|
idData: resultNotificationError.notification_error_id,
|
|
|
|
|
userPhone: dataUser.contact_phone,
|
|
|
|
|
userName: dataUser.contact_name,
|
|
|
|
|
bodyMessage: bodyMessage,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const checkNotifExist = await getReminderNotificationErrorByMonthlyDb(
|
|
|
|
|
monthlyCode,
|
|
|
|
|
currentMonth,
|
|
|
|
|
currentDeviceId
|
|
|
|
|
);
|
|
|
|
|
const resultNotificationErrorUser = await createNotificationErrorUserDb({
|
|
|
|
|
notification_error_id: param.idData,
|
|
|
|
|
contact_phone: param.userPhone,
|
|
|
|
|
contact_name: param.userName,
|
|
|
|
|
message_error_issue: param.bodyMessage,
|
|
|
|
|
is_send: false,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (checkNotifExist) {
|
|
|
|
|
throw new Error(`Reminder untuk device ${deviceName} device id ${currentDeviceId} bulan ${currentMonth} sudah pernah dibuat.`);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
const resultSend = await sendNotifikasi(
|
|
|
|
|
param.userPhone,
|
|
|
|
|
param.bodyMessage
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const spareparts = await getSparepartsByMonthlyDb(currentMonth);
|
|
|
|
|
|
|
|
|
|
let sparepartList = "";
|
|
|
|
|
if (spareparts && spareparts.length > 0) {
|
|
|
|
|
sparepartList = "\n\nDaftar sparepart yang perlu diperiksa:\n" +
|
|
|
|
|
spareparts.map((sp, idx) => `${idx + 1}. ${sp.sparepart_name || 'Sparepart'}`).join('\n');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const data = {
|
|
|
|
|
error_code_id: monthlyCode,
|
|
|
|
|
error_chanel: 0,
|
|
|
|
|
is_send: 0,
|
|
|
|
|
is_delivered: 0,
|
|
|
|
|
is_read: 0,
|
|
|
|
|
is_active: 1,
|
|
|
|
|
message_error_issue: `reminder device ${deviceName} device_id: ${currentDeviceId} in month ${currentMonth}`,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const resultNotificationError = await InsertNotificationErrorDb(data);
|
|
|
|
|
const results = await getAllContactDb(paramDb);
|
|
|
|
|
const dataUsers = results.data;
|
|
|
|
|
|
|
|
|
|
let isSendNotification = false;
|
|
|
|
|
|
|
|
|
|
for (const dataUser of dataUsers) {
|
|
|
|
|
if (dataUser.is_active) {
|
|
|
|
|
|
|
|
|
|
const tokenRedirect = await generateTokenRedirect(
|
|
|
|
|
dataUser.contact_phone,
|
|
|
|
|
dataUser.contact_name,
|
|
|
|
|
resultNotificationError.notification_error_id
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const encodedToken = encodeURIComponent(tokenRedirect);
|
|
|
|
|
const shortUrl = await shortUrltiny(encodedToken);
|
|
|
|
|
|
|
|
|
|
const bodyMessage =
|
|
|
|
|
`Hai ${dataUser.contact_name || "-"},\n\n` +
|
|
|
|
|
`Diberitahukan bahwa terdapat sparepart pada device "${deviceName}" ` +
|
|
|
|
|
`yang telah memasuki jadwal perawatan bulanan untuk bulan ${currentMonth} pada tahun ${currentYear}.${sparepartList}\n\n` +
|
|
|
|
|
`Silakan segera lakukan pengecekan dan perawatan untuk memastikan kinerja tetap optimal.`;
|
|
|
|
|
|
|
|
|
|
const param = {
|
|
|
|
|
idData: resultNotificationError.notification_error_id,
|
|
|
|
|
userPhone: dataUser.contact_phone,
|
|
|
|
|
userName: dataUser.contact_name,
|
|
|
|
|
bodyMessage: bodyMessage,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const resultNotificationErrorUser = await createNotificationErrorUserDb({
|
|
|
|
|
notification_error_id: param.idData,
|
|
|
|
|
contact_phone: param.userPhone,
|
|
|
|
|
contact_name: param.userName,
|
|
|
|
|
message_error_issue: param.bodyMessage,
|
|
|
|
|
is_send: false,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const resultSend = await sendNotifikasi(
|
|
|
|
|
param.userPhone,
|
|
|
|
|
param.bodyMessage
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
await updateNotificationErrorUserDb(
|
|
|
|
|
resultNotificationErrorUser[0].notification_error_user_id,
|
|
|
|
|
{
|
|
|
|
|
is_send: resultSend.success,
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (resultSend.success) {
|
|
|
|
|
isSendNotification = resultSend.success;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await updateNotificationErrorDb(
|
|
|
|
|
resultNotificationError.notification_error_id,
|
|
|
|
|
if (resultNotificationErrorUser && resultNotificationErrorUser.length > 0) {
|
|
|
|
|
await updateNotificationErrorUserDb(
|
|
|
|
|
resultNotificationErrorUser[0].notification_error_user_id,
|
|
|
|
|
{
|
|
|
|
|
is_send: isSendNotification,
|
|
|
|
|
is_delivered: isSendNotification,
|
|
|
|
|
is_send: resultSend.success,
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await this.saveReminder({
|
|
|
|
|
notification_log: resultNotificationError.notification_error_id,
|
|
|
|
|
error_code_id: data['error_code_id'],
|
|
|
|
|
error_chanel: data['error_chanel'],
|
|
|
|
|
start_at: reminderAt.format('HH:mm'),
|
|
|
|
|
interval: 1,
|
|
|
|
|
max: 3,
|
|
|
|
|
active: 1,
|
|
|
|
|
count: 0,
|
|
|
|
|
last_run: now.toISOString(),
|
|
|
|
|
last_run_indo: now.format('DD-MM-YYYY HH:mm:ss'),
|
|
|
|
|
next_run: null,
|
|
|
|
|
next_run_indo: null,
|
|
|
|
|
message: `Reminder untuk ${deviceName} bulan ${currentMonth} telah dijalankan.`,
|
|
|
|
|
}, false);
|
|
|
|
|
|
|
|
|
|
if (resultSend.success) {
|
|
|
|
|
isSendNotification = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return { success: true, message: "Reminder has been sent." };
|
|
|
|
|
await updateNotificationErrorDb(
|
|
|
|
|
resultNotificationError.notification_error_id,
|
|
|
|
|
{
|
|
|
|
|
is_send: isSendNotification,
|
|
|
|
|
is_delivered: isSendNotification,
|
|
|
|
|
}
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.log('Error on Monthly Reminder:', err);
|
|
|
|
|
throw err;
|
|
|
|
|
await this.saveReminder({
|
|
|
|
|
notification_log: resultNotificationError.notification_error_id,
|
|
|
|
|
error_code_id: data['error_code_id'],
|
|
|
|
|
error_chanel: data['error_chanel'],
|
|
|
|
|
start_at: now.format('HH:mm'),
|
|
|
|
|
interval: 1,
|
|
|
|
|
max: 3,
|
|
|
|
|
active: 1,
|
|
|
|
|
count: 0,
|
|
|
|
|
last_run: now.toISOString(),
|
|
|
|
|
last_run_indo: now.format('DD-MM-YYYY HH:mm:ss'),
|
|
|
|
|
next_run: null,
|
|
|
|
|
next_run_indo: null,
|
|
|
|
|
message: `Reminder monthly untuk ${deviceName} bulan ${currentMonth} telah dijalankan.`,
|
|
|
|
|
}, false);
|
|
|
|
|
|
|
|
|
|
this.stopCronJob(deviceId);
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
success: true,
|
|
|
|
|
message: "Reminder has been sent.",
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@@ -777,7 +945,7 @@ class NotifikasiWaService {
|
|
|
|
|
if (!inputStartDate || !inputEndDate) {
|
|
|
|
|
return {
|
|
|
|
|
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'
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@@ -787,14 +955,14 @@ class NotifikasiWaService {
|
|
|
|
|
if (!startDateObj.isValid() || !endDateObj.isValid()) {
|
|
|
|
|
return {
|
|
|
|
|
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)) {
|
|
|
|
|
return {
|
|
|
|
|
success: false,
|
|
|
|
|
message: 'end_date harus lebih besar dari start_date'
|
|
|
|
|
message: 'End Date harus lebih besar dari Start Date'
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@@ -821,11 +989,9 @@ class NotifikasiWaService {
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log(`Berhasil update start_date dan end_date untuk device ${deviceName}`);
|
|
|
|
|
|
|
|
|
|
this.stopCronJob(currentDeviceId);
|
|
|
|
|
|
|
|
|
|
const scheduleResult = await this.scheduleReminderJob(
|
|
|
|
|
const scheduleResult = await this.scheduleCustomReminderJob(
|
|
|
|
|
currentDeviceId,
|
|
|
|
|
deviceName,
|
|
|
|
|
startDateObj,
|
|
|
|
|
@@ -837,7 +1003,7 @@ class NotifikasiWaService {
|
|
|
|
|
|
|
|
|
|
if (isEndDatePassed) {
|
|
|
|
|
console.log(`⏰ End_date sudah terlewati, mengirim reminder sekarang untuk ${deviceName}`);
|
|
|
|
|
const sendResult = await this.sendReminderNow(
|
|
|
|
|
const sendResult = await this.sendCustomReminderNow(
|
|
|
|
|
currentDeviceId,
|
|
|
|
|
deviceName,
|
|
|
|
|
startDateObj,
|
|
|
|
|
@@ -847,16 +1013,12 @@ class NotifikasiWaService {
|
|
|
|
|
return {
|
|
|
|
|
success: true,
|
|
|
|
|
message: 'Reminder berhasil dijadwalkan dan dikirim sekarang',
|
|
|
|
|
schedule: scheduleResult,
|
|
|
|
|
sendResult: sendResult
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
success: true,
|
|
|
|
|
message: `Reminder berhasil dijadwalkan untuk device ${deviceName}`,
|
|
|
|
|
schedule: scheduleResult,
|
|
|
|
|
nextRun: scheduleResult.nextRun
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
} catch (err) {
|
|
|
|
|
@@ -865,7 +1027,7 @@ class NotifikasiWaService {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async scheduleReminderJob(deviceId, deviceName, startDateObj, endDateObj) {
|
|
|
|
|
async scheduleCustomReminderJob(deviceId, deviceName, startDateObj, endDateObj) {
|
|
|
|
|
try {
|
|
|
|
|
const now = dayjs().tz(this.timeZone);
|
|
|
|
|
|
|
|
|
|
@@ -875,10 +1037,6 @@ class NotifikasiWaService {
|
|
|
|
|
|
|
|
|
|
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 () => {
|
|
|
|
|
console.log(`Waktu pengiriman tiba untuk ${deviceName} pada ${dayjs().tz(this.timeZone).format('YYYY-MM-DD HH:mm:ss')}`);
|
|
|
|
|
try {
|
|
|
|
|
@@ -886,13 +1044,11 @@ class NotifikasiWaService {
|
|
|
|
|
const isEndDatePassed = now.isAfter(endDateObj) || now.isSame(endDateObj);
|
|
|
|
|
|
|
|
|
|
if (isEndDatePassed) {
|
|
|
|
|
await this.sendReminderNow(deviceId, deviceName, startDateObj, endDateObj);
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`End_date untuk ${deviceName} belum terlewati, menunggu...`);
|
|
|
|
|
this.rescheduleReminderCheck(deviceId, deviceName, startDateObj, endDateObj);
|
|
|
|
|
await this.sendCustomReminderNow(deviceId, deviceName, startDateObj, endDateObj);
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error(`Gagal mengirim reminder untuk ${deviceName}:`, error);
|
|
|
|
|
|
|
|
|
|
} catch (err) {
|
|
|
|
|
throw err
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
@@ -907,10 +1063,8 @@ class NotifikasiWaService {
|
|
|
|
|
const endMinute = endDateObj.minute();
|
|
|
|
|
const cronExpression = `${endMinute} ${endHour} * * *`;
|
|
|
|
|
|
|
|
|
|
console.log(`Backup cron akan berjalan setiap hari pada ${endHour}:${endMinute}`);
|
|
|
|
|
|
|
|
|
|
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 {
|
|
|
|
|
const now = dayjs().tz(this.timeZone);
|
|
|
|
|
const isEndDatePassed = now.isAfter(endDateObj) || now.isSame(endDateObj);
|
|
|
|
|
@@ -924,20 +1078,23 @@ class NotifikasiWaService {
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (!checkNotifExist) {
|
|
|
|
|
await this.sendReminderNow(deviceId, deviceName, startDateObj, endDateObj);
|
|
|
|
|
await this.sendCustomReminderNow(deviceId, deviceName, startDateObj, endDateObj);
|
|
|
|
|
} else {
|
|
|
|
|
console.log(`Reminder untuk ${deviceName} sudah pernah dikirim`);
|
|
|
|
|
return {
|
|
|
|
|
success: false,
|
|
|
|
|
message: `Reminder untuk ${deviceName} sudah pernah dikirim`
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
cronTask.stop();
|
|
|
|
|
this.cronJobs.delete(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
|
|
|
|
|
});
|
|
|
|
|
@@ -962,30 +1119,15 @@ class NotifikasiWaService {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async rescheduleReminderCheck(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 {
|
|
|
|
|
await this.sendReminderNow(deviceId, deviceName, startDateObj, endDateObj);
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error(`Gagal mengirim reminder untuk ${deviceName}:`, error);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}, 60000);
|
|
|
|
|
|
|
|
|
|
this.cronJobs.set(`interval_${deviceId}`, {
|
|
|
|
|
intervalId: checkInterval
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async sendReminderNow(deviceId, deviceName, startDateObj, endDateObj) {
|
|
|
|
|
async sendCustomReminderNow(deviceId, deviceName, startDateObj, endDateObj) {
|
|
|
|
|
try {
|
|
|
|
|
console.log(`Mengirim reminder untuk ${deviceName}`);
|
|
|
|
|
|
|
|
|
|
const paramDb = {
|
|
|
|
|
limit: 100,
|
|
|
|
|
page: 1,
|
|
|
|
|
criteria: "",
|
|
|
|
|
active: true,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const now = dayjs().tz(this.timeZone);
|
|
|
|
|
const currentMonth = now.month() + 1;
|
|
|
|
|
@@ -998,7 +1140,6 @@ class NotifikasiWaService {
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (checkNotifExist) {
|
|
|
|
|
console.log(`Reminder untuk ${deviceName} sudah pernah dibuat`);
|
|
|
|
|
return {
|
|
|
|
|
success: false,
|
|
|
|
|
message: `Reminder untuk device ${deviceName} sudah pernah dibuat.`
|
|
|
|
|
@@ -1017,12 +1158,6 @@ class NotifikasiWaService {
|
|
|
|
|
|
|
|
|
|
const resultNotificationError = await InsertNotificationErrorDb(data);
|
|
|
|
|
|
|
|
|
|
const paramDb = {
|
|
|
|
|
limit: 100,
|
|
|
|
|
page: 1,
|
|
|
|
|
criteria: "",
|
|
|
|
|
active: true,
|
|
|
|
|
};
|
|
|
|
|
const results = await getAllContactDb(paramDb);
|
|
|
|
|
const dataUsers = results.data;
|
|
|
|
|
|
|
|
|
|
@@ -1078,7 +1213,7 @@ class NotifikasiWaService {
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (resultSend.success) {
|
|
|
|
|
isSendNotification = resultSend.success;
|
|
|
|
|
isSendNotification = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
@@ -1109,12 +1244,11 @@ class NotifikasiWaService {
|
|
|
|
|
|
|
|
|
|
this.stopCronJob(deviceId);
|
|
|
|
|
|
|
|
|
|
console.log(`Reminder berhasil dikirim untuk ${deviceName}`);
|
|
|
|
|
return { success: true, message: "Reminder has been sent." };
|
|
|
|
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error sending reminder now:', error);
|
|
|
|
|
throw error;
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error('Error sending reminder now:', err);
|
|
|
|
|
throw err;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@@ -1142,39 +1276,6 @@ class NotifikasiWaService {
|
|
|
|
|
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() {
|
|
|
|
|
try {
|
|
|
|
|
|
|
|
|
|
@@ -1186,19 +1287,18 @@ class NotifikasiWaService {
|
|
|
|
|
const endJSON = cleanJSON.lastIndexOf(']') + 1;
|
|
|
|
|
|
|
|
|
|
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 processes = JSON.parse(index);
|
|
|
|
|
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 pathDelete = waProcess.pm2_env.pm_cwd;
|
|
|
|
|
|
|
|
|
|
// console.log(`stop proses id: ${waProcessId}`);
|
|
|
|
|
await execPromise(`pm2 stop ${waProcessId}`);
|
|
|
|
|
|
|
|
|
|
const pathFolderDelete = [
|
|
|
|
|
@@ -1206,8 +1306,6 @@ class NotifikasiWaService {
|
|
|
|
|
path.join(pathDelete, ".wwebjs_cache"),
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
// console.log(`path: ${pathDelete}`);
|
|
|
|
|
|
|
|
|
|
for (const dir of pathFolderDelete) {
|
|
|
|
|
try {
|
|
|
|
|
await fs.access(dir);
|
|
|
|
|
@@ -1221,12 +1319,19 @@ class NotifikasiWaService {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// console.log(`start proses id: ${waProcessId}`);
|
|
|
|
|
await execPromise(`pm2 start ${waProcessId}`);
|
|
|
|
|
|
|
|
|
|
return { success: true, message: "WhatsApp has been restarted." };
|
|
|
|
|
return {
|
|
|
|
|
success: true,
|
|
|
|
|
message: "WhatsApp has been restarted."
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
} catch (err) {
|
|
|
|
|
return { success: false, error: err.message || err };
|
|
|
|
|
return {
|
|
|
|
|
success: false,
|
|
|
|
|
message: `Gagal mengirim Whatsapp`
|
|
|
|
|
};
|
|
|
|
|
throw err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|