import type { Prisma } from '@generated/prisma/client'; import type { GroupList, GroupQuery, ProblemDetails, Result, } from '@gruperly/shared'; import { ok } from '@gruperly/shared'; import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; import prisma from '@/lib/prisma'; import { DEFAULT_TIME_ZONE, nextClassOccurrence } from '@/modules/home/lib/scheduler'; import { buildGroupWhereForUser, type GroupDb, type GroupListRecord, toGroupListItemDto, } from '../../lib'; type ListGroupsDeps = { db?: Pick; now?: Date; }; const LIST_COUNT_INCLUDE = { _count: { select: { // Group members. No status filter, same as the detail page counts. attendees: true, // Waitlist: the ones still waiting for a spot (the reviewed ones drop out). waitlist: { where: { status: 'PENDING' as const } }, // Payments still to collect: the ones pending and the overdue ones. payments: { where: { status: { in: ['PENDING' as const, 'OVERDUE' as const] } } }, }, }, } satisfies Prisma.GroupInclude; export class ListGroups { constructor(private readonly deps: ListGroupsDeps = {}) {} async execute( query: GroupQuery, userId: string, ): Promise> { const db = this.deps.db ?? prisma; const now = this.deps.now ?? new Date(); const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput; // We fetch the user's groups with their counters and sort them here: the next // class is derived from days + time, there is no column to sort on in the // database. It's the same engine the home summary uses, with the person's // time zone (or the server's if it doesn't come along). const records: GroupListRecord[] = await db.group.findMany({ where, include: LIST_COUNT_INCLUDE, }); const timeZone = query.timeZone ?? DEFAULT_TIME_ZONE; const withNextClass = records.map((record) => ({ record, nextAt: nextOccurrenceAt(record, now, timeZone), })); /* A group with no schedule has no class to compare, so it goes last; between groups with the same class (or with no schedule) the newest one breaks the tie, which was the listing's previous criterion. */ const ordered = withNextClass.sort((a, b) => { if (a.nextAt !== null && b.nextAt !== null) { return a.nextAt - b.nextAt || b.record.createdAt.getTime() - a.record.createdAt.getTime(); } if (a.nextAt !== null) { return -1; } if (b.nextAt !== null) { return 1; } return b.record.createdAt.getTime() - a.record.createdAt.getTime(); }); const offset = getPaginationOffset(query); const page = ordered.slice(offset, offset + query.pageSize); return ok({ data: page.map(({ record }) => toGroupListItemDto(record)), pagination: getPaginationMetadata(query, ordered.length), }); } } function nextOccurrenceAt(record: GroupListRecord, now: Date, timeZone: string): number | null { if (!record.days?.length || !record.time) { return null; } const occurrence = nextClassOccurrence({ days: record.days, time: record.time, now, timeZone, }); return occurrence ? occurrence.occurrenceAt.getTime() : null; }