|
1
|
--- |
|
2
|
sidebar_label: "Storefront Customizations" |
|
3
|
tags: |
|
4
|
- name: nextjs |
|
5
|
label: Ticket Booking Storefront |
|
6
|
- tutorial |
|
7
|
products: |
|
8
|
- product |
|
9
|
- cart |
|
10
|
- order |
|
11
|
--- |
|
12
|
|
|
13
|
import { Prerequisites } from "docs-ui" |
|
14
|
|
|
15
|
export const metadata = { |
|
16
|
title: `Customize Storefront for Ticket Booking`, |
|
17
|
} |
|
18
|
|
|
19
|
# {metadata.title} |
|
20
|
|
|
21
|
In this tutorial, you'll customize the Next.js Starter Storefront based on the [Ticket Booking system](../page.mdx) you implemented in the backend. |
|
22
|
|
|
23
|
<Prerequisites |
|
24
|
items={[ |
|
25
|
{ |
|
26
|
text: "Medusa backend with ticket booking functionality", |
|
27
|
link: "../page.mdx", |
|
28
|
}, |
|
29
|
{ |
|
30
|
text: "Next.js Starter Storefront", |
|
31
|
link: "../../../..//nextjs-starter/page.mdx", |
|
32
|
} |
|
33
|
]} |
|
34
|
/> |
|
35
|
|
|
36
|
## Summary |
|
37
|
|
|
38
|
In this tutorial, you'll customize the [Next.js Starter Storefront](../../../..//nextjs-starter/page.mdx) to support ticket booking: |
|
39
|
|
|
40
|
1. **Product Page**: Allow customers to choose a show date, select seats from a seating layout, and add tickets to the cart. |
|
41
|
2. **Cart Page**: Display selected tickets with their seat numbers and show dates, and remove quantity controls for ticket items. |
|
42
|
3. **Checkout Page**: Remove the shipping steps and complete the cart using the custom complete cart API route you created earlier. |
|
43
|
4. **Order Confirmation Page**: Display ticket details for ticket items. |
|
44
|
|
|
45
|
 |
|
46
|
|
|
47
|
<Note title="Reminder" forceMultiline> |
|
48
|
|
|
49
|
If you installed the Next.js Starter Storefront with the Medusa backend, the storefront was installed in a separate directory. The directory's name is `{your-project}-storefront`. |
|
50
|
|
|
51
|
So, if your Medusa application's directory is `medusa-ticketing`, you can find the storefront by going back to the parent directory and changing to the `medusa-ticketing-storefront` directory: |
|
52
|
|
|
53
|
```bash |
|
54
|
cd ../medusa-ticketing-storefront # change based on your project name |
|
55
|
``` |
|
56
|
|
|
57
|
</Note> |
|
58
|
|
|
59
|
## Step 1: Ticket Product Utilities |
|
60
|
|
|
61
|
Before you customize the storefront, you'll create some types and utility functions that you'll use in your customizations. |
|
62
|
|
|
63
|
Create the file `src/lib/util/ticket-product.ts` with the following content: |
|
64
|
|
|
65
|
```ts title="src/lib/util/ticket-product.ts" |
|
66
|
import { HttpTypes } from "@medusajs/types" |
|
67
|
|
|
68
|
export interface TicketProductAvailability { |
|
69
|
date: string |
|
70
|
row_types: { |
|
71
|
row_type: string |
|
72
|
total_seats: number |
|
73
|
available_seats: number |
|
74
|
sold_out: boolean |
|
75
|
}[] |
|
76
|
sold_out: boolean |
|
77
|
} |
|
78
|
|
|
79
|
export interface TicketProduct { |
|
80
|
id: string |
|
81
|
product_id: string |
|
82
|
venue: { |
|
83
|
id: string |
|
84
|
name: string |
|
85
|
address: string |
|
86
|
rows: Array<{ |
|
87
|
id: string |
|
88
|
row_number: string |
|
89
|
row_type: string |
|
90
|
seat_count: number |
|
91
|
}> |
|
92
|
} |
|
93
|
dates: string[] |
|
94
|
} |
|
95
|
|
|
96
|
export interface TicketProductAvailabilityData { |
|
97
|
ticket_product: TicketProduct |
|
98
|
availability: TicketProductAvailability[] |
|
99
|
} |
|
100
|
|
|
101
|
export interface TicketProductSeatsData { |
|
102
|
venue: { |
|
103
|
id: string |
|
104
|
name: string |
|
105
|
address: string |
|
106
|
rows: Array<{ |
|
107
|
id: string |
|
108
|
row_number: string |
|
109
|
row_type: string |
|
110
|
seat_count: number |
|
111
|
}> |
|
112
|
} |
|
113
|
date: string |
|
114
|
seat_map: { |
|
115
|
row_number: string |
|
116
|
row_type: string |
|
117
|
seats: { |
|
118
|
number: string |
|
119
|
is_purchased: boolean |
|
120
|
variant_id: string | null |
|
121
|
}[] |
|
122
|
}[] |
|
123
|
} |
|
124
|
|
|
125
|
/** |
|
126
|
* Check if a product is a ticket product by looking for the ticket_product property |
|
127
|
*/ |
|
128
|
export function isTicketProduct(product: HttpTypes.StoreProduct): boolean { |
|
129
|
return !!(product as any).ticket_product |
|
130
|
} |
|
131
|
``` |
|
132
|
|
|
133
|
You define types for the ticket product availability and seating layout API responses, as well as a utility function to check if a product is a ticket product. |
|
134
|
|
|
135
|
--- |
|
136
|
|
|
137
|
## Step 2: Support Adding Items to Cart with Metadata |
|
138
|
|
|
139
|
Next, you'll add support for adding items to the cart with metadata. This is necessary because when adding tickets to the cart, you need to include metadata such as the seat number and show date. |
|
140
|
|
|
141
|
This functionality is supported by the Medusa APIs, but you need to update the `addToCart` function in the storefront to accept and send metadata. |
|
142
|
|
|
143
|
In `src/lib/data/cart.ts`, find the `addToCart` function and update its object parameter to include an optional `metadata` property: |
|
144
|
|
|
145
|
```ts title="src/lib/data/cart.ts" highlights={[["3"], ["6"]]} |
|
146
|
export async function addToCart({ |
|
147
|
// ... |
|
148
|
metadata, |
|
149
|
}: { |
|
150
|
// ... |
|
151
|
metadata?: Record<string, any> |
|
152
|
}) { |
|
153
|
// ... |
|
154
|
} |
|
155
|
``` |
|
156
|
|
|
157
|
Then, find the `sdk.store.cart.createLineItem` method usage and pass the `metadata` property to it: |
|
158
|
|
|
159
|
```ts title="src/lib/data/cart.ts" highlights={[["6"]]} |
|
160
|
await sdk.store.cart |
|
161
|
.createLineItem( |
|
162
|
cart.id, |
|
163
|
{ |
|
164
|
// ... |
|
165
|
metadata, |
|
166
|
} |
|
167
|
// ... |
|
168
|
) |
|
169
|
``` |
|
170
|
|
|
171
|
Now, the `addToCart` function accepts an optional `metadata` property and sends it to the Medusa backend when creating a line item. |
|
172
|
|
|
173
|
--- |
|
174
|
|
|
175
|
## Step 3: Customize Product Page |
|
176
|
|
|
177
|
Next, you'll customize the product page. This includes: |
|
178
|
|
|
179
|
- Creating a component that displays a calendar to choose a show date, with available dates determined by the availability API route you created earlier. |
|
180
|
- Creating a component that displays a seat chart in a modal to select seats, with purchased seats determined by the seating layout API route you created earlier. |
|
181
|
- Customizing the product page to use the above components. |
|
182
|
|
|
183
|
### Date Selector Component |
|
184
|
|
|
185
|
The date selector component will fetch the available dates for a ticket product using the API route you created in the [backend part of the tutorial](../page.mdx#a-available-dates-api-route). Before creating the component, you'll add a server function to fetch the available dates. |
|
186
|
|
|
187
|
Create the file `src/lib/data/ticket-products.ts` with the following content: |
|
188
|
|
|
189
|
```ts title="src/lib/data/ticket-products.ts" |
|
190
|
"use server" |
|
191
|
|
|
192
|
import { sdk } from "@lib/config" |
|
193
|
import { getAuthHeaders, getCacheOptions } from "./cookies" |
|
194
|
import { TicketProductAvailabilityData } from "@lib/util/ticket-product" |
|
195
|
|
|
196
|
export const getTicketProductAvailability = async ( |
|
197
|
productId: string |
|
198
|
): Promise<TicketProductAvailabilityData> => { |
|
199
|
const headers = { |
|
200
|
...(await getAuthHeaders()), |
|
201
|
} |
|
202
|
|
|
203
|
const next = { |
|
204
|
...(await getCacheOptions("ticket-products")), |
|
205
|
} |
|
206
|
|
|
207
|
return sdk.client |
|
208
|
.fetch<TicketProductAvailabilityData>( |
|
209
|
`/store/ticket-products/${productId}/availability`, |
|
210
|
{ |
|
211
|
method: "GET", |
|
212
|
headers, |
|
213
|
next, |
|
214
|
cache: "no-store", // Always fetch fresh data for availability |
|
215
|
} |
|
216
|
) |
|
217
|
.then((data) => data) |
|
218
|
} |
|
219
|
``` |
|
220
|
|
|
221
|
You create a server function `getTicketProductAvailability` that fetches the available dates for a ticket product using the `/store/ticket-products/{id}/availability` API route. |
|
222
|
|
|
223
|
Next, you'll create the date selector component. It will show an input to select the number of tickets and a calendar to select a date. |
|
224
|
|
|
225
|
 |
|
226
|
|
|
227
|
Create the file `src/modules/products/components/ticket-product-layout/date-quantity-selection.tsx` with the following content: |
|
228
|
|
|
229
|
```tsx title="src/modules/products/components/ticket-product-layout/date-quantity-selection.tsx" collapsibleLines="1-9" expandButtonLabel="Show Imports" |
|
230
|
"use client" |
|
231
|
|
|
232
|
import { getTicketProductAvailability } from "@lib/data/ticket-products" |
|
233
|
import { TicketProductAvailability } from "@lib/util/ticket-product" |
|
234
|
import { HttpTypes } from "@medusajs/types" |
|
235
|
import { Button, Calendar, Label, IconButton, toast } from "@medusajs/ui" |
|
236
|
import { Minus, Plus } from "@medusajs/icons" |
|
237
|
import { useState, useEffect } from "react" |
|
238
|
|
|
239
|
type TicketDateSelectionProps = { |
|
240
|
product: HttpTypes.StoreProduct |
|
241
|
onDateSelect: (date: string, nbOfTickets: number) => void |
|
242
|
disabled?: boolean |
|
243
|
} |
|
244
|
|
|
245
|
export default function TicketDateSelection({ |
|
246
|
product, |
|
247
|
onDateSelect, |
|
248
|
disabled = false, |
|
249
|
}: TicketDateSelectionProps) { |
|
250
|
const [nbOfTickets, setNbOfTickets] = useState(1) |
|
251
|
const [selectedDate, setSelectedDate] = useState<Date | null>(null) |
|
252
|
const [availability, setAvailability] = useState<TicketProductAvailability[]>([]) |
|
253
|
const [isLoading, setIsLoading] = useState(false) |
|
254
|
|
|
255
|
// Load availability data on mount |
|
256
|
useEffect(() => { |
|
257
|
const loadAvailability = async () => { |
|
258
|
setIsLoading(true) |
|
259
|
try { |
|
260
|
const data = await getTicketProductAvailability(product.id) |
|
261
|
setAvailability(data.availability) |
|
262
|
} catch (error) { |
|
263
|
toast.error("Failed to load ticket availability: " + error) |
|
264
|
} finally { |
|
265
|
setIsLoading(false) |
|
266
|
} |
|
267
|
} |
|
268
|
|
|
269
|
loadAvailability() |
|
270
|
}, [product.id]) |
|
271
|
|
|
272
|
const getTotalAvailableSeats = (dateAvailability: TicketProductAvailability) => { |
|
273
|
return dateAvailability.row_types.reduce( |
|
274
|
(sum, rowType) => sum + rowType.available_seats, 0 |
|
275
|
) |
|
276
|
} |
|
277
|
|
|
278
|
const getFilteredAvailability = (quantity: number) => { |
|
279
|
return availability.filter((avail) => getTotalAvailableSeats(avail) >= quantity) |
|
280
|
} |
|
281
|
|
|
282
|
const filteredAvailability = getFilteredAvailability(nbOfTickets) |
|
283
|
|
|
284
|
const dateAsStr = (date: Date) => { |
|
285
|
return `${ |
|
286
|
date.getFullYear() |
|
287
|
}-${ |
|
288
|
String(date.getMonth() + 1).padStart(2, "0") |
|
289
|
}-${String(date.getDate()).padStart(2, "0")}` |
|
290
|
} |
|
291
|
|
|
292
|
const isDateUnavailable = (date: Date) => { |
|
293
|
const dateString = dateAsStr(date) |
|
294
|
return !filteredAvailability.some((avail) => avail.date === dateString) |
|
295
|
} |
|
296
|
|
|
297
|
const handleDateChange = (date: Date | null) => { |
|
298
|
setSelectedDate(date) |
|
299
|
} |
|
300
|
|
|
301
|
const handlePickSeats = () => { |
|
302
|
if (!selectedDate) { |
|
303
|
toast.error("Please select a date") |
|
304
|
return |
|
305
|
} |
|
306
|
|
|
307
|
const dateString = dateAsStr(selectedDate) |
|
308
|
onDateSelect(dateString, nbOfTickets) |
|
309
|
} |
|
310
|
|
|
311
|
// TODO render date selector |
|
312
|
} |
|
313
|
``` |
|
314
|
|
|
315
|
The `TicketDateSelection` component accepts the following props: |
|
316
|
|
|
317
|
- `product`: The Medusa product to select a date for. |
|
318
|
- `onDateSelect`: A callback function that is called when the date and number of tickets are selected. |
|
319
|
- `disabled`: A boolean to disable the component. |
|
320
|
|
|
321
|
In the component, you define state variables to manage the number of tickets, the selected date, the availability data, and the loading state. You also load the availability data when the component mounts. |
|
322
|
|
|
323
|
In addition, you define the following functions: |
|
324
|
|
|
325
|
- `getTotalAvailableSeats`: Calculates the total available seats for a given date availability. |
|
326
|
- `getFilteredAvailability`: Filters the availability data based on the number of tickets requested. |
|
327
|
- `dateAsStr`: Converts a `Date` object to a string in the format `YYYY-MM-DD`. |
|
328
|
- `isDateUnavailable`: Checks if a date is unavailable based on the filtered availability. |
|
329
|
- `handleDateChange`: Updates the selected date when the user selects a date from the calendar. |
|
330
|
- `handlePickSeats`: Calls the `onDateSelect` callback with the selected date and number of tickets, or shows an error if no date is selected. |
|
331
|
|
|
332
|
Next, you'll render the date selector form. Replace the `TODO` with the following: |
|
333
|
|
|
334
|
```tsx title="src/modules/products/components/ticket-product-layout/date-quantity-selection.tsx" |
|
335
|
return ( |
|
336
|
<div className="bg-ui-bg-base"> |
|
337
|
<h3 className="txt-large text-center mb-4">Select Show Date</h3> |
|
338
|
{isLoading && ( |
|
339
|
<div className="flex flex-col gap-y-4"> |
|
340
|
<div className="h-6 bg-ui-bg-subtle rounded animate-pulse w-32 mx-auto" /> |
|
341
|
<div className="h-10 bg-ui-bg-subtle rounded animate-pulse w-48 mx-auto" /> |
|
342
|
<div className="h-6 bg-ui-bg-subtle rounded animate-pulse w-40 mx-auto" /> |
|
343
|
</div> |
|
344
|
)} |
|
345
|
{!isLoading && ( |
|
346
|
<div className="flex flex-col gap-y-4"> |
|
347
|
{/* Number of tickets selection */} |
|
348
|
<div className="flex justify-center"> |
|
349
|
<div className="flex flex-col gap-y-2"> |
|
350
|
<Label htmlFor="nbOfTickets" className="text-ui-fg-subtle txt-compact-small">Number of Tickets</Label> |
|
351
|
<div className="flex items-center justify-between rounded-md"> |
|
352
|
<IconButton |
|
353
|
onClick={() => setNbOfTickets(Math.max(1, nbOfTickets - 1))} |
|
354
|
disabled={disabled || nbOfTickets <= 1} |
|
355
|
variant="transparent" |
|
356
|
> |
|
357
|
<Minus /> |
|
358
|
</IconButton> |
|
359
|
{nbOfTickets} |
|
360
|
<IconButton |
|
361
|
onClick={() => setNbOfTickets(Math.min(10, nbOfTickets + 1))} |
|
362
|
disabled={disabled || nbOfTickets >= 10} |
|
363
|
variant="transparent" |
|
364
|
> |
|
365
|
<Plus /> |
|
366
|
</IconButton> |
|
367
|
</div> |
|
368
|
</div> |
|
369
|
</div> |
|
370
|
|
|
371
|
{/* Calendar */} |
|
372
|
<div className="flex justify-center"> |
|
373
|
<Calendar |
|
374
|
onChange={handleDateChange} |
|
375
|
minValue={filteredAvailability.length > 0 ? |
|
376
|
new Date(filteredAvailability[0].date) : undefined |
|
377
|
} |
|
378
|
maxValue={filteredAvailability.length > 0 ? |
|
379
|
new Date(filteredAvailability[filteredAvailability.length - 1].date) : undefined |
|
380
|
} |
|
381
|
isDateUnavailable={isDateUnavailable} |
|
382
|
/> |
|
383
|
</div> |
|
384
|
|
|
385
|
{/* Available dates info */} |
|
386
|
{filteredAvailability.length > 0 && ( |
|
387
|
<p className="txt-small text-ui-fg-subtle text-center txt-compact-small"> |
|
388
|
{filteredAvailability.length} show{filteredAvailability.length !== 1 ? "s" : ""} available for {nbOfTickets} ticket{nbOfTickets !== 1 ? "s" : ""} |
|
389
|
</p> |
|
390
|
)} |
|
391
|
|
|
392
|
{/* Pick Seats Button */} |
|
393
|
<Button |
|
394
|
onClick={handlePickSeats} |
|
395
|
disabled={disabled || !selectedDate || filteredAvailability.length === 0} |
|
396
|
variant="primary" |
|
397
|
className="w-full" |
|
398
|
> |
|
399
|
Pick Seats |
|
400
|
</Button> |
|
401
|
</div> |
|
402
|
)} |
|
403
|
</div> |
|
404
|
) |
|
405
|
``` |
|
406
|
|
|
407
|
You display a quantity selector to choose the number of tickets, which affects the available dates shown in the calendar based on whether they have enough available seats. |
|
408
|
|
|
409
|
You also display a calendar to select a show date, and a button to pick seats that calls the `onDateSelect` callback with the selected date and number of tickets. |
|
410
|
|
|
411
|
### Seat Selector Component |
|
412
|
|
|
413
|
The seat selector component will fetch the seating layout for a venue and date using the API route you created in the [backend part of the tutorial](../page.mdx#b-seating-layout-api-route). Before creating the component, you'll add a server function to fetch the seating layout. |
|
414
|
|
|
415
|
In `src/lib/data/ticket-products.ts`, add the following import at the top of the file: |
|
416
|
|
|
417
|
```ts title="src/lib/data/ticket-products.ts" |
|
418
|
import { TicketProductSeatsData } from "@lib/util/ticket-product" |
|
419
|
``` |
|
420
|
|
|
421
|
Then, add the following function to the file: |
|
422
|
|
|
423
|
```ts title="src/lib/data/ticket-products.ts" |
|
424
|
export const getTicketProductSeats = async ( |
|
425
|
productId: string, |
|
426
|
date: string |
|
427
|
): Promise<TicketProductSeatsData> => { |
|
428
|
const headers = { |
|
429
|
...(await getAuthHeaders()), |
|
430
|
} |
|
431
|
|
|
432
|
const next = { |
|
433
|
...(await getCacheOptions("ticket-products")), |
|
434
|
} |
|
435
|
|
|
436
|
return sdk.client |
|
437
|
.fetch<TicketProductSeatsData>( |
|
438
|
`/store/ticket-products/${productId}/seats`, |
|
439
|
{ |
|
440
|
method: "GET", |
|
441
|
query: { |
|
442
|
date, |
|
443
|
}, |
|
444
|
headers, |
|
445
|
next, |
|
446
|
cache: "no-store", // Always fetch fresh data for seats |
|
447
|
} |
|
448
|
) |
|
449
|
.then((data) => data) |
|
450
|
} |
|
451
|
``` |
|
452
|
|
|
453
|
You create a server function `getTicketProductSeats` that fetches the seating layout for a ticket product and date using the `/store/ticket-products/{id}/seats` API route. |
|
454
|
|
|
455
|
Next, you'll create the seat selector component. It will show a modal with a seat chart to select seats, and a button to add the seats to the cart and proceed to checkout. |
|
456
|
|
|
457
|
 |
|
458
|
|
|
459
|
You'll first create the seat chart component that displays the seating layout and allows selecting seats. Create the file `src/modules/products/components/ticket-product-layout/seat-selection.tsx` with the following content: |
|
460
|
|
|
461
|
```tsx title="src/modules/products/components/ticket-product-layout/seat-selection.tsx" collapsibleLines="1-7" expandButtonLabel="Show Imports" |
|
462
|
"use client" |
|
463
|
|
|
464
|
import { TicketProductSeatsData } from "@lib/util/ticket-product" |
|
465
|
import { Tooltip, TooltipProvider } from "@medusajs/ui" |
|
466
|
import { HttpTypes } from "@medusajs/types" |
|
467
|
import { convertToLocale } from "../../../../lib/util/money" |
|
468
|
|
|
469
|
export type SelectedSeat = { |
|
470
|
seatNumber: string |
|
471
|
rowNumber: string |
|
472
|
rowType: string |
|
473
|
variantId: string |
|
474
|
date: string |
|
475
|
venueRowId: string |
|
476
|
} |
|
477
|
|
|
478
|
type SeatSelectionProps = { |
|
479
|
seatData: TicketProductSeatsData |
|
480
|
selectedSeats: SelectedSeat[] |
|
481
|
onSeatSelect: (seat: SelectedSeat) => void |
|
482
|
disabled?: boolean |
|
483
|
product: HttpTypes.StoreProduct |
|
484
|
maxSeats: number |
|
485
|
} |
|
486
|
|
|
487
|
export default function SeatSelection({ |
|
488
|
seatData, |
|
489
|
selectedSeats, |
|
490
|
onSeatSelect, |
|
491
|
disabled = false, |
|
492
|
product, |
|
493
|
maxSeats, |
|
494
|
}: SeatSelectionProps) { |
|
495
|
const getSeatStatus = (rowNumber: string, seatNumber: string) => { |
|
496
|
const seat = seatData.seat_map |
|
497
|
.find((row) => row.row_number === rowNumber) |
|
498
|
?.seats.find((s) => s.number === seatNumber) |
|
499
|
|
|
500
|
if (!seat) {return "unavailable"} |
|
501
|
|
|
502
|
if (seat.is_purchased) {return "purchased"} |
|
503
|
|
|
504
|
const isSelected = selectedSeats.some((s) => |
|
505
|
s.seatNumber === seatNumber && s.rowNumber === rowNumber && s.date === seatData.date |
|
506
|
) |
|
507
|
|
|
508
|
if (isSelected) {return "selected"} |
|
509
|
|
|
510
|
return "available" |
|
511
|
} |
|
512
|
|
|
513
|
const getSeatColor = (status: string) => { |
|
514
|
switch (status) { |
|
515
|
case "purchased": |
|
516
|
return "bg-ui-tag-neutral-bg text-ui-tag-neutral-text cursor-not-allowed" |
|
517
|
case "selected": |
|
518
|
return "bg-ui-tag-blue-bg text-ui-tag-blue-text" |
|
519
|
case "available": |
|
520
|
return "bg-ui-tag-green-bg text-ui-tag-green-text cursor-pointer hover:bg-ui-tag-green-bg-hover" |
|
521
|
default: |
|
522
|
return "bg-ui-tag-neutral-bg text-ui-tag-neutral-text cursor-not-allowed" |
|
523
|
} |
|
524
|
} |
|
525
|
|
|
526
|
const formatRowType = (rowType: string) => { |
|
527
|
switch (rowType.toLowerCase()) { |
|
528
|
case "vip": |
|
529
|
return "VIP" |
|
530
|
default: |
|
531
|
return rowType.charAt(0).toUpperCase() + rowType.slice(1).toLowerCase() |
|
532
|
} |
|
533
|
} |
|
534
|
|
|
535
|
// TODO handle seat selection |
|
536
|
} |
|
537
|
``` |
|
538
|
|
|
539
|
The `SeatSelection` component accepts the following props: |
|
540
|
|
|
541
|
- `seatData`: The seating layout data for the venue and date retrieved from the API. |
|
542
|
- `selectedSeats`: An array of currently selected seats. |
|
543
|
- `onSeatSelect`: A callback function that is called when a seat is selected. |
|
544
|
- `disabled`: A boolean to disable seat selection. |
|
545
|
- `product`: The Medusa product to select seats for. |
|
546
|
- `maxSeats`: The maximum number of seats that can be selected. |
|
547
|
|
|
548
|
In the component, you define the following functions: |
|
549
|
|
|
550
|
- `getSeatStatus`: Determines the status of a seat (purchased, selected, available, or unavailable) based on the seating data and selected seats. |
|
551
|
- `getSeatColor`: Returns the appropriate CSS classes for a seat based on its status. |
|
552
|
- `formatRowType`: Formats the row type string for display. |
|
553
|
|
|
554
|
Next, you'll add a function to handle seat selection. Replace the `TODO` with the following: |
|
555
|
|
|
556
|
```tsx title="src/modules/products/components/ticket-product-layout/seat-selection.tsx" |
|
557
|
const handleSeatClick = (rowNumber: string, seatNumber: string, rowType: string) => { |
|
558
|
if (disabled) {return} |
|
559
|
|
|
560
|
const seat = seatData.seat_map |
|
561
|
.find((row) => row.row_number === rowNumber) |
|
562
|
?.seats.find((s) => s.number === seatNumber) |
|
563
|
|
|
564
|
if (!seat || seat.is_purchased || !seat.variant_id) {return} |
|
565
|
|
|
566
|
// Check if seat is already selected |
|
567
|
const isAlreadySelected = selectedSeats.some( |
|
568
|
(selectedSeat) => selectedSeat.seatNumber === seatNumber && selectedSeat.rowNumber === rowNumber |
|
569
|
) |
|
570
|
|
|
571
|
if (isAlreadySelected) { |
|
572
|
// Unselect the seat |
|
573
|
onSeatSelect({ |
|
574
|
seatNumber, |
|
575
|
rowNumber, |
|
576
|
rowType, |
|
577
|
variantId: seat.variant_id, |
|
578
|
date: seatData.date, |
|
579
|
venueRowId: seatData.venue.rows.find((row) => row.row_number === rowNumber)?.id as string, |
|
580
|
}) |
|
581
|
return |
|
582
|
} |
|
583
|
|
|
584
|
// Check if we've reached the maximum number of seats |
|
585
|
if (selectedSeats.length >= maxSeats) { |
|
586
|
return |
|
587
|
} |
|
588
|
|
|
589
|
// Select the seat |
|
590
|
onSeatSelect({ |
|
591
|
seatNumber, |
|
592
|
rowNumber, |
|
593
|
rowType, |
|
594
|
variantId: seat.variant_id, |
|
595
|
date: seatData.date, |
|
596
|
venueRowId: seatData.venue.rows.find((row) => row.row_number === rowNumber)?.id as string, |
|
597
|
}) |
|
598
|
} |
|
599
|
|
|
600
|
// TODO render seat chart |
|
601
|
``` |
|
602
|
|
|
603
|
You define the `handleSeatClick` function that handles the logic for toggling seat selection. It checks if the seat is purchasable, if it's already selected, and if the maximum number of seats has been reached before calling the `onSeatSelect` callback. |
|
604
|
|
|
605
|
Finally, you'll render the seat chart. Replace the `TODO` with the following: |
|
606
|
|
|
607
|
```tsx title="src/modules/products/components/ticket-product-layout/seat-selection.tsx" |
|
608
|
return ( |
|
609
|
<TooltipProvider> |
|
610
|
<div className="flex flex-col gap-y-4"> |
|
611
|
{/* Theater Layout */} |
|
612
|
<div className="bg-gradient-to-b from-ui-bg-subtle to-ui-bg-subtle rounded-lg p-4 shadow-elevation-card-rest overflow-y-auto max-h-[500px]"> |
|
613
|
{/* Stage Area */} |
|
614
|
<div className="text-center mb-6"> |
|
615
|
<div className="bg-gradient-to-b from-ui-fg-base to-ui-fg-base text-white px-8 py-4 rounded-lg shadow-xl relative"> |
|
616
|
<div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent rounded-lg"></div> |
|
617
|
<div className="relative"> |
|
618
|
<div className="txt-large-plus mb-1">STAGE</div> |
|
619
|
<div className="txt-small text-ui-alpha-250">Performance Area</div> |
|
620
|
</div> |
|
621
|
</div> |
|
622
|
</div> |
|
623
|
|
|
624
|
{/* Seating Area */} |
|
625
|
<div> |
|
626
|
<div className="space-y-4"> |
|
627
|
{seatData.seat_map.map((row, index) => ( |
|
628
|
<div key={row.row_number} className="flex items-baseline justify-center gap-x-3"> |
|
629
|
{/* Row label */} |
|
630
|
<div className="txt-small text-ui-fg-subtle"> |
|
631
|
{row.row_number} |
|
632
|
</div> |
|
633
|
|
|
634
|
{/* Seats */} |
|
635
|
<div className="flex gap-x-1 gap-y-1 flex-wrap justify-center"> |
|
636
|
{row.seats.map((seat) => { |
|
637
|
const status = getSeatStatus(row.row_number, seat.number) |
|
638
|
const variant = product.variants?.find((v) => v.id === seat.variant_id) |
|
639
|
const seatPrice = variant?.calculated_price?.calculated_amount || 0 |
|
640
|
const currencyCode = variant?.calculated_price?.currency_code || "USD" |
|
641
|
|
|
642
|
const tooltipContent = status === "purchased" |
|
643
|
? "Sold" |
|
644
|
: status === "selected" |
|
645
|
? "Selected" |
|
646
|
: seatPrice > 0 |
|
647
|
? `Seat ${seat.number} - ${formatRowType(row.row_type)} - ${convertToLocale({ |
|
648
|
amount: seatPrice, |
|
649
|
currency_code: currencyCode, |
|
650
|
minimumFractionDigits: 0, |
|
651
|
})}` |
|
652
|
: `Seat ${seat.number} - ${formatRowType(row.row_type)}` |
|
653
|
|
|
654
|
return ( |
|
655
|
<Tooltip key={seat.number} content={tooltipContent} className="z-[76]"> |
|
656
|
<button |
|
657
|
onClick={() => handleSeatClick(row.row_number, seat.number, row.row_type)} |
|
658
|
disabled={disabled || status === "purchased" || status === "unavailable" || (status === "available" && selectedSeats.length >= maxSeats)} |
|
659
|
className={` |
|
660
|
w-8 h-8 rounded-sm txt-xsmall transition-all duration-200 flex items-center justify-center |
|
661
|
${getSeatColor(status)} |
|
662
|
${status === "purchased" ? "cursor-not-allowed" : "cursor-pointer"} |
|
663
|
${(status === "available" && selectedSeats.length >= maxSeats) || status === "purchased" ? "opacity-50 cursor-not-allowed" : ""} |
|
664
|
${status === "available" ? "shadow-sm" : ""} |
|
665
|
${status === "selected" ? "border border-ui-border-interactive" : ""} |
|
666
|
`} |
|
667
|
> |
|
668
|
{seat.number} |
|
669
|
</button> |
|
670
|
</Tooltip> |
|
671
|
) |
|
672
|
})} |
|
673
|
</div> |
|
674
|
</div> |
|
675
|
))} |
|
676
|
</div> |
|
677
|
</div> |
|
678
|
</div> |
|
679
|
|
|
680
|
{/* Legend */} |
|
681
|
<div className="flex flex-wrap justify-center gap-x-6 gap-y-2 txt-small"> |
|
682
|
<div className="flex items-center gap-x-2"> |
|
683
|
<div className="w-5 h-5 bg-ui-tag-green-bg rounded"></div> |
|
684
|
<span className="txt-small-plus">Available</span> |
|
685
|
</div> |
|
686
|
<div className="flex items-center gap-x-2"> |
|
687
|
<div className="w-5 h-5 bg-ui-tag-blue-bg rounded"></div> |
|
688
|
<span className="txt-small-plus">Selected</span> |
|
689
|
</div> |
|
690
|
<div className="flex items-center gap-x-2"> |
|
691
|
<div className="w-5 h-5 bg-ui-tag-neutral-bg rounded"></div> |
|
692
|
<span className="txt-small-plus">Sold</span> |
|
693
|
</div> |
|
694
|
</div> |
|
695
|
</div> |
|
696
|
</TooltipProvider> |
|
697
|
) |
|
698
|
``` |
|
699
|
|
|
700
|
You display the seating layout with rows and seats. Each seat is a button that shows its status (available, selected, purchased) with different colors and tooltips. You also include a legend to explain the seat colors. |
|
701
|
|
|
702
|
Next, you'll create the seat selector modal component that renders the `SeatSelection` component inside a modal. Create the file `src/modules/products/components/ticket-product-layout/seat-selection-modal.tsx` with the following content: |
|
703
|
|
|
704
|
```tsx title="src/modules/products/components/ticket-product-layout/seat-selection-modal.tsx" collapsibleLines="1-13" expandButtonLabel="Show Imports" |
|
705
|
"use client" |
|
706
|
|
|
707
|
import { addToCart } from "@lib/data/cart" |
|
708
|
import { getTicketProductSeats } from "@lib/data/ticket-products" |
|
709
|
import { TicketProductSeatsData } from "@lib/util/ticket-product" |
|
710
|
import { HttpTypes } from "@medusajs/types" |
|
711
|
import { Button, toast } from "@medusajs/ui" |
|
712
|
import { useParams, useRouter } from "next/navigation" |
|
713
|
import { useEffect, useMemo, useState } from "react" |
|
714
|
import { convertToLocale } from "@lib/util/money" |
|
715
|
import SeatSelection, { SelectedSeat } from "./seat-selection" |
|
716
|
import Modal from "../../../common/components/modal" |
|
717
|
|
|
718
|
type SeatSelectionModalProps = { |
|
719
|
product: HttpTypes.StoreProduct |
|
720
|
selectedDate: string |
|
721
|
selectedQuantity: number |
|
722
|
isOpen: boolean |
|
723
|
onClose: () => void |
|
724
|
disabled?: boolean |
|
725
|
} |
|
726
|
|
|
727
|
export default function SeatSelectionModal({ |
|
728
|
product, |
|
729
|
selectedDate, |
|
730
|
selectedQuantity, |
|
731
|
isOpen, |
|
732
|
onClose, |
|
733
|
disabled = false, |
|
734
|
}: SeatSelectionModalProps) { |
|
735
|
const [selectedSeats, setSelectedSeats] = useState<SelectedSeat[]>([]) |
|
736
|
const [seatData, setSeatData] = useState<TicketProductSeatsData | null>(null) |
|
737
|
const [isAddingToCart, setIsAddingToCart] = useState(false) |
|
738
|
|
|
739
|
const countryCode = useParams().countryCode as string |
|
740
|
const router = useRouter() |
|
741
|
|
|
742
|
const formatDate = (dateString: string) => { |
|
743
|
const date = new Date(dateString) |
|
744
|
return date.toLocaleDateString("en-US", { |
|
745
|
weekday: "long", |
|
746
|
year: "numeric", |
|
747
|
month: "long", |
|
748
|
day: "numeric", |
|
749
|
}) |
|
750
|
} |
|
751
|
|
|
752
|
const totalPrice = useMemo(() => { |
|
753
|
return selectedSeats.reduce((total, seat) => { |
|
754
|
const variant = product.variants?.find((v) => v.id === seat.variantId) |
|
755
|
return total + (variant?.calculated_price?.calculated_amount || 0) |
|
756
|
}, 0) |
|
757
|
}, [selectedSeats, product.variants]) |
|
758
|
|
|
759
|
// Load seat data when modal opens |
|
760
|
useEffect(() => { |
|
761
|
if (!isOpen || !selectedDate) { |
|
762
|
return |
|
763
|
} |
|
764
|
setSelectedSeats([]) |
|
765
|
setSeatData(null) |
|
766
|
|
|
767
|
const loadSeatData = async () => { |
|
768
|
try { |
|
769
|
const data = await getTicketProductSeats(product.id, selectedDate) |
|
770
|
setSeatData(data) |
|
771
|
} catch (error) { |
|
772
|
toast.error("Failed to load seat data: " + error) |
|
773
|
} |
|
774
|
} |
|
775
|
|
|
776
|
loadSeatData() |
|
777
|
}, [isOpen, selectedDate, product.id]) |
|
778
|
|
|
779
|
// TODO handle seat selection and cart addition |
|
780
|
} |
|
781
|
``` |
|
782
|
|
|
783
|
The `SeatSelectionModal` component accepts the following props: |
|
784
|
|
|
785
|
- `product`: The Medusa product to select seats for. |
|
786
|
- `selectedDate`: The selected show date. |
|
787
|
- `selectedQuantity`: The number of tickets to select. |
|
788
|
- `isOpen`: A boolean to control the visibility of the modal. |
|
789
|
- `onClose`: A callback function that is called when the modal is closed. |
|
790
|
- `disabled`: A boolean to disable seat selection. |
|
791
|
|
|
792
|
In the component, you define state and memo variables to manage the selected seats, the seating data, the loading state for the cart addition action, and the total price for the seat selection. You also load the seating data when the modal opens. |
|
793
|
|
|
794
|
Next, you'll add functions to handle seat selection and adding seats to the cart. Replace the `TODO` with the following: |
|
795
|
|
|
796
|
```tsx title="src/modules/products/components/ticket-product-layout/seat-selection-modal.tsx" |
|
797
|
const handleSeatSelect = (seat: SelectedSeat) => { |
|
798
|
setSelectedSeats((prev) => { |
|
799
|
const existingIndex = prev.findIndex( |
|
800
|
(s) => s.seatNumber === seat.seatNumber && s.rowNumber === seat.rowNumber |
|
801
|
) |
|
802
|
|
|
803
|
if (existingIndex >= 0) { |
|
804
|
// Remove seat if already selected |
|
805
|
return prev.filter((_, index) => index !== existingIndex) |
|
806
|
} else { |
|
807
|
// Add seat if not selected and under limit |
|
808
|
if (prev.length < selectedQuantity) { |
|
809
|
return [...prev, seat] |
|
810
|
} |
|
811
|
return prev |
|
812
|
} |
|
813
|
}) |
|
814
|
} |
|
815
|
|
|
816
|
const handleAddToCart = async () => { |
|
817
|
if (selectedSeats.length === 0) { |
|
818
|
toast.error("Please select at least one seat") |
|
819
|
return |
|
820
|
} |
|
821
|
|
|
822
|
if (selectedSeats.length !== selectedQuantity) { |
|
823
|
toast.error(`Please select exactly ${selectedQuantity} seat${selectedQuantity !== 1 ? "s" : ""}`) |
|
824
|
return |
|
825
|
} |
|
826
|
|
|
827
|
setIsAddingToCart(true) |
|
828
|
try { |
|
829
|
// Add each seat as a separate cart item |
|
830
|
for (const seat of selectedSeats) { |
|
831
|
await addToCart({ |
|
832
|
variantId: seat.variantId, |
|
833
|
quantity: 1, |
|
834
|
countryCode, |
|
835
|
metadata: { |
|
836
|
seat_number: seat.seatNumber, |
|
837
|
row_number: seat.rowNumber, |
|
838
|
show_date: seat.date, |
|
839
|
venue_row_id: seat.venueRowId, |
|
840
|
}, |
|
841
|
}) |
|
842
|
} |
|
843
|
|
|
844
|
toast.success(`Added ${selectedSeats.length} ticket${selectedSeats.length !== 1 ? "s" : ""} to cart`) |
|
845
|
|
|
846
|
// Redirect to checkout |
|
847
|
router.push(`/${countryCode}/checkout?step=address`) |
|
848
|
} catch (error) { |
|
849
|
toast.error("Failed to add tickets to cart: " + error) |
|
850
|
} finally { |
|
851
|
setIsAddingToCart(false) |
|
852
|
} |
|
853
|
} |
|
854
|
|
|
855
|
// TODO render modal with seat selection |
|
856
|
``` |
|
857
|
|
|
858
|
You define the `handleSeatSelect` function that updates the selected seats when a seat is clicked, and the `handleAddToCart` function that adds the selected seats to the cart and redirects to the checkout page. |
|
859
|
|
|
860
|
Finally, you'll render the modal with the seat selection component. Replace the `TODO` with the following: |
|
861
|
|
|
862
|
```tsx title="src/modules/products/components/ticket-product-layout/seat-selection-modal.tsx" |
|
863
|
return ( |
|
864
|
<Modal isOpen={isOpen} close={onClose}> |
|
865
|
<div className="flex items-center justify-between w-full mb-4"> |
|
866
|
<div> |
|
867
|
<h2 className="txt-large-plus">Select Your Seats</h2> |
|
868
|
<p className="txt-small text-ui-fg-subtle"> |
|
869
|
{formatDate(selectedDate)} • {seatData?.venue.name} • ({selectedSeats.length}/{selectedQuantity} tickets selected) |
|
870
|
</p> |
|
871
|
</div> |
|
872
|
<Button |
|
873
|
variant="transparent" |
|
874
|
onClick={onClose} |
|
875
|
className="text-ui-fg-muted hover:text-ui-fg-base" |
|
876
|
> |
|
877
|
✕ |
|
878
|
</Button> |
|
879
|
</div> |
|
880
|
|
|
881
|
<div> |
|
882
|
{seatData ? ( |
|
883
|
<SeatSelection |
|
884
|
product={product} |
|
885
|
seatData={seatData} |
|
886
|
selectedSeats={selectedSeats} |
|
887
|
onSeatSelect={handleSeatSelect} |
|
888
|
maxSeats={selectedQuantity} |
|
889
|
disabled={disabled || isAddingToCart} |
|
890
|
/> |
|
891
|
) : ( |
|
892
|
<div className="text-center py-8 min-h-[500px]"> |
|
893
|
<p className="txt-medium text-ui-fg-subtle">No seat data available</p> |
|
894
|
</div> |
|
895
|
)} |
|
896
|
</div> |
|
897
|
|
|
898
|
{seatData && ( |
|
899
|
<div className="flex items-center justify-between w-full mt-4"> |
|
900
|
<div className="flex items-center justify-between w-full"> |
|
901
|
<div className="txt-small text-ui-fg-subtle"> |
|
902
|
{selectedSeats.length} of {selectedQuantity} seats selected |
|
903
|
</div> |
|
904
|
<div className="flex gap-x-3"> |
|
905
|
<Button |
|
906
|
variant="secondary" |
|
907
|
onClick={onClose} |
|
908
|
disabled={isAddingToCart} |
|
909
|
> |
|
910
|
Cancel |
|
911
|
</Button> |
|
912
|
<Button |
|
913
|
variant="primary" |
|
914
|
onClick={handleAddToCart} |
|
915
|
disabled={disabled || isAddingToCart || selectedSeats.length !== selectedQuantity} |
|
916
|
isLoading={isAddingToCart} |
|
917
|
> |
|
918
|
{selectedSeats.length > 0 ? ( |
|
919
|
<> |
|
920
|
Buy Tickets - {convertToLocale({ |
|
921
|
amount: totalPrice, |
|
922
|
currency_code: product.variants?.[0]?.calculated_price?.currency_code || "USD", |
|
923
|
})} |
|
924
|
</> |
|
925
|
) : ( |
|
926
|
"Buy Tickets" |
|
927
|
)} |
|
928
|
</Button> |
|
929
|
</div> |
|
930
|
</div> |
|
931
|
</div> |
|
932
|
)} |
|
933
|
</Modal> |
|
934
|
) |
|
935
|
``` |
|
936
|
|
|
937
|
You display a modal with the seat selection component, along with a header and a footer. You use the `Modal` component that's part of the Next.js Starter Storefront. |
|
938
|
|
|
939
|
### Add Ticket Layout Component |
|
940
|
|
|
941
|
Next, you'll create a component that renders the date selector and seat selector modal components together. You'll display this component on the product page for ticket products. |
|
942
|
|
|
943
|
Create the file `src/modules/products/components/ticket-product-layout/index.tsx` with the following content: |
|
944
|
|
|
945
|
```tsx title="src/modules/products/components/ticket-product-layout/index.tsx" |
|
946
|
"use client" |
|
947
|
|
|
948
|
import React, { useState } from "react" |
|
949
|
import { HttpTypes } from "@medusajs/types" |
|
950
|
import TicketDateSelection from "./date-quantity-selection" |
|
951
|
import SeatSelectionModal from "./seat-selection-modal" |
|
952
|
|
|
953
|
type TicketLayoutProps = { |
|
954
|
product: HttpTypes.StoreProduct |
|
955
|
} |
|
956
|
|
|
957
|
const TicketLayout: React.FC<TicketLayoutProps> = ({ product }) => { |
|
958
|
const [isSeatModalOpen, setIsSeatModalOpen] = useState(false) |
|
959
|
const [selectedDate, setSelectedDate] = useState<string | null>(null) |
|
960
|
const [selectedQuantity, setSelectedQuantity] = useState<number>(1) |
|
961
|
|
|
962
|
const handleDateQuantitySelect = (date: string, quantity: number) => { |
|
963
|
setSelectedDate(date) |
|
964
|
setSelectedQuantity(quantity) |
|
965
|
setIsSeatModalOpen(true) |
|
966
|
} |
|
967
|
|
|
968
|
const handleCloseSeatModal = () => { |
|
969
|
setIsSeatModalOpen(false) |
|
970
|
setSelectedDate(null) |
|
971
|
setSelectedQuantity(1) |
|
972
|
} |
|
973
|
|
|
974
|
return ( |
|
975
|
<> |
|
976
|
<TicketDateSelection |
|
977
|
product={product} |
|
978
|
onDateSelect={handleDateQuantitySelect} |
|
979
|
disabled={false} |
|
980
|
/> |
|
981
|
|
|
982
|
<SeatSelectionModal |
|
983
|
product={product} |
|
984
|
selectedDate={selectedDate || ""} |
|
985
|
selectedQuantity={selectedQuantity} |
|
986
|
isOpen={isSeatModalOpen} |
|
987
|
onClose={handleCloseSeatModal} |
|
988
|
disabled={false} |
|
989
|
/> |
|
990
|
</> |
|
991
|
) |
|
992
|
} |
|
993
|
|
|
994
|
export default TicketLayout |
|
995
|
``` |
|
996
|
|
|
997
|
The `TicketLayout` component manages the state for the selected date, number of tickets, and the visibility of the seat selection modal. It renders the `TicketDateSelection` component to select a date and quantity, and the `SeatSelectionModal` component to select seats. |
|
998
|
|
|
999
|
When a date and quantity are selected, it opens the seat selection modal. When the modal is closed, it resets the state. |
|
1000
|
|
|
1001
|
### Update Product Page Layout |
|
1002
|
|
|
1003
|
Next, you'll update the product page layout to use the date selector and seat selector modal components you created earlier. |
|
1004
|
|
|
1005
|
In `src/modules/products/templates/index.tsx`, replace the file content with the following: |
|
1006
|
|
|
1007
|
```tsx title="src/modules/products/templates/index.tsx" collapsibleLines="1-10" expandButtonLabel="Show Imports" |
|
1008
|
import React, { Suspense } from "react" |
|
1009
|
|
|
1010
|
import ImageGallery from "@modules/products/components/image-gallery" |
|
1011
|
import RelatedProducts from "@modules/products/components/related-products" |
|
1012
|
import ProductInfo from "@modules/products/templates/product-info" |
|
1013
|
import SkeletonRelatedProducts from "@modules/skeletons/templates/skeleton-related-products" |
|
1014
|
import { notFound } from "next/navigation" |
|
1015
|
import { HttpTypes } from "@medusajs/types" |
|
1016
|
import TicketLayout from "../components/ticket-product-layout" |
|
1017
|
|
|
1018
|
type ProductTemplateProps = { |
|
1019
|
product: HttpTypes.StoreProduct |
|
1020
|
region: HttpTypes.StoreRegion |
|
1021
|
countryCode: string |
|
1022
|
} |
|
1023
|
|
|
1024
|
const ProductTemplate: React.FC<ProductTemplateProps> = ({ |
|
1025
|
product, |
|
1026
|
countryCode, |
|
1027
|
}) => { |
|
1028
|
if (!product || !product.id) { |
|
1029
|
return notFound() |
|
1030
|
} |
|
1031
|
|
|
1032
|
return ( |
|
1033
|
<> |
|
1034
|
<div |
|
1035
|
className="content-container flex flex-col py-6 relative" |
|
1036
|
data-testid="product-container" |
|
1037
|
> |
|
1038
|
<div className="flex flex-col small:flex-row small:items-start gap-y-6"> |
|
1039
|
<div className="flex flex-col small:sticky small:top-48 small:py-0 small:max-w-[300px] w-full py-8 gap-y-6"> |
|
1040
|
<ProductInfo product={product} /> |
|
1041
|
</div> |
|
1042
|
<div className="flex flex-col w-full relative"> |
|
1043
|
<div className="block w-full relative"> |
|
1044
|
<ImageGallery images={product?.images || []} /> |
|
1045
|
</div> |
|
1046
|
</div> |
|
1047
|
<div className="flex flex-col small:sticky small:top-48 small:py-0 small:max-w-[300px] w-full py-8 gap-y-6"> |
|
1048
|
<TicketLayout product={product} /> |
|
1049
|
</div> |
|
1050
|
</div> |
|
1051
|
</div> |
|
1052
|
|
|
1053
|
<div |
|
1054
|
className="content-container my-16 small:my-32" |
|
1055
|
data-testid="related-products-container" |
|
1056
|
> |
|
1057
|
<Suspense fallback={<SkeletonRelatedProducts />}> |
|
1058
|
<RelatedProducts product={product} countryCode={countryCode} /> |
|
1059
|
</Suspense> |
|
1060
|
</div> |
|
1061
|
</> |
|
1062
|
) |
|
1063
|
} |
|
1064
|
|
|
1065
|
export default ProductTemplate |
|
1066
|
``` |
|
1067
|
|
|
1068
|
This makes the following main changes: |
|
1069
|
|
|
1070
|
- Removes the `ProductTabs` component since it's not needed for ticket products. |
|
1071
|
- Shows the `TicketLayout` component on the right side of the product images. |
|
1072
|
|
|
1073
|
### Allow Retrieving Ticket Products |
|
1074
|
|
|
1075
|
Every Store API route defines the fields that clients can request in the `fields` query parameter. Medusa strips any other field from the response without throwing an error. So, to retrieve ticket products from the `/store/products` route, add the following route object to the array passed to `defineMiddlewares` in the Medusa application's `src/api/middlewares.ts` file: |
|
1076
|
|
|
1077
|
```ts title="src/api/middlewares.ts" |
|
1078
|
import { allowFields } from "@medusajs/framework/http" |
|
1079
|
|
|
1080
|
export default defineMiddlewares({ |
|
1081
|
routes: [ |
|
1082
|
// ... |
|
1083
|
{ |
|
1084
|
matcher: "/store/products", |
|
1085
|
middlewares: [allowFields("ticket_product")], |
|
1086
|
}, |
|
1087
|
], |
|
1088
|
}) |
|
1089
|
``` |
|
1090
|
|
|
1091
|
<Note> |
|
1092
|
|
|
1093
|
`allowFields` is available since Medusa [v2.21.0](https://github.com/medusajs/medusa/releases/tag/v2.21.0). In earlier versions, write the middleware yourself, as explained in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields#how-to-override-allowed-fields-of-medusas-api-routes) documentation. |
|
1094
|
|
|
1095
|
</Note> |
|
1096
|
|
|
1097
|
<Note title="Important"> |
|
1098
|
|
|
1099
|
The middleware must be global, so don't set a `method` property on the route object. Medusa runs a method-scoped middleware after it validates the `fields` query parameter, which is too late to change the allowed fields. |
|
1100
|
|
|
1101
|
</Note> |
|
1102
|
|
|
1103
|
Learn more about this behavior in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields) documentation. |
|
1104
|
|
|
1105
|
### Retrieve Ticket Product with Product |
|
1106
|
|
|
1107
|
Next, you'll update the server function that retrieves products to include ticket products. This allows you to access the ticket product details when fetching a product. |
|
1108
|
|
|
1109
|
In `src/lib/data/products.ts`, find the `listProducts` function and update the `fields` parameter passed to the SDK call to include the `*ticket_product` relation: |
|
1110
|
|
|
1111
|
```ts title="src/lib/data/products.ts" highlights={[["18"]]} |
|
1112
|
export const listProducts = async ({ |
|
1113
|
// ... |
|
1114
|
}: { |
|
1115
|
// ... |
|
1116
|
}): Promise<{ |
|
1117
|
// ... |
|
1118
|
}> => { |
|
1119
|
// ... |
|
1120
|
return sdk.client |
|
1121
|
.fetch<{ |
|
1122
|
// ... |
|
1123
|
}>( |
|
1124
|
`/store/products`, |
|
1125
|
{ |
|
1126
|
// ... |
|
1127
|
query: { |
|
1128
|
// ... |
|
1129
|
fields: "*variants.calculated_price,+variants.inventory_quantity,+metadata,+tags,*ticket_product", |
|
1130
|
}, |
|
1131
|
} |
|
1132
|
) |
|
1133
|
// ... |
|
1134
|
} |
|
1135
|
``` |
|
1136
|
|
|
1137
|
This updates the `fields` parameter to include `*ticket_product`, which retrieves the ticket product relation when fetching products. |
|
1138
|
|
|
1139
|
### Change Modal Styling |
|
1140
|
|
|
1141
|
To ensure the height of the modal can hold the seat selection component, you'll need to adjust the modal styling. |
|
1142
|
|
|
1143
|
In `src/modules/common/components/modal/index.tsx`, change the `classNames` of the `Dialog.Panel` to include `max-h-[90vh] overflow-y-auto`: |
|
1144
|
|
|
1145
|
```tsx title="src/modules/common/components/modal/index.tsx" highlights={[["3"]]} |
|
1146
|
<Dialog.Panel |
|
1147
|
className={clx( |
|
1148
|
"flex flex-col justify-start w-full transform p-5 text-left align-middle transition-all max-h-[90vh] h-fit overflow-y-auto", |
|
1149
|
{ |
|
1150
|
// ... |
|
1151
|
} |
|
1152
|
)} |
|
1153
|
// ... |
|
1154
|
> |
|
1155
|
{/* ... */} |
|
1156
|
</Dialog.Panel> |
|
1157
|
``` |
|
1158
|
|
|
1159
|
### Add Toaster to Layout |
|
1160
|
|
|
1161
|
Since you used the `toast` function in your customization to show toast messages, you need to ensure the `Toaster` component is included in your layout. |
|
1162
|
|
|
1163
|
In `src/app/layout.tsx`, add the following import at the top of the file: |
|
1164
|
|
|
1165
|
```tsx title="src/app/layout.tsx" |
|
1166
|
import { Toaster } from "@medusajs/ui" |
|
1167
|
``` |
|
1168
|
|
|
1169
|
Then, add the `<Toaster />` component at the end of the body tag in the `return` statement: |
|
1170
|
|
|
1171
|
```tsx title="src/app/layout.tsx" highlights={[["5"]]} |
|
1172
|
return ( |
|
1173
|
<html lang="en" data-mode="light"> |
|
1174
|
<body> |
|
1175
|
<main className="relative">{props.children}</main> |
|
1176
|
<Toaster /> |
|
1177
|
</body> |
|
1178
|
</html> |
|
1179
|
) |
|
1180
|
``` |
|
1181
|
|
|
1182
|
### Test Product Page |
|
1183
|
|
|
1184
|
To test the product page in the Next.js Starter Storefront, run the following command in the Medusa application's directory: |
|
1185
|
|
|
1186
|
```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green" |
|
1187
|
npm run dev |
|
1188
|
``` |
|
1189
|
|
|
1190
|
And run the following command in the Next.js Starter Storefront application's directory: |
|
1191
|
|
|
1192
|
```bash npm2yarn |
|
1193
|
npm run dev |
|
1194
|
``` |
|
1195
|
|
|
1196
|
Then: |
|
1197
|
|
|
1198
|
1. Open the storefront at `http://localhost:8000`. |
|
1199
|
2. Click on Menu in the navbar, and choose Store. |
|
1200
|
3. In the store page, click on a ticket product you created. |
|
1201
|
|
|
1202
|
You'll see on the product page the date selector component on the right side of the product images. |
|
1203
|
|
|
1204
|
 |
|
1205
|
|
|
1206
|
Select a date and number of tickets, then click the "Pick Seats" button. A modal will open with the seat selection component. You can select seats and click the "Buy Tickets" button to add them to the cart and proceed to checkout. |
|
1207
|
|
|
1208
|
 |
|
1209
|
|
|
1210
|
This will open the checkout page with the selected tickets in the cart. You'll customize the checkout and cart components next. |
|
1211
|
|
|
1212
|
--- |
|
1213
|
|
|
1214
|
## Step 4: Customize Cart and Checkout |
|
1215
|
|
|
1216
|
In this section, you'll customize the cart and checkout components and functions to: |
|
1217
|
|
|
1218
|
1. Display the selected seats for items, which appears in the cart and checkout pages. |
|
1219
|
2. Remove the Shipping Address and Shipping Method steps from the checkout process since ticket products don't require shipping. Instead, you'll only collect the billing address. |
|
1220
|
3. Update the function that retrieves the cart to retrieve its billing address. |
|
1221
|
4. Update the function that saves the address to only save the billing address. |
|
1222
|
5. Use the custom cart completion API route to place an order. |
|
1223
|
|
|
1224
|
### Display Selected Seats in Cart and Checkout |
|
1225
|
|
|
1226
|
First, you'll customize the cart item component to display the selected seats for ticket products. |
|
1227
|
|
|
1228
|
In `src/modules/cart/components/item/index.tsx`, find the `LineItemOptions` component in the `return` statement of the `Item` component, and replace it with the following: |
|
1229
|
|
|
1230
|
```tsx title="src/modules/cart/components/item/index.tsx" |
|
1231
|
{item.metadata?.seat_number !== undefined && ( |
|
1232
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1233
|
Seat {item.metadata?.row_number as string}{item.metadata?.seat_number as string} |
|
1234
|
</Text> |
|
1235
|
)} |
|
1236
|
{item.metadata?.show_date !== undefined && ( |
|
1237
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1238
|
Show Date: {new Date(item.metadata?.show_date as string).toLocaleDateString()} |
|
1239
|
</Text> |
|
1240
|
)} |
|
1241
|
``` |
|
1242
|
|
|
1243
|
This displays the selected seat number and show date for ticket products instead of the variant name. |
|
1244
|
|
|
1245
|
You should also remove the quantity selector for ticket products since you can't purchase multiple tickets for the same seat. Remove the following highlighted lines from the `return` statement of the `Item` component: |
|
1246
|
|
|
1247
|
```tsx title="src/modules/cart/components/item/index.tsx" |
|
1248
|
{type === "full" && ( |
|
1249
|
<Table.Cell> |
|
1250
|
<div className="flex gap-2 items-center w-28"> |
|
1251
|
<DeleteButton id={item.id} data-testid="product-delete-button" /> |
|
1252
|
<CartItemSelect |
|
1253
|
value={item.quantity} |
|
1254
|
onChange={(value) => changeQuantity(parseInt(value.target.value))} |
|
1255
|
className="w-14 h-10 p-4" |
|
1256
|
data-testid="product-select-button" |
|
1257
|
> |
|
1258
|
{/* TODO: Update this with the v2 way of managing inventory */} |
|
1259
|
{Array.from( |
|
1260
|
{ |
|
1261
|
length: Math.min(maxQuantity, 10), |
|
1262
|
}, |
|
1263
|
(_, i) => ( |
|
1264
|
<option value={i + 1} key={i}> |
|
1265
|
{i + 1} |
|
1266
|
</option> |
|
1267
|
) |
|
1268
|
)} |
|
1269
|
|
|
1270
|
<option value={1} key={1}> |
|
1271
|
1 |
|
1272
|
</option> |
|
1273
|
</CartItemSelect> |
|
1274
|
{updating && <Spinner />} |
|
1275
|
</div> |
|
1276
|
<ErrorMessage error={error} data-testid="product-error-message" /> |
|
1277
|
</Table.Cell> |
|
1278
|
)} |
|
1279
|
``` |
|
1280
|
|
|
1281
|
This removes the quantity selector and error message for ticket products. |
|
1282
|
|
|
1283
|
You can also remove the quantity indicator later in the component. Remove the following line from the `return` statement of the `Item` component: |
|
1284
|
|
|
1285
|
```tsx title="src/modules/cart/components/item/index.tsx" |
|
1286
|
<Text className="text-ui-fg-muted">{item.quantity}x </Text> |
|
1287
|
``` |
|
1288
|
|
|
1289
|
This prevents displaying the quantity for ticket products, as it's redundant. |
|
1290
|
|
|
1291
|
### Add Billing Address Step |
|
1292
|
|
|
1293
|
Next, you'll add a component that shows a step to enter the billing address during checkout. You'll later use this component in the checkout page. |
|
1294
|
|
|
1295
|
Create the file `src/modules/checkout/components/billing-address/index.tsx` with the following content: |
|
1296
|
|
|
1297
|
```tsx title="src/modules/checkout/components/billing-address/index.tsx" collapsibleLines="1-8" expandButtonLabel="Show Imports" |
|
1298
|
import { HttpTypes } from "@medusajs/types" |
|
1299
|
import { Container } from "@medusajs/ui" |
|
1300
|
import Input from "@modules/common/components/input" |
|
1301
|
import { mapKeys } from "lodash" |
|
1302
|
import React, { useEffect, useMemo, useState } from "react" |
|
1303
|
import AddressSelect from "../address-select" |
|
1304
|
import CountrySelect from "../country-select" |
|
1305
|
|
|
1306
|
const BillingAddress = ({ |
|
1307
|
customer, |
|
1308
|
cart, |
|
1309
|
}: { |
|
1310
|
customer: HttpTypes.StoreCustomer | null |
|
1311
|
cart: HttpTypes.StoreCart | null |
|
1312
|
}) => { |
|
1313
|
const [formData, setFormData] = useState<Record<string, any>>({ |
|
1314
|
"billing_address.first_name": cart?.billing_address?.first_name || "", |
|
1315
|
"billing_address.last_name": cart?.billing_address?.last_name || "", |
|
1316
|
"billing_address.address_1": cart?.billing_address?.address_1 || "", |
|
1317
|
"billing_address.company": cart?.billing_address?.company || "", |
|
1318
|
"billing_address.postal_code": cart?.billing_address?.postal_code || "", |
|
1319
|
"billing_address.city": cart?.billing_address?.city || "", |
|
1320
|
"billing_address.country_code": cart?.billing_address?.country_code || "", |
|
1321
|
"billing_address.province": cart?.billing_address?.province || "", |
|
1322
|
"billing_address.phone": cart?.billing_address?.phone || "", |
|
1323
|
email: cart?.email || "", |
|
1324
|
}) |
|
1325
|
|
|
1326
|
const countriesInRegion = useMemo( |
|
1327
|
() => cart?.region?.countries?.map((c) => c.iso_2), |
|
1328
|
[cart?.region] |
|
1329
|
) |
|
1330
|
|
|
1331
|
// check if customer has saved addresses that are in the current region |
|
1332
|
const addressesInRegion = useMemo( |
|
1333
|
() => |
|
1334
|
customer?.addresses.filter( |
|
1335
|
(a) => a.country_code && countriesInRegion?.includes(a.country_code) |
|
1336
|
), |
|
1337
|
[customer?.addresses, countriesInRegion] |
|
1338
|
) |
|
1339
|
|
|
1340
|
const setFormAddress = ( |
|
1341
|
address?: HttpTypes.StoreCartAddress, |
|
1342
|
email?: string |
|
1343
|
) => { |
|
1344
|
address && |
|
1345
|
setFormData((prevState: Record<string, any>) => ({ |
|
1346
|
...prevState, |
|
1347
|
"billing_address.first_name": address?.first_name || "", |
|
1348
|
"billing_address.last_name": address?.last_name || "", |
|
1349
|
"billing_address.address_1": address?.address_1 || "", |
|
1350
|
"billing_address.company": address?.company || "", |
|
1351
|
"billing_address.postal_code": address?.postal_code || "", |
|
1352
|
"billing_address.city": address?.city || "", |
|
1353
|
"billing_address.country_code": address?.country_code || "", |
|
1354
|
"billing_address.province": address?.province || "", |
|
1355
|
"billing_address.phone": address?.phone || "", |
|
1356
|
})) |
|
1357
|
|
|
1358
|
email && |
|
1359
|
setFormData((prevState: Record<string, any>) => ({ |
|
1360
|
...prevState, |
|
1361
|
email: email, |
|
1362
|
})) |
|
1363
|
} |
|
1364
|
|
|
1365
|
useEffect(() => { |
|
1366
|
// Ensure cart is not null and has a billing_address before setting form data |
|
1367
|
if (cart && cart.billing_address) { |
|
1368
|
setFormAddress(cart?.billing_address, cart?.email) |
|
1369
|
} |
|
1370
|
|
|
1371
|
if (cart && !cart.email && customer?.email) { |
|
1372
|
setFormAddress(undefined, customer.email) |
|
1373
|
} |
|
1374
|
}, [cart]) // Add cart as a dependency |
|
1375
|
|
|
1376
|
const handleChange = ( |
|
1377
|
e: React.ChangeEvent< |
|
1378
|
HTMLInputElement | HTMLInputElement | HTMLSelectElement |
|
1379
|
> |
|
1380
|
) => { |
|
1381
|
setFormData({ |
|
1382
|
...formData, |
|
1383
|
[e.target.name]: e.target.value, |
|
1384
|
}) |
|
1385
|
} |
|
1386
|
|
|
1387
|
return ( |
|
1388
|
<> |
|
1389
|
{customer && (addressesInRegion?.length || 0) > 0 && ( |
|
1390
|
<Container className="mb-6 flex flex-col gap-y-4 p-5"> |
|
1391
|
<p className="text-small-regular"> |
|
1392
|
{`Hi ${customer.first_name}, do you want to use one of your saved addresses?`} |
|
1393
|
</p> |
|
1394
|
<AddressSelect |
|
1395
|
addresses={customer.addresses} |
|
1396
|
addressInput={ |
|
1397
|
mapKeys(formData, (_, key) => |
|
1398
|
key.replace("billing_address.", "") |
|
1399
|
) as HttpTypes.StoreCartAddress |
|
1400
|
} |
|
1401
|
onSelect={setFormAddress} |
|
1402
|
/> |
|
1403
|
</Container> |
|
1404
|
)} |
|
1405
|
<div className="grid grid-cols-2 gap-4"> |
|
1406
|
<Input |
|
1407
|
label="First name" |
|
1408
|
name="billing_address.first_name" |
|
1409
|
autoComplete="given-name" |
|
1410
|
value={formData["billing_address.first_name"]} |
|
1411
|
onChange={handleChange} |
|
1412
|
required |
|
1413
|
data-testid="shipping-first-name-input" |
|
1414
|
/> |
|
1415
|
<Input |
|
1416
|
label="Last name" |
|
1417
|
name="billing_address.last_name" |
|
1418
|
autoComplete="family-name" |
|
1419
|
value={formData["billing_address.last_name"]} |
|
1420
|
onChange={handleChange} |
|
1421
|
required |
|
1422
|
data-testid="shipping-last-name-input" |
|
1423
|
/> |
|
1424
|
<Input |
|
1425
|
label="Address" |
|
1426
|
name="billing_address.address_1" |
|
1427
|
autoComplete="address-line1" |
|
1428
|
value={formData["billing_address.address_1"]} |
|
1429
|
onChange={handleChange} |
|
1430
|
required |
|
1431
|
data-testid="shipping-address-input" |
|
1432
|
/> |
|
1433
|
<Input |
|
1434
|
label="Company" |
|
1435
|
name="billing_address.company" |
|
1436
|
value={formData["billing_address.company"]} |
|
1437
|
onChange={handleChange} |
|
1438
|
autoComplete="organization" |
|
1439
|
data-testid="shipping-company-input" |
|
1440
|
/> |
|
1441
|
<Input |
|
1442
|
label="Postal code" |
|
1443
|
name="billing_address.postal_code" |
|
1444
|
autoComplete="postal-code" |
|
1445
|
value={formData["billing_address.postal_code"]} |
|
1446
|
onChange={handleChange} |
|
1447
|
required |
|
1448
|
data-testid="shipping-postal-code-input" |
|
1449
|
/> |
|
1450
|
<Input |
|
1451
|
label="City" |
|
1452
|
name="billing_address.city" |
|
1453
|
autoComplete="address-level2" |
|
1454
|
value={formData["billing_address.city"]} |
|
1455
|
onChange={handleChange} |
|
1456
|
required |
|
1457
|
data-testid="shipping-city-input" |
|
1458
|
/> |
|
1459
|
<CountrySelect |
|
1460
|
name="billing_address.country_code" |
|
1461
|
autoComplete="country" |
|
1462
|
region={cart?.region} |
|
1463
|
value={formData["billing_address.country_code"]} |
|
1464
|
onChange={handleChange} |
|
1465
|
required |
|
1466
|
data-testid="shipping-country-select" |
|
1467
|
/> |
|
1468
|
<Input |
|
1469
|
label="State / Province" |
|
1470
|
name="billing_address.province" |
|
1471
|
autoComplete="address-level1" |
|
1472
|
value={formData["billing_address.province"]} |
|
1473
|
onChange={handleChange} |
|
1474
|
data-testid="shipping-province-input" |
|
1475
|
/> |
|
1476
|
<Input |
|
1477
|
label="Email" |
|
1478
|
name="email" |
|
1479
|
type="email" |
|
1480
|
title="Enter a valid email address." |
|
1481
|
autoComplete="email" |
|
1482
|
value={formData.email} |
|
1483
|
onChange={handleChange} |
|
1484
|
required |
|
1485
|
data-testid="shipping-email-input" |
|
1486
|
/> |
|
1487
|
<Input |
|
1488
|
label="Phone" |
|
1489
|
name="billing_address.phone" |
|
1490
|
autoComplete="tel" |
|
1491
|
value={formData["billing_address.phone"]} |
|
1492
|
onChange={handleChange} |
|
1493
|
data-testid="shipping-phone-input" |
|
1494
|
/> |
|
1495
|
</div> |
|
1496
|
</> |
|
1497
|
) |
|
1498
|
} |
|
1499
|
|
|
1500
|
export default BillingAddress |
|
1501
|
``` |
|
1502
|
|
|
1503
|
This displays the billing address form with the relevant fields. If the customer has saved addresses, it also displays an address selector at the top. |
|
1504
|
|
|
1505
|
### Update Checkout Steps |
|
1506
|
|
|
1507
|
Next, you'll update the checkout steps to remove the shipping address and shipping method steps, and add the billing address step. |
|
1508
|
|
|
1509
|
In `src/modules/checkout/templates/checkout-form/index.tsx`, remove the `shippingMethods` variable in the `CheckoutForm` component and change the condition before the `return` statement: |
|
1510
|
|
|
1511
|
```tsx title="src/modules/checkout/templates/checkout-form/index.tsx" highlights={[["10"], ["14"]]} |
|
1512
|
export default async function CheckoutForm({ |
|
1513
|
cart, |
|
1514
|
customer, |
|
1515
|
}: { |
|
1516
|
cart: HttpTypes.StoreCart | null |
|
1517
|
customer: HttpTypes.StoreCustomer | null |
|
1518
|
}) { |
|
1519
|
// ... |
|
1520
|
// REMOVE THIS LINE |
|
1521
|
// const shippingMethods = await listCartShippingMethods(cart.id) |
|
1522
|
const paymentMethods = await listCartPaymentMethods(cart.region?.id ?? "") |
|
1523
|
|
|
1524
|
// Change this condition to only check for payment methods |
|
1525
|
if (!paymentMethods) { |
|
1526
|
return null |
|
1527
|
} |
|
1528
|
// ... |
|
1529
|
} |
|
1530
|
``` |
|
1531
|
|
|
1532
|
This removes the `shippingMethods` variable and changes the condition to only check for payment methods since shipping is not needed for ticket products. |
|
1533
|
|
|
1534
|
Then, remove the `Shipping` component from the `return` statement. The `return` statement should look like this: |
|
1535
|
|
|
1536
|
```tsx title="src/modules/checkout/templates/checkout-form/index.tsx" |
|
1537
|
return ( |
|
1538
|
<div className="w-full grid grid-cols-1 gap-y-8"> |
|
1539
|
<Addresses cart={cart} customer={customer} /> |
|
1540
|
|
|
1541
|
<Payment cart={cart} availablePaymentMethods={paymentMethods} /> |
|
1542
|
|
|
1543
|
<Review cart={cart} /> |
|
1544
|
</div> |
|
1545
|
) |
|
1546
|
``` |
|
1547
|
|
|
1548
|
This removes the `Shipping` component since shipping is not needed for ticket products. |
|
1549
|
|
|
1550
|
Next, you'll update the `Addresses` component to use the `BillingAddress` component you created earlier. |
|
1551
|
|
|
1552
|
In `src/modules/checkout/components/addresses/index.tsx`, add the following import at the top of the file: |
|
1553
|
|
|
1554
|
```tsx title="src/modules/checkout/components/addresses/index.tsx" |
|
1555
|
import BillingAddress from "../billing-address" |
|
1556
|
``` |
|
1557
|
|
|
1558
|
Then, you'll change the `return` statement of the `Addresses` component to: |
|
1559
|
|
|
1560
|
1. Use the `BillingAddress` component instead of the `ShippingAddress` component. |
|
1561
|
2. Update the header text to "Billing Address". |
|
1562
|
3. Replace all instances of `shipping_address` with `billing_address`. |
|
1563
|
4. Remove the same-as-billing checkbox and related logic. |
|
1564
|
5. Change the button that proceeds to the next step to say "Continue to payment". |
|
1565
|
|
|
1566
|
The `return` statement should look like this: |
|
1567
|
|
|
1568
|
```tsx title="src/modules/checkout/components/addresses/index.tsx" |
|
1569
|
return ( |
|
1570
|
<div className="bg-white"> |
|
1571
|
<div className="flex flex-row items-center justify-between mb-6"> |
|
1572
|
<Heading |
|
1573
|
level="h2" |
|
1574
|
className="flex flex-row text-3xl-regular gap-x-2 items-baseline" |
|
1575
|
> |
|
1576
|
Billing Address |
|
1577
|
{!isOpen && <CheckCircleSolid />} |
|
1578
|
</Heading> |
|
1579
|
{!isOpen && cart?.billing_address && ( |
|
1580
|
<Text> |
|
1581
|
<button |
|
1582
|
onClick={handleEdit} |
|
1583
|
className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover" |
|
1584
|
data-testid="edit-address-button" |
|
1585
|
> |
|
1586
|
Edit |
|
1587
|
</button> |
|
1588
|
</Text> |
|
1589
|
)} |
|
1590
|
</div> |
|
1591
|
{isOpen ? ( |
|
1592
|
<form action={formAction}> |
|
1593
|
<div className="pb-8"> |
|
1594
|
<BillingAddress |
|
1595
|
customer={customer} |
|
1596
|
cart={cart} |
|
1597
|
/> |
|
1598
|
<SubmitButton className="mt-6" data-testid="submit-address-button"> |
|
1599
|
Continue to payment |
|
1600
|
</SubmitButton> |
|
1601
|
<ErrorMessage error={message} data-testid="address-error-message" /> |
|
1602
|
</div> |
|
1603
|
</form> |
|
1604
|
) : ( |
|
1605
|
<div> |
|
1606
|
<div className="text-small-regular"> |
|
1607
|
{cart && cart.billing_address ? ( |
|
1608
|
<div className="flex items-start gap-x-8"> |
|
1609
|
<div className="flex items-start gap-x-1 w-full"> |
|
1610
|
<div |
|
1611
|
className="flex flex-col w-1/3" |
|
1612
|
data-testid="billing-address-summary" |
|
1613
|
> |
|
1614
|
<Text className="txt-medium-plus text-ui-fg-base mb-1"> |
|
1615
|
Billing Address |
|
1616
|
</Text> |
|
1617
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1618
|
{cart.billing_address.first_name}{" "} |
|
1619
|
{cart.billing_address.last_name} |
|
1620
|
</Text> |
|
1621
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1622
|
{cart.billing_address.address_1}{" "} |
|
1623
|
{cart.billing_address.address_2} |
|
1624
|
</Text> |
|
1625
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1626
|
{cart.billing_address.postal_code},{" "} |
|
1627
|
{cart.billing_address.city} |
|
1628
|
</Text> |
|
1629
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1630
|
{cart.billing_address.country_code?.toUpperCase()} |
|
1631
|
</Text> |
|
1632
|
</div> |
|
1633
|
|
|
1634
|
<div |
|
1635
|
className="flex flex-col w-1/3 " |
|
1636
|
data-testid="billing-contact-summary" |
|
1637
|
> |
|
1638
|
<Text className="txt-medium-plus text-ui-fg-base mb-1"> |
|
1639
|
Contact |
|
1640
|
</Text> |
|
1641
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1642
|
{cart.billing_address.phone} |
|
1643
|
</Text> |
|
1644
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1645
|
{cart.email} |
|
1646
|
</Text> |
|
1647
|
</div> |
|
1648
|
|
|
1649
|
<div |
|
1650
|
className="flex flex-col w-1/3" |
|
1651
|
data-testid="billing-address-summary" |
|
1652
|
> |
|
1653
|
<Text className="txt-medium-plus text-ui-fg-base mb-1"> |
|
1654
|
Billing Address |
|
1655
|
</Text> |
|
1656
|
</div> |
|
1657
|
</div> |
|
1658
|
</div> |
|
1659
|
) : ( |
|
1660
|
<div> |
|
1661
|
<Spinner /> |
|
1662
|
</div> |
|
1663
|
)} |
|
1664
|
</div> |
|
1665
|
</div> |
|
1666
|
)} |
|
1667
|
<Divider className="mt-8" /> |
|
1668
|
</div> |
|
1669
|
) |
|
1670
|
``` |
|
1671
|
|
|
1672
|
Next, you'll update other steps to remove the checks for the shipping address and shipping method. |
|
1673
|
|
|
1674
|
In `src/modules/checkout/components/payment/index.tsx`, find the `paymentReady` variable in the `Payment` component and change it to the following: |
|
1675
|
|
|
1676
|
```tsx title="src/modules/checkout/components/payment/index.tsx" |
|
1677
|
const paymentReady = |
|
1678
|
activeSession || paidByGiftcard |
|
1679
|
``` |
|
1680
|
|
|
1681
|
Similarly, in `src/modules/checkout/components/payment-button/index.tsx`, find the `notReady` variable in the `PaymentButton` component and change it to the following: |
|
1682
|
|
|
1683
|
```tsx title="src/modules/checkout/components/payment-button/index.tsx" |
|
1684
|
const notReady = |
|
1685
|
!cart || |
|
1686
|
!cart.billing_address || |
|
1687
|
!cart.email |
|
1688
|
``` |
|
1689
|
|
|
1690
|
Finally, in `src/modules/checkout/components/review/index.tsx`, find the `previousStepsCompleted` variable in the `Review` component and change it to the following: |
|
1691
|
|
|
1692
|
```tsx title="src/modules/checkout/components/review/index.tsx" |
|
1693
|
const previousStepsCompleted = |
|
1694
|
cart.billing_address && |
|
1695
|
(cart.payment_collection || paidByGiftcard) |
|
1696
|
``` |
|
1697
|
|
|
1698
|
### Update Cart Functions |
|
1699
|
|
|
1700
|
Next, you'll update cart server functions to retrieve and save the billing address instead of the shipping address, and to use the custom cart completion API route. |
|
1701
|
|
|
1702
|
In `src/lib/data/cart.ts`, find the `retrieveCart` function and update the `fields` variable to include `billing_address`: |
|
1703
|
|
|
1704
|
```ts title="src/lib/data/cart.ts" |
|
1705
|
export async function retrieveCart(cartId?: string, fields?: string) { |
|
1706
|
fields ??= "*items, *region, *items.product, *items.variant, *items.thumbnail, *items.metadata, +items.total, *promotions, +shipping_methods.name, *billing_address" |
|
1707
|
// ... |
|
1708
|
} |
|
1709
|
``` |
|
1710
|
|
|
1711
|
Then, you need to update the `setAddresses` function in the same file to only save billing address information. Replace the entire function with the following: |
|
1712
|
|
|
1713
|
```ts title="src/lib/data/cart.ts" |
|
1714
|
export async function setAddresses(currentState: unknown, formData: FormData) { |
|
1715
|
try { |
|
1716
|
if (!formData) { |
|
1717
|
throw new Error("No form data found when setting addresses") |
|
1718
|
} |
|
1719
|
const cartId = getCartId() |
|
1720
|
if (!cartId) { |
|
1721
|
throw new Error("No existing cart found when setting addresses") |
|
1722
|
} |
|
1723
|
|
|
1724
|
const data = { |
|
1725
|
billing_address: { |
|
1726
|
first_name: formData.get("billing_address.first_name"), |
|
1727
|
last_name: formData.get("billing_address.last_name"), |
|
1728
|
address_1: formData.get("billing_address.address_1"), |
|
1729
|
address_2: "", |
|
1730
|
company: formData.get("billing_address.company"), |
|
1731
|
postal_code: formData.get("billing_address.postal_code"), |
|
1732
|
city: formData.get("billing_address.city"), |
|
1733
|
country_code: formData.get("billing_address.country_code"), |
|
1734
|
province: formData.get("billing_address.province"), |
|
1735
|
phone: formData.get("billing_address.phone"), |
|
1736
|
}, |
|
1737
|
email: formData.get("email"), |
|
1738
|
} as any |
|
1739
|
await updateCart(data) |
|
1740
|
} catch (e: any) { |
|
1741
|
return e.message |
|
1742
|
} |
|
1743
|
|
|
1744
|
redirect( |
|
1745
|
`/${formData.get("billing_address.country_code")}/checkout?step=payment` |
|
1746
|
) |
|
1747
|
} |
|
1748
|
``` |
|
1749
|
|
|
1750
|
This updates the function to only handle the billing address and email fields. It also redirects to the `payment` step of checkout instead of the `shipping` step. |
|
1751
|
|
|
1752
|
Finally, you'll update the `placeOrder` function to use the custom cart completion API route you created in the [backend part of the tutorial](../page.mdx#custom-complete-cart-workflow). Replace the entire function with the following: |
|
1753
|
|
|
1754
|
```ts title="src/lib/data/cart.ts" |
|
1755
|
export async function placeOrder(cartId?: string) { |
|
1756
|
const id = cartId || (await getCartId()) |
|
1757
|
|
|
1758
|
if (!id) { |
|
1759
|
throw new Error("No existing cart found when placing an order") |
|
1760
|
} |
|
1761
|
|
|
1762
|
const headers = { |
|
1763
|
...(await getAuthHeaders()), |
|
1764
|
} |
|
1765
|
|
|
1766
|
const cartRes = await sdk.client.fetch<HttpTypes.StoreCompleteCartResponse>(`/store/carts/${id}/complete-tickets`, { |
|
1767
|
method: "POST", |
|
1768
|
headers, |
|
1769
|
}) |
|
1770
|
.then(async (cartRes) => { |
|
1771
|
const cartCacheTag = await getCacheTag("carts") |
|
1772
|
revalidateTag(cartCacheTag) |
|
1773
|
return cartRes |
|
1774
|
}) |
|
1775
|
.catch(medusaError) |
|
1776
|
|
|
1777
|
if (cartRes?.type === "order") { |
|
1778
|
const countryCode = |
|
1779
|
cartRes.order.billing_address?.country_code?.toLowerCase() |
|
1780
|
|
|
1781
|
const orderCacheTag = await getCacheTag("orders") |
|
1782
|
revalidateTag(orderCacheTag) |
|
1783
|
|
|
1784
|
removeCartId() |
|
1785
|
redirect(`/${countryCode}/order/${cartRes?.order.id}/confirmed`) |
|
1786
|
} |
|
1787
|
|
|
1788
|
return cartRes.cart |
|
1789
|
} |
|
1790
|
``` |
|
1791
|
|
|
1792
|
This updates the function to call the `/store/carts/{id}/complete-tickets` endpoint to complete the cart and place the order. It also retrieves the country code from the billing address instead of the shipping address to redirect to the order confirmation page. |
|
1793
|
|
|
1794
|
### Test Checkout Page |
|
1795
|
|
|
1796
|
To test the latest cart and checkout changes, start both the Medusa application and the Next.js Starter Storefront. |
|
1797
|
|
|
1798
|
Then, add a ticket product to the cart by selecting a date, quantity, and seats on the product page. You'll be taken to the checkout page where you can see only three steps: Billing Address, Payment, and Review. |
|
1799
|
|
|
1800
|
 |
|
1801
|
|
|
1802
|
Fill out the billing address form, choose a payment method, and click "Place Order" in the Review step. Once the order is placed, you'll be redirected to the order confirmation page. You may see an error related to shipping details missing, which you'll fix by customizing the order confirmation page next. |
|
1803
|
|
|
1804
|
--- |
|
1805
|
|
|
1806
|
## Step 5: Customize Order Confirmation Page |
|
1807
|
|
|
1808
|
The last storefront customization you'll make is to: |
|
1809
|
|
|
1810
|
- Display billing details instead of shipping details on the order confirmation page. |
|
1811
|
- Display the selected seats and show date for each ticket item on the order confirmation page. |
|
1812
|
|
|
1813
|
### Add Billing Details Component |
|
1814
|
|
|
1815
|
First, you'll create a component that displays the billing details on the order confirmation page. |
|
1816
|
|
|
1817
|
Create the file `src/modules/order/components/billing-details/index.tsx` with the following content: |
|
1818
|
|
|
1819
|
```tsx title="src/modules/order/components/billing-details/index.tsx" |
|
1820
|
import { convertToLocale } from "@lib/util/money" |
|
1821
|
import { HttpTypes } from "@medusajs/types" |
|
1822
|
import { Heading, Text } from "@medusajs/ui" |
|
1823
|
|
|
1824
|
import Divider from "@modules/common/components/divider" |
|
1825
|
|
|
1826
|
type BillingDetailsProps = { |
|
1827
|
order: HttpTypes.StoreOrder |
|
1828
|
} |
|
1829
|
|
|
1830
|
const BillingDetails = ({ order }: BillingDetailsProps) => { |
|
1831
|
return ( |
|
1832
|
<div> |
|
1833
|
<Heading level="h2" className="flex flex-row text-3xl-regular my-6"> |
|
1834
|
Billing Address |
|
1835
|
</Heading> |
|
1836
|
<div className="flex items-start gap-x-8"> |
|
1837
|
<div |
|
1838
|
className="flex flex-col w-1/3" |
|
1839
|
data-testid="shipping-address-summary" |
|
1840
|
> |
|
1841
|
<Text className="txt-medium-plus text-ui-fg-base mb-1"> |
|
1842
|
Billing Address |
|
1843
|
</Text> |
|
1844
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1845
|
{order.billing_address?.first_name}{" "} |
|
1846
|
{order.billing_address?.last_name} |
|
1847
|
</Text> |
|
1848
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1849
|
{order.billing_address?.address_1}{" "} |
|
1850
|
{order.billing_address?.address_2} |
|
1851
|
</Text> |
|
1852
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1853
|
{order.billing_address?.postal_code},{" "} |
|
1854
|
{order.billing_address?.city} |
|
1855
|
</Text> |
|
1856
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1857
|
{order.billing_address?.country_code?.toUpperCase()} |
|
1858
|
</Text> |
|
1859
|
</div> |
|
1860
|
|
|
1861
|
<div |
|
1862
|
className="flex flex-col w-1/3 " |
|
1863
|
data-testid="billing-contact-summary" |
|
1864
|
> |
|
1865
|
<Text className="txt-medium-plus text-ui-fg-base mb-1">Contact</Text> |
|
1866
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1867
|
{order.billing_address?.phone} |
|
1868
|
</Text> |
|
1869
|
<Text className="txt-medium text-ui-fg-subtle">{order.email}</Text> |
|
1870
|
</div> |
|
1871
|
</div> |
|
1872
|
<Divider className="mt-8" /> |
|
1873
|
</div> |
|
1874
|
) |
|
1875
|
} |
|
1876
|
|
|
1877
|
export default BillingDetails |
|
1878
|
``` |
|
1879
|
|
|
1880
|
This component displays the billing address and contact information from the order. |
|
1881
|
|
|
1882
|
Then, you'll update the order confirmation and order details pages to use the `BillingDetails` component. |
|
1883
|
|
|
1884
|
In `src/modules/order/templates/order-completed-template.tsx`, add the following import at the top of the file: |
|
1885
|
|
|
1886
|
```tsx title="src/modules/order/templates/order-completed-template.tsx" |
|
1887
|
import BillingDetails from "@modules/order/components/billing-details" |
|
1888
|
``` |
|
1889
|
|
|
1890
|
And replace the `ShippingDetails` component in the `return` statement of the `OrderCompletedTemplate` component with the `BillingDetails` component: |
|
1891
|
|
|
1892
|
```tsx title="src/modules/order/templates/order-completed-template.tsx" |
|
1893
|
<BillingDetails order={order} /> |
|
1894
|
``` |
|
1895
|
|
|
1896
|
Similarly, in `src/modules/order/templates/order-details-template.tsx`, add the following import at the top of the file: |
|
1897
|
|
|
1898
|
```tsx title="src/modules/order/templates/order-details-template.tsx" |
|
1899
|
import BillingDetails from "@modules/order/components/billing-details" |
|
1900
|
``` |
|
1901
|
|
|
1902
|
And replace the `ShippingDetails` component in the `return` statement of the `OrderDetailsTemplate` component with the `BillingDetails` component: |
|
1903
|
|
|
1904
|
```tsx title="src/modules/order/templates/order-details-template.tsx" |
|
1905
|
<BillingDetails order={order} /> |
|
1906
|
``` |
|
1907
|
|
|
1908
|
The order confirmation page now should show the billing details instead of shipping details. |
|
1909
|
|
|
1910
|
 |
|
1911
|
|
|
1912
|
### Show Selected Seats in Order Items |
|
1913
|
|
|
1914
|
Next, you'll update the order item component to display the selected seats and show date for ticket products. |
|
1915
|
|
|
1916
|
In `src/modules/order/components/item/index.tsx`, find the `LineItemOptions` component in the `return` statement of the `Item` component, and replace it with the following: |
|
1917
|
|
|
1918
|
```tsx title="src/modules/order/components/item/index.tsx" |
|
1919
|
{item.metadata?.seat_number !== undefined && ( |
|
1920
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1921
|
Seat {item.metadata?.row_number as string}{item.metadata?.seat_number as string} |
|
1922
|
</Text> |
|
1923
|
)} |
|
1924
|
{item.metadata?.show_date !== undefined && ( |
|
1925
|
<Text className="txt-medium text-ui-fg-subtle"> |
|
1926
|
Show Date: {new Date(item.metadata?.show_date as string).toLocaleDateString()} |
|
1927
|
</Text> |
|
1928
|
)} |
|
1929
|
``` |
|
1930
|
|
|
1931
|
You can also remove the quantity by removing the following line from the `return` statement of the `Item` component: |
|
1932
|
|
|
1933
|
```tsx title="src/modules/order/components/item/index.tsx" |
|
1934
|
<Text className="text-ui-fg-muted"> |
|
1935
|
<span data-testid="product-quantity">{item.quantity}</span>x{" "} |
|
1936
|
</Text> |
|
1937
|
``` |
|
1938
|
|
|
1939
|
This prevents displaying the quantity for ticket products, as it's redundant. |
|
1940
|
|
|
1941
|
If you check the order confirmation page now, you'll see the selected seats and show dates for each ticket item. |
|
1942
|
|
|
1943
|
 |
|
1944
|
|
|
1945
|
--- |
|
1946
|
|
|
1947
|
## Next Steps |
|
1948
|
|
|
1949
|
You've now customized the Next.js Starter Storefront to support ticket products. You can further customize the storefront to change the styling and user experience to fit your brand. |
|
1950
|
|
|
1951
|
### Learn More About Medusa |
|
1952
|
|
|
1953
|
If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth understanding of all the concepts you've used in this guide and more. |
|
1954
|
|
|
1955
|
To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../..//commerce-modules/page.mdx). |
|
1956
|
|
|
1957
|
### Troubleshooting |
|
1958
|
|
|
1959
|
If you encounter issues during your development, check out the [troubleshooting guides](../../../..//troubleshooting/page.mdx). |
|
1960
|
|
|
1961
|
### Getting Help |
|
1962
|
|
|
1963
|
If you encounter issues not covered in the troubleshooting guides: |
|
1964
|
|
|
1965
|
1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions. |
|
1966
|
2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members. |