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 { getErrorCodeByBrandAndCodeDb } = 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 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); 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 kode error ${chanel?.value ?? "-"} ${errorCode?.error_code_name ?? ""} Chanel ${chanel?.chanel_id ?? "-"} ` + `pada device ${deviceNotification?.device_name ?? "berikut" }, 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: 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 ? true : false, } ); } } } } } catch (error) { // throw new ErrorHandler(error.statusCode, error.message); return error; } } } module.exports = new NotifikasiWaService();