repair api resend wa & delete log.json
This commit is contained in:
@@ -1 +0,0 @@
|
|||||||
[]
|
|
||||||
@@ -1 +1,19 @@
|
|||||||
[]
|
[
|
||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -27,7 +27,7 @@ const { getDeviceReminderChanelDb } = require("../db/device.db");
|
|||||||
|
|
||||||
const baseDir = path.resolve(__dirname, '../scheduler');
|
const baseDir = path.resolve(__dirname, '../scheduler');
|
||||||
const filePath = path.join(baseDir, 'reminder.json');
|
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 dayjs = require('dayjs');
|
||||||
const utc = require('dayjs/plugin/utc');
|
const utc = require('dayjs/plugin/utc');
|
||||||
@@ -41,7 +41,7 @@ dayjs.extend(timezone);
|
|||||||
class NotifikasiWaService {
|
class NotifikasiWaService {
|
||||||
|
|
||||||
async saveReminder(data, isReset = false) {
|
async saveReminder(data, isReset = false) {
|
||||||
console.log(`Reminder proses dibuat`);
|
console.log(`Reminder dibuat`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let existing = [];
|
let existing = [];
|
||||||
@@ -95,58 +95,57 @@ class NotifikasiWaService {
|
|||||||
|
|
||||||
await fs.writeFile(filePath, JSON.stringify(finalData, null, 2), 'utf-8');
|
await fs.writeFile(filePath, JSON.stringify(finalData, null, 2), 'utf-8');
|
||||||
|
|
||||||
await this.saveLogReminder({
|
// await this.saveReminder({
|
||||||
message: `Reminder berhasil disimpan`,
|
// message: `Reminder berhasil disimpan`,
|
||||||
data,
|
// data,
|
||||||
});
|
// });
|
||||||
|
|
||||||
console.log(`Reminder berhasil disimpan`);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('Error saveReminder:', error);
|
next(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async saveLogReminder(data) {
|
// async saveLogReminder(data) {
|
||||||
console.log(`Reminder Log dibuat`);
|
// console.log(`Reminder Log dibuat`);
|
||||||
|
|
||||||
try {
|
// try {
|
||||||
let existing = [];
|
// let existing = [];
|
||||||
|
|
||||||
// pastikan folder ada
|
// // pastikan folder ada
|
||||||
await fs.mkdir(path.dirname(filePathLog), { recursive: true });
|
// await fs.mkdir(path.dirname(filePathLog), { recursive: true });
|
||||||
|
|
||||||
try {
|
// try {
|
||||||
const raw = await fs.readFile(filePathLog, 'utf-8');
|
// const raw = await fs.readFile(filePathLog, 'utf-8');
|
||||||
if (raw) {
|
// if (raw) {
|
||||||
existing = JSON.parse(raw);
|
// existing = JSON.parse(raw);
|
||||||
}
|
// }
|
||||||
} catch (err) {
|
// } catch (err) {
|
||||||
// file belum ada → buat file kosong
|
// // file belum ada → buat file kosong
|
||||||
await fs.writeFile(filePathLog, '[]', 'utf-8');
|
// await fs.writeFile(filePathLog, '[]', 'utf-8');
|
||||||
existing = [];
|
// existing = [];
|
||||||
}
|
// }
|
||||||
|
|
||||||
const now = dayjs().tz(timeZone);
|
// const now = dayjs().tz(timeZone);
|
||||||
|
|
||||||
const newData = {
|
// const newData = {
|
||||||
...data,
|
// ...data,
|
||||||
|
|
||||||
// 🔹 jam (HH:mm) WIB
|
// // 🔹 jam (HH:mm) WIB
|
||||||
time: now.format('HH:mm'),
|
// time: now.format('HH:mm'),
|
||||||
|
|
||||||
// 🔹 timestamp UTC (untuk DB)
|
// // 🔹 timestamp UTC (untuk DB)
|
||||||
created_at: now.toISOString()
|
// 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`);
|
// console.log(`Reminder Log berhasil disimpan`);
|
||||||
} catch (error) {
|
// } catch (error) {
|
||||||
console.log('Error saveReminder:', error);
|
// console.log('Error saveReminder:', error);
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
async onNotification(topic, message) {
|
async onNotification(topic, message) {
|
||||||
try {
|
try {
|
||||||
@@ -298,7 +297,7 @@ class NotifikasiWaService {
|
|||||||
|
|
||||||
await this.saveReminder(newData, true);
|
await this.saveReminder(newData, true);
|
||||||
|
|
||||||
await this.saveLogReminder({
|
await this.saveReminder({
|
||||||
message: `Reminder ${id} berhasil dihapus`
|
message: `Reminder ${id} berhasil dihapus`
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -326,7 +325,7 @@ class NotifikasiWaService {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
await this.saveLogReminder({
|
await this.saveReminder({
|
||||||
message: `Reminder ${id} berhasil dihapus`
|
message: `Reminder ${id} berhasil dihapus`
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -378,7 +377,7 @@ class NotifikasiWaService {
|
|||||||
dataUser.bodyMessage
|
dataUser.bodyMessage
|
||||||
);
|
);
|
||||||
|
|
||||||
await this.saveLogReminder(resultSend);
|
await this.saveReminder(resultSend);
|
||||||
|
|
||||||
await updateNotificationErrorUserDb(
|
await updateNotificationErrorUserDb(
|
||||||
dataUser.notification_error_user_id,
|
dataUser.notification_error_user_id,
|
||||||
@@ -491,21 +490,6 @@ class NotifikasiWaService {
|
|||||||
|
|
||||||
const resultNotificationError = await InsertNotificationErrorDb(data);
|
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 results = await getAllContactDb(paramDb);
|
||||||
|
|
||||||
const dataUsers = results.data;
|
const dataUsers = results.data;
|
||||||
@@ -554,10 +538,26 @@ class NotifikasiWaService {
|
|||||||
param.bodyMessage
|
param.bodyMessage
|
||||||
);
|
);
|
||||||
|
|
||||||
await this.saveLogReminder({
|
await this.saveReminder({
|
||||||
message: `Reminder dijalankan`,
|
notification_log: resultNotificationError.notification_error_id,
|
||||||
resultSend
|
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(
|
await updateNotificationErrorUserDb(
|
||||||
resultNotificationErrorUser[0].notification_error_user_id,
|
resultNotificationErrorUser[0].notification_error_user_id,
|
||||||
@@ -593,25 +593,29 @@ class NotifikasiWaService {
|
|||||||
|
|
||||||
async restartWhatsapp() {
|
async restartWhatsapp() {
|
||||||
try {
|
try {
|
||||||
const processName = "Whatsapp-API-notification" && "cod-whatsapp-notif";
|
|
||||||
|
const processName = "cod-whatsapp-notif";
|
||||||
const { stdout } = await execPromise("pm2 jlist");
|
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);
|
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 waProcessId = waProcess.pm_id;
|
||||||
const pathDelete = waProcess.pm2_env.pm_cwd;
|
const pathDelete = waProcess.pm2_env.pm_cwd;
|
||||||
|
|
||||||
// const execLogs = (cmd) => {
|
// console.log(`stop proses id: ${waProcessId}`);
|
||||||
// const p = exec(cmd);
|
await execPromise(`pm2 stop ${waProcessId}`);
|
||||||
// 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}"`);
|
|
||||||
|
|
||||||
const pathFolderDelete = [
|
const pathFolderDelete = [
|
||||||
path.join(pathDelete, ".wwebjs_auth"),
|
path.join(pathDelete, ".wwebjs_auth"),
|
||||||
@@ -620,19 +624,25 @@ class NotifikasiWaService {
|
|||||||
|
|
||||||
// console.log(`path: ${pathDelete}`);
|
// console.log(`path: ${pathDelete}`);
|
||||||
|
|
||||||
pathFolderDelete.forEach((dir) => {
|
for (const dir of pathFolderDelete) {
|
||||||
if (fs.existsSync(dir)) {
|
try {
|
||||||
// console.log(`path folder: ${dir}`);
|
await fs.access(dir);
|
||||||
fs.rmSync(dir, { recursive: true, force: true });
|
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}`);
|
// 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." };
|
return { success: true, message: "WhatsApp has been restarted." };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return err;
|
return { success: false, error: err.message || err };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user