import { NextResponse, type NextRequest } from 'next/server'; import Stripe from 'stripe'; import { commerceDb } from '@/app/lib/commerce-db'; import { prodigiFetch } from '@/app/lib/prodigi'; import { prodigiItem } from '@/app/lib/prodigi-skus'; import { sendEmail } from '@/app/lib/email'; import { env } from '@/app/lib/env'; import { displayOrderId } from '@/app/lib/orders'; import { customerWelcomeHtml, ownerNotificationHtml, inProductionHtml, receiptHtml } from '@/app/lib/order-emails'; import { generateMagicLink } from '@/app/lib/magic-link'; import { fulfillStudioPrint, isStudioPrintOrder, STUDIO_PRINT_WORKFLOW } from '@/app/lib/studio-print-fulfillment'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export async function POST(req: NextRequest) { const sig = req.headers.get('stripe-signature'); if (!sig) return new NextResponse('missing signature', { status: 400 }); const body = await req.text(); let event: Stripe.Event; try { event = await Stripe.webhooks.constructEventAsync(body, sig, env.stripe.webhookSecret()); } catch (e) { const msg = e instanceof Error ? e.message : 'invalid signature'; return new NextResponse(`signature verification failed: ${msg}`, { status: 400 }); } if (event.type !== 'checkout.session.completed' && event.type !== 'checkout.session.async_payment_succeeded') { return NextResponse.json({ received: true, ignored: event.type }); } const session = event.data.object; const orderId = session.metadata?.orderId; if (!orderId) return NextResponse.json({ received: true, ignored: 'no orderId in metadata' }); const admin = commerceDb(); const { data: order, error: orderError } = await admin .from('orders') .select('*') .eq('id', orderId) .single(); if (orderError && orderError.code !== 'PGRST116') { return new NextResponse('Order lookup temporarily unavailable', { status: 503 }); } if (!order) return new NextResponse(`order ${orderId} not found`, { status: 404 }); // An explicit workflow marker on either side keeps malformed/incomplete // self-service events from ever falling through to the hand-reviewed queue. if (isStudioPrintOrder(order.config) || session.metadata?.workflow === STUDIO_PRINT_WORKFLOW) { if (event.livemode !== session.livemode) return NextResponse.json({ received: true, ignored: 'payment mode mismatch' }); const result = await fulfillStudioPrint(order, session); if (result.state === 'unavailable') return new NextResponse('Order fulfillment temporarily unavailable', { status: 503 }); const messages: Promise[] = []; if (result.paidNow && result.paidCents) { const paidDate = new Date().toLocaleDateString('en-US', { year:'numeric', month:'short', day:'numeric' }); messages.push(sendEmail({ to: order.user_email, subject: `Your Lumen & Gesso print receipt — ${displayOrderId(orderId)}`, html: receiptHtml(orderId, result.paidCents, paidDate, 'Lumen & Gesso physical print'), text: `Receipt for print ${displayOrderId(orderId)} — $${(result.paidCents / 100).toFixed(2)} paid on ${paidDate}. View your order: ${env.site.url()}/orders/${orderId}`, })); } if (result.state === 'submitted' && result.prodigiOrderId) { const orderUrl = `${env.site.url()}/orders/${orderId}`; messages.push(sendEmail({ to: order.user_email, subject: `In production — ${displayOrderId(orderId)}`, html: inProductionHtml(orderId, orderUrl, result.prodigiOrderId), text: `Your approved artwork was sent to print. View your order: ${orderUrl}`, })); } // An email outage must not retry a printer submission. Logs never // include third-party error bodies or customer addresses. for (const [index, sent] of (await Promise.allSettled(messages)).entries()) { if (sent.status === 'rejected') console.warn('[studio print] customer notice failed', { orderId, index }); } return NextResponse.json({ received: true, fulfillment: result.state, prodigiOrderId: result.prodigiOrderId ?? null }); } if (event.type !== 'checkout.session.completed') { return NextResponse.json({ received: true, ignored: 'legacy workflow' }); } if (order.status === 'in_production' || order.status === 'shipped' || order.prodigi_order_id) { return NextResponse.json({ received: true, idempotent: true }); } const shipping = session.collected_information?.shipping_details ?? null; const paymentIntentId = typeof session.payment_intent === 'string' ? session.payment_intent : session.payment_intent?.id ?? null; // New flow: this webhook fires at SUBMIT TIME (customer just paid for // a fresh commission). Move the order from pending_payment into the // design queue and dispatch the welcome / studio-notification emails. // Prodigi creation continues to happen at design-approval time via // the existing approve route (no longer creates a Stripe session, // just transitions status to 'approved' + this same Prodigi block). if (order.status === 'pending_payment') { // Compare-and-swap: only the first delivery of this event wins the // transition, so duplicate/concurrent Stripe deliveries can't fire // the welcome + studio emails twice. const { data: claimed, error: claimError } = await admin.from('orders').update({ status: 'pending_design', stripe_payment_intent_id: paymentIntentId, shipping_address: shipping, }).eq('id', orderId).eq('status', 'pending_payment').select('id'); if (claimError) return new NextResponse('Order update temporarily unavailable', { status: 503 }); if (!claimed || claimed.length === 0) { return NextResponse.json({ received: true, idempotent: 'already transitioned' }); } const amount = `$${(order.price_cents / 100).toFixed(2)}`; const paidDate = new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }); const studioTo = env.site.studioEmail(); const sends: Promise[] = []; // Branded Lumen & Gesso receipt — replaces Stripe's auto-receipt // (we dropped receipt_email on the Checkout Session). Sent regardless // of the magic link, since a receipt is a standalone financial record. sends.push(sendEmail({ to: order.user_email, subject: `Your Lumen & Gesso receipt — ${displayOrderId(orderId)}`, html: receiptHtml(orderId, order.price_cents, paidDate, 'Lumen & Gesso commission'), text: `Receipt for commission ${displayOrderId(orderId)} — ${amount} paid on ${paidDate}. Questions? hello@lumengesso.com`, })); // Welcome / "view your order" email needs the magic link. If the link // failed to mint, skip just this one — the receipt above still goes out. const actionLink = await generateMagicLink(order.user_email, `/orders/${orderId}`); if (actionLink) { sends.push(sendEmail({ to: order.user_email, subject: 'Your Lumen & Gesso commission — view your order', html: customerWelcomeHtml(orderId, actionLink), text: `Your commission is in the queue. View your order: ${actionLink}`, })); } else { console.error(`[webhook] order ${orderId}: no magic link generated — welcome email skipped (receipt still sent)`); } if (studioTo) { sends.push(sendEmail({ to: studioTo, subject: `New paid commission: ${orderId} — ${order.user_email}`, html: ownerNotificationHtml(orderId, order.user_email, order.price_cents), text: `New order ${orderId} from ${order.user_email} — ${amount}.`, })); } // Don't let an email failure crash the webhook (Stripe would retry and // the CAS guard above would then skip the resend) — but DO surface it. const results = await Promise.allSettled(sends); results.forEach((r, i) => { if (r.status === 'rejected') { console.error(`[webhook] order ${orderId} email send #${i} failed:`, r.reason); } }); return NextResponse.json({ received: true, transitioned: 'pending_payment→pending_design' }); } // Legacy flow (order was awaiting_approval when paid). Falls through // to mark the order approved and create the Prodigi order. This path // is preserved for any historical orders mid-flight; new orders never // reach here because they pay at submit time, not at approval. // // Guard: only awaiting_approval/approved orders belong on this path. // Anything else reaching here is a stale/duplicate delivery — ignore // it rather than corrupting the order's status (e.g. shoving a // pending_design order to approved on a Stripe redelivery). if (order.status !== 'awaiting_approval' && order.status !== 'approved') { return NextResponse.json({ received: true, ignored: `no action for status ${order.status}` }); } if (order.status !== 'approved') { const { error: updateError } = await admin.from('orders').update({ status: 'approved', stripe_payment_intent_id: paymentIntentId, shipping_address: shipping, }).eq('id', orderId); if (updateError) return new NextResponse('Order update temporarily unavailable', { status: 503 }); } // Look up the published generation's clean URL. const proofQuery = admin .from('generations') .select('clean_url') .eq('order_id', orderId); const { data: pubGen } = await (order.current_generation_id ? proofQuery.eq('id', order.current_generation_id) : proofQuery.eq('published', true)).single(); const cleanUrl = pubGen?.clean_url; if (!cleanUrl) { return new NextResponse(`order ${orderId} paid but no published generation`, { status: 200 }); } // Create Prodigi order. const cfg = order.config as { productId: 'matted' | 'canvas' | 'classic' | 'stretched'; size: string; frame: string; matteId?: string; wrap?: string }; const { sku, attributes } = prodigiItem({ productId: cfg.productId, sizeId: cfg.size, frameId: cfg.frame, matteId: cfg.matteId, wrapId: cfg.wrap, }); const recipient = shipping ? { name: shipping.name, address: { line1: shipping.address?.line1, line2: shipping.address?.line2 ?? undefined, townOrCity: shipping.address?.city, stateOrCounty: shipping.address?.state, postalOrZipCode: shipping.address?.postal_code, countryCode: shipping.address?.country, }, } : null; let prodigiOrderId: string | null = null; if (recipient) { try { const prodigiRes = await prodigiFetch('Orders', { method: 'POST', body: JSON.stringify({ shippingMethod: 'Standard', recipient, items: [{ sku, copies: 1, sizing: 'fillPrintArea', attributes, assets: [{ printArea: 'default', url: cleanUrl }], }], callbackUrl: `${env.site.url()}/api/webhooks/prodigi/${process.env.PRODIGI_WEBHOOK_TOKEN}`, }), }); const prodigiJson = await prodigiRes.json() as { order?: { id?: string }; outcome?: string }; if (prodigiRes.ok && prodigiJson.order?.id) { prodigiOrderId = prodigiJson.order.id; await admin.from('orders').update({ status: 'in_production', prodigi_order_id: prodigiOrderId, }).eq('id', orderId); } else { console.error('[stripe webhook] prodigi rejected', prodigiRes.status, prodigiJson); } } catch (e) { console.error('[stripe webhook] prodigi error', e); } } if (!prodigiOrderId) { return NextResponse.json({ received: true, prodigiOrderId }); } // Confirmation email — magic-link to /orders/[id] so customer lands signed-in. const reviewPath = `/orders/${orderId}#review`; const orderLink = await generateMagicLink(order.user_email, reviewPath); const fallbackUrl = `${env.site.url()}${reviewPath}`; await sendEmail({ to: order.user_email, subject: `In production — ${displayOrderId(orderId)}`, html: inProductionHtml(orderId, orderLink ?? fallbackUrl, prodigiOrderId), text: `Your portrait is on its way to print. We'll email you again when it ships. Once it arrives, you can leave a star rating, write a review, and share a photo from your order page. View your order: ${orderLink ?? fallbackUrl}`, }).catch(() => {}); return NextResponse.json({ received: true, prodigiOrderId }); }