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:
@@ -16,6 +16,7 @@ import {
|
||||
studentStatusRoutes,
|
||||
} from './modules/analytics';
|
||||
import { attendeesRoutes } from './modules/attendees';
|
||||
import { attentionRoutes } from './modules/attention';
|
||||
import { authRoutes } from './modules/auth';
|
||||
import { billingRoutes, planReadOnlyMiddleware } from './modules/billing';
|
||||
import { classesRoutes } from './modules/classes';
|
||||
@@ -65,6 +66,7 @@ api.route('/waitlist', waitlistRoutes);
|
||||
api.route('/classes', classesRoutes);
|
||||
api.route('/students', studentStatusRoutes);
|
||||
api.route('/groups-risk', groupsRiskOverviewRoute);
|
||||
api.route('/attention', attentionRoutes);
|
||||
|
||||
app.notFound((c) => {
|
||||
return problemJson(c, notFoundProblem(c.req.path));
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { AttendanceRiskLevel, AttendanceStatus, MemberAttendance, MemberCla
|
||||
/* How many classes we look back per attendee. That is the real ceiling of the
|
||||
model: `class_sessions` are not created on their own, they get materialized
|
||||
when someone opens "today's classes", so pulling years of rows makes no
|
||||
sense. 20 classes is enough for the streak, for the 4+4 trend window and for
|
||||
sense. 20 classes is enough for the streak, for the 6-class window and for
|
||||
the attendance rate the card shows. */
|
||||
export const MEMBER_HISTORY_LIMIT = 20;
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { GetAttentionOverview } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
|
||||
const useCase = new GetAttentionOverview();
|
||||
const result = await useCase.execute(user.id);
|
||||
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -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;
|
||||
}
|
||||
23
apps/backend/src/modules/attention/features/resolve/route.ts
Normal file
23
apps/backend/src/modules/attention/features/resolve/route.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import type { ResolveAlert } from '@gruperly/shared';
|
||||
import { ResolveAlertSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { ResolveStudentAlert } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:attendeeId/resolve', validate.json(ResolveAlertSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
|
||||
const payload = c.req.valid('json') as ResolveAlert;
|
||||
const useCase = new ResolveStudentAlert();
|
||||
const result = await useCase.execute(c.req.param('attendeeId'), user.id, payload);
|
||||
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { Prisma } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, ResolveAlert, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import { ALERT_TYPE_TO_KIND } from '../../lib/alert-kind';
|
||||
|
||||
type ResolveAlertDeps = {
|
||||
db?: {
|
||||
attendee: Prisma.AttendeeDelegate;
|
||||
attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate;
|
||||
};
|
||||
};
|
||||
|
||||
export type ResolveAlertResult = ResolveAlert & { attendeeId: string };
|
||||
|
||||
/* "Resuelto": stores the signature of the alert the professor saw. One row per
|
||||
attendee and type, overwritten on each resolve, so the table never grows past
|
||||
two rows per attendee. An attendee outside the user's groups is a 404, not a
|
||||
403: we don't confirm that the id exists. */
|
||||
export class ResolveStudentAlert {
|
||||
constructor(private readonly deps: ResolveAlertDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
attendeeId: string,
|
||||
userId: string,
|
||||
payload: ResolveAlert,
|
||||
): Promise<Result<ResolveAlertResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, group: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
const kind = ALERT_TYPE_TO_KIND[payload.tipo];
|
||||
await db.attendeeAlertResolution.upsert({
|
||||
where: { attendeeId_kind: { attendeeId, kind } },
|
||||
create: { attendeeId, kind, signature: payload.firma, resolvedById: userId },
|
||||
update: { signature: payload.firma, resolvedById: userId, resolvedAt: new Date() },
|
||||
});
|
||||
|
||||
return ok({ attendeeId, tipo: payload.tipo, firma: payload.firma });
|
||||
}
|
||||
}
|
||||
1
apps/backend/src/modules/attention/index.ts
Normal file
1
apps/backend/src/modules/attention/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as attentionRoutes } from './routes';
|
||||
13
apps/backend/src/modules/attention/lib/alert-kind.ts
Normal file
13
apps/backend/src/modules/attention/lib/alert-kind.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import type { StudentAlertKind } from '@generated/prisma/client';
|
||||
import type { StudentAlertType } from '@gruperly/shared';
|
||||
|
||||
/** The API speaks Spanish (`asistencia` / `pago`), the table speaks enums. */
|
||||
export const ALERT_KIND_TO_TYPE: Record<StudentAlertKind, StudentAlertType> = {
|
||||
ATTENDANCE: 'asistencia',
|
||||
PAYMENT: 'pago',
|
||||
};
|
||||
|
||||
export const ALERT_TYPE_TO_KIND: Record<StudentAlertType, StudentAlertKind> = {
|
||||
asistencia: 'ATTENDANCE',
|
||||
pago: 'PAYMENT',
|
||||
};
|
||||
10
apps/backend/src/modules/attention/routes.ts
Normal file
10
apps/backend/src/modules/attention/routes.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { Hono } from 'hono';
|
||||
import getOverviewRoute from './features/get-overview/route';
|
||||
import resolveRoute from './features/resolve/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', getOverviewRoute);
|
||||
routes.route('/', resolveRoute);
|
||||
|
||||
export default routes;
|
||||
Reference in New Issue
Block a user