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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 | 17x 17x 17x 17x 17x 17x 27x 27x 27x 11x 11x 11x 11x 11x 11x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 1x 1x 1x 3x 3x 3x 3x 3x 1x 2x 2x 2x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 4x 2x 2x 2x 2x 4x 4x 4x 2x 9x 9x 9x 1x 8x 8x 1x 7x 7x 7x 2x 2x 3x 3x 1x 2x 1x 1x 1x 1x 3x 3x 1x 2x 1x 2x 2x 2x 1x 2x 2x 1x 1x 1x 3x 2x 1x | import { Injectable, NotFoundException, ForbiddenException, Logger, BadRequestException, OnModuleInit } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import * as admin from 'firebase-admin';
import { PrismaService } from '@app/modules/prisma/prisma.service';
import { RegisterDeviceDto } from './dto/register-device.dto';
import { UpdatePreferencesDto } from './dto/update-preferences.dto';
@Injectable()
export class NotificationsService implements OnModuleInit {
private readonly logger = new Logger(NotificationsService.name);
private fcm?: admin.messaging.Messaging;
constructor(
private prisma: PrismaService,
@InjectQueue('notifications') private notificationQueue: Queue,
) {}
onModuleInit() {
try {
// Initialize Firebase Admin if credentials are available
if (!admin.apps.length) {
const credJson = process.env.FIREBASE_SERVICE_ACCOUNT_JSON;
Iif (credJson) {
const creds = JSON.parse(credJson);
admin.initializeApp({
credential: admin.credential.cert(creds),
});
this.fcm = admin.messaging();
this.logger.log('Firebase Admin initialized for push notifications');
} else Iif (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
admin.initializeApp();
this.fcm = admin.messaging();
this.logger.log('Firebase Admin initialized from GOOGLE_APPLICATION_CREDENTIALS');
} else {
this.logger.warn('Firebase credentials not provided; push notifications will be no-op');
}
} else E{
this.fcm = admin.messaging();
}
} catch (e) {
this.logger.error(`Failed to initialize Firebase Admin: ${(e as any)?.message || e}`);
}
}
async createNotification(params: { userId: number; type: string; payload: any }) {
try {
this.logger.debug(`Creating notification of type ${params.type} for user ${params.userId}`);
// Validate input
Iif (!params.type || params.type.trim().length === 0) {
throw new BadRequestException('Notification type is required');
}
Iif (!params.payload) {
throw new BadRequestException('Notification payload is required');
}
// Verify user exists
const user = await this.prisma.user.findUnique({
where: { id: params.userId },
select: { id: true },
});
Iif (!user) {
this.logger.warn(`Attempted to create notification for non-existent user ${params.userId}`);
throw new NotFoundException(`User #${params.userId} not found`);
}
const notification = await this.prisma.notification.create({
data: {
userId: params.userId,
type: params.type,
payload: params.payload,
},
});
// Enqueue for multi-channel delivery
await this.notificationQueue.add('deliver', { notificationId: notification.id });
this.logger.log(`Created notification ${notification.id} of type ${params.type} for user ${params.userId}`);
return notification;
} catch (error) {
Iif (error instanceof NotFoundException || error instanceof BadRequestException || error instanceof ForbiddenException) {
throw error;
}
this.logger.error(`Error creating notification for user ${params.userId}:`, error);
throw new Error('Failed to create notification');
}
}
async getNotifications(
userId: number,
options?: {
unreadOnly?: boolean;
type?: string;
limit?: number;
offset?: number;
}
) {
const { unreadOnly, type, limit = 50, offset = 0 } = options || {};
return this.prisma.notification.findMany({
where: {
userId,
...(unreadOnly && { readAt: null }),
...(type && { type }),
},
orderBy: { createdAt: 'desc' },
take: limit,
skip: offset,
});
}
async markAsRead(notificationId: number, userId: number) {
const notification = await this.prisma.notification.findUnique({
where: { id: notificationId },
});
Iif (!notification) {
throw new NotFoundException('Notification not found');
}
// For privacy, do not reveal the existence of other users' notifications
if (notification.userId !== userId) {
throw new NotFoundException('Notification not found');
}
return this.prisma.notification.update({
where: { id: notificationId },
data: { readAt: new Date() },
});
}
async markAllAsRead(userId: number) {
await this.prisma.notification.updateMany({
where: { userId, readAt: null },
data: { readAt: new Date() },
});
return { success: true };
}
async getUnreadCount(userId: number) {
const count = await this.prisma.notification.count({
where: { userId, readAt: null },
});
return { count };
}
async updatePreferences(userId: number, preferences: UpdatePreferencesDto) {
try {
this.logger.debug(`Updating notification preferences for user ${userId}`);
// Get existing preferences or create default ones
let existingPrefs = await this.prisma.notificationPreference.findUnique({
where: { userId },
});
Iif (!existingPrefs) {
existingPrefs = await this.prisma.notificationPreference.create({
data: {
userId,
channels: { email: true, push: true, sms: false },
topics: { new_messages: true, listings_updates: true },
},
});
}
// Update only the provided fields
const updateData: any = {};
if (preferences.channels !== undefined) {
updateData.channels = preferences.channels;
}
// Handle both 'topics' and 'types' for backward compatibility
Iif (preferences.topics !== undefined) {
updateData.topics = preferences.topics;
} else if (preferences.types !== undefined) {
updateData.topics = preferences.types;
}
const result = await this.prisma.notificationPreference.update({
where: { userId },
data: updateData,
});
this.logger.log(`Updated notification preferences for user ${userId}`);
return result;
} catch (error) {
this.logger.error(`Error updating notification preferences for user ${userId}:`, error);
throw new Error('Failed to update notification preferences');
}
}
async getPreferences(userId: number) {
let prefs = await this.prisma.notificationPreference.findUnique({
where: { userId },
});
// Return default preferences if none exist
if (!prefs) {
prefs = await this.prisma.notificationPreference.create({
data: {
userId,
channels: { email: true, push: true, inApp: true },
topics: {},
},
});
}
return prefs;
}
async registerDevice(userId: number, dto: RegisterDeviceDto) {
try {
this.logger.debug(`Registering ${dto.platform} device for user ${userId}`);
// Validate token format
if (!dto.token || dto.token.trim().length === 0) {
throw new BadRequestException('Device token is required');
}
// Verify user exists
const user = await this.prisma.user.findUnique({
where: { id: userId },
select: { id: true },
});
if (!user) {
throw new NotFoundException(`User #${userId} not found`);
}
const device = await this.prisma.pushDeviceToken.upsert({
where: { token: dto.token },
update: { userId, platform: dto.platform },
create: { userId, platform: dto.platform, token: dto.token },
});
this.logger.log(`Registered ${dto.platform} device for user ${userId}`);
return device;
} catch (error) {
if (error instanceof NotFoundException || error instanceof BadRequestException || error instanceof ForbiddenException) {
throw error;
}
this.logger.error(`Error registering device for user ${userId}:`, error);
throw new Error('Failed to register device');
}
}
async unregisterDevice(userId: number, token: string) {
const device = await this.prisma.pushDeviceToken.findUnique({
where: { token },
});
if (!device) {
throw new NotFoundException('Device token not found');
}
if (device.userId !== userId) {
throw new ForbiddenException('You can only unregister your own devices');
}
await this.prisma.pushDeviceToken.delete({ where: { token } });
return { success: true };
}
async getUserDevices(userId: number) {
return this.prisma.pushDeviceToken.findMany({
where: { userId },
orderBy: { createdAt: 'desc' },
});
}
async sendPush(userId: number, notification: any) {
// Get all registered devices for user
const devices = await this.prisma.pushDeviceToken.findMany({
where: { userId },
});
if (devices.length === 0) {
return;
}
// Prefer FCM if configured; otherwise log as fallback
if (this.fcm) {
const messages: admin.messaging.TokenMessage[] = devices.map((device) => {
const data: Record<string, string> | undefined =
notification && notification.payload != null
? {
payload:
typeof notification.payload === 'string'
? notification.payload
: JSON.stringify(notification.payload),
}
: undefined;
const msg: admin.messaging.TokenMessage = {
token: device.token,
notification: {
title: String(notification.type),
body: this.formatNotificationBody(notification),
},
...(data ? { data } : {}),
};
return msg;
});
// Send individually to capture per-token errors
for (const msg of messages) {
try {
await this.fcm.send(msg);
} catch (err) {
this.logger.warn(`FCM send failed for token ${msg.token}: ${(err as any)?.message || err}`);
}
}
} else {
for (const device of devices) {
this.logger.log(`[PUSH-DRYRUN] ${device.platform}:${device.token} -> ${notification.type} | ${this.formatNotificationBody(notification)}`);
}
}
}
// Helper method to format notification body for display
private formatNotificationBody(notification: any): string {
switch (notification.type) {
case 'NEW_MESSAGE':
return `New message from ${notification.payload.senderName}`;
case 'LISTING_UPDATE':
return `Listing "${notification.payload.listingTitle}" was updated`;
case 'PRICE_DROP':
return `Price dropped on "${notification.payload.listingTitle}"`;
default:
return notification.type;
}
}
}
|