From 73b05c5d0d511a52b4b93cb760968a1c23e7dd50 Mon Sep 17 00:00:00 2001 From: Muhammad Afif Date: Mon, 1 Jun 2026 14:50:35 +0700 Subject: [PATCH] repair api resend wa & delete log.json --- scheduler/log.json | 1 - scheduler/reminder.json | 20 +++- services/notifikasi-wa.service.js | 170 ++++++++++++++++-------------- 3 files changed, 109 insertions(+), 82 deletions(-) delete mode 100644 scheduler/log.json diff --git a/scheduler/log.json b/scheduler/log.json deleted file mode 100644 index 0637a08..0000000 --- a/scheduler/log.json +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/scheduler/reminder.json b/scheduler/reminder.json index 0637a08..7f82023 100644 --- a/scheduler/reminder.json +++ b/scheduler/reminder.json @@ -1 +1,19 @@ -[] \ No newline at end of file +[ + { + "notification_log": 851, + "error_code_id": 1, + "error_chanel": 2025, + "start_at": "02:10", + "interval": 1, + "max": 3, + "active": 1, + "count": 0, + "last_run": "2026-05-31T17:41:09.191Z", + "last_run_indo": "01-06-2026 00:41:09", + "next_run": "2026-05-31T18:41:09.191Z", + "next_run_indo": "01-06-2026 01:41:09", + "message": "Reminder untuk PLC Compressor B dengan reminder 1YEAR telah dijalankan pada 01-06-2026 00:41:09, hasil pengiriman: sukses", + "time": "00:41", + "created_at": "2026-05-31T17:41:18.802Z" + } +] \ No newline at end of file diff --git a/services/notifikasi-wa.service.js b/services/notifikasi-wa.service.js index d66e778..f50183b 100644 --- a/services/notifikasi-wa.service.js +++ b/services/notifikasi-wa.service.js @@ -27,7 +27,7 @@ const { getDeviceReminderChanelDb } = require("../db/device.db"); const baseDir = path.resolve(__dirname, '../scheduler'); const filePath = path.join(baseDir, 'reminder.json'); -const filePathLog = path.join(baseDir, 'log.json'); +// const filePathLog = path.join(baseDir, 'log.json'); const dayjs = require('dayjs'); const utc = require('dayjs/plugin/utc'); @@ -41,7 +41,7 @@ dayjs.extend(timezone); class NotifikasiWaService { async saveReminder(data, isReset = false) { - console.log(`Reminder proses dibuat`); + console.log(`Reminder dibuat`); try { let existing = []; @@ -95,58 +95,57 @@ class NotifikasiWaService { await fs.writeFile(filePath, JSON.stringify(finalData, null, 2), 'utf-8'); - await this.saveLogReminder({ - message: `Reminder berhasil disimpan`, - data, - }); + // await this.saveReminder({ + // message: `Reminder berhasil disimpan`, + // data, + // }); - console.log(`Reminder berhasil disimpan`); } catch (error) { - console.log('Error saveReminder:', error); + next(error); } } - async saveLogReminder(data) { - console.log(`Reminder Log dibuat`); + // async saveLogReminder(data) { + // console.log(`Reminder Log dibuat`); - try { - let existing = []; + // try { + // let existing = []; - // pastikan folder ada - await fs.mkdir(path.dirname(filePathLog), { recursive: true }); + // // pastikan folder ada + // await fs.mkdir(path.dirname(filePathLog), { recursive: true }); - try { - const raw = await fs.readFile(filePathLog, 'utf-8'); - if (raw) { - existing = JSON.parse(raw); - } - } catch (err) { - // file belum ada → buat file kosong - await fs.writeFile(filePathLog, '[]', 'utf-8'); - existing = []; - } + // try { + // const raw = await fs.readFile(filePathLog, 'utf-8'); + // if (raw) { + // existing = JSON.parse(raw); + // } + // } catch (err) { + // // file belum ada → buat file kosong + // await fs.writeFile(filePathLog, '[]', 'utf-8'); + // existing = []; + // } - const now = dayjs().tz(timeZone); + // const now = dayjs().tz(timeZone); - const newData = { - ...data, + // const newData = { + // ...data, - // 🔹 jam (HH:mm) WIB - time: now.format('HH:mm'), + // // 🔹 jam (HH:mm) WIB + // time: now.format('HH:mm'), - // 🔹 timestamp UTC (untuk DB) - created_at: now.toISOString() - }; + // // 🔹 timestamp UTC (untuk DB) + // created_at: now.toISOString() + // }; - await existing.push(newData); + // await existing.push(newData); - await fs.writeFile(filePathLog, JSON.stringify(existing, null, 2), 'utf-8'); + // await fs.writeFile(filePathLog, JSON.stringify(existing, null, 2), 'utf-8'); - console.log(`Reminder Log berhasil disimpan`); - } catch (error) { - console.log('Error saveReminder:', error); - } - } + // console.log(`Reminder Log berhasil disimpan`); + // } catch (error) { + // console.log('Error saveReminder:', error); + // } + // } async onNotification(topic, message) { try { @@ -298,7 +297,7 @@ class NotifikasiWaService { await this.saveReminder(newData, true); - await this.saveLogReminder({ + await this.saveReminder({ message: `Reminder ${id} berhasil dihapus` }) @@ -326,7 +325,7 @@ class NotifikasiWaService { } ); - await this.saveLogReminder({ + await this.saveReminder({ message: `Reminder ${id} berhasil dihapus` }) @@ -378,7 +377,7 @@ class NotifikasiWaService { dataUser.bodyMessage ); - await this.saveLogReminder(resultSend); + await this.saveReminder(resultSend); await updateNotificationErrorUserDb( dataUser.notification_error_user_id, @@ -491,21 +490,6 @@ class NotifikasiWaService { const resultNotificationError = await InsertNotificationErrorDb(data); - 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 - }, false); - const results = await getAllContactDb(paramDb); const dataUsers = results.data; @@ -554,10 +538,26 @@ class NotifikasiWaService { param.bodyMessage ); - await this.saveLogReminder({ - message: `Reminder dijalankan`, - resultSend - }) + 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 ${chanel.value} telah dijalankan pada ${now.format('DD-MM-YYYY HH:mm:ss')}, hasil pengiriman: ${resultSend.success ? 'sukses' : 'gagal'}`, + }, false); + + // await this.saveLogReminder({ + // message: `Reminder dijalankan`, + // resultSend + // }) await updateNotificationErrorUserDb( resultNotificationErrorUser[0].notification_error_user_id, @@ -593,25 +593,29 @@ class NotifikasiWaService { async restartWhatsapp() { try { - const processName = "Whatsapp-API-notification" && "cod-whatsapp-notif"; + + const processName = "cod-whatsapp-notif"; const { stdout } = await execPromise("pm2 jlist"); - const processes = JSON.parse(stdout); + const cleanJSON = stdout.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, ''); + + const startJSON = cleanJSON.indexOf('['); + const endJSON = cleanJSON.lastIndexOf(']') + 1; + + if (startJSON === -1 || endJSON === 0) { + throw new 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 ${processName} not found`); + if (!waProcess) throw new Error(`PM2 proses dengan nama "${processName}" tidak ditemukan!`); const waProcessId = waProcess.pm_id; const pathDelete = waProcess.pm2_env.pm_cwd; - // const execLogs = (cmd) => { - // const p = exec(cmd); - // p.stdout.pipe(process.stdout); - // p.stderr.pipe(process.stderr); - // return new Promise((res) => p.on("exit", res)); - // }; - - // console.log(`stop proses id: ${waProcessId}`) - await execPromise(`start powershell -Command "pm2 stop ${waProcessId}"`); + // console.log(`stop proses id: ${waProcessId}`); + await execPromise(`pm2 stop ${waProcessId}`); const pathFolderDelete = [ path.join(pathDelete, ".wwebjs_auth"), @@ -620,19 +624,25 @@ class NotifikasiWaService { // console.log(`path: ${pathDelete}`); - pathFolderDelete.forEach((dir) => { - if (fs.existsSync(dir)) { - // console.log(`path folder: ${dir}`); - fs.rmSync(dir, { recursive: true, force: true }); + for (const dir of pathFolderDelete) { + try { + await fs.access(dir); + console.log(`path folder ditemukan, menghapus: ${dir}`); + + await fs.rm(dir, { recursive: true, force: true }); + } catch (fsErr) { + if (fsErr.code !== 'ENOENT') { + console.error(`Gagal memproses folder ${dir}:`, fsErr.message); + } } - }); + } // console.log(`start proses id: ${waProcessId}`); - await execPromise(`start powershell -Command "pm2 start ${waProcessId}"`); + await execPromise(`pm2 start ${waProcessId}`); return { success: true, message: "WhatsApp has been restarted." }; } catch (err) { - return err; + return { success: false, error: err.message || err }; } } }