From 4cf28213ff748d3a4d5ed3bc1b650573697ebb51 Mon Sep 17 00:00:00 2001 From: neodk2004 Date: Sun, 4 Oct 2026 17:52:23 +0200 Subject: [PATCH] feat: Jede Mitteilung fuehrt direkt zum Ziel (Liste + Push) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- mobile/app/(app)/(tabs)/notifications.tsx | 74 +++++++----------- mobile/app/(app)/_layout.tsx | 3 + mobile/app/(app)/story-viewer.tsx | 6 +- mobile/src/hooks/useNotificationTapRouting.ts | 39 ++++++++++ mobile/src/lib/notification-route.test.ts | 71 +++++++++++++++++ mobile/src/lib/notification-route.ts | 78 +++++++++++++++++++ src/__tests__/notifications.test.ts | 19 +++++ src/app/(app)/notifications/page.tsx | 3 + src/lib/notify.ts | 25 +++++- src/lib/team-pet.ts | 2 +- src/trpc/routers/messages.ts | 10 +-- src/trpc/routers/notifications.ts | 25 +++++- 12 files changed, 295 insertions(+), 60 deletions(-) create mode 100644 mobile/src/hooks/useNotificationTapRouting.ts create mode 100644 mobile/src/lib/notification-route.test.ts create mode 100644 mobile/src/lib/notification-route.ts diff --git a/mobile/app/(app)/(tabs)/notifications.tsx b/mobile/app/(app)/(tabs)/notifications.tsx index 5b4fb8e..744ea19 100644 --- a/mobile/app/(app)/(tabs)/notifications.tsx +++ b/mobile/app/(app)/(tabs)/notifications.tsx @@ -10,6 +10,7 @@ import { useTheme } from "../../../src/context/ThemeContext"; import { PetAvatar } from "../../../src/components/PetAvatar"; import { formatPetName, formatRelativeTime } from "../../../src/lib/format"; import { isoToDisplayDate } from "../../../src/lib/date-format"; +import { notificationRoute } from "../../../src/lib/notification-route"; import { getTypography, type ColorTokens, type Typography } from "../../../src/theme/tokens"; import type { NotificationItem } from "../../../src/api/types"; @@ -60,53 +61,32 @@ const SELF_ICONS: Partial> = { }; /** - * Port of web's notifications/page.tsx getHref()/getPostId(): FOLLOW goes to - * the actor's profile, BIRTHDAY/ADOPTION_DAY to this pet's own health page - * (the anniversary is about *this* pet, there's no other actor to visit), - * and REACTION/COMMENT/MENTION/PAW_BACK go to the post. Web opens the post - * in an inline dialog; mobile has no such dialog, so this goes to the - * comments screen instead — the closest existing route to "the post". - * MESSAGE has no target here either, matching web (it doesn't handle it - * there so this doesn't try to be smarter about it). + * Ziel einer Mitteilung — gemeinsame Regel mit dem Antippen von Push-Mitteilungen + * (src/lib/notification-route.ts): Nachricht → Gespräch, Kommentar/Pfote/Erwähnung + * → Beitrag, Story-Mitteilungen → die Story, Follow/Vorschlag → Profil, + * Geburtstag/Impfung → Gesundheit. Nur in Event-Handlern aufrufen (Date.now()). */ function getNotificationRoute(item: NotificationItem): string | null { - // Story-Mitteilungen: Story öffnen, solange sie läuft (der Besitzer sieht - // eigene Storys 7 Tage), sonst das Tierprofil. - if (item.story && (item.type === "STORY_MENTION" || item.type === "STORY_COMMENT" || item.type === "STORY_REACTION")) { - const isOwnStory = item.story.petId === item.recipientPetId; - const isRunning = new Date(item.story.expiresAt).getTime() > Date.now(); - if (isRunning || isOwnStory) { - const params = new URLSearchParams({ - petId: item.story.petId, - petName: item.story.pet.name, - petAvatarKey: item.story.pet.avatarKey ?? "", - storyId: item.story.id, - }); - return `/story-viewer?${params.toString()}`; - } - return `/pets/${item.story.petId}`; - } - switch (item.type) { - case "FOLLOW": - case "PET_SUGGESTION": - case "REFERRAL_JOINED": - return item.actorPet ? `/pets/${item.actorPet.id}` : null; - case "REFERRAL_RANK_UP": - return "/invite"; - case "BIRTHDAY": - case "ADOPTION_DAY": - case "VACCINE_DUE": - return item.recipientPetId ? `/pets/${item.recipientPetId}/health` : null; - case "REACTION": - case "COMMENT": - case "MENTION": - case "PAW_BACK": - return item.post?.id ? `/posts/${item.post.id}/comments` : null; - default: - return null; - } + return notificationRoute( + { + type: item.type, + recipientPetId: item.recipientPetId, + actorPetId: item.actorPet?.id ?? null, + postId: item.post?.id ?? null, + conversationId: item.conversationId, + storyId: item.story?.id ?? null, + storyPetId: item.story?.petId ?? null, + storyPetName: item.story?.pet.name ?? null, + storyPetAvatarKey: item.story?.pet.avatarKey ?? null, + storyExpiresAt: item.story?.expiresAt ?? null, + }, + Date.now() + ); } +/** Bei diesen Typen führt auch der Name direkt zum Ziel (nicht zum Profil-Umweg). */ +const NAME_OPENS_TARGET = new Set(["MESSAGE", "STORY_MENTION", "STORY_COMMENT", "STORY_REACTION"]); + /** Port of web's notifications list — tapping a row marks it read and navigates to its target (post/pet). */ export default function NotificationsScreen() { const { t } = useTranslation(); @@ -201,11 +181,11 @@ export default function NotificationsScreen() { { - // Bei Story-Mitteilungen führt auch der Name zur Story (nicht zum Profil-Umweg). - const storyRoute = item.story ? getNotificationRoute(item) : null; - if (storyRoute) { + // Bei Nachrichten und Storys führt auch der Name direkt zum Ziel. + const targetRoute = NAME_OPENS_TARGET.has(item.type) ? getNotificationRoute(item) : null; + if (targetRoute) { if (!item.read) markRead.mutate({ notificationId: item.id }); - router.push(storyRoute); + router.push(targetRoute); } else { router.push(`/pets/${item.actorPet!.id}`); } diff --git a/mobile/app/(app)/_layout.tsx b/mobile/app/(app)/_layout.tsx index 265afce..47d9cca 100644 --- a/mobile/app/(app)/_layout.tsx +++ b/mobile/app/(app)/_layout.tsx @@ -4,6 +4,7 @@ import { X } from "lucide-react-native"; import { useTranslation } from "react-i18next"; import { useTheme } from "../../src/context/ThemeContext"; import { fontFamily } from "../../src/theme/tokens"; +import { useNotificationTapRouting } from "../../src/hooks/useNotificationTapRouting"; function CloseModalButton() { const router = useRouter(); @@ -17,6 +18,8 @@ function CloseModalButton() { export default function AppLayout() { const { t } = useTranslation(); + // Push-Mitteilung angetippt → direkt zum Ziel (Gespräch, Beitrag, Story …) + useNotificationTapRouting(); const { colors } = useTheme(); // Plain prop objects, not StyleSheet.create — safe to recompute on every // render, unlike the module-level StyleSheet.create calls most other diff --git a/mobile/app/(app)/story-viewer.tsx b/mobile/app/(app)/story-viewer.tsx index 69afb31..896ed81 100644 --- a/mobile/app/(app)/story-viewer.tsx +++ b/mobile/app/(app)/story-viewer.tsx @@ -34,7 +34,7 @@ type Sheet = "comments" | "viewers" | "confirm-delete" | "away" | null; * die Lösch-Rückfrage offen ist, hält der Timer an. */ export default function StoryViewerScreen() { - const { petId, petName, petAvatarKey, storyId: initialStoryId } = useLocalSearchParams<{ + const { petId, petName: petNameParam, petAvatarKey: petAvatarKeyParam, storyId: initialStoryId } = useLocalSearchParams<{ petId: string; petName: string; petAvatarKey?: string; @@ -48,6 +48,10 @@ export default function StoryViewerScreen() { const { activePetId } = useActivePet(); const insets = useSafeAreaInsets(); const isOwnStory = activePetId === petId; + // Über eine Push-Mitteilung geöffnet → nur petId bekannt, Name/Bild nachladen. + const { data: storyPet } = useQuery({ ...trpc.pets.getProfile.queryOptions({ petId }), enabled: !petNameParam }); + const petName = petNameParam || storyPet?.name || ""; + const petAvatarKey = petAvatarKeyParam || storyPet?.avatarKey || undefined; const listQuery = trpc.stories.listActive.queryOptions({ petId, viewerPetId: activePetId ?? undefined }); const { data: stories = [], isSuccess: storiesLoaded } = useQuery(listQuery); diff --git a/mobile/src/hooks/useNotificationTapRouting.ts b/mobile/src/hooks/useNotificationTapRouting.ts new file mode 100644 index 0000000..8dc57a5 --- /dev/null +++ b/mobile/src/hooks/useNotificationTapRouting.ts @@ -0,0 +1,39 @@ +import { useEffect, useRef } from "react"; +import * as Notifications from "expo-notifications"; +import { useRouter } from "expo-router"; +import { useActivePet } from "../context/ActivePetContext"; +import { notificationRoute, targetFromPushData } from "../lib/notification-route"; + +/** + * Antippen einer Push-Mitteilung führt direkt zum Ziel (Gespräch, Beitrag, + * Story, Profil, Gesundheit) — vorher öffnete ein Tipp nur die App. + * useLastNotificationResponse deckt laufende App und Kaltstart ab. + * + * Gilt die Mitteilung für ein anderes eigenes Tier, wird vorher dorthin + * gewechselt (Nachrichten und Gesundheit hängen am aktiven Tier). + * Läuft im (app)-Layout, also erst nach Login und mit geladenen Tieren. + */ +export function useNotificationTapRouting(): void { + const response = Notifications.useLastNotificationResponse(); + const router = useRouter(); + const { activePetId, setActivePetId, pets, isPending } = useActivePet(); + const handledId = useRef(null); + + useEffect(() => { + if (!response || isPending) return; + if (response.actionIdentifier !== Notifications.DEFAULT_ACTION_IDENTIFIER) return; + const id = response.notification.request.identifier; + if (handledId.current === id) return; + handledId.current = id; + + const target = targetFromPushData(response.notification.request.content.data as Record | undefined); + Notifications.clearLastNotificationResponse(); + if (!target) return; + + if (target.recipientPetId && target.recipientPetId !== activePetId && pets.some((p) => p.id === target.recipientPetId)) { + setActivePetId(target.recipientPetId); + } + const route = notificationRoute(target, Date.now()); + if (route) router.push(route); + }, [response, isPending, activePetId, pets, setActivePetId, router]); +} diff --git a/mobile/src/lib/notification-route.test.ts b/mobile/src/lib/notification-route.test.ts new file mode 100644 index 0000000..d257127 --- /dev/null +++ b/mobile/src/lib/notification-route.test.ts @@ -0,0 +1,71 @@ +import { describe, it, expect } from "vitest"; +import { notificationRoute, targetFromPushData } from "./notification-route"; + +const NOW = new Date("2026-10-04T12:00:00Z").getTime(); + +describe("notificationRoute", () => { + it("opens the conversation for messages", () => { + expect(notificationRoute({ type: "MESSAGE", conversationId: "c1" }, NOW)).toBe("/messages/c1"); + expect(notificationRoute({ type: "MESSAGE" }, NOW)).toBe("/messages"); + }); + + it("opens the post for reactions, comments, mentions and paw-backs", () => { + for (const type of ["REACTION", "COMMENT", "MENTION", "PAW_BACK"]) { + expect(notificationRoute({ type, postId: "p1" }, NOW)).toBe("/posts/p1/comments"); + } + }); + + it("opens the actor's profile for follows, suggestions and referrals", () => { + for (const type of ["FOLLOW", "PET_SUGGESTION", "REFERRAL_JOINED"]) { + expect(notificationRoute({ type, actorPetId: "a1" }, NOW)).toBe("/pets/a1"); + } + expect(notificationRoute({ type: "REFERRAL_RANK_UP" }, NOW)).toBe("/invite"); + }); + + it("opens the own pet's health page for birthdays, adoption days and vaccines", () => { + for (const type of ["BIRTHDAY", "ADOPTION_DAY", "VACCINE_DUE"]) { + expect(notificationRoute({ type, recipientPetId: "me" }, NOW)).toBe("/pets/me/health"); + } + }); + + it("opens the tagged story directly, at the right story", () => { + const route = notificationRoute({ type: "STORY_MENTION", recipientPetId: "me", actorPetId: "tagger", storyId: "s1" }, NOW)!; + expect(route.startsWith("/story-viewer?")).toBe(true); + const params = new URLSearchParams(route.split("?")[1]); + expect(params.get("petId")).toBe("tagger"); + expect(params.get("storyId")).toBe("s1"); + }); + + it("comments and paws on the own story open the own story", () => { + const route = notificationRoute({ type: "STORY_COMMENT", recipientPetId: "me", actorPetId: "fan", storyId: "s2" }, NOW)!; + expect(new URLSearchParams(route.split("?")[1]).get("petId")).toBe("me"); + }); + + it("falls back to the profile when someone else's story has expired", () => { + expect( + notificationRoute( + { type: "STORY_MENTION", recipientPetId: "me", storyId: "s1", storyPetId: "tagger", storyExpiresAt: "2026-10-03T00:00:00Z" }, + NOW + ) + ).toBe("/pets/tagger"); + }); + + it("returns null for unknown types", () => { + expect(notificationRoute({ type: "SOMETHING_NEW" }, NOW)).toBeNull(); + }); +}); + +describe("targetFromPushData", () => { + it("reads the server's push payload and treats empty strings as missing", () => { + expect(targetFromPushData({ type: "MESSAGE", petId: "me", actorPetId: "a", postId: "", storyId: "", conversationId: "c1" })).toEqual({ + type: "MESSAGE", + recipientPetId: "me", + actorPetId: "a", + postId: null, + storyId: null, + conversationId: "c1", + }); + expect(targetFromPushData(undefined)).toBeNull(); + expect(targetFromPushData({ foo: 1 })).toBeNull(); + }); +}); diff --git a/mobile/src/lib/notification-route.ts b/mobile/src/lib/notification-route.ts new file mode 100644 index 0000000..e6941b3 --- /dev/null +++ b/mobile/src/lib/notification-route.ts @@ -0,0 +1,78 @@ +/** + * Wohin führt eine Mitteilung? Eine Regel für die Mitteilungsliste und für das + * Antippen einer Push-Mitteilung (Tester-Wunsch 04.10.: „Benachrichtigung bringt + * dich auf kürzestem Weg dorthin, wo es wichtig ist“). + * + * Push-Daten kommen von src/lib/notify.ts (Server): type, petId (Empfänger), + * actorPetId, postId, storyId, conversationId — fehlende Felder als "". + */ +export type NotificationTarget = { + type: string; + /** Empfänger-Tier (eigenes Tier) */ + recipientPetId?: string | null; + actorPetId?: string | null; + postId?: string | null; + conversationId?: string | null; + storyId?: string | null; + /** Tier, dem die Story gehört — aus der Liste bekannt, beim Push hergeleitet */ + storyPetId?: string | null; + storyPetName?: string | null; + storyPetAvatarKey?: string | null; + /** Ablauf der Story, falls bekannt (Liste); beim Push unbekannt → Viewer prüft selbst */ + storyExpiresAt?: string | Date | null; +}; + +const STORY_TYPES = new Set(["STORY_MENTION", "STORY_COMMENT", "STORY_REACTION"]); + +export function notificationRoute(target: NotificationTarget, now: number): string | null { + const { type, recipientPetId, actorPetId, postId, conversationId } = target; + + if (STORY_TYPES.has(type) && target.storyId) { + // Markierung: Story gehört dem markierenden Tier; Kommentar/Pfote: der eigenen. + const storyPetId = target.storyPetId || (type === "STORY_MENTION" ? actorPetId : recipientPetId); + if (!storyPetId) return null; + const isOwnStory = storyPetId === recipientPetId; + const expired = target.storyExpiresAt ? new Date(target.storyExpiresAt).getTime() <= now : false; + if (expired && !isOwnStory) return `/pets/${storyPetId}`; + const params = new URLSearchParams({ petId: storyPetId, storyId: target.storyId }); + if (target.storyPetName) params.set("petName", target.storyPetName); + if (target.storyPetAvatarKey) params.set("petAvatarKey", target.storyPetAvatarKey); + return `/story-viewer?${params.toString()}`; + } + + switch (type) { + case "MESSAGE": + return conversationId ? `/messages/${conversationId}` : "/messages"; + case "REACTION": + case "COMMENT": + case "MENTION": + case "PAW_BACK": + return postId ? `/posts/${postId}/comments` : null; + case "FOLLOW": + case "PET_SUGGESTION": + case "REFERRAL_JOINED": + return actorPetId ? `/pets/${actorPetId}` : null; + case "REFERRAL_RANK_UP": + return "/invite"; + case "BIRTHDAY": + case "ADOPTION_DAY": + case "VACCINE_DUE": + return recipientPetId ? `/pets/${recipientPetId}/health` : null; + default: + return null; + } +} + +/** Push-Daten (alles Strings, leer = fehlt) → Ziel. */ +export function targetFromPushData(data: Record | null | undefined): NotificationTarget | null { + if (!data || typeof data.type !== "string") return null; + const str = (key: string) => (typeof data[key] === "string" && data[key] ? (data[key] as string) : null); + return { + type: data.type, + recipientPetId: str("petId"), + actorPetId: str("actorPetId"), + postId: str("postId"), + storyId: str("storyId"), + conversationId: str("conversationId"), + }; +} diff --git a/src/__tests__/notifications.test.ts b/src/__tests__/notifications.test.ts index 9c01f00..9c1c313 100644 --- a/src/__tests__/notifications.test.ts +++ b/src/__tests__/notifications.test.ts @@ -61,6 +61,25 @@ describe("notifications.list", () => { expect(result).toEqual({ notifications: [], nextCursor: null }); }); + + it("adds the conversation to message notifications so a tap opens the chat", async () => { + const { caller, mockPrisma } = await createNotificationsCaller(); + mockPrisma.pet.findUnique.mockResolvedValue({ id: "my-pet", ownerId: "owner-1" }); + mockPrisma.notification.findMany.mockResolvedValue([ + { id: "n1", type: "MESSAGE", recipientPetId: "my-pet", actorPetId: "a-friend", createdAt: new Date() }, + { id: "n2", type: "FOLLOW", recipientPetId: "my-pet", actorPetId: "a-friend", createdAt: new Date() }, + ]); + // Gespräch ist sortiert gespeichert (petAId < petBId) + mockPrisma.conversation.findMany.mockResolvedValue([{ id: "conv-1", petAId: "a-friend", petBId: "my-pet" }]); + + const result = await caller.notifications.list({ petId: "my-pet" }); + + expect(result.notifications.map((n: { id: string; conversationId: string | null }) => [n.id, n.conversationId])).toEqual([ + ["n1", "conv-1"], + ["n2", null], + ]); + expect(mockPrisma.conversation.findMany.mock.calls[0][0].where.OR).toEqual([{ petAId: "a-friend", petBId: "my-pet" }]); + }); }); describe("notifications.unreadCount", () => { diff --git a/src/app/(app)/notifications/page.tsx b/src/app/(app)/notifications/page.tsx index ba01c1d..de864fa 100644 --- a/src/app/(app)/notifications/page.tsx +++ b/src/app/(app)/notifications/page.tsx @@ -109,6 +109,9 @@ export default function NotificationsPage() { return notif.actorPet ? `/pets/${notif.actorPet.id}` : null; case "REFERRAL_RANK_UP": return "/einladen"; + // Nachricht → direkt ins Gespräch (conversationId liefert notifications.list) + case "MESSAGE": + return notif.conversationId ? `/messages/${notif.conversationId}` : "/messages"; // Story-Mitteilungen: läuft die Story noch (oder ist es die eigene, 7 Tage sichtbar), // öffnet getStoryTarget() sie direkt; sonst bleibt nur das Tierprofil. case "STORY_MENTION": diff --git a/src/lib/notify.ts b/src/lib/notify.ts index 79fd936..83cf8c0 100644 --- a/src/lib/notify.ts +++ b/src/lib/notify.ts @@ -12,6 +12,12 @@ interface NotifyParams { 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, @@ -22,10 +28,11 @@ interface NotifyParams { */ export function notify( prisma: Pick, - params: NotifyParams + params: NotifyParams, + extras?: PushExtras ): void { prisma.notification.create({ data: params }).catch((err) => console.error("[notify] failed", err)); - sendPushForNotification(prisma, params).catch((err) => console.error("[notify] push failed", err)); + sendPushForNotification(prisma, params, undefined, extras).catch((err) => console.error("[notify] push failed", err)); } const PUSH_COPY: Record< @@ -64,7 +71,8 @@ const PUSH_COPY: Record< export async function sendPushForNotification( prisma: Pick, params: NotifyParams, - bodyOverride?: string + bodyOverride?: string, + extras?: PushExtras ): Promise { const recipientPet = await prisma.pet.findUnique({ where: { id: params.recipientPetId }, @@ -86,6 +94,15 @@ export async function sendPushForNotification( await sendExpoPushNotification(owner.expoPushToken, { title: copy.title, body: bodyOverride ?? (actorPet ? copy.actorBody(actorPet.name) : copy.genericBody), - data: { type: params.type, postId: params.postId ?? "", commentId: params.commentId ?? "" }, + // 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 ?? "", + }, }); } diff --git a/src/lib/team-pet.ts b/src/lib/team-pet.ts index b7cd614..ef7c542 100644 --- a/src/lib/team-pet.ts +++ b/src/lib/team-pet.ts @@ -83,5 +83,5 @@ export async function sendTeamMessage( }), ]); - notify(prisma, { recipientPetId: targetPetId, type: "MESSAGE", actorPetId: teamPet.id }); + notify(prisma, { recipientPetId: targetPetId, type: "MESSAGE", actorPetId: teamPet.id }, { conversationId: conversation.id }); } diff --git a/src/trpc/routers/messages.ts b/src/trpc/routers/messages.ts index 742d8f2..76b044e 100644 --- a/src/trpc/routers/messages.ts +++ b/src/trpc/routers/messages.ts @@ -248,11 +248,11 @@ export const messagesRouter = router({ ]); // MESSAGE notification — fire-and-forget - notify(ctx.prisma, { - recipientPetId, - type: "MESSAGE", - actorPetId: input.senderPetId, - }); + notify( + ctx.prisma, + { recipientPetId, type: "MESSAGE", actorPetId: input.senderPetId }, + { conversationId: input.conversationId } + ); return message; }), diff --git a/src/trpc/routers/notifications.ts b/src/trpc/routers/notifications.ts index 0a08853..d3f52b7 100644 --- a/src/trpc/routers/notifications.ts +++ b/src/trpc/routers/notifications.ts @@ -36,8 +36,29 @@ export const notificationsRouter = router({ }); const hasNextPage = notifications.length > input.limit; - const items = hasNextPage ? notifications.slice(0, input.limit) : notifications; - const nextCursor = hasNextPage ? items[items.length - 1].createdAt.toISOString() : null; + const page = hasNextPage ? notifications.slice(0, input.limit) : notifications; + const nextCursor = hasNextPage ? page[page.length - 1].createdAt.toISOString() : null; + + // Nachrichten-Mitteilungen führen direkt ins Gespräch: Notification hat + // keine conversationId, das Gespräch ist aber über das Tier-Paar eindeutig + // (Conversation.petAId < petBId, sortiert wie in messages.getOrCreate). + const pairs = page + .filter((n) => n.type === "MESSAGE" && n.actorPetId) + .map((n) => [n.recipientPetId, n.actorPetId as string].sort()); + const conversations = pairs.length + ? await ctx.prisma.conversation.findMany({ + where: { OR: pairs.map(([petAId, petBId]) => ({ petAId, petBId })) }, + select: { id: true, petAId: true, petBId: true }, + }) + : []; + const conversationByPair = new Map(conversations.map((c) => [`${c.petAId}|${c.petBId}`, c.id])); + const items = page.map((n) => ({ + ...n, + conversationId: + n.type === "MESSAGE" && n.actorPetId + ? (conversationByPair.get([n.recipientPetId, n.actorPetId].sort().join("|")) ?? null) + : null, + })); return { notifications: items, nextCursor }; }),