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 | 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 { CommunicationTemplate, CommunicationProvider, CommunicationCampaign, CommunicationBatch, CommunicationMessage, CommunicationPreference, CommunicationSuppression, CommunicationConsent, CommunicationAnalytics, } from './schemas/communication.schema'; import { PushNotificationService } from './push/push.service'; import { WebPushService } from './web-push/web-push.service'; import { EventBusService } from '../events/event-bus.service'; @Injectable() export class CommunicationHubService { private readonly logger = new Logger(CommunicationHubService.name); constructor( @InjectModel(CommunicationTemplate.name) private readonly templateModel: Model<CommunicationTemplate>, @InjectModel(CommunicationProvider.name) private readonly providerModel: Model<CommunicationProvider>, @InjectModel(CommunicationCampaign.name) private readonly campaignModel: Model<CommunicationCampaign>, @InjectModel(CommunicationBatch.name) private readonly batchModel: Model<CommunicationBatch>, @InjectModel(CommunicationMessage.name) private readonly messageModel: Model<CommunicationMessage>, @InjectModel(CommunicationPreference.name) private readonly preferenceModel: Model<CommunicationPreference>, @InjectModel(CommunicationSuppression.name) private readonly suppressionModel: Model<CommunicationSuppression>, @InjectModel(CommunicationConsent.name) private readonly consentModel: Model<CommunicationConsent>, @InjectModel(CommunicationAnalytics.name) private readonly analyticsModel: Model<CommunicationAnalytics>, @InjectQueue('notification.dispatch') private readonly dispatchQueue: Queue, private readonly pushService: PushNotificationService, private readonly webPushService: WebPushService, private readonly eventBus: EventBusService, ) {} async triggerMessage(params: { tenantId: string; userId: string; templateKey: string; recipientAddress: string; variables?: Record<string, any>; priority?: 'LOW' | 'MEDIUM' | 'HIGH'; }): Promise<void> { const template = await this.templateModel .findOne({ key: params.templateKey, isActive: true }) .exec(); if (!template) { this.logger.error( `Communication template not found: ${params.templateKey}`, ); return; } // Resolve template variables const subject = this.interpolate( template.subjectTemplate, params.variables || {}, ); const body = this.interpolate( template.bodyTemplate, params.variables || {}, ); // Create the message object const msg = await this.messageModel.create({ tenantId: params.tenantId, recipientId: params.userId, recipientAddress: params.recipientAddress, channel: template.channel, subject, body, status: 'queued', }); // Add to the job queue await this.dispatchQueue.add( 'communication.dispatch', { messageId: (msg as any)._id.toString(), tenantId: params.tenantId, userId: params.userId, channel: template.channel, recipientAddress: params.recipientAddress, subject, body, }, { priority: params.priority === 'HIGH' ? 1 : 2, }, ); this.logger.log( `Queued message ${msg._id} for channel ${template.channel}`, ); } async processQueuedDelivery(jobData: { messageId: string; tenantId: string; userId: string; channel: string; recipientAddress: string; subject: string; body: string; }): Promise<void> { const msg = await this.messageModel.findById(jobData.messageId).exec(); if (!msg) return; // Check Suppression list const suppressed = await this.suppressionModel .findOne({ tenantId: jobData.tenantId, emailOrPhone: jobData.recipientAddress, isActive: true, }) .exec(); if (suppressed) { msg.status = 'failed'; msg.errorMessage = `Recipient address suppressed: ${suppressed.reason}`; await msg.save(); return; } // Check Preferences/Quiet hours const prefs = await this.preferenceModel .findOne({ userId: jobData.userId, tenantId: jobData.tenantId }) .exec(); if ( prefs?.quietHoursEnabled && this.isQuietHour(prefs.quietHoursStart, prefs.quietHoursEnd) ) { this.logger.log( `Decline dispatch to user ${jobData.userId} due to quiet hours`, ); // Re-queue or park msg.status = 'pending'; await msg.save(); return; } try { if (jobData.channel === 'PUSH') { await this.pushService.sendToUser( jobData.tenantId, jobData.userId, jobData.subject, jobData.body, ); msg.status = 'sent'; } else if (jobData.channel === 'BROWSER') { await this.webPushService.sendNotification( jobData.tenantId, jobData.userId, { title: jobData.subject, body: jobData.body, }, ); msg.status = 'sent'; } else { // Fallback or external channel this.logger.log( `[Mock Send] Delivery on channel ${jobData.channel} to ${jobData.recipientAddress}`, ); msg.status = 'sent'; } msg.sentAt = new Date(); } catch (err: any) { msg.status = 'failed'; msg.errorMessage = err.message || 'Unknown send error'; } finally { await msg.save(); await this.eventBus.publish( 'platform.communication.dispatched.v1', { messageId: jobData.messageId, tenantId: jobData.tenantId, channel: jobData.channel, status: msg.status, }, jobData.tenantId, ); } } 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; return current >= start || current <= end; } private interpolate(tmpl: string, vars: Record<string, any>): string { return tmpl.replace(/{{\s*(\w+)\s*}}/g, (_, key) => vars[key] !== undefined ? String(vars[key]) : `{{${key}}}`, ); } } |