Branchwell

Lumen & Gesso / website · lumengesso.com / app / api / cron / cart-reminders / route.ts

1import { NextResponse, type NextRequest } from 'next/server';
2import { physicalCheckoutEnabled } from '@/app/lib/free-studio-checkout';
3import { commerceDb, sweepD1AbandonedCheckouts } from '@/app/lib/commerce-db';
4import { sendEmail } from '@/app/lib/email';
5import { env } from '@/app/lib/env';
6import { cartReminderHtml } from '@/app/lib/order-emails';
7import { displayOrderId } from '@/app/lib/orders';
8
9export const runtime = 'nodejs';
10export const dynamic = 'force-dynamic';
11
12// The cart-reminder scheduler calls this every 15 minutes with its bearer secret.
13//
14// Two-touch sequence, anchored on cart creation time:
15// touch 1 — ~1h after the cart was created (cart_reminders_sent 0 → 1)
16// touch 2 — ~24h after (cart_reminders_sent 1 → 2), the final nudge
17// Only pending_payment carts are eligible; once paid (→ pending_design)
18// or swept to abandoned at seven days, they drop out. We also
19// never chase carts older than that 7-day window.
20const TOUCH1_AFTER_MS = 60 * 60 * 1000; // 1 hour
21const TOUCH2_AFTER_MS = 24 * 60 * 60 * 1000; // 24 hours
22const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // matches sweep_abandoned_checkouts
23
24type CartRow = {
25 id: string;
26 user_email: string | null;
27 config: { styleId?: string; productId?: string; size?: string } | null;
28 cart_reminders_sent: number;
29 created_at: string;
30};
31
32function summaryOf(config: CartRow['config']): string | null {
33 const c = config ?? {};
34 const parts = [c.styleId, c.productId, c.size].filter(Boolean);
35 return parts.length ? parts.join(' · ') : null;
36}
37
38export async function GET(req: NextRequest) {
39 if (!physicalCheckoutEnabled()) {
40 return NextResponse.json({ ok: true, skipped: true, considered: 0, due: 0, sent: 0, failed: 0 });
41 }
42
43 // Only the scheduler may trigger reminder delivery.
44 if (req.headers.get('authorization') !== `Bearer ${env.cron.secret()}`) {
45 return NextResponse.json({ error: 'unauthorized' }, { status: 401 });
46 }
47
48 const admin = commerceDb();
49 const now = Date.now();
50 const maxAgeIso = new Date(now - MAX_AGE_MS).toISOString();
51 await sweepD1AbandonedCheckouts(maxAgeIso);
52
53 const { data, error } = await admin
54 .from('orders')
55 .select('id, user_email, config, cart_reminders_sent, created_at')
56 .eq('status', 'pending_payment')
57 .lt('cart_reminders_sent', 2)
58 .gt('created_at', maxAgeIso)
59 .order('created_at', { ascending: true })
60 .limit(100);
61
62 if (error) {
63 return NextResponse.json({ error: error.message }, { status: 500 });
64 }
65
66 const rows = (data ?? []) as CartRow[];
67 const due = rows.filter((o) => {
68 if (!o.user_email || !o.user_email.includes('@')) return false;
69 const ageMs = now - new Date(o.created_at).getTime();
70 if (o.cart_reminders_sent === 0) return ageMs >= TOUCH1_AFTER_MS;
71 if (o.cart_reminders_sent === 1) return ageMs >= TOUCH2_AFTER_MS;
72 return false;
73 });
74
75 const results = await Promise.allSettled(
76 due.map(async (o) => {
77 const finalTouch = o.cart_reminders_sent === 1;
78 // Claim the reminder before sending. A concurrent tick or a cart
79 // paid since the SELECT returns no row and must not send an email.
80 const { data: claimed, error: bumpErr } = await admin
81 .from('orders')
82 .update({ cart_reminders_sent: o.cart_reminders_sent + 1 })
83 .eq('id', o.id)
84 .eq('status', 'pending_payment')
85 .eq('cart_reminders_sent', o.cart_reminders_sent)
86 .select('id')
87 .maybeSingle();
88 if (bumpErr) throw new Error(`bump failed for ${o.id}: ${bumpErr.message}`);
89 if (!claimed) return false;
90
91 const resumeUrl = `${env.site.url()}/checkout?orderId=${o.id}&resume=1`;
92 await sendEmail({
93 to: o.user_email!,
94 subject: finalTouch
95 ? 'Still thinking it over? Your portrait is saved'
96 : 'You left a portrait in your cart',
97 html: cartReminderHtml(o.id, resumeUrl, { summary: summaryOf(o.config), finalTouch }),
98 text: `Your custom pet portrait commission (${displayOrderId(o.id)}) is saved — no charge has been made. Pick up where you left off: ${resumeUrl}`,
99 });
100 return true;
101 }),
102 );
103
104 const sent = results.filter((r) => r.status === 'fulfilled' && r.value).length;
105 return NextResponse.json({
106 ok: true,
107 considered: rows.length,
108 due: due.length,
109 sent,
110 failed: results.filter((r) => r.status === 'rejected').length,
111 });
112}