|
1
|
import { |
|
2
|
Context, |
|
3
|
DAL, |
|
4
|
InferEntityType, |
|
5
|
InternalModuleDeclaration, |
|
6
|
ITaxModuleService, |
|
7
|
ITaxProvider, |
|
8
|
ModulesSdkTypes, |
|
9
|
TaxRegionDTO, |
|
10
|
TaxTypes, |
|
11
|
} from "@medusajs/framework/types" |
|
12
|
import { |
|
13
|
EmitEvents, |
|
14
|
InjectManager, |
|
15
|
InjectTransactionManager, |
|
16
|
isDefined, |
|
17
|
isString, |
|
18
|
MedusaContext, |
|
19
|
MedusaError, |
|
20
|
ModulesSdkUtils, |
|
21
|
} from "@medusajs/framework/utils" |
|
22
|
import { TaxProvider, TaxRate, TaxRateRule, TaxRegion } from "@models" |
|
23
|
import { TaxProviderService } from "@services" |
|
24
|
|
|
25
|
type InjectedDependencies = { |
|
26
|
baseRepository: DAL.RepositoryService |
|
27
|
taxRateService: ModulesSdkTypes.IMedusaInternalService<any> |
|
28
|
taxRegionService: ModulesSdkTypes.IMedusaInternalService<any> |
|
29
|
taxRateRuleService: ModulesSdkTypes.IMedusaInternalService<any> |
|
30
|
taxProviderService: TaxProviderService |
|
31
|
[key: `tp_${string}`]: ITaxProvider |
|
32
|
} |
|
33
|
|
|
34
|
const generateForModels = { TaxRate, TaxRegion, TaxRateRule, TaxProvider } |
|
35
|
|
|
36
|
type ItemWithRates = { |
|
37
|
rates: InferEntityType<typeof TaxRate>[] |
|
38
|
item: TaxTypes.TaxableItemDTO | TaxTypes.TaxableShippingDTO |
|
39
|
} |
|
40
|
|
|
41
|
export default class TaxModuleService |
|
42
|
extends ModulesSdkUtils.MedusaService<{ |
|
43
|
TaxRate: { dto: TaxTypes.TaxRateDTO } |
|
44
|
TaxRegion: { dto: TaxTypes.TaxRegionDTO } |
|
45
|
TaxRateRule: { dto: TaxTypes.TaxRateRuleDTO } |
|
46
|
TaxProvider: { dto: TaxTypes.TaxProviderDTO } |
|
47
|
}>(generateForModels) |
|
48
|
implements ITaxModuleService |
|
49
|
{ |
|
50
|
protected readonly container_: InjectedDependencies |
|
51
|
protected baseRepository_: DAL.RepositoryService |
|
52
|
protected taxRateService_: ModulesSdkTypes.IMedusaInternalService< |
|
53
|
InferEntityType<typeof TaxRate> |
|
54
|
> |
|
55
|
protected taxRegionService_: ModulesSdkTypes.IMedusaInternalService< |
|
56
|
InferEntityType<typeof TaxRegion> |
|
57
|
> |
|
58
|
protected taxRateRuleService_: ModulesSdkTypes.IMedusaInternalService< |
|
59
|
InferEntityType<typeof TaxRateRule> |
|
60
|
> |
|
61
|
protected taxProviderService_: TaxProviderService |
|
62
|
|
|
63
|
constructor( |
|
64
|
{ |
|
65
|
baseRepository, |
|
66
|
taxRateService, |
|
67
|
taxRegionService, |
|
68
|
taxRateRuleService, |
|
69
|
taxProviderService, |
|
70
|
}: InjectedDependencies, |
|
71
|
protected readonly moduleDeclaration: InternalModuleDeclaration |
|
72
|
) { |
|
73
|
// @ts-ignore |
|
74
|
super(...arguments) |
|
75
|
|
|
76
|
this.container_ = arguments[0] |
|
77
|
this.baseRepository_ = baseRepository |
|
78
|
this.taxRateService_ = taxRateService |
|
79
|
this.taxRegionService_ = taxRegionService |
|
80
|
this.taxRateRuleService_ = taxRateRuleService |
|
81
|
this.taxProviderService_ = taxProviderService |
|
82
|
} |
|
83
|
|
|
84
|
// @ts-expect-error |
|
85
|
async createTaxRates( |
|
86
|
data: TaxTypes.CreateTaxRateDTO[], |
|
87
|
sharedContext?: Context |
|
88
|
): Promise<TaxTypes.TaxRateDTO[]> |
|
89
|
|
|
90
|
// @ts-expect-error |
|
91
|
async createTaxRates( |
|
92
|
data: TaxTypes.CreateTaxRateDTO, |
|
93
|
sharedContext?: Context |
|
94
|
): Promise<TaxTypes.TaxRateDTO> |
|
95
|
|
|
96
|
@InjectManager() |
|
97
|
@EmitEvents() |
|
98
|
// @ts-expect-error |
|
99
|
async createTaxRates( |
|
100
|
data: TaxTypes.CreateTaxRateDTO[] | TaxTypes.CreateTaxRateDTO, |
|
101
|
@MedusaContext() sharedContext: Context = {} |
|
102
|
): Promise<TaxTypes.TaxRateDTO[] | TaxTypes.TaxRateDTO> { |
|
103
|
const input = Array.isArray(data) ? data : [data] |
|
104
|
const rates = await this.createTaxRates_(input, sharedContext) |
|
105
|
|
|
106
|
const serialized = await this.baseRepository_.serialize< |
|
107
|
TaxTypes.TaxRateDTO[] | TaxTypes.TaxRateDTO |
|
108
|
>(rates) |
|
109
|
|
|
110
|
return Array.isArray(data) ? serialized : serialized[0] |
|
111
|
} |
|
112
|
|
|
113
|
@InjectTransactionManager() |
|
114
|
protected async createTaxRates_( |
|
115
|
data: TaxTypes.CreateTaxRateDTO[], |
|
116
|
@MedusaContext() sharedContext: Context = {} |
|
117
|
) { |
|
118
|
const [rules, rateData] = data.reduce( |
|
119
|
(acc, region) => { |
|
120
|
const { rules, ...rest } = region |
|
121
|
acc[0].push(rules) |
|
122
|
acc[1].push(rest) |
|
123
|
return acc |
|
124
|
}, |
|
125
|
[[], []] as [ |
|
126
|
(Omit<TaxTypes.CreateTaxRateRuleDTO, "tax_rate_id">[] | undefined)[], |
|
127
|
Partial<TaxTypes.CreateTaxRegionDTO>[] |
|
128
|
] |
|
129
|
) |
|
130
|
|
|
131
|
const rates = await this.taxRateService_.create(rateData, sharedContext) |
|
132
|
const rulesToCreate = rates |
|
133
|
.reduce((acc, rate, i) => { |
|
134
|
const rateRules = rules[i] |
|
135
|
if (isDefined(rateRules)) { |
|
136
|
acc.push( |
|
137
|
rateRules.map((r) => { |
|
138
|
return { |
|
139
|
...r, |
|
140
|
created_by: rate.created_by, |
|
141
|
tax_rate_id: rate.id, |
|
142
|
} |
|
143
|
}) |
|
144
|
) |
|
145
|
} |
|
146
|
return acc |
|
147
|
}, [] as TaxTypes.CreateTaxRateRuleDTO[][]) |
|
148
|
.flat() |
|
149
|
|
|
150
|
if (rulesToCreate.length > 0) { |
|
151
|
await this.taxRateRuleService_.create(rulesToCreate, sharedContext) |
|
152
|
} |
|
153
|
|
|
154
|
return rates |
|
155
|
} |
|
156
|
|
|
157
|
// @ts-expect-error |
|
158
|
async updateTaxRates( |
|
159
|
id: string, |
|
160
|
data: TaxTypes.UpdateTaxRateDTO, |
|
161
|
sharedContext?: Context |
|
162
|
): Promise<TaxTypes.TaxRateDTO> |
|
163
|
// @ts-expect-error |
|
164
|
async updateTaxRates( |
|
165
|
ids: string[], |
|
166
|
data: TaxTypes.UpdateTaxRateDTO, |
|
167
|
sharedContext?: Context |
|
168
|
): Promise<TaxTypes.TaxRateDTO[]> |
|
169
|
// @ts-expect-error |
|
170
|
async updateTaxRates( |
|
171
|
selector: TaxTypes.FilterableTaxRateProps, |
|
172
|
data: TaxTypes.UpdateTaxRateDTO, |
|
173
|
sharedContext?: Context |
|
174
|
): Promise<TaxTypes.TaxRateDTO[]> |
|
175
|
|
|
176
|
@InjectManager() |
|
177
|
@EmitEvents() |
|
178
|
// @ts-expect-error |
|
179
|
async updateTaxRates( |
|
180
|
selector: string | string[] | TaxTypes.FilterableTaxRateProps, |
|
181
|
data: TaxTypes.UpdateTaxRateDTO, |
|
182
|
@MedusaContext() sharedContext: Context = {} |
|
183
|
): Promise<TaxTypes.TaxRateDTO | TaxTypes.TaxRateDTO[]> { |
|
184
|
const rates = await this.updateTaxRates_(selector, data, sharedContext) |
|
185
|
|
|
186
|
const serialized = await this.baseRepository_.serialize< |
|
187
|
TaxTypes.TaxRateDTO[] |
|
188
|
>(rates) |
|
189
|
|
|
190
|
return isString(selector) ? serialized[0] : serialized |
|
191
|
} |
|
192
|
|
|
193
|
@InjectTransactionManager() |
|
194
|
protected async updateTaxRates_( |
|
195
|
idOrSelector: string | string[] | TaxTypes.FilterableTaxRateProps, |
|
196
|
data: TaxTypes.UpdateTaxRateDTO, |
|
197
|
@MedusaContext() sharedContext: Context = {} |
|
198
|
) { |
|
199
|
const selector = |
|
200
|
Array.isArray(idOrSelector) || isString(idOrSelector) |
|
201
|
? { id: idOrSelector } |
|
202
|
: idOrSelector |
|
203
|
|
|
204
|
if (data.rules) { |
|
205
|
await this.setTaxRateRulesForTaxRates( |
|
206
|
idOrSelector, |
|
207
|
data.rules, |
|
208
|
data.updated_by, |
|
209
|
sharedContext |
|
210
|
) |
|
211
|
|
|
212
|
delete data.rules |
|
213
|
} |
|
214
|
|
|
215
|
return await this.taxRateService_.update({ selector, data }, sharedContext) |
|
216
|
} |
|
217
|
|
|
218
|
private async setTaxRateRulesForTaxRates( |
|
219
|
idOrSelector: string | string[] | TaxTypes.FilterableTaxRateProps, |
|
220
|
rules: Omit<TaxTypes.CreateTaxRateRuleDTO, "tax_rate_id">[], |
|
221
|
createdBy?: string, |
|
222
|
sharedContext: Context = {} |
|
223
|
) { |
|
224
|
const selector = |
|
225
|
Array.isArray(idOrSelector) || isString(idOrSelector) |
|
226
|
? { id: idOrSelector } |
|
227
|
: idOrSelector |
|
228
|
|
|
229
|
await this.taxRateRuleService_.softDelete( |
|
230
|
{ tax_rate: selector }, |
|
231
|
sharedContext |
|
232
|
) |
|
233
|
|
|
234
|
// TODO: this is a temporary solution seems like mikro-orm doesn't persist |
|
235
|
// the soft delete which results in the creation below breaking the unique |
|
236
|
// constraint |
|
237
|
await this.taxRateRuleService_.list( |
|
238
|
{ tax_rate: selector }, |
|
239
|
{ select: ["id"] }, |
|
240
|
sharedContext |
|
241
|
) |
|
242
|
|
|
243
|
if (rules.length === 0) { |
|
244
|
return |
|
245
|
} |
|
246
|
|
|
247
|
const rateIds = await this.getTaxRateIdsFromSelector(idOrSelector) |
|
248
|
const toCreate = rateIds |
|
249
|
.map((id) => { |
|
250
|
return rules.map((r) => { |
|
251
|
return { |
|
252
|
...r, |
|
253
|
created_by: createdBy, |
|
254
|
tax_rate_id: id, |
|
255
|
} |
|
256
|
}) |
|
257
|
}) |
|
258
|
.flat() |
|
259
|
|
|
260
|
return await this.createTaxRateRules(toCreate, sharedContext) |
|
261
|
} |
|
262
|
|
|
263
|
private async getTaxRateIdsFromSelector( |
|
264
|
idOrSelector: string | string[] | TaxTypes.FilterableTaxRateProps, |
|
265
|
sharedContext: Context = {} |
|
266
|
) { |
|
267
|
if (Array.isArray(idOrSelector)) { |
|
268
|
return idOrSelector |
|
269
|
} |
|
270
|
|
|
271
|
if (isString(idOrSelector)) { |
|
272
|
return [idOrSelector] |
|
273
|
} |
|
274
|
|
|
275
|
const rates = await this.taxRateService_.list( |
|
276
|
idOrSelector, |
|
277
|
{ select: ["id"] }, |
|
278
|
sharedContext |
|
279
|
) |
|
280
|
return rates.map((r) => r.id) |
|
281
|
} |
|
282
|
|
|
283
|
async upsertTaxRates( |
|
284
|
data: TaxTypes.UpsertTaxRateDTO[], |
|
285
|
sharedContext?: Context |
|
286
|
): Promise<TaxTypes.TaxRateDTO[]> |
|
287
|
async upsertTaxRates( |
|
288
|
data: TaxTypes.UpsertTaxRateDTO, |
|
289
|
sharedContext?: Context |
|
290
|
): Promise<TaxTypes.TaxRateDTO> |
|
291
|
|
|
292
|
@InjectManager() |
|
293
|
@EmitEvents() |
|
294
|
async upsertTaxRates( |
|
295
|
data: TaxTypes.UpsertTaxRateDTO | TaxTypes.UpsertTaxRateDTO[], |
|
296
|
@MedusaContext() sharedContext: Context = {} |
|
297
|
): Promise<TaxTypes.TaxRateDTO | TaxTypes.TaxRateDTO[]> { |
|
298
|
const result = await this.taxRateService_.upsert(data, sharedContext) |
|
299
|
|
|
300
|
const serialized = await this.baseRepository_.serialize< |
|
301
|
TaxTypes.TaxRateDTO[] |
|
302
|
>(result) |
|
303
|
|
|
304
|
return Array.isArray(data) ? serialized : serialized[0] |
|
305
|
} |
|
306
|
|
|
307
|
// @ts-ignore |
|
308
|
createTaxRegions( |
|
309
|
data: TaxTypes.CreateTaxRegionDTO, |
|
310
|
sharedContext?: Context |
|
311
|
): Promise<TaxRegionDTO> |
|
312
|
|
|
313
|
// @ts-expect-error |
|
314
|
createTaxRegions( |
|
315
|
data: TaxTypes.CreateTaxRegionDTO[], |
|
316
|
sharedContext?: Context |
|
317
|
): Promise<TaxRegionDTO[]> |
|
318
|
|
|
319
|
@InjectManager() |
|
320
|
@EmitEvents() |
|
321
|
// @ts-expect-error |
|
322
|
async createTaxRegions( |
|
323
|
data: TaxTypes.CreateTaxRegionDTO | TaxTypes.CreateTaxRegionDTO[], |
|
324
|
@MedusaContext() sharedContext: Context = {} |
|
325
|
) { |
|
326
|
const input = Array.isArray(data) ? data : [data] |
|
327
|
const result = await this.createTaxRegions_(input, sharedContext) |
|
328
|
|
|
329
|
const serialized = await this.baseRepository_.serialize< |
|
330
|
TaxTypes.TaxRegionDTO[] | TaxTypes.TaxRegionDTO |
|
331
|
>(result) |
|
332
|
|
|
333
|
return Array.isArray(data) ? serialized : serialized[0] |
|
334
|
} |
|
335
|
|
|
336
|
@InjectTransactionManager() |
|
337
|
async createTaxRegions_( |
|
338
|
data: TaxTypes.CreateTaxRegionDTO[], |
|
339
|
sharedContext: Context = {} |
|
340
|
) { |
|
341
|
const { defaultRates, regionData } = |
|
342
|
this.prepareTaxRegionInputForCreate(data) |
|
343
|
|
|
344
|
await this.verifyProvinceToCountryMatch(regionData, sharedContext) |
|
345
|
|
|
346
|
const regions = await this.taxRegionService_.create( |
|
347
|
regionData, |
|
348
|
sharedContext |
|
349
|
) |
|
350
|
|
|
351
|
const rates = regions |
|
352
|
.map((region, i) => { |
|
353
|
if (!defaultRates[i]) { |
|
354
|
return false |
|
355
|
} |
|
356
|
return { |
|
357
|
...defaultRates[i], |
|
358
|
tax_region_id: region.id, |
|
359
|
} |
|
360
|
}) |
|
361
|
.filter(Boolean) as TaxTypes.CreateTaxRateDTO[] |
|
362
|
|
|
363
|
if (rates.length !== 0) { |
|
364
|
await this.createTaxRates(rates, sharedContext) |
|
365
|
} |
|
366
|
|
|
367
|
return regions |
|
368
|
} |
|
369
|
|
|
370
|
// @ts-expect-error |
|
371
|
createTaxRateRules( |
|
372
|
data: TaxTypes.CreateTaxRateRuleDTO, |
|
373
|
sharedContext?: Context |
|
374
|
): Promise<TaxTypes.TaxRateRuleDTO> |
|
375
|
// @ts-expect-error |
|
376
|
createTaxRateRules( |
|
377
|
data: TaxTypes.CreateTaxRateRuleDTO[], |
|
378
|
sharedContext?: Context |
|
379
|
): Promise<TaxTypes.TaxRateRuleDTO[]> |
|
380
|
|
|
381
|
@InjectManager() |
|
382
|
@EmitEvents() |
|
383
|
// @ts-expect-error |
|
384
|
async createTaxRateRules( |
|
385
|
data: TaxTypes.CreateTaxRateRuleDTO | TaxTypes.CreateTaxRateRuleDTO[], |
|
386
|
@MedusaContext() sharedContext: Context = {} |
|
387
|
) { |
|
388
|
const input = Array.isArray(data) ? data : [data] |
|
389
|
const result = await this.createTaxRateRules_(input, sharedContext) |
|
390
|
|
|
391
|
const serialized = await this.baseRepository_.serialize< |
|
392
|
TaxTypes.TaxRateRuleDTO[] | TaxTypes.TaxRateRuleDTO |
|
393
|
>(result) |
|
394
|
|
|
395
|
return Array.isArray(data) ? serialized : serialized[0] |
|
396
|
} |
|
397
|
|
|
398
|
@InjectTransactionManager() |
|
399
|
async createTaxRateRules_( |
|
400
|
data: TaxTypes.CreateTaxRateRuleDTO[], |
|
401
|
@MedusaContext() sharedContext: Context = {} |
|
402
|
) { |
|
403
|
const rules = await this.taxRateRuleService_.create(data, sharedContext) |
|
404
|
return rules |
|
405
|
} |
|
406
|
|
|
407
|
@InjectManager() |
|
408
|
async getTaxLines( |
|
409
|
items: (TaxTypes.TaxableItemDTO | TaxTypes.TaxableShippingDTO)[], |
|
410
|
calculationContext: TaxTypes.TaxCalculationContext, |
|
411
|
@MedusaContext() sharedContext: Context = {} |
|
412
|
): Promise<(TaxTypes.ItemTaxLineDTO | TaxTypes.ShippingTaxLineDTO)[]> { |
|
413
|
const normalizedContext = |
|
414
|
this.normalizeTaxCalculationContext(calculationContext) |
|
415
|
const regions = await this.taxRegionService_.list( |
|
416
|
{ |
|
417
|
$or: [ |
|
418
|
{ |
|
419
|
country_code: normalizedContext.address.country_code, |
|
420
|
province_code: null, |
|
421
|
}, |
|
422
|
{ |
|
423
|
country_code: normalizedContext.address.country_code, |
|
424
|
province_code: normalizedContext.address.province_code, |
|
425
|
}, |
|
426
|
], |
|
427
|
}, |
|
428
|
{}, |
|
429
|
sharedContext |
|
430
|
) |
|
431
|
|
|
432
|
const parentRegion = regions.find((r) => r.province_code === null) |
|
433
|
if (!parentRegion) { |
|
434
|
return [] |
|
435
|
} |
|
436
|
|
|
437
|
const regionIds = regions.map((r) => r.id) |
|
438
|
|
|
439
|
// Collect all unique reference IDs for batch query |
|
440
|
const productIds = new Set<string>() |
|
441
|
const productTypeIds = new Set<string>() |
|
442
|
const shippingOptionIds = new Set<string>() |
|
443
|
|
|
444
|
items.forEach((item) => { |
|
445
|
if ("shipping_option_id" in item) { |
|
446
|
shippingOptionIds.add(item.shipping_option_id) |
|
447
|
} else { |
|
448
|
productIds.add(item.product_id) |
|
449
|
if (item.product_type_id) { |
|
450
|
productTypeIds.add(item.product_type_id) |
|
451
|
} |
|
452
|
} |
|
453
|
}) |
|
454
|
|
|
455
|
// Build comprehensive query for all items |
|
456
|
const ruleQueries = [ |
|
457
|
...Array.from(productIds).map((id) => ({ |
|
458
|
reference: "product", |
|
459
|
reference_id: id, |
|
460
|
})), |
|
461
|
...Array.from(productTypeIds).map((id) => ({ |
|
462
|
reference: "product_type", |
|
463
|
reference_id: id, |
|
464
|
})), |
|
465
|
...Array.from(shippingOptionIds).map((id) => ({ |
|
466
|
reference: "shipping_option", |
|
467
|
reference_id: id, |
|
468
|
})), |
|
469
|
] |
|
470
|
|
|
471
|
const allCandidateRates = await this.taxRateService_.list( |
|
472
|
{ |
|
473
|
$and: [ |
|
474
|
{ tax_region_id: regionIds }, |
|
475
|
{ |
|
476
|
$or: [ |
|
477
|
{ is_default: true }, |
|
478
|
...(ruleQueries.length ? [{ rules: { $or: ruleQueries } }] : []), |
|
479
|
], |
|
480
|
}, |
|
481
|
], |
|
482
|
}, |
|
483
|
{ |
|
484
|
relations: ["tax_region", "rules"], |
|
485
|
}, |
|
486
|
sharedContext |
|
487
|
) |
|
488
|
|
|
489
|
const toReturn = items.map((item) => { |
|
490
|
const rateQuery = this.getTaxRateQueryForItem(item, regionIds) |
|
491
|
const candidateRates = allCandidateRates.filter((rate) => |
|
492
|
this.rateMatchesQuery(rate, rateQuery) |
|
493
|
) |
|
494
|
const applicableRates = this.getTaxRatesForItem(item, candidateRates) |
|
495
|
|
|
496
|
return { |
|
497
|
rates: applicableRates, |
|
498
|
item, |
|
499
|
} |
|
500
|
}) |
|
501
|
|
|
502
|
const taxLines = await this.getTaxLinesFromProvider( |
|
503
|
parentRegion.provider_id as string, |
|
504
|
toReturn, |
|
505
|
calculationContext |
|
506
|
) |
|
507
|
|
|
508
|
return taxLines |
|
509
|
} |
|
510
|
|
|
511
|
getProvider(providerId: string): ITaxProvider { |
|
512
|
return this.taxProviderService_.retrieveProvider(providerId) |
|
513
|
} |
|
514
|
|
|
515
|
private async getTaxLinesFromProvider( |
|
516
|
providerId: string, |
|
517
|
items: ItemWithRates[], |
|
518
|
calculationContext: TaxTypes.TaxCalculationContext |
|
519
|
) { |
|
520
|
const provider = this.taxProviderService_.retrieveProvider(providerId) |
|
521
|
|
|
522
|
const [itemLines, shippingLines] = items.reduce( |
|
523
|
(acc, line) => { |
|
524
|
if ("shipping_option_id" in line.item) { |
|
525
|
acc[1].push({ |
|
526
|
shipping_line: line.item, |
|
527
|
rates: line.rates, |
|
528
|
}) |
|
529
|
} else { |
|
530
|
acc[0].push({ |
|
531
|
line_item: line.item, |
|
532
|
rates: line.rates, |
|
533
|
}) |
|
534
|
} |
|
535
|
return acc |
|
536
|
}, |
|
537
|
[[], []] as [ |
|
538
|
TaxTypes.ItemTaxCalculationLine[], |
|
539
|
TaxTypes.ShippingTaxCalculationLine[] |
|
540
|
] |
|
541
|
) |
|
542
|
|
|
543
|
const itemTaxLines = await provider.getTaxLines( |
|
544
|
itemLines, |
|
545
|
shippingLines, |
|
546
|
calculationContext |
|
547
|
) |
|
548
|
|
|
549
|
return itemTaxLines |
|
550
|
} |
|
551
|
|
|
552
|
private normalizeTaxCalculationContext( |
|
553
|
context: TaxTypes.TaxCalculationContext |
|
554
|
): TaxTypes.TaxCalculationContext { |
|
555
|
return { |
|
556
|
...context, |
|
557
|
address: { |
|
558
|
...context.address, |
|
559
|
country_code: this.normalizeRegionCodes(context.address.country_code), |
|
560
|
province_code: context.address.province_code |
|
561
|
? this.normalizeRegionCodes(context.address.province_code) |
|
562
|
: null, |
|
563
|
}, |
|
564
|
} |
|
565
|
} |
|
566
|
|
|
567
|
private prepareTaxRegionInputForCreate( |
|
568
|
data: TaxTypes.CreateTaxRegionDTO | TaxTypes.CreateTaxRegionDTO[] |
|
569
|
) { |
|
570
|
const regionsWithDefaultRate = Array.isArray(data) ? data : [data] |
|
571
|
|
|
572
|
const defaultRates: (Omit< |
|
573
|
TaxTypes.CreateTaxRateDTO, |
|
574
|
"tax_region_id" |
|
575
|
> | null)[] = [] |
|
576
|
const regionData: TaxTypes.CreateTaxRegionDTO[] = [] |
|
577
|
|
|
578
|
for (const region of regionsWithDefaultRate) { |
|
579
|
const { default_tax_rate, ...rest } = region |
|
580
|
if (!default_tax_rate) { |
|
581
|
defaultRates.push(null) |
|
582
|
} else { |
|
583
|
defaultRates.push({ |
|
584
|
...default_tax_rate, |
|
585
|
is_default: true, |
|
586
|
created_by: region.created_by, |
|
587
|
}) |
|
588
|
} |
|
589
|
|
|
590
|
regionData.push({ |
|
591
|
...rest, |
|
592
|
province_code: rest.province_code |
|
593
|
? this.normalizeRegionCodes(rest.province_code) |
|
594
|
: null, |
|
595
|
country_code: this.normalizeRegionCodes(rest.country_code), |
|
596
|
}) |
|
597
|
} |
|
598
|
|
|
599
|
return { defaultRates, regionData } |
|
600
|
} |
|
601
|
|
|
602
|
private async verifyProvinceToCountryMatch( |
|
603
|
regionsToVerify: TaxTypes.CreateTaxRegionDTO[], |
|
604
|
sharedContext: Context = {} |
|
605
|
) { |
|
606
|
const parentIds = regionsToVerify.map((i) => i.parent_id).filter(isDefined) |
|
607
|
if (parentIds.length > 0) { |
|
608
|
const parentRegions = await this.taxRegionService_.list( |
|
609
|
{ id: { $in: parentIds } }, |
|
610
|
{ select: ["id", "country_code"] }, |
|
611
|
sharedContext |
|
612
|
) |
|
613
|
|
|
614
|
for (const region of regionsToVerify) { |
|
615
|
if (isDefined(region.parent_id)) { |
|
616
|
const parentRegion = parentRegions.find( |
|
617
|
(r) => r.id === region.parent_id |
|
618
|
) |
|
619
|
if (!isDefined(parentRegion)) { |
|
620
|
throw new MedusaError( |
|
621
|
MedusaError.Types.INVALID_DATA, |
|
622
|
`Province region must belong to a parent region. You are trying to create a province region with (country: ${region.country_code}, province: ${region.province_code}) but parent does not exist` |
|
623
|
) |
|
624
|
} |
|
625
|
|
|
626
|
if (parentRegion.country_code !== region.country_code) { |
|
627
|
throw new MedusaError( |
|
628
|
MedusaError.Types.INVALID_DATA, |
|
629
|
`Province region must belong to a parent region with the same country code. You are trying to create a province region with (country: ${region.country_code}, province: ${region.province_code}) but parent expects (country: ${parentRegion.country_code})` |
|
630
|
) |
|
631
|
} |
|
632
|
} |
|
633
|
} |
|
634
|
} |
|
635
|
} |
|
636
|
|
|
637
|
private getTaxRatesForItem( |
|
638
|
item: TaxTypes.TaxableItemDTO | TaxTypes.TaxableShippingDTO, |
|
639
|
rates: InferEntityType<typeof TaxRate>[] |
|
640
|
): InferEntityType<typeof TaxRate>[] { |
|
641
|
if (!rates.length) { |
|
642
|
return [] |
|
643
|
} |
|
644
|
|
|
645
|
const prioritizedRates = this.prioritizeRates(rates, item) |
|
646
|
const rate = prioritizedRates[0] |
|
647
|
|
|
648
|
const ratesToReturn = [rate] |
|
649
|
|
|
650
|
// If the rate can be combined we need to find the rate's |
|
651
|
// parent region and add that rate too. If not we can return now. |
|
652
|
if (!(rate.is_combinable && rate.tax_region.parent_id)) { |
|
653
|
return ratesToReturn |
|
654
|
} |
|
655
|
|
|
656
|
// First parent region rate in prioritized rates |
|
657
|
// will be the most granular rate. |
|
658
|
const parentRate = prioritizedRates.find( |
|
659
|
(r) => r.tax_region.id === rate.tax_region.parent_id |
|
660
|
) |
|
661
|
|
|
662
|
if (parentRate) { |
|
663
|
ratesToReturn.push(parentRate) |
|
664
|
} |
|
665
|
|
|
666
|
return ratesToReturn |
|
667
|
} |
|
668
|
|
|
669
|
private getTaxRateQueryForItem( |
|
670
|
item: TaxTypes.TaxableItemDTO | TaxTypes.TaxableShippingDTO, |
|
671
|
regionIds: string[] |
|
672
|
): { |
|
673
|
$and: { |
|
674
|
tax_region_id?: string[] |
|
675
|
$or?: { |
|
676
|
is_default?: boolean |
|
677
|
rules?: { |
|
678
|
$or: { reference: string; reference_id: string | undefined }[] |
|
679
|
} |
|
680
|
}[] |
|
681
|
}[] |
|
682
|
} { |
|
683
|
const isShipping = "shipping_option_id" in item |
|
684
|
let ruleQuery = isShipping |
|
685
|
? [ |
|
686
|
{ |
|
687
|
reference: "shipping_option", |
|
688
|
reference_id: item.shipping_option_id, |
|
689
|
}, |
|
690
|
] |
|
691
|
: [ |
|
692
|
{ |
|
693
|
reference: "product", |
|
694
|
reference_id: item.product_id, |
|
695
|
}, |
|
696
|
{ |
|
697
|
reference: "product_type", |
|
698
|
reference_id: item.product_type_id, |
|
699
|
}, |
|
700
|
] |
|
701
|
|
|
702
|
return { |
|
703
|
$and: [ |
|
704
|
{ tax_region_id: regionIds }, |
|
705
|
{ $or: [{ is_default: true }, { rules: { $or: ruleQuery } }] }, |
|
706
|
], |
|
707
|
} |
|
708
|
} |
|
709
|
|
|
710
|
private rateMatchesQuery( |
|
711
|
rate: InferEntityType<typeof TaxRate>, |
|
712
|
query: { |
|
713
|
$and: { |
|
714
|
tax_region_id?: string[] |
|
715
|
$or?: { |
|
716
|
is_default?: boolean |
|
717
|
rules?: { |
|
718
|
$or: { reference: string; reference_id: string | undefined }[] |
|
719
|
} |
|
720
|
}[] |
|
721
|
}[] |
|
722
|
} |
|
723
|
): boolean { |
|
724
|
const { $and } = query |
|
725
|
const [regionCheck, ruleCheck] = $and |
|
726
|
|
|
727
|
// Check region match |
|
728
|
if (!regionCheck.tax_region_id?.includes(rate.tax_region_id)) { |
|
729
|
return false |
|
730
|
} |
|
731
|
|
|
732
|
// Check rule match |
|
733
|
const { $or } = ruleCheck |
|
734
|
if (rate.is_default) { |
|
735
|
return true |
|
736
|
} |
|
737
|
|
|
738
|
// Check if any rule matches |
|
739
|
for (const ruleCondition of $or ?? []) { |
|
740
|
if (ruleCondition.is_default && rate.is_default) { |
|
741
|
return true |
|
742
|
} |
|
743
|
if (ruleCondition.rules) { |
|
744
|
const { $or: ruleQueries } = ruleCondition.rules |
|
745
|
for (const ruleQuery of ruleQueries) { |
|
746
|
if ( |
|
747
|
[...(rate.rules ?? [])]?.some( |
|
748
|
(rule: InferEntityType<typeof TaxRateRule>) => |
|
749
|
rule.reference === ruleQuery.reference && |
|
750
|
rule.reference_id === ruleQuery.reference_id |
|
751
|
) |
|
752
|
) { |
|
753
|
return true |
|
754
|
} |
|
755
|
} |
|
756
|
} |
|
757
|
} |
|
758
|
|
|
759
|
return false |
|
760
|
} |
|
761
|
|
|
762
|
private checkRuleMatches( |
|
763
|
rate: InferEntityType<typeof TaxRate>, |
|
764
|
item: TaxTypes.TaxableItemDTO | TaxTypes.TaxableShippingDTO |
|
765
|
) { |
|
766
|
if (rate.rules.length === 0) { |
|
767
|
return { |
|
768
|
isProductMatch: false, |
|
769
|
isProductTypeMatch: false, |
|
770
|
isShippingMatch: false, |
|
771
|
} |
|
772
|
} |
|
773
|
|
|
774
|
let isProductMatch = false |
|
775
|
const isShipping = "shipping_option_id" in item |
|
776
|
const matchingRules = rate.rules.filter((rule) => { |
|
777
|
if (isShipping) { |
|
778
|
return ( |
|
779
|
rule.reference === "shipping_option" && |
|
780
|
rule.reference_id === item.shipping_option_id |
|
781
|
) |
|
782
|
} |
|
783
|
return ( |
|
784
|
(rule.reference === "product" && |
|
785
|
rule.reference_id === item.product_id) || |
|
786
|
(rule.reference === "product_type" && |
|
787
|
rule.reference_id === item.product_type_id) |
|
788
|
) |
|
789
|
}) |
|
790
|
|
|
791
|
if (matchingRules.some((rule) => rule.reference === "product")) { |
|
792
|
isProductMatch = true |
|
793
|
} |
|
794
|
|
|
795
|
return { |
|
796
|
isProductMatch, |
|
797
|
isProductTypeMatch: matchingRules.length > 0, |
|
798
|
isShippingMatch: isShipping && matchingRules.length > 0, |
|
799
|
} |
|
800
|
} |
|
801
|
|
|
802
|
private prioritizeRates( |
|
803
|
rates: InferEntityType<typeof TaxRate>[], |
|
804
|
item: TaxTypes.TaxableItemDTO | TaxTypes.TaxableShippingDTO |
|
805
|
) { |
|
806
|
const decoratedRates = rates.map((rate) => { |
|
807
|
const { isProductMatch, isProductTypeMatch, isShippingMatch } = |
|
808
|
this.checkRuleMatches(rate, item) |
|
809
|
|
|
810
|
const isProvince = rate.tax_region.province_code !== null |
|
811
|
const isDefault = rate.is_default |
|
812
|
|
|
813
|
const decoratedRate = { |
|
814
|
...rate, |
|
815
|
priority_score: 7, |
|
816
|
} |
|
817
|
|
|
818
|
if ((isShippingMatch || isProductMatch) && isProvince) { |
|
819
|
decoratedRate.priority_score = 1 |
|
820
|
} else if (isProductTypeMatch && isProvince) { |
|
821
|
decoratedRate.priority_score = 2 |
|
822
|
} else if (isDefault && isProvince) { |
|
823
|
decoratedRate.priority_score = 3 |
|
824
|
} else if ((isShippingMatch || isProductMatch) && !isProvince) { |
|
825
|
decoratedRate.priority_score = 4 |
|
826
|
} else if (isProductTypeMatch && !isProvince) { |
|
827
|
decoratedRate.priority_score = 5 |
|
828
|
} else if (isDefault && !isProvince) { |
|
829
|
decoratedRate.priority_score = 6 |
|
830
|
} |
|
831
|
|
|
832
|
return decoratedRate |
|
833
|
}) as (InferEntityType<typeof TaxRate> & { |
|
834
|
priority_score: number |
|
835
|
})[] |
|
836
|
|
|
837
|
return decoratedRates.sort( |
|
838
|
(a, b) => (a as any).priority_score - (b as any).priority_score |
|
839
|
) |
|
840
|
} |
|
841
|
|
|
842
|
private normalizeRegionCodes(code: string) { |
|
843
|
return code.toLowerCase() |
|
844
|
} |
|
845
|
} |