|
1
|
--- |
|
2
|
sidebar_label: "Loyalty Points" |
|
3
|
tags: |
|
4
|
- name: cart |
|
5
|
label: "Implement Loyalty Points" |
|
6
|
- server |
|
7
|
- tutorial |
|
8
|
- name: order |
|
9
|
label: "Implement Loyalty Points" |
|
10
|
- name: customer |
|
11
|
label: "Implement Loyalty Points" |
|
12
|
- name: promotion |
|
13
|
label: "Implement Loyalty Points" |
|
14
|
products: |
|
15
|
- cart |
|
16
|
- order |
|
17
|
- customer |
|
18
|
- promotion |
|
19
|
--- |
|
20
|
|
|
21
|
import { Github, PlaySolid } from "@medusajs/icons" |
|
22
|
import { Prerequisites, WorkflowDiagram, CardList } from "docs-ui" |
|
23
|
|
|
24
|
export const metadata = { |
|
25
|
title: `Implement Loyalty Points System in Medusa`, |
|
26
|
} |
|
27
|
|
|
28
|
# {metadata.title} |
|
29
|
|
|
30
|
In this tutorial, you'll learn how to implement a loyalty points system in Medusa. |
|
31
|
|
|
32
|
<Note title="New: Loyalty Plugin"> |
|
33
|
|
|
34
|
This guide was written before the release of the [Loyalty Plugin](../../../commerce-modules/loyalty/page.mdx), which adds features like gift cards and store credit. You can follow the approach of this guide, or use the [Store Credit Module](../../../commerce-modules/store-credit/page.mdx) from the Loyalty Plugin to implement a loyalty points system. |
|
35
|
|
|
36
|
</Note> |
|
37
|
|
|
38
|
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 management capabilities related to carts, orders, promotions, and more. |
|
39
|
|
|
40
|
A loyalty point system allows customers to earn points for purchases, which can be redeemed for discounts or rewards. In this tutorial, you'll learn how to customize the Medusa application to implement a loyalty points system. |
|
41
|
|
|
42
|
You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer. |
|
43
|
|
|
44
|
## Summary |
|
45
|
|
|
46
|
By following this tutorial, you will learn how to: |
|
47
|
|
|
48
|
- Install and set up Medusa. |
|
49
|
- Define models to store loyalty points and the logic to manage them. |
|
50
|
- Build flows that allow customers to earn and redeem points during checkout. |
|
51
|
- Points are redeemed through dynamic promotions specific to the customer. |
|
52
|
- Customize the cart completion flow to validate applied loyalty points. |
|
53
|
|
|
54
|
 |
|
55
|
|
|
56
|
<CardList items={[ |
|
57
|
{ |
|
58
|
href: "https://github.com/medusajs/examples/tree/main/loyalty-points", |
|
59
|
title: "Loyalty Points Repository", |
|
60
|
text: "Find the full code for this guide in this repository.", |
|
61
|
icon: Github, |
|
62
|
}, |
|
63
|
{ |
|
64
|
href: "https://res.cloudinary.com/dza7lstvk/raw/upload/v1744212595/OpenApi/Loyalty-Points_jwi5e9.yaml", |
|
65
|
title: "OpenApi Specs for Postman", |
|
66
|
text: "Import this OpenApi Specs file into tools like Postman.", |
|
67
|
icon: PlaySolid, |
|
68
|
}, |
|
69
|
]} /> |
|
70
|
|
|
71
|
--- |
|
72
|
|
|
73
|
## Step 1: Install a Medusa Application |
|
74
|
|
|
75
|
<Prerequisites items={[ |
|
76
|
{ |
|
77
|
text: "Node.js v20.19.0+ or v22.12.0+", |
|
78
|
link: "https://nodejs.org/en/download" |
|
79
|
}, |
|
80
|
{ |
|
81
|
text: "Git CLI tool", |
|
82
|
link: "https://git-scm.com/downloads" |
|
83
|
}, |
|
84
|
{ |
|
85
|
text: "PostgreSQL", |
|
86
|
link: "https://www.postgresql.org/download/" |
|
87
|
} |
|
88
|
]} /> |
|
89
|
|
|
90
|
Start by installing the Medusa application on your machine with the following command: |
|
91
|
|
|
92
|
```bash npx2yarnExec |
|
93
|
npx create-medusa-app@latest |
|
94
|
``` |
|
95
|
|
|
96
|
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. |
|
97
|
|
|
98
|
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. |
|
99
|
|
|
100
|
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. |
|
101
|
|
|
102
|
<Note title="Ran into Errors"> |
|
103
|
|
|
104
|
Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help. |
|
105
|
|
|
106
|
</Note> |
|
107
|
|
|
108
|
<Note> |
|
109
|
|
|
110
|
In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project. |
|
111
|
|
|
112
|
</Note> |
|
113
|
|
|
114
|
--- |
|
115
|
|
|
116
|
## Step 2: Create Loyalty Module |
|
117
|
|
|
118
|
In Medusa, you can build custom features in a [module](!docs!/learn/fundamentals/modules). A module is a reusable package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup. |
|
119
|
|
|
120
|
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. |
|
121
|
|
|
122
|
In this step, you'll build a Loyalty Module that defines the necessary data models to store and manage loyalty points for customers. |
|
123
|
|
|
124
|
<Note> |
|
125
|
|
|
126
|
Refer to the [Modules documentation](!docs!/learn/fundamentals/modules) to learn more. |
|
127
|
|
|
128
|
</Note> |
|
129
|
|
|
130
|
### Create Module Directory |
|
131
|
|
|
132
|
Modules are created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/loyalty`. |
|
133
|
|
|
134
|
### Create Data Models |
|
135
|
|
|
136
|
A data model represents a table in the database. You create data models using Medusa's Data Model Language (DML). It simplifies defining a table's columns, relations, and indexes with straightforward methods and configurations. |
|
137
|
|
|
138
|
<Note> |
|
139
|
|
|
140
|
Refer to the [Data Models documentation](!docs!/learn/fundamentals/modules#1-create-data-model) to learn more. |
|
141
|
|
|
142
|
</Note> |
|
143
|
|
|
144
|
For the Loyalty Module, you need to define a `LoyaltyPoint` data model that represents a customer's loyalty points. So, create the file `src/modules/loyalty/models/loyalty-point.ts` with the following content: |
|
145
|
|
|
146
|
export const dmlHighlights = [ |
|
147
|
["4", "id", "Unique ID for the loyalty points"], |
|
148
|
["5", "points", "Number of loyalty points a customer has"], |
|
149
|
["6", "customer_id", "ID of the customer who owns the loyalty points"], |
|
150
|
["6", "unique", "Ensure that each customer has only one record in the loyalty_point table"], |
|
151
|
] |
|
152
|
|
|
153
|
```ts title="src/modules/loyalty/models/loyalty-point.ts" highlights={dmlHighlights} |
|
154
|
import { model } from "@medusajs/framework/utils" |
|
155
|
|
|
156
|
const LoyaltyPoint = model.define("loyalty_point", { |
|
157
|
id: model.id().primaryKey(), |
|
158
|
points: model.number().default(0), |
|
159
|
customer_id: model.text().unique("IDX_LOYALTY_CUSTOMER_ID"), |
|
160
|
}) |
|
161
|
|
|
162
|
export default LoyaltyPoint |
|
163
|
``` |
|
164
|
|
|
165
|
You define the `LoyaltyPoint` 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. |
|
166
|
|
|
167
|
The `LoyaltyPoint` data model has the following properties: |
|
168
|
|
|
169
|
- `id`: A unique ID for the loyalty points. |
|
170
|
- `points`: The number of loyalty points a customer has. |
|
171
|
- `customer_id`: The ID of the customer who owns the loyalty points. This property has a unique index to ensure that each customer has only one record in the `loyalty_point` table. |
|
172
|
|
|
173
|
<Note> |
|
174
|
|
|
175
|
Learn more about defining data model properties in the [Property Types documentation](!docs!/learn/fundamentals/data-models/properties). |
|
176
|
|
|
177
|
</Note> |
|
178
|
|
|
179
|
### Create Module's Service |
|
180
|
|
|
181
|
You now have the necessary data model in the Loyalty Module, but you'll need to manage its records. You do this by creating a service in the module. |
|
182
|
|
|
183
|
A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to the database, allowing you to manage your data models, or connect to a third-party service, which is useful if you're integrating with external services. |
|
184
|
|
|
185
|
<Note> |
|
186
|
|
|
187
|
Refer to the [Module Service documentation](!docs!/learn/fundamentals/modules#2-create-service) to learn more. |
|
188
|
|
|
189
|
</Note> |
|
190
|
|
|
191
|
To create the Loyalty Module's service, create the file `src/modules/loyalty/service.ts` with the following content: |
|
192
|
|
|
193
|
```ts title="src/modules/loyalty/service.ts" |
|
194
|
import { MedusaError, MedusaService } from "@medusajs/framework/utils" |
|
195
|
import LoyaltyPoint from "./models/loyalty-point" |
|
196
|
import { InferTypeOf } from "@medusajs/framework/types" |
|
197
|
|
|
198
|
type LoyaltyPoint = InferTypeOf<typeof LoyaltyPoint> |
|
199
|
|
|
200
|
class LoyaltyModuleService extends MedusaService({ |
|
201
|
LoyaltyPoint, |
|
202
|
}) { |
|
203
|
// TODO add methods |
|
204
|
} |
|
205
|
|
|
206
|
export default LoyaltyModuleService |
|
207
|
``` |
|
208
|
|
|
209
|
The `LoyaltyModuleService` extends `MedusaService` from the Modules SDK which generates a class with data-management methods for your module's data models. This saves you time on implementing Create, Read, Update, and Delete (CRUD) methods. |
|
210
|
|
|
211
|
So, the `LoyaltyModuleService` class now has methods like `createLoyaltyPoints` and `retrieveLoyaltyPoint`. |
|
212
|
|
|
213
|
<Note> |
|
214
|
|
|
215
|
Find all methods generated by the `MedusaService` in [the Service Factory reference](../../../service-factory-reference/page.mdx). |
|
216
|
|
|
217
|
</Note> |
|
218
|
|
|
219
|
#### Add Methods to the Service |
|
220
|
|
|
221
|
Aside from the basic CRUD methods, you need to add methods that handle custom functionalities related to loyalty points. |
|
222
|
|
|
223
|
First, you need a method that adds loyalty points for a customer. Add the following method to the `LoyaltyModuleService`: |
|
224
|
|
|
225
|
```ts title="src/modules/loyalty/service.ts" |
|
226
|
class LoyaltyModuleService extends MedusaService({ |
|
227
|
LoyaltyPoint, |
|
228
|
}) { |
|
229
|
async addPoints(customerId: string, points: number): Promise<LoyaltyPoint> { |
|
230
|
const existingPoints = await this.listLoyaltyPoints({ |
|
231
|
customer_id: customerId, |
|
232
|
}) |
|
233
|
|
|
234
|
if (existingPoints.length > 0) { |
|
235
|
return await this.updateLoyaltyPoints({ |
|
236
|
id: existingPoints[0].id, |
|
237
|
points: existingPoints[0].points + points, |
|
238
|
}) |
|
239
|
} |
|
240
|
|
|
241
|
return await this.createLoyaltyPoints({ |
|
242
|
customer_id: customerId, |
|
243
|
points, |
|
244
|
}) |
|
245
|
} |
|
246
|
} |
|
247
|
``` |
|
248
|
|
|
249
|
You add an `addPoints` method that accepts two parameters: the ID of the customer and the points to add. |
|
250
|
|
|
251
|
In the method, you retrieve the customer's existing loyalty points using the `listLoyaltyPoints` method, which is automatically generated by the `MedusaService`. If the customer has existing points, you update them with the new points using the `updateLoyaltyPoints` method. |
|
252
|
|
|
253
|
Otherwise, if the customer doesn't have existing loyalty points, you create a new record with the `createLoyaltyPoints` method. |
|
254
|
|
|
255
|
The next method you'll add deducts points from the customer's loyalty points, which is useful when the customer redeems points. Add the following method to the `LoyaltyModuleService`: |
|
256
|
|
|
257
|
```ts title="src/modules/loyalty/service.ts" |
|
258
|
class LoyaltyModuleService extends MedusaService({ |
|
259
|
LoyaltyPoint, |
|
260
|
}) { |
|
261
|
// ... |
|
262
|
async deductPoints(customerId: string, points: number): Promise<LoyaltyPoint> { |
|
263
|
const existingPoints = await this.listLoyaltyPoints({ |
|
264
|
customer_id: customerId, |
|
265
|
}) |
|
266
|
|
|
267
|
if (existingPoints.length === 0 || existingPoints[0].points < points) { |
|
268
|
throw new MedusaError( |
|
269
|
MedusaError.Types.NOT_ALLOWED, |
|
270
|
"Insufficient loyalty points" |
|
271
|
) |
|
272
|
} |
|
273
|
|
|
274
|
return await this.updateLoyaltyPoints({ |
|
275
|
id: existingPoints[0].id, |
|
276
|
points: existingPoints[0].points - points, |
|
277
|
}) |
|
278
|
} |
|
279
|
} |
|
280
|
``` |
|
281
|
|
|
282
|
The `deductPoints` method accepts the customer ID and the points to deduct. |
|
283
|
|
|
284
|
In the method, you retrieve the customer's existing loyalty points using the `listLoyaltyPoints` method. If the customer doesn't have existing points or if the points to deduct are greater than the existing points, you throw an error. |
|
285
|
|
|
286
|
Otherwise, you update the customer's loyalty points with the new value using the `updateLoyaltyPoints` method, which is automatically generated by `MedusaService`. |
|
287
|
|
|
288
|
Next, you'll add the method that retrieves the points of a customer. Add the following method to the `LoyaltyModuleService`: |
|
289
|
|
|
290
|
```ts title="src/modules/loyalty/service.ts" |
|
291
|
class LoyaltyModuleService extends MedusaService({ |
|
292
|
LoyaltyPoint, |
|
293
|
}) { |
|
294
|
// ... |
|
295
|
async getPoints(customerId: string): Promise<number> { |
|
296
|
const points = await this.listLoyaltyPoints({ |
|
297
|
customer_id: customerId, |
|
298
|
}) |
|
299
|
|
|
300
|
return points[0]?.points || 0 |
|
301
|
} |
|
302
|
} |
|
303
|
``` |
|
304
|
|
|
305
|
The `getPoints` method accepts the customer ID and retrieves the customer's loyalty points using the `listLoyaltyPoints` method. If the customer has no points, it returns `0`. |
|
306
|
|
|
307
|
#### Add Method to Map Points to Discount |
|
308
|
|
|
309
|
Finally, you'll add a method that implements the logic of mapping loyalty points to a discount amount. This is useful when the customer wants to redeem their points during checkout. |
|
310
|
|
|
311
|
The mapping logic may differ for each use case. For example, you may need to use a third-party service to map the loyalty points discount amount, or use some custom calculation. |
|
312
|
|
|
313
|
To simplify the logic in this tutorial, you'll use a simple calculation that maps 1 point to 1 currency unit. For example, `100` points = `$100` discount. |
|
314
|
|
|
315
|
Add the following method to the `LoyaltyModuleService`: |
|
316
|
|
|
317
|
```ts title="src/modules/loyalty/service.ts" |
|
318
|
class LoyaltyModuleService extends MedusaService({ |
|
319
|
LoyaltyPoint, |
|
320
|
}) { |
|
321
|
// ... |
|
322
|
async calculatePointsFromAmount(amount: number): Promise<number> { |
|
323
|
// Convert amount to points using a standard conversion rate |
|
324
|
// For example, $1 = 1 point |
|
325
|
// Round down to nearest whole point |
|
326
|
const points = Math.floor(amount) |
|
327
|
|
|
328
|
if (points < 0) { |
|
329
|
throw new MedusaError( |
|
330
|
MedusaError.Types.INVALID_DATA, |
|
331
|
"Amount cannot be negative" |
|
332
|
) |
|
333
|
} |
|
334
|
|
|
335
|
return points |
|
336
|
} |
|
337
|
} |
|
338
|
``` |
|
339
|
|
|
340
|
The `calculatePointsFromAmount` method accepts the amount and converts it to the nearest whole number of points. If the amount is negative, it throws an error. |
|
341
|
|
|
342
|
You'll use this method later to calculate the amount discounted when a customer redeems their loyalty points. |
|
343
|
|
|
344
|
### Export Module Definition |
|
345
|
|
|
346
|
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. |
|
347
|
|
|
348
|
So, create the file `src/modules/loyalty/index.ts` with the following content: |
|
349
|
|
|
350
|
```ts title="src/modules/loyalty/index.ts" |
|
351
|
import { Module } from "@medusajs/framework/utils" |
|
352
|
import LoyaltyModuleService from "./service" |
|
353
|
|
|
354
|
export const LOYALTY_MODULE = "loyalty" |
|
355
|
|
|
356
|
export default Module(LOYALTY_MODULE, { |
|
357
|
service: LoyaltyModuleService, |
|
358
|
}) |
|
359
|
``` |
|
360
|
|
|
361
|
You use the `Module` function from the Modules SDK to create the module's definition. It accepts two parameters: |
|
362
|
|
|
363
|
1. The module's name, which is `loyalty`. |
|
364
|
2. An object with a required property `service` indicating the module's service. |
|
365
|
|
|
366
|
You also export the module's name as `LOYALTY_MODULE` so you can reference it later. |
|
367
|
|
|
368
|
### Add Module to Medusa's Configurations |
|
369
|
|
|
370
|
Once you finish building the module, add it to Medusa's configurations to start using it. |
|
371
|
|
|
372
|
In `medusa-config.ts`, add a `modules` property and pass an array with your custom module: |
|
373
|
|
|
374
|
```ts title="medusa-config.ts" |
|
375
|
module.exports = defineConfig({ |
|
376
|
// ... |
|
377
|
modules: [ |
|
378
|
{ |
|
379
|
resolve: "./src/modules/loyalty", |
|
380
|
}, |
|
381
|
], |
|
382
|
}) |
|
383
|
``` |
|
384
|
|
|
385
|
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. |
|
386
|
|
|
387
|
### Generate Migrations |
|
388
|
|
|
389
|
Since data models represent tables in the database, you define how they're created in the database with migrations. A migration is a TypeScript or JavaScript file that defines database changes made by a module. |
|
390
|
|
|
391
|
<Note> |
|
392
|
|
|
393
|
Refer to the [Migrations documentation](!docs!/learn/fundamentals/modules#5-generate-migrations) to learn more. |
|
394
|
|
|
395
|
</Note> |
|
396
|
|
|
397
|
Medusa's CLI tool can generate the migrations for you. To generate a migration for the Loyalty Module, run the following command in the `apps/backend` directory: |
|
398
|
|
|
399
|
```bash npx2yarn |
|
400
|
npx medusa db:generate loyalty |
|
401
|
``` |
|
402
|
|
|
403
|
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/loyalty` that holds the generated migration. |
|
404
|
|
|
405
|
Then, to reflect these migrations on the database, run the following command: |
|
406
|
|
|
407
|
```bash npx2yarn |
|
408
|
npx medusa db:migrate |
|
409
|
``` |
|
410
|
|
|
411
|
The table for the `LoyaltyPoint` data model is now created in the database. |
|
412
|
|
|
413
|
--- |
|
414
|
|
|
415
|
## Step 3: Change Loyalty Points Flow |
|
416
|
|
|
417
|
Now that you have a module that stores and manages loyalty points in the database, you'll start building flows around it that allow customers to earn and redeem points. |
|
418
|
|
|
419
|
The first flow you'll build will either add points to a customer's loyalty points or deduct them based on a purchased order. If the customer hasn't redeemed points, the points are added to their loyalty points. Otherwise, the points are deducted from their loyalty points. |
|
420
|
|
|
421
|
To build custom commerce features in Medusa, you create a [workflow](!docs!/learn/fundamentals/workflows). A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it's a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in an endpoint. |
|
422
|
|
|
423
|
In this section, you'll build the workflow that adds or deducts loyalty points for an order's customer. Later, you'll execute this workflow when an order is placed. |
|
424
|
|
|
425
|
<Note> |
|
426
|
|
|
427
|
Learn more about workflows in the [Workflows documentation](!docs!/learn/fundamentals/workflows). |
|
428
|
|
|
429
|
</Note> |
|
430
|
|
|
431
|
The workflow will have the following steps: |
|
432
|
|
|
433
|
<WorkflowDiagram |
|
434
|
workflow={{ |
|
435
|
name: "handleOrderPointsWorkflow", |
|
436
|
steps: [ |
|
437
|
{ |
|
438
|
type: "step", |
|
439
|
name: "useQueryGraphStep", |
|
440
|
description: "Retrieve the order's details.", |
|
441
|
link: "/references/helper-steps/useQueryGraphStep", |
|
442
|
depth: 1 |
|
443
|
}, |
|
444
|
{ |
|
445
|
type: "step", |
|
446
|
name: "validateCustomerExistsStep", |
|
447
|
description: "Validate that the customer is registered.", |
|
448
|
depth: 1, |
|
449
|
}, |
|
450
|
{ |
|
451
|
type: "step", |
|
452
|
name: "getCartLoyaltyPromoStep", |
|
453
|
description: "Retrieve the cart's loyalty promotion.", |
|
454
|
depth: 1, |
|
455
|
}, |
|
456
|
{ |
|
457
|
type: "when", |
|
458
|
condition: "Order's cart has a loyalty promotion.", |
|
459
|
steps: [ |
|
460
|
{ |
|
461
|
type: "step", |
|
462
|
name: "deductPurchasePointsStep", |
|
463
|
description: "Deduct points from the customer's loyalty points.", |
|
464
|
depth: 2, |
|
465
|
}, |
|
466
|
{ |
|
467
|
type: "step", |
|
468
|
name: "updatePromotionsStep", |
|
469
|
description: "Deactivate the cart's loyalty promotion.", |
|
470
|
link: "/references/medusa-workflows/steps/updatePromotionsStep", |
|
471
|
depth: 2, |
|
472
|
} |
|
473
|
], |
|
474
|
depth: 1 |
|
475
|
}, |
|
476
|
{ |
|
477
|
type: "when", |
|
478
|
condition: "Order's cart doesn't have a loyalty promotion.", |
|
479
|
steps: [ |
|
480
|
{ |
|
481
|
type: "step", |
|
482
|
name: "addPurchaseAsPointsStep", |
|
483
|
description: "Add points to the customer's loyalty points.", |
|
484
|
depth: 2, |
|
485
|
}, |
|
486
|
], |
|
487
|
depth: 1 |
|
488
|
} |
|
489
|
] |
|
490
|
}} |
|
491
|
/> |
|
492
|
|
|
493
|
Medusa provides the `useQueryGraphStep` and `updatePromotionsStep` in its `@medusajs/medusa/core-flows` package. So, you'll only implement the other steps. |
|
494
|
|
|
495
|
### validateCustomerExistsStep |
|
496
|
|
|
497
|
In the workflow, you first need to validate that the customer is registered. Only registered customers can earn and redeem loyalty points. |
|
498
|
|
|
499
|
To do this, create the file `src/workflows/steps/validate-customer-exists.ts` with the following content: |
|
500
|
|
|
501
|
```ts title="src/workflows/steps/validate-customer-exists.ts" |
|
502
|
import { CustomerDTO } from "@medusajs/framework/types" |
|
503
|
import { createStep } from "@medusajs/framework/workflows-sdk" |
|
504
|
import { MedusaError } from "@medusajs/framework/utils" |
|
505
|
|
|
506
|
export type ValidateCustomerExistsStepInput = { |
|
507
|
customer: CustomerDTO | null | undefined |
|
508
|
} |
|
509
|
|
|
510
|
export const validateCustomerExistsStep = createStep( |
|
511
|
"validate-customer-exists", |
|
512
|
async ({ customer }: ValidateCustomerExistsStepInput) => { |
|
513
|
if (!customer) { |
|
514
|
throw new MedusaError( |
|
515
|
MedusaError.Types.INVALID_DATA, |
|
516
|
"Customer not found" |
|
517
|
) |
|
518
|
} |
|
519
|
|
|
520
|
if (!customer.has_account) { |
|
521
|
throw new MedusaError( |
|
522
|
MedusaError.Types.INVALID_DATA, |
|
523
|
"Customer must have an account to earn or manage points" |
|
524
|
) |
|
525
|
} |
|
526
|
} |
|
527
|
) |
|
528
|
``` |
|
529
|
|
|
530
|
You create a step with `createStep` from the Workflows SDK. It accepts two parameters: |
|
531
|
|
|
532
|
1. The step's unique name, which is `validate-customer-exists`. |
|
533
|
2. An async function that receives two parameters: |
|
534
|
- The step's input, which is in this case an object with the customer's details. |
|
535
|
- 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. |
|
536
|
|
|
537
|
In the step function, you validate that the customer is defined and that it's registered based on its `has_account` property. Otherwise, you throw an error. |
|
538
|
|
|
539
|
### getCartLoyaltyPromoStep |
|
540
|
|
|
541
|
Next, you'll need to retrieve the loyalty promotion applied on the cart, if there's any. This is useful to determine whether the customer has redeemed points. |
|
542
|
|
|
543
|
Before you create a step, you'll create a utility function that the step uses to retrieve the loyalty promotion of a cart. You'll create it as a separate utility function to use it later in other customizations. |
|
544
|
|
|
545
|
Create the file `src/utils/promo.ts` with the following content: |
|
546
|
|
|
547
|
```ts title="src/utils/promo.ts" |
|
548
|
import { PromotionDTO, CustomerDTO, CartDTO } from "@medusajs/framework/types" |
|
549
|
|
|
550
|
export type CartData = CartDTO & { |
|
551
|
promotions?: PromotionDTO[] |
|
552
|
customer?: CustomerDTO |
|
553
|
metadata: { |
|
554
|
loyalty_promo_id?: string |
|
555
|
} |
|
556
|
} |
|
557
|
|
|
558
|
export function getCartLoyaltyPromotion( |
|
559
|
cart: CartData |
|
560
|
): PromotionDTO | undefined { |
|
561
|
if (!cart?.metadata?.loyalty_promo_id) { |
|
562
|
return |
|
563
|
} |
|
564
|
|
|
565
|
return cart.promotions?.find( |
|
566
|
(promotion) => promotion.id === cart.metadata.loyalty_promo_id |
|
567
|
) |
|
568
|
} |
|
569
|
``` |
|
570
|
|
|
571
|
You create a `getCartLoyaltyPromotion` function that accepts the cart's details as an input and returns the loyalty promotion if it exists. You retrieve the loyalty promotion if its ID is stored in the cart's `metadata.loyalty_promo_id` property. |
|
572
|
|
|
573
|
You can now create the step that uses this utility to retrieve a carts loyalty points promotion. To create the step, create the file `src/workflows/steps/get-cart-loyalty-promo.ts` with the following content: |
|
574
|
|
|
575
|
```ts title="src/workflows/steps/get-cart-loyalty-promo.ts" |
|
576
|
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk" |
|
577
|
import { CartData, getCartLoyaltyPromotion } from "../../utils/promo" |
|
578
|
import { MedusaError } from "@medusajs/framework/utils" |
|
579
|
|
|
580
|
type GetCartLoyaltyPromoStepInput = { |
|
581
|
cart: CartData, |
|
582
|
throwErrorOn?: "found" | "not-found" |
|
583
|
} |
|
584
|
|
|
585
|
export const getCartLoyaltyPromoStep = createStep( |
|
586
|
"get-cart-loyalty-promo", |
|
587
|
async ({ cart, throwErrorOn }: GetCartLoyaltyPromoStepInput) => { |
|
588
|
const loyaltyPromo = getCartLoyaltyPromotion(cart) |
|
589
|
|
|
590
|
if (throwErrorOn === "found" && loyaltyPromo) { |
|
591
|
throw new MedusaError( |
|
592
|
MedusaError.Types.INVALID_DATA, |
|
593
|
"Loyalty promotion already applied to cart" |
|
594
|
) |
|
595
|
} else if (throwErrorOn === "not-found" && !loyaltyPromo) { |
|
596
|
throw new MedusaError( |
|
597
|
MedusaError.Types.INVALID_DATA, |
|
598
|
"No loyalty promotion found on cart" |
|
599
|
) |
|
600
|
} |
|
601
|
|
|
602
|
return new StepResponse(loyaltyPromo) |
|
603
|
} |
|
604
|
) |
|
605
|
``` |
|
606
|
|
|
607
|
You create a step that accepts an object having the following properties: |
|
608
|
|
|
609
|
- `cart`: The cart's details. |
|
610
|
- `throwErrorOn`: An optional property that indicates whether to throw an error if the loyalty promotion is found or not found. |
|
611
|
|
|
612
|
The `throwErrorOn` property is useful to make the step reusable in different scenarios, allowing you to use it in later workflows. |
|
613
|
|
|
614
|
In the step, you call the `getCartLoyaltyPromotion` utility to retrieve the loyalty promotion. If the `throwErrorOn` property is set to `found` and the loyalty promotion is found, you throw an error. |
|
615
|
|
|
616
|
Otherwise, if the `throwErrorOn` property is set to `not-found` and the loyalty promotion is not found, you throw an error. |
|
617
|
|
|
618
|
To return data from a step, you return an instance of `StepResponse` from the Workflows SDK. It accepts as a parameter the data to return, which is the loyalty promotion in this case. |
|
619
|
|
|
620
|
### deductPurchasePointsStep |
|
621
|
|
|
622
|
If the order's cart has a loyalty promotion, you need to deduct points from the customer's loyalty points. To do this, create the file `src/workflows/steps/deduct-purchase-points.ts` with the following content: |
|
623
|
|
|
624
|
<Note> |
|
625
|
|
|
626
|
If you get a type error on resolving the Loyalty Module, run the Medusa application once with the `npm run dev` or `yarn dev` command to generate the necessary type definitions, as explained in the [Automatically Generated Types guide](!docs!/learn/fundamentals/generated-types). |
|
627
|
|
|
628
|
</Note> |
|
629
|
|
|
630
|
export const deductStepHighlights = [ |
|
631
|
["18", "loyaltyModuleService", "Resolve the Loyalty Module's service."], |
|
632
|
["22", "calculatePointsFromAmount", "Calculate the points to deduct from the promotion's amount."], |
|
633
|
["26", "deductPoints", "Deduct the points from the customer's loyalty points."], |
|
634
|
["31", "result", "Return the loyalty points result"], |
|
635
|
["36", "", "Add a compensation function to undo the step's actions if an error occurs."], |
|
636
|
["46", "addPoints", "Restore points in case of failure."], |
|
637
|
] |
|
638
|
|
|
639
|
```ts title="src/workflows/steps/deduct-purchase-points.ts" highlights={deductStepHighlights} collapsibleLines="1-7" expandButtonLabel="Show Imports" |
|
640
|
import { |
|
641
|
createStep, |
|
642
|
StepResponse, |
|
643
|
} from "@medusajs/framework/workflows-sdk" |
|
644
|
import { LOYALTY_MODULE } from "../../modules/loyalty" |
|
645
|
import LoyaltyModuleService from "../../modules/loyalty/service" |
|
646
|
|
|
647
|
type DeductPurchasePointsInput = { |
|
648
|
customer_id: string |
|
649
|
amount: number |
|
650
|
} |
|
651
|
|
|
652
|
export const deductPurchasePointsStep = createStep( |
|
653
|
"deduct-purchase-points", |
|
654
|
async ({ |
|
655
|
customer_id, amount, |
|
656
|
}: DeductPurchasePointsInput, { container }) => { |
|
657
|
const loyaltyModuleService: LoyaltyModuleService = container.resolve( |
|
658
|
LOYALTY_MODULE |
|
659
|
) |
|
660
|
|
|
661
|
const pointsToDeduct = await loyaltyModuleService.calculatePointsFromAmount( |
|
662
|
amount |
|
663
|
) |
|
664
|
|
|
665
|
const result = await loyaltyModuleService.deductPoints( |
|
666
|
customer_id, |
|
667
|
pointsToDeduct |
|
668
|
) |
|
669
|
|
|
670
|
return new StepResponse(result, { |
|
671
|
customer_id, |
|
672
|
points: pointsToDeduct, |
|
673
|
}) |
|
674
|
}, |
|
675
|
async (data, { container }) => { |
|
676
|
if (!data) { |
|
677
|
return |
|
678
|
} |
|
679
|
|
|
680
|
const loyaltyModuleService: LoyaltyModuleService = container.resolve( |
|
681
|
LOYALTY_MODULE |
|
682
|
) |
|
683
|
|
|
684
|
// Restore points in case of failure |
|
685
|
await loyaltyModuleService.addPoints( |
|
686
|
data.customer_id, |
|
687
|
data.points |
|
688
|
) |
|
689
|
} |
|
690
|
) |
|
691
|
``` |
|
692
|
|
|
693
|
You create a step that accepts an object having the following properties: |
|
694
|
|
|
695
|
- `customer_id`: The ID of the customer to deduct points from. |
|
696
|
- `amount`: The promotion's amount, which will be used to calculate the points to deduct. |
|
697
|
|
|
698
|
In the step, you resolve the Loyalty Module's service from the Medusa container. Then, you use the `calculatePointsFromAmount` method to calculate the points to deduct from the promotion's amount. |
|
699
|
|
|
700
|
After that, you call the `deductPoints` method to deduct the points from the customer's loyalty points. |
|
701
|
|
|
702
|
Finally, you return a `StepResponse` with the result of the `deductPoints`. |
|
703
|
|
|
704
|
#### Compensation Function |
|
705
|
|
|
706
|
This step has a compensation function, which is passed as a third parameter to the `createStep` function. |
|
707
|
|
|
708
|
The compensation function undoes the actions performed in a step. Then, if an error occurs during the workflow's execution, the compensation functions of executed steps are called to roll back the changes. This mechanism ensures data consistency in your application, especially as you integrate external systems. |
|
709
|
|
|
710
|
The compensation function accepts two parameters: |
|
711
|
|
|
712
|
1. Data passed from the step function to the compensation function. The data is passed as a second parameter of the returned `StepResponse` instance. |
|
713
|
2. An object that has properties including the [Medusa container](!docs!/learn/fundamentals/medusa-container). |
|
714
|
|
|
715
|
In the compensation function, you resolve the Loyalty Module's service from the Medusa container. Then, you call the `addPoints` method to restore the points deducted from the customer's loyalty points if an error occurs. |
|
716
|
|
|
717
|
### addPurchaseAsPointsStep |
|
718
|
|
|
719
|
The last step you'll create adds points to the customer's loyalty points. You'll use this step if the customer didn't redeem points during checkout. |
|
720
|
|
|
721
|
To create the step, create the file `src/workflows/steps/add-purchase-as-points.ts` with the following content: |
|
722
|
|
|
723
|
export const addPointsHighlights = [ |
|
724
|
["20", "calculatePointsFromAmount", "Calculate the points to add from the order's amount."], |
|
725
|
["24", "addPoints", "Add the points to the customer's loyalty points."], |
|
726
|
["29", "result", "Return the loyalty points result"], |
|
727
|
["34", "", "Add a compensation function to undo the step's actions if an error occurs."], |
|
728
|
["43", "deductPoints", "Deduct points in case of failure."], |
|
729
|
] |
|
730
|
|
|
731
|
```ts title="src/workflows/steps/add-purchase-as-points.ts" highlights={addPointsHighlights} collapsibleLines="1-7" expandButtonLabel="Show Imports" |
|
732
|
import { |
|
733
|
createStep, |
|
734
|
StepResponse, |
|
735
|
} from "@medusajs/framework/workflows-sdk" |
|
736
|
import { LOYALTY_MODULE } from "../../modules/loyalty" |
|
737
|
import LoyaltyModuleService from "../../modules/loyalty/service" |
|
738
|
|
|
739
|
type StepInput = { |
|
740
|
customer_id: string |
|
741
|
amount: number |
|
742
|
} |
|
743
|
|
|
744
|
export const addPurchaseAsPointsStep = createStep( |
|
745
|
"add-purchase-as-points", |
|
746
|
async (input: StepInput, { container }) => { |
|
747
|
const loyaltyModuleService: LoyaltyModuleService = container.resolve( |
|
748
|
LOYALTY_MODULE |
|
749
|
) |
|
750
|
|
|
751
|
const pointsToAdd = await loyaltyModuleService.calculatePointsFromAmount( |
|
752
|
input.amount |
|
753
|
) |
|
754
|
|
|
755
|
const result = await loyaltyModuleService.addPoints( |
|
756
|
input.customer_id, |
|
757
|
pointsToAdd |
|
758
|
) |
|
759
|
|
|
760
|
return new StepResponse(result, { |
|
761
|
customer_id: input.customer_id, |
|
762
|
points: pointsToAdd, |
|
763
|
}) |
|
764
|
}, |
|
765
|
async (data, { container }) => { |
|
766
|
if (!data) { |
|
767
|
return |
|
768
|
} |
|
769
|
|
|
770
|
const loyaltyModuleService: LoyaltyModuleService = container.resolve( |
|
771
|
LOYALTY_MODULE |
|
772
|
) |
|
773
|
|
|
774
|
await loyaltyModuleService.deductPoints( |
|
775
|
data.customer_id, |
|
776
|
data.points |
|
777
|
) |
|
778
|
} |
|
779
|
) |
|
780
|
``` |
|
781
|
|
|
782
|
You create a step that accepts an object having the following properties: |
|
783
|
|
|
784
|
- `customer_id`: The ID of the customer to add points to. |
|
785
|
- `amount`: The order's amount, which will be used to calculate the points to add. |
|
786
|
|
|
787
|
In the step, you resolve the Loyalty Module's service from the Medusa container. Then, you use the `calculatePointsFromAmount` method to calculate the points to add from the order's amount. |
|
788
|
|
|
789
|
After that, you call the `addPoints` method to add the points to the customer's loyalty points. |
|
790
|
|
|
791
|
Finally, you return a `StepResponse` with the result of the `addPoints`. |
|
792
|
|
|
793
|
You also pass to the compensation function the customer's ID and the points added. In the compensation function, you deduct the points if an error occurs. |
|
794
|
|
|
795
|
### Add Utility Functions |
|
796
|
|
|
797
|
Before you create the workflow, you need a utility function that checks whether an order's cart has a loyalty promotion. This is useful to determine whether the customer redeemed points during checkout, allowing you to decide which steps to execute. |
|
798
|
|
|
799
|
To add the utility function, add the following to `src/utils/promo.ts`: |
|
800
|
|
|
801
|
```ts title="src/utils/promo.ts" |
|
802
|
import { OrderDTO } from "@medusajs/framework/types" |
|
803
|
|
|
804
|
export type OrderData = OrderDTO & { |
|
805
|
promotion?: PromotionDTO[] |
|
806
|
customer?: CustomerDTO |
|
807
|
cart?: CartData |
|
808
|
} |
|
809
|
|
|
810
|
export const CUSTOMER_ID_PROMOTION_RULE_ATTRIBUTE = "customer_id" |
|
811
|
|
|
812
|
export function orderHasLoyaltyPromotion(order: OrderData): boolean { |
|
813
|
const loyaltyPromotion = getCartLoyaltyPromotion( |
|
814
|
order.cart as unknown as CartData |
|
815
|
) |
|
816
|
|
|
817
|
return loyaltyPromotion?.rules?.some((rule) => { |
|
818
|
return rule?.attribute === CUSTOMER_ID_PROMOTION_RULE_ATTRIBUTE && ( |
|
819
|
rule?.values?.some((value) => value.value === order.customer?.id) || false |
|
820
|
) |
|
821
|
}) || false |
|
822
|
} |
|
823
|
``` |
|
824
|
|
|
825
|
You first define an `OrderData` type that extends the `OrderDTO` type. This type has the order's details, including the cart, customer, and promotions details. |
|
826
|
|
|
827
|
Then, you define a constant `CUSTOMER_ID_PROMOTION_RULE_ATTRIBUTE` that represents the attribute used in the promotion rule to check whether the customer ID is valid. |
|
828
|
|
|
829
|
Finally, you create the `orderHasLoyaltyPromotion` function that accepts an order's details and checks whether it has a loyalty promotion. It returns `true` if: |
|
830
|
|
|
831
|
- The order's cart has a loyalty promotion. You use the `getCartLoyaltyPromotion` utility to try to retrieve the loyalty promotion. |
|
832
|
- The promotion's rules include the `customer_id` attribute and its value matches the order's customer ID. |
|
833
|
- When you create the promotion for the cart later, you'll see how to set this rule. |
|
834
|
|
|
835
|
You'll use this utility in the workflow next. |
|
836
|
|
|
837
|
### Create the Workflow |
|
838
|
|
|
839
|
Now that you have all the steps, you can create the workflow that uses them. |
|
840
|
|
|
841
|
To create the workflow, create the file `src/workflows/handle-order-points.ts` with the following content: |
|
842
|
|
|
843
|
export const handleOrderPointsHighlights = [ |
|
844
|
["17", "useQueryGraphStep", "Retrieve the order's details."], |
|
845
|
["37", "validateCustomerExistsStep", "Validate that the customer is registered."], |
|
846
|
["41", "getCartLoyaltyPromoStep", "Retrieve the cart's loyalty promotion."], |
|
847
|
["45", "when", "Check whether the order's cart has a loyalty promotion."], |
|
848
|
["50", "deductPurchasePointsStep", "Deduct points from the customer's loyalty points."], |
|
849
|
["55", "updatePromotionsStep", "Deactivate the cart's loyalty promotion."], |
|
850
|
["64", "when", "Check whether the order's cart doesn't have a loyalty promotion."], |
|
851
|
["69", "addPurchaseAsPointsStep", "Add points to the customer's loyalty points."], |
|
852
|
] |
|
853
|
|
|
854
|
```ts title="src/workflows/handle-order-points.ts" highlights={handleOrderPointsHighlights} collapsibleLines="1-9" expandButtonLabel="Show Imports" |
|
855
|
import { createWorkflow, when } from "@medusajs/framework/workflows-sdk" |
|
856
|
import { updatePromotionsStep, useQueryGraphStep } from "@medusajs/medusa/core-flows" |
|
857
|
import { validateCustomerExistsStep, ValidateCustomerExistsStepInput } from "./steps/validate-customer-exists" |
|
858
|
import { deductPurchasePointsStep } from "./steps/deduct-purchase-points" |
|
859
|
import { addPurchaseAsPointsStep } from "./steps/add-purchase-as-points" |
|
860
|
import { OrderData, CartData } from "../utils/promo" |
|
861
|
import { orderHasLoyaltyPromotion } from "../utils/promo" |
|
862
|
import { getCartLoyaltyPromoStep } from "./steps/get-cart-loyalty-promo" |
|
863
|
|
|
864
|
type WorkflowInput = { |
|
865
|
order_id: string |
|
866
|
} |
|
867
|
|
|
868
|
export const handleOrderPointsWorkflow = createWorkflow( |
|
869
|
"handle-order-points", |
|
870
|
({ order_id }: WorkflowInput) => { |
|
871
|
const { data: orders } = useQueryGraphStep({ |
|
872
|
entity: "order", |
|
873
|
fields: [ |
|
874
|
"id", |
|
875
|
"customer.*", |
|
876
|
"total", |
|
877
|
"cart.*", |
|
878
|
"cart.promotions.*", |
|
879
|
"cart.promotions.rules.*", |
|
880
|
"cart.promotions.rules.values.*", |
|
881
|
"cart.promotions.application_method.*", |
|
882
|
], |
|
883
|
filters: { |
|
884
|
id: order_id, |
|
885
|
}, |
|
886
|
options: { |
|
887
|
throwIfKeyNotFound: true, |
|
888
|
}, |
|
889
|
}) |
|
890
|
|
|
891
|
validateCustomerExistsStep({ |
|
892
|
customer: orders[0].customer, |
|
893
|
} as ValidateCustomerExistsStepInput) |
|
894
|
|
|
895
|
const loyaltyPointsPromotion = getCartLoyaltyPromoStep({ |
|
896
|
cart: orders[0].cart as unknown as CartData, |
|
897
|
}) |
|
898
|
|
|
899
|
when(orders, (orders) => |
|
900
|
orderHasLoyaltyPromotion(orders[0] as unknown as OrderData) && |
|
901
|
loyaltyPointsPromotion !== undefined |
|
902
|
) |
|
903
|
.then(() => { |
|
904
|
deductPurchasePointsStep({ |
|
905
|
customer_id: orders[0].customer!.id, |
|
906
|
amount: loyaltyPointsPromotion.application_method!.value as number, |
|
907
|
}) |
|
908
|
|
|
909
|
updatePromotionsStep([ |
|
910
|
{ |
|
911
|
id: loyaltyPointsPromotion.id, |
|
912
|
status: "inactive", |
|
913
|
}, |
|
914
|
]) |
|
915
|
}) |
|
916
|
|
|
917
|
|
|
918
|
when( |
|
919
|
orders, |
|
920
|
(order) => !orderHasLoyaltyPromotion(order[0] as unknown as OrderData) |
|
921
|
) |
|
922
|
.then(() => { |
|
923
|
addPurchaseAsPointsStep({ |
|
924
|
customer_id: orders[0].customer!.id, |
|
925
|
amount: orders[0].total, |
|
926
|
}) |
|
927
|
}) |
|
928
|
} |
|
929
|
) |
|
930
|
``` |
|
931
|
|
|
932
|
You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter. |
|
933
|
|
|
934
|
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 order's ID. |
|
935
|
|
|
936
|
In the workflow's constructor function, you: |
|
937
|
|
|
938
|
- Use `useQueryGraphStep` to retrieve the order's details. You pass the order's ID as a filter to retrieve the order. |
|
939
|
- This step uses [Query](!docs!/learn/fundamentals/query), which is a tool that retrieves data across modules. |
|
940
|
- Validate that the customer is registered using the `validateCustomerExistsStep`. |
|
941
|
- Retrieve the cart's loyalty promotion using the `getCartLoyaltyPromoStep`. |
|
942
|
- Use `when` to check whether the order's cart has a loyalty promotion. |
|
943
|
- Since you can't perform data manipulation in a workflow's constructor function, `when` allows you to perform steps if a condition is satisfied. |
|
944
|
- You pass as a first parameter the object to perform the condition on, which is the order in this case. In the second parameter, you pass a function that returns a boolean value, indicating whether the condition is satisfied. |
|
945
|
- To specify the steps to perform if a condition is satisfied, you chain a `then` method to the `when` method. You can perform any step within the `then` method. |
|
946
|
- In this case, if the order's cart has a loyalty promotion, you call the `deductPurchasePointsStep` to deduct points from the customer's loyalty points. You also call the `updatePromotionsStep` to deactivate the cart's loyalty promotion. |
|
947
|
- You use another `when` to check whether the order's cart doesn't have a loyalty promotion. |
|
948
|
- If the condition is satisfied, you call the `addPurchaseAsPointsStep` to add points to the customer's loyalty points. |
|
949
|
|
|
950
|
You'll use this workflow next when an order is placed. |
|
951
|
|
|
952
|
<Note title="Tip"> |
|
953
|
|
|
954
|
To learn more about the constraints on a workflow's constructor function, refer to the [Workflow Constraints](!docs!/learn/fundamentals/workflows/constructor-constraints) documentation. Refer to the [When-Then](!docs!/learn/fundamentals/workflows/conditions) documentation to learn more about the `when` method and how to use it in a workflow. |
|
955
|
|
|
956
|
</Note> |
|
957
|
|
|
958
|
--- |
|
959
|
|
|
960
|
## Step 4: Handle Order Placed Event |
|
961
|
|
|
962
|
Now that you have the workflow that handles adding or deducting loyalty points for an order, you need to execute it when an order is placed. |
|
963
|
|
|
964
|
Medusa has an event system that allows you to listen to events emitted by the Medusa server using a [subscriber](!docs!//learn/fundamentals/events-and-subscribers). A subscriber is an asynchronous function that's executed when its associated event is emitted. In a subscriber, you can execute a workflow that performs actions in result of the event. |
|
965
|
|
|
966
|
In this step, you'll create a subscriber that listens to the `order.placed` event and executes the `handleOrderPointsWorkflow` workflow. |
|
967
|
|
|
968
|
<Note> |
|
969
|
|
|
970
|
Refer to the [Events and Subscribers](!docs!/learn/fundamentals/events-and-subscribers) documentation to learn more. |
|
971
|
|
|
972
|
</Note> |
|
973
|
|
|
974
|
Subscribers are created in a TypeScript or JavaScript file under the `src/subscribers` directory. So, to create a subscriber, create the file `src/subscribers/order-placed.ts` with the following content: |
|
975
|
|
|
976
|
```ts title="src/subscribers/order-placed.ts" |
|
977
|
import type { |
|
978
|
SubscriberArgs, |
|
979
|
SubscriberConfig, |
|
980
|
} from "@medusajs/framework" |
|
981
|
import { handleOrderPointsWorkflow } from "../workflows/handle-order-points" |
|
982
|
|
|
983
|
export default async function orderPlacedHandler({ |
|
984
|
event: { data }, |
|
985
|
container, |
|
986
|
}: SubscriberArgs<{ id: string }>) { |
|
987
|
await handleOrderPointsWorkflow(container).run({ |
|
988
|
input: { |
|
989
|
order_id: data.id, |
|
990
|
}, |
|
991
|
}) |
|
992
|
} |
|
993
|
|
|
994
|
export const config: SubscriberConfig = { |
|
995
|
event: "order.placed", |
|
996
|
} |
|
997
|
``` |
|
998
|
|
|
999
|
The subscriber file must export: |
|
1000
|
|
|
1001
|
- An asynchronous subscriber function that's executed whenever the associated event, which is `order.placed` is triggered. |
|
1002
|
- A configuration object with an event property whose value is the event the subscriber is listening to. You can also pass an array of event names to listen to multiple events in the same subscriber. |
|
1003
|
|
|
1004
|
The subscriber function accepts an object with the following properties: |
|
1005
|
|
|
1006
|
- `event`: An object with the event's data payload. For example, the `order.placed` event has the order's ID in its data payload. |
|
1007
|
- `container`: The Medusa container, which you can use to resolve services and tools. |
|
1008
|
|
|
1009
|
In the subscriber function, you execute the `handleOrderPointsWorkflow` by invoking it, passing it the Medusa container, then using its `run` method, passing it the workflow's input. |
|
1010
|
|
|
1011
|
Whenever an order is placed now, the subscriber will be executed, which in turn will execute the workflow that handles the loyalty points flow. |
|
1012
|
|
|
1013
|
### Test it Out |
|
1014
|
|
|
1015
|
To test out the loyalty points flow, you'll use the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) that you installed in the first step. The storefront is available in the `apps/storefront` directory of your project. |
|
1016
|
|
|
1017
|
So, run the following command in the `apps/backend` directory to start the Medusa server: |
|
1018
|
|
|
1019
|
```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green" |
|
1020
|
npm run dev |
|
1021
|
``` |
|
1022
|
|
|
1023
|
Then, run the following command in the Next.js Starter Storefront's directory to start the Next.js server: |
|
1024
|
|
|
1025
|
```bash npm2yarn badgeLabel="Storefront" badgeColor="blue" |
|
1026
|
npm run dev |
|
1027
|
``` |
|
1028
|
|
|
1029
|
The Next.js Starter Storefront will be running on `http://localhost:8000`, and the Medusa server will be running on `http://localhost:9000`. |
|
1030
|
|
|
1031
|
Open the Next.js Starter Storefront in your browser and create a new account by going to Account at the top right. |
|
1032
|
|
|
1033
|
Once you're logged in, add an item to the cart and go through the checkout flow. |
|
1034
|
|
|
1035
|
After you place the order, you'll see the following message in your Medusa application's terminal: |
|
1036
|
|
|
1037
|
```bash |
|
1038
|
info: Processing order.placed which has 1 subscribers |
|
1039
|
``` |
|
1040
|
|
|
1041
|
This message indicates that the `order.placed` event was emitted, and that your subscriber was executed. |
|
1042
|
|
|
1043
|
Since you didn't redeem any points during checkout, loyalty points will be added to your account. You'll implement an API route that allows you to retrieve the loyalty points in the next step. |
|
1044
|
|
|
1045
|
--- |
|
1046
|
|
|
1047
|
## Step 5: Retrieve Loyalty Points API Route |
|
1048
|
|
|
1049
|
Next, you want to allow customers to view their loyalty points. You can show them on their profile page, or during checkout. |
|
1050
|
|
|
1051
|
To expose a feature to clients, you create an [API route](!docs!/learn/fundamentals/api-routes). An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts. |
|
1052
|
|
|
1053
|
You'll create an API route at the path `/store/customers/me/loyalty-points` that returns the loyalty points of the authenticated customer. |
|
1054
|
|
|
1055
|
<Note> |
|
1056
|
|
|
1057
|
Learn more about API routes in [this documentation](!docs!/learn/fundamentals/api-routes). |
|
1058
|
|
|
1059
|
</Note> |
|
1060
|
|
|
1061
|
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`. |
|
1062
|
|
|
1063
|
So, to create an API route at the path `/store/customers/me/loyalty-points`, create the file `src/api/store/customers/me/loyalty-points/route.ts` with the following content: |
|
1064
|
|
|
1065
|
```ts title="src/api/store/customers/me/loyalty-points/route.ts" |
|
1066
|
|
|
1067
|
import { |
|
1068
|
AuthenticatedMedusaRequest, |
|
1069
|
MedusaResponse, |
|
1070
|
} from "@medusajs/framework/http" |
|
1071
|
import { LOYALTY_MODULE } from "../../../../../modules/loyalty" |
|
1072
|
import LoyaltyModuleService from "../../../../../modules/loyalty/service" |
|
1073
|
|
|
1074
|
export async function GET( |
|
1075
|
req: AuthenticatedMedusaRequest, |
|
1076
|
res: MedusaResponse |
|
1077
|
) { |
|
1078
|
const loyaltyModuleService: LoyaltyModuleService = req.scope.resolve( |
|
1079
|
LOYALTY_MODULE |
|
1080
|
) |
|
1081
|
|
|
1082
|
const points = await loyaltyModuleService.getPoints( |
|
1083
|
req.auth_context.actor_id |
|
1084
|
) |
|
1085
|
|
|
1086
|
res.json({ |
|
1087
|
points, |
|
1088
|
}) |
|
1089
|
} |
|
1090
|
``` |
|
1091
|
|
|
1092
|
Since you export a `GET` route handler function, you're exposing a `GET` endpoint at `/store/customers/me/loyalty-points`. The route handler function accepts two parameters: |
|
1093
|
|
|
1094
|
1. A request object with details and context on the request, such as body parameters or authenticated customer details. |
|
1095
|
2. A response object to manipulate and send the response. |
|
1096
|
|
|
1097
|
In the route handler, you resolve the Loyalty Module's service from the Medusa container (which is available at `req.scope`). |
|
1098
|
|
|
1099
|
Then, you call the service's `getPoints` method to retrieve the authenticated customer's loyalty points. Note that routes starting with `/store/customers/me` are only accessible by authenticated customers. You can access the authenticated customer ID from the request's context, which is available at `req.auth_context.actor_id`. |
|
1100
|
|
|
1101
|
Finally, you return the loyalty points in the response. |
|
1102
|
|
|
1103
|
You'll test out this route as you customize the Next.js Starter Storefront next. |
|
1104
|
|
|
1105
|
--- |
|
1106
|
|
|
1107
|
## Step 6: Show Loyalty Points During Checkout |
|
1108
|
|
|
1109
|
Now that you have the API route to retrieve the loyalty points, you can show them during checkout. |
|
1110
|
|
|
1111
|
In this step, you'll customize the Next.js Starter Storefront to show the loyalty points in the checkout page. |
|
1112
|
|
|
1113
|
First, you'll add a server action function that retrieves the loyalty points from the route you created earlier. In `src/lib/data/customer.ts`, add the following function: |
|
1114
|
|
|
1115
|
```ts title="src/lib/data/customer.ts" badgeLabel="Storefront" badgeColor="blue" |
|
1116
|
export const getLoyaltyPoints = async () => { |
|
1117
|
const headers = { |
|
1118
|
...(await getAuthHeaders()), |
|
1119
|
} |
|
1120
|
|
|
1121
|
return sdk.client.fetch<{ points: number }>( |
|
1122
|
`/store/customers/me/loyalty-points`, |
|
1123
|
{ |
|
1124
|
method: "GET", |
|
1125
|
headers, |
|
1126
|
} |
|
1127
|
) |
|
1128
|
.then(({ points }) => points) |
|
1129
|
.catch(() => null) |
|
1130
|
} |
|
1131
|
``` |
|
1132
|
|
|
1133
|
You add a `getLoyaltyPoints` function that retrieves the authenticated customer's loyalty points from the API route you created earlier. You pass the authentication headers using the `getAuthHeaders` function, which is a utility function defined in the Next.js Starter Storefront. |
|
1134
|
|
|
1135
|
If the customer isn't authenticated, the request will fail. So, you catch the error and return `null` in that case. |
|
1136
|
|
|
1137
|
Next, you'll create a component that shows the loyalty points in the checkout page. Create the file `src/modules/checkout/components/loyalty-points/index.tsx` with the following content: |
|
1138
|
|
|
1139
|
export const loyaltyPointsHighlights = [ |
|
1140
|
["16", "isLoyaltyPointsPromoApplied", "A boolean indicating whether the cart has a loyalty promotion applied."], |
|
1141
|
["21", "loyaltyPoints", "Store the customer's loyalty points."], |
|
1142
|
["26", "getLoyaltyPoints", "Retrieve the customer's loyalty points."], |
|
1143
|
["33", "handleTogglePromotion", "Handle the click event to apply or remove the promotion."], |
|
1144
|
["48", "Link", "Show a link to sign up if the customer isn't authenticated."], |
|
1145
|
["54", "Button", "Show a button to apply or remove the promotion if the customer is authenticated."], |
|
1146
|
] |
|
1147
|
|
|
1148
|
```tsx title="src/modules/checkout/components/loyalty-points/index.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={loyaltyPointsHighlights} |
|
1149
|
"use client" |
|
1150
|
|
|
1151
|
import { HttpTypes } from "@medusajs/types" |
|
1152
|
import { useEffect, useMemo, useState } from "react" |
|
1153
|
import { getLoyaltyPoints } from "../../../../lib/data/customer" |
|
1154
|
import { Button, Heading } from "@medusajs/ui" |
|
1155
|
import Link from "next/link" |
|
1156
|
|
|
1157
|
type LoyaltyPointsProps = { |
|
1158
|
cart: HttpTypes.StoreCart & { |
|
1159
|
promotions: HttpTypes.StorePromotion[] |
|
1160
|
} |
|
1161
|
} |
|
1162
|
|
|
1163
|
const LoyaltyPoints = ({ cart }: LoyaltyPointsProps) => { |
|
1164
|
const isLoyaltyPointsPromoApplied = useMemo(() => { |
|
1165
|
return cart.promotions.find( |
|
1166
|
(promo) => promo.id === cart.metadata?.loyalty_promo_id |
|
1167
|
) !== undefined |
|
1168
|
}, [cart]) |
|
1169
|
const [loyaltyPoints, setLoyaltyPoints] = useState< |
|
1170
|
number | null |
|
1171
|
>(null) |
|
1172
|
|
|
1173
|
useEffect(() => { |
|
1174
|
getLoyaltyPoints() |
|
1175
|
.then((points) => { |
|
1176
|
console.log(points) |
|
1177
|
setLoyaltyPoints(points) |
|
1178
|
}) |
|
1179
|
}, []) |
|
1180
|
|
|
1181
|
const handleTogglePromotion = async ( |
|
1182
|
e: React.MouseEvent<HTMLButtonElement, MouseEvent> |
|
1183
|
) => { |
|
1184
|
e.preventDefault() |
|
1185
|
// TODO apply or remove loyalty promotion |
|
1186
|
} |
|
1187
|
|
|
1188
|
return ( |
|
1189
|
<> |
|
1190
|
<div className="h-px w-full border-b border-gray-200 my-4" /> |
|
1191
|
<div className="flex flex-col"> |
|
1192
|
<Heading className="txt-medium mb-2"> |
|
1193
|
Loyalty Points |
|
1194
|
</Heading> |
|
1195
|
{loyaltyPoints === null && ( |
|
1196
|
<Link href="/account" className="txt-medium text-ui-fg-interactive hover:text-ui-fg-interactive-hover"> |
|
1197
|
Sign up to get and use loyalty points |
|
1198
|
</Link> |
|
1199
|
)} |
|
1200
|
{loyaltyPoints !== null && ( |
|
1201
|
<div className="flex items-center justify-between my-6 gap-1"> |
|
1202
|
<Button |
|
1203
|
variant="secondary" |
|
1204
|
className="w-1/2" |
|
1205
|
onClick={handleTogglePromotion} |
|
1206
|
> |
|
1207
|
{isLoyaltyPointsPromoApplied ? "Remove" : "Apply"} Loyalty Points |
|
1208
|
</Button> |
|
1209
|
<span className="txt-medium text-ui-fg-subtle"> |
|
1210
|
You have {loyaltyPoints} loyalty points |
|
1211
|
</span> |
|
1212
|
</div> |
|
1213
|
)} |
|
1214
|
</div> |
|
1215
|
</> |
|
1216
|
) |
|
1217
|
} |
|
1218
|
|
|
1219
|
export default LoyaltyPoints |
|
1220
|
``` |
|
1221
|
|
|
1222
|
You create a `LoyaltyPoints` component that accepts the cart's details as a prop. In the component, you: |
|
1223
|
|
|
1224
|
- Create a `isLoyaltyPointsPromoApplied` memoized value that checks whether the cart has a loyalty promotion applied. You use the `cart.metadata.loyalty_promo_id` property to check this. |
|
1225
|
- Create a `loyaltyPoints` state to store the customer's loyalty points. |
|
1226
|
- Call the `getLoyaltyPoints` function in a `useEffect` hook to retrieve the loyalty points from the API route you created earlier. You set the `loyaltyPoints` state with the retrieved points. |
|
1227
|
- Define `handleTogglePromotion` that, when clicked, would either apply or remove the promotion. You'll implement these functionalities later. |
|
1228
|
- Render the loyalty points in the component. If the customer isn't authenticated, you show a link to the account page to sign up. Otherwise, you show the loyalty points and a button to apply or remove the promotion. |
|
1229
|
|
|
1230
|
Next, you'll show this component at the end of the checkout's summary component. So, import the component in `src/modules/checkout/templates/checkout-summary/index.tsx`: |
|
1231
|
|
|
1232
|
```tsx title="src/modules/checkout/templates/checkout-summary/index.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
1233
|
import LoyaltyPoints from "../../components/loyalty-points" |
|
1234
|
``` |
|
1235
|
|
|
1236
|
Then, in the return statement of the `CheckoutSummary` component, add the following after the `div` wrapping the `DiscountCode`: |
|
1237
|
|
|
1238
|
```tsx title="src/modules/checkout/templates/checkout-summary/index.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
1239
|
<LoyaltyPoints cart={cart} /> |
|
1240
|
``` |
|
1241
|
|
|
1242
|
This will show the loyalty points component at the end of the checkout summary. |
|
1243
|
|
|
1244
|
### Test it Out |
|
1245
|
|
|
1246
|
To test out the customizations to the checkout flow, make sure both the Medusa application and Next.js Starter Storefront are running. |
|
1247
|
|
|
1248
|
Then, as an authenticated customer, add an item to cart and proceed to checkout. You'll find a new "Loyalty Points" section at the end of the checkout summary. |
|
1249
|
|
|
1250
|
 |
|
1251
|
|
|
1252
|
If you made a purchase before, you can see your loyalty points. You'll also see the "Apply Loyalty Points" button, which doesn't yet do anything. You'll add the functionality next. |
|
1253
|
|
|
1254
|
--- |
|
1255
|
|
|
1256
|
## Step 7: Apply Loyalty Points to Cart |
|
1257
|
|
|
1258
|
The next feature you'll implement allows the customer to apply their loyalty points during checkout. To implement the feature, you need: |
|
1259
|
|
|
1260
|
- A workflow that implements the steps of the apply loyalty points flow. |
|
1261
|
- An API route that exposes the workflow's functionality to clients. You'll then send a request to this API route to apply the loyalty points on the customer's cart. |
|
1262
|
- A function in the Next.js Starter Storefront that sends the request to the API route you created earlier. |
|
1263
|
|
|
1264
|
The workflow will have the following steps: |
|
1265
|
|
|
1266
|
<WorkflowDiagram |
|
1267
|
workflow={{ |
|
1268
|
name: "applyLoyaltyOnCartWorkflow", |
|
1269
|
steps: [ |
|
1270
|
{ |
|
1271
|
type: "step", |
|
1272
|
name: "useQueryGraphStep", |
|
1273
|
description: "Retrieve the cart's details.", |
|
1274
|
link: "/references/helper-steps/useQueryGraphStep", |
|
1275
|
depth: 1 |
|
1276
|
}, |
|
1277
|
{ |
|
1278
|
type: "step", |
|
1279
|
name: "validateCustomerExistsStep", |
|
1280
|
description: "Validate that the customer is registered.", |
|
1281
|
depth: 2, |
|
1282
|
}, |
|
1283
|
{ |
|
1284
|
type: "step", |
|
1285
|
name: "getCartLoyaltyPromoStep", |
|
1286
|
description: "Retrieve the cart's loyalty promotion.", |
|
1287
|
depth: 3, |
|
1288
|
}, |
|
1289
|
{ |
|
1290
|
type: "step", |
|
1291
|
name: "acquireLockStep", |
|
1292
|
description: "Acquire a lock on the cart to prevent concurrent modifications.", |
|
1293
|
link: "/references/medusa-workflows/steps/acquireLockStep", |
|
1294
|
depth: 4, |
|
1295
|
}, |
|
1296
|
{ |
|
1297
|
type: "step", |
|
1298
|
name: "getCartLoyaltyPromoAmountStep", |
|
1299
|
description: "Get the amount to be discounted based on the loyalty points.", |
|
1300
|
depth: 5, |
|
1301
|
}, |
|
1302
|
{ |
|
1303
|
type: "step", |
|
1304
|
name: "createPromotionsStep", |
|
1305
|
description: "Create a new loyalty promotion for the cart.", |
|
1306
|
link: "/references/medusa-workflows/steps/createPromotionsStep", |
|
1307
|
depth: 6, |
|
1308
|
}, |
|
1309
|
{ |
|
1310
|
type: "workflow", |
|
1311
|
name: "updateCartPromotionsWorkflow", |
|
1312
|
description: "Update the cart's promotions with the new loyalty promotion.", |
|
1313
|
link: "/references/medusa-workflows/updateCartPromotionsWorkflow", |
|
1314
|
depth: 7, |
|
1315
|
}, |
|
1316
|
{ |
|
1317
|
type: "step", |
|
1318
|
name: "updateCartsStep", |
|
1319
|
description: "Update the cart to store the ID of the loyalty promotion in the metadata.", |
|
1320
|
link: "/references/medusa-workflows/steps/updateCartsStep", |
|
1321
|
depth: 8, |
|
1322
|
}, |
|
1323
|
{ |
|
1324
|
type: "step", |
|
1325
|
name: "useQueryGraphStep", |
|
1326
|
description: "Retrieve the cart's details again.", |
|
1327
|
link: "/references/helper-steps/useQueryGraphStep", |
|
1328
|
depth: 9 |
|
1329
|
}, |
|
1330
|
{ |
|
1331
|
type: "step", |
|
1332
|
name: "releaseLockStep", |
|
1333
|
description: "Release the lock on the cart.", |
|
1334
|
link: "/references/medusa-workflows/steps/releaseLockStep", |
|
1335
|
depth: 10 |
|
1336
|
} |
|
1337
|
] |
|
1338
|
}} |
|
1339
|
/> |
|
1340
|
|
|
1341
|
Most of the workflow's steps are either provided by Medusa in the `@medusajs/medusa/core-flows` package or steps you've already implemented. You only need to implement the `getCartLoyaltyPromoAmountStep` step. |
|
1342
|
|
|
1343
|
### getCartLoyaltyPromoAmountStep |
|
1344
|
|
|
1345
|
The fourth step in the workflow is the `getCartLoyaltyPromoAmountStep`, which retrieves the amount to be discounted based on the loyalty points. This step is useful to determine how much discount to apply to the cart. |
|
1346
|
|
|
1347
|
To create the step, create the file `src/workflows/steps/get-cart-loyalty-promo-amount.ts` with the following content: |
|
1348
|
|
|
1349
|
export const getCartLoyaltyPromoAmountStepHighlights = [ |
|
1350
|
["23", "getPoints", "Get the customer's loyalty points."], |
|
1351
|
["34", "calculatePointsFromAmount", "Calculate the amount to be discounted based on the loyalty points."], |
|
1352
|
["38", "Math.min", "Ensure that the amount doesn't exceed the cart's total."], |
|
1353
|
["40", "amount", "Return the amount to be discounted."], |
|
1354
|
] |
|
1355
|
|
|
1356
|
```ts title="src/workflows/steps/get-cart-loyalty-promo-amount.ts" highlights={getCartLoyaltyPromoAmountStepHighlights} |
|
1357
|
import { PromotionDTO, CustomerDTO } from "@medusajs/framework/types" |
|
1358
|
import { MedusaError } from "@medusajs/framework/utils" |
|
1359
|
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk" |
|
1360
|
import LoyaltyModuleService from "../../modules/loyalty/service" |
|
1361
|
import { LOYALTY_MODULE } from "../../modules/loyalty" |
|
1362
|
|
|
1363
|
export type GetCartLoyaltyPromoAmountStepInput = { |
|
1364
|
cart: { |
|
1365
|
id: string |
|
1366
|
customer: CustomerDTO |
|
1367
|
promotions?: PromotionDTO[] |
|
1368
|
total: number |
|
1369
|
} |
|
1370
|
} |
|
1371
|
|
|
1372
|
export const getCartLoyaltyPromoAmountStep = createStep( |
|
1373
|
"get-cart-loyalty-promo-amount", |
|
1374
|
async ({ cart }: GetCartLoyaltyPromoAmountStepInput, { container }) => { |
|
1375
|
// Check if customer has any loyalty points |
|
1376
|
const loyaltyModuleService: LoyaltyModuleService = container.resolve( |
|
1377
|
LOYALTY_MODULE |
|
1378
|
) |
|
1379
|
const loyaltyPoints = await loyaltyModuleService.getPoints( |
|
1380
|
cart.customer.id |
|
1381
|
) |
|
1382
|
|
|
1383
|
if (loyaltyPoints <= 0) { |
|
1384
|
throw new MedusaError( |
|
1385
|
MedusaError.Types.INVALID_DATA, |
|
1386
|
"Customer has no loyalty points" |
|
1387
|
) |
|
1388
|
} |
|
1389
|
|
|
1390
|
const pointsAmount = await loyaltyModuleService.calculatePointsFromAmount( |
|
1391
|
loyaltyPoints |
|
1392
|
) |
|
1393
|
|
|
1394
|
const amount = Math.min(pointsAmount, cart.total) |
|
1395
|
|
|
1396
|
return new StepResponse(amount) |
|
1397
|
} |
|
1398
|
) |
|
1399
|
``` |
|
1400
|
|
|
1401
|
You create a step that accepts an object having the cart's details. |
|
1402
|
|
|
1403
|
In the step, you resolve the Loyalty Module's service from the Medusa container. Then, you call the `getPoints` method to retrieve the customer's loyalty points. If the customer has no loyalty points, you throw an error. |
|
1404
|
|
|
1405
|
Next, you call the `calculatePointsFromAmount` method to calculate the amount to be discounted based on the loyalty points. You use the `Math.min` function to ensure that the amount doesn't exceed the cart's total. |
|
1406
|
|
|
1407
|
Finally, you return a `StepResponse` with the amount to be discounted. |
|
1408
|
|
|
1409
|
### Create the Workflow |
|
1410
|
|
|
1411
|
You can now create the workflow that applies a loyalty promotion to the cart. |
|
1412
|
|
|
1413
|
To create the workflow, create the file `src/workflows/apply-loyalty-on-cart.ts` with the following content: |
|
1414
|
|
|
1415
|
export const applyLoyaltyOnCartWorkflowHighlights = [ |
|
1416
|
["46", "useQueryGraphStep", "Retrieve the cart's details."], |
|
1417
|
["57", "validateCustomerExistsStep", "Validate that the customer is registered."], |
|
1418
|
["61", "getCartLoyaltyPromoStep", "Retrieve the cart's loyalty promotion."], |
|
1419
|
["66", "acquireLockStep", "Acquire a lock on the cart to prevent concurrent modifications."], |
|
1420
|
["72", "getCartLoyaltyPromoAmountStep", "Get the amount to be discounted based on the loyalty points."], |
|
1421
|
] |
|
1422
|
|
|
1423
|
```ts title="src/workflows/apply-loyalty-on-cart.ts" highlights={applyLoyaltyOnCartWorkflowHighlights} collapsibleLines="1-26" expandButtonLabel="Show Imports" |
|
1424
|
import { |
|
1425
|
createWorkflow, |
|
1426
|
transform, |
|
1427
|
WorkflowResponse, |
|
1428
|
} from "@medusajs/framework/workflows-sdk" |
|
1429
|
import { |
|
1430
|
acquireLockStep, |
|
1431
|
createPromotionsStep, |
|
1432
|
releaseLockStep, |
|
1433
|
updateCartPromotionsWorkflow, |
|
1434
|
updateCartsStep, |
|
1435
|
useQueryGraphStep, |
|
1436
|
} from "@medusajs/medusa/core-flows" |
|
1437
|
import { |
|
1438
|
validateCustomerExistsStep, |
|
1439
|
ValidateCustomerExistsStepInput, |
|
1440
|
} from "./steps/validate-customer-exists" |
|
1441
|
import { |
|
1442
|
getCartLoyaltyPromoAmountStep, |
|
1443
|
GetCartLoyaltyPromoAmountStepInput, |
|
1444
|
} from "./steps/get-cart-loyalty-promo-amount" |
|
1445
|
import { CartData, CUSTOMER_ID_PROMOTION_RULE_ATTRIBUTE } from "../utils/promo" |
|
1446
|
import { CreatePromotionDTO } from "@medusajs/framework/types" |
|
1447
|
import { PromotionActions } from "@medusajs/framework/utils" |
|
1448
|
import { getCartLoyaltyPromoStep } from "./steps/get-cart-loyalty-promo" |
|
1449
|
|
|
1450
|
type WorkflowInput = { |
|
1451
|
cart_id: string |
|
1452
|
} |
|
1453
|
|
|
1454
|
const fields = [ |
|
1455
|
"id", |
|
1456
|
"customer.*", |
|
1457
|
"promotions.*", |
|
1458
|
"promotions.application_method.*", |
|
1459
|
"promotions.rules.*", |
|
1460
|
"promotions.rules.values.*", |
|
1461
|
"currency_code", |
|
1462
|
"total", |
|
1463
|
"metadata", |
|
1464
|
] |
|
1465
|
|
|
1466
|
export const applyLoyaltyOnCartWorkflow = createWorkflow( |
|
1467
|
"apply-loyalty-on-cart", |
|
1468
|
(input: WorkflowInput) => { |
|
1469
|
const { data: carts } = useQueryGraphStep({ |
|
1470
|
entity: "cart", |
|
1471
|
fields, |
|
1472
|
filters: { |
|
1473
|
id: input.cart_id, |
|
1474
|
}, |
|
1475
|
options: { |
|
1476
|
throwIfKeyNotFound: true, |
|
1477
|
}, |
|
1478
|
}) |
|
1479
|
|
|
1480
|
validateCustomerExistsStep({ |
|
1481
|
customer: carts[0].customer, |
|
1482
|
} as ValidateCustomerExistsStepInput) |
|
1483
|
|
|
1484
|
getCartLoyaltyPromoStep({ |
|
1485
|
cart: carts[0] as unknown as CartData, |
|
1486
|
throwErrorOn: "found", |
|
1487
|
}) |
|
1488
|
|
|
1489
|
acquireLockStep({ |
|
1490
|
key: input.cart_id, |
|
1491
|
timeout: 2, |
|
1492
|
ttl: 10, |
|
1493
|
}) |
|
1494
|
|
|
1495
|
const amount = getCartLoyaltyPromoAmountStep({ |
|
1496
|
cart: carts[0], |
|
1497
|
} as unknown as GetCartLoyaltyPromoAmountStepInput) |
|
1498
|
|
|
1499
|
// TODO create and apply the promotion on the cart |
|
1500
|
} |
|
1501
|
) |
|
1502
|
``` |
|
1503
|
|
|
1504
|
You create a workflow that accepts an object with the cart's ID as input. |
|
1505
|
|
|
1506
|
So far, you: |
|
1507
|
|
|
1508
|
- Use `useQueryGraphStep` to retrieve the cart's details. You pass the cart's ID as a filter to retrieve the cart. |
|
1509
|
- Validate that the customer is registered using the `validateCustomerExistsStep`. |
|
1510
|
- Check whether the cart has a loyalty promotion using the `getCartLoyaltyPromoStep`. You pass the `throwErrorOn` parameter with the value `found` to throw an error if a loyalty promotion is found in the cart. |
|
1511
|
- Acquire a lock on the cart using the `acquireLockStep` to prevent concurrent modifications. |
|
1512
|
- Retrieve the amount to be discounted based on the loyalty points using the `getCartLoyaltyPromoAmountStep`. |
|
1513
|
|
|
1514
|
Next, you need to create a new loyalty promotion for the cart. First, you'll prepare the data of the promotion to be created. |
|
1515
|
|
|
1516
|
Replace the `TODO` with the following: |
|
1517
|
|
|
1518
|
export const prepareLoyaltyPromoDataHighlights = [ |
|
1519
|
["15", "value", "Set the promotion's amount to the discounted amount."], |
|
1520
|
["22", "CUSTOMER_ID_PROMOTION_RULE_ATTRIBUTE", "Set the promotion's rule to be only valid for this cart's customer"], |
|
1521
|
["31", "budget", "Limit the promotion's usage to 1."], |
|
1522
|
] |
|
1523
|
|
|
1524
|
```ts title="src/workflows/apply-loyalty-on-cart.ts" highlights={prepareLoyaltyPromoDataHighlights} |
|
1525
|
const promoToCreate = transform({ |
|
1526
|
carts, |
|
1527
|
amount, |
|
1528
|
}, (data) => { |
|
1529
|
const randomStr = Math.random().toString(36).substring(2, 8) |
|
1530
|
const uniqueId = ( |
|
1531
|
"LOYALTY-" + data.carts[0].customer?.first_name + "-" + randomStr |
|
1532
|
).toUpperCase() |
|
1533
|
return { |
|
1534
|
code: uniqueId, |
|
1535
|
type: "standard", |
|
1536
|
status: "active", |
|
1537
|
application_method: { |
|
1538
|
type: "fixed", |
|
1539
|
value: data.amount, |
|
1540
|
target_type: "order", |
|
1541
|
currency_code: data.carts[0].currency_code, |
|
1542
|
allocation: "across", |
|
1543
|
}, |
|
1544
|
rules: [ |
|
1545
|
{ |
|
1546
|
attribute: CUSTOMER_ID_PROMOTION_RULE_ATTRIBUTE, |
|
1547
|
operator: "eq", |
|
1548
|
values: [data.carts[0].customer!.id], |
|
1549
|
}, |
|
1550
|
], |
|
1551
|
campaign: { |
|
1552
|
name: uniqueId, |
|
1553
|
description: "Loyalty points promotion for " + data.carts[0].customer!.email, |
|
1554
|
campaign_identifier: uniqueId, |
|
1555
|
budget: { |
|
1556
|
type: "usage", |
|
1557
|
limit: 1, |
|
1558
|
}, |
|
1559
|
}, |
|
1560
|
} |
|
1561
|
}) |
|
1562
|
|
|
1563
|
// TODO create promotion and apply it on cart |
|
1564
|
``` |
|
1565
|
|
|
1566
|
Since data manipulation isn't allowed in a workflow constructor, you use the [transform](!docs!/learn/fundamentals/workflows/variable-manipulation) function from the Workflows SDK. It accepts two parameters: |
|
1567
|
|
|
1568
|
- The data to perform manipulation on. In this case, you pass the cart's details and the amount to be discounted. |
|
1569
|
- A function that receives the data from the first parameter, and returns the transformed data. |
|
1570
|
|
|
1571
|
In the transformation function, you prepare th data of the loyalty promotion to be created. Some key details include: |
|
1572
|
|
|
1573
|
- You set the discount amount in the application method of the promotion. |
|
1574
|
- You add a rule to the promotion that ensures it can be used only in carts having their `customer_id` equal to this customer's ID. This prevents other customers from using this promotion. |
|
1575
|
- You create a campaign for the promotion, and you set the campaign budget to a single usage. This prevents the customer from using the promotion again. |
|
1576
|
|
|
1577
|
<Note> |
|
1578
|
|
|
1579
|
Learn more about promotion concepts in the [Promotion Module](../../../commerce-modules/promotion/page.mdx)'s documentation. |
|
1580
|
|
|
1581
|
</Note> |
|
1582
|
|
|
1583
|
You can now use the returned data to create a promotion and apply it to the cart. Replace the new `TODO` with the following: |
|
1584
|
|
|
1585
|
export const createLoyaltyPromoStepHighlights = [ |
|
1586
|
["1", "createPromotionsStep", "Create the loyalty promotion."], |
|
1587
|
["5", "transform", "Prepare the data to update the cart's promotions."], |
|
1588
|
["25", "updateCartPromotionsWorkflow", "Update the cart's promotions with the new loyalty promotion."], |
|
1589
|
["29", "updateCartsStep", "Update the cart to store the ID of the loyalty promotion in the metadata."], |
|
1590
|
["37", "useQueryGraphStep", "Retrieve the cart's details again."], |
|
1591
|
["43", "releaseLockStep", "Release the lock on the cart."], |
|
1592
|
] |
|
1593
|
|
|
1594
|
```ts title="src/workflows/apply-loyalty-on-cart.ts" highlights={createLoyaltyPromoStepHighlights} |
|
1595
|
const loyaltyPromo = createPromotionsStep([ |
|
1596
|
promoToCreate, |
|
1597
|
] as CreatePromotionDTO[]) |
|
1598
|
|
|
1599
|
const { metadata, ...updatePromoData } = transform({ |
|
1600
|
carts, |
|
1601
|
promoToCreate, |
|
1602
|
loyaltyPromo, |
|
1603
|
}, (data) => { |
|
1604
|
const promos = [ |
|
1605
|
...(data.carts[0].promotions?.map((promo) => promo?.code).filter(Boolean) || []) as string[], |
|
1606
|
data.promoToCreate.code, |
|
1607
|
] |
|
1608
|
|
|
1609
|
return { |
|
1610
|
cart_id: data.carts[0].id, |
|
1611
|
promo_codes: promos, |
|
1612
|
action: PromotionActions.ADD, |
|
1613
|
metadata: { |
|
1614
|
loyalty_promo_id: data.loyaltyPromo[0].id, |
|
1615
|
}, |
|
1616
|
} |
|
1617
|
}) |
|
1618
|
|
|
1619
|
updateCartPromotionsWorkflow.runAsStep({ |
|
1620
|
input: updatePromoData, |
|
1621
|
}) |
|
1622
|
|
|
1623
|
updateCartsStep([ |
|
1624
|
{ |
|
1625
|
id: input.cart_id, |
|
1626
|
metadata, |
|
1627
|
}, |
|
1628
|
]) |
|
1629
|
|
|
1630
|
// retrieve cart with updated promotions |
|
1631
|
const { data: updatedCarts } = useQueryGraphStep({ |
|
1632
|
entity: "cart", |
|
1633
|
fields, |
|
1634
|
filters: { id: input.cart_id }, |
|
1635
|
}).config({ name: "retrieve-cart" }) |
|
1636
|
|
|
1637
|
releaseLockStep({ |
|
1638
|
key: input.cart_id, |
|
1639
|
}) |
|
1640
|
|
|
1641
|
return new WorkflowResponse(updatedCarts[0]) |
|
1642
|
``` |
|
1643
|
|
|
1644
|
In the rest of the workflow, you: |
|
1645
|
|
|
1646
|
- Create the loyalty promotion using the data you prepared earlier using the `createPromotionsStep`. |
|
1647
|
- Use the `transform` function to prepare the data to update the cart's promotions. You add the new loyalty promotion code to the cart's promotions codes, and set the `loyalty_promo_id` in the cart's metadata. |
|
1648
|
- Update the cart's promotions with the new loyalty promotion using the `updateCartPromotionsWorkflow` workflow. |
|
1649
|
- Update the cart's metadata with the loyalty promotion ID using the `updateCartsStep`. |
|
1650
|
- Retrieve the cart's details again using `useQueryGraphStep` to get the updated cart with the new loyalty promotion. |
|
1651
|
- Release the lock on the cart using the `releaseLockStep`. |
|
1652
|
|
|
1653
|
To return data from the workflow, you must return an instance of `WorkflowResponse`. You pass it the data to be returned, which is in this case the cart's details. |
|
1654
|
|
|
1655
|
### Create the API Route |
|
1656
|
|
|
1657
|
Next, you'll create the API route that executes this workflow. |
|
1658
|
|
|
1659
|
To create the API route, create the file `src/api/store/carts/[id]/loyalty-points/route.ts` with the following content: |
|
1660
|
|
|
1661
|
```ts title="src/api/store/carts/[id]/loyalty-points/route.ts" |
|
1662
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http" |
|
1663
|
import { applyLoyaltyOnCartWorkflow } from "../../../../../workflows/apply-loyalty-on-cart" |
|
1664
|
|
|
1665
|
export async function POST( |
|
1666
|
req: MedusaRequest, |
|
1667
|
res: MedusaResponse |
|
1668
|
) { |
|
1669
|
const { id: cart_id } = req.params |
|
1670
|
|
|
1671
|
const { result: cart } = await applyLoyaltyOnCartWorkflow(req.scope) |
|
1672
|
.run({ |
|
1673
|
input: { |
|
1674
|
cart_id, |
|
1675
|
}, |
|
1676
|
}) |
|
1677
|
|
|
1678
|
res.json({ cart }) |
|
1679
|
} |
|
1680
|
``` |
|
1681
|
|
|
1682
|
Since you export a `POST` route handler, you expose a `POST` API route at `/store/carts/[id]/loyalty-points`. |
|
1683
|
|
|
1684
|
In the route handler, you execute the `applyLoyaltyOnCartWorkflow` workflow, passing it the cart ID as an input. You return the cart's details in the response. |
|
1685
|
|
|
1686
|
You can now use this API route in the Next.js Starter Storefront. |
|
1687
|
|
|
1688
|
### Apply Loyalty Points in the Storefront |
|
1689
|
|
|
1690
|
In the Next.js Starter Storefront, you need to add a server action function that sends a request to the API route you created earlier. Then, you'll use that function when the customer clicks the "Apply Loyalty Points" button. |
|
1691
|
|
|
1692
|
To add the function, add the following to `src/lib/data/cart.ts` in the Next.js Starter Storefront: |
|
1693
|
|
|
1694
|
```ts title="src/lib/data/cart.ts" badgeLabel="Storefront" badgeColor="blue" |
|
1695
|
export async function applyLoyaltyPointsOnCart() { |
|
1696
|
const cartId = await getCartId() |
|
1697
|
const headers = { |
|
1698
|
...(await getAuthHeaders()), |
|
1699
|
} |
|
1700
|
|
|
1701
|
return await sdk.client.fetch<{ |
|
1702
|
cart: HttpTypes.StoreCart & { |
|
1703
|
promotions: HttpTypes.StorePromotion[] |
|
1704
|
} |
|
1705
|
}>(`/store/carts/${cartId}/loyalty-points`, { |
|
1706
|
method: "POST", |
|
1707
|
headers, |
|
1708
|
}) |
|
1709
|
.then(async (result) => { |
|
1710
|
const cartCacheTag = await getCacheTag("carts") |
|
1711
|
revalidateTag(cartCacheTag) |
|
1712
|
|
|
1713
|
return result |
|
1714
|
}) |
|
1715
|
} |
|
1716
|
``` |
|
1717
|
|
|
1718
|
You create an `applyLoyaltyPointsOnCart` function that sends a request to the API route you created earlier. |
|
1719
|
|
|
1720
|
In the function, you retrieve the cart ID stored in the cookie using the `getCartId` function, which is available in the Next.js Starter Storefront. |
|
1721
|
|
|
1722
|
Then, you send the request. Once the request is resolved successfully, you revalidate the cart cache tag to ensure that the cart's details are updated and refetched by other components. This ensures that the applied promotion is shown in the checkout summary without needing to refresh the page. |
|
1723
|
|
|
1724
|
Finally, you'll use this function in the `handleTogglePromotion` function in the `LoyaltyPoints` component you created earlier. |
|
1725
|
|
|
1726
|
At the top of `src/modules/checkout/components/loyalty-points/index.tsx`, import the function: |
|
1727
|
|
|
1728
|
```tsx title="src/modules/checkout/components/loyalty-points/index.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
1729
|
import { applyLoyaltyPointsOnCart } from "../../../../lib/data/cart" |
|
1730
|
``` |
|
1731
|
|
|
1732
|
Then, replace the `handleTogglePromotion` function with the following: |
|
1733
|
|
|
1734
|
```tsx title="src/modules/checkout/components/loyalty-points/index.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
1735
|
const handleTogglePromotion = async ( |
|
1736
|
e: React.MouseEvent<HTMLButtonElement, MouseEvent> |
|
1737
|
) => { |
|
1738
|
e.preventDefault() |
|
1739
|
if (!isLoyaltyPointsPromoApplied) { |
|
1740
|
await applyLoyaltyPointsOnCart() |
|
1741
|
} else { |
|
1742
|
// TODO remove loyalty points |
|
1743
|
} |
|
1744
|
} |
|
1745
|
``` |
|
1746
|
|
|
1747
|
In the `handleTogglePromotion` function, you call the `applyLoyaltyPointsOnCart` function if the cart doesn't have a loyalty promotion. This will send a request to the API route you created earlier, which will execute the workflow that applies the loyalty promotion to the cart. |
|
1748
|
|
|
1749
|
You'll implement removing the loyalty points promotion in a later step. |
|
1750
|
|
|
1751
|
### Test it Out |
|
1752
|
|
|
1753
|
To test out applying the loyalty points on the cart, start the Medusa application and Next.js Starter Storefront. |
|
1754
|
|
|
1755
|
Then, in the checkout flow as an authenticated customer, click on the "Apply Loyalty Points" button. The checkout summary will be updated with the applied promotion and the discount amount. |
|
1756
|
|
|
1757
|
<Note title="Tip"> |
|
1758
|
|
|
1759
|
If you don't want the promotion to be shown in the "Promotions(s) applied" section, you can filter the promotions in `src/modules/checkout/components/discount-code/index.tsx` to not show a promotion matching `cart.metadata.loyalty_promo_id`. |
|
1760
|
|
|
1761
|
</Note> |
|
1762
|
|
|
1763
|
 |
|
1764
|
|
|
1765
|
--- |
|
1766
|
|
|
1767
|
## Step 8: Remove Loyalty Points From Cart |
|
1768
|
|
|
1769
|
In this step, you'll implement the functionality to remove the loyalty points promotion from the cart. This is useful if the customer changes their mind and wants to remove the promotion. |
|
1770
|
|
|
1771
|
To implement this functionality, you'll need to: |
|
1772
|
|
|
1773
|
- Create a workflow that removes the loyalty points promotion from the cart. |
|
1774
|
- Create an API route that executes the workflow. |
|
1775
|
- Create a function in the Next.js Starter Storefront that sends a request to the API route you created earlier. |
|
1776
|
- Use the function in the `handleTogglePromotion` function in the `LoyaltyPoints` component you created earlier. |
|
1777
|
|
|
1778
|
### Create the Workflow |
|
1779
|
|
|
1780
|
The workflow will have the following steps: |
|
1781
|
|
|
1782
|
<WorkflowDiagram |
|
1783
|
workflow={{ |
|
1784
|
name: "removeLoyaltyFromCartWorkflow", |
|
1785
|
steps: [ |
|
1786
|
{ |
|
1787
|
type: "step", |
|
1788
|
name: "useQueryGraphStep", |
|
1789
|
description: "Retrieve the cart's details.", |
|
1790
|
link: "/references/helper-steps/useQueryGraphStep", |
|
1791
|
depth: 1 |
|
1792
|
}, |
|
1793
|
{ |
|
1794
|
type: "step", |
|
1795
|
name: "getCartLoyaltyPromoStep", |
|
1796
|
description: "Retrieve the cart's loyalty promotion.", |
|
1797
|
depth: 2, |
|
1798
|
}, |
|
1799
|
{ |
|
1800
|
type: "step", |
|
1801
|
name: "acquireLockStep", |
|
1802
|
description: "Acquire a lock on the cart to prevent concurrent modifications.", |
|
1803
|
link: "/references/medusa-workflows/steps/acquireLockStep", |
|
1804
|
depth: 3, |
|
1805
|
}, |
|
1806
|
{ |
|
1807
|
type: "workflow", |
|
1808
|
name: "updateCartPromotionsWorkflow", |
|
1809
|
description: "Update the cart's promotions to remove the loyalty promotion.", |
|
1810
|
link: "/references/medusa-workflows/updateCartPromotionsWorkflow", |
|
1811
|
depth: 4, |
|
1812
|
}, |
|
1813
|
{ |
|
1814
|
type: "step", |
|
1815
|
name: "updateCartsStep", |
|
1816
|
description: "Update the cart to remove the loyalty promotion ID from the metadata.", |
|
1817
|
link: "/references/medusa-workflows/steps/updateCartsStep", |
|
1818
|
depth: 5, |
|
1819
|
}, |
|
1820
|
{ |
|
1821
|
type: "step", |
|
1822
|
name: "updatePromotionsStep", |
|
1823
|
description: "Deactivate the loyalty promotion.", |
|
1824
|
link: "/references/medusa-workflows/steps/updatePromotionsStep", |
|
1825
|
depth: 6, |
|
1826
|
}, |
|
1827
|
{ |
|
1828
|
type: "step", |
|
1829
|
name: "useQueryGraphStep", |
|
1830
|
description: "Retrieve the cart's details again.", |
|
1831
|
link: "/references/helper-steps/useQueryGraphStep", |
|
1832
|
depth: 7 |
|
1833
|
}, |
|
1834
|
{ |
|
1835
|
type: "step", |
|
1836
|
name: "releaseLockStep", |
|
1837
|
description: "Release the lock on the cart.", |
|
1838
|
link: "/references/medusa-workflows/steps/releaseLockStep", |
|
1839
|
depth: 8 |
|
1840
|
} |
|
1841
|
] |
|
1842
|
}} |
|
1843
|
/> |
|
1844
|
|
|
1845
|
Since you already have all the steps, you can create the workflow. |
|
1846
|
|
|
1847
|
To create the workflow, create the file `src/workflows/remove-loyalty-from-cart.ts` with the following content: |
|
1848
|
|
|
1849
|
export const removeLoyaltyFromCartWorkflowHighlights = [ |
|
1850
|
["37", "useQueryGraphStep", "Retrieve the cart's details."], |
|
1851
|
["48", "getCartLoyaltyPromoStep", "Retrieve the cart's loyalty promotion."], |
|
1852
|
["53", "acquireLockStep", "Acquire a lock on the cart to prevent concurrent modifications."], |
|
1853
|
["59", "updateCartPromotionsWorkflow", "Update the cart's promotions to remove the loyalty promotion."], |
|
1854
|
["67", "transform", "Prepare the new metadata to remove the loyalty promotion ID."], |
|
1855
|
["78", "updateCartsStep", "Update the cart to remove the loyalty promotion ID from the metadata."], |
|
1856
|
["85", "updatePromotionsStep", "Deactivate the loyalty promotion."], |
|
1857
|
["93", "useQueryGraphStep", "Retrieve the cart's details again."], |
|
1858
|
["99", "releaseLockStep", "Release the lock on the cart."] |
|
1859
|
] |
|
1860
|
|
|
1861
|
```ts title="src/workflows/remove-loyalty-from-cart.ts" collapsibleLines="1-15" expandButtonLabel="Show Imports" highlights={removeLoyaltyFromCartWorkflowHighlights} |
|
1862
|
import { |
|
1863
|
createWorkflow, |
|
1864
|
transform, |
|
1865
|
WorkflowResponse, |
|
1866
|
} from "@medusajs/framework/workflows-sdk" |
|
1867
|
import { |
|
1868
|
acquireLockStep, |
|
1869
|
releaseLockStep, |
|
1870
|
useQueryGraphStep, |
|
1871
|
updateCartPromotionsWorkflow, |
|
1872
|
updateCartsStep, |
|
1873
|
updatePromotionsStep, |
|
1874
|
} from "@medusajs/medusa/core-flows" |
|
1875
|
import { getCartLoyaltyPromoStep } from "./steps/get-cart-loyalty-promo" |
|
1876
|
import { PromotionActions } from "@medusajs/framework/utils" |
|
1877
|
import { CartData } from "../utils/promo" |
|
1878
|
|
|
1879
|
type WorkflowInput = { |
|
1880
|
cart_id: string |
|
1881
|
} |
|
1882
|
|
|
1883
|
const fields = [ |
|
1884
|
"id", |
|
1885
|
"customer.*", |
|
1886
|
"promotions.*", |
|
1887
|
"promotions.application_method.*", |
|
1888
|
"promotions.rules.*", |
|
1889
|
"promotions.rules.values.*", |
|
1890
|
"currency_code", |
|
1891
|
"total", |
|
1892
|
"metadata", |
|
1893
|
] |
|
1894
|
|
|
1895
|
export const removeLoyaltyFromCartWorkflow = createWorkflow( |
|
1896
|
"remove-loyalty-from-cart", |
|
1897
|
(input: WorkflowInput) => { |
|
1898
|
const { data: carts } = useQueryGraphStep({ |
|
1899
|
entity: "cart", |
|
1900
|
fields, |
|
1901
|
filters: { |
|
1902
|
id: input.cart_id, |
|
1903
|
}, |
|
1904
|
options: { |
|
1905
|
throwIfKeyNotFound: true, |
|
1906
|
}, |
|
1907
|
}) |
|
1908
|
|
|
1909
|
const loyaltyPromo = getCartLoyaltyPromoStep({ |
|
1910
|
cart: carts[0] as unknown as CartData, |
|
1911
|
throwErrorOn: "not-found", |
|
1912
|
}) |
|
1913
|
|
|
1914
|
acquireLockStep({ |
|
1915
|
key: input.cart_id, |
|
1916
|
timeout: 2, |
|
1917
|
ttl: 10, |
|
1918
|
}) |
|
1919
|
|
|
1920
|
updateCartPromotionsWorkflow.runAsStep({ |
|
1921
|
input: { |
|
1922
|
cart_id: input.cart_id, |
|
1923
|
promo_codes: [loyaltyPromo.code!], |
|
1924
|
action: PromotionActions.REMOVE, |
|
1925
|
}, |
|
1926
|
}) |
|
1927
|
|
|
1928
|
const newMetadata = transform({ |
|
1929
|
carts, |
|
1930
|
}, (data) => { |
|
1931
|
const { loyalty_promo_id, ...rest } = data.carts[0].metadata || {} |
|
1932
|
|
|
1933
|
return { |
|
1934
|
...rest, |
|
1935
|
loyalty_promo_id: null, |
|
1936
|
} |
|
1937
|
}) |
|
1938
|
|
|
1939
|
updateCartsStep([ |
|
1940
|
{ |
|
1941
|
id: input.cart_id, |
|
1942
|
metadata: newMetadata, |
|
1943
|
}, |
|
1944
|
]) |
|
1945
|
|
|
1946
|
updatePromotionsStep([ |
|
1947
|
{ |
|
1948
|
id: loyaltyPromo.id, |
|
1949
|
status: "inactive", |
|
1950
|
}, |
|
1951
|
]) |
|
1952
|
|
|
1953
|
// retrieve cart with updated promotions |
|
1954
|
const { data: updatedCarts } = useQueryGraphStep({ |
|
1955
|
entity: "cart", |
|
1956
|
fields, |
|
1957
|
filters: { id: input.cart_id }, |
|
1958
|
}).config({ name: "retrieve-cart" }) |
|
1959
|
|
|
1960
|
releaseLockStep({ |
|
1961
|
key: input.cart_id, |
|
1962
|
}) |
|
1963
|
|
|
1964
|
return new WorkflowResponse(updatedCarts[0]) |
|
1965
|
} |
|
1966
|
) |
|
1967
|
``` |
|
1968
|
|
|
1969
|
You create a workflow that accepts an object with the cart's ID as input. |
|
1970
|
|
|
1971
|
In the workflow, you: |
|
1972
|
|
|
1973
|
- Use `useQueryGraphStep` to retrieve the cart's details. You pass the cart's ID as a filter to retrieve the cart. |
|
1974
|
- Check whether the cart has a loyalty promotion using the `getCartLoyaltyPromoStep`. You pass the `throwErrorOn` parameter with the value `not-found` to throw an error if a loyalty promotion isn't found in the cart. |
|
1975
|
- Acquire a lock on the cart using the `acquireLockStep` to prevent concurrent modifications. |
|
1976
|
- Update the cart's promotions using the `updateCartPromotionsWorkflow`, removing the loyalty promotion. |
|
1977
|
- Use the `transform` function to prepare the new metadata of the cart. You remove the `loyalty_promo_id` from the metadata. |
|
1978
|
- Update the cart's metadata with the new metadata using the `updateCartsStep`. |
|
1979
|
- Deactivate the loyalty promotion using the `updatePromotionsStep`. |
|
1980
|
- Retrieve the cart's details again using `useQueryGraphStep` to get the updated cart with the new loyalty promotion. |
|
1981
|
- Release the lock on the cart using the `releaseLockStep`. |
|
1982
|
- Return the cart's details in a `WorkflowResponse` instance. |
|
1983
|
|
|
1984
|
### Create the API Route |
|
1985
|
|
|
1986
|
Next, you'll create the API route that executes this workflow. |
|
1987
|
|
|
1988
|
To create the API route, add the following in `src/api/store/carts/[id]/loyalty-points/route.ts`: |
|
1989
|
|
|
1990
|
```ts title="src/api/store/carts/[id]/loyalty-points/route.ts" |
|
1991
|
// other imports... |
|
1992
|
import { removeLoyaltyFromCartWorkflow } from "../../../../../workflows/remove-loyalty-from-cart" |
|
1993
|
|
|
1994
|
// ... |
|
1995
|
export async function DELETE( |
|
1996
|
req: MedusaRequest, |
|
1997
|
res: MedusaResponse |
|
1998
|
) { |
|
1999
|
const { id: cart_id } = req.params |
|
2000
|
|
|
2001
|
const { result: cart } = await removeLoyaltyFromCartWorkflow(req.scope) |
|
2002
|
.run({ |
|
2003
|
input: { |
|
2004
|
cart_id, |
|
2005
|
}, |
|
2006
|
}) |
|
2007
|
|
|
2008
|
res.json({ cart }) |
|
2009
|
} |
|
2010
|
``` |
|
2011
|
|
|
2012
|
You export a `DELETE` route handler, which exposes a `DELETE` API route at `/store/carts/[id]/loyalty-points`. |
|
2013
|
|
|
2014
|
In the route handler, you execute the `removeLoyaltyFromCartWorkflow` workflow, passing it the cart ID as an input. You return the cart's details in the response. |
|
2015
|
|
|
2016
|
You can now use this API route in the Next.js Starter Storefront. |
|
2017
|
|
|
2018
|
### Remove Loyalty Points in the Storefront |
|
2019
|
|
|
2020
|
In the Next.js Starter Storefront, you need to add a server action function that sends a request to the API route you created earlier. Then, you'll use that function when the customer clicks the "Remove Loyalty Points" button, which shows when the cart has a loyalty promotion applied. |
|
2021
|
|
|
2022
|
To add the function, add the following to `src/lib/data/cart.ts`: |
|
2023
|
|
|
2024
|
```ts title="src/lib/data/cart.ts" badgeLabel="Storefront" badgeColor="blue" |
|
2025
|
export async function removeLoyaltyPointsOnCart() { |
|
2026
|
const cartId = await getCartId() |
|
2027
|
const headers = { |
|
2028
|
...(await getAuthHeaders()), |
|
2029
|
} |
|
2030
|
const next = { |
|
2031
|
...(await getCacheOptions("carts")), |
|
2032
|
} |
|
2033
|
|
|
2034
|
return await sdk.client.fetch<{ |
|
2035
|
cart: HttpTypes.StoreCart & { |
|
2036
|
promotions: HttpTypes.StorePromotion[] |
|
2037
|
} |
|
2038
|
}>(`/store/carts/${cartId}/loyalty-points`, { |
|
2039
|
method: "DELETE", |
|
2040
|
headers, |
|
2041
|
}) |
|
2042
|
.then(async (result) => { |
|
2043
|
const cartCacheTag = await getCacheTag("carts") |
|
2044
|
revalidateTag(cartCacheTag) |
|
2045
|
|
|
2046
|
return result |
|
2047
|
}) |
|
2048
|
} |
|
2049
|
``` |
|
2050
|
|
|
2051
|
You create a `removeLoyaltyPointsOnCart` function that sends a request to the API route you created earlier. |
|
2052
|
|
|
2053
|
In the function, you retrieve the cart ID stored in the cookie using the `getCartId` function, which is available in the Next.js Starter Storefront. |
|
2054
|
|
|
2055
|
Then, you send the request to the API route. Once the request is resolved successfully, you revalidate the cart cache tag to ensure that the cart's details are updated and refetched by other components. This ensures that the promotion is removed from the checkout summary without needing to refresh the page. |
|
2056
|
|
|
2057
|
Finally, you'll use this function in the `handleTogglePromotion` function in the `LoyaltyPoints` component you created earlier. |
|
2058
|
|
|
2059
|
At the top of `src/modules/checkout/components/loyalty-points/index.tsx`, add the following import: |
|
2060
|
|
|
2061
|
```tsx title="src/modules/checkout/components/loyalty-points/index.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
2062
|
import { removeLoyaltyPointsOnCart } from "../../../../lib/data/cart" |
|
2063
|
``` |
|
2064
|
|
|
2065
|
Then, replace the `TODO` in `handleTogglePromotion` with the following: |
|
2066
|
|
|
2067
|
```tsx title="src/modules/checkout/components/loyalty-points/index.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
2068
|
await removeLoyaltyPointsOnCart() |
|
2069
|
``` |
|
2070
|
|
|
2071
|
In the `handleTogglePromotion` function, you call the `removeLoyaltyPointsOnCart` function if the cart has a loyalty promotion. This will send a request to the API route you created earlier, which will execute the workflow that removes the loyalty promotion from the cart. |
|
2072
|
|
|
2073
|
### Test it Out |
|
2074
|
|
|
2075
|
To test out removing the loyalty points from the cart, start the Medusa application and Next.js Starter Storefront. |
|
2076
|
|
|
2077
|
Then, in the checkout flow as an authenticated customer, after applying the loyalty points, click on the "Remove Loyalty Points" button. The checkout summary will be updated with the removed promotion and the discount amount. |
|
2078
|
|
|
2079
|
 |
|
2080
|
|
|
2081
|
--- |
|
2082
|
|
|
2083
|
## Step 9: Validate Loyalty Points on Cart Completion |
|
2084
|
|
|
2085
|
After the customer applies the loyalty points to the cart and places the order, you need to validate that the customer actually has the loyalty points. This prevents edge cases where the customer may have applied the loyalty points previously but they don't have them anymore. |
|
2086
|
|
|
2087
|
So, in this step, you'll hook into Medusa's cart completion flow to perform the validation. |
|
2088
|
|
|
2089
|
Since Medusa uses workflows in its API routes, it allows you to hook into them and perform custom functionalities using [Workflow Hooks](!docs!/learn/fundamentals/workflows/workflow-hooks). A workflow hook is a point in a workflow where you can inject custom functionality as a step function, called a hook handler. |
|
2090
|
|
|
2091
|
Medusa uses the [completeCartWorkflow](/references/medusa-workflows/completeCartWorkflow) hook to complete the cart and place an order. This workflow has a `validate` hook that allows you to perform custom validation before the cart is completed. |
|
2092
|
|
|
2093
|
To consume the `validate` hook, create the file `src/workflows/hooks/complete-cart.ts` with the following content: |
|
2094
|
|
|
2095
|
export const completeCartWorkflowHookHighlights = [ |
|
2096
|
["10", "validate", "Consume the validate hook."], |
|
2097
|
["19", "graph", "Retrieve the cart's details."], |
|
2098
|
["37", "getCartLoyaltyPromotion", "Get the cart's loyalty promotion."], |
|
2099
|
["45", "getPoints", "Get the customer's loyalty points."], |
|
2100
|
["48", "requiredPoints", "Calculate the amount to be discounted based on the loyalty points."], |
|
2101
|
["54", "MedusaError", "Throw an error if the customer doesn't have enough loyalty points."], |
|
2102
|
] |
|
2103
|
|
|
2104
|
```ts title="src/workflows/hooks/complete-cart.ts" highlights={completeCartWorkflowHookHighlights} collapsibleLines="1-9" expandButtonLabel="Show Imports" |
|
2105
|
import { completeCartWorkflow } from "@medusajs/medusa/core-flows" |
|
2106
|
import LoyaltyModuleService from "../../modules/loyalty/service" |
|
2107
|
import { LOYALTY_MODULE } from "../../modules/loyalty" |
|
2108
|
import { CartData, getCartLoyaltyPromotion } from "../../utils/promo" |
|
2109
|
import { |
|
2110
|
MedusaError, |
|
2111
|
ContainerRegistrationKeys, |
|
2112
|
} from "@medusajs/framework/utils" |
|
2113
|
|
|
2114
|
completeCartWorkflow.hooks.validate( |
|
2115
|
async ({ cart }, { container }) => { |
|
2116
|
const query = container.resolve( |
|
2117
|
ContainerRegistrationKeys.QUERY |
|
2118
|
) |
|
2119
|
const loyaltyModuleService: LoyaltyModuleService = container.resolve( |
|
2120
|
LOYALTY_MODULE |
|
2121
|
) |
|
2122
|
|
|
2123
|
const { data: carts } = await query.graph({ |
|
2124
|
entity: "cart", |
|
2125
|
fields: [ |
|
2126
|
"id", |
|
2127
|
"promotions.*", |
|
2128
|
"customer.*", |
|
2129
|
"promotions.rules.*", |
|
2130
|
"promotions.rules.values.*", |
|
2131
|
"promotions.application_method.*", |
|
2132
|
"metadata", |
|
2133
|
], |
|
2134
|
filters: { |
|
2135
|
id: cart.id, |
|
2136
|
}, |
|
2137
|
}, { |
|
2138
|
throwIfKeyNotFound: true, |
|
2139
|
}) |
|
2140
|
|
|
2141
|
const loyaltyPromo = getCartLoyaltyPromotion( |
|
2142
|
carts[0] as unknown as CartData |
|
2143
|
) |
|
2144
|
|
|
2145
|
if (!loyaltyPromo) { |
|
2146
|
return |
|
2147
|
} |
|
2148
|
|
|
2149
|
const customerLoyaltyPoints = await loyaltyModuleService.getPoints( |
|
2150
|
carts[0].customer!.id |
|
2151
|
) |
|
2152
|
const requiredPoints = await loyaltyModuleService.calculatePointsFromAmount( |
|
2153
|
loyaltyPromo.application_method!.value as number |
|
2154
|
) |
|
2155
|
|
|
2156
|
if (customerLoyaltyPoints < requiredPoints) { |
|
2157
|
throw new MedusaError( |
|
2158
|
MedusaError.Types.INVALID_DATA, |
|
2159
|
`Customer does not have enough loyalty points. Required: ${ |
|
2160
|
requiredPoints |
|
2161
|
}, Available: ${customerLoyaltyPoints}` |
|
2162
|
) |
|
2163
|
} |
|
2164
|
} |
|
2165
|
) |
|
2166
|
``` |
|
2167
|
|
|
2168
|
Workflows have a special `hooks` property that includes all the hooks that you can consume in that workflow. You consume the hook by invoking it from the workflow's `hooks` property. |
|
2169
|
|
|
2170
|
Since the hook is essentially a step function, it accepts the following parameters: |
|
2171
|
|
|
2172
|
- The hook's input passed from the workflow, which differs for each hook. The `validate` hook receives an object having the cart's details. |
|
2173
|
- The step context object, which contains the Medusa container. You can use it to resolve services and perform actions. |
|
2174
|
|
|
2175
|
In the hook, you resolve Query and the Loyalty Module's service. Then, you use Query to retrieve the cart's necessary details, including its promotions, customer, and metadata. |
|
2176
|
|
|
2177
|
After that, you retrieve the customer's loyalty points and calculate the required points to apply the loyalty promotion. |
|
2178
|
|
|
2179
|
If the customer doesn't have enough loyalty points, you throw an error. This will prevent the cart from being completed if the customer doesn't have enough loyalty points. |
|
2180
|
|
|
2181
|
--- |
|
2182
|
|
|
2183
|
## Test Out Cart Completion with Loyalty Points |
|
2184
|
|
|
2185
|
Since you now have the entire loyalty points flow implemented, you can test it out by going through the checkout flow, applying the loyalty points to the cart. |
|
2186
|
|
|
2187
|
When you place the order, if the customer has sufficient loyalty points, the validation hook will pass. |
|
2188
|
|
|
2189
|
Then, the `order.placed` event will be emitted, which will execute the subscriber that calls the `handleOrderPointsWorkflow`. |
|
2190
|
|
|
2191
|
In the workflow, since the order's cart has a loyalty promotion, the points equivalent to the promotion will be deducted, and the promotion becomes inactive. |
|
2192
|
|
|
2193
|
You can confirm that the loyalty points were deducted either by sending a request to the [retrieve loyalty points API route](#step-5-retrieve-loyalty-points-api-route), or by going through the checkout process again in the storefront. |
|
2194
|
|
|
2195
|
--- |
|
2196
|
|
|
2197
|
## Next Steps |
|
2198
|
|
|
2199
|
You've now implement a loyalty points system in Medusa. There's still more that you can implement based on your use case: |
|
2200
|
|
|
2201
|
- Add loyalty points on registration or other events. Refer to the [Events Reference](/references/events) for a full list of available events you can listen to. |
|
2202
|
- Show the customer their loyalty point usage history. This will require adding another data model in the Loyalty Module that records the usage history. You can create records of that data model when an order that has a loyalty promotion is placed, then customize the storefront to show a new page for loyalty points history. |
|
2203
|
- Customize the Medusa Admin to show a new page or [UI Route](!docs!/learn/fundamentals/admin/ui-routes) for loyalty points information and analytics. |
|
2204
|
|
|
2205
|
If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth learning of all the concepts you've used in this guide and more. |
|
2206
|
|
|
2207
|
To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx). |