add backend/src/services/notificationService.ts
This commit is contained in:
parent
1f6f9d5842
commit
d6f1bc781a
54
backend/src/services/notificationService.ts
Normal file
54
backend/src/services/notificationService.ts
Normal file
@ -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<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<void> {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user