|
1
|
--- |
|
2
|
sidebar_label: "First-Purchase Discount" |
|
3
|
tags: |
|
4
|
- name: cart |
|
5
|
label: "Implement First-Purchase Discount" |
|
6
|
- server |
|
7
|
- nextjs |
|
8
|
- tutorial |
|
9
|
- name: customer |
|
10
|
label: "Implement First-Purchase Discount" |
|
11
|
- name: promotion |
|
12
|
label: "Implement First-Purchase Discount" |
|
13
|
products: |
|
14
|
- cart |
|
15
|
- customer |
|
16
|
- promotion |
|
17
|
--- |
|
18
|
|
|
19
|
import { Github } from "@medusajs/icons" |
|
20
|
import { Prerequisites, WorkflowDiagram, CardList } from "docs-ui" |
|
21
|
|
|
22
|
export const metadata = { |
|
23
|
title: `Implement First-Purchase Discount in Medusa`, |
|
24
|
} |
|
25
|
|
|
26
|
# {metadata.title} |
|
27
|
|
|
28
|
In this tutorial, you'll learn how to implement first-purchase discounts in Medusa. |
|
29
|
|
|
30
|
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 promotion and cart management features. |
|
31
|
|
|
32
|
The first-purchase discount feature encourages customers to sign up and make their first purchase by offering them a discount. In this tutorial, you'll learn how to implement this feature in Medusa. |
|
33
|
|
|
34
|
## Summary |
|
35
|
|
|
36
|
By following this tutorial, you'll learn how to: |
|
37
|
|
|
38
|
- Install and set up Medusa. |
|
39
|
- Apply a first-purchase discount to a customer's cart if they are a first-time customer. |
|
40
|
- Add custom validation to ensure the discount is only used by first-time customers. |
|
41
|
- Customize the Next.js Starter Storefront to display a pop-up encouraging first-time customers to sign up and receive a discount. |
|
42
|
|
|
43
|
You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer. |
|
44
|
|
|
45
|
 |
|
46
|
|
|
47
|
<Card |
|
48
|
title="View on Github" |
|
49
|
icon={Github} |
|
50
|
href="https://github.com/medusajs/examples/tree/main/first-purchase-discount" |
|
51
|
text="Find the full code for this tutorial." |
|
52
|
/> |
|
53
|
|
|
54
|
--- |
|
55
|
|
|
56
|
## Step 1: Install a Medusa Application |
|
57
|
|
|
58
|
<Prerequisites items={[ |
|
59
|
{ |
|
60
|
text: "Node.js v20.19.0+ or v22.12.0+", |
|
61
|
link: "https://nodejs.org/en/download" |
|
62
|
}, |
|
63
|
{ |
|
64
|
text: "Git CLI tool", |
|
65
|
link: "https://git-scm.com/downloads" |
|
66
|
}, |
|
67
|
{ |
|
68
|
text: "PostgreSQL", |
|
69
|
link: "https://www.postgresql.org/download/" |
|
70
|
} |
|
71
|
]} /> |
|
72
|
|
|
73
|
Start by installing the Medusa application on your machine with the following command: |
|
74
|
|
|
75
|
```bash npx2yarnExec |
|
76
|
npx create-medusa-app@latest |
|
77
|
``` |
|
78
|
|
|
79
|
First, you'll be asked for the project's name. Then, when prompted about installing the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose "Yes." |
|
80
|
|
|
81
|
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. |
|
82
|
|
|
83
|
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. |
|
84
|
|
|
85
|
<Note title="Ran into Errors?"> |
|
86
|
|
|
87
|
Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help. |
|
88
|
|
|
89
|
</Note> |
|
90
|
|
|
91
|
<Note> |
|
92
|
|
|
93
|
In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project. |
|
94
|
|
|
95
|
</Note> |
|
96
|
|
|
97
|
--- |
|
98
|
|
|
99
|
## Step 2: Create a First-Purchase Promotion |
|
100
|
|
|
101
|
Before you apply the first-purchase discount or promotion to a customer's cart, you need to create the promotion that will be applied. |
|
102
|
|
|
103
|
Start your Medusa application with the following command: |
|
104
|
|
|
105
|
```bash npm2yarn |
|
106
|
npm run dev |
|
107
|
``` |
|
108
|
|
|
109
|
Then, open the Medusa Admin dashboard at `http://localhost:9000/app` and log in with the user you created in the previous step. |
|
110
|
|
|
111
|
Next, click on the "Promotions" tab in the left sidebar, then click on the "Create Promotion" button to create a new promotion. |
|
112
|
|
|
113
|
You can customize the promotion based on your use case. For example, it can be a `10%` off the entire order, or a fixed amount off specific items. |
|
114
|
|
|
115
|
Make sure to set the promotion's code to `FIRST_PURCHASE`, as you'll be using this code in your Medusa customization. If you want to use a different code, make sure to update the code in the next steps accordingly. |
|
116
|
|
|
117
|
<Note title="Need help?"> |
|
118
|
|
|
119
|
Refer to the [Create Promotions User Guide](!user-guide!/promotions/create) to learn how to create promotions in Medusa. |
|
120
|
|
|
121
|
</Note> |
|
122
|
|
|
123
|
Once you create and publish the promotion, you can proceed to the next steps. |
|
124
|
|
|
125
|
 |
|
126
|
|
|
127
|
--- |
|
128
|
|
|
129
|
## Step 3: Apply the First-Purchase Discount to Cart |
|
130
|
|
|
131
|
In this step, you'll customize the Medusa application to automatically apply the first-purchase promotion to a cart. |
|
132
|
|
|
133
|
To build this feature, you need to: |
|
134
|
|
|
135
|
- Create a [workflow](!docs!/learn/fundamentals/workflows) that implements the logic to apply the first-purchase promotion to a cart. |
|
136
|
- Execute the workflow in a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that is triggered when a cart is created, or when it's transferred to a customer. |
|
137
|
|
|
138
|
### a. Store the First-Purchase Promotion Code |
|
139
|
|
|
140
|
Since you'll refer to the first-purchase promotion code in multiple places, it's a good idea to store it as a constant in your Medusa application. |
|
141
|
|
|
142
|
So, create the file `src/constants.ts` with the following content: |
|
143
|
|
|
144
|
```ts title="src/constants.ts" |
|
145
|
export const FIRST_PURCHASE_PROMOTION_CODE = "FIRST_PURCHASE" |
|
146
|
``` |
|
147
|
|
|
148
|
You'll reference this constant in the next steps. |
|
149
|
|
|
150
|
### b. Create the Workflow |
|
151
|
|
|
152
|
Next, you'll create the workflow that implements the logic to apply the first-purchase promotion to a cart. |
|
153
|
|
|
154
|
A [workflow](!docs!/learn/fundamentals/workflows) is a series of actions, called steps, that complete a task with rollback and retry mechanisms. In Medusa, you build commerce features in workflows, then execute them in other customizations, such as subscribers, scheduled jobs, and API routes. |
|
155
|
|
|
156
|
The workflow you'll build will have the following steps: |
|
157
|
|
|
158
|
<WorkflowDiagram |
|
159
|
workflow={{ |
|
160
|
name: "applyFirstPurchasePromoWorkflow", |
|
161
|
steps: [ |
|
162
|
{ |
|
163
|
type: "step", |
|
164
|
name: "useQueryGraphStep", |
|
165
|
description: "Retrieve the cart's details, including its promotions and customer.", |
|
166
|
depth: 1, |
|
167
|
link: "/references/helper-steps/useQueryGraphStep" |
|
168
|
}, |
|
169
|
{ |
|
170
|
type: "step", |
|
171
|
name: "useQueryGraphStep", |
|
172
|
description: "Retrieve the details of the first-purchase promotion.", |
|
173
|
depth: 2, |
|
174
|
link: "/references/helper-steps/useQueryGraphStep" |
|
175
|
}, |
|
176
|
{ |
|
177
|
type: "when", |
|
178
|
steps: [ |
|
179
|
{ |
|
180
|
type: "step", |
|
181
|
name: "updateCartPromotionsStep", |
|
182
|
description: "Add the first-purchase promotion to the cart if the customer is a first-time customer.", |
|
183
|
path: "/references/medusa-workflows/steps/updateCartPromotionsStep", |
|
184
|
} |
|
185
|
], |
|
186
|
depth: 3 |
|
187
|
}, |
|
188
|
{ |
|
189
|
type: "step", |
|
190
|
name: "useQueryGraphStep", |
|
191
|
description: "Retrieve the updated cart's details, including its promotions.", |
|
192
|
depth: 4, |
|
193
|
link: "/references/helper-steps/useQueryGraphStep" |
|
194
|
} |
|
195
|
] |
|
196
|
}} |
|
197
|
/> |
|
198
|
|
|
199
|
Medusa provides all these steps in its `@medusajs/medusa/core-flows` package, so you can implement the workflow right away. |
|
200
|
|
|
201
|
To create the workflow, create the file `src/workflows/apply-first-purchase-promo.ts` with the following content: |
|
202
|
|
|
203
|
export const workflowHighlights = [ |
|
204
|
["7", "cart_id", "Receive cart ID as input."], |
|
205
|
["13", "carts", "Retrieve the cart's details."], |
|
206
|
["21", "promotions", "Retrieve the first-purchase promotion's details."], |
|
207
|
["29", "when", "Check if the first-purchase promotion can be applied."], |
|
208
|
["39", "updateCartPromotionsStep", "Add the first-purchase promotion to the cart."], |
|
209
|
["47", "updatedCarts", "Retrieve the updated cart's details."], |
|
210
|
["55", "WorkflowResponse", "Return the updated cart's details."] |
|
211
|
] |
|
212
|
|
|
213
|
```ts title="src/workflows/apply-first-purchase-promo.ts" highlights={workflowHighlights} |
|
214
|
import { createWorkflow, when, WorkflowResponse } from "@medusajs/framework/workflows-sdk" |
|
215
|
import { updateCartPromotionsStep, useQueryGraphStep } from "@medusajs/medusa/core-flows" |
|
216
|
import { FIRST_PURCHASE_PROMOTION_CODE } from "../constants" |
|
217
|
import { PromotionActions } from "@medusajs/framework/utils" |
|
218
|
|
|
219
|
type WorkflowInput = { |
|
220
|
cart_id: string |
|
221
|
} |
|
222
|
|
|
223
|
export const applyFirstPurchasePromoWorkflow = createWorkflow( |
|
224
|
"apply-first-purchase-promo", |
|
225
|
(input: WorkflowInput) => { |
|
226
|
const { data: carts } = useQueryGraphStep({ |
|
227
|
entity: "cart", |
|
228
|
fields: ["promotions.*", "customer.*", "customer.orders.*"], |
|
229
|
filters: { |
|
230
|
id: input.cart_id, |
|
231
|
}, |
|
232
|
}) |
|
233
|
|
|
234
|
const { data: promotions } = useQueryGraphStep({ |
|
235
|
entity: "promotion", |
|
236
|
fields: ["code"], |
|
237
|
filters: { |
|
238
|
code: FIRST_PURCHASE_PROMOTION_CODE, |
|
239
|
}, |
|
240
|
}).config({ name: "retrieve-promotions" }) |
|
241
|
|
|
242
|
when({ |
|
243
|
carts, |
|
244
|
promotions, |
|
245
|
}, (data) => { |
|
246
|
return data.promotions.length > 0 && |
|
247
|
!data.carts[0].promotions?.some((promo) => promo?.id === data.promotions[0].id) && |
|
248
|
data.carts[0].customer !== null && |
|
249
|
data.carts[0].customer.orders?.length === 0 |
|
250
|
}) |
|
251
|
.then(() => { |
|
252
|
updateCartPromotionsStep({ |
|
253
|
id: carts[0].id, |
|
254
|
promo_codes: [promotions[0].code!], |
|
255
|
action: PromotionActions.ADD, |
|
256
|
}) |
|
257
|
}) |
|
258
|
|
|
259
|
// retrieve updated cart |
|
260
|
const { data: updatedCarts } = useQueryGraphStep({ |
|
261
|
entity: "cart", |
|
262
|
fields: ["*", "promotions.*"], |
|
263
|
filters: { |
|
264
|
id: input.cart_id, |
|
265
|
}, |
|
266
|
}).config({ name: "retrieve-updated-cart" }) |
|
267
|
|
|
268
|
return new WorkflowResponse(updatedCarts[0]) |
|
269
|
} |
|
270
|
) |
|
271
|
``` |
|
272
|
|
|
273
|
You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter. |
|
274
|
|
|
275
|
`createWorkflow` accepts as a second parameter a constructor function, which is the workflow's implementation. The function accepts as an input an object with the ID of the cart to apply the first-purchase promotion to. |
|
276
|
|
|
277
|
In the workflow's constructor function, you: |
|
278
|
|
|
279
|
- Retrieve the cart's details, including its promotions and customer, using the [useQueryGraphStep](/references/helper-steps/useQueryGraphStep). |
|
280
|
- Retrieve the details of the first-purchase promotion using the `useQueryGraphStep`. |
|
281
|
- You pass the `FIRST_PURCHASE_PROMOTION_CODE` constant to the `filters` option to retrieve the promotion. |
|
282
|
- Use the [when-then](!docs!/learn/fundamentals/workflows/conditions) utility to only apply the promotion if the first-purchase promotion exists, the cart doesn't have the promotion, and the customer doesn't have any orders. `when` receives two parameters: |
|
283
|
- An object to use in the condition function. |
|
284
|
- A condition function that receives the first parameter object and returns a boolean indicating whether to execute the steps in the `then` block. |
|
285
|
- Retrieve the updated cart's details, including its promotions, using the `useQueryGraphStep` again. |
|
286
|
|
|
287
|
Finally, you return a `WorkflowResponse` with the updated cart's details. |
|
288
|
|
|
289
|
<Note title="Why use when-then?"> |
|
290
|
|
|
291
|
You can't perform data manipulation in a workflow's constructor function. Instead, the Workflows SDK includes utility functions like `when` to perform typical operations that require accessing data values. Learn more about workflow constraints in the [Workflow Constraints](!docs!/learn/fundamentals/workflows/constructor-constraints) documentation. |
|
292
|
|
|
293
|
</Note> |
|
294
|
|
|
295
|
### c. Create the Subscriber |
|
296
|
|
|
297
|
Next, you'll create a subscriber that executes the workflow when a cart is created or transferred to a customer. |
|
298
|
|
|
299
|
<Note title="Tip"> |
|
300
|
|
|
301
|
A cart can be transferred to a customer when they sign up or log in, or in B2B use cases. |
|
302
|
|
|
303
|
</Note> |
|
304
|
|
|
305
|
A [subscriber](!docs!/learn/fundamentals/events-and-subscribers) is an asynchronous function that listens to events to perform a task. In this case, you'll create a subscriber that listens to the `cart.created` and `cart.customer_transferred` events to execute the workflow. |
|
306
|
|
|
307
|
To create the subscriber, create the file `src/subscribers/apply-first-purchase.ts` with the following content: |
|
308
|
|
|
309
|
```ts title="src/subscribers/apply-first-purchase.ts" |
|
310
|
import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework" |
|
311
|
import { applyFirstPurchasePromoWorkflow } from "../workflows/apply-first-purchase-promo" |
|
312
|
|
|
313
|
export default async function cartCreatedHandler({ |
|
314
|
event: { data }, |
|
315
|
container, |
|
316
|
}: SubscriberArgs<{ |
|
317
|
id: string |
|
318
|
}>) { |
|
319
|
await applyFirstPurchasePromoWorkflow(container) |
|
320
|
.run({ |
|
321
|
input: { |
|
322
|
cart_id: data.id, |
|
323
|
}, |
|
324
|
}) |
|
325
|
} |
|
326
|
|
|
327
|
export const config: SubscriberConfig = { |
|
328
|
event: ["cart.created", "cart.customer_transferred"], |
|
329
|
} |
|
330
|
``` |
|
331
|
|
|
332
|
A subscriber file must export: |
|
333
|
|
|
334
|
1. An asynchronous function, which is the subscriber that is executed when the event is emitted. |
|
335
|
2. A configuration object that holds the names of the events the subscriber listens to, which are `cart.created` and `cart.customer_transferred` in this case. |
|
336
|
|
|
337
|
The subscriber function receives an object as a parameter that has a `container` property, which is the [Medusa container](!docs!/learn/fundamentals/medusa-container). The Medusa container holds Framework and commerce tools that you can resolve and use in your customizations. |
|
338
|
|
|
339
|
In the subscriber function, you execute the `applyFirstPurchasePromoWorkflow` by invoking it, passing it the Medusa container, then calling its `run` method. You pass the `cart_id` from the event payload as an input to the workflow. |
|
340
|
|
|
341
|
### Test it Out |
|
342
|
|
|
343
|
You can now test the automatic application of the first-purchase promotion to a cart. To do that, you'll use the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) you installed in the first step. |
|
344
|
|
|
345
|
<Note title="Reminder" forceMultiline> |
|
346
|
|
|
347
|
The Next.js Starter Storefront is available in the `apps/storefront` directory of your project: |
|
348
|
|
|
349
|
```bash |
|
350
|
cd apps/storefront |
|
351
|
``` |
|
352
|
|
|
353
|
</Note> |
|
354
|
|
|
355
|
First, start the Medusa application with the following command: |
|
356
|
|
|
357
|
```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green" |
|
358
|
npm run dev |
|
359
|
``` |
|
360
|
|
|
361
|
Then, start the Next.js Starter Storefront with the following command: |
|
362
|
|
|
363
|
```bash npm2yarn badgeLabel="Storefront" badgeColor="blue" |
|
364
|
npm run dev |
|
365
|
``` |
|
366
|
|
|
367
|
The storefront will run at `http://localhost:8000`. Open it in your browser and click on Account at the top right to register. |
|
368
|
|
|
369
|
After you register, add a product to the cart, then go to the cart page. You'll find that the `FIRST_PURCHASE` promotion has been applied to the cart automatically. |
|
370
|
|
|
371
|
 |
|
372
|
|
|
373
|
--- |
|
374
|
|
|
375
|
## Step 4: Validate First-Purchase Discount Usage |
|
376
|
|
|
377
|
You now automatically apply the first-purchase promotion to a cart, but any customer can use the promotion code at the moment. |
|
378
|
|
|
379
|
So, you need to add custom validation to ensure that the first-purchase promotion is only used by first-time customers. |
|
380
|
|
|
381
|
In this step, you'll customize Medusa's existing workflows to validate the first-purchase promotion usage. You can do that by consuming the [workflows' 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. |
|
382
|
|
|
383
|
You'll consume the hooks of the following workflows: |
|
384
|
|
|
385
|
- [updateCartPromotionsWorkflow](/references/medusa-workflows/updateCartPromotionsWorkflow): This workflow is used to add or remove promotions from a cart. You'll check that the customer is a first-time customer before allowing the promotion to be added. |
|
386
|
- [completeCartWorkflow](/references/medusa-workflows/completeCartWorkflow): This workflow is used to complete a cart and place an order. You'll validate that the first-purchase promotion is only used by first-time customers before allowing the order to be placed. |
|
387
|
|
|
388
|
### a. Consume `updateCartPromotionsWorkflow.validate` Hook |
|
389
|
|
|
390
|
You'll start by consuming the `validate` hook of the `updateCartPromotionsWorkflow`. This hook is called before any operations are performed in the workflow. |
|
391
|
|
|
392
|
To consume the hook, create the file `src/workflows/hooks/validate-promotion.ts` with the following content: |
|
393
|
|
|
394
|
export const validatePromotionHighlights = [ |
|
395
|
["12", "hasFirstPurchasePromo", "Check if the first-purchase promotion is being applied."], |
|
396
|
["20", "", "Throw an error if the cart isn't associated with a customer."], |
|
397
|
["30", "customer", "Retrieve the customer associated with the cart."], |
|
398
|
["38", "", "Throw an error if the customer doesn't have an account or has previous orders."], |
|
399
|
] |
|
400
|
|
|
401
|
```ts title="src/workflows/hooks/validate-promotion.ts" highlights={validatePromotionHighlights} |
|
402
|
import { |
|
403
|
updateCartPromotionsWorkflow, |
|
404
|
} from "@medusajs/medusa/core-flows" |
|
405
|
import { FIRST_PURCHASE_PROMOTION_CODE } from "../../constants" |
|
406
|
import { |
|
407
|
MedusaError, |
|
408
|
ContainerRegistrationKeys, |
|
409
|
} from "@medusajs/framework/utils" |
|
410
|
|
|
411
|
updateCartPromotionsWorkflow.hooks.validate( |
|
412
|
(async ({ input, cart }, { container }) => { |
|
413
|
const hasFirstPurchasePromo = input.promo_codes?.some( |
|
414
|
(code) => code === FIRST_PURCHASE_PROMOTION_CODE |
|
415
|
) |
|
416
|
|
|
417
|
if (!hasFirstPurchasePromo) { |
|
418
|
return |
|
419
|
} |
|
420
|
|
|
421
|
if (!cart.customer_id) { |
|
422
|
throw new MedusaError( |
|
423
|
MedusaError.Types.INVALID_DATA, |
|
424
|
"First purchase discount can only be applied to carts with a customer" |
|
425
|
) |
|
426
|
} |
|
427
|
const query = container.resolve( |
|
428
|
ContainerRegistrationKeys.QUERY |
|
429
|
) |
|
430
|
|
|
431
|
const { data: [customer] } = await query.graph({ |
|
432
|
entity: "customer", |
|
433
|
fields: ["orders.*", "has_account"], |
|
434
|
filters: { |
|
435
|
id: cart.customer_id, |
|
436
|
}, |
|
437
|
}) |
|
438
|
|
|
439
|
if (!customer.has_account || (customer?.orders?.length || 0) > 0) { |
|
440
|
throw new MedusaError( |
|
441
|
MedusaError.Types.INVALID_DATA, |
|
442
|
"First purchase discount can only be applied to carts with no previous orders" |
|
443
|
) |
|
444
|
} |
|
445
|
}) |
|
446
|
) |
|
447
|
``` |
|
448
|
|
|
449
|
You consume a workflow's hook by calling the `hooks` property of the workflow, then calling the hook you want to consume. In this case, you call the `validate` hook of the `updateCartPromotionsWorkflow`. |
|
450
|
|
|
451
|
The `validate` hook receives a step function as a parameter. The function receives two parameters: |
|
452
|
|
|
453
|
- The hook's input, which differs based on the workflow. In this case, it receives the following properties: |
|
454
|
- `input`: The input of the `updateCartPromotionsWorkflow`, which includes the `promo_codes` to add or remove from the cart. |
|
455
|
- `cart`: The cart being updated. |
|
456
|
- The hook or step context object. Most notably, it has a `container` property, which is the Medusa container. |
|
457
|
|
|
458
|
In the step function, you check if the `FIRST_PURCHASE_PROMOTION_CODE` is being applied to the cart. If so, you validate that: |
|
459
|
|
|
460
|
- The cart is associated with a customer. |
|
461
|
- The customer has an account. |
|
462
|
- The customer has no previous orders. |
|
463
|
|
|
464
|
If any of these validations fail, you throw a `MedusaError` with the appropriate error message. This will prevent the promotion from being applied to the cart. |
|
465
|
|
|
466
|
<Note title="Tip"> |
|
467
|
|
|
468
|
To retrieve the customer's details, you use [Query](!docs!/learn/fundamentals/query). Query allows you to retrieve data across modules in your Medusa application. |
|
469
|
|
|
470
|
</Note> |
|
471
|
|
|
472
|
### b. Consume `completeCartWorkflow.validate` Hook |
|
473
|
|
|
474
|
Next, you'll consume the `validate` hook of the `completeCartWorkflow`. This workflow is used to complete a cart and place an order. You'll validate that the first-purchase promotion is only used by first-time customers before allowing the order to be placed. |
|
475
|
|
|
476
|
In the same `src/workflows/hooks/validate-promotion.ts` file, add the following import at the top of the file: |
|
477
|
|
|
478
|
```ts title="src/workflows/hooks/validate-promotion.ts" |
|
479
|
import { |
|
480
|
completeCartWorkflow, |
|
481
|
} from "@medusajs/medusa/core-flows" |
|
482
|
``` |
|
483
|
|
|
484
|
Then, consume the hook at the end of the file: |
|
485
|
|
|
486
|
export const validateCartCompletionHighlights = [ |
|
487
|
["3", "hasFirstPurchasePromo", "Check if the first-purchase promotion is being applied."], |
|
488
|
["11", "", "Throw an error if the cart isn't associated with a customer."], |
|
489
|
["22", "customer", "Retrieve the customer associated with the cart."], |
|
490
|
["30", "", "Throw an error if the customer doesn't have an account or has previous orders."], |
|
491
|
] |
|
492
|
|
|
493
|
```ts title="src/workflows/hooks/validate-promotion.ts" highlights={validateCartCompletionHighlights} |
|
494
|
completeCartWorkflow.hooks.validate( |
|
495
|
(async ({ input, cart }, { container }) => { |
|
496
|
const hasFirstPurchasePromo = cart.promotions?.some( |
|
497
|
(promo) => promo?.code === FIRST_PURCHASE_PROMOTION_CODE |
|
498
|
) |
|
499
|
|
|
500
|
if (!hasFirstPurchasePromo) { |
|
501
|
return |
|
502
|
} |
|
503
|
|
|
504
|
if (!cart.customer_id) { |
|
505
|
throw new MedusaError( |
|
506
|
MedusaError.Types.INVALID_DATA, |
|
507
|
"First purchase discount can only be applied to carts with a customer" |
|
508
|
) |
|
509
|
} |
|
510
|
|
|
511
|
const query = container.resolve( |
|
512
|
ContainerRegistrationKeys.QUERY |
|
513
|
) |
|
514
|
|
|
515
|
const { data: [customer] } = await query.graph({ |
|
516
|
entity: "customer", |
|
517
|
fields: ["orders.*", "has_account"], |
|
518
|
filters: { |
|
519
|
id: cart.customer_id, |
|
520
|
}, |
|
521
|
}) |
|
522
|
|
|
523
|
if (!customer.has_account || (customer?.orders?.length || 0) > 0) { |
|
524
|
throw new MedusaError( |
|
525
|
MedusaError.Types.INVALID_DATA, |
|
526
|
"First purchase discount can only be applied to carts with no previous orders" |
|
527
|
) |
|
528
|
} |
|
529
|
}) |
|
530
|
) |
|
531
|
``` |
|
532
|
|
|
533
|
You consume the `validate` hook of the `completeCartWorkflow` in the same way as the previous hook. The step function receives the cart being completed as an input. |
|
534
|
|
|
535
|
In the step function, you check if the `FIRST_PURCHASE_PROMOTION_CODE` is applied to the cart. If so, you validate that: |
|
536
|
|
|
537
|
- The cart is associated with a customer. |
|
538
|
- The customer has an account. |
|
539
|
- The customer has no previous orders. |
|
540
|
|
|
541
|
If any of these validations fail, you throw a `MedusaError` with the appropriate error message. This will prevent the order from being placed if the first-purchase promotion is used by a customer who is not a first-time customer. |
|
542
|
|
|
543
|
### Test it Out |
|
544
|
|
|
545
|
To test the custom validation, start the Medusa application and the Next.js Starter Storefront as you did in the previous steps. |
|
546
|
|
|
547
|
Then, register a new customer in the storefront, and place an order. The first-purchase promotion will be applied to the cart automatically and the order will be placed successfully. |
|
548
|
|
|
549
|
Try to place another order with the same customer. The first-purchase promotion will not be automatically applied to the cart. If you also try to apply the first-purchase promotion manually, you'll receive an error message indicating that the promotion can only be applied to first-time customers. |
|
550
|
|
|
551
|
--- |
|
552
|
|
|
553
|
## Step 5: Show Discount Pop-Up in Storefront |
|
554
|
|
|
555
|
The first-time purchase promotion is now fully functional. However, you need to inform first-time customers about the discount and encourage them to sign up. |
|
556
|
|
|
557
|
To do that, you'll customize the Next.js Starter Storefront to show a pop-up when a first-time customer visits the storefront. |
|
558
|
|
|
559
|
### a. Create the Pop-Up Component |
|
560
|
|
|
561
|
You'll first create the pop-up component that will be displayed to first-time customers. |
|
562
|
|
|
563
|
Create the file `src/modules/common/components/discount-popup/index.tsx` with the following content: |
|
564
|
|
|
565
|
```tsx title="src/modules/common/components/discount-popup/index.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
566
|
"use client" |
|
567
|
|
|
568
|
import { Button, Heading, Text } from "@medusajs/ui" |
|
569
|
import Modal from "@modules/common/components/modal" |
|
570
|
import useToggleState from "@lib/hooks/use-toggle-state" |
|
571
|
import { useEffect } from "react" |
|
572
|
import LocalizedClientLink from "@modules/common/components/localized-client-link" |
|
573
|
|
|
574
|
const DISCOUNT_POPUP_KEY = "discount_popup_shown" |
|
575
|
|
|
576
|
const DiscountPopup = () => { |
|
577
|
const { state, open, close } = useToggleState(false) |
|
578
|
|
|
579
|
useEffect(() => { |
|
580
|
// Check if the popup has been shown before |
|
581
|
const hasBeenShown = localStorage.getItem(DISCOUNT_POPUP_KEY) |
|
582
|
|
|
583
|
if (!hasBeenShown) { |
|
584
|
open() |
|
585
|
// Mark as shown |
|
586
|
localStorage.setItem(DISCOUNT_POPUP_KEY, "true") |
|
587
|
} |
|
588
|
}, [open]) |
|
589
|
|
|
590
|
return ( |
|
591
|
<Modal isOpen={state} close={close} size="small" data-testid="discount-popup"> |
|
592
|
<div className="relative overflow-hidden bg-gradient-to-br from-amber-50 to-amber-100 rounded-t-lg px-6 pt-8 pb-6"> |
|
593
|
{/* Decorative elements */} |
|
594
|
<div className="absolute top-0 right-0 w-20 h-20 bg-amber-200 rounded-full -mr-10 -mt-10 opacity-50"></div> |
|
595
|
<div className="absolute bottom-0 left-0 w-16 h-16 bg-amber-200 rounded-full -ml-8 -mb-8 opacity-40"></div> |
|
596
|
|
|
597
|
<div className="relative"> |
|
598
|
{/* Sale tag */} |
|
599
|
<div className="absolute -top-2 -right-2 bg-rose-500 text-white text-xs font-bold px-3 py-1 rounded-full transform rotate-12 shadow-md"> |
|
600
|
SAVE 10% |
|
601
|
</div> |
|
602
|
|
|
603
|
<Heading level="h2" className="text-2xl font-bold text-center text-amber-900"> |
|
604
|
Limited Time Offer! |
|
605
|
</Heading> |
|
606
|
|
|
607
|
<div className="flex justify-center my-4"> |
|
608
|
<div className="relative"> |
|
609
|
<div className="text-5xl font-bold text-rose-600">10%</div> |
|
610
|
<div className="text-lg font-semibold text-amber-900 mt-1">OFF YOUR FIRST ORDER</div> |
|
611
|
<div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-8xl text-amber-200 opacity-20 font-bold -z-10"> |
|
612
|
% |
|
613
|
</div> |
|
614
|
</div> |
|
615
|
</div> |
|
616
|
</div> |
|
617
|
</div> |
|
618
|
|
|
619
|
<Modal.Body> |
|
620
|
<div className="flex flex-col items-center gap-y-6 py-6 px-6 bg-white"> |
|
621
|
<Text className="text-center text-gray-700"> |
|
622
|
Sign up now to receive an exclusive 10% discount on your first purchase. Join our community of satisfied customers! |
|
623
|
</Text> |
|
624
|
|
|
625
|
<div className="flex flex-col gap-y-4 w-full"> |
|
626
|
<LocalizedClientLink href="/account" className="w-full"> |
|
627
|
<Button |
|
628
|
variant="primary" |
|
629
|
className="w-full h-12 font-semibold text-base shadow-md hover:shadow-lg transition-all" |
|
630
|
onClick={close} |
|
631
|
> |
|
632
|
Register & Save 10% |
|
633
|
</Button> |
|
634
|
</LocalizedClientLink> |
|
635
|
|
|
636
|
<Button |
|
637
|
variant="secondary" |
|
638
|
className="w-full h-10 font-medium" |
|
639
|
onClick={close} |
|
640
|
> |
|
641
|
Maybe Later |
|
642
|
</Button> |
|
643
|
</div> |
|
644
|
|
|
645
|
<div className="text-xs text-gray-400 text-center mt-2"> |
|
646
|
*Discount applies to your first order only |
|
647
|
</div> |
|
648
|
</div> |
|
649
|
</Modal.Body> |
|
650
|
</Modal> |
|
651
|
) |
|
652
|
} |
|
653
|
|
|
654
|
export default DiscountPopup |
|
655
|
``` |
|
656
|
|
|
657
|
This component uses the `Modal` component that is already available in the Next.js Starter Storefront. It displays a pop-up with a discount offer and two buttons: one to register and save the discount, and another to close the pop-up. |
|
658
|
|
|
659
|
The pop-up will only be shown to first-time customers. Once the pop-up is shown, a `discount_popup_shown` key is stored in the local storage to prevent it from being shown again. |
|
660
|
|
|
661
|
### b. Add the Pop-Up to Layout |
|
662
|
|
|
663
|
To ensure that the pop-up is displayed when the customer visits the storefront, you need to add the `DiscountPopup` component to the main layout of the Next.js Starter Storefront. |
|
664
|
|
|
665
|
In `src/app/[countryCode]/(main)/layout.tsx`, add the following import at the top of the file: |
|
666
|
|
|
667
|
```tsx title="src/app/[countryCode]/(main)/layout.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
668
|
import DiscountPopup from "@modules/common/components/discount-popup" |
|
669
|
``` |
|
670
|
|
|
671
|
Then, in the return statement of the `PageLayout` component, add the `DiscountPopup` component before rendering `props.children`: |
|
672
|
|
|
673
|
```tsx title="src/app/[countryCode]/(main)/layout.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
674
|
<> |
|
675
|
{/* ... */} |
|
676
|
{!customer && <DiscountPopup />} |
|
677
|
{props.children} |
|
678
|
{/* ... */} |
|
679
|
</> |
|
680
|
``` |
|
681
|
|
|
682
|
Notice that you only display the pop-up if the customer is not logged in. This way, the pop-up will only be shown to first-time customers. |
|
683
|
|
|
684
|
### c. Show Registration Form Before Login |
|
685
|
|
|
686
|
If you go to the `/account` page in the Next.js Starter Storefront as a guest customer, you'll see the login form. However, in this case, you want to show the registration form first instead. |
|
687
|
|
|
688
|
To change this behavior, in `src/modules/account/templates/login-template.tsx`, change the default value of `currentView` to `"register"`: |
|
689
|
|
|
690
|
```tsx title="src/modules/account/templates/login-template.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
691
|
const [currentView, setCurrentView] = useState("register") |
|
692
|
``` |
|
693
|
|
|
694
|
This way, when a guest customer visits the `/account` page, they will see the registration form instead of the login form. |
|
695
|
|
|
696
|
### Test it Out |
|
697
|
|
|
698
|
To test the pop-up, start the Medusa application and the Next.js Starter Storefront as you did in the previous steps. |
|
699
|
|
|
700
|
Then, open the storefront in your browser. If you're a first-time customer, you'll see the discount pop-up encouraging you to sign up and receive the first-purchase discount. |
|
701
|
|
|
702
|
<Note title="Tip"> |
|
703
|
|
|
704
|
If you don't see the pop-up, make sure that you're logged out. |
|
705
|
|
|
706
|
</Note> |
|
707
|
|
|
708
|
 |
|
709
|
|
|
710
|
--- |
|
711
|
|
|
712
|
## Next Steps |
|
713
|
|
|
714
|
You've now implemented the first-purchase discount feature in Medusa. You can add more features to build customer loyalty, such as a [loyalty points system](../loyalty-points/page.mdx) or [product reviews](../product-reviews/page.mdx). |
|
715
|
|
|
716
|
If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth understanding of all the concepts you've used in this guide and more. |
|
717
|
|
|
718
|
To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx). |
|
719
|
|
|
720
|
### Troubleshooting |
|
721
|
|
|
722
|
If you encounter issues during your development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx). |
|
723
|
|
|
724
|
### Getting Help |
|
725
|
|
|
726
|
If you encounter issues not covered in the troubleshooting guides: |
|
727
|
|
|
728
|
1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions. |
|
729
|
2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members. |