111 lines
2.7 KiB
TypeScript
111 lines
2.7 KiB
TypeScript
import { db } from "@/lib/db";
|
|
import { sendMail } from "@/lib/mail";
|
|
|
|
async function registrarEmail(params: {
|
|
briefingId: string;
|
|
destino: string;
|
|
assunto: string;
|
|
texto: string;
|
|
}) {
|
|
const registro = await db.envioNotificacao.create({
|
|
data: {
|
|
briefingId: params.briefingId,
|
|
canal: "EMAIL",
|
|
destino: params.destino,
|
|
assunto: params.assunto,
|
|
status: "PENDENTE"
|
|
}
|
|
});
|
|
|
|
try {
|
|
await sendMail({
|
|
to: params.destino,
|
|
subject: params.assunto,
|
|
text: params.texto
|
|
});
|
|
|
|
await db.envioNotificacao.update({
|
|
where: { id: registro.id },
|
|
data: {
|
|
status: "ENVIADO",
|
|
tentativas: { increment: 1 },
|
|
enviadoEm: new Date()
|
|
}
|
|
});
|
|
} catch (error) {
|
|
await db.envioNotificacao.update({
|
|
where: { id: registro.id },
|
|
data: {
|
|
status: "ERRO",
|
|
tentativas: { increment: 1 },
|
|
erro: error instanceof Error ? error.message : "Erro desconhecido"
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function notificarBriefingEnviado(briefingId: string) {
|
|
const briefing = await db.briefing.findUnique({
|
|
where: { id: briefingId },
|
|
include: {
|
|
cliente: {
|
|
include: { user: true }
|
|
}
|
|
}
|
|
});
|
|
|
|
if (!briefing) {
|
|
return;
|
|
}
|
|
|
|
const appUrl = process.env.APP_URL ?? "http://localhost:3000";
|
|
const pdfUrl = `${appUrl}/api/briefings/${briefing.id}/pdf`;
|
|
const adminEmail = process.env.ADMIN_EMAIL;
|
|
|
|
await registrarEmail({
|
|
briefingId,
|
|
destino: briefing.cliente.user.email,
|
|
assunto: "Briefing enviado - SeConectai",
|
|
texto: [
|
|
`O briefing "${briefing.titulo}" foi enviado com sucesso.`,
|
|
"",
|
|
`Voce pode baixar o PDF em: ${pdfUrl}`,
|
|
"",
|
|
"Este e-mail nao inclui CPF completo nem senhas."
|
|
].join("\n")
|
|
});
|
|
|
|
if (adminEmail) {
|
|
await registrarEmail({
|
|
briefingId,
|
|
destino: adminEmail,
|
|
assunto: "Novo briefing enviado",
|
|
texto: [
|
|
`Um novo briefing foi enviado por ${briefing.cliente.nomeCompleto}.`,
|
|
`Titulo: ${briefing.titulo}`,
|
|
`Painel: ${appUrl}/admin/briefings/${briefing.id}`,
|
|
"",
|
|
"Este e-mail nao inclui CPF completo nem senhas."
|
|
].join("\n")
|
|
});
|
|
}
|
|
|
|
if (
|
|
process.env.EVOLUTION_API_URL &&
|
|
process.env.EVOLUTION_API_KEY &&
|
|
process.env.EVOLUTION_API_INSTANCE &&
|
|
process.env.ADMIN_WHATSAPP
|
|
) {
|
|
await db.envioNotificacao.create({
|
|
data: {
|
|
briefingId,
|
|
canal: "WHATSAPP",
|
|
destino: process.env.ADMIN_WHATSAPP,
|
|
assunto: "Novo briefing enviado",
|
|
status: "PENDENTE",
|
|
erro: "Pendente de consulta da versao/formato de payload da Evolution API antes do envio."
|
|
}
|
|
});
|
|
}
|
|
}
|