@thorprovider/create-thor-app 4.1.9 → 4.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,395 @@
1
+ 'use client'
2
+
3
+ import React, { useEffect, useState } from 'react'
4
+ import { useRouter } from 'next/navigation'
5
+ import { useCart } from '@/components/providers/cart-provider'
6
+ import { useCommerce } from '@/components/providers/commerce-provider'
7
+ import type { ShippingMethod, PaymentMethod } from '@thorprovider/types'
8
+
9
+ type Step = 'address' | 'shipping' | 'payment' | 'confirm'
10
+
11
+ interface AddressForm {
12
+ firstName: string
13
+ lastName: string
14
+ email: string
15
+ address1: string
16
+ address2: string
17
+ city: string
18
+ province: string
19
+ postalCode: string
20
+ countryCode: string
21
+ phone: string
22
+ }
23
+
24
+ const EMPTY_ADDRESS: AddressForm = {
25
+ firstName: '',
26
+ lastName: '',
27
+ email: '',
28
+ address1: '',
29
+ address2: '',
30
+ city: '',
31
+ province: '',
32
+ postalCode: '',
33
+ countryCode: 'US',
34
+ phone: '',
35
+ }
36
+
37
+ export default function CheckoutPage() {
38
+ const { cart, items } = useCart()
39
+ const { commerce } = useCommerce()
40
+ const router = useRouter()
41
+
42
+ const [step, setStep] = useState<Step>('address')
43
+ const [address, setAddress] = useState<AddressForm>(EMPTY_ADDRESS)
44
+ const [shippingMethods, setShippingMethods] = useState<ShippingMethod[]>([])
45
+ const [selectedShippingId, setSelectedShippingId] = useState<string>('')
46
+ const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>([])
47
+ const [selectedPaymentId, setSelectedPaymentId] = useState<string>('')
48
+ const [loading, setLoading] = useState(false)
49
+ const [error, setError] = useState<string | null>(null)
50
+
51
+ const cartId = cart?.id
52
+
53
+ // Redirect to cart if empty
54
+ useEffect(() => {
55
+ if (items.length === 0) {
56
+ router.replace('/cart')
57
+ }
58
+ }, [items.length, router])
59
+
60
+ function updateAddress(field: keyof AddressForm, value: string) {
61
+ setAddress((prev) => ({ ...prev, [field]: value }))
62
+ }
63
+
64
+ async function handleAddressSubmit(e: React.FormEvent) {
65
+ e.preventDefault()
66
+ if (!cartId) return
67
+ setError(null)
68
+ setLoading(true)
69
+ try {
70
+ await commerce.updateShippingAddress?.(cartId, address)
71
+ const methods = await commerce.getShippingMethods(cartId)
72
+ setShippingMethods(methods)
73
+ if (methods[0]) setSelectedShippingId(methods[0].id)
74
+ setStep('shipping')
75
+ } catch (err: any) {
76
+ setError(err.message ?? 'Failed to save address. Please try again.')
77
+ } finally {
78
+ setLoading(false)
79
+ }
80
+ }
81
+
82
+ async function handleShippingSubmit(e: React.FormEvent) {
83
+ e.preventDefault()
84
+ if (!cartId || !selectedShippingId) return
85
+ setError(null)
86
+ setLoading(true)
87
+ try {
88
+ await commerce.addShippingMethod(cartId, selectedShippingId)
89
+ const methods = await commerce.getPaymentMethods({ cartId })
90
+ setPaymentMethods(methods)
91
+ if (methods[0]) setSelectedPaymentId(methods[0].id)
92
+ setStep('payment')
93
+ } catch (err: any) {
94
+ setError(err.message ?? 'Failed to set shipping method.')
95
+ } finally {
96
+ setLoading(false)
97
+ }
98
+ }
99
+
100
+ async function handlePaymentSubmit(e: React.FormEvent) {
101
+ e.preventDefault()
102
+ if (!cartId || !selectedPaymentId) return
103
+ setError(null)
104
+ setLoading(true)
105
+ try {
106
+ await commerce.initiatePaymentSession(cartId, selectedPaymentId)
107
+ setStep('confirm')
108
+ } catch (err: any) {
109
+ setError(err.message ?? 'Failed to initiate payment.')
110
+ } finally {
111
+ setLoading(false)
112
+ }
113
+ }
114
+
115
+ async function handlePlaceOrder() {
116
+ if (!cartId) return
117
+ setError(null)
118
+ setLoading(true)
119
+ try {
120
+ const order = await commerce.completeCheckout(cartId)
121
+ router.push(`/checkout/success?orderId=${order.id}&orderNumber=${order.orderNumber}`)
122
+ } catch (err: any) {
123
+ setError(err.message ?? 'Failed to place order.')
124
+ setLoading(false)
125
+ }
126
+ }
127
+
128
+ return (
129
+ <main className="container mx-auto max-w-lg px-4 py-8">
130
+ <h1 className="mb-6 text-2xl font-bold">Checkout</h1>
131
+
132
+ {/* Step indicator */}
133
+ <div className="mb-8 flex gap-2 text-sm">
134
+ {(['address', 'shipping', 'payment', 'confirm'] as Step[]).map((s, i) => (
135
+ <React.Fragment key={s}>
136
+ <span
137
+ className={
138
+ step === s
139
+ ? 'font-semibold text-foreground'
140
+ : 'text-muted-foreground'
141
+ }
142
+ >
143
+ {s.charAt(0).toUpperCase() + s.slice(1)}
144
+ </span>
145
+ {i < 3 && <span className="text-muted-foreground">›</span>}
146
+ </React.Fragment>
147
+ ))}
148
+ </div>
149
+
150
+ {error && (
151
+ <div className="mb-4 rounded-lg border border-destructive bg-destructive/10 px-4 py-3 text-sm text-destructive">
152
+ {error}
153
+ </div>
154
+ )}
155
+
156
+ {/* Step: Address */}
157
+ {step === 'address' && (
158
+ <form className="flex flex-col gap-4" onSubmit={handleAddressSubmit}>
159
+ <div className="grid grid-cols-2 gap-3">
160
+ <Field
161
+ label="First name"
162
+ onChange={(v) => updateAddress('firstName', v)}
163
+ required
164
+ value={address.firstName}
165
+ />
166
+ <Field
167
+ label="Last name"
168
+ onChange={(v) => updateAddress('lastName', v)}
169
+ required
170
+ value={address.lastName}
171
+ />
172
+ </div>
173
+ <Field
174
+ label="Email"
175
+ onChange={(v) => updateAddress('email', v)}
176
+ required
177
+ type="email"
178
+ value={address.email}
179
+ />
180
+ <Field
181
+ label="Address"
182
+ onChange={(v) => updateAddress('address1', v)}
183
+ required
184
+ value={address.address1}
185
+ />
186
+ <Field
187
+ label="Apt, suite, etc. (optional)"
188
+ onChange={(v) => updateAddress('address2', v)}
189
+ value={address.address2}
190
+ />
191
+ <div className="grid grid-cols-2 gap-3">
192
+ <Field
193
+ label="City"
194
+ onChange={(v) => updateAddress('city', v)}
195
+ required
196
+ value={address.city}
197
+ />
198
+ <Field
199
+ label="State / Province"
200
+ onChange={(v) => updateAddress('province', v)}
201
+ required
202
+ value={address.province}
203
+ />
204
+ </div>
205
+ <div className="grid grid-cols-2 gap-3">
206
+ <Field
207
+ label="Postal code"
208
+ onChange={(v) => updateAddress('postalCode', v)}
209
+ required
210
+ value={address.postalCode}
211
+ />
212
+ <Field
213
+ label="Country code"
214
+ onChange={(v) => updateAddress('countryCode', v)}
215
+ maxLength={2}
216
+ placeholder="US"
217
+ required
218
+ value={address.countryCode}
219
+ />
220
+ </div>
221
+ <Field
222
+ label="Phone"
223
+ onChange={(v) => updateAddress('phone', v)}
224
+ type="tel"
225
+ value={address.phone}
226
+ />
227
+ <SubmitButton disabled={loading} label="Continue to shipping" loading={loading} />
228
+ </form>
229
+ )}
230
+
231
+ {/* Step: Shipping */}
232
+ {step === 'shipping' && (
233
+ <form className="flex flex-col gap-4" onSubmit={handleShippingSubmit}>
234
+ <p className="text-sm text-muted-foreground">Select a shipping method</p>
235
+ {shippingMethods.length === 0 && (
236
+ <p className="text-sm text-muted-foreground">No shipping methods available.</p>
237
+ )}
238
+ {shippingMethods.map((method) => (
239
+ <label
240
+ className={`flex cursor-pointer items-start gap-3 rounded-xl border p-4 transition-colors ${
241
+ selectedShippingId === method.id ? 'border-primary bg-primary/5' : ''
242
+ }`}
243
+ key={method.id}
244
+ >
245
+ <input
246
+ checked={selectedShippingId === method.id}
247
+ className="mt-1"
248
+ name="shipping"
249
+ onChange={() => setSelectedShippingId(method.id)}
250
+ type="radio"
251
+ value={method.id}
252
+ />
253
+ <div className="flex-1">
254
+ <p className="font-medium">{method.name}</p>
255
+ {method.description && (
256
+ <p className="text-sm text-muted-foreground">{method.description}</p>
257
+ )}
258
+ {method.estimatedDays && (
259
+ <p className="text-sm text-muted-foreground">{method.estimatedDays}</p>
260
+ )}
261
+ </div>
262
+ <p className="font-medium">
263
+ {parseFloat(method.price.amount) === 0
264
+ ? 'Free'
265
+ : `${method.price.currencyCode} ${method.price.amount}`}
266
+ </p>
267
+ </label>
268
+ ))}
269
+ <SubmitButton
270
+ disabled={loading || !selectedShippingId}
271
+ label="Continue to payment"
272
+ loading={loading}
273
+ />
274
+ </form>
275
+ )}
276
+
277
+ {/* Step: Payment */}
278
+ {step === 'payment' && (
279
+ <form className="flex flex-col gap-4" onSubmit={handlePaymentSubmit}>
280
+ <p className="text-sm text-muted-foreground">Select a payment method</p>
281
+ {paymentMethods.length === 0 && (
282
+ <p className="text-sm text-muted-foreground">No payment methods available.</p>
283
+ )}
284
+ {paymentMethods.map((method) => (
285
+ <label
286
+ className={`flex cursor-pointer items-start gap-3 rounded-xl border p-4 transition-colors ${
287
+ selectedPaymentId === method.id ? 'border-primary bg-primary/5' : ''
288
+ }`}
289
+ key={method.id}
290
+ >
291
+ <input
292
+ checked={selectedPaymentId === method.id}
293
+ className="mt-1"
294
+ name="payment"
295
+ onChange={() => setSelectedPaymentId(method.id)}
296
+ type="radio"
297
+ value={method.id}
298
+ />
299
+ <p className="font-medium">{method.name}</p>
300
+ </label>
301
+ ))}
302
+ <SubmitButton
303
+ disabled={loading || !selectedPaymentId}
304
+ label="Review order"
305
+ loading={loading}
306
+ />
307
+ </form>
308
+ )}
309
+
310
+ {/* Step: Confirm */}
311
+ {step === 'confirm' && (
312
+ <div className="flex flex-col gap-6">
313
+ <div className="rounded-xl border bg-card p-4">
314
+ <p className="font-semibold">Shipping to</p>
315
+ <p className="mt-1 text-sm text-muted-foreground">
316
+ {address.firstName} {address.lastName}
317
+ <br />
318
+ {address.address1}
319
+ {address.address2 && `, ${address.address2}`}
320
+ <br />
321
+ {address.city}, {address.province} {address.postalCode}
322
+ <br />
323
+ {address.countryCode}
324
+ </p>
325
+ </div>
326
+ <button
327
+ className="rounded-lg bg-primary px-6 py-3 text-sm font-semibold text-primary-foreground disabled:opacity-50"
328
+ disabled={loading}
329
+ onClick={handlePlaceOrder}
330
+ type="button"
331
+ >
332
+ {loading ? 'Placing order…' : 'Place order'}
333
+ </button>
334
+ </div>
335
+ )}
336
+ </main>
337
+ )
338
+ }
339
+
340
+ /** Minimal labeled input to reduce repetition */
341
+ function Field({
342
+ label,
343
+ value,
344
+ onChange,
345
+ required,
346
+ type = 'text',
347
+ placeholder,
348
+ maxLength,
349
+ }: {
350
+ label: string
351
+ value: string
352
+ onChange: (v: string) => void
353
+ required?: boolean
354
+ type?: string
355
+ placeholder?: string
356
+ maxLength?: number
357
+ }) {
358
+ return (
359
+ <div className="flex flex-col gap-1">
360
+ <label className="text-sm font-medium">
361
+ {label}
362
+ {required && <span className="text-destructive"> *</span>}
363
+ </label>
364
+ <input
365
+ className="rounded-md border bg-background px-3 py-2 text-sm placeholder:text-muted-foreground"
366
+ maxLength={maxLength}
367
+ onChange={(e) => onChange(e.target.value)}
368
+ placeholder={placeholder}
369
+ required={required}
370
+ type={type}
371
+ value={value}
372
+ />
373
+ </div>
374
+ )
375
+ }
376
+
377
+ function SubmitButton({
378
+ label,
379
+ loading,
380
+ disabled,
381
+ }: {
382
+ label: string
383
+ loading: boolean
384
+ disabled: boolean
385
+ }) {
386
+ return (
387
+ <button
388
+ className="mt-2 rounded-lg bg-primary px-6 py-3 text-sm font-semibold text-primary-foreground disabled:opacity-50"
389
+ disabled={disabled}
390
+ type="submit"
391
+ >
392
+ {loading ? 'Loading…' : label}
393
+ </button>
394
+ )
395
+ }
@@ -0,0 +1,43 @@
1
+ import React from 'react'
2
+ import Link from 'next/link'
3
+ import type { Metadata } from 'next'
4
+
5
+ export const metadata: Metadata = {
6
+ title: 'Order confirmed',
7
+ }
8
+
9
+ interface SuccessPageProps {
10
+ searchParams: Promise<{ orderId?: string; orderNumber?: string }>
11
+ }
12
+
13
+ export default async function CheckoutSuccessPage({ searchParams }: SuccessPageProps) {
14
+ const { orderId, orderNumber } = await searchParams
15
+
16
+ return (
17
+ <main className="container mx-auto max-w-lg px-4 py-16 text-center">
18
+ <div className="flex flex-col items-center gap-6">
19
+ <div className="flex h-16 w-16 items-center justify-center rounded-full bg-primary/10 text-3xl">
20
+ ✓
21
+ </div>
22
+ <div>
23
+ <h1 className="text-2xl font-bold">Order confirmed!</h1>
24
+ {orderNumber && (
25
+ <p className="mt-1 text-muted-foreground">Order #{orderNumber}</p>
26
+ )}
27
+ {orderId && !orderNumber && (
28
+ <p className="mt-1 font-mono text-sm text-muted-foreground">{orderId}</p>
29
+ )}
30
+ </div>
31
+ <p className="text-muted-foreground">
32
+ Thank you for your purchase. You&apos;ll receive a confirmation email shortly.
33
+ </p>
34
+ <Link
35
+ className="rounded-lg bg-primary px-6 py-3 text-sm font-semibold text-primary-foreground"
36
+ href="/"
37
+ >
38
+ Continue shopping
39
+ </Link>
40
+ </div>
41
+ </main>
42
+ )
43
+ }
@@ -4,15 +4,12 @@ import { Inter } from 'next/font/google'
4
4
  import { AppProviders } from '@/components/providers/app-providers'
5
5
  import type { CommerceClientConfig } from '@/lib/commerce-client'
6
6
  import { getConfiguredProvider, shouldUseMockProvider } from '@/lib/env'
7
+ import { commerce } from '@/lib/commerce'
8
+ import { accentColorToOklch } from '@/lib/theme'
7
9
  import './globals.css'
8
10
 
9
11
  const inter = Inter({ subsets: ['latin'], variable: '--font-inter' })
10
12
 
11
- export const metadata: Metadata = {
12
- title: 'My Store | Powered by Thor Commerce',
13
- description: 'An e-commerce store built with Thor Commerce.',
14
- }
15
-
16
13
  /**
17
14
  * Root Layout — async Server Component.
18
15
  *
@@ -20,7 +17,23 @@ export const metadata: Metadata = {
20
17
  * serializable CommerceClientConfig, and injects it into the client
21
18
  * provider tree. This prevents build-time inlining of undefined values
22
19
  * in V0's preview sandbox.
20
+ *
21
+ * Also fetches StorefrontConfig from the backend (gracefully degrading
22
+ * when the plugin is not installed) to apply dynamic metadata and theme.
23
23
  */
24
+
25
+ export async function generateMetadata(): Promise<Metadata> {
26
+ const config = await commerce.getStorefrontConfig?.().catch(() => null) ?? null
27
+ return {
28
+ title: config?.seoDefaults?.title ?? 'My Store | Powered by Thor Commerce',
29
+ description:
30
+ config?.seoDefaults?.description ?? 'An e-commerce store built with Thor Commerce.',
31
+ openGraph: config?.seoDefaults?.ogImage
32
+ ? { images: [{ url: config.seoDefaults.ogImage }] }
33
+ : undefined,
34
+ }
35
+ }
36
+
24
37
  export default async function RootLayout({
25
38
  children,
26
39
  }: Readonly<{
@@ -29,18 +42,29 @@ export default async function RootLayout({
29
42
  const rawProvider = getConfiguredProvider()
30
43
  const isMock = shouldUseMockProvider()
31
44
 
45
+ // Fetch StorefrontConfig — optional plugin; silently falls back if unavailable
46
+ const storefrontConfig = await commerce.getStorefrontConfig?.().catch(() => null) ?? null
47
+ const accentColor = storefrontConfig?.themeAccentColor
48
+ ? accentColorToOklch(storefrontConfig.themeAccentColor)
49
+ : undefined
50
+
32
51
  const commerceConfig: CommerceClientConfig = {
33
52
  provider: rawProvider === 'custom' ? 'mock' : rawProvider,
34
53
  baseUrl: process.env.NEXT_PUBLIC_COMMERCE_API_URL ?? '',
35
54
  apiKey: process.env.NEXT_PUBLIC_COMMERCE_API_KEY ?? '',
36
- currencyCode: process.env.NEXT_PUBLIC_DEFAULT_CURRENCY ?? 'USD',
55
+ currencyCode:
56
+ storefrontConfig?.currencyCode ?? process.env.NEXT_PUBLIC_DEFAULT_CURRENCY ?? 'USD',
37
57
  salesChannelId: process.env.NEXT_PUBLIC_SALES_CHANNEL_ID,
38
58
  siteUrl: process.env.NEXT_PUBLIC_SITE_URL,
39
59
  isMock,
40
60
  }
41
61
 
42
62
  return (
43
- <html lang="en" suppressHydrationWarning>
63
+ <html
64
+ lang="en"
65
+ style={accentColor ? ({ '--accent-color': accentColor } as React.CSSProperties) : undefined}
66
+ suppressHydrationWarning
67
+ >
44
68
  <body className={`${inter.variable} font-sans antialiased`}>
45
69
  <AppProviders commerceConfig={commerceConfig}>
46
70
  {children}
@@ -0,0 +1,85 @@
1
+ 'use client'
2
+
3
+ import React, { useState } from 'react'
4
+ import { useCart } from '@/components/providers/cart-provider'
5
+ import type { Product, ProductVariant } from '@thorprovider/types'
6
+
7
+ interface AddToCartButtonProps {
8
+ product: Product
9
+ }
10
+
11
+ export function AddToCartButton({ product }: AddToCartButtonProps) {
12
+ const { addItem, isLoading } = useCart()
13
+ const [selectedVariantId, setSelectedVariantId] = useState<string>(
14
+ product.variants[0]?.id ?? '',
15
+ )
16
+ const [quantity, setQuantity] = useState(1)
17
+ const [added, setAdded] = useState(false)
18
+
19
+ const selectedVariant: ProductVariant | undefined = product.variants.find(
20
+ (v) => v.id === selectedVariantId,
21
+ )
22
+
23
+ const unavailable = !selectedVariant?.availableForSale
24
+
25
+ async function handleAddToCart() {
26
+ if (!selectedVariantId || unavailable) return
27
+ await addItem(selectedVariantId, quantity)
28
+ setAdded(true)
29
+ setTimeout(() => setAdded(false), 2000)
30
+ }
31
+
32
+ return (
33
+ <div className="flex flex-col gap-4">
34
+ {product.variants.length > 1 && (
35
+ <div className="flex flex-col gap-1">
36
+ <label className="text-sm font-medium" htmlFor="variant-select">
37
+ Variant
38
+ </label>
39
+ <select
40
+ className="rounded-md border bg-background px-3 py-2 text-sm"
41
+ id="variant-select"
42
+ onChange={(e) => setSelectedVariantId(e.target.value)}
43
+ value={selectedVariantId}
44
+ >
45
+ {product.variants.map((v) => (
46
+ <option disabled={!v.availableForSale} key={v.id} value={v.id}>
47
+ {v.title}
48
+ {!v.availableForSale ? ' — Out of stock' : ''}
49
+ </option>
50
+ ))}
51
+ </select>
52
+ </div>
53
+ )}
54
+
55
+ <div className="flex items-center gap-2">
56
+ <label className="text-sm font-medium" htmlFor="quantity-input">
57
+ Qty
58
+ </label>
59
+ <input
60
+ className="w-16 rounded-md border bg-background px-3 py-2 text-sm"
61
+ id="quantity-input"
62
+ min={1}
63
+ onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value, 10) || 1))}
64
+ type="number"
65
+ value={quantity}
66
+ />
67
+ </div>
68
+
69
+ <button
70
+ className="rounded-lg bg-primary px-6 py-3 text-sm font-semibold text-primary-foreground transition-opacity disabled:opacity-50"
71
+ disabled={isLoading || unavailable}
72
+ onClick={handleAddToCart}
73
+ type="button"
74
+ >
75
+ {isLoading
76
+ ? 'Adding…'
77
+ : added
78
+ ? 'Added to cart!'
79
+ : unavailable
80
+ ? 'Out of stock'
81
+ : 'Add to cart'}
82
+ </button>
83
+ </div>
84
+ )
85
+ }