Files
cod-api/services/notification_error.service.js

268 lines
7.6 KiB
JavaScript

// services/notification_error.service.js
const {
getAllNotificationDb,
getNotificationByIdDb,
InsertNotificationErrorDb,
getUsersNotificationErrorDb,
updateNotificationErrorDb,
} = require("../db/notification_error.db");
const { getErrorCodeByIdDb } = require("../db/brand_code.db");
const { getSolutionsByErrorCodeIdDb } = require("../db/brand_code_solution.db");
const {
getAllNotificationErrorLogDb,
getNotificationErrorLogByNotificationErrorIdDb,
} = require("../db/notification_error_log.db");
const { getSparepartsByErrorCodeIdDb } = require("../db/brand_sparepart.db");
const {
getNotificationErrorByIdDb,
} = require("../db/notification_error_user.db");
const { getFileUploadByPathDb } = require("../db/file_uploads.db");
const {
generateTokenRedirect,
shortUrltiny,
sendNotifikasi,
} = require("../db/notification_wa.db");
const { ErrorHandler } = require("../helpers/error");
class NotificationService {
static async getAllNotification(param) {
try {
const results = await getAllNotificationDb(param);
if (results && Array.isArray(results.data)) {
results.data = await Promise.all(
results.data.map(async (notification) => {
const usersNotification =
(await getUsersNotificationErrorDb(
notification.notification_error_id
)) || [];
return {
...notification,
users: usersNotification,
};
})
);
}
return results;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
static async createNotificationError(data) {
try {
if (!data || typeof data !== "object") data = {};
const result = await InsertNotificationErrorDb(data);
return result;
} catch (error) {
return error;
}
}
static async getNotificationById(id) {
try {
const notification = await getNotificationByIdDb(id);
if (
!notification ||
(Array.isArray(notification) && notification.length < 1)
) {
throw new ErrorHandler(404, "Notification not found");
}
const usersNotification = (await getUsersNotificationErrorDb(id)) || [];
// Get error code details if error_code_id exists
if (notification.error_code_id) {
const errorCode = await getErrorCodeByIdDb(notification.error_code_id);
if (errorCode) {
// Get solutions for this error code
const solutions =
(await getSolutionsByErrorCodeIdDb(errorCode.error_code_id)) || [];
const spareparts =
(await getSparepartsByErrorCodeIdDb(errorCode.error_code_id)) || [];
const solutionsWithDetails = await Promise.all(
solutions.map(async (solution) => {
let fileData = null;
if (
solution.path_solution &&
solution.type_solution &&
solution.type_solution !== "text"
) {
try {
fileData = await getFileUploadByPathDb(
solution.path_solution
);
} catch (e) {
fileData = null;
}
}
return {
...solution,
file_upload_name: fileData?.file_upload_name || null,
path_document: fileData?.path_document || null,
};
})
);
notification.error_code = {
...errorCode,
solution: solutionsWithDetails,
spareparts: spareparts,
};
}
}
// Get activity logs for this notification
const notificationLogs =
(await getNotificationErrorLogByNotificationErrorIdDb(id)) || [];
notification.users = usersNotification;
notification.activity_logs = notificationLogs;
return notification;
} catch (error) {
throw new ErrorHandler(error.statusCode, error.message);
}
}
static async updateNotificationError(notification_error_id, data) {
try {
const dataExist = await getNotificationErrorByIdDb(notification_error_id);
if (!dataExist || (Array.isArray(dataExist) && dataExist.length < 1)) {
throw new ErrorHandler(404, "Notification Error User not found");
}
const notification = Array.isArray(dataExist) ? dataExist[0] : dataExist;
if (notification.is_read === true) {
return { success: true, message: "Notification has already been read" };
}
if (!notification.is_read) {
const updateStatus = await updateNotificationErrorDb(
notification_error_id,
{ is_read: true }
);
if (!updateStatus) {
throw new ErrorHandler(500, "Failed to update notification");
}
}
return { success: true, message: "Notification marked as read" };
} catch (error) {
throw new ErrorHandler(error.statusCode || 500, error.message);
}
}
static async resendNotification(id) {
const deviceNotification = await getNotificationByIdDb(id);
if (!deviceNotification)
throw new ErrorHandler(404, "Notification Data not found");
const errorCode = await getErrorCodeByIdDb(
deviceNotification.error_code_id
);
const dataExist = await getUsersNotificationErrorDb(id);
const activeUsers =
dataExist?.filter((user) => user.is_active === true) || [];
if (activeUsers.length < 1)
throw new ErrorHandler(404, "No active contacts");
this._executeResendWa(
id,
activeUsers,
deviceNotification,
errorCode
).catch((err) => console.error("Background Process Error:", err));
return {
count: activeUsers.length,
};
}
static async _executeResendWa(
id,
activeUsers,
deviceNotification,
errorCode
) {
console.log(`user active: `, id, activeUsers);
const sendPromises = activeUsers.map(async (user) => {
try {
console.log(`user: ${user.contact_name} (${user.contact_phone})`);
const tokenRedirect = await generateTokenRedirect(
user.contact_phone,
user.contact_name,
id
);
const encodedToken = encodeURIComponent(tokenRedirect);
console.log("token: ", tokenRedirect);
const shortUrl = await shortUrltiny(encodedToken);
console.log("URL:", shortUrl);
const bodyWithUrl =
`Hai ${user.contact_name || "-"}\n` +
`Terjadi peringatan dengan kode ${errorCode?.error_code || "-"} - ${
errorCode?.error_code_name
} pada device ${deviceNotification.device_name || "-"}.\n` +
`Silahkan cek detail pada link berikut:\n ${shortUrl}`;
const resultSend = await sendNotifikasi(
user.contact_phone,
bodyWithUrl
);
console.log("notifikasi wa:", resultSend)
const isSuccess = resultSend?.error ? false : true;
await updateNotificationErrorDb(user.notification_error_id, {
is_send: isSuccess,
is_delivered: isSuccess,
});
return { phone: user.contact_phone, status: "success" };
} catch (err) {
console.error(`Gagal mengirim ke ${user.contact_phone}:`, err.message);
return {
phone: user.contact_phone,
status: "failed",
error: err.message,
};
}
});
const results = await Promise.all(sendPromises);
console.log("result akhir: ", results)
console.log(
`Resend chat: ${
results.filter((r) => r.status === "success").length
}, Gagal: ${results.filter((r) => r.status === "failed").length}`
);
}
}
module.exports = NotificationService;