|
1
|
import { MathBN, MedusaError } from "@medusajs/framework/utils"; |
|
2
|
import { createStep } from "@medusajs/framework/workflows-sdk"; |
|
3
|
import { ModuleAccountStats, ModuleGiftCard } from "../../../types"; |
|
4
|
|
|
5
|
/** |
|
6
|
* Input to validate that all gift cards in a collection have a positive balance. |
|
7
|
*/ |
|
8
|
export interface ValidateGiftCardBalancesStepInput { |
|
9
|
/** |
|
10
|
* The gift cards to validate. |
|
11
|
*/ |
|
12
|
giftCards: ModuleGiftCard[] |
|
13
|
/** |
|
14
|
* A map of gift card codes to their account statistics, including the current balance. |
|
15
|
*/ |
|
16
|
giftCardsBalanceMap: Record<string, ModuleAccountStats> |
|
17
|
} |
|
18
|
|
|
19
|
/** |
|
20
|
* This step validates that all gift cards in a collection have a positive balance. |
|
21
|
* It throws an error for any gift card with zero or negative balance. |
|
22
|
* |
|
23
|
* @example |
|
24
|
* const data = validateGiftCardBalancesStep({ |
|
25
|
* giftCards: [ |
|
26
|
* { |
|
27
|
* id: "gc_123", |
|
28
|
* code: "GC-XXXX", |
|
29
|
* // other gift card properties... |
|
30
|
* } |
|
31
|
* ], |
|
32
|
* giftCardsBalanceMap: { |
|
33
|
* "GC-XXXX": { |
|
34
|
* balance: 100, |
|
35
|
* credit: 150, |
|
36
|
* debit: 50, |
|
37
|
* } |
|
38
|
* }, |
|
39
|
* }) |
|
40
|
*/ |
|
41
|
export const validateGiftCardBalancesStep = createStep( |
|
42
|
"validate-gift-card-balances", |
|
43
|
async function ({ |
|
44
|
giftCards, |
|
45
|
giftCardsBalanceMap, |
|
46
|
}: ValidateGiftCardBalancesStepInput) { |
|
47
|
for (const giftCard of giftCards) { |
|
48
|
const stats = giftCardsBalanceMap[giftCard.code]; |
|
49
|
|
|
50
|
if (MathBN.convert(stats.balance).lte(0)) { |
|
51
|
throw new MedusaError( |
|
52
|
MedusaError.Types.INVALID_DATA, |
|
53
|
`Gift card (${giftCard.code}) has no balance` |
|
54
|
); |
|
55
|
} |
|
56
|
} |
|
57
|
} |
|
58
|
); |