From 862975813f1696c7a591ab8dd9dfd0434da221c7 Mon Sep 17 00:00:00 2001 From: esteban Date: Tue, 28 Jul 2026 21:59:43 -0500 Subject: [PATCH] change to brevo again --- src/pages/api/emailInfo/send.ts | 32 +++- src/pages/api/emailPostulacion/send.ts | 28 +++- src/pages/api/lib/email.ts | 208 ++++++++++++++----------- 3 files changed, 167 insertions(+), 101 deletions(-) diff --git a/src/pages/api/emailInfo/send.ts b/src/pages/api/emailInfo/send.ts index 34ac7ab..858c543 100644 --- a/src/pages/api/emailInfo/send.ts +++ b/src/pages/api/emailInfo/send.ts @@ -1,6 +1,5 @@ import type { APIRoute } from "astro"; import { prisma } from "../lib/prisma"; -import { sendEmail } from "../lib/email"; export const prerender = false; @@ -65,11 +64,32 @@ export const POST: APIRoute = async ({ request }) => { }, }); } - await sendEmail( - { nombre, email, mensaje }, - "daviddevelope24r@outlook.com", - "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_INFO", - ); + const emailApiKey = import.meta.env.EMAIL_API_KEY; + + const emailResponse = await fetch("https://flows2.carpa.com/webhook/email/send", { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-api-key": emailApiKey!, + }, + body: JSON.stringify({ + type: "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_INFO", + data: { + nombre, + email, + mensaje, + senderName : "Centro del Reino de Paz y Justicia", + }, + }), + }); + + if (!emailResponse.ok) { + console.error("Error enviando correo"); + return new Response( + JSON.stringify({ error: "Error en servicio de correo" }), + { status: 500 } + ); + } return new Response(null, { status: 302, diff --git a/src/pages/api/emailPostulacion/send.ts b/src/pages/api/emailPostulacion/send.ts index 62d0a9c..72ec10d 100644 --- a/src/pages/api/emailPostulacion/send.ts +++ b/src/pages/api/emailPostulacion/send.ts @@ -1,6 +1,5 @@ import type { APIRoute } from "astro"; import { appendToSheet, emailExists } from "../lib/googleSheets"; -import { sendEmail } from "../lib/email"; export const prerender = false; export const POST: APIRoute = async ({ request }) => { @@ -52,12 +51,31 @@ export const POST: APIRoute = async ({ request }) => { new Date().toLocaleString() ]; - // πŸ”Ή Enviar correo y guardar en Google Sheets - await Promise.all([ - sendEmail({ nombres, apellidos }, email, "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION"), - appendToSheet(valuesForSheets), + // πŸ”Ή Enviar a tu backend real + const [emailResponse] = await Promise.all([ + fetch("http://155.138.215.11:3050/email/send", { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-api-key": emailApiKey!, + }, + body: JSON.stringify({ + type: "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION", + data: dataSend, + }), + }), + appendToSheet(valuesForSheets) // Guardar en Google Sheets ]); + if (!emailResponse.ok) { + return new Response(null, { + status: 302, + headers: { + Location: "/", + }, + }); + } + // πŸ”Ή RedirecciΓ³n elegante despuΓ©s de enviar return new Response(null, { status: 302, diff --git a/src/pages/api/lib/email.ts b/src/pages/api/lib/email.ts index 285754d..fb98027 100644 --- a/src/pages/api/lib/email.ts +++ b/src/pages/api/lib/email.ts @@ -1,110 +1,138 @@ -import Cloudflare from "cloudflare"; +// import Cloudflare from "cloudflare"; type TypeEmailData = "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_INFO" | "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION"; -const TEMPLATE_URLS: Record = { - CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION: { - subject: "ConfirmaciΓ³n de inscripciΓ³n al voluntariado", - url: "https://pub-910ed90860804520b9202194cf43c0a6.r2.dev/centro_del_reino_paz_y_justicia_postulacion_user.html", - }, - CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_INFO: { - subject: "NotificaciΓ³n de contacto institucional", - url: "https://pub-910ed90860804520b9202194cf43c0a6.r2.dev/centro_del_reino_paz_y_justicia_info.html", - }, -}; +export async function sendEmail(data: object, to: string, type: TypeEmailData) { + const emailApiKey = import.meta.env.EMAIL_API_KEY; -const TEMPLATE_CACHE = new Map(); + const dataFinal = { + ...data, + email: to, + senderName: "Centro del Reino de Paz y Justicia", + }; -async function fetchTemplate(type: TypeEmailData): Promise { - const cached = TEMPLATE_CACHE.get(type); - if (cached) return cached; + const emailResponse = await fetch("https://flows2.carpa.com/webhook/email/send", { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-api-key": emailApiKey!, + }, + body: JSON.stringify({ + type: type, + data: dataFinal, + }), + }); - const { url } = TEMPLATE_URLS[type]; - const res = await fetch(url); - if (!res.ok) { - throw new Error(`Error descargando template ${type}: HTTP ${res.status}`); - } + const responseBody = await emailResponse.text(); - const html = await res.text(); - TEMPLATE_CACHE.set(type, html); - return html; + if (!emailResponse.ok) { + console.error(`Error enviando correo (status ${emailResponse.status}): ${responseBody}`); + throw new Error(`Error en servicio de correo: ${emailResponse.status}`); + } } -function renderTemplate(template: string, data: Record): string { - let html = template; - for (const [key, value] of Object.entries(data)) { - html = html.replaceAll(new RegExp(`\\{\\{${key}\\}\\}`, "g"), value ?? ""); - } - return html; -} +// ═══════════════════════════════════════════════════════════════ +// CΓ“DIGO COMENTADO β€” Cloudflare (Email Workers) +// Descomentar para volver a Cloudflare en lugar de n8n/Brevo +// ═══════════════════════════════════════════════════════════════ -function stripHtml(html: string): string { - return html.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim(); -} +// const TEMPLATE_URLS: Record = { +// CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION: { +// subject: "ConfirmaciΓ³n de inscripciΓ³n al voluntariado", +// url: "https://pub-910ed90860804520b9202194cf43c0a6.r2.dev/centro_del_reino_paz_y_justicia_postulacion_user.html", +// }, +// CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_INFO: { +// subject: "NotificaciΓ³n de contacto institucional", +// url: "https://pub-910ed90860804520b9202194cf43c0a6.r2.dev/centro_del_reino_paz_y_justicia_info.html", +// }, +// }; -export async function sendEmail(data: Record, to: string, type: TypeEmailData) { - const apiToken = import.meta.env.CLOUDFLARE_API_TOKEN; - const accountId = import.meta.env.CLOUDFLARE_ACCOUNT_ID; +// const TEMPLATE_CACHE = new Map(); - const client = new Cloudflare({ apiToken }); - const { subject } = TEMPLATE_URLS[type]; - const rawHtml = await fetchTemplate(type); - const html = renderTemplate(rawHtml, data); - const text = stripHtml(html); +// async function fetchTemplate(type: TypeEmailData): Promise { +// const cached = TEMPLATE_CACHE.get(type); +// if (cached) return cached; - const response = await client.emailSending.send({ - account_id: accountId, - from: "welcome@mail.centrodelreinodepazyjusticia.com", - to, - subject, - html, - text, - }); +// const { url } = TEMPLATE_URLS[type]; +// const res = await fetch(url); +// if (!res.ok) { +// throw new Error(`Error descargando template ${type}: HTTP ${res.status}`); +// } - if (!response.delivered) { - console.error("Cloudflare email not delivered", response); - throw new Error("El correo no fue entregado"); - } -} +// const html = await res.text(); +// TEMPLATE_CACHE.set(type, html); +// return html; +// } -/* -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ ALTERNATIVA: Brevo (API v3) β”‚ -β”‚ Para volver a Brevo: β”‚ -β”‚ 1. Instalar: pnpm add @getbrevo/brevo β”‚ -β”‚ 2. Agregar a .env: BREVO_API_KEY=xxx β”‚ -β”‚ 3. Cambiar "from" a tu dominio verificado en Brevo β”‚ -β”‚ 4. En sendEmail(), comentar el bloque Cloudflare β”‚ -β”‚ y descomentar la llamada a sendEmailViaBrevo() β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +// function renderTemplate(template: string, data: Record): string { +// let html = template; +// for (const [key, value] of Object.entries(data)) { +// html = html.replaceAll(new RegExp(`\\{\\{${key}\\}\\}`, "g"), value ?? ""); +// } +// return html; +// } -import { - TransactionalEmailsApi, - SendSmtpEmail, -} from "@getbrevo/brevo"; +// function stripHtml(html: string): string { +// return html.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim(); +// } -async function sendEmailViaBrevo( - data: Record, - to: string, - type: TypeEmailData -) { - const apiKey = import.meta.env.BREVO_API_KEY; - const { subject } = TEMPLATE_URLS[type]; - const rawHtml = await fetchTemplate(type); - const html = renderTemplate(rawHtml, data); - const text = stripHtml(html); +// export async function sendEmailCf(data: Record, to: string, type: TypeEmailData) { +// const apiToken = import.meta.env.CLOUDFLARE_API_TOKEN; +// const accountId = import.meta.env.CLOUDFLARE_ACCOUNT_ID; - const api = new TransactionalEmailsApi(); - api.setApiKey(0, apiKey); +// const client = new Cloudflare({ apiToken }); +// const { subject } = TEMPLATE_URLS[type]; +// const rawHtml = await fetchTemplate(type); +// const html = renderTemplate(rawHtml, data); +// const text = stripHtml(html); - const email = new SendSmtpEmail(); - email.subject = subject; - email.sender = { name: "Centro del Reino de Paz y Justicia", email: "welcome@mail.centrodelreinodepazyjusticia.com" }; - email.to = [{ email: to }]; - email.htmlContent = html; - email.textContent = text; +// const response = await client.emailSending.send({ +// account_id: accountId, +// from: "welcome@mail.centrodelreinodepazyjusticia.com", +// to, +// subject, +// html, +// text, +// }); - const response = await api.sendTransacEmail(email); - console.log("Brevo email sent:", response.body?.messageId); -} -*/ +// if (!response.delivered) { +// console.error("Cloudflare email not delivered", response); +// throw new Error("El correo no fue entregado"); +// } +// } + +// ═══════════════════════════════════════════════════════════════ +// ALTERNATIVA: Brevo (SDK directo) +// Descomentar y usar sendEmailViaBrevo() en lugar de lo de arriba +// Requiere: pnpm add @getbrevo/brevo + BREVO_API_KEY en .env +// ═══════════════════════════════════════════════════════════════ + +// import { +// TransactionalEmailsApi, +// SendSmtpEmail, +// } from "@getbrevo/brevo"; + +// async function sendEmailViaBrevo( +// data: Record, +// to: string, +// type: TypeEmailData +// ) { +// const apiKey = import.meta.env.BREVO_API_KEY; +// const { subject } = TEMPLATE_URLS[type]; +// const rawHtml = await fetchTemplate(type); +// const html = renderTemplate(rawHtml, data); +// const text = stripHtml(html); + +// const api = new TransactionalEmailsApi(); +// api.setApiKey(0, apiKey); + +// const email = new SendSmtpEmail(); +// email.subject = subject; +// email.sender = { name: "Centro del Reino de Paz y Justicia", email: "welcome@mail.centrodelreinodepazyjusticia.com" }; +// email.to = [{ email: to }]; +// email.htmlContent = html; +// email.textContent = text; + +// const response = await api.sendTransacEmail(email); +// console.log("Brevo email sent:", response.body?.messageId); +// } -- 2.39.5