Lumen & Gesso / website · lumengesso.com / app / lib / studio-print-fulfillment.ts
| 1 | import 'server-only'; |
| 2 | import { createHash } from 'node:crypto'; |
| 3 | import type Stripe from 'stripe'; |
| 4 | import { authOrigin } from './lumen-auth'; |
| 5 | import { prodigiFetch } from './prodigi'; |
| 6 | import { prodigiItem } from './prodigi-skus'; |
| 7 | import { boundedBody, StudioError } from './studio-media'; |
| 8 | import { studioDatabase } from './studio-config'; |
| 9 | |
| 10 | type FulfillmentStmt = { bind(...values:(string | number | null)[]): FulfillmentStmt; first<T>():Promise<T|null> }; |
| 11 | function fulfillmentDatabase() { return studioDatabase() as unknown as {prepare(sql:string):FulfillmentStmt}; } |
| 12 | import { printAssetMatches, PRINT_SHIPPING_COUNTRY, PRINT_WORKFLOW, validPrintOrder, type PrintApproval } from '../api/studio/print/protocol'; |
| 13 | import { readPrintArtworkForOrder, readStoredPrint } from '../api/studio/print/persistence'; |
| 14 | |
| 15 | export const STUDIO_PRINT_WORKFLOW = PRINT_WORKFLOW; |
| 16 | const SUBMITTING = 'fulfillment_submitting'; |
| 17 | const REVIEW = 'fulfillment_review'; |
| 18 | const GENERATION_ID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i; |
| 19 | const PRODIGI_ORDER_ID = /^ord_[A-Za-z0-9]{1,64}$/; |
| 20 | // Never issue a second vendor POST for a claimed order, even on timeout or a 5xx. |
| 21 | // Stable Prodigi v4 idempotency is a second layer, not permission to retry. |
| 22 | const PRINTER_TIMEOUT_MS = 20_000; |
| 23 | |
| 24 | type Order = { |
| 25 | id: string; |
| 26 | status: string; |
| 27 | config: Record<string, unknown>; |
| 28 | price_cents: number; |
| 29 | current_generation_id: string | null; |
| 30 | stripe_session_id: string | null; |
| 31 | stripe_payment_intent_id: string | null; |
| 32 | prodigi_order_id: string | null; |
| 33 | updated_at: string; |
| 34 | }; |
| 35 | |
| 36 | type ShippingDetails = NonNullable<NonNullable<Stripe.Checkout.Session['collected_information']>['shipping_details']>; |
| 37 | type PrintResult = { |
| 38 | state: 'waiting_for_payment' | 'ignored' | 'already_processed' | 'submitted' | 'needs_review' | 'unavailable'; |
| 39 | paidNow?: boolean; |
| 40 | paidCents?: number; |
| 41 | prodigiOrderId?: string; |
| 42 | reason?: string; |
| 43 | }; |
| 44 | |
| 45 | function record(value: unknown): Record<string, unknown> | null { |
| 46 | return !!value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null; |
| 47 | } |
| 48 | |
| 49 | export function isStudioPrintOrder(config: unknown) { |
| 50 | const saved = record(config); |
| 51 | return saved?.workflow === STUDIO_PRINT_WORKFLOW || !!record(saved?.selfServicePrint); |
| 52 | } |
| 53 | |
| 54 | function bounded(value: string | null | undefined, limit: number, required = true) { |
| 55 | const normalized = value?.trim() ?? ''; |
| 56 | if ((required && !normalized) || normalized.length > limit || /[\u0000-\u001f\u007f]/.test(normalized)) return null; |
| 57 | return normalized; |
| 58 | } |
| 59 | |
| 60 | function recipient(shipping: ShippingDetails | null) { |
| 61 | const name = bounded(shipping?.name, 100); |
| 62 | const line1 = bounded(shipping?.address?.line1, 120); |
| 63 | const line2 = bounded(shipping?.address?.line2, 120, false); |
| 64 | const city = bounded(shipping?.address?.city, 100); |
| 65 | const state = bounded(shipping?.address?.state, 2); |
| 66 | const postal = bounded(shipping?.address?.postal_code, 10); |
| 67 | const country = shipping?.address?.country; |
| 68 | if (!name || !line1 || line2 === null || !city || !state || !/^[A-Z]{2}$/.test(state) |
| 69 | || !postal || !/^\d{5}(-\d{4})?$/.test(postal) || country !== PRINT_SHIPPING_COUNTRY) return null; |
| 70 | return { name, address: { |
| 71 | line1, ...(line2 ? { line2 } : {}), townOrCity: city, stateOrCounty: state, postalOrZipCode: postal, countryCode: country, |
| 72 | } }; |
| 73 | } |
| 74 | |
| 75 | function validAssetURL(approval: PrintApproval, orderId: string, origin: string) { |
| 76 | try { |
| 77 | const url = new URL(approval.cleanUrl); |
| 78 | return url.protocol === 'https:' && url.origin === origin && !url.hash && !url.username && !url.password |
| 79 | && url.pathname === '/api/studio/print/asset/' + orderId |
| 80 | && [...url.searchParams.keys()].length === 1 && /^[a-f0-9]{64}\.[a-f0-9]{64}$/.test(url.searchParams.get('key') ?? ''); |
| 81 | } catch { return false; } |
| 82 | } |
| 83 | |
| 84 | function vendorMode(isLive: boolean, origin: string) { |
| 85 | try { |
| 86 | const callback = process.env.PRODIGI_WEBHOOK_TOKEN; |
| 87 | const url = new URL(process.env.PRODIGI_API_BASE_URL || 'https://api.prodigi.com/v4.0/'); |
| 88 | const stripeKey = process.env.STRIPE_SECRET_KEY ?? ''; |
| 89 | const prodigiKey = isLive ? process.env.PRODIGI_API_KEY : process.env.PRODIGI_API_KEY_SANDBOX; |
| 90 | const expectedHost = isLive ? 'api.prodigi.com' : 'api.sandbox.prodigi.com'; |
| 91 | if (!callback || !/^[A-Za-z0-9_-]{16,}$/.test(callback) || !prodigiKey |
| 92 | || !(isLive ? /^(sk|rk)_live_/ : /^(sk|rk)_test_/).test(stripeKey) || !origin.startsWith('https://') |
| 93 | || url.origin !== 'https://' + expectedHost || !/^\/v4\.0\/?$/.test(url.pathname) || url.search || url.hash || url.username || url.password) return null; |
| 94 | return origin + '/api/webhooks/prodigi/' + callback; |
| 95 | } catch { return null; } |
| 96 | } |
| 97 | |
| 98 | function warn(orderId: string, reason: string, vendorId?: string) { |
| 99 | // Operational identifiers only: no image URL, Stripe body, customer |
| 100 | // name/address/email, vendor response body, API credentials or error text. |
| 101 | console.warn('[studio print] requires reconciliation', { orderId, reason, ...(vendorId ? {vendorId} : {}) }); |
| 102 | } |
| 103 | |
| 104 | async function claim( |
| 105 | order: Order, session: Stripe.Checkout.Session, intent: string, shipping: ShippingDetails | null, |
| 106 | next: typeof SUBMITTING | typeof REVIEW, generation?: {id: string; url: string}, |
| 107 | ) { |
| 108 | const query = fulfillmentDatabase().prepare(` |
| 109 | UPDATE orders SET status=?, stripe_payment_intent_id=?, shipping_address=?, |
| 110 | updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now') |
| 111 | WHERE id=? AND status='pending_payment' AND stripe_session_id=? AND updated_at=? |
| 112 | AND prodigi_order_id IS NULL AND stripe_payment_intent_id IS NULL |
| 113 | ${generation ? 'AND current_generation_id=? AND EXISTS (SELECT 1 FROM generations WHERE id=? AND order_id=orders.id AND clean_url=? AND model=?)' : ''} |
| 114 | RETURNING id`); |
| 115 | const bindings = [next, intent, shipping ? JSON.stringify(shipping) : null, order.id, session.id, order.updated_at]; |
| 116 | if (generation) bindings.push(generation.id, generation.id, generation.url, PRINT_WORKFLOW); |
| 117 | return !!await query.bind(...bindings).first<{id: string}>(); |
| 118 | } |
| 119 | |
| 120 | async function claimedConcurrently(orderId: string, paymentIntent: string) { |
| 121 | const other = await fulfillmentDatabase().prepare('SELECT stripe_payment_intent_id FROM orders WHERE id=?') |
| 122 | .bind(orderId).first<{stripe_payment_intent_id:string|null}>(); |
| 123 | return other?.stripe_payment_intent_id === paymentIntent; |
| 124 | } |
| 125 | |
| 126 | async function finish(orderId: string, intent: string, next: 'in_production' | typeof REVIEW, vendorId: string | null) { |
| 127 | const r = await fulfillmentDatabase().prepare(` |
| 128 | UPDATE orders SET status=?, prodigi_order_id=?, updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now') |
| 129 | WHERE id=? AND status=? AND stripe_payment_intent_id=? AND prodigi_order_id IS NULL |
| 130 | RETURNING id`).bind(next, vendorId, orderId, SUBMITTING, intent).first<{id: string}>(); |
| 131 | return !!r; |
| 132 | } |
| 133 | |
| 134 | export async function fulfillStudioPrint(order: Order, session: Stripe.Checkout.Session): Promise<PrintResult> { |
| 135 | // The caller must have verified the Stripe signature. Recheck the |
| 136 | // particular payment/session matches precisely; a marked order must |
| 137 | // never fall through to the legacy paid-commission branch. |
| 138 | const shipping = session.collected_information?.shipping_details ?? null; |
| 139 | const intent = typeof session.payment_intent === 'string' ? session.payment_intent : session.payment_intent?.id; |
| 140 | if (session.payment_status !== 'paid') return { state: 'waiting_for_payment' }; |
| 141 | if (!validPrintOrder(order.id) || session.id !== order.stripe_session_id || !intent || !/^pi_[A-Za-z0-9_]{1,180}$/.test(intent) |
| 142 | || session.mode !== 'payment' || session.status !== 'complete') { |
| 143 | warn(order.id, 'invalid_or_unmatched_paid_session'); |
| 144 | return { state: 'ignored', reason: 'invalid_or_unmatched_paid_session' }; |
| 145 | } |
| 146 | const expectedSessionPrefix = session.livemode === true ? 'cs_live_' : 'cs_test_'; |
| 147 | if (typeof session.livemode !== 'boolean' || !session.id.startsWith(expectedSessionPrefix)) { |
| 148 | warn(order.id, 'bad_session_mode'); |
| 149 | return { state: 'ignored', reason: 'bad_session_mode' }; |
| 150 | } |
| 151 | if (order.status !== 'pending_payment' || order.prodigi_order_id || order.stripe_payment_intent_id) { |
| 152 | return { state: 'already_processed' }; |
| 153 | } |
| 154 | |
| 155 | const paidCents = typeof session.amount_total === 'number' && Number.isSafeInteger(session.amount_total) |
| 156 | && session.amount_total > 0 && session.currency === 'usd' ? session.amount_total : undefined; |
| 157 | const reviewPaid = async (reason: string): Promise<PrintResult> => { |
| 158 | try { |
| 159 | if (!await claim(order, session, intent, shipping, REVIEW)) { |
| 160 | if (await claimedConcurrently(order.id, intent)) return { state:'already_processed' }; |
| 161 | return { state:'unavailable', reason:'could_not_record_paid_order' }; |
| 162 | } |
| 163 | warn(order.id, reason); |
| 164 | return { state:'needs_review', paidNow:true, paidCents, reason }; |
| 165 | } catch { return { state:'unavailable', reason:'could_not_record_paid_order' }; } |
| 166 | }; |
| 167 | |
| 168 | const cfg = readStoredPrint(order.config); |
| 169 | const approval = cfg?.selfServicePrint; |
| 170 | const tax = session.total_details?.amount_tax; |
| 171 | const metadata = session.metadata; |
| 172 | if (!cfg || !approval || !GENERATION_ID.test(approval.generationId) || metadata?.workflow !== STUDIO_PRINT_WORKFLOW || metadata.orderId !== order.id |
| 173 | || session.client_reference_id !== order.id || approval.generationId !== order.current_generation_id |
| 174 | || metadata.generationId !== approval.generationId || metadata.artworkSha256 !== approval.artworkSha256 |
| 175 | || metadata.configSha256 !== approval.configSha256 || approval.amountCents !== order.price_cents |
| 176 | || session.amount_subtotal !== approval.amountCents |
| 177 | || session.total_details?.amount_discount !== 0 || session.total_details?.amount_shipping !== 0 |
| 178 | || session.automatic_tax?.enabled !== true || session.automatic_tax.status !== 'complete' |
| 179 | || typeof tax !== 'number' || tax < 0 || !Number.isSafeInteger(tax) |
| 180 | || paidCents !== approval.amountCents + tax) return reviewPaid('approval_or_payment_mismatch'); |
| 181 | const destination = recipient(shipping); |
| 182 | if (!destination) return reviewPaid('invalid_shipping'); |
| 183 | |
| 184 | let origin: string; |
| 185 | try { origin = authOrigin(); } catch { return reviewPaid('printer_environment_unavailable'); } |
| 186 | const callbackUrl = vendorMode(session.livemode, origin); |
| 187 | if (!callbackUrl || !validAssetURL(approval, order.id, origin) || !printAssetMatches(approval.cleanUrl, order.id, approval.artworkSha256)) return reviewPaid('printer_environment_or_asset_url_mismatch'); |
| 188 | |
| 189 | let item: ReturnType<typeof prodigiItem>; |
| 190 | try { |
| 191 | item = prodigiItem({ productId: cfg.productId, sizeId: cfg.size, frameId: cfg.frame, matteId: cfg.matteId, wrapId: cfg.wrap }); |
| 192 | } catch { return reviewPaid('invalid_print_approval'); } |
| 193 | |
| 194 | let generation: {id: string; url: string}; |
| 195 | try { |
| 196 | const row = await fulfillmentDatabase().prepare('SELECT id,clean_url FROM generations WHERE id=? AND order_id=? AND model=?') |
| 197 | .bind(approval.generationId, order.id, PRINT_WORKFLOW).first<{ id: string; clean_url: string }>(); |
| 198 | if (!row || row.clean_url !== approval.cleanUrl) return reviewPaid('approved_print_asset_changed'); |
| 199 | generation = { id: row.id, url: row.clean_url }; |
| 200 | } catch { return { state:'unavailable', reason:'generation_lookup_unavailable' }; } |
| 201 | |
| 202 | try { |
| 203 | const bytes = await readPrintArtworkForOrder(order.id, approval.artworkSha256); |
| 204 | if (!bytes || createHash('sha256').update(bytes).digest('hex') !== approval.artworkSha256) { |
| 205 | return reviewPaid('approved_print_artwork_changed'); |
| 206 | } |
| 207 | } catch { return { state:'unavailable', reason:'artwork_lookup_unavailable' }; } |
| 208 | |
| 209 | try { |
| 210 | if (!await claim(order, session, intent, shipping, SUBMITTING, generation)) { |
| 211 | // A concurrent delivery has claimed it, or the approved snapshot |
| 212 | // changed before the atomic claim. Let a fresh lookup distinguish. |
| 213 | if (await claimedConcurrently(order.id, intent)) return { state:'already_processed' }; |
| 214 | return { state:'unavailable', reason:'fulfillment_claim_changed' }; |
| 215 | } |
| 216 | } catch { return { state:'unavailable', reason:'paid_fulfillment_claim_unavailable' }; } |
| 217 | |
| 218 | const paid = { paidNow:true, paidCents }; |
| 219 | let vendorId: string | null = null; |
| 220 | let reason = 'vendor_acceptance_unknown'; |
| 221 | try { |
| 222 | const response = await prodigiFetch('Orders', { |
| 223 | method: 'POST', signal: AbortSignal.timeout(PRINTER_TIMEOUT_MS), redirect: 'error', |
| 224 | body: JSON.stringify({ |
| 225 | idempotencyKey: approval.generationId, merchantReference: order.id, shippingMethod: 'Standard', |
| 226 | recipient: destination, |
| 227 | items: [{ sku: item.sku, copies: 1, sizing: 'fillPrintArea', attributes: item.attributes, assets: [{ printArea: 'default', url: generation.url }] }], |
| 228 | callbackUrl, |
| 229 | }), |
| 230 | }); |
| 231 | const raw = await boundedBody(response.body, 512 * 1024, new StudioError('printer_response_large', 502, 'Unexpected vendor response.')); |
| 232 | const data = JSON.parse(new TextDecoder().decode(raw)) as { outcome?: string; order?: { id?: string; merchantReference?: string; idempotencyKey?: string } }; |
| 233 | const outcome = data.outcome?.toLowerCase(); |
| 234 | const identified = typeof data.order?.id === 'string' && PRODIGI_ORDER_ID.test(data.order.id); |
| 235 | const matches = data.order?.merchantReference === order.id && data.order?.idempotencyKey === approval.generationId; |
| 236 | if (response.ok && identified && matches) { |
| 237 | vendorId = data.order!.id!; |
| 238 | if (outcome === 'created' || outcome === 'alreadyexists') { |
| 239 | if (await finish(order.id, intent, 'in_production', vendorId)) return { state:'submitted', ...paid, prodigiOrderId:vendorId }; |
| 240 | warn(order.id, 'accepted_but_persistence_unconfirmed', vendorId); |
| 241 | return { state:'needs_review', ...paid, reason:'accepted_but_persistence_unconfirmed' }; |
| 242 | } |
| 243 | reason = 'vendor_order_requires_attention'; |
| 244 | } else if (response.ok && identified && outcome === 'onhold' && !data.order?.merchantReference && !data.order?.idempotencyKey) { |
| 245 | // v4 onHold returns only the newly accepted order's ID. Never report |
| 246 | // production started, but durably keep the ID for reconciliation. |
| 247 | vendorId = data.order!.id!; |
| 248 | reason = 'vendor_order_requires_attention'; |
| 249 | } else if (response.status === 400 && outcome === 'validationfailed') reason = 'vendor_rejected_order'; |
| 250 | } catch { /* may already have been accepted; never resubmit automatically */ } |
| 251 | |
| 252 | try { |
| 253 | if (!await finish(order.id, intent, REVIEW, vendorId)) reason = 'vendor_result_persistence_unconfirmed'; |
| 254 | } catch { reason = 'vendor_result_persistence_unconfirmed'; } |
| 255 | warn(order.id, reason, vendorId ?? undefined); |
| 256 | return { state:'needs_review', ...paid, reason }; |
| 257 | } |