1 ---
2 sidebar_label: "Customer Tiers"
3 tags:
4 - name: customer
5 label: "Implement Customer Tiers"
6 - server
7 - tutorial
8 - nextjs
9 - name: promotion
10 label: "Implement Customer Tiers"
11 products:
12 - customer
13 - promotion
14 - cart
15 ---
16
17 import { Github, PlaySolid } from "@medusajs/icons"
18 import { Prerequisites, WorkflowDiagram, CardList } from "docs-ui"
19
20 export const metadata = {
21 title: `Implement Customer Tiers in Medusa`,
22 }
23
24 # {metadata.title}
25
26 In this tutorial, you'll learn how to implement a customer tiers system in Medusa.
27
28 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. These features include customer and promotion management capabilities.
29
30 A customer tiers system allows you to segment customers based on their purchase history and automatically apply promotions to their carts. Customers are assigned to tiers based on their total purchase value, and each tier can have an associated promotion that is automatically applied to their carts.
31
32 ## Summary
33
34 By following this tutorial, you will learn how to:
35
36 - Install and set up Medusa.
37 - Create a Tier Module to manage customer tiers and tier rules.
38 - Customize the Medusa Admin to manage tiers.
39 - Automatically assign customers to tiers based on their purchase history.
40 - Automatically apply tier promotions to customer carts.
41 - Customize the Next.js Starter Storefront to display tier information to customers.
42
43 You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer.
44
45 ![Diagram illustrating how the customer tiers system works, starting from the customer adding a product to the cart, Medusa applying the tier promotion automatically, customer placing the order, and Medusa updating the customer's tier.](https://res.cloudinary.com/dza7lstvk/image/upload/v1764079847/Medusa%20Resources/customer-tiers_hx504i.jpg)
46
47 <CardList items={[
48 {
49 href: "https://github.com/medusajs/examples/tree/main/customer-tiers",
50 title: "Customer Tiers Repository",
51 text: "Find the full code for this guide in this repository.",
52 icon: Github,
53 },
54 {
55 href: "https://res.cloudinary.com/dza7lstvk/raw/upload/v1764080003/OpenApi/openapi_bzizgg.yaml",
56 title: "OpenAPI Specs for Postman",
57 text: "Import this OpenAPI Specs file into tools like Postman.",
58 icon: PlaySolid,
59 },
60 ]} />
61
62 ---
63
64 ## Step 1: Install a Medusa Application
65
66 <Prerequisites items={[
67 {
68 text: "Node.js v20.19.0+ or v22.12.0+",
69 link: "https://nodejs.org/en/download"
70 },
71 {
72 text: "Git CLI tool",
73 link: "https://git-scm.com/downloads"
74 },
75 {
76 text: "PostgreSQL",
77 link: "https://www.postgresql.org/download/"
78 }
79 ]} />
80
81 Start by installing the Medusa application on your machine with the following command:
82
83 ```bash npx2yarnExec
84 npx create-medusa-app@latest
85 ```
86
87 You'll first be asked for the project's name. Then, when asked whether you want to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose Yes.
88
89 Afterward, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory.
90
91 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterward, you can log in with the new user and explore the dashboard.
92
93 <Note title="Ran into Errors">
94
95 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
96
97 </Note>
98
99 <Note>
100
101 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
102
103 </Note>
104
105 ---
106
107 ## Step 2: Create Tier Module
108
109 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 affecting your setup.
110
111 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.
112
113 In this step, you'll build a Tier Module that defines the necessary data models to store and manage customer tiers and tier rules.
114
115 <Note>
116
117 Refer to the [Modules documentation](!docs!/learn/fundamentals/modules) to learn more.
118
119 </Note>
120
121 ### Create Module Directory
122
123 Modules are created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/tier`.
124
125 ### Create Data Models
126
127 A data model represents a table in the database. You create data models using Medusa's Data Model Language (DML), which simplifies defining a table's columns, relations, and indexes with straightforward methods and configurations.
128
129 <Note>
130
131 Refer to the [Data Models documentation](!docs!/learn/fundamentals/modules#1-create-data-model) to learn more.
132
133 </Note>
134
135 For the Tier Module, you need to define two data models:
136
137 1. `Tier`: Represents a customer tier (for example, Bronze, Silver, Gold).
138 2. `TierRule`: Represents the rules that determine when a customer qualifies for a tier (for example, minimum purchase value in a specific currency).
139
140 So, create the file `src/modules/tier/models/tier.ts` with the following content:
141
142 ```ts title="src/modules/tier/models/tier.ts"
143 import { model } from "@medusajs/framework/utils"
144 import { TierRule } from "./tier-rule"
145
146 export const Tier = model.define("tier", {
147 id: model.id().primaryKey(),
148 name: model.text(),
149 promo_id: model.text().nullable(),
150 tier_rules: model.hasMany(() => TierRule, {
151 mappedBy: "tier",
152 }),
153 })
154 ```
155
156 You define the `Tier` 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.
157
158 The `Tier` data model has the following properties:
159
160 - `id`: A unique ID for the tier.
161 - `name`: The name of the tier (for example, "Bronze", "Silver", "Gold").
162 - `promo_id`: The ID of the promotion associated with this tier.
163 - `tier_rules`: A one-to-many relationship with `TierRule` data model. Ignore the type error as you'll define the `TierRule` data model next.
164
165 <Note>
166
167 Learn more about defining data model properties in the [Property Types documentation](!docs!/learn/fundamentals/data-models/properties).
168
169 </Note>
170
171 Next, create the file `src/modules/tier/models/tier-rule.ts` with the following content:
172
173 ```ts title="src/modules/tier/models/tier-rule.ts"
174 import { model } from "@medusajs/framework/utils"
175 import { Tier } from "./tier"
176
177 export const TierRule = model.define("tier_rule", {
178 id: model.id().primaryKey(),
179 min_purchase_value: model.number(),
180 currency_code: model.text(),
181 tier: model.belongsTo(() => Tier, {
182 mappedBy: "tier_rules",
183 }),
184 })
185 .indexes([
186 {
187 on: ["tier_id", "currency_code"],
188 unique: true,
189 },
190 ])
191 ```
192
193 You define the `TierRule` data model with the following properties:
194
195 - `id`: A unique ID for the tier rule.
196 - `min_purchase_value`: The minimum purchase value required to qualify for the tier.
197 - `currency_code`: The currency code for which this rule applies (for example, `usd`, `eur`).
198 - `tier`: A many-to-one relationship with the `Tier` data model.
199
200 You also add a unique index on `tier_id` and `currency_code` to ensure that each tier has only one rule per currency.
201
202 <Note title="Tip">
203
204 Alternatively, you can store the minimum purchase value for a specific currency, then integrate with real-time exchange rate services to convert values between currencies. However, for simplicity, this tutorial uses fixed amounts for each currency.
205
206 </Note>
207
208 ### Create Module's Service
209
210 You now have the necessary data models in the Tier Module, but you'll need to manage their records. You do this by creating a service in the module.
211
212 A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to the database to manage your data models, or connect to a third-party service, which is useful when integrating with external systems.
213
214 <Note>
215
216 Refer to the [Module Service documentation](!docs!/learn/fundamentals/modules#2-create-service) to learn more.
217
218 </Note>
219
220 To create the Tier Module's service, create the file `src/modules/tier/service.ts` with the following content:
221
222 ```ts title="src/modules/tier/service.ts"
223 import { MedusaService } from "@medusajs/framework/utils"
224 import { Tier } from "./models/tier"
225 import { TierRule } from "./models/tier-rule"
226
227 class TierModuleService extends MedusaService({
228 Tier,
229 TierRule,
230 }) {
231 }
232
233 export default TierModuleService
234 ```
235
236 The `TierModuleService` extends `MedusaService` from the Modules SDK, which generates a class with data-management methods for your module's data models. This saves you time implementing Create, Read, Update, and Delete (CRUD) methods.
237
238 So, the `TierModuleService` class now has methods like `createTiers`, `retrieveTier`, `listTierRules`, and more.
239
240 <Note>
241
242 Find all methods generated by the `MedusaService` in [the Service Factory reference](../../../service-factory-reference/page.mdx).
243
244 </Note>
245
246 ### Export Module Definition
247
248 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.
249
250 So, create the file `src/modules/tier/index.ts` with the following content:
251
252 ```ts title="src/modules/tier/index.ts"
253 import TierModuleService from "./service"
254 import { Module } from "@medusajs/framework/utils"
255
256 export const TIER_MODULE = "tier"
257
258 export default Module(TIER_MODULE, {
259 service: TierModuleService,
260 })
261 ```
262
263 You use the `Module` function from the Modules SDK to create the module's definition. It accepts two parameters:
264
265 1. The module's name, which is `tier`.
266 2. An object with a required property `service` indicating the module's service.
267
268 You also export the module's name as `TIER_MODULE` so you can reference it later.
269
270 ### Add Module to Medusa's Configurations
271
272 Once you finish building the module, add it to Medusa's configurations to start using it.
273
274 In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
275
276 ```ts title="medusa-config.ts"
277 module.exports = defineConfig({
278 // ...
279 modules: [
280 {
281 resolve: "./src/modules/tier",
282 },
283 ],
284 })
285 ```
286
287 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.
288
289 ### Generate Migrations
290
291 Since data models represent tables in the database, you define how to create them in the database using migrations. A migration is a TypeScript or JavaScript file that defines database changes made by a module.
292
293 <Note>
294
295 Refer to the [Migrations documentation](!docs!/learn/fundamentals/modules#5-generate-migrations) to learn more.
296
297 </Note>
298
299 Medusa's CLI tool can generate the migrations for you. To generate a migration for the Tier Module, run the following command in the `apps/backend` directory:
300
301 ```bash npx2yarn
302 npx medusa db:generate tier
303 ```
304
305 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/tier` that holds the generated migration.
306
307 Then, to reflect these migrations on the database, run the following command:
308
309 ```bash npx2yarn
310 npx medusa db:migrate
311 ```
312
313 The tables for the `Tier` and `TierRule` data models are now created in the database.
314
315 ---
316
317 ## Step 3: Define Module Links
318
319 When you defined the `Tier` data model, you added properties that store IDs of records managed by other modules. For example, the `promo_id` property stores a promotion ID, but promotions are managed by the [Promotion Module](../../../commerce-modules/promotion/page.mdx).
320
321 Medusa integrates modules into your application without side effects by isolating them from one another. This means you can't directly create relationships between data models in your module and data models in other modules.
322
323 Instead, Medusa provides a mechanism to define links between data models and to retrieve and manage linked records while maintaining module isolation. Links are useful for defining associations between data models in different modules or for extending a model in another module to associate custom properties with it.
324
325 <Note>
326
327 Refer to the [Module Isolation documentation](!docs!/learn/fundamentals/modules/isolation) to learn more.
328
329 </Note>
330
331 In this step, you'll define:
332
333 1. A link between the Tier Module's `Tier` data model and the Customer Module's `Customer` data model.
334 2. A read-only link between the Tier Module's `Tier` data model and the Promotion Module's `Promotion` data model.
335
336 ### Define Tier ↔ Customer Link
337
338 You can define links between data models in a TypeScript or JavaScript file under the `src/links` directory. So, create the file `src/links/tier-customer.ts` with the following content:
339
340 ```ts title="src/links/tier-customer.ts"
341 import { defineLink } from "@medusajs/framework/utils"
342 import TierModule from "../modules/tier"
343 import CustomerModule from "@medusajs/medusa/customer"
344
345 export default defineLink(
346 {
347 linkable: TierModule.linkable.tier,
348 filterable: ["id"],
349 },
350 {
351 linkable: CustomerModule.linkable.customer,
352 isList: true,
353 }
354 )
355 ```
356
357 You define a link using the `defineLink` function from the Modules SDK. It accepts two parameters:
358
359 1. An object indicating the first data model in the link. You pass the link configurations for the `Tier` data model from the Tier Module. You also specify the `id` property as filterable, allowing you to filter customers by their tier later using the [Index Module](!docs!/learn/fundamentals/query/index-module).
360 2. An object indicating the second data model in the link. You pass the linkable configurations of the Customer Module's `Customer` data model. You set `isList` to `true` because a tier can have multiple customers.
361
362 This link allows you to retrieve and manage customers associated with a tier, and vice versa.
363
364 ### Define Tier ↔ Promotion Link
365
366 Next, create the file `src/links/tier-promotion.ts` with the following content:
367
368 ```ts title="src/links/tier-promotion.ts"
369 import { defineLink } from "@medusajs/framework/utils"
370 import TierModule from "../modules/tier"
371 import PromotionModule from "@medusajs/medusa/promotion"
372
373 export default defineLink(
374 {
375 linkable: TierModule.linkable.tier,
376 field: "promo_id",
377 },
378 PromotionModule.linkable.promotion,
379 {
380 readOnly: true,
381 }
382 )
383 ```
384
385 You define a link between the `Tier` data model and the `Promotion` data model. You specify that the `promo_id` field in the `Tier` data model holds the ID of the linked promotion. You also set `readOnly` to `true` because you only want to retrieve the linked promotion without managing the link itself.
386
387 You can now retrieve the promotion associated with a tier, as you'll see in later steps.
388
389 ---
390
391 ## Step 4: Create Tier
392
393 Now that you have the Tier Module set up, you'll add the functionality to create tiers. This requires creating:
394
395 - A [workflow](!docs!/learn/fundamentals/workflows) with steps to create a tier.
396 - An [API route](!docs!/learn/fundamentals/api-routes) that exposes the workflow's functionality to client applications.
397
398 Later, you'll customize the Medusa Admin to allow creating tiers from the dashboard.
399
400 ### a. Create Tier Workflow
401
402 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 can track the workflow's execution progress, define rollback logic, and configure other advanced features.
403
404 <Note>
405
406 Learn more about workflows in the [Workflows documentation](!docs!/learn/fundamentals/workflows).
407
408 </Note>
409
410 The workflow to create a tier has the following steps:
411
412 <WorkflowDiagram
413 workflow={{
414 name: "createTierWorkflow",
415 steps: [
416 {
417 type: "when",
418 condition: "!!data.input.promo_id",
419 steps: [
420 {
421 type: "step",
422 name: "useQueryGraphStep",
423 description: "Retrieve the promotion if specified to validate it exists.",
424 link: "/references/helper-steps/useQueryGraphStep",
425 depth: 1
426 },
427 ],
428 depth: 1,
429 },
430 {
431 type: "step",
432 name: "createTierStep",
433 description: "Create the tier.",
434 depth: 2,
435 },
436 {
437 type: "when",
438 condition: "!!data.input.tier_rules?.length",
439 steps: [
440 {
441 type: "step",
442 name: "createTierRulesStep",
443 description: "Create the tier rules.",
444 depth: 1
445 },
446 ],
447 depth: 3,
448 },
449 {
450 type: "step",
451 name: "useQueryGraphStep",
452 description: "Retrieve the created tier with its rules.",
453 link: "/references/helper-steps/useQueryGraphStep",
454 depth: 4,
455 },
456 ]
457 }}
458 />
459
460 Medusa provides the last step out of the box. You'll create the other steps before creating the workflow.
461
462
463 #### Create Tier Step
464
465 First, you'll create a step that creates a tier. Create the file `src/workflows/steps/create-tier.ts` with the following content:
466
467 ```ts title="src/workflows/steps/create-tier.ts"
468 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
469 import { TIER_MODULE } from "../../modules/tier"
470
471 export type CreateTierStepInput = {
472 name: string
473 promo_id: string | null
474 }
475
476 export const createTierStep = createStep(
477 "create-tier",
478 async (input: CreateTierStepInput, { container }) => {
479 const tierModuleService = container.resolve(TIER_MODULE)
480
481 const tier = await tierModuleService.createTiers({
482 name: input.name,
483 promo_id: input.promo_id || null,
484 })
485
486 return new StepResponse(tier, tier)
487 },
488 async (tier, { container }) => {
489 if (!tier) {
490 return
491 }
492
493 const tierModuleService = container.resolve(TIER_MODULE)
494 await tierModuleService.deleteTiers(tier.id)
495 }
496 )
497 ```
498
499 You create a step with `createStep` from the Workflows SDK. It accepts three parameters:
500
501 1. The step's unique name, which is `create-tier`.
502 2. An async function that receives two parameters:
503 - The step's input, which is in this case an object with the tier's properties.
504 - 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.
505 3. An async compensation function that undoes the actions performed in the step if an error occurs during the workflow's execution.
506
507 In the step function, you resolve the Tier Module's service from the Medusa container and create the tier using the `createTiers` method.
508
509 A step function must return a `StepResponse` instance. The `StepResponse` constructor accepts two parameters:
510
511 1. The step's output, which is the tier created.
512 2. Data to pass to the step's compensation function.
513
514 In the compensation function, you delete the tier if an error occurs during the workflow's execution.
515
516 #### Create Tier Rules Step
517
518 The `createTierRulesStep` creates tier rules for a tier.
519
520 Create the file `src/workflows/steps/create-tier-rules.ts` with the following content:
521
522 ```ts title="src/workflows/steps/create-tier-rules.ts"
523 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
524 import { TIER_MODULE } from "../../modules/tier"
525
526 export type CreateTierRulesStepInput = {
527 tier_id: string
528 tier_rules: Array<{
529 min_purchase_value: number
530 currency_code: string
531 }>
532 }
533
534 export const createTierRulesStep = createStep(
535 "create-tier-rules",
536 async (input: CreateTierRulesStepInput, { container }) => {
537 const tierModuleService = container.resolve(TIER_MODULE)
538
539 const createdRules = await tierModuleService.createTierRules(
540 input.tier_rules.map((rule) => ({
541 tier_id: input.tier_id,
542 min_purchase_value: rule.min_purchase_value,
543 currency_code: rule.currency_code,
544 }))
545 )
546
547 return new StepResponse(createdRules, createdRules)
548 },
549 async (createdRules, { container }) => {
550 if (!createdRules?.length) {
551 return
552 }
553
554 const tierModuleService = container.resolve(TIER_MODULE)
555 await tierModuleService.deleteTierRules(createdRules.map((rule) => rule.id))
556 }
557 )
558 ```
559
560 This step receives the rules to create with the ID of the tier they belong to.
561
562 In the step function, you create the tier rules. In the compensation function, you delete them if an error occurs during the workflow's execution.
563
564
565 #### Create Tier Workflow
566
567 You can now create the workflow that creates a tier.
568
569 Create the file `src/workflows/create-tier.ts` with the following content:
570
571 ```ts title="src/workflows/create-tier.ts" collapsibleLines="1-10" expandButtonLabel="Show Imports"
572 import {
573 createWorkflow,
574 WorkflowResponse,
575 transform,
576 when,
577 } from "@medusajs/framework/workflows-sdk"
578 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
579 import { createTierStep } from "./steps/create-tier"
580 import { createTierRulesStep } from "./steps/create-tier-rules"
581
582 export type CreateTierWorkflowInput = {
583 name: string
584 promo_id?: string | null
585 tier_rules?: Array<{
586 min_purchase_value: number
587 currency_code: string
588 }>
589 }
590
591 export const createTierWorkflow = createWorkflow(
592 "create-tier",
593 (input: CreateTierWorkflowInput) => {
594 // Validate promotion if provided
595 when({ input }, (data) => !!data.input.promo_id)
596 .then(() => {
597 useQueryGraphStep({
598 entity: "promotion",
599 fields: ["id"],
600 filters: {
601 id: input.promo_id!,
602 },
603 options: {
604 throwIfKeyNotFound: true,
605 },
606 })
607 })
608 const promoId = transform(
609 { input },
610 ({ input }) => input.promo_id || null
611 )
612
613 // Create the tier
614 const tier = createTierStep({
615 name: input.name,
616 promo_id: promoId,
617 })
618
619 // Create tier rules if provided
620 when({ input }, (data) => {
621 return !!data.input.tier_rules?.length
622 }).then(() => {
623 return createTierRulesStep({
624 tier_id: tier.id,
625 tier_rules: input.tier_rules!,
626 })
627 })
628
629 // Retrieve the created tier with rules
630 const { data: tiers } = useQueryGraphStep({
631 entity: "tier",
632 fields: ["*", "tier_rules.*"],
633 filters: {
634 id: tier.id,
635 },
636 }).config({ name: "retrieve-tier" })
637
638 return new WorkflowResponse({
639 tier: tiers[0],
640 })
641 }
642 )
643 ```
644
645 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
646
647 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 with the tier's details.
648
649 In the workflow's constructor function, you:
650
651 - Use [when-then](!docs!/learn/fundamentals/workflows/conditions) to check whether the promotion ID is provided and retrieve the promotion to validate that it exists.
652 - By specifying the `throwIfKeyNotFound` option, the `useQueryGraphStep` throws an error if the promotion isn't found, which stops the workflow's execution.
653 - This step uses [Query](!docs!/learn/fundamentals/query) under the hood to retrieve data across modules.
654 - Create the tier using the `createTierStep`.
655 - Use [when-then](!docs!/learn/fundamentals/workflows/conditions) to conditionally create tier rules if they're provided using the `createTierRulesStep`.
656 - Retrieve the created tier with its rules using `useQueryGraphStep`.
657
658 Finally, you return a `WorkflowResponse` with the created tier.
659
660 <Note title="Tip">
661
662 In workflows, you need `when-then` to check conditions based on execution values. Learn more in the [Conditions](!docs!/learn/fundamentals/workflows/conditions) workflow documentation.
663
664 </Note>
665
666 ### b. Create Tier API Route
667
668 Now that you have the workflow to create tiers, you'll create an API route that exposes this functionality to client applications.
669
670 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`.
671
672 <Note>
673
674 Refer to the [API routes](!docs!/learn/fundamentals/api-routes) documentation to learn more about them.
675
676 </Note>
677
678 Create the file `src/api/admin/tiers/route.ts` with the following content:
679
680 <Note>
681
682 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
683
684 </Note>
685
686 ```ts title="src/api/admin/tiers/route.ts"
687 import {
688 MedusaRequest,
689 MedusaResponse,
690 } from "@medusajs/framework/http"
691 import { z } from "@medusajs/framework/zod"
692 import { createTierWorkflow } from "../../../workflows/create-tier"
693
694 export const CreateTierSchema = z.object({
695 name: z.string(),
696 promo_id: z.string().nullable(),
697 tier_rules: z.array(z.object({
698 min_purchase_value: z.number(),
699 currency_code: z.string(),
700 })),
701 })
702
703 type CreateTierInput = z.infer<typeof CreateTierSchema>
704
705 export async function POST(
706 req: MedusaRequest<CreateTierInput>,
707 res: MedusaResponse
708 ): Promise<void> {
709 const { name, promo_id, tier_rules } = req.validatedBody
710
711 const { result } = await createTierWorkflow(req.scope).run({
712 input: {
713 name,
714 promo_id: promo_id || null,
715 tier_rules: tier_rules || [],
716 },
717 })
718
719 res.json({ tier: result.tier })
720 }
721 ```
722
723 First, you define a Zod schema that validates the request body.
724
725 Then, you export a `POST` function, which exposes a `POST` API route at `/admin/tiers`.
726
727 In the route handler function, you execute the `createTierWorkflow` by invoking it, passing it the Medusa container, then executing its `run` method.
728
729 You return the created tier in the response.
730
731 You'll test out this API route later when you customize the Medusa Admin dashboard.
732
733 ### c. Apply Validation Middleware
734
735 To ensure incoming request bodies are validated, you need to apply a [middleware](!docs!/learn/fundamentals/api-routes/middlewares).
736
737 To apply a middleware to the API route, create the file `src/api/middlewares.ts` with the following content:
738
739 ```ts title="src/api/middlewares.ts"
740 import {
741 defineMiddlewares,
742 validateAndTransformBody,
743 } from "@medusajs/framework/http"
744 import { CreateTierSchema } from "./admin/tiers/route"
745
746 export default defineMiddlewares({
747 routes: [
748 {
749 matcher: "/admin/tiers",
750 methods: ["POST"],
751 middlewares: [validateAndTransformBody(CreateTierSchema)],
752 },
753 ],
754 })
755 ```
756
757 You apply the `validateAndTransformBody` middleware to the `POST` route of the `/admin/tiers` path, passing it the Zod schema you created in the route file.
758
759 Any request that doesn't conform to the schema will receive a `400` Bad Request response.
760
761 <Note title="Tip">
762
763 Refer to the [Middlewares](!docs!/learn/fundamentals/api-routes/middlewares) documentation to learn more.
764
765 </Note>
766
767 ---
768
769 ## Step 5: Retrieve Tiers API Route
770
771 In this step, you'll add an API route that retrieves tiers. You'll use this API route later when you customize the Medusa Admin to display tiers in the Medusa Admin.
772
773 To create the API route, add the following function to the `src/api/admin/tiers/route.ts` file:
774
775 ```ts title="src/api/admin/tiers/route.ts"
776 export async function GET(
777 req: MedusaRequest,
778 res: MedusaResponse
779 ): Promise<void> {
780 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
781
782 const { data: tiers, metadata } = await query.graph({
783 entity: "tier",
784 ...req.queryConfig,
785 })
786
787 res.json({
788 tiers,
789 count: metadata?.count || 0,
790 offset: metadata?.skip || 0,
791 limit: metadata?.take || 15,
792 })
793 }
794 ```
795
796 You export a `GET` route handler function, which will expose a `GET` API route at `/admin/tiers`.
797
798 In the route handler, you resolve Query from the Medusa container and use it to retrieve a list of tiers.
799
800 Notice that you spread the `req.queryConfig` object into the `query.graph` method. This allows clients to pass query parameters for pagination and configure returned fields. You'll learn how to set these configurations in a bit.
801
802 You return the list of tiers in the response.
803
804 You'll test out this API route later when you customize the Medusa Admin dashboard.
805
806 ### Apply Query Configurations Middleware
807
808 Next, you need to apply a middleware that validates the query parameters passed to the request, and sets the default Query configurations.
809
810 In `src/api/middlewares.ts`, add the following imports at the top of the file:
811
812 ```ts title="src/api/middlewares.ts"
813 import {
814 validateAndTransformQuery,
815 } from "@medusajs/framework/http"
816 import { createFindParams } from "@medusajs/medusa/api/utils/validators"
817 ```
818
819 Then, add the following object to the `routes` array passed to `defineMiddlewares`:
820
821 ```ts title="src/api/middlewares.ts"
822 export default defineMiddlewares({
823 routes: [
824 // ...
825 {
826 matcher: "/admin/tiers",
827 methods: ["GET"],
828 middlewares: [validateAndTransformQuery(createFindParams(), {
829 isList: true,
830 defaults: ["id", "name", "promotion.id", "promotion.code"],
831 })],
832 },
833 ],
834 })
835 ```
836
837 You apply the `validateAndTransformQuery` middleware to `GET` requests sent to the `/admin/tiers` route, passing it the `createFindParams` utility function to create a schema that validates common query parameters like `limit`, `offset`, `fields`, and `order`.
838
839 You set the following configurations:
840
841 - `isList`: Set to `true` to indicate that the API route returns a list of records.
842 - `defaults`: An array of fields to return by default if the client doesn't specify any fields in the request.
843
844 <Note>
845
846 Refer to the [Request Query Configuration](!docs!/learn/fundamentals/query#request-query-configurations) documentation to learn more about this middleware and the query configurations.
847
848 </Note>
849
850 ---
851
852 ## Step 6: Manage Customer Tiers in Medusa Admin
853
854 In this step, you'll customize the Medusa Admin to display and create tiers.
855
856 The Medusa Admin dashboard is customizable, allowing you to insert widgets into existing pages, or create new pages.
857
858 <Note title="Tip">
859
860 Refer to the [Admin Development](!docs!/learn/fundamentals/admin) documentation to learn more.
861
862 </Note>
863
864 ### a. Initialize JS SDK
865
866 To send requests to the Medusa server, you'll use the [JS SDK](../../../js-sdk/page.mdx). It's already installed in your Medusa project, but you need to initialize it before using it in your customizations.
867
868 Create the file `src/admin/lib/sdk.ts` with the following content:
869
870 export const sdkHighlights = [
871 ["3", "new Medusa", "Initialize the Medusa JS SDK."],
872 ["4", "baseUrl", "Backend server URL."],
873 ["5", "debug", "Enable debug mode in development."],
874 ["7", "type: \"session\"", "Use session-based authentication."]
875 ]
876
877 ```ts title="src/admin/lib/sdk.ts" highlights={sdkHighlights}
878 import Medusa from "@medusajs/js-sdk"
879
880 export const sdk = new Medusa({
881 baseUrl: import.meta.env.MEDUSA_BACKEND_URL || "http://localhost:9000",
882 debug: import.meta.env.NODE_ENV === "development",
883 auth: {
884 type: "session",
885 },
886 })
887 ```
888
889 Learn more about the initialization options in the [JS SDK](../../../js-sdk/page.mdx) reference.
890
891 ### b. Tiers UI Route
892
893 Next, you'll create a UI route that displays the list of tiers in the Medusa Admin.
894
895 A UI route is a React component that specifies the content to be shown in a new page in the Medusa Admin dashboard.
896
897 <Note>
898
899 Learn more about UI routes in the [UI Routes documentation](!docs!/learn/fundamentals/admin/ui-routes).
900
901 </Note>
902
903 To create the UI route, create the file `src/admin/routes/tiers/page.tsx` with the following content:
904
905 ```tsx title="src/admin/routes/tiers/page.tsx" collapsibleLines="1-16" expandButtonLabel="Show Imports"
906 import { defineRouteConfig } from "@medusajs/admin-sdk"
907 import {
908 Container,
909 Heading,
910 Button,
911 DataTable,
912 createDataTableColumnHelper,
913 useDataTable,
914 DataTablePaginationState,
915 } from "@medusajs/ui"
916 import { useNavigate, Link } from "react-router-dom"
917 import { UserGroup } from "@medusajs/icons"
918 import { useQuery } from "@tanstack/react-query"
919 import { useState, useMemo } from "react"
920 import { sdk } from "../../lib/sdk"
921
922 export type Tier = {
923 id: string
924 name: string
925 promotion: {
926 id: string
927 code: string
928 } | null
929 tier_rules: Array<{
930 id: string
931 min_purchase_value: number
932 currency_code: string
933 }>
934 }
935
936 type TiersResponse = {
937 tiers: Tier[]
938 count: number
939 offset: number
940 limit: number
941 }
942
943 const columnHelper = createDataTableColumnHelper<Tier>()
944
945 const columns = [
946 columnHelper.accessor("name", {
947 header: "Name",
948 enableSorting: true,
949 }),
950 columnHelper.accessor("promotion", {
951 header: "Promotion",
952 cell: ({ getValue }) => {
953 const promotion = getValue()
954 return promotion ? <Link to={`/promotions/${promotion.id}`}>{promotion.code}</Link> : "-"
955 },
956 }),
957 ]
958
959 const TiersPage = () => {
960 const navigate = useNavigate()
961 const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
962 const limit = 15
963 const [pagination, setPagination] = useState<DataTablePaginationState>({
964 pageSize: limit,
965 pageIndex: 0,
966 })
967
968 const offset = useMemo(() => {
969 return pagination.pageIndex * limit
970 }, [pagination])
971
972 const { data, isLoading } = useQuery({
973 queryFn: () =>
974 sdk.client.fetch<TiersResponse>("/admin/tiers", {
975 method: "GET",
976 query: {
977 limit,
978 offset,
979 },
980 }),
981 queryKey: ["tiers", "list", limit, offset],
982 })
983
984 const tiers = data?.tiers || []
985
986 const table = useDataTable({
987 columns,
988 data: tiers,
989 getRowId: (tier) => tier.id,
990 rowCount: data?.count || 0,
991 isLoading,
992 pagination: {
993 state: pagination,
994 onPaginationChange: setPagination,
995 },
996 onRowClick: (_event, row) => {
997 // TODO navigate to the tier details page
998 },
999 })
1000
1001 return (
1002 <Container className="divide-y p-0">
1003 <DataTable instance={table}>
1004 <DataTable.Toolbar className="flex items-center justify-between px-6 py-4">
1005 <Heading level="h1">Customer Tiers</Heading>
1006 <Button onClick={() => setIsCreateModalOpen(true)}>
1007 Create Tier
1008 </Button>
1009 </DataTable.Toolbar>
1010 <DataTable.Table />
1011 <DataTable.Pagination />
1012 </DataTable>
1013 {/* TODO show create tier modal */}
1014 </Container>
1015 )
1016 }
1017
1018 export const config = defineRouteConfig({
1019 label: "Customer Tiers",
1020 icon: UserGroup,
1021 })
1022
1023 export default TiersPage
1024 ```
1025
1026 A UI route file must export a React component as the default export. This component is rendered when the user navigates to the UI route. It can also export a route configuration object that defines the UI route's label and icon in the sidebar.
1027
1028 In the component, you:
1029
1030 - Define state variables to configure pagination.
1031 - Fetch the tiers using the JS SDK and Tanstack Query. By using Tanstack Query, you can easily manage the data fetching state, handle pagination, and cache the data.
1032 - Create a DataTable instance from [Medusa UI](!ui!). You pass the columns, data, and pagination configurations to the hook.
1033 - Render the DataTable component with a toolbar and pagination controls.
1034
1035 ### c. Create Tier Modal Component
1036
1037 Next, you'll create a component that shows a form to create a tier in a modal.
1038
1039 Create the file `src/admin/components/create-tier-modal.tsx` with the following content:
1040
1041 ```tsx title="src/admin/components/create-tier-modal.tsx" collapsibleLines="1-9" expandButtonLabel="Show Imports"
1042 import { FocusModal, Heading, Label, Input, Button, Select, IconButton, toast } from "@medusajs/ui"
1043 import { Trash } from "@medusajs/icons"
1044 import { useForm, Controller, FormProvider } from "react-hook-form"
1045 import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
1046 import { sdk } from "../lib/sdk"
1047 import { useState } from "react"
1048 import { useNavigate } from "react-router-dom"
1049 import { Tier } from "../routes/tiers/page"
1050
1051 type CreateTierFormData = {
1052 name: string
1053 promo_id: string | null
1054 tier_rules: Array<{
1055 min_purchase_value: number
1056 currency_code: string
1057 }>
1058 }
1059
1060 type CreateTierModalProps = {
1061 open: boolean
1062 onOpenChange: (open: boolean) => void
1063 }
1064
1065 export const CreateTierModal = ({ open, onOpenChange }: CreateTierModalProps) => {
1066 const navigate = useNavigate()
1067 const queryClient = useQueryClient()
1068 const [tierRules, setTierRules] = useState<{
1069 currency_code: string
1070 min_purchase_value: number
1071 }[]>([])
1072
1073 const form = useForm<CreateTierFormData>({
1074 defaultValues: {
1075 name: "",
1076 promo_id: null,
1077 tier_rules: [],
1078 },
1079 })
1080
1081 // TODO add queries and mutations
1082 }
1083 ```
1084
1085 You define a component that receives the modal's open state and a function to close it.
1086
1087 In the component, so far you define necessary variables and initialize the form.
1088
1089 Next, you'll define Tanstack queries and mutations to retrieve form data and create the tier. Replace the `TODO` with the following:
1090
1091 ```tsx title="src/admin/components/create-tier-modal.tsx"
1092 const { data: promotionsData } = useQuery({
1093 queryFn: () => sdk.admin.promotion.list(),
1094 queryKey: ["promotions", "list"],
1095 })
1096
1097 const { data: storeData } = useQuery({
1098 queryFn: () =>
1099 sdk.admin.store.list({
1100 fields: "id,supported_currencies.*,supported_currencies.currency.*",
1101 }),
1102 queryKey: ["store"],
1103 })
1104
1105 const createTierMutation = useMutation({
1106 mutationFn: async (data: CreateTierFormData) => {
1107 return await sdk.client.fetch<{ tier: Tier }>("/admin/tiers", {
1108 method: "POST",
1109 body: data,
1110 })
1111 },
1112 onSuccess: (data: { tier: Tier }) => {
1113 queryClient.invalidateQueries({ queryKey: ["tiers"] })
1114 form.reset()
1115 setTierRules([])
1116 onOpenChange(false)
1117 // TODO navigate to the new tier page
1118 toast.success("Success", {
1119 description: "Tier created successfully",
1120 position: "top-right",
1121 })
1122 },
1123 onError: (error) => {
1124 toast.error("Error", {
1125 description: error.message,
1126 position: "top-right",
1127 })
1128 },
1129 })
1130
1131 // TODO and function handlers
1132 ```
1133
1134 You retrieve the promotions and store data to populate the form with promotions and supported currencies for rules.
1135
1136 You also define a mutation to create a tier using the `useMutation` hook from Tanstack Query.
1137
1138 Next, you'll add functions to handle form submissions and other actions. Replace the `TODO` with the following:
1139
1140 ```tsx title="src/admin/components/create-tier-modal.tsx"
1141 const handleSubmit = form.handleSubmit((data) => {
1142 createTierMutation.mutate({
1143 ...data,
1144 tier_rules: tierRules,
1145 })
1146 })
1147
1148 const promotions = promotionsData?.promotions || []
1149 const store = storeData?.stores?.[0]
1150 const supportedCurrencies = store?.supported_currencies || []
1151
1152 const getAvailableCurrencies = () => {
1153 const usedCurrencies = new Set(tierRules.map((rule) => rule.currency_code))
1154 return supportedCurrencies.filter((sc) => !usedCurrencies.has(sc.currency_code))
1155 }
1156
1157 const addTierRule = () => {
1158 const availableCurrencies = getAvailableCurrencies()
1159 if (availableCurrencies.length > 0) {
1160 const firstCurrency = availableCurrencies[0].currency_code
1161 setTierRules([
1162 ...tierRules,
1163 {
1164 currency_code: firstCurrency,
1165 min_purchase_value: 0,
1166 },
1167 ])
1168 }
1169 }
1170
1171 const removeTierRule = (index: number) => {
1172 setTierRules(tierRules.filter((_, i) => i !== index))
1173 }
1174
1175 const updateTierRule = (index: number, field: "currency_code" | "min_purchase_value", value: string | number) => {
1176 const updated = [...tierRules]
1177 updated[index] = {
1178 ...updated[index],
1179 [field]: value,
1180 }
1181 setTierRules(updated)
1182 }
1183
1184 // TODO add return statement
1185 ```
1186
1187 You define the following functions:
1188
1189 - `handleSubmit`: Handles form submissions by calling the `createTierMutation`, passing it the form data and tier rules.
1190 - `getAvailableCurrencies`: Returns the available currencies that haven't been used yet in the tier rules.
1191 - `addTierRule`: Adds a new tier rule to the form.
1192 - `removeTierRule`: Removes a tier rule from the form.
1193 - `updateTierRule`: Updates a tier rule in the form.
1194
1195 Finally, replace the `TODO` with the following return statement to render the modal:
1196
1197 ```tsx title="src/admin/components/create-tier-modal.tsx"
1198 return (
1199 <FocusModal open={open} onOpenChange={onOpenChange}>
1200 <FocusModal.Content>
1201 <FormProvider {...form}>
1202 <form onSubmit={handleSubmit} className="flex h-full flex-col overflow-hidden">
1203 <FocusModal.Header>
1204 <div className="flex items-center justify-between">
1205 <Heading level="h1">Create Tier</Heading>
1206 </div>
1207 </FocusModal.Header>
1208 <FocusModal.Body className="flex flex-1 flex-col overflow-y-auto">
1209 <div className="mx-auto flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16">
1210 <div className="flex flex-col gap-y-4">
1211 <Controller
1212 control={form.control}
1213 name="name"
1214 rules={{ required: "Name is required" }}
1215 render={({ field }) => (
1216 <div className="flex flex-col gap-y-2">
1217 <Label size="small" weight="plus">
1218 Name
1219 </Label>
1220 <Input {...field} placeholder="e.g., Bronze, Silver, Gold" />
1221 </div>
1222 )}
1223 />
1224
1225 <Controller
1226 control={form.control}
1227 name="promo_id"
1228 render={({ field }) => (
1229 <div className="flex flex-col gap-y-2">
1230 <Label size="small" weight="plus">
1231 Promotion (Optional)
1232 </Label>
1233 <Select
1234 value={field.value || ""}
1235 onValueChange={(value) => field.onChange(value || null)}
1236 >
1237 <Select.Trigger>
1238 <Select.Value placeholder="Select a promotion" />
1239 </Select.Trigger>
1240 <Select.Content>
1241 {promotions.map((promo) => (
1242 <Select.Item key={promo.id} value={promo.id}>
1243 {promo.code}
1244 </Select.Item>
1245 ))}
1246 </Select.Content>
1247 </Select>
1248 </div>
1249 )}
1250 />
1251
1252 <div className="flex flex-col gap-y-4">
1253 <div className="flex items-center justify-between">
1254 <Label size="small" weight="plus">
1255 Tier Rules
1256 </Label>
1257 <Button
1258 type="button"
1259 variant="secondary"
1260 size="small"
1261 onClick={addTierRule}
1262 disabled={getAvailableCurrencies().length === 0}
1263 >
1264 Add Rule
1265 </Button>
1266 </div>
1267
1268 {tierRules.length === 0 && (
1269 <div className="text-sm text-gray-500">
1270 No tier rules added. Click "Add Rule" to add a rule for a currency.
1271 </div>
1272 )}
1273
1274 {tierRules.map((rule, index) => (
1275 <div key={index} className="flex items-end gap-x-2 rounded-lg border p-4">
1276 <div className="flex flex-1 flex-col gap-y-2">
1277 <Label size="small">Currency</Label>
1278 <Select
1279 value={rule.currency_code}
1280 onValueChange={(value) => updateTierRule(index, "currency_code", value)}
1281 >
1282 <Select.Trigger>
1283 <Select.Value placeholder="Select currency" />
1284 </Select.Trigger>
1285 <Select.Content>
1286 {supportedCurrencies
1287 .filter((sc) => {
1288 // Allow current selection or currencies not used in other rules
1289 return (
1290 sc.currency_code === rule.currency_code ||
1291 !tierRules.some(
1292 (r, i) => i !== index && r.currency_code === sc.currency_code
1293 )
1294 )
1295 })
1296 .map((sc) => (
1297 <Select.Item key={sc.currency_code} value={sc.currency_code}>
1298 {sc.currency.code.toUpperCase()} - {sc.currency.name}
1299 </Select.Item>
1300 ))}
1301 </Select.Content>
1302 </Select>
1303 </div>
1304 <div className="flex flex-1 flex-col gap-y-2">
1305 <Label size="small">Minimum Purchase Value</Label>
1306 <Input
1307 type="number"
1308 min="0"
1309 step="0.01"
1310 value={rule.min_purchase_value}
1311 onChange={(e) =>
1312 updateTierRule(index, "min_purchase_value", parseFloat(e.target.value) || 0)
1313 }
1314 />
1315 </div>
1316 <IconButton
1317 type="button"
1318 variant="transparent"
1319 size="small"
1320 onClick={() => removeTierRule(index)}
1321 >
1322 <Trash />
1323 </IconButton>
1324 </div>
1325 ))}
1326 </div>
1327 </div>
1328 </div>
1329 </FocusModal.Body>
1330 <FocusModal.Footer>
1331 <div className="flex items-center gap-x-2">
1332 <FocusModal.Close asChild>
1333 <Button variant="secondary" size="small">
1334 Cancel
1335 </Button>
1336 </FocusModal.Close>
1337 <Button type="submit" size="small" isLoading={createTierMutation.isPending}>
1338 Create
1339 </Button>
1340 </div>
1341 </FocusModal.Footer>
1342 </form>
1343 </FormProvider>
1344 </FocusModal.Content>
1345 </FocusModal>
1346 )
1347 ```
1348
1349 You display a `FocusModal` from Medusa UI. In the modal, you render a form with the following fields:
1350
1351 1. **Name**: The name of the tier.
1352 2. **Promotion**: A select input to choose a promotion that's associated with the tier.
1353 3. **Tier Rules**: A list of inputs to specify the minimum purchase value required in a specific currency to qualify for the tier.
1354
1355 ### d. Show Create Tier Modal
1356
1357 Next, you'll show the create tier modal when the user clicks the "Create Tier" button in the tiers page.
1358
1359 First, add the following import at the top of `src/admin/routes/tiers/page.tsx`:
1360
1361 ```tsx title="src/admin/routes/tiers/page.tsx"
1362 import { CreateTierModal } from "../../components/create-tier-modal"
1363 ```
1364
1365 Next, replace the `TODO` in the `TiersPage` component's `return` statement with the following:
1366
1367 ```tsx title="src/admin/routes/tiers/page.tsx"
1368 <CreateTierModal open={isCreateModalOpen} onOpenChange={setIsCreateModalOpen} />
1369 ```
1370
1371 You display the create tier modal when the user clicks the "Create Tier" button in the tiers page.
1372
1373 ### Test Customer Tiers in Medusa Admin
1374
1375 To test out the customer tiers in the Medusa Admin, start the Medusa application:
1376
1377 ```bash npm2yarn
1378 npm run dev
1379 ```
1380
1381 Then, open the Medusa Admin dashboard at `http://localhost:9000/app` and log in using the credentials you set up earlier.
1382
1383 You'll find a new sidebar item labeled "Customer Tiers." Click on it to view the list of tiers.
1384
1385 ![Customer Tiers page showing list of tiers](https://res.cloudinary.com/dza7lstvk/image/upload/v1764065196/Medusa%20Resources/CleanShot_2025-11-25_at_12.05.51_2x_u2khaj.png)
1386
1387 Before creating a tier, you should [create a promotion](!user-guide!/promotions/create).
1388
1389 Then, on the Customer Tiers page, click the "Create Tier" button to open the create tier modal.
1390
1391 In the modal, enter the tier's name, select the promotion you created, and add tier rules for the currencies in your store. Once you're done, click the "Create" button to create the tier.
1392
1393 ![Create tier modal showing form to create a tier](https://res.cloudinary.com/dza7lstvk/image/upload/v1764065361/Medusa%20Resources/CleanShot_2025-11-25_at_12.08.18_2x_nid87p.png)
1394
1395 You'll see the new tier in the list of tiers. Later, you'll add a page to view and edit a single tier's details.
1396
1397 ---
1398
1399 ## Step 7: Retrieve Tier API Route
1400
1401 In this step, you'll add an API route that retrieves a tier.
1402
1403 To create the API route, create the file `src/api/admin/tiers/[id]/route.ts` with the following content:
1404
1405 ```ts title="src/api/admin/tiers/[id]/route.ts"
1406 import {
1407 MedusaRequest,
1408 MedusaResponse,
1409 } from "@medusajs/framework/http"
1410 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
1411
1412 export async function GET(
1413 req: MedusaRequest,
1414 res: MedusaResponse
1415 ): Promise<void> {
1416 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
1417 const { id } = req.params
1418
1419 const { data: tiers } = await query.graph({
1420 entity: "tier",
1421 filters: {
1422 id,
1423 },
1424 ...req.queryConfig,
1425 }, {
1426 throwIfKeyNotFound: true,
1427 })
1428
1429 res.json({ tier: tiers[0] })
1430 }
1431 ```
1432
1433 You export a `GET` route handler function, which will expose a `GET` API route at `/admin/tiers/:id`.
1434
1435 In the route handler, you resolve Query from the Medusa container and use it to retrieve the tier with the given ID.
1436
1437 You return the tier in the response.
1438
1439 You'll test out this API route later when you customize the Medusa Admin dashboard.
1440
1441 ### Apply Query Configurations Middleware
1442
1443 Next, you need to apply a middleware that validates the query parameters passed to the request, and sets the default Query configurations.
1444
1445 In `src/api/middlewares.ts`, add the following object to the `routes` array passed to `defineMiddlewares`:
1446
1447 ```ts title="src/api/middlewares.ts"
1448 export default defineMiddlewares({
1449 routes: [
1450 // ...
1451 {
1452 matcher: "/admin/tiers/:id",
1453 methods: ["GET"],
1454 middlewares: [
1455 validateAndTransformQuery(createFindParams(), {
1456 isList: false,
1457 defaults: ["id", "name", "promotion.id", "promotion.code", "tier_rules.*"],
1458 }),
1459 ],
1460 },
1461 ],
1462 })
1463 ```
1464
1465 Similar to before, you define the query configurations for the `GET` request to the `/admin/tiers/:id` route.
1466
1467 ---
1468
1469 ## Step 8: Update Tier
1470
1471 In this step, you'll add the functionality to update tiers. This includes creating a workflow to update a tier and an API route that executes it.
1472
1473 ### a. Update Tier Workflow
1474
1475 The workflow to update a tier has the following steps:
1476
1477 <WorkflowDiagram
1478 workflow={{
1479 name: "updateTierWorkflow",
1480 steps: [
1481 {
1482 type: "step",
1483 name: "useQueryGraphStep",
1484 description: "Retrieve the tier to update.",
1485 link: "/references/helper-steps/useQueryGraphStep",
1486 depth: 1,
1487 },
1488 {
1489 type: "when",
1490 condition: "!!data.input.promo_id",
1491 steps: [
1492 {
1493 type: "step",
1494 name: "useQueryGraphStep",
1495 description: "Retrieve the promotion to validate that it exists.",
1496 link: "/references/helper-steps/useQueryGraphStep",
1497 depth: 1,
1498 }
1499 ],
1500 depth: 2,
1501 },
1502 {
1503 type: "step",
1504 name: "updateTierStep",
1505 description: "Update the tier.",
1506 depth: 3,
1507 },
1508 {
1509 type: "when",
1510 condition: "!!data.input.tier_rules?.length",
1511 steps: [
1512 {
1513 type: "step",
1514 name: "deleteTierRulesStep",
1515 description: "Delete the existing tier rules if new rules are provided.",
1516 depth: 1,
1517 },
1518 {
1519 type: "step",
1520 name: "createTierRulesStep",
1521 description: "Create the new tier rules if provided.",
1522 depth: 2,
1523 }
1524 ],
1525 depth: 4,
1526 },
1527 {
1528 type: "step",
1529 name: "useQueryGraphStep",
1530 description: "Retrieve the updated tier with rules.",
1531 link: "/references/helper-steps/useQueryGraphStep",
1532 depth: 5,
1533 }
1534 ]
1535 }}
1536 />
1537
1538 Medusa provides the `useQueryGraphStep` out-of-the-box, and you've implemented the `createTierRulesStep`. You'll create the other steps before creating the workflow.
1539
1540 #### Update Tier Step
1541
1542 The `updateTierStep` updates a tier.
1543
1544 To create the step, create the file `src/workflows/steps/update-tier.ts` with the following content:
1545
1546 ```ts title="src/workflows/steps/update-tier.ts"
1547 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1548 import { TIER_MODULE } from "../../modules/tier"
1549 import TierModuleService from "../../modules/tier/service"
1550
1551 export type UpdateTierStepInput = {
1552 id: string
1553 name: string
1554 promo_id: string | null
1555 }
1556
1557 export const updateTierStep = createStep(
1558 "update-tier",
1559 async (input: UpdateTierStepInput, { container }) => {
1560 const tierModuleService: TierModuleService = container.resolve(TIER_MODULE)
1561
1562 const originalTier = await tierModuleService.retrieveTier(input.id)
1563
1564 const tier = await tierModuleService.updateTiers(input)
1565
1566 return new StepResponse(tier, originalTier)
1567 },
1568 async (originalInput, { container }) => {
1569 if (!originalInput) {
1570 return
1571 }
1572
1573 const tierModuleService = container.resolve(TIER_MODULE)
1574
1575 await tierModuleService.updateTiers({
1576 id: originalInput.id,
1577 name: originalInput.name,
1578 promo_id: originalInput.promo_id,
1579 })
1580 }
1581 )
1582 ```
1583
1584 The step receives the tier's ID and the details to update.
1585
1586 In the step function, you retrieve the original tier, then you update it. You pass the original tier details to the compensation function.
1587
1588 In the compensation function, you restore the original tier details if an error occurs during the workflow's execution.
1589
1590 #### Delete Tier Rules Step
1591
1592 The `deleteTierRulesStep` deletes tier rules.
1593
1594 To create the step, create the file `src/workflows/steps/delete-tier-rules.ts` with the following content:
1595
1596 ```ts title="src/workflows/steps/delete-tier-rules.ts"
1597 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1598 import { TIER_MODULE } from "../../modules/tier"
1599 import TierModuleService from "../../modules/tier/service"
1600
1601 export type DeleteTierRulesStepInput = {
1602 ids: string[]
1603 }
1604
1605 export const deleteTierRulesStep = createStep(
1606 "delete-tier-rules",
1607 async (input: DeleteTierRulesStepInput, { container }) => {
1608 const tierModuleService: TierModuleService = container.resolve(TIER_MODULE)
1609
1610 // Get existing rules
1611 const existingRules = await tierModuleService.listTierRules({
1612 id: input.ids,
1613 })
1614
1615 // Delete all rules
1616 await tierModuleService.deleteTierRules(input.ids)
1617
1618 return new StepResponse(void 0, existingRules)
1619 },
1620 async (compensationData, { container }) => {
1621 if (!compensationData?.length) {
1622 return
1623 }
1624
1625 const tierModuleService: TierModuleService = container.resolve(TIER_MODULE)
1626 // Restore deleted rules
1627 await tierModuleService.createTierRules(
1628 compensationData.map((rule) => ({
1629 tier_id: rule.tier_id,
1630 min_purchase_value: rule.min_purchase_value,
1631 currency_code: rule.currency_code,
1632 }))
1633 )
1634 }
1635 )
1636 ```
1637
1638 The step receives the IDs of the tier rules to delete.
1639
1640 In the step function, you retrieve the existing rules, then you delete them. You pass the existing rules to the compensation function.
1641
1642 In the compensation function, you restore the existing rules if an error occurs during the workflow's execution.
1643
1644 #### Update Tier Workflow
1645
1646 You can now create the workflow that updates a tier.
1647
1648 Create the file `src/workflows/update-tier.ts` with the following content:
1649
1650 ```ts title="src/workflows/update-tier.ts" collapsibleLines="1-11" expandButtonLabel="Show Imports"
1651 import {
1652 createWorkflow,
1653 WorkflowResponse,
1654 transform,
1655 when,
1656 } from "@medusajs/framework/workflows-sdk"
1657 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
1658 import { updateTierStep } from "./steps/update-tier"
1659 import { deleteTierRulesStep } from "./steps/delete-tier-rules"
1660 import { createTierRulesStep } from "./steps/create-tier-rules"
1661
1662 export type UpdateTierWorkflowInput = {
1663 id: string
1664 name: string
1665 promo_id?: string | null
1666 tier_rules?: Array<{
1667 min_purchase_value: number
1668 currency_code: string
1669 }>
1670 }
1671
1672 export const updateTierWorkflow = createWorkflow(
1673 "update-tier",
1674 (input: UpdateTierWorkflowInput) => {
1675 const { data: tiers } = useQueryGraphStep({
1676 entity: "tier",
1677 fields: ["tier_rules.*"],
1678 filters: {
1679 id: input.id,
1680 },
1681 options: {
1682 throwIfKeyNotFound: true,
1683 },
1684 })
1685 // Validate promotion if provided
1686 when({ input }, (data) => !!data.input.promo_id)
1687 .then(() => {
1688 useQueryGraphStep({
1689 entity: "promotion",
1690 fields: ["id"],
1691 filters: {
1692 id: input.promo_id!,
1693 },
1694 options: {
1695 throwIfKeyNotFound: true,
1696 },
1697 }).config({ name: "retrieve-promotion" })
1698 })
1699 const promoId = transform(
1700 { input },
1701 ({ input }) => input.promo_id || null
1702 )
1703
1704 // Update the tier
1705 updateTierStep({
1706 id: input.id,
1707 name: input.name,
1708 promo_id: promoId,
1709 })
1710
1711 when({ input }, (data) => {
1712 return !!data.input.tier_rules?.length
1713 }).then(() => {
1714 const ids = transform({
1715 tiers,
1716 }, (data) => {
1717 return (data.tiers[0].tier_rules?.map((rule) => rule?.id) || []) as string[]
1718 })
1719 deleteTierRulesStep({
1720 ids,
1721 })
1722 return createTierRulesStep({
1723 tier_id: input.id,
1724 tier_rules: input.tier_rules!,
1725 })
1726 })
1727
1728 // Retrieve the updated tier with rules
1729 const { data: updatedTiers } = useQueryGraphStep({
1730 entity: "tier",
1731 fields: ["*", "tier_rules.*"],
1732 filters: {
1733 id: input.id,
1734 },
1735 }).config({ name: "updated-tier" })
1736
1737 return new WorkflowResponse({
1738 tier: updatedTiers[0],
1739 })
1740 }
1741 )
1742 ```
1743
1744 The workflow receives the details to update the tier.
1745
1746 In the workflow, you:
1747
1748 1. Retrieve the tier to update using the `useQueryGraphStep`.
1749 2. Use `when-then` to check if the promotion ID is provided. If so, use `useQueryGraphStep` to validate that it exists.
1750 2. Update the tier using the `updateTierStep`.
1751 3. If new tier rules are provided, you:
1752 - delete the existing tier rules using the `deleteTierRulesStep`.
1753 - Create the new tier rules using the `createTierRulesStep`.
1754 5. Retrieve the updated tier with rules using the `useQueryGraphStep`.
1755
1756 Finally, you return a `WorkflowResponse` with the updated tier.
1757
1758 <Note>
1759
1760 In workflows, you need `transform` to prepare data based on execution values. Learn more in the [Data Manipulation](!docs!/learn/fundamentals/workflows/variable-manipulation) workflow documentation.
1761
1762 </Note>
1763
1764 ### b. Update Tier API Route
1765
1766 Next, you'll create the API route that exposes the workflow's functionality to client applications.
1767
1768 In `src/api/admin/tiers/[id]/route.ts`, add the following imports at the top of the file:
1769
1770 ```ts title="src/api/admin/tiers/[id]/route.ts"
1771 import { z } from "@medusajs/framework/zod"
1772 import { updateTierWorkflow } from "../../../../workflows/update-tier"
1773 ```
1774
1775 Then, add the following at the end of the file:
1776
1777 ```ts title="src/api/admin/tiers/[id]/route.ts"
1778 export const UpdateTierSchema = z.object({
1779 name: z.string(),
1780 promo_id: z.string().nullable(),
1781 tier_rules: z.array(z.object({
1782 min_purchase_value: z.number(),
1783 currency_code: z.string(),
1784 })),
1785 })
1786
1787 type UpdateTierInput = z.infer<typeof UpdateTierSchema>
1788
1789 export async function POST(
1790 req: MedusaRequest<UpdateTierInput>,
1791 res: MedusaResponse
1792 ): Promise<void> {
1793 const { id } = req.params
1794 const { name, promo_id, tier_rules } = req.validatedBody
1795
1796 const { result } = await updateTierWorkflow(req.scope).run({
1797 input: {
1798 id,
1799 name,
1800 promo_id: promo_id !== undefined ? promo_id : null,
1801 tier_rules: tier_rules || [],
1802 },
1803 })
1804
1805 res.json({ tier: result.tier })
1806 }
1807 ```
1808
1809 You define a Zod schema that validates the request body.
1810
1811 Then, you export a `POST` function, which exposes a `POST` API route at `/admin/tiers/:id`.
1812
1813 In the route handler, you execute the `updateTierWorkflow` and return the updated tier in the response.
1814
1815 You'll test out the API route later when you customize the Medusa Admin dashboard.
1816
1817 #### c. Apply Validation Middleware
1818
1819 Next, you'll apply a validation middleware to the API route.
1820
1821 In `src/api/middlewares.ts`, add the following import at the top of the file:
1822
1823 ```ts title="src/api/middlewares.ts"
1824 import { UpdateTierSchema } from "./admin/tiers/[id]/route"
1825 ```
1826
1827 Then, add a new route object passed to the array in `defineMiddlewares`:
1828
1829 ```ts title="src/api/middlewares.ts"
1830 export default defineMiddlewares({
1831 routes: [
1832 // ...
1833 {
1834 matcher: "/admin/tiers/:id",
1835 methods: ["POST"],
1836 middlewares: [validateAndTransformBody(UpdateTierSchema)],
1837 },
1838 ],
1839 })
1840 ```
1841
1842 You apply the `validateAndTransformBody` middleware to the `POST` route of the `/admin/tiers/:id` path, passing it the Zod schema you created in the route file.
1843
1844 Any request that doesn't conform to the schema will receive a `400` Bad Request response.
1845
1846 ---
1847
1848 ## Step 9: Retrieve Customers in Tier API Route
1849
1850 In this step, you'll add an API route that retrieves customers in a tier. This will be useful to show the customers in the tier's page on the Medusa Admin.
1851
1852 ### a. Retrieve Customers in Tier API Route
1853
1854 To create the API route, create the file `src/api/admin/tiers/[id]/customers/route.ts` with the following content:
1855
1856 ```ts title="src/api/admin/tiers/[id]/customers/route.ts"
1857 import {
1858 MedusaRequest,
1859 MedusaResponse,
1860 } from "@medusajs/framework/http"
1861 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
1862
1863 export async function GET(
1864 req: MedusaRequest,
1865 res: MedusaResponse
1866 ): Promise<void> {
1867 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
1868 const { id } = req.params
1869
1870 // Query customers linked to this tier
1871 const { data: customers, metadata } = await query.index({
1872 entity: "customer",
1873 filters: {
1874 tier: {
1875 id,
1876 },
1877 },
1878 ...req.queryConfig,
1879 })
1880
1881 res.json({
1882 customers,
1883 count: metadata?.estimate_count || 0,
1884 offset: metadata?.skip || 0,
1885 limit: metadata?.take || 15,
1886 })
1887 }
1888 ```
1889
1890 You export a `GET` function, which exposes a `GET` API route at `/admin/tiers/:id/customers`.
1891
1892 In the route handler, you resolve Query from the Medusa container and use it to retrieve customers linked to the tier with the given ID.
1893
1894 Notice that you use the `query.index` method. This method is similar to `query.graph` but allows you to filter by linked records using the [Index Module](!docs!/learn/fundamentals/query/index-module).
1895
1896 You return the customers in the response.
1897
1898 You'll test out this API route later when you customize the Medusa Admin dashboard.
1899
1900 ### b. Apply Query Configurations Middleware
1901
1902 Next, you need to apply a middleware that validates the query parameters passed to the request, and sets the default Query configurations.
1903
1904 In `src/api/middlewares.ts`, add the following object to the `routes` array passed to `defineMiddlewares`:
1905
1906 ```ts title="src/api/middlewares.ts"
1907 export default defineMiddlewares({
1908 routes: [
1909 // ...
1910 {
1911 matcher: "/admin/tiers/:id/customers",
1912 methods: ["GET"],
1913 middlewares: [
1914 validateAndTransformQuery(createFindParams(), {
1915 isList: true,
1916 defaults: ["id", "email", "first_name", "last_name"],
1917 }),
1918 ],
1919 },
1920 ],
1921 })
1922 ```
1923
1924 You apply the `validateAndTransformQuery` middleware to the `GET` route of the `/admin/tiers/:id/customers` path, passing it the `createFindParams` utility function to create a schema that validates common query parameters like `limit`, `offset`, `fields`, and `order`.
1925
1926 You set the following configurations:
1927
1928 - `isList`: Set to `true` to indicate that the API route returns a list of records.
1929 - `defaults`: An array of fields to return by default if the client doesn't specify any fields in the request.
1930
1931 ### c. Install Index Module
1932
1933 The [Index Module](!docs!/learn/fundamentals/query/index-module) is a tool for performing high-performance queries across modules, such as filtering linked modules.
1934
1935 The Index Module is currently experimental, so you need to install and configure it manually.
1936
1937 To install the Index Module, run the following command in the `apps/backend` directory:
1938
1939 ```bash npm2yarn
1940 npm install @medusajs/index
1941 ```
1942
1943 Then, add the following to your Medusa application's configuration file:
1944
1945 ```ts title="medusa-config.ts"
1946 export default config({
1947 modules: [
1948 // ...
1949 {
1950 resolve: "@medusajs/index",
1951 },
1952 ],
1953 })
1954 ```
1955
1956 Next, run the migrations to create the necessary tables for the Index Module in your database:
1957
1958 ```bash npm2yarn
1959 npx medusa db:migrate
1960 ```
1961
1962 Lastly, start the Medusa application to ingest the data into the Index Module:
1963
1964 ```bash npx2yarn
1965 npm run dev
1966 ```
1967
1968 You can now use the Index Module to filter customers by their tier. You'll test out the API route when you customize the Medusa Admin dashboard in the next step.
1969
1970 <Note>
1971
1972 Refer to the [Index Module](!docs!/learn/fundamentals/query/index-module) documentation to learn more.
1973
1974 </Note>
1975
1976 ---
1977
1978 ## Step 10: Tier Details UI Route
1979
1980 In this step, you'll create a UI route that displays the details of a tier.
1981
1982 The UI route is composed of three sections:
1983
1984 - Tier Details Section: This also includes a form to edit the tier's details.
1985 - Tier Rules Table
1986 - Tier Customers Table
1987
1988 You'll create the components for each section first, then you'll create the UI route.
1989
1990 ### a. Edit Tier Drawer Component
1991
1992 You'll first create a drawer component that displays a form to edit the tier's details. You'll then display the component in the Tier Details Section.
1993
1994 To create the drawer component, create the file `src/admin/components/edit-tier-drawer.tsx` with the following content:
1995
1996 ```tsx title="src/admin/components/edit-tier-drawer.tsx"
1997 import { Drawer, Heading, Label, Input, Button, Select, IconButton, toast } from "@medusajs/ui"
1998 import { useForm, Controller, FormProvider } from "react-hook-form"
1999 import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
2000 import { sdk } from "../lib/sdk"
2001 import { useState, useEffect } from "react"
2002 import { Tier } from "../routes/tiers/page"
2003 import { Trash } from "@medusajs/icons"
2004
2005 type EditTierFormData = {
2006 name: string
2007 promo_id: string | null
2008 tier_rules: Array<{
2009 min_purchase_value: number
2010 currency_code: string
2011 }>
2012 }
2013
2014 type EditTierDrawerProps = {
2015 tier: Tier | undefined
2016 }
2017
2018 export const EditTierDrawer = ({ tier }: EditTierDrawerProps) => {
2019 const queryClient = useQueryClient()
2020 const [open, setOpen] = useState(false)
2021 const [tierRules, setTierRules] = useState<{
2022 currency_code: string
2023 min_purchase_value: number
2024 }[]>([])
2025
2026 const form = useForm<EditTierFormData>({
2027 defaultValues: {
2028 name: "",
2029 promo_id: null,
2030 tier_rules: [],
2031 },
2032 })
2033
2034 // TODO add queries and mutations
2035 }
2036 ```
2037
2038 You define a component that receives the tier to edit.
2039
2040 In the component, you define the form and the necessary variables.
2041
2042 Next, you'll add queries to retrieve promotions and store data, and a mutation to update the tier. Replace the `TODO` with the following:
2043
2044 ```tsx title="src/admin/components/edit-tier-drawer.tsx"
2045 const { data: promotionsData } = useQuery({
2046 queryFn: () => sdk.admin.promotion.list(),
2047 queryKey: ["promotions", "list"],
2048 enabled: open,
2049 })
2050
2051 const { data: storeData } = useQuery({
2052 queryFn: () =>
2053 sdk.admin.store.list({
2054 fields: "id,supported_currencies.*,supported_currencies.currency.*",
2055 }),
2056 queryKey: ["store"],
2057 enabled: open,
2058 })
2059
2060 const updateTierMutation = useMutation({
2061 mutationFn: async (data: EditTierFormData) => {
2062 if (!tier) {return}
2063 return await sdk.client.fetch(`/admin/tiers/${tier.id}`, {
2064 method: "POST",
2065 body: data,
2066 })
2067 },
2068 onSuccess: () => {
2069 queryClient.invalidateQueries({ queryKey: ["tier", tier?.id] })
2070 queryClient.invalidateQueries({ queryKey: ["tiers"] })
2071 setOpen(false)
2072 toast.success("Success", {
2073 description: "Tier updated successfully",
2074 position: "top-right",
2075 })
2076 },
2077 onError: (error) => {
2078 toast.error("Error", {
2079 description: error.message,
2080 position: "top-right",
2081 })
2082 },
2083 })
2084
2085 // TODO initialize form on component mount
2086 ```
2087
2088 You retrieve the promotions and store data to populate the form with promotions and supported currencies for rules.
2089
2090 You also define a mutation to update a tier using the `useMutation` hook from Tanstack Query.
2091
2092 Next, you'll reset form data when the drawer is opened or closed. Replace the `TODO` with the following:
2093
2094 ```tsx title="src/admin/components/edit-tier-drawer.tsx"
2095 useEffect(() => {
2096 if (tier && open) {
2097 form.reset({
2098 name: tier.name,
2099 promo_id: tier.promotion?.id || null,
2100 tier_rules: tier.tier_rules || [],
2101 })
2102 setTierRules(
2103 tier.tier_rules?.map((rule) => ({
2104 currency_code: rule.currency_code,
2105 min_purchase_value: rule.min_purchase_value,
2106 })) || []
2107 )
2108 }
2109 }, [tier, open, form])
2110
2111 // TODO add function handlers
2112 ```
2113
2114 You reset the form data when the drawer is opened.
2115
2116 Next, you'll add functions to handle form submissions and other actions. Replace the `TODO` with the following:
2117
2118 ```tsx title="src/admin/components/edit-tier-drawer.tsx"
2119 const handleSubmit = form.handleSubmit((data) => {
2120 updateTierMutation.mutate({
2121 ...data,
2122 tier_rules: tierRules,
2123 })
2124 })
2125
2126 const promotions = promotionsData?.promotions || []
2127 const store = storeData?.stores?.[0]
2128 const supportedCurrencies = store?.supported_currencies || []
2129
2130 const getAvailableCurrencies = () => {
2131 const usedCurrencies = new Set(tierRules.map((rule) => rule.currency_code))
2132 return supportedCurrencies.filter((sc) => !usedCurrencies.has(sc.currency_code))
2133 }
2134
2135 const addTierRule = () => {
2136 const availableCurrencies = getAvailableCurrencies()
2137 if (availableCurrencies.length > 0) {
2138 const firstCurrency = availableCurrencies[0].currency_code
2139 setTierRules([
2140 ...tierRules,
2141 {
2142 currency_code: firstCurrency,
2143 min_purchase_value: 0,
2144 },
2145 ])
2146 }
2147 }
2148
2149 const removeTierRule = (index: number) => {
2150 setTierRules(tierRules.filter((_, i) => i !== index))
2151 }
2152
2153 const updateTierRule = (
2154 index: number,
2155 field: "currency_code" | "min_purchase_value",
2156 value: string | number
2157 ) => {
2158 const updated = [...tierRules]
2159 updated[index] = {
2160 ...updated[index],
2161 [field]: value,
2162 }
2163 setTierRules(updated)
2164 }
2165
2166 // TODO add return statement
2167 ```
2168
2169 You define the following functions:
2170
2171 - `handleSubmit`: Handles form submissions by calling the `updateTierMutation` mutation with the form data and tier rules.
2172 - `getAvailableCurrencies`: Returns the available currencies that haven't been used yet in the tier rules.
2173 - `addTierRule`: Adds a new tier rule to the form.
2174 - `removeTierRule`: Removes a tier rule from the form.
2175 - `updateTierRule`: Updates a tier rule in the form.
2176
2177 Finally, replace the `TODO` with the following return statement to render the drawer:
2178
2179 ```tsx title="src/admin/components/edit-tier-drawer.tsx"
2180 return (
2181 <Drawer open={open} onOpenChange={setOpen}>
2182 <Drawer.Trigger asChild>
2183 <Button variant="secondary" size="small">
2184 Edit
2185 </Button>
2186 </Drawer.Trigger>
2187 <Drawer.Content>
2188 <FormProvider {...form}>
2189 <form onSubmit={handleSubmit} className="flex flex-1 flex-col overflow-hidden">
2190 <Drawer.Header>
2191 <Heading level="h1">Edit Tier</Heading>
2192 </Drawer.Header>
2193 <Drawer.Body className="flex max-w-full flex-1 flex-col gap-y-8 overflow-y-auto">
2194 <Controller
2195 control={form.control}
2196 name="name"
2197 rules={{ required: "Name is required" }}
2198 render={({ field }) => (
2199 <div className="flex flex-col space-y-2">
2200 <Label size="small" weight="plus">
2201 Name
2202 </Label>
2203 <Input {...field} placeholder="e.g., Bronze, Silver, Gold" />
2204 </div>
2205 )}
2206 />
2207
2208 <Controller
2209 control={form.control}
2210 name="promo_id"
2211 render={({ field }) => (
2212 <div className="flex flex-col space-y-2">
2213 <Label size="small" weight="plus">
2214 Promotion (Optional)
2215 </Label>
2216 <Select
2217 value={field.value || ""}
2218 onValueChange={(value) => field.onChange(value || null)}
2219 >
2220 <Select.Trigger>
2221 <Select.Value placeholder="Select a promotion" />
2222 </Select.Trigger>
2223 <Select.Content>
2224 {promotions.map((promo) => (
2225 <Select.Item key={promo.id} value={promo.id}>
2226 {promo.code}
2227 </Select.Item>
2228 ))}
2229 </Select.Content>
2230 </Select>
2231 </div>
2232 )}
2233 />
2234
2235 <div className="flex flex-col gap-y-4">
2236 <div className="flex items-center justify-between">
2237 <Label size="small" weight="plus">
2238 Tier Rules
2239 </Label>
2240 <Button
2241 type="button"
2242 variant="secondary"
2243 size="small"
2244 onClick={addTierRule}
2245 disabled={getAvailableCurrencies().length === 0}
2246 >
2247 Add Rule
2248 </Button>
2249 </div>
2250
2251 {tierRules.length === 0 && (
2252 <div className="text-sm text-gray-500">
2253 No tier rules added. Click "Add Rule" to add a rule for a currency.
2254 </div>
2255 )}
2256
2257 {tierRules.map((rule, index) => (
2258 <div key={index} className="flex items-end gap-x-2 rounded-lg border p-4">
2259 <div className="flex flex-1 flex-col gap-y-2">
2260 <Label size="small">Currency</Label>
2261 <Select
2262 value={rule.currency_code}
2263 onValueChange={(value) => updateTierRule(index, "currency_code", value)}
2264 >
2265 <Select.Trigger>
2266 <Select.Value />
2267 </Select.Trigger>
2268 <Select.Content>
2269 {supportedCurrencies
2270 .filter((sc) => {
2271 return (
2272 sc.currency_code === rule.currency_code ||
2273 !tierRules.some(
2274 (r, i) => i !== index && r.currency_code === sc.currency_code
2275 )
2276 )
2277 })
2278 .map((sc) => (
2279 <Select.Item key={sc.currency_code} value={sc.currency_code}>
2280 {sc.currency.code.toUpperCase()} - {sc.currency.name}
2281 </Select.Item>
2282 ))}
2283 </Select.Content>
2284 </Select>
2285 </div>
2286 <div className="flex flex-1 flex-col gap-y-2">
2287 <Label size="small">Minimum Purchase Value</Label>
2288 <Input
2289 type="number"
2290 min="0"
2291 step="0.01"
2292 value={rule.min_purchase_value}
2293 onChange={(e) =>
2294 updateTierRule(index, "min_purchase_value", parseFloat(e.target.value) || 0)
2295 }
2296 />
2297 </div>
2298 <IconButton
2299 type="button"
2300 variant="transparent"
2301 size="small"
2302 onClick={() => removeTierRule(index)}
2303 >
2304 <Trash />
2305 </IconButton>
2306 </div>
2307 ))}
2308 </div>
2309 </Drawer.Body>
2310 <Drawer.Footer>
2311 <div className="flex items-center justify-end gap-x-2">
2312 <Drawer.Close asChild>
2313 <Button size="small" variant="secondary">
2314 Cancel
2315 </Button>
2316 </Drawer.Close>
2317 <Button size="small" type="submit" isLoading={updateTierMutation.isPending}>
2318 Save
2319 </Button>
2320 </div>
2321 </Drawer.Footer>
2322 </form>
2323 </FormProvider>
2324 </Drawer.Content>
2325 </Drawer>
2326 )
2327 ```
2328
2329 You display a `Drawer` from Medusa UI. In the drawer, you render a form with the following fields:
2330
2331 1. **Name**: The name of the tier.
2332 2. **Promotion**: A select input to choose a promotion that's associated with the tier.
2333 3. **Tier Rules**: A list of inputs to specify the minimum purchase value required in a specific currency to qualify for the tier.
2334
2335 ### b. Tier Details Section Component
2336
2337 Next, you'll create a component that displays the details of a tier, with a button to open the edit tier drawer.
2338
2339 To create the component, create the file `src/admin/components/tier-details-section.tsx` with the following content:
2340
2341 ```tsx title="src/admin/components/tier-details-section.tsx"
2342 import { Code, Container, Heading, Text } from "@medusajs/ui"
2343 import { Link } from "react-router-dom"
2344 import { Tier } from "../routes/tiers/page"
2345 import { EditTierDrawer } from "./edit-tier-drawer"
2346
2347 type TierDetailsSectionProps = {
2348 tier: Tier | undefined
2349 }
2350
2351 export const TierDetailsSection = ({ tier }: TierDetailsSectionProps) => {
2352 return (
2353 <Container className="divide-y p-0">
2354 <div className="flex items-center justify-between px-6 py-4">
2355 <Heading level="h1">Tier Details</Heading>
2356 <div className="flex items-center gap-x-2">
2357 <EditTierDrawer tier={tier} />
2358 </div>
2359 </div>
2360 <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
2361 <Text size="small" weight="plus" leading="compact">
2362 Name
2363 </Text>
2364
2365 <Text
2366 size="small"
2367 leading="compact"
2368 className="whitespace-pre-line text-pretty"
2369 >
2370 {tier?.name ?? "-"}
2371 </Text>
2372 </div>
2373 <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
2374 <Text size="small" weight="plus" leading="compact">
2375 Promotion
2376 </Text>
2377
2378 {tier?.promotion && (
2379 <Link to={`/promotions/${tier.promotion.id}`}>
2380 <Code>{tier.promotion.code}</Code>
2381 </Link>
2382 )}
2383 </div>
2384 </Container>
2385 )
2386 }
2387 ```
2388
2389 You display the tier's name and a link to its associated promotion. You also display a button to open the edit tier drawer.
2390
2391 ### c. Tier Rules Table Component
2392
2393 Next, you'll create a component that displays the tier rules in a table.
2394
2395 To create the component, create the file `src/admin/components/tier-rules-table.tsx` with the following content:
2396
2397 ```tsx title="src/admin/components/tier-rules-table.tsx"
2398 import { Heading, DataTable, createDataTableColumnHelper, useDataTable, Container } from "@medusajs/ui"
2399 import { Tier } from "../routes/tiers/page"
2400
2401 type TierRulesTableProps = {
2402 tierRules: Tier["tier_rules"] | undefined
2403 }
2404
2405 type TierRule = {
2406 id: string
2407 currency_code: string
2408 min_purchase_value: number
2409 }
2410
2411 const columnHelper = createDataTableColumnHelper<TierRule>()
2412
2413 const columns = [
2414 columnHelper.accessor("currency_code", {
2415 header: "Currency",
2416 cell: ({ getValue }) => getValue().toUpperCase(),
2417 }),
2418 columnHelper.accessor("min_purchase_value", {
2419 header: "Minimum Purchase Value",
2420 }),
2421 ]
2422
2423 export const TierRulesTable = ({ tierRules }: TierRulesTableProps) => {
2424 const rules = tierRules || []
2425
2426 const table = useDataTable({
2427 columns,
2428 data: rules,
2429 getRowId: (rule) => rule.id,
2430 rowCount: rules.length,
2431 isLoading: false,
2432 })
2433
2434 return (
2435 <Container className="divide-y p-0">
2436 <DataTable instance={table}>
2437 <DataTable.Toolbar className="flex items-center justify-between px-6 py-4">
2438 <Heading level="h2">
2439 Tier Rules
2440 </Heading>
2441 </DataTable.Toolbar>
2442 <DataTable.Table />
2443 </DataTable>
2444 </Container>
2445 )
2446 }
2447 ```
2448
2449 The component receives the tier rules to display.
2450
2451 In the component, you display the tier rules in a `DataTable`. The table shows the currency code and the minimum purchase value required to qualify for the tier.
2452
2453 ### d. Tier Customers Table Component
2454
2455 Next, you'll create a component that displays the customers in a tier in a table.
2456
2457 To create the component, create the file `src/admin/components/tier-customers-table.tsx` with the following content:
2458
2459 ```tsx title="src/admin/components/tier-customers-table.tsx"
2460 import { Heading, DataTable, createDataTableColumnHelper, useDataTable, Container, DataTablePaginationState } from "@medusajs/ui"
2461 import { sdk } from "../lib/sdk"
2462 import { useQuery } from "@tanstack/react-query"
2463 import { useMemo, useState } from "react"
2464
2465 type TierCustomersTableProps = {
2466 tierId: string
2467 }
2468
2469 type Customer = {
2470 id: string
2471 email: string
2472 first_name: string | null
2473 last_name: string | null
2474 }
2475
2476 type CustomersResponse = {
2477 customers: Customer[]
2478 count: number
2479 offset: number
2480 limit: number
2481 }
2482
2483 const columnHelper = createDataTableColumnHelper<Customer>()
2484
2485 const columns = [
2486 columnHelper.accessor("email", {
2487 header: "Email",
2488 }),
2489 columnHelper.accessor("first_name", {
2490 header: "Name",
2491 cell: ({ row }) => {
2492 const customer = row.original
2493 return customer.first_name || customer.last_name
2494 ? `${customer.first_name || ""} ${customer.last_name || ""}`.trim()
2495 : "-"
2496 },
2497 }),
2498 ]
2499
2500 export const TierCustomersTable = ({ tierId }: TierCustomersTableProps) => {
2501 const limit = 15
2502 const [pagination, setPagination] = useState<DataTablePaginationState>({
2503 pageSize: limit,
2504 pageIndex: 0,
2505 })
2506
2507 const offset = useMemo(() => {
2508 return pagination.pageIndex * limit
2509 }, [pagination])
2510
2511 const { data: customersData, isLoading: customersLoading } = useQuery({
2512 queryFn: () =>
2513 sdk.client.fetch<CustomersResponse>(`/admin/tiers/${tierId}/customers`, {
2514 method: "GET",
2515 query: {
2516 limit,
2517 offset,
2518 },
2519 }),
2520 queryKey: ["tier", tierId, "customers"],
2521 enabled: !!tierId,
2522 })
2523 const table = useDataTable({
2524 columns,
2525 data: customersData?.customers || [],
2526 getRowId: (customer) => customer.id,
2527 rowCount: customersData?.count || 0,
2528 isLoading: customersLoading,
2529 pagination: {
2530 state: pagination,
2531 onPaginationChange: setPagination,
2532 },
2533 })
2534
2535 return (
2536 <Container className="divide-y p-0">
2537 <DataTable instance={table}>
2538 <DataTable.Toolbar className="flex items-center justify-between px-6 py-4">
2539 <Heading level="h2">
2540 Customers in this Tier
2541 </Heading>
2542 </DataTable.Toolbar>
2543 <DataTable.Table />
2544 <DataTable.Pagination />
2545 </DataTable>
2546 </Container>
2547 )
2548 }
2549 ```
2550
2551 The component receives the tier ID to retrieve the customers.
2552
2553 In the component, you fetch the customers in the tier using the API route you created in the previous step.
2554
2555 You display the customers in a `DataTable`. The table shows the email and the name of the customers with pagination controls.
2556
2557 ### e. Tier Details UI Route
2558
2559 Finally, you'll create the UI route that displays the details of a tier.
2560
2561 To create the UI route, create the file `src/admin/routes/tiers/[id]/page.tsx` with the following content:
2562
2563 ```tsx title="src/admin/routes/tiers/[id]/page.tsx"
2564 import { useParams } from "react-router-dom"
2565 import { useQuery } from "@tanstack/react-query"
2566 import { sdk } from "../../../lib/sdk"
2567 import { Tier } from "../page"
2568 import { TierDetailsSection } from "../../../components/tier-details-section"
2569 import { TierRulesTable } from "../../../components/tier-rules-table"
2570 import { TierCustomersTable } from "../../../components/tier-customers-table"
2571
2572 type TierResponse = {
2573 tier: Tier
2574 }
2575
2576 const TierDetailsPage = () => {
2577 const { id } = useParams()
2578
2579 const { data: tierData } = useQuery({
2580 queryFn: () =>
2581 sdk.client.fetch<TierResponse>(`/admin/tiers/${id}`, {
2582 method: "GET",
2583 }),
2584 queryKey: ["tier", id],
2585 enabled: !!id,
2586 })
2587
2588 const tier = tierData?.tier
2589
2590 return (
2591 <>
2592 <TierDetailsSection tier={tier} />
2593 <TierRulesTable tierRules={tier?.tier_rules} />
2594 {tier?.id && <TierCustomersTable tierId={tier.id} />}
2595 </>
2596 )
2597 }
2598
2599 export default TierDetailsPage
2600 ```
2601
2602 The component retrieves the tier details using the API route you created in the previous step.
2603
2604 Then, you display the components of the different sections you created earlier.
2605
2606 ### f. Navigate to Tier Details Page
2607
2608 Next, you'll navigate to the tier details page when the admin user clicks on a row in the tiers list, and after creating a tier.
2609
2610 In `src/admin/routes/tiers/page.tsx`, find the `onRowClick` handler and replace it with the following:
2611
2612 ```tsx title="src/admin/routes/tiers/page.tsx"
2613 onRowClick: (_event, row) => {
2614 navigate(`/tiers/${row.id}`)
2615 }
2616 ```
2617
2618 You navigate to the tier details page when the user clicks on a tier in the tiers list.
2619
2620 Next, you'll navigate to the tier details page after creating a tier.
2621
2622 In `src/admin/components/create-tier-modal.tsx`, find the `TODO navigate to the new tier page` comment and replace it with the following:
2623
2624 ```tsx title="src/admin/components/create-tier-modal.tsx"
2625 navigate(`/tiers/${data.tier.id}`)
2626 ```
2627
2628 You navigate to the tier details page after creating a tier.
2629
2630 ### Test Customer Tiers in Medusa Admin
2631
2632 To test out the customer tiers in the Medusa Admin, start the Medusa application:
2633
2634 ```bash npm2yarn
2635 npm run dev
2636 ```
2637
2638 Then, open the Medusa Admin dashboard at `http://localhost:9000/app` and log in using the credentials you set up earlier.
2639
2640 You'll find a new sidebar item labeled "Customer Tiers." Click on it to view the list of tiers.
2641
2642 Click on the tier you created earlier. This will open its details page where you can view the tier's details, its rules, and its customers.
2643
2644 ![Tier details page showing tier details, rules, and customers](https://res.cloudinary.com/dza7lstvk/image/upload/v1764067752/Medusa%20Resources/CleanShot_2025-11-25_at_12.48.45_2x_ahjflr.png)
2645
2646 To edit the tier's details, click the Edit button. This will open a drawer where you can edit the tier's name, its associated promotion, and its tier rules.
2647
2648 ![Edit tier drawer showing form to edit tier details](https://res.cloudinary.com/dza7lstvk/image/upload/v1764068307/Medusa%20Resources/CleanShot_2025-11-25_at_12.58.17_2x_me8gbo.png)
2649
2650 ---
2651
2652 ## Step 11: Update Customer Tier on Order
2653
2654 In this step, you'll add the logic to update a customer's tier when an order is placed. This requires creating:
2655
2656 - A method in the Tier Module's service to determine the qualifying tier based on a customer's purchase history.
2657 - A workflow to determine a customer's tier based on their purchase history.
2658 - A [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that listens to the order placement event and executes the workflow.
2659
2660 ### a. Determine Qualifying Tier Method
2661
2662 To determine the qualifying tier based on the customer's purchase history, you'll add a method to the Tier Module's service.
2663
2664 In `src/modules/tier/service.ts`, add the following method to the `TierModuleService` class:
2665
2666 ```ts title="src/modules/tier/service.ts"
2667 class TierModuleService extends MedusaService({
2668 Tier,
2669 TierRule,
2670 }) {
2671 async calculateQualifyingTier(
2672 currencyCode: string,
2673 purchaseValue: number
2674 ) {
2675 const rules = await this.listTierRules(
2676 {
2677 currency_code: currencyCode,
2678 }
2679 )
2680
2681 if (!rules || rules.length === 0) {
2682 return null
2683 }
2684
2685 const sortedRules = rules.sort(
2686 (a, b) => b.min_purchase_value - a.min_purchase_value
2687 )
2688
2689 const qualifyingRule = sortedRules.find(
2690 (rule) => purchaseValue >= rule.min_purchase_value
2691 )
2692
2693 return qualifyingRule?.tier?.id || null
2694 }
2695 }
2696 ```
2697
2698 The `calculateQualifyingTier` method receives the currency code and the purchase value of a customer.
2699
2700 In the method, you:
2701
2702 - Retrieve the tier rules for the given currency code.
2703 - Sort the rules by the minimum purchase value in ascending order.
2704 - Find the tier whose minimum purchase value is less than or equal to the purchase value.
2705 - Return the ID of the qualifying tier.
2706
2707 You'll use this method in the steps of the workflow to update the customer's tier.
2708
2709 ### b. Update Customer Tier on Order Workflow
2710
2711 The workflow to update a customer's tier on order placement has the following steps:
2712
2713 <WorkflowDiagram
2714 workflow={{
2715 name: "updateCustomerTierOnOrderWorkflow",
2716 steps: [
2717 {
2718 type: "step",
2719 name: "useQueryGraphStep",
2720 description: "Retrieve the details of the order with its customer and tier.",
2721 link: "/references/helper-steps/useQueryGraphStep",
2722 depth: 1,
2723 },
2724 {
2725 type: "step",
2726 name: "validateCustomerStep",
2727 description: "Validate that the customer is a registered customer.",
2728 depth: 2,
2729 },
2730 {
2731 type: "step",
2732 name: "useQueryGraphStep",
2733 description: "Retrieve the completed orders for the customer in the same currency.",
2734 link: "/references/helper-steps/useQueryGraphStep",
2735 depth: 3,
2736 },
2737 {
2738 type: "step",
2739 name: "determineTierStep",
2740 description: "Determine the appropriate tier.",
2741 depth: 4,
2742 },
2743 {
2744 type: "when",
2745 condition: "!!data.orders[0].customer?.tier?.id && data.tierId !== data.orders[0].customer?.tier?.id",
2746 steps: [
2747 {
2748 type: "step",
2749 name: "dismissRemoteLinkStep",
2750 description: "Dismiss the existing tier link if it exists and the customer's tier has changed.",
2751 depth: 1,
2752 },
2753 ],
2754 depth: 5,
2755 },
2756 {
2757 type: "when",
2758 condition: "!!data.tierId && data.orders[0].customer?.tier?.id !== data.tierId",
2759 steps: [
2760 {
2761 type: "step",
2762 name: "createRemoteLinkStep",
2763 description: "Create a new tier link if the customer's tier has changed and a new tier ID is provided.",
2764 depth: 1,
2765 },
2766 ],
2767 depth: 6,
2768 }
2769 ]
2770 }}
2771 />
2772
2773 You only need to create the `validateCustomerStep` and `determineTierStep` steps. Medusa provides the other steps out of the box.
2774
2775 #### Validate Customer Step
2776
2777 The `validateCustomerStep` validates that the customer is a registered customer.
2778
2779 To create the step, create the file `src/workflows/steps/validate-customer.ts` with the following content:
2780
2781 ```ts title="src/workflows/steps/validate-customer.ts"
2782 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
2783 import { MedusaError } from "@medusajs/framework/utils"
2784
2785 export type ValidateCustomerStepInput = {
2786 customer: any
2787 }
2788
2789 export const validateCustomerStep = createStep(
2790 "validate-customer",
2791 async (input: ValidateCustomerStepInput, { container }) => {
2792 if (!input.customer) {
2793 throw new MedusaError(
2794 MedusaError.Types.NOT_FOUND,
2795 "Customer not found"
2796 )
2797 }
2798
2799 if (!input.customer.has_account) {
2800 throw new MedusaError(
2801 MedusaError.Types.INVALID_DATA,
2802 "Customer must be registered to be assigned a tier"
2803 )
2804 }
2805
2806 return new StepResponse(input.customer)
2807 }
2808 )
2809 ```
2810
2811 The step receives the customer to validate.
2812
2813 In the step, you validate that the customer is defined and that it's registered based on its `has_account` property. Otherwise, you throw an error.
2814
2815 #### Determine Tier Step
2816
2817 The `determineTierStep` determines the appropriate tier based on the customer's purchase history.
2818
2819 To create the step, create the file `src/workflows/steps/determine-tier.ts` with the following content:
2820
2821 ```ts title="src/workflows/steps/determine-tier.ts"
2822 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
2823 import { TIER_MODULE } from "../../modules/tier"
2824 import TierModuleService from "../../modules/tier/service"
2825
2826 export type DetermineTierStepInput = {
2827 currency_code: string
2828 purchase_value: number
2829 }
2830
2831 export const determineTierStep = createStep(
2832 "determine-tier",
2833 async (input: DetermineTierStepInput, { container }) => {
2834 const tierModuleService: TierModuleService = container.resolve(TIER_MODULE)
2835
2836 const qualifyingTier = await tierModuleService.calculateQualifyingTier(
2837 input.currency_code,
2838 input.purchase_value
2839 )
2840
2841 return new StepResponse(qualifyingTier)
2842 }
2843 )
2844 ```
2845
2846 The step receives the currency code and the purchase value of a customer.
2847
2848 In the step, you resolve the Tier Module's service from the Medusa container and call the `calculateQualifyingTier` method to determine the qualifying tier.
2849
2850 You return the ID of the qualifying tier.
2851
2852 #### Update Customer Tier on Order Workflow
2853
2854 You can create the workflow that updates a customer's tier on order placement.
2855
2856 To create the workflow, create the file `src/workflows/update-customer-tier-on-order.ts` with the following content:
2857
2858 ```ts title="src/workflows/update-customer-tier-on-order.ts" collapsibleLines="1-16" expandButtonLabel="Show Imports"
2859 import {
2860 createWorkflow,
2861 WorkflowResponse,
2862 transform,
2863 when,
2864 } from "@medusajs/framework/workflows-sdk"
2865 import {
2866 useQueryGraphStep,
2867 createRemoteLinkStep,
2868 dismissRemoteLinkStep,
2869 } from "@medusajs/medusa/core-flows"
2870 import { Modules, OrderStatus } from "@medusajs/framework/utils"
2871 import { validateCustomerStep } from "./steps/validate-customer"
2872 import { determineTierStep } from "./steps/determine-tier"
2873 import { TIER_MODULE } from "../modules/tier"
2874
2875 type WorkflowInput = {
2876 order_id: string
2877 }
2878
2879 export const updateCustomerTierOnOrderWorkflow = createWorkflow(
2880 "update-customer-tier-on-order",
2881 (input: WorkflowInput) => {
2882 // Get order details
2883 const { data: orders } = useQueryGraphStep({
2884 entity: "order",
2885 fields: ["id", "currency_code", "total", "customer.*", "customer.tier.*"],
2886 filters: {
2887 id: input.order_id,
2888 },
2889 options: {
2890 throwIfKeyNotFound: true,
2891 },
2892 })
2893
2894 const validatedCustomer = validateCustomerStep({
2895 customer: orders[0].customer,
2896 })
2897
2898 // Query completed orders for the customer in the same currency
2899 const { data: completedOrders } = useQueryGraphStep({
2900 entity: "order",
2901 fields: ["id", "total", "currency_code"],
2902 filters: {
2903 customer_id: validatedCustomer.id,
2904 currency_code: orders[0].currency_code,
2905 status: {
2906 $nin: [
2907 OrderStatus.CANCELED,
2908 OrderStatus.DRAFT,
2909 ],
2910 },
2911 },
2912 }).config({ name: "completed-orders" })
2913
2914 // Calculate total purchase value using transform
2915 const purchasedValue = transform(
2916 { completedOrders },
2917 (data) => {
2918 return data.completedOrders.reduce(
2919 (sum: number, order: any) => sum + (order.total || 0),
2920 0
2921 )
2922 }
2923 )
2924
2925 // Determine appropriate tier
2926 const tierId = determineTierStep({
2927 currency_code: orders[0].currency_code as string,
2928 purchase_value: purchasedValue,
2929 })
2930
2931 const existingTierId = transform(
2932 { orders },
2933 ({ orders }) => orders[0].customer?.tier?.id as string
2934 )
2935
2936 // Dismiss existing tier link if it exists
2937 // and the tier id is not the same as the tier id in the determine tier step
2938 when({ orders, tierId }, (data) => !!data.orders[0].customer?.tier?.id && data.tierId !== data.orders[0].customer?.tier?.id).then(
2939 () => {
2940 dismissRemoteLinkStep([
2941 {
2942 [TIER_MODULE]: { tier_id: existingTierId },
2943 [Modules.CUSTOMER]: { customer_id: validatedCustomer.id },
2944 },
2945 ])
2946 }
2947 )
2948
2949 // Create new tier link if tierId is provided
2950 when({ tierId, orders }, (data) => !!data.tierId && data.orders[0].customer?.tier?.id !== data.tierId).then(() => {
2951 createRemoteLinkStep([
2952 {
2953 [TIER_MODULE]: { tier_id: tierId },
2954 [Modules.CUSTOMER]: { customer_id: validatedCustomer.id },
2955 },
2956 ])
2957 })
2958
2959 return new WorkflowResponse({
2960 customer_id: validatedCustomer.id,
2961 tier_id: tierId,
2962 })
2963 }
2964 )
2965 ```
2966
2967 The workflow receives the order ID as input.
2968
2969 In the workflow, you:
2970
2971 - Retrieve the order details using the `useQueryGraphStep`.
2972 - Validate the customer using the `validateCustomerStep`. This will throw an error if the customer is not a registered customer, which will stop the workflow's execution.
2973 - Retrieve the customer's completed orders in the same currency using `useQueryGraphStep`.
2974 - Calculate the total purchase value using `transform`.
2975 - Determine the appropriate tier using `determineTierStep`.
2976 - Dismiss the existing tier link if it exists and the customer's tier has changed, using `dismissRemoteLinkStep`.
2977 - Create a new tier link if the customer's tier has changed and a new tier ID is provided, using `createRemoteLinkStep`.
2978
2979 Finally, you return a `WorkflowResponse` with the customer ID and the tier ID.
2980
2981 ### c. Update Customer Tier on Order Subscriber
2982
2983 Next, you'll create a subscriber that listens to the order placement event and executes the workflow.
2984
2985 A subscriber is an asynchronous function that runs in the background when specific events are emitted.
2986
2987 To create the subscriber, create the file `src/subscribers/order-placed.ts` with the following content:
2988
2989 ```ts title="src/subscribers/order-placed.ts"
2990 import {
2991 SubscriberArgs,
2992 SubscriberConfig,
2993 } from "@medusajs/framework"
2994 import { updateCustomerTierOnOrderWorkflow } from "../workflows/update-customer-tier-on-order"
2995 import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
2996
2997 export default async function orderPlacedHandler({
2998 event: { data },
2999 container,
3000 }: SubscriberArgs<{ id: string }>) {
3001 const logger = container.resolve(
3002 ContainerRegistrationKeys.LOGGER
3003 )
3004 try {
3005 await updateCustomerTierOnOrderWorkflow(container).run({
3006 input: {
3007 order_id: data.id,
3008 },
3009 })
3010 } catch (error) {
3011 logger.error(error)
3012 }
3013 }
3014
3015 export const config: SubscriberConfig = {
3016 event: "order.placed",
3017 }
3018 ```
3019
3020 A subscriber file must export:
3021
3022 - An asynchronous subscriber function that executes whenever the associated event is triggered.
3023 - A configuration object with an event property whose value is the event the subscriber is listening to, which is `order.placed` in this case.
3024
3025 The subscriber function receives an object with the following properties:
3026
3027 - `event`: An object holding the event's details. It has a `data` property, which is the event's data payload.
3028 - `container`: The Medusa container. Use it to resolve modules' main services and other registered resources.
3029
3030 In the subscriber function, you resolve the logger from the Medusa container and execute the workflow. If an error occurs, you log it.
3031
3032 ### Test Update Customer Tier on Order
3033
3034 To test the workflow and subscriber, you'll need to place an order using the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) that you installed in the first step.
3035
3036 <Note title="Reminder" forceMultiline>
3037
3038 The Next.js Starter Storefront is available in the `apps/storefront` directory of your project:
3039
3040 ```bash
3041 cd apps/storefront
3042 ```
3043
3044 </Note>
3045
3046 First, start the Medusa application by running the following command in the `apps/backend` directory:
3047
3048 ```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green"
3049 npm run dev
3050 ```
3051
3052 Then, start the Next.js Starter Storefront by running the following command in the storefront's directory:
3053
3054 ```bash npm2yarn badgeLabel="Next.js Starter Storefront" badgeColor="blue"
3055 npm run dev
3056 ```
3057
3058 Next:
3059
3060 1. Open the Next.js Starter Storefront in your browser at `http://localhost:8000`.
3061 2. Click on "Account" in the navigation bar and create a new account.
3062 3. After you're logged in, add products to the cart and complete the checkout process.
3063 - Make sure the order total is high enough to qualify for the next tier.
3064 4. After you place the order, open the Medusa Admin dashboard at `http://localhost:9000/app` and log in.
3065 5. Go to the Customer Tiers page and click on the tier that the customer should have been assigned to.
3066 6. You'll see the customer in the tier's customers list section.
3067
3068 ![Customer in tier's customers list section](https://res.cloudinary.com/dza7lstvk/image/upload/v1764070515/Medusa%20Resources/CleanShot_2025-11-25_at_13.34.32_2x_wro2yk.png)
3069
3070 ---
3071
3072 ## Step 12: Apply Tier Promotion to Customer Carts
3073
3074 In this step, you'll apply a customer's tier promotion whenever they update their cart if it's not already applied.
3075
3076 To build this feature, you need a workflow that applies the tier promotion to a cart and a subscriber that listens to the cart update event and executes the workflow.
3077
3078 ### a. Add Tier Promotion to Cart Workflow
3079
3080 The workflow to add a customer's tier promotion to a cart has the following steps:
3081
3082 <WorkflowDiagram
3083 workflow={{
3084 name: "addTierPromotionToCartWorkflow",
3085 steps: [
3086 {
3087 type: "step",
3088 name: "useQueryGraphStep",
3089 description: "Retrieve the details of the cart with its customer and tier.",
3090 link: "/references/helper-steps/useQueryGraphStep",
3091 depth: 1,
3092 },
3093 {
3094 type: "step",
3095 name: "acquireLockStep",
3096 description: "Acquire a lock on the cart to prevent concurrent modifications.",
3097 link: "/references/medusa-workflows/steps/acquireLockStep",
3098 depth: 2,
3099 },
3100 {
3101 type: "when",
3102 condition: "!!data.carts[0].customer",
3103 steps: [
3104 {
3105 type: "step",
3106 name: "validateTierPromotionStep",
3107 description: "Validate that the customer has a tier promotion.",
3108 depth: 1,
3109 }
3110 ],
3111 depth: 3,
3112 },
3113 {
3114 type: "when",
3115 steps: [
3116 {
3117 type: "workflow",
3118 name: "updateCartPromotionsWorkflow",
3119 description: "Update the cart's promotions if the customer has a tier promotion that hasn't been applied yet.",
3120 link: "/references/medusa-workflows/updateCartPromotionsWorkflow",
3121 depth: 1
3122 }
3123 ],
3124 depth: 4,
3125 },
3126 {
3127 type: "step",
3128 name: "releaseLockStep",
3129 description: "Release the lock on the cart.",
3130 link: "/references/medusa-workflows/steps/releaseLockStep",
3131 depth: 5,
3132 }
3133 ]
3134 }}
3135 />
3136
3137 You only need to create the `validateTierPromotionStep`. Medusa provides the other steps and workflows out-of-the-box.
3138
3139 #### Validate Tier Promotion Step
3140
3141 The `validateTierPromotionStep` validates that the customer is registered and has a tier promotion.
3142
3143 To create the step, create the file `src/workflows/steps/validate-tier-promotion.ts` with the following content:
3144
3145 ```ts title="src/workflows/steps/validate-tier-promotion.ts"
3146 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
3147
3148 export type ValidateTierPromotionStepInput = {
3149 customer: {
3150 has_account: boolean
3151 tier?: {
3152 promo_id?: string | null
3153 promotion?: {
3154 id?: string
3155 code?: string | null
3156 status?: string | null
3157 } | null
3158 } | null
3159 } | null
3160 }
3161
3162 export const validateTierPromotionStep = createStep(
3163 "validate-tier-promotion",
3164 async (input: ValidateTierPromotionStepInput) => {
3165 if (!input.customer || !input.customer.has_account) {
3166 return new StepResponse(null)
3167 }
3168
3169 const tier = input.customer.tier
3170
3171 if (!tier?.promo_id || !tier.promotion || tier.promotion.status !== "active") {
3172 return new StepResponse({ promotion_code: null })
3173 }
3174
3175 return new StepResponse({
3176 promotion_code: tier.promotion.code || null,
3177 })
3178 }
3179 )
3180 ```
3181
3182 The step receives the customer to validate.
3183
3184 In the step, you return `null` if the customer is not registered or if it doesn't have a tier promotion. Otherwise, you return the promotion code.
3185
3186 #### Add Tier Promotion to Cart Workflow
3187
3188 You can now create the workflow that adds a customer's tier promotion to a cart.
3189
3190 To create the workflow, create the file `src/workflows/add-tier-promotion-to-cart.ts` with the following content:
3191
3192 ```ts title="src/workflows/add-tier-promotion-to-cart.ts" collapsibleLines="1-15" expandButtonLabel="Show Imports"
3193 import {
3194 createWorkflow,
3195 WorkflowResponse,
3196 transform,
3197 when,
3198 } from "@medusajs/framework/workflows-sdk"
3199 import {
3200 acquireLockStep,
3201 releaseLockStep,
3202 updateCartPromotionsWorkflow,
3203 useQueryGraphStep,
3204 } from "@medusajs/medusa/core-flows"
3205 import { PromotionActions } from "@medusajs/framework/utils"
3206 import { validateTierPromotionStep } from "./steps/validate-tier-promotion"
3207
3208 export type AddTierPromotionToCartWorkflowInput = {
3209 cart_id: string
3210 }
3211
3212 export const addTierPromotionToCartWorkflow = createWorkflow(
3213 "add-tier-promotion-to-cart",
3214 (input: AddTierPromotionToCartWorkflowInput) => {
3215 // Get cart with customer, tier, and promotions
3216 const { data: carts } = useQueryGraphStep({
3217 entity: "cart",
3218 fields: [
3219 "id",
3220 "customer.id",
3221 "customer.has_account",
3222 "customer.tier.*",
3223 "customer.tier.promotion.id",
3224 "customer.tier.promotion.code",
3225 "customer.tier.promotion.status",
3226 "promotions.*",
3227 "promotions.code",
3228 ],
3229 filters: {
3230 id: input.cart_id,
3231 },
3232 options: {
3233 throwIfKeyNotFound: true,
3234 },
3235 })
3236
3237 acquireLockStep({
3238 key: input.cart_id,
3239 timeout: 2,
3240 ttl: 10,
3241 })
3242
3243
3244 // Check if customer exists and has tier
3245 // @ts-ignore
3246 const tierPromotionInput = transform({ carts }, ({ carts }) => ({
3247 has_account: carts[0].customer!.has_account,
3248 tier: {
3249 promo_id: carts[0].customer!.tier!.promo_id || null,
3250 promotion: {
3251 id: carts[0].customer!.tier!.promotion!.id,
3252 code: carts[0].customer!.tier!.promotion!.code || null,
3253 status: carts[0].customer!.tier!.promotion!.status || null,
3254 },
3255 },
3256 }))
3257
3258 const validationResult = when({ carts }, (data) => !!data.carts[0].customer).then(() => {
3259 return validateTierPromotionStep({
3260 customer: tierPromotionInput,
3261 })
3262 })
3263
3264 // Add promotion to cart if valid and not already applied
3265 when({ validationResult, carts }, (data) => {
3266 if (!data.validationResult?.promotion_code) {
3267 return false
3268 }
3269
3270 const appliedPromotionCodes = data.carts[0].promotions?.map(
3271 (promo: any) => promo.code
3272 ) || []
3273
3274 return (
3275 data.validationResult?.promotion_code !== null &&
3276 !appliedPromotionCodes.includes(data.validationResult?.promotion_code!)
3277 )
3278 }).then(() => {
3279 const promoCodes = transform(
3280 { validationResult },
3281 ({ validationResult }) => [validationResult?.promotion_code!]
3282 )
3283
3284 return updateCartPromotionsWorkflow.runAsStep({
3285 input: {
3286 cart_id: input.cart_id,
3287 promo_codes: promoCodes,
3288 action: PromotionActions.ADD,
3289 },
3290 })
3291 })
3292
3293 releaseLockStep({
3294 key: input.cart_id,
3295 })
3296
3297 return new WorkflowResponse(void 0)
3298 }
3299 )
3300 ```
3301
3302 The workflow receives the cart's ID as input.
3303
3304 In the workflow, you:
3305
3306 - Retrieve the cart details using `useQueryGraphStep`.
3307 - Acquire a lock on the cart using `acquireLockStep`.
3308 - Validate that the customer exists and has a tier promotion using `validateTierPromotionStep`.
3309 - Update the cart's promotions if the customer has a tier promotion that hasn't been applied yet, using `updateCartPromotionsWorkflow`.
3310 - Release the lock on the cart using `releaseLockStep`.
3311
3312 ### b. Cart Updated Subscriber
3313
3314 Next, you'll create a subscriber that listens to the cart update event and executes the workflow.
3315
3316 To create the subscriber, create the file `src/subscribers/cart-updated.ts` with the following content:
3317
3318 ```ts title="src/subscribers/cart-updated.ts"
3319 import {
3320 SubscriberArgs,
3321 SubscriberConfig,
3322 } from "@medusajs/framework"
3323 import { addTierPromotionToCartWorkflow } from "../workflows/add-tier-promotion-to-cart"
3324
3325 export default async function cartUpdatedHandler({
3326 event: { data },
3327 container,
3328 }: SubscriberArgs<{ id: string }>) {
3329 await addTierPromotionToCartWorkflow(container).run({
3330 input: {
3331 cart_id: data.id,
3332 },
3333 })
3334 }
3335
3336 export const config: SubscriberConfig = {
3337 event: "cart.updated",
3338 }
3339 ```
3340
3341 The subscriber listens to the `cart.updated` event and executes the workflow.
3342
3343 ### Test Add Tier Promotion to Cart
3344
3345 To test the automated tier promotion, make sure both the Medusa application and the Next.js Starter Storefront are running.
3346
3347 Then, in the Next.js Starter Storefront, log in as a customer in a tier, and add a product to the cart.
3348
3349 You can see that the discount of the customer's tier is applied to the cart.
3350
3351 <Note>
3352
3353 If you don't see the promotion applied, try to refresh the page.
3354
3355 </Note>
3356
3357 ![Cart showing the promotion of the tier applied](https://res.cloudinary.com/dza7lstvk/image/upload/v1764072761/Medusa%20Resources/CleanShot_2025-11-25_at_13.47.49_2x_xmewsm.png)
3358
3359 ---
3360
3361 ## Step 13: Validate Applied Promotion
3362
3363 In this step, you'll validate that a cart's promotions match the customer's tier. You'll apply validation when new promotions are added to the cart, and when completing the cart.
3364
3365 ### Validate Promotion Addition
3366
3367 When a customer adds a promotion to the cart, the storefront sends a request to the [Add Promotions API Route](!api!/store/carts/add-promotions), which executes the [updateCartPromotionsWorkflow](/references/medusa-workflows/updateCartPromotionsWorkflow).
3368
3369 To ensure that customers don't add promotions that belong to different tiers, you can consume the `validate` [hook](!docs!/learn/fundamentals/workflows/workflow-hooks) of the `updateCartPromotionsWorkflow`. A hook is a specific point in a workflow where you can inject custom functionality.
3370
3371 To consume the hook, create the file `src/workflows/hooks/update-cart-promotions-validate.ts` with the following content:
3372
3373 ```ts title="src/workflows/hooks/update-cart-promotions-validate.ts"
3374 import { updateCartPromotionsWorkflow } from "@medusajs/medusa/core-flows"
3375 import {
3376 MedusaError,
3377 ContainerRegistrationKeys,
3378 } from "@medusajs/framework/utils"
3379 import { PromotionActions } from "@medusajs/framework/utils"
3380
3381 updateCartPromotionsWorkflow.hooks.validate(async ({ input, cart }, { container }) => {
3382 const query = container.resolve(
3383 ContainerRegistrationKeys.QUERY
3384 )
3385
3386 // Only validate when adding promotions
3387 if (
3388 (input.action !== PromotionActions.ADD && input.action !== PromotionActions.REPLACE) ||
3389 !input.promo_codes || input.promo_codes.length === 0
3390 ) {
3391 return
3392 }
3393
3394 // Get customer details with tier
3395 const data = cart.customer_id ? await query.graph({
3396 entity: "customer",
3397 fields: ["id", "tier.*"],
3398 filters: {
3399 id: cart.customer_id,
3400 },
3401 }) : null
3402
3403 // Get customer's tier
3404 const customerTier = data?.data?.[0]?.tier
3405
3406 // Get promotions by codes to check if they're tier promotions
3407 const { data: promotions } = await query.graph({
3408 entity: "promotion",
3409 fields: ["id", "code"],
3410 filters: {
3411 code: input.promo_codes,
3412 },
3413 })
3414
3415 // Get all tiers with their promotion IDs
3416 const { data: allTiers } = await query.graph({
3417 entity: "tier",
3418 fields: ["id", "promo_id"],
3419 filters: {
3420 promo_id: promotions.map((p) => p.id),
3421 },
3422 })
3423
3424 // Validate each promotion being added
3425 for (const promotion of promotions || []) {
3426 const tierId = allTiers.find((t) => t.promo_id === promotion?.id)?.id
3427
3428 // If this promotion belongs to a tier
3429 if (tierId && customerTier?.id !== tierId) {
3430 throw new MedusaError(
3431 MedusaError.Types.INVALID_DATA,
3432 `Promotion ${promotion.code || promotion.id} can only be applied by customers in the corresponding tier.`
3433 )
3434 }
3435 }
3436 })
3437 ```
3438
3439 You consume a hook by accessing it through the workflow's `hooks` property. The hook accepts a step function as a parameter.
3440
3441 In the hook, you:
3442
3443 1. Return early if the customer isn't adding a promotion.
3444 2. Retrieve the customer if it's set in the cart.
3445 3. Retrieve promotions being added to the cart.
3446 4. Retrieve all tiers associated with the promotions.
3447 5. Loop over the promotions and check if the customer belongs to the tier associated with the promotion.
3448 - If not, you throw an error, which will stop the customer from adding the promotion to the cart.
3449
3450 ### Test Validate Promotion Addition
3451
3452 To test the promotion addition validation, make sure both the Medusa application and the Next.js Starter Storefront are running.
3453
3454 Then, in the Next.js Starter Storefront, log in as a customer in a tier, and add a product to the cart.
3455
3456 Try to add a promotion that belongs to a different tier. You should see an error message.
3457
3458 ![Error message when trying to add a promotion of a different tier to the cart](https://res.cloudinary.com/dza7lstvk/image/upload/v1764074555/Medusa%20Resources/CleanShot_2025-11-25_at_14.42.18_2x_uxkfgk.png)
3459
3460 ### Validate Cart Completion
3461
3462 Next, you'll add similar validation for the cart's promotions when completing the cart. You'll perform the validation by consuming the `validate` hook of the `completeCartWorkflow`.
3463
3464 Create the file `src/workflows/hooks/complete-cart-validate.ts` with the following content:
3465
3466 ```ts title="src/workflows/hooks/complete-cart-validate.ts"
3467 import { completeCartWorkflow } from "@medusajs/medusa/core-flows"
3468 import {
3469 MedusaError,
3470 ContainerRegistrationKeys,
3471 } from "@medusajs/framework/utils"
3472
3473 completeCartWorkflow.hooks.validate(async ({ cart }, { container }) => {
3474 const query = container.resolve(
3475 ContainerRegistrationKeys.QUERY
3476 )
3477
3478 // Get cart with promotions
3479 const { data: [detailedCart] } = await query.graph({
3480 entity: "cart",
3481 fields: ["id", "promotions.*", "customer.id", "customer.tier.*"],
3482 filters: {
3483 id: cart.id,
3484 },
3485 }, {
3486 throwIfKeyNotFound: true,
3487 })
3488
3489 if (!detailedCart?.promotions || detailedCart.promotions.length === 0) {
3490 return
3491 }
3492
3493 // Get customer's tier
3494 const customerTier = detailedCart.customer?.tier
3495
3496 // Get all tier promotions to check
3497 const { data: allTiers } = await query.graph({
3498 entity: "tier",
3499 fields: ["id", "promo_id"],
3500 filters: {
3501 promo_id: detailedCart.promotions.map((p) => p?.id).filter(Boolean) as string[],
3502 },
3503 })
3504
3505 // Validate that if a tier promotion is applied, the customer belongs to that tier
3506 for (const promotion of detailedCart.promotions) {
3507 const tierId = allTiers.find((t) => t.promo_id === promotion?.id)?.id
3508 if (tierId && customerTier?.id !== tierId) {
3509 throw new MedusaError(
3510 MedusaError.Types.INVALID_DATA,
3511 `Promotion ${promotion?.code || promotion?.id} can only be applied by customers in the corresponding tier.`
3512 )
3513 }
3514 }
3515 })
3516 ```
3517
3518 Similar to the previous hook, you:
3519
3520 1. Retrieve the cart with its promotions and customer tier.
3521 - If the cart doesn't have promotions, return early.
3522 2. Retrieve the tiers associated with the applied promotions.
3523 3. Loop over the promotions and check if any promotion doesn't belong to the customer's tier.
3524 - If so, you throw an error, which will stop the customer from completing the cart.
3525
3526 This validation will run every time the cart is completed and before the order is placed.
3527
3528 ---
3529
3530 ## Step 14: Show Customer Tier in Storefront
3531
3532 In this step, you'll add an API route that retrieves a customer's current tier and their next tier. Then, you'll customize the Next.js Starter Storefront to show a tier progress indicator on the account and order confirmation pages.
3533
3534 ### a. Calculate Next Tier Method
3535
3536 To calculate the customer's next tier, you'll add a method to the Tier Module's service. You'll then use that method in the API route to retrieve the customer's next tier.
3537
3538 In `src/modules/tier/service.ts`, add the following method to the `TierModuleService` class:
3539
3540 ```ts title="src/modules/tier/service.ts"
3541 class TierModuleService extends MedusaService({
3542 Tier,
3543 TierRule,
3544 }) {
3545 // ...
3546 async calculateNextTierUpgrade(
3547 currencyCode: string,
3548 currentPurchaseValue: number
3549 ) {
3550 const rules = await this.listTierRules(
3551 {
3552 currency_code: currencyCode,
3553 },
3554 {
3555 relations: ["tier"],
3556 }
3557 )
3558
3559 // Sort rules by min_purchase_value in ascending orderding order
3560 const sortedRules = rules.sort(
3561 (a, b) => a.min_purchase_value - b.min_purchase_value
3562 )
3563
3564 // Find the next tier the customer hasn't reached
3565 const nextRule = sortedRules.find(
3566 (rule) => rule.min_purchase_value > currentPurchaseValue
3567 )
3568
3569 if (!nextRule || !nextRule.tier) {
3570 return null
3571 }
3572
3573 const requiredAmount = nextRule.min_purchase_value - currentPurchaseValue
3574
3575 return {
3576 tier: nextRule.tier,
3577 required_amount: requiredAmount,
3578 current_purchase_value: currentPurchaseValue,
3579 next_tier_min_purchase: nextRule.min_purchase_value,
3580 }
3581 }
3582 }
3583 ```
3584
3585 The `calculateNextTierUpgrade` method receives the currency code and the current purchase value of a customer.
3586
3587 In the method, you:
3588
3589 - Retrieve the tier rules for the given currency code.
3590 - Sort the rules by the minimum purchase value in ascending order.
3591 - Find the next tier the customer hasn't reached.
3592 - Return the next tier, the required amount to reach the next tier, the current purchase value, and the minimum purchase value of the next tier.
3593
3594 ### b. Next Tier API Route
3595
3596 Next, you'll create an API route that retrieves a customer's current tier and their next tier.
3597
3598 To create the API route, create the file `src/api/store/customers/me/next-tier/route.ts` with the following content:
3599
3600 ```ts title="src/api/store/customers/me/next-tier/route.ts"
3601 import {
3602 AuthenticatedMedusaRequest,
3603 MedusaResponse,
3604 } from "@medusajs/framework/http"
3605 import { TIER_MODULE } from "../../../../../modules/tier"
3606 import {
3607 MedusaError,
3608 ContainerRegistrationKeys,
3609 } from "@medusajs/framework/utils"
3610 import { z } from "@medusajs/framework/zod"
3611 import { OrderStatus } from "@medusajs/framework/utils"
3612
3613 export const NextTierSchema = z.object({
3614 region_id: z.string(),
3615 })
3616
3617 type NextTierInput = z.infer<typeof NextTierSchema>
3618
3619 export async function GET(
3620 req: AuthenticatedMedusaRequest<{}, NextTierInput>,
3621 res: MedusaResponse
3622 ): Promise<void> {
3623 // Validate customer is authenticated
3624 const customerId = req.auth_context?.actor_id
3625
3626 if (!customerId) {
3627 throw new MedusaError(
3628 MedusaError.Types.UNAUTHORIZED,
3629 "Customer must be authenticated"
3630 )
3631 }
3632
3633 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
3634 const tierModuleService = req.scope.resolve(TIER_MODULE)
3635
3636 // Get customer details to validate they're registered
3637 const { data: [customer] } = await query.graph({
3638 entity: "customer",
3639 fields: ["id", "has_account", "tier.*"],
3640 filters: {
3641 id: customerId,
3642 },
3643 }, {
3644 throwIfKeyNotFound: true,
3645 })
3646
3647 if (!customer.has_account) {
3648 throw new MedusaError(
3649 MedusaError.Types.INVALID_DATA,
3650 "Customer must be registered to view tier information"
3651 )
3652 }
3653
3654 // Get currency code from cart or region context
3655 // Try to get from cart first, then region
3656 const regionId = req.validatedQuery.region_id
3657
3658 // Calculate total purchase value
3659 const { data: orders } = await query.graph({
3660 entity: "order",
3661 fields: ["id", "total", "currency_code"],
3662 filters: {
3663 customer_id: customerId,
3664 region_id: regionId,
3665 status: {
3666 $nin: [
3667 OrderStatus.CANCELED,
3668 OrderStatus.DRAFT,
3669 ],
3670 },
3671 },
3672 })
3673
3674 // Get currency code from region if no orders
3675 let currencyCode: string | null = null
3676 if (orders.length > 0) {
3677 currencyCode = orders[0].currency_code
3678 } else {
3679 // Get currency from region
3680 const { data: regions } = await query.graph({
3681 entity: "region",
3682 fields: ["id", "currency_code"],
3683 filters: {
3684 id: regionId,
3685 },
3686 })
3687
3688 if (regions && regions.length > 0) {
3689 currencyCode = regions[0].currency_code
3690 }
3691 }
3692
3693 const totalPurchaseValue = orders.length > 0
3694 ? orders.reduce((sum: number, order: any) => sum + (order.total || 0), 0)
3695 : 0
3696
3697 // Current tier is always the customer's assigned tier (null if not assigned)
3698 const currentTier = customer.tier || null
3699
3700 // Determine next tier upgrade
3701 const nextTierUpgrade = await tierModuleService.calculateNextTierUpgrade(
3702 currencyCode as string,
3703 totalPurchaseValue
3704 )
3705
3706 res.json({
3707 current_tier: currentTier,
3708 current_purchase_value: totalPurchaseValue,
3709 currency_code: currencyCode,
3710 next_tier_upgrade: nextTierUpgrade,
3711 })
3712 }
3713 ```
3714
3715 You first define a Zod schema to validate incoming requests. Requests must have a `region_id` query parameter. This determines the currency code to use for the tier calculation.
3716
3717 Then, you export a `GET` function, which exposes a `GET` API route at `/store/customers/me/next-tier`.
3718
3719 In the route handler, you:
3720
3721 - Validate that the customer is authenticated.
3722 - Resolve Query and the Tier Module service from the Medusa container.
3723 - Retrieve the customer details to validate that they're registered.
3724 - Retrieve the currency code from the cart or region context.
3725 - Calculate the total purchase value of the customer.
3726 - Determine the customer's current tier.
3727 - Determine the customer's next tier upgrade.
3728 - Return the customer's current tier, current purchase value, currency code, and next tier upgrade in the response.
3729
3730 ### c. Apply Query Validation Middleware
3731
3732 Next, you need to apply a middleware that validates the query parameters passed to the request, and sets the default Query configurations.
3733
3734 In `src/api/middlewares.ts`, add the import at the top of the file:
3735
3736 ```ts title="src/api/middlewares.ts"
3737 import { NextTierSchema } from "./store/customers/me/next-tier/route"
3738 ```
3739
3740 Then, add the following object to the `routes` array passed to `defineMiddlewares`:
3741
3742 ```ts title="src/api/middlewares.ts"
3743 export default defineMiddlewares({
3744 routes: [
3745 // ...
3746 {
3747 matcher: "/store/customers/me/next-tier",
3748 methods: ["GET"],
3749 middlewares: [validateAndTransformQuery(NextTierSchema, {})],
3750 },
3751 ],
3752 })
3753 ```
3754
3755 You apply the `validateAndTransformQuery` middleware to the `GET` route of the `/store/customers/me/next-tier` path, passing it the `NextTierSchema` schema to validate the request parameters.
3756
3757 ### d. Show Customer Tier in Storefront
3758
3759 Next, you'll customize the Next.js Starter Storefront to show a tier progress indicator in the account and order confirmation pages.
3760
3761 #### Define Tier Types
3762
3763 First, you'll define types for the tier information received from the Medusa server.
3764
3765 Create the file `src/types/tier.ts` in the storefront with the following content:
3766
3767 ```ts title="src/types/tier.ts" badgeLabel="Storefront" badgeColor="blue"
3768 export type Tier = {
3769 id: string
3770 name: string
3771 promotion_id: string
3772 }
3773
3774 export type CustomerNextTier = {
3775 current_tier: Tier | null
3776 current_purchase_value: number
3777 currency_code: string
3778 next_tier_upgrade: {
3779 tier: Tier | null
3780 required_amount: number
3781 current_purchase_value: number
3782 next_tier_min_purchase: number
3783 } | null
3784 }
3785 ```
3786
3787 The `Tier` type represents a tier, and the `CustomerNextTier` type represents the response received from the `/store/customers/me/next-tier` API route.
3788
3789 #### Retrieve Customer Tier and Next Tier
3790
3791 Next, you'll add a server function that retrieves the customer's current tier and their next tier.
3792
3793 In `src/lib/data/customer.ts`, add the following imports at the top of the file:
3794
3795 ```ts title="src/lib/data/customer.ts" badgeLabel="Storefront" badgeColor="blue"
3796 import { CustomerNextTier } from "types/tier"
3797 import { getRegion } from "./regions"
3798 ```
3799
3800 Then, add the following function to the file:
3801
3802 ```ts title="src/lib/data/customer.ts" badgeLabel="Storefront" badgeColor="blue"
3803 export const retrieveCustomerNextTier =
3804 async (countryCode: string): Promise<CustomerNextTier | null> => {
3805 const authHeaders = await getAuthHeaders()
3806 const region = await getRegion(countryCode)
3807
3808 if (!region) {return null}
3809
3810 if (!authHeaders) {return null}
3811
3812 const headers = {
3813 ...authHeaders,
3814 }
3815
3816 const next = {
3817 ...(await getCacheOptions("customers")),
3818 }
3819
3820 return await sdk.client
3821 .fetch<CustomerNextTier>(`/store/customers/me/next-tier`, {
3822 method: "GET",
3823 headers,
3824 next,
3825 query: {
3826 region_id: region.id,
3827 },
3828 })
3829 .then((data) => data)
3830 .catch(() => null)
3831 }
3832 ```
3833
3834 You create a function that retrieves the customer's current tier and their next tier from the `/store/customers/me/next-tier` API route.
3835
3836 #### Add Customer Tier Component
3837
3838 Next, you'll create a component that displays a progress indicator for the customer's tier. You'll use this component on the account and order confirmation pages.
3839
3840 Create the file `src/modules/common/customer-tier/index.tsx` with the following content:
3841
3842 ```tsx title="src/modules/common/customer-tier/index.tsx" badgeLabel="Storefront" badgeColor="blue"
3843 import { convertToLocale } from "@lib/util/money"
3844 import { clx } from "@medusajs/ui"
3845 import { CustomerNextTier } from "types/tier"
3846
3847 type CustomerTierProps = {
3848 tierData: CustomerNextTier | null
3849 }
3850
3851 const CustomerTier = ({ tierData }: CustomerTierProps) => {
3852 if (!tierData) {
3853 return null
3854 }
3855
3856 const { current_tier, current_purchase_value, currency_code, next_tier_upgrade } = tierData
3857
3858 // Calculate progress if there's a next tier
3859 let progressPercentage = 100
3860 let amountNeeded = 0
3861 let minPurchaseValue = 0
3862 let hasNextTier = false
3863 let nextTierName = ""
3864
3865 if (next_tier_upgrade && next_tier_upgrade.tier) {
3866 hasNextTier = true
3867 nextTierName = next_tier_upgrade.tier.name
3868 amountNeeded = next_tier_upgrade.required_amount
3869 minPurchaseValue = next_tier_upgrade.next_tier_min_purchase
3870
3871 // Calculate progress percentage
3872 // Use the current purchase value and next tier min purchase from the API
3873 const currentPurchase = next_tier_upgrade.current_purchase_value
3874 const nextMin = next_tier_upgrade.next_tier_min_purchase
3875
3876 // Calculate progress: current purchase value / next tier min purchase
3877 if (nextMin > 0) {
3878 progressPercentage = Math.min(100, Math.max(0, (currentPurchase / nextMin) * 100))
3879 } else {
3880 progressPercentage = 100
3881 }
3882 }
3883
3884 // If no current tier and no next tier, don't show anything
3885 if (!current_tier && !hasNextTier) {
3886 return null
3887 }
3888
3889 return (
3890 <div className="flex flex-col gap-y-4">
3891 <h3 className="text-large-semi">Membership Tier</h3>
3892 <div className="flex flex-col gap-y-3">
3893 {current_tier ? (
3894 <div className="flex items-center gap-x-2">
3895 <span className="text-large-semi" data-testid="current-tier-name">
3896 {current_tier.name}
3897 </span>
3898 </div>
3899 ) : (
3900 <div className="flex items-center gap-x-2">
3901 <span className="text-large-semi text-ui-fg-subtle" data-testid="current-tier-name">
3902 No tier
3903 </span>
3904 </div>
3905 )}
3906
3907 {hasNextTier && (
3908 <div className="flex flex-col gap-y-2">
3909 <div className="flex justify-between text-small-regular text-ui-fg-subtle">
3910 <span>Progress to {nextTierName}</span>
3911 {amountNeeded > 0 ? (
3912 <span>
3913 {convertToLocale({
3914 amount: amountNeeded,
3915 currency_code: currency_code,
3916 })}{" "}
3917 to go
3918 </span>
3919 ) : (
3920 <span className="text-ui-fg-interactive">Threshold reached!</span>
3921 )}
3922 </div>
3923 <div className="flex">
3924 <div
3925 className={clx(
3926 `h-2 rounded-s-full transition-all duration-500 ease-in-out`,
3927 progressPercentage >= 100
3928 ? "bg-gradient-to-r from-green-400 to-green-500"
3929 : "bg-gradient-to-r from-ui-fg-interactive to-ui-fg-interactive-hover",
3930 progressPercentage === 100 && "rounded-e-full"
3931 )}
3932 style={{ width: `${progressPercentage}%` }}
3933 data-testid="tier-progress-bar"
3934 />
3935 <div className={clx(
3936 "bg-gray-200 h-2 rounded-e-full flex-grow",
3937 progressPercentage === 0 && "rounded-s-full"
3938 )} />
3939 </div>
3940 <div className="flex justify-between text-xs text-ui-fg-subtle">
3941 <span>
3942 {convertToLocale({
3943 amount: next_tier_upgrade?.current_purchase_value || current_purchase_value,
3944 currency_code: currency_code,
3945 })}
3946 </span>
3947 {minPurchaseValue > 0 && (
3948 <span>
3949 {convertToLocale({
3950 amount: minPurchaseValue,
3951 currency_code: currency_code,
3952 })}
3953 </span>
3954 )}
3955 </div>
3956 </div>
3957 )}
3958
3959 {!hasNextTier && current_tier && (
3960 <div className="text-small-regular text-ui-fg-subtle">
3961 You&apos;ve reached the highest tier!
3962 </div>
3963 )}
3964 </div>
3965 </div>
3966 )
3967 }
3968
3969 export default CustomerTier
3970 ```
3971
3972 The component receives the tier data retrieved from the Medusa server as a prop. It then calculates and displays a progress bar indicating how much the customer needs to spend to unlock the next tier.
3973
3974 #### Show Customer Tier on Account Page
3975
3976 Next, you'll show the customer's tier on the account page.
3977
3978 In `src/modules/account/components/overview/index.tsx`, add the following imports at the top of the file:
3979
3980 ```tsx title="src/modules/account/components/overview/index.tsx" badgeLabel="Storefront" badgeColor="blue"
3981 import CustomerTier from "@modules/common/customer-tier"
3982 import { CustomerNextTier } from "types/tier"
3983 ```
3984
3985 Then, update the `Overview` component's props to include the `tierData` prop:
3986
3987 ```tsx title="src/modules/account/components/overview/index.tsx" badgeLabel="Storefront" badgeColor="blue"
3988 type OverviewProps = {
3989 // ...
3990 tierData: CustomerNextTier | null
3991 }
3992
3993 const Overview = ({ customer, orders, tierData }: OverviewProps) => {
3994 // ...
3995 }
3996 ```
3997
3998 Finally, update the `return` statement to render the `CustomerTier` component before the `div` wrapping the recent orders:
3999
4000 ```tsx title="src/modules/account/components/overview/index.tsx" badgeLabel="Storefront" badgeColor="blue"
4001 return (
4002 <div>
4003 {/* ... */}
4004 {tierData && (
4005 <div className="mb-6">
4006 <CustomerTier tierData={tierData} />
4007 </div>
4008 )}
4009 {/* ... */}
4010 </div>
4011 )
4012 ```
4013
4014 To pass the tier data to the `Overview` component, replace the content of `src/app/[countryCode]/(main)/account/@dashboard/page.tsx` with the following:
4015
4016 ```tsx title="src/app/[countryCode]/(main)/account/@dashboard/page.tsx" badgeLabel="Storefront" badgeColor="blue"
4017 import { Metadata } from "next"
4018
4019 import Overview from "@modules/account/components/overview"
4020 import { notFound } from "next/navigation"
4021 import { retrieveCustomer, retrieveCustomerNextTier } from "@lib/data/customer"
4022 import { listOrders } from "@lib/data/orders"
4023
4024 export const metadata: Metadata = {
4025 title: "Account",
4026 description: "Overview of your account activity.",
4027 }
4028
4029 type Props = {
4030 params: Promise<{ countryCode: string }>
4031 }
4032
4033 export default async function OverviewTemplate(props: Props) {
4034 const params = await props.params
4035 const { countryCode } = params
4036 const customer = await retrieveCustomer().catch(() => null)
4037 const orders = (await listOrders().catch(() => null)) || null
4038 const tierData = await retrieveCustomerNextTier(countryCode).catch(() => null)
4039
4040 if (!customer) {
4041 notFound()
4042 }
4043
4044 return <Overview customer={customer} orders={orders} tierData={tierData} />
4045 }
4046 ```
4047
4048 You make the following key changes:
4049
4050 - Add the import for the `retrieveCustomerNextTier` function.
4051 - Add the `countryCode` parameter type to the `OverviewTemplate` component props.
4052 - Retrieve the customer's tier and next tier information using the `retrieveCustomerNextTier` function.
4053 - Pass the tier data to the `Overview` component.
4054
4055 #### Test Customer Tier on Account Page
4056
4057 To test the customer tier component on the account page, make sure both the Medusa server and the Next.js Starter Storefront are running.
4058
4059 Then, on the storefront, click "Account" in the navigation bar. The main account page will display the customer's current tier with a progress bar showing their progress toward the next tier.
4060
4061 ![Customer tier component on account page](https://res.cloudinary.com/dza7lstvk/image/upload/v1764078181/Medusa%20Resources/CleanShot_2025-11-25_at_15.42.44_2x_hhguzm.png)
4062
4063 #### Show Customer Tier on Order Confirmation Page
4064
4065 Next, you'll show the customer tier component on the order confirmation page.
4066
4067 In `src/modules/order/templates/order-completed-template.tsx`, add the following imports at the top of the file:
4068
4069 ```tsx title="src/modules/order/templates/order-completed-template.tsx" badgeLabel="Storefront" badgeColor="blue"
4070 import CustomerTier from "@modules/common/customer-tier"
4071 import { CustomerNextTier } from "types/tier"
4072 ```
4073
4074 Then, update the `OrderCompletedTemplate` component's props to include the `tierData` prop:
4075
4076 ```tsx title="src/modules/order/templates/order-completed-template.tsx" badgeLabel="Storefront" badgeColor="blue"
4077 type OrderCompletedTemplateProps = {
4078 // ...
4079 tierData: CustomerNextTier | null
4080 }
4081
4082 export default async function OrderCompletedTemplate({
4083 // ...
4084 tierData,
4085 }: OrderCompletedTemplateProps) {
4086 // ...
4087 }
4088 ```
4089
4090 Finally, update the `return` statement to render the `CustomerTier` component before the "Summary" heading:
4091
4092 ```tsx title="src/modules/order/templates/order-completed-template.tsx" badgeLabel="Storefront" badgeColor="blue"
4093 return (
4094 <div>
4095 {/* ... */}
4096 {tierData && (
4097 <div className="mt-6">
4098 <CustomerTier tierData={tierData} />
4099 </div>
4100 )}
4101 {/* ... */}
4102 </div>
4103 )
4104 ```
4105
4106 To pass the tier data to the `OrderCompletedTemplate` component, open `src/app/[countryCode]/(main)/order/[id]/confirmed/page.tsx` and replace the content with the following:
4107
4108 ```tsx title="src/app/[countryCode]/(main)/order/[id]/confirmed/page.tsx" badgeLabel="Storefront" badgeColor="blue"
4109 import { retrieveOrder } from "@lib/data/orders"
4110 import OrderCompletedTemplate from "@modules/order/templates/order-completed-template"
4111 import { Metadata } from "next"
4112 import { notFound } from "next/navigation"
4113 import { retrieveCustomerNextTier } from "@lib/data/customer"
4114
4115 type Props = {
4116 params: Promise<{ id: string; countryCode: string }>
4117 }
4118 export const metadata: Metadata = {
4119 title: "Order Confirmed",
4120 description: "You purchase was successful",
4121 }
4122
4123 export default async function OrderConfirmedPage(props: Props) {
4124 const params = await props.params
4125 const order = await retrieveOrder(params.id).catch(() => null)
4126 const tierData = await retrieveCustomerNextTier(params.countryCode).catch(() => null)
4127
4128 if (!order) {
4129 return notFound()
4130 }
4131
4132 return <OrderCompletedTemplate order={order} tierData={tierData} />
4133 }
4134 ```
4135
4136 You make the following key changes:
4137
4138 - Add the import for the `retrieveCustomerNextTier` function.
4139 - Add the `countryCode` parameter to the `OrderConfirmedPage` component.
4140 - Retrieve the customer's tier and their next tier using the `retrieveCustomerNextTier` function.
4141 - Pass the tier data to the `OrderCompletedTemplate` component.
4142
4143 #### Test Customer Tier on Order Confirmation Page
4144
4145 To test the customer tier component on the order confirmation page, make sure both the Medusa server and the Next.js Starter Storefront are running.
4146
4147 Then, on the storefront, place an order. The order confirmation page will display the customer's tier with a progress bar showing their progress toward the next tier.
4148
4149 ![Customer tier component on order confirmation page](https://res.cloudinary.com/dza7lstvk/image/upload/v1764078663/Medusa%20Resources/CleanShot_2025-11-25_at_15.50.50_2x_liqi8r.png)
4150
4151 ---
4152
4153 ## Next Steps
4154
4155 You've now implemented customer tiers in Medusa. You can expand on this feature to add more features like:
4156
4157 - Automated emails to customers when they reach a new tier. Cloud users can benefit from zero-config email setup with [Medusa Emails](!cloud!/emails).
4158 - More complex tier rules, such as rules based on product categories or collections.
4159 - Other tier privileges, such as early access to new products or free shipping.
4160
4161
4162 If you're new to Medusa, check out the [main documentation](!docs!/learn) for a more in-depth understanding of the concepts you've used in this guide and more.
4163
4164 To learn more about the commerce features Medusa provides, check out [Commerce Modules](../../../commerce-modules/page.mdx).
4165
4166 ### Troubleshooting
4167
4168 If you encounter issues during your development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx).
4169
4170 ### Getting Help
4171
4172 If you encounter issues not covered in the troubleshooting guides:
4173
4174 1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions.
4175 2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members.