Files
cod-api/services/notifikasi-wa.service.js
2026-03-16 11:09:36 +07:00

187 lines
5.7 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 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() {
return new Promise((resolve, reject) => {
exec('pm2 jlist', (err, stdout) => {
if (err) return reject({ success: false, message: "Error list PM2" });
try {
const processes = JSON.parse(stdout);
const waProcess = processes.find(p =>
p.name.toLowerCase().includes('whatsapp') ||
p.name.toLowerCase().includes('wa-api')
);
if (!waProcess) return reject({ success: false, message: "PM2 List PM2 Not Found" });
const processId = waProcess.pm_id;
exec(`pm2 stop ${processId}`, () => {
const paths = [
path.join(__dirname, "../../.wwebjs_auth"),
path.join(__dirname, "../../.wwebjs_cache")
];
paths.forEach(dir => {
if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
});
exec(`pm2 restart ${processId}`, (reErr) => {
if (reErr) return reject({ success: false, message: "Gagal restart" });
resolve({ success: true, message: `WA has been restart.` });
});
});
} catch (e) {
reject({ success: false, message: "JSON Parse Error: " + e.message });
}
});
});
}
}
module.exports = new NotifikasiWaService();