feat: ura bot by connected whatsapp number

gertec
adriano 2024-05-31 12:00:06 -03:00
parent 0866cbce79
commit 1d78de9dc9
2 changed files with 243 additions and 161 deletions

View File

@ -9,7 +9,8 @@ import AppError from "../../errors/AppError";
import { userInfo } from "os"; import { userInfo } from "os";
import ShowQueueService from "../QueueService/ShowQueueService"; import ShowQueueService from "../QueueService/ShowQueueService";
import UpdateTicketService from "./UpdateTicketService"; import UpdateTicketService from "./UpdateTicketService";
import { getSettingValue } from "../../helpers/WhaticketSettings";
import ListWhatsAppsNumber from "../WhatsappService/ListWhatsAppsNumber";
const FindOrCreateTicketServiceBot = async ( const FindOrCreateTicketServiceBot = async (
contact: Contact, contact: Contact,
@ -17,10 +18,32 @@ const FindOrCreateTicketServiceBot = async (
unreadMessages: number, unreadMessages: number,
groupContact?: Contact groupContact?: Contact
): Promise<any> => { ): Promise<any> => {
try { try {
// let ticket = await Ticket.findOne({
// where: {
// status: {
// [Op.or]: ["open", "pending", "queueChoice"]
// },
// contactId: groupContact ? groupContact.id : contact.id
// }
// });
let ticket = await Ticket.findOne({ let ticket;
if (getSettingValue("oneContactChatWithManyWhats")?.value == "enabled") {
let whats = await ListWhatsAppsNumber(whatsappId);
ticket = await Ticket.findOne({
where: {
status: {
[Op.or]: ["open", "pending", "queueChoice"]
},
contactId: groupContact ? groupContact.id : contact.id,
whatsappId: { [Op.in]: whats.whatsapps.map((w: any) => w.id) }
}
});
} else {
ticket = await Ticket.findOne({
where: { where: {
status: { status: {
[Op.or]: ["open", "pending", "queueChoice"] [Op.or]: ["open", "pending", "queueChoice"]
@ -28,17 +51,15 @@ const FindOrCreateTicketServiceBot = async (
contactId: groupContact ? groupContact.id : contact.id contactId: groupContact ? groupContact.id : contact.id
} }
}); });
}
const { queues, greetingMessage, phoneNumberId } = const { queues, greetingMessage, phoneNumberId } =
await ShowWhatsAppService(whatsappId); await ShowWhatsAppService(whatsappId);
//Habilitar esse caso queira usar o bot //Habilitar esse caso queira usar o bot
const botInfo = await BotIsOnQueue('botqueue') const botInfo = await BotIsOnQueue("botqueue");
// const botInfo = { isOnQueue: false } // const botInfo = { isOnQueue: false }
if (ticket) { if (ticket) {
await ticket.update({ unreadMessages }); await ticket.update({ unreadMessages });
} }
@ -51,8 +72,6 @@ const FindOrCreateTicketServiceBot = async (
// order: [["updatedAt", "DESC"]] // order: [["updatedAt", "DESC"]]
// }); // });
// if (ticket) { // if (ticket) {
// await ticket.update({ // await ticket.update({
@ -64,42 +83,39 @@ const FindOrCreateTicketServiceBot = async (
// } // }
if (!ticket && !groupContact) { if (!ticket && !groupContact) {
console.log("BOT CREATING OR REOPENING THE TICKET");
console.log('BOT CREATING OR REOPENING THE TICKET')
ticket = await Ticket.findOne({ ticket = await Ticket.findOne({
where: { where: {
contactId: contact.id, contactId: contact.id,
userId: botInfo.userIdBot userId: botInfo.userIdBot,
whatsappId: whatsappId
}, },
order: [["updatedAt", "DESC"]] order: [["updatedAt", "DESC"]]
}); });
if (ticket) { if (ticket) {
await ticket.update({ await ticket.update({
status: "open", status: "open",
userId: botInfo.userIdBot, userId: botInfo.userIdBot,
unreadMessages unreadMessages
}); });
console.log('lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') console.log("lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
await dialogFlowStartContext(contact, ticket, botInfo); await dialogFlowStartContext(contact, ticket, botInfo);
} }
} }
let created = false let created = false;
if (!ticket) { if (!ticket) {
created = true;
created = true let status = "open";
let status = "open"
if (queues.length > 1 && !botInfo.isOnQueue) { if (queues.length > 1 && !botInfo.isOnQueue) {
status = "queueChoice" status = "queueChoice";
} }
ticket = await Ticket.create({ ticket = await Ticket.create({
@ -112,27 +128,31 @@ const FindOrCreateTicketServiceBot = async (
phoneNumberId phoneNumberId
}); });
console.log('yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy') console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy");
await dialogFlowStartContext(contact, ticket, botInfo); await dialogFlowStartContext(contact, ticket, botInfo);
} }
ticket = await ShowTicketService(ticket.id); ticket = await ShowTicketService(ticket.id);
return { ticket, created }; return { ticket, created };
} catch (error: any) { } catch (error: any) {
console.error('===> Error on FindOrCreateTicketServiceBot.ts file: \n', error) console.error(
"===> Error on FindOrCreateTicketServiceBot.ts file: \n",
error
);
throw new AppError(error.message); throw new AppError(error.message);
} }
}; };
export default FindOrCreateTicketServiceBot; export default FindOrCreateTicketServiceBot;
async function dialogFlowStartContext(contact: Contact, ticket: Ticket, botInfo: any) { async function dialogFlowStartContext(
contact: Contact,
let msg: any = { type: 'chat', from: `${contact.number}@c.us`, body: '0' }; ticket: Ticket,
botInfo: any
) {
let msg: any = { type: "chat", from: `${contact.number}@c.us`, body: "0" };
let queue = await ShowQueueService(botInfo.botQueueId); let queue = await ShowQueueService(botInfo.botQueueId);
@ -144,6 +164,4 @@ async function dialogFlowStartContext(contact: Contact, ticket: Ticket, botInfo:
ticket = await ShowTicketService(ticket.id); ticket = await ShowTicketService(ticket.id);
// await sendDialogflowAnswer(ticket.whatsappId, ticket, msg, contact, false); // await sendDialogflowAnswer(ticket.whatsappId, ticket, msg, contact, false);
} }

View File

@ -184,7 +184,11 @@ const verifyMediaMessage = async (
phoneNumberId: msg?.phoneNumberId, phoneNumberId: msg?.phoneNumberId,
fromAgent: false fromAgent: false
}; };
if(messageData.mediaType === 'video' || messageData.mediaType === 'audio' && getSettingValue('blockAudioVideoMedia')?.value === 'enabled'){ if (
messageData.mediaType === "video" ||
(messageData.mediaType === "audio" &&
getSettingValue("blockAudioVideoMedia")?.value === "enabled")
) {
mediaAuthorized = false; mediaAuthorized = false;
} }
if (msg?.fromMe) { if (msg?.fromMe) {
@ -204,7 +208,16 @@ const verifyMediaMessage = async (
if (mediaAuthorized) { if (mediaAuthorized) {
try { try {
await writeFileAsync( await writeFileAsync(
join(__dirname, "..", "..", "..", "..", "..", "public", media.filename), join(
__dirname,
"..",
"..",
"..",
"..",
"..",
"public",
media.filename
),
media.data, media.data,
"base64" "base64"
); );
@ -226,10 +239,14 @@ const verifyMediaMessage = async (
); );
} }
messageData.body = `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`; messageData.body = `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`;
messageData.mediaUrl = ''; messageData.mediaUrl = "";
await ticket.update({ lastMessage: `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`}); await ticket.update({
lastMessage: `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`
});
const newMessage = await CreateMessageService({ messageData }); const newMessage = await CreateMessageService({ messageData });
console.log(`--------->>> Mensagem do tipo: ${messageData.mediaType}, ignorada!`) console.log(
`--------->>> Mensagem do tipo: ${messageData.mediaType}, ignorada!`
);
} }
}; };
@ -318,12 +335,15 @@ const verifyMessage = async (
quotedMsgId: quotedMsg, quotedMsgId: quotedMsg,
phoneNumberId: msg?.phoneNumberId phoneNumberId: msg?.phoneNumberId
}; };
if (msg?.fromMe) { if (msg?.fromMe) {
const botInfo = await BotIsOnQueue("botqueue"); const botInfo = await BotIsOnQueue("botqueue");
if (botInfo.isOnQueue) { if (botInfo.isOnQueue) {
const ura: any = await get({ key: "ura" }); let whatsapp = await whatsappCache(ticket.whatsappId);
const ura: any = await get({
key: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
});
if (ura && !ura.includes(JSON.stringify(msg?.body))) { if (ura && !ura.includes(JSON.stringify(msg?.body))) {
messageData = { ...messageData, fromAgent: true }; messageData = { ...messageData, fromAgent: true };
@ -399,12 +419,17 @@ const verifyQueue = async (
ticketId: ticket.id ticketId: ticket.id
}); });
const data = await get({ key: "ura", parse: true }); const whatsapp = await whatsappCache(ticket.whatsappId);
const data = await get({
key: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
parse: true
});
await createObject({ await createObject({
whatsappId: `${ticket.whatsappId}`, whatsappId: `${ticket.whatsappId}`,
contactId: `${ticket.contactId}`, contactId: `${ticket.contactId}`,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: data[1].id, value: data[1].id,
history: `|${data[1].id}` history: `|${data[1].id}`
}); });
@ -435,7 +460,7 @@ const verifyQueue = async (
body = `\u200e${choosenQueue.greetingMessage}`; body = `\u200e${choosenQueue.greetingMessage}`;
} }
io.emit('notifyPeding', {data: {ticket, queue: choosenQueue}}); io.emit("notifyPeding", { data: { ticket, queue: choosenQueue } });
sendWhatsAppMessageSocket(ticket, body); sendWhatsAppMessageSocket(ticket, body);
} else { } else {
@ -1004,8 +1029,17 @@ const handleMessage = async (
}; };
const menu = async (userTyped: string, whatsappId: any, contactId: any) => { const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
let lastId = await findObject(whatsappId, contactId, "ura"); let whatsapp = await whatsappCache(whatsappId);
const data: any = await get({ key: "ura", parse: true });
let lastId = await findObject(
whatsappId,
contactId,
whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
);
const data: any = await get({
key: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
parse: true
});
console.log("lastId[0]: ", lastId[0]); console.log("lastId[0]: ", lastId[0]);
@ -1013,13 +1047,17 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: data[1].id, value: data[1].id,
history: `|${data[1].id}` history: `|${data[1].id}`
}); });
} }
lastId = await findObject(whatsappId, contactId, "ura"); lastId = await findObject(
whatsappId,
contactId,
whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
);
console.log("LAST ID: ", lastId); console.log("LAST ID: ", lastId);
let option: any; let option: any;
@ -1043,7 +1081,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
let uraOptionSelected = await findObject( let uraOptionSelected = await findObject(
whatsappId, whatsappId,
contactId, contactId,
"ura" whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
); );
uraOptionSelected = uraOptionSelected[4].split("|"); uraOptionSelected = uraOptionSelected[4].split("|");
@ -1052,7 +1090,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: data[1].id, value: data[1].id,
history: `|${data[1].id}` history: `|${data[1].id}`
}); });
@ -1068,7 +1106,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: id, value: id,
history history
}); });
@ -1091,7 +1129,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: response.id, value: response.id,
history history
}); });
@ -1101,7 +1139,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: data[1].id, value: data[1].id,
history: `|${data[1].id}` history: `|${data[1].id}`
}); });
@ -1121,7 +1159,11 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
} }
async function mainOptionsMenu(userTyped: any) { async function mainOptionsMenu(userTyped: any) {
let currentMenu = await findObject(whatsappId, contactId, "ura"); let currentMenu = await findObject(
whatsappId,
contactId,
whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
);
const menuValues = data const menuValues = data
.filter((m: any) => m.idmaster == currentMenu[3]) .filter((m: any) => m.idmaster == currentMenu[3])
@ -1141,7 +1183,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: response.id, value: response.id,
history history
}); });
@ -1328,7 +1370,13 @@ async function vcard(msg: any) {
} }
async function backUra(whatsappId: any, contactId: any, data: any) { async function backUra(whatsappId: any, contactId: any, data: any) {
let uraOptionSelected = await findObject(whatsappId, contactId, "ura"); let whatsapp = await whatsappCache(whatsappId);
let uraOptionSelected = await findObject(
whatsappId,
contactId,
whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
);
uraOptionSelected = uraOptionSelected[4].split("|").filter(Boolean); uraOptionSelected = uraOptionSelected[4].split("|").filter(Boolean);
@ -1349,7 +1397,7 @@ async function backUra(whatsappId: any, contactId: any, data: any) {
await createObject({ await createObject({
whatsappId, whatsappId,
contactId, contactId,
identifier: "ura", identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura",
value: id, value: id,
history history
}); });
@ -1365,7 +1413,13 @@ async function historyUra(
id: any, id: any,
remove?: boolean remove?: boolean
) { ) {
let uraOptionSelected = await findObject(whatsappId, contactId, "ura"); let whatsapp = await whatsappCache(whatsappId);
let uraOptionSelected = await findObject(
whatsappId,
contactId,
whatsapp?.number ? `ura_${whatsapp?.number}` : "ura"
);
let history = ""; let history = "";
console.log("SELECED OPTION uraOptionSelected: ", uraOptionSelected); console.log("SELECED OPTION uraOptionSelected: ", uraOptionSelected);
@ -1387,3 +1441,13 @@ async function historyUra(
async function whatsappInfo(whatsappId: string | number) { async function whatsappInfo(whatsappId: string | number) {
return await Whatsapp.findByPk(whatsappId); return await Whatsapp.findByPk(whatsappId);
} }
async function whatsappCache(whatsappId: any) {
let whatsapp = await get({ key: "whatsapp:*", parse: true });
let uraByNumber = await get({ key: "ura_*", parse: true });
// console.log("------------------------> uraByNumber: ", uraByNumber);
whatsapp = whatsapp.filter((w: any) => +w?.id == +whatsappId);
if (whatsapp && whatsapp.length > 0 && uraByNumber) return whatsapp[0];
}