import type { NotificationType, Prisma, PrismaClient } from '@prisma/client'; import { notFound } from '../lib/errors.js'; export interface CreateNotificationInput { userId: string; type: NotificationType; title: string; payload: Prisma.InputJsonObject; } /** Tworzy pojedyncze osobiste powiadomienie (warstwa systemowa feedu). */ export async function createNotification(prisma: PrismaClient, input: CreateNotificationInput) { return prisma.notification.create({ data: { userId: input.userId, type: input.type, title: input.title, payload: input.payload, }, }); } /** * Fan-out powiadomienia GYM_DELETED: wszyscy członkowie siłowni ∪ właściciele * planów wskazujących na tę siłownię. Nazwa siłowni ląduje w payload, więc * powiadomienie przeżywa twarde usunięcie encji. */ export async function notifyGymDeleted(prisma: PrismaClient, gymId: string, gymName: string) { const [members, planOwners] = await Promise.all([ prisma.gymMembership.findMany({ where: { gymId }, select: { userId: true } }), prisma.trainingPlan.findMany({ where: { gymId }, select: { userId: true } }), ]); const userIds = [...new Set([...members, ...planOwners].map((r) => r.userId))]; if (userIds.length === 0) return; await prisma.notification.createMany({ data: userIds.map((userId) => ({ userId, type: 'GYM_DELETED' as const, title: `Siłownia „${gymName}” została usunięta`, payload: { gymName }, })), }); } export interface FeedNotificationItem { source: 'notification'; id: string; type: NotificationType; title: string; payload: Record; read: boolean; createdAt: string; } export interface FeedAnnouncementItem { source: 'announcement'; id: string; kind: 'MANUAL' | 'HOURS_CHANGE' | 'EXCEPTION'; title: string; body: string; gymId: string | null; gymName: string | null; createdAt: string; read: boolean; } export type FeedItem = FeedNotificationItem | FeedAnnouncementItem; /** gymId, których user jest członkiem (widoczność ogłoszeń siłowni). */ async function memberGymIds(prisma: PrismaClient, userId: string): Promise { const memberships = await prisma.gymMembership.findMany({ where: { userId }, select: { gymId: true }, }); return memberships.map((m) => m.gymId); } /** * Umerged feed „Aktualności”: osobiste powiadomienia + ogłoszenia siłowni usera * i globalne. Po `limit` z każdego źródła (kursor = `createdAt`), merge po * `createdAt desc`, slice do `limit`. */ export async function getFeed( prisma: PrismaClient, userId: string, opts: { limit?: number; cursor?: string | null } = {}, ) { const limit = Math.min(Math.max(opts.limit ?? 20, 1), 100); // Nieprawidłowy kursor traktujemy jak brak kursora (pierwsza strona). const parsed = opts.cursor ? new Date(opts.cursor) : null; const createdBefore = parsed && !Number.isNaN(parsed.getTime()) ? { lt: parsed } : undefined; const gymIds = await memberGymIds(prisma, userId); const [notifications, announcements] = await Promise.all([ prisma.notification.findMany({ where: { userId, ...(createdBefore ? { createdAt: createdBefore } : {}) }, orderBy: { createdAt: 'desc' }, take: limit, }), prisma.announcement.findMany({ where: { OR: [{ gymId: { in: gymIds } }, { gymId: null }], ...(createdBefore ? { createdAt: createdBefore } : {}), }, orderBy: { createdAt: 'desc' }, take: limit, include: { gym: { select: { id: true, name: true } } }, }), ]); const readSet = new Set( ( await prisma.announcementRead.findMany({ where: { userId, announcementId: { in: announcements.map((a) => a.id) } }, select: { announcementId: true }, }) ).map((r) => r.announcementId), ); const items: FeedItem[] = [ ...notifications.map((n): FeedNotificationItem => ({ source: 'notification', id: n.id, type: n.type, title: n.title, payload: n.payload as Record, read: n.readAt !== null, createdAt: n.createdAt.toISOString(), })), ...announcements.map((a): FeedAnnouncementItem => ({ source: 'announcement', id: a.id, kind: a.kind, title: a.title, body: a.body, gymId: a.gymId, gymName: a.gym?.name ?? null, createdAt: a.createdAt.toISOString(), read: readSet.has(a.id), })), ].sort((a, b) => b.createdAt.localeCompare(a.createdAt)); const page = items.slice(0, limit); const nextCursor = page.length === limit ? page[page.length - 1].createdAt : null; return { items: page, nextCursor }; } /** Licznik nieprzeczytanych: powiadomienia + widoczne ogłoszenia bez wiersza reads. */ export async function getFeedUnreadCount(prisma: PrismaClient, userId: string) { const gymIds = await memberGymIds(prisma, userId); const [notifications, announcements] = await Promise.all([ prisma.notification.count({ where: { userId, readAt: null } }), prisma.announcement.count({ where: { AND: [ { OR: [{ gymId: { in: gymIds } }, { gymId: null }] }, { reads: { none: { userId } } }, ], }, }), ]); return { unreadCount: notifications + announcements }; } /** Zaznacza powiadomienie jako przeczytane (właściciel). */ export async function markNotificationRead(prisma: PrismaClient, userId: string, id: string) { const result = await prisma.notification.updateMany({ where: { id, userId, readAt: null }, data: { readAt: new Date() }, }); if (result.count === 0) { const existing = await prisma.notification.findFirst({ where: { id, userId } }); if (!existing) throw notFound('Notification not found'); } return { ok: true }; } /** Zaznacza ogłoszenie jako przeczytane (tylko globalne albo z siłowni usera). */ export async function markAnnouncementRead(prisma: PrismaClient, userId: string, id: string) { const announcement = await prisma.announcement.findUnique({ where: { id } }); if (!announcement) throw notFound('Announcement not found'); if (announcement.gymId !== null) { const membership = await prisma.gymMembership.findFirst({ where: { userId, gymId: announcement.gymId }, select: { id: true }, }); if (!membership) throw notFound('Announcement not found'); } await prisma.announcementRead.upsert({ where: { announcementId_userId: { announcementId: id, userId } }, update: {}, create: { announcementId: id, userId }, }); return { ok: true }; } /** Oznacza wszystkie widoczne wpisy jako przeczytane (oba źródła naraz). */ export async function markFeedAllRead(prisma: PrismaClient, userId: string) { const gymIds = await memberGymIds(prisma, userId); const [_updated, announcements] = await Promise.all([ prisma.notification.updateMany({ where: { userId, readAt: null }, data: { readAt: new Date() }, }), prisma.announcement.findMany({ where: { AND: [ { OR: [{ gymId: { in: gymIds } }, { gymId: null }] }, { reads: { none: { userId } } }, ], }, select: { id: true }, }), ]); if (announcements.length > 0) { await prisma.announcementRead.createMany({ data: announcements.map((a) => ({ announcementId: a.id, userId })), skipDuplicates: true, }); } return { ok: true }; }