diff --git a/api/src/services/messages.ts b/api/src/services/messages.ts index 29cf96c..9a0af44 100644 --- a/api/src/services/messages.ts +++ b/api/src/services/messages.ts @@ -28,7 +28,7 @@ async function assertActiveRelation(prisma: PrismaClient, userId: string, coachi /** * All ACTIVE coaching relations of the user (both roles) with the last message * and the unread count (messages from the other side newer than lastReadAt). - * Batched — no N+1. + * Bounded queries (DISTINCT ON + agregacja SQL) — bez wczytywania całej historii. */ export async function listConversations(prisma: PrismaClient, userId: string) { const coachings = await prisma.coaching.findMany({ @@ -38,27 +38,30 @@ export async function listConversations(prisma: PrismaClient, userId: string) { const coachingIds = coachings.map((c) => c.id); const otherIds = [...new Set(coachings.flatMap((c) => [c.trainerId, c.userId]))]; - const [messages, reads, users] = await Promise.all([ - prisma.message.findMany({ where: { coachingId: { in: coachingIds } }, orderBy: { createdAt: 'asc' } }), - prisma.conversationRead.findMany({ where: { userId } }), + const [lastMessages, unreadRows, users] = await Promise.all([ + prisma.$queryRaw<{ coachingId: string; body: string; createdAt: Date; senderId: string }[]>` + SELECT DISTINCT ON ("coachingId") "coachingId", "body", "createdAt", "senderId" + FROM "Message" + WHERE "coachingId" = ANY(${coachingIds}::text[]) + ORDER BY "coachingId", "createdAt" DESC + `, + prisma.$queryRaw<{ coachingId: string; unread: bigint }[]>` + SELECT m."coachingId", COUNT(*)::bigint AS unread + FROM "Message" m + LEFT JOIN "ConversationRead" r ON r."coachingId" = m."coachingId" AND r."userId" = ${userId} + WHERE m."coachingId" = ANY(${coachingIds}::text[]) + AND m."senderId" <> ${userId} + AND (r."lastReadAt" IS NULL OR m."createdAt" > r."lastReadAt") + GROUP BY m."coachingId" + `, prisma.user.findMany({ where: { id: { in: otherIds } }, select: { id: true, firstName: true, lastName: true, nickname: true }, }), ]); - const readByCoaching = new Map(reads.map((r) => [r.coachingId, r.lastReadAt])); - const lastByCoaching = new Map(); - const unreadByCoaching = new Map(); - for (const m of messages) { - lastByCoaching.set(m.coachingId, m); - if (m.senderId !== userId) { - const lastReadAt = readByCoaching.get(m.coachingId); - if (!lastReadAt || m.createdAt > lastReadAt) { - unreadByCoaching.set(m.coachingId, (unreadByCoaching.get(m.coachingId) ?? 0) + 1); - } - } - } + const lastByCoaching = new Map(lastMessages.map((m) => [m.coachingId, m])); + const unreadByCoaching = new Map(unreadRows.map((r) => [r.coachingId, Number(r.unread)])); const userById = new Map(users.map((u) => [u.id, u])); const conversations: ConversationListItem[] = coachings.map((c) => { @@ -69,7 +72,12 @@ export async function listConversations(prisma: PrismaClient, userId: string) { coachingId: c.id, role: c.trainerId === userId ? ('trainer' as const) : ('trainee' as const), other: other - ? { id: other.id, firstName: other.firstName, lastName: other.lastName, nickname: other.nickname } + ? { + id: other.id, + firstName: other.firstName, + lastName: other.lastName, + nickname: other.nickname, + } : { id: otherId, firstName: null, lastName: null, nickname: null }, lastMessage: last ? { body: last.body, createdAt: last.createdAt.toISOString(), senderId: last.senderId } @@ -96,7 +104,12 @@ export interface MessageAttachment { index: number; reps: number | null; rir: number | null; - planned: { reps: number | null; loadKg: number | null; restSec: number | null; rir: number | null } | null; + planned: { + reps: number | null; + loadKg: number | null; + restSec: number | null; + rir: number | null; + } | null; }[]; } | null; /** Only when exercise == null. */ @@ -160,17 +173,20 @@ export async function getConversation(prisma: PrismaClient, userId: string, coac return { role, other: other - ? { id: other.id, firstName: other.firstName, lastName: other.lastName, nickname: other.nickname } + ? { + id: other.id, + firstName: other.firstName, + lastName: other.lastName, + nickname: other.nickname, + } : { id: otherId, firstName: null, lastName: null, nickname: null }, - messages: messages - .reverse() - .map((m) => ({ - id: m.id, - senderId: m.senderId, - body: m.body, - createdAt: m.createdAt.toISOString(), - attachment: buildAttachment(m), - })), + messages: messages.reverse().map((m) => ({ + id: m.id, + senderId: m.senderId, + body: m.body, + createdAt: m.createdAt.toISOString(), + attachment: buildAttachment(m), + })), }; } @@ -186,7 +202,17 @@ function buildAttachment(m: { } | null; sessionExercise: { exercise: { name: string }; - sets: { index: number; reps: number | null; rir: number | null; planSet: { reps: number | null; loadKg: number | null; restSec: number | null; rir: number | null } | null }[]; + sets: { + index: number; + reps: number | null; + rir: number | null; + planSet: { + reps: number | null; + loadKg: number | null; + restSec: number | null; + rir: number | null; + } | null; + }[]; } | null; }): MessageAttachment | null { if (!m.sessionId || !m.session) return null; @@ -245,7 +271,11 @@ export async function sendMessage( where: { id: input.sessionId }, include: { day: { select: { week: { select: { plan: { select: { userId: true } } } } } } }, }); - if (!session || session.status !== 'COMPLETED' || session.day.week.plan.userId !== coaching.userId) { + if ( + !session || + session.status !== 'COMPLETED' || + session.day.week.plan.userId !== coaching.userId + ) { throw badRequest('Attachment must be a completed session of the trainee in this relation'); } sessionId = session.id; @@ -253,7 +283,8 @@ export async function sendMessage( const se = await prisma.sessionExercise.findFirst({ where: { id: input.sessionExerciseId, sessionId: session.id }, }); - if (!se || se.removed) throw badRequest('Attachment exercise does not belong to this session'); + if (!se || se.removed) + throw badRequest('Attachment exercise does not belong to this session'); sessionExerciseId = se.id; } }