projeto-hit/backend/src/helpers/GetDefaultWhatsApp.ts

73 lines
1.7 KiB
TypeScript
Raw Normal View History

import AppError from "../errors/AppError";
import Whatsapp from "../models/Whatsapp";
2023-09-08 19:50:51 +00:00
import WhatsappQueue from "../models/WhatsappQueue";
import UserQueue from "../models/UserQueue";
import { Op, where } from "sequelize";
import wbotByUserQueue from "../helpers/GetWbotByUserQueue";
import { WhatsIndex } from "./LoadBalanceWhatsSameQueue";
2023-09-08 19:50:51 +00:00
interface Request {
userId?: string | number;
queueId?: string | number;
}
2023-09-08 19:50:51 +00:00
//const GetDefaultWhatsApp = async (userId?: string | number): Promise<Whatsapp> => {
const GetDefaultWhatsApp = async ({
userId,
queueId
}: Request): Promise<any> => {
// test del
let defaultWhatsapp = await Whatsapp.findOne({
where: { isDefault: true }
});
if (!defaultWhatsapp) {
if (userId) {
let whatsapps = await wbotByUserQueue({ userId, queueId });
2023-09-08 19:50:51 +00:00
if (userId && queueId) {
if (whatsapps.length > 1) {
let whatsAppOfficial: any = whatsapps.find(
(w: any) => w.phoneNumberId && w.phoneNumberId.trim().length > 0
2023-09-08 19:50:51 +00:00
);
2023-09-08 19:50:51 +00:00
if (whatsAppOfficial) {
return whatsapps;
}
}
2023-09-08 19:50:51 +00:00
}
2023-09-08 19:50:51 +00:00
if (whatsapps.length > 0) {
if (whatsapps.length > 1) {
defaultWhatsapp = whatsapps[+WhatsIndex(whatsapps)];
} else {
defaultWhatsapp = whatsapps[0];
}
} // Quando o usuário não está em nenhuma fila
else {
2023-09-08 19:50:51 +00:00
defaultWhatsapp = await Whatsapp.findOne({
where: { status: "CONNECTED" }
});
}
2023-09-08 19:50:51 +00:00
} else {
defaultWhatsapp = await Whatsapp.findOne({
where: { status: "CONNECTED" }
});
}
}
if (!defaultWhatsapp) {
throw new AppError("ERR_NO_DEF_WAPP_FOUND");
}
return defaultWhatsapp;
//
};
export default GetDefaultWhatsApp;