1 ---
2 sidebar_label: "Example"
3 tags:
4 - name: product
5 label: "Implement Ticket Booking"
6 - server
7 - tutorial
8 products:
9 - product
10 - cart
11 - order
12 ---
13
14 import { Github, PlaySolid } from "@medusajs/icons"
15 import { Prerequisites, WorkflowDiagram, CardList } from "docs-ui"
16
17 export const metadata = {
18 title: `Implement a Ticket Booking System with Medusa`,
19 }
20
21 # {metadata.title}
22
23 In this tutorial, you'll learn how to implement a ticket booking system using Medusa.
24
25 <Note>
26
27 This tutorial is divided into two parts: this part that covers the backend and admin customizations, and a [storefront part](./storefront/page.mdx) that covers the Next.js Starter Storefront customizations.
28
29 </Note>
30
31 When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. The Medusa application's commerce features are built around [Commerce Modules](../../../commerce-modules/page.mdx) that are available out-of-the-box.
32
33 The Medusa [Framework](!docs!/learn/fundamentals/framework) facilitates customizing Medusa's core features for your specific use case, such as ticket booking.
34
35 <Note>
36
37 This tutorial provides an approach to implement a ticket booking system using Medusa. Depending on your specific requirements, you might need to adjust the implementation details or explore a different approach.
38
39 </Note>
40
41 ## Summary
42
43 By following this tutorial, you will learn how to:
44
45 - Install and set up Medusa with the Next.js Starter Storefront.
46 - Create data models for venues and tickets, and link them to Medusa's data models.
47 - Customize the Medusa Admin to manage venues and shows or events.
48 - Implement custom validation and flows for ticket booking.
49 - Generate QR codes for tickets and verify them at the venue.
50 - [Extend the Next.js Starter Storefront to allow booking tickets and choosing seats](./storefront/page.mdx): This part of the tutorial is covered separately.
51
52 ![Diagram showing the architecture of the ticket booking system with Medusa](https://res.cloudinary.com/dza7lstvk/image/upload/v1757512301/Medusa%20Resources/ticket-booking-diagram_egbpye.jpg)
53
54 <CardList items={[
55 {
56 href: "https://github.com/medusajs/examples/tree/main/ticket-booking",
57 title: "Full Code",
58 text: "Find the full code for this tutorial in this repository.",
59 icon: Github,
60 },
61 {
62 href: "https://res.cloudinary.com/dza7lstvk/raw/upload/v1757423563/OpenApi/Ticket_Booking_System_iqq1k6.yaml",
63 title: "OpenApi Specs for Postman",
64 text: "Import this OpenApi Specs file into tools like Postman.",
65 icon: PlaySolid,
66 },
67 ]} />
68
69 ---
70
71 ## Step 1: Install a Medusa Application
72
73 <Prerequisites items={[
74 {
75 text: "Node.js v20.19.0+ or v22.12.0+",
76 link: "https://nodejs.org/en/download"
77 },
78 {
79 text: "Git CLI tool",
80 link: "https://git-scm.com/downloads"
81 },
82 {
83 text: "PostgreSQL",
84 link: "https://www.postgresql.org/download/"
85 }
86 ]} />
87
88 Start by installing the Medusa application on your machine with the following command:
89
90 ```bash npx2yarnExec
91 npx create-medusa-app@latest
92 ```
93
94 You'll first be asked for the project's name. Then, when asked whether you want to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose Yes.
95
96 the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory.
97
98 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterward, you can log in with the new user and explore the dashboard.
99
100 <Note title="Ran into Errors?">
101
102 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
103
104 </Note>
105
106 <Note>
107
108 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
109
110 </Note>
111
112 ---
113
114 ## Step 2: Create Ticket Booking Module
115
116 In Medusa, you can build custom features in a [module](!docs!/learn/fundamentals/modules). A module is a reusable package with the data models and functionality related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
117
118 In this step, you'll build a Ticket Booking Module that defines the data models and logic to manage venues and tickets. Later, you'll build commerce flows related to ticket booking around the module.
119
120 <Note>
121
122 Refer to the [Modules documentation](!docs!/learn/fundamentals/modules) to learn more.
123
124 </Note>
125
126 ### a. Create Module Directory
127
128 Create the directory `src/modules/ticket-booking` that will hold the Ticket Booking Module's code.
129
130 ### b. Define Data Models
131
132 A data model represents a table in the database. You create data models using Medusa's Data Model Language (DML). It simplifies defining a table's columns, relations, and indexes with straightforward methods and configurations.
133
134 <Note>
135
136 Refer to the [Data Models documentation](!docs!/learn/fundamentals/modules#1-create-data-model) to learn more.
137
138 </Note>
139
140 You'll define data models to represent venues, tickets, and purchases. Later, you'll link these data models to Medusa's data models, such as products and orders.
141
142 #### Venue Model
143
144 The `Venue` data model represents a venue where shows or events take place.
145
146 To create the `Venue` data model, create the file `src/modules/ticket-booking/models/venue.ts` with the following content:
147
148 ```ts title="src/modules/ticket-booking/models/venue.ts"
149 import { model } from "@medusajs/framework/utils"
150 import { VenueRow } from "./venue-row"
151
152 export const Venue = model.define("venue", {
153 id: model.id().primaryKey(),
154 name: model.text(),
155 address: model.text().nullable(),
156 rows: model.hasMany(() => VenueRow, {
157 mappedBy: "venue",
158 }),
159 })
160 .cascades({
161 delete: ["rows"],
162 })
163
164 export default Venue
165 ```
166
167 The `Venue` data model has the following properties:
168
169 - `id`: The primary key of the table.
170 - `name`: The name of the venue.
171 - `address`: The address of the venue.
172 - `rows`: A one-to-many relation with the `VenueRow` data model, which you'll create next.
173
174 <Note>
175
176 Learn more about defining data model properties in the [Property Types documentation](!docs!/learn/fundamentals/data-models/properties).
177
178 </Note>
179
180 #### VenueRow Model
181
182 The `VenueRow` data model represents a row in a venue, each with a specific type and number of seats.
183
184 To create the `VenueRow` data model, create the file `src/modules/ticket-booking/models/venue-row.ts` with the following content:
185
186 ```ts title="src/modules/ticket-booking/models/venue-row.ts"
187 import { model } from "@medusajs/framework/utils"
188 import { Venue } from "./venue"
189
190 export enum RowType {
191 PREMIUM = "premium",
192 BALCONY = "balcony",
193 STANDARD = "standard",
194 VIP = "vip"
195 }
196
197 export const VenueRow = model.define("venue_row", {
198 id: model.id().primaryKey(),
199 row_number: model.text(),
200 row_type: model.enum(RowType),
201 seat_count: model.number(),
202 venue: model.belongsTo(() => Venue, {
203 mappedBy: "rows",
204 }),
205 })
206 .indexes([
207 {
208 on: ["venue_id", "row_number"],
209 unique: true,
210 },
211 ])
212
213 export default VenueRow
214 ```
215
216 The `VenueRow` data model has the following properties:
217
218 - `id`: The primary key of the table.
219 - `row_number`: The identifier of the row, such as "A" and "B", or "1" and "2".
220 - `row_type`: The type of the row, which can be "premium", "balcony", "standard", or "vip".
221 - `seat_count`: The number of seats in the row.
222 - `venue`: A many-to-one relation with the `Venue` data model, which represents the venue that the row belongs to.
223
224 You also add a unique index on the combination of `venue_id` and `row_number` to ensure that each row number is unique within a venue.
225
226 #### TicketProduct Model
227
228 The `TicketProduct` data model represents a product purchased as a ticket, such as a show or event. It will be linked to Medusa's `Product` data model.
229
230 To create the `TicketProduct` data model, create the file `src/modules/ticket-booking/models/ticket-product.ts` with the following content:
231
232 ```ts title="src/modules/ticket-booking/models/ticket-product.ts"
233 import { model } from "@medusajs/framework/utils"
234 import { Venue } from "./venue"
235 import { TicketProductVariant } from "./ticket-product-variant"
236 import { TicketPurchase } from "./ticket-purchase"
237
238 export const TicketProduct = model.define("ticket_product", {
239 id: model.id().primaryKey(),
240 product_id: model.text().unique(),
241 venue: model.belongsTo(() => Venue),
242 dates: model.array(),
243 variants: model.hasMany(() => TicketProductVariant, {
244 mappedBy: "ticket_product",
245 }),
246 purchases: model.hasMany(() => TicketPurchase, {
247 mappedBy: "ticket_product",
248 }),
249 })
250 .indexes([
251 {
252 on: ["venue_id", "dates"],
253 },
254 ])
255
256 export default TicketProduct
257 ```
258
259 The `TicketProduct` data model has the following properties:
260
261 - `id`: The primary key of the table.
262 - `product_id`: The ID of the linked product in Medusa's `Product` data model.
263 - `venue`: A many-to-one relation with the `Venue` data model, which represents the venue where the show takes place.
264 - `dates`: An array of dates when the show takes place.
265 - `variants`: A one-to-many relation with the `TicketProductVariant` data model, which you'll create next.
266 - `purchases`: A one-to-many relation with the `TicketPurchase` data model, which you'll create next.
267
268 You also add an index on the combination of `venue_id` and `dates` to optimize queries that filter by these fields.
269
270 <Note title="Tip">
271
272 Data relevant for ticket sales like price, inventory, etc., are all either included in the `Product` and `ProductVariant` data models or their linked records. So, you don't need to duplicate this information in the `TicketProduct` data model.
273
274 </Note>
275
276 #### TicketProductVariant Model
277
278 The `TicketProductVariant` data model represents a variant of a ticket product, such as a specific row type. It will be linked to Medusa's `ProductVariant` data model.
279
280 To create the `TicketProductVariant` data model, create the file `src/modules/ticket-booking/models/ticket-product-variant.ts` with the following content:
281
282 ```ts title="src/modules/ticket-booking/models/ticket-product-variant.ts"
283 import { model } from "@medusajs/framework/utils"
284 import { TicketProduct } from "./ticket-product"
285 import { RowType } from "./venue-row"
286 import { TicketPurchase } from "./ticket-purchase"
287
288 export const TicketProductVariant = model.define("ticket_product_variant", {
289 id: model.id().primaryKey(),
290 product_variant_id: model.text().unique(),
291 ticket_product: model.belongsTo(() => TicketProduct, {
292 mappedBy: "variants",
293 }),
294 row_type: model.enum(RowType),
295 purchases: model.hasMany(() => TicketPurchase, {
296 mappedBy: "ticket_variant",
297 }),
298 })
299 .indexes([
300 {
301 on: ["ticket_product_id", "row_type"],
302 },
303 ])
304
305 export default TicketProductVariant
306 ```
307
308 The `TicketProductVariant` data model has the following properties:
309
310 - `id`: The primary key of the table.
311 - `product_variant_id`: The ID of the linked product variant in Medusa's `ProductVariant` data model.
312 - `ticket_product`: A many-to-one relation with the `TicketProduct` data model, which represents the ticket product the variant belongs to.
313 - `row_type`: The type of the row associated with the variant, which can be "premium", "balcony", "standard", or "vip".
314 - `purchases`: A one-to-many relation with the `TicketPurchase` data model, which you'll create next.
315
316 #### TicketPurchase Model
317
318 The `TicketPurchase` data model represents the purchase of a seat for a specific `TicketProduct`. It will be linked to Medusa's `Order` data model.
319
320 To create the `TicketPurchase` data model, create the file `src/modules/ticket-booking/models/ticket-purchase.ts` with the following content:
321
322 ```ts title="src/modules/ticket-booking/models/ticket-purchase.ts"
323 import { model } from "@medusajs/framework/utils"
324 import { TicketProduct } from "./ticket-product"
325 import { TicketProductVariant } from "./ticket-product-variant"
326 import { VenueRow } from "./venue-row"
327
328 export const TicketPurchase = model.define("ticket_purchase", {
329 id: model.id().primaryKey(),
330 order_id: model.text(),
331 ticket_product: model.belongsTo(() => TicketProduct),
332 ticket_variant: model.belongsTo(() => TicketProductVariant),
333 venue_row: model.belongsTo(() => VenueRow),
334 seat_number: model.text(),
335 show_date: model.dateTime(),
336 status: model.enum(["pending", "scanned"]).default("pending"),
337 })
338 .indexes([
339 {
340 on: ["order_id"],
341 },
342 {
343 on: ["ticket_product_id", "venue_row_id", "seat_number", "show_date"],
344 unique: true,
345 },
346 ])
347
348 export default TicketPurchase
349 ```
350
351 The `TicketPurchase` data model has the following properties:
352
353 - `id`: The primary key of the table.
354 - `order_id`: The ID of the linked order in Medusa's `Order` data model.
355 - `ticket_product`: A many-to-one relation with the `TicketProduct` data model, which represents the ticket product purchased.
356 - `ticket_variant`: A many-to-one relation with the `TicketProductVariant` data model, which represents the variant (row type) of the ticket product purchased.
357 - `venue_row`: A many-to-one relation with the `VenueRow` data model, which represents the row of the seat purchased.
358 - `seat_number`: The number of the seat purchased.
359 - `show_date`: The date of the show for which the ticket was purchased.
360 - `status`: The status of the ticket purchase, which can be "pending" or "scanned". This is useful later when you add QR scanning functionality.
361
362 You also add two indexes:
363
364 - An index on the `order_id` field to optimize queries that filter by this field.
365 - A unique index on the combination of `ticket_product_id`, `venue_row_id`, `seat_number`, and `show_date` to ensure that a specific seat for a specific show date can only be purchased once.
366
367 ### c. Create Module's Service
368
369 You can manage your module's data models in a service.
370
371 A service is a TypeScript class that the module exports. In the service's methods, you can connect to the database, allowing you to manage your data models, or connect to third-party services, which is useful if you're integrating with external services.
372
373 <Note>
374
375 Refer to the [Module Service documentation](!docs!/learn/fundamentals/modules#2-create-service) to learn more.
376
377 </Note>
378
379 To create the Ticket Booking Module's service, create the file `src/modules/ticket-booking/service.ts` with the following content:
380
381 ```ts title="src/modules/ticket-booking/service.ts"
382 import { MedusaService } from "@medusajs/framework/utils"
383 import Venue from "./models/venue"
384 import VenueRow from "./models/venue-row"
385 import TicketProduct from "./models/ticket-product"
386 import TicketProductVariant from "./models/ticket-product-variant"
387 import TicketPurchase from "./models/ticket-purchase"
388
389 export class TicketBookingModuleService extends MedusaService({
390 Venue,
391 VenueRow,
392 TicketProduct,
393 TicketProductVariant,
394 TicketPurchase,
395 }) { }
396
397 export default TicketBookingModuleService
398 ```
399
400 The `TicketBookingModuleService` extends `MedusaService`, which generates a class with data-management methods for your module's data models. This saves you time on implementing Create, Read, Update, and Delete (CRUD) methods.
401
402 The `TicketBookingModuleService` class now has methods like `createTicketProducts` and `retrieveVenue`.
403
404 <Note>
405
406 Find all methods generated by the `MedusaService` in [the Service Factory reference](../../../service-factory-reference/page.mdx).
407
408 </Note>
409
410 ### d. Export Module Definition
411
412 The final piece of a module is its definition, which you export in an `index.ts` file at its root directory. This definition tells Medusa the name of the module and its service.
413
414 So, create the file `src/modules/ticket-booking/index.ts` with the following content:
415
416 ```ts title="src/modules/ticket-booking/index.ts"
417 import TicketBookingModuleService from "./service"
418 import { Module } from "@medusajs/framework/utils"
419
420 export const TICKET_BOOKING_MODULE = "ticketBooking"
421
422 export default Module(TICKET_BOOKING_MODULE, {
423 service: TicketBookingModuleService,
424 })
425 ```
426
427 You use the `Module` function to create the module's definition. It accepts two parameters:
428
429 1. The module's name, which is `ticketBooking`.
430 2. An object with a required property `service` indicating the module's service.
431
432 You also export the module's name as `TICKET_BOOKING_MODULE` so you can reference it later.
433
434 ### e. Add Module to Medusa's Configurations
435
436 Once you finish building the module, add it to Medusa's configurations to start using it.
437
438 In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
439
440 ```ts title="medusa-config.ts"
441 module.exports = defineConfig({
442 // ...
443 modules: [
444 {
445 resolve: "./src/modules/ticket-booking",
446 },
447 ],
448 })
449 ```
450
451 Each object in the `modules` array has a `resolve` property, whose value is either a path to the module's directory, or an `npm` package’s name.
452
453 ### f. Generate Migrations
454
455 Since data models represent tables in the database, you define how they're created in the database with migrations. A migration is a TypeScript class that defines database changes made by a module.
456
457 <Note>
458
459 Refer to the [Migrations documentation](!docs!/learn/fundamentals/modules#5-generate-migrations) to learn more.
460
461 </Note>
462
463 Medusa's CLI tool can generate the migrations for you. To generate a migration for the Ticket Booking Module, run the following command in your Medusa application's directory:
464
465 ```bash npx2yarn
466 npx medusa db:generate ticketBooking
467 ```
468
469 The `db:generate` command of the Medusa CLI accepts the name of the module to generate the migration for. You'll now have a `migrations` directory under `src/modules/ticket-booking` that holds the generated migration.
470
471 Then, to reflect these migrations on the database, run the following command:
472
473 ```bash npx2yarn
474 npx medusa db:migrate
475 ```
476
477 The tables for the Ticket Booking Module's data models are now created in the database.
478
479 ---
480
481 ## Step 3: Link Ticket Booking to Medusa Data Models
482
483 Since Medusa isolates modules to integrate them into your application without side effects, you can't directly create relationships between data models of different modules.
484
485 Instead, Medusa provides a mechanism to define links between data models and retrieve and manage linked records while maintaining module isolation.
486
487 <Note>
488
489 Refer to the [Module Isolation documentation](!docs!/learn/fundamentals/modules/isolation) to learn more.
490
491 </Note>
492
493 In this step, you'll define a link between the data models in the Ticket Booking Module and Medusa's Commerce Modules.
494
495 ### a. TicketProduct \<\> Product Link
496
497 To define a link between the `TicketProduct` data model and Medusa's `Product` data model, create the file `src/links/ticket-product.ts` with the following content:
498
499 ```ts title="src/links/ticket-product.ts"
500 import TicketingModule from "../modules/ticket-booking"
501 import ProductModule from "@medusajs/medusa/product"
502 import { defineLink } from "@medusajs/framework/utils"
503
504 export default defineLink(
505 {
506 linkable: TicketingModule.linkable.ticketProduct,
507 deleteCascade: true,
508 },
509 ProductModule.linkable.product
510 )
511
512 ```
513
514 You define a link using the `defineLink` function. It accepts two parameters:
515
516 1. An object indicating the first data model part of the link. A module has a special `linkable` property that contains link configurations for its data models. You pass the linkable configurations of the Ticket Booking Module's `TicketProduct` data model. You also set the `deleteCascade` property to `true`, indicating that a ticket product should be deleted if its linked product is deleted.
517 2. An object indicating the second data model part of the link. You pass the linkable configurations of the Product Module's `Product` data model.
518
519 In later steps, you'll learn how this link allows you to retrieve and manage ticket products and their related Medusa products.
520
521 <Note title="Tip">
522
523 Refer to the [Module Links](!docs!/learn/fundamentals/module-links) documentation to learn more about defining links.
524
525 </Note>
526
527 ### b. TicketProductVariant \<\> ProductVariant Link
528
529 To define a link between the `TicketProductVariant` data model and Medusa's `ProductVariant` data model, create the file `src/links/ticket-product-variant.ts` with the following content:
530
531 ```ts title="src/links/ticket-product-variant.ts"
532 import TicketingModule from "../modules/ticket-booking"
533 import ProductModule from "@medusajs/medusa/product"
534 import { defineLink } from "@medusajs/framework/utils"
535
536 export default defineLink(
537 {
538 linkable: TicketingModule.linkable.ticketProductVariant,
539 deleteCascade: true,
540 },
541 ProductModule.linkable.productVariant
542 )
543 ```
544
545 You define a link in a similar way as the previous link, but this time between the `TicketProductVariant` and `ProductVariant` data models.
546
547 ### c. TicketPurchase \<\> Order Link
548
549 Finally, to define a link between the `TicketPurchase` data model and Medusa's `Order` data model, create the file `src/links/ticket-purchase-order.ts` with the following content:
550
551 ```ts title="src/links/ticket-purchase-order.ts"
552 import TicketingModule from "../modules/ticket-booking"
553 import OrderModule from "@medusajs/medusa/order"
554 import { defineLink } from "@medusajs/framework/utils"
555
556 export default defineLink(
557 {
558 linkable: TicketingModule.linkable.ticketPurchase,
559 deleteCascade: true,
560 isList: true,
561 },
562 OrderModule.linkable.order
563 )
564
565 ```
566
567 You define a link in a similar way as the previous links, but this time between the `TicketPurchase` and `Order` data models. You also set the `isList` property to `true` for the `TicketPurchase` data model, indicating that an order can have multiple ticket purchases.
568
569 ### d. Sync Links to Database
570
571 After defining links, you need to sync them to the database. This creates the necessary tables to manage the links.
572
573 To sync the links to the database, run the migrations command again in the Medusa application's directory:
574
575 ```bash npx2yarn
576 npx medusa db:migrate
577 ```
578
579 This command will create the necessary tables to manage the links between the Ticket Booking Module's data models and Medusa's data models.
580
581 ---
582
583 ## Step 4: Create Venue
584
585 In this step, you'll implement the logic to create a venue.
586
587 When you build commerce features in Medusa that can be consumed by client applications, such as the Medusa Admin dashboard or storefront, you need to implement:
588
589 1. A [workflow](!docs!/learn/fundamentals/workflows) with steps that define the business logic of the feature.
590 2. An [API route](!docs!/learn/fundamentals/api-routes) that exposes the workflow's functionality to client applications.
591
592 In this step, you'll implement the workflow and API route for creating a venue.
593
594 ### a. Create Venue Workflow
595
596 A workflow is a series of queries and actions, called steps, that complete a task. A workflow is similar to a function, but it allows you to track its executions' progress, define roll-back logic, and configure other advanced features.
597
598 <Note>
599
600 Refer to the [Workflows documentation](!docs!/learn/fundamentals/workflows) to learn more.
601
602 </Note>
603
604 The workflow to create a venue will have the following steps:
605
606 <WorkflowDiagram
607 workflow={{
608 name: "createVenueWorkflow",
609 steps: [
610 {
611 type: "step",
612 name: "createVenueStep",
613 description: "Creates a venue.",
614 depth: 1
615 },
616 {
617 type: "step",
618 name: "createVenueRowsStep",
619 description: "Creates the venue's rows.",
620 depth: 2
621 },
622 {
623 type: "step",
624 name: "useQueryGraphStep",
625 description: "Retrieves the created venue with its rows.",
626 link: "/references/helper-steps/useQueryGraphStep",
627 depth: 3
628 }
629 ]
630 }}
631 hideLegend
632 />
633
634 The `useQueryGraphStep` is available through Medusa's `@medusajs/medusa/core-flows` package. You'll implement other steps in the workflow.
635
636 #### createVenueStep
637
638 The `createVenueStep` creates a venue.
639
640 To create the step, create the file `src/workflows/steps/create-venue.ts` with the following content:
641
642 ```ts title="src/workflows/steps/create-venue.ts"
643 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
644 import { TICKET_BOOKING_MODULE } from "../../modules/ticket-booking"
645
646 export type CreateVenueStepInput = {
647 name: string
648 address?: string
649 }
650
651 export const createVenueStep = createStep(
652 "create-venue",
653 async (input: CreateVenueStepInput, { container }) => {
654 const ticketBookingModuleService = container.resolve(TICKET_BOOKING_MODULE)
655
656 const venue = await ticketBookingModuleService.createVenues(input)
657
658 return new StepResponse(venue, venue)
659 },
660 async (venue, { container }) => {
661 if (!venue) {return}
662
663 const ticketBookingModuleService = container.resolve(TICKET_BOOKING_MODULE)
664
665 await ticketBookingModuleService.deleteVenues(venue.id)
666 }
667 )
668 ```
669
670 You create a step with the `createStep` function. It accepts three parameters:
671
672 1. The step's unique name.
673 2. An async function that receives two parameters:
674 - The step's input, which is an object with the `name` and `address` properties of the venue to create.
675 - An object that has properties including the [Medusa container](!docs!/learn/fundamentals/medusa-container), which is a registry of Framework and commerce tools that you can access in the step.
676 3. An async compensation function that undoes the actions performed by the step function. This function is only executed if an error occurs during the workflow's execution.
677
678 In the step function, you resolve the Ticket Booking Module's service from the Medusa container using its `resolve` method, passing it the module's name as a parameter.
679
680 Then, you use the generated `createVenues` method of the Ticket Booking Module's service to create a venue with the provided input.
681
682 Finally, a step function must return a `StepResponse` instance. The `StepResponse` constructor accepts two parameters:
683
684 1. The step's output, which is the venue created.
685 2. Data to pass to the step's compensation function.
686
687 In the compensation function, you undo creating the venue by deleting it using the generated `deleteVenues` method of the Ticket Booking Module's service.
688
689 #### createVenueRowsStep
690
691 The `createVenueRowsStep` creates rows in a venue.
692
693 To create the step, create the file `src/workflows/steps/create-venue-rows.ts` with the following content:
694
695 ```ts title="src/workflows/steps/create-venue-rows.ts"
696 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
697 import { TICKET_BOOKING_MODULE } from "../../modules/ticket-booking"
698 import { RowType } from "../../modules/ticket-booking/models/venue-row"
699
700 export type CreateVenueRowsStepInput = {
701 rows: {
702 venue_id: string
703 row_number: string
704 row_type: RowType
705 seat_count: number
706 }[]
707 }
708
709 export const createVenueRowsStep = createStep(
710 "create-venue-rows",
711 async (input: CreateVenueRowsStepInput, { container }) => {
712 const ticketBookingModuleService = container.resolve(TICKET_BOOKING_MODULE)
713
714 const venueRows = await ticketBookingModuleService.createVenueRows(
715 input.rows
716 )
717
718 return new StepResponse(venueRows, venueRows)
719 },
720 async (venueRows, { container }) => {
721 if (!venueRows) {return}
722
723 const ticketBookingModuleService = container.resolve(TICKET_BOOKING_MODULE)
724
725 await ticketBookingModuleService.deleteVenueRows(
726 venueRows.map((row) => row.id)
727 )
728 }
729 )
730 ```
731
732 This step receives the rows to create as an input.
733
734 In the step function, you create the rows and return them.
735
736 In the compensation function, you undo creating the rows by deleting them.
737
738 #### Create Venue Workflow
739
740 You can now create the workflow that uses the steps you implemented.
741
742 To create the workflow, create the file `src/workflows/create-venue.ts` with the following content:
743
744 ```ts title="src/workflows/create-venue.ts"
745 import { createWorkflow, transform, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
746 import { createVenueStep } from "./steps/create-venue"
747 import { createVenueRowsStep } from "./steps/create-venue-rows"
748 import { RowType } from "../modules/ticket-booking/models/venue-row"
749 import { useQueryGraphStep } from "@medusajs/core-flows"
750
751 export type CreateVenueWorkflowInput = {
752 name: string
753 address?: string
754 rows: Array<{
755 row_number: string
756 row_type: RowType
757 seat_count: number
758 }>
759 }
760
761 export const createVenueWorkflow = createWorkflow(
762 "create-venue",
763 (input: CreateVenueWorkflowInput) => {
764 const venue = createVenueStep({
765 name: input.name,
766 address: input.address,
767 })
768
769 const venueRowsData = transform({
770 venue,
771 input,
772 }, (data) => {
773 return data.input.rows.map((row) => ({
774 venue_id: data.venue.id,
775 row_number: row.row_number,
776 row_type: row.row_type,
777 seat_count: row.seat_count,
778 }))
779 })
780
781 createVenueRowsStep({
782 rows: venueRowsData,
783 })
784
785 const { data: venues } = useQueryGraphStep({
786 entity: "venue",
787 fields: ["id", "name", "address", "rows.*"],
788 filters: {
789 id: venue.id,
790 },
791 })
792
793 return new WorkflowResponse({
794 venue: venues[0],
795 })
796 }
797 )
798 ```
799
800 You create a workflow using the `createWorkflow` function. It accepts the workflow's unique name as a first parameter.
801
802 It accepts as a second parameter a constructor function that holds the workflow's implementation. The function accepts an input object containing the details of the venue and its rows.
803
804 In the workflow, you:
805
806 1. Create a venue using the `createVenueStep`.
807 2. Prepare the data to create the venue's rows.
808 3. Create the venue's rows using the `createVenueRowsStep`.
809 4. Retrieve the created venue with its rows using the `useQueryGraphStep`.
810 - This step uses [Query](!docs!/learn/fundamentals/query) under the hood. It allows you to retrieve data across modules.
811
812 A workflow must return an instance of `WorkflowResponse` that accepts the data to return to the workflow's executor. You return the created venue with its rows.
813
814 <Note title="Tip">
815
816 `transform` allows you to access the values of data during execution. Learn more in the [Data Manipulation](!docs!/learn/fundamentals/workflows/variable-manipulation) documentation.
817
818 </Note>
819
820 ### b. Create Venue API Route
821
822 Next, you'll create an API route that exposes the functionality of the `createVenueWorkflow` to client applications.
823
824 An API route is created in a `route.ts` file under a sub-directory of the `src/api` directory. The path of the API route is the file's path relative to `src/api`.
825
826 <Note>
827
828 Refer to the [API routes](!docs!/learn/fundamentals/api-routes) documentation to learn more about them.
829
830 </Note>
831
832 Create the file `src/api/admin/venues/route.ts` with the following content:
833
834 <Note>
835
836 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
837
838 </Note>
839
840 ```ts title="src/api/admin/venues/route.ts"
841 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
842 import { createVenueWorkflow } from "../../../workflows/create-venue"
843 import { RowType } from "../../../modules/ticket-booking/models/venue-row"
844 import { z } from "@medusajs/framework/zod"
845
846 export const CreateVenueSchema = z.object({
847 name: z.string(),
848 address: z.string().optional(),
849 rows: z.array(z.object({
850 row_number: z.string(),
851 row_type: z.enum(RowType),
852 seat_count: z.number(),
853 })),
854 })
855
856 type CreateVenueSchema = z.infer<typeof CreateVenueSchema>
857
858 export async function POST(
859 req: MedusaRequest<CreateVenueSchema>,
860 res: MedusaResponse
861 ) {
862 const { result } = await createVenueWorkflow(req.scope).run({
863 input: req.validatedBody,
864 })
865
866 res.json(result)
867 }
868 ```
869
870 You use [Zod](https://zod.dev/) to create the `CreateVenueSchema` that is used to validate request bodies sent to this API route.
871
872 Then, you export a `POST` route handler function, which will expose a `POST` API route at `/admin/venues`.
873
874 In the route handler, you execute the `createVenueWorkflow`, passing it the request body as an input.
875
876 Finally, you return the created venue with its rows in the response.
877
878 You'll test this API route later when you customize the Medusa Admin.
879
880 #### Add Validation Middleware for Create Venue API Route
881
882 To validate the body parameters of requests sent to the API route, you need to apply a [middleware](!docs!/learn/fundamentals/api-routes/middlewares).
883
884 To apply a middleware to a route, create the file `src/api/middlewares.ts` with the following content:
885
886 ```ts title="src/api/middlewares.ts"
887 import {
888 defineMiddlewares,
889 validateAndTransformBody,
890 } from "@medusajs/framework/http"
891 import { CreateVenueSchema } from "./admin/venues/route"
892
893 export default defineMiddlewares({
894 routes: [
895 {
896 matcher: "/admin/venues",
897 methods: ["POST"],
898 middlewares: [
899 validateAndTransformBody(CreateVenueSchema),
900 ],
901 },
902 ],
903 })
904 ```
905
906 You apply Medusa's `validateAndTransformBody` middleware to `POST` requests sent to the `/admin/venues` route.
907
908 The middleware function accepts a Zod schema, which you created in the API route's file.
909
910 <Note title="Tip">
911
912 Refer to the [Middlewares](!docs!/learn/fundamentals/api-routes/middlewares) documentation to learn more.
913
914 </Note>
915
916 ---
917
918 ## Step 5: List Venues API Route
919
920 In this step, you'll add an API route to retrieve a list of venues. You'll use this API route later to display a list of venues in the Medusa Admin.
921
922 To create the API route, add the following to the `src/api/admin/venues/route.ts` file:
923
924 ```ts title="src/api/admin/venues/route.ts"
925 export async function GET(
926 req: MedusaRequest,
927 res: MedusaResponse
928 ) {
929 const query = req.scope.resolve(
930 ContainerRegistrationKeys.QUERY
931 )
932
933 const {
934 data: venues,
935 metadata,
936 } = await query.graph({
937 entity: "venue",
938 ...req.queryConfig,
939 })
940
941 res.json({
942 venues,
943 count: metadata?.count,
944 limit: metadata?.take,
945 offset: metadata?.skip,
946 })
947 }
948 ```
949
950 You export a `GET` route handler function, which will expose a `GET` API route at `/admin/venues`.
951
952 In the route handler, you resolve Query from the Medusa container and use it to retrieve a list of venues.
953
954 Notice that you spread the `req.queryConfig` object into the `query.graph` method. This allows clients to pass query parameters for pagination and configure returned fields. You'll learn how to set these configurations in a bit.
955
956 Finally, you return the list of venues and pagination details in the response.
957
958 You'll test out this API route later when you customize the Medusa Admin.
959
960 ### Add Validation Middleware for List Venues API Route
961
962 To validate the query parameters of requests sent to the API route, and to allow clients to configure pagination and returned fields, you need to apply a middleware.
963
964 To apply a middleware to the route, add the following imports at the top of the `src/api/middlewares.ts` file:
965
966 ```ts title="src/api/middlewares.ts"
967 import { validateAndTransformQuery } from "@medusajs/framework/http"
968 import { createFindParams } from "@medusajs/medusa/api/utils/validators"
969 ```
970
971 Then, add the following object to the `routes` array passed to `defineMiddlewares`:
972
973 ```ts title="src/api/middlewares.ts"
974 export default defineMiddlewares({
975 routes: [
976 // ...
977 {
978 matcher: "/admin/venues",
979 methods: ["GET"],
980 middlewares: [
981 validateAndTransformQuery(createFindParams(), {
982 isList: true,
983 defaults: ["id", "name", "address", "rows.*"],
984 }),
985 ],
986 },
987 ],
988 })
989 ```
990
991 You apply the `validateAndTransformQuery` middleware to `GET` requests sent to the `/admin/venues` route. This allows you to validate query parameters and set configurations for pagination and returned fields.
992
993 The middleware function accepts two parameters:
994
995 1. A Zod schema to validate the query parameters. You use Medusa's `createFindParams` utility function to create a schema that validates common query parameters like `limit`, `offset`, `fields`, and `order`.
996 2. Query configurations that you use in the API route using the `req.queryConfig` object. You set the following configurations:
997 - `isList`: Set to `true` to indicate that the API route returns a list of records.
998 - `defaults`: An array of fields to return by default if the client doesn't specify any fields in the request.
999
1000 <Note title="Tip">
1001
1002 Refer to the [Query](!docs!/learn/fundamentals/query#request-query-configurations) documentation to learn more about query request configurations.
1003
1004 </Note>
1005
1006 ---
1007
1008 ## Step 6: Manage Venues in Medusa Admin
1009
1010 In this step, you'll customize the Medusa Admin to allow admin users to manage venues.
1011
1012 The Medusa Admin dashboard is customizable, allowing you to insert widgets into existing pages, or create new pages.
1013
1014 <Note title="Tip">
1015
1016 Refer to the [Admin Development](!docs!/learn/fundamentals/admin) documentation to learn more.
1017
1018 </Note>
1019
1020 In this step, you'll create a new page or UI route in the Medusa Admin to view a list of venues and create new venues.
1021
1022 ### a. Initialize JS SDK
1023
1024 To send requests to the Medusa server, you'll use the [JS SDK](../../../js-sdk/page.mdx). It's already installed in your Medusa project, but you need to initialize it before using it in your customizations.
1025
1026 Create the file `src/admin/lib/sdk.ts` with the following content:
1027
1028 ```ts title="src/admin/lib/sdk.ts"
1029 import Medusa from "@medusajs/js-sdk"
1030
1031 export const sdk = new Medusa({
1032 baseUrl: import.meta.env.VITE_BACKEND_URL || "/",
1033 debug: import.meta.env.DEV,
1034 auth: {
1035 type: "session",
1036 },
1037 })
1038 ```
1039
1040 Learn more about the initialization options in the [JS SDK](../../../js-sdk/page.mdx) reference.
1041
1042 ### b. Define Types
1043
1044 Next, you'll define types that you'll use in your admin customizations.
1045
1046 Create the file `src/admin/types.ts` with the following content:
1047
1048 ```ts title="src/admin/types.ts"
1049 export enum RowType {
1050 PREMIUM = "premium",
1051 BALCONY = "balcony",
1052 STANDARD = "standard",
1053 VIP = "vip"
1054 }
1055
1056 export interface VenueRow {
1057 id: string
1058 row_number: string
1059 row_type: RowType
1060 seat_count: number
1061 venue_id: string
1062 created_at: string
1063 updated_at: string
1064 }
1065
1066 export interface Venue {
1067 id: string
1068 name: string
1069 address?: string
1070 rows: VenueRow[]
1071 created_at: string
1072 updated_at: string
1073 }
1074
1075 export interface CreateVenueRequest {
1076 name: string
1077 address?: string
1078 rows: {
1079 row_number: string
1080 row_type: RowType
1081 seat_count: number
1082 }[]
1083 }
1084
1085 export interface VenuesResponse {
1086 venues: Venue[]
1087 count: number
1088 limit: number
1089 offset: number
1090 }
1091 ```
1092
1093 You define types for the `RowType` enum, `VenueRow` and `Venue` data models, as well as types for API request and response bodies.
1094
1095 ### c. Create Venues Page
1096
1097 You can now create a page that shows a list of venues in a table.
1098
1099 You create a page by creating a UI route. A UI route is a React component defined under the `src/admin/routes` directory in a `page.tsx` file. The path of the UI route is the file's path relative to `src/admin/routes`.
1100
1101 To create the venues page, create the file `src/admin/routes/venues/page.tsx` with the following content:
1102
1103 ```tsx title="src/admin/routes/venues/page.tsx" collapsibleLines="1-15" expandButtonLabel="Show Imports"
1104 import { defineRouteConfig } from "@medusajs/admin-sdk"
1105 import { Buildings } from "@medusajs/icons"
1106 import {
1107 createDataTableColumnHelper,
1108 Container,
1109 DataTable,
1110 useDataTable,
1111 Heading,
1112 DataTablePaginationState,
1113 } from "@medusajs/ui"
1114 import { useQuery, useQueryClient } from "@tanstack/react-query"
1115 import { useState, useMemo } from "react"
1116 import { sdk } from "../../lib/sdk"
1117 import { Venue, CreateVenueRequest } from "../../types"
1118
1119 const VenuesPage = () => {
1120 // TODO implement component
1121 }
1122
1123 export const config = defineRouteConfig({
1124 label: "Venues",
1125 icon: Buildings,
1126 })
1127
1128 export default VenuesPage
1129 ```
1130
1131 A UI route file must export:
1132
1133 - A React component as the default export. This component is rendered when the user navigates to the UI route.
1134 - A route configuration object defined using the `defineRouteConfig` function. This object configures the UI route's label and icon in the sidebar.
1135
1136 In the `VenuesPage` component, you'll display the list of venues in a [Data Table](!ui!/components/data-table) component.
1137
1138 To define the columns of the data table, add the following before the `VenuesPage` component:
1139
1140 ```tsx title="src/admin/routes/venues/page.tsx"
1141 const columnHelper = createDataTableColumnHelper<Venue>()
1142
1143 const columns = [
1144 columnHelper.accessor("name", {
1145 header: "Name",
1146 cell: ({ row }) => (
1147 <div>
1148 <div className="txt-small-plus">{row.original.name}</div>
1149 {row.original.address && (
1150 <div className="txt-small text-gray-500">{row.original.address}</div>
1151 )}
1152 </div>
1153 ),
1154 }),
1155 columnHelper.accessor("rows", {
1156 header: "Total Capacity",
1157 cell: ({ row }) => {
1158 const totalCapacity = row.original.rows.reduce(
1159 (sum, rowItem) => sum + rowItem.seat_count,
1160 0
1161 )
1162 return <span className="txt-small-plus">{totalCapacity} seats</span>
1163 },
1164 }),
1165 columnHelper.accessor("address", {
1166 header: "Address",
1167 cell: ({ row }) => (
1168 <span>{row.original.address || "-"}</span>
1169 ),
1170 }),
1171 ]
1172 ```
1173
1174 You define three columns: `Name`, `Total Capacity`, and `Address`.
1175
1176 Next, to show the data table, replace the `VenuesPage` component with the following:
1177
1178 ```tsx title="src/admin/routes/venues/page.tsx"
1179 const VenuesPage = () => {
1180 const limit = 15
1181 const [pagination, setPagination] = useState<DataTablePaginationState>({
1182 pageSize: limit,
1183 pageIndex: 0,
1184 })
1185
1186 const queryClient = useQueryClient()
1187
1188 const offset = useMemo(() => {
1189 return pagination.pageIndex * limit
1190 }, [pagination])
1191
1192 const { data, isLoading } = useQuery<{
1193 venues: Venue[]
1194 count: number
1195 limit: number
1196 offset: number
1197 }>({
1198 queryKey: ["venues", offset, limit],
1199 queryFn: () => sdk.client.fetch("/admin/venues", {
1200 query: {
1201 offset: pagination.pageIndex * pagination.pageSize,
1202 limit: pagination.pageSize,
1203 order: "-created_at",
1204 },
1205 }),
1206 })
1207
1208 const table = useDataTable({
1209 columns,
1210 data: data?.venues || [],
1211 rowCount: data?.count || 0,
1212 isLoading,
1213 pagination: {
1214 state: pagination,
1215 onPaginationChange: setPagination,
1216 },
1217 getRowId: (row) => row.id,
1218 })
1219
1220 return (
1221 <Container className="divide-y p-0">
1222 <DataTable instance={table}>
1223 <DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">
1224 <Heading>
1225 Venues
1226 </Heading>
1227 </DataTable.Toolbar>
1228 <DataTable.Table />
1229 <DataTable.Pagination />
1230 </DataTable>
1231 </Container>
1232 )
1233 }
1234 ```
1235
1236 In the component, you use React Query's `useQuery` hook to fetch the list of venues from the `GET /admin/venues` API route you created earlier. You pass the `offset` and `limit` query parameters to paginate the results.
1237
1238 Then, you use the `useDataTable` hook from Medusa UI to create a data table instance with the fetched venues and the columns you defined earlier.
1239
1240 Finally, you render the data table.
1241
1242 ### d. Create Venue Modal
1243
1244 Next, you'll add a component that shows a form in a modal to create a new venue. You'll open this modal when the user clicks a button on the venues page.
1245
1246 Before adding the modal, you'll add a component that visualizes the venue rows in a seat chart. You'll use this component in the modal to help admin users visualize the rows they're adding to the venue.
1247
1248 To create the seat chart component, create the file `src/admin/components/seat-chart.tsx` with the following content:
1249
1250 ```tsx title="src/admin/components/seat-chart.tsx"
1251 import React from "react"
1252 import { Heading } from "@medusajs/ui"
1253 import { RowType, VenueRow } from "../types"
1254
1255 interface ChartVenueRow extends Pick<VenueRow, "row_number" | "row_type" | "seat_count"> {}
1256
1257 interface SeatChartProps {
1258 rows: ChartVenueRow[]
1259 className?: string
1260 }
1261
1262 const getRowTypeColor = (rowType: RowType): string => {
1263 switch (rowType) {
1264 case RowType.VIP:
1265 return "bg-purple-500"
1266 case RowType.PREMIUM:
1267 return "bg-orange-500"
1268 case RowType.BALCONY:
1269 return "bg-blue-500"
1270 case RowType.STANDARD:
1271 return "bg-gray-500"
1272 default:
1273 return "bg-gray-300"
1274 }
1275 }
1276
1277 const getRowTypeLabel = (rowType: RowType): string => {
1278 switch (rowType) {
1279 case RowType.VIP:
1280 return "VIP"
1281 case RowType.PREMIUM:
1282 return "Premium"
1283 case RowType.BALCONY:
1284 return "Balcony"
1285 case RowType.STANDARD:
1286 return "Standard"
1287 default:
1288 return "Unknown"
1289 }
1290 }
1291
1292 export const SeatChart = ({ rows, className = "" }: SeatChartProps) => {
1293 if (rows.length === 0) {
1294 return (
1295 <div className={`p-8 text-center text-gray-500 ${className}`}>
1296 <p>No rows added yet. Add rows to see the seat chart.</p>
1297 </div>
1298 )
1299 }
1300
1301 // Sort rows by row_number for consistent display
1302 const sortedRows = [...rows].sort((a, b) => a.row_number.localeCompare(b.row_number))
1303
1304 return (
1305 <div className={`space-y-4 ${className}`}>
1306 <div className="flex items-center justify-between">
1307 <Heading level="h3">Seat Chart Preview</Heading>
1308 <div className="flex items-center gap-4 txt-small">
1309 <div className="flex items-center gap-2">
1310 <div className="w-4 h-4 bg-purple-500 rounded"></div>
1311 <span>VIP</span>
1312 </div>
1313 <div className="flex items-center gap-2">
1314 <div className="w-4 h-4 bg-orange-500 rounded"></div>
1315 <span>Premium</span>
1316 </div>
1317 <div className="flex items-center gap-2">
1318 <div className="w-4 h-4 bg-blue-500 rounded"></div>
1319 <span>Balcony</span>
1320 </div>
1321 <div className="flex items-center gap-2">
1322 <div className="w-4 h-4 bg-gray-500 rounded"></div>
1323 <span>Standard</span>
1324 </div>
1325 </div>
1326 </div>
1327
1328 <div className="border rounded-lg p-4 bg-gray-50">
1329 <div className="grid grid-cols-[auto_auto_1fr_auto] gap-4 items-center">
1330 {/* Header row */}
1331 <div className="txt-small-plus text-gray-700 text-center">Row</div>
1332 <div className="txt-small-plus text-gray-700 text-center">Type</div>
1333 <div className="txt-small-plus text-gray-700 text-center">Seats</div>
1334 <div className="txt-small-plus text-gray-700 text-center">Count</div>
1335
1336 {/* Data rows */}
1337 {sortedRows.map((row) => (
1338 <React.Fragment key={row.row_number}>
1339 <div className="txt-small-plus text-gray-700 text-center">
1340 {row.row_number}
1341 </div>
1342 <div className="flex items-center justify-center gap-2">
1343 <div className={`w-4 h-4 rounded ${getRowTypeColor(row.row_type)}`}></div>
1344 <span className="txt-small text-ui-fg-subtle">
1345 {getRowTypeLabel(row.row_type)}
1346 </span>
1347 </div>
1348 <div className="flex justify-center gap-1 flex-wrap">
1349 {Array.from({ length: row.seat_count }, (_, i) => (
1350 <div
1351 key={i}
1352 className={`w-3 h-3 rounded-sm ${getRowTypeColor(row.row_type)} opacity-70`}
1353 />
1354 ))}
1355 </div>
1356 <div className="txt-small text-gray-500 text-center">
1357 {row.seat_count}
1358 </div>
1359 </React.Fragment>
1360 ))}
1361 </div>
1362 </div>
1363
1364 <div className="txt-small text-gray-500">
1365 Total capacity: {rows.reduce((sum, row) => sum + row.seat_count, 0)} seats
1366 </div>
1367 </div>
1368 )
1369 }
1370 ```
1371
1372 This component accepts a list of venue rows and visualizes them in a seat chart.
1373
1374 Then, to create the component for the modal, create the file `src/admin/components/create-venue-modal.tsx` with the following content:
1375
1376 ```tsx title="src/admin/components/create-venue-modal.tsx" collapsibleLines="1-14" expandButtonLabel="Show Imports"
1377 import { useState } from "react"
1378 import {
1379 FocusModal,
1380 Heading,
1381 Input,
1382 Select,
1383 Textarea,
1384 Label,
1385 Button,
1386 toast,
1387 } from "@medusajs/ui"
1388 import { CreateVenueRequest, RowType, VenueRow } from "../types"
1389 import { SeatChart } from "./seat-chart"
1390
1391 interface NewVenueRow extends Pick<VenueRow, "row_number" | "row_type" | "seat_count"> {}
1392
1393 interface CreateVenueModalProps {
1394 open: boolean
1395 onOpenChange: (open: boolean) => void
1396 onSubmit: (data: CreateVenueRequest) => Promise<void>
1397 }
1398
1399 export const CreateVenueModal = ({
1400 open,
1401 onOpenChange,
1402 onSubmit,
1403 }: CreateVenueModalProps) => {
1404 const [name, setName] = useState("")
1405 const [address, setAddress] = useState("")
1406 const [rows, setRows] = useState<NewVenueRow[]>([])
1407 const [newRow, setNewRow] = useState({
1408 row_number: "",
1409 row_type: RowType.VIP,
1410 seat_count: 10,
1411 })
1412 const [isLoading, setIsLoading] = useState(false)
1413
1414 // TODO add functions to manage venue rows
1415 }
1416 ```
1417
1418 You create a `CreateVenueModal` component that accepts three props:
1419
1420 - `open`: A boolean indicating whether the modal is open or closed.
1421 - `onOpenChange`: A function called when the modal's open state changes.
1422 - `onSubmit`: A function called when the user submits the form to create a venue.
1423
1424 In the component, you define state variables to hold the venue's name, address, rows, a new row being added, and a loading state.
1425
1426 In the form, admin users should be able to add multiple rows to the venue. So, you'll add methods to manage rows, such as adding and removing rows.
1427
1428 Replace the `TODO` in the `CreateVenueModal` component with the following:
1429
1430 ```tsx title="src/admin/components/create-venue-modal.tsx"
1431 const addRow = () => {
1432 if (!newRow.row_number.trim()) {
1433 toast.error("Row number is required")
1434 return
1435 }
1436
1437 if (rows.some((row) => row.row_number === newRow.row_number)) {
1438 toast.error("Row number already exists")
1439 return
1440 }
1441
1442 if (newRow.seat_count <= 0) {
1443 toast.error("Seat count must be greater than 0")
1444 return
1445 }
1446
1447 setRows([...rows, {
1448 row_number: newRow.row_number,
1449 row_type: newRow.row_type,
1450 seat_count: newRow.seat_count,
1451 }])
1452 setNewRow({
1453 row_number: "",
1454 row_type: RowType.VIP,
1455 seat_count: 10,
1456 })
1457 }
1458
1459 const removeRow = (rowNumber: string) => {
1460 setRows(rows.filter((row) => row.row_number !== rowNumber))
1461 }
1462
1463 const formatRowType = (rowType: RowType) => {
1464 switch (rowType) {
1465 case RowType.VIP:
1466 return "VIP"
1467 default:
1468 return rowType.charAt(0).toUpperCase() + rowType.slice(1).toLowerCase()
1469 }
1470 }
1471
1472 // TODO handle form submission and modal close
1473 ```
1474
1475 You add the `addRow` function to add a new row to the venue, and the `removeRow` function to remove a row by its row number. You also add the `formatRowType` function to format the row type for display.
1476
1477 Next, you'll implement the logic to submit the form to create a venue and to close the modal and reset the form when the user closes it.
1478
1479 Replace the `TODO` in the `CreateVenueModal` component with the following:
1480
1481 ```tsx title="src/admin/components/create-venue-modal.tsx"
1482 const handleClose = () => {
1483 setName("")
1484 setAddress("")
1485 setRows([])
1486 setNewRow({
1487 row_number: "",
1488 row_type: RowType.VIP,
1489 seat_count: 10,
1490 })
1491 onOpenChange(false)
1492 }
1493
1494 const handleSubmit = async (e: React.FormEvent) => {
1495 e.preventDefault()
1496
1497 if (!name.trim()) {
1498 toast.error("Venue name is required")
1499 return
1500 }
1501
1502 if (rows.length === 0) {
1503 toast.error("At least one row is required")
1504 return
1505 }
1506
1507 setIsLoading(true)
1508 try {
1509 await onSubmit({
1510 name: name.trim(),
1511 address: address.trim() || undefined,
1512 rows: rows.map((row) => ({
1513 row_number: row.row_number,
1514 row_type: row.row_type,
1515 seat_count: row.seat_count,
1516 })),
1517 })
1518 handleClose()
1519 } catch (error: any) {
1520 toast.error(error.message)
1521 } finally {
1522 setIsLoading(false)
1523 }
1524 }
1525
1526 // TODO render modal
1527 ```
1528
1529 You add the `handleClose` function to reset the form and call the `onOpenChange` prop to close the modal. You'll trigger this function when users close the modal or after successfully creating a venue.
1530
1531 You also add the `handleSubmit` function to validate the form data, call the `onSubmit` prop with the venue data, and handle loading and error states.
1532
1533 Finally, you'll render the modal with the form. Replace the `TODO` in the `CreateVenueModal` component with the following:
1534
1535 ```tsx title="src/admin/components/create-venue-modal.tsx"
1536 return (
1537 <FocusModal open={open} onOpenChange={handleClose}>
1538 <FocusModal.Content>
1539 <form onSubmit={handleSubmit} className="flex h-full flex-col overflow-hidden">
1540 <FocusModal.Header>
1541 <Heading level="h1">Create New Venue</Heading>
1542 </FocusModal.Header>
1543 <FocusModal.Body className="p-6 overflow-auto">
1544 <div className="max-w-[720px] mx-auto">
1545 <div className="space-y-4 w-fit mx-auto">
1546 <div>
1547 <Label htmlFor="name">Venue Name</Label>
1548 <Input
1549 id="name"
1550 value={name}
1551 onChange={(e) => setName(e.target.value)}
1552 placeholder="Enter venue name"
1553 />
1554 </div>
1555
1556 <div>
1557 <Label htmlFor="address">
1558 Address
1559 <span className="text-ui-fg-muted txt-compact-small"> (Optional)</span>
1560 </Label>
1561 <Textarea
1562 id="address"
1563 value={address}
1564 onChange={(e) => setAddress(e.target.value)}
1565 placeholder="Enter venue address"
1566 rows={3}
1567 />
1568 </div>
1569
1570 <div className="border-t pt-4">
1571 <Heading level="h3" className="mb-2">Add Rows</Heading>
1572
1573 <div className="space-y-3">
1574 <div className="grid grid-cols-3 gap-3">
1575 <div>
1576 <Label htmlFor="row_number">Row Number</Label>
1577 <Input
1578 id="row_number"
1579 value={newRow.row_number}
1580 onChange={(e) => setNewRow({ ...newRow, row_number: e.target.value })}
1581 placeholder="A, B, 1, 2..."
1582 />
1583 </div>
1584
1585 <div>
1586 <Label htmlFor="row_type">Row Type</Label>
1587 <Select
1588 value={newRow.row_type}
1589 onValueChange={(value) => setNewRow({ ...newRow, row_type: value as RowType })}
1590 >
1591 <Select.Trigger>
1592 <Select.Value />
1593 </Select.Trigger>
1594 <Select.Content>
1595 <Select.Item value={RowType.VIP}>VIP</Select.Item>
1596 <Select.Item value={RowType.PREMIUM}>Premium</Select.Item>
1597 <Select.Item value={RowType.BALCONY}>Balcony</Select.Item>
1598 <Select.Item value={RowType.STANDARD}>Standard</Select.Item>
1599 </Select.Content>
1600 </Select>
1601 </div>
1602
1603 <div>
1604 <Label htmlFor="seat_count">Seat Count</Label>
1605 <Input
1606 id="seat_count"
1607 type="number"
1608 min="1"
1609 value={newRow.seat_count}
1610 onChange={(e) => setNewRow({ ...newRow, seat_count: parseInt(e.target.value) || 0 })}
1611 />
1612 </div>
1613 </div>
1614
1615 <Button
1616 type="button"
1617 variant="secondary"
1618 onClick={addRow}
1619 disabled={!newRow.row_number.trim()}
1620 >
1621 Add Row
1622 </Button>
1623 </div>
1624
1625 {rows.length > 0 && (
1626 <div className="mt-4">
1627 <h4 className="txt-small-plus mb-2">Added Rows</h4>
1628 <div className="space-y-2">
1629 {rows.map((row) => (
1630 <div key={row.row_number} className="flex items-center justify-between p-2 bg-ui-bg-subtle rounded">
1631 <span className="txt-small">
1632 Row {row.row_number} - {formatRowType(row.row_type)} ({row.seat_count} seats)
1633 </span>
1634 <Button
1635 type="button"
1636 variant="danger"
1637 size="small"
1638 onClick={() => removeRow(row.row_number)}
1639 >
1640 Remove
1641 </Button>
1642 </div>
1643 ))}
1644 </div>
1645 </div>
1646 )}
1647 </div>
1648 </div>
1649
1650 <hr className="my-10" />
1651
1652 <div>
1653 <SeatChart rows={rows} />
1654 </div>
1655 </div>
1656 </FocusModal.Body>
1657 <FocusModal.Footer>
1658
1659 <Button
1660 type="submit"
1661 variant="primary"
1662 isLoading={isLoading}
1663 disabled={!name.trim() || rows.length === 0}
1664 >
1665 Create Venue
1666 </Button>
1667 </FocusModal.Footer>
1668 </form>
1669 </FocusModal.Content>
1670 </FocusModal>
1671 )
1672 ```
1673
1674 You use Medusa UI's `FocusModal` component to render the modal. Inside the modal, you render a form with input fields for the venue's name and address, and fields to add rows.
1675
1676 You also render the `SeatChart` component to visualize the added rows.
1677
1678 Now that the `CreateVenueModal` component is ready, you'll use it in the `VenuesPage` component.
1679
1680 In `src/admin/routes/venues/page.tsx`, add the following imports at the top of the file:
1681
1682 ```tsx title="src/admin/routes/venues/page.tsx"
1683 import {
1684 Button,
1685 } from "@medusajs/ui"
1686 import { CreateVenueModal } from "../../components/create-venue-modal"
1687 ```
1688
1689 Then, in the `VenuesPage` component, add the following state variable to manage the modal's open state:
1690
1691 ```tsx title="src/admin/routes/venues/page.tsx"
1692 const VenuesPage = () => {
1693 const [isModalOpen, setIsModalOpen] = useState(false)
1694 // ...
1695 }
1696 ```
1697
1698 Next, add the following functions before the `return` statement to handle opening and closing the modal, and to handle creating a venue:
1699
1700 ```tsx title="src/admin/routes/venues/page.tsx"
1701 const VenuesPage = () => {
1702 // ...
1703 const handleCloseModal = () => {
1704 setIsModalOpen(false)
1705 }
1706
1707 const handleCreateVenue = async (data: CreateVenueRequest) => {
1708 try {
1709 await sdk.client.fetch("/admin/venues", {
1710 method: "POST",
1711 body: data,
1712 })
1713 queryClient.invalidateQueries({ queryKey: ["venues"] })
1714 handleCloseModal()
1715 } catch (error: any) {
1716 throw new Error(`Failed to create venue: ${error.message}`)
1717 }
1718 }
1719 // ...
1720 }
1721 ```
1722
1723 You add the `handleCloseModal` function to close the modal by setting the `isModalOpen` state to `false`.
1724
1725 You also add the `handleCreateVenue` function to send a `POST` request to the `/admin/venues` API route you created earlier.
1726
1727 Then, to trigger opening the modal, add the following button as the last child of `<DataTable.Toolbar>` in the `return` statement:
1728
1729 ```tsx title="src/admin/routes/venues/page.tsx"
1730 return (
1731 <Container className="divide-y p-0">
1732 {/* ... */}
1733 <Button
1734 variant="secondary"
1735 onClick={() => setIsModalOpen(true)}
1736 >
1737 Create Venue
1738 </Button>
1739 {/* ... */}
1740 </Container>
1741 )
1742 ```
1743
1744 Finally, render the `CreateVenueModal` component as the last child of the `<Container>` component in the `return` statement:
1745
1746 ```tsx title="src/admin/routes/venues/page.tsx"
1747 return (
1748 <Container className="divide-y p-0">
1749 {/* ... */}
1750 <CreateVenueModal
1751 open={isModalOpen}
1752 onOpenChange={handleCloseModal}
1753 onSubmit={handleCreateVenue}
1754 />
1755 </Container>
1756 )
1757 ```
1758
1759 You render the `CreateVenueModal` component, passing it the `isModalOpen` state, and the `handleCloseModal` and `handleCreateVenue` functions as props.
1760
1761 ### Test the Venues Page
1762
1763 You can now test the venues page in the Medusa Admin.
1764
1765 Run the following command to start the Medusa server:
1766
1767 ```bash npm2yarn
1768 npm run dev
1769 ```
1770
1771 Then, open `http://localhost:9000/app` in your browser to access the Medusa Admin. Log in with the admin user you created earlier.
1772
1773 You should see a new "Venues" item in the sidebar. Click on it to navigate to the venues page. You'll see an empty table with a "Create Venue" button.
1774
1775 ![Venues Page in the Medusa Admin with an empty table](https://res.cloudinary.com/dza7lstvk/image/upload/v1757430925/Medusa%20Resources/CleanShot_2025-09-09_at_18.15.02_2x_o0pf16.png)
1776
1777 To create a venue:
1778
1779 1. Click the "Create Venue" button to open the modal.
1780 2. In the modal, enter a name for the venue, and optionally an address.
1781 3. Add rows and visualize them in the seat chart.
1782 4. Once you're done, click the "Create Venue" button to create the venue.
1783
1784 ![Create Venue Modal in the Medusa Admin](https://res.cloudinary.com/dza7lstvk/image/upload/v1757431196/Medusa%20Resources/CleanShot_2025-09-09_at_18.19.45_2x_qyov67.png)
1785
1786 After creating the venue, you can see it listed in the table.
1787
1788 ---
1789
1790 ## Step 7: Create Ticket Product
1791
1792 In this step, you'll add functionality to create a ticket product for a show. You'll create a workflow and an API route to handle ticket product creation.
1793
1794 ### a. Create Create Ticket Product Workflow
1795
1796 The workflow that creates a ticket product will also create the Medusa product and its variants. It will create a variant for each show date and row type. For example, if a show has two dates and three row types, the workflow will create six variants for the Medusa product.
1797
1798 The workflow will also create inventory items for each variant, ensuring that customers can't purchase more tickets than the venue's capacity.
1799
1800 {/* TODO add diagram */}
1801
1802 The workflow will have the following steps:
1803
1804 <WorkflowDiagram
1805 workflow={{
1806 name: "createTicketProductWorkflow",
1807 steps: [
1808 {
1809 type: "step",
1810 name: "validateVenueAvailabilityStep",
1811 description: "Validates that the selected venue is available for the show date and time.",
1812 depth: 1
1813 },
1814 {
1815 type: "step",
1816 name: "useQueryGraphStep",
1817 description: "Retrieve default store configuration that are useful for creating the Medusa product.",
1818 depth: 2,
1819 link: "/references/helper-steps/useQueryGraphStep",
1820 },
1821 {
1822 type: "step",
1823 name: "createInventoryItemsWorkflow",
1824 description: "Creates inventory items for the Medusa product.",
1825 depth: 3,
1826 link: "/references/medusa-workflows/createInventoryItemsWorkflow"
1827 },
1828 {
1829 type: "step",
1830 name: "createProductsWorkflow",
1831 description: "Creates the Medusa product and its variants.",
1832 depth: 4,
1833 link: "/references/medusa-workflows/createProductsWorkflow"
1834 },
1835 {
1836 type: "step",
1837 name: "createTicketProductsStep",
1838 description: "Creates the ticket product.",
1839 depth: 5
1840 },
1841 {
1842 type: "step",
1843 name: "createTicketProductVariantsStep",
1844 description: "Creates the ticket product variants.",
1845 depth: 6
1846 },
1847 {
1848 type: "step",
1849 name: "createRemoteLinkStep",
1850 description: "Create links between the ticket product and variants and the Medusa product and variants.",
1851 depth: 7
1852 },
1853 {
1854 type: "step",
1855 name: "useQueryGraphStep",
1856 description: "Retrieve the created ticket product with its relations.",
1857 depth: 8,
1858 link: "/references/helper-steps/useQueryGraphStep",
1859 }
1860 ]
1861 }}
1862 hideLegend
1863 />
1864
1865 You only need to implement the `validateVenueAvailabilityStep`, `createTicketProductsStep`, and `createTicketProductVariantsStep` steps. The other steps are provided by Medusa.
1866
1867 #### validateVenueAvailabilityStep
1868
1869 The `validateVenueAvailabilityStep` validates that the selected venue is available for the show's date and time.
1870
1871 To create the step, create the file `src/workflows/steps/validate-venue-availability.ts` with the following content:
1872
1873 ```ts title="src/workflows/steps/validate-venue-availability.ts"
1874 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1875 import { TICKET_BOOKING_MODULE } from "../../modules/ticket-booking"
1876 import { MedusaError } from "@medusajs/framework/utils"
1877
1878 export type ValidateVenueAvailabilityStepInput = {
1879 venue_id: string
1880 dates: string[]
1881 }
1882
1883 export const validateVenueAvailabilityStep = createStep(
1884 "validate-venue-availability",
1885 async (input: ValidateVenueAvailabilityStepInput, { container }) => {
1886 const ticketBookingModuleService = container.resolve(TICKET_BOOKING_MODULE)
1887
1888 // Get all existing ticket products for this venue
1889 const existingTicketProducts = await ticketBookingModuleService
1890 .listTicketProducts({
1891 venue_id: input.venue_id,
1892 })
1893
1894 const hasConflict = existingTicketProducts.some((ticketProduct) =>
1895 ticketProduct.dates.some((date) => input.dates.includes(date))
1896 )
1897
1898 if (hasConflict) {
1899 throw new MedusaError(
1900 MedusaError.Types.INVALID_DATA,
1901 `Venue has conflicting shows on dates: ${input.dates.join(", ")}`
1902 )
1903 }
1904
1905 return new StepResponse({ valid: true })
1906 }
1907 )
1908 ```
1909
1910 In the step, you retrieve all existing ticket products for the selected venue and throw an error if any of the existing ticket products has a date that conflicts with the new show's dates.
1911
1912 #### createTicketProductsStep
1913
1914 The `createTicketProductsStep` creates ticket products.
1915
1916 To create the step, create the file `src/workflows/steps/create-ticket-products.ts` with the following content:
1917
1918 ```ts title="src/workflows/steps/create-ticket-products.ts"
1919 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1920 import { TICKET_BOOKING_MODULE } from "../../modules/ticket-booking"
1921
1922 export type CreateTicketProductsStepInput = {
1923 ticket_products: {
1924 product_id: string
1925 venue_id: string
1926 dates: string[]
1927 }[]
1928 }
1929
1930 export const createTicketProductsStep = createStep(
1931 "create-ticket-products",
1932 async (input: CreateTicketProductsStepInput, { container }) => {
1933 const ticketBookingModuleService = container.resolve(TICKET_BOOKING_MODULE)
1934
1935 // Create the main ticket product
1936 const ticketProducts = await ticketBookingModuleService
1937 .createTicketProducts(
1938 input.ticket_products
1939 )
1940
1941 return new StepResponse(
1942 {
1943 ticket_products: ticketProducts,
1944 },
1945 {
1946 ticket_products: ticketProducts,
1947 }
1948 )
1949 },
1950 async (compensationData, { container }) => {
1951 if (!compensationData?.ticket_products) {return}
1952
1953 const ticketBookingModuleService = container.resolve(TICKET_BOOKING_MODULE)
1954
1955 // Delete the ticket product
1956 await ticketBookingModuleService.deleteTicketProducts(
1957 compensationData.ticket_products.map((tp) => tp.id)
1958 )
1959 }
1960 )
1961 ```
1962
1963 This step receives an array of ticket products to create. It creates the ticket products and returns them.
1964
1965 In the compensation function, you delete the created ticket products if an error occurs in the workflow.
1966
1967 #### createTicketProductVariantsStep
1968
1969 The `createTicketProductVariantsStep` creates ticket product variants.
1970
1971 To create the step, create the file `src/workflows/steps/create-ticket-product-variants.ts` with the following content:
1972
1973 ```ts title="src/workflows/steps/create-ticket-product-variants.ts"
1974 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1975 import { TICKET_BOOKING_MODULE } from "../../modules/ticket-booking"
1976 import { RowType } from "../../modules/ticket-booking/models/venue-row"
1977
1978 export type CreateTicketProductVariantsStepInput = {
1979 variants: {
1980 ticket_product_id: string
1981 product_variant_id: string
1982 row_type: RowType
1983 }[]
1984 }
1985
1986 export const createTicketProductVariantsStep = createStep(
1987 "create-ticket-product-variants",
1988 async (input: CreateTicketProductVariantsStepInput, { container }) => {
1989 const ticketBookingModuleService = container.resolve(TICKET_BOOKING_MODULE)
1990
1991 // Create ticket product variants for each Medusa variant
1992 const ticketVariants = await ticketBookingModuleService
1993 .createTicketProductVariants(
1994 input.variants
1995 )
1996
1997 return new StepResponse(
1998 {
1999 ticket_product_variants: ticketVariants,
2000 },
2001 {
2002 ticket_product_variants: ticketVariants,
2003 }
2004 )
2005 },
2006 async (compensationData, { container }) => {
2007 if (!compensationData?.ticket_product_variants) {return}
2008
2009 const ticketBookingModuleService = container.resolve(TICKET_BOOKING_MODULE)
2010
2011 await ticketBookingModuleService.deleteTicketProductVariants(
2012 compensationData.ticket_product_variants.map((v) => v.id)
2013 )
2014 }
2015 )
2016 ```
2017
2018 This step receives an array of ticket product variants to create. It creates the ticket product variants and returns them.
2019
2020 In the compensation function, you delete the created ticket product variants if an error occurs in the workflow.
2021
2022 #### Create Ticket Product Workflow
2023
2024 You can now create the workflow that creates a ticket product.
2025
2026 To create the workflow, create the file `src/workflows/create-ticket-product.ts` with the following content:
2027
2028 ```ts title="src/workflows/create-ticket-product.ts" collapsibleLines="1-10" expandButtonLabel="Show Imports"
2029 import { createWorkflow, transform, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
2030 import { validateVenueAvailabilityStep } from "./steps/validate-venue-availability"
2031 import { createTicketProductsStep } from "./steps/create-ticket-products"
2032 import { useQueryGraphStep, createProductsWorkflow, createRemoteLinkStep, createInventoryItemsWorkflow } from "@medusajs/medusa/core-flows"
2033 import { CreateProductWorkflowInputDTO, CreateMoneyAmountDTO } from "@medusajs/framework/types"
2034 import { Modules } from "@medusajs/framework/utils"
2035 import { TICKET_BOOKING_MODULE } from "../modules/ticket-booking"
2036 import { RowType } from "../modules/ticket-booking/models/venue-row"
2037 import { createTicketProductVariantsStep } from "./steps/create-ticket-product-variants"
2038
2039 export type CreateTicketProductWorkflowInput = {
2040 name: string
2041 venue_id: string
2042 dates: string[]
2043 variants: Array<{
2044 row_type: RowType
2045 seat_count: number
2046 prices: CreateMoneyAmountDTO[]
2047 }>
2048 }
2049
2050 export const createTicketProductWorkflow = createWorkflow(
2051 "create-ticket-product",
2052 (input: CreateTicketProductWorkflowInput) => {
2053 validateVenueAvailabilityStep({
2054 venue_id: input.venue_id,
2055 dates: input.dates,
2056 })
2057
2058 const { data: stores } = useQueryGraphStep({
2059 entity: "store",
2060 fields: ["id", "default_location_id", "default_sales_channel_id"],
2061 })
2062
2063 // TODO create inventory items for each variant
2064 }
2065 )
2066 ```
2067
2068 You create the `createTicketProductWorkflow` workflow that accepts the details of the ticket product and its variants.
2069
2070 In the workflow, you validate the venue's availability using the `validateVenueAvailabilityStep`.
2071
2072 Then, you retrieve the default store configuration using the `useQueryGraphStep`. These configurations are useful when creating the Medusa inventory items and product.
2073
2074 <Note>
2075
2076 Make sure you have [default location and sales channel set up in your Medusa store](!user-guide!/settings/store).
2077
2078 </Note>
2079
2080 Next, you'll create inventory items for each variant before creating the Medusa product. Replace the `TODO` with the following:
2081
2082 ```ts title="src/workflows/create-ticket-product.ts"
2083 const inventoryItemsData = transform({
2084 input,
2085 stores,
2086 }, (data) => {
2087 const inventoryItems: any[] = []
2088
2089 for (const date of data.input.dates) {
2090 for (const variant of data.input.variants) {
2091 inventoryItems.push({
2092 sku: `${data.input.name}-${date}-${variant.row_type}`,
2093 title: `${data.input.name} - ${date} - ${variant.row_type}`,
2094 description: `Ticket for ${data.input.name} on ${date} in ${variant.row_type} seating`,
2095 location_levels: [{
2096 location_id: data.stores[0].default_location_id,
2097 stocked_quantity: variant.seat_count,
2098 }],
2099 requires_shipping: false,
2100 })
2101 }
2102 }
2103
2104 return inventoryItems
2105 })
2106
2107 const inventoryItems = createInventoryItemsWorkflow.runAsStep({
2108 input: {
2109 items: inventoryItemsData,
2110 },
2111 })
2112
2113 // TODO create the Medusa product
2114 ```
2115
2116 You prepare the inventory items to be created using the `transform` function. You create an inventory item for each combination of show date and variant.
2117
2118 Notice that for each inventory item, you set the `stocked_quantity` to the `seat_count` of the variant, ensuring that the inventory reflects the venue's seating capacity. You also set `requires_shipping` to `false`, allowing you to skip the shipping step during checkout.
2119
2120 Then, you create the inventory items using the `createInventoryItemsWorkflow`.
2121
2122 Next, you'll create the Medusa product and variants. Replace the `TODO` with the following:
2123
2124 ```ts title="src/workflows/create-ticket-product.ts"
2125 const productData = transform({
2126 input,
2127 inventoryItems,
2128 stores,
2129 }, (data) => {
2130 const rowTypes = [...new Set(
2131 data.input.variants.map((variant: any) => variant.row_type)
2132 )]
2133
2134 const product: CreateProductWorkflowInputDTO = {
2135 title: data.input.name,
2136 status: "published",
2137 options: [
2138 {
2139 title: "Date",
2140 values: data.input.dates,
2141 },
2142 {
2143 title: "Row Type",
2144 values: rowTypes,
2145 },
2146 ],
2147 variants: [] as any[],
2148 }
2149
2150 if (data.stores[0].default_sales_channel_id) {
2151 product.sales_channels = [
2152 {
2153 id: data.stores[0].default_sales_channel_id,
2154 },
2155 ]
2156 }
2157
2158 // Create variants for each date and row type combination
2159 let inventoryIndex = 0
2160 for (const date of data.input.dates) {
2161 for (const variant of data.input.variants) {
2162 product.variants!.push({
2163 title: `${data.input.name} - ${date} - ${variant.row_type}`,
2164 options: {
2165 Date: date,
2166 "Row Type": variant.row_type,
2167 },
2168 manage_inventory: true,
2169 inventory_items: [{
2170 inventory_item_id: data.inventoryItems[inventoryIndex].id,
2171 }],
2172 prices: variant.prices,
2173 })
2174 inventoryIndex++
2175 }
2176 }
2177
2178 return [product]
2179 })
2180
2181 const medusaProduct = createProductsWorkflow.runAsStep({
2182 input: {
2183 products: productData,
2184 },
2185 })
2186
2187 // TODO create the ticket product and variants
2188 ```
2189
2190 You prepare the Medusa product data using the `transform` function. You create options for "Date" and "Row Type" and create a variant for each combination of show date and row type.
2191
2192 You associate each variant with the corresponding inventory item created earlier, ensuring that the inventory is correctly linked to the product variants.
2193
2194 Then, you create the Medusa product using the `createProductsWorkflow`.
2195
2196 Next, you'll create the ticket product and its variants. Replace the `TODO` with the following:
2197
2198 ```ts title="src/workflows/create-ticket-product.ts"
2199 const ticketProductData = transform({
2200 medusaProduct,
2201 input,
2202 }, (data) => {
2203 return {
2204 ticket_products: data.medusaProduct.map((product: any) => ({
2205 product_id: product.id,
2206 venue_id: data.input.venue_id,
2207 dates: data.input.dates,
2208 })),
2209 }
2210 })
2211
2212 const { ticket_products } = createTicketProductsStep(
2213 ticketProductData
2214 )
2215
2216 const ticketVariantsData = transform({
2217 medusaProduct,
2218 ticket_products,
2219 input,
2220 }, (data) => {
2221 return {
2222 variants: data.medusaProduct[0].variants.map((variant: any) => {
2223 const rowType = variant.options.find(
2224 (opt: any) => opt.option?.title === "Row Type"
2225 )?.value
2226 return {
2227 ticket_product_id: data.ticket_products[0].id,
2228 product_variant_id: variant.id,
2229 row_type: rowType,
2230 }
2231 }),
2232 }
2233 })
2234
2235 const { ticket_product_variants } = createTicketProductVariantsStep(
2236 ticketVariantsData
2237 )
2238
2239 // TODO create links and retrieve the created ticket product
2240 ```
2241
2242 You prepare the ticket product data using the `transform` function, then create the ticket product using the `createTicketProductsStep`.
2243
2244 You also prepare the ticket product variants data, then create the ticket product variants using the `createTicketProductVariantsStep`.
2245
2246 Finally, you'll create links between the ticket product and variants and the Medusa product and variants, and retrieve the created ticket product with its relations. Replace the `TODO` with the following:
2247
2248 ```ts title="src/workflows/create-ticket-product.ts"
2249 const linksData = transform({
2250 medusaProduct,
2251 ticket_products,
2252 ticket_product_variants,
2253 }, (data) => {
2254 // Create links between ticket product and Medusa product
2255 const productLinks = [{
2256 [TICKET_BOOKING_MODULE]: {
2257 ticket_product_id: data.ticket_products[0].id,
2258 },
2259 [Modules.PRODUCT]: {
2260 product_id: data.medusaProduct[0].id,
2261 },
2262 }]
2263
2264 // Create links between ticket variants and Medusa variants
2265 const variantLinks = data.ticket_product_variants.map((variant) => ({
2266 [TICKET_BOOKING_MODULE]: {
2267 ticket_product_variant_id: variant.id,
2268 },
2269 [Modules.PRODUCT]: {
2270 product_variant_id: variant.product_variant_id,
2271 },
2272 }))
2273
2274 return [...productLinks, ...variantLinks]
2275 })
2276
2277 createRemoteLinkStep(linksData)
2278
2279 const { data: finalTicketProduct } = useQueryGraphStep({
2280 entity: "ticket_product",
2281 fields: [
2282 "id",
2283 "product_id",
2284 "venue_id",
2285 "dates",
2286 "venue.*",
2287 "product.*",
2288 "variants.*",
2289 ],
2290 filters: {
2291 id: ticket_products[0].id,
2292 },
2293 }).config({ name: "retrieve-ticket-product" })
2294
2295 return new WorkflowResponse({
2296 ticket_product: finalTicketProduct[0],
2297 })
2298 ```
2299
2300 You create links between the ticket product and the Medusa product, and between the ticket product variants and the Medusa product variants using the `createRemoteLinkStep`.
2301
2302 Then, you retrieve the created ticket product with its relations using the `useQueryGraphStep`.
2303
2304 Finally, you return the created ticket product in the workflow response.
2305
2306 ### b. Create Ticket Product API Route
2307
2308 Next, you'll create an API route that allows admin users to create a ticket product.
2309
2310 To create the API route, create the file `src/api/admin/ticket-products/route.ts` with the following content:
2311
2312 ```ts title="src/api/admin/ticket-products/route.ts" collapsibleLines="1-7" expandButtonLabel="Show Imports"
2313 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
2314 import {
2315 createTicketProductWorkflow,
2316 } from "../../../workflows/create-ticket-product"
2317 import { RowType } from "../../../modules/ticket-booking/models/venue-row"
2318 import { z } from "@medusajs/framework/zod"
2319
2320 export const CreateTicketProductSchema = z.object({
2321 name: z.string().min(1, "Name is required"),
2322 venue_id: z.string().min(1, "Venue ID is required"),
2323 dates: z.array(z.string()).min(1, "At least one date is required"),
2324 variants: z.array(z.object({
2325 row_type: z.enum(RowType),
2326 seat_count: z.number().min(1, "Seat count must be at least 1"),
2327 prices: z.array(z.object({
2328 currency_code: z.string().min(1, "Currency code is required"),
2329 amount: z.number().min(0, "Amount must be non-negative"),
2330 min_quantity: z.number().optional(),
2331 max_quantity: z.number().optional(),
2332 })).min(1, "At least one price is required"),
2333 })).min(1, "At least one variant is required"),
2334 })
2335
2336 type CreateTicketProductSchema = z.infer<typeof CreateTicketProductSchema>
2337
2338 export async function POST(
2339 req: MedusaRequest<CreateTicketProductSchema>,
2340 res: MedusaResponse
2341 ) {
2342 const { result } = await createTicketProductWorkflow(req.scope).run({
2343 input: req.validatedBody,
2344 })
2345
2346 res.json(result)
2347 }
2348 ```
2349
2350 You define the validation schema `CreateTicketProductSchema` that will be used to validate the request body.
2351
2352 Then, you export a `POST` route handler function, which will expose a `POST` API route at `/admin/ticket-products`.
2353
2354 In the route handler, you execute the `createTicketProductWorkflow` and return the created ticket product in the response.
2355
2356 You'll test the API route when you customize the Medusa Admin later.
2357
2358 ### c. Create Ticket Product Validation Middleware
2359
2360 To validate the request body against the schema you defined for creating ticket products, you'll apply a validation middleware to the API route.
2361
2362 In `src/api/middlewares.ts`, add the following import at the top of the file:
2363
2364 ```ts title="src/api/middlewares.ts"
2365 import { CreateTicketProductSchema } from "./admin/ticket-products/route"
2366 ```
2367
2368 Then, add a new object to the `routes` array passed to the `defineMiddlewares` function:
2369
2370 ```ts title="src/api/middlewares.ts"
2371 export default defineMiddlewares({
2372 routes: [
2373 // ...
2374 {
2375 matcher: "/admin/ticket-products",
2376 methods: ["POST"],
2377 middlewares: [
2378 validateAndTransformBody(CreateTicketProductSchema),
2379 ],
2380 },
2381 ],
2382 })
2383 ```
2384
2385 You apply the `validateAndTransformBody` middleware to the `POST /admin/ticket-products` route, passing it the `CreateTicketProductSchema` for validation.
2386
2387 ---
2388
2389 ## Step 8: List Ticket Products API Route
2390
2391 In this step, you'll add an API route to list ticket products. This will be useful when you customize the Medusa Admin to display ticket products.
2392
2393 To create the API route, add the following to the `src/api/admin/ticket-products/route.ts` file:
2394
2395 ```ts title="src/api/admin/ticket-products/route.ts"
2396 export async function GET(
2397 req: MedusaRequest,
2398 res: MedusaResponse
2399 ) {
2400 const query = req.scope.resolve(
2401 ContainerRegistrationKeys.QUERY
2402 )
2403
2404 const {
2405 data: ticketProducts,
2406 metadata,
2407 } = await query.graph({
2408 entity: "ticket_product",
2409 ...req.queryConfig,
2410 })
2411
2412 res.json({
2413 ticket_products: ticketProducts,
2414 count: metadata?.count,
2415 limit: metadata?.take,
2416 offset: metadata?.skip,
2417 })
2418 }
2419 ```
2420
2421 You export a `GET` route handler function, which will expose a `GET` API route at `/admin/ticket-products`.
2422
2423 In the route handler, you use Query to retrieve ticket products. You pass the `req.queryConfig` object to support pagination and field selection based on query configurations and parameters.
2424
2425 Finally, you return the ticket products along with pagination metadata in the response.
2426
2427 You'll test the API route when you customize the Medusa Admin later.
2428
2429 ### Add Validation Middleware for List Ticket Products API Route
2430
2431 To validate the query parameters of requests sent to the API route, and to allow clients to configure pagination and returned fields, you need to apply a query validation middleware.
2432
2433 To apply a middleware to the route, in `src/api/middlewares.ts`, add the following object to the `routes` array passed to the `defineMiddlewares` function:
2434
2435 ```ts title="src/api/middlewares.ts"
2436 export default defineMiddlewares({
2437 routes: [
2438 // ...
2439 {
2440 matcher: "/admin/ticket-products",
2441 methods: ["GET"],
2442 middlewares: [
2443 validateAndTransformQuery(createFindParams(), {
2444 isList: true,
2445 defaults: [
2446 "id",
2447 "product_id",
2448 "venue_id",
2449 "dates",
2450 "venue.*",
2451 "variants.*",
2452 "product.*",
2453 ],
2454 }),
2455 ],
2456 },
2457 ],
2458 })
2459 ```
2460
2461 You apply the `validateAndTransformQuery` middleware to `GET` requests sent to the `/admin/ticket-products` route. You pass it the `createFindParams` function to allow passing pagination and field selection parameters.
2462
2463 You also define the default fields of a ticket product to be returned in the response.
2464
2465 ---
2466
2467 ## Step 9: Manage Ticket Products in Medusa Admin
2468
2469 In this step, you'll customize the Medusa Admin to add a new page that shows a list of ticket products and allows creating new ticket products.
2470
2471 ### a. Define Ticket Product Type
2472
2473 Before you customize the Medusa Admin, you'll define a type for the ticket product to use in your customizations.
2474
2475 In `src/admin/types.ts`, add the following interface at the end of the file:
2476
2477 ```ts title="src/admin/types.ts"
2478 export interface TicketProduct {
2479 id: string
2480 product_id: string
2481 venue_id: string
2482 dates: string[]
2483 venue: {
2484 id: string
2485 name: string
2486 address?: string
2487 }
2488 product: {
2489 id: string
2490 title: string
2491 }
2492 variants: Array<{
2493 id: string
2494 row_type: string
2495 }>
2496 created_at: string
2497 updated_at: string
2498 }
2499 ```
2500
2501 You define the `TicketProduct` interface that describes the shape of a ticket product object.
2502
2503 ### b. Create Ticket Products Page
2504
2505 Next, you'll create the UI route for the ticket products page.
2506
2507 Create the file `src/admin/routes/ticket-products/page.tsx` with the following content:
2508
2509 ```tsx title="src/admin/routes/ticket-products/page.tsx" collapsibleLines="1-20" expandButtonLabel="Show Imports"
2510 import { defineRouteConfig } from "@medusajs/admin-sdk"
2511 import { ReceiptPercent } from "@medusajs/icons"
2512 import {
2513 createDataTableColumnHelper,
2514 Container,
2515 DataTable,
2516 useDataTable,
2517 Heading,
2518 DataTablePaginationState,
2519 Badge,
2520 toast,
2521 } from "@medusajs/ui"
2522 import { useQuery, useQueryClient } from "@tanstack/react-query"
2523 import { Link } from "react-router-dom"
2524 import React, { useState, useMemo } from "react"
2525 import { sdk } from "../../lib/sdk"
2526 import { TicketProduct } from "../../types"
2527
2528 const columnHelper = createDataTableColumnHelper<TicketProduct>()
2529
2530 const columns = [
2531 columnHelper.accessor("product.title", {
2532 header: "Name",
2533 }),
2534 columnHelper.accessor("venue.name", {
2535 header: "Venue",
2536 }),
2537 columnHelper.accessor("dates", {
2538 header: "Dates",
2539 cell: ({ row }) => {
2540 const dates = row.original.dates || []
2541 // Show first and last dates
2542 const displayDates = [dates[0], dates[dates.length - 1]]
2543 return (
2544 <div className="flex flex-wrap gap-1 items-center">
2545 {displayDates.map((date, index) => (
2546 <React.Fragment key={date}>
2547 <Badge color="grey" size="small">
2548 {new Date(date).toLocaleDateString()}
2549 </Badge>
2550 {index < displayDates.length - 1 && (
2551 <span className="text-gray-500 txt-small">
2552 -
2553 </span>
2554 )}
2555 </React.Fragment>
2556 ))}
2557 </div>
2558 )
2559 },
2560 }),
2561 columnHelper.accessor("product_id", {
2562 header: "Product",
2563 cell: ({ row }) => {
2564 return (
2565 <Link to={`/products/${row.original.product_id}`}>
2566 View Product Details
2567 </Link>
2568 )
2569 },
2570 }),
2571 ]
2572
2573 const TicketProductsPage = () => {
2574 // TODO show table
2575 }
2576
2577 export const config = defineRouteConfig({
2578 label: "Shows",
2579 icon: ReceiptPercent,
2580 })
2581
2582 export default TicketProductsPage
2583 ```
2584
2585 First, you define the columns for the data table that will display ticket products. You create columns for the ticket product's name, venue, dates, and a link to view the associated Medusa product.
2586
2587 Then, you create the `TicketProductsPage` component and export a configuration object that defines the route's sidebar label and icon.
2588
2589 Next, you'll implement the `TicketProductsPage` component to show the table of ticket products. Replace the `TicketProductsPage` component with the following:
2590
2591 ```tsx title="src/admin/routes/ticket-products/page.tsx"
2592 const TicketProductsPage = () => {
2593 const limit = 15
2594 const [pagination, setPagination] = useState<DataTablePaginationState>({
2595 pageSize: limit,
2596 pageIndex: 0,
2597 })
2598
2599 const queryClient = useQueryClient()
2600
2601 const offset = useMemo(() => {
2602 return pagination.pageIndex * limit
2603 }, [pagination])
2604
2605 const { data, isLoading } = useQuery<{
2606 ticket_products: TicketProduct[]
2607 count: number
2608 limit: number
2609 offset: number
2610 }>({
2611 queryKey: ["ticket-products", offset, limit],
2612 queryFn: () => sdk.client.fetch("/admin/ticket-products", {
2613 query: {
2614 offset: pagination.pageIndex * pagination.pageSize,
2615 limit: pagination.pageSize,
2616 order: "-created_at",
2617 },
2618 }),
2619 })
2620
2621 const table = useDataTable({
2622 columns,
2623 data: data?.ticket_products || [],
2624 rowCount: data?.count || 0,
2625 isLoading,
2626 pagination: {
2627 state: pagination,
2628 onPaginationChange: setPagination,
2629 },
2630 getRowId: (row) => row.id,
2631 })
2632
2633 return (
2634 <Container className="divide-y p-0">
2635 <DataTable instance={table}>
2636 <DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center">
2637 <Heading>
2638 Shows
2639 </Heading>
2640 </DataTable.Toolbar>
2641 <DataTable.Table />
2642 <DataTable.Pagination />
2643 </DataTable>
2644 </Container>
2645 )
2646 }
2647 ```
2648
2649 In the component, you define variables to manage pagination in the data table. You also use Tanstack Query and the JS SDK to retrieve the ticket products from the `GET /admin/ticket-products` API route you created earlier.
2650
2651 Then, you use Medusa UI's `DataTable` component to render the table of ticket products.
2652
2653 ### c. Create Ticket Product Modal
2654
2655 Next, you'll create a modal component that allows creating a new ticket product. You'll show the modal when a button is clicked on the ticket products page.
2656
2657 The modal form is made up of two steps: one to select the venue and show dates, and another to set the prices of each row type. So, you'll create the components for each step first.
2658
2659 #### Create Product Details Step
2660
2661 To create the first step component, create the file `src/admin/components/product-details-step.tsx` with the following content:
2662
2663 ```tsx title="src/admin/components/product-details-step.tsx" collapsibleLines="1-13" expandButtonLabel="Show Imports"
2664 import { useState } from "react"
2665 import {
2666 Input,
2667 Label,
2668 Select,
2669 DatePicker,
2670 Button,
2671 Text,
2672 Heading,
2673 Badge,
2674 } from "@medusajs/ui"
2675 import { XMark } from "@medusajs/icons"
2676 import { Venue } from "../types"
2677
2678 interface ProductDetailsStepProps {
2679 name: string
2680 setName: (name: string) => void
2681 selectedVenueId: string
2682 setSelectedVenueId: (venueId: string) => void
2683 selectedDates: string[]
2684 setSelectedDates: (dates: string[]) => void
2685 venues: Venue[]
2686 }
2687
2688 export const ProductDetailsStep = ({
2689 name,
2690 setName,
2691 selectedVenueId,
2692 setSelectedVenueId,
2693 selectedDates,
2694 setSelectedDates,
2695 venues,
2696 }: ProductDetailsStepProps) => {
2697 const selectedVenue = venues.find((v) => v.id === selectedVenueId)
2698
2699 // Local state for start and end dates
2700 const [startDate, setStartDate] = useState<Date | undefined>(
2701 selectedDates.length > 0 ? new Date(selectedDates[0] + "T00:00:00") : undefined
2702 )
2703 const [endDate, setEndDate] = useState<Date | undefined>(
2704 selectedDates.length > 1 ? new Date(selectedDates[selectedDates.length - 1] + "T00:00:00") : undefined
2705 )
2706
2707 // TODO handle date selection
2708 }
2709 ```
2710
2711 You define the `ProductDetailsStep` component that accepts props for managing the form state, including the ticket product name, selected venue, and selected dates.
2712
2713 In the component, you also define local state for the start and end dates used in the date picker.
2714
2715 Next, you'll add functions that handle selecting dates. Admins can select a start and end date, which will select the range of dates in between. Admins can also delete any date from the range.
2716
2717 Replace the `TODO` with the following:
2718
2719 ```tsx title="src/admin/components/product-details-step.tsx"
2720 const generateDateRange = (start: Date, end?: Date) => {
2721 const dates: string[] = []
2722 const currentDate = new Date(start)
2723
2724 do {
2725 // Use local date formatting to avoid timezone issues
2726 const year = currentDate.getFullYear()
2727 const month = String(currentDate.getMonth() + 1).padStart(2, "0")
2728 const day = String(currentDate.getDate()).padStart(2, "0")
2729 dates.push(`${year}-${month}-${day}`)
2730 currentDate.setDate(currentDate.getDate() + 1)
2731 } while (end && currentDate <= end)
2732
2733 return dates
2734 }
2735
2736 const handleStartDateChange = (date: Date | null) => {
2737 const dateValue = date || undefined
2738 setStartDate(dateValue)
2739 setSelectedDates(
2740 dateValue ? generateDateRange(dateValue, endDate) : []
2741 )
2742 }
2743
2744 const handleEndDateChange = (date: Date | null) => {
2745 const dateValue = date || undefined
2746 setEndDate(dateValue)
2747 if (startDate && dateValue) {
2748 setSelectedDates(generateDateRange(startDate, dateValue))
2749 } else if (dateValue) {
2750 setSelectedDates(generateDateRange(dateValue))
2751 } else {
2752 setSelectedDates([])
2753 }
2754 }
2755
2756 const removeDate = (dateToRemove: string) => {
2757 setSelectedDates(selectedDates.filter((d) => d !== dateToRemove))
2758 }
2759
2760 // TODO render form
2761 ```
2762
2763 You define the following functions:
2764
2765 - `generateDateRange`: Generates an array of date strings between a start and optional end date.
2766 - `handleStartDateChange`: Handles changes to the start date, updating the selected dates accordingly.
2767 - `handleEndDateChange`: Handles changes to the end date, updating the selected dates accordingly.
2768 - `removeDate`: Removes a specific date from the selected dates.
2769
2770 Finally, you'll render the form for the product details step. Replace the `TODO` with the following:
2771
2772 ```tsx title="src/admin/components/product-details-step.tsx"
2773 return (
2774 <div className="space-y-6">
2775 <Heading level="h2">Show Details</Heading>
2776 <div>
2777 <Label htmlFor="name">Name</Label>
2778 <Input
2779 id="name"
2780 value={name}
2781 onChange={(e) => setName(e.target.value)}
2782 placeholder="Enter name"
2783 />
2784 </div>
2785
2786 <div>
2787 <Label htmlFor="venue">Venue</Label>
2788 <Select
2789 value={selectedVenueId}
2790 onValueChange={setSelectedVenueId}
2791 >
2792 <Select.Trigger>
2793 <Select.Value placeholder="Select a venue" />
2794 </Select.Trigger>
2795 <Select.Content>
2796 {venues.map((venue) => (
2797 <Select.Item key={venue.id} value={venue.id}>
2798 {venue.name}
2799 </Select.Item>
2800 ))}
2801 </Select.Content>
2802 </Select>
2803 </div>
2804
2805 {selectedVenue && (
2806 <div className="p-4 bg-gray-50 rounded-lg">
2807 <Text className="txt-small-plus mb-2">Selected Venue: {selectedVenue.name}</Text>
2808 {selectedVenue.address && (
2809 <Text className="txt-small text-ui-fg-subtle mb-2">{selectedVenue.address}</Text>
2810 )}
2811 <Text className="txt-small text-ui-fg-subtle">
2812 Rows: {[...new Set(selectedVenue.rows.map((row) => row.row_type))].join(", ")}<br/>
2813 Total Seats: {selectedVenue.rows.reduce((acc, row) => acc + row.seat_count, 0)}
2814 </Text>
2815 </div>
2816 )}
2817
2818 <hr className="my-6" />
2819
2820 <div>
2821 <Heading level="h2">Dates</Heading>
2822 <div className="mt-2 space-y-4">
2823 <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
2824 <div>
2825 <Label htmlFor="start-date">Start Date</Label>
2826 <DatePicker
2827 value={startDate}
2828 onChange={handleStartDateChange}
2829 maxValue={endDate}
2830 />
2831 </div>
2832 <div>
2833 <Label htmlFor="end-date">End Date</Label>
2834 <DatePicker
2835 value={endDate}
2836 onChange={handleEndDateChange}
2837 minValue={startDate}
2838 />
2839 </div>
2840 </div>
2841
2842 {selectedDates.length > 0 && (
2843 <div className="space-y-2">
2844 <Text className="txt-small-plus">
2845 Selected Dates ({selectedDates.length} day{selectedDates.length !== 1 ? "s" : ""}):
2846 </Text>
2847 <div className="flex flex-wrap gap-2">
2848 {selectedDates.map((date) => (
2849 <Badge
2850 key={date}
2851 color="blue"
2852 >
2853 <span>{new Date(date).toLocaleDateString()}</span>
2854 <Button
2855 variant="transparent"
2856 size="small"
2857 onClick={() => removeDate(date)}
2858 className="p-1 hover:bg-transparent"
2859 >
2860 <XMark />
2861 </Button>
2862 </Badge>
2863 ))}
2864 </div>
2865 </div>
2866 )}
2867 </div>
2868 </div>
2869 </div>
2870 )
2871 ```
2872
2873 You render the form for the product details step, including inputs for the ticket product name, venue selection, and date selection.
2874
2875 #### Pricing Step
2876
2877 Next, you'll create the second step component for setting prices for each row type.
2878
2879 To create the step component, create the file `src/admin/components/pricing-step.tsx` with the following content:
2880
2881 ```tsx title="src/admin/components/pricing-step.tsx" collapsibleLines="1-10" expandButtonLabel="Show Imports"
2882 import {
2883 Input,
2884 Label,
2885 Text,
2886 Heading,
2887 Container,
2888 Badge,
2889 } from "@medusajs/ui"
2890 import { RowType, Venue } from "../types"
2891
2892 export interface CurrencyRegionCombination {
2893 currency: string
2894 region_id?: string
2895 region_name?: string
2896 is_store_currency: boolean
2897 }
2898
2899 interface PricingStepProps {
2900 selectedVenue: Venue | undefined
2901 currencyRegionCombinations: CurrencyRegionCombination[]
2902 prices: Record<string, Record<string, number>>
2903 setPrices: (prices: Record<string, Record<string, number>>) => void
2904 }
2905
2906 export const PricingStep = ({
2907 selectedVenue,
2908 currencyRegionCombinations,
2909 prices,
2910 setPrices,
2911 }: PricingStepProps) => {
2912 if (!selectedVenue) {
2913 return (
2914 <div className="text-center py-8">
2915 <Text>Please select a venue in the previous step</Text>
2916 </div>
2917 )
2918 }
2919
2920 // TODO add price and row type functions
2921 }
2922 ```
2923
2924 You define the `PricingStep` component that accepts props for the selected venue, currency-region combinations, and prices.
2925
2926 <Note title="Tip">
2927
2928 In Medusa, you can set the price of a product variant in multiple currencies and regions. This allows you to sell products in different markets with localized pricing. Learn more in the [Pricing documentation](../../../commerce-modules/pricing/concepts/page.mdx).
2929
2930 </Note>
2931
2932 In the component, if no venue is selected, you display a message prompting the user to select a venue in the previous step.
2933
2934 Next, you'll add functions for formatting and to handle price changes. Replace the `TODO` with the following:
2935
2936 ```tsx title="src/admin/components/pricing-step.tsx"
2937 const updatePrice = (
2938 rowType: string,
2939 currency: string,
2940 regionId: string | undefined,
2941 amount: number
2942 ) => {
2943 const key = regionId ? `${currency}_${regionId}` : `${currency}_store`
2944 setPrices({
2945 ...prices,
2946 [rowType]: {
2947 ...prices[rowType],
2948 [key]: amount,
2949 },
2950 })
2951 }
2952
2953 const getRowTypeColor = (
2954 type: RowType
2955 ): "purple" | "orange" | "blue" | "grey" => {
2956 switch (type) {
2957 case RowType.VIP:
2958 return "purple"
2959 case RowType.PREMIUM:
2960 return "orange"
2961 case RowType.BALCONY:
2962 return "blue"
2963 default:
2964 return "grey"
2965 }
2966 }
2967
2968 const getRowTypeLabel = (type: RowType) => {
2969 switch (type) {
2970 case RowType.VIP:
2971 return "VIP"
2972 default:
2973 return type.charAt(0).toUpperCase() + type.slice(1)
2974 }
2975 }
2976
2977 // Get unique row types from venue
2978 const rowTypes = [...new Set(selectedVenue.rows.map((row) => row.row_type))]
2979
2980 // TODO render form
2981 ```
2982
2983 You define the following functions:
2984
2985 - `updatePrice`: Updates the price for a specific row type and currency-region combination.
2986 - `getRowTypeColor`: Returns a color based on the row type for styling purposes.
2987 - `getRowTypeLabel`: Returns a formatted label for the row type.
2988
2989 You also extract the unique row types from the selected venue to use in the form.
2990
2991 Finally, you'll render the form for the pricing step. Replace the `TODO` with the following:
2992
2993 ```tsx title="src/admin/components/pricing-step.tsx"
2994 return (
2995 <div className="space-y-6">
2996 <div>
2997 <Heading level="h3">Set Prices for Each Row Type</Heading>
2998 <Text className="text-ui-fg-subtle">
2999 Enter prices for each row type by region and currency. All prices are optional.
3000 </Text>
3001 </div>
3002
3003 <div className="space-y-4">
3004 {rowTypes.map((rowType) => {
3005 const totalSeats = selectedVenue.rows
3006 .filter((row) => row.row_type === rowType)
3007 .reduce((sum, row) => sum + row.seat_count, 0)
3008
3009 return (
3010 <Container key={rowType} className="p-4">
3011 <div className="flex items-center gap-3 mb-4">
3012 <Badge color={getRowTypeColor(rowType as RowType)} size="small">
3013 {getRowTypeLabel(rowType)}
3014 </Badge>
3015 <Text className="txt-small text-ui-fg-subtle">
3016 {totalSeats} seats total
3017 </Text>
3018 </div>
3019
3020 <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
3021 {currencyRegionCombinations.map((combo) => {
3022 const key = combo.region_id ? `${combo.currency}_${combo.region_id}` : `${combo.currency}_store`
3023 return (
3024 <div key={key}>
3025 <Label htmlFor={`${rowType}-${key}`}>
3026 {combo.currency.toUpperCase()} - {combo.region_name || "Store"}
3027 </Label>
3028 <Input
3029 id={`${rowType}-${key}`}
3030 type="number"
3031 min="0"
3032 step="0.01"
3033 value={prices[rowType]?.[key] || ""}
3034 onChange={(e) => {
3035 const amount = parseFloat(e.target.value) || 0
3036 updatePrice(rowType, combo.currency, combo.region_id, amount)
3037 }}
3038 placeholder="0.00"
3039 />
3040 </div>
3041 )
3042 })}
3043 </div>
3044 </Container>
3045 )
3046 })}
3047 </div>
3048 </div>
3049 )
3050 ```
3051
3052 You render the form for the pricing step, including sections for each row type with inputs for setting prices in different currencies and regions.
3053
3054 #### Create Ticket Product Modal
3055
3056 You can now create the modal component that shows a multi-step form to create a ticket product.
3057
3058 Create the file `src/admin/components/create-ticket-product-modal.tsx` with the following content:
3059
3060 ```tsx title="src/admin/components/create-ticket-product-modal.tsx" collapsibleLines="1-13" expandButtonLabel="Show Imports"
3061 import React, { useState } from "react"
3062 import {
3063 Button,
3064 FocusModal,
3065 ProgressTabs,
3066 toast,
3067 } from "@medusajs/ui"
3068 import { useQuery } from "@tanstack/react-query"
3069 import { sdk } from "../lib/sdk"
3070 import { RowType, Venue } from "../types"
3071 import { ProductDetailsStep } from "./product-details-step"
3072 import { CurrencyRegionCombination, PricingStep } from "./pricing-step"
3073
3074 interface CreateTicketProductModalProps {
3075 open: boolean
3076 onOpenChange: (open: boolean) => void
3077 onSubmit: (data: any) => Promise<void>
3078 }
3079
3080 export const CreateTicketProductModal = ({
3081 open,
3082 onOpenChange,
3083 onSubmit,
3084 }: CreateTicketProductModalProps) => {
3085 const [currentStep, setCurrentStep] = useState("0")
3086 const [isLoading, setIsLoading] = useState(false)
3087
3088 // Step 1 data
3089 const [name, setName] = useState("")
3090 const [selectedVenueId, setSelectedVenueId] = useState("")
3091 const [selectedDates, setSelectedDates] = useState<string[]>([])
3092
3093 // Step 2 data - prices[rowType][currency_region] = amount
3094 const [prices, setPrices] = useState<Record<string, Record<string, number>>>({})
3095
3096 // TODO fetch venues and currency-region combinations
3097 }
3098 ```
3099
3100 You define the `CreateTicketProductModal` component that accepts props for managing the modal's open state and handling form submission.
3101
3102 In the component, you define state variables to manage the current step, loading state, and form data for both steps.
3103
3104 Next, you'll fetch the list of venues, regions, and store currencies from the Medusa backend. Replace the `TODO` with the following:
3105
3106 ```tsx title="src/admin/components/create-ticket-product-modal.tsx"
3107 // Fetch venues
3108 const { data: venuesData } = useQuery<{
3109 venues: Venue[]
3110 count: number
3111 }>({
3112 queryKey: ["venues"],
3113 queryFn: () => sdk.client.fetch("/admin/venues"),
3114 })
3115
3116 // Fetch regions
3117 const { data: regionsData } = useQuery({
3118 queryKey: ["regions"],
3119 queryFn: () => sdk.admin.region.list(),
3120 })
3121
3122 // Fetch stores
3123 const { data: storesData } = useQuery({
3124 queryKey: ["stores"],
3125 queryFn: () => sdk.admin.store.list(),
3126 })
3127
3128 const venues = venuesData?.venues || []
3129 const regions = regionsData?.regions || []
3130 const stores = storesData?.stores || []
3131 const selectedVenue = venues?.find((v) => v.id === selectedVenueId)
3132
3133 // TODO prepare currency-region combinations
3134 ```
3135
3136 You use Tanstack Query and the JS SDK to fetch the list of venues from the `GET /admin/venues` API route, and the list of regions and stores from admin API routes.
3137
3138 Next, you'll prepare the currency-region combinations based on the store and region data fetched. Replace the `TODO` with the following:
3139
3140 ```tsx title="src/admin/components/create-ticket-product-modal.tsx"
3141 const currencyRegionCombinations = React.useMemo(() => {
3142 const combinations: Array<CurrencyRegionCombination> = []
3143
3144 // Add combinations from regions
3145 regions.forEach((region: any) => {
3146 combinations.push({
3147 currency: region.currency_code,
3148 region_id: region.id,
3149 region_name: region.name,
3150 is_store_currency: false,
3151 })
3152 })
3153
3154 // Add combinations from stores (all supported currencies)
3155 stores.forEach((store) => {
3156 // Add all supported currencies
3157 store.supported_currencies.forEach((currency) => {
3158 combinations.push({
3159 currency: currency.currency_code,
3160 region_id: undefined, // No region for store currencies
3161 is_store_currency: true,
3162 })
3163 })
3164 })
3165
3166 return combinations
3167 }, [regions, stores])
3168
3169 // TODO handle form actions
3170 ```
3171
3172 You create a memoized array of currency-region combinations by iterating over the fetched regions and stores. You add combinations for each region's currency and each store's supported currencies.
3173
3174 Next, you'll add functions to handle form actions like resetting the form or moving between steps. Replace the `TODO` with the following:
3175
3176 ```tsx title="src/admin/components/create-ticket-product-modal.tsx"
3177 const resetForm = () => {
3178 setName("")
3179 setSelectedVenueId("")
3180 setSelectedDates([])
3181 setPrices({})
3182 setCurrentStep("0")
3183 }
3184
3185 const handleCloseModal = (open: boolean) => {
3186 if (!open) {
3187 resetForm()
3188 }
3189 onOpenChange(open)
3190 }
3191
3192 const handleStep1Next = () => {
3193 if (!name.trim()) {
3194 toast.error("Name is required")
3195 return
3196 }
3197 if (!selectedVenueId) {
3198 toast.error("Please select a venue")
3199 return
3200 }
3201 if (selectedDates.length === 0) {
3202 toast.error("Please select at least one date")
3203 return
3204 }
3205 setCurrentStep("1")
3206 }
3207
3208 const handleStep2Submit = async () => {
3209 if (!selectedVenue) {
3210 toast.error("Venue not found")
3211 return
3212 }
3213
3214 // Prepare variants data
3215 // combine rows with the same row_type
3216 const combinedRows: Record<RowType, { seat_count: number }> = {
3217 premium: { seat_count: 0 },
3218 balcony: { seat_count: 0 },
3219 standard: { seat_count: 0 },
3220 vip: { seat_count: 0 },
3221 }
3222 selectedVenue.rows.forEach((row) => {
3223 if (!combinedRows[row.row_type]) {
3224 combinedRows[row.row_type] = { seat_count: 0 }
3225 }
3226 combinedRows[row.row_type].seat_count += row.seat_count
3227 })
3228 const variants = Object.keys(combinedRows).map((rowType) => ({
3229 row_type: rowType as RowType,
3230 seat_count: combinedRows[rowType as RowType].seat_count,
3231 prices: currencyRegionCombinations.map((combo) => {
3232 const key = combo.region_id ? `${combo.currency}_${combo.region_id}` : `${combo.currency}_store`
3233 const amount = prices[rowType as RowType]?.[key] || 0
3234
3235 const price: any = {
3236 currency_code: combo.currency,
3237 amount: amount,
3238 }
3239
3240 // Only add rules for region-based currencies
3241 if (combo.region_id && !combo.is_store_currency) {
3242 price.rules = {
3243 region_id: combo.region_id,
3244 }
3245 }
3246
3247 return price
3248 }).filter((price) => price.amount > 0), // Only include prices > 0
3249 })).filter((variant) => variant.seat_count > 0) // Only create variants for row types with seats
3250
3251 setIsLoading(true)
3252 try {
3253 await onSubmit({
3254 name,
3255 venue_id: selectedVenueId,
3256 dates: selectedDates,
3257 variants,
3258 })
3259 toast.success("Show created successfully")
3260 handleCloseModal(false)
3261 } catch (error: any) {
3262 toast.error(error.message || "Failed to create show")
3263 } finally {
3264 setIsLoading(false)
3265 }
3266 }
3267
3268 // TODO define steps
3269 ```
3270
3271 You define the following functions:
3272
3273 - `resetForm`: Resets the form state to its initial values.
3274 - `handleCloseModal`: Handles closing the modal and resets the form if it's being closed.
3275 - `handleStep1Next`: Validates the inputs in the first step before moving to the next step.
3276 - `handleStep2Submit`: Prepares the data from both steps and calls the `onSubmit` prop to create the ticket product.
3277
3278 Before submitting the form, you combine rows with the same `row_type` to create variants and prepare the prices for each variant based on the selected currency-region combinations.
3279
3280 Next, you'll define step variables useful to render the multi-step form. Replace the `TODO` with the following:
3281
3282 ```tsx title="src/admin/components/create-ticket-product-modal.tsx"
3283 // Check if step 1 (Product Details) is completed
3284 const isStep1Completed = name.trim() && selectedVenueId && selectedDates.length > 0
3285
3286 // Check if step 2 (Pricing) is completed
3287 const hasAnyPrices = Object.values(prices).some((rowPrices) =>
3288 Object.values(rowPrices).some((amount) => amount > 0)
3289 )
3290 const isStep2Completed = isStep1Completed && hasAnyPrices
3291
3292 const steps = [
3293 {
3294 label: "Product Details",
3295 value: "0",
3296 status: isStep1Completed ? "completed" as const : undefined,
3297 content: (
3298 <ProductDetailsStep
3299 name={name}
3300 setName={setName}
3301 selectedVenueId={selectedVenueId}
3302 setSelectedVenueId={setSelectedVenueId}
3303 selectedDates={selectedDates}
3304 setSelectedDates={setSelectedDates}
3305 venues={venues}
3306 />
3307 ),
3308 },
3309 {
3310 label: "Pricing",
3311 value: "1",
3312 status: isStep2Completed ? "completed" as const : undefined,
3313 content: (
3314 <PricingStep
3315 selectedVenue={selectedVenue}
3316 currencyRegionCombinations={currencyRegionCombinations}
3317 prices={prices}
3318 setPrices={setPrices}
3319 />
3320 ),
3321 },
3322 ]
3323
3324 // TODO render modal
3325 ```
3326
3327 You define variables to check if each step is completed based on the form inputs. You also define an array of step objects, each containing a label, value, status, and content component.
3328
3329 Finally, you'll render the modal with the multi-step form. Replace the `TODO` with the following:
3330
3331 ```tsx title="src/admin/components/create-ticket-product-modal.tsx"
3332 return (
3333 <FocusModal open={open} onOpenChange={handleCloseModal}>
3334 <FocusModal.Content>
3335 <FocusModal.Header className="justify-start py-0">
3336 <div className="flex flex-col gap-4 w-full">
3337 <ProgressTabs
3338 value={currentStep}
3339 onValueChange={setCurrentStep}
3340 className="w-full"
3341 >
3342 <ProgressTabs.List className="w-full">
3343 {steps.map((step) => (
3344 <ProgressTabs.Trigger
3345 key={step.value}
3346 value={step.value}
3347 status={step.status}
3348 >
3349 {step.label}
3350 </ProgressTabs.Trigger>
3351 ))}
3352 </ProgressTabs.List>
3353 </ProgressTabs>
3354 </div>
3355 </FocusModal.Header>
3356 <FocusModal.Body className="flex flex-1 flex-col p-6">
3357 <ProgressTabs
3358 value={currentStep}
3359 onValueChange={setCurrentStep}
3360 className="flex-1 w-full mx-auto"
3361 >
3362 {steps.map((step) => (
3363 <ProgressTabs.Content key={step.value} value={step.value} className="flex-1">
3364 <div className="max-w-[720px] mx-auto">
3365 {step.content}
3366 </div>
3367 </ProgressTabs.Content>
3368 ))}
3369 </ProgressTabs>
3370 </FocusModal.Body>
3371 <FocusModal.Footer>
3372 <Button
3373 variant="secondary"
3374 onClick={() => setCurrentStep(currentStep === "1" ? "0" : "0")}
3375 disabled={currentStep === "0"}
3376 >
3377 Previous
3378 </Button>
3379
3380 {currentStep === "0" ? (
3381 <Button
3382 variant="primary"
3383 onClick={handleStep1Next}
3384 >
3385 Next
3386 </Button>
3387 ) : (
3388 <Button
3389 variant="primary"
3390 onClick={handleStep2Submit}
3391 isLoading={isLoading}
3392 >
3393 Create Show
3394 </Button>
3395 )}
3396 </FocusModal.Footer>
3397 </FocusModal.Content>
3398 </FocusModal>
3399 )
3400 ```
3401
3402 You render the `FocusModal` component with a header containing progress tabs for navigation between steps, a body displaying the content of the current step, and a footer with buttons to navigate between steps or submit the form.
3403
3404 ### d. Add Modal to Ticket Products Page
3405
3406 You can now render the `CreateTicketProductModal` component in the `TicketProductsPage` component.
3407
3408 In `src/admin/routes/ticket-products/page.tsx`, add the following imports at the top of the file:
3409
3410 ```tsx title="src/admin/routes/ticket-products/page.tsx"
3411 import {
3412 Button,
3413 } from "@medusajs/ui"
3414 import { CreateTicketProductModal } from "../../components/create-ticket-product-modal"
3415 ```
3416
3417 Then, in the `TicketProductsPage` component, add the following state variable to manage the modal's open state:
3418
3419 ```tsx title="src/admin/routes/ticket-products/page.tsx"
3420 const TicketProductsPage = () => {
3421 const [isModalOpen, setIsModalOpen] = useState(false)
3422 // ...
3423 }
3424 ```
3425
3426 Next, before the return statement, add the following functions to handle closing the modal and submitting the form:
3427
3428 ```tsx title="src/admin/routes/ticket-products/page.tsx"
3429 const TicketProductsPage = () => {
3430 // ...
3431 const handleCloseModal = () => {
3432 setIsModalOpen(false)
3433 }
3434
3435 const handleCreateTicketProduct = async (data: any) => {
3436 try {
3437 await sdk.client.fetch("/admin/ticket-products", {
3438 method: "POST",
3439 body: data,
3440 })
3441 queryClient.invalidateQueries({ queryKey: ["ticket-products"] })
3442 handleCloseModal()
3443 } catch (error: any) {
3444 toast.error(`Failed to create show: ${error.message}`)
3445 }
3446 }
3447 // ...
3448 }
3449 ```
3450
3451 You define the `handleCloseModal` function to close the modal, and the `handleCreateTicketProduct` function to submit the form data to the `POST /admin/ticket-products` API route you created earlier.
3452
3453 Finally, in the return statement, add a button to open the modal as the last child of `DataTable.Toolbar`:
3454
3455 ```tsx title="src/admin/routes/ticket-products/page.tsx"
3456 return (
3457 <Container className="divide-y p-0">
3458 {/* ... */}
3459 <Button
3460 variant="secondary"
3461 onClick={() => setIsModalOpen(true)}
3462 >
3463 Create Show
3464 </Button>
3465 {/* ... */}
3466 </Container>
3467 )
3468 ```
3469
3470 And add the `CreateTicketProductModal` component as the last child of the `Container` component:
3471
3472 ```tsx title="src/admin/routes/ticket-products/page.tsx"
3473 return (
3474 <Container className="divide-y p-0">
3475 {/* ... */}
3476 <CreateTicketProductModal
3477 open={isModalOpen}
3478 onOpenChange={handleCloseModal}
3479 onSubmit={handleCreateTicketProduct}
3480 />
3481 </Container>
3482 )
3483 ```
3484
3485 ### Test the Ticket Products Page
3486
3487 You can now test the ticket products page in the Medusa Admin.
3488
3489 Start the Medusa server if it isn't already running. If you open the Medusa Admin and log in, you should see a new "Shows" item in the sidebar. If you click on it, you can see a table of ticket products with a button to create a new show.
3490
3491 ![Shows page with the table of ticket products and a button to create a new show](https://res.cloudinary.com/dza7lstvk/image/upload/v1757490157/Medusa%20Resources/CleanShot_2025-09-10_at_10.42.00_2x_jsaq7v.png)
3492
3493 To create a new show (or ticket product):
3494
3495 1. Click the "Create Show" button to open the modal.
3496 2. In the "Product Details" step, enter a name for the show, select a venue, and select one or more dates using the date pickers.
3497 3. Click "Next" to go to the "Pricing" step.
3498
3499 ![Create Show modal with the Product Details step](https://res.cloudinary.com/dza7lstvk/image/upload/v1757490395/Medusa%20Resources/CleanShot_2025-09-10_at_10.46.23_2x_v2pbuo.png)
3500
3501 4. In the "Pricing" step, set prices for each row type. You can set prices in different currencies and regions. All prices are optional.
3502 5. Once you're done, click "Create Show" to submit the form.
3503
3504 ![Create Show modal with the Pricing step](https://res.cloudinary.com/dza7lstvk/image/upload/v1757490725/Medusa%20Resources/CleanShot_2025-09-10_at_10.51.55_2x_bijkab.png)
3505
3506 This will create a new ticket product with a Medusa product. You can view the ticket product in the table, and you can click the link to view the associated Medusa product.
3507
3508 You can edit the associated Medusa product to add images, descriptions, and other details for the show.
3509
3510 ---
3511
3512 ## Step 10: Validate Ticket on Add to Cart
3513
3514 In this step, you'll add custom validation to the core add-to-cart operation that ensures a seat isn't purchased more than once for the same date.
3515
3516 Medusa implements cart operations in workflows. Specifically, you'll focus on the `addToCartWorkflow`. Medusa allows you to inject custom logic into workflows using [hooks](!docs!/learn/fundamentals/workflows/workflow-hooks).
3517
3518 A workflow hook is a point in a workflow where you can inject custom functionality as a step function.
3519
3520 To consume the `validate` hook of the `addToCartWorkflow` that holds the add-to-cart logic, create the file `src/workflows/hooks/add-to-cart-validation.ts` with the following content:
3521
3522 ```ts title="src/workflows/hooks/add-to-cart-validation.ts"
3523 import { addToCartWorkflow } from "@medusajs/medusa/core-flows"
3524 import {
3525 MedusaError,
3526 ContainerRegistrationKeys,
3527 } from "@medusajs/framework/utils"
3528
3529 // Hook for addToCartWorkflow to validate seat availability
3530 addToCartWorkflow.hooks.validate(
3531 async ({ input }, { container }) => {
3532 const items = input.items
3533 const query = container.resolve(
3534 ContainerRegistrationKeys.QUERY
3535 )
3536
3537 // Get the product variant to check if it's a ticket product variant
3538 const { data: productVariants } = await query.graph({
3539 entity: "product_variant",
3540 fields: ["id", "product_id", "ticket_product_variant.purchases.*"],
3541 filters: {
3542 id: items.map((item) => item.variant_id).filter(Boolean) as string[],
3543 },
3544 })
3545
3546 // Get existing cart items to check for conflicts
3547 const { data: [cart] } = await query.graph({
3548 entity: "cart",
3549 fields: ["items.*"],
3550 filters: {
3551 id: input.cart_id,
3552 },
3553 }, {
3554 throwIfKeyNotFound: true,
3555 })
3556
3557 // Check each item being added to cart
3558 for (const item of items) {
3559 if (item.quantity !== 1) {
3560 throw new MedusaError(
3561 MedusaError.Types.INVALID_DATA,
3562 "You can only purchase one ticket for a seat."
3563 )
3564 }
3565 const productVariant = productVariants.find(
3566 (variant) => variant.id === item.variant_id
3567 )
3568
3569 if (!productVariant || !item.metadata?.seat_number) {continue}
3570
3571 if (!item.metadata?.show_date) {
3572 throw new MedusaError(
3573 MedusaError.Types.INVALID_DATA,
3574 `Show date is required for seat ${item.metadata?.seat_number} in product ${productVariant.product_id}`
3575 )
3576 }
3577
3578 // Check if seat has already been purchased
3579 const existingPurchase = productVariant.ticket_product_variant?.purchases.find(
3580 (purchase) => purchase?.seat_number === item.metadata?.seat_number
3581 && purchase?.show_date === item.metadata?.show_date
3582 )
3583
3584 if (existingPurchase) {
3585 throw new MedusaError(
3586 MedusaError.Types.INVALID_DATA,
3587 `Seat ${item.metadata?.seat_number} has already been purchased for show date ${item.metadata?.show_date}`
3588 )
3589 }
3590
3591 // Check if seat is already in the cart
3592 const existingCartItem = cart.items.find(
3593 (cartItem) => cartItem?.metadata?.seat_number === item.metadata?.seat_number
3594 && cartItem?.metadata?.show_date === item.metadata?.show_date
3595 )
3596
3597 if (existingCartItem) {
3598 throw new MedusaError(
3599 MedusaError.Types.INVALID_DATA,
3600 `Seat ${item.metadata?.seat_number} is already in your cart for show date ${item.metadata?.show_date}`
3601 )
3602 }
3603 }
3604 }
3605 )
3606 ```
3607
3608 You consume the hook by calling `addToCartWorkflow.hooks.validate`, passing it a step function.
3609
3610 In the step function, you:
3611
3612 - Retrieve the product variants being added to the cart with their associated ticket product variant purchases.
3613 - Retrieve the existing cart items to check for conflicts.
3614 - Throw an error if:
3615 - The quantity of any item being added is more than 1 (you can only purchase one ticket for a seat).
3616 - The show date is missing in the item metadata.
3617 - The seat has already been purchased for the same show date.
3618 - The seat is already in the cart for the same show date.
3619
3620 If the hook throws an error, the add-to-cart operation will be aborted and the error message will be returned to the client.
3621
3622 You can test out the hook when you [customize the storefront](./storefront/page.mdx).
3623
3624 ---
3625
3626 ## Step 11: Custom Complete Cart
3627
3628 In this step, you'll create a custom complete cart workflow that wraps the default `completeCartWorkflow` to add logic that creates ticket purchases for each ticket product variant in the cart. Then, you'll execute that workflow in a custom API route.
3629
3630 ### a. Custom Complete Cart Workflow
3631
3632 The custom workflow that completes the cart has the following steps:
3633
3634 <WorkflowDiagram
3635 workflow={{
3636 name: "completeCartWithTicketsWorkflow",
3637 steps: [
3638 {
3639 type: "step",
3640 name: "acquireLockStep",
3641 description: "Acquire a lock on the cart to prevent concurrent modifications",
3642 link: "/references/medusa-workflows/steps/acquireLockStep",
3643 depth: 1,
3644 },
3645 {
3646 type: "workflow",
3647 name: "completeCartWorkflow",
3648 description: "Complete the cart using Medusa's default completeCartWorkflow",
3649 depth: 2,
3650 link: "/references/medusa-workflows/completeCartWorkflow"
3651 },
3652 {
3653 type: "step",
3654 name: "useQueryGraphStep",
3655 description: "Retrieve the cart details",
3656 depth: 3,
3657 link: "/references/helper-steps/useQueryGraphStep"
3658 },
3659 {
3660 type: "step",
3661 name: "useQueryGraphStep",
3662 description: "Retrieve existing ticket purchases to ensure idempotency",
3663 depth: 4,
3664 link: "/references/helper-steps/useQueryGraphStep"
3665 },
3666 {
3667 type: "when",
3668 condition: "existingLinks.length === 0",
3669 steps: [
3670 {
3671 type: "step",
3672 name: "validateTicketOrderStep",
3673 description: "Validate that the ticket order can be processed",
3674 depth: 1,
3675 },
3676 {
3677 type: "step",
3678 name: "createTicketPurchasesStep",
3679 description: "Create ticket purchases for each ticket product variant in the cart",
3680 depth: 2,
3681 },
3682 {
3683 type: "step",
3684 name: "createRemoteLinkStep",
3685 description: "Create links between the order and ticket purchases",
3686 depth: 3,
3687 link: "/references/helper-steps/createRemoteLinkStep"
3688 },
3689 ],
3690 depth: 5
3691 },
3692 {
3693 type: "step",
3694 name: "useQueryGraphStep",
3695 description: "Retrieve the order details",
3696 depth: 6,
3697 link: "/references/helper-steps/useQueryGraphStep"
3698 },
3699 {
3700 type: "step",
3701 name: "releaseLockStep",
3702 description: "Release the lock on the cart",
3703 depth: 7,
3704 link: "/references/medusa-workflows/steps/releaseLockStep"
3705 }
3706 ]
3707 }}
3708 hideLegend
3709 />
3710
3711 You only need to implement the `createTicketPurchasesStep` and `validateTicketOrderStep` steps, as the other steps and workflows are provided by Medusa.
3712
3713 #### createTicketPurchasesStep
3714
3715 The `createTicketPurchasesStep` creates ticket purchases for each ticket product variant in a cart.
3716
3717 To create the step, create the file `src/workflows/steps/create-ticket-purchases.ts` with the following content:
3718
3719 ```ts title="src/workflows/steps/create-ticket-purchases.ts" collapsibleLines="1-10" expandButtonLabel="Show Imports"
3720 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
3721 import {
3722 CartDTO,
3723 CartLineItemDTO,
3724 ProductVariantDTO,
3725 InferTypeOf,
3726 } from "@medusajs/framework/types"
3727 import { TICKET_BOOKING_MODULE } from "../../modules/ticket-booking"
3728 import TicketProductVariant from "../../modules/ticket-booking/models/ticket-product-variant"
3729
3730 export type CreateTicketPurchasesStepInput = {
3731 order_id: string
3732 cart: CartDTO & {
3733 items: CartLineItemDTO & {
3734 variant?: ProductVariantDTO & {
3735 ticket_product_variant?: InferTypeOf<typeof TicketProductVariant>
3736 }
3737 }[]
3738 }
3739 }
3740
3741 export const createTicketPurchasesStep = createStep(
3742 "create-ticket-purchases",
3743 async (input: CreateTicketPurchasesStepInput, { container }) => {
3744 const { order_id, cart } = input
3745 const ticketBookingModuleService = container.resolve(TICKET_BOOKING_MODULE)
3746
3747 const ticketPurchasesToCreate: {
3748 order_id: string
3749 ticket_product_id: string
3750 ticket_variant_id: string
3751 venue_row_id: string
3752 seat_number: string
3753 show_date: Date
3754 }[] = []
3755
3756 // Process each item in the cart
3757 for (const item of cart.items) {
3758 if (
3759 !item?.variant?.ticket_product_variant ||
3760 !item?.metadata?.venue_row_id ||
3761 !item?.metadata?.seat_number
3762 ) {continue}
3763
3764 ticketPurchasesToCreate.push({
3765 order_id,
3766 ticket_product_id: item.variant.ticket_product_variant.ticket_product_id,
3767 ticket_variant_id: item.variant.ticket_product_variant.id,
3768 venue_row_id: item?.metadata.venue_row_id as string,
3769 seat_number: item?.metadata.seat_number as string,
3770 show_date: new Date(
3771 item?.variant.options.find(
3772 (option: any) => option.option.title === "Date"
3773 )?.value as string
3774 ),
3775 })
3776 }
3777
3778 const ticketPurchases = await ticketBookingModuleService.createTicketPurchases(
3779 ticketPurchasesToCreate
3780 )
3781
3782 return new StepResponse(
3783 ticketPurchases,
3784 ticketPurchases
3785 )
3786 },
3787 async (ticketPurchases, { container }) => {
3788 if (!ticketPurchases) {return}
3789
3790 const ticketBookingModuleService = container.resolve(TICKET_BOOKING_MODULE)
3791
3792 // Delete the created ticket purchases
3793 await ticketBookingModuleService.deleteTicketPurchases(
3794 ticketPurchases.map((ticketPurchase) => ticketPurchase.id)
3795 )
3796 }
3797 )
3798 ```
3799
3800 The `createTicketPurchasesStep` accepts the cart and order ID as input.
3801
3802 In the step function, you prepare the ticket purchases to be created, create the ticket purchases, and return them.
3803
3804 In the compensation function, you delete the created ticket purchases if an error occurs in the workflow.
3805
3806 #### validateTicketOrderStep
3807
3808 The `validateTicketOrderStep` validates that the tickets can be purchased based on their availability.
3809
3810 To create the step, create the file `src/workflows/steps/validate-ticket-order.ts` with the following content:
3811
3812 ```ts title="src/workflows/steps/validate-ticket-order.ts"
3813 import { MedusaError } from "@medusajs/framework/utils"
3814 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
3815 import { cancelOrderWorkflow } from "@medusajs/medusa/core-flows"
3816
3817 export type ValidateTicketOrderStepInput = {
3818 items: {
3819 id: string
3820 variant_id: string
3821 metadata: Record<string, unknown>
3822 quantity: number
3823 variant?: {
3824 id: string
3825 product_id: string
3826 ticket_product_variant?: {
3827 purchases?: {
3828 seat_number: string
3829 show_date: Date
3830 }[]
3831 }
3832 }
3833 }[]
3834 order_id: string
3835 }
3836
3837 export const validateTicketOrderStep = createStep(
3838 "validate-ticket-order",
3839 async ({ items, order_id }: ValidateTicketOrderStepInput, { container }) => {
3840 // Check for duplicate seats within the cart
3841 const seatDateCombinations = new Set<string>()
3842
3843 for (const item of items) {
3844 if (item.quantity !== 1) {
3845 throw new MedusaError(
3846 MedusaError.Types.INVALID_DATA,
3847 "You can only purchase one ticket for a seat."
3848 )
3849 }
3850
3851 if (!item.variant || !item.metadata?.seat_number) {continue}
3852
3853 if (!item.metadata?.show_date) {
3854 throw new MedusaError(
3855 MedusaError.Types.INVALID_DATA,
3856 `Show date is required for seat ${item.metadata?.seat_number} in product ${item.variant.product_id}`
3857 )
3858 }
3859
3860 // Create a unique key for seat and date combination
3861 const seatDateKey = `${item.metadata?.seat_number}-${item.metadata?.show_date}`
3862
3863 // Check if this seat-date combination already exists in the cart
3864 if (seatDateCombinations.has(seatDateKey)) {
3865 throw new MedusaError(
3866 MedusaError.Types.INVALID_DATA,
3867 `Duplicate seat ${item.metadata?.seat_number} found for show date ${item.metadata?.show_date} in cart`
3868 )
3869 }
3870
3871 // Add to the set to track this combination
3872 seatDateCombinations.add(seatDateKey)
3873
3874 // Check if seat has already been purchased
3875 const existingPurchase = item.variant.ticket_product_variant?.purchases?.find(
3876 (purchase) => purchase?.seat_number === item.metadata?.seat_number
3877 && purchase?.show_date === item.metadata?.show_date
3878 )
3879
3880 if (existingPurchase) {
3881 throw new MedusaError(
3882 MedusaError.Types.INVALID_DATA,
3883 `Seat ${item.metadata?.seat_number} has already been purchased for show date ${item.metadata?.show_date}`
3884 )
3885 }
3886 }
3887
3888 return new StepResponse({ validated: true }, order_id)
3889 },
3890 async (order_id, { container, context }) => {
3891 if (!order_id) {return}
3892
3893 cancelOrderWorkflow(container).run({
3894 input: {
3895 order_id,
3896 },
3897 context,
3898 container,
3899 })
3900 }
3901 )
3902 ```
3903
3904 The `validateTicketOrderStep` accepts the cart items and order ID as input.
3905
3906 In the step function, you validate that:
3907
3908 1. No seat is purchased more than once for the same date within the cart.
3909 2. No seat has already been purchased for the same date.
3910
3911 If any validation fails, you throw an error to abort the workflow.
3912
3913 The step also has a compensation function that cancels the order if an error occurs later in the workflow. This is important to ensure that if ticket purchase creation fails, the order is not left in a completed state.
3914
3915 #### Custom Complete Cart Workflow
3916
3917 You can now create the custom workflow that completes the cart and creates ticket purchases.
3918
3919 Create the file `src/workflows/complete-cart-with-tickets.ts` with the following content:
3920
3921 ```ts title="src/workflows/complete-cart-with-tickets.ts" collapsibleLines="1-14" expandButtonLabel="Show Imports"
3922 import { createWorkflow, transform, when, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
3923 import {
3924 completeCartWorkflow,
3925 createRemoteLinkStep,
3926 acquireLockStep,
3927 releaseLockStep,
3928 useQueryGraphStep,
3929 } from "@medusajs/medusa/core-flows"
3930 import { createTicketPurchasesStep, CreateTicketPurchasesStepInput } from "./steps/create-ticket-purchases"
3931 import { TICKET_BOOKING_MODULE } from "../modules/ticket-booking"
3932 import { Modules } from "@medusajs/framework/utils"
3933 import ticketPurchaseOrderLink from "../links/ticket-purchase-order"
3934 import { validateTicketOrderStep, ValidateTicketOrderStepInput } from "./steps/validate-ticket-order"
3935
3936 export type CompleteCartWithTicketsWorkflowInput = {
3937 cart_id: string
3938 }
3939
3940 export const completeCartWithTicketsWorkflow = createWorkflow(
3941 "complete-cart-with-tickets",
3942 (input: CompleteCartWithTicketsWorkflowInput) => {
3943 acquireLockStep({
3944 key: input.cart_id,
3945 timeout: 2,
3946 ttl: 10,
3947 })
3948 const order = completeCartWorkflow.runAsStep({
3949 input: {
3950 id: input.cart_id,
3951 },
3952 })
3953
3954 const { data: carts } = useQueryGraphStep({
3955 entity: "cart",
3956 fields: [
3957 "id",
3958 "items.variant.*",
3959 "items.variant.options.*",
3960 "items.variant.options.option.*",
3961 "items.variant.ticket_product_variant.*",
3962 "items.variant.ticket_product_variant.ticket_product.*",
3963 "items.variant.ticket_product_variant.purchases.*",
3964 "items.metadata",
3965 "items.quantity",
3966 ],
3967 filters: {
3968 id: input.cart_id,
3969 },
3970 options: {
3971 throwIfKeyNotFound: true,
3972 },
3973 })
3974
3975 const { data: existingLinks } = useQueryGraphStep({
3976 entity: ticketPurchaseOrderLink.entryPoint,
3977 fields: ["ticket_purchase.id"],
3978 filters: { order_id: order.id },
3979 }).config({ name: "retrieve-existing-links" })
3980
3981 when({ existingLinks }, (data) => data.existingLinks.length === 0)
3982 .then(() => {
3983 validateTicketOrderStep({
3984 items: carts[0].items,
3985 order_id: order.id,
3986 } as unknown as ValidateTicketOrderStepInput)
3987 const ticketPurchases = createTicketPurchasesStep({
3988 order_id: order.id,
3989 cart: carts[0],
3990 } as unknown as CreateTicketPurchasesStepInput)
3991
3992 const linkData = transform({
3993 order,
3994 ticketPurchases,
3995 }, (data) => {
3996 return data.ticketPurchases.map((purchase) => ({
3997 [TICKET_BOOKING_MODULE]: {
3998 ticket_purchase_id: purchase.id,
3999 },
4000 [Modules.ORDER]: {
4001 order_id: data.order.id,
4002 },
4003 }))
4004 })
4005
4006 createRemoteLinkStep(linkData)
4007 })
4008
4009 const { data: refetchedOrder } = useQueryGraphStep({
4010 entity: "order",
4011 fields: [
4012 "id",
4013 "currency_code",
4014 "email",
4015 "customer.*",
4016 "billing_address.*",
4017 "payment_collections.*",
4018 "items.*",
4019 "total",
4020 "subtotal",
4021 "tax_total",
4022 "shipping_total",
4023 "discount_total",
4024 "created_at",
4025 "updated_at",
4026 ],
4027 filters: {
4028 id: order.id,
4029 },
4030 }).config({ name: "refetch-order" })
4031
4032 releaseLockStep({
4033 key: input.cart_id,
4034 })
4035
4036 return new WorkflowResponse({
4037 order: refetchedOrder[0],
4038 })
4039 }
4040 )
4041 ```
4042
4043 The `completeCartWithTicketsWorkflow` accepts the cart ID as input.
4044
4045 In the workflow function, you:
4046
4047 1. Acquire a lock on the cart to prevent concurrent modifications using the `acquireLockStep`.
4048 2. Complete the cart using Medusa's `completeCartWorkflow`.
4049 3. Retrieve the cart details using the `useQueryGraphStep`.
4050 4. Retrieve existing ticket purchases linked to the order to ensure idempotency using the `useQueryGraphStep`.
4051 - This is important because if the workflow is retried, you don't want to create duplicate ticket purchases.
4052 5. Use `when` to check that there are no existing links between the order and ticket purchases. If so, you:
4053 1. Validate that the ticket order can be processed using the `validateTicketOrderStep`.
4054 2. Create ticket purchases for each ticket product variant in the cart using the `createTicketPurchasesStep`.
4055 3. Create links between the order and the created ticket purchases using the `createRemoteLinkStep`.
4056 6. Retrieve the order details using the `useQueryGraphStep`.
4057 7. Release the lock on the cart using the `releaseLockStep`.
4058
4059 Finally, you return the order details.
4060
4061 ### b. Custom Complete Cart API Route
4062
4063 Next, you'll create a custom API route that executes the `completeCartWithTicketsWorkflow` to complete the cart and create ticket purchases.
4064
4065 Create the file `src/api/store/carts/[id]/complete-tickets/route.ts` with the following content:
4066
4067 ```ts title="src/api/store/carts/[id]/complete-tickets/route.ts"
4068 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
4069 import { completeCartWithTicketsWorkflow } from "../../../../../workflows/complete-cart-with-tickets"
4070
4071 export async function POST(
4072 req: MedusaRequest,
4073 res: MedusaResponse
4074 ) {
4075 const { result } = await completeCartWithTicketsWorkflow(req.scope).run({
4076 input: {
4077 cart_id: req.params.id,
4078 },
4079 })
4080
4081 res.json({
4082 type: "order",
4083 order: result.order,
4084 })
4085 }
4086 ```
4087
4088 Since you export a `POST` route handler function, you expose a `POST` API route at `/store/carts/{id}/complete-tickets`.
4089
4090 In the route handler, you execute the `completeCartWithTicketsWorkflow` and return the created order in the response.
4091
4092 You'll test out this API route when you [customize the storefront](./storefront/page.mdx#update-cart-functions).
4093
4094 ---
4095
4096 ## Step 12: Storefront API Routes
4097
4098 To [customize the storefront](./storefront/page.mdx) in the next part, you need two API routes that the storefront will consume:
4099
4100 1. An API route to fetch the available dates for a ticket product.
4101 2. An API route to fetch the seating layout for a venue, including details on which seats are already booked for a specific date.
4102
4103 You'll test these API routes when you customize the storefront.
4104
4105 ### a. Available Dates API Route
4106
4107 The first API route you'll create fetches the available dates for a ticket product.
4108
4109 Create the file `src/api/store/ticket-products/[id]/availability/route.ts` with the following content:
4110
4111 ```ts title="src/api/store/ticket-products/[id]/availability/route.ts"
4112 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
4113 import {
4114 MedusaError,
4115 ContainerRegistrationKeys,
4116 } from "@medusajs/framework/utils"
4117
4118 export const GET = async (req: MedusaRequest, res: MedusaResponse) => {
4119 const { id } = req.params
4120 const query = req.scope.resolve(
4121 ContainerRegistrationKeys.QUERY
4122 )
4123
4124 const { data: [ticketProduct] } = await query.graph({
4125 entity: "ticket_product",
4126 fields: [
4127 "id",
4128 "product_id",
4129 "dates",
4130 "venue.*",
4131 "venue.rows.*",
4132 "variants.*",
4133 "variants.product_variant.*",
4134 "variants.product_variant.options.*",
4135 "variants.product_variant.options.option.*",
4136 "variants.product_variant.ticket_product_variant.*",
4137 "variants.product_variant.ticket_product_variant.purchases.*",
4138 ],
4139 filters: {
4140 product_id: id,
4141 },
4142 })
4143
4144 if (!ticketProduct) {
4145 throw new MedusaError(MedusaError.Types.NOT_FOUND, "Ticket product not found")
4146 }
4147
4148 // Calculate availability for each date and row type
4149 const availability = ticketProduct.dates.map((date: string) => {
4150 // Group rows by row_type to get total seats per row type
4151 const rowTypeGroups = ticketProduct.venue.rows.reduce((groups: any, row: any) => {
4152 if (!groups[row.row_type]) {
4153 groups[row.row_type] = {
4154 row_type: row.row_type,
4155 total_seats: 0,
4156 rows: [],
4157 }
4158 }
4159 groups[row.row_type].total_seats += row.seat_count
4160 groups[row.row_type].rows.push(row)
4161 return groups
4162 }, {})
4163
4164 const dateAvailability = {
4165 date,
4166 row_types: Object.values(rowTypeGroups).map((group: any) => {
4167 // Find the variant for this date and row type
4168 const variant = ticketProduct.variants.find((v: any) => {
4169 const variantDate = v.product_variant.options.find((opt: any) =>
4170 opt.option?.title === "Date"
4171 )?.value
4172 const variantRowType = v.product_variant.options.find((opt: any) =>
4173 opt.option?.title === "Row Type"
4174 )?.value
4175
4176 return variantDate === date && variantRowType === group.row_type
4177 })
4178
4179 if (!variant) {
4180 return {
4181 row_type: group.row_type,
4182 total_seats: group.totalSeats,
4183 available_seats: 0,
4184 soldOut: true,
4185 }
4186 }
4187
4188 // Count purchased seats for this variant
4189 const purchasedSeats = variant.product_variant?.ticket_product_variant?.purchases?.length || 0
4190 const availableSeats = Math.max(0, group.total_seats - purchasedSeats)
4191 const soldOut = availableSeats === 0
4192
4193 return {
4194 row_type: group.row_type,
4195 total_seats: group.total_seats,
4196 available_seats: availableSeats,
4197 sold_out: soldOut,
4198 }
4199 }),
4200 }
4201
4202 // Check if the entire date is sold out
4203 const totalAvailableSeats = dateAvailability.row_types.reduce(
4204 (sum, rowType) => sum + rowType.available_seats, 0
4205 )
4206 const dateSoldOut = totalAvailableSeats === 0
4207
4208 return {
4209 ...dateAvailability,
4210 sold_out: dateSoldOut,
4211 }
4212 })
4213
4214 return res.json({
4215 ticket_product: ticketProduct,
4216 availability,
4217 })
4218 }
4219 ```
4220
4221 You expose a `GET` API route at `/store/ticket-products/{id}/availability`.
4222
4223 In the route handler, you:
4224
4225 1. Retrieve the ticket product by its associated Medusa product ID, including its dates, venue, variants, and purchases.
4226 2. For each show date, you group the venue rows by `row_type` to calculate the total seats per row type.
4227 3. For each row type, you find the corresponding variant for the date and row type, count the purchased seats, and calculate the available seats.
4228 4. You also determine if a row type or an entire date is sold out.
4229 5. Finally, you return the ticket product and its availability in the response.
4230
4231 ### b. Seating Layout API Route
4232
4233 The second API route you'll create fetches the seating layout for a venue, including details on which seats are already booked for a specific date.
4234
4235 Create the file `src/api/store/ticket-products/[id]/seats/route.ts` with the following content:
4236
4237 ```ts title="src/api/store/ticket-products/[id]/seats/route.ts"
4238 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
4239 import {
4240 MedusaError,
4241 ContainerRegistrationKeys,
4242 } from "@medusajs/framework/utils"
4243 import { z } from "@medusajs/framework/zod"
4244
4245 export const GetTicketProductSeatsSchema = z.object({
4246 date: z.string(),
4247 })
4248
4249 export const GET = async (req: MedusaRequest, res: MedusaResponse) => {
4250 const { id } = req.params
4251 const { date } = req.validatedQuery
4252 const query = req.scope.resolve(
4253 ContainerRegistrationKeys.QUERY
4254 )
4255
4256 const { data: [ticketProduct] } = await query.graph({
4257 entity: "ticket_product",
4258 fields: [
4259 "id",
4260 "product_id",
4261 "venue.*",
4262 "venue.rows.*",
4263 "variants.*",
4264 "variants.product_variant.*",
4265 "variants.product_variant.options.*",
4266 "variants.product_variant.options.option.*",
4267 "variants.product_variant.ticket_product_variant.*",
4268 "variants.product_variant.ticket_product_variant.purchases.*",
4269 ],
4270 filters: {
4271 product_id: id,
4272 },
4273 })
4274
4275 if (!ticketProduct) {
4276 throw new MedusaError(MedusaError.Types.NOT_FOUND, "Ticket product not found")
4277 }
4278
4279 // Build seat map for the specified date
4280 const seatMap = ticketProduct.venue.rows.map((row: any) => {
4281 // Find the variant for this date and row type
4282 const variant = ticketProduct.variants.find((v: any) => {
4283 const variantDate = v.product_variant.options.find((opt: any) =>
4284 opt.option?.title === "Date"
4285 )?.value
4286 const variantRowType = v.product_variant.options.find((opt: any) =>
4287 opt.option?.title === "Row Type"
4288 )?.value
4289
4290 return variantDate === date && variantRowType === row.row_type
4291 })
4292
4293 // Get purchased seats for this variant
4294 const purchasedSeats = variant?.product_variant?.ticket_product_variant?.purchases?.map(
4295 (purchase) => purchase?.seat_number
4296 ).filter(Boolean) || []
4297
4298 // Generate seat numbers for this row
4299 const seats = Array.from({ length: row.seat_count }, (_, index) => {
4300 const seatNumber = (index + 1).toString()
4301 const isPurchased = purchasedSeats.includes(seatNumber)
4302
4303 return {
4304 number: seatNumber,
4305 is_purchased: isPurchased,
4306 variant_id: variant?.product_variant?.id || null,
4307 }
4308 })
4309
4310 return {
4311 row_number: row.row_number,
4312 row_type: row.row_type,
4313 seats,
4314 }
4315 })
4316
4317 return res.json({
4318 venue: ticketProduct.venue,
4319 date,
4320 seat_map: seatMap,
4321 })
4322 }
4323 ```
4324
4325 You expose a `GET` API route at `/store/ticket-products/{id}/seats`. You also define a Zod schema to validate the `date` query parameter.
4326
4327 In the route handler, you:
4328
4329 1. Retrieve the ticket product by its associated Medusa product ID, including its venue, rows, variants, and purchases.
4330 2. For each venue row, you find the corresponding variant for the specified date and row type.
4331 3. You get the purchased seats for that variant and generate a list of seats for the row, marking which seats are already purchased.
4332 4. Finally, you return the venue details, the specified date, and the seat map in the response.
4333
4334 You also need to apply a middleware to validate the query parameters using the Zod schema you defined. So, in `src/api/middlewares.ts`, add the following import at the top of the file:
4335
4336 ```ts title="src/api/middlewares.ts"
4337 import { GetTicketProductSeatsSchema } from "./store/ticket-products/[id]/seats/route"
4338 ```
4339
4340 Then, pass a new object to the `routes` array passed to the `defineMiddlewares` function:
4341
4342 ```ts title="src/api/middlewares.ts"
4343 export default defineMiddlewares({
4344 routes: [
4345 // ...
4346 {
4347 matcher: "/store/ticket-products/:id/seats",
4348 methods: ["GET"],
4349 middlewares: [validateAndTransformQuery(GetTicketProductSeatsSchema, {})],
4350 },
4351 ],
4352 })
4353 ```
4354
4355 You apply the `validateAndTransformQuery` middleware to the `/store/ticket-products/:id/seats` route for `GET` requests. You pass the `GetTicketProductSeatsSchema` to validate the query parameters.
4356
4357 ---
4358
4359 ## Step 13: Send Order Confirmation Email with Tickets
4360
4361 The last step is to send order confirmation emails to customers with their tickets as QR codes.
4362
4363 To send an email in Medusa when an order is placed, you'll need:
4364
4365 - A [Notification Module Provider](../../../infrastructure-modules/notification/page.mdx) to handle sending emails. For example, [SendGrid](../../../infrastructure-modules/notification/sendgrid/page.mdx) or [Resend](../../../integrations/guides/resend/page.mdx).
4366 - You also need to define an email template for the order confirmation email in the provider.
4367 - A method in the Ticket Booking Module's service that generates the ticket QR codes.
4368 - A [Subscriber](!docs!/learn/fundamentals/events-and-subscribers) that listens to the `order.placed` event and sends an email with the order details.
4369 - A workflow and API route to handle verifying scanned QR codes at the event entrance.
4370
4371 ### a. Set Up Notification Module
4372
4373 First, set up a Notification Module Provider in your Medusa application.
4374
4375 For example, to set up the SendGrid Notification Module Provider, add it to `medusa-config.ts`:
4376
4377 ```ts title="medusa-config.ts"
4378 module.exports = defineConfig({
4379 // ...
4380 modules: [
4381 // ...
4382 {
4383 resolve: "@medusajs/medusa/notification",
4384 options: {
4385 providers: [
4386 {
4387 resolve: "@medusajs/medusa/notification-sendgrid",
4388 id: "sendgrid",
4389 options: {
4390 channels: ["email"],
4391 api_key: process.env.SENDGRID_API_KEY,
4392 from: process.env.SENDGRID_FROM,
4393 },
4394 },
4395 ],
4396 },
4397 },
4398 ],
4399 })
4400 ```
4401
4402 Make sure to set the `SENDGRID_API_KEY` and `SENDGRID_FROM` environment variables in your `.env` file, as explained in the [SendGrid Notification Module Provider guide](../../../infrastructure-modules/notification/sendgrid/page.mdx).
4403
4404 You also need to define an email template for the order confirmation email in SendGrid. The following is a dynamic template you can use:
4405
4406 ```html
4407 <!doctype html>
4408 <html lang="en" style="margin:0;padding:0;">
4409 <head>
4410 <meta charset="utf-8" />
4411 <meta name="viewport" content="width=device-width, initial-scale=1" />
4412 <title>Order Confirmation – {{brand_name}}</title>
4413 <style>
4414 /* Dark mode friendly neutrals, safe for most clients */
4415 :root { color-scheme: light dark; supported-color-schemes: light dark; }
4416 body { margin:0; padding:0; background:#f6f7f9; -webkit-text-size-adjust:100%; }
4417 .wrapper { width:100%; table-layout:fixed; background:#f6f7f9; padding:24px 0; }
4418 .container { margin:0 auto; width:100%; max-width:640px; background:#ffffff; border-radius:12px; overflow:hidden; }
4419 .header { padding:24px; text-align:left; background:#0e1116; color:#ffffff; }
4420 .brand { font: 600 20px/1.2 system-ui, -apple-system, Segoe UI, Roboto, "Helvetica Neue", Arial, sans-serif; }
4421 .content { padding:24px; color:#0e1116; font: 400 16px/1.5 system-ui, -apple-system, Segoe UI, Roboto, "Helvetica Neue", Arial, sans-serif; }
4422 .muted { color:#6b7280; font-size:14px; }
4423 .section-title { font-weight:600; margin:24px 0 8px; }
4424 .card { border:1px solid #e5e7eb; border-radius:12px; padding:16px; }
4425 .divider { height:1px; background:#e5e7eb; margin:24px 0; }
4426 .btn {
4427 display:inline-block; text-decoration:none; background:#0e1116; color:#ffffff !important;
4428 padding:12px 18px; border-radius:10px; font-weight:600;
4429 }
4430 /* QR grid */
4431 .qr-grid { display:grid; grid-template-columns: repeat(2, 1fr); gap:16px; }
4432 @media (max-width:480px) { .qr-grid { grid-template-columns: 1fr; } }
4433 .qr-item { border:1px solid #e5e7eb; border-radius:10px; padding:14px; text-align:center; }
4434 .qr-item img { display:block; margin:0 auto 10px; width:220px; height:220px; object-fit:contain; }
4435 .qr-label { font-weight:600; margin-bottom:2px; }
4436 .qr-meta { font-size:13px; color:#6b7280; }
4437 .ticket-note { font-size:13px; color:#374151; margin-top:8px; }
4438 /* Small print */
4439 .footer { padding:18px 24px 28px; text-align:center; color:#6b7280; font-size:12px; }
4440 .nowrap { white-space:nowrap; }
4441 a { color:#0e63ff; }
4442 </style>
4443 </head>
4444 <body>
4445 <table role="presentation" class="wrapper" cellpadding="0" cellspacing="0" width="100%">
4446 <tr>
4447 <td align="center">
4448 <table role="presentation" class="container" cellpadding="0" cellspacing="0" width="100%">
4449 <!-- Header -->
4450 <tr>
4451 <td class="header">
4452 <div class="brand">Medusa</div>
4453 </td>
4454 </tr>
4455
4456 <!-- Greeting & Summary -->
4457 <tr>
4458 <td class="content">
4459 <p>Hi {{customer.first_name}},</p>
4460 <p>Thanks for your order! Your tickets for <strong>{{show.name}}</strong> are confirmed.</p>
4461
4462 <div class="card">
4463 <div><strong>Order #:</strong> {{order.display_id}}</div>
4464 <div><strong>Date:</strong> {{order.created_at}}</div>
4465 {{#if order.email}}
4466 <div><strong>Sent to:</strong> {{order.email}}</div>
4467 {{/if}}
4468 {{#if show.date}}
4469 <div><strong>Event:</strong> {{show.date}}</div>
4470 {{/if}}
4471 {{#if show.venue}}
4472 <div><strong>Venue:</strong> {{show.venue}}</div>
4473 {{/if}}
4474 </div>
4475
4476 <div class="divider"></div>
4477
4478 <!-- QR Codes -->
4479 <h3 class="section-title">Your Tickets (QR Codes)</h3>
4480 <p class="muted" style="margin-top:0;">Show each QR code at the entrance. Each QR admits one person unless noted otherwise.</p>
4481
4482 <div class="qr-grid">
4483 {{#each tickets}}
4484 <div class="qr-item">
4485 <!-- `qr` can be a full https URL or a data URI (e.g. data:image/png;base64,...) -->
4486 <img src="{{this.qr}}" alt="QR code for {{this.label}}" width="220" height="220" />
4487 <div class="qr-label">{{this.label}}</div>
4488 {{#if this.seat}}
4489 <div class="qr-meta">Seat: {{this.seat}}</div>
4490 {{/if}}
4491 {{#if this.row}}
4492 <div class="qr-meta">Row: {{this.row}}</div>
4493 {{/if}}
4494 </div>
4495 {{/each}}
4496 </div>
4497
4498 <p class="muted" style="margin-top:18px;">Please arrive at least 15 minutes before showtime and have your tickets ready.</p>
4499
4500 <div class="divider"></div>
4501
4502 <!-- Billing snippet -->
4503 <h3 class="section-title">Billing</h3>
4504 <div class="card">
4505 {{#if billing_address}}
4506 <div><strong>Billing address</strong><br/>
4507 {{billing_address.first_name}} {{billing_address.last_name}}<br/>
4508 {{billing_address.address_1}}{{#if billing_address.address_2}}, {{billing_address.address_2}}{{/if}}<br/>
4509 {{billing_address.city}}, {{billing_address.province}} {{billing_address.postal_code}}<br/>
4510 {{billing_address.country_code}}
4511 </div>
4512 {{/if}}
4513 </div>
4514
4515 <p style="margin-top:24px;">Enjoy the show!</p>
4516 </td>
4517 </tr>
4518 </table>
4519 </td>
4520 </tr>
4521 </table>
4522 </body>
4523 </html>
4524 ```
4525
4526 You can customize the template to fit your brand and requirements. If you change any variable names or add new variables, make sure to update the code in the next sections accordingly.
4527
4528 ### b. Generate Ticket QR Codes
4529
4530 Next, you'll add a method in the Ticket Booking Module's service that generates the ticket QR codes.
4531
4532 Start by installing the `qrcode` package in your Medusa application with the following command:
4533
4534 ```bash npm2yarn
4535 npm install qrcode
4536 npm install --save-dev @types/qrcode
4537 ```
4538
4539 Then, in `src/modules/ticket-booking/service.ts`, add the following imports at the top of the file:
4540
4541 ```ts title="src/modules/ticket-booking/service.ts"
4542 import { promiseAll } from "@medusajs/framework/utils"
4543 import QRCode from "qrcode"
4544 ```
4545
4546 And add the following method to `TicketBookingModuleService`:
4547
4548 ```ts title="src/modules/ticket-booking/service.ts"
4549 export class TicketBookingModuleService extends MedusaService({
4550 Venue,
4551 VenueRow,
4552 TicketProduct,
4553 TicketProductVariant,
4554 TicketPurchase,
4555 }) {
4556 async generateTicketQRCodes(
4557 ticketPurchaseIds: string[]
4558 ): Promise<Record<string, string>> {
4559 const ticketPurchases = await this.listTicketPurchases({
4560 id: ticketPurchaseIds,
4561 })
4562 const qrCodeData: Record<string, string> = {}
4563
4564 await promiseAll(
4565 ticketPurchases.map(async (ticketPurchase) => {
4566 qrCodeData[ticketPurchase.id] = await QRCode.toDataURL(
4567 ticketPurchase.id
4568 )
4569 })
4570 )
4571
4572 return qrCodeData
4573 }
4574 }
4575 ```
4576
4577 The `generateTicketQRCodes` method takes an array of ticket purchase IDs. It retrieves the ticket purchases and generates a QR code for each ticket purchase using the `qrcode` package.
4578
4579 The QR code encodes the ticket purchase ID, which can be used later for verification at the event entrance.
4580
4581 ### c. Create Order Placed Subscriber
4582
4583 Next, you'll create a subscriber that listens to the `order.placed` event and sends an order confirmation email with the tickets.
4584
4585 A subscriber is an asynchronous function that is executed when its associated event is emitted.
4586
4587 To create a subscriber that sends a notification to the customer when an order is placed, create the file `src/subscribers/order-placed.ts` with the following content:
4588
4589 ```ts title="src/subscribers/order-placed.ts"
4590 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/medusa"
4591 import { TICKET_BOOKING_MODULE } from "../modules/ticket-booking"
4592 import {
4593 Modules,
4594 ContainerRegistrationKeys,
4595 } from "@medusajs/framework/utils"
4596
4597 export default async function handleOrderPlaced({
4598 event: { data },
4599 container,
4600 }: SubscriberArgs<{ id: string }>) {
4601 const query = container.resolve(
4602 ContainerRegistrationKeys.QUERY
4603 )
4604 const notificationModuleService = container.resolve(
4605 Modules.NOTIFICATION
4606 )
4607 const ticketBookingModuleService = container.resolve(TICKET_BOOKING_MODULE)
4608
4609 const { data: [order] } = await query.graph({
4610 entity: "order",
4611 fields: [
4612 "id",
4613 "email",
4614 "created_at",
4615 "items.*",
4616 "ticket_purchases.*",
4617 "ticket_purchases.ticket_product.*",
4618 "ticket_purchases.ticket_product.product.*",
4619 "ticket_purchases.ticket_product.venue.*",
4620 "ticket_purchases.venue_row.*",
4621 "customer.*",
4622 "billing_address.*",
4623 ],
4624 filters: {
4625 id: data.id,
4626 },
4627 })
4628
4629 const ticketPurchaseIds: string[] = order.ticket_purchases?.
4630 map((purchase) => purchase?.id).filter(Boolean) as string[] || []
4631
4632 const qrCodes = await ticketBookingModuleService.generateTicketQRCodes(
4633 ticketPurchaseIds
4634 )
4635 const firstTicketPurchase = order.ticket_purchases?.[0]
4636
4637 await notificationModuleService.createNotifications({
4638 to: order.email || "",
4639 channel: "feed",
4640 // TODO replace with a proper template
4641 template: "order.placed",
4642 data: {
4643 customer: {
4644 first_name: order.customer?.first_name ||
4645 order.billing_address?.first_name,
4646 last_name: order.customer?.last_name ||
4647 order.billing_address?.last_name,
4648 },
4649 order: {
4650 display_id: order.id,
4651 created_at: order.created_at,
4652 email: order.email,
4653 },
4654 show: {
4655 name: firstTicketPurchase?.ticket_product?.product?.title ||
4656 "Your Event",
4657 date: firstTicketPurchase?.show_date.toLocaleString(),
4658 venue: firstTicketPurchase?.ticket_product?.venue?.name ||
4659 "Venue Name",
4660 },
4661 tickets: order.ticket_purchases?.map((purchase) => ({
4662 label: purchase?.venue_row.row_type.toUpperCase(),
4663 seat: purchase?.seat_number,
4664 row: purchase?.venue_row.row_number,
4665 qr: qrCodes[purchase?.id || ""] || "",
4666 })),
4667 billing_address: order.billing_address,
4668 },
4669 })
4670 }
4671
4672 export const config: SubscriberConfig = {
4673 event: "order.placed",
4674 }
4675 ```
4676
4677 A subscriber file must export:
4678
4679 - An asynchronous function that is executed when its associated event is emitted.
4680 - An object that indicates the event that the subscriber is listening to.
4681
4682 The subscriber receives among its parameters the data payload of the emitted event, which includes the order ID.
4683
4684 In the subscriber, you:
4685
4686 - Retrieve the order details, including ticket purchases, customer information, and billing address.
4687 - Extract the ticket purchase IDs from the order.
4688 - Generate QR codes for the ticket purchases.
4689 - Use the Notification Module's service to send an email to the customer with the order details and tickets.
4690 - The `data` object contains the variables used in the email template you defined earlier.
4691 - Make sure to change the `template` property to match the template ID you created in your Notification Module Provider. For example, the ID of the dynamic template in SendGrid.
4692
4693 ### Test Order Confirmation Email
4694
4695 To test the order confirmation email, [customize the storefront](./storefront/page.mdx) first. Then, start the Medusa application and the Next.js Starter Storefront.
4696
4697 Place an order with at least one ticket product. After placing the order, you'll see the following message in your Medusa application's terminal:
4698
4699 ```bash
4700 info: Processing order.placed which has 1 subscribers
4701 ```
4702
4703 If no errors occur, you should receive an order confirmation email at the email address you used when placing the order. The email should contain the order details and the tickets with QR codes.
4704
4705 ### d. Verify Ticket QR Code Workflow
4706
4707 In this section, you'll implement functionality to verify QR codes, which is useful for checking tickets at event entrances.
4708
4709 To implement this functionality, you'll create a workflow and then execute it in an API route.
4710
4711 The workflow that verifies a ticket QR code has the following steps:
4712
4713 <WorkflowDiagram
4714 workflow={{
4715 name: "verifyTicketPurchaseWorkflow",
4716 steps: [
4717 {
4718 type: "step",
4719 name: "verifyTicketPurchaseStep",
4720 description: "Verifies a ticket purchase by its ID",
4721 depth: 1
4722 },
4723 {
4724 type: "step",
4725 name: "updateTicketPurchaseStatusStep",
4726 description: "Updates the status of a ticket purchase",
4727 depth: 1
4728 }
4729 ]
4730 }}
4731 hideLegend
4732 />
4733
4734 You need to implement both steps.
4735
4736 #### verifyTicketPurchaseStep
4737
4738 The `verifyTicketPurchaseStep` verifies that a ticket purchase is valid and has not been used yet.
4739
4740 To create the step, create the file `src/workflows/steps/verify-ticket-purchase-step.ts` with the following content:
4741
4742 ```ts title="src/workflows/steps/verify-ticket-purchase-step.ts"
4743 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
4744 import { TICKET_BOOKING_MODULE } from "../../modules/ticket-booking"
4745 import { MedusaError } from "@medusajs/framework/utils"
4746
4747 export type VerifyTicketPurchaseStepInput = {
4748 ticket_purchase_id: string
4749 }
4750
4751 export const verifyTicketPurchaseStep = createStep(
4752 "verify-ticket-purchase",
4753 async (input: VerifyTicketPurchaseStepInput, { container }) => {
4754 const ticketBookingService = container.resolve(TICKET_BOOKING_MODULE)
4755
4756 const ticketPurchase = await ticketBookingService.retrieveTicketPurchase(
4757 input.ticket_purchase_id
4758 )
4759
4760 if (ticketPurchase.status !== "pending") {
4761 throw new MedusaError(
4762 MedusaError.Types.NOT_ALLOWED,
4763 "Ticket has already been scanned"
4764 )
4765 }
4766
4767 if (ticketPurchase.show_date < new Date()) {
4768 throw new MedusaError(
4769 MedusaError.Types.NOT_ALLOWED,
4770 "Ticket is expired or show date has passed"
4771 )
4772 }
4773
4774 return new StepResponse(true)
4775 }
4776 )
4777 ```
4778
4779 The step takes the ticket purchase ID as input. In the step, you throw an error if the ticket has already been scanned or if the show date has passed.
4780
4781 #### updateTicketPurchaseStatusStep
4782
4783 The `updateTicketPurchaseStatusStep` updates the status of a ticket purchase.
4784
4785 To create the step, create the file `src/workflows/steps/update-ticket-purchase-status-step.ts` with the following content:
4786
4787 ```ts title="src/workflows/steps/update-ticket-purchase-status-step.ts"
4788 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
4789 import { TICKET_BOOKING_MODULE } from "../../modules/ticket-booking"
4790
4791 export type UpdateTicketPurchaseStatusStepInput = {
4792 ticket_purchase_id: string
4793 status: "pending" | "scanned"
4794 }
4795
4796 export const updateTicketPurchaseStatusStep = createStep(
4797 "update-ticket-purchase-status",
4798 async (input: UpdateTicketPurchaseStatusStepInput, { container }) => {
4799 const ticketBookingService = container.resolve(TICKET_BOOKING_MODULE)
4800
4801 const currentTicket = await ticketBookingService.retrieveTicketPurchase(
4802 input.ticket_purchase_id
4803 )
4804
4805 const updatedTicket = await ticketBookingService.updateTicketPurchases({
4806 id: input.ticket_purchase_id,
4807 status: input.status,
4808 })
4809
4810 return new StepResponse(updatedTicket, {
4811 id: input.ticket_purchase_id,
4812 previousStatus: currentTicket.status,
4813 })
4814 },
4815 async (compensationData, { container }) => {
4816 if (!compensationData) {return}
4817
4818 const ticketBookingService = container.resolve(TICKET_BOOKING_MODULE)
4819 await ticketBookingService.updateTicketPurchases({
4820 id: compensationData.id,
4821 status: compensationData.previousStatus,
4822 })
4823 }
4824 )
4825 ```
4826
4827 The step receives the ticket purchase ID and the new status as input.
4828
4829 In the step, you update the ticket purchase status. In the compensation function, you undo the update if an error occurs in the workflow.
4830
4831 #### Verify Ticket QR Code Workflow
4832
4833 You can now create the workflow that verifies a ticket QR code.
4834
4835 Create the file `src/workflows/verify-ticket-purchase.ts` with the following content:
4836
4837 ```ts title="src/workflows/verify-ticket-purchase.ts"
4838 import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
4839 import { verifyTicketPurchaseStep } from "./steps/verify-ticket-purchase-step"
4840 import { updateTicketPurchaseStatusStep } from "./steps/update-ticket-purchase-status-step"
4841
4842 export type VerifyTicketPurchaseWorkflowInput = {
4843 ticket_purchase_id: string
4844 }
4845
4846 export const verifyTicketPurchaseWorkflow = createWorkflow(
4847 "verify-ticket-purchase",
4848 function (input: VerifyTicketPurchaseWorkflowInput) {
4849 verifyTicketPurchaseStep(input)
4850
4851 const ticketPurchase = updateTicketPurchaseStatusStep({
4852 ticket_purchase_id: input.ticket_purchase_id,
4853 status: "scanned",
4854 })
4855
4856 return new WorkflowResponse(ticketPurchase)
4857 }
4858 )
4859 ```
4860
4861 The workflow receives the ticket purchase ID as input.
4862
4863 In the workflow, you verify the ticket purchase and then update its status to `scanned`.
4864
4865 ### e. Verify Ticket API Route
4866
4867 Finally, you'll create an API route that executes the `verifyTicketPurchaseWorkflow` workflow to verify a ticket QR code. A QR scanner can call this API route when scanning a ticket at the event entrance.
4868
4869 To create the API route, create the file `src/api/tickets/[id]/verify/route.ts` with the following content:
4870
4871 ```ts title="src/api/tickets/[id]/verify/route.ts"
4872 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
4873 import { verifyTicketPurchaseWorkflow } from "../../../../workflows/verify-ticket-purchase"
4874
4875 export async function POST(req: MedusaRequest, res: MedusaResponse) {
4876 const { id } = req.params
4877
4878 await verifyTicketPurchaseWorkflow(req.scope).run({
4879 input: {
4880 ticket_purchase_id: id,
4881 },
4882 })
4883
4884 res.json({
4885 success: true,
4886 })
4887 }
4888 ```
4889
4890 You expose a `POST` API route at `/tickets/:id/verify`. In the route handler, you execute the `verifyTicketPurchaseWorkflow` workflow with the ticket purchase ID from the URL parameters.
4891
4892 If the ticket is valid, the route returns a success response with `200` status code. If the ticket is invalid, an error is thrown with `400` status code.
4893
4894 ### Test Ticket Verification
4895
4896 To test the ticket verification functionality, start the Medusa application.
4897
4898 Then, place an order with at least one ticket product. After placing the order, check your email for the order confirmation email containing the tickets with QR codes.
4899
4900 Next, decode the QR code to get the ticket purchase ID. You can use an online QR code decoder or a QR code scanner app on your phone.
4901
4902 Finally, make a `POST` request to the `/tickets/:id/verify` API route with the ticket purchase ID:
4903
4904 ```bash
4905 curl -X POST http://localhost:9000/tickets/{ticket_purchase_id}/verify
4906 ```
4907
4908 Replace `{ticket_purchase_id}` with the actual ticket purchase ID you obtained from the QR code.
4909
4910 If the ticket is valid, you'll receive a success response. Otherwise, you'll receive an error response indicating the ticket is invalid or has already been scanned.
4911
4912 ---
4913
4914 ## Next Steps
4915
4916 You've now implemented the ticket booking functionality in the backend. Follow the [Ticket Booking Storefront](./storefront/page.mdx) tutorial to customize the Next.js Starter Storefront for ticket booking.
4917
4918 You can expand on this tutorial by adding more features, such as:
4919
4920 - Provide more management features for venues and ticket products, such as updating and deleting them.
4921 - Allow purchasing tickets for specific times in a day.
4922 - Handle [order events](/references/events#order-events), such as `order.canceled`, to make changes to ticket purchases.
4923
4924 ### Learn More about Medusa
4925
4926 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.
4927
4928 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).
4929
4930 ### Troubleshooting
4931
4932 If you encounter issues during your development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx).
4933
4934 ### Getting Help
4935
4936 If you encounter issues not covered in the troubleshooting guides:
4937
4938 1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions.
4939 2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members.