1 import {
2 Context,
3 DAL,
4 InferEntityType,
5 INotificationModuleService,
6 InternalModuleDeclaration,
7 Logger,
8 ModulesSdkTypes,
9 NotificationTypes,
10 } from "@medusajs/framework/types"
11 import {
12 EmitEvents,
13 generateEntityId,
14 InjectManager,
15 MedusaContext,
16 MedusaError,
17 MedusaService,
18 NotificationStatus,
19 promiseAll,
20 } from "@medusajs/framework/utils"
21 import { Notification } from "@models"
22 import NotificationProviderService from "./notification-provider"
23
24 type InjectedDependencies = {
25 logger?: Logger
26 baseRepository: DAL.RepositoryService
27 notificationService: ModulesSdkTypes.IMedusaInternalService<
28 typeof Notification
29 >
30 notificationProviderService: NotificationProviderService
31 }
32
33 export default class NotificationModuleService
34 extends MedusaService<{
35 Notification: { dto: NotificationTypes.NotificationDTO }
36 }>({ Notification })
37 implements INotificationModuleService
38 {
39 protected baseRepository_: DAL.RepositoryService
40 protected readonly notificationService_: ModulesSdkTypes.IMedusaInternalService<
41 typeof Notification
42 >
43 protected readonly notificationProviderService_: NotificationProviderService
44
45 constructor(
46 {
47 baseRepository,
48 notificationService,
49 notificationProviderService,
50 }: InjectedDependencies,
51 protected readonly moduleDeclaration: InternalModuleDeclaration
52 ) {
53 // @ts-ignore
54 super(...arguments)
55 this.baseRepository_ = baseRepository
56 this.notificationService_ = notificationService
57 this.notificationProviderService_ = notificationProviderService
58 }
59
60 // @ts-expect-error
61 createNotifications(
62 data: NotificationTypes.CreateNotificationDTO[],
63 sharedContext?: Context
64 ): Promise<NotificationTypes.NotificationDTO[]>
65 // @ts-expect-error
66 createNotifications(
67 data: NotificationTypes.CreateNotificationDTO,
68 sharedContext?: Context
69 ): Promise<NotificationTypes.NotificationDTO>
70
71 @InjectManager()
72 @EmitEvents()
73 // @ts-expect-error
74 async createNotifications(
75 data:
76 | NotificationTypes.CreateNotificationDTO
77 | NotificationTypes.CreateNotificationDTO[],
78 @MedusaContext() sharedContext: Context = {}
79 ): Promise<
80 NotificationTypes.NotificationDTO | NotificationTypes.NotificationDTO[]
81 > {
82 const normalized = Array.isArray(data) ? data : [data]
83
84 const createdNotifications = await this.createNotifications_(
85 normalized,
86 sharedContext
87 )
88
89 const serialized = await this.baseRepository_.serialize<
90 NotificationTypes.NotificationDTO[]
91 >(createdNotifications)
92
93 return Array.isArray(data) ? serialized : serialized[0]
94 }
95
96 @InjectManager()
97 protected async createNotifications_(
98 data: NotificationTypes.CreateNotificationDTO[],
99 @MedusaContext() sharedContext: Context = {}
100 ): Promise<InferEntityType<typeof Notification>[]> {
101 if (!data.length) {
102 return []
103 }
104
105 // TODO: At this point we should probably take a lock with the idempotency keys so we don't have race conditions.
106 // Also, we should probably rely on Redis for this instead of the database.
107 const idempotencyKeys = data
108 .map((entry) => entry.idempotency_key)
109 .filter(Boolean)
110
111 let { notificationsToProcess, createdNotifications } =
112 await this.baseRepository_.transaction(async (txManager) => {
113 const context = {
114 ...sharedContext,
115 transactionManager: txManager,
116 }
117
118 const alreadySentNotifications = await this.notificationService_.list(
119 {
120 idempotency_key: idempotencyKeys,
121 },
122 {},
123 context
124 )
125
126 const existsMap = new Map(
127 alreadySentNotifications.map((n) => [n.idempotency_key as string, n])
128 )
129
130 const notificationsToProcess = data.filter(
131 (entry) =>
132 !entry.idempotency_key ||
133 !existsMap.has(entry.idempotency_key) ||
134 (existsMap.has(entry.idempotency_key) &&
135 existsMap.get(entry.idempotency_key)!.status ===
136 NotificationStatus.FAILURE)
137 )
138
139 const channels = notificationsToProcess.map((not) => not.channel)
140 const providers =
141 await this.notificationProviderService_.getProviderForChannels(
142 channels,
143 context
144 )
145
146 // Create the notifications to be sent to prevent concurrent actions listing the same notifications
147 const normalizedNotificationsToProcess = notificationsToProcess.map(
148 (entry) => {
149 const provider = providers.find((provider) =>
150 provider?.channels.includes(entry.channel)
151 )
152
153 return {
154 provider,
155 data: {
156 id: generateEntityId(undefined, "noti"),
157 ...entry,
158 provider_id: provider?.id,
159 },
160 }
161 }
162 )
163
164 const toCreate = normalizedNotificationsToProcess
165 .filter(
166 (e) =>
167 !e.data.idempotency_key || !existsMap.has(e.data.idempotency_key)
168 )
169 .map((e) => e.data)
170
171 const createdNotifications = toCreate.length
172 ? await this.notificationService_.create(toCreate, context)
173 : []
174
175 return {
176 notificationsToProcess: normalizedNotificationsToProcess,
177 createdNotifications,
178 }
179 })
180
181 const notificationToUpdate: { id: string; external_id?: string }[] = []
182
183 try {
184 await promiseAll(
185 notificationsToProcess.map(async (entry) => {
186 const provider = entry.provider
187
188 if (!provider?.is_enabled) {
189 entry.data.status = NotificationStatus.FAILURE
190 notificationToUpdate.push(entry.data)
191
192 const errorMessage = !provider
193 ? `Could not find a notification provider for channel: ${entry.data.channel} for notification id ${entry.data.id}`
194 : `Notification provider ${provider.id} is not enabled. To enable it, configure it as a provider in the notification module options.`
195
196 throw new MedusaError(MedusaError.Types.NOT_FOUND, errorMessage)
197 }
198
199 const res = await this.notificationProviderService_
200 .send(provider, entry.data)
201 .catch((e) => {
202 entry.data.status = NotificationStatus.FAILURE
203 notificationToUpdate.push(entry.data)
204 throw new MedusaError(
205 MedusaError.Types.UNEXPECTED_STATE,
206 `Failed to send notification with id ${entry.data.id}:\n${e.message}`
207 )
208 })
209
210 entry.data.external_id = res.id
211 entry.data.status = NotificationStatus.SUCCESS
212
213 notificationToUpdate.push(entry.data)
214 }),
215 {
216 aggregateErrors: true,
217 }
218 )
219 } finally {
220 const updatedNotifications = await this.notificationService_.update(
221 notificationToUpdate,
222 sharedContext
223 )
224 const updatedNotificationsMap = new Map(
225 updatedNotifications.map((n) => [n.id, n])
226 )
227
228 // Maintain the order of the notifications
229 createdNotifications = createdNotifications.map((notification) => {
230 return updatedNotificationsMap.get(notification.id) || notification
231 })
232 }
233
234 return createdNotifications
235 }
236 }