|
1
|
import { |
|
2
|
Context, |
|
3
|
CreateRegionDTO, |
|
4
|
DAL, |
|
5
|
FilterableRegionProps, |
|
6
|
InferEntityType, |
|
7
|
InternalModuleDeclaration, |
|
8
|
IRegionModuleService, |
|
9
|
ModulesSdkTypes, |
|
10
|
RegionCountryDTO, |
|
11
|
RegionDTO, |
|
12
|
SoftDeleteReturn, |
|
13
|
UpdateRegionDTO, |
|
14
|
UpsertRegionDTO, |
|
15
|
} from "@medusajs/framework/types" |
|
16
|
import { |
|
17
|
arrayDifference, |
|
18
|
EmitEvents, |
|
19
|
getDuplicates, |
|
20
|
InjectManager, |
|
21
|
InjectTransactionManager, |
|
22
|
isString, |
|
23
|
MedusaContext, |
|
24
|
MedusaError, |
|
25
|
MedusaService, |
|
26
|
normalizeCurrencyCode, |
|
27
|
promiseAll, |
|
28
|
removeUndefined, |
|
29
|
} from "@medusajs/framework/utils" |
|
30
|
import { Country, Region } from "@models" |
|
31
|
import { UpdateRegionInput } from "@types" |
|
32
|
|
|
33
|
type InjectedDependencies = { |
|
34
|
baseRepository: DAL.RepositoryService |
|
35
|
regionService: ModulesSdkTypes.IMedusaInternalService<any> |
|
36
|
countryService: ModulesSdkTypes.IMedusaInternalService<any> |
|
37
|
} |
|
38
|
|
|
39
|
export default class RegionModuleService |
|
40
|
extends MedusaService<{ |
|
41
|
Region: { |
|
42
|
dto: RegionDTO |
|
43
|
model: typeof Region |
|
44
|
} |
|
45
|
Country: { |
|
46
|
dto: RegionCountryDTO |
|
47
|
model: typeof Country |
|
48
|
} |
|
49
|
}>({ Region, Country }) |
|
50
|
implements IRegionModuleService |
|
51
|
{ |
|
52
|
protected baseRepository_: DAL.RepositoryService |
|
53
|
protected readonly regionService_: ModulesSdkTypes.IMedusaInternalService< |
|
54
|
typeof Region |
|
55
|
> |
|
56
|
protected readonly countryService_: ModulesSdkTypes.IMedusaInternalService< |
|
57
|
typeof Country |
|
58
|
> |
|
59
|
|
|
60
|
constructor( |
|
61
|
{ baseRepository, regionService, countryService }: InjectedDependencies, |
|
62
|
protected readonly moduleDeclaration: InternalModuleDeclaration |
|
63
|
) { |
|
64
|
// @ts-ignore |
|
65
|
super(...arguments) |
|
66
|
this.baseRepository_ = baseRepository |
|
67
|
this.regionService_ = regionService |
|
68
|
this.countryService_ = countryService |
|
69
|
} |
|
70
|
|
|
71
|
// @ts-expect-error |
|
72
|
async createRegions( |
|
73
|
data: CreateRegionDTO[], |
|
74
|
sharedContext?: Context |
|
75
|
): Promise<RegionDTO[]> |
|
76
|
// @ts-expect-error |
|
77
|
async createRegions( |
|
78
|
data: CreateRegionDTO, |
|
79
|
sharedContext?: Context |
|
80
|
): Promise<RegionDTO> |
|
81
|
|
|
82
|
@InjectManager() |
|
83
|
@EmitEvents() |
|
84
|
// @ts-expect-error |
|
85
|
async createRegions( |
|
86
|
data: CreateRegionDTO | CreateRegionDTO[], |
|
87
|
@MedusaContext() sharedContext: Context = {} |
|
88
|
): Promise<RegionDTO | RegionDTO[]> { |
|
89
|
const input = Array.isArray(data) ? data : [data] |
|
90
|
|
|
91
|
const result = await this.createRegions_(input, sharedContext) |
|
92
|
|
|
93
|
return await this.baseRepository_.serialize<RegionDTO[]>( |
|
94
|
Array.isArray(data) ? result : result[0] |
|
95
|
) |
|
96
|
} |
|
97
|
|
|
98
|
@InjectTransactionManager() |
|
99
|
async createRegions_( |
|
100
|
data: CreateRegionDTO[], |
|
101
|
@MedusaContext() sharedContext: Context = {} |
|
102
|
): Promise<InferEntityType<typeof Region>[]> { |
|
103
|
let normalizedInput = RegionModuleService.normalizeInput(data) |
|
104
|
|
|
105
|
let normalizedDbRegions = normalizedInput.map((region) => |
|
106
|
removeUndefined({ |
|
107
|
...region, |
|
108
|
countries: undefined, |
|
109
|
}) |
|
110
|
) |
|
111
|
|
|
112
|
const result = await this.regionService_.create( |
|
113
|
normalizedDbRegions, |
|
114
|
sharedContext |
|
115
|
) |
|
116
|
|
|
117
|
if (data.some((input) => input.countries?.length)) { |
|
118
|
await this.validateCountries( |
|
119
|
normalizedInput.map((r) => r.countries ?? []).flat(), |
|
120
|
sharedContext |
|
121
|
) |
|
122
|
|
|
123
|
await this.countryService_.update( |
|
124
|
normalizedInput.map((region, i) => ({ |
|
125
|
selector: { iso_2: region.countries }, |
|
126
|
data: { |
|
127
|
region_id: result[i].id, |
|
128
|
}, |
|
129
|
})), |
|
130
|
sharedContext |
|
131
|
) |
|
132
|
} |
|
133
|
|
|
134
|
return result |
|
135
|
} |
|
136
|
|
|
137
|
@InjectManager() |
|
138
|
@EmitEvents() |
|
139
|
// @ts-expect-error |
|
140
|
async softDeleteRegions( |
|
141
|
ids: string | object | string[] | object[], |
|
142
|
config?: SoftDeleteReturn<string>, |
|
143
|
@MedusaContext() sharedContext: Context = {} |
|
144
|
): Promise<Record<string, string[]> | void> { |
|
145
|
const result = await super.softDeleteRegions(ids, config, sharedContext) |
|
146
|
// Note: You cannot revert the state of a region by simply restoring it. The association with countries is lost. |
|
147
|
await super.updateCountries( |
|
148
|
{ |
|
149
|
selector: { region_id: ids }, |
|
150
|
data: { region_id: null } as any, |
|
151
|
}, |
|
152
|
sharedContext |
|
153
|
) |
|
154
|
|
|
155
|
return result |
|
156
|
} |
|
157
|
|
|
158
|
async upsertRegions( |
|
159
|
data: UpsertRegionDTO[], |
|
160
|
sharedContext?: Context |
|
161
|
): Promise<RegionDTO[]> |
|
162
|
async upsertRegions( |
|
163
|
data: UpsertRegionDTO, |
|
164
|
sharedContext?: Context |
|
165
|
): Promise<RegionDTO> |
|
166
|
|
|
167
|
@InjectManager() |
|
168
|
@EmitEvents() |
|
169
|
async upsertRegions( |
|
170
|
data: UpsertRegionDTO | UpsertRegionDTO[], |
|
171
|
@MedusaContext() sharedContext: Context = {} |
|
172
|
): Promise<RegionDTO | RegionDTO[]> { |
|
173
|
const result = await this.upsertRegions_(data, sharedContext) |
|
174
|
|
|
175
|
return await this.baseRepository_.serialize<RegionDTO[] | RegionDTO>( |
|
176
|
Array.isArray(data) ? result : result[0] |
|
177
|
) |
|
178
|
} |
|
179
|
|
|
180
|
@InjectTransactionManager() |
|
181
|
protected async upsertRegions_( |
|
182
|
data: UpsertRegionDTO | UpsertRegionDTO[], |
|
183
|
@MedusaContext() sharedContext: Context = {} |
|
184
|
): Promise<InferEntityType<typeof Region>[]> { |
|
185
|
const input = Array.isArray(data) ? data : [data] |
|
186
|
const forUpdate = input.filter( |
|
187
|
(region): region is UpdateRegionInput => !!region.id |
|
188
|
) |
|
189
|
const forCreate = input.filter( |
|
190
|
(region): region is CreateRegionDTO => !region.id |
|
191
|
) |
|
192
|
|
|
193
|
const operations: Promise<InferEntityType<typeof Region>[]>[] = [] |
|
194
|
|
|
195
|
if (forCreate.length) { |
|
196
|
operations.push(this.createRegions_(forCreate, sharedContext)) |
|
197
|
} |
|
198
|
if (forUpdate.length) { |
|
199
|
operations.push(this.updateRegions_(forUpdate, sharedContext)) |
|
200
|
} |
|
201
|
|
|
202
|
const result = (await promiseAll(operations)).flat() |
|
203
|
|
|
204
|
return result |
|
205
|
} |
|
206
|
|
|
207
|
// @ts-expect-error |
|
208
|
async updateRegions( |
|
209
|
id: string, |
|
210
|
data: UpdateRegionDTO, |
|
211
|
sharedContext?: Context |
|
212
|
): Promise<RegionDTO> |
|
213
|
// @ts-expect-error |
|
214
|
async updateRegions( |
|
215
|
selector: FilterableRegionProps, |
|
216
|
data: UpdateRegionDTO, |
|
217
|
sharedContext?: Context |
|
218
|
): Promise<RegionDTO[]> |
|
219
|
|
|
220
|
@InjectManager() |
|
221
|
@EmitEvents() |
|
222
|
// @ts-expect-error |
|
223
|
async updateRegions( |
|
224
|
idOrSelector: string | FilterableRegionProps, |
|
225
|
data: UpdateRegionDTO, |
|
226
|
@MedusaContext() sharedContext: Context = {} |
|
227
|
): Promise<RegionDTO | RegionDTO[]> { |
|
228
|
let normalizedInput: UpdateRegionInput[] = [] |
|
229
|
if (isString(idOrSelector)) { |
|
230
|
normalizedInput = [{ id: idOrSelector, ...data }] |
|
231
|
} else { |
|
232
|
const regions = await this.regionService_.list( |
|
233
|
idOrSelector, |
|
234
|
{}, |
|
235
|
sharedContext |
|
236
|
) |
|
237
|
|
|
238
|
normalizedInput = regions.map((region) => ({ |
|
239
|
id: region.id, |
|
240
|
...data, |
|
241
|
})) |
|
242
|
} |
|
243
|
|
|
244
|
const updateResult = await this.updateRegions_( |
|
245
|
normalizedInput, |
|
246
|
sharedContext |
|
247
|
) |
|
248
|
|
|
249
|
const regions = await this.baseRepository_.serialize< |
|
250
|
RegionDTO[] | RegionDTO |
|
251
|
>(updateResult) |
|
252
|
|
|
253
|
return isString(idOrSelector) ? regions[0] : regions |
|
254
|
} |
|
255
|
|
|
256
|
@InjectTransactionManager() |
|
257
|
protected async updateRegions_( |
|
258
|
data: UpdateRegionInput[], |
|
259
|
@MedusaContext() sharedContext: Context = {} |
|
260
|
): Promise<InferEntityType<typeof Region>[]> { |
|
261
|
const normalizedInput = RegionModuleService.normalizeInput(data) |
|
262
|
|
|
263
|
// If countries are being updated for a region, first make previously set countries' region to null to get to a clean slate. |
|
264
|
// Somewhat less efficient, but region operations will be very rare, so it is better to go with a simple solution |
|
265
|
const regionsWithCountryUpdate = normalizedInput |
|
266
|
.filter((region) => !!region.countries) |
|
267
|
.map((region) => region.id) |
|
268
|
.flat() |
|
269
|
|
|
270
|
let normalizedDbRegions = normalizedInput.map((region) => |
|
271
|
removeUndefined({ |
|
272
|
...region, |
|
273
|
countries: undefined, // -> delete countries if passed because we want to do update "manually" |
|
274
|
}) |
|
275
|
) |
|
276
|
|
|
277
|
if (regionsWithCountryUpdate.length) { |
|
278
|
await this.countryService_.update( |
|
279
|
{ |
|
280
|
selector: { |
|
281
|
region_id: regionsWithCountryUpdate, |
|
282
|
}, |
|
283
|
data: { region_id: null }, |
|
284
|
}, |
|
285
|
sharedContext |
|
286
|
) |
|
287
|
|
|
288
|
await this.validateCountries( |
|
289
|
normalizedInput.map((d) => d.countries ?? []).flat(), |
|
290
|
sharedContext |
|
291
|
) |
|
292
|
|
|
293
|
await this.countryService_.update( |
|
294
|
normalizedInput.map((region) => ({ |
|
295
|
selector: { iso_2: region.countries }, |
|
296
|
data: { |
|
297
|
region_id: region.id, |
|
298
|
}, |
|
299
|
})), |
|
300
|
sharedContext |
|
301
|
) |
|
302
|
} |
|
303
|
|
|
304
|
return await this.regionService_.update(normalizedDbRegions, sharedContext) |
|
305
|
} |
|
306
|
|
|
307
|
private static normalizeInput<T extends UpdateRegionDTO>(regions: T[]): T[] { |
|
308
|
return regions.map((region) => |
|
309
|
removeUndefined({ |
|
310
|
...region, |
|
311
|
currency_code: region.currency_code ? normalizeCurrencyCode(region.currency_code) : undefined, |
|
312
|
name: region.name?.trim(), |
|
313
|
countries: region.countries?.map((country) => country.toLowerCase()), |
|
314
|
}) |
|
315
|
) |
|
316
|
} |
|
317
|
|
|
318
|
/** |
|
319
|
* Validate that countries can be assigned to a region. |
|
320
|
* |
|
321
|
* NOTE: this method relies on countries of the regions that we are assigning to need to be unassigned first. |
|
322
|
* @param countries |
|
323
|
* @param sharedContext |
|
324
|
* @private |
|
325
|
*/ |
|
326
|
private async validateCountries( |
|
327
|
countries: string[] | undefined, |
|
328
|
sharedContext: Context |
|
329
|
): Promise<InferEntityType<typeof Country>[]> { |
|
330
|
if (!countries?.length) { |
|
331
|
return [] |
|
332
|
} |
|
333
|
|
|
334
|
// The new regions being created have a country conflict |
|
335
|
const uniqueCountries = Array.from(new Set(countries)) |
|
336
|
if (uniqueCountries.length !== countries.length) { |
|
337
|
throw new MedusaError( |
|
338
|
MedusaError.Types.INVALID_DATA, |
|
339
|
`Countries with codes: "${getDuplicates(countries).join( |
|
340
|
", " |
|
341
|
)}" are already assigned to a region` |
|
342
|
) |
|
343
|
} |
|
344
|
|
|
345
|
const countriesInDb = await this.countryService_.list( |
|
346
|
{ iso_2: uniqueCountries }, |
|
347
|
{ select: ["iso_2", "region_id"] }, |
|
348
|
sharedContext |
|
349
|
) |
|
350
|
const countryCodesInDb = countriesInDb.map((c) => c.iso_2.toLowerCase()) |
|
351
|
|
|
352
|
// Countries missing in the database |
|
353
|
if (countriesInDb.length !== uniqueCountries.length) { |
|
354
|
const missingCountries = arrayDifference( |
|
355
|
uniqueCountries, |
|
356
|
countryCodesInDb |
|
357
|
) |
|
358
|
|
|
359
|
throw new MedusaError( |
|
360
|
MedusaError.Types.INVALID_DATA, |
|
361
|
`Countries with codes: "${missingCountries.join(", ")}" do not exist` |
|
362
|
) |
|
363
|
} |
|
364
|
|
|
365
|
// Countries that already have a region already assigned to them |
|
366
|
// @ts-ignore |
|
367
|
const countriesWithRegion = countriesInDb.filter((c) => !!c.region_id) |
|
368
|
if (countriesWithRegion.length) { |
|
369
|
throw new MedusaError( |
|
370
|
MedusaError.Types.INVALID_DATA, |
|
371
|
`Countries with codes: "${countriesWithRegion |
|
372
|
.map((c) => c.iso_2) |
|
373
|
.join(", ")}" are already assigned to a region` |
|
374
|
) |
|
375
|
} |
|
376
|
|
|
377
|
return countriesInDb |
|
378
|
} |
|
379
|
} |