All files / services/notification notification.service.ts

100% Statements 53/53
100% Branches 37/37
100% Functions 10/10
100% Lines 48/48

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                                43x 43x       15x     15x 15x 2x 2x     15x 2x 2x       15x                     13x 13x   1x                       13x     13x 13x 9x 9x     4x           15x   4x 2x                                   15x 13x   13x   13x 12x   12x           12x   12x           12x 6x 6x   2x                 6x 4x 4x   2x                       13x 13x 13x   13x       18x 18x 18x 18x 5x      
import type { Dal } from "../../dal";
import { generateId } from "../../lib/utils";
import { getCategoryForEventType } from "../../lib/notification-categories";
import { sendWebPush, type VapidKeys } from "./web-push";
 
type NotifyParams = {
	proId?: string;
	eventType: string;
	title: string;
	body?: string;
	data?: Record<string, unknown>;
	targetUserIds?: string[];
};
 
export class NotificationService {
	constructor(
		private dal: Dal,
		private env: CloudflareBindings,
	) {}
 
	async notify(params: NotifyParams): Promise<void> {
		const category = getCategoryForEventType(params.eventType);
 
		// Resolve target users
		let userIds = params.targetUserIds ?? [];
		if (userIds.length === 0 && params.proId) {
			const roles = await this.dal.userTenantRoles.findByProId(params.proId);
			userIds = roles.map((r) => r.userId);
		}
 
		if (userIds.length === 0) {
			console.warn(`[NotificationService] No recipients resolved for event=${params.eventType} proId=${params.proId}`);
			return;
		}
 
		// Create in-app notifications
		const notifications = userIds.map((userId) => ({
			id: generateId(),
			userId,
			proId: params.proId ?? null,
			eventType: params.eventType,
			category,
			title: params.title,
			body: params.body ?? null,
			dataJson: params.data ? JSON.stringify(params.data) : null,
		}));
 
		try {
			await this.dal.notifications.createMany(notifications);
		} catch (err) {
			console.error(JSON.stringify({
				level: "error",
				service: "NotificationService",
				action: "createMany",
				eventType: params.eventType,
				userCount: userIds.length,
				/* v8 ignore start -- V8 artifact: ternary false branch */
				error: err instanceof Error ? err.message : String(err),
				/* v8 ignore stop */
			}));
		}
 
		console.info(`[Notify] In-app created: eventType=${params.eventType}, users=${userIds.length}, proId=${params.proId}`);
 
		// Send push notifications (awaited so Workers doesn't kill the promises)
		const vapidKeys = this.getVapidKeys();
		if (!vapidKeys) {
			console.warn("[NotificationService] VAPID keys not configured — push notifications disabled");
			return;
		}
 
		const payload = JSON.stringify({
			title: params.title,
			body: params.body,
			url: params.data?.url,
		});
 
		await Promise.allSettled(
			userIds.map((userId) =>
				this.sendPushToUser(userId, payload, vapidKeys).catch((err) => {
					console.error(JSON.stringify({
						level: "error",
						service: "NotificationService",
						action: "sendPush",
						userId,
						eventType: params.eventType,
						error: err instanceof Error ? err.message : String(err),
					}));
				})
			),
		);
	}
 
	async sendPushToUser(
		userId: string,
		payload: string,
		vapidKeys: VapidKeys,
	): Promise<{ sent: number; failed: number; details: Array<{ endpoint: string; success: boolean; error?: string }> }> {
		const subscriptions = await this.dal.pushSubscriptions.findActiveByUser(userId);
		const details: Array<{ endpoint: string; success: boolean; error?: string }> = [];
 
		console.info(`[Push] Sending to user=${userId}, subscriptions=${subscriptions.length}, payload=${payload.substring(0, 100)}`);
 
		for (const sub of subscriptions) {
			console.info(`[Push] → endpoint=${sub.endpoint.substring(0, 60)}...`);
 
			const result = await sendWebPush(
				{ endpoint: sub.endpoint, p256dh: sub.p256dh, auth: sub.auth },
				payload,
				vapidKeys,
			);
 
			console.info(`[Push] ← success=${result.success}, statusCode=${result.statusCode ?? "N/A"}, error=${result.error ?? "none"}`);
 
			details.push({
				endpoint: sub.endpoint,
				success: result.success,
				error: result.error,
			});
 
			if (result.success) {
				try {
					await this.dal.pushSubscriptions.updateLastActive(sub.id);
				} catch (dbErr) {
					console.error(JSON.stringify({
						level: "error",
						service: "NotificationService",
						action: "updateLastActive",
						subscriptionId: sub.id,
						userId,
						error: dbErr instanceof Error ? dbErr.message : String(dbErr),
					}));
				}
			} else if (result.statusCode === 410 || result.statusCode === 404) {
				try {
					await this.dal.pushSubscriptions.deactivate(sub.id);
				} catch (dbErr) {
					console.error(JSON.stringify({
						level: "error",
						service: "NotificationService",
						action: "deactivateSubscription",
						subscriptionId: sub.id,
						userId,
						error: dbErr instanceof Error ? dbErr.message : String(dbErr),
					}));
				}
			}
		}
 
		const sent = details.filter((d) => d.success).length;
		const failed = details.filter((d) => !d.success).length;
		console.info(`[Push] Summary: user=${userId}, sent=${sent}, failed=${failed}`);
 
		return { sent, failed, details };
	}
 
	getVapidKeys(): VapidKeys | null {
		const publicKey = this.env.VAPID_PUBLIC_KEY;
		const privateKey = this.env.VAPID_PRIVATE_KEY;
		const subject = this.env.VAPID_SUBJECT;
		if (!publicKey || !privateKey || !subject) return null;
		return { publicKey, privateKey, subject };
	}
}