feat: add absence notification and analytics features
- Implemented AbsenceNotifyView for notifying absence with session details. - Created AnalyticsView for displaying group analytics and managing students at risk. - Added ClassAttendanceView for marking attendance in classes. - Defined new schemas for analytics and attendance in shared package.
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
import type { MarkAttendance } from '@gruperly/shared';
|
||||
import { MarkAttendanceSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { MarkSessionAttendance } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:sessionId/attendance', validate.json(MarkAttendanceSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
|
||||
const sessionId = c.req.param('sessionId');
|
||||
const payload = c.req.valid('json') as MarkAttendance;
|
||||
const useCase = new MarkSessionAttendance();
|
||||
const result = await useCase.execute(sessionId, payload, user.id);
|
||||
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,105 @@
|
||||
import { AttendanceStatus } from '@generated/prisma/client';
|
||||
import type {
|
||||
MarkAttendance,
|
||||
MarkAttendanceResult,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { validationProblem } from '@/http/problem-builders';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import { type ClassesDb, ensureSessionAccess, sessionNotFound } from '../../lib';
|
||||
|
||||
type MarkSessionAttendanceDeps = {
|
||||
db?: Pick<ClassesDb, 'classSession' | 'attendee'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
};
|
||||
|
||||
export class MarkSessionAttendance {
|
||||
constructor(private readonly deps: MarkSessionAttendanceDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
sessionId: string,
|
||||
payload: MarkAttendance,
|
||||
userId: string,
|
||||
): Promise<Result<MarkAttendanceResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
|
||||
if (payload.classSessionId !== sessionId) {
|
||||
return err(
|
||||
validationProblem({
|
||||
detail: 'El identificador de la clase no coincide con la ruta.',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const session = await db.classSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
include: {
|
||||
group: { include: { members: { where: { userId } } } },
|
||||
},
|
||||
});
|
||||
if (!session) {
|
||||
return err(sessionNotFound(sessionId));
|
||||
}
|
||||
|
||||
const access = ensureSessionAccess(session, userId);
|
||||
if (!access.ok) {
|
||||
return access;
|
||||
}
|
||||
|
||||
const uniqueRecords = [
|
||||
...new Map(payload.records.map((record) => [record.attendeeId, record])).values(),
|
||||
];
|
||||
|
||||
const attendees = await db.attendee.findMany({
|
||||
where: {
|
||||
groupId: session.groupId,
|
||||
id: { in: uniqueRecords.map((record) => record.attendeeId) },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
const attendeeIds = new Set(attendees.map((attendee) => attendee.id));
|
||||
const invalidRecord = uniqueRecords.find((record) => !attendeeIds.has(record.attendeeId));
|
||||
if (invalidRecord) {
|
||||
return err(
|
||||
validationProblem({
|
||||
detail: 'Uno o más alumnos no pertenecen al grupo de esta clase.',
|
||||
errors: { attendeeId: [invalidRecord.attendeeId] },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const markedAt = new Date();
|
||||
return unitOfWork.executeResult(async (tx) => {
|
||||
for (const record of uniqueRecords) {
|
||||
await tx.attendance.upsert({
|
||||
where: {
|
||||
attendeeId_classSessionId: {
|
||||
attendeeId: record.attendeeId,
|
||||
classSessionId: sessionId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
attendeeId: record.attendeeId,
|
||||
classSessionId: sessionId,
|
||||
status:
|
||||
record.status === 'PRESENT'
|
||||
? AttendanceStatus.PRESENT
|
||||
: AttendanceStatus.ABSENT,
|
||||
markedAt,
|
||||
},
|
||||
update: {
|
||||
status:
|
||||
record.status === 'PRESENT'
|
||||
? AttendanceStatus.PRESENT
|
||||
: AttendanceStatus.ABSENT,
|
||||
markedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
return ok({ classSessionId: sessionId, marked: uniqueRecords.length });
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { NotifyAbsence } from '@gruperly/shared';
|
||||
import { NotifyAbsenceSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { NotifySessionAbsence } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:sessionId/notify-absence', validate.json(NotifyAbsenceSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
|
||||
const sessionId = c.req.param('sessionId');
|
||||
const payload = c.req.valid('json') as NotifyAbsence;
|
||||
const useCase = new NotifySessionAbsence();
|
||||
const result = await useCase.execute(sessionId, payload, user.id);
|
||||
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,71 @@
|
||||
import type {
|
||||
NotifyAbsence,
|
||||
NotifyAbsenceResult,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err } from '@gruperly/shared';
|
||||
import { validationProblem } from '@/http/problem-builders';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import {
|
||||
absenceReleaseHours,
|
||||
type ClassesDb,
|
||||
ensureSessionAccess,
|
||||
registerAbsence,
|
||||
sessionNotFound,
|
||||
} from '../../lib';
|
||||
|
||||
type NotifySessionAbsenceDeps = {
|
||||
db?: Pick<ClassesDb, 'classSession' | 'attendee'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
now?: Date;
|
||||
releaseHours?: number;
|
||||
};
|
||||
|
||||
export class NotifySessionAbsence {
|
||||
constructor(private readonly deps: NotifySessionAbsenceDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
sessionId: string,
|
||||
payload: NotifyAbsence,
|
||||
userId: string,
|
||||
): Promise<Result<NotifyAbsenceResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
const now = this.deps.now ?? new Date();
|
||||
const releaseHours = this.deps.releaseHours ?? absenceReleaseHours();
|
||||
|
||||
if (payload.classSessionId !== sessionId) {
|
||||
return err(
|
||||
validationProblem({
|
||||
detail: 'El identificador de la clase no coincide con la ruta.',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const session = await db.classSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
include: {
|
||||
group: { include: { members: { where: { userId } } } },
|
||||
},
|
||||
});
|
||||
if (!session) {
|
||||
return err(sessionNotFound(sessionId));
|
||||
}
|
||||
|
||||
const access = ensureSessionAccess(session, userId);
|
||||
if (!access.ok) {
|
||||
return access;
|
||||
}
|
||||
|
||||
return registerAbsence(
|
||||
{ db, unitOfWork },
|
||||
{
|
||||
attendeeId: payload.attendeeId,
|
||||
classSessionId: sessionId,
|
||||
now,
|
||||
releaseHours,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { AbsenceQuery } from '@gruperly/shared';
|
||||
import { AbsenceQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { resultJson } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { GetAbsenceDetails } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
// Ruta pública (whitelistada en session-auth): el alumno entra con su token personal.
|
||||
route.get('/absence', validate.query(AbsenceQuerySchema), async (c) => {
|
||||
const query = c.req.valid('query') as AbsenceQuery;
|
||||
const useCase = new GetAbsenceDetails();
|
||||
const result = await useCase.execute(query);
|
||||
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { AbsenceDetails, AbsenceQuery, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { DEFAULT_TIME_ZONE } from '@/modules/home/lib/scheduler';
|
||||
import {
|
||||
buildTodayCandidates,
|
||||
type ClassesDb,
|
||||
ensureTodaySessions,
|
||||
} from '../../lib';
|
||||
|
||||
type GetAbsenceDetailsDeps = {
|
||||
db?: Pick<
|
||||
ClassesDb,
|
||||
'attendee' | 'group' | 'classSession' | 'attendance' | 'slotRelease'
|
||||
>;
|
||||
now?: Date;
|
||||
timeZone?: string;
|
||||
};
|
||||
|
||||
export class GetAbsenceDetails {
|
||||
constructor(private readonly deps: GetAbsenceDetailsDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
query: AbsenceQuery,
|
||||
): Promise<Result<AbsenceDetails, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
const timeZone = this.deps.timeZone ?? DEFAULT_TIME_ZONE;
|
||||
|
||||
const attendee = await db.attendee.findUnique({
|
||||
where: { notifyToken: query.token },
|
||||
include: {
|
||||
group: { select: { id: true, name: true, days: true, time: true } },
|
||||
},
|
||||
});
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', 'notify token'));
|
||||
}
|
||||
|
||||
const candidates = buildTodayCandidates(
|
||||
[{ id: attendee.group.id, days: attendee.group.days, time: attendee.group.time }],
|
||||
now,
|
||||
timeZone,
|
||||
);
|
||||
if (candidates.length === 0) {
|
||||
return ok({
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
groupName: attendee.group.name,
|
||||
sessions: [],
|
||||
});
|
||||
}
|
||||
|
||||
const sessionIds = await ensureTodaySessions(db, candidates);
|
||||
const [sessions, attendances, releases] = await Promise.all([
|
||||
db.classSession.findMany({
|
||||
where: { id: { in: sessionIds } },
|
||||
orderBy: { startsAt: 'asc' },
|
||||
}),
|
||||
db.attendance.findMany({
|
||||
where: { classSessionId: { in: sessionIds }, attendeeId: attendee.id },
|
||||
select: { classSessionId: true, status: true },
|
||||
}),
|
||||
db.slotRelease.findMany({
|
||||
where: { classSessionId: { in: sessionIds }, attendeeId: attendee.id },
|
||||
select: { classSessionId: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const attendanceBySession = new Map(
|
||||
attendances.map((attendance) => [attendance.classSessionId, attendance.status]),
|
||||
);
|
||||
const releasedSessionIds = new Set(releases.map((release) => release.classSessionId));
|
||||
|
||||
return ok({
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
groupName: attendee.group.name,
|
||||
sessions: sessions.map((session) => {
|
||||
const attendanceStatus = attendanceBySession.get(session.id) ?? null;
|
||||
return {
|
||||
sessionId: session.id,
|
||||
groupName: attendee.group.name,
|
||||
startsAt: session.startsAt.toISOString(),
|
||||
notified:
|
||||
attendanceStatus === 'EXCUSED' || releasedSessionIds.has(session.id),
|
||||
attendanceStatus,
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { PublicNotifyAbsence } from '@gruperly/shared';
|
||||
import { PublicNotifyAbsenceSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { resultJson } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { PublicNotifyAbsenceUseCase } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
// Ruta pública (whitelistada en session-auth): el alumno avisa su ausencia con token.
|
||||
route.post('/notify-absence', validate.json(PublicNotifyAbsenceSchema), async (c) => {
|
||||
const payload = c.req.valid('json') as PublicNotifyAbsence;
|
||||
const useCase = new PublicNotifyAbsenceUseCase();
|
||||
const result = await useCase.execute(payload);
|
||||
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,48 @@
|
||||
import type {
|
||||
NotifyAbsenceResult,
|
||||
ProblemDetails,
|
||||
PublicNotifyAbsence,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import { absenceReleaseHours, type ClassesDb, registerAbsence } from '../../lib';
|
||||
|
||||
type PublicNotifyAbsenceDeps = {
|
||||
db?: Pick<ClassesDb, 'attendee' | 'classSession'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
now?: Date;
|
||||
releaseHours?: number;
|
||||
};
|
||||
|
||||
export class PublicNotifyAbsenceUseCase {
|
||||
constructor(private readonly deps: PublicNotifyAbsenceDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
payload: PublicNotifyAbsence,
|
||||
): Promise<Result<NotifyAbsenceResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
const now = this.deps.now ?? new Date();
|
||||
const releaseHours = this.deps.releaseHours ?? absenceReleaseHours();
|
||||
|
||||
const attendee = await db.attendee.findUnique({
|
||||
where: { notifyToken: payload.token },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', 'notify token'));
|
||||
}
|
||||
|
||||
return registerAbsence(
|
||||
{ db, unitOfWork },
|
||||
{
|
||||
attendeeId: attendee.id,
|
||||
classSessionId: payload.classSessionId,
|
||||
now,
|
||||
releaseHours,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { TodayClassesQuery } from '@gruperly/shared';
|
||||
import { TodayClassesQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { GetSessionStudents } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/:sessionId/students', validate.query(TodayClassesQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
|
||||
const sessionId = c.req.param('sessionId');
|
||||
const query = c.req.valid('query') as TodayClassesQuery;
|
||||
const useCase = new GetSessionStudents();
|
||||
const result = await useCase.execute(sessionId, user.id, query);
|
||||
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
ProblemDetails,
|
||||
Result,
|
||||
SessionStudents,
|
||||
TodayClassesQuery,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { DEFAULT_TIME_ZONE, startOfDayInTimeZone } from '@/modules/home/lib/scheduler';
|
||||
import {
|
||||
type ClassesDb,
|
||||
ensureSessionAccess,
|
||||
resolvePaymentStatus,
|
||||
sessionNotFound,
|
||||
} from '../../lib';
|
||||
|
||||
type GetSessionStudentsDeps = {
|
||||
db?: Pick<
|
||||
ClassesDb,
|
||||
'classSession' | 'attendee' | 'payment' | 'attendance' | 'slotRelease'
|
||||
> &
|
||||
Pick<PrismaClient, 'group'>;
|
||||
now?: Date;
|
||||
timeZone?: string;
|
||||
};
|
||||
|
||||
export class GetSessionStudents {
|
||||
constructor(private readonly deps: GetSessionStudentsDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
sessionId: string,
|
||||
userId: string,
|
||||
query: TodayClassesQuery = {},
|
||||
): Promise<Result<SessionStudents, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
const timeZone = this.deps.timeZone ?? query.timeZone ?? DEFAULT_TIME_ZONE;
|
||||
|
||||
const session = await db.classSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
include: {
|
||||
group: {
|
||||
include: { members: { where: { userId } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!session) {
|
||||
return err(sessionNotFound(sessionId));
|
||||
}
|
||||
|
||||
const access = ensureSessionAccess(session, userId);
|
||||
if (!access.ok) {
|
||||
return access;
|
||||
}
|
||||
|
||||
const startOfToday = startOfDayInTimeZone(now, timeZone);
|
||||
|
||||
const [attendees, payments, attendances, releases] = await Promise.all([
|
||||
db.attendee.findMany({
|
||||
where: { groupId: session.groupId },
|
||||
orderBy: { fullName: 'asc' },
|
||||
}),
|
||||
db.payment.findMany({
|
||||
where: { groupId: session.groupId },
|
||||
select: { attendeeId: true, status: true, dueDate: true },
|
||||
}),
|
||||
db.attendance.findMany({
|
||||
where: { classSessionId: sessionId },
|
||||
select: { attendeeId: true, status: true },
|
||||
}),
|
||||
db.slotRelease.findMany({
|
||||
where: { classSessionId: sessionId },
|
||||
select: { attendeeId: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const paymentsByAttendee = new Map<string, typeof payments>();
|
||||
for (const payment of payments) {
|
||||
const list = paymentsByAttendee.get(payment.attendeeId) ?? [];
|
||||
list.push(payment);
|
||||
paymentsByAttendee.set(payment.attendeeId, list);
|
||||
}
|
||||
|
||||
const attendanceByAttendee = new Map(
|
||||
attendances.map((attendance) => [attendance.attendeeId, attendance.status]),
|
||||
);
|
||||
const releasedAttendeeIds = new Set(releases.map((release) => release.attendeeId));
|
||||
|
||||
return ok({
|
||||
sessionId: session.id,
|
||||
groupId: session.groupId,
|
||||
groupName: session.group.name,
|
||||
startsAt: session.startsAt.toISOString(),
|
||||
students: attendees.map((attendee) => {
|
||||
const attendanceStatus = attendanceByAttendee.get(attendee.id) ?? null;
|
||||
return {
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
paymentStatus: resolvePaymentStatus(
|
||||
paymentsByAttendee.get(attendee.id) ?? [],
|
||||
startOfToday,
|
||||
),
|
||||
attendanceStatus,
|
||||
notifiedAbsence:
|
||||
attendanceStatus === 'EXCUSED' || releasedAttendeeIds.has(attendee.id),
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
23
apps/backend/src/modules/classes/features/today/route.ts
Normal file
23
apps/backend/src/modules/classes/features/today/route.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import type { TodayClassesQuery } from '@gruperly/shared';
|
||||
import { TodayClassesQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { GetTodayClasses } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/today', validate.query(TodayClassesQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
|
||||
const query = c.req.valid('query') as TodayClassesQuery;
|
||||
const useCase = new GetTodayClasses();
|
||||
const result = await useCase.execute(user.id, query);
|
||||
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
82
apps/backend/src/modules/classes/features/today/use-case.ts
Normal file
82
apps/backend/src/modules/classes/features/today/use-case.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import type { ClassTodayList, ProblemDetails, Result, TodayClassesQuery } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib/helpers';
|
||||
import { DEFAULT_TIME_ZONE } from '@/modules/home/lib/scheduler';
|
||||
import {
|
||||
buildTodayCandidates,
|
||||
type ClassesDb,
|
||||
ensureTodaySessions,
|
||||
toClassToday,
|
||||
} from '../../lib';
|
||||
|
||||
type GetTodayClassesDeps = {
|
||||
db?: Pick<ClassesDb, 'group' | 'classSession' | 'attendance'>;
|
||||
now?: Date;
|
||||
timeZone?: string;
|
||||
};
|
||||
|
||||
export class GetTodayClasses {
|
||||
constructor(private readonly deps: GetTodayClassesDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
userId: string,
|
||||
query: TodayClassesQuery = {},
|
||||
): Promise<Result<ClassTodayList, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
const timeZone = this.deps.timeZone ?? query.timeZone ?? DEFAULT_TIME_ZONE;
|
||||
|
||||
const groups = await db.group.findMany({
|
||||
where: buildGroupWhereForUser(userId),
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
days: true,
|
||||
time: true,
|
||||
capacity: true,
|
||||
_count: {
|
||||
select: { attendees: { where: { status: 'ACTIVE' } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const candidates = buildTodayCandidates(groups, now, timeZone);
|
||||
if (candidates.length === 0) {
|
||||
return ok({ data: [] });
|
||||
}
|
||||
|
||||
const sessionIds = await ensureTodaySessions(db, candidates);
|
||||
|
||||
const [sessions, markedAttendances] = await Promise.all([
|
||||
db.classSession.findMany({
|
||||
where: { id: { in: sessionIds } },
|
||||
include: {
|
||||
group: { select: { id: true, name: true, capacity: true } },
|
||||
},
|
||||
orderBy: { startsAt: 'asc' },
|
||||
}),
|
||||
db.attendance.findMany({
|
||||
where: {
|
||||
classSessionId: { in: sessionIds },
|
||||
status: { in: ['PRESENT', 'ABSENT'] },
|
||||
},
|
||||
select: { classSessionId: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const markedSessionIds = new Set(markedAttendances.map((a) => a.classSessionId));
|
||||
const enrolledByGroup = new Map(groups.map((group) => [group.id, group._count.attendees]));
|
||||
|
||||
return ok({
|
||||
data: sessions.map((session) =>
|
||||
toClassToday(
|
||||
session,
|
||||
session.group,
|
||||
enrolledByGroup.get(session.groupId) ?? 0,
|
||||
markedSessionIds.has(session.id),
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user