feat: rediseño de Grupos y pantalla "Requiere atención"
- Grupos: subtítulo con resumen (grupos · alumnos · lugares libres), sección "Requiere atención" con los 4 alumnos más urgentes y tarjetas con avatares (punteados por lugar libre en grupos chicos, superpuestos con "+N" en grandes; con alerta primero y anillo de gravedad). - Pantalla nueva /groups/attention: filtros Todos/Asistencia/Pagos, secciones Urgente y A vigilar, Contactar / Enviar recordatorio por wa.me y "Resuelto" persistente con update optimista. - FAB "Nuevo grupo" que se pliega al scrollear (respeta reduced motion); los toasts en mobile suben para no quedar debajo. - Alertas centralizadas en computeStudentAlerts (shared). La regla de asistencia pasa a: urgente = 3 seguidas o 4 de las últimas 6; a vigilar = 2 de las últimas 4 (sin inactividad por días ni tendencia). Cuotas: 1 vencida vigilar, 2+ urgente. - Backend: GET /attention y POST /attention/:attendeeId/resolve; tabla attendee_alert_resolutions (la alerta vuelve si cambia la firma). - Tokens de gravedad para claro y oscuro; se quita el indicador de pills. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,174 @@
|
||||
import type { Prisma } from '@generated/prisma/client';
|
||||
import type {
|
||||
AttendanceStatus,
|
||||
AttentionGroup,
|
||||
AttentionMember,
|
||||
AttentionOverview,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
StudentAlertType,
|
||||
} from '@gruperly/shared';
|
||||
import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
|
||||
|
||||
type GetAttentionOverviewDeps = {
|
||||
db?: {
|
||||
group: Prisma.GroupDelegate;
|
||||
attendee: Prisma.AttendeeDelegate;
|
||||
classSession: Prisma.ClassSessionDelegate;
|
||||
attendance: Prisma.AttendanceDelegate;
|
||||
payment: Prisma.PaymentDelegate;
|
||||
attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate;
|
||||
user: Prisma.UserDelegate;
|
||||
};
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
type GroupRow = { id: string; name: string; capacity: number | null };
|
||||
type AttendeeRow = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
fullName: string;
|
||||
phone: string | null;
|
||||
guardianPhone: string | null;
|
||||
createdAt: Date;
|
||||
};
|
||||
type SessionRow = { id: string; groupId: string; startsAt: Date };
|
||||
type AttendanceRow = {
|
||||
attendeeId: string;
|
||||
classSessionId: string;
|
||||
status: AttendanceStatus;
|
||||
classSession: { startsAt: Date };
|
||||
};
|
||||
type PaymentRow = {
|
||||
id: string;
|
||||
attendeeId: string;
|
||||
amount: Prisma.Decimal;
|
||||
currency: string;
|
||||
dueDate: Date;
|
||||
checkoutUrl: string | null;
|
||||
};
|
||||
type ResolutionRow = { attendeeId: string; kind: keyof typeof ALERT_KIND_TO_TYPE; signature: string };
|
||||
|
||||
/* Every ACTIVE member of the user's groups with their alerts ("Requiere
|
||||
atención"). The list screen draws all the avatars from here, so it returns
|
||||
members without alerts too. The rule is `computeStudentAlerts` (shared) over
|
||||
the same attendance input the risk overview builds (`toMemberAttendance`). */
|
||||
export class GetAttentionOverview {
|
||||
constructor(private readonly deps: GetAttentionOverviewDeps = {}) {}
|
||||
|
||||
async execute(userId: string): Promise<Result<AttentionOverview, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
|
||||
const groups = (await db.group.findMany({
|
||||
where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
|
||||
select: { id: true, name: true, capacity: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
})) as GroupRow[];
|
||||
|
||||
if (groups.length === 0) {
|
||||
return ok({ groups: [] });
|
||||
}
|
||||
|
||||
const groupIds = groups.map((group) => group.id);
|
||||
|
||||
const [owner, attendees, sessions, attendances, payments, resolutions] = await Promise.all([
|
||||
// Phones are stored the way people write them (`11 2345-6789`): the
|
||||
// professor's country settles the calling code, as in the WhatsApp jobs.
|
||||
db.user.findUnique({ where: { id: userId }, select: { country: true } }),
|
||||
db.attendee.findMany({
|
||||
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
|
||||
select: { id: true, groupId: true, fullName: true, phone: true, guardianPhone: true, createdAt: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}) as Promise<AttendeeRow[]>,
|
||||
// Past classes only, most recent first: `toMemberAttendance` keeps the
|
||||
// last 20 per attendee, more than the 6-class window needs.
|
||||
db.classSession.findMany({
|
||||
where: { groupId: { in: groupIds }, startsAt: { lte: now } },
|
||||
select: { id: true, groupId: true, startsAt: true },
|
||||
orderBy: { startsAt: 'desc' },
|
||||
}) as Promise<SessionRow[]>,
|
||||
db.attendance.findMany({
|
||||
where: { attendee: { groupId: { in: groupIds }, status: 'ACTIVE' } },
|
||||
select: {
|
||||
attendeeId: true,
|
||||
classSessionId: true,
|
||||
status: true,
|
||||
classSession: { select: { startsAt: true } },
|
||||
},
|
||||
}) as Promise<AttendanceRow[]>,
|
||||
db.payment.findMany({
|
||||
where: { groupId: { in: groupIds }, status: 'OVERDUE', attendee: { status: 'ACTIVE' } },
|
||||
select: { id: true, attendeeId: true, amount: true, currency: true, dueDate: true, checkoutUrl: true },
|
||||
orderBy: { dueDate: 'asc' },
|
||||
}) as Promise<PaymentRow[]>,
|
||||
db.attendeeAlertResolution.findMany({
|
||||
where: { attendee: { groupId: { in: groupIds } } },
|
||||
select: { attendeeId: true, kind: true, signature: true },
|
||||
}) as Promise<ResolutionRow[]>,
|
||||
]);
|
||||
|
||||
const country = countryCodeSchema.safeParse(owner?.country);
|
||||
const sessionsByGroup = groupBy(sessions, (session) => session.groupId);
|
||||
const attendanceByAttendee = groupBy(attendances, (row) => row.attendeeId);
|
||||
const paymentsByAttendee = groupBy(payments, (row) => row.attendeeId);
|
||||
const resolutionsByAttendee = groupBy(resolutions, (row) => row.attendeeId);
|
||||
const attendeesByGroup = groupBy(attendees, (attendee) => attendee.groupId);
|
||||
|
||||
const items: AttentionGroup[] = groups.map((group) => ({
|
||||
groupId: group.id,
|
||||
groupName: group.name,
|
||||
capacity: group.capacity,
|
||||
members: (attendeesByGroup.get(group.id) ?? []).map((attendee): AttentionMember => {
|
||||
const overduePayments = (paymentsByAttendee.get(attendee.id) ?? []).map((payment) => ({
|
||||
id: payment.id,
|
||||
amount: Number(payment.amount),
|
||||
currency: payment.currency,
|
||||
dueDate: payment.dueDate.toISOString(),
|
||||
checkoutUrl: payment.checkoutUrl,
|
||||
}));
|
||||
const alerts = computeStudentAlerts(
|
||||
{
|
||||
attendance: toMemberAttendance(
|
||||
attendee,
|
||||
sessionsByGroup.get(group.id) ?? [],
|
||||
attendanceByAttendee.get(attendee.id) ?? [],
|
||||
),
|
||||
overduePayments,
|
||||
},
|
||||
now,
|
||||
);
|
||||
const resolved = (resolutionsByAttendee.get(attendee.id) ?? []).map((row) => ({
|
||||
tipo: ALERT_KIND_TO_TYPE[row.kind] as StudentAlertType,
|
||||
firma: row.signature,
|
||||
}));
|
||||
|
||||
const phone = attendee.phone ?? attendee.guardianPhone;
|
||||
return {
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
phone,
|
||||
whatsappPhone: phone ? toWhatsappE164(phone, country.success ? country.data : null) : null,
|
||||
alerts: applyResolutions(alerts, resolved),
|
||||
overduePayments,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
return ok({ groups: items });
|
||||
}
|
||||
}
|
||||
|
||||
function groupBy<T>(rows: T[], key: (row: T) => string): Map<string, T[]> {
|
||||
const map = new Map<string, T[]>();
|
||||
for (const row of rows) {
|
||||
const list = map.get(key(row)) ?? [];
|
||||
list.push(row);
|
||||
map.set(key(row), list);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
Reference in New Issue
Block a user