|
1
|
import { isPresent } from "@medusajs/framework/utils" |
|
2
|
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk" |
|
3
|
import { |
|
4
|
ILoyaltyModuleService, |
|
5
|
ModuleCreateGiftCard, |
|
6
|
PluginModule, |
|
7
|
} from "../../../types" |
|
8
|
import { generateCode } from "../../../utils/code-generator" |
|
9
|
|
|
10
|
/** |
|
11
|
* Data for creating one or more gift cards in the Loyalty module. |
|
12
|
*/ |
|
13
|
export type CreateGiftCardsStepInput = ModuleCreateGiftCard[] |
|
14
|
|
|
15
|
/** |
|
16
|
* This step creates gift cards. If no code is provided for |
|
17
|
* a gift card, a unique code is automatically generated. The step supports rollback |
|
18
|
* by deleting the created gift cards. |
|
19
|
* |
|
20
|
* @example |
|
21
|
* const data = createGiftCardsStep([ |
|
22
|
* { |
|
23
|
* value: 100, |
|
24
|
* currency_code: "usd", |
|
25
|
* // other gift card properties... |
|
26
|
* }, |
|
27
|
* ]) |
|
28
|
*/ |
|
29
|
export const createGiftCardsStep = createStep( |
|
30
|
"create-gift-cards", |
|
31
|
async (input: CreateGiftCardsStepInput, { container }) => { |
|
32
|
const module = container.resolve<ILoyaltyModuleService>( |
|
33
|
PluginModule.LOYALTY |
|
34
|
) |
|
35
|
|
|
36
|
const { prefix, sections } = await module.getOptions() |
|
37
|
|
|
38
|
for (const giftCard of input) { |
|
39
|
if (!isPresent(giftCard.code)) { |
|
40
|
giftCard.code = generateCode(prefix, sections) |
|
41
|
} |
|
42
|
} |
|
43
|
|
|
44
|
const giftCards = await module.createGiftCards(input) |
|
45
|
|
|
46
|
return new StepResponse( |
|
47
|
giftCards, |
|
48
|
giftCards.map((gc) => gc.id) |
|
49
|
) |
|
50
|
}, |
|
51
|
async (ids, { container }) => { |
|
52
|
if (!ids?.length) { |
|
53
|
return |
|
54
|
} |
|
55
|
|
|
56
|
const module = container.resolve<ILoyaltyModuleService>( |
|
57
|
PluginModule.LOYALTY |
|
58
|
) |
|
59
|
|
|
60
|
await module.deleteGiftCards(ids) |
|
61
|
} |
|
62
|
) |