projeto-hit/backend/src/services/WhatsappService/UpdateWhatsAppService.ts

111 lines
2.4 KiB
TypeScript
Raw Normal View History

import * as Yup from "yup";
import { Op } from "sequelize";
import AppError from "../../errors/AppError";
import Whatsapp from "../../models/Whatsapp";
import ShowWhatsAppService from "./ShowWhatsAppService";
import AssociateWhatsappQueue from "./AssociateWhatsappQueue";
2023-01-01 23:40:00 +00:00
// import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";
import { getWbot } from "../../libs/wbot";
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";
interface WhatsappData {
name?: string;
status?: string;
session?: string;
isDefault?: boolean;
greetingMessage?: string;
farewellMessage?: string;
queueIds?: number[];
}
interface Request {
whatsappData: WhatsappData;
whatsappId: string;
}
interface Response {
whatsapp: Whatsapp;
oldDefaultWhatsapp: Whatsapp | null;
}
const UpdateWhatsAppService = async ({
whatsappData,
whatsappId
}: Request): Promise<Response> => {
const schema = Yup.object().shape({
name: Yup.string().min(2),
status: Yup.string(),
isDefault: Yup.boolean()
});
const {
name,
status,
isDefault,
session,
greetingMessage,
farewellMessage,
queueIds = []
} = whatsappData;
try {
await schema.validate({ name, status, isDefault });
2023-01-01 23:40:00 +00:00
} catch (err: any) {
throw new AppError(err.message);
}
if (queueIds.length > 1 && !greetingMessage) {
throw new AppError("ERR_WAPP_GREETING_REQUIRED");
}
let oldDefaultWhatsapp: Whatsapp | null = null;
if (isDefault) {
oldDefaultWhatsapp = await Whatsapp.findOne({
where: { isDefault: true, id: { [Op.not]: whatsappId } }
});
if (oldDefaultWhatsapp) {
await oldDefaultWhatsapp.update({ isDefault: false });
}
}
const whatsapp = await ShowWhatsAppService(whatsappId);
// console.log('############## whatsapp: ', JSON.parse(JSON.stringify(whatsapp)))
if(name && !name.includes(whatsapp.number) && whatsapp.status === 'CONNECTED'){
throw new AppError("ERR_WAPP_WRONG_SESSION_NAME");
}
await whatsapp.update({
name,
status,
session,
greetingMessage,
farewellMessage,
isDefault
});
2023-01-01 23:40:00 +00:00
// await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, {
// name,
// status,
// session,
// greetingMessage,
// farewellMessage,
// isDefault
// })
2022-11-17 14:40:37 +00:00
await AssociateWhatsappQueue(whatsapp, queueIds);
return { whatsapp, oldDefaultWhatsapp };
};
export default UpdateWhatsAppService;