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"; // 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 => { 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 }); } 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 }); // await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { // name, // status, // session, // greetingMessage, // farewellMessage, // isDefault // }) await AssociateWhatsappQueue(whatsapp, queueIds); return { whatsapp, oldDefaultWhatsapp }; }; export default UpdateWhatsAppService;