1 import {
2 convertItemResponseToUpdateRequest,
3 getSelectsAndRelationsFromObjectArray,
4 } from "@medusajs/framework/utils";
5 import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk";
6 import {
7 ILoyaltyModuleService,
8 ModuleUpdateGiftCard,
9 PluginModule,
10 } from "../../../types";
11
12 /**
13 * Data for updating one or more gift cards in the Loyalty module.
14 */
15 export type UpdateGiftCardsStepInput = ModuleUpdateGiftCard[]
16
17 /**
18 * This step updates gift cards. It stores the previous state of the gift cards
19 * before the update to enable rollback.
20 *
21 * @example
22 * const data = updateGiftCardsStep([
23 * {
24 * id: "gc_123",
25 * status: GiftCardStatus.REDEEMED,
26 * // other updatable gift card properties...
27 * },
28 * ])
29 */
30 export const updateGiftCardsStep = createStep(
31 "update-gift-cards",
32 async (data: UpdateGiftCardsStepInput, { container }) => {
33 const loyaltyModule = container.resolve<ILoyaltyModuleService>(
34 PluginModule.LOYALTY
35 );
36 const { selects, relations } = getSelectsAndRelationsFromObjectArray(data);
37
38 const dataBeforeUpdate = await loyaltyModule.listGiftCards(
39 { id: data.map((d) => d.id) },
40 { relations, select: selects }
41 );
42
43 const updatedGiftCards = await loyaltyModule.updateGiftCards(data);
44
45 return new StepResponse(updatedGiftCards, {
46 dataBeforeUpdate,
47 selects,
48 relations,
49 });
50 },
51 async (revertInput, { container }) => {
52 if (!revertInput) {
53 return;
54 }
55
56 const { dataBeforeUpdate, selects, relations } = revertInput;
57 const loyaltyModule = container.resolve<ILoyaltyModuleService>(
58 PluginModule.LOYALTY
59 );
60
61 const revertData = dataBeforeUpdate.map((data) =>
62 convertItemResponseToUpdateRequest(data, selects, relations)
63 );
64
65 if (revertData.length) {
66 await loyaltyModule.updateGiftCards(revertData);
67 }
68 }
69 );