|
1
|
--- |
|
2
|
sidebar_label: "Extend Promotion" |
|
3
|
tags: |
|
4
|
- promotion |
|
5
|
- tutorial |
|
6
|
- extend module |
|
7
|
- server |
|
8
|
--- |
|
9
|
|
|
10
|
import { Prerequisites } from "docs-ui" |
|
11
|
|
|
12
|
export const metadata = { |
|
13
|
title: `Extend Promotion Data Model`, |
|
14
|
} |
|
15
|
|
|
16
|
# {metadata.title} |
|
17
|
|
|
18
|
In this documentation, you'll learn how to extend a data model of the Promotion Module to add a custom property. |
|
19
|
|
|
20
|
You'll create a `Custom` data model in a module. This data model will have a `custom_name` property, which is the property you want to add to the [Promotion data model](/references/promotion/models/Promotion) defined in the Promotion Module. |
|
21
|
|
|
22
|
You'll then learn how to: |
|
23
|
|
|
24
|
- Link the `Custom` data model to the `Promotion` data model. |
|
25
|
- Set the `custom_name` property when a promotion is created or updated using Medusa's API routes. |
|
26
|
- Retrieve the `custom_name` property with the promotion's details, in custom or existing API routes. |
|
27
|
|
|
28
|
<Note title="Tip"> |
|
29
|
|
|
30
|
Similar steps can be applied to the `Campaign` data model. |
|
31
|
|
|
32
|
</Note> |
|
33
|
|
|
34
|
## Step 1: Define Custom Data Model |
|
35
|
|
|
36
|
Consider you have a Hello Module defined in the `/src/modules/hello` directory. |
|
37
|
|
|
38
|
<Note title="Tip"> |
|
39
|
|
|
40
|
If you don't have a module, follow [this guide](!docs!/learn/fundamentals/modules) to create one. |
|
41
|
|
|
42
|
</Note> |
|
43
|
|
|
44
|
To add the `custom_name` property to the `Promotion` data model, you'll create in the Hello Module a data model that has the `custom_name` property. |
|
45
|
|
|
46
|
Create the file `src/modules/hello/models/custom.ts` with the following content: |
|
47
|
|
|
48
|
```ts title="src/modules/hello/models/custom.ts" |
|
49
|
import { model } from "@medusajs/framework/utils" |
|
50
|
|
|
51
|
export const Custom = model.define("custom", { |
|
52
|
id: model.id().primaryKey(), |
|
53
|
custom_name: model.text(), |
|
54
|
}) |
|
55
|
``` |
|
56
|
|
|
57
|
This creates a `Custom` data model that has the `id` and `custom_name` properties. |
|
58
|
|
|
59
|
<Note title="Tip"> |
|
60
|
|
|
61
|
Learn more about data models in [this guide](!docs!/learn/fundamentals/modules#1-create-data-model). |
|
62
|
|
|
63
|
</Note> |
|
64
|
|
|
65
|
--- |
|
66
|
|
|
67
|
## Step 2: Define Link to Promotion Data Model |
|
68
|
|
|
69
|
Next, you'll define a module link between the `Custom` and `Promotion` data model. A module link allows you to form a relation between two data models of separate modules while maintaining module isolation. |
|
70
|
|
|
71
|
<Note title="Tip"> |
|
72
|
|
|
73
|
Learn more about module links in [this guide](!docs!/learn/fundamentals/module-links). |
|
74
|
|
|
75
|
</Note> |
|
76
|
|
|
77
|
Create the file `src/links/promotion-custom.ts` with the following content: |
|
78
|
|
|
79
|
```ts title="src/links/promotion-custom.ts" |
|
80
|
import { defineLink } from "@medusajs/framework/utils" |
|
81
|
import HelloModule from "../modules/hello" |
|
82
|
import PromotionModule from "@medusajs/medusa/promotion" |
|
83
|
|
|
84
|
export default defineLink( |
|
85
|
PromotionModule.linkable.promotion, |
|
86
|
HelloModule.linkable.custom |
|
87
|
) |
|
88
|
``` |
|
89
|
|
|
90
|
This defines a link between the `Promotion` and `Custom` data models. Using this link, you'll later query data across the modules, and link records of each data model. |
|
91
|
|
|
92
|
--- |
|
93
|
|
|
94
|
## Step 3: Generate and Run Migrations |
|
95
|
|
|
96
|
<Prerequisites |
|
97
|
items={[ |
|
98
|
{ |
|
99
|
text: "Module must be registered in medusa-config.js", |
|
100
|
link: "!docs!/learn/fundamentals/modules#4-add-module-to-configurations" |
|
101
|
} |
|
102
|
]} |
|
103
|
/> |
|
104
|
|
|
105
|
To reflect the `Custom` data model in the database, generate a migration that defines the table to be created for it. |
|
106
|
|
|
107
|
Run the following command in your Medusa project's root: |
|
108
|
|
|
109
|
```bash npx2yarn |
|
110
|
npx medusa db:generate helloModuleService |
|
111
|
``` |
|
112
|
|
|
113
|
Where `helloModuleService` is your module's name. |
|
114
|
|
|
115
|
Then, run the `db:migrate` command to run the migrations and create a table in the database for the link between the `Promotion` and `Custom` data models: |
|
116
|
|
|
117
|
```bash npx2yarn |
|
118
|
npx medusa db:migrate |
|
119
|
``` |
|
120
|
|
|
121
|
A table for the link is now created in the database. You can now retrieve and manage the link between records of the data models. |
|
122
|
|
|
123
|
--- |
|
124
|
|
|
125
|
## Step 4: Consume promotionsCreated Workflow Hook |
|
126
|
|
|
127
|
When a promotion is created, you also want to create a `Custom` record and set the `custom_name` property, then create a link between the `Promotion` and `Custom` records. |
|
128
|
|
|
129
|
To do that, you'll consume the [promotionsCreated](/references/medusa-workflows/createPromotionsWorkflow#promotionsCreated) hook of the [createPromotionsWorkflow](/references/medusa-workflows/createPromotionsWorkflow). This workflow is executed in the [Create Promotion Admin API route](!api!/admin/promotions/create-promotion) |
|
130
|
|
|
131
|
<Note title="Tip"> |
|
132
|
|
|
133
|
Learn more about workflow hooks in [this guide](!docs!/learn/fundamentals/workflows/workflow-hooks). |
|
134
|
|
|
135
|
</Note> |
|
136
|
|
|
137
|
The API route accepts in its request body an `additional_data` parameter. You can pass in it custom data, which is passed to the workflow hook handler. |
|
138
|
|
|
139
|
### Add custom_name to Additional Data Validation |
|
140
|
|
|
141
|
To pass the `custom_name` in the `additional_data` parameter, you must add a validation rule that tells the Medusa application about this custom property. |
|
142
|
|
|
143
|
Create the file `src/api/middlewares.ts` with the following content: |
|
144
|
|
|
145
|
<Note> |
|
146
|
|
|
147
|
As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`. |
|
148
|
|
|
149
|
</Note> |
|
150
|
|
|
151
|
```ts title="src/api/middlewares.ts" |
|
152
|
import { defineMiddlewares } from "@medusajs/framework/http" |
|
153
|
import { z } from "@medusajs/framework/zod" |
|
154
|
|
|
155
|
export default defineMiddlewares({ |
|
156
|
routes: [ |
|
157
|
{ |
|
158
|
method: "POST", |
|
159
|
matcher: "/admin/promotions", |
|
160
|
additionalDataValidator: { |
|
161
|
custom_name: z.string().optional(), |
|
162
|
}, |
|
163
|
}, |
|
164
|
], |
|
165
|
}) |
|
166
|
``` |
|
167
|
|
|
168
|
The `additional_data` parameter validation is customized using `defineMiddlewares`. In the routes middleware configuration object, the `additionalDataValidator` property accepts [Zod](https://zod.dev/) validation rules. |
|
169
|
|
|
170
|
In the snippet above, you add a validation rule indicating that `custom_name` is a string that can be passed in the `additional_data` object. |
|
171
|
|
|
172
|
<Note title="Tip"> |
|
173
|
|
|
174
|
Learn more about additional data validation in [this guide](!docs!/learn/fundamentals/api-routes/additional-data). |
|
175
|
|
|
176
|
</Note> |
|
177
|
|
|
178
|
### Create Workflow to Create Custom Record |
|
179
|
|
|
180
|
You'll now create a workflow that will be used in the hook handler. |
|
181
|
|
|
182
|
This workflow will create a `Custom` record, then link it to the promotion. |
|
183
|
|
|
184
|
Start by creating the step that creates the `Custom` record. Create the file `src/workflows/create-custom-from-promotion/steps/create-custom.ts` with the following content: |
|
185
|
|
|
186
|
```ts title="src/workflows/create-custom-from-promotion/steps/create-custom.ts" |
|
187
|
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk" |
|
188
|
import HelloModuleService from "../../../modules/hello/service" |
|
189
|
import { HELLO_MODULE } from "../../../modules/hello" |
|
190
|
|
|
191
|
type CreateCustomStepInput = { |
|
192
|
custom_name?: string |
|
193
|
} |
|
194
|
|
|
195
|
export const createCustomStep = createStep( |
|
196
|
"create-custom", |
|
197
|
async (data: CreateCustomStepInput, { container }) => { |
|
198
|
if (!data.custom_name) { |
|
199
|
return |
|
200
|
} |
|
201
|
|
|
202
|
const helloModuleService: HelloModuleService = container.resolve( |
|
203
|
HELLO_MODULE |
|
204
|
) |
|
205
|
|
|
206
|
const custom = await helloModuleService.createCustoms(data) |
|
207
|
|
|
208
|
return new StepResponse(custom, custom) |
|
209
|
}, |
|
210
|
async (custom, { container }) => { |
|
211
|
const helloModuleService: HelloModuleService = container.resolve( |
|
212
|
HELLO_MODULE |
|
213
|
) |
|
214
|
|
|
215
|
await helloModuleService.deleteCustoms(custom.id) |
|
216
|
} |
|
217
|
) |
|
218
|
``` |
|
219
|
|
|
220
|
In the step, you resolve the Hello Module's main service and create a `Custom` record. |
|
221
|
|
|
222
|
In the compensation function that undoes the step's actions in case of an error, you delete the created record. |
|
223
|
|
|
224
|
<Note title="Tip"> |
|
225
|
|
|
226
|
Learn more about compensation functions in [this guide](!docs!/learn/fundamentals/workflows/compensation-function). |
|
227
|
|
|
228
|
</Note> |
|
229
|
|
|
230
|
Then, create the workflow at `src/workflows/create-custom-from-promotion/index.ts` with the following content: |
|
231
|
|
|
232
|
```ts title="src/workflows/create-custom-from-promotion/index.ts" collapsibleLines="1-7" expandButtonLabel="Show Imports" |
|
233
|
import { createWorkflow, transform, when, WorkflowResponse } from "@medusajs/framework/workflows-sdk" |
|
234
|
import { PromotionDTO } from "@medusajs/framework/types" |
|
235
|
import { createRemoteLinkStep } from "@medusajs/medusa/core-flows" |
|
236
|
import { Modules } from "@medusajs/framework/utils" |
|
237
|
import { HELLO_MODULE } from "../../modules/hello" |
|
238
|
import { createCustomStep } from "./steps/create-custom" |
|
239
|
|
|
240
|
export type CreateCustomFromPromotionWorkflowInput = { |
|
241
|
promotion: PromotionDTO |
|
242
|
additional_data?: { |
|
243
|
custom_name?: string |
|
244
|
} |
|
245
|
} |
|
246
|
|
|
247
|
export const createCustomFromPromotionWorkflow = createWorkflow( |
|
248
|
"create-custom-from-promotion", |
|
249
|
(input: CreateCustomFromPromotionWorkflowInput) => { |
|
250
|
const customName = transform( |
|
251
|
{ |
|
252
|
input, |
|
253
|
}, |
|
254
|
(data) => data.input.additional_data.custom_name || "" |
|
255
|
) |
|
256
|
|
|
257
|
const custom = createCustomStep({ |
|
258
|
custom_name: customName, |
|
259
|
}) |
|
260
|
|
|
261
|
when(({ custom }), ({ custom }) => custom !== undefined) |
|
262
|
.then(() => { |
|
263
|
createRemoteLinkStep([{ |
|
264
|
[Modules.PROMOTION]: { |
|
265
|
promotion_id: input.promotion.id, |
|
266
|
}, |
|
267
|
[HELLO_MODULE]: { |
|
268
|
custom_id: custom.id, |
|
269
|
}, |
|
270
|
}]) |
|
271
|
}) |
|
272
|
|
|
273
|
return new WorkflowResponse({ |
|
274
|
custom, |
|
275
|
}) |
|
276
|
} |
|
277
|
) |
|
278
|
``` |
|
279
|
|
|
280
|
The workflow accepts as an input the created promotion and the `additional_data` parameter passed in the request. This is the same input that the `promotionsCreated` hook accepts. |
|
281
|
|
|
282
|
In the workflow, you: |
|
283
|
|
|
284
|
1. Use `transform` to get the value of `custom_name` based on whether it's set in `additional_data`. Learn more about why you can't use conditional operators in a workflow without using `transform` in [this guide](!docs!/learn/fundamentals/workflows/conditions#why-if-conditions-arent-allowed-in-workflows). |
|
285
|
2. Create the `Custom` record using the `createCustomStep`. |
|
286
|
3. Use `when-then` to link the promotion to the `Custom` record if it was created. Learn more about why you can't use if-then conditions in a workflow without using `when-then` in [this guide](!docs!/learn/fundamentals/workflows/conditions#why-if-conditions-arent-allowed-in-workflows). |
|
287
|
|
|
288
|
You'll next execute the workflow in the hook handler. |
|
289
|
|
|
290
|
### Consume Workflow Hook |
|
291
|
|
|
292
|
You can now consume the `promotionsCreated` hook, which is executed in the `createPromotionsWorkflow` after the promotion is created. |
|
293
|
|
|
294
|
To consume the hook, create the file `src/workflow/hooks/promotion-created.ts` with the following content: |
|
295
|
|
|
296
|
```ts title="src/workflow/hooks/promotion-created.ts" collapsibleLines="1-6" expandButtonLabel="Show Imports" |
|
297
|
import { createPromotionsWorkflow } from "@medusajs/medusa/core-flows" |
|
298
|
import { |
|
299
|
createCustomFromPromotionWorkflow, |
|
300
|
CreateCustomFromPromotionWorkflowInput, |
|
301
|
} from "../create-custom-from-promotion" |
|
302
|
|
|
303
|
createPromotionsWorkflow.hooks.promotionsCreated( |
|
304
|
async ({ promotions, additional_data }, { container }) => { |
|
305
|
const workflow = createCustomFromPromotionWorkflow(container) |
|
306
|
|
|
307
|
for (const promotion of promotions) { |
|
308
|
await workflow.run({ |
|
309
|
input: { |
|
310
|
promotion, |
|
311
|
additional_data, |
|
312
|
} as CreateCustomFromPromotionWorkflowInput, |
|
313
|
}) |
|
314
|
} |
|
315
|
} |
|
316
|
) |
|
317
|
``` |
|
318
|
|
|
319
|
The hook handler executes the `createPromotionsWorkflow`, passing it its input. |
|
320
|
|
|
321
|
### Test it Out |
|
322
|
|
|
323
|
To test it out, send a `POST` request to `/admin/promotions` to create a promotion, passing `custom_name` in `additional_data`: |
|
324
|
|
|
325
|
```bash |
|
326
|
curl --location 'localhost:9000/admin/promotions' \ |
|
327
|
-H 'Content-Type: application/json' \ |
|
328
|
-H 'Authorization: Bearer {token}' \ |
|
329
|
--data '{ |
|
330
|
"additional_data": { |
|
331
|
"custom_name": "test" |
|
332
|
}, |
|
333
|
"code": "50OFF", |
|
334
|
"type": "standard", |
|
335
|
"application_method": { |
|
336
|
"description": "My promotion", |
|
337
|
"value": 50, |
|
338
|
"currency_code": "usd", |
|
339
|
"max_quantity": 1, |
|
340
|
"type": "percentage", |
|
341
|
"target_type": "items", |
|
342
|
"apply_to_quantity": 0, |
|
343
|
"buy_rules_min_quantity": 1, |
|
344
|
"allocation": "each" |
|
345
|
} |
|
346
|
}' |
|
347
|
``` |
|
348
|
|
|
349
|
Make sure to replace `{token}` with an admin user's JWT token. Learn how to retrieve it in the [API reference](!api!/admin#1-bearer-authorization-with-jwt-tokens). |
|
350
|
|
|
351
|
The request will return the promotion's details. You'll learn how to retrieve the `custom_name` property with the promotion's details in the next section. |
|
352
|
|
|
353
|
--- |
|
354
|
|
|
355
|
## Step 5: Retrieve custom_name with Promotion Details |
|
356
|
|
|
357
|
When you extend an existing data model through links, you also want to retrieve the custom properties with the data model. |
|
358
|
|
|
359
|
### Retrieve in API Routes |
|
360
|
|
|
361
|
To retrieve the `custom_name` property when you're retrieving the promotion through API routes, such as the [Get Promotion API Route](!api!/admin/promotions/get-a-promotion), pass in the `fields` query parameter `+custom.*`, which retrieves the linked `Custom` record's details. |
|
362
|
|
|
363
|
<Note title="Tip"> |
|
364
|
|
|
365
|
The `+` prefix in `+custom.*` indicates that the relation should be retrieved with the default promotion fields. Learn more about selecting fields and relations in the [API reference](!api!/admin/select-fields-and-relations). |
|
366
|
|
|
367
|
</Note> |
|
368
|
|
|
369
|
For example: |
|
370
|
|
|
371
|
```bash |
|
372
|
curl 'localhost:9000/admin/promotions/{promotion_id}?fields=+custom.*' \ |
|
373
|
-H 'Authorization: Bearer {token}' |
|
374
|
``` |
|
375
|
|
|
376
|
Make sure to replace `{promotion_id}` with the promotion's ID, and `{token}` with an admin user's JWT token. |
|
377
|
|
|
378
|
Among the returned `promotion` object, you'll find a `custom` property which holds the details of the linked `Custom` record: |
|
379
|
|
|
380
|
```json |
|
381
|
{ |
|
382
|
"promotion": { |
|
383
|
// ... |
|
384
|
"custom": { |
|
385
|
"id": "01J9NP7ANXDZ0EAYF0956ZE1ZA", |
|
386
|
"custom_name": "test", |
|
387
|
"created_at": "2024-10-08T09:09:06.877Z", |
|
388
|
"updated_at": "2024-10-08T09:09:06.877Z", |
|
389
|
"deleted_at": null |
|
390
|
} |
|
391
|
} |
|
392
|
} |
|
393
|
``` |
|
394
|
|
|
395
|
### Retrieve in Store API Routes |
|
396
|
|
|
397
|
Medusa doesn't have a Store Promotion API route. A storefront retrieves a cart's promotions through the [Store Cart API routes](!api!/store/carts) instead. Those routes only return the fields in their allowed fields, and `promotions.custom` isn't one of them, so Medusa removes it from the response without an error. To retrieve it, add it to the route's allowed fields in `src/api/middlewares.ts`: |
|
398
|
|
|
399
|
```ts title="src/api/middlewares.ts" |
|
400
|
import { allowFields } from "@medusajs/framework/http" |
|
401
|
|
|
402
|
export default defineMiddlewares({ |
|
403
|
routes: [ |
|
404
|
// ... |
|
405
|
{ |
|
406
|
matcher: "/store/carts", |
|
407
|
middlewares: [allowFields("promotions.custom")], |
|
408
|
}, |
|
409
|
], |
|
410
|
}) |
|
411
|
``` |
|
412
|
|
|
413
|
<Note> |
|
414
|
|
|
415
|
`allowFields` is available since Medusa [v2.21.0](https://github.com/medusajs/medusa/releases/tag/v2.21.0). In earlier versions, write the middleware yourself, as explained in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields#how-to-override-allowed-fields-of-medusas-api-routes) documentation. |
|
416
|
|
|
417
|
</Note> |
|
418
|
|
|
419
|
You can then pass `+promotions.custom.*` in the `fields` query parameter of the Store Cart API routes. |
|
420
|
|
|
421
|
<Note title="Important"> |
|
422
|
|
|
423
|
The middleware must be global, so don't set a `method` property in the route object. Medusa runs a middleware scoped to a method after it validates the `fields` query parameter, so it has no effect. |
|
424
|
|
|
425
|
</Note> |
|
426
|
|
|
427
|
Learn more in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields) documentation. |
|
428
|
|
|
429
|
### Retrieve using Query |
|
430
|
|
|
431
|
You can also retrieve the `Custom` record linked to a promotion in your code using [Query](!docs!/learn/fundamentals/query). |
|
432
|
|
|
433
|
For example: |
|
434
|
|
|
435
|
```ts |
|
436
|
const { data: [promotion] } = await query.graph({ |
|
437
|
entity: "promotion", |
|
438
|
fields: ["*", "custom.*"], |
|
439
|
filters: { |
|
440
|
id: promotion_id, |
|
441
|
}, |
|
442
|
}) |
|
443
|
``` |
|
444
|
|
|
445
|
Learn more about how to use Query in [this guide](!docs!/learn/fundamentals/query). |
|
446
|
|
|
447
|
--- |
|
448
|
|
|
449
|
## Step 6: Consume promotionsUpdated Workflow Hook |
|
450
|
|
|
451
|
Similar to the `promotionsCreated` hook, you'll consume the [promotionsUpdated](/references/medusa-workflows/updatePromotionsWorkflow#promotionsUpdated) hook of the [updatePromotionsWorkflow](/references/medusa-workflows/updatePromotionsWorkflow) to update `custom_name` when the promotion is updated. |
|
452
|
|
|
453
|
The `updatePromotionsWorkflow` is executed by the [Update Promotion API route](!api!/admin/promotions/update-a-promotion), which accepts the `additional_data` parameter to pass custom data to the hook. |
|
454
|
|
|
455
|
### Add custom_name to Additional Data Validation |
|
456
|
|
|
457
|
To allow passing `custom_name` in the `additional_data` parameter of the update promotion route, add in `src/api/middlewares.ts` a new route middleware configuration object: |
|
458
|
|
|
459
|
<Note> |
|
460
|
|
|
461
|
As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`. |
|
462
|
|
|
463
|
</Note> |
|
464
|
|
|
465
|
```ts title="src/api/middlewares.ts" |
|
466
|
import { defineMiddlewares } from "@medusajs/framework/http" |
|
467
|
import { z } from "@medusajs/framework/zod" |
|
468
|
|
|
469
|
export default defineMiddlewares({ |
|
470
|
routes: [ |
|
471
|
// ... |
|
472
|
{ |
|
473
|
method: "POST", |
|
474
|
matcher: "/admin/promotions/:id", |
|
475
|
additionalDataValidator: { |
|
476
|
custom_name: z.string().nullish(), |
|
477
|
}, |
|
478
|
}, |
|
479
|
], |
|
480
|
}) |
|
481
|
``` |
|
482
|
|
|
483
|
The validation schema is the similar to that of the Create Promotion API route, except you can pass a `null` value for `custom_name` to remove or unset the `custom_name`'s value. |
|
484
|
|
|
485
|
### Create Workflow to Update Custom Record |
|
486
|
|
|
487
|
Next, you'll create a workflow that creates, updates, or deletes `Custom` records based on the provided `additional_data` parameter: |
|
488
|
|
|
489
|
1. If `additional_data.custom_name` is set and it's `null`, the `Custom` record linked to the promotion is deleted. |
|
490
|
2. If `additional_data.custom_name` is set and the promotion doesn't have a linked `Custom` record, a new record is created and linked to the promotion. |
|
491
|
3. If `additional_data.custom_name` is set and the promotion has a linked `Custom` record, the `custom_name` property of the `Custom` record is updated. |
|
492
|
|
|
493
|
Start by creating the step that updates a `Custom` record. Create the file `src/workflows/update-custom-from-promotion/steps/update-custom.ts` with the following content: |
|
494
|
|
|
495
|
```ts title="src/workflows/update-custom-from-promotion/steps/update-custom.ts" |
|
496
|
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk" |
|
497
|
import { HELLO_MODULE } from "../../../modules/hello" |
|
498
|
import HelloModuleService from "../../../modules/hello/service" |
|
499
|
|
|
500
|
type UpdateCustomStepInput = { |
|
501
|
id: string |
|
502
|
custom_name: string |
|
503
|
} |
|
504
|
|
|
505
|
export const updateCustomStep = createStep( |
|
506
|
"update-custom", |
|
507
|
async ({ id, custom_name }: UpdateCustomStepInput, { container }) => { |
|
508
|
const helloModuleService: HelloModuleService = container.resolve( |
|
509
|
HELLO_MODULE |
|
510
|
) |
|
511
|
|
|
512
|
const prevData = await helloModuleService.retrieveCustom(id) |
|
513
|
|
|
514
|
const custom = await helloModuleService.updateCustoms({ |
|
515
|
id, |
|
516
|
custom_name, |
|
517
|
}) |
|
518
|
|
|
519
|
return new StepResponse(custom, prevData) |
|
520
|
}, |
|
521
|
async (prevData, { container }) => { |
|
522
|
const helloModuleService: HelloModuleService = container.resolve( |
|
523
|
HELLO_MODULE |
|
524
|
) |
|
525
|
|
|
526
|
await helloModuleService.updateCustoms(prevData) |
|
527
|
} |
|
528
|
) |
|
529
|
``` |
|
530
|
|
|
531
|
In this step, you update a `Custom` record. In the compensation function, you revert the update. |
|
532
|
|
|
533
|
Next, you'll create the step that deletes a `Custom` record. Create the file `src/workflows/update-custom-from-promotion/steps/delete-custom.ts` with the following content: |
|
534
|
|
|
535
|
```ts title="src/workflows/update-custom-from-promotion/steps/delete-custom.ts" collapsibleLines="1-6" expandButtonLabel="Show Imports" |
|
536
|
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk" |
|
537
|
import { Custom } from "../../../modules/hello/models/custom" |
|
538
|
import { InferTypeOf } from "@medusajs/framework/types" |
|
539
|
import HelloModuleService from "../../../modules/hello/service" |
|
540
|
import { HELLO_MODULE } from "../../../modules/hello" |
|
541
|
|
|
542
|
type DeleteCustomStepInput = { |
|
543
|
custom: InferTypeOf<typeof Custom> |
|
544
|
} |
|
545
|
|
|
546
|
export const deleteCustomStep = createStep( |
|
547
|
"delete-custom", |
|
548
|
async ({ custom }: DeleteCustomStepInput, { container }) => { |
|
549
|
const helloModuleService: HelloModuleService = container.resolve( |
|
550
|
HELLO_MODULE |
|
551
|
) |
|
552
|
|
|
553
|
await helloModuleService.deleteCustoms(custom.id) |
|
554
|
|
|
555
|
return new StepResponse(custom, custom) |
|
556
|
}, |
|
557
|
async (custom, { container }) => { |
|
558
|
const helloModuleService: HelloModuleService = container.resolve( |
|
559
|
HELLO_MODULE |
|
560
|
) |
|
561
|
|
|
562
|
await helloModuleService.createCustoms(custom) |
|
563
|
} |
|
564
|
) |
|
565
|
``` |
|
566
|
|
|
567
|
In this step, you delete a `Custom` record. In the compensation function, you create it again. |
|
568
|
|
|
569
|
Finally, you'll create the workflow. Create the file `src/workflows/update-custom-from-promotion/index.ts` with the following content: |
|
570
|
|
|
571
|
```ts title="src/workflows/update-custom-from-promotion/index.ts" collapsibleLines="1-9" expandButtonLabel="Show Imports" |
|
572
|
import { PromotionDTO } from "@medusajs/framework/types" |
|
573
|
import { createWorkflow, when, WorkflowResponse } from "@medusajs/framework/workflows-sdk" |
|
574
|
import { createRemoteLinkStep, dismissRemoteLinkStep, useQueryGraphStep } from "@medusajs/medusa/core-flows" |
|
575
|
import { createCustomStep } from "../create-custom-from-cart/steps/create-custom" |
|
576
|
import { Modules } from "@medusajs/framework/utils" |
|
577
|
import { HELLO_MODULE } from "../../modules/hello" |
|
578
|
import { deleteCustomStep } from "./steps/delete-custom" |
|
579
|
import { updateCustomStep } from "./steps/update-custom" |
|
580
|
|
|
581
|
export type UpdateCustomFromPromotionStepInput = { |
|
582
|
promotion: PromotionDTO |
|
583
|
additional_data?: { |
|
584
|
custom_name?: string | null |
|
585
|
} |
|
586
|
} |
|
587
|
|
|
588
|
export const updateCustomFromPromotionWorkflow = createWorkflow( |
|
589
|
"update-custom-from-promotion", |
|
590
|
(input: UpdateCustomFromPromotionStepInput) => { |
|
591
|
const { data: promotions } = useQueryGraphStep({ |
|
592
|
entity: "promotion", |
|
593
|
fields: ["custom.*"], |
|
594
|
filters: { |
|
595
|
id: input.promotion.id, |
|
596
|
}, |
|
597
|
}) |
|
598
|
|
|
599
|
// TODO create, update, or delete Custom record |
|
600
|
} |
|
601
|
) |
|
602
|
``` |
|
603
|
|
|
604
|
The workflow accepts the same input as the `promotionsUpdated` workflow hook handler would. |
|
605
|
|
|
606
|
In the workflow, you retrieve the promotion's linked `Custom` record using Query. |
|
607
|
|
|
608
|
Next, replace the `TODO` with the following: |
|
609
|
|
|
610
|
```ts title="src/workflows/update-custom-from-promotion/index.ts" |
|
611
|
const created = when( |
|
612
|
"create-promotion-custom-link", |
|
613
|
{ |
|
614
|
input, |
|
615
|
promotions, |
|
616
|
}, (data) => |
|
617
|
!data.promotions[0].custom && |
|
618
|
data.input.additional_data?.custom_name?.length > 0 |
|
619
|
) |
|
620
|
.then(() => { |
|
621
|
const custom = createCustomStep({ |
|
622
|
custom_name: input.additional_data.custom_name, |
|
623
|
}) |
|
624
|
|
|
625
|
createRemoteLinkStep([{ |
|
626
|
[Modules.PROMOTION]: { |
|
627
|
promotion_id: input.promotion.id, |
|
628
|
}, |
|
629
|
[HELLO_MODULE]: { |
|
630
|
custom_id: custom.id, |
|
631
|
}, |
|
632
|
}]) |
|
633
|
|
|
634
|
return custom |
|
635
|
}) |
|
636
|
|
|
637
|
// TODO update, or delete Custom record |
|
638
|
``` |
|
639
|
|
|
640
|
Using `when-then`, you check if the promotion doesn't have a linked `Custom` record and the `custom_name` property is set. If so, you create a `Custom` record and link it to the promotion. |
|
641
|
|
|
642
|
To create the `Custom` record, you use the `createCustomStep` you created in an earlier section. |
|
643
|
|
|
644
|
Next, replace the new `TODO` with the following: |
|
645
|
|
|
646
|
```ts title="src/workflows/update-custom-from-promotion/index.ts" |
|
647
|
const deleted = when( |
|
648
|
"delete-promotion-custom-link", |
|
649
|
{ |
|
650
|
input, |
|
651
|
promotions, |
|
652
|
}, (data) => |
|
653
|
data.promotions[0].custom && ( |
|
654
|
data.input.additional_data?.custom_name === null || |
|
655
|
data.input.additional_data?.custom_name.length === 0 |
|
656
|
) |
|
657
|
) |
|
658
|
.then(() => { |
|
659
|
deleteCustomStep({ |
|
660
|
custom: promotions[0].custom, |
|
661
|
}) |
|
662
|
|
|
663
|
dismissRemoteLinkStep({ |
|
664
|
[HELLO_MODULE]: { |
|
665
|
custom_id: promotions[0].custom.id, |
|
666
|
}, |
|
667
|
}) |
|
668
|
|
|
669
|
return promotions[0].custom.id |
|
670
|
}) |
|
671
|
|
|
672
|
// TODO delete Custom record |
|
673
|
``` |
|
674
|
|
|
675
|
Using `when-then`, you check if the promotion has a linked `Custom` record and `custom_name` is `null` or an empty string. If so, you delete the linked `Custom` record and dismiss its links. |
|
676
|
|
|
677
|
Finally, replace the new `TODO` with the following: |
|
678
|
|
|
679
|
```ts title="src/workflows/update-custom-from-promotion/index.ts" |
|
680
|
const updated = when({ |
|
681
|
input, |
|
682
|
promotions, |
|
683
|
}, (data) => data.promotions[0].custom && data.input.additional_data?.custom_name?.length > 0) |
|
684
|
.then(() => { |
|
685
|
return updateCustomStep({ |
|
686
|
id: promotions[0].custom.id, |
|
687
|
custom_name: input.additional_data.custom_name, |
|
688
|
}) |
|
689
|
}) |
|
690
|
|
|
691
|
return new WorkflowResponse({ |
|
692
|
created, |
|
693
|
updated, |
|
694
|
deleted, |
|
695
|
}) |
|
696
|
``` |
|
697
|
|
|
698
|
Using `when-then`, you check if the promotion has a linked `Custom` record and `custom_name` is passed in the `additional_data`. If so, you update the linked `Custom` record. |
|
699
|
|
|
700
|
You return in the workflow response the created, updated, and deleted `Custom` record. |
|
701
|
|
|
702
|
### Consume promotionsUpdated Workflow Hook |
|
703
|
|
|
704
|
You can now consume the `promotionsUpdated` and execute the workflow you created. |
|
705
|
|
|
706
|
Create the file `src/workflows/hooks/promotion-updated.ts` with the following content: |
|
707
|
|
|
708
|
```ts title="src/workflows/hooks/promotion-updated.ts" |
|
709
|
import { updatePromotionsWorkflow } from "@medusajs/medusa/core-flows" |
|
710
|
import { |
|
711
|
UpdateCustomFromPromotionStepInput, |
|
712
|
updateCustomFromPromotionWorkflow, |
|
713
|
} from "../update-custom-from-promotion" |
|
714
|
|
|
715
|
updatePromotionsWorkflow.hooks.promotionsUpdated( |
|
716
|
async ({ promotions, additional_data }, { container }) => { |
|
717
|
const workflow = updateCustomFromPromotionWorkflow(container) |
|
718
|
|
|
719
|
for (const promotion of promotions) { |
|
720
|
await workflow.run({ |
|
721
|
input: { |
|
722
|
promotion, |
|
723
|
additional_data, |
|
724
|
} as UpdateCustomFromPromotionStepInput, |
|
725
|
}) |
|
726
|
} |
|
727
|
} |
|
728
|
) |
|
729
|
``` |
|
730
|
|
|
731
|
In the workflow hook handler, you execute the workflow, passing it the hook's input. |
|
732
|
|
|
733
|
### Test it Out |
|
734
|
|
|
735
|
To test it out, send a `POST` request to `/admin/promotions/:id` to update a promotion, passing `custom_name` in `additional_data`: |
|
736
|
|
|
737
|
```bash |
|
738
|
curl -X POST 'localhost:9000/admin/promotions/{promotion_id}?fields=+custom.*' \ |
|
739
|
-H 'Content-Type: application/json' \ |
|
740
|
-H 'Authorization: Bearer {token}' \ |
|
741
|
--data '{ |
|
742
|
"additional_data": { |
|
743
|
"custom_name": "test 2" |
|
744
|
} |
|
745
|
}' |
|
746
|
``` |
|
747
|
|
|
748
|
Make sure to replace `{promotion_id}` with the promotion's ID, and `{token}` with the JWT token of an admin user. |
|
749
|
|
|
750
|
The request will return the promotion's details with the updated `custom` linked record. |