1
1
import { IPromotionModuleService } from "@medusajs/framework/types"
2
- import { Modules , PromotionActions } from "@medusajs/framework/utils"
3
- import { StepResponse , createStep } from "@medusajs/framework/workflows-sdk"
2
+ import {
3
+ MedusaError ,
4
+ Modules ,
5
+ PromotionActions ,
6
+ } from "@medusajs/framework/utils"
7
+ import { createStep , StepResponse } from "@medusajs/framework/workflows-sdk"
4
8
5
9
/**
6
10
* The details of the promotion codes to apply on a cart.
@@ -68,14 +72,12 @@ export const getPromotionCodesToApply = createStep(
68
72
async ( data : GetPromotionCodesToApplyStepInput , { container } ) => {
69
73
const { promo_codes = [ ] , cart, action = PromotionActions . ADD } = data
70
74
const { items = [ ] , shipping_methods = [ ] } = cart
71
- const adjustmentCodes : string [ ] = [ ]
72
75
const promotionService = container . resolve < IPromotionModuleService > (
73
76
Modules . PROMOTION
74
77
)
75
78
76
- const objects = items . concat ( shipping_methods )
77
-
78
- objects . forEach ( ( object ) => {
79
+ const adjustmentCodes : string [ ] = [ ]
80
+ items . concat ( shipping_methods ) . forEach ( ( object ) => {
79
81
object . adjustments ?. forEach ( ( adjustment ) => {
80
82
if ( adjustment . code && ! adjustmentCodes . includes ( adjustment . code ) ) {
81
83
adjustmentCodes . push ( adjustment . code )
@@ -94,17 +96,38 @@ export const getPromotionCodesToApply = createStep(
94
96
: [ ]
95
97
)
96
98
97
- if ( action === PromotionActions . ADD ) {
98
- promo_codes . forEach ( ( code ) => promotionCodesToApply . add ( code ) )
99
- }
100
-
101
99
if ( action === PromotionActions . REMOVE ) {
102
100
promo_codes . forEach ( ( code ) => promotionCodesToApply . delete ( code ) )
103
101
}
104
102
105
103
if ( action === PromotionActions . REPLACE ) {
106
104
promotionCodesToApply . clear ( )
107
- promo_codes . forEach ( ( code ) => promotionCodesToApply . add ( code ) )
105
+ }
106
+
107
+ if (
108
+ action === PromotionActions . ADD ||
109
+ action === PromotionActions . REPLACE
110
+ ) {
111
+ const validPromoCodes : Set < string > = new Set (
112
+ promo_codes . length
113
+ ? (
114
+ await promotionService . listPromotions (
115
+ { code : promo_codes } ,
116
+ { select : [ "code" ] }
117
+ )
118
+ ) . map ( ( p ) => p . code ! )
119
+ : [ ]
120
+ )
121
+
122
+ promo_codes . forEach ( ( code ) => {
123
+ if ( ! validPromoCodes . has ( code ) ) {
124
+ throw new MedusaError (
125
+ MedusaError . Types . INVALID_DATA ,
126
+ `The promotion code ${ code } is invalid`
127
+ )
128
+ }
129
+ promotionCodesToApply . add ( code )
130
+ } )
108
131
}
109
132
110
133
return new StepResponse (
0 commit comments