Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 | import { Injectable, Logger } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { InjectQueue } from '@nestjs/bullmq'; import { Queue } from 'bullmq'; import { Notification } from './schemas/notification.schema'; import { NotificationTemplate } from './schemas/template.schema'; import { NotificationPreference } from './schemas/preference.schema'; import { NotificationDelivery } from './schemas/delivery.schema'; import { SystemAnnouncement } from './schemas/announcement.schema'; import { NotificationChannelProvider } from './notification-provider.interface'; import { MockEmailProvider } from './providers/mock-email.provider'; import { MockSmsProvider, MockWhatsappProvider, MockPushProvider, } from './providers/mock-other.providers'; import { EventBusService } from '../events/event-bus.service'; @Injectable() export class NotificationService { private readonly logger = new Logger(NotificationService.name); private readonly providers = new Map<string, NotificationChannelProvider>(); constructor( @InjectModel(Notification.name) private readonly notificationModel: Model<Notification>, @InjectModel(NotificationTemplate.name) private readonly templateModel: Model<NotificationTemplate>, @InjectModel(NotificationPreference.name) private readonly preferenceModel: Model<NotificationPreference>, @InjectModel(NotificationDelivery.name) private readonly deliveryModel: Model<NotificationDelivery>, @InjectModel(SystemAnnouncement.name) private readonly announcementModel: Model<SystemAnnouncement>, @InjectQueue('notification.dispatch') private readonly dispatchQueue: Queue, private readonly eventBus: EventBusService, ) { // Register mock providers automatically this.registerProvider(new MockEmailProvider()); this.registerProvider(new MockSmsProvider()); this.registerProvider(new MockWhatsappProvider()); this.registerProvider(new MockPushProvider()); } registerProvider(provider: NotificationChannelProvider) { this.providers.set(provider.channel, provider); this.logger.log( `Registered notification provider: ${provider.name} for channel: ${provider.channel}`, ); } /** * Send notification trigger by queuing a dispatch job. */ async trigger(params: { tenantId: string; userId: string; templateName: string; variables?: any; priority?: 'LOW' | 'MEDIUM' | 'HIGH'; metadata?: any; }) { // Add job to the BullMQ dispatch queue await this.dispatchQueue.add('dispatch', params, { priority: params.priority === 'HIGH' ? 1 : 2, attempts: 3, backoff: { type: 'exponential', delay: 5000 }, }); this.logger.log( `Queued notification trigger for user: ${params.userId} using template: ${params.templateName}`, ); } /** * Sync/Direct dispatch method used by the queue processor. */ async processDispatch(jobData: { tenantId: string; userId: string; templateName: string; variables?: any; metadata?: any; }) { const template = await this.templateModel .findOne({ name: jobData.templateName }) .lean() .exec(); if (!template) { this.logger.error( `Notification template not found: ${jobData.templateName}`, ); return; } // Resolve user preferences const preferences = await this.preferenceModel .findOne({ userId: jobData.userId }) .lean() .exec(); const allowedChannels = template.channels.filter((ch) => { if (!preferences || !preferences.channels) return true; const chPrefs = preferences.channels[jobData.templateName] || preferences.channels['default']; return chPrefs ? chPrefs.includes(ch) : true; }); // Check quiet hours if ( preferences?.quietHoursEnabled && this.isQuietHour(preferences.quietHoursStart, preferences.quietHoursEnd) ) { this.logger.log( `Quiet hours active for user ${jobData.userId}. Deferring delivery.`, ); // Defer or schedule logic can go here; for now, we schedule for later or log deferral } for (const channel of allowedChannels) { const subject = this.render(template.subject, jobData.variables || {}); const body = this.render(template.body, jobData.variables || {}); // Create notification record for In-App (so it appears on inbox) let notificationId = 'system'; if (channel === 'IN_APP') { const notif = await this.notificationModel.create({ tenantId: jobData.tenantId, userId: jobData.userId, title: subject, message: body, channel: 'IN_APP', metadata: jobData.metadata, }); notificationId = (notif as any)._id.toString(); await this.eventBus.publish( 'platform.notification.delivered.v1', { userId: jobData.userId, channel: 'IN_APP', }, jobData.tenantId, ); } // Log delivery record const delivery = await this.deliveryModel.create({ tenantId: jobData.tenantId, notificationId, channel, status: 'PENDING', }); const provider = this.providers.get(channel); if (provider) { try { const result = await provider.send( jobData.userId, subject, body, jobData.metadata, ); delivery.status = result.success ? 'SENT' : 'FAILED'; delivery.providerUsed = provider.name; delivery.messageId = result.messageId || ''; delivery.error = result.error || ''; delivery.sentAt = new Date(); await delivery.save(); } catch (err: any) { delivery.status = 'FAILED'; delivery.error = err.message || 'Unknown error'; await delivery.save(); } } else { delivery.status = 'FAILED'; delivery.error = `No provider configured for channel: ${channel}`; await delivery.save(); } } } private isQuietHour(start: string, end: string): boolean { const now = new Date(); const current = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`; if (start < end) { return current >= start && current <= end; } else { return current >= start || current <= end; } } private render(templateString: string, variables: any): string { let output = templateString; for (const key of Object.keys(variables)) { output = output.replace( new RegExp(`{{\\s*${key}\\s*}}`, 'g'), variables[key], ); } return output; } // ============================================================ // USER NOTIFICATIONS INBOX APIs // ============================================================ async getInbox( tenantId: string, userId: string, page = 1, limit = 20, ): Promise<any> { const skip = (page - 1) * limit; const [data, total] = await Promise.all([ this.notificationModel .find({ tenantId, userId, channel: 'IN_APP' }) .skip(skip) .limit(limit) .sort({ createdAt: -1 }) .lean() .exec(), this.notificationModel .countDocuments({ tenantId, userId, channel: 'IN_APP' }) .exec(), ]); return { data: data.map((d) => ({ ...d, id: (d as any)._id.toString() })), meta: { total, page, limit, totalPages: Math.ceil(total / limit) }, }; } async getUnreadCount(tenantId: string, userId: string): Promise<number> { return this.notificationModel .countDocuments({ tenantId, userId, channel: 'IN_APP', isRead: false }) .exec(); } async markAsRead(id: string, tenantId: string, userId: string) { const result = await this.notificationModel .findOneAndUpdate( { _id: id, tenantId, userId }, { $set: { isRead: true } }, { new: true }, ) .lean() .exec(); if (result) { await this.eventBus.publish( 'platform.notification.read.v1', { notificationId: id, userId }, tenantId, ); } return result; } async markAllAsRead(tenantId: string, userId: string) { return this.notificationModel .updateMany( { tenantId, userId, channel: 'IN_APP', isRead: false }, { $set: { isRead: true } }, ) .exec(); } async delete(id: string, tenantId: string, userId: string) { return this.notificationModel .deleteOne({ _id: id, tenantId, userId }) .exec(); } // ============================================================ // PREFERENCE APIs // ============================================================ async getPreferences(userId: string) { return this.preferenceModel.findOne({ userId }).lean().exec(); } async updatePreferences(userId: string, data: any) { return this.preferenceModel .findOneAndUpdate( { userId }, { userId, ...data }, { upsert: true, new: true }, ) .lean() .exec(); } } |