Lumen & Gesso / website · lumengesso.com / app / api / webhooks / stripe / route.ts
| 1 | import { NextResponse, type NextRequest } from 'next/server'; |
| 2 | import Stripe from 'stripe'; |
| 3 | import { commerceDb } from '@/app/lib/commerce-db'; |
| 4 | import { prodigiFetch } from '@/app/lib/prodigi'; |
| 5 | import { prodigiItem } from '@/app/lib/prodigi-skus'; |
| 6 | import { sendEmail } from '@/app/lib/email'; |
| 7 | import { env } from '@/app/lib/env'; |
| 8 | import { displayOrderId } from '@/app/lib/orders'; |
| 9 | import { customerWelcomeHtml, ownerNotificationHtml, inProductionHtml, receiptHtml } from '@/app/lib/order-emails'; |
| 10 | import { generateMagicLink } from '@/app/lib/magic-link'; |
| 11 | import { fulfillStudioPrint, isStudioPrintOrder, STUDIO_PRINT_WORKFLOW } from '@/app/lib/studio-print-fulfillment'; |
| 12 | |
| 13 | export const runtime = 'nodejs'; |
| 14 | export const dynamic = 'force-dynamic'; |
| 15 | |
| 16 | export async function POST(req: NextRequest) { |
| 17 | const sig = req.headers.get('stripe-signature'); |
| 18 | if (!sig) return new NextResponse('missing signature', { status: 400 }); |
| 19 | |
| 20 | const body = await req.text(); |
| 21 | let event: Stripe.Event; |
| 22 | try { |
| 23 | event = await Stripe.webhooks.constructEventAsync(body, sig, env.stripe.webhookSecret()); |
| 24 | } catch (e) { |
| 25 | const msg = e instanceof Error ? e.message : 'invalid signature'; |
| 26 | return new NextResponse(`signature verification failed: ${msg}`, { status: 400 }); |
| 27 | } |
| 28 | |
| 29 | if (event.type !== 'checkout.session.completed' && event.type !== 'checkout.session.async_payment_succeeded') { |
| 30 | return NextResponse.json({ received: true, ignored: event.type }); |
| 31 | } |
| 32 | |
| 33 | const session = event.data.object; |
| 34 | const orderId = session.metadata?.orderId; |
| 35 | if (!orderId) return NextResponse.json({ received: true, ignored: 'no orderId in metadata' }); |
| 36 | |
| 37 | const admin = commerceDb(); |
| 38 | const { data: order, error: orderError } = await admin |
| 39 | .from('orders') |
| 40 | .select('*') |
| 41 | .eq('id', orderId) |
| 42 | .single(); |
| 43 | if (orderError && orderError.code !== 'PGRST116') { |
| 44 | return new NextResponse('Order lookup temporarily unavailable', { status: 503 }); |
| 45 | } |
| 46 | if (!order) return new NextResponse(`order ${orderId} not found`, { status: 404 }); |
| 47 | |
| 48 | // An explicit workflow marker on either side keeps malformed/incomplete |
| 49 | // self-service events from ever falling through to the hand-reviewed queue. |
| 50 | if (isStudioPrintOrder(order.config) || session.metadata?.workflow === STUDIO_PRINT_WORKFLOW) { |
| 51 | if (event.livemode !== session.livemode) return NextResponse.json({ received: true, ignored: 'payment mode mismatch' }); |
| 52 | const result = await fulfillStudioPrint(order, session); |
| 53 | if (result.state === 'unavailable') return new NextResponse('Order fulfillment temporarily unavailable', { status: 503 }); |
| 54 | |
| 55 | const messages: Promise<unknown>[] = []; |
| 56 | if (result.paidNow && result.paidCents) { |
| 57 | const paidDate = new Date().toLocaleDateString('en-US', { year:'numeric', month:'short', day:'numeric' }); |
| 58 | messages.push(sendEmail({ |
| 59 | to: order.user_email, |
| 60 | subject: `Your Lumen & Gesso print receipt — ${displayOrderId(orderId)}`, |
| 61 | html: receiptHtml(orderId, result.paidCents, paidDate, 'Lumen & Gesso physical print'), |
| 62 | text: `Receipt for print ${displayOrderId(orderId)} — $${(result.paidCents / 100).toFixed(2)} paid on ${paidDate}. View your order: ${env.site.url()}/orders/${orderId}`, |
| 63 | })); |
| 64 | } |
| 65 | if (result.state === 'submitted' && result.prodigiOrderId) { |
| 66 | const orderUrl = `${env.site.url()}/orders/${orderId}`; |
| 67 | messages.push(sendEmail({ |
| 68 | to: order.user_email, |
| 69 | subject: `In production — ${displayOrderId(orderId)}`, |
| 70 | html: inProductionHtml(orderId, orderUrl, result.prodigiOrderId), |
| 71 | text: `Your approved artwork was sent to print. View your order: ${orderUrl}`, |
| 72 | })); |
| 73 | } |
| 74 | // An email outage must not retry a printer submission. Logs never |
| 75 | // include third-party error bodies or customer addresses. |
| 76 | for (const [index, sent] of (await Promise.allSettled(messages)).entries()) { |
| 77 | if (sent.status === 'rejected') console.warn('[studio print] customer notice failed', { orderId, index }); |
| 78 | } |
| 79 | return NextResponse.json({ received: true, fulfillment: result.state, prodigiOrderId: result.prodigiOrderId ?? null }); |
| 80 | } |
| 81 | if (event.type !== 'checkout.session.completed') { |
| 82 | return NextResponse.json({ received: true, ignored: 'legacy workflow' }); |
| 83 | } |
| 84 | |
| 85 | if (order.status === 'in_production' || order.status === 'shipped' || order.prodigi_order_id) { |
| 86 | return NextResponse.json({ received: true, idempotent: true }); |
| 87 | } |
| 88 | |
| 89 | const shipping = session.collected_information?.shipping_details ?? null; |
| 90 | const paymentIntentId = typeof session.payment_intent === 'string' |
| 91 | ? session.payment_intent |
| 92 | : session.payment_intent?.id ?? null; |
| 93 | |
| 94 | // New flow: this webhook fires at SUBMIT TIME (customer just paid for |
| 95 | // a fresh commission). Move the order from pending_payment into the |
| 96 | // design queue and dispatch the welcome / studio-notification emails. |
| 97 | // Prodigi creation continues to happen at design-approval time via |
| 98 | // the existing approve route (no longer creates a Stripe session, |
| 99 | // just transitions status to 'approved' + this same Prodigi block). |
| 100 | if (order.status === 'pending_payment') { |
| 101 | // Compare-and-swap: only the first delivery of this event wins the |
| 102 | // transition, so duplicate/concurrent Stripe deliveries can't fire |
| 103 | // the welcome + studio emails twice. |
| 104 | const { data: claimed, error: claimError } = await admin.from('orders').update({ |
| 105 | status: 'pending_design', |
| 106 | stripe_payment_intent_id: paymentIntentId, |
| 107 | shipping_address: shipping, |
| 108 | }).eq('id', orderId).eq('status', 'pending_payment').select('id'); |
| 109 | if (claimError) return new NextResponse('Order update temporarily unavailable', { status: 503 }); |
| 110 | if (!claimed || claimed.length === 0) { |
| 111 | return NextResponse.json({ received: true, idempotent: 'already transitioned' }); |
| 112 | } |
| 113 | |
| 114 | const amount = `$${(order.price_cents / 100).toFixed(2)}`; |
| 115 | const paidDate = new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }); |
| 116 | const studioTo = env.site.studioEmail(); |
| 117 | const sends: Promise<unknown>[] = []; |
| 118 | |
| 119 | // Branded Lumen & Gesso receipt — replaces Stripe's auto-receipt |
| 120 | // (we dropped receipt_email on the Checkout Session). Sent regardless |
| 121 | // of the magic link, since a receipt is a standalone financial record. |
| 122 | sends.push(sendEmail({ |
| 123 | to: order.user_email, |
| 124 | subject: `Your Lumen & Gesso receipt — ${displayOrderId(orderId)}`, |
| 125 | html: receiptHtml(orderId, order.price_cents, paidDate, 'Lumen & Gesso commission'), |
| 126 | text: `Receipt for commission ${displayOrderId(orderId)} — ${amount} paid on ${paidDate}. Questions? hello@lumengesso.com`, |
| 127 | })); |
| 128 | |
| 129 | // Welcome / "view your order" email needs the magic link. If the link |
| 130 | // failed to mint, skip just this one — the receipt above still goes out. |
| 131 | const actionLink = await generateMagicLink(order.user_email, `/orders/${orderId}`); |
| 132 | if (actionLink) { |
| 133 | sends.push(sendEmail({ |
| 134 | to: order.user_email, |
| 135 | subject: 'Your Lumen & Gesso commission — view your order', |
| 136 | html: customerWelcomeHtml(orderId, actionLink), |
| 137 | text: `Your commission is in the queue. View your order: ${actionLink}`, |
| 138 | })); |
| 139 | } else { |
| 140 | console.error(`[webhook] order ${orderId}: no magic link generated — welcome email skipped (receipt still sent)`); |
| 141 | } |
| 142 | |
| 143 | if (studioTo) { |
| 144 | sends.push(sendEmail({ |
| 145 | to: studioTo, |
| 146 | subject: `New paid commission: ${orderId} — ${order.user_email}`, |
| 147 | html: ownerNotificationHtml(orderId, order.user_email, order.price_cents), |
| 148 | text: `New order ${orderId} from ${order.user_email} — ${amount}.`, |
| 149 | })); |
| 150 | } |
| 151 | |
| 152 | // Don't let an email failure crash the webhook (Stripe would retry and |
| 153 | // the CAS guard above would then skip the resend) — but DO surface it. |
| 154 | const results = await Promise.allSettled(sends); |
| 155 | results.forEach((r, i) => { |
| 156 | if (r.status === 'rejected') { |
| 157 | console.error(`[webhook] order ${orderId} email send #${i} failed:`, r.reason); |
| 158 | } |
| 159 | }); |
| 160 | |
| 161 | return NextResponse.json({ received: true, transitioned: 'pending_payment→pending_design' }); |
| 162 | } |
| 163 | |
| 164 | // Legacy flow (order was awaiting_approval when paid). Falls through |
| 165 | // to mark the order approved and create the Prodigi order. This path |
| 166 | // is preserved for any historical orders mid-flight; new orders never |
| 167 | // reach here because they pay at submit time, not at approval. |
| 168 | // |
| 169 | // Guard: only awaiting_approval/approved orders belong on this path. |
| 170 | // Anything else reaching here is a stale/duplicate delivery — ignore |
| 171 | // it rather than corrupting the order's status (e.g. shoving a |
| 172 | // pending_design order to approved on a Stripe redelivery). |
| 173 | if (order.status !== 'awaiting_approval' && order.status !== 'approved') { |
| 174 | return NextResponse.json({ received: true, ignored: `no action for status ${order.status}` }); |
| 175 | } |
| 176 | if (order.status !== 'approved') { |
| 177 | const { error: updateError } = await admin.from('orders').update({ |
| 178 | status: 'approved', |
| 179 | stripe_payment_intent_id: paymentIntentId, |
| 180 | shipping_address: shipping, |
| 181 | }).eq('id', orderId); |
| 182 | if (updateError) return new NextResponse('Order update temporarily unavailable', { status: 503 }); |
| 183 | } |
| 184 | |
| 185 | // Look up the published generation's clean URL. |
| 186 | const proofQuery = admin |
| 187 | .from('generations') |
| 188 | .select('clean_url') |
| 189 | .eq('order_id', orderId); |
| 190 | const { data: pubGen } = await (order.current_generation_id |
| 191 | ? proofQuery.eq('id', order.current_generation_id) |
| 192 | : proofQuery.eq('published', true)).single(); |
| 193 | |
| 194 | const cleanUrl = pubGen?.clean_url; |
| 195 | if (!cleanUrl) { |
| 196 | return new NextResponse(`order ${orderId} paid but no published generation`, { status: 200 }); |
| 197 | } |
| 198 | |
| 199 | // Create Prodigi order. |
| 200 | const cfg = order.config as { productId: 'matted' | 'canvas' | 'classic' | 'stretched'; size: string; frame: string; matteId?: string; wrap?: string }; |
| 201 | const { sku, attributes } = prodigiItem({ |
| 202 | productId: cfg.productId, |
| 203 | sizeId: cfg.size, |
| 204 | frameId: cfg.frame, |
| 205 | matteId: cfg.matteId, |
| 206 | wrapId: cfg.wrap, |
| 207 | }); |
| 208 | |
| 209 | const recipient = shipping ? { |
| 210 | name: shipping.name, |
| 211 | address: { |
| 212 | line1: shipping.address?.line1, |
| 213 | line2: shipping.address?.line2 ?? undefined, |
| 214 | townOrCity: shipping.address?.city, |
| 215 | stateOrCounty: shipping.address?.state, |
| 216 | postalOrZipCode: shipping.address?.postal_code, |
| 217 | countryCode: shipping.address?.country, |
| 218 | }, |
| 219 | } : null; |
| 220 | |
| 221 | let prodigiOrderId: string | null = null; |
| 222 | if (recipient) { |
| 223 | try { |
| 224 | const prodigiRes = await prodigiFetch('Orders', { |
| 225 | method: 'POST', |
| 226 | body: JSON.stringify({ |
| 227 | shippingMethod: 'Standard', |
| 228 | recipient, |
| 229 | items: [{ |
| 230 | sku, |
| 231 | copies: 1, |
| 232 | sizing: 'fillPrintArea', |
| 233 | attributes, |
| 234 | assets: [{ printArea: 'default', url: cleanUrl }], |
| 235 | }], |
| 236 | callbackUrl: `${env.site.url()}/api/webhooks/prodigi/${process.env.PRODIGI_WEBHOOK_TOKEN}`, |
| 237 | }), |
| 238 | }); |
| 239 | const prodigiJson = await prodigiRes.json() as { order?: { id?: string }; outcome?: string }; |
| 240 | if (prodigiRes.ok && prodigiJson.order?.id) { |
| 241 | prodigiOrderId = prodigiJson.order.id; |
| 242 | await admin.from('orders').update({ |
| 243 | status: 'in_production', |
| 244 | prodigi_order_id: prodigiOrderId, |
| 245 | }).eq('id', orderId); |
| 246 | } else { |
| 247 | console.error('[stripe webhook] prodigi rejected', prodigiRes.status, prodigiJson); |
| 248 | } |
| 249 | } catch (e) { |
| 250 | console.error('[stripe webhook] prodigi error', e); |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | if (!prodigiOrderId) { |
| 255 | return NextResponse.json({ received: true, prodigiOrderId }); |
| 256 | } |
| 257 | |
| 258 | // Confirmation email — magic-link to /orders/[id] so customer lands signed-in. |
| 259 | const reviewPath = `/orders/${orderId}#review`; |
| 260 | const orderLink = await generateMagicLink(order.user_email, reviewPath); |
| 261 | const fallbackUrl = `${env.site.url()}${reviewPath}`; |
| 262 | await sendEmail({ |
| 263 | to: order.user_email, |
| 264 | subject: `In production — ${displayOrderId(orderId)}`, |
| 265 | html: inProductionHtml(orderId, orderLink ?? fallbackUrl, prodigiOrderId), |
| 266 | 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}`, |
| 267 | }).catch(() => {}); |
| 268 | |
| 269 | return NextResponse.json({ received: true, prodigiOrderId }); |
| 270 | } |