2022-01-06 01:26:15 +00:00
|
|
|
import * as Yup from "yup";
|
|
|
|
|
|
|
|
import AppError from "../../errors/AppError";
|
|
|
|
import Whatsapp from "../../models/Whatsapp";
|
|
|
|
import AssociateWhatsappQueue from "./AssociateWhatsappQueue";
|
|
|
|
|
|
|
|
interface Request {
|
|
|
|
name: string;
|
|
|
|
queueIds?: number[];
|
|
|
|
greetingMessage?: string;
|
|
|
|
farewellMessage?: string;
|
|
|
|
status?: string;
|
|
|
|
isDefault?: boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface Response {
|
|
|
|
whatsapp: Whatsapp;
|
|
|
|
oldDefaultWhatsapp: Whatsapp | null;
|
|
|
|
}
|
|
|
|
|
|
|
|
const CreateWhatsAppService = async ({
|
|
|
|
name,
|
|
|
|
status = "OPENING",
|
|
|
|
queueIds = [],
|
|
|
|
greetingMessage,
|
|
|
|
farewellMessage,
|
|
|
|
isDefault = false
|
|
|
|
}: Request): Promise<Response> => {
|
|
|
|
const schema = Yup.object().shape({
|
|
|
|
name: Yup.string()
|
|
|
|
.required()
|
|
|
|
.min(2)
|
|
|
|
.test(
|
|
|
|
"Check-name",
|
|
|
|
"This whatsapp name is already used.",
|
|
|
|
async value => {
|
|
|
|
if (!value) return false;
|
|
|
|
const nameExists = await Whatsapp.findOne({
|
|
|
|
where: { name: value }
|
|
|
|
});
|
|
|
|
return !nameExists;
|
|
|
|
}
|
|
|
|
),
|
|
|
|
isDefault: Yup.boolean().required()
|
|
|
|
});
|
|
|
|
|
|
|
|
try {
|
|
|
|
await schema.validate({ name, status, isDefault });
|
2023-02-10 12:39:50 +00:00
|
|
|
} catch (err: any) {
|
2022-01-06 01:26:15 +00:00
|
|
|
throw new AppError(err.message);
|
|
|
|
}
|
|
|
|
|
|
|
|
const whatsappFound = await Whatsapp.findOne();
|
|
|
|
|
|
|
|
isDefault = !whatsappFound;
|
|
|
|
|
|
|
|
let oldDefaultWhatsapp: Whatsapp | null = null;
|
|
|
|
|
|
|
|
if (isDefault) {
|
|
|
|
oldDefaultWhatsapp = await Whatsapp.findOne({
|
|
|
|
where: { isDefault: true }
|
|
|
|
});
|
|
|
|
if (oldDefaultWhatsapp) {
|
|
|
|
await oldDefaultWhatsapp.update({ isDefault: false });
|
2022-11-17 14:40:37 +00:00
|
|
|
|
2022-01-06 01:26:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (queueIds.length > 1 && !greetingMessage) {
|
|
|
|
throw new AppError("ERR_WAPP_GREETING_REQUIRED");
|
|
|
|
}
|
|
|
|
|
|
|
|
const whatsapp = await Whatsapp.create(
|
|
|
|
{
|
|
|
|
name,
|
|
|
|
status,
|
|
|
|
greetingMessage,
|
|
|
|
farewellMessage,
|
|
|
|
isDefault
|
|
|
|
},
|
|
|
|
{ include: ["queues"] }
|
|
|
|
);
|
|
|
|
|
|
|
|
await AssociateWhatsappQueue(whatsapp, queueIds);
|
|
|
|
|
|
|
|
return { whatsapp, oldDefaultWhatsapp };
|
|
|
|
};
|
|
|
|
|
|
|
|
export default CreateWhatsAppService;
|