From 2a9d00ada35dcf0a9f7483508ad52eff1879b0e2 Mon Sep 17 00:00:00 2001 From: AdisakKanthawilang Date: Fri, 21 Mar 2025 17:05:52 +0700 Subject: [PATCH] add rabbit noti --- src/controllers/CommandController.ts | 130 +++------------------------ src/services/rabbitmq.ts | 77 ++++++++++++++-- 2 files changed, 83 insertions(+), 124 deletions(-) diff --git a/src/controllers/CommandController.ts b/src/controllers/CommandController.ts index 3e6be6b8..21012d1b 100644 --- a/src/controllers/CommandController.ts +++ b/src/controllers/CommandController.ts @@ -50,7 +50,7 @@ import { EmployeePosMaster } from "../entities/EmployeePosMaster"; import { ProfileDiscipline } from "../entities/ProfileDiscipline"; import { ProfileDisciplineHistory } from "../entities/ProfileDisciplineHistory"; import { PosMasterAct } from "../entities/PosMasterAct"; -import { sendToQueue } from "../services/rabbitmq"; +import { sendToQueue, sendToQueueCommandNoti } from "../services/rabbitmq"; import { PosLevel } from "../entities/PosLevel"; import { PosType } from "../entities/PosType"; import { @@ -1149,124 +1149,16 @@ export class CommandController extends Controller { })) : []; - await new CallAPI() - .PostData(request, "/placement/noti/profiles", { - subject: `${command.issue}`, - body: `${command.issue}`, - receiverUserIds: profiles, - payload: "", //แนบไฟล์ - isSendMail: true, - isSendInbox: true, - isSendNotification: true, - }) - .catch((error) => { - console.error("Error calling API:", error); - }); - let profilesSend = - command && command.commandSends.length > 0 - ? command.commandSends - .filter((x) => x.profileId != null) - .map((x) => ({ - receiverUserId: x.profileId, - notiLink: "", - isSendMail: x.commandSendCCs.map((x) => x.name == "EMAIL").length > 0 ? true : false, - isSendInbox: x.commandSendCCs.map((x) => x.name == "INBOX").length > 0 ? true : false, - isSendNotification: true, - })) - : []; - - await new CallAPI() - .PostData(request, "/placement/noti/profiles-send", { - subject: `${command.issue}`, - body: `${command.issue}`, - receiverUserIds: profilesSend, - payload: "", //แนบไฟล์ - }) - .catch((error) => { - console.error("Error calling API:", error); - }); - if ( - new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()) < - new Date( - command.commandExcecuteDate.getFullYear(), - command.commandExcecuteDate.getMonth(), - command.commandExcecuteDate.getDate(), - ) - ) { - command.status = "WAITING"; - command.lastUpdateUserId = request.user.sub; - command.lastUpdateFullName = request.user.name; - command.lastUpdatedAt = new Date(); - await this.commandRepository.save(command); - } else { - const path = commandTypePath(command.commandType.code); - if (path == null) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบประเภทคำสั่งนี้ในระบบ"); - const msg = { - data: { - id: command.id, - status: "REPORTED", - lastUpdateUserId: request.user.sub, - lastUpdateFullName: request.user.name, - lastUpdatedAt: new Date(), - }, - user: request.user, - token: request.headers["authorization"], - }; - sendToQueue(msg); - } - return new HttpSuccess(); - } - - /** - * API ออกคำสั่ง - * - * @summary API ออกคำสั่ง - * - * @param {string} id Id คำสั่ง - */ - @Put("testRabbit/{id}") - async testRabbit( - @Path() id: string, - @Body() - requestBody: { sign?: boolean }, - @Request() request: RequestWithUser, - ) { - await new permission().PermissionUpdate(request, "COMMAND"); - const command = await this.commandRepository.findOne({ - where: { id: id }, - relations: ["commandType", "commandRecives"], - }); - if (!command) { - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลคำสั่งนี้"); - } - command.isSign = true; - if (command.commandExcecuteDate == null) - throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบวันที่คำสั่งมีผล"); - - let profiles = - command && command.commandRecives.length > 0 - ? command.commandRecives - .filter((x) => x.profileId != null) - .map((x) => ({ - receiverUserId: x.profileId, - notiLink: "", - })) - : []; - - await new CallAPI() - .PostData(request, "/placement/noti/profiles", { - subject: `${command.issue}`, - body: `${command.issue}`, - receiverUserIds: profiles, - payload: "", //แนบไฟล์ - isSendMail: true, - isSendInbox: true, - isSendNotification: true, - }) - .catch((error) => { - console.error("Error calling API:", error); - }); - + const msgNoti = { + data: { + command: command, + profiles: profiles + }, + user: request.user, + token: request.headers["authorization"], + }; + sendToQueueCommandNoti(msgNoti); + if ( new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()) < new Date( diff --git a/src/services/rabbitmq.ts b/src/services/rabbitmq.ts index d47e0bd3..45a95520 100644 --- a/src/services/rabbitmq.ts +++ b/src/services/rabbitmq.ts @@ -28,13 +28,15 @@ import { PermissionOrg } from "../entities/PermissionOrg"; export let sendToQueue: (payload: any) => void; export let sendToQueueOrg: (payload: any) => void; export let sendToQueueOrgDraft: (payload: any) => void; +export let sendToQueueCommandNoti: (payload: any) => void; export async function init() { //----> (1) Producer if ( !process.env.AMQ_URL || !process.env.AMQ_QUEUE || !process.env.AMQ_QUEUE_ORG || - !process.env.AMQ_QUEUE_ORG_DRAFT + !process.env.AMQ_QUEUE_ORG_DRAFT || + !process.env.AMQ_QUEUE_COMMAND_NOTI ) return; @@ -43,6 +45,7 @@ export async function init() { AMQ_QUEUE: queue, AMQ_QUEUE_ORG: queue_org, AMQ_QUEUE_ORG_DRAFT: queue_org_draft, + AMQ_QUEUE_COMMAND_NOTI: queue_command_noti, } = process.env; //----> (1.2) get url and queue from .env const connection = await amqp.connect(url); //----> (1.3) set up url with amqp protocol @@ -54,9 +57,10 @@ export async function init() { console.log(channel ? "[AMQ] Create channel success" : "[AMQ] Create channel failed"); channel.assertQueue(queue, { durable: true }), //----> (1.5) assert queue and set durable (if "true" save to disk on RabbitMQ) - channel.assertQueue(queue_org, { durable: true }), - channel.assertQueue(queue_org_draft, { durable: true }), - channel.prefetch(1); + channel.assertQueue(queue_org, { durable: true }), + channel.assertQueue(queue_org_draft, { durable: true }), + channel.assertQueue(queue_command_noti, { durable: true }), + channel.prefetch(1); sendToQueue = (payload: any, persistent = true) => { //----> (2) sendQueue To RabbitMQ and set persistent (if "true" redo the failed queue when server run again) @@ -73,10 +77,15 @@ export async function init() { channel.sendToQueue(queue_org_draft, Buffer.from(JSON.stringify(payload)), { persistent }); }; + sendToQueueCommandNoti = (payload: any, persistent = true) => { + channel.sendToQueue(queue_command_noti, Buffer.from(JSON.stringify(payload)), { persistent }); + }; + console.log("[AMQ] Listening for message..."); createConsumer(queue, channel, handler), //----> (3) Process Consumer - createConsumer(queue_org, channel, handler_org); + createConsumer(queue_org, channel, handler_org); createConsumer(queue_org_draft, channel, handler_org_draft); + createConsumer(queue_command_noti, channel, handler_command_noti); // createConsumer(queue2, channel, handler2); } @@ -156,6 +165,64 @@ async function handler(msg: amqp.ConsumeMessage): Promise { }); } +async function handler_command_noti(msg: amqp.ConsumeMessage): Promise { + const { data, token, user } = JSON.parse(msg.content.toString()); + const { profiles, command } = data; + + try { + const profilesNotiRequest = new CallAPI() + .PostData( + { headers: { authorization: token } }, + "/placement/noti/profiles", + { + subject: `${command.issue}`, + body: `${command.issue}`, + receiverUserIds: profiles, + payload: "",// แนบไฟล์ (ถ้าจำเป็น) + isSendMail: true, + isSendInbox: true, + isSendNotification: true, + }, + false + ); + + let profilesSend = command && command.commandSends.length > 0 + ? command.commandSends + .filter((x: any) => x.profileId != null) + .map((x: any) => ({ + receiverUserId: x.profileId, + notiLink: "", + isSendMail: x.commandSendCCs.map((x: any) => x.name == "EMAIL").length > 0, + isSendInbox: x.commandSendCCs.map((x: any) => x.name == "INBOX").length > 0, + isSendNotification: true, + })) + : []; + + const profilesSendRequest = new CallAPI() + .PostData( + { headers: { authorization: token } }, + "/placement/noti/profiles-send", + { + subject: `${command.issue}`, + body: `${command.issue}`, + receiverUserIds: profilesSend, + payload: "", // แนบไฟล์ (ถ้าจำเป็น) + }, + false + ); + + await Promise.all([profilesNotiRequest, profilesSendRequest]); + + console.log("[AMQ] Send Notification Success"); + return true; + + } catch (error) { + console.error("[AMQ] Error:", error); + return false; + } +} + + async function handler_org(msg: amqp.ConsumeMessage): Promise { //----> condition before process consume const repoPosmaster = AppDataSource.getRepository(PosMaster);