From d6f1bc781a3010440112ddad1ba5469ae8bbf7e2 Mon Sep 17 00:00:00 2001 From: Giuseppe Lombardo Date: Wed, 12 Aug 2026 16:35:02 +0000 Subject: [PATCH] add backend/src/services/notificationService.ts --- backend/src/services/notificationService.ts | 54 +++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 backend/src/services/notificationService.ts diff --git a/backend/src/services/notificationService.ts b/backend/src/services/notificationService.ts new file mode 100644 index 0000000..352d12e --- /dev/null +++ b/backend/src/services/notificationService.ts @@ -0,0 +1,54 @@ +import { PrismaClient } from '@prisma/client'; + +const prisma = new PrismaClient(); + +const ONESIGNAL_APP_ID = process.env.ONESIGNAL_APP_ID!; +const ONESIGNAL_API_KEY = process.env.ONESIGNAL_API_KEY!; + +interface PushInput { + userId: string; + type: string; + title: string; + body: string; + payload?: Record; +} + +/** + * Sendet eine Push-Notification via OneSignal und protokolliert sie in der + * `notifications`-Tabelle (Audit-Trail + In-App-Benachrichtigungszentrum). + */ +export async function sendPushNotification(input: PushInput): Promise { + const user = await prisma.user.findUnique({ where: { id: input.userId } }); + + await prisma.notification.create({ + data: { + userId: input.userId, + type: input.type, + title: input.title, + body: input.body, + payload: input.payload as any, + }, + }); + + if (!user?.pushToken) return; // kein registriertes Gerät -> nur In-App geloggt + + try { + await fetch('https://onesignal.com/api/v1/notifications', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Basic ${ONESIGNAL_API_KEY}`, + }, + body: JSON.stringify({ + app_id: ONESIGNAL_APP_ID, + include_player_ids: [user.pushToken], + headings: { en: input.title, de: input.title }, + contents: { en: input.body, de: input.body }, + data: { type: input.type, ...input.payload }, + }), + }); + } catch (err) { + // Push-Fehler dürfen den Business-Flow (z.B. Zahlungsabgleich) nicht blockieren. + console.error('[notificationService] OneSignal-Versand fehlgeschlagen:', err); + } +}