Files
cod-api/services/notifikasi-wa.service.js
2026-03-18 17:25:40 +07:00

198 lines
5.9 KiB
JavaScript

const { getAllContactDb } = require("../db/contact.db");
const {
InsertNotificationErrorDb,
updateNotificationErrorDb,
} = require("../db/notification_error.db");
const {
createNotificationErrorUserDb,
updateNotificationErrorUserDb,
} = require("../db/notification_error_user.db");
const {
generateTokenRedirect,
shortUrltiny,
sendNotifikasi,
} = require("../db/notification_wa.db");
const { getErrorCodeByBrandAndCodeDb } = require("../db/brand_code.db");
const { getDeviceNotificationByIdDb } = require("../db/notification_error.db");
const { exec } = require("child_process");
const util = require("util");
const execPromise = util.promisify(exec);
const fs = require("fs");
const path = require("path");
class NotifikasiWaService {
async onNotification(topic, message) {
try {
const paramDb = {
limit: 100,
page: 1,
criteria: "",
active: 1,
};
// const chanel = {
// "time": "2025-12-11 11:10:58",
// "c_4501": 4,
// "c_5501": 3,
// "c_6501": 0
// }
if (topic === process.env.TOPIC_COD ?? "morek") {
const dataMqtt = JSON.parse(message);
const resultChanel = [];
Object.entries(dataMqtt).forEach(([key, value]) => {
if (key.startsWith("c_")) {
resultChanel.push({
chanel_id: Number(key.slice(2)),
value,
});
}
});
const results = await getAllContactDb(paramDb);
const dataUsers = results.data;
for (const chanel of resultChanel) {
const deviceNotification = await getDeviceNotificationByIdDb(
Number(chanel.chanel_id)
);
const errorCode = await getErrorCodeByBrandAndCodeDb(
deviceNotification?.brand_id ?? 0,
chanel.value
);
const data = {
error_code_id: chanel.value,
error_chanel: chanel.chanel_id,
is_send: false,
is_delivered: false,
is_read: false,
is_active: true,
};
const resultNotificationError = await InsertNotificationErrorDb(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` +
`Terjadi peringatan dengan kode ${chanel?.value ?? "-"} "${
errorCode?.error_code_name ?? ""
}", Chanel ${chanel?.chanel_id ?? "-"} ` +
`pada device ${deviceNotification?.device_name ?? "berikut"},` +
`\nSilahkan cek detail pada link :` +
`${shortUrl}`;
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,
{
is_send: isSendNotification,
is_delivered: isSendNotification,
}
);
}
}
} catch (err) {
return err;
}
}
async restartWhatsapp() {
try {
const processName = "Whatsapp-API-notification";
const { stdout } = await execPromise("pm2 jlist");
const processes = JSON.parse(stdout);
const waProcess = processes.find((p) => p.name === processName);
if (!waProcess) throw new Error(`PM2 ${processName} not found`);
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}"`);
const pathFolderDelete = [
path.join(pathDelete, ".wwebjs_auth"),
path.join(pathDelete, ".wwebjs_cache"),
];
// console.log(`path: ${pathDelete}`);
pathFolderDelete.forEach((dir) => {
if (fs.existsSync(dir)) {
// console.log(`path folder: ${dir}`);
fs.rmSync(dir, { recursive: true, force: true });
}
});
// console.log(`start proses id: ${waProcessId}`);
await execPromise(`start powershell -Command "pm2 restart ${waProcessId}"`);
return { success: true, message: "WhatsApp has been restarted." };
} catch (err) {
return err;
}
}
}
module.exports = new NotifikasiWaService();