1 import { moduleProviderLoader } from "@medusajs/framework/modules-sdk"
2
3 import {
4 CreateTaxProviderDTO,
5 LoaderOptions,
6 ModuleProvider,
7 ModulesSdkTypes,
8 } from "@medusajs/framework/types"
9 import { asFunction, asValue, Lifetime } from "@medusajs/framework/awilix"
10
11 import { MedusaError } from "@medusajs/framework/utils"
12 import * as providers from "../providers"
13 import TaxProviderService from "../services/tax-provider"
14
15 const PROVIDER_REGISTRATION_KEY = "tax_providers" as const
16
17 const registrationFn = async (klass, container, pluginOptions) => {
18 if (!klass?.identifier) {
19 throw new MedusaError(
20 MedusaError.Types.INVALID_ARGUMENT,
21 `Trying to register a tax provider without a provider identifier.`
22 )
23 }
24
25 const key = `tp_${klass.identifier}${
26 pluginOptions.id ? `_${pluginOptions.id}` : ""
27 }`
28
29 container.register({
30 [key]: asFunction((cradle) => new klass(cradle, pluginOptions.options), {
31 lifetime: klass.LIFE_TIME || Lifetime.SINGLETON,
32 }),
33 })
34
35 container.registerAdd(PROVIDER_REGISTRATION_KEY, asValue(key))
36 }
37
38 export default async ({
39 container,
40 options,
41 }: LoaderOptions<
42 (
43 | ModulesSdkTypes.ModuleServiceInitializeOptions
44 | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
45 ) & { providers: ModuleProvider[] }
46 >): Promise<void> => {
47 // Local providers
48 for (const provider of Object.values(providers)) {
49 await registrationFn(provider, container, {})
50 }
51
52 await moduleProviderLoader({
53 container,
54 providers: options?.providers || [],
55 registerServiceFn: registrationFn,
56 })
57
58 await registerProvidersInDb({ container })
59 }
60
61 const registerProvidersInDb = async ({
62 container,
63 }: LoaderOptions): Promise<void> => {
64 const providersToLoad = container.resolve<string[]>(PROVIDER_REGISTRATION_KEY)
65 const taxProviderService =
66 container.resolve<TaxProviderService>("taxProviderService")
67
68 const existingProviders = await taxProviderService.list(
69 { id: providersToLoad },
70 {}
71 )
72
73 const upsertData: CreateTaxProviderDTO[] = []
74
75 for (const { id } of existingProviders) {
76 if (!providersToLoad.includes(id)) {
77 upsertData.push({ id, is_enabled: false })
78 }
79 }
80
81 for (const id of providersToLoad) {
82 upsertData.push({ id, is_enabled: true })
83 }
84
85 await taxProviderService.upsert(upsertData)
86 }