const { getAllContactDb } = require("../db/contact.db"); const { InsertNotificationErrorDb } = require("../db/notification_error.db"); const { createNotificationErrorUserDb, updateNotificationErrorUserDb, } = require("../db/notification_error_user.db"); const { generateTokenRedirect, shortUrltiny, sendNotifikasi, } = require("../db/notification_wa.db"); const { getErrorCodeByIdDb } = require("../db/brand_code.db"); const { getDeviceNotificationByIdDb } = require("../db/notification_error.db"); 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 errorCode = await getErrorCodeByIdDb(chanel.value); const deviceNotification = await getDeviceNotificationByIdDb( chanel.chanel_id ); 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); 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 error ${errorCode?.error_code || "-" } - ${errorCode?.error_code_name || "-"} ` + `pada device ${deviceNotification?.device_name || "-" }, silahkan cek detail pada link berikut:\n` + `${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: resultNotificationError.notification_error_id, contact_phone: param.userPhone, contact_name: param.userName, is_send: false, }); const resultSend = await sendNotifikasi( param.userPhone, param.bodyMessage ); console.log("resultSend: ", resultSend); await updateNotificationErrorUserDb( resultNotificationErrorUser[0].notification_error_user_id, { is_send: resultSend?.error ? false : true, } ); } } } } } catch (error) { // throw new ErrorHandler(error.statusCode, error.message); return error; } } } module.exports = new NotifikasiWaService();