Files
petfeed/src/lib/notify.ts
T
adminandClaude Opus 5.5 4cf28213ff feat: Jede Mitteilung fuehrt direkt zum Ziel (Liste + Push)
Tester-Wunsch 04.10.: „Benachrichtigung bringt dich auf kuerzestem Weg
dorthin, wo es wichtig ist“.
- Nachrichten: notifications.list liefert die conversationId (ueber das
  sortierte Tier-Paar), App und Web oeffnen direkt das Gespraech.
- Push-Mitteilungen: Antippen fuehrte bisher nur in die App. Jetzt
  useNotificationTapRouting (useLastNotificationResponse, auch Kaltstart),
  wechselt bei Bedarf aufs betroffene eigene Tier. Push-Daten tragen dafuer
  petId, actorPetId, storyId, conversationId.
- Eine gemeinsame Zielregel fuer Liste und Push (mobile/src/lib/
  notification-route.ts, getestet): Nachricht → Gespraech, Kommentar/Pfote/
  Erwaehnung/Paw-Back → Beitrag, Story → Story, Follow/Vorschlag → Profil,
  Geburtstag/Adoption/Impfung → Gesundheit, Rang → Einladen.
- Bei Nachrichten und Storys fuehrt auch der Name zum Ziel; Story-Viewer
  laedt Name/Bild nach, wenn er per Push geoeffnet wird.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 17:52:23 +02:00

109 lines
5.5 KiB
TypeScript

import "server-only";
import type { PrismaClient, NotificationType } from "@prisma/client";
import { sendExpoPushNotification } from "@/lib/push";
interface NotifyParams {
recipientPetId: string;
type: NotificationType;
actorPetId?: string;
postId?: string;
commentId?: string;
vaccineId?: string;
storyId?: string;
}
/**
* Nur für die Push-Daten (nicht in der Notification-Tabelle): Ziele, die die
* App beim Antippen der Push-Mitteilung braucht, z. B. das Gespräch einer Nachricht.
*/
export type PushExtras = { conversationId?: string };
/**
* Fire-and-forget notification create — never blocks or fails the caller.
* Use for user-triggered notifications (follow, reaction, comment, repost,
* message, mention) where a notification failure must not fail the
* underlying action. For notifications that must be awaited (e.g. batch
* cron jobs that track a created-count), call prisma.notification.create
* directly instead.
*/
export function notify(
prisma: Pick<PrismaClient, "notification" | "pet" | "owner">,
params: NotifyParams,
extras?: PushExtras
): void {
prisma.notification.create({ data: params }).catch((err) => console.error("[notify] failed", err));
sendPushForNotification(prisma, params, undefined, extras).catch((err) => console.error("[notify] push failed", err));
}
const PUSH_COPY: Record<
NotificationType,
{ title: string; genericBody: string; actorBody: (actorName: string) => string }
> = {
FOLLOW: { title: "Neuer Follower", genericBody: "Du hast einen neuen Follower.", actorBody: (a) => `${a} folgt dir jetzt.` },
REACTION: { title: "Neue Reaktion", genericBody: "Jemand hat auf deinen Beitrag reagiert.", actorBody: (a) => `${a} hat auf deinen Beitrag reagiert.` },
COMMENT: { title: "Neuer Kommentar", genericBody: "Neuer Kommentar zu deinem Beitrag.", actorBody: (a) => `${a} hat deinen Beitrag kommentiert.` },
MESSAGE: { title: "Neue Nachricht", genericBody: "Du hast eine neue Nachricht erhalten.", actorBody: (a) => `${a} hat dir eine Nachricht geschickt.` },
BIRTHDAY: { title: "Geburtstag", genericBody: "Ein Tier hat heute Geburtstag.", actorBody: (a) => `${a} hat heute Geburtstag!` },
ADOPTION_DAY: { title: "Adoptionstag", genericBody: "Ein Adoptionstag steht an.", actorBody: (a) => `${a} feiert heute den Adoptionstag!` },
MENTION: { title: "Erwähnung", genericBody: "Du wurdest in einem Beitrag erwähnt.", actorBody: (a) => `${a} hat dich erwähnt.` },
PAW_BACK: { title: "Paw-Back", genericBody: "Jemand hat deinen Beitrag geteilt.", actorBody: (a) => `${a} hat deinen Beitrag geteilt.` },
PET_SUGGESTION: { title: "Vorschlag für dich", genericBody: "Ein Tier könnte dir gefallen.", actorBody: (a) => `${a} könnte dir gefallen!` },
REFERRAL_JOINED: { title: "Deine Einladung hat geklappt", genericBody: "Ein neues Tier ist über deine Einladung zu PawFeed gekommen.", actorBody: (a) => `${a} ist über deine Einladung zu PawFeed gekommen.` },
REFERRAL_RANK_UP: { title: "Neuer Rang", genericBody: "Du hast einen neuen Empfehlungsrang erreicht.", actorBody: () => "Du hast einen neuen Empfehlungsrang erreicht." },
VACCINE_DUE: { title: "Impfung bald fällig", genericBody: "Eine Impfung wird bald fällig.", actorBody: () => "Eine Impfung wird bald fällig." },
STORY_MENTION: { title: "In einer Story markiert", genericBody: "Du wurdest in einer Story markiert.", actorBody: (a) => `${a} hat dich in einer Story markiert.` },
STORY_COMMENT: { title: "Neuer Story-Kommentar", genericBody: "Jemand hat deine Story kommentiert.", actorBody: (a) => `${a} hat deine Story kommentiert.` },
STORY_REACTION: { title: "Neue Pfote", genericBody: "Jemand hat deiner Story eine Pfote gegeben.", actorBody: (a) => `${a} hat deiner Story eine Pfote gegeben.` },
};
/**
* Best-effort Expo push to the recipient owner's registered device, if any.
* Separate from the in-app Notification row above — a missing/expired push
* token, or the owner never having opened the mobile app, is the normal case
* and must silently no-op rather than error.
*
* Exported (not just used via notify() above) so a batch cron job that needs
* an awaited, counted prisma.notification.create (see notify()'s own doc
* comment) can still trigger the matching push afterward. `bodyOverride` lets
* such a job send a more specific text than PUSH_COPY's fixed one (e.g. the
* vaccine name and due date for VACCINE_DUE).
*/
export async function sendPushForNotification(
prisma: Pick<PrismaClient, "pet" | "owner">,
params: NotifyParams,
bodyOverride?: string,
extras?: PushExtras
): Promise<void> {
const recipientPet = await prisma.pet.findUnique({
where: { id: params.recipientPetId },
select: { ownerId: true },
});
if (!recipientPet) return;
const owner = await prisma.owner.findUnique({
where: { id: recipientPet.ownerId },
select: { expoPushToken: true },
});
if (!owner?.expoPushToken) return;
const actorPet = params.actorPetId
? await prisma.pet.findUnique({ where: { id: params.actorPetId }, select: { name: true } })
: null;
const copy = PUSH_COPY[params.type];
await sendExpoPushNotification(owner.expoPushToken, {
title: copy.title,
body: bodyOverride ?? (actorPet ? copy.actorBody(actorPet.name) : copy.genericBody),
// Ziele für das Antippen der Push-Mitteilung (App: src/lib/notification-route.ts).
data: {
type: params.type,
postId: params.postId ?? "",
commentId: params.commentId ?? "",
petId: params.recipientPetId,
actorPetId: params.actorPetId ?? "",
storyId: params.storyId ?? "",
conversationId: extras?.conversationId ?? "",
},
});
}