Files
gruperly/apps/backend/src/modules/attention/features/get-overview/use-case.ts
Jose Selesan d21e1c3730 feat: un miembro puede pertenecer a más de un grupo
- Nuevo modelo `Person` (`people`): contacto y notas por profe, con
  teléfono único (índice parcial `people_owner_phone_key`). `Attendee`
  pasa a ser la membresía (`group_id` + `person_id`, único por grupo).
- La cuenta de la app de alumnos se vincula a la persona
  (`student_account_people`): una sola cuenta ve todos sus grupos.
- Migración unifica attendees del mismo profe y teléfono, y fusiona sus
  cuentas de alumno (conserva la usada más recientemente).
- `POST /groups/:gid/attendees/:aid/add-to-group` y
  `GET /people/lookup` para detectar personas existentes al cargar;
  el alta responde `409 person_exists` y acepta `personId`. Bulk, lista
  de espera y preinscripciones vinculan solas.
- El límite del plan cuenta personas con al menos un grupo activo.
- Web: "Agregar a otro grupo", sección "También está en" en la ficha y
  aviso "Ya tenés a esta persona" en el alta individual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 09:46:37 -03:00

189 lines
6.9 KiB
TypeScript

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 { flattenPerson } from '@/modules/attendees/lib/helpers';
import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { contactPhone } from '@/modules/people/lib/people';
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,
createdAt: true,
person: { select: { fullName: true, phone: true, guardianPhone: true } },
},
orderBy: { createdAt: 'asc' },
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
// 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' },
// A fee the student reported (with a receipt) is out of the alert while
// the teacher reviews it; a rejection brings it back.
reportedItems: { none: { reportedPayment: { status: 'REPORTED' } } },
},
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 = contactPhone(attendee);
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;
}