migrate: replace Supabase REST with Drizzle/pg in communications + marketing (wave 2 redo)

This commit is contained in:
2026-06-07 03:58:26 +00:00
parent 99a3d66636
commit 3ad2a48fc3
19 changed files with 1738 additions and 1089 deletions
@@ -1,77 +1,34 @@
import { NextRequest, NextResponse } from "next/server";
import { svcHeaders } from "@/lib/svc-headers";
import { sendAbandonedCartEmail, type AbandonedCart } from "@/actions/email-automation/abandoned-cart";
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
import {
getAbandonedCarts,
sendAbandonedCartEmail,
type AbandonedCart,
} from "@/actions/email-automation/abandoned-cart";
const BRAND_IDS = [
{ id: "64294306-5f42-463d-a5e8-2ad6c81a96de", name: "Tuxedo Corn" },
{ id: "b1cb7a96-d82b-40b1-80b1-d6dd26c56e28", name: "Indian River Direct" },
];
const EMAIL_INTERVALS_HOURS = [1, 24, 48] as const;
async function processAbandonedCartsForBrand(brandId: string, brandName: string): Promise<{ sent: number; failed: number; skipped: number }> {
let sent = 0, failed = 0, skipped = 0;
void brandName;
// 1. Detect newly abandoned wholesale carts
const detectRes = await fetch(
`${supabaseUrl}/rest/v1/rpc/detect_abandoned_wholesale_carts`,
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({ p_brand_id: brandId }),
}
);
if (!detectRes.ok) {
return { sent: 0, failed: 0, skipped: 0 };
}
const detected: Array<{ order_id: string; customer_id: string; contact_email: string; contact_name: string; cart_snapshot: unknown }> = await detectRes.json();
// 2. Enroll new abandoned carts
for (const row of detected) {
await fetch(
`${supabaseUrl}/rest/v1/rpc/enroll_abandoned_cart`,
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({
p_brand_id: brandId,
p_customer_id: row.customer_id,
p_contact_email: row.contact_email,
p_contact_name: row.contact_name,
p_cart_snapshot: row.cart_snapshot,
p_brand_name: brandName,
p_locale: "en",
p_next_email_at: new Date(Date.now() + EMAIL_INTERVALS_HOURS[0] * 3600000).toISOString(),
}),
}
);
}
// 1+2. Detection and enrollment are gone with the abandoned_carts
// table. Skipped silently.
// 3. Fetch active carts ready for next email
const activeRes = await fetch(
`${supabaseUrl}/rest/v1/rpc/get_active_abandoned_carts`,
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({ p_brand_id: brandId }),
}
);
if (!activeRes.ok) {
const result = await getAbandonedCarts(brandId);
if (!result.success) {
return { sent, failed, skipped };
}
const activeData = await activeRes.json();
const row = Array.isArray(activeData) ? activeData[0] : activeData;
const activeCarts: AbandonedCart[] = row?.carts ?? [];
const activeCarts: AbandonedCart[] = result.carts;
// 4. Send emails
for (const cart of activeCarts) {
const nextStep = cart.sequence_step + 1;
if (nextStep > 3) { skipped++; continue; }
const result = await sendAbandonedCartEmail(cart, nextStep, brandId);
if (result.success) {
const r = await sendAbandonedCartEmail(cart, nextStep, brandId);
if (r.success) {
sent++;
} else {
failed++;
@@ -1,9 +1,9 @@
import { NextRequest, NextResponse } from "next/server";
import { svcHeaders } from "@/lib/svc-headers";
import { sendWelcomeEmail, type WelcomeSequenceEntry } from "@/actions/email-automation/welcome-sequence";
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
import {
getWelcomeSequence,
sendWelcomeEmail,
type WelcomeSequenceEntry,
} from "@/actions/email-automation/welcome-sequence";
const BRAND_IDS = [
{ id: "64294306-5f42-463d-a5e8-2ad6c81a96de", name: "Tuxedo Corn" },
@@ -13,28 +13,19 @@ const BRAND_IDS = [
async function processWelcomeSequencesForBrand(brandId: string): Promise<{ sent: number; failed: number; skipped: number }> {
let sent = 0, failed = 0, skipped = 0;
const res = await fetch(
`${supabaseUrl}/rest/v1/rpc/get_active_welcome_sequence`,
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({ p_brand_id: brandId }),
}
);
if (!res.ok) {
const result = await getWelcomeSequence(brandId);
if (!result.success) {
return { sent: 0, failed: 0, skipped: 0 };
}
const data = await res.json();
const row = Array.isArray(data) ? data[0] : data;
const entries: WelcomeSequenceEntry[] = row?.entries ?? [];
const entries: WelcomeSequenceEntry[] = result.entries;
for (const entry of entries) {
const nextStep = entry.sequence_step + 1;
if (nextStep > 4) { skipped++; continue; }
if (entry.status === "unsubscribed" || entry.status === "bounced") { skipped++; continue; }
const result = await sendWelcomeEmail(entry, nextStep);
if (result.success) {
const r = await sendWelcomeEmail(entry, nextStep);
if (r.success) {
sent++;
} else {
failed++;
+9 -74
View File
@@ -1,6 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import crypto from "crypto";
import { svcHeaders } from "@/lib/svc-headers";
// Resend webhook events: email.delivered, email.opened, email.clicked,
// email.bounced, email.failed, email.unsubscribed
@@ -48,78 +47,14 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
const { type, data } = event;
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
// Look up by customer_email + subject (event_id is not populated by send_campaign)
// Filter to recent logs (last 7 days) to avoid stale matches
const sevenDaysAgo = new Date();
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
const findRes = await fetch(
`${supabaseUrl}/rest/v1/communication_message_logs?` +
`customer_email=eq.${encodeURIComponent(data.to)}` +
`&subject=eq.${encodeURIComponent(data.subject ?? "")}` +
`&delivery_method=eq.email` +
`&created_at=gt.${sevenDaysAgo.toISOString()}` +
`&order=created_at.desc` +
`&limit=5&select=id,brand_id`,
{
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
}
);
if (!findRes.ok) {
return NextResponse.json({ error: "Failed to look up message" }, { status: 500 });
}
const logs: { id: string; brand_id: string }[] = await findRes.json();
if (logs.length === 0) {
// No matching log found — silently acknowledge to avoid Resend retries
return NextResponse.json({ ok: true });
}
// Update the most recent matching log
const log = logs[0];
const updates: Record<string, string | undefined> = {};
switch (type) {
case "email.delivered":
updates.delivered_at = data.delivered_at ?? new Date().toISOString();
updates.status = "delivered";
break;
case "email.opened":
updates.opened_at = data.opened_at ?? new Date().toISOString();
break;
case "email.clicked":
updates.clicked_at = data.clicked_at ?? new Date().toISOString();
break;
case "email.bounced":
case "email.failed":
updates.bounced_at = data.bounced_at ?? new Date().toISOString();
updates.bounce_reason = data.bounce_reason ?? undefined;
updates.status = "bounced";
break;
case "email.unsubscribed":
updates.status = "unsubscribed";
break;
default:
return NextResponse.json({ ok: true });
}
const patchRes = await fetch(
`${supabaseUrl}/rest/v1/communication_message_logs?id=eq.${log.id}`,
{
method: "PATCH",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json", Prefer: "return=minimal" },
body: JSON.stringify(updates),
}
);
if (!patchRes.ok) {
return NextResponse.json({ error: "Failed to update log" }, { status: 500 });
}
// The new schema does not have a `communication_message_logs` table
// — the per-recipient delivery log has been retired. We still
// acknowledge the event so Resend does not retry, but there is
// nothing to update. When a new log table is added, this is the
// place to look up by `customer_email + subject` (the event_id is
// never populated by `send_campaign`) and write delivered/opened/
// clicked/bounced timestamps.
void event;
return NextResponse.json({ ok: true });
}
}