1 import { Lifetime, asFunction, asValue } from "@medusajs/framework/awilix"
2 import { moduleProviderLoader } from "@medusajs/framework/modules-sdk"
3 import { LoaderOptions, ModulesSdkTypes } from "@medusajs/framework/types"
4 import {
5 ContainerRegistrationKeys,
6 lowerCaseFirst,
7 promiseAll,
8 } from "@medusajs/framework/utils"
9 import { NotificationProvider } from "@models"
10 import { NotificationProviderService } from "@services"
11 import {
12 NotificationIdentifiersRegistrationName,
13 NotificationModuleOptions,
14 NotificationProviderRegistrationPrefix,
15 } from "@types"
16 import { MedusaCloudEmailNotificationProvider } from "../providers/medusa-cloud-email"
17
18 const validateCloudOptions = (options: NotificationModuleOptions["cloud"]) => {
19 const { api_key, endpoint, environment_handle, sandbox_handle } =
20 options ?? {}
21
22 if (!environment_handle && !sandbox_handle) {
23 return false
24 }
25
26 if (!api_key || !endpoint) {
27 return false
28 }
29
30 return true
31 }
32
33 const registrationFn = async (klass, container, pluginOptions) => {
34 container.register({
35 [NotificationProviderRegistrationPrefix + pluginOptions.id]: asFunction(
36 (cradle) => new klass(cradle, pluginOptions.options ?? {}),
37 {
38 lifetime: klass.LIFE_TIME || Lifetime.SINGLETON,
39 }
40 ),
41 })
42
43 container.registerAdd(
44 NotificationIdentifiersRegistrationName,
45 asValue(pluginOptions.id)
46 )
47 }
48
49 export default async ({
50 container,
51 options,
52 }: LoaderOptions<
53 (
54 | ModulesSdkTypes.ModuleServiceInitializeOptions
55 | ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
56 ) &
57 NotificationModuleOptions
58 >): Promise<void> => {
59 let providers = options?.providers || []
60
61 // We add the Medusa Cloud Email provider if there is no other email provider configured
62 const hasEmailProvider = options?.providers?.some((provider) =>
63 provider.options?.channels?.some((channel) => channel === "email")
64 )
65 if (!hasEmailProvider) {
66 const shouldRegisterMedusaCloudEmailProvider = validateCloudOptions(
67 options?.cloud
68 )
69
70 if (shouldRegisterMedusaCloudEmailProvider) {
71 await registrationFn(MedusaCloudEmailNotificationProvider, container, {
72 options: options?.cloud,
73 id: "cloud",
74 })
75 const provider = {
76 id: "cloud",
77 resolve: "",
78 options: {
79 ...options?.cloud,
80 channels: ["email"],
81 },
82 }
83 providers = [...providers, provider]
84 }
85 }
86
87 await moduleProviderLoader({
88 container,
89 providers: options?.providers || [],
90 registerServiceFn: registrationFn,
91 })
92
93 await syncDatabaseProviders({
94 container,
95 providers: providers,
96 })
97 }
98
99 async function syncDatabaseProviders({
100 container,
101 providers,
102 }: {
103 container: any
104 providers: Exclude<NotificationModuleOptions["providers"], undefined>
105 }) {
106 const providerServiceRegistrationKey = lowerCaseFirst(
107 NotificationProviderService.name
108 )
109 const providerService: ModulesSdkTypes.IMedusaInternalService<
110 typeof NotificationProvider
111 > = container.resolve(providerServiceRegistrationKey)
112
113 const logger = container.resolve(ContainerRegistrationKeys.LOGGER) ?? console
114 const normalizedProviders = providers.map((provider) => {
115 if (!provider.id) {
116 throw new Error(
117 "An entry in the provider config is required to initialize notification providers"
118 )
119 }
120
121 return {
122 id: provider.id,
123 handle: provider.id,
124 name: provider.id,
125 is_enabled: true,
126 channels: provider.options?.channels ?? [],
127 }
128 })
129
130 validateProviders(normalizedProviders)
131
132 try {
133 const providersInDb = await providerService.list({})
134 const providersToDisable = providersInDb.filter(
135 (dbProvider) =>
136 !normalizedProviders.some(
137 (normalizedProvider) => normalizedProvider.id === dbProvider.id
138 )
139 )
140
141 const promises: Promise<any>[] = []
142
143 if (normalizedProviders.length) {
144 promises.push(providerService.upsert(normalizedProviders))
145 }
146
147 if (providersToDisable.length) {
148 promises.push(
149 providerService.update(
150 providersToDisable.map((p) => ({
151 id: p.id,
152 is_enabled: false,
153 }))
154 )
155 )
156 }
157
158 await promiseAll(promises)
159 } catch (error) {
160 logger.error(`Error syncing the notification providers: ${error.message}`)
161 }
162 }
163
164 function validateProviders(providers: { channels: string[] }[]) {
165 const hasForChannel = {}
166 providers.forEach((provider) => {
167 provider.channels.forEach((channel) => {
168 if (hasForChannel[channel]) {
169 throw new Error(
170 `Multiple providers are configured for the same channel: ${channel}`
171 )
172 }
173 hasForChannel[channel] = true
174 })
175 })
176 }