Lumen & Gesso / website · lumengesso.com / app / lib / studio-print-fulfillment.test.cjs
| 1 | // node app/lib/studio-print-fulfillment.test.cjs |
| 2 | // Local SQLite migrations, actually signed Stripe payloads, mock email/R2/Prodigi. |
| 3 | // This test always overrides all vendor HTTP; never call the live API. |
| 4 | const assert = require('node:assert/strict'); |
| 5 | const { DatabaseSync } = require('node:sqlite'); |
| 6 | const { createHash, randomUUID } = require('node:crypto'); |
| 7 | const fs = require('node:fs'); |
| 8 | const Module = require('node:module'); |
| 9 | const path = require('node:path'); |
| 10 | const root = path.resolve(__dirname, '../..'); |
| 11 | const backend = Module.createRequire(path.join(root, 'package.json')); |
| 12 | const Stripe = backend('stripe'); |
| 13 | const esbuild = backend('esbuild'); |
| 14 | const nextServer=backend('next/server'); |
| 15 | const sharp=backend('sharp'); |
| 16 | const origin = 'https://lumengesso.com'; |
| 17 | const webhookSecret = 'whsec_mock_event_locally_no_external_request'; |
| 18 | const flow = 'self_service_print_v1'; |
| 19 | const initialTimestamp = '2026-10-29T17:16:00.000Z'; |
| 20 | let db, printer, notifications, artwork, unavailable; |
| 21 | const artworkHash = bytes => createHash('sha256').update(bytes).digest('hex'); |
| 22 | const binding = { |
| 23 | prepare(sql) { |
| 24 | return { |
| 25 | all: async () => ({ results: db.prepare(sql).all() }), |
| 26 | bind: (...params) => ({ |
| 27 | first: async () => { |
| 28 | if (unavailable && sql.includes(unavailable)) throw Error('mock persistence failure'); |
| 29 | return db.prepare(sql).get(...params) ?? null; |
| 30 | }, |
| 31 | all: async () => ({ results: db.prepare(sql).all(...params) }), |
| 32 | }), |
| 33 | }; |
| 34 | }, |
| 35 | }; |
| 36 | function reset() { |
| 37 | db = new DatabaseSync(':memory:'); |
| 38 | db.exec(fs.readFileSync(path.join(root, 'd1/migrations/0001_commerce.sql'), 'utf8')); |
| 39 | printer = []; |
| 40 | notifications = []; |
| 41 | artwork = new Map(); |
| 42 | unavailable = ''; |
| 43 | process.env.LUMEN_SELF_SERVICE_PRINT_SECRET = 'fake-only-an-exact-print-approval-secret-1234'; |
| 44 | delete process.env.LUMEN_SELF_SERVICE_PRINT_ENABLED; // existing paid order must still finish. |
| 45 | process.env.STRIPE_SECRET_KEY = 'sk_test_mock_never_call'; |
| 46 | process.env.PRODIGI_API_BASE_URL = 'https://api.sandbox.prodigi.com/v4.0/'; |
| 47 | process.env.PRODIGI_API_KEY = 'must-never-use-live-credential'; |
| 48 | process.env.PRODIGI_API_KEY_SANDBOX = 'fake-sandbox-key-no-remote-call'; |
| 49 | process.env.PRODIGI_WEBHOOK_TOKEN = 'test_webhook_token_nothing_real'; |
| 50 | } |
| 51 | function fixture(protocol, id = 'lg_23456789ab', options = {}) { |
| 52 | const selection = {productId:'stretched', size:'8x10', orientation:'portrait', frame:'none', wrap:'mirror'}; |
| 53 | // Use the canonical product tuple and the live domain only as input. |
| 54 | const selected = protocol.parsePrintSelection(selection); |
| 55 | const configSha256 = protocol.printConfigSha256(selected); |
| 56 | const binary = Buffer.from('mock private unwatermarked image bytes // ' + id); |
| 57 | const sha256 = artworkHash(binary); |
| 58 | const generationId = randomUUID(); |
| 59 | const sessionId = 'cs_test_mock' + id.slice(3); |
| 60 | const cleanUrl = protocol.printAssetURL(id, sha256); |
| 61 | const config = { ...selected, workflow: flow, selfServicePrint: { |
| 62 | version: 1, generationId, amountCents: 1200, configSha256, artworkSha256:sha256, |
| 63 | cleanUrl, approvedAt:initialTimestamp, shippingCountry:'US', artworkMime:'image/jpeg', |
| 64 | } }; |
| 65 | db.prepare('INSERT INTO orders(id,user_id,user_email,status,config,price_cents,pet_photo_urls,cart_reminders_sent,created_at,updated_at,stripe_session_id) VALUES (?,?,?,?,?,?,?,?,?,?,?)') |
| 66 | .run(id,'test-holder','synthetic@example.invalid',options.status || 'pending_payment',JSON.stringify(options.config || config),1200,'[]',0,initialTimestamp,initialTimestamp,sessionId); |
| 67 | db.prepare('INSERT INTO generations (id,order_id,prompt,model,clean_url,watermarked_url,published,created_at) VALUES (?,?,?,?,?,?,?,?)') |
| 68 | .run(generationId,id,'',flow,cleanUrl,cleanUrl,0,initialTimestamp); |
| 69 | db.prepare('UPDATE orders SET current_generation_id=? WHERE id=?').run(generationId,id); |
| 70 | artwork.set(id,binary); |
| 71 | const session = { |
| 72 | id:sessionId,object:'checkout.session',livemode:false,mode:'payment',status:'complete',payment_status:'paid', |
| 73 | payment_intent:'pi_testing_fixture', |
| 74 | amount_total:1284,amount_subtotal:1200,currency:'usd',automatic_tax:{enabled:true,status:'complete'}, |
| 75 | total_details:{amount_tax:84,amount_discount:0,amount_shipping:0}, |
| 76 | client_reference_id:id,metadata:{orderId:id,workflow:flow,generationId,configSha256,artworkSha256:sha256}, |
| 77 | collected_information:{shipping_details:{ |
| 78 | name:'Synthetic Person', |
| 79 | address:{line1:'123 Example Road',line2:null,postal_code:'10001',city:'New York',country:'US',state:'NY'}, |
| 80 | }}, |
| 81 | }; |
| 82 | return { id, session, generationId, cleanUrl }; |
| 83 | } |
| 84 | |
| 85 | (async()=>{ |
| 86 | const result = await esbuild.build({ |
| 87 | stdin:{contents:"export { POST } from './app/api/webhooks/stripe/route'; export * as protocol from './app/api/studio/print/protocol';",resolveDir:root,loader:'ts'}, |
| 88 | absWorkingDir:root, bundle:true, write:false, platform:'node',format:'cjs', |
| 89 | external:['server-only','stripe','sharp','next/server','@opennextjs/cloudflare','@/app/lib/email','@/app/lib/magic-link','@/app/lib/lumen-auth','./lumen-auth'], |
| 90 | }); |
| 91 | const bundled = new Module(path.join(root,'.studio-print-test.cjs'),module); |
| 92 | const oldLoad = Module._load; |
| 93 | Module._load = function(specifier){ |
| 94 | if (specifier === 'server-only') return {}; |
| 95 | if (specifier === '@opennextjs/cloudflare') return {getCloudflareContext:()=>({env:{ |
| 96 | COMMERCE_DB:binding, |
| 97 | REVIEW_PHOTOS:{get:async key=>{ |
| 98 | const bytes = artwork.get(key.split('/')[2]); |
| 99 | return !bytes ? null : {body:new Blob([bytes]).stream()}; |
| 100 | }}, |
| 101 | }})}; |
| 102 | if (specifier === '@/app/lib/lumen-auth' || specifier === './lumen-auth') return {authOrigin:()=>origin}; |
| 103 | if (specifier === '@/app/lib/email') return {sendEmail:async message=>{notifications.push(message)}}; |
| 104 | if (specifier === '@/app/lib/magic-link') return {generateMagicLink:async()=>null}; |
| 105 | if (specifier === 'stripe') return Stripe; |
| 106 | if (specifier === 'sharp') return sharp; |
| 107 | if (specifier === 'next/server') return nextServer; |
| 108 | return oldLoad.apply(this,arguments); |
| 109 | }; |
| 110 | bundled._compile(result.outputFiles[0].text, path.join(root,'.studio-print-test.cjs')); |
| 111 | const {POST,protocol} = bundled.exports; |
| 112 | process.env.STRIPE_WEBHOOK_SECRET = webhookSecret; |
| 113 | process.env.NEXT_PUBLIC_SITE_URL = origin; |
| 114 | let vendorReply; |
| 115 | global.fetch = async (url, init) => { |
| 116 | assert.equal(String(url), 'https://api.sandbox.prodigi.com/v4.0/Orders'); |
| 117 | assert.equal(init.method,'POST'); |
| 118 | assert.equal(new Headers(init.headers).get('x-api-key'),'fake-sandbox-key-no-remote-call'); |
| 119 | const body = JSON.parse(init.body); |
| 120 | printer.push(body); |
| 121 | const fixture = db.prepare('SELECT status,stripe_payment_intent_id FROM orders WHERE id=?').get(body.merchantReference); |
| 122 | assert.deepEqual({...fixture},{status:'fulfillment_submitting',stripe_payment_intent_id:'pi_testing_fixture'}); |
| 123 | if (vendorReply) return vendorReply(body); |
| 124 | return Response.json({outcome:'Created',order:{id:'ord_123456',merchantReference:body.merchantReference,idempotencyKey:body.idempotencyKey}}); |
| 125 | }; |
| 126 | function event(session, {type='checkout.session.completed', signature=true} = {}) { |
| 127 | const payload = JSON.stringify({id:'evt_mock',object:'event',livemode:false,type,data:{object:session}}); |
| 128 | const header = Stripe.webhooks.generateTestHeaderString({payload,secret:signature ? webhookSecret : 'bad_secret'}); |
| 129 | return POST(new Request(origin+'/api/webhooks/stripe',{method:'POST',headers:{'stripe-signature':header},body:payload})); |
| 130 | } |
| 131 | const row = id => db.prepare('SELECT status,prodigi_order_id,stripe_payment_intent_id FROM orders WHERE id=?').get(id); |
| 132 | reset(); |
| 133 | const valid = fixture(protocol); |
| 134 | assert.equal((await event(valid.session,{signature:false})).status,400); |
| 135 | assert.equal((await (await event({...valid.session,payment_status:'unpaid'})).json()).fulfillment,'waiting_for_payment'); |
| 136 | assert.equal((await (await event({...valid.session,id:'cs_test_aDifferentSession'})).json()).fulfillment,'ignored'); |
| 137 | assert.equal(row(valid.id).status,'pending_payment'); |
| 138 | assert.equal(printer.length,0); |
| 139 | assert.equal(notifications.length,0); |
| 140 | const duplicate = await Promise.all(Array.from({length:5},()=>event(valid.session,{type:'checkout.session.async_payment_succeeded'}))); |
| 141 | assert(duplicate.every(r=>r.status===200)); |
| 142 | const dispositions = await Promise.all(duplicate.map(r=>r.json())); |
| 143 | assert.equal(dispositions.filter(r=>r.fulfillment==='submitted').length,1); |
| 144 | assert.equal(dispositions.filter(r=>r.fulfillment==='already_processed').length,4); |
| 145 | assert.deepEqual({...row(valid.id)},{status:'in_production',prodigi_order_id:'ord_123456',stripe_payment_intent_id:'pi_testing_fixture'}); |
| 146 | assert.equal(printer.length,1); |
| 147 | assert.equal(printer[0].merchantReference,valid.id); |
| 148 | assert.equal(printer[0].idempotencyKey,valid.generationId); |
| 149 | assert.equal(printer[0].items[0].assets[0].url,valid.cleanUrl); |
| 150 | assert.equal(notifications.length,2); |
| 151 | |
| 152 | for (const tamper of [ |
| 153 | s=>{s.amount_total-=1}, |
| 154 | s=>{s.amount_subtotal-=1}, |
| 155 | s=>{s.currency='jpy'}, |
| 156 | s=>{s.client_reference_id='wrong-order'}, |
| 157 | s=>{s.metadata.generationId=randomUUID()}, |
| 158 | s=>{s.metadata.workflow='different'}, |
| 159 | s=>{s.collected_information=null}, |
| 160 | s=>{s.collected_information.shipping_details.address.country='GB'}, |
| 161 | ]) { |
| 162 | reset(); |
| 163 | const x=fixture(protocol); |
| 164 | tamper(x.session); |
| 165 | assert.equal((await (await event(x.session)).json()).fulfillment,'needs_review'); |
| 166 | assert.equal(row(x.id).status,'fulfillment_review'); |
| 167 | assert.equal(row(x.id).stripe_payment_intent_id,'pi_testing_fixture'); |
| 168 | assert.equal(printer.length,0); |
| 169 | } |
| 170 | |
| 171 | reset(); |
| 172 | const swapped = fixture(protocol); |
| 173 | artwork.set(swapped.id,Buffer.from('unexpected different file')); |
| 174 | assert.equal((await (await event(swapped.session)).json()).fulfillment,'needs_review'); |
| 175 | assert.equal(printer.length,0); |
| 176 | |
| 177 | reset(); |
| 178 | const snapshot = fixture(protocol); |
| 179 | db.prepare("UPDATE generations SET clean_url='https://wrong.invalid' WHERE id=?").run(snapshot.generationId); |
| 180 | assert.equal((await (await event(snapshot.session)).json()).fulfillment,'needs_review'); |
| 181 | assert.equal(printer.length,0); |
| 182 | |
| 183 | reset(); |
| 184 | const mismatch = fixture(protocol); |
| 185 | process.env.PRODIGI_API_BASE_URL = 'https://api.prodigi.com/v4.0/'; |
| 186 | assert.equal((await (await event(mismatch.session)).json()).fulfillment,'needs_review'); |
| 187 | assert.equal(printer.length,0); |
| 188 | |
| 189 | reset(); |
| 190 | const unknown = fixture(protocol); |
| 191 | vendorReply=()=>{throw Error('connection lost after accepted POST')}; |
| 192 | assert.equal((await (await event(unknown.session)).json()).fulfillment,'needs_review'); |
| 193 | assert.equal((await (await event(unknown.session)).json()).fulfillment,'already_processed'); |
| 194 | assert.equal(row(unknown.id).status,'fulfillment_review'); |
| 195 | assert.equal(printer.length,1); |
| 196 | assert.equal(notifications.length,1); |
| 197 | |
| 198 | reset(); |
| 199 | const onHold = fixture(protocol); |
| 200 | vendorReply=()=>Response.json({outcome:'OnHold',order:{id:'ord_42'}}); |
| 201 | assert.equal((await (await event(onHold.session)).json()).fulfillment,'needs_review'); |
| 202 | assert.equal(row(onHold.id).prodigi_order_id,'ord_42'); |
| 203 | assert.equal(printer.length,1); |
| 204 | |
| 205 | reset(); |
| 206 | const lostWrite = fixture(protocol); |
| 207 | vendorReply=body=>Response.json({outcome:'Created',order:{id:'ord_23',merchantReference:body.merchantReference,idempotencyKey:body.idempotencyKey}}); |
| 208 | unavailable='SET status=?, prodigi_order_id='; |
| 209 | assert.equal((await (await event(lostWrite.session)).json()).fulfillment,'needs_review'); |
| 210 | unavailable=''; |
| 211 | assert.equal(row(lostWrite.id).status,'fulfillment_submitting'); |
| 212 | assert.equal((await (await event(lostWrite.session)).json()).fulfillment,'already_processed'); |
| 213 | assert.equal(printer.length,1); |
| 214 | |
| 215 | reset(); |
| 216 | const prior = fixture(protocol,'lg_23456789ac',{status:'pending_design',config:{}}); |
| 217 | delete prior.session.metadata.workflow; |
| 218 | assert.match((await (await event(prior.session)).json()).ignored,/no action for status pending_design/); |
| 219 | assert.equal(printer.length,0); |
| 220 | console.log('Signed Stripe, D1 claim, product/asset, confirmation, duplicate, mismatch, vendor ambiguity and legacy regression tests passed.'); |
| 221 | })().catch(e=>{console.error(e);process.exitCode=1}); |