Raw
1 ---
2 products:
3 - product
4 - sales channel
5 - inventory
6 ---
7
8 import { Card, Prerequisites, Details, WorkflowDiagram } from "docs-ui"
9 import { Github } from "@medusajs/icons"
10
11 export const ogImage = "https://res.cloudinary.com/dza7lstvk/image/upload/v1733326703/Medusa%20Resources/restock-notification_sw5k7d.jpg"
12
13 export const metadata = {
14 title: `Implement Restock Notifications in Medusa`,
15 openGraph: {
16 images: [
17 {
18 url: ogImage,
19 width: 1600,
20 height: 836,
21 type: "image/jpeg"
22 }
23 ],
24 },
25 twitter: {
26 images: [
27 {
28 url: ogImage,
29 width: 1600,
30 height: 836,
31 type: "image/jpeg"
32 }
33 ]
34 }
35 }
36
37 # {metadata.title}
38
39 In this guide, you'll learn how to notify customers when a variant is restocked in Medusa.
40
41 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 managing the inventory of product variants in different stock locations and sales channels.
42
43 Customers browsing your store may be interested in a product that is currently out of stock. To keep the customer interested in your store and encourage them to purchase the product in the future, you can build customizations around Medusa's commerce features to subscribe customers to receive a notification when the product is restocked.
44
45 This guide will teach you how to:
46
47 - Install and set up Medusa.
48 - Implement the data model to subscribe for variant restocking.
49 - Add a custom endpoint to subscribe a customer to a variant's restock notification.
50 - Build a flow to send a notification to customers subscribed to a variant when it's restocked.
51
52 You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
53
54 <Card
55 title="Example Repository"
56 text="Find the full code of the guide in this repository."
57 href="https://github.com/medusajs/examples/tree/main/restock-notification"
58 icon={Github}
59 />
60
61 ---
62
63 ## Step 1: Install a Medusa Application
64
65 <Prerequisites items={[
66 {
67 text: "Node.js v20.19.0+ or v22.12.0+",
68 link: "https://nodejs.org/en/download"
69 },
70 {
71 text: "Git CLI tool",
72 link: "https://git-scm.com/downloads"
73 },
74 {
75 text: "PostgreSQL",
76 link: "https://www.postgresql.org/download/"
77 }
78 ]} />
79
80 Start by installing the Medusa application on your machine with the following command:
81
82 ```bash npx2yarnExec
83 npx create-medusa-app@latest
84 ```
85
86 You'll first be asked for the project's name. You can also optionally choose to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx).
87
88 the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory. If you chose to install the Next.js Starter Storefront, it'll be in the `apps/storefront` directory.
89
90 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credential and submit the form. Afterwards, you can login with the new user and explore the dashboard.
91
92 <Note title="Ran into Errors">
93
94 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
95
96 </Note>
97
98 <Note>
99
100 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
101
102 </Note>
103
104 ---
105
106 ## Step 2: Create Restock Module
107
108 To add custom tables to the database, which are called data models, you create a module. A module is a re-usable 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.
109
110 In this step, you'll create a Restock Module that adds a custom data model for restock notification subscriptions. In later steps, you'll store customer subscriptions in this data model.
111
112 <Note>
113
114 Learn more about modules in [this documentation](!docs!/learn/fundamentals/modules).
115
116 </Note>
117
118 ### Create Module Directory
119
120 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/restock`.
121
122 ![Diagram showcasing the module directory to create](https://res.cloudinary.com/dza7lstvk/image/upload/v1733222736/Medusa%20Resources/restock-dir-overview-1_hiz58j.jpg)
123
124 ### Create Data Models
125
126 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.
127
128 <Note>
129
130 Learn more about data models in [this documentation](!docs!/learn/fundamentals/modules#1-create-data-model).
131
132 </Note>
133
134 In Medusa, you have sales channels that indicate the channels you sell your products through, such as online storefront or offline store. A product's variants have different inventory quantities across stock locations, which are associated with sales channels.
135
136 ![A diagram showcasing how a variant's inventory is stored across modules](https://res.cloudinary.com/dza7lstvk/image/upload/v1733224214/Medusa%20Resources/inventory-details-example_nvx4cj.jpg)
137
138 So, a customer sees the inventory quantity of a product variant based on their sales channel. To subscribe a customer to a product variant's restock notification, you'll store the subscription in a `RestockSubscription` data model.
139
140 You create a data model in a TypeScript or JavaScript file under the `models` directory of a module. So, create the file `src/modules/restock/models/restock-subscription.ts` with the following content:
141
142 ![The directory structure of the Restock Module after adding this model.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733224503/Medusa%20Resources/restock-dir-overview-2_chap79.jpg)
143
144 ```ts title="src/modules/restock/models/restock-subscription.ts"
145 import { model } from "@medusajs/framework/utils"
146
147 const RestockSubscription = model.define("restock_subscription", {
148 id: model.id().primaryKey(),
149 variant_id: model.text(),
150 sales_channel_id: model.text(),
151 email: model.text(),
152 customer_id: model.text().nullable(),
153 })
154 .indexes([
155 {
156 on: ["variant_id", "sales_channel_id", "email"],
157 unique: true,
158 },
159 ])
160
161 export default RestockSubscription
162 ```
163
164 You define the data model using DML's `define` method. It accepts two parameters:
165
166 1. The first one is the name of the data model's table in the database.
167 2. The second is an object, which is the data model's schema. The schema's properties are defined using DML methods.
168
169 In the data model, you define the following properties:
170
171 1. `id`: A primary key ID for each record.
172 2. `variant_id`: The ID of a variant that customers have subscribed to.
173 3. `sales_channel_id`: The ID of the sales channel that this variant is out-of-stock in.
174 4. `email`: The email of the customer subscribed to the restock notification.
175 5. `customer_id`: The customer's ID in Medusa. This is nullable in case the customer is a guest.
176
177 <Note>
178
179 Learn more about data model [properties](!docs!/learn/fundamentals/data-models/properties) and [relations](!docs!/learn/fundamentals/data-models/relationships).
180
181 </Note>
182
183 You also define a unique index on the `variant_id`, `sales_channel_id`, and `email` properties using the `indexes` method.
184
185 <Note>
186
187 Learn more about data model indexes in [this documentation](!docs!/learn/fundamentals/data-models/indexes).
188
189 </Note>
190
191 ### Create Service
192
193 You define data-management methods of your data models in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can perform database operations.
194
195 <Note>
196
197 Learn more about services in [this documentation](!docs!/learn/fundamentals/modules#2-create-service).
198
199 </Note>
200
201 In this section, you'll create the Restock Module's service. Create the file `src/modules/restock/service.ts` with the following content:
202
203 ![The directory structure of the Restock Module after adding this service.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733224957/Medusa%20Resources/restock-dir-overview-4_pkypup.jpg)
204
205 ```ts title="src/modules/restock/service.ts"
206 import { MedusaService } from "@medusajs/framework/utils"
207 import RestockSubscription from "./models/restock-subscription"
208
209 class RestockModuleService extends MedusaService({
210 RestockSubscription,
211 }) { }
212
213 export default RestockModuleService
214 ```
215
216 The `RestockModuleService` 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.
217
218 So, the `RestockModuleService` class now has methods like `createRestockSubscriptions` and `retrieveRestockSubscription`.
219
220 <Note>
221
222 Find all methods generated by the `MedusaService` in [this reference](../../../service-factory-reference/page.mdx).
223
224 </Note>
225
226 You'll use this service in a later method to store and manage restock subscriptions.
227
228 ### Export Module Definition
229
230 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.
231
232 So, create the file `src/modules/restock/index.ts` with the following content:
233
234 ![The directory structure of the Restock Module after adding the definition file.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733225036/Medusa%20Resources/restock-dir-overview-5_dcam6u.jpg)
235
236 ```ts title="src/modules/restock/index.ts"
237 import { Module } from "@medusajs/framework/utils"
238 import RestockModuleService from "./service"
239
240 export const RESTOCK_MODULE = "restock"
241
242 export default Module(RESTOCK_MODULE, {
243 service: RestockModuleService,
244 })
245 ```
246
247 You use the `Module` function from the Modules SDK to create the module's definition. It accepts two parameters:
248
249 1. The module's name, which is `restock`.
250 2. An object with a required property `service` indicating the module's service.
251
252 ### Add Module to Medusa's Configurations
253
254 Once you finish building the module, add it to Medusa's configurations to start using it.
255
256 In `medusa-config.ts`, add a `modules` property and pass an array with your custom module:
257
258 ```ts title="medusa-config.ts"
259 module.exports = defineConfig({
260 // ...
261 modules: [
262 {
263 resolve: "./src/modules/restock",
264 },
265 ],
266 })
267 ```
268
269 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.
270
271 ### Generate Migrations
272
273 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.
274
275 <Note>
276
277 Learn more about migrations in [this documentation](!docs!/learn/fundamentals/modules#5-generate-migrations).
278
279 </Note>
280
281 Medusa's CLI tool generates the migrations for you. To generate a migration for the Restock Module, run the following command in your Medusa application's directory:
282
283 ```bash npx2yarn
284 npx medusa db:generate restock
285 ```
286
287 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/restock` that holds the generated migration.
288
289 ![The directory structure of the Restock Module after generating the migration](https://res.cloudinary.com/dza7lstvk/image/upload/v1733225157/Medusa%20Resources/restock-dir-overview-6_c2z6oi.jpg)
290
291 Then, to reflect these migrations on the database, run the following command:
292
293 ```bash npx2yarn
294 npx medusa db:migrate
295 ```
296
297 The table of the Restock Module's data model are now created in the database.
298
299 ---
300
301 ## Step 3: Link Restock Subscription to Product Variant
302
303 Since the `RestockSubscription` data model stores the product variant's ID, you may want to retrieve the product variant's details while retrieving a restock subscription record.
304
305 However, modules are [isolated](!docs!/learn/fundamentals/modules/isolation) to ensure they're re-usable and don't have side effects when integrated into the Medusa application. So, to build associations between modules, you define [module links](!docs!/learn/fundamentals/module-links). A Module link associates two modules' data models while maintaining module isolation.
306
307 In this section, you'll link the `RestockSubscription` data model to the [Product Module](../../../commerce-modules/product/page.mdx)'s `ProductVariant` data model.
308
309 <Note>
310
311 Learn more about module links in [this documentation](!docs!/learn/fundamentals/module-links).
312
313 </Note>
314
315 To define a link, create the file `src/links/restock-variant.ts` with the following content:
316
317 ![The directory structure of the Medusa Application after adding this link.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733225402/Medusa%20Resources/restock-dir-overview-7_dln3fw.jpg)
318
319 ```ts title="src/links/restock-variant.ts"
320 import { defineLink } from "@medusajs/framework/utils"
321 import RestockModule from "../modules/restock"
322 import ProductModule from "@medusajs/medusa/product"
323
324 export default defineLink(
325 {
326 linkable: RestockModule.linkable.restockSubscription.id,
327 field: "variant_id",
328 },
329 ProductModule.linkable.productVariant,
330 {
331 readOnly: true,
332 }
333 )
334 ```
335
336 You define a link using `defineLink` from the Modules SDK. It accepts three parameters:
337
338 1. The first data model part of the link, which is the Restock Module's `restockSubscription` data model. A module has a special `linkable` property that contain link configurations for its data models. You also specify the field that points to the product variant.
339 2. The second data model part of the link, which is the Product Module's `productVariant` data model.
340 3. An object of configurations for the module link. By default, Medusa creates a table in the database to represent the link you define. However, in this guide, you only want this link to retrieve the variants associated with a subscription. So, you enable `readOnly` telling Medusa not to create a table for this link.
341
342 In the next steps, you'll see how this link allows you to retrieve product variants' details when retrieving restock subscriptions.
343
344 ---
345
346 ## Step 4: Create Restock Subscription Workflow
347
348 To subscribe customers to a variant's restock notification, you need a workflow.
349
350 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.
351
352 In this section, you'll create a workflow that validates that a variant is out-of-stock in the customer's sales channel, then subscribes the customer to the variant's restock notification. Later, you'll execute this workflow in an endpoint that you use in a storefront.
353
354 <Note>
355
356 Learn more about workflows in [this documentation](!docs!/learn/fundamentals/workflows)
357
358 </Note>
359
360 The workflow has the following steps:
361
362 <WorkflowDiagram
363 workflow={{
364 name: "createRestockSubscriptionWorkflow",
365 steps: [
366 {
367 type: "when",
368 condition: "!customer.email",
369 steps: [
370 {
371 type: "step",
372 name: "useQueryGraphStep",
373 description: "Retrieve the customer using Query if an email isn't provided.",
374 depth: 1,
375 link: "/references/helper-steps/useQueryGraphStep"
376 },
377 ]
378 },
379 {
380 type: "step",
381 name: "validateVariantOutOfStockStep",
382 description: "Validate that the variant is out-of-stock, otherwise throw an error.",
383 depth: 1,
384 link: "#validatevariantoutofstockstep"
385 },
386 {
387 type: "step",
388 name: "useQueryGraphStep",
389 description: "Retrieve the restock subscription using Query if it exists.",
390 depth: 1,
391 link: "/references/helper-steps/useQueryGraphStep"
392 },
393 {
394 type: "when",
395 condition: "data.length === 0",
396 steps: [
397 {
398 type: "step",
399 name: "createRestockSubscriptionStep",
400 description: "Create the restock subscription if it doesn't exist.",
401 depth: 2,
402 link: "#createrestocksubscriptionstep"
403 },
404 {
405 type: "step",
406 name: "updateRestockSubscriptionStep",
407 description: "Update the restock subscription if it exists.",
408 depth: 2,
409 link: "#updatesestocksubscriptionstep"
410 }
411 ],
412 depth: 1,
413 },
414 {
415 type: "step",
416 name: "useQueryGraphStep",
417 description: "Retrieve the restock subscription using Query again to return it.",
418 depth: 1,
419 link: "/references/helper-steps/useQueryGraphStep"
420 },
421 ]
422 }}
423 />
424
425 The `useQueryGraphStep` is from Medusa's workflows package. So, you'll only implement the other steps.
426
427 ### validateVariantOutOfStockStep
428
429 The second step in the workflow will validate that the variant is actually out of stock in the customer's sales channel.
430
431 Create the file `src/workflows/create-restock-subscription/steps/validate-variant-out-of-stock.ts` with the following content:
432
433 ![The directory structure of the Medusa application after adding the step.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733227547/Medusa%20Resources/restock-dir-overview-10_g3dbi3.jpg)
434
435 ```ts title="src/workflows/create-restock-subscription/steps/validate-variant-out-of-stock.ts"
436 import {
437 getVariantAvailability,
438 MedusaError,
439 ContainerRegistrationKeys,
440 } from "@medusajs/framework/utils"
441 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
442
443 type ValidateVariantOutOfStockStepInput = {
444 variant_id: string
445 sales_channel_id: string
446 }
447
448 export const validateVariantOutOfStockStep = createStep(
449 "validate-variant-out-of-stock",
450 async ({ variant_id, sales_channel_id }: ValidateVariantOutOfStockStepInput, { container }) => {
451 const query = container.resolve(
452 ContainerRegistrationKeys.QUERY
453 )
454 const availability = await getVariantAvailability(query, {
455 variant_ids: [variant_id],
456 sales_channel_id,
457 })
458
459 if ((availability[variant_id].availability || 0) > 0) {
460 throw new MedusaError(
461 MedusaError.Types.INVALID_DATA,
462 "Variant isn't out of stock."
463 )
464 }
465 }
466 )
467 ```
468
469 This step accepts the ID of the variant and the ID of the customer's sales channel. In the step, you use the `getVariantAvailability` from the Medusa Framework to get the variant's quantity in the specified sales channels. If the variant's quantity is greater than `0`, you throw an error, stopping the workflow's execution.
470
471 ### createRestockSubscriptionStep
472
473 In the workflow, you'll try to retrieve the restock subscription if it already exists for the same email, variant ID, and sales channel ID. If it doesn't exist, you'll use this step to create the restock subscription.
474
475 Create the file `src/workflows/create-restock-subscription/steps/create-restock-subscription.ts` with the following content:
476
477 ![The directory structure of the Medusa application after adding the step.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733227679/Medusa%20Resources/restock-dir-overview-11_dyrpao.jpg)
478
479 export const createRSHighlights = [
480 ["15", "restockModuleService", "Resolve the Restock Module's service from the Medusa container."],
481 ["19", "createRestockSubscriptions", "Use the service's generated method to create restock subscriptions."]
482 ]
483
484 ```ts title="src/workflows/create-restock-subscription/steps/create-restock-subscription.ts" highlights={createRSHighlights}
485 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
486 import RestockModuleService from "../../../modules/restock/service"
487 import { RESTOCK_MODULE } from "../../../modules/restock"
488
489 type CreateRestockSubscriptionStepInput = {
490 variant_id: string
491 sales_channel_id: string
492 email: string
493 customer_id?: string
494 }
495
496 export const createRestockSubscriptionStep = createStep(
497 "create-restock-subscription",
498 async (input: CreateRestockSubscriptionStepInput, { container }) => {
499 const restockModuleService: RestockModuleService = container.resolve(
500 RESTOCK_MODULE
501 )
502
503 const restockSubscription = await restockModuleService.createRestockSubscriptions(
504 input
505 )
506
507 return new StepResponse(restockSubscription, restockSubscription)
508 }
509 )
510 ```
511
512 In the step, you resolve the Restock Module's service from the Medusa container. Medusa registers the service of custom and core modules in the container under the module's name.
513
514 Then, you use the service's `createRestockSubscriptions` method, which was generated by `MedusaService`, to create the restock subscription.
515
516 <Note>
517
518 Learn more about a service's generated methods in [this reference](../../../service-factory-reference/page.mdx).
519
520 </Note>
521
522 Finally, you return the created restock subscription by passing it as a first parameter to `StepResponse`. The second parameter is data passed to the compensation function, which you'll learn about next.
523
524 #### Add Compensation Function
525
526 A compensation function defines the rollback logic of a step, and it's only executed if an error occurs in the workflow. This eliminates data inconsistency if an error occurs and the workflow can't finish execution successfully.
527
528 <Note title="Tip">
529
530 Learn more about compensation functions in [this documentation](!docs!/learn/fundamentals/workflows/compensation-function).
531
532 </Note>
533
534 Since the `createRestockSubscriptionStep` creates a restock subscription, you'll undo that in the compensation function. To add a compensation function, pass it as a third parameter to `createStep`:
535
536 ```ts title="src/workflows/create-restock-subscription/steps/create-restock-subscription.ts"
537 export const createOrGetRestockSubscriptionsStep = createStep(
538 // ...
539 async (restockSubscription, { container }) => {
540 if (!restockSubscription) {
541 return
542 }
543 const restockModuleService: RestockModuleService = container.resolve(
544 RESTOCK_MODULE
545 )
546
547 await restockModuleService.deleteRestockSubscriptions(restockSubscription.id)
548 }
549 )
550 ```
551
552 The compensation function receives two parameters:
553
554 1. The second parameter of `StepResponse`, which is the created restock subscription.
555 2. An object similar to the second parameter of a step function. It has a `container` property to resolve resources from the Medusa container.
556
557 In the compensation function, you resolve the Restock Module's service from the container, then delete the created subscription using the generated `deleteRestockSubscriptions` method.
558
559 ### updateRestockSubscriptionStep
560
561 As mentioned in the previous step, the workflow will try to retrieve the restock subscription in case it already exists. If it does, you'll run this step to update its customer ID if it wasn't previously set in the subscription.
562
563 Create the file `src/workflows/create-restock-subscription/steps/update-restock-subscription.ts` with the following content:
564
565 ![The directory structure of the Medusa application after adding the step.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733227952/Medusa%20Resources/restock-dir-overview-12_vubtkp.jpg)
566
567 ```ts title="src/workflows/create-restock-subscription/steps/update-restock-subscription.ts"
568 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
569 import RestockModuleService from "../../../modules/restock/service"
570 import { RESTOCK_MODULE } from "../../../modules/restock"
571
572 type UpdateRestockSubscriptionStepInput = {
573 id: string
574 customer_id?: string
575 }
576
577 export const updateRestockSubscriptionStep = createStep(
578 "update-restock-subscription",
579 async ({ id, customer_id }: UpdateRestockSubscriptionStepInput, { container }) => {
580 const restockModuleService: RestockModuleService = container.resolve(
581 RESTOCK_MODULE
582 )
583
584 const oldData = await restockModuleService.retrieveRestockSubscription(
585 id
586 )
587 const restockSubscription = await restockModuleService.updateRestockSubscriptions({
588 id,
589 customer_id: oldData.customer_id || customer_id,
590 })
591
592 return new StepResponse(restockSubscription, oldData)
593 },
594 async (restockSubscription, { container }) => {
595 if (!restockSubscription) {
596 return
597 }
598 const restockModuleService: RestockModuleService = container.resolve(
599 RESTOCK_MODULE
600 )
601
602 await restockModuleService.updateRestockSubscriptions(restockSubscription)
603 }
604 )
605 ```
606
607 In the step, you resolve the Restock Module's service and use its generated `retrieveRestockSubscription` method to retrieve the restock subscription. You then update the subscription with the `updateRestockSubscriptions`, updating the customer ID if it wasn't set in the subscription.
608
609 The step returns the updated restock subscription. It also passes to the compensation function the subscription's data before the update to undo the change in case an error occurs.
610
611 ### Add createRestockSubscriptionWorkflow
612
613 You can now finally add the workflow that uses all these steps. Create the file `src/workflows/create-restock-subscription/index.ts` with the following content:
614
615 ![The directory structure of the Medusa application after adding the workflow.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733229373/Medusa%20Resources/restock-dir-overview-13_zdwawe.jpg)
616
617 export const subscriptionWorkflow1Highlights = [
618 ["16", "createWorkflow", "Create a workflow."],
619 ["23", "transform", "Set the customer ID to an empty string if not provided."],
620 ["28", "when", "If email is not set, try to retrieve customer by its ID."],
621 ["48", "transform", "Set the email either to the one in the input or the specified customer's email."],
622 ]
623
624 ```ts title="src/workflows/create-restock-subscription/index.ts" highlights={subscriptionWorkflow1Highlights}
625 import { createWorkflow, transform, when, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
626 import { validateVariantOutOfStockStep } from "./steps/validate-variant-out-of-stock"
627 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
628 import { createRestockSubscriptionStep } from "./steps/create-restock-subscription"
629 import { updateRestockSubscriptionStep } from "./steps/update-restock-subscription"
630
631 type CreateRestockSubscriptionWorkflowInput = {
632 variant_id: string
633 sales_channel_id: string
634 customer: {
635 email?: string
636 customer_id?: string
637 }
638 }
639
640 export const createRestockSubscriptionWorkflow = createWorkflow(
641 "create-restock-subscription",
642 ({
643 variant_id,
644 sales_channel_id,
645 customer,
646 }: CreateRestockSubscriptionWorkflowInput) => {
647 const customerId = transform({
648 customer,
649 }, (data) => {
650 return data.customer.customer_id || ""
651 })
652 const retrievedCustomer = when(
653 "retrieve-customer-by-id",
654 { customer },
655 ({ customer }) => {
656 return !customer.email
657 }
658 ).then(() => {
659 // @ts-ignore
660 const { data } = useQueryGraphStep({
661 entity: "customer",
662 fields: ["email"],
663 filters: { id: customerId },
664 options: {
665 throwIfKeyNotFound: true,
666 },
667 }).config({ name: "retrieve-customer" })
668
669 return data
670 })
671
672 const email = transform({
673 retrievedCustomer,
674 customer,
675 }, (data) => {
676 return data.customer?.email ?? data.retrievedCustomer?.[0].email
677 })
678
679 // TODO add more steps
680 }
681 )
682 ```
683
684 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
685
686 It accepts as a second parameter a constructor function, which is the workflow's implementation. In the workflow, you:
687
688 - Use [transform](!docs!/learn/fundamentals/workflows/variable-manipulation) from the Workflows SDK to create a `customerId` variable. Its value is either the ID of the customer passed in the workflow's input if it's not `undefined`, or an empty string.
689 - Use [when-then](!docs!/learn/fundamentals/workflows/conditions) from the Workflows SDK that performs steps if a condition is met. If the customer's email isn't set in the workflow's input, you retrieve the customer using `useQueryGraphStep` by its ID.
690 - Use `transform` again to create an `email` variable whose value is either the email passed in the workflow's input or the retrieved customer's email.
691
692 <Note title="Tip">
693
694 A workflow's constructor function has some constraints in implementation, which is why you need to use `transform` for variable manipulation and `when-then` to perform steps based on a condition. Learn more about these constraints in [this documentation](!docs!/learn/fundamentals/workflows/constructor-constraints).
695
696 </Note>
697
698 Next, replace the `TODO` with the following:
699
700 export const subscriptionWorkflow2Highlights = [
701 ["1", "validateVariantOutOfStockStep", "Validate that the variant is out of stock in the specified sales channel."],
702 ["6", "useQueryGraphStep", "Get the restock subscription to check if it already exists."],
703 ["16", "when", "Perform an action if the restock subscription doesn't exist."],
704 ["20", "createRestockSubscriptionStep", "Create the restock subscription if it doesn't exist."],
705 ["28", "when", "Perform an action if the restock subscription exists."],
706 ["32", "updateRestockSubscriptionStep", "Update the restock subscription if it exists."],
707 ["38", "useQueryGraphStep", "Retrieve the restock subscription again to return it."],
708 ["48", "WorkflowResponse", "Return the restock subscription."]
709 ]
710
711 ```ts title="src/workflows/create-restock-subscription/index.ts" highlights={subscriptionWorkflow2Highlights}
712 validateVariantOutOfStockStep({
713 variant_id,
714 sales_channel_id,
715 })
716
717 const { data: restockSubscriptions } = useQueryGraphStep({
718 entity: "restock_subscription",
719 fields: ["*"],
720 filters: {
721 email,
722 variant_id,
723 sales_channel_id,
724 },
725 }).config({ name: "retrieve-subscriptions" })
726
727 when({ restockSubscriptions }, ({ restockSubscriptions }) => {
728 return restockSubscriptions.length === 0
729 })
730 .then(() => {
731 createRestockSubscriptionStep({
732 variant_id,
733 sales_channel_id,
734 email,
735 customer_id: customer.customer_id,
736 })
737 })
738
739 when({ restockSubscriptions }, ({ restockSubscriptions }) => {
740 return restockSubscriptions.length > 0
741 })
742 .then(() => {
743 updateRestockSubscriptionStep({
744 id: restockSubscriptions[0].id,
745 customer_id: customer.customer_id,
746 })
747 })
748
749 const { data: restockSubscription } = useQueryGraphStep({
750 entity: "restock_subscription",
751 fields: ["*"],
752 filters: {
753 email,
754 variant_id,
755 sales_channel_id,
756 },
757 }).config({ name: "retrieve-restock-subscription" })
758
759 return new WorkflowResponse(
760 restockSubscription
761 )
762 ```
763
764 You add the following steps to the workflow:
765
766 - `validateVariantOutOfStockStep` to validate that the variant is out of stock in the specified sales channel. If not, an error is thrown, halting the workflow's execution.
767 - `useQueryGraphStep` to retrieve the restock subscription in case it already exists.
768 - Use [when-then](!docs!/learn/fundamentals/workflows/conditions) to perform an action if a condition is met.
769 - The first when-then block checks if the restock subscription doesn't exist, then creates it using the `createRestockSubscriptionStep`.
770 - The second when-then block checks if the restock subscription already exists, then updates it using the `updateRestockSubscriptionStep`.
771 - `useQueryGraphStep` again to retrieve the restock subscription before returning it.
772
773 Workflows must return an instance of `WorkflowResponse`, passing as a parameter the data to return to the workflow's executor. The workflow returns the restock subscription.
774
775 You'll execute the workflow when you create the API route next.
776
777 ---
778
779 ## Step 5: Subscribe to Restock Notifications API Route
780
781 Now that you implemented the flow to subscribe customers to a variant's restock notifications, you'll expose this feature through an API route.
782
783 An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts. You'll create an API route at the path `/store/restock-subscriptions` that executes the workflow from the previous step.
784
785 <Note>
786
787 Learn more about API routes in [this documentation](!docs!/learn/fundamentals/api-routes).
788
789 </Note>
790
791 ### Implement API Route
792
793 An API route is created in a `route.ts` file under a sub-directory of the `src/api` directory.
794
795 The path of the API route is the file's path relative to `src/api`. So, to create the `/store/restock-subscriptions` API route, create the file `src/api/store/restock-subscriptions/route.ts` with the following content:
796
797 ![The directory structure of the Medusa application after adding the route file.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733230210/Medusa%20Resources/restock-dir-overview-16_sv7yk2.jpg)
798
799 export const routeHighlights = [
800 ["11", "POST", "Define a `POST` API route"],
801 ["12", "req", "The request's details."],
802 ["13", "res", "The object to manipulate and return a response."],
803 ["15", "salesChannelId", "Set the sales channel ID either to the request body parameter or the publishable API key's sales channel."],
804 ["15", "validatedBody", "Access body parameters in `validatedBody`."],
805 ["16", "publishable_key_context", "Access the customer's sales channels based on the specified publishable API key."],
806 ["26", "run", "Execute the `createRestockSubscriptionWorkflow`."],
807 ["27", "input", "Pass input to the workflow."],
808 ["32", "customer_id", "If the customer is logged in, their ID is stored in `req.auth_context.actor_id`."],
809 ["37", "sendStatus", "Return a response with `201` status code."]
810 ]
811
812 ```ts title="src/api/store/restock-subscriptions/route.ts" highlights={routeHighlights}
813 import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
814 import { MedusaError } from "@medusajs/framework/utils"
815 import { createRestockSubscriptionWorkflow } from "../../../workflows/create-restock-subscription"
816
817 type PostStoreCreateRestockSubscription = {
818 variant_id: string
819 email?: string
820 sales_channel_id?: string
821 }
822
823 export async function POST(
824 req: AuthenticatedMedusaRequest<PostStoreCreateRestockSubscription>,
825 res: MedusaResponse
826 ) {
827 const salesChannelId = req.validatedBody.sales_channel_id || (
828 req.publishable_key_context?.sales_channel_ids?.length ?
829 req.publishable_key_context?.sales_channel_ids[0] : undefined
830 )
831 if (!salesChannelId) {
832 throw new MedusaError(
833 MedusaError.Types.INVALID_DATA,
834 "At least one sales channel ID is required, either associated with the publishable API key or in the request body."
835 )
836 }
837 const { result } = await createRestockSubscriptionWorkflow(req.scope)
838 .run({
839 input: {
840 variant_id: req.validatedBody.variant_id,
841 sales_channel_id: salesChannelId,
842 customer: {
843 email: req.validatedBody.email,
844 customer_id: req.auth_context?.actor_id,
845 },
846 },
847 })
848
849 return res.sendStatus(200)
850 }
851
852 ```
853
854 Since you export a `POST` function in this file, you're exposing a `POST` API route at `/store/restock-subscriptions`. The route handler function accepts two parameters:
855
856 1. A request object with details and context on the request, such as body parameters or authenticated customer details.
857 2. A response object to manipulate and send the response.
858
859 <Note title="Tip">
860
861 `AuthenticatedMedusaRequest` accepts the request body's type as a type argument.
862
863 </Note>
864
865 In the function, you first declare the sales channel ID either based on the parameter specified in the request body or the publishable API key's first sales channel. If the sales channel's ID is not set, an error is thrown.
866
867 Then, you execute the `createRestockSubscriptionWorkflow` by invoking it, passing it the Medusa container which is stored in the `scope` property of the request object, and invoking its `run` method.
868
869 The `run` method accepts an object having an `input` property, which is the input to pass to the workflow. You pass the following input:
870
871 1. `variant_id`: The ID of the variant the customer is subscribing to. You access the request body parameters from the `validatedBody` property of the request object.
872 2. `sales_channel_id`: The ID of the sales channel.
873 3. `customer`: The subscriber customer's details:
874 - `email`: The email passed in the request body, if available.
875 - `customer_id`: The ID of the customer if they're authenticated.
876
877 Finally, you return a `201` response code, indicating that the customer has subscribed to restock notifications of the specified variant.
878
879 ### Add Validation Schema
880
881 The API route accepts the variant ID, and optionally the customer email and sales channel ID as request body parameters. So, you'll create a schema to validate the request body.
882
883 In Medusa, you create validation schemas using [Zod](https://zod.dev/) in a TypeScript file under the `src/api` directory. So, create the file `src/api/store/restock-subscriptions/validators.ts` with the following content:
884
885 ![The directory structure of the Medusa application after adding the validator file.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733229734/Medusa%20Resources/restock-dir-overview-14_au0h15.jpg)
886
887 <Note>
888
889 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
890
891 </Note>
892
893 ```ts title="src/api/store/restock-subscriptions/validators.ts"
894 import { z } from "@medusajs/framework/zod"
895
896 export const PostStoreCreateRestockSubscription = z.object({
897 variant_id: z.string(),
898 email: z.string().optional(),
899 sales_channel_id: z.string().optional(),
900 })
901 ```
902
903 You create an object schema with the following properties:
904
905 - `variant_id`: A required string parameter.
906 - `email`: An optional string parameter. The email is optional if the customer is authenticated.
907 - `sales_channel_id`: An optional string parameter. By default, every route starting with `/store` must pass the publishable API key, which is linked to one or more sales channels. This parameter takes a precedence over the publishable API key's channel.
908
909 <Note>
910
911 Learn more about creating schemas in [Zod's documentation](https://zod.dev/).
912
913 </Note>
914
915 You can now replace the `PostStoreCreateRestockSubscription` type in `src/api/store/restock-subscriptions/route.ts` with the following:
916
917 <Note>
918
919 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
920
921 </Note>
922
923 ```ts title="src/api/store/restock-subscriptions/route.ts"
924 // ...
925 import { z } from "@medusajs/framework/zod"
926 import { PostStoreCreateRestockSubscription } from "./validators"
927
928 type PostStoreCreateRestockSubscription = z.infer<
929 typeof PostStoreCreateRestockSubscription
930 >
931 // ...
932 ```
933
934 Next, you'll use this schema for validation.
935
936 ### Add Validation and Auth Middlewares
937
938 To use the Zod schema for validation, you apply the `validateAndTransformBody` middleware on the `/store/restock-subscriptions` route. A middleware is a function executed before the API route when a request is sent to it.
939
940 <Note>
941
942 Learn more about middlewares in [this documentation](!docs!/learn/fundamentals/api-routes/middlewares).
943
944 </Note>
945
946 To apply middlewares, create the file `src/api/middlewares.ts` with the following content:
947
948 ![The directory structure of the Medusa application after adding the middlewares file.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733229866/Medusa%20Resources/restock-dir-overview-15_xvwkc0.jpg)
949
950 export const middlewaresHighlights = [
951 ["10", "defineMiddlewares", "Export middlewares definition."],
952 ["13", "matcher", "The route to apply the middleware on."],
953 ["14", "method", "The HTTP method that the middleware is applied on for the specified route."],
954 ["15", "middlewares", "The middlewares to apply on the route."],
955 ["16", "authenticate", "Apply this middleware to access the customer's ID if they're logged in."],
956 ["19", "validateAndTransformBody", "Apply the validation schema on the route."]
957 ]
958
959 ```ts title="src/api/middlewares.ts" highlights={middlewaresHighlights}
960 import {
961 authenticate,
962 defineMiddlewares,
963 validateAndTransformBody,
964 } from "@medusajs/framework/http"
965 import {
966 PostStoreCreateRestockSubscription,
967 } from "./store/restock-subscriptions/validators"
968
969 export default defineMiddlewares({
970 routes: [
971 {
972 matcher: "/store/restock-subscriptions",
973 method: "POST",
974 middlewares: [
975 authenticate("customer", ["bearer", "session"], {
976 allowUnauthenticated: true,
977 }),
978 validateAndTransformBody(PostStoreCreateRestockSubscription),
979 ],
980 },
981 ],
982 })
983 ```
984
985 In this file, you export the middlewares definition using `defineMiddlewares` from the Medusa Framework. This function accepts an object having a `routes` property, which is an array of middleware configurations to apply on routes.
986
987 You pass in the `routes` array an object having the following properties:
988
989 - `matcher`: The route to apply the middleware on.
990 - `method`: The HTTP method to apply the middleware on for the specified API route.
991 - `middlewares`: An array of the middlewares to apply. You apply two middlewares:
992 - `authenticate`: A middleware that guards and attaches the logged-in customer details to the request object received by the API route handler. The middleware accepts three parameters:
993 - The type of user to authenticate, which is `customer`.
994 - The types of authentication methods allowed.
995 - An optional object of options. You enable the `allowUnauthenticated`, which allows both authenticated and guest customers to access the route, and attaches the authenticated customer's ID to the request object.
996 - `validateAndTransformBody`: A middleware to ensure the received request body is valid against the Zod schema you defined earlier.
997
998 Any request sent to `/store/restock-subscriptions` will now automatically fail if its body parameters don't match the `PostStoreCreateRestockSubscription` validation schema.
999
1000 ### Test API Route
1001
1002 To test out this API route, start the Medusa application by running the following command in the root directory of the Medusa application:
1003
1004 ```bash npm2yarn
1005 npm run dev
1006 ```
1007
1008 Before sending the request, you need to obtain a publishable API key. So, open the Medusa Admin at `http://localhost:9000/app` and log in with the user you created earlier.
1009
1010 To access your application's API keys in the admin, go to Settings -> Publishable API Keys. You'll have an API key created by default, which is associated with the default sales channel. You can use this publishable API key in the request header.
1011
1012 ![In the admin, click on Publishable API key in the sidebar. A table will show your API keys and allow you to create one.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733230421/Medusa%20Resources/Screenshot_2024-12-03_at_2.53.07_PM_gau9jy.png)
1013
1014 Then, to obtain an ID of a variant that's out of stock, access a product from the Products page and:
1015
1016 1. Under Variants, click on the variant you want to edit its inventory quantity.
1017
1018 ![The variants table shows a product's variants. Click on a variant to open its details page.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733230534/Medusa%20Resources/Screenshot_2024-12-03_at_2.55.11_PM_c1ml9l.png)
1019
1020 2. Under Inventory Items, click on an inventory item.
1021
1022 ![The inventory items table shows the variant's items. Click on an item to open its details page.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733230649/Medusa%20Resources/Screenshot_2024-12-03_at_2.57.01_PM_ccc9of.png)
1023
1024 3. Under Locations, click on the third-dots icon at the right of a location, then choose Edit from the dropdown.
1025
1026 ![The locations are shown in a table. Click on the three-dots at a location's right side, then choose Edit from the dropdown.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733230730/Medusa%20Resources/Screenshot_2024-12-03_at_2.58.18_PM_waeepw.png)
1027
1028 4. In the drawer form, enter `0` for the item's in-stock quantity.
1029 5. Click the Save button.
1030
1031 ![In the drawer form, enter `0` in the In stock field, then click the Save button at the bottom.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733230822/Medusa%20Resources/Screenshot_2024-12-03_at_2.59.48_PM_vqaige.png)
1032
1033 6. Go back to the variant's page and click on the icon at the right of the JSON section.
1034
1035 ![Click on the icon at the right of the JSON section.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733230912/Medusa%20Resources/Screenshot_2024-12-03_at_3.01.28_PM_bcau0e.png)
1036
1037 7. In the JSON object, hover over the `id` field and click the copy icon.
1038
1039 ![Click on the copy icon next to the ID field.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733230981/Medusa%20Resources/Screenshot_2024-12-03_at_3.02.34_PM_ujyv5w.png)
1040
1041 Finally, send a `POST` request to the `/store/restock-subscriptions` API route:
1042
1043 ```bash
1044 curl -X POST http://localhost:9000/store/restock-subscriptions \
1045 -H 'x-publishable-api-key: {api_key}' \
1046 --data '{
1047 "variant_id": "{variant_id}",
1048 "email": "customer@gmail.com"
1049 }'
1050 ```
1051
1052 Make sure to replace `{api_key}` with the publishable API key you copied from the settings, and `{variant_id}` for the ID of the out-of-stock variant.
1053
1054 You'll receive a `201` response, indicating that the guest customer with email `customer@gmail.com` is now subscribed to restock notifications for the specified variant in the first sales channel associated with the specified publishable API key.
1055
1056 In the next step, you'll implement the functionality to send a notification to the variant's subscribers when it's restocked.
1057
1058 ---
1059
1060 ## Step 6: Send Restock Notification Workflow
1061
1062 After allowing customers to subscribe to a variant's restock notification, you want to implement the flow that checks the variant is restocked and sends a notification to its subscribers.
1063
1064 In this step, you'll create a workflow that retrieves all restock subscriptions, checks which variants are now restocked, and sends a notification to their subscribers.
1065
1066 The workflow has the following steps:
1067
1068 <WorkflowDiagram
1069 workflow={{
1070 name: "sendRestockNotificationsWorkflow",
1071 steps: [
1072 {
1073 type: "step",
1074 name: "getDistinctSubscriptionsStep",
1075 description: "Retrieve restock subscriptions for distinct variant ID and sales channel pairings.",
1076 depth: 1
1077 },
1078 {
1079 type: "step",
1080 name: "getRestockedStep",
1081 description: "Filter out the restock subscriptions to retrieve only ones for restocked variants.",
1082 depth: 1,
1083 link: "#getrestockedstep"
1084 },
1085 {
1086 type: "step",
1087 name: "useQueryGraphStep",
1088 description: "Retrieve restocked subscriptions for all subscribers using Query.",
1089 depth: 1,
1090 link: "/references/helper-steps/useQueryGraphStep"
1091 },
1092 {
1093 type: "step",
1094 name: "sendRestockNotificationStep",
1095 description: "Send a notification to the subscribers of restock subscriptions.",
1096 depth: 1,
1097 link: "#sendrestocknotificationstep"
1098 },
1099 {
1100 type: "step",
1101 name: "deleteRestockSubscriptionStep",
1102 description: "Delete the restock subscriptions from the database.",
1103 depth: 1,
1104 link: "#deleterestocksubscriptionstep"
1105 }
1106 ]
1107 }}
1108 />
1109
1110 The `useQueryGraphStep` is from Medusa's workflows. So, you'll only implement the other steps.
1111
1112 ### Optional Prerequisite: Notification Module Provider
1113
1114 Within this workflow, you'll use Medusa's [Notification Module](../../../infrastructure-modules/notification/page.mdx) to send an email to the customer.
1115
1116 The module delegates the email sending to a module provider, such as [SendGrid](../../../infrastructure-modules/notification/sendgrid/page.mdx) or [Resend](../../../integrations/guides/resend/page.mdx). You can refer to their linked guides to set up either module providers.
1117
1118 Alternatively, for development and debugging purposes, you can use the default Notification Module Provider that only logs a message in the terminal instead of sending an email. To do that, add the following to the `modules` array in `medusa-config.ts`:
1119
1120 ```ts title="medusa-config.ts"
1121 module.exports = defineConfig({
1122 // ...
1123 modules: [
1124 // ...
1125 {
1126 resolve: "@medusajs/medusa/notification",
1127 options: {
1128 providers: [
1129 {
1130 resolve: "@medusajs/medusa/notification-local",
1131 id: "local",
1132 options: {
1133 channels: ["email", "feed"],
1134 },
1135 },
1136 ],
1137 },
1138 },
1139 ],
1140 })
1141
1142 ```
1143
1144 ## getDistinctSubscriptionsStep
1145
1146 The first step is to retrieve all restock subscriptions to later check which variants have been restocked in their sales channel. However, considering there could be a lot of subscribers to the same variant and sales channel pairing, you'll retrieve subscriptions with distinct variant and sales channel ID pairings.
1147
1148 Before adding the step that does this, you'll add a method in the `RestockModuleService` to retrieve the distinct records from the database. So, add the following to `src/modules/restock/service.ts`:
1149
1150 ```ts title="src/modules/restock/service.ts"
1151 // other imports...
1152 import { InjectManager, MedusaContext } from "@medusajs/framework/utils"
1153 import { Context } from "@medusajs/framework/types"
1154 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
1155
1156 class RestockModuleService extends MedusaService({
1157 RestockSubscription,
1158 }) {
1159 // ...
1160 @InjectManager()
1161 async getUniqueSubscriptions(
1162 @MedusaContext() context: Context<EntityManager> = {}
1163 ) {
1164 return await context.manager?.createQueryBuilder("restock_subscription")
1165 .select(["variant_id", "sales_channel_id"]).distinct().execute()
1166 }
1167 }
1168
1169 export default RestockModuleService
1170 ```
1171
1172 To perform queries on the database in a method, add the `@InjectManager` decorator to the method. This will inject a [forked MikroORM entity manager](https://mikro-orm.io/docs/identity-map#forking-entity-manager) that you can use in your method.
1173
1174 Methods with the `@InjectManager` decorator accept as a last parameter a context object that has the `@MedusaContext` decorator. The entity manager is injected into the `manager` property of this parameter.
1175
1176 In the method, you use the `createQueryBuilder` to construct a query, passing it the name of the `RestockSubscription`'s table. You then select distinct `variant_id` and `sales_channel` pairings, and execute and return the query's result.
1177
1178 You'll use this method in the step. To create the step, create the file `src/workflows/send-restock-notifications/steps/get-distinct-subscriptions.ts` with the following content:
1179
1180 ![Directory structure of the Medusa application after adding the step.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733399774/Medusa%20Resources/restock-dir-overview-22_kzchmm.jpg)
1181
1182 ```ts title="src/workflows/send-restock-notifications/steps/get-distinct-subscriptions.ts"
1183 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1184 import RestockModuleService from "../../../modules/restock/service"
1185 import { RESTOCK_MODULE } from "../../../modules/restock"
1186
1187 export const getDistinctSubscriptionsStep = createStep(
1188 "get-distinct-subscriptions",
1189 async (_, { container }) => {
1190 const restockModuleService: RestockModuleService = container.resolve(
1191 RESTOCK_MODULE
1192 )
1193
1194 const distinctSubscriptions = await restockModuleService.getUniqueSubscriptions()
1195
1196 return new StepResponse(distinctSubscriptions)
1197 }
1198 )
1199 ```
1200
1201 In the step, you resolve the Restock Module's service and use the `getUniqueSubscriptions` method to retrieve the distinct subscriptions. You return those subscriptions in the `StepResponse`.
1202
1203 ### getRestockedStep
1204
1205 The second step of the workflow receives all restock subscriptions and returns only those whose variants are restocked in the specified sales channel.
1206
1207 Create the file `src/workflows/send-restock-notifications/steps/get-restocked.ts` with the following content:
1208
1209 ![The directory structure of the Medusa application after adding the step.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733234506/Medusa%20Resources/restock-dir-overview-17_pdtees.jpg)
1210
1211 ```ts title="src/workflows/send-restock-notifications/steps/get-restocked.ts"
1212 import {
1213 getVariantAvailability,
1214 promiseAll,
1215 ContainerRegistrationKeys,
1216 } from "@medusajs/framework/utils"
1217 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1218
1219 type GetRestockedStepInput = {
1220 variant_id: string
1221 sales_channel_id: string
1222 }[]
1223
1224 export const getRestockedStep = createStep(
1225 "get-restocked",
1226 async (input: GetRestockedStepInput, { container }) => {
1227 const restocked: GetRestockedStepInput = []
1228 const query = container.resolve(
1229 ContainerRegistrationKeys.QUERY
1230 )
1231
1232 await promiseAll(
1233 input.map(async (restockSubscription) => {
1234 const variantAvailability = await getVariantAvailability(query, {
1235 variant_ids: [restockSubscription.variant_id],
1236 sales_channel_id: restockSubscription.sales_channel_id,
1237 })
1238
1239 if ((variantAvailability[restockSubscription.variant_id].availability || 0) > 0) {
1240 restocked.push(restockSubscription)
1241 }
1242 })
1243 )
1244
1245 return new StepResponse(restocked)
1246 }
1247 )
1248 ```
1249
1250 In this step, you loop over the restock subscriptions and use `getVariantAvailability` from the Medusa Framework to retrieve a variant's quantity in the sales channel.
1251
1252 If the variant isn't out of stock, then the restock subscription is pushed into the `restocked` array, which is returned in the step's response.
1253
1254 ### sendRestockNotificationStep
1255
1256 The third step of the workflow receives the subscriptions whose variants have been restocked to send a notification to their subscribers.
1257
1258 Create the file `src/workflows/send-restock-notifications/steps/send-restock-notification.ts` with the following content:
1259
1260 ![The directory structure of the Medusa application after adding the step.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733234507/Medusa%20Resources/restock-dir-overview-18_uvlu0l.jpg)
1261
1262 ```ts title="src/workflows/send-restock-notifications/steps/send-restock-notification.ts"
1263 import { promiseAll, Modules } from "@medusajs/framework/utils"
1264 import { createStep } from "@medusajs/framework/workflows-sdk"
1265 import { InferTypeOf, ProductVariantDTO } from "@medusajs/framework/types"
1266 import RestockSubscription from "../../../modules/restock/models/restock-subscription"
1267
1268 type SendRestockNotificationStepInput = (InferTypeOf<typeof RestockSubscription> & {
1269 product_variant?: ProductVariantDTO
1270 })[]
1271
1272 export const sendRestockNotificationStep = createStep(
1273 "send-restock-notification",
1274 async (input: SendRestockNotificationStepInput, { container }) => {
1275 const notificationModuleService = container.resolve(
1276 Modules.NOTIFICATION
1277 )
1278
1279 const notificationData = input.map((subscription) => ({
1280 to: subscription.email,
1281 channel: "email",
1282 template: "variant-restock",
1283 data: {
1284 variant: subscription.product_variant,
1285 },
1286 }))
1287
1288 await notificationModuleService.createNotifications(notificationData)
1289 }
1290 )
1291 ```
1292
1293 This step resolves the Notification Module's service from the Medusa container and, for each subscription, sends a notification to its subscribers.
1294
1295 To send a notification, you use the `createNotifications` method of the Notification Module's service. It accepts an array of notification objects, each having the following properties:
1296
1297 - `to`: The email to send the notification to.
1298 - `channel`: The channel to send the notification through, which is `email` for sending an email.
1299 - `template`: The email template to use for this notification.
1300 - `data`: Data to pass to the template relevant for the notification. Since the email will probably include details about the variant, you pass the variant's details.
1301
1302 ### deleteRestockSubscriptionStep
1303
1304 The final step deletes the restock subscriptions whose subscribers have been notified.
1305
1306 Create the file `src/workflows/send-restock-notifications/steps/delete-restock-subscriptions.ts` with the following content:
1307
1308 ![The directory structure of the Medusa application after adding the step.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733234506/Medusa%20Resources/restock-dir-overview-19_qfospx.jpg)
1309
1310 ```ts title="src/workflows/send-restock-notifications/steps/delete-restock-subscriptions.ts"
1311 import { InferTypeOf } from "@medusajs/framework/types"
1312 import RestockSubscription from "../../../modules/restock/models/restock-subscription"
1313 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1314 import RestockModuleService from "../../../modules/restock/service"
1315 import { RESTOCK_MODULE } from "../../../modules/restock"
1316
1317 type DeleteRestockSubscriptionsStepInput = InferTypeOf<typeof RestockSubscription>[]
1318
1319 export const deleteRestockSubscriptionStep = createStep(
1320 "delete-restock-subscription",
1321 async (
1322 restockSubscriptions: DeleteRestockSubscriptionsStepInput,
1323 { container }
1324 ) => {
1325 const restockModuleService: RestockModuleService = container.resolve(
1326 RESTOCK_MODULE
1327 )
1328
1329 await restockModuleService.deleteRestockSubscriptions(
1330 restockSubscriptions.map((subscription) => subscription.id)
1331 )
1332
1333 return new StepResponse(undefined, restockSubscriptions)
1334 },
1335 async (restockSubscriptions, { container }) => {
1336 if (!restockSubscriptions) {
1337 return
1338 }
1339
1340 const restockModuleService: RestockModuleService = container.resolve(
1341 RESTOCK_MODULE
1342 )
1343
1344 await restockModuleService.createRestockSubscriptions(restockSubscriptions)
1345 }
1346 )
1347 ```
1348
1349 In the step, you resolve the Restock Module's service and use its `deleteRestockSubscriptions` to delete the restock subscriptions.
1350
1351 In the step's compensation, which receives the deleted restock subscriptions as a parameter, you resolve the Restock Module's service and use its `createRestockSubscriptions` to create these subscriptions again if an error occurs.
1352
1353 ### Implement sendRestockNotificationsWorkflow
1354
1355 You can now implement the workflow that sends restock notifications using the above steps.
1356
1357 Create the file `src/workflows/send-restock-notifications/index.ts` with the following content:
1358
1359 ![The directory structure of the Medusa application after adding the workflow.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733234507/Medusa%20Resources/restock-dir-overview-20_mcqkkx.jpg)
1360
1361 ```ts title="src/workflows/send-restock-notifications/index.ts"
1362 import { createWorkflow, transform, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
1363 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
1364 import { getRestockedStep } from "./steps/get-restocked"
1365 import { sendRestockNotificationStep } from "./steps/send-restock-notification"
1366 import { deleteRestockSubscriptionStep } from "./steps/delete-restock-subscriptions"
1367 import { getDistinctSubscriptionsStep } from "./steps/get-distinct-subscriptions"
1368
1369 export const sendRestockNotificationsWorkflow = createWorkflow(
1370 "send-restock-notifications",
1371 () => {
1372 const subscriptions = getDistinctSubscriptionsStep()
1373
1374 // @ts-ignore
1375 const restockedSubscriptions = getRestockedStep(subscriptions)
1376
1377 const { variant_ids, sales_channel_ids } = transform({
1378 restockedSubscriptions,
1379 }, (data) => {
1380 const filters: Record<string, string[]> = {
1381 variant_ids: [],
1382 sales_channel_ids: [],
1383 }
1384 data.restockedSubscriptions.map((subscription) => {
1385 filters.variant_ids.push(subscription.variant_id)
1386 filters.sales_channel_ids.push(subscription.sales_channel_id)
1387 })
1388
1389 return filters
1390 })
1391
1392 const { data: restockedSubscriptionsWithEmails } = useQueryGraphStep({
1393 entity: "restock_subscription",
1394 fields: ["*", "product_variant.*"],
1395 filters: {
1396 variant_id: variant_ids,
1397 sales_channel_id: sales_channel_ids,
1398 },
1399 })
1400
1401 // @ts-ignore
1402 sendRestockNotificationStep(restockedSubscriptionsWithEmails)
1403
1404 // @ts-ignore
1405 deleteRestockSubscriptionStep(restockedSubscriptionsWithEmails)
1406
1407 return new WorkflowResponse({
1408 subscriptions: restockedSubscriptionsWithEmails,
1409 })
1410 }
1411 )
1412 ```
1413
1414 This workflow has the following steps:
1415
1416 1. `getDistinctSubscriptionsStep` to retrieve the restock subscriptions by distinct variant and sales channel ID pairings.
1417 2. `getRestockedStep` to filter the subscriptions retrieved by the previous step and return only those whose variants have been restocked.
1418 1. `useQueryGraphStep` to retrieve all subscriptions that have a restocked variant and sales channel ID pairing using [Query](!docs!/learn/fundamentals/query). Notice that in the specified `fields` you pass `product_variant.*`, which retrieves the details of the subscription's variant from the Product Module. This is possible due to the module link you created between the `RestockSubscription` and `ProductVariant` models in an earlier step.
1419 3. `sendRestockNotificationStep` to send the notification to the subscribers of the restocked variants.
1420 4. `deleteRestockSubscriptionStep` to delete the restock subscriptions since their subscribers have been notified.
1421
1422 The workflow returns the restocked subscriptions, which are now deleted.
1423
1424 You'll execute this workflow in the next section.
1425
1426 ---
1427
1428 ## Step 7: Send Restock Notifications Daily
1429
1430 Now that you've built the flow to send restock notifications, you want to check for restocked variants and send notifications to their subscribers once a day. To do so, you'll use a scheduled job.
1431
1432 A scheduled job is an asynchronous function that the Medusa application runs at the schedule you specify during the Medusa application's runtime. Scheduled jobs are useful for automating tasks at a fixed schedule.
1433
1434 <Note>
1435
1436 Learn more about scheduled jobs in [this documentation](!docs!/learn/fundamentals/scheduled-jobs).
1437
1438 </Note>
1439
1440 In this step, you'll create a scheduled job that runs once a day to execute the `sendRestockNotificationsWorkflow` from the previous step.
1441
1442 A scheduled job is created in a TypeScript or JavaScript file under the `src/jobs` directory. So, create the file `src/jobs/check-restock.ts` with the following content:
1443
1444 ![The directory structure of the Medusa application after adding the scheduled job.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733234524/Medusa%20Resources/restock-dir-overview-21_reaqp3.jpg)
1445
1446 ```ts title="src/jobs/check-restock.ts"
1447 import {
1448 MedusaContainer,
1449 } from "@medusajs/framework/types"
1450 import {
1451 sendRestockNotificationsWorkflow,
1452 } from "../workflows/send-restock-notifications"
1453
1454 export default async function myCustomJob(container: MedusaContainer) {
1455 await sendRestockNotificationsWorkflow(container)
1456 .run()
1457 }
1458
1459 export const config = {
1460 name: "check-restock",
1461 schedule: "0 0 * * *", // For debugging, change to `* * * * *`
1462 }
1463 ```
1464
1465 In this file, you export:
1466
1467 - An asynchronous function, which is the task to execute at the specified schedule.
1468 - A configuration object having the following properties:
1469 - `name`: A unique name for the scheduled job.
1470 - `schedule`: A [cron expression](https://crontab.guru/) string indicating the schedule to run the job at. The specified schedule indicates that this job should run every day at midnight.
1471
1472 The scheduled job function accepts the Medusa container as a parameter. In the function, you execute the `sendRestockNotificationsWorkflow` by invoking it, passing it the container, then executing its `run` method.
1473
1474 ### Test Scheduled Job
1475
1476 To test out the scheduled job, start the Medusa application:
1477
1478 ```bash npm2yarn
1479 npm run dev
1480 ```
1481
1482 Then, open the Medusa Admin again at `http://localhost:9000/app` and log in. After that:
1483
1484 1. Go to the same product -> variant that you edited earlier to make out of stock.
1485 2. On the variant's details page, click on an inventory item under the Inventory Items section.
1486
1487 ![The inventory items table shows the variant's items. Click on an item to open its details page.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733230649/Medusa%20Resources/Screenshot_2024-12-03_at_2.57.01_PM_ccc9of.png)
1488
1489 3. On the inventory item's page, click on the three dots icon next to a location, then choose edit from the dropdown.
1490
1491 ![The locations are shown in a table. Click on the three-dots at a location's right side, then choose Edit from the dropdown.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733230730/Medusa%20Resources/Screenshot_2024-12-03_at_2.58.18_PM_waeepw.png)
1492
1493 4. In the drawer form, enter any value greater than `0`.
1494 5. Click the Save button.
1495
1496 ![In the drawer form, enter value greater than `0` in the In stock field, then click the Save button at the bottom.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733234710/Medusa%20Resources/Screenshot_2024-12-03_at_3.53.55_PM_uwt06f.png)
1497
1498 With this change, the variant you previously subscribed to is now restocked. To trigger the scheduled job to run, change its `config` object to run every minute:
1499
1500 ```ts title="src/jobs/check-restock.ts"
1501 // ...
1502 export const config = {
1503 // ...
1504 schedule: "* * * * *", // For debugging, change to `* * * * *`
1505 }
1506 ```
1507
1508 After the application restarts, wait for the scheduled job to execute. If you're using the default Notification Module Provider that logs notifications in the terminal, you'll see a message similar to the following:
1509
1510 ```bash
1511 Attempting to send a notification to: 'customer@gmail.com' on the channel: 'email' with template: 'variant-restock' and data: '{"variant":{"id":"variant_01JE3H6WHFMJ2WS64RM2MV1CJ6",...}}'
1512 ```
1513
1514 ---
1515
1516 ## Next Steps
1517
1518 You've now implemented restock notifications in Medusa. You can also customize the [storefront](../../../nextjs-starter/page.mdx) to allow customers to subscribe to the restock notification using the new API route you added.
1519
1520 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.
1521
1522 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).