Branchwell

Lumen & Gesso / website · lumengesso.com / app / api / orders / route.ts

1import { NextResponse, type NextRequest } from 'next/server';
2import { physicalCheckoutEnabled, physicalCheckoutPausedMessage } from '@/app/lib/free-studio-checkout';
3import { commerceDb } from '@/app/lib/commerce-db';
4import { provisionCustomer } from '@/app/lib/lumen-auth';
5import { uploadImage } from '@/app/lib/cf-images';
6import { generateOrderId } from '@/app/lib/orders';
7import { priceCents, type ProductId, type Orientation } from '@/app/lib/pricing';
8import { validateUpload } from '@/app/lib/upload-limits';
9
10export const runtime = 'nodejs';
11export const dynamic = 'force-dynamic';
12export const maxDuration = 60;
13
14type Config = {
15 styleId: string;
16 productId: ProductId;
17 size: string;
18 // Portrait/landscape — persisted via the `...config` spread below and
19 // read back by generation, preview, and Prodigi. Doesn't affect price
20 // (same SKU + tier in both orientations). Optional so legacy orders
21 // without it parse fine.
22 orientation?: Orientation;
23 frame: string;
24 // Mat board colour, or 'nomat' (no mat → Classic Frame fulfilment +
25 // its own lower price). Optional so legacy orders parse; defaults to
26 // the mounted price when absent.
27 matteId?: string;
28 // Edge wrap for the frameless stretched canvas. Optional; ignored by
29 // framed products.
30 wrap?: string;
31 bgColorId: string;
32 bgCustom: string;
33 fontId: string;
34 includeName: boolean;
35 commissionName: string | null;
36};
37
38export async function POST(req: NextRequest) {
39 if (!physicalCheckoutEnabled()) {
40 return NextResponse.json({ error: physicalCheckoutPausedMessage, studio: '/studio' }, {
41 status: 503,
42 headers: { 'Cache-Control': 'no-store' },
43 });
44 }
45
46 let form: FormData;
47 try {
48 form = await req.formData();
49 } catch {
50 return NextResponse.json({ error: 'invalid form data' }, { status: 400 });
51 }
52
53 const email = String(form.get('email') ?? '').trim().toLowerCase();
54 const configRaw = String(form.get('config') ?? '');
55 if (!email || !/.+@.+\..+/.test(email)) {
56 return NextResponse.json({ error: 'valid email required' }, { status: 400 });
57 }
58
59 let config: Config;
60 try {
61 config = JSON.parse(configRaw);
62 } catch {
63 return NextResponse.json({ error: 'invalid config json' }, { status: 400 });
64 }
65
66 // Collect pet files and names by index.
67 const pets: { name: string; url?: string }[] = [];
68 for (let i = 0; i < 4; i++) {
69 const name = String(form.get(`pet_${i}_name`) ?? '').trim();
70 const file = form.get(`pet_${i}_file`);
71 if (file instanceof File && file.size > 0) {
72 pets.push({ name });
73 } else if (name) {
74 pets.push({ name });
75 }
76 }
77
78 const customStyleFile = form.get('custom_style_file');
79 const hasCustomStyle = customStyleFile instanceof File && customStyleFile.size > 0;
80
81 // Validate every uploaded image (JPG/PNG, ≤10MB) BEFORE creating the
82 // user or uploading anything — never trust the client-side check in
83 // ImageDrop. Fail fast with a 400 listing the offending file.
84 const uploadsToCheck: Array<{ label: string; file: unknown }> = [
85 { label: 'custom style reference', file: customStyleFile },
86 ];
87 for (let i = 0; i < 4; i++) uploadsToCheck.push({ label: `pet photo ${i + 1}`, file: form.get(`pet_${i}_file`) });
88 for (const { label, file } of uploadsToCheck) {
89 if (file instanceof File && file.size > 0) {
90 const err = validateUpload(file);
91 if (err) {
92 return NextResponse.json({ error: `${label}: ${err}` }, { status: 400 });
93 }
94 }
95 }
96
97 let userId: string;
98 try {
99 userId = await provisionCustomer(email);
100 } catch {
101 return NextResponse.json({ error: 'Could not set up the customer account. Please try again.' }, { status: 503 });
102 }
103
104 // Upload pet photos to CF Images. Each photo becomes a public URL the
105 // image-gen step (later) and Prodigi (much later) can pull.
106 const photoUrls: string[] = [];
107 try {
108 for (let i = 0; i < 4; i++) {
109 const file = form.get(`pet_${i}_file`);
110 if (!(file instanceof File) || file.size === 0) continue;
111 const { publicUrl } = await uploadImage(file, {
112 filename: file.name,
113 metadata: { kind: 'pet_photo', email, slot: String(i) },
114 });
115 photoUrls.push(publicUrl);
116 }
117 } catch (e) {
118 const msg = e instanceof Error ? e.message : String(e);
119 return NextResponse.json({ error: `photo upload failed: ${msg}` }, { status: 500 });
120 }
121
122 let customStyleUrl: string | null = null;
123 if (hasCustomStyle && customStyleFile instanceof File) {
124 try {
125 const { publicUrl } = await uploadImage(customStyleFile, {
126 filename: customStyleFile.name,
127 metadata: { kind: 'custom_style', email },
128 });
129 customStyleUrl = publicUrl;
130 } catch (e) {
131 const msg = e instanceof Error ? e.message : String(e);
132 return NextResponse.json({ error: `custom style upload failed: ${msg}` }, { status: 500 });
133 }
134 }
135
136 const orderId = generateOrderId();
137 // Sold at cost: the artwork is free, so extra pets and custom style
138 // references don't change the price (see pricing.ts).
139 const cents = priceCents(config.productId, config.size, config.matteId);
140
141 const { error: insertErr } = await commerceDb().from('orders').insert({
142 id: orderId,
143 user_id: userId,
144 user_email: email,
145 // Customer pays before we start the design (new flow). The webhook
146 // transitions this to 'pending_design' on checkout.session.completed
147 // and dispatches the magic-link email at that point.
148 status: 'pending_payment',
149 config: {
150 ...config,
151 pets: pets.map((p, i) => ({ slot: i, name: p.name })),
152 hasCustomStyle,
153 },
154 pet_photo_urls: photoUrls,
155 custom_style_url: customStyleUrl,
156 price_cents: cents,
157 });
158 if (insertErr) {
159 return NextResponse.json({ error: `order insert failed: ${insertErr.message}` }, { status: 500 });
160 }
161
162 // Magic link + welcome emails are deferred to the Stripe webhook —
163 // we only want to email a confirmation once payment succeeds, so the
164 // customer's inbox doesn't fill with "your order is pending" pings
165 // for abandoned checkout sessions.
166
167 return NextResponse.json({ orderId, email });
168}