1 ---
2 sidebar_label: "Implement Quote Management"
3 tags:
4 - cart
5 - order
6 - server
7 - tutorial
8 products:
9 - cart
10 - order
11 - customer
12 ---
13
14 import { Github, PlaySolid } from "@medusajs/icons"
15 import { Prerequisites, WorkflowDiagram } from "docs-ui"
16
17 export const ogImage = "https://res.cloudinary.com/dza7lstvk/image/upload/v1741682814/Medusa%20Resources/quote_ldmqaq.jpg"
18
19 export const metadata = {
20 title: `Implement Quote Management in Medusa`,
21 openGraph: {
22 images: [
23 {
24 url: ogImage,
25 width: 1600,
26 height: 836,
27 type: "image/jpeg"
28 }
29 ],
30 },
31 twitter: {
32 images: [
33 {
34 url: ogImage,
35 width: 1600,
36 height: 836,
37 type: "image/jpeg"
38 }
39 ]
40 }
41 }
42
43 # {metadata.title}
44
45 In this guide, you'll learn how to implement quote management in Medusa.
46
47 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) which are available out-of-the-box.
48
49 By default, the Medusa application provides standard commerce features for orders and carts. However, Medusa's customization capabilities facilitate extending existing features to implement quote-management features.
50
51 By building quote management features, you allow customers to request a quote for a set of products and, once the merchant and customer reach an agreement, you create an order for that quote. Quote management is useful in many use cases, including B2B stores.
52
53 <Note title="Tip">
54
55 This guide is based on the [B2B starter](https://github.com/medusajs/b2b-starter) explaining how to implement some of its quote management features. You can refer to the B2B starter for other features not covered in this guide.
56
57 </Note>
58
59 ## Summary
60
61 By following this guide, you'll add the following features to Medusa:
62
63 1. Customers can request a quote for a set of products.
64 2. Merchants can manage quotes in the Medusa Admin dashboard. They can reject a quote or send a counter-offer, and they can make edits to item prices and quantities.
65 3. Customers can accept or reject a quote once it's been sent by the merchant.
66 4. Once the customer accepts a quote, it's converted to an order in Medusa.
67
68 ![Quote management system workflow diagram illustrating the complete quote lifecycle: customers request quotes from cart items, merchants review and create detailed quotes with pricing, quotes are sent to customers for approval, and upon acceptance, quotes are automatically converted into processable orders within the Medusa e-commerce platform](https://res.cloudinary.com/dza7lstvk/image/upload/v1741173690/Medusa%20Resources/quote-management-summary_xd319j.jpg)
69
70 To implement these features, you'll be customizing the Medusa server and the Medusa Admin dashboard.
71
72 You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
73
74 <CardList items={[
75 {
76 href: "https://github.com/medusajs/examples/tree/main/quotes-management",
77 title: "Quote Management Repository",
78 text: "Find the full code for this guide in this repository.",
79 icon: Github,
80 },
81 {
82 href: "https://res.cloudinary.com/dza7lstvk/raw/upload/v1741171875/OpenApi/quote-management_tbk552.yml",
83 title: "OpenApi Specs for Postman",
84 text: "Import this OpenApi Specs file into tools like Postman.",
85 icon: PlaySolid,
86 },
87 ]} />
88
89 ---
90
91 ## Step 1: Install a Medusa Application
92
93 <Prerequisites items={[
94 {
95 text: "Node.js v20.19.0+ or v22.12.0+",
96 link: "https://nodejs.org/en/download"
97 },
98 {
99 text: "Git CLI tool",
100 link: "https://git-scm.com/downloads"
101 },
102 {
103 text: "PostgreSQL",
104 link: "https://www.postgresql.org/download/"
105 }
106 ]} />
107
108 Start by installing the Medusa application on your machine with the following command:
109
110 ```bash npx2yarnExec
111 npx create-medusa-app@latest
112 ```
113
114 You'll first be asked for the project's name. You can also optionally choose to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx).
115
116 Afterwards, 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. If you chose to install the Next.js Starter Storefront, it'll be in the `apps/storefront` directory.
117
118 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. Afterwards, you can log in with the new user and explore the dashboard.
119
120 <Note title="Ran into Errors">
121
122 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
123
124 </Note>
125
126 <Note>
127
128 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
129
130 </Note>
131
132 ---
133
134 ## Step 2: Add Quote Module
135
136 In Medusa, you can build custom features in a [module](!docs!/learn/fundamentals/modules). A module is a reusable package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
137
138 In the module, you define the data models necessary for a feature and the logic to manage these data models. Later, you can build commerce flows around your module and link its data models to other modules' data models, such as orders and carts.
139
140 In this step, you'll build a Quote Module that defines the necessary data model to store quotes.
141
142 <Note>
143
144 Learn more about modules in [this documentation](!docs!/learn/fundamentals/modules).
145
146 </Note>
147
148 ### Create Module Directory
149
150 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/quote`.
151
152 ![Diagram showcasing the directory structure after adding the Quote Module's directory](https://res.cloudinary.com/dza7lstvk/image/upload/v1741074268/Medusa%20Resources/quote-1_lxgyyg.jpg)
153
154 ### Create Data Models
155
156 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.
157
158 <Note>
159
160 Learn more about data models in [this documentation](!docs!/learn/fundamentals/modules#1-create-data-model).
161
162 </Note>
163
164 For the Quote Module, you need to define a `Quote` data model that represents a quote requested by a customer.
165
166 So, start by creating the `Quote` data model. Create the file `src/modules/quote/models/quote.ts` with the following content:
167
168 ![Diagram showcasing the directory structure after adding the quote model](https://res.cloudinary.com/dza7lstvk/image/upload/v1741074453/Medusa%20Resources/quote-2_lh012l.jpg)
169
170 export const quoteModelHighlights = [
171 ["12", "id", "A unique identifier for the quote."],
172 ["13", "status", "The status of the quote."],
173 ["16", "customer_id", "The ID of the customer who requested the quote."],
174 ["17", "draft_order_id", "The ID of the draft order created for the quote."],
175 ["18", "order_change_id", "The ID of the order change created for the quote."],
176 ["19", "cart_id", "The ID of the cart that the quote was created from."],
177 ]
178
179 ```ts title="src/modules/quote/models/quote.ts" highlights={quoteModelHighlights}
180 import { model } from "@medusajs/framework/utils"
181
182 export enum QuoteStatus {
183 PENDING_MERCHANT = "pending_merchant",
184 PENDING_CUSTOMER = "pending_customer",
185 ACCEPTED = "accepted",
186 CUSTOMER_REJECTED = "customer_rejected",
187 MERCHANT_REJECTED = "merchant_rejected",
188 }
189
190 export const Quote = model.define("quote", {
191 id: model.id().primaryKey(),
192 status: model
193 .enum(Object.values(QuoteStatus))
194 .default(QuoteStatus.PENDING_MERCHANT),
195 customer_id: model.text(),
196 draft_order_id: model.text(),
197 order_change_id: model.text(),
198 cart_id: model.text(),
199 })
200 ```
201
202 You define the `Quote` data model using the `model.define` method of the DML. It accepts the data model's table name as a first parameter, and the model's schema object as a second parameter.
203
204 `Quote` has the following properties:
205
206 - `id`: A unique identifier for the quote.
207 - `status`: The status of the quote, which can be one of the following:
208 - `pending_merchant`: The quote is pending the merchant's approval or rejection.
209 - `pending_customer`: The quote is pending the customer's acceptance or rejection.
210 - `accepted`: The quote has been accepted by the customer and converted to an order.
211 - `customer_rejected`: The customer has rejected the quote.
212 - `merchant_rejected`: The merchant has rejected the quote.
213 - `customer_id`: The ID of the customer who requested the quote. You'll later learn how to link this to a customer record.
214 - `draft_order_id`: The ID of the draft order created for the quote. You'll later learn how to link this to an order record.
215 - `order_change_id`: The ID of the order change created for the quote. An [order change](../../../commerce-modules/order/order-change/page.mdx) is a record of changes made to an order, such as price or quantity updates of the order's items. These changes are later applied to the order. You'll later learn how to link this to an order change record.
216 - `cart_id`: The ID of the cart that the quote was created from. The cart will hold the items that the customer wants a quote for. You'll later learn how to link this to a cart record.
217
218 <Note>
219
220 Learn more about defining data model properties in the [Property Types documentation](!docs!/learn/fundamentals/data-models/properties).
221
222 </Note>
223
224 ### Create Module's Service
225
226 You now have the necessary data model in the Quote Module, but you need to define the logic to manage it. You do this by creating a service in the module.
227
228 A service is a TypeScript or JavaScript 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 a third-party service, which is useful if you're integrating with external services.
229
230 <Note>
231
232 Learn more about services in [this documentation](!docs!/learn/fundamentals/modules#2-create-service).
233
234 </Note>
235
236 To create the Quote Module's service, create the file `src/modules/quote/service.ts` with the following content:
237
238 ![Directory structure after adding the service](https://res.cloudinary.com/dza7lstvk/image/upload/v1741075946/Medusa%20Resources/quote-4_hg4bnr.jpg)
239
240 ```ts title="src/modules/quote/service.ts"
241 import { MedusaService } from "@medusajs/framework/utils"
242 import { Quote } from "./models/quote"
243
244 class QuoteModuleService extends MedusaService({
245 Quote,
246 }) {}
247
248 export default QuoteModuleService
249 ```
250
251 The `QuoteModuleService` extends `MedusaService` from the Modules SDK 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.
252
253 So, the `QuoteModuleService` class now has methods like `createQuotes` and `retrieveQuote`.
254
255 <Note>
256
257 Find all methods generated by the `MedusaService` in [this reference](../../../service-factory-reference/page.mdx).
258
259 </Note>
260
261 You'll use this service later when you implement custom flows for quote management.
262
263 ### Export Module Definition
264
265 The final piece to 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.
266
267 So, create the file `src/modules/quote/index.ts` with the following content:
268
269 ![Directory structure after adding the module definition](https://res.cloudinary.com/dza7lstvk/image/upload/v1741076106/Medusa%20Resources/quote-5_ngitn1.jpg)
270
271 ```ts title="src/modules/quote/index.ts"
272 import { Module } from "@medusajs/framework/utils"
273 import QuoteModuleService from "./service"
274
275 export const QUOTE_MODULE = "quote"
276
277 export default Module(QUOTE_MODULE, {
278 service: QuoteModuleService,
279 })
280 ```
281
282 You use the `Module` function from the Modules SDK to create the module's definition. It accepts two parameters:
283
284 1. The module's name, which is `quote`.
285 2. An object with a required property `service` indicating the module's service.
286
287 You also export the module's name as `QUOTE_MODULE` so you can reference it later.
288
289 ### Add Module to Medusa's Configurations
290
291 Once you finish building the module, add it to Medusa's configurations to start using it.
292
293 In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
294
295 ```ts title="medusa-config.ts"
296 module.exports = defineConfig({
297 // ...
298 modules: [
299 {
300 resolve: "./src/modules/quote",
301 },
302 ],
303 })
304 ```
305
306 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.
307
308 ### Generate Migrations
309
310 Since data models represent tables in the database, you define how they're created in the database with migrations. A migration is a TypeScript or JavaScript file that defines database changes made by a module.
311
312 <Note>
313
314 Learn more about migrations in [this documentation](!docs!/learn/fundamentals/modules#5-generate-migrations).
315
316 </Note>
317
318 Medusa's CLI tool generates the migrations for you. To generate a migration for the Quote Module, run the following command in your `apps/backend` directory:
319
320 ```bash npx2yarn
321 npx medusa db:generate quote
322 ```
323
324 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/quote` that holds the generated migration.
325
326 ![The directory structure of the Quote Module after generating the migration](https://res.cloudinary.com/dza7lstvk/image/upload/v1741076301/Medusa%20Resources/quote-6_adzf76.jpg)
327
328 Then, to reflect these migrations on the database, run the following command:
329
330 ```bash npx2yarn
331 npx medusa db:migrate
332 ```
333
334 The table for the `Quote` data model is now created in the database.
335
336 ---
337
338 ## Step 3: Define Links to Other Modules
339
340 When you defined the `Quote` data model, you added properties that store the ID of records managed by other modules. For example, the `customer_id` property stores the ID of the customer that requested the quote, but customers are managed by the [Customer Module](../../../commerce-modules/customer/page.mdx).
341
342 Medusa integrates modules into your application without implications or side effects by isolating modules from one another. This means you can't directly create relationships between data models in your module and data models in other modules.
343
344 Instead, Medusa provides the mechanism to define links between data models, and retrieve and manage linked records while maintaining module isolation. Links are useful to define associations between data models in different modules, or extend a model in another module to associate custom properties with it.
345
346 <Note>
347
348 To learn more about module isolation, refer to the [Module Isolation documentation](!docs!/learn/fundamentals/modules/isolation).
349
350 </Note>
351
352 In this step, you'll define the following links between the Quote Module's data model and data models in other modules:
353
354 1. `Quote` \<\> `Cart` data model of the [Cart Module](../../../commerce-modules/cart/page.mdx): link quotes to the carts they were created from.
355 2. `Quote` \<\> `Customer` data model of the [Customer Module](../../../commerce-modules/customer/page.mdx): link quotes to the customers who requested them.
356 3. `Quote` \<\> `OrderChange` data model of the [Order Module](../../../commerce-modules/order/page.mdx): link quotes to the order changes that record adjustments made to the quote's draft order.
357 4. `Quote` \<\> `Order` data model of the [Order Module](../../../commerce-modules/order/page.mdx): link quotes to their draft orders that are later converted to orders.
358
359 ### Define Quote \<\> Cart Link
360
361 You can define links between data models in a TypeScript or JavaScript file under the `src/links` directory. So, to define the link between the `Quote` and `Cart` data models, create the file `src/links/quote-cart.ts` with the following content:
362
363 ![Directory structure after adding the quote-cart link](https://res.cloudinary.com/dza7lstvk/image/upload/v1741077395/Medusa%20Resources/quote-7_xrvodi.jpg)
364
365 export const quoteCartHighlights = [
366 ["7", "linkable", "Link configurations of the Quote Module's data models."],
367 ["8", "field", "Specify the property that holds the ID of the linked record."],
368 ["12", "readOnly", "Indicate that the link can only be used to retrieve linked records."],
369 ]
370
371 ```ts title="src/links/quote-cart.ts" highlights={quoteCartHighlights}
372 import { defineLink } from "@medusajs/framework/utils"
373 import QuoteModule from "../modules/quote"
374 import CartModule from "@medusajs/medusa/cart"
375
376 export default defineLink(
377 {
378 linkable: QuoteModule.linkable.quote.id,
379 field: "cart_id",
380 },
381 CartModule.linkable.cart,
382 {
383 readOnly: true,
384 }
385 )
386 ```
387
388 You define a link using the `defineLink` function from the Modules SDK. It accepts three parameters:
389
390 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. So, you can pass the link configurations for the `Quote` data model from the `QuoteModule` module, specifying that its `cart_id` property holds the ID of the linked record.
391 2. An object indicating the second data model part of the link. You pass the link configurations for the `Cart` data model from the `CartModule` module.
392 3. An optional object with additional configurations for the link. By default, Medusa creates a table in the database to represent the link you define. However, when you only want to retrieve the linked records without managing and storing the links, you can set the `readOnly` option to `true`.
393
394 You'll now be able to retrieve the cart that a quote was created from, as you'll see in later steps.
395
396 ### Define Quote \<\> Customer Link
397
398 Next, you'll define the link between the `Quote` and `Customer` data model of the Customer Module. So, create the file `src/links/quote-customer.ts` with the following content:
399
400 ![Directory structure after adding the quote-customer link](https://res.cloudinary.com/dza7lstvk/image/upload/v1741078047/Medusa%20Resources/quote-8_bbngmh.jpg)
401
402 ```ts title="src/links/quote-customer.ts"
403 import { defineLink } from "@medusajs/framework/utils"
404 import QuoteModule from "../modules/quote"
405 import CustomerModule from "@medusajs/medusa/customer"
406
407 export default defineLink(
408 {
409 linkable: QuoteModule.linkable.quote.id,
410 field: "customer_id",
411 },
412 CustomerModule.linkable.customer,
413 {
414 readOnly: true,
415 }
416 )
417 ```
418
419 You define the link between the `Quote` and `Customer` data models in the same way as the `Quote` and `Cart` link. In the first object parameter of `defineLink`, you pass the linkable configurations of the `Quote` data model, specifying the `customer_id` property as the link field. In the second object parameter, you pass the linkable configurations of the `Customer` data model from the Customer Module. You also configure the link to be read-only.
420
421 ### Define Quote \<\> OrderChange Link
422
423 Next, you'll define the link between the `Quote` and `OrderChange` data model of the Order Module. So, create the file `src/links/quote-order-change.ts` with the following content:
424
425 ![Directory structure after adding the quote-order-change link](https://res.cloudinary.com/dza7lstvk/image/upload/v1741078511/Medusa%20Resources/quote-11_faac5m.jpg)
426
427 ```ts title="src/links/quote-order-change.ts"
428 import { defineLink } from "@medusajs/framework/utils"
429 import QuoteModule from "../modules/quote"
430 import OrderModule from "@medusajs/medusa/order"
431
432 export default defineLink(
433 {
434 linkable: QuoteModule.linkable.quote.id,
435 field: "order_change_id",
436 },
437 OrderModule.linkable.orderChange,
438 {
439 readOnly: true,
440 }
441 )
442 ```
443
444 You define the link between the `Quote` and `OrderChange` data models in the same way as the previous links. You pass the linkable configurations of the `Quote` data model, specifying the `order_change_id` property as the link field. In the second object parameter, you pass the linkable configurations of the `OrderChange` data model from the Order Module. You also configure the link to be read-only.
445
446 ### Define Quote \<\> Order Link
447
448 Finally, you'll define the link between the `Quote` and `Order` data model of the Order Module. So, create the file `src/links/quote-order.ts` with the following content:
449
450 ![Directory structure after adding the quote-order link](https://res.cloudinary.com/dza7lstvk/image/upload/v1741078607/Medusa%20Resources/quote-12_ixr2f7.jpg)
451
452 ```ts title="src/links/quote-order.ts"
453 import { defineLink } from "@medusajs/framework/utils"
454 import QuoteModule from "../modules/quote"
455 import OrderModule from "@medusajs/medusa/order"
456
457 export default defineLink(
458 {
459 linkable: QuoteModule.linkable.quote.id,
460 field: "draft_order_id",
461 },
462 {
463 linkable: OrderModule.linkable.order.id,
464 alias: "draft_order",
465 },
466 {
467 readOnly: true,
468 }
469 )
470 ```
471
472 You define the link between the `Quote` and `Order` data models similar to the previous links. You pass the linkable configurations of the `Quote` data model, specifying the `draft_order_id` property as the link field.
473
474 In the second object parameter, you pass the linkable configurations of the `Order` data model from the Order Module. You also set an `alias` property to `draft_order`. This allows you later to retrieve the draft order of a quote with the `draft_order` alias rather than the default `order` alias. Finally, you configure the link to be read-only.
475
476 You've finished creating the links that allow you to retrieve data related to quotes. You'll see how to use these links in later steps.
477
478 ---
479
480 ## Step 4: Implement Create Quote Workflow
481
482 You're now ready to start implementing quote-management features. The first one you'll implement is the ability for customers to request a quote for a set of items in their cart.
483
484 To build custom commerce features in Medusa, you create a [workflow](!docs!/learn/fundamentals/workflows). A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it's a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in an endpoint.
485
486 So, in this section, you'll learn how to create a workflow that creates a quote for a customer.
487
488 <Note>
489
490 Learn more about workflows in the [Workflows documentation](!docs!/learn/fundamentals/workflows).
491
492 </Note>
493
494 The workflow will have the following steps:
495
496 <WorkflowDiagram
497 workflow={{
498 name: "createRequestForQuoteWorkflow",
499 steps: [
500 {
501 type: "step",
502 name: "useQueryGraphStep",
503 description: "Retrieve the cart that the customer wants a quote for.",
504 link: "/references/helper-steps/useQueryGraphStep",
505 depth: 1
506 },
507 {
508 type: "step",
509 name: "useQueryGraphStep",
510 description: "Retrieve the customer requesting the quote.",
511 link: "/references/helper-steps/useQueryGraphStep",
512 depth: 1
513 },
514 {
515 type: "workflow",
516 name: "createOrderWorkflow",
517 description: "Create the draft order for the quote.",
518 link: "/references/medusa-workflows/createOrderWorkflow",
519 depth: 1,
520 },
521 {
522 type: "workflow",
523 name: "beginOrderEditOrderWorkflow",
524 description: "Create the order change for the draft order.",
525 link: "/references/medusa-workflows/beginOrderEditOrderWorkflow",
526 depth: 1
527 },
528 {
529 type: "step",
530 name: "createQuotesStep",
531 description: "Create the quote for the customer.",
532 depth: 1,
533 }
534 ]
535 }}
536 hideLegend
537 />
538
539 The first four steps are provided by Medusa in its `@medusajs/medusa/core-flows` package. So, you only need to implement the `createQuotesStep` step.
540
541 ### createQuotesStep
542
543 In the last step of the workflow, you'll create a quote for the customer using the Quote Module's service.
544
545 To create a step, create the file `src/workflows/steps/create-quotes.ts` with the following content:
546
547 ![Directory structure after adding the create-quotes step](https://res.cloudinary.com/dza7lstvk/image/upload/v1741085446/Medusa%20Resources/quote-13_tv9i23.jpg)
548
549 export const createQuotesStepHighlights = [
550 ["15", "container", "Resolve the Quote Module's service from the Medusa container."],
551 ["19", "createQuotes", "Create the quotes using the generated method."],
552 ["22", "quotes", "Return the quotes as the step's output."],
553 ["23", "map", "Pass the quote IDs to the compensation function."]
554 ]
555
556 ```ts title="src/workflows/steps/create-quotes.ts" highlights={createQuotesStepHighlights}
557 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
558 import { QUOTE_MODULE } from "../../modules/quote"
559 import QueryModuleService from "../../modules/quote/service"
560
561 type StepInput = {
562 draft_order_id: string;
563 order_change_id: string;
564 cart_id: string;
565 customer_id: string;
566 }[]
567
568 export const createQuotesStep = createStep(
569 "create-quotes",
570 async (input: StepInput, { container }) => {
571 const quoteModuleService: QueryModuleService = container.resolve(
572 QUOTE_MODULE
573 )
574
575 const quotes = await quoteModuleService.createQuotes(input)
576
577 return new StepResponse(
578 quotes,
579 quotes.map((quote) => quote.id)
580 )
581 }
582 )
583 ```
584
585 You create a step with `createStep` from the Workflows SDK. It accepts two parameters:
586
587 1. The step's unique name, which is `create-quotes`.
588 2. An async function that receives two parameters:
589 - The step's input, which is in this case an array of quotes to create.
590 - 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.
591
592 In the step function, you resolve the Quote Module's service from the Medusa container using the `resolve` method of the container, passing it the module's name as a parameter.
593
594 Then, you create the quotes using the `createQuotes` method. As you remember, the Quote Module's service extends the `MedusaService` which generates data-management methods for you.
595
596 A step function must return a `StepResponse` instance. The `StepResponse` constructor accepts two parameters:
597
598 1. The step's output, which is the quotes created.
599 2. Data to pass to the step's compensation function, which you'll add next.
600
601 #### Add Compensation to Step
602
603 A step can have a compensation function that undoes the actions performed in a step. Then, if an error occurs during the workflow's execution, the compensation functions of executed steps are called to roll back the changes. This mechanism ensures data consistency in your application, especially as you integrate external systems.
604
605 To add a compensation function to a step, pass it as a third-parameter to `createStep`:
606
607 ```ts title="src/workflows/steps/create-quotes.ts"
608 export const createQuotesStep = createStep(
609 // ...
610 async (quoteIds, { container }) => {
611 if (!quoteIds) {
612 return
613 }
614
615 const quoteModuleService: QueryModuleService = container.resolve(
616 QUOTE_MODULE
617 )
618
619 await quoteModuleService.deleteQuotes(quoteIds)
620 }
621 )
622 ```
623
624 The compensation function accepts two parameters:
625
626 1. The data passed from the step in the second parameter of `StepResponse`, which in this case is an array of quote IDs.
627 2. An object that has properties including the [Medusa container](!docs!/learn/fundamentals/medusa-container).
628
629 In the compensation function, you resolve the Quote Module's service from the Medusa container and call the `deleteQuotes` method to delete the quotes created in the step.
630
631 ### createRequestForQuoteWorkflow
632
633 You can now create the workflow using the steps provided by Medusa and your custom step.
634
635 To create the workflow, create the file `src/workflows/create-request-for-quote.ts` with the following content:
636
637 export const createRequestForQuoteHighlights = [
638 ["24", "useQueryGraphStep", "Retrieve the cart's details."],
639 ["45", "useQueryGraphStep", "Retrieve the customer's details."]
640 ]
641
642 ```ts title="src/workflows/create-request-for-quote.ts" highlights={createRequestForQuoteHighlights} collapsibleLines="1-20" expandButtonLabel="Show Imports"
643 import {
644 beginOrderEditOrderWorkflow,
645 createOrderWorkflow,
646 CreateOrderWorkflowInput,
647 useQueryGraphStep,
648 } from "@medusajs/medusa/core-flows"
649 import { OrderStatus } from "@medusajs/framework/utils"
650 import {
651 createWorkflow,
652 transform,
653 WorkflowResponse,
654 } from "@medusajs/framework/workflows-sdk"
655 import { CreateOrderLineItemDTO } from "@medusajs/framework/types"
656 import { createQuotesStep } from "./steps/create-quotes"
657
658 type WorkflowInput = {
659 cart_id: string;
660 customer_id: string;
661 };
662
663 export const createRequestForQuoteWorkflow = createWorkflow(
664 "create-request-for-quote",
665 (input: WorkflowInput) => {
666 const { data: carts } = useQueryGraphStep({
667 entity: "cart",
668 fields: [
669 "id",
670 "sales_channel_id",
671 "currency_code",
672 "region_id",
673 "customer.id",
674 "customer.email",
675 "shipping_address.*",
676 "billing_address.*",
677 "items.*",
678 "shipping_methods.*",
679 "promotions.code",
680 ],
681 filters: { id: input.cart_id },
682 options: {
683 throwIfKeyNotFound: true,
684 },
685 })
686
687 const { data: customers } = useQueryGraphStep({
688 entity: "customer",
689 fields: ["id", "customer"],
690 filters: { id: input.customer_id },
691 options: {
692 throwIfKeyNotFound: true,
693 },
694 }).config({ name: "customer-query" })
695
696 // TODO create order
697 }
698 )
699 ```
700
701 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
702
703 It accepts as a second parameter a constructor function, which is the workflow's implementation. The function can accept input, which in this case is an object having the ID of the customer requesting the quote, and the ID of their cart.
704
705 In the workflow's constructor function, you use `useQueryGraphStep` to retrieve the cart and customer details using the IDs passed as an input to the workflow.
706
707 <Note title="Tip">
708
709 `useQueryGraphStep` uses [Query](!docs!/learn/fundamentals/query), which allows you to retrieve data across modules. For example, in the above snippet you're retrieving the cart's promotions, which are managed in the [Promotion Module](../../../commerce-modules/promotion/page.mdx), by passing `promotions.code` to the `fields` array.
710
711 </Note>
712
713 Next, you want to create the draft order for the quote. Replace the `TODO` in the workflow with the following:
714
715 ```ts title="src/workflows/create-request-for-quote.ts"
716 const orderInput = transform({ carts, customers }, ({ carts, customers }) => {
717 return {
718 is_draft_order: true,
719 status: OrderStatus.DRAFT,
720 sales_channel_id: carts[0].sales_channel_id || undefined,
721 email: customers[0].email || undefined,
722 customer_id: customers[0].id || undefined,
723 billing_address: carts[0].billing_address,
724 shipping_address: carts[0].shipping_address,
725 items: carts[0].items as CreateOrderLineItemDTO[] || [],
726 region_id: carts[0].region_id || undefined,
727 promo_codes: carts[0].promotions?.map((promo) => promo?.code),
728 currency_code: carts[0].currency_code,
729 shipping_methods: carts[0].shipping_methods || [],
730 } as CreateOrderWorkflowInput
731 })
732
733 const draftOrder = createOrderWorkflow.runAsStep({
734 input: orderInput,
735 })
736
737 // TODO create order change
738 ```
739
740 You first prepare the order's details using `transform` from the Workflows SDK. Since Medusa creates an internal representation of the workflow's constructor before any data actually has a value, you can't manipulate data directly in the function. So, Medusa provides utilities like `transform` to manipulate data instead. You can learn more in the [transform variables](!docs!/learn/fundamentals/workflows/variable-manipulation) documentation.
741
742 Then, you create the draft order using the `createOrderWorkflow` workflow which you imported from `@medusajs/medusa/core-flows`. The workflow creates and returns the created order.
743
744 After that, you want to create an order change for the draft order. This will allow the admin later to make edits to the draft order, such as updating the prices or quantities of the items in the order.
745
746 Replace the `TODO` with the following:
747
748 ```ts title="src/workflows/create-request-for-quote.ts"
749 const orderEditInput = transform({ draftOrder }, ({ draftOrder }) => {
750 return {
751 order_id: draftOrder.id,
752 description: "",
753 internal_note: "",
754 metadata: {},
755 }
756 })
757
758 const changeOrder = beginOrderEditOrderWorkflow.runAsStep({
759 input: orderEditInput,
760 })
761
762 // TODO create quote
763 ```
764
765 You prepare the order change's details using `transform` and then create the order change using the `beginOrderEditOrderWorkflow` workflow which is provided by Medusa.
766
767 Finally, you want to create the quote for the customer and return it. Replace the last `TODO` with the following:
768
769 ```ts title="src/workflows/create-request-for-quote.ts"
770 const quoteData = transform({
771 draftOrder,
772 carts,
773 customers,
774 changeOrder,
775 }, ({ draftOrder, carts, customers, changeOrder }) => {
776 return {
777 draft_order_id: draftOrder.id,
778 cart_id: carts[0].id,
779 customer_id: customers[0].id,
780 order_change_id: changeOrder.id,
781 }
782 })
783
784 const quotes = createQuotesStep([
785 quoteData,
786 ])
787
788 return new WorkflowResponse({ quote: quotes[0] })
789 ```
790
791 Similar to before, you prepare the quote's details using `transform`. Then, you create the quote using the `createQuotesStep` you implemented earlier.
792
793 A workflow must return an instance of `WorkflowResponse`. The `WorkflowResponse` constructor accepts the workflow's output as a parameter, which is an object holding the created quote in this case.
794
795 In the next step, you'll learn how to execute the workflow when a customer requests a quote.
796
797 ---
798
799 ## Step 5: Create Quote API Route
800
801 Now that you have the logic to create a quote for a customer, you need to expose it so that frontend clients, such as a storefront, can use it. You do this by creating an [API route](!docs!/learn/fundamentals/api-routes).
802
803 An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts. You'll create an API route at the path `/store/customers/me/quotes` that executes the workflow from the previous step.
804
805 <Note>
806
807 Learn more about API routes in [this documentation](!docs!/learn/fundamentals/api-routes).
808
809 </Note>
810
811 ### Implement API Route
812
813 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`.
814
815 By default, all routes starting with `/store/customers/me` require the customer to be authenticated. So, you'll be creating the API route at `/store/customers/me/quotes`.
816
817 To create the API route, create the file `src/api/store/customers/me/quotes/route.ts` with the following content:
818
819 ![Directory structure after adding the store/quotes route](https://res.cloudinary.com/dza7lstvk/image/upload/v1741086995/Medusa%20Resources/quote-14_meo0yo.jpg)
820
821 export const createQuoteApiHighlights = [
822 ["20", "createRequestForQuoteWorkflow", "Execute the workflow to create a quote."],
823 ["33", "query", "Use Query to retrieve the quote."]
824 ]
825
826 ```ts title="src/api/store/customers/me/quotes/route.ts" highlights={createQuoteApiHighlights} collapsibleLines="1-9" expandButtonLabel="Show Imports"
827 import {
828 AuthenticatedMedusaRequest,
829 MedusaResponse,
830 } from "@medusajs/framework/http"
831 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
832 import {
833 createRequestForQuoteWorkflow,
834 } from "../../../../../workflows/create-request-for-quote"
835
836 type CreateQuoteType = {
837 cart_id: string;
838 }
839
840 export const POST = async (
841 req: AuthenticatedMedusaRequest<CreateQuoteType>,
842 res: MedusaResponse
843 ) => {
844 const {
845 result: { quote: createdQuote },
846 } = await createRequestForQuoteWorkflow(req.scope).run({
847 input: {
848 ...req.validatedBody,
849 customer_id: req.auth_context.actor_id,
850 },
851 })
852
853 const query = req.scope.resolve(
854 ContainerRegistrationKeys.QUERY
855 )
856
857 const {
858 data: [quote],
859 } = await query.graph(
860 {
861 entity: "quote",
862 fields: req.queryConfig.fields,
863 filters: { id: createdQuote.id },
864 },
865 { throwIfKeyNotFound: true }
866 )
867
868 return res.json({ quote })
869 }
870 ```
871
872 Since you export a `POST` function in this file, you're exposing a `POST` API route at `/store/customers/me/quotes`. The route handler function accepts two parameters:
873
874 1. A request object with details and context on the request, such as body parameters or authenticated customer details.
875 2. A response object to manipulate and send the response.
876
877 <Note title="Tip">
878
879 `AuthenticatedMedusaRequest` accepts the request body's type as a type argument.
880
881 </Note>
882
883 In the route handler function, you create the quote using the [createRequestForQuoteWorkflow](#createrequestforquoteworkflow) from the previous step. Then, you resolve Query from the Medusa container, which is available in the request object's `req.scope` property.
884
885 You use Query to retrieve the Quote with its fields and linked records, which you'll learn how to specify soon. Finally, you send the quote as a response.
886
887 ### Add Validation Schema
888
889 The API route accepts the cart ID as a request body parameter. So, it's important to validate the body of a request before executing the route's handler. You can do this by specifying a validation schema in a middleware for the API route.
890
891 In Medusa, you create validation schemas using [Zod](https://zod.dev/) in a TypeScript file under the `src/api` directory. So, create the file `src/api/store/validators.ts` with the following content:
892
893 ![Directory structure after adding the validators file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741089363/Medusa%20Resources/quote-15_iy6jem.jpg)
894
895 <Note>
896
897 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
898
899 </Note>
900
901 ```ts title="src/api/store/validators.ts"
902 import { z } from "@medusajs/framework/zod"
903
904 export type CreateQuoteType = z.infer<typeof CreateQuote>;
905 export const CreateQuote = z.strictObject({
906 cart_id: z.string().min(1),
907 })
908 ```
909
910 You define a `CreateQuote` schema using Zod that specifies the `cart_id` parameter as a required string.
911
912 You also export a type inferred from the schema. So, go back to `src/api/store/customers/me/quotes/route.ts` and replace the implementation of `CreateQuoteType` to import the type from the `validators.ts` file instead:
913
914 ```ts title="src/api/store/customers/me/quotes/route.ts"
915 // other imports...
916 // add the following import
917 import { CreateQuoteType } from "../../../validators"
918
919 // remove CreateQuoteType definition
920
921 export const POST = async (
922 // keep type argument the same
923 req: AuthenticatedMedusaRequest<CreateQuoteType>,
924 res: MedusaResponse
925 ) => {
926 // ...
927 }
928 ```
929
930 ### Apply Validation Schema Middleware
931
932 Now that you have the validation schema, you need to add the middleware that ensures the request body is validated before the route handler is executed. A middleware is a function executed when a request is sent to an API Route. It's executed before the route handler.
933
934 <Note>
935
936 Learn more about middleware in the [Middlewares documentation](!docs!/learn/fundamentals/api-routes/middlewares).
937
938 </Note>
939
940 Middlewares are created in the `src/api/middlewares.ts` file. So create the file `src/api/middlewares.ts` with the following content:
941
942 ![Directory structure after adding the store middlewares file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741089625/Medusa%20Resources/quote-16_oryolz.jpg)
943
944 ```ts title="src/api/middlewares.ts"
945 import {
946 defineMiddlewares,
947 validateAndTransformBody,
948 } from "@medusajs/framework/http"
949 import { CreateQuote } from "./store/validators"
950
951 export default defineMiddlewares({
952 routes: [
953 {
954 method: ["POST"],
955 matcher: "/store/customers/me/quotes",
956 middlewares: [
957 validateAndTransformBody(CreateQuote),
958 ],
959 },
960 ],
961 })
962 ```
963
964 To export the middlewares, you use the `defineMiddlewares` function. It accepts an object having a `routes` property, whose value is an array of middleware route objects. Each middleware route object has the following properties:
965
966 - `method`: The HTTP methods the middleware applies to, which is in this case `POST`.
967 - `matcher`: The path of the route the middleware applies to.
968 - `middlewares`: An array of middleware functions to apply to the route. In this case, you apply the `validateAndTransformBody` middleware, which accepts a Zod schema as a parameter and validates that a request's body matches the schema. If not, it throws and returns an error.
969
970 ### Specify Quote Fields to Retrieve
971
972 In the route handler you just created, you specified what fields to retrieve in a quote using the `req.queryConfig.fields` property. The `req.queryConfig` field holds query configurations indicating the default fields to retrieve when using Query to return data in a request. This is useful to unify the returned data structure across different routes, or to allow clients to specify the fields they want to retrieve.
973
974 To add the Query configurations, you'll first create a file that exports the default fields to retrieve for a quote, then apply them in a `validateAndTransformQuery` middleware.
975
976 <Note>
977
978 Learn more about configuring Query for requests in the [Request Query Configurations documentation](!docs!/learn/fundamentals/query#request-query-configurations).
979
980 </Note>
981
982 Create the file `src/api/store/customers/me/quotes/query-config.ts` with the following content:
983
984 ![Directory structure after adding the query-config file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741090067/Medusa%20Resources/quote-17_n6xsdb.jpg)
985
986 ```ts title="src/api/store/customers/me/quotes/query-config.ts"
987 export const quoteFields = [
988 "id",
989 "status",
990 "*customer",
991 "cart.id",
992 "draft_order.id",
993 "draft_order.currency_code",
994 "draft_order.display_id",
995 "draft_order.region_id",
996 "draft_order.status",
997 "draft_order.version",
998 "draft_order.summary",
999 "draft_order.total",
1000 "draft_order.subtotal",
1001 "draft_order.tax_total",
1002 "draft_order.order_change",
1003 "draft_order.discount_total",
1004 "draft_order.discount_tax_total",
1005 "draft_order.original_total",
1006 "draft_order.original_tax_total",
1007 "draft_order.item_total",
1008 "draft_order.item_subtotal",
1009 "draft_order.item_tax_total",
1010 "draft_order.original_item_total",
1011 "draft_order.original_item_subtotal",
1012 "draft_order.original_item_tax_total",
1013 "draft_order.shipping_total",
1014 "draft_order.shipping_subtotal",
1015 "draft_order.shipping_tax_total",
1016 "draft_order.original_shipping_tax_total",
1017 "draft_order.original_shipping_subtotal",
1018 "draft_order.original_shipping_total",
1019 "draft_order.created_at",
1020 "draft_order.updated_at",
1021 "*draft_order.items",
1022 "*draft_order.items.tax_lines",
1023 "*draft_order.items.adjustments",
1024 "*draft_order.items.variant",
1025 "*draft_order.items.variant.product",
1026 "*draft_order.items.detail",
1027 "*draft_order.payment_collections",
1028 "*order_change.actions",
1029 ]
1030
1031 export const retrieveStoreQuoteQueryConfig = {
1032 defaults: quoteFields,
1033 isList: false,
1034 }
1035
1036 export const listStoreQuoteQueryConfig = {
1037 defaults: quoteFields,
1038 isList: true,
1039 }
1040 ```
1041
1042 You export two objects:
1043
1044 - `retrieveStoreQuoteQueryConfig`: Specifies the default fields to retrieve for a single quote.
1045 - `listStoreQuoteQueryConfig`: Specifies the default fields to retrieve for a list of quotes, which you'll use later.
1046
1047 Notice that in the fields retrieved, you specify linked records such as `customer` and `draft_order`. You can do this because you've defined links between the `Quote` data model and these data models previously.
1048
1049 <Note>
1050
1051 For simplicity, this guide will apply the `listStoreQuoteQueryConfig` to all routes starting with `/store/customers/me/quotes`. However, you should instead apply `retrieveStoreQuoteQueryConfig` to routes that retrieve a single quote, and `listStoreQuoteQueryConfig` to routes that retrieve a list of quotes.
1052
1053 </Note>
1054
1055 Next, you'll define a Zod schema that allows client applications to specify the fields they want to retrieve in a quote as a query parameter. In `src/api/store/validators.ts`, add the following schema:
1056
1057 ```ts title="src/api/store/validators.ts"
1058 // other imports...
1059 import { createFindParams } from "@medusajs/medusa/api/utils/validators"
1060
1061 // ...
1062
1063 export type GetQuoteParamsType = z.infer<typeof GetQuoteParams>;
1064 export const GetQuoteParams = createFindParams({
1065 limit: 15,
1066 offset: 0,
1067 })
1068 ```
1069
1070 You create a `GetQuoteParams` schema using the `createFindParams` utility from Medusa. This utility creates a schema that allows clients to specify query parameters such as:
1071
1072 - `fields`: The fields to retrieve in a quote.
1073 - `limit`: The maximum number of quotes to retrieve. This is useful for routes that return a list of quotes.
1074 - `offset`: The number of quotes to skip before retrieving the next set of quotes. This is useful for routes that return a list of quotes.
1075 - `order`: The fields to sort the quotes by either in ascending or descending order. This is useful for routes that return a list of quotes.
1076
1077 Finally, you'll apply these Query configurations in a middleware. So, add the following middleware in `src/api/middlewares.ts`:
1078
1079 ```ts title="src/api/store/middlewares.ts"
1080 // other imports...
1081 import { GetQuoteParams } from "./store/validators"
1082 import { validateAndTransformQuery } from "@medusajs/framework/http"
1083 import { listStoreQuoteQueryConfig } from "./store/customers/me/quotes/query-config"
1084
1085 export default defineMiddlewares({
1086 routes: [
1087 // ...
1088 {
1089 matcher: "/store/customers/me/quotes*",
1090 middlewares: [
1091 validateAndTransformQuery(
1092 GetQuoteParams,
1093 listStoreQuoteQueryConfig
1094 ),
1095 ],
1096 },
1097 ],
1098 })
1099 ```
1100
1101 You apply the `validateAndTransformQuery` middleware on all routes starting with `/store/customers/me/quotes`. The `validateAndTransformQuery` middleware that Medusa provides accepts two parameters:
1102
1103 1. A Zod schema that specifies how to validate the query parameters of incoming requests.
1104 2. A Query configuration object that specifies the default fields to retrieve in the response, which you defined in the `query-config.ts` file.
1105
1106 The create quote route is now ready to be used by clients to create quotes for customers.
1107
1108 ### Test the API Route
1109
1110 To test out the API route, start the Medusa application:
1111
1112 ```bash npm2yarn
1113 npm run dev
1114 ```
1115
1116 Then, open the Medusa Admin dashboard at `http://localhost:9000/app` and login using the credentials you set up earlier.
1117
1118 #### Retrieve Publishable API Key
1119
1120 All requests sent to routes starting with `/store` must have a publishable API key in their header. This ensures that the request is scoped to a specific sales channel of your storefront.
1121
1122 <Note>
1123
1124 To learn more about publishable API keys, refer to the [Publishable API Key documentation](../../../commerce-modules/sales-channel/publishable-api-keys/page.mdx).
1125
1126 </Note>
1127
1128 To retrieve the publishable API key from the Medusa Admin, refer to [this user guide](!user-guide!/settings/developer/publishable-api-keys).
1129
1130 #### Retrieve Customer Authentication Token
1131
1132 As mentioned before, the API route you added requires the customer to be authenticated. So, you'll first create a customer, then retrieve their authentication token to use in the request.
1133
1134 Before creating the customer, retrieve a registration token using the [Retrieve Registration JWT Token API route](!api!/store/auth/retrieve-registration-jwt-token):
1135
1136 ```bash
1137 curl -X POST 'http://localhost:9000/auth/customer/emailpass/register' \
1138 -H 'Content-Type: application/json' \
1139 --data-raw '{
1140 "email": "customer@gmail.com",
1141 "password": "supersecret"
1142 }'
1143 ```
1144
1145 Make sure to replace the email and password with the credentials you want.
1146
1147 Then, register the customer using the [Create Customer API route](!api!/store/customers/register-customer):
1148
1149 ```bash
1150 curl -X POST 'http://localhost:9000/store/customers' \
1151 -H 'Authorization: Bearer {token}' \
1152 -H 'Content-Type: application/json' \
1153 -H 'x-publishable-api-key: {your_publishable_api_key}' \
1154 --data-raw '{
1155 "email": "customer@gmail.com"
1156 }'
1157 ```
1158
1159 Make sure to replace:
1160
1161 - `{token}` with the registration token you received from the previous request.
1162 - `{your_publishable_api_key}` with the publishable API key you retrieved from the Medusa Admin.
1163
1164 Also, if you changed the email in the first request, make sure to change it here as well.
1165
1166 The customer is now registered. Lastly, you need to retrieve its authenticated token by sending a request to the [Authenticate Customer API route](!api!/store/auth/authenticate-customer):
1167
1168 ```bash
1169 curl -X POST 'http://localhost:9000/auth/customer/emailpass' \
1170 -H 'Content-Type: application/json' \
1171 --data-raw '{
1172 "email": "customer@gmail.com",
1173 "password": "supersecret"
1174 }'
1175 ```
1176
1177 Copy the returned token to use it in the next requests.
1178
1179 #### Create Cart
1180
1181 The customer needs a cart with an item before creating the quote.
1182
1183 A cart requires a region ID. You can retrieve a region ID using the [List Regions API route](!api!/store/regions/list-regions):
1184
1185 ```bash
1186 curl 'http://localhost:9000/store/regions' \
1187 -H 'x-publishable-api-key: {your_publishable_api_key}'
1188 ```
1189
1190 Make sure to replace the `{your_publishable_api_key}` with the publishable API key you retrieved from the Medusa Admin.
1191
1192 Then, create a cart for the customer using the [Create Cart API route](!api!/store/carts/create-cart):
1193
1194 ```bash
1195 curl -X POST 'http://localhost:9000/store/carts' \
1196 -H 'Authorization: Bearer {token}' \
1197 -H 'Content-Type: application/json' \
1198 -H 'x-publishable-api-key: {your_publishable_api_key}' \
1199 --data '{
1200 "region_id": "{region_id}"
1201 }'
1202 ```
1203
1204 Make sure to replace:
1205
1206 - `{token}` with the authentication token you received from the previous request.
1207 - `{your_publishable_api_key}` with the publishable API key you retrieved from the Medusa Admin.
1208 - `{region_id}` with the region ID you retrieved from the previous request.
1209
1210 This will create and return a cart. Copy its ID for the next request.
1211
1212 You now need to add a product variant to the cart. You can retrieve a product variant ID using the [List Products API route](!api!/store/products/list-products):
1213
1214 ```bash
1215 curl 'http://localhost:9000/store/products' \
1216 -H 'x-publishable-api-key: {your_publishable_api_key}'
1217 ```
1218
1219 Make sure to replace the `{your_publishable_api_key}` with the publishable API key you retrieved from the Medusa Admin.
1220
1221 Copy the ID of a variant in a product from the response.
1222
1223 Finally, to add the product variant to the cart, use the [Add Item to Cart API route](!api!/store/carts/add-line-item):
1224
1225 ```bash
1226 curl -X POST 'http://localhost:9000/store/carts/{id}/line-items' \
1227 -H 'Authorization: Bearer {token}' \
1228 -H 'Content-Type: application/json' \
1229 -H 'x-publishable-api-key: {your_publishable_api_key}' \
1230 --data-raw '{
1231 "variant_id": "{variant_id}",
1232 "quantity": 1,
1233 }'
1234 ```
1235
1236 Make sure to replace:
1237
1238 - `{id}` with the cart ID you retrieved previously.
1239 - `{token}` with the authentication token you retrieved previously.
1240 - `{your_publishable_api_key}` with the publishable API key you retrieved from the Medusa Admin.
1241 - `{variant_id}` with the product variant ID you retrieved in the previous request.
1242
1243 This adds the product variant to the cart. You can now use the cart to create a quote.
1244
1245 <Note>
1246
1247 For more accurate totals and processing of the quote's draft order, you should:
1248
1249 - Add shipping and billing addresses by [updating the cart](!api!/store/carts/update-a-cart).
1250 - [Choose a shipping method](!api!/store/carts/add-shipping-method) for the cart.
1251 - [Create a payment collection](!api!/store/payment-collections/create-payment-collection) for the cart.
1252 - [Initialize payment session](!api!/store/payment-collections/initialize-payment-session) in the payment collection.
1253
1254 You can also learn how to build a checkout experience in a storefront by following [this storefront development guide](../../../storefront-development/checkout/page.mdx). It's not specific to quote management, so you'll need to change the last step to create a quote instead of an order.
1255
1256 </Note>
1257
1258 #### Create Quote
1259
1260 To create a quote for the customer, send a request to the `/store/customers/me/quotes` route you created:
1261
1262 ```bash
1263 curl -X POST 'http://localhost:9000/store/customers/me/quotes' \
1264 -H 'Authorization: Bearer {token}' \
1265 -H 'Content-Type: application/json' \
1266 -H 'x-publishable-api-key: {your_publishable_api_key}' \
1267 --data-raw '{
1268 "cart_id": "{cart_id}"
1269 }'
1270 ```
1271
1272 Make sure to replace:
1273
1274 - `{token}` with the authentication token you retrieved previously.
1275 - `{your_publishable_api_key}` with the publishable API key you retrieved from the Medusa Admin.
1276 - `{cart_id}` with the ID of the customer's cart.
1277
1278 This will create a quote for the customer and you'll receive its details in the response.
1279
1280 ---
1281
1282 ## Step 6: List Quotes API Route
1283
1284 After the customer creates a quote, the admin user needs to view these quotes to manage them. In this step, you'll create the API route to list quotes for the admin user. Then, in the next step, you'll customize the Medusa Admin dashboard to display these quotes.
1285
1286 The process of creating this API route will be somewhat similar to the previous route you created. You'll create the route, define the query configurations, and apply them in a middleware.
1287
1288 ### Implement API Route
1289
1290 To create the API route, create the file `src/api/admin/quotes/route.ts` with the following content:
1291
1292 ![Directory structure after adding the admin quotes route](https://res.cloudinary.com/dza7lstvk/image/upload/v1741094735/Medusa%20Resources/quote-18_uvwqt6.jpg)
1293
1294 export const listQuotesHighlights = [
1295 ["10", "metadata", "Holds pagination parameters of the Query result."],
1296 ["10", "query", "Retrieve the list of quotes."],
1297 ["12", "req.queryConfig", "Pass the configured Query configurations for selected fields and pagination."]
1298 ]
1299
1300 ```ts title="src/api/admin/quotes/route.ts" highlights={listQuotesHighlights}
1301 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
1302 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
1303
1304 export const GET = async (
1305 req: MedusaRequest,
1306 res: MedusaResponse
1307 ) => {
1308 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
1309
1310 const { data: quotes, metadata } = await query.graph({
1311 entity: "quote",
1312 ...req.queryConfig,
1313 })
1314
1315 res.json({
1316 quotes,
1317 count: metadata!.count,
1318 offset: metadata!.skip,
1319 limit: metadata!.take,
1320 })
1321 }
1322 ```
1323
1324 You export a `GET` function in this file, which exposes a `GET` API route at `/admin/quotes`.
1325
1326 In the route handler function, you resolve Query from the Medusa container and use it to retrieve the list of quotes. Similar to before, you use `req.queryConfig` to specify the fields to retrieve in the response.
1327
1328 `req.queryConfig` also includes pagination parameters, such as `limit`, `offset`, and `count`, and they're returned in the `metadata` property of Query's result. You return the pagination details and the list of quotes in the response.
1329
1330 <Note>
1331
1332 Learn more about paginating Query results in the [Query documentation](!docs!/learn/fundamentals/query#apply-pagination).
1333
1334 </Note>
1335
1336 ### Add Query Configurations
1337
1338 Similar to before, you need to specify the default fields to retrieve in a quote and apply them in a middleware for this new route.
1339
1340 Since this is an admin route, create the file `src/api/admin/quotes/query-config.ts` with the following content:
1341
1342 ![Directory structure after adding the query-config file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741095492/Medusa%20Resources/quote-19_xca6aq.jpg)
1343
1344 ```ts title="src/api/admin/quotes/query-config.ts"
1345 export const quoteFields = [
1346 "id",
1347 "status",
1348 "created_at",
1349 "updated_at",
1350 "*customer",
1351 "cart.id",
1352 "draft_order.id",
1353 "draft_order.currency_code",
1354 "draft_order.display_id",
1355 "draft_order.region_id",
1356 "draft_order.status",
1357 "draft_order.version",
1358 "draft_order.summary",
1359 "draft_order.total",
1360 "draft_order.subtotal",
1361 "draft_order.tax_total",
1362 "draft_order.order_change",
1363 "draft_order.discount_total",
1364 "draft_order.discount_tax_total",
1365 "draft_order.original_total",
1366 "draft_order.original_tax_total",
1367 "draft_order.item_total",
1368 "draft_order.item_subtotal",
1369 "draft_order.item_tax_total",
1370 "draft_order.original_item_total",
1371 "draft_order.original_item_subtotal",
1372 "draft_order.original_item_tax_total",
1373 "draft_order.shipping_total",
1374 "draft_order.shipping_subtotal",
1375 "draft_order.shipping_tax_total",
1376 "draft_order.original_shipping_tax_total",
1377 "draft_order.original_shipping_subtotal",
1378 "draft_order.original_shipping_total",
1379 "draft_order.created_at",
1380 "draft_order.updated_at",
1381 "*draft_order.items",
1382 "*draft_order.items.tax_lines",
1383 "*draft_order.items.adjustments",
1384 "*draft_order.items.variant",
1385 "*draft_order.items.variant.product",
1386 "*draft_order.items.detail",
1387 "*order_change.actions",
1388 ]
1389
1390 export const retrieveAdminQuoteQueryConfig = {
1391 defaults: quoteFields,
1392 isList: false,
1393 }
1394
1395 export const listAdminQuoteQueryConfig = {
1396 defaults: quoteFields,
1397 isList: true,
1398 }
1399 ```
1400
1401 You export two objects: `retrieveAdminQuoteQueryConfig` and `listAdminQuoteQueryConfig`, which specify the default fields to retrieve for a single quote and a list of quotes, respectively.
1402
1403 <Note>
1404
1405 For simplicity, this guide will apply the `listAdminQuoteQueryConfig` to all routes starting with `/admin/quotes`. However, you should instead apply `retrieveAdminQuoteQueryConfig` to routes that retrieve a single quote, and `listAdminQuoteQueryConfig` to routes that retrieve a list of quotes.
1406
1407 </Note>
1408
1409 Next, you'll define a Zod schema that allows client applications to specify the fields to retrieve and pagination fields as a query parameter. Create the file `src/api/admin/validators.ts` with the following content:
1410
1411 ![Directory structure after adding the admin validators file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741095771/Medusa%20Resources/quote-20_iygrip.jpg)
1412
1413 ```ts title="src/api/admin/validators.ts"
1414 import {
1415 createFindParams,
1416 } from "@medusajs/medusa/api/utils/validators"
1417
1418 export const AdminGetQuoteParams = createFindParams({
1419 limit: 15,
1420 offset: 0,
1421 })
1422 ```
1423
1424 You define the `AdminGetQuoteParams` schema using the `createFindParams` utility from Medusa. The schema allows clients to specify query parameters such as:
1425
1426 - `fields`: The fields to retrieve in a quote.
1427 - `limit`: The maximum number of quotes to retrieve.
1428 - `offset`: The number of quotes to skip before retrieving the next set of quotes.
1429 - `order`: The fields to sort the quotes by either in ascending or descending order.
1430
1431 Finally, you need to apply the `validateAndTransformQuery` middleware on this route. So, add the following to `src/api/middlewares.ts`:
1432
1433 ```ts title="src/api/middlewares.ts"
1434 // other imports...
1435 import { AdminGetQuoteParams } from "./admin/quotes/validators"
1436 import { listAdminQuoteQueryConfig } from "./admin/quotes/query-config"
1437
1438 export default defineMiddlewares({
1439 routes: [
1440 // ...
1441 {
1442 matcher: "/admin/quotes*",
1443 middlewares: [
1444 validateAndTransformQuery(
1445 AdminGetQuoteParams,
1446 listAdminQuoteQueryConfig
1447 ),
1448 ],
1449 },
1450 ],
1451 })
1452 ```
1453
1454 You add the `validateAndTransformQuery` middleware to all routes starting with `/admin/quotes`. It validates the query parameters and sets the Query configurations based on the defaults you defined and the passed query parameters.
1455
1456 Your API route is now ready for use. You'll test it in the next step by customizing the Medusa Admin dashboard to display the quotes.
1457
1458 ---
1459
1460 ## Step 7: List Quotes Route in Medusa Admin
1461
1462 Now that you have the API route to retrieve the list of quotes, you want to show these quotes to the admin user in the Medusa Admin dashboard. The Medusa Admin is customizable, allowing you to add new pages as UI routes.
1463
1464 A UI route is a React component that specifies the content to be shown in a new page in the Medusa Admin dashboard. You'll create a UI route to display the list of quotes in the Medusa Admin.
1465
1466 <Note>
1467
1468 Learn more about UI routes in the [UI Routes documentation](!docs!/learn/fundamentals/admin/ui-routes).
1469
1470 </Note>
1471
1472 ### Configure JS SDK
1473
1474 Medusa provides a [JS SDK](../../../js-sdk/page.mdx) that you can use to send requests to the Medusa server from any client application, including your Medusa Admin customizations.
1475
1476 The JS SDK is installed by default in your Medusa application. To configure it, create the file `src/admin/lib/sdk.ts` with the following content:
1477
1478 ![Directory structure after adding the sdk file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741098137/Medusa%20Resources/quote-23_plm90s.jpg)
1479
1480 ```ts title="src/admin/lib/sdk.ts"
1481 import Medusa from "@medusajs/js-sdk"
1482
1483 export const sdk = new Medusa({
1484 baseUrl: import.meta.env.VITE_BACKEND_URL || "/",
1485 debug: import.meta.env.DEV,
1486 auth: {
1487 type: "session",
1488 },
1489 })
1490 ```
1491
1492 You create an instance of the JS SDK using the `Medusa` class from the `@medusajs/js-sdk` package. You pass it an object having the following properties:
1493
1494 - `baseUrl`: The base URL of the Medusa server.
1495 - `debug`: A boolean indicating whether to log debug information.
1496 - `auth`: An object specifying the authentication type. When using the JS SDK for admin customizations, you use the `session` authentication type.
1497
1498 ### Add Admin Types
1499
1500 In your development, you'll need types that represents the data you'll retrieve from the Medusa server. So, create the file `src/admin/types.ts` with the following content:
1501
1502 ![Directory structure after adding the admin type](https://res.cloudinary.com/dza7lstvk/image/upload/v1741098478/Medusa%20Resources/quote-25_jr79pa.jpg)
1503
1504 ```ts title="src/admin/types.ts"
1505 import {
1506 AdminCustomer,
1507 AdminOrder,
1508 AdminUser,
1509 FindParams,
1510 PaginatedResponse,
1511 StoreCart,
1512 } from "@medusajs/framework/types"
1513
1514 export type AdminQuote = {
1515 id: string;
1516 status: string;
1517 draft_order_id: string;
1518 order_change_id: string;
1519 cart_id: string;
1520 customer_id: string;
1521 created_at: string;
1522 updated_at: string;
1523 draft_order: AdminOrder;
1524 cart: StoreCart;
1525 customer: AdminCustomer
1526 };
1527
1528 export interface QuoteQueryParams extends FindParams {}
1529
1530 export type AdminQuotesResponse = PaginatedResponse<{
1531 quotes: AdminQuote[];
1532 }>
1533
1534 export type AdminQuoteResponse = {
1535 quote: AdminQuote;
1536 };
1537 ```
1538
1539 You define the following types:
1540
1541 - `AdminQuote`: Represents a quote.
1542 - `QuoteQueryParams`: Represents the query parameters that can be passed when retrieving quotes.
1543 - `AdminQuotesResponse`: Represents the response when retrieving a list of quotes.
1544 - `AdminQuoteResponse`: Represents the response when retrieving a single quote, which you'll implement later in this guide.
1545
1546 You'll use these types in the rest of the customizations.
1547
1548 ### Create useQuotes Hook
1549
1550 When sending requests to the Medusa server from your admin customizations, it's recommended to use [Tanstack Query](https://tanstack.com/query/latest), allowing you to benefit from its caching and data fetching capabilities.
1551
1552 So, you'll create a `useQuotes` hook that uses Tanstack Query and the JS SDK to fetch the list of quotes from the Medusa server.
1553
1554 Create the file `src/admin/hooks/quotes.tsx` with the following content:
1555
1556 ![Directory structure after adding the hooks quotes file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741098244/Medusa%20Resources/quote-24_apdpem.jpg)
1557
1558 ```ts title="src/admin/hooks/quotes.tsx"
1559 import { ClientHeaders, FetchError } from "@medusajs/js-sdk"
1560 import {
1561 QuoteQueryParams,
1562 AdminQuotesResponse,
1563 } from "../types"
1564 import {
1565 QueryKey,
1566 useQuery,
1567 UseQueryOptions,
1568 } from "@tanstack/react-query"
1569 import { sdk } from "../lib/sdk"
1570
1571 export const useQuotes = (
1572 query: QuoteQueryParams,
1573 options?: UseQueryOptions<
1574 AdminQuotesResponse,
1575 FetchError,
1576 AdminQuotesResponse,
1577 QueryKey
1578 >
1579 ) => {
1580 const fetchQuotes = (query: QuoteQueryParams, headers?: ClientHeaders) =>
1581 sdk.client.fetch<AdminQuotesResponse>(`/admin/quotes`, {
1582 query,
1583 headers,
1584 })
1585
1586 const { data, ...rest } = useQuery({
1587 ...options,
1588 queryFn: () => fetchQuotes(query)!,
1589 queryKey: ["quote", "list"],
1590 })
1591
1592 return { ...data, ...rest }
1593 }
1594 ```
1595
1596 You define a `useQuotes` hook that accepts query parameters and optional options as a parameter. In the hook, you use the JS SDK's `client.fetch` method to retrieve the quotes from the `/admin/quotes` route.
1597
1598 You return the fetched data from the Medusa server. You'll use this hook in the UI route.
1599
1600 ### Create Quotes UI Route
1601
1602 You can now create the UI route that will show a new page in the Medusa Admin with the list of quotes.
1603
1604 UI routes are created in a `page.tsx` file under the `src/admin/routes` directory. The path of the UI route is the file's path relative to `src/admin/routes`.
1605
1606 So, to add the UI route at `/quotes` in the Medusa Admin, create the file `src/admin/routes/quotes/page.tsx` with the following content:
1607
1608 ![Directory structure after adding the Quotes UI route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741099122/Medusa%20Resources/quote-26_qrqzut.jpg)
1609
1610 ```tsx title="src/admin/routes/quotes/page.tsx"
1611 import { defineRouteConfig } from "@medusajs/admin-sdk"
1612 import { DocumentText } from "@medusajs/icons"
1613 import {
1614 Container, createDataTableColumnHelper, DataTable,
1615 DataTablePaginationState, Heading, Toaster, useDataTable,
1616 } from "@medusajs/ui"
1617 import { useNavigate } from "react-router-dom"
1618 import { useQuotes } from "../../hooks/quotes"
1619 import { AdminQuote } from "../../types"
1620 import { useState } from "react"
1621
1622 const Quotes = () => {
1623 // TODO implement page content
1624 }
1625
1626 export const config = defineRouteConfig({
1627 label: "Quotes",
1628 icon: DocumentText,
1629 })
1630
1631 export default Quotes
1632 ```
1633
1634 The route file must export a React component that implements the content of the page. To show a link to the route in the sidebar, you can also export a configuration object created with `defineRouteConfig` that specifies the label and icon of the route in the Medusa Admin sidebar.
1635
1636 In the `Quotes` component, you'll show a table of quotes using the [DataTable component](!ui!/components/data-table) from Medusa UI. This component requires you first define the columns of the table.
1637
1638 To define the table's columns, add in the same file and before the `Quotes` component the following:
1639
1640 ```tsx title="src/admin/routes/quotes/page.tsx"
1641 const StatusTitles: Record<string, string> = {
1642 accepted: "Accepted",
1643 customer_rejected: "Customer Rejected",
1644 merchant_rejected: "Merchant Rejected",
1645 pending_merchant: "Pending Merchant",
1646 pending_customer: "Pending Customer",
1647 }
1648
1649 const columnHelper = createDataTableColumnHelper<AdminQuote>()
1650
1651 const columns = [
1652 columnHelper.accessor("draft_order.display_id", {
1653 header: "ID",
1654 }),
1655 columnHelper.accessor("status", {
1656 header: "Status",
1657 cell: ({ getValue }) => StatusTitles[getValue()],
1658 }),
1659 columnHelper.accessor("customer.email", {
1660 header: "Email",
1661 }),
1662 columnHelper.accessor("draft_order.customer.first_name", {
1663 header: "First Name",
1664 }),
1665 columnHelper.accessor("draft_order.customer.company_name", {
1666 header: "Company Name",
1667 }),
1668 columnHelper.accessor("draft_order.total", {
1669 header: "Total",
1670 cell: ({ getValue, row }) =>
1671 `${row.original.draft_order.currency_code.toUpperCase()} ${getValue()}`,
1672 }),
1673 columnHelper.accessor("created_at", {
1674 header: "Created At",
1675 cell: ({ getValue }) => new Date(getValue()).toLocaleDateString(),
1676 }),
1677 ]
1678 ```
1679
1680 You use the `createDataTableColumnHelper` utility to create a function that allows you to define the columns of the table. Then, you create a `columns` array variable that defines the following columns:
1681
1682 1. `ID`: The display ID of the quote's draft order.
1683 2. `Status`: The status of the quote. Here, you use an object to map the status to a human-readable title.
1684 - The `cell` property of the second object passed to the `columnHelper.accessor` function allows you to customize how the cell is rendered.
1685 3. `Email`: The email of the customer.
1686 4. `First Name`: The first name of the customer.
1687 5. `Company Name`: The company name of the customer.
1688 6. `Total`: The total amount of the quote's draft order. You format it to include the currency code.
1689 7. `Created At`: The date the quote was created.
1690
1691 Next, you'll use these columns to render the `DataTable` component in the `Quotes` component.
1692
1693 Change the implementation of `Quotes` to the following:
1694
1695 ```tsx title="src/admin/routes/quotes/page.tsx"
1696 const Quotes = () => {
1697 const navigate = useNavigate()
1698 const [pagination, setPagination] = useState<DataTablePaginationState>({
1699 pageSize: 15,
1700 pageIndex: 0,
1701 })
1702
1703 const {
1704 quotes = [],
1705 count,
1706 isPending,
1707 } = useQuotes({
1708 limit: pagination.pageSize,
1709 offset: pagination.pageIndex * pagination.pageSize,
1710 fields:
1711 "+draft_order.total,*draft_order.customer",
1712 order: "-created_at",
1713 })
1714
1715 const table = useDataTable({
1716 columns,
1717 data: quotes,
1718 getRowId: (quote) => quote.id,
1719 rowCount: count,
1720 isLoading: isPending,
1721 pagination: {
1722 state: pagination,
1723 onPaginationChange: setPagination,
1724 },
1725 onRowClick(event, row) {
1726 navigate(`/quotes/${row.id}`)
1727 },
1728 })
1729
1730
1731 return (
1732 <>
1733 <Container className="flex flex-col p-0 overflow-hidden">
1734 <Heading className="p-6 pb-0 font-sans font-medium h1-core">
1735 Quotes
1736 </Heading>
1737
1738 <DataTable instance={table}>
1739 <DataTable.Toolbar>
1740 <Heading>Products</Heading>
1741 </DataTable.Toolbar>
1742 <DataTable.Table />
1743 <DataTable.Pagination />
1744 </DataTable>
1745 </Container>
1746 <Toaster />
1747 </>
1748 )
1749 }
1750 ```
1751
1752 In the component, you use the `useQuotes` hook to fetch the quotes from the Medusa server. You pass the following query parameters in the request:
1753
1754 - `limit` and `offset`: Pagination fields to specify the current page and the number of quotes to retrieve. These are based on the `pagination` state variable, which will be managed by the `DataTable` component.
1755 - `fields`: The fields to retrieve in the response. You specify the total amount of the draft order and the customer of the draft order. Since you prefix the fields with `+` and `*`, the fields are retrieved along with the default fields specified in the Query configurations.
1756 - `order`: The order in which to retrieve the quotes. Here, you retrieve the quotes in descending order of their creation date.
1757
1758 Next, you use the `useDataTable` hook to create a table instance with the columns you defined. You pass the fetched quotes to the `DataTable` component, along with configurations related to pagination and loading.
1759
1760 Notice that as part of the `useDataTable` configurations you navigate to the `/quotes/:id` UI route when a row is clicked. You'll create that route in a later step.
1761
1762 Finally, you render the `DataTable` component to display the quotes in a table.
1763
1764 ### Test List Quotes UI Route
1765
1766 You can now test out the UI route and the route added in the previous section from the Medusa Admin.
1767
1768 First, start the Medusa application:
1769
1770 ```bash npm2yarn
1771 npm run dev
1772 ```
1773
1774 Then, open the Medusa Admin dashboard at `http://localhost:9000/app` and login using the credentials you set up earlier.
1775
1776 You'll find a "Quotes" sidebar item. If you click on it, it will show you the table of quotes.
1777
1778 ![Medusa Admin dashboard displaying the Quotes management interface with a data table showing quote entries including columns for quote ID, customer information, status, and creation date](https://res.cloudinary.com/dza7lstvk/image/upload/v1741099952/Medusa%20Resources/Screenshot_2025-03-04_at_4.52.17_PM_nqxyfq.png)
1779
1780 ---
1781
1782 ## Step 8: Retrieve Quote API Route
1783
1784 Next, you'll add an admin API route to retrieve a single quote. You'll use this route in the next step to add a UI route to view a quote's details. You'll later expand on that UI route to allow the admin to manage the quote.
1785
1786 To add the API route, create the file `src/api/admin/quotes/[id]/route.ts` with the following content:
1787
1788 ![Directory structure after adding the single quote route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741100686/Medusa%20Resources/quote-27_ugvhbb.jpg)
1789
1790 ```ts title="src/api/admin/quotes/[id]/route.ts"
1791 import type {
1792 AuthenticatedMedusaRequest,
1793 MedusaResponse,
1794 } from "@medusajs/framework/http"
1795 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
1796
1797 export const GET = async (
1798 req: AuthenticatedMedusaRequest,
1799 res: MedusaResponse
1800 ) => {
1801 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
1802 const { id } = req.params
1803
1804 const {
1805 data: [quote],
1806 } = await query.graph(
1807 {
1808 entity: "quote",
1809 filters: { id },
1810 fields: req.queryConfig.fields,
1811 },
1812 { throwIfKeyNotFound: true }
1813 )
1814
1815 res.json({ quote })
1816 }
1817 ```
1818
1819 You export a `GET` route handler, which will create a `GET` API route at `/admin/quotes/:id`.
1820
1821 In the route handler, you resolve Query and use it to retrieve the quote. You pass the ID in the path parameter as a filter in Query. You also pass the query configuration fields, which are the same as the ones you've configured before, to retrieve the default fields and the fields specified in the query parameter.
1822
1823 <Note title="Tip">
1824
1825 Since you applied the middleware earlier to the `/admin/quotes*` route pattern, it will automatically apply to this route as well.
1826
1827 </Note>
1828
1829 You'll test this route in the next step as you create the UI route for a single quote.
1830
1831 ---
1832
1833 ## Step 9: Quote Details UI Route
1834
1835 In the Quotes List UI route, you configured the data table to navigate to a quote's page when you click on it in the table. Now that you have the API route to retrieve a single quote, you'll create the UI route that shows a quote's details.
1836
1837 ![Preview of the quote details page in Medusa Admin](https://res.cloudinary.com/dza7lstvk/image/upload/v1741158359/Medusa%20Resources/Screenshot_2025-03-05_at_9.05.45_AM_wfmb5w.png)
1838
1839 Before you create the UI route, you need to create the hooks necessary to retrieve data from the Medusa server, and some components that will show the different elements of the page.
1840
1841 ### Add Hooks
1842
1843 The first hook you'll add is a hook that will retrieve a quote using the API route you added in the previous step.
1844
1845 In `src/admin/hooks/quote.tsx`, add the following:
1846
1847 ```tsx title="src/admin/hooks/quote.tsx"
1848 // other imports...
1849 import { AdminQuoteResponse } from "../types"
1850
1851 // ...
1852
1853 export const useQuote = (
1854 id: string,
1855 query?: QuoteQueryParams,
1856 options?: UseQueryOptions<
1857 AdminQuoteResponse,
1858 FetchError,
1859 AdminQuoteResponse,
1860 QueryKey
1861 >
1862 ) => {
1863 const fetchQuote = (
1864 id: string,
1865 query?: QuoteQueryParams,
1866 headers?: ClientHeaders
1867 ) =>
1868 sdk.client.fetch<AdminQuoteResponse>(`/admin/quotes/${id}`, {
1869 query,
1870 headers,
1871 })
1872
1873 const { data, ...rest } = useQuery({
1874 queryFn: () => fetchQuote(id, query),
1875 queryKey: ["quote", id],
1876 ...options,
1877 })
1878
1879 return { ...data, ...rest }
1880 }
1881 ```
1882
1883 You define a `useQuote` hook that accepts the quote's ID and optional query parameters and options as parameters. In the hook, you use the JS SDK's `client.fetch` method to retrieve the quotes from the `/admin/quotes/:id` route.
1884
1885 The hook returns the fetched data from the Medusa server. You'll use this hook later in the UI route.
1886
1887 In addition, you'll need a hook to retrieve a preview of the quote's draft order. An order preview includes changes or edits to be applied on an order's items, such as changes in prices and quantities. Medusa already provides a [Get Order Preview API route](!api!/admin/orders/get-preview) that you can use to retrieve the preview.
1888
1889 To create the hook, create the file `src/admin/hooks/order-preview.tsx` with the following content:
1890
1891 ![Directory structure after adding the order preview hook file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741157692/Medusa%20Resources/quote-32_tb1tqw.jpg)
1892
1893 ```tsx title="src/admin/hooks/order-preview.tsx"
1894 import { HttpTypes } from "@medusajs/framework/types"
1895 import { FetchError } from "@medusajs/js-sdk"
1896 import { QueryKey, useQuery, UseQueryOptions } from "@tanstack/react-query"
1897 import { sdk } from "../lib/sdk"
1898
1899 export const orderPreviewQueryKey = "custom_orders"
1900
1901 export const useOrderPreview = (
1902 id: string,
1903 query?: HttpTypes.AdminOrderFilters,
1904 options?: Omit<
1905 UseQueryOptions<
1906 HttpTypes.AdminOrderPreviewResponse,
1907 FetchError,
1908 HttpTypes.AdminOrderPreviewResponse,
1909 QueryKey
1910 >,
1911 "queryFn" | "queryKey"
1912 >
1913 ) => {
1914 const { data, ...rest } = useQuery({
1915 queryFn: async () => sdk.admin.order.retrievePreview(id, query),
1916 queryKey: [orderPreviewQueryKey, id],
1917 ...options,
1918 })
1919
1920 return { ...data, ...rest }
1921 }
1922 ```
1923
1924 You add a `useOrderPreview` hook that accepts as parameters the order's ID, query parameters, and options. In the hook, you use the JS SDK's `admin.order.retrievePreview` method to retrieve the order preview and return it.
1925
1926 You'll use this hook later in the quote's details page.
1927
1928 ### Add formatAmount Utility
1929
1930 In the quote's details page, you'll display the amounts of the items in the quote. To format the amounts, you'll create a utility function that formats the amount based on the currency code.
1931
1932 Create the file `src/admin/utils/format-amount.ts` with the following content:
1933
1934 ![Directory structure after adding the format amount utility file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741157986/Medusa%20Resources/quote-33_k5sa9q.jpg)
1935
1936 ```ts title="src/admin/utils/format-amount.ts"
1937 export const formatAmount = (amount: number, currency_code: string) => {
1938 return new Intl.NumberFormat("en-US", {
1939 style: "currency",
1940 currency: currency_code,
1941 }).format(amount)
1942 }
1943 ```
1944
1945 You define a `formatAmount` function that accepts an amount and a currency code as parameters. The function uses the `Intl.NumberFormat` API to format the amount as a currency based on the currency code.
1946
1947 You'll use this function in the UI route and its components.
1948
1949 ### Create Amount Component
1950
1951 In the quote's details page, you want to display changes in amounts for items and totals. This is useful as you later add the capability to edit the price and quantity of items.
1952
1953 ![Diagram showcasing where this component will be in the page](https://res.cloudinary.com/dza7lstvk/image/upload/v1741183186/Medusa%20Resources/amount-highlighted_havznm.png)
1954
1955 To display changes in an amount, you'll create an `Amount` component and re-use it where necessary. So, create the file `src/admin/components/amount.tsx` with the following content:
1956
1957 ![Directory structure after adding the amount component](https://res.cloudinary.com/dza7lstvk/image/upload/v1741101819/Medusa%20Resources/quote-28_iwukg2.jpg)
1958
1959 ```tsx title="src/admin/components/amount.tsx"
1960 import { clx } from "@medusajs/ui"
1961 import { formatAmount } from "../utils/format-amount"
1962
1963 type AmountProps = {
1964 currencyCode: string;
1965 amount?: number | null;
1966 originalAmount?: number | null;
1967 align?: "left" | "right";
1968 className?: string;
1969 };
1970
1971 export const Amount = ({
1972 currencyCode,
1973 amount,
1974 originalAmount,
1975 align = "left",
1976 className,
1977 }: AmountProps) => {
1978 if (typeof amount === "undefined" || amount === null) {
1979 return (
1980 <div className="flex h-full w-full items-center">
1981 <span className="text-ui-fg-muted">-</span>
1982 </div>
1983 )
1984 }
1985
1986 const formatted = formatAmount(amount, currencyCode)
1987 const originalAmountPresent = typeof originalAmount === "number"
1988 const originalAmountDiffers = originalAmount !== amount
1989 const shouldShowAmountDiff = originalAmountPresent && originalAmountDiffers
1990
1991 return (
1992 <div
1993 className={clx(
1994 "flex h-full w-full items-center overflow-hidden",
1995 {
1996 "flex-col": shouldShowAmountDiff,
1997 "justify-start text-left": align === "left",
1998 "justify-end text-right": align === "right",
1999 },
2000 className
2001 )}
2002 >
2003 {shouldShowAmountDiff ? (
2004 <>
2005 <span className="truncate line-through text-xs">
2006 {formatAmount(originalAmount!, currencyCode)}
2007 </span>
2008 <span className="truncate text-blue-400 txt-small">{formatted}</span>
2009 </>
2010 ) : (
2011 <>
2012 <span className="truncate">{formatted}</span>
2013 </>
2014 )}
2015 </div>
2016 )
2017 }
2018 ```
2019
2020 In this component, you show the current amount of an item and, if it has been changed, you show previous amount as well.
2021
2022 You'll use this component in other components whenever you want to display any amount that can be changed.
2023
2024
2025 ### Create QuoteItems Component
2026
2027 In the quote's UI route, you want to display the details of the items in the quote. You'll create a separate component that you'll use within the UI route.
2028
2029 ![Screenshot showcasing where this component will be in the page](https://res.cloudinary.com/dza7lstvk/image/upload/v1741183303/Medusa%20Resources/item-highlighted-cropped_ddyikt.png)
2030
2031 Create the file `src/admin/components/quote-items.tsx` with the following content:
2032
2033 ![Directory structure after adding the quote items component](https://res.cloudinary.com/dza7lstvk/image/upload/v1741102170/Medusa%20Resources/quote-29_r5ljph.jpg)
2034
2035 ```tsx title="src/admin/components/quote-items.tsx"
2036 import {
2037 AdminOrder,
2038 AdminOrderLineItem,
2039 AdminOrderPreview,
2040 } from "@medusajs/framework/types"
2041 import { Badge, Text } from "@medusajs/ui"
2042 import { useMemo } from "react"
2043 import { Amount } from "./amount-cell"
2044
2045 export const QuoteItem = ({
2046 item,
2047 originalItem,
2048 currencyCode,
2049 }: {
2050 item: AdminOrderPreview["items"][0];
2051 originalItem?: AdminOrderLineItem;
2052 currencyCode: string;
2053 }) => {
2054
2055 const isItemUpdated = useMemo(
2056 () => !!item.actions?.find((a) => a.action === "ITEM_UPDATE"),
2057 [item]
2058 )
2059
2060 return (
2061 <div
2062 key={item.id}
2063 className="text-ui-fg-subtle grid grid-cols-2 items-center gap-x-4 px-6 py-4 text-left"
2064 >
2065 <div className="flex items-start gap-x-4">
2066 <div>
2067 <Text
2068 size="small"
2069 leading="compact"
2070 weight="plus"
2071 className="text-ui-fg-base"
2072 >
2073 {item.title}
2074 </Text>
2075
2076 {item.variant_sku && (
2077 <div className="flex items-center gap-x-1">
2078 <Text size="small">{item.variant_sku}</Text>
2079 </div>
2080 )}
2081 <Text size="small">
2082 {item.variant?.options?.map((o) => o.value).join(" · ")}
2083 </Text>
2084 </div>
2085 </div>
2086
2087 <div className="grid grid-cols-3 items-center gap-x-4">
2088 <div className="flex items-center justify-end gap-x-4">
2089 <Amount
2090 className="text-sm text-right justify-end items-end"
2091 currencyCode={currencyCode}
2092 // @ts-ignore
2093 amount={item.detail.unit_price}
2094 originalAmount={item.unit_price}
2095 />
2096 </div>
2097
2098 <div className="flex items-center gap-x-2">
2099 <div className="w-fit min-w-[27px]">
2100 <Badge size="xsmall" color="grey">
2101 <span className="tabular-nums text-xs">{item.quantity}</span>x
2102 </Badge>
2103 </div>
2104
2105 <div>
2106
2107 {isItemUpdated && (
2108 <Badge
2109 size="2xsmall"
2110 rounded="full"
2111 color="orange"
2112 className="mr-1"
2113 >
2114 Modified
2115 </Badge>
2116 )}
2117 </div>
2118
2119 <div className="overflow-visible"></div>
2120 </div>
2121
2122 <Amount
2123 className="text-sm text-right justify-end items-end"
2124 currencyCode={currencyCode}
2125 amount={item.total}
2126 originalAmount={originalItem?.total}
2127 />
2128 </div>
2129 </div>
2130 )
2131 }
2132 ```
2133
2134 You first define the component for one quote item. In the component, you show the item's title, variant SKU, and quantity. You also use the `Amount` component to show the item's current and previous amounts.
2135
2136 Next, add to the same file the `QuoteItems` component:
2137
2138 ```tsx title="src/admin/components/quote-items.tsx"
2139 export const QuoteItems = ({
2140 order,
2141 preview,
2142 }: {
2143 order: AdminOrder;
2144 preview: AdminOrderPreview;
2145 }) => {
2146 const itemsMap = useMemo(() => {
2147 return new Map(order.items.map((item) => [item.id, item]))
2148 }, [order])
2149
2150 return (
2151 <div>
2152 {preview.items?.map((item) => {
2153 return (
2154 <QuoteItem
2155 key={item.id}
2156 item={item}
2157 originalItem={itemsMap.get(item.id)}
2158 currencyCode={order.currency_code}
2159 />
2160 )
2161 })}
2162 </div>
2163 )
2164 }
2165 ```
2166
2167 In this component, you loop over the order's items and show each of them using the `QuoteItem` component.
2168
2169 ### Create TotalsBreakdown Component
2170
2171 Another component you'll need in the quote's UI route is a component that breaks down the totals of the quote's draft order, such as its discount or shipping totals.
2172
2173 ![Screenshot showcasing where this component will be in the page](https://res.cloudinary.com/dza7lstvk/image/upload/v1741183481/Medusa%20Resources/totals-highlighted_hpxier.png)
2174
2175 Create the file `src/admin/components/totals-breakdown.tsx` with the following content:
2176
2177 ![Directory structure after adding the totals breakdown component](https://res.cloudinary.com/dza7lstvk/image/upload/v1741155757/Medusa%20Resources/quote-30_de0kjq.jpg)
2178
2179 ```tsx title="src/admin/components/totals-breakdown.tsx"
2180 import { AdminOrder } from "@medusajs/framework/types"
2181 import { Text } from "@medusajs/ui"
2182 import { ReactNode } from "react"
2183 import { formatAmount } from "../utils/format-amount"
2184
2185 export const Total = ({
2186 label,
2187 value,
2188 secondaryValue,
2189 tooltip,
2190 }: {
2191 label: string;
2192 value: string | number;
2193 secondaryValue: string;
2194 tooltip?: ReactNode;
2195 }) => (
2196 <div className="grid grid-cols-3 items-center">
2197 <Text size="small" leading="compact">
2198 {label} {tooltip}
2199 </Text>
2200 <div className="text-right">
2201 <Text size="small" leading="compact">
2202 {secondaryValue}
2203 </Text>
2204 </div>
2205
2206 <div className="text-right">
2207 <Text size="small" leading="compact">
2208 {value}
2209 </Text>
2210 </div>
2211 </div>
2212 )
2213 ```
2214
2215 You first define the `Total` component, which breaksdown a total item, such as discount. You'll use this component to breakdown the different totals in the `TotalsBreakdown` component.
2216
2217 Add the `TotalsBreakdown` component after the `Total` component:
2218
2219 ```tsx title="src/admin/components/totals-breakdown.tsx"
2220 export const TotalsBreakdown = ({ order }: { order: AdminOrder }) => {
2221 return (
2222 <div className="text-ui-fg-subtle flex flex-col gap-y-2 px-6 py-4">
2223 <Total
2224 label="Discounts"
2225 secondaryValue=""
2226 value={
2227 order.discount_total > 0
2228 ? `- ${formatAmount(order.discount_total, order.currency_code)}`
2229 : "-"
2230 }
2231 />
2232 {(order.shipping_methods || [])
2233 .sort((m1, m2) =>
2234 (m1.created_at as string).localeCompare(m2.created_at as string)
2235 )
2236 .map((sm, i) => {
2237 return (
2238 <div key={i}>
2239 <Total
2240 key={sm.id}
2241 label={"Shipping"}
2242 secondaryValue={sm.name}
2243 value={formatAmount(sm.total, order.currency_code)}
2244 />
2245 </div>
2246 )
2247 })}
2248 </div>
2249 )
2250 }
2251 ```
2252
2253 In this component, you show the different totals of the quote's draft order, such as discounts and shipping totals. You use the `Total` component to show each total item.
2254
2255 ### Create Quote Details UI Route
2256
2257 You can now create the UI route that will show a quote's details in the Medusa Admin.
2258
2259 Create the file `src/admin/routes/quote/[id]/page.tsx` with the following content:
2260
2261 ![Diagram showcasing the directory structure after adding the quote details UI route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741157385/Medusa%20Resources/quote-31_grwlon.jpg)
2262
2263 export const quotesDetailsHighlights = [
2264 ["21", "useQuote", "Retrieve the quote's details from the Medusa server."],
2265 ["26", "useOrderPreview", "Retrieve the preview of the quote's draft order."]
2266 ]
2267
2268 ```tsx title="src/admin/routes/quote/[id]/page.tsx" highlights={quotesDetailsHighlights}
2269 import { CheckCircleSolid } from "@medusajs/icons"
2270 import {
2271 Button,
2272 Container,
2273 Heading,
2274 Text,
2275 Toaster,
2276 } from "@medusajs/ui"
2277 import { Link, useNavigate, useParams } from "react-router-dom"
2278 import { useOrderPreview } from "../../../hooks/order-preview"
2279 import {
2280 useQuote,
2281 } from "../../../hooks/quotes"
2282 import { QuoteItems } from "../../../components/quote-items"
2283 import { TotalsBreakdown } from "../../../components/totals-breakdown"
2284 import { formatAmount } from "../../../utils/format-amount"
2285
2286 const QuoteDetails = () => {
2287 const { id } = useParams()
2288 const navigate = useNavigate()
2289 const { quote, isLoading } = useQuote(id!, {
2290 fields:
2291 "*draft_order.customer",
2292 })
2293
2294 const { order: preview, isLoading: isPreviewLoading } = useOrderPreview(
2295 quote?.draft_order_id!,
2296 {},
2297 { enabled: !!quote?.draft_order_id }
2298 )
2299
2300 if (isLoading || !quote) {
2301 return <></>
2302 }
2303
2304 if (isPreviewLoading) {
2305 return <></>
2306 }
2307
2308 if (!isPreviewLoading && !preview) {
2309 throw "preview not found"
2310 }
2311
2312 // TODO render content
2313 }
2314
2315 export default QuoteDetails
2316 ```
2317
2318 The `QuoteDetails` component will render the content of the quote's details page. So far, you retrieve the quote and its preview using the hooks you created earlier. You also render empty components or an error message if the data is still loading or not found.
2319
2320 To add the rendered content, replace the `TODO` with the following:
2321
2322 ```tsx title="src/admin/routes/quote/[id]/page.tsx"
2323 return (
2324 <div className="flex flex-col gap-y-3">
2325 <div className="flex flex-col gap-x-4 lg:flex-row xl:items-start">
2326 <div className="flex w-full flex-col gap-y-3">
2327 {quote.status === "accepted" && (
2328 <Container className="divide-y divide-dashed p-0">
2329 <div className="flex items-center justify-between px-6 py-4">
2330 <Text className="txt-compact-small">
2331 <CheckCircleSolid className="inline-block mr-2 text-green-500 text-lg" />
2332 Quote accepted by customer. Order is ready for processing.
2333 </Text>
2334
2335 <Button
2336 size="small"
2337 onClick={() => navigate(`/orders/${quote.draft_order_id}`)}
2338 >
2339 View Order
2340 </Button>
2341 </div>
2342 </Container>
2343 )}
2344
2345 <Container className="divide-y divide-dashed p-0">
2346 <div className="flex items-center justify-between px-6 py-4">
2347 <Heading level="h2">Quote Summary</Heading>
2348 </div>
2349 <QuoteItems order={quote.draft_order} preview={preview!} />
2350 <TotalsBreakdown order={quote.draft_order} />
2351 <div className=" flex flex-col gap-y-2 px-6 py-4">
2352 <div className="text-ui-fg-base flex items-center justify-between">
2353 <Text
2354 weight="plus"
2355 className="text-ui-fg-subtle"
2356 size="small"
2357 leading="compact"
2358 >
2359 Original Total
2360 </Text>
2361 <Text
2362 weight="plus"
2363 className="text-ui-fg-subtle"
2364 size="small"
2365 leading="compact"
2366 >
2367 {formatAmount(quote.draft_order.total, quote.draft_order.currency_code)}
2368 </Text>
2369 </div>
2370
2371 <div className="text-ui-fg-base flex items-center justify-between">
2372 <Text
2373 className="text-ui-fg-subtle text-semibold"
2374 size="small"
2375 leading="compact"
2376 weight="plus"
2377 >
2378 Quote Total
2379 </Text>
2380 <Text
2381 className="text-ui-fg-subtle text-bold"
2382 size="small"
2383 leading="compact"
2384 weight="plus"
2385 >
2386 {formatAmount(preview!.summary.current_order_total, quote.draft_order.currency_code)}
2387 </Text>
2388 </div>
2389 </div>
2390
2391 {/* TODO add actions later */}
2392 </Container>
2393
2394 </div>
2395
2396 <div className="mt-2 flex w-full max-w-[100%] flex-col gap-y-3 xl:mt-0 xl:max-w-[400px]">
2397 <Container className="divide-y p-0">
2398 <div className="flex items-center justify-between px-6 py-4">
2399 <Heading level="h2">Customer</Heading>
2400 </div>
2401
2402 <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4">
2403 <Text size="small" weight="plus" leading="compact">
2404 Email
2405 </Text>
2406
2407 <Link
2408 className="text-sm text-pretty text-blue-500"
2409 to={`/customers/${quote.draft_order?.customer?.id}`}
2410 onClick={(e) => e.stopPropagation()}
2411 >
2412 {quote.draft_order?.customer?.email}
2413 </Link>
2414 </div>
2415 </Container>
2416 </div>
2417 </div>
2418
2419 <Toaster />
2420 </div>
2421 )
2422 ```
2423
2424 You first check if the quote has been accepted by the customer, and show a banner to view the created order if so.
2425
2426 Next, you use the `QuoteItems` and `TotalsBreakdown` components that you created to show the quote's items and totals. You also show the original and current totals of the quote, where the original total is the total of the draft order before any changes are made to its items.
2427
2428 Finally, you show the customer's email and a link to view their details.
2429
2430 ### Test Quote Details UI Route
2431
2432 To test the quote details UI route, start the Medusa application:
2433
2434 ```bash npm2yarn
2435 npm run dev
2436 ```
2437
2438 Then, open the Medusa Admin dashboard at `http://localhost:9000/app` and login using the credentials you set up earlier.
2439
2440 Next, click on Quotes in the sidebar, which will open the list of quotes UI route you created earlier. Click on one of the quotes to view its details page.
2441
2442 On the quote's details page, you can see the quote's items, its totals, and the customer's details. In the next steps, you'll add management features to the page.
2443
2444 ![Quote details page in Medusa Admin](https://res.cloudinary.com/dza7lstvk/image/upload/v1741158359/Medusa%20Resources/Screenshot_2025-03-05_at_9.05.45_AM_wfmb5w.png)
2445
2446 ---
2447
2448 ## Step 10: Add Merchant Reject Quote Feature
2449
2450 After the merchant or admin views the quote, they can choose to either reject it, send the quote back to the customer to review it, or make changes to the quote's prices and quantities.
2451
2452 In this step, you'll implement the functionality to reject a quote from the quote's details page. This will include:
2453
2454 1. Implementing the workflow to reject a quote.
2455 2. Adding the API route to reject a quote that uses the workflow.
2456 3. Add a hook in admin customizations that sends a request to the reject quote API route.
2457 4. Add a button to reject the quote in the quote's details page.
2458
2459 ### Implement Merchant Reject Quote Workflow
2460
2461 To reject a quote, you'll need to create a workflow that will handle the rejection process. The workflow has the following steps:
2462
2463 <WorkflowDiagram
2464 workflow={{
2465 name: "merchantRejectQuoteWorkflow",
2466 steps: [
2467 {
2468 type: "step",
2469 name: "useQueryGraphStep",
2470 description: "Retrieve the quote's details.",
2471 link: "/references/helper-steps/useQueryGraphStep",
2472 depth: 1
2473 },
2474 {
2475 type: "step",
2476 name: "validateQuoteNotAccepted",
2477 description: "Validate that the quote isn't already accepted by the customer.",
2478 depth: 1
2479 },
2480 {
2481 type: "step",
2482 name: "updateQuoteStatusStep",
2483 description: "Update the quote's status to `merchant_rejected`.",
2484 depth: 1
2485 }
2486 ]
2487 }}
2488 hideLegend
2489 />
2490
2491 As mentioned before, the `useQueryGraphStep` is provided by Medusa's `@medusajs/medusa/core-flows` package. So, you'll only implement the remaining steps.
2492
2493 #### validateQuoteNotAccepted
2494
2495 The second step of the merchant rejection workflow ensures that a quote isn't already accepted, as it can't be rejected afterwards.
2496
2497 To create the step, create the file `src/workflows/steps/validate-quote-not-accepted.ts` with the following content:
2498
2499 ![Diagram showcasing the directory structure after adding the validate quote rejection step file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741159537/Medusa%20Resources/quote-34_mtcxwa.jpg)
2500
2501 ```ts title="src/workflows/steps/validate-quote-not-accepted.ts"
2502 import { MedusaError } from "@medusajs/framework/utils"
2503 import { createStep } from "@medusajs/framework/workflows-sdk"
2504 import { InferTypeOf } from "@medusajs/framework/types"
2505 import { Quote, QuoteStatus } from "../../modules/quote/models/quote"
2506
2507 type StepInput = {
2508 quote: InferTypeOf<typeof Quote>
2509 }
2510
2511 export const validateQuoteNotAccepted = createStep(
2512 "validate-quote-not-accepted",
2513 async function ({ quote }: StepInput) {
2514 if (quote.status === QuoteStatus.ACCEPTED) {
2515 throw new MedusaError(
2516 MedusaError.Types.INVALID_DATA,
2517 `Quote is already accepted by customer`
2518 )
2519 }
2520 }
2521 )
2522 ```
2523
2524 You create a step that accepts a quote as an input and throws an error if the quote's status is `accepted`, as you can't reject a quote that has been accepted by the customer.
2525
2526 #### updateQuoteStatusStep
2527
2528 In the last step of the workflow, you'll change the workflow's status to `merchant_rejected`. So, you'll create a step that can be used to update a quote's status.
2529
2530 Create the file `src/workflows/steps/update-quotes.ts` with the following content:
2531
2532 ![Diagram showcasing the directory structure after adding the update quotes step file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741159754/Medusa%20Resources/quote-35_moaulz.jpg)
2533
2534 ```ts title="src/workflows/steps/update-quotes.ts"
2535 import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
2536 import { QUOTE_MODULE } from "../../modules/quote"
2537 import { QuoteStatus } from "../../modules/quote/models/quote"
2538 import QuoteModuleService from "../../modules/quote/service"
2539
2540 type StepInput = {
2541 id: string;
2542 status?: QuoteStatus;
2543 }[]
2544
2545 export const updateQuotesStep = createStep(
2546 "update-quotes",
2547 async (data: StepInput, { container }) => {
2548 const quoteModuleService: QuoteModuleService = container.resolve(
2549 QUOTE_MODULE
2550 )
2551
2552 const dataBeforeUpdate = await quoteModuleService.listQuotes(
2553 { id: data.map((d) => d.id) }
2554 )
2555
2556 const updatedQuotes = await quoteModuleService.updateQuotes(data)
2557
2558 return new StepResponse(updatedQuotes, {
2559 dataBeforeUpdate,
2560 })
2561 },
2562 async (revertInput, { container }) => {
2563 if (!revertInput) {
2564 return
2565 }
2566
2567 const quoteModuleService: QuoteModuleService = container.resolve(
2568 QUOTE_MODULE
2569 )
2570
2571 await quoteModuleService.updateQuotes(
2572 revertInput.dataBeforeUpdate
2573 )
2574 }
2575 )
2576 ```
2577
2578 This step accepts an array of quotes to update their status. In the step function, you resolve the Quote Module's service. Then, you retrieve the quotes' original data so that you can pass them to the compensation function. Finally, you update the quotes' data and return the updated quotes.
2579
2580 In the compensation function, you resolve the Quote Module's service and update the quotes with their original data.
2581
2582 #### Implement Workflow
2583
2584 You can now implement the merchant-rejection workflow. Create the file `src/workflows/merchant-reject-quote.ts` with the following content:
2585
2586 ![Diagram showcasing the directory structure after adding the merchant reject quote workflow file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741159969/Medusa%20Resources/quote-36_l1ffxm.jpg)
2587
2588 export const merchantRejectionWorkflowHighlights = [
2589 ["14", "useQueryGraphStep", "Retrieve the quote's details."],
2590 ["23", "validateQuoteNotAccepted", "Validate that the quote isn't already accepted by the customer."],
2591 ["28", "updateQuotesStep", "Update the quote's status to `merchant_rejected`."]
2592 ]
2593
2594 ```ts title="src/workflows/merchant-reject-quote.ts" highlights={merchantRejectionWorkflowHighlights}
2595 import { useQueryGraphStep } from "@medusajs/core-flows"
2596 import { createWorkflow } from "@medusajs/framework/workflows-sdk"
2597 import { QuoteStatus } from "../modules/quote/models/quote"
2598 import { validateQuoteNotAccepted } from "./steps/validate-quote-not-accepted"
2599 import { updateQuotesStep } from "./steps/update-quotes"
2600
2601 type WorkflowInput = {
2602 quote_id: string;
2603 }
2604
2605 export const merchantRejectQuoteWorkflow = createWorkflow(
2606 "merchant-reject-quote-workflow",
2607 (input: WorkflowInput) => {
2608 const { data: quotes } = useQueryGraphStep({
2609 entity: "quote",
2610 fields: ["id", "status"],
2611 filters: { id: input.quote_id },
2612 options: {
2613 throwIfKeyNotFound: true,
2614 },
2615 })
2616
2617 validateQuoteNotAccepted({
2618 // @ts-ignore
2619 quote: quotes[0],
2620 })
2621
2622 updateQuotesStep([
2623 {
2624 id: input.quote_id,
2625 status: QuoteStatus.MERCHANT_REJECTED,
2626 },
2627 ])
2628 }
2629 )
2630 ```
2631
2632 You create a workflow that accepts the ID of a quote to reject. In the workflow, you:
2633
2634 1. Use the `useQueryGraphStep` to retrieve the quote's details.
2635 2. Validate that the quote isn't already accepted using the `validateQuoteNotAccepted`.
2636 3. Update the quote's status to `merchant_rejected` using the `updateQuotesStep`.
2637
2638 You'll use this workflow next in an API route that allows a merchant to reject a quote.
2639
2640 ### Add Admin Reject Quote API Route
2641
2642 You'll now add the API route that allows a merchant to reject a quote. The route will use the `merchantRejectQuoteWorkflow` you created in the previous step.
2643
2644 Create the file `src/api/admin/quotes/[id]/reject/route.ts` with the following content:
2645
2646 ![Diagram showcasing the directory structure after adding the reject quote API route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741160251/Medusa%20Resources/quote-37_jwlfcw.jpg)
2647
2648 ```ts title="src/api/admin/quotes/[id]/reject/route.ts"
2649 import type {
2650 AuthenticatedMedusaRequest,
2651 MedusaResponse,
2652 } from "@medusajs/framework/http"
2653 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
2654 import { merchantRejectQuoteWorkflow } from "../../../../../workflows/merchant-reject-quote"
2655
2656 export const POST = async (
2657 req: AuthenticatedMedusaRequest,
2658 res: MedusaResponse
2659 ) => {
2660 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
2661 const { id } = req.params
2662
2663 await merchantRejectQuoteWorkflow(req.scope).run({
2664 input: {
2665 quote_id: id,
2666 },
2667 })
2668
2669 const {
2670 data: [quote],
2671 } = await query.graph(
2672 {
2673 entity: "quote",
2674 filters: { id },
2675 fields: req.queryConfig.fields,
2676 },
2677 { throwIfKeyNotFound: true }
2678 )
2679
2680 res.json({ quote })
2681 }
2682 ```
2683
2684 You create a `POST` route handler, which will expose a `POST` API route at `/admin/quotes/:id/reject`. In the route handler, you run the `merchantRejectQuoteWorkflow` with the quote's ID as input. You then retrieve the updated quote using Query and return it in the response.
2685
2686 Notice that you can pass `req.queryConfig.fields` to the `query.graph` method because you've applied the `validateAndTransformQuery` middleware before to all routes starting with `/admin/quotes`.
2687
2688 ### Add Reject Quote Hook
2689
2690 Now that you have the API route, you can add a React hook in the admin customizations that sends a request to the route to reject a quote.
2691
2692 In `src/admin/hooks/quotes.tsx` add the following new hook:
2693
2694 ```tsx title="src/admin/hooks/quotes.tsx"
2695 // other imports...
2696 import {
2697 useMutation,
2698 UseMutationOptions,
2699 } from "@tanstack/react-query"
2700
2701 // ...
2702
2703 export const useRejectQuote = (
2704 id: string,
2705 options?: UseMutationOptions<AdminQuoteResponse, FetchError, void>
2706 ) => {
2707 const queryClient = useQueryClient()
2708
2709 const rejectQuote = async (id: string) =>
2710 sdk.client.fetch<AdminQuoteResponse>(`/admin/quotes/${id}/reject`, {
2711 method: "POST",
2712 })
2713
2714 return useMutation({
2715 mutationFn: () => rejectQuote(id),
2716 onSuccess: (data: AdminQuoteResponse, variables: any, context: any) => {
2717 queryClient.invalidateQueries({
2718 queryKey: [orderPreviewQueryKey, id],
2719 })
2720
2721 queryClient.invalidateQueries({
2722 queryKey: ["quote", id],
2723 })
2724
2725 queryClient.invalidateQueries({
2726 queryKey: ["quote", "list"],
2727 })
2728
2729 options?.onSuccess?.(data, variables, context)
2730 },
2731 ...options,
2732 })
2733 }
2734 ```
2735
2736 You add a `useRejectQuote` hook that accepts the quote's ID and optional options as parameters. In the hook, you use the `useMutation` hook to define the mutation action that sends a request to the reject quote API route.
2737
2738 When the mutation is invoked, the hook sends a request to the API route to reject the quote, then invalidates all data related to the quote in the query client, which will trigger a re-fetch of the data.
2739
2740 ### Add Reject Quote Button
2741
2742 Finally, you can add a button to the quote's details page that allows a merchant to reject the quote.
2743
2744 In `src/admin/routes/quote/[id]/page.tsx`, add the following imports:
2745
2746 ```tsx title="src/admin/routes/quote/[id]/page.tsx"
2747 import {
2748 toast,
2749 usePrompt,
2750 } from "@medusajs/ui"
2751 import { useEffect, useState } from "react"
2752 import {
2753 useRejectQuote,
2754 } from "../../../hooks/quotes"
2755 ```
2756
2757 Then, in the `QuoteDetails` component, add the following after the `useOrderPreview` hook usage:
2758
2759 ```tsx title="src/admin/routes/quote/[id]/page.tsx"
2760 const prompt = usePrompt()
2761 const { mutateAsync: rejectQuote, isPending: isRejectingQuote } =
2762 useRejectQuote(id!)
2763 const [showRejectQuote, setShowRejectQuote] = useState(false)
2764
2765 useEffect(() => {
2766 if (
2767 ["customer_rejected", "merchant_rejected", "accepted"].includes(
2768 quote?.status!
2769 )
2770 ) {
2771 setShowRejectQuote(false)
2772 } else {
2773 setShowRejectQuote(true)
2774 }
2775 }, [quote])
2776
2777 const handleRejectQuote = async () => {
2778 const res = await prompt({
2779 title: "Reject quote?",
2780 description:
2781 "You are about to reject this customer's quote. Do you want to continue?",
2782 confirmText: "Continue",
2783 cancelText: "Cancel",
2784 variant: "confirmation",
2785 })
2786
2787 if (res) {
2788 await rejectQuote(void 0, {
2789 onSuccess: () =>
2790 toast.success("Successfully rejected customer's quote"),
2791 onError: (e) => toast.error(e.message),
2792 })
2793 }
2794 }
2795 ```
2796
2797 First, you initialize the following variables:
2798
2799 1. `prompt`: A function that you'll use to show a confirmation pop-up when the merchant tries to reject the quote. The `usePrompt` hook is available from the Medusa UI package.
2800 2. `rejectQuote` and `isRejectingQuote`: both are returned by the `useRejectQuote` hook. The `rejectQuote` function invokes the mutation, rejecting the quote; `isRejectingQuote` is a boolean that indicates if the mutation is in progress.
2801 3. `showRejectQuote`: A boolean that indicates whether the "Reject Quote" button should be shown. The button is shown if the quote's status is not `customer_rejected`, `merchant_rejected`, or `accepted`. This state variable is changed based on the quote's status in the `useEffect` hook.
2802
2803 You also define a `handleRejectQuote` function that will be called when the merchant clicks the reject quote button. The function shows a confirmation pop-up using the `prompt` function. If the user confirms the action, the function calls the `rejectQuote` function to reject the quote.
2804
2805 Finally, find the `TODO` in the `return` statement and replace it with the following:
2806
2807 ```tsx title="src/admin/routes/quote/[id]/page.tsx"
2808 <div className="bg-ui-bg-subtle flex items-center justify-end gap-x-2 rounded-b-xl px-4 py-4">
2809 {showRejectQuote && (
2810 <Button
2811 size="small"
2812 variant="secondary"
2813 onClick={() => handleRejectQuote()}
2814 disabled={isRejectingQuote}
2815 >
2816 Reject Quote
2817 </Button>
2818 )}
2819 </div>
2820 ```
2821
2822 In this code snippet, you show the reject quote button if the `showRejectQuote` state is `true`. When the button is clicked, you call the `handleRejectQuote` function to reject the quote.
2823
2824 ### Test Reject Quote Feature
2825
2826 To test the reject quote feature, start the Medusa application:
2827
2828 ```bash npm2yarn
2829 npm run dev
2830 ```
2831
2832 Then, open the Medusa Admin dashboard at `http://localhost:9000/app` and login using the credentials you set up earlier.
2833
2834 Next, open a quote's details page. You'll find a new "Reject Quote" button. If you click on it and confirm rejecting the quote, the quote will be rejected, and a success message will be shown.
2835
2836 ![Quote details page with reject quote button in Medusa Admin](https://res.cloudinary.com/dza7lstvk/image/upload/v1741161544/Medusa%20Resources/Screenshot_2025-03-05_at_9.58.41_AM_xzdv6k.png)
2837
2838 ---
2839
2840 ## Step 11: Add Merchant Send Quote Feature
2841
2842 Another action that a merchant can take on a quote is to send the quote back to the customer for review. The customer can then reject or accept the quote, which would convert it to an order.
2843
2844 In this step, you'll implement the functionality to send a quote back to the customer for review. This will include:
2845
2846 1. Implementing the workflow to send a quote back to the customer.
2847 2. Adding the API route to send a quote back to the customer that uses the workflow.
2848 3. Add a hook in admin customizations that sends a request to the send quote API route.
2849 4. Add a button to send the quote back to the customer in the quote's details page.
2850
2851 ### Implement Merchant Send Quote Workflow
2852
2853 You'll implement the logic of sending the quote in a workflow. The workflow has the following steps:
2854
2855 <WorkflowDiagram
2856 workflow={{
2857 name: "merchantSendQuoteWorkflow",
2858 steps: [
2859 {
2860 type: "step",
2861 name: "useQueryGraphStep",
2862 description: "Retrieve the quote's details.",
2863 link: "/references/helper-steps/useQueryGraphStep",
2864 depth: 1
2865 },
2866 {
2867 type: "step",
2868 name: "validateQuoteNotAccepted",
2869 description: "Validate that the quote isn't already accepted by the customer.",
2870 depth: 1
2871 },
2872 {
2873 type: "step",
2874 name: "updateQuoteStatusStep",
2875 description: "Update the quote's status to `pending_customer`.",
2876 depth: 1
2877 }
2878 ]
2879 }}
2880 hideLegend
2881 />
2882
2883 All the steps are available for use, so you can implement the workflow directly.
2884
2885 Create the file `src/workflows/merchant-send-quote.ts` with the following content:
2886
2887 ![Directory structure after adding the merchant send quote workflow file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741162342/Medusa%20Resources/quote-38_n4ksr0.jpg)
2888
2889 export const sendQuoteHighlights = [
2890 ["14", "useQueryGraphStep", "Retrieve the quote's details."],
2891 ["23", "validateQuoteNotAccepted", "Validate that the quote isn't already accepted by the customer."],
2892 ["28", "updateQuotesStep", "Update the quote's status to `pending_customer`."]
2893 ]
2894
2895 ```ts title="src/workflows/merchant-send-quote.ts" highlights={sendQuoteHighlights}
2896 import { useQueryGraphStep } from "@medusajs/core-flows"
2897 import { createWorkflow } from "@medusajs/framework/workflows-sdk"
2898 import { QuoteStatus } from "../modules/quote/models/quote"
2899 import { updateQuotesStep } from "./steps/update-quotes"
2900 import { validateQuoteNotAccepted } from "./steps/validate-quote-not-accepted"
2901
2902 type WorkflowInput = {
2903 quote_id: string;
2904 }
2905
2906 export const merchantSendQuoteWorkflow = createWorkflow(
2907 "merchant-send-quote-workflow",
2908 (input: WorkflowInput) => {
2909 const { data: quotes } = useQueryGraphStep({
2910 entity: "quote",
2911 fields: ["id", "status"],
2912 filters: { id: input.quote_id },
2913 options: {
2914 throwIfKeyNotFound: true,
2915 },
2916 })
2917
2918 validateQuoteNotAccepted({
2919 // @ts-ignore
2920 quote: quotes[0],
2921 })
2922
2923 updateQuotesStep([
2924 {
2925 id: input.quote_id,
2926 status: QuoteStatus.PENDING_CUSTOMER,
2927 },
2928 ])
2929 }
2930 )
2931 ```
2932
2933 You create a workflow that accepts the ID of a quote to send back to the customer. In the workflow, you:
2934
2935 1. Use the `useQueryGraphStep` to retrieve the quote's details.
2936 2. Validate that the quote can be sent back to the customer using the `validateQuoteNotAccepted` step.
2937 3. Update the quote's status to `pending_customer` using the `updateQuotesStep`.
2938
2939 You'll use this workflow next in an API route that allows a merchant to send a quote back to the customer.
2940
2941 ### Add Send Quote API Route
2942
2943 You'll now add the API route that allows a merchant to send a quote back to the customer. The route will use the `merchantSendQuoteWorkflow` you created in the previous step.
2944
2945 Create the file `src/api/admin/quotes/[id]/send/route.ts` with the following content:
2946
2947 ![Directory structure after adding the send quote API route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741162497/Medusa%20Resources/quote-39_us1jbh.jpg)
2948
2949 ```ts title="src/api/admin/quotes/[id]/send/route.ts"
2950 import type {
2951 AuthenticatedMedusaRequest,
2952 MedusaResponse,
2953 } from "@medusajs/framework/http"
2954 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
2955 import {
2956 merchantSendQuoteWorkflow,
2957 } from "../../../../../workflows/merchant-send-quote"
2958
2959 export const POST = async (
2960 req: AuthenticatedMedusaRequest,
2961 res: MedusaResponse
2962 ) => {
2963 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
2964 const { id } = req.params
2965
2966 await merchantSendQuoteWorkflow(req.scope).run({
2967 input: {
2968 quote_id: id,
2969 },
2970 })
2971
2972 const {
2973 data: [quote],
2974 } = await query.graph(
2975 {
2976 entity: "quote",
2977 filters: { id },
2978 fields: req.queryConfig.fields,
2979 },
2980 { throwIfKeyNotFound: true }
2981 )
2982
2983 res.json({ quote })
2984 }
2985 ```
2986
2987 You create a `POST` route handler, which will expose a `POST` API route at `/admin/quotes/:id/send`. In the route handler, you run the `merchantSendQuoteWorkflow` with the quote's ID as input. You then retrieve the updated quote using Query and return it in the response.
2988
2989 Notice that you can pass `req.queryConfig.fields` to the `query.graph` method because you've applied the `validateAndTransformQuery` middleware before to all routes starting with `/admin/quotes`.
2990
2991 ### Add Send Quote Hook
2992
2993 Now that you have the API route, you can add a React hook in the admin customizations that sends a request to the quote send API route.
2994
2995 In `src/admin/hooks/quotes.tsx` add the new hook:
2996
2997 ```tsx title="src/admin/hooks/quotes.tsx"
2998 export const useSendQuote = (
2999 id: string,
3000 options?: UseMutationOptions<AdminQuoteResponse, FetchError, void>
3001 ) => {
3002 const queryClient = useQueryClient()
3003
3004 const sendQuote = async (id: string) =>
3005 sdk.client.fetch<AdminQuoteResponse>(`/admin/quotes/${id}/send`, {
3006 method: "POST",
3007 })
3008
3009 return useMutation({
3010 mutationFn: () => sendQuote(id),
3011 onSuccess: (data: any, variables: any, context: any) => {
3012 queryClient.invalidateQueries({
3013 queryKey: [orderPreviewQueryKey, id],
3014 })
3015
3016 queryClient.invalidateQueries({
3017 queryKey: ["quote", id],
3018 })
3019
3020 queryClient.invalidateQueries({
3021 queryKey: ["quote", "list"],
3022 })
3023
3024 options?.onSuccess?.(data, variables, context)
3025 },
3026 ...options,
3027 })
3028 }
3029 ```
3030
3031 You add a `useSendQuote` hook that accepts the quote's ID and optional options as parameters. In the hook, you use the `useMutation` hook to define the mutation action that sends a request to the send quote API route.
3032
3033 When the mutation is invoked, the hook sends a request to the send quote API route, then invalidates all data related to the quote in the query client, which will trigger a re-fetch of the data.
3034
3035 ### Add Send Quote Button
3036
3037 Finally, you can add a button to the quote's details page that allows a merchant to send the quote back to the customer for review.
3038
3039 First, add the following import to the `src/admin/routes/quote/[id]/page.tsx` file:
3040
3041 ```tsx title="src/admin/routes/quote/[id]/page.tsx"
3042 import {
3043 useSendQuote,
3044 } from "../../../hooks/quotes"
3045 ```
3046
3047 Then, after the `useRejectQuote` hook usage, add the following:
3048
3049 ```tsx title="src/admin/routes/quote/[id]/page.tsx"
3050 const { mutateAsync: sendQuote, isPending: isSendingQuote } = useSendQuote(
3051 id!
3052 )
3053 const [showSendQuote, setShowSendQuote] = useState(false)
3054 ```
3055
3056 You initialize the following variables:
3057
3058 1. `sendQuote` and `isSendingQuote`: Data returned by the `useSendQuote` hook. The `sendQuote` function invokes the mutation, sending the quote back to the customer; `isSendingQuote` is a boolean that indicates if the mutation is in progress.
3059 2. `showSendQuote`: A boolean that indicates whether the "Send Quote" button should be shown.
3060
3061 Next, update the existing `useEffect` hook to change `showSendQuote` based on the quote's status:
3062
3063 ```tsx title="src/admin/routes/quote/[id]/page.tsx"
3064 useEffect(() => {
3065 if (["pending_merchant", "customer_rejected"].includes(quote?.status!)) {
3066 setShowSendQuote(true)
3067 } else {
3068 setShowSendQuote(false)
3069 }
3070
3071 if (
3072 ["customer_rejected", "merchant_rejected", "accepted"].includes(
3073 quote?.status!
3074 )
3075 ) {
3076 setShowRejectQuote(false)
3077 } else {
3078 setShowRejectQuote(true)
3079 }
3080 }, [quote])
3081 ```
3082
3083 The `useEffect` hook now updates both the `showSendQuote` and `showRejectQuote` states based on the quote's status. The "Send Quote" button is hidden if the quote's status is not `pending_merchant` or `customer_rejected`.
3084
3085 Then, after the `handleRejectQuote` function, add the following `handleSendQuote` function:
3086
3087 ```tsx title="src/admin/routes/quote/[id]/page.tsx"
3088 const handleSendQuote = async () => {
3089 const res = await prompt({
3090 title: "Send quote?",
3091 description:
3092 "You are about to send this quote to the customer. Do you want to continue?",
3093 confirmText: "Continue",
3094 cancelText: "Cancel",
3095 variant: "confirmation",
3096 })
3097
3098 if (res) {
3099 await sendQuote(
3100 void 0,
3101 {
3102 onSuccess: () => toast.success("Successfully sent quote to customer"),
3103 onError: (e) => toast.error(e.message),
3104 }
3105 )
3106 }
3107 }
3108 ```
3109
3110 You define a `handleSendQuote` function that will be called when the merchant clicks the "Send Quote" button. The function shows a confirmation pop-up using the `prompt` hook. If the user confirms the action, the function calls the `sendQuote` function to send the quote back to the customer.
3111
3112 Finally, add the following after the reject quote button in the `return` statement:
3113
3114 ```tsx title="src/admin/routes/quote/[id]/page.tsx"
3115 {showSendQuote && (
3116 <Button
3117 size="small"
3118 variant="secondary"
3119 onClick={() => handleSendQuote()}
3120 disabled={isSendingQuote || isRejectingQuote}
3121 >
3122 Send Quote
3123 </Button>
3124 )}
3125 ```
3126
3127 In this code snippet, you show the "Send Quote" button if the `showSendQuote` state is `true`. When the button is clicked, you call the `handleSendQuote` function to send the quote back to the customer.
3128
3129 ### Test Send Quote Feature
3130
3131 To test the send quote feature, start the Medusa application:
3132
3133 ```bash npm2yarn
3134 npm run dev
3135 ```
3136
3137 Then, open the Medusa Admin dashboard at `http://localhost:9000/app` and login using the credentials you set up earlier.
3138
3139 Next, open a quote's details page. You'll find a new "Send Quote" button. If you click on it and confirm sending the quote, the quote will be sent back to the customer, and a success message will be shown.
3140
3141 <Note>
3142
3143 You'll later add the feature to update the quote item's details before sending the quote back to the customer.
3144
3145 </Note>
3146
3147 ![Quote details page with send quote button in Medusa Admin](https://res.cloudinary.com/dza7lstvk/image/upload/v1741162950/Medusa%20Resources/Screenshot_2025-03-05_at_10.22.11_AM_sjuipg.png)
3148
3149 ---
3150
3151 ## Step 12: Add Customer Preview Order API Route
3152
3153 When the merchant sends back the quote to the customer, you want to show the customer the details of the quote and the order that would be created if they accept the quote. This helps the customer decide whether to accept or reject the quote (which you'll implement next).
3154
3155 In this step, you'll add the API route that allows a customer to preview a quote's order.
3156
3157 To create the API route, create the file `src/api/store/customers/me/quotes/[id]/preview/route.ts` with the following content:
3158
3159 ![Directory structure after adding the customer preview order API route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741163145/Medusa%20Resources/quote-40_lmcgve.jpg)
3160
3161 ```ts title="src/api/store/customers/me/quotes/[id]/preview/route.ts"
3162 import type {
3163 AuthenticatedMedusaRequest,
3164 MedusaResponse,
3165 } from "@medusajs/framework/http"
3166 import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
3167
3168 export const GET = async (
3169 req: AuthenticatedMedusaRequest,
3170 res: MedusaResponse
3171 ) => {
3172 const { id } = req.params
3173 const query = req.scope.resolve(
3174 ContainerRegistrationKeys.QUERY
3175 )
3176
3177 const {
3178 data: [quote],
3179 } = await query.graph(
3180 {
3181 entity: "quote",
3182 filters: { id },
3183 fields: req.queryConfig.fields,
3184 },
3185 { throwIfKeyNotFound: true }
3186 )
3187
3188 const orderModuleService = req.scope.resolve(
3189 Modules.ORDER
3190 )
3191
3192 const preview = await orderModuleService.previewOrderChange(
3193 quote.draft_order_id
3194 )
3195
3196 res.status(200).json({
3197 quote: {
3198 ...quote,
3199 order_preview: preview,
3200 },
3201 })
3202 }
3203 ```
3204
3205 You create a `GET` route handler, which will expose a `GET` API route at `/store/customers/me/quotes/:id/preview`. In the route handler, you retrieve the quote's details using Query, then preview the order that would be created from the quote using the `previewOrderChange` method from the Order Module's service. Finally, you return the quote and its order preview in the response.
3206
3207 Notice that you're using the `req.queryConfig.fields` object in the `query.graph` method because you've applied the `validateAndTransformQuery` middleware before to all routes starting with `/store/customers/me/quotes`.
3208
3209 ### Test Customer Preview Order API Route
3210
3211 To test the customer preview order API route, start the Medusa application:
3212
3213 ```bash npm2yarn
3214 npm run dev
3215 ```
3216
3217 Then, grab the ID of a quote placed by a customer that you have their [authentication token](#retrieve-customer-authentication-token). You can find the quote ID in the URL when viewing the quote's details page in the Medusa Admin dashboard.
3218
3219 Finally, send the following request to get a preview of the customer's quote and order:
3220
3221 ```bash
3222 curl 'http://localhost:9000/store/customers/me/quotes/{quote_id}/preview' \
3223 -H 'x-publishable-api-key: {your_publishable_api_key}' \
3224 -H 'Authorization: Bearer {token}'
3225 ```
3226
3227 Make sure to replace:
3228
3229 - `{quote_id}` with the ID of the quote you want to preview.
3230 - `{your_publishable_api_key}` with [your publishable API key](#retrieve-publishable-api-key).
3231 - `{token}` with the customer's authentication token.
3232
3233 You'll receive in the response the quote's details with the order preview. You can show the customer these details in the storefront.
3234
3235 ---
3236
3237 ## Step 13: Add Customer Reject Quote Feature
3238
3239 After the customer previews the quote and its order, they can choose to reject the quote. When the customer rejects the quote, the quote's status is changed to `customer_rejected`. The merchant will still be able to update the quote and send it back to the customer for review.
3240
3241 In this step, you'll implement the functionality to reject a quote from the customer's perspective. This will include:
3242
3243 1. Implementing the workflow to reject a quote as a customer.
3244 2. Adding the API route to allow customers to reject a quote using the workflow.
3245
3246 ### Implement Customer Reject Quote Workflow
3247
3248 To reject a quote from the customer's perspective, you'll need to create a workflow that will handle the rejection process. The workflow has the following steps:
3249
3250 <WorkflowDiagram
3251 workflow={{
3252 name: "customerRejectQuoteWorkflow",
3253 steps: [
3254 {
3255 type: "step",
3256 name: "useQueryGraphStep",
3257 description: "Retrieve the quote's details.",
3258 link: "/references/helper-steps/useQueryGraphStep",
3259 depth: 1
3260 },
3261 {
3262 type: "step",
3263 name: "validateQuoteNotAccepted",
3264 description: "Validate that the quote isn't already accepted by the customer.",
3265 depth: 1
3266 },
3267 {
3268 type: "step",
3269 name: "updateQuoteStatusStep",
3270 description: "Update the quote's status to `customer_rejected`.",
3271 depth: 1
3272 }
3273 ]
3274 }}
3275 hideLegend
3276 />
3277
3278 All the steps are available for use, so you can implement the workflow directly.
3279
3280 Create the file `src/workflows/customer-reject-quote.ts` with the following content:
3281
3282 ![Directory structure after adding the customer reject quote workflow file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741164371/Medusa%20Resources/quote-41_fgpqhz.jpg)
3283
3284 export const customerRejectQuoteHighlights = [
3285 ["15", "useQueryGraphStep", "Retrieve the quote's details."],
3286 ["24", "validateQuoteNotAccepted", "Validate that the quote isn't already accepted by the customer."],
3287 ["29", "updateQuotesStep", "Update the quote's status to `customer_rejected`."]
3288 ]
3289
3290 ```ts title="src/workflows/customer-reject-quote.ts" highlights={customerRejectQuoteHighlights}
3291 import { useQueryGraphStep } from "@medusajs/core-flows"
3292 import { createWorkflow } from "@medusajs/framework/workflows-sdk"
3293 import { QuoteStatus } from "../modules/quote/models/quote"
3294 import { updateQuotesStep } from "./steps/update-quotes"
3295 import { validateQuoteNotAccepted } from "./steps/validate-quote-not-accepted"
3296
3297 type WorkflowInput = {
3298 quote_id: string;
3299 customer_id: string;
3300 }
3301
3302 export const customerRejectQuoteWorkflow = createWorkflow(
3303 "customer-reject-quote-workflow",
3304 (input: WorkflowInput) => {
3305 const { data: quotes } = useQueryGraphStep({
3306 entity: "quote",
3307 fields: ["id", "status"],
3308 filters: { id: input.quote_id, customer_id: input.customer_id },
3309 options: {
3310 throwIfKeyNotFound: true,
3311 },
3312 })
3313
3314 validateQuoteNotAccepted({
3315 // @ts-ignore
3316 quote: quotes[0],
3317 })
3318
3319 updateQuotesStep([
3320 {
3321 id: input.quote_id,
3322 status: QuoteStatus.CUSTOMER_REJECTED,
3323 },
3324 ])
3325 }
3326 )
3327 ```
3328
3329 You create a workflow that accepts the IDs of the quote to reject and the customer rejecting it. In the workflow, you:
3330
3331 1. Use the `useQueryGraphStep` to retrieve the quote's details. Notice that you pass the IDs of the quote and the customer as filters to ensure that the quote belongs to the customer.
3332 2. Validate that the quote isn't already accepted using the `validateQuoteNotAccepted` step.
3333 3. Update the quote's status to `customer_rejected` using the `updateQuotesStep`.
3334
3335 You'll use this workflow next in an API route that allows a customer to reject a quote.
3336
3337 ### Add Customer Reject Quote API Route
3338
3339 You'll now add the API route that allows a customer to reject a quote. The route will use the `customerRejectQuoteWorkflow` you created in the previous step.
3340
3341 Create the file `src/api/store/customers/me/quotes/[id]/reject/route.ts` with the following content:
3342
3343 ![Directory structure after adding the customer reject quote API route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741164538/Medusa%20Resources/quote-42_bryo2z.jpg)
3344
3345 ```ts title="src/api/store/customers/me/quotes/[id]/reject/route.ts"
3346 import type {
3347 AuthenticatedMedusaRequest,
3348 MedusaResponse,
3349 } from "@medusajs/framework/http"
3350 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
3351 import {
3352 customerRejectQuoteWorkflow,
3353 } from "../../../../../../../workflows/customer-reject-quote"
3354
3355 export const POST = async (
3356 req: AuthenticatedMedusaRequest,
3357 res: MedusaResponse
3358 ) => {
3359 const { id } = req.params
3360 const query = req.scope.resolve(
3361 ContainerRegistrationKeys.QUERY
3362 )
3363
3364 await customerRejectQuoteWorkflow(req.scope).run({
3365 input: {
3366 quote_id: id,
3367 customer_id: req.auth_context.actor_id,
3368 },
3369 })
3370
3371 const {
3372 data: [quote],
3373 } = await query.graph(
3374 {
3375 entity: "quote",
3376 filters: { id },
3377 fields: req.queryConfig.fields,
3378 },
3379 { throwIfKeyNotFound: true }
3380 )
3381
3382 return res.json({ quote })
3383 }
3384 ```
3385
3386 You create a `POST` route handler, which will expose a `POST` API route at `/store/customers/me/quotes/:id/reject`. In the route handler, you run the `customerRejectQuoteWorkflow` with the quote's ID as input. You then retrieve the updated quote using Query and return it in the response.
3387
3388 Notice that you can pass `req.queryConfig.fields` to the `query.graph` method because you've applied the `validateAndTransformQuery` middleware before to all routes starting with `/store/customers/me/quotes`.
3389
3390 ### Test Customer Reject Quote Feature
3391
3392 To test the customer reject quote feature, start the Medusa application:
3393
3394 ```bash npm2yarn
3395 npm run dev
3396 ```
3397
3398 Then, send a request to reject a quote for the authenticated customer:
3399
3400 ```bash
3401 curl -X POST 'http://localhost:9000/store/customers/me/quotes/{quote_id}/reject' \
3402 -H 'x-publishable-api-key: {your_publishable_api_key}' \
3403 -H 'Authorization: Bearer {token}'
3404 ```
3405
3406 Make sure to replace:
3407
3408 - `{quote_id}` with the ID of the quote you want to reject.
3409 - `{your_publishable_api_key}` with [your publishable API key](#retrieve-publishable-api-key).
3410 - `{token}` with the customer's [authentication token](#retrieve-customer-authentication-token).
3411
3412 After sending the request, the quote will be rejected, and the updated quote will be returned in the response. You can also view the quote from the Medusa Admin dashboard, where you'll find its status has changed.
3413
3414 ---
3415
3416 ## Step 14: Add Customer Accept Quote Feature
3417
3418 The customer alternatively can choose to accept a quote after previewing it. When the customer accepts a quote, the quote's draft order should become an order whose payment can be processed and items fulfilled. No further changes can be made on the quote after it's accepted.
3419
3420 In this step, you'll implement the functionality to allow a customer to accept a quote. This will include:
3421
3422 1. Implementing the workflow to accept a quote as a customer.
3423 2. Adding the API route to allow customers to accept a quote using the workflow.
3424
3425 ### Implement Customer Accept Quote Workflow
3426
3427 You'll implement the quote acceptance logic in a workflow. The workflow has the following steps:
3428
3429 <WorkflowDiagram
3430 workflow={{
3431 name: "customerAcceptQuoteWorkflow",
3432 steps: [
3433 {
3434 type: "step",
3435 name: "useQueryGraphStep",
3436 description: "Retrieve the quote's details.",
3437 link: "/references/helper-steps/useQueryGraphStep",
3438 depth: 1
3439 },
3440 {
3441 type: "step",
3442 name: "validateQuoteCanAcceptStep",
3443 description: "Validate that the quote can be accepted.",
3444 depth: 1
3445 },
3446 {
3447 type: "step",
3448 name: "updateQuotesStep",
3449 description: "Update the quote's status to `accepted`.",
3450 depth: 1
3451 },
3452 {
3453 type: "workflow",
3454 name: "confirmOrderEditRequestWorkflow",
3455 description: "Confirm the changes made on the draft order, such as changes to item quantities and prices.",
3456 link: "/references/medusa-workflows/confirmOrderEditRequestWorkflow",
3457 depth: 1
3458 },
3459 {
3460 type: "workflow",
3461 name: "updateOrderWorkflow",
3462 description: "Update the draft order to change its status and convert it into an order.",
3463 link: "/references/medusa-workflows/updateOrderWorkflow",
3464 depth: 1
3465 }
3466 ]
3467 }}
3468 hideLegend
3469 />
3470
3471 You only need to implement the `validateQuoteCanAcceptStep` step before implementing the workflow, as the other steps are already available for use.
3472
3473 #### validateQuoteCanAcceptStep
3474
3475 In the `validateQuoteCanAcceptStep`, you'll validate whether the customer can accept the quote. The customer can only accept a quote if the quote's status is `pending_customer`, meaning the merchant sent the quote back to the customer for review.
3476
3477 Create the file `src/workflows/steps/validate-quote-can-accept.ts` with the following content:
3478
3479 ![Directory structure after adding the validate quote can accept step file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741165829/Medusa%20Resources/quote-43_cxc3qi.jpg)
3480
3481 ```ts title="src/workflows/steps/validate-quote-can-accept.ts"
3482 import { MedusaError } from "@medusajs/framework/utils"
3483 import { createStep } from "@medusajs/framework/workflows-sdk"
3484 import { InferTypeOf } from "@medusajs/framework/types"
3485 import { Quote, QuoteStatus } from "../../modules/quote/models/quote"
3486
3487 type StepInput = {
3488 quote: InferTypeOf<typeof Quote>
3489 }
3490
3491 export const validateQuoteCanAcceptStep = createStep(
3492 "validate-quote-can-accept",
3493 async function ({ quote }: StepInput) {
3494 if (quote.status !== QuoteStatus.PENDING_CUSTOMER) {
3495 throw new MedusaError(
3496 MedusaError.Types.INVALID_DATA,
3497 `Cannot accept quote when quote status is ${quote.status}`
3498 )
3499 }
3500 }
3501 )
3502 ```
3503
3504 You create a step that accepts a quote as input. In the step function, you throw an error if the quote's status is not `pending_customer`.
3505
3506 #### Implement Workflow
3507
3508 You can now implement the workflow that accepts a quote for a customer. Create the file `src/workflows/customer-accept-quote.ts` with the following content:
3509
3510 ![Directory structure after adding the customer accept quote workflow file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741166025/Medusa%20Resources/quote-44_c09ts9.jpg)
3511
3512 export const customerAcceptQuoteHighlights = [
3513 ["20", "useQueryGraphStep", "Retrieve the quote's details."],
3514 ["29", "validateQuoteCanAcceptStep", "Validate that the quote can be accepted."],
3515 ["34", "updateQuotesStep", "Update the quote's status to `accepted`."],
3516 ["39", "confirmOrderEditRequestWorkflow", "Confirm the changes made on the draft order, such as changes to item quantities and prices."],
3517 ["46", "updateOrderWorkflow", "Update the draft order to change its status and convert it into an order."]
3518 ]
3519
3520 ```ts title="src/workflows/customer-accept-quote.ts" highlights={customerAcceptQuoteHighlights}
3521 import {
3522 confirmOrderEditRequestWorkflow,
3523 updateOrderWorkflow,
3524 useQueryGraphStep,
3525 } from "@medusajs/core-flows"
3526 import { OrderStatus } from "@medusajs/framework/utils"
3527 import { createWorkflow } from "@medusajs/framework/workflows-sdk"
3528 import { validateQuoteCanAcceptStep } from "./steps/validate-quote-can-accept"
3529 import { QuoteStatus } from "../modules/quote/models/quote"
3530 import { updateQuotesStep } from "./steps/update-quotes"
3531
3532 type WorkflowInput = {
3533 quote_id: string;
3534 customer_id: string;
3535 };
3536
3537 export const customerAcceptQuoteWorkflow = createWorkflow(
3538 "customer-accept-quote-workflow",
3539 (input: WorkflowInput) => {
3540 const { data: quotes } = useQueryGraphStep({
3541 entity: "quote",
3542 fields: ["id", "draft_order_id", "status"],
3543 filters: { id: input.quote_id, customer_id: input.customer_id },
3544 options: {
3545 throwIfKeyNotFound: true,
3546 },
3547 })
3548
3549 validateQuoteCanAcceptStep({
3550 // @ts-ignore
3551 quote: quotes[0],
3552 })
3553
3554 updateQuotesStep([{
3555 id: input.quote_id,
3556 status: QuoteStatus.ACCEPTED,
3557 }])
3558
3559 confirmOrderEditRequestWorkflow.runAsStep({
3560 input: {
3561 order_id: quotes[0].draft_order_id,
3562 confirmed_by: input.customer_id,
3563 },
3564 })
3565
3566 updateOrderWorkflow.runAsStep({
3567 input:{
3568 id: quotes[0].draft_order_id,
3569 // @ts-ignore
3570 status: OrderStatus.PENDING,
3571 is_draft_order: false,
3572 },
3573 })
3574 }
3575 )
3576 ```
3577
3578 You create a workflow that accepts the IDs of the quote to accept and the customer accepting it. In the workflow, you:
3579
3580 1. Use the `useQueryGraphStep` to retrieve the quote's details. You pass the IDs of the quotes and the customer as filters to ensure that the quote belongs to the customer.
3581 2. Validate that the quote can be accepted using the `validateQuoteCanAcceptStep`.
3582 3. Update the quote's status to `accepted` using the `updateQuotesStep`.
3583 4. Confirm the changes made on the draft order using the `confirmOrderEditRequestWorkflow` executed as a step. This is useful when you soon add the admin functionality to edit the quote items. Any changes that the admin has made will be applied on the draft order using this step.
3584 5. Update the draft order to change its status and convert it into an order using the `updateOrderWorkflow` executed as a step.
3585
3586 You'll use this workflow next in an API route that allows a customer to accept a quote.
3587
3588 ### Add Customer Accept Quote API Route
3589
3590 You'll now add the API route that allows a customer to accept a quote. The route will use the `customerAcceptQuoteWorkflow` you created in the previous step.
3591
3592 Create the file `src/api/store/customers/me/quotes/[id]/accept/route.ts` with the following content:
3593
3594 ![Directory structure after adding the customer accept quote API route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741166543/Medusa%20Resources/quote-45_y8zprn.jpg)
3595
3596 ```ts title="src/api/store/customers/me/quotes/[id]/accept/route.ts"
3597 import type {
3598 AuthenticatedMedusaRequest,
3599 MedusaResponse,
3600 } from "@medusajs/framework/http"
3601 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
3602 import {
3603 customerAcceptQuoteWorkflow,
3604 } from "../../../../../../../workflows/customer-accept-quote"
3605
3606 export const POST = async (
3607 req: AuthenticatedMedusaRequest,
3608 res: MedusaResponse
3609 ) => {
3610 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
3611 const { id } = req.params
3612
3613 await customerAcceptQuoteWorkflow(req.scope).run({
3614 input: {
3615 quote_id: id,
3616 customer_id: req.auth_context.actor_id,
3617 },
3618 })
3619
3620 const {
3621 data: [quote],
3622 } = await query.graph(
3623 {
3624 entity: "quote",
3625 filters: { id },
3626 fields: req.queryConfig.fields,
3627 },
3628 { throwIfKeyNotFound: true }
3629 )
3630
3631 return res.json({ quote })
3632 }
3633 ```
3634
3635 You create a `POST` route handler, which will expose a `POST` API route at `/store/customers/me/quotes/:id/accept`. In the route handler, you run the `customerAcceptQuoteWorkflow` with the quote's ID as input. You then retrieve the updated quote using Query and return it in the response.
3636
3637 Notice that you can pass `req.queryConfig.fields` to the `query.graph` method because you've applied the `validateAndTransformQuery` middleware before to all routes starting with `/store/customers/me/quotes`.
3638
3639 ### Test Customer Accept Quote Feature
3640
3641 To test the customer accept quote feature, start the Medusa application:
3642
3643 ```bash npm2yarn
3644 npm run dev
3645 ```
3646
3647 Then, send a request to accept a quote for the authenticated customer:
3648
3649 ```bash
3650 curl -X POST 'http://localhost:9000/store/customers/me/quotes/{quote_id}/accept' \
3651 -H 'x-publishable-api-key: {your_publishable_api_key}' \
3652 -H 'Authorization: Bearer {token}'
3653 ```
3654
3655 Make sure to replace:
3656
3657 - `{quote_id}` with the ID of the quote you want to accept.
3658 - `{your_publishable_api_key}` with [your publishable API key](#retrieve-publishable-api-key).
3659 - `{token}` with the customer's [authentication token](#retrieve-customer-authentication-token).
3660
3661 After sending the request, the quote will be accepted, and the updated quote will be returned in the response.
3662
3663 You can also view the quote from the Medusa Admin dashboard, where you'll find its status has changed. The quote will also have an order, which you can view in the Orders page or using the "View Order" button on the quote's details page.
3664
3665 ![View order button on quote's details page in Medusa Admin](https://res.cloudinary.com/dza7lstvk/image/upload/v1741166844/Medusa%20Resources/Screenshot_2025-03-05_at_11.27.02_AM_s90rqh.png)
3666
3667 ---
3668
3669 ## Step 15: Edit Quote Items UI Route
3670
3671 The last feature you'll add is allowing merchants or admin users to make changes to the quote's items. This includes updating the item's quantity and price.
3672
3673 Since you're using an [order change](../../../commerce-modules/order/order-change/page.mdx) to manage edits to the quote's draft orders, you don't need to implement customizations on the server side, such as adding workflows or API routes. Instead, you'll only add a new UI route in the Medusa Admin that uses the [Order Edit API routes](!api!/admin/order-edits) to provide the functionality to edit the quote's items.
3674
3675 <Note>
3676
3677 Order changes also allow you to add or remove items from the quote. However, for simplicity, this guide only covers how to update the item's quantity and price. Refer to the [Order Change](../../../commerce-modules/order/order-change/page.mdx) documentation to learn more.
3678
3679 </Note>
3680
3681 ![Edit quote items page in Medusa Admin](https://res.cloudinary.com/dza7lstvk/image/upload/v1741169659/Medusa%20Resources/Screenshot_2025-03-05_at_12.14.05_PM_ufvkqb.png)
3682
3683 In this step, you'll add a new UI route to manage the quote's items. This will include:
3684
3685 1. Adding hooks to send requests to [Medusa's Order Edits API routes](!api!/admin/order-edits).
3686 2. Implement the components you'll use within the UI route.
3687 3. Add the new UI route to the Medusa Admin.
3688
3689 ### Intermission: Order Editing Overview
3690
3691 Before you start implementing the customizations, here's a quick overview of how order editing works in Medusa.
3692
3693 When the admin wants to edit an order's items, Medusa creates an order change. You've already implemented this part on quote creation.
3694
3695 Then, when the admin makes an edit to an item, Medusa saves that edit but without applying it to the order or finalizing the edit. This allows the admin to make multiple edits before finalizing the changes.
3696
3697 Once the admin is finished editing, they can confirm the order edit, which finalizes it to later be applied on the order. You've already implemented applying the order edit on the order when the customer accepts the quote.
3698
3699 So, you still need two implement two aspects: updating the quote items, and confirming the order edit. You'll implement these in the next steps.
3700
3701 ### Add Hooks
3702
3703 To implement the edit quote items functionality, you'll need two hooks:
3704
3705 1. A hook that updates a quote item's quantity and price using the Order Edits API routes.
3706 2. A hook that confirms the edit of the items using the Order Edits API routes.
3707
3708 #### Update Quote Item Hook
3709
3710 The first hook updates an item's quantity and price using the Order Edits API routes. You'll use this whenever an admin updates an item's quantity or price.
3711
3712 In `src/admin/hooks/quotes.tsx`, add the following hook:
3713
3714 ```tsx title="src/admin/hooks/quotes.tsx"
3715 // other imports...
3716 import { HttpTypes } from "@medusajs/framework/types"
3717
3718 // ...
3719
3720 export const useUpdateQuoteItem = (
3721 id: string,
3722 options?: UseMutationOptions<
3723 HttpTypes.AdminOrderEditPreviewResponse,
3724 FetchError,
3725 UpdateQuoteItemParams
3726 >
3727 ) => {
3728 const queryClient = useQueryClient()
3729
3730 return useMutation({
3731 mutationFn: ({
3732 itemId,
3733 ...payload
3734 }: UpdateQuoteItemParams) => {
3735 return sdk.admin.orderEdit.updateOriginalItem(id, itemId, payload)
3736 },
3737 onSuccess: (data: any, variables: any, context: any) => {
3738 queryClient.invalidateQueries({
3739 queryKey: [orderPreviewQueryKey, id],
3740 })
3741
3742 options?.onSuccess?.(data, variables, context)
3743 },
3744 ...options,
3745 })
3746 }
3747 ```
3748
3749 You create a `useUpdateQuoteItem` hook that accepts the quote's ID and optional options as parameters. In the hook, you use the `useMutation` hook to define the mutation action that updates an item's quantity and price using the `sdk.admin.orderEdit.updateOriginalItem` method.
3750
3751 When the mutation is invoked, the hook invalidates the quote's data in the query client, which will trigger a re-fetch of the data.
3752
3753 #### Confirm Order Edit Hook
3754
3755 Next, you'll add a hook that confirms the order edit. This hook will be used when the admin is done editing the quote's items. As mentioned earlier, confirming the order edit doesn't apply the changes to the order but finalizes the edit.
3756
3757 In `src/admin/hooks/quotes.tsx`, add the following hook:
3758
3759 ```tsx title="src/admin/hooks/quotes.tsx"
3760 export const useConfirmQuote = (
3761 id: string,
3762 options?: UseMutationOptions<
3763 HttpTypes.AdminOrderEditPreviewResponse,
3764 FetchError,
3765 void
3766 >
3767 ) => {
3768 const queryClient = useQueryClient()
3769
3770 return useMutation({
3771 mutationFn: () => sdk.admin.orderEdit.request(id),
3772 onSuccess: (data: any, variables: any, context: any) => {
3773 queryClient.invalidateQueries({
3774 queryKey: [orderPreviewQueryKey, id],
3775 })
3776
3777 options?.onSuccess?.(data, variables, context)
3778 },
3779 ...options,
3780 })
3781 }
3782 ```
3783
3784 You create a `useConfirmQuote` hook that accepts the quote's ID and optional options as parameters. In the hook, you use the `useMutation` hook to define the mutation action that confirms the order edit using the `sdk.admin.orderEdit.request` method.
3785
3786 When the mutation is invoked, the hook invalidates the quote's data in the query client, which will trigger a re-fetch of the data.
3787
3788 Now that you have the necessary hooks, you can use them in the UI route and its components.
3789
3790 ### Add ManageItem Component
3791
3792 The UI route will show the list of items to the admin user and allows them to update the item's quantity and price. So, you'll create a component that allows the admin to manage a single item's details. You'll later use this component for each item in the quote.
3793
3794 ![Screenshot of the manage item component in Medusa Admin](https://res.cloudinary.com/dza7lstvk/image/upload/v1741186495/Medusa%20Resources/manage-item-highlight_ouffnu.png)
3795
3796 Create the file `src/admin/components/manage-item.tsx` with the following content:
3797
3798 ![Directory structure after adding the manage item component file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741168152/Medusa%20Resources/quote-46_yxanj7.jpg)
3799
3800 ```tsx
3801 import { AdminOrder, AdminOrderPreview } from "@medusajs/framework/types"
3802 import {
3803 Badge,
3804 CurrencyInput,
3805 Hint,
3806 Input,
3807 Label,
3808 Text,
3809 toast,
3810 } from "@medusajs/ui"
3811 import { useMemo } from "react"
3812 import {
3813 useUpdateQuoteItem,
3814 } from "../hooks/quotes"
3815 import { Amount } from "./amount"
3816
3817 type ManageItemProps = {
3818 originalItem: AdminOrder["items"][0];
3819 item: AdminOrderPreview["items"][0];
3820 currencyCode: string;
3821 orderId: string;
3822 };
3823
3824 export function ManageItem({
3825 originalItem,
3826 item,
3827 currencyCode,
3828 orderId,
3829 }: ManageItemProps) {
3830 const { mutateAsync: updateItem } = useUpdateQuoteItem(orderId)
3831
3832 const isItemUpdated = useMemo(
3833 () => !!item.actions?.find((a) => a.action === "ITEM_UPDATE"),
3834 [item]
3835 )
3836
3837 const onUpdate = async ({
3838 quantity,
3839 unit_price,
3840 }: {
3841 quantity?: number;
3842 unit_price?: number;
3843 }) => {
3844 if (
3845 typeof quantity === "number" &&
3846 quantity <= item.detail.fulfilled_quantity
3847 ) {
3848 toast.error("Quantity should be greater than the fulfilled quantity")
3849 return
3850 }
3851
3852 try {
3853 await updateItem({
3854 quantity,
3855 unit_price,
3856 itemId: item.id,
3857 })
3858 } catch (e) {
3859 toast.error((e as any).message)
3860 }
3861 }
3862
3863 // TODO render the item's details and input fields
3864 }
3865 ```
3866
3867 You define a `ManageItem` component that accepts the following props:
3868
3869 - `originalItem`: The original item details from the quote. This is the item's details before any edits.
3870 - `item`: The item's details from the quote's order preview. This is the item's details which may have been edited.
3871 - `currencyCode`: The currency code of the quote's draft order.
3872 - `orderId`: The ID of the quote's draft order.
3873
3874 In the component, you define the following variables:
3875
3876 - `updateItem`: The `mutateAsync` function returned by the `useUpdateQuoteItem` hook. This function updates the item's quantity and price using Medusa's Order Edits API routes.
3877 - `isItemUpdated`: A boolean that indicates whether the item has been updated.
3878
3879 You also define an `onUpdate` function that will be called when the admin updates the item's quantity or price. The function sends a request to update the item's quantity and price using the `updateItem` function. If the quantity is less than or equal to the fulfilled quantity, you show an error message.
3880
3881 Next, you'll add a return statement to show the item's details and allow the admin to update the item's quantity and price. Replace the `TODO` with the following:
3882
3883 ```tsx title="src/admin/components/manage-item.tsx"
3884 return (
3885 <div
3886 key={item.quantity}
3887 className="bg-ui-bg-subtle shadow-elevation-card-rest my-2 rounded-xl "
3888 >
3889 <div className="flex flex-col items-center gap-x-2 gap-y-2 p-3 text-sm md:flex-row">
3890 <div className="flex flex-1 items-center justify-between">
3891 <div className="flex flex-row items-center gap-x-3">
3892
3893 <div className="flex flex-col">
3894 <div>
3895 <Text className="txt-small" as="span" weight="plus">
3896 {item.title}{" "}
3897 </Text>
3898
3899 {item.variant_sku && <span>({item.variant_sku})</span>}
3900 </div>
3901 <Text as="div" className="text-ui-fg-subtle txt-small">
3902 {item.product_title}
3903 </Text>
3904 </div>
3905 </div>
3906
3907 {isItemUpdated && (
3908 <Badge
3909 size="2xsmall"
3910 rounded="full"
3911 color="orange"
3912 className="mr-1"
3913 >
3914 Modified
3915 </Badge>
3916 )}
3917 </div>
3918
3919 <div className="flex flex-1 justify-between">
3920 <div className="flex flex-grow items-center gap-2">
3921 <Input
3922 className="bg-ui-bg-base txt-small w-[67px] rounded-lg [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
3923 type="number"
3924 disabled={item.detail.fulfilled_quantity === item.quantity}
3925 min={item.detail.fulfilled_quantity}
3926 defaultValue={item.quantity}
3927 onBlur={(e) => {
3928 const val = e.target.value
3929 const quantity = val === "" ? null : Number(val)
3930
3931 if (quantity) {
3932 onUpdate({ quantity })
3933 }
3934 }}
3935 />
3936 <Text className="txt-small text-ui-fg-subtle">
3937 Quantity
3938 </Text>
3939 </div>
3940
3941 <div className="text-ui-fg-subtle txt-small mr-2 flex flex-shrink-0">
3942 <Amount
3943 currencyCode={currencyCode}
3944 amount={item.total}
3945 originalAmount={originalItem?.total}
3946 />
3947 </div>
3948 </div>
3949 </div>
3950
3951 <div className="grid grid-cols-1 gap-2 p-3 md:grid-cols-2">
3952 <div className="flex flex-col gap-y-1">
3953 <Label>Price</Label>
3954 <Hint className="!mt-1">
3955 Override the unit price of this product
3956 </Hint>
3957 </div>
3958
3959 <div className="flex items-center gap-1">
3960 <div className="flex-grow">
3961 <CurrencyInput
3962 symbol={currencyCode}
3963 code={currencyCode}
3964 defaultValue={item.unit_price}
3965 type="numeric"
3966 min={0}
3967 onBlur={(e) => {
3968 onUpdate({
3969 unit_price: parseFloat(e.target.value),
3970 quantity: item.quantity,
3971 })
3972 }}
3973 className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
3974 />
3975 </div>
3976 </div>
3977 </div>
3978 </div>
3979 )
3980 ```
3981
3982 You show the item's title, product title, and variant SKU. If the item has been updated, you show a "Modified" badge.
3983
3984 You also show input fields for the quantity and price of the item, allowing the admin to update the item's quantity and price. Once the admin updates the quantity or price, the `onUpdate` function is called to send a request to update the item's details.
3985
3986 ### Add ManageQuoteForm Component
3987
3988 Next, you'll add the form component that shows the list of items in the quote and allows the admin to manage each item. You'll use the `ManageItem` component you created in the previous step for each item in the quote.
3989
3990 ![Screenshot of the manage quote form in the Medusa Admin](https://res.cloudinary.com/dza7lstvk/image/upload/v1741186643/Medusa%20Resources/manage-quote-form-highlight_pfyee5.png)
3991
3992 Create the file `src/admin/components/manage-quote-form.tsx` with the following content:
3993
3994 ![Directory structure after adding the manage quote form component file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741168581/Medusa%20Resources/quote-47_f5kamq.jpg)
3995
3996 ```tsx title="src/admin/components/manage-quote-form.tsx"
3997 import { AdminOrder } from "@medusajs/framework/types"
3998 import { Button, Heading, toast } from "@medusajs/ui"
3999 import { useConfirmQuote } from "../hooks/quotes"
4000 import { formatAmount } from "../utils/format-amount"
4001 import { useOrderPreview } from "../hooks/order-preview"
4002 import { useNavigate, useParams } from "react-router-dom"
4003 import { useMemo } from "react"
4004 import { ManageItem } from "./manage-item"
4005
4006 type ReturnCreateFormProps = {
4007 order: AdminOrder;
4008 };
4009
4010 export const ManageQuoteForm = ({ order }: ReturnCreateFormProps) => {
4011 const { order: preview } = useOrderPreview(order.id)
4012 const navigate = useNavigate()
4013 const { id: quoteId } = useParams()
4014
4015 const { mutateAsync: confirmQuote, isPending: isRequesting } =
4016 useConfirmQuote(order.id)
4017
4018 const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
4019 e.preventDefault()
4020 try {
4021 await confirmQuote()
4022 navigate(`/quotes/${quoteId}`)
4023
4024 toast.success("Successfully updated quote")
4025 } catch (e) {
4026 toast.error("Error", {
4027 description: (e as any).message,
4028 })
4029 }
4030 }
4031
4032 const originalItemsMap = useMemo(() => {
4033 return new Map(order.items.map((item) => [item.id, item]))
4034 }, [order])
4035
4036 if (!preview) {
4037 return <></>
4038 }
4039
4040 // TODO render form
4041 }
4042 ```
4043
4044 You define a `ManageQuoteForm` component that accepts the quote's draft order as a prop. In the component, you retrieve the preview of that order. The preview holds any edits made on the order's items.
4045
4046 You also define the `confirmQuote` function using the `useConfirmQuote` hook. This function confirms the order edit, finalizing the changes made on the order's items.
4047
4048 Then, you define the `handleSubmit` function that will be called when the admin submits the form. The function confirms the order edit using the `confirmQuote` function and navigates the admin back to the quote's details page.
4049
4050 Next, you'll add a return statement to show the edit form for the quote's items. Replace the `TODO` with the following:
4051
4052 ```tsx title="src/admin/components/manage-quote-form.tsx"
4053 return (
4054 <form onSubmit={handleSubmit} className="flex h-full flex-col p-4 gap-2">
4055 <div>
4056 <div className="mb-3 mt-8 flex items-center justify-between">
4057 <Heading level="h2">Items</Heading>
4058 </div>
4059
4060 {preview.items.map((item) => (
4061 <ManageItem
4062 key={item.id}
4063 originalItem={originalItemsMap.get(item.id)!}
4064 item={item}
4065 orderId={order.id}
4066 currencyCode={order.currency_code}
4067 />
4068 ))}
4069 </div>
4070
4071 <div className="mt-8 border-y border-dotted py-4">
4072 <div className="mb-2 flex items-center justify-between">
4073 <span className="txt-small text-ui-fg-subtle">
4074 Current Total
4075 </span>
4076
4077 <span className="txt-small text-ui-fg-subtle">
4078 {formatAmount(order.total, order.currency_code)}
4079 </span>
4080 </div>
4081
4082 <div className="mb-2 flex items-center justify-between">
4083 <span className="txt-small text-ui-fg-subtle">
4084 New Total
4085 </span>
4086
4087 <span className="txt-small text-ui-fg-subtle">
4088 {formatAmount(preview.total, order.currency_code)}
4089 </span>
4090 </div>
4091 </div>
4092
4093 <div className="flex w-full items-center justify-end gap-x-4">
4094 <div className="flex items-center justify-end gap-x-2">
4095 <Button
4096 key="submit-button"
4097 type="submit"
4098 variant="primary"
4099 size="small"
4100 disabled={isRequesting}
4101 >
4102 Confirm Edit
4103 </Button>
4104 </div>
4105 </div>
4106 </form>
4107 )
4108 ```
4109
4110 You use the `ManageItem` component to show each item in the quote and allow the admin to update the item's quantity and price. You also show the updated total amount of the quote and a button to confirm the order edit.
4111
4112 You'll use this component next in the UI route that allows the admin to edit the quote's items.
4113
4114 ### Implement UI Route
4115
4116 Finally, you'll add the UI route that allows the admin to edit the quote's items. The route will use the `ManageQuoteForm` component you created in the previous step.
4117
4118 Create the file `src/admin/routes/quotes/[id]/manage/page.tsx` with the following content:
4119
4120 ![Directory structure after adding the edit quote items UI route file](https://res.cloudinary.com/dza7lstvk/image/upload/v1741168993/Medusa%20Resources/quote-48_roangs.jpg)
4121
4122 ```tsx title="src/admin/routes/quotes/[id]/manage/page.tsx"
4123 import { useParams } from "react-router-dom"
4124 import { useQuote } from "../../../../hooks/quotes"
4125 import { Container, Heading, Toaster } from "@medusajs/ui"
4126 import { ManageQuoteForm } from "../../../../components/manage-quote-form"
4127
4128 const QuoteManage = () => {
4129 const { id } = useParams()
4130 const { quote, isLoading } = useQuote(id!, {
4131 fields:
4132 "*draft_order.customer",
4133 })
4134
4135 if (isLoading) {
4136 return <></>
4137 }
4138
4139 if (!quote) {
4140 throw "quote not found"
4141 }
4142
4143 return (
4144 <>
4145 <Container className="divide-y p-0">
4146 <Heading className="flex items-center justify-between px-6 py-4">
4147 Manage Quote
4148 </Heading>
4149
4150 <ManageQuoteForm order={quote.draft_order} />
4151 </Container>
4152 <Toaster />
4153 </>
4154 )
4155 }
4156
4157 export default QuoteManage
4158 ```
4159
4160 You define a `QuoteManage` component that will show the form to manage the quote's items in the Medusa Admin dashboard.
4161
4162 In the component, you first retrieve the quote's details using the `useQuote` hook. Then, you show the `ManageQuoteForm` component, passing the quote's draft order as a prop.
4163
4164 ### Add Manage Button to Quote Details Page
4165
4166 To allow the admin to access the manage page you just added, you'll add a new button on the quote's details page that links to the manage page.
4167
4168 In `src/admin/routes/quotes/[id]/page.tsx`, add the following variable definition after the `showSendQuote` variable:
4169
4170 ```tsx title="src/admin/routes/quotes/[id]/page.tsx"
4171 const [showManageQuote, setShowManageQuote] = useState(false)
4172 ```
4173
4174 This variable will be used to show or hide the manage quote button.
4175
4176 Then, update the existing `useEffect` hook to the following:
4177
4178 ```tsx title="src/admin/routes/quotes/[id]/page.tsx"
4179 useEffect(() => {
4180 if (["pending_merchant", "customer_rejected"].includes(quote?.status!)) {
4181 setShowSendQuote(true)
4182 } else {
4183 setShowSendQuote(false)
4184 }
4185
4186 if (
4187 ["customer_rejected", "merchant_rejected", "accepted"].includes(
4188 quote?.status!
4189 )
4190 ) {
4191 setShowRejectQuote(false)
4192 } else {
4193 setShowRejectQuote(true)
4194 }
4195
4196 if (![
4197 "pending_merchant",
4198 "customer_rejected",
4199 "merchant_rejected",
4200 ].includes(quote?.status!)) {
4201 setShowManageQuote(false)
4202 } else {
4203 setShowManageQuote(true)
4204 }
4205 }, [quote])
4206 ```
4207
4208 The `showManageQuote` variable is now updated based on the quote's status, where you only show it if the quote is pending the merchant's action, or if it has been rejected by either the customer or merchant.
4209
4210 Finally, add the following button component after the `Send Quote` button:
4211
4212 ```tsx title="src/admin/routes/quotes/[id]/page.tsx"
4213 {showManageQuote && (
4214 <Button
4215 size="small"
4216 variant="secondary"
4217 onClick={() => navigate(`/quotes/${quote.id}/manage`)}
4218 >
4219 Manage Quote
4220 </Button>
4221 )}
4222 ```
4223
4224 The Manage Quote button is now shown if the `showManageQuote` variable is `true`. When clicked, it navigates the admin to the manage quote page.
4225
4226 ### Test Edit Quote Items UI Route
4227
4228 To test the edit quote items UI route, start the Medusa application:
4229
4230 ```bash npm2yarn
4231 npm run dev
4232 ```
4233
4234 Then, open the Medusa Admin dashboard at `http://localhost:9000/admin`. Open a quote's details page whose status is either `pending_merchant`, `merchant_rejected` or `customer_rejected`. You'll find a new "Manage Quote" button.
4235
4236 ![Manage Quote button on quote's details page in Medusa Admin](https://res.cloudinary.com/dza7lstvk/image/upload/v1741169567/Medusa%20Resources/Screenshot_2025-03-05_at_12.12.21_PM_c5fhsp.png)
4237
4238 Click on the button, and you'll be taken to the manage quote page where you can update the quote's items. Try to update the items' quantities or price. Then, once you're done, click the "Confirm Edit" button to finalize the changes.
4239
4240 ![Edit quote items page in Medusa Admin](https://res.cloudinary.com/dza7lstvk/image/upload/v1741169659/Medusa%20Resources/Screenshot_2025-03-05_at_12.14.05_PM_ufvkqb.png)
4241
4242 The changes can now be previewed from the quote's details page. The customer can also see these changes using the preview API route you created earlier. Once the customer accepts the quote, the changes will be applied to the order.
4243
4244 ---
4245
4246 ## Next Steps
4247
4248 You've now implemented quote management features in Medusa. There's still more that you can implement to enhance the quote management experience:
4249
4250 - Refer to the [B2B starter](https://github.com/medusajs/b2b-starter) for more quote-management related features, including how to add or remove items from a quote, and how to allow messages between the customer and the merchant.
4251 - To build a storefront, refer to the [Storefront development guide](../../../storefront-development/page.mdx). You can also add to the storefront features related to quote-management using the APIs you implemented in this guide.
4252
4253 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
4254
4255 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).