Skip to content

Commit

Permalink
Inclusão na Api: userId e queueId
Browse files Browse the repository at this point in the history
  • Loading branch information
rtenorioh committed Sep 24, 2024
1 parent d7c442c commit 3847ac7
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 56 deletions.
63 changes: 45 additions & 18 deletions backend/src/controllers/ApiController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,19 @@ import SetTicketMessagesAsRead from "../helpers/SetTicketMessagesAsRead";
import Message from "../models/Message";
import Whatsapp from "../models/Whatsapp";
import CreateOrUpdateContactService from "../services/ContactServices/CreateOrUpdateContactService";
import ListSettingsServiceOne from "../services/SettingServices/ListSettingsServiceOne";
import FindOrCreateTicketService from "../services/TicketServices/FindOrCreateTicketService";
import ShowTicketService from "../services/TicketServices/ShowTicketService";
import UpdateTicketService from "../services/TicketServices/UpdateTicketService";
import CheckIsValidContact from "../services/WbotServices/CheckIsValidContact";
import CheckContactNumber from "../services/WbotServices/CheckNumber";
import GetProfilePicUrl from "../services/WbotServices/GetProfilePicUrl";
import SendWhatsAppMedia from "../services/WbotServices/SendWhatsAppMedia";
import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage";
import UpdateTicketService from "../services/TicketServices/UpdateTicketService";
import ListSettingsServiceOne from "../services/SettingServices/ListSettingsServiceOne";

type WhatsappData = {
whatsappId: number;
}
};

type MessageData = {
body: string;
Expand All @@ -33,7 +33,9 @@ interface ContactData {

const createContact = async (
whatsappId: number | undefined,
newContact: string
newContact: string,
userId?: number,
queueId?: number
) => {
await CheckIsValidContact(newContact);

Expand Down Expand Up @@ -67,7 +69,9 @@ const createContact = async (
const createTicket = await FindOrCreateTicketService(
contact,
whatsapp.id,
1
1,
userId,
queueId
);

const ticket = await ShowTicketService(createTicket.id);
Expand All @@ -78,49 +82,72 @@ const createContact = async (
};

export const index = async (req: Request, res: Response): Promise<Response> => {
const newContact: ContactData = req.body;
const { whatsappId }: WhatsappData = req.body;
const { body, quotedMsg }: MessageData = req.body;
const {
whatsappId,
body,
quotedMsg,
userId,
queueId
}: MessageData & WhatsappData & { userId: number; queueId: number } =
req.body;
const medias = req.files as Express.Multer.File[];
const newContact: ContactData = req.body;

newContact.number = newContact.number.replace("-", "").replace(" ", "");
const formattedNumber = newContact.number.replace("-", "").replace(" ", "");

const schema = Yup.object().shape({
number: Yup.string()
.required()
.matches(/^\d+$/, "Invalid number format. Only numbers is allowed.")
.matches(/^\d+$/, "Invalid number format. Only numbers are allowed."),
userId: Yup.number().required("User ID is required")
});

try {
await schema.validate(newContact);
await schema.validate({ number: formattedNumber, userId });
} catch (err: any) {
throw new AppError(err.message);
}

const contactAndTicket = await createContact(whatsappId, newContact.number);
const contactAndTicket = await createContact(
whatsappId,
formattedNumber,
userId,
queueId
);

let resp: any;

if (medias) {
await Promise.all(
medias.map(async (media: Express.Multer.File) => {
resp = await SendWhatsAppMedia({ body, media, ticket: contactAndTicket });
resp = await SendWhatsAppMedia({
body,
media,
ticket: contactAndTicket
});
})
);
} else {
resp = await SendWhatsAppMessage({ body, ticket: contactAndTicket, quotedMsg });
resp = await SendWhatsAppMessage({
body,
ticket: contactAndTicket,
quotedMsg
});
}

const listSettingsService = await ListSettingsServiceOne({ key: "closeTicketApi" });
var closeTicketApi = listSettingsService?.value;
const listSettingsService = await ListSettingsServiceOne({
key: "closeTicketApi"
});
const closeTicketApi = listSettingsService?.value;

if (closeTicketApi === 'enabled') {
if (closeTicketApi === "enabled") {
setTimeout(async () => {
await UpdateTicketService({
ticketId: contactAndTicket.id,
ticketData: { status: "closed" }
});
}, 1000);
}

return res.send({ error: resp });
};
};
26 changes: 17 additions & 9 deletions backend/src/services/TicketServices/FindOrCreateTicketService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { subSeconds } from "date-fns";
import { Op } from "sequelize";
import Contact from "../../models/Contact";
import Ticket from "../../models/Ticket";
import ShowTicketService from "./ShowTicketService";
import ListSettingsServiceOne from "../SettingServices/ListSettingsServiceOne";
import ShowTicketService from "./ShowTicketService";

const FindOrCreateTicketService = async (
contact: Contact,
whatsappId: number,
unreadMessages: number,
userId?: number,
queueId?: number,
groupContact?: Contact
): Promise<Ticket> => {
let ticket = await Ticket.findOne({
Expand All @@ -17,7 +19,7 @@ const FindOrCreateTicketService = async (
[Op.or]: ["open", "pending"]
},
contactId: groupContact ? groupContact.id : contact.id,
whatsappId: whatsappId
whatsappId
}
});

Expand All @@ -29,7 +31,7 @@ const FindOrCreateTicketService = async (
ticket = await Ticket.findOne({
where: {
contactId: groupContact.id,
whatsappId: whatsappId
whatsappId
},
order: [["updatedAt", "DESC"]]
});
Expand All @@ -44,17 +46,21 @@ const FindOrCreateTicketService = async (
}

if (!ticket && !groupContact) {
const listSettingsService = await ListSettingsServiceOne({key: "timeCreateNewTicket"});
var timeCreateNewTicket = listSettingsService?.value;

const listSettingsService = await ListSettingsServiceOne({
key: "timeCreateNewTicket"
});
const timeCreateNewTicket = listSettingsService?.value;

ticket = await Ticket.findOne({
where: {
updatedAt: {
[Op.between]: [+subSeconds(new Date(), Number(timeCreateNewTicket)), +new Date()]
[Op.between]: [
+subSeconds(new Date(), Number(timeCreateNewTicket)),
+new Date()
]
},
contactId: contact.id,
whatsappId: whatsappId
whatsappId
},
order: [["updatedAt", "DESC"]]
});
Expand All @@ -73,6 +79,8 @@ const FindOrCreateTicketService = async (
contactId: groupContact ? groupContact.id : contact.id,
status: "pending",
isGroup: !!groupContact,
userId,
queueId,
unreadMessages,
whatsappId
});
Expand All @@ -83,4 +91,4 @@ const FindOrCreateTicketService = async (
return ticket;
};

export default FindOrCreateTicketService;
export default FindOrCreateTicketService;
54 changes: 25 additions & 29 deletions backend/src/services/WbotServices/wbotMessageListener.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
/* eslint-disable no-plusplus */
/* eslint-disable no-nested-ternary */
import * as Sentry from "@sentry/node";
import { writeFile } from "fs";
import { join } from "path";
import { promisify } from "util";
import { writeFile } from "fs";
import * as Sentry from "@sentry/node";

import {
Contact as WbotContact,
Message as WbotMessage,
Client,
MessageAck,
Client
Contact as WbotContact,
Message as WbotMessage
} from "whatsapp-web.js";

import ffmpeg from "fluent-ffmpeg";
import Contact from "../../models/Contact";
import Ticket from "../../models/Ticket";
import Integration from "../../models/Integration";
import Message from "../../models/Message";
import Settings from "../../models/Setting";
import Integration from "../../models/Integration";
import Ticket from "../../models/Ticket";

import { debounce } from "../../helpers/Debounce";
import formatBody from "../../helpers/Mustache";
import { getIO } from "../../libs/socket";
import CreateMessageService from "../MessageServices/CreateMessageService";
import { logger } from "../../utils/logger";
import CreateContactService from "../ContactServices/CreateContactService";
import CreateOrUpdateContactService from "../ContactServices/CreateOrUpdateContactService";
import CreateMessageService from "../MessageServices/CreateMessageService";
import ListSettingsServiceOne from "../SettingServices/ListSettingsServiceOne";
import FindOrCreateTicketService from "../TicketServices/FindOrCreateTicketService";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import { debounce } from "../../helpers/Debounce";
import UpdateTicketService from "../TicketServices/UpdateTicketService";
import CreateContactService from "../ContactServices/CreateContactService";
import formatBody from "../../helpers/Mustache";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";

ffmpeg.setFfmpegPath("/usr/bin/ffmpeg");

Expand Down Expand Up @@ -93,7 +93,6 @@ const verifyRevoked = async (msgBody?: string): Promise<void> => {
}

if (message) {
// console.log(message);
await Message.update(
{ isDeleted: true },
{
Expand Down Expand Up @@ -140,7 +139,6 @@ const verifyMediaMessage = async (
media.filename = `${new Date().getTime()}.${ext}`;
} else {
const originalFilename = media.filename ? `-${media.filename}` : "";
// Always write a random filename
media.filename = `${new Date().getTime()}${originalFilename}`;
}

Expand All @@ -151,8 +149,6 @@ const verifyMediaMessage = async (
"base64"
)
.then(() => {
console.log("Arquivo salvo com sucesso!");

const inputFile = `./public/${media.filename}`;
let outputFile: string;

Expand All @@ -161,14 +157,10 @@ const verifyMediaMessage = async (
} else if (inputFile.endsWith(".ogg")) {
outputFile = inputFile.replace(".ogg", ".mp3");
} else {
// Trate outros formatos de arquivo conforme necessário
console.error("Formato de arquivo não suportado:", inputFile);
console.warn("Formato de arquivo não é .mpeg ou .ogg:", inputFile);
return;
}

console.log("Input File:", inputFile);
console.log("Output File:", outputFile);

return new Promise<void>((resolve, reject) => {
ffmpeg(inputFile)
.toFormat("mp3")
Expand Down Expand Up @@ -215,11 +207,10 @@ const verifyMediaMessage = async (
const prepareLocation = (msg: WbotMessage): WbotMessage => {
const gmapsUrl = `https://maps.google.com/maps?q=${msg.location.latitude}%2C${msg.location.longitude}&z=17`;
msg.body = `data:image/png;base64,${msg.body}|${gmapsUrl}`;
msg.body += `|${
msg.location.options
msg.body += `|${msg.location.options
? msg.location.options
: `${msg.location.latitude}, ${msg.location.longitude}`
}`;
}`;
return msg;
};

Expand Down Expand Up @@ -336,9 +327,8 @@ const verifyQueue = async (
queues.forEach((queue, index) => {
if (queue.startWork && queue.endWork) {
if (isDisplay) {
options += `*${index + 1}* - ${queue.name} das ${
queue.startWork
} as ${queue.endWork}\n`;
options += `*${index + 1}* - ${queue.name} das ${queue.startWork
} as ${queue.endWork}\n`;
} else {
options += `*${index + 1}* - ${queue.name}\n`;
}
Expand Down Expand Up @@ -427,7 +417,7 @@ const handleMessage = async (
msg.type === "e2e_notification" ||
msg.type === "notification_template" ||
msg.from === "status@broadcast" ||
msg.author != null ||
// msg.author !== null ||
chat.isGroup
) {
return;
Expand All @@ -438,6 +428,8 @@ const handleMessage = async (
try {
let msgContact: WbotContact;
let groupContact: Contact | undefined;
const userId = 0;
const queueId = 0;

if (msg.fromMe) {
// messages sent automatically by wbot have a special character in front of it
Expand Down Expand Up @@ -487,6 +479,8 @@ const handleMessage = async (
contact,
wbot.id!,
unreadMessages,
queueId,
userId,
groupContact
);

Expand All @@ -501,6 +495,8 @@ const handleMessage = async (
contact,
wbot.id!,
unreadMessages,
userId,
queueId,
groupContact
);

Expand Down Expand Up @@ -680,4 +676,4 @@ const wbotMessageListener = async (wbot: Session): Promise<void> => {
});
};

export { wbotMessageListener, handleMessage, handleMsgAck };
export { handleMessage, handleMsgAck, wbotMessageListener };

0 comments on commit 3847ac7

Please sign in to comment.