Compare commits

..

No commits in common. "f5cb6f794df5fba64a6a5571eaee4a056e7eda39" and "5757d20b3b5cfeb13660e860019f0792d46d8f97" have entirely different histories.

3 changed files with 101 additions and 167 deletions

View File

@ -1,5 +1,6 @@
import type { APIRoute } from "astro"; import type { APIRoute } from "astro";
import { prisma } from "../lib/prisma"; import { prisma } from "../lib/prisma";
import { sendEmail } from "../lib/email";
export const prerender = false; export const prerender = false;
@ -64,32 +65,11 @@ export const POST: APIRoute = async ({ request }) => {
}, },
}); });
} }
const emailApiKey = import.meta.env.EMAIL_API_KEY; await sendEmail(
{ nombre, email, mensaje },
const emailResponse = await fetch("https://flows2.carpa.com/webhook/email/send", { "daviddevelope24r@outlook.com",
method: "POST", "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_INFO",
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, { return new Response(null, {
status: 302, status: 302,

View File

@ -1,5 +1,6 @@
import type { APIRoute } from "astro"; import type { APIRoute } from "astro";
import { appendToSheet, emailExists } from "../lib/googleSheets"; import { appendToSheet, emailExists } from "../lib/googleSheets";
import { sendEmail } from "../lib/email";
export const prerender = false; export const prerender = false;
export const POST: APIRoute = async ({ request }) => { export const POST: APIRoute = async ({ request }) => {
@ -51,31 +52,12 @@ export const POST: APIRoute = async ({ request }) => {
new Date().toLocaleString() new Date().toLocaleString()
]; ];
// 🔹 Enviar a tu backend real // 🔹 Enviar correo y guardar en Google Sheets
const [emailResponse] = await Promise.all([ await Promise.all([
fetch("http://155.138.215.11:3050/email/send", { sendEmail({ nombres, apellidos }, email, "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION"),
method: "POST", appendToSheet(valuesForSheets),
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 // 🔹 Redirección elegante después de enviar
return new Response(null, { return new Response(null, {
status: 302, status: 302,

View File

@ -1,138 +1,110 @@
// import Cloudflare from "cloudflare"; import Cloudflare from "cloudflare";
type TypeEmailData = "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_INFO" | "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION"; type TypeEmailData = "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_INFO" | "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION";
export async function sendEmail(data: object, to: string, type: TypeEmailData) { const TEMPLATE_URLS: Record<TypeEmailData, { subject: string; url: string }> = {
const emailApiKey = import.meta.env.EMAIL_API_KEY; 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",
},
};
const dataFinal = { const TEMPLATE_CACHE = new Map<string, string>();
...data,
email: to,
senderName: "Centro del Reino de Paz y Justicia",
};
const emailResponse = await fetch("https://flows2.carpa.com/webhook/email/send", { async function fetchTemplate(type: TypeEmailData): Promise<string> {
method: "POST", const cached = TEMPLATE_CACHE.get(type);
headers: { if (cached) return cached;
"Content-Type": "application/json",
"x-api-key": emailApiKey!,
},
body: JSON.stringify({
type: type,
data: dataFinal,
}),
});
const responseBody = await emailResponse.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 (!emailResponse.ok) { const html = await res.text();
console.error(`Error enviando correo (status ${emailResponse.status}): ${responseBody}`); TEMPLATE_CACHE.set(type, html);
throw new Error(`Error en servicio de correo: ${emailResponse.status}`); return html;
}
} }
// ═══════════════════════════════════════════════════════════════ function renderTemplate(template: string, data: Record<string, string>): string {
// CÓDIGO COMENTADO — Cloudflare (Email Workers) let html = template;
// Descomentar para volver a Cloudflare en lugar de n8n/Brevo for (const [key, value] of Object.entries(data)) {
// ═══════════════════════════════════════════════════════════════ html = html.replaceAll(new RegExp(`\\{\\{${key}\\}\\}`, "g"), value ?? "");
}
return html;
}
// const TEMPLATE_URLS: Record<TypeEmailData, { subject: string; url: string }> = { function stripHtml(html: string): string {
// CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION: { return html.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim();
// 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",
// },
// };
// const TEMPLATE_CACHE = new Map<string, string>(); export async function sendEmail(data: Record<string, string>, to: string, type: TypeEmailData) {
const apiToken = import.meta.env.CLOUDFLARE_API_TOKEN;
const accountId = import.meta.env.CLOUDFLARE_ACCOUNT_ID;
// async function fetchTemplate(type: TypeEmailData): Promise<string> { const client = new Cloudflare({ apiToken });
// const cached = TEMPLATE_CACHE.get(type); const { subject } = TEMPLATE_URLS[type];
// if (cached) return cached; const rawHtml = await fetchTemplate(type);
const html = renderTemplate(rawHtml, data);
const text = stripHtml(html);
// const { url } = TEMPLATE_URLS[type]; const response = await client.emailSending.send({
// const res = await fetch(url); account_id: accountId,
// if (!res.ok) { from: "welcome@mail.centrodelreinodepazyjusticia.com",
// throw new Error(`Error descargando template ${type}: HTTP ${res.status}`); to,
// } subject,
html,
text,
});
// const html = await res.text(); if (!response.delivered) {
// TEMPLATE_CACHE.set(type, html); console.error("Cloudflare email not delivered", response);
// return html; throw new Error("El correo no fue entregado");
// } }
}
// function renderTemplate(template: string, data: Record<string, string>): string { /*
// let html = template;
// for (const [key, value] of Object.entries(data)) { ALTERNATIVA: Brevo (API v3)
// html = html.replaceAll(new RegExp(`\\{\\{${key}\\}\\}`, "g"), value ?? ""); Para volver a Brevo:
// } 1. Instalar: pnpm add @getbrevo/brevo
// return html; 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 stripHtml(html: string): string { import {
// return html.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim(); TransactionalEmailsApi,
// } SendSmtpEmail,
} from "@getbrevo/brevo";
// export async function sendEmailCf(data: Record<string, string>, to: string, type: TypeEmailData) { async function sendEmailViaBrevo(
// const apiToken = import.meta.env.CLOUDFLARE_API_TOKEN; data: Record<string, string>,
// const accountId = import.meta.env.CLOUDFLARE_ACCOUNT_ID; 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 client = new Cloudflare({ apiToken }); const api = new TransactionalEmailsApi();
// const { subject } = TEMPLATE_URLS[type]; api.setApiKey(0, apiKey);
// const rawHtml = await fetchTemplate(type);
// const html = renderTemplate(rawHtml, data);
// const text = stripHtml(html);
// const response = await client.emailSending.send({ const email = new SendSmtpEmail();
// account_id: accountId, email.subject = subject;
// from: "welcome@mail.centrodelreinodepazyjusticia.com", email.sender = { name: "Centro del Reino de Paz y Justicia", email: "welcome@mail.centrodelreinodepazyjusticia.com" };
// to, email.to = [{ email: to }];
// subject, email.htmlContent = html;
// html, email.textContent = text;
// text,
// });
// if (!response.delivered) { const response = await api.sendTransacEmail(email);
// console.error("Cloudflare email not delivered", response); console.log("Brevo email sent:", response.body?.messageId);
// 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<string, string>,
// 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);
// }