Branchwell

Lumen & Gesso / website · lumengesso.com / app / checkout / LegacyCheckout.tsx

1'use client';
2
3import { Suspense, useEffect, useState } from 'react';
4import { useRouter, useSearchParams } from 'next/navigation';
5import { STYLE_CATALOG } from '../data/styleCatalog';
6import { BACKGROUND_COLORS } from '../data/backgrounds';
7import { PRODUCTS, salePrice, sizeLabel, type ProductId, type Orientation } from '../lib/pricing';
8import { getDraft, draftToFormData, uploadedCount, type Draft } from '../lib/draft-order';
9
10// /checkout — the page that takes over from the inline Submit form in
11// the Review step. Reads the in-memory draft order (set by Builder when
12// the customer clicked "Continue to payment"), shows the order summary,
13// collects email, and kicks off the Stripe Checkout Session.
14//
15// Refresh-safety: the draft lives in module memory, so a hard refresh
16// loses it. In that case we route the customer back to /builder, where
17// their saved state would (in a future refinement) be rehydrated. For
18// now, refresh = restart.
19//
20// Stripe-cancel return: Stripe's hosted checkout redirects the customer
21// back here with ?orderId=…&canceled=1 if they hit Cancel. That's a
22// full-page external navigation, so the in-memory draft is gone — but
23// the order row already exists on the server. We detect that case and
24// show a resume screen with a single "Resume payment" button that
25// re-mints a Stripe session from the existing orderId, instead of
26// bouncing them all the way back to pick-a-pet.
27// Persisted-order shape returned by GET /api/orders/[id]/summary —
28// just the fields the resume screen renders.
29type ResumeSummary = {
30 status: string;
31 config: {
32 styleId?: string;
33 productId?: ProductId;
34 size?: string;
35 orientation?: Orientation;
36 };
37 petPhotoUrls: string[];
38 customStyleUrl: string | null;
39 priceCents: number;
40};
41
42export default function LegacyCheckout() {
43 // useSearchParams() forces a CSR bailout, which Next 15 requires us
44 // to opt into with a Suspense boundary. The fallback is what static
45 // prerendering emits before client-side params resolve.
46 return (
47 <Suspense fallback={
48 <div className="checkout">
49 <div className="checkout__card">
50 <p>Loading your commission…</p>
51 </div>
52 </div>
53 }>
54 <CheckoutInner />
55 </Suspense>
56 );
57}
58
59function CheckoutInner() {
60 const router = useRouter();
61 const searchParams = useSearchParams();
62 // The resume screen serves two entry points that both arrive without the
63 // in-memory draft: Stripe's cancel redirect (?canceled=1) and the
64 // abandoned-cart reminder email (?resume=1). In both cases the order row
65 // already exists, so we re-mint a Stripe session from the orderId.
66 const isReminderResume = searchParams.get('resume') === '1';
67 const pendingOrderId =
68 searchParams.get('canceled') === '1' || isReminderResume
69 ? searchParams.get('orderId')
70 : null;
71
72 const [draft, setDraftLocal] = useState<Draft | null>(() => getDraft());
73 const [email, setEmail] = useState('');
74 const [submitting, setSubmitting] = useState(false);
75 const [error, setError] = useState<string | null>(null);
76 const [resuming, setResuming] = useState(false);
77
78 // When we land on the resume screen the in-memory draft is gone (the
79 // Stripe redirect / reminder email is a full-page navigation), so we
80 // fetch the persisted order to show the customer their saved photos
81 // and design instead of a bare "Resume payment" button.
82 const [summary, setSummary] = useState<ResumeSummary | null>(null);
83 const [summaryLoading, setSummaryLoading] = useState(false);
84 useEffect(() => {
85 if (draft || !pendingOrderId) return;
86 let cancelled = false;
87 setSummaryLoading(true);
88 fetch(`/api/orders/${encodeURIComponent(pendingOrderId)}/summary`)
89 .then((r) => (r.ok ? r.json() : null))
90 .then((data: ResumeSummary | null) => { if (!cancelled) setSummary(data); })
91 .catch(() => { /* leave summary null — the button-only screen still works */ })
92 .finally(() => { if (!cancelled) setSummaryLoading(false); });
93 return () => { cancelled = true; };
94 }, [draft, pendingOrderId]);
95
96 // "Make changes" → reopen the builder for this exact order. The builder
97 // reads ?edit=… and rehydrates the design + photos (see Builder.tsx),
98 // so nothing has to be re-uploaded. Clear the pending-order hint so the
99 // builder's own mount effect doesn't bounce us straight back here.
100 const makeChanges = () => {
101 try { sessionStorage.removeItem('lg_pending_order_id'); } catch {}
102 router.push(pendingOrderId ? `/builder?edit=${encodeURIComponent(pendingOrderId)}` : '/builder');
103 };
104
105 // If the draft is missing (hard refresh, deep-link), bounce back to
106 // the builder so the customer can re-enter their commission. Skip
107 // the bounce when we're handling a Stripe cancel: the order already
108 // exists server-side and we render a resume UI below.
109 useEffect(() => {
110 if (!draft && !pendingOrderId) router.replace('/builder');
111 }, [draft, pendingOrderId, router]);
112
113 const resumePayment = async () => {
114 if (!pendingOrderId) return;
115 setResuming(true);
116 setError(null);
117 try {
118 const sessionRes = await fetch(`/api/orders/${pendingOrderId}/checkout`, {
119 method: 'POST',
120 headers: { 'content-type': 'application/json' },
121 body: JSON.stringify({ termsAccepted: true }),
122 });
123 if (!sessionRes.ok) {
124 const data = await sessionRes.json().catch(() => null) as { error?: string } | null;
125 throw new Error(data?.error ?? `Checkout session failed (${sessionRes.status})`);
126 }
127 const { url } = await sessionRes.json() as { url: string };
128 window.location.href = url;
129 } catch (err) {
130 setError(err instanceof Error ? err.message : 'Resume failed');
131 setResuming(false);
132 }
133 };
134
135 if (!draft && pendingOrderId) {
136 const cfg = summary?.config ?? {};
137 const resumeStyle = STYLE_CATALOG.find((s) => s.id === cfg.styleId);
138 const resumeProduct = cfg.productId ? PRODUCTS[cfg.productId] : null;
139 const resumeSize = cfg.productId && cfg.size
140 ? sizeLabel(cfg.productId, cfg.size, cfg.orientation ?? 'portrait')
141 : null;
142 const photos = summary?.petPhotoUrls ?? [];
143 const priceDollars = summary ? Math.round(summary.priceCents / 100) : null;
144
145 return (
146 <div className="checkout">
147 <div className="checkout__card">
148 <h1 className="checkout__title">
149 {isReminderResume ? 'Your portrait is waiting' : 'Payment canceled'}
150 </h1>
151 <p className="checkout__sub">
152 No charge was made. Your photos and design are saved — pick up where
153 you left off, or make changes first.
154 </p>
155
156 {photos.length > 0 && (
157 <div className="resume__photos" aria-label="Your uploaded pet photos">
158 {photos.map((url, i) => (
159 // eslint-disable-next-line @next/next/no-img-element
160 <img key={i} src={url} alt={`Pet photo ${i + 1}`} className="resume__photo" />
161 ))}
162 </div>
163 )}
164
165 {summary && (
166 <div className="checkout__summary">
167 {resumeStyle && (
168 <div className="checkout__summary-row">
169 <span>Style</span><span>{resumeStyle.name}</span>
170 </div>
171 )}
172 {resumeProduct && resumeSize && (
173 <div className="checkout__summary-row">
174 <span>Product</span><span>{resumeProduct.label}, {resumeSize}</span>
175 </div>
176 )}
177 {photos.length > 0 && (
178 <div className="checkout__summary-row">
179 <span>Photos</span>
180 <span>{photos.length} {photos.length === 1 ? 'pet' : 'pets'}</span>
181 </div>
182 )}
183 {priceDollars != null && (
184 <div className="checkout__summary-row">
185 <span>Total</span><span>${priceDollars} <span className="ccy">USD</span></span>
186 </div>
187 )}
188 </div>
189 )}
190
191 {summaryLoading && !summary && (
192 <p className="checkout__sub" style={{ marginTop: 0 }}>Loading your commission…</p>
193 )}
194
195 <button
196 type="button"
197 className="btn btn--rose btn--lg btn--block"
198 onClick={resumePayment}
199 disabled={resuming}
200 >
201 {resuming ? 'Redirecting to payment…' : <>Resume payment <span aria-hidden="true">→</span></>}
202 </button>
203 {error && <p className="auth__error" style={{ margin: 0 }}>{error}</p>}
204
205 <p className="checkout__fineprint">
206 Secure payment via Stripe. By paying you agree to our{' '}
207 <a href="/terms" target="_blank" rel="noopener">commission terms</a> and{' '}
208 <a href="/refund-policy" target="_blank" rel="noopener">refund policy</a>.
209 </p>
210 <button
211 type="button"
212 className="btn btn--secondary btn--block"
213 onClick={makeChanges}
214 disabled={resuming}
215 style={{ marginTop: '0.75rem' }}
216 >
217 Make changes to my design
218 </button>
219 <p className="checkout__fineprint" style={{ marginTop: '0.5rem' }}>
220 Change the style, size, frame, background, or photos — your uploads
221 come with you, and nothing is charged until you complete payment.
222 </p>
223 </div>
224 </div>
225 );
226 }
227
228 if (!draft) {
229 return (
230 <div className="checkout">
231 <div className="checkout__card">
232 <p>Loading your commission…</p>
233 </div>
234 </div>
235 );
236 }
237
238 const style = STYLE_CATALOG.find((s) => s.id === draft.config.styleId);
239 const product = PRODUCTS[draft.config.productId];
240 // Orientation-aware label ('10 × 8 in' for landscape). No live framed
241 // preview on this fallback page — just the text summary.
242 const displaySizeLabel = sizeLabel(draft.config.productId, draft.config.size, draft.config.orientation ?? 'portrait');
243 const hasCustomStyle = !!draft.customStyle;
244 const photoCount = uploadedCount(draft);
245 // At cost: matches what /api/orders charges. Artwork is free, so pets
246 // and custom style references don't change the price.
247 const saleTotal = salePrice(draft.config.productId, draft.config.size, draft.config.matteId);
248
249 const onPay = async (e: React.FormEvent) => {
250 e.preventDefault();
251 if (!email.trim() || !/.+@.+\..+/.test(email)) {
252 setError('Enter a valid email.');
253 return;
254 }
255 setSubmitting(true);
256 setError(null);
257 try {
258 // 1. Create the order via the existing /api/orders endpoint —
259 // this uploads photos to CF Images, creates the user, inserts
260 // the order row. Returns { orderId, email }.
261 const orderRes = await fetch('/api/orders', {
262 method: 'POST',
263 body: draftToFormData(draft, email),
264 });
265 if (!orderRes.ok) {
266 const data = await orderRes.json().catch(() => null) as { error?: string } | null;
267 throw new Error(data?.error ?? `Order create failed (${orderRes.status})`);
268 }
269 const { orderId } = await orderRes.json() as { orderId: string };
270
271 // 2. Create the Stripe Checkout Session for this order, also
272 // records terms acceptance on the order row. Redirects the
273 // browser to the hosted Stripe page.
274 const sessionRes = await fetch(`/api/orders/${orderId}/checkout`, {
275 method: 'POST',
276 headers: { 'content-type': 'application/json' },
277 body: JSON.stringify({ email, termsAccepted: true }),
278 });
279 if (!sessionRes.ok) {
280 const data = await sessionRes.json().catch(() => null) as { error?: string } | null;
281 throw new Error(data?.error ?? `Checkout session failed (${sessionRes.status})`);
282 }
283 const { url } = await sessionRes.json() as { url: string };
284 window.location.href = url;
285 } catch (err) {
286 setError(err instanceof Error ? err.message : 'Submit failed');
287 setSubmitting(false);
288 }
289 };
290
291 const back = () => router.push('/builder');
292
293 return (
294 <div className="checkout">
295 <div className="checkout__card">
296 <button type="button" className="checkout__back" onClick={back}>
297 <span aria-hidden="true">←</span> Back to design
298 </button>
299 <h1 className="checkout__title">Confirm and pay</h1>
300 <p className="checkout__sub">
301 Your commission is saved. Pay now to send it into the studio queue —
302 we&rsquo;ll email your proof within one business day. Studio hours
303 are Monday–Friday; orders placed on a Friday arrive Monday.
304 </p>
305
306 <div className="checkout__summary">
307 <div className="checkout__summary-row">
308 <span>Style</span>
309 <span>{style?.name ?? draft.config.styleId}</span>
310 </div>
311 <div className="checkout__summary-row">
312 <span>Product</span>
313 <span>{product.label}, {displaySizeLabel}</span>
314 </div>
315 <div className="checkout__summary-row">
316 <span>Photos</span>
317 <span>
318 {photoCount} {photoCount === 1 ? 'pet' : 'pets'}
319 </span>
320 </div>
321 {draft.config.bgColorId && draft.config.bgColorId !== 'custom' && (
322 <div className="checkout__summary-row">
323 <span>Background</span>
324 <span>{BACKGROUND_COLORS[draft.config.bgColorId as keyof typeof BACKGROUND_COLORS]?.label ?? draft.config.bgColorId}</span>
325 </div>
326 )}
327 {hasCustomStyle && (
328 <div className="checkout__summary-row">
329 <span>Style reference</span>
330 <span>Attached · free</span>
331 </div>
332 )}
333 </div>
334
335 {/* The artwork is free and the print is at cost. */}
336 <ul className="summary__breakdown">
337 <li className="summary__breakdown-row">
338 <span>Portrait artwork</span>
339 <span>Free</span>
340 </li>
341 <li className="summary__breakdown-row">
342 <span>{product.label}, {displaySizeLabel}, at cost</span>
343 <span>${saleTotal}</span>
344 </li>
345 </ul>
346
347 <div className="checkout__pricerow">
348 <div>
349 <div className="checkout__pricelabel">
350 Total
351 </div>
352 <div className="checkout__price">
353 ${saleTotal}<span className="ccy">USD</span>
354 </div>
355 </div>
356 <div className="checkout__ships">
357 Ships in 10 days<br />Shipping included
358 </div>
359 </div>
360
361 <form className="checkout__form" onSubmit={onPay}>
362 <label className="checkout__label" htmlFor="checkout-email">
363 Email where we&rsquo;ll send your proof
364 </label>
365 <input
366 id="checkout-email"
367 type="email"
368 required
369 autoComplete="email"
370 placeholder="you@example.com"
371 value={email}
372 onChange={(e) => setEmail(e.target.value)}
373 className="auth__input"
374 disabled={submitting}
375 />
376
377 <button
378 type="submit"
379 className="btn btn--rose btn--lg btn--block"
380 disabled={submitting || !email.trim()}
381 >
382 {submitting ? 'Redirecting to payment…' : <>Continue to payment <span aria-hidden="true">→</span></>}
383 </button>
384 {error && <p className="auth__error" style={{ margin: 0 }}>{error}</p>}
385 <p className="checkout__fineprint">
386 Secure payment via Stripe. By paying you agree to our{' '}
387 <a href="/terms" target="_blank" rel="noopener">commission terms</a> and{' '}
388 <a href="/refund-policy" target="_blank" rel="noopener">refund policy</a>.
389 </p>
390 </form>
391 </div>
392 </div>
393 );
394}