diff --git a/scheduler/reminder.json b/scheduler/reminder.json index 0637a08..e69de29 100644 --- a/scheduler/reminder.json +++ b/scheduler/reminder.json @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/services/notifikasi-wa.service.js b/services/notifikasi-wa.service.js index 35f1828..7e372f4 100644 --- a/services/notifikasi-wa.service.js +++ b/services/notifikasi-wa.service.js @@ -591,171 +591,163 @@ class NotifikasiWaService { } } - async onMonthlySparepartReminder(deviceId) { - try { - const paramDb = { - limit: 100, - page: 1, - criteria: "", - active: 1, - }; +async onMonthlySparepartReminder(deviceId) { + try { + const paramDb = { + limit: 100, + page: 1, + criteria: "", + active: true, + }; - const allDeviceReminders = await getDeviceReminderMonthlyDb(deviceId); + const allDeviceReminders = await getDeviceReminderMonthlyDb(deviceId); - if (!allDeviceReminders || allDeviceReminders.length === 0) { - return { success: false, message: 'Tidak ada data device.' }; - } + if (!allDeviceReminders || allDeviceReminders.length === 0) { + return { success: false, message: 'Tidak ada data device.' }; + } - const now = dayjs().tz(timeZone); - const currentYear = dayjs().tz(timeZone).year(); - const currentMonth = dayjs().tz(timeZone).month() + 1; + const now = dayjs().tz(timeZone); + const currentYear = dayjs().tz(timeZone).year(); + const currentMonth = dayjs().tz(timeZone).month() + 1; - for (const deviceReminder of allDeviceReminders) { + for (const deviceReminder of allDeviceReminders) { - if (deviceReminder?.reminder_at_monthly) { - const deviceName = deviceReminder.device_name ?? '-'; + if (deviceReminder?.reminder_at_monthly) { + const deviceName = deviceReminder.device_name ?? '-'; - const reminderAt = dayjs.tz( - deviceReminder.reminder_at_monthly, - timeZone + const reminderAt = dayjs.tz( + deviceReminder.reminder_at_monthly, + timeZone + ); + + const nowKey = now.format('MM-DD HH:mm'); + const reminderKey = reminderAt.format('MM-DD HH:mm'); + + const isTriggered = nowKey >= reminderKey; + + if (isTriggered) { + const monthlyCode = parseInt(`${currentMonth}`); + + const checkNotifExist = await getReminderNotificationErrorByMonthlyDb( + monthlyCode, + currentMonth ); - const nowKey = now.format('MM-DD HH:mm'); + if (checkNotifExist) { + throw new Error(`Reminder untuk device ${deviceName} bulan ${currentMonth} sudah pernah dibuat.`); + } - const reminderKey = reminderAt.format('MM-DD HH:mm'); + const spareparts = await getSparepartsByMonthlyDb(currentMonth); - const isTriggered = nowKey >= reminderKey; + 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'); + } - if (isTriggered) { - const monthlyCode = parseInt(`${currentMonth}`); + 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} in month ${currentMonth}`, + }; - const checkNotifExist = await getReminderNotificationErrorByMonthlyDb( - monthlyCode, - currentMonth - ); + const resultNotificationError = await InsertNotificationErrorDb(data); + const results = await getAllContactDb(paramDb); + const dataUsers = results.data; - if (!checkNotifExist) { + let isSendNotification = false; + let successLogMessage = ""; - const spareparts = await getSparepartsByMonthlyDb(currentMonth); + for (const dataUser of dataUsers) { + if (dataUser.is_active) { - 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 tokenRedirect = await generateTokenRedirect( + dataUser.contact_phone, + dataUser.contact_name, + resultNotificationError.notification_error_id + ); - 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} in month ${currentMonth}`, + 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 resultNotificationError = await InsertNotificationErrorDb(data); + 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 results = await getAllContactDb(paramDb); + const resultSend = await sendNotifikasi( + param.userPhone, + param.bodyMessage + ); - const dataUsers = results.data; - - let isSendNotification = false; - - for (const dataUser of dataUsers) { - if (dataUser.is_active || dataUser.is_active === 1) { - - return { success: false, message: 'Tidak ada data user yang aktif.' }; - - 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 this.saveLogReminder({ - // message: `Reminder dijalankan`, - // resultSend - // }) - - await updateNotificationErrorUserDb( - resultNotificationErrorUser[0].notification_error_user_id, - { - 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} dengan reminder bulan ${currentMonth} telah dijalankan pada ${now.format('DD-MM-YYYY HH:mm:ss')}, hasil pengiriman: ${resultSend.success ? 'sukses' : 'gagal'}`, - }, false); - - if (resultSend.success) { - isSendNotification = resultSend.success; - } - } - } - - await updateNotificationErrorDb( - resultNotificationError.notification_error_id, + await updateNotificationErrorUserDb( + resultNotificationErrorUser[0].notification_error_user_id, { - is_send: isSendNotification, - is_delivered: isSendNotification, + is_send: resultSend.success, } ); + + if (resultSend.success) { + isSendNotification = resultSend.success; + } } } + + await updateNotificationErrorDb( + resultNotificationError.notification_error_id, + { + is_send: isSendNotification, + is_delivered: isSendNotification, + } + ); + + 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. Detail: ${successLogMessage}`, + }, false); + } } - - } catch (err) { - console.log('Error onNotificationReminder:', err); - throw err; } + + return { success: true, message: "Reminder has been sent." }; + + } catch (err) { + console.log('Error onNotificationReminder:', err); + throw err; } +} async restartWhatsapp() {