1 import {
2 Context,
3 DAL,
4 InferEntityType,
5 InternalModuleDeclaration,
6 IStoreModuleService,
7 ModulesSdkTypes,
8 StoreTypes,
9 } from "@medusajs/framework/types"
10 import {
11 EmitEvents,
12 getDuplicates,
13 InjectManager,
14 InjectTransactionManager,
15 isString,
16 MedusaContext,
17 MedusaError,
18 MedusaService,
19 normalizeCurrencyCode,
20 promiseAll,
21 removeUndefined,
22 } from "@medusajs/framework/utils"
23
24 import { Store, StoreCurrency, StoreLocale } from "@models"
25 import { UpdateStoreInput } from "@types"
26
27 type InjectedDependencies = {
28 baseRepository: DAL.RepositoryService
29 storeService: ModulesSdkTypes.IMedusaInternalService<any>
30 }
31
32 export default class StoreModuleService
33 extends MedusaService<{
34 Store: { dto: StoreTypes.StoreDTO }
35 StoreCurrency: { dto: StoreTypes.StoreCurrencyDTO }
36 StoreLocale: { dto: StoreTypes.StoreLocaleDTO }
37 }>({ Store, StoreCurrency, StoreLocale })
38 implements IStoreModuleService
39 {
40 protected baseRepository_: DAL.RepositoryService
41 protected readonly storeService_: ModulesSdkTypes.IMedusaInternalService<
42 InferEntityType<typeof Store>
43 >
44
45 constructor(
46 { baseRepository, storeService }: InjectedDependencies,
47 protected readonly moduleDeclaration: InternalModuleDeclaration
48 ) {
49 // @ts-ignore
50 super(...arguments)
51 this.baseRepository_ = baseRepository
52 this.storeService_ = storeService
53 }
54
55 // @ts-expect-error
56 async createStores(
57 data: StoreTypes.CreateStoreDTO[],
58 sharedContext?: Context
59 ): Promise<StoreTypes.StoreDTO[]>
60 // @ts-expect-error
61 async createStores(
62 data: StoreTypes.CreateStoreDTO,
63 sharedContext?: Context
64 ): Promise<StoreTypes.StoreDTO>
65
66 @InjectManager()
67 @EmitEvents()
68 // @ts-expect-error
69 async createStores(
70 data: StoreTypes.CreateStoreDTO | StoreTypes.CreateStoreDTO[],
71 @MedusaContext() sharedContext: Context = {}
72 ): Promise<StoreTypes.StoreDTO | StoreTypes.StoreDTO[]> {
73 const input = Array.isArray(data) ? data : [data]
74
75 const result = await this.create_(input, sharedContext)
76
77 return await this.baseRepository_.serialize<StoreTypes.StoreDTO[]>(
78 Array.isArray(data) ? result : result[0]
79 )
80 }
81
82 @InjectTransactionManager()
83 async create_(
84 data: StoreTypes.CreateStoreDTO[],
85 @MedusaContext() sharedContext: Context = {}
86 ): Promise<InferEntityType<typeof Store>[]> {
87 let normalizedInput = StoreModuleService.normalizeInput(data)
88 StoreModuleService.validateCreateRequest(normalizedInput)
89
90 return (
91 await this.storeService_.upsertWithReplace(
92 normalizedInput,
93 { relations: ["supported_currencies", "supported_locales"] },
94 sharedContext
95 )
96 ).entities
97 }
98
99 async upsertStores(
100 data: StoreTypes.UpsertStoreDTO[],
101 sharedContext?: Context
102 ): Promise<StoreTypes.StoreDTO[]>
103 async upsertStores(
104 data: StoreTypes.UpsertStoreDTO,
105 sharedContext?: Context
106 ): Promise<StoreTypes.StoreDTO>
107
108 @InjectManager()
109 @EmitEvents()
110 async upsertStores(
111 data: StoreTypes.UpsertStoreDTO | StoreTypes.UpsertStoreDTO[],
112 @MedusaContext() sharedContext: Context = {}
113 ): Promise<StoreTypes.StoreDTO | StoreTypes.StoreDTO[]> {
114 const result = await this.upsertStores_(data, sharedContext)
115
116 return await this.baseRepository_.serialize<
117 StoreTypes.StoreDTO[] | StoreTypes.StoreDTO
118 >(Array.isArray(data) ? result : result[0])
119 }
120
121 @InjectTransactionManager()
122 protected async upsertStores_(
123 data: StoreTypes.UpsertStoreDTO | StoreTypes.UpsertStoreDTO[],
124 @MedusaContext() sharedContext: Context = {}
125 ): Promise<InferEntityType<typeof Store>[]> {
126 const input = Array.isArray(data) ? data : [data]
127 const forUpdate = input.filter(
128 (store): store is UpdateStoreInput => !!store.id
129 )
130 const forCreate = input.filter(
131 (store): store is StoreTypes.CreateStoreDTO => !store.id
132 )
133
134 const operations: Promise<InferEntityType<typeof Store>[]>[] = []
135
136 if (forCreate.length) {
137 operations.push(this.create_(forCreate, sharedContext))
138 }
139 if (forUpdate.length) {
140 operations.push(this.update_(forUpdate, sharedContext))
141 }
142
143 const result = (await promiseAll(operations)).flat()
144
145 return result
146 }
147
148 // @ts-expect-error
149 async updateStores(
150 id: string,
151 data: StoreTypes.UpdateStoreDTO,
152 sharedContext?: Context
153 ): Promise<StoreTypes.StoreDTO>
154 // @ts-expect-error
155 async updateStores(
156 selector: StoreTypes.FilterableStoreProps,
157 data: StoreTypes.UpdateStoreDTO,
158 sharedContext?: Context
159 ): Promise<StoreTypes.StoreDTO[]>
160
161 @InjectManager()
162 @EmitEvents()
163 // @ts-expect-error
164 async updateStores(
165 idOrSelector: string | StoreTypes.FilterableStoreProps,
166 data: StoreTypes.UpdateStoreDTO,
167 @MedusaContext() sharedContext: Context = {}
168 ): Promise<StoreTypes.StoreDTO | StoreTypes.StoreDTO[]> {
169 let normalizedInput: UpdateStoreInput[] = []
170 if (isString(idOrSelector)) {
171 normalizedInput = [{ id: idOrSelector, ...data }]
172 } else {
173 const stores = await this.storeService_.list(
174 idOrSelector,
175 {},
176 sharedContext
177 )
178
179 normalizedInput = stores.map((store) => ({
180 id: store.id,
181 ...data,
182 }))
183 }
184
185 const updateResult = await this.update_(normalizedInput, sharedContext)
186
187 const stores = await this.baseRepository_.serialize<
188 StoreTypes.StoreDTO[] | StoreTypes.StoreDTO
189 >(updateResult)
190
191 return isString(idOrSelector) ? stores[0] : stores
192 }
193
194 @InjectTransactionManager()
195 protected async update_(
196 data: UpdateStoreInput[],
197 @MedusaContext() sharedContext: Context = {}
198 ): Promise<InferEntityType<typeof Store>[]> {
199 const normalizedInput = StoreModuleService.normalizeInput(data)
200 StoreModuleService.validateUpdateRequest(normalizedInput)
201
202 return (
203 await this.storeService_.upsertWithReplace(
204 normalizedInput,
205 { relations: ["supported_currencies", "supported_locales"] },
206 sharedContext
207 )
208 ).entities
209 }
210
211 private static normalizeInput<T extends StoreTypes.UpdateStoreDTO>(
212 stores: T[]
213 ): T[] {
214 return stores.map((store) =>
215 removeUndefined({
216 ...store,
217 supported_currencies: store.supported_currencies?.map((c) => ({
218 ...c,
219 currency_code: normalizeCurrencyCode(c.currency_code),
220 })),
221 name: store.name?.trim(),
222 })
223 )
224 }
225
226 private static validateCreateRequest(
227 stores: StoreTypes.CreateStoreDTO[] | StoreTypes.UpdateStoreDTO[]
228 ) {
229 for (const store of stores) {
230 if (store.supported_currencies?.length) {
231 StoreModuleService.validateUnique(
232 store.supported_currencies.map((currency) => currency.currency_code),
233 "currency"
234 )
235
236 let seenDefault = false
237 store.supported_currencies.forEach((currency) => {
238 if (currency.is_default) {
239 if (seenDefault) {
240 throw new MedusaError(
241 MedusaError.Types.INVALID_DATA,
242 `Only one default currency is allowed`
243 )
244 }
245 seenDefault = true
246 }
247 })
248
249 if (!seenDefault) {
250 throw new MedusaError(
251 MedusaError.Types.INVALID_DATA,
252 `There should be a default currency set for the store`
253 )
254 }
255 }
256
257 if (store.supported_locales?.length) {
258 StoreModuleService.validateUnique(
259 store.supported_locales.map((locale) => locale.locale_code),
260 "locale"
261 )
262 }
263 }
264 }
265
266 private static validateUnique = (items: string[], fieldName: string) => {
267 const duplicates = getDuplicates(items)
268
269 if (duplicates.length) {
270 throw new MedusaError(
271 MedusaError.Types.INVALID_DATA,
272 `Duplicate ${fieldName} codes: ${duplicates.join(", ")}`
273 )
274 }
275 }
276
277 private static validateUpdateRequest(stores: UpdateStoreInput[]) {
278 StoreModuleService.validateCreateRequest(stores)
279 }
280 }