Merge pull request 'task/improve-ui' (#8) from task/improve-ui into development

Reviewed-on: #8
This commit is contained in:
2026-10-01 15:36:44 +00:00
63 changed files with 4806 additions and 777 deletions

View File

@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@@ -0,0 +1,71 @@
---
name: frontend-design
description: Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.
license: Complete terms in LICENSE.txt
---
# Frontend Design
Approach this as the design lead at a design studio known for giving every client a distinct visual identity that is not mistaken for anyone else's. This client has already rejected proposals that felt cliché or templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take aesthetic risk if justified.
## Ground your designs in the subject matter
If the brief does not identify what the product or subject matter is, identify it yourself before designing, and confirm with the client. You can come up with one concrete subject, the design's audience, and the design's primary job, as a proposal. If there's any information in your memory about the client's preferences or context about what they're building, use that as a hint. The subject's industry, subject matter, materials, and vernacular are where distinctive visual choices come from — a design for a toy for girls aged 8–11 will be very aesthetically different from a dashboard for financial analysts. Build with the brief's real content and subject matter throughout.
## Design principles
For web designs, the hero is the first thing viewers will see. Open with the most characteristic thing in the subject's world, in the form that is most appropriate: a headline, an image, an animation, a live demo, an interactive moment, or other treatments. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the default treatment, so only use it if that's truly the best option.
Typography carries the personality of the page. You don't need a different typeface for display or headline text and body content: use one family or two, and if two, make them clearly distinct.
Choose your typefaces deliberately, not the default families you would reach for on any other project, and set a clear type scale following the default guidance of The Elements of Typographic Style with intentional weights, widths, and spacing. When type is used as a headline or visual element, use the type treatment itself as an active part of the design, not a neutral delivery vehicle for the content.
Default to line lengths of less than 80 characters. Serif typefaces can have slightly longer line lengths; give serif body text slightly more line-height than a sans-serif.
Avoid these default typographic treatments; they are the commonest tells of a generated page:
- Accenting just a single word or phrase in a headline, like putting one word in italic/bold or a different color.
- Using all caps for labels.
- Adding unnecessary typographic labels above content.
Visual structure is information. Structural devices like outlines, borders, numbering, eyebrows, dividers, labels, etc., encode useful information about the content rather than decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence — like a stepped process or a timeline. Before adding numbered markers, check the content really is a sequence.
Use non-user-triggered motion sparingly and deliberately, only to draw attention. A single orchestrated moment — one page-load sequence or one reveal — lands better than scattered effects; fade-and-slide-up entrances on each section and hover transitions on every card are the generic default and read as AI-generated. Motion that answers a person's action (opening, expanding, confirming) is welcome when it shows what changed.
Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy and placeholder content. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance.
## Process: plan, review against the brief, build, critique
For calibration, AI-generated design right now clusters around some traits:
1. a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta or warm-clay accent (often near #D97757 — Anthropic's own Claude-interaction accent, so on a user's brief it reads as a tell);
2. a near-black background with a single bright acid-green or vermilion accent;
3. a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns;
4. the SaaS-card kit: content chopped into identical rounded cards, one border-radius on everything regardless of hierarchy, the same soft grey shadow (rgba(0,0,0,.1)) under each, and gradient washes as decoration;
5. template chrome that appears whatever the subject: a tracked-out ALL-CAPS eyebrow label above every heading; meta strings joined with middle dots ('A · B · C'); labels built as 'WORD — fragment' with a spaced em dash; tinted near-black (#0B0B0B, #111) standing in for black; a monospace face for small data labels; a '→' appended to link and button text.
All traits are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. As with a hired human designer, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn.
Work in two passes. First, brainstorm a short design plan based on the client's design brief: create a compact token system with color, type, layout, and principles.
- Color: describe the core base palette as 4–6 named hex values.
- Type: the typefaces and their roles.
- Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Include alignment guidance; should the content be left aligned, center aligned, justified?
- Principles: the high-level guidance for what makes this page unique.
Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan.
When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and an element-based selector like .cta). This can happen often with padding/margin between sections.
## Restraint and self-critique
Spend your boldness in one place. Let one element be the memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected, visually accessible, harmonious color palettes. Critique your own work as you build, taking screenshots to review if your environment supports it — a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creatives have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes.
## More on writing in design
Words appear in a design for one reason: to make it easier to understand and use. They are design content, not decoration. Bring the same intentionality and minimalism to copywriting that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience.
Write from the end user's perspective. Name things by what users will understand in simple language, not by how the system is built. A user manages notifications, not webhook config. Describe what something is or does in plain terms rather than selling it. Being specific and legible to new users is always better than being clever.
Use active voice as default. A CTA says exactly what happens when it is used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around.
Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act.
Keep the tone conversational: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each written element do exactly one job.

View File

@@ -4,19 +4,30 @@ import type {
GroupRiskLevel, GroupRiskLevel,
GroupRiskSummary, GroupRiskSummary,
GroupsRiskOverview, GroupsRiskOverview,
MemberClassSession,
ProblemDetails, ProblemDetails,
Result, Result,
UrgentMemberSummary,
} from '@gruperly/shared'; } from '@gruperly/shared';
import { ok } from '@gruperly/shared'; import { getGroupAttendanceSummary, ok, URGENT_MEMBERS_LIMIT } from '@gruperly/shared';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { buildGroupWhereForUser } from '@/modules/groups/lib'; import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { import {
classifyRisk, classifyRisk,
MIN_RISK_ABSENCE_STREAK,
MIN_RISK_MONTHLY_RATE,
monthlyAttendanceRate, monthlyAttendanceRate,
trailingAbsentStreak, trailingAbsentStreak,
} from '../../lib/risk'; } from '../../lib/risk';
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case'; import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
/* Cuántas clases se miran hacia atrás por alumno. Es el techo real del modelo:
los `class_sessions` no se crean solos, se materializan cuando alguien entra
a "clases de hoy", así que no tiene sentido traer años de filas. Con 20
clases alcanza para la racha, para la ventana de tendencia de 4+4 y para el
porcentaje de asistencia que muestra la tarjeta. */
const MEMBER_HISTORY_LIMIT = 20;
type GetGroupsRiskOverviewDeps = { type GetGroupsRiskOverviewDeps = {
db?: { db?: {
group: Prisma.GroupDelegate; group: Prisma.GroupDelegate;
@@ -27,18 +38,26 @@ type GetGroupsRiskOverviewDeps = {
now?: Date; now?: Date;
}; };
type GroupRow = { id: string; name: string }; type GroupRow = {
type AttendeeRow = { id: string; groupId: string }; id: string;
type SessionRow = { id: string; groupId: string }; name: string;
capacity: number | null;
/** Los que todavía esperan cupo (`GroupWaitlistEntry` en PENDING). */
_count: { waitlist: number };
};
type AttendeeRow = { id: string; groupId: string; fullName: string; createdAt: Date };
type SessionRow = { id: string; groupId: string; startsAt: Date };
type AttendanceRow = { type AttendanceRow = {
attendeeId: string; attendeeId: string;
classSessionId: string;
status: AttendanceStatus; status: AttendanceStatus;
classSession: { startsAt: Date }; classSession: { startsAt: Date };
}; };
// Resumen de semáforo de riesgo por grupo para la lista de grupos. // Resumen de semáforo de riesgo por grupo para la lista de grupos.
// Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si // Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si
// alguno en riesgo moderado y NONE en caso contrario. // alguno en riesgo moderado y NONE en caso contrario. Los contadores dicen el
// motivo (faltas seguidas o asistencia baja) para que la lista pueda nombrarlo.
export class GetGroupsRiskOverview { export class GetGroupsRiskOverview {
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {} constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
@@ -49,30 +68,39 @@ export class GetGroupsRiskOverview {
const groups = (await db.group.findMany({ const groups = (await db.group.findMany({
where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput, where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
select: { id: true, name: true }, select: {
})) as GroupRow[]; id: true,
name: true,
capacity: true,
_count: { select: { waitlist: { where: { status: 'PENDING' } } } },
},
})) as unknown as GroupRow[];
if (groups.length === 0) { if (groups.length === 0) {
return ok({ items: [] }); return ok({ items: [] });
} }
const groupIds = groups.map((group) => group.id); const groupIds = groups.map((group) => group.id);
const attendeeGroup = new Map<string, string>();
const sessionCountByGroup = new Map<string, number>();
const [attendees, sessions, attendances] = await Promise.all([ const [attendees, sessions, attendances] = await Promise.all([
db.attendee.findMany({ db.attendee.findMany({
where: { groupId: { in: groupIds }, status: 'ACTIVE' }, where: { groupId: { in: groupIds }, status: 'ACTIVE' },
select: { id: true, groupId: true }, select: { id: true, groupId: true, fullName: true, createdAt: true },
}) as Promise<AttendeeRow[]>, }) as Promise<AttendeeRow[]>,
db.classSession.findMany({ db.classSession.findMany({
where: { groupId: { in: groupIds }, startsAt: { gte: since } }, where: { groupId: { in: groupIds }, startsAt: { gte: since } },
select: { id: true, groupId: true }, select: { id: true, groupId: true, startsAt: true },
orderBy: { startsAt: 'desc' },
}) as Promise<SessionRow[]>, }) as Promise<SessionRow[]>,
/* Sin filtro de fecha, como antes: la racha del semáforo cuenta sobre el
historial completo del alumno, no sobre la ventana mensual. Sin recorte
tampoco: el corte a las últimas 20 clases lo hace `memberSessions`,
sobre las clases del grupo y no sobre estas filas. */
db.attendance.findMany({ db.attendance.findMany({
where: { attendee: { groupId: { in: groupIds } } }, where: { attendee: { groupId: { in: groupIds } } },
select: { select: {
attendeeId: true, attendeeId: true,
classSessionId: true,
status: true, status: true,
classSession: { select: { startsAt: true } }, classSession: { select: { startsAt: true } },
}, },
@@ -80,18 +108,24 @@ export class GetGroupsRiskOverview {
}) as Promise<AttendanceRow[]>, }) as Promise<AttendanceRow[]>,
]); ]);
for (const attendee of attendees) { const sessionsByGroup = new Map<string, SessionRow[]>();
attendeeGroup.set(attendee.id, attendee.groupId);
}
for (const session of sessions) { for (const session of sessions) {
sessionCountByGroup.set(session.groupId, (sessionCountByGroup.get(session.groupId) ?? 0) + 1); const list = sessionsByGroup.get(session.groupId) ?? [];
list.push(session);
sessionsByGroup.set(session.groupId, list);
} }
const streamByAttendee = groupAttendanceByAttendee(attendances); const streamByAttendee = groupAttendanceByAttendee(attendances);
const worstRiskByGroup = new Map<string, GroupRiskLevel>(); const worstRiskByGroup = new Map<string, GroupRiskLevel>();
// Por qué hay riesgo, en la misma pasada: un miembro con racha de faltas
// cuenta en el primero y solo en ese; el segundo agrupa a los que no llegan
// a racha y aun así quedan por debajo del mínimo de asistencia.
const absenceStreakCountByGroup = new Map<string, number>();
const lowAttendanceCountByGroup = new Map<string, number>();
for (const attendee of attendees) { for (const attendee of attendees) {
const groupId = attendeeGroup.get(attendee.id)!; const groupId = attendee.groupId;
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({ const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
status: row.status, status: row.status,
occurredAt: row.classSession.startsAt, occurredAt: row.classSession.startsAt,
@@ -99,13 +133,19 @@ export class GetGroupsRiskOverview {
const streak = trailingAbsentStreak(stream); const streak = trailingAbsentStreak(stream);
const monthlyRate = monthlyAttendanceRate( const monthlyRate = monthlyAttendanceRate(
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()), stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
sessionCountByGroup.get(groupId) ?? 0, sessionsByGroup.get(groupId)?.length ?? 0,
); );
const riskLevel = classifyRisk(streak, monthlyRate); const riskLevel = classifyRisk(streak, monthlyRate);
if (!riskLevel) { if (!riskLevel) {
continue; continue;
} }
if (streak >= MIN_RISK_ABSENCE_STREAK) {
bump(absenceStreakCountByGroup, groupId);
} else if (monthlyRate < MIN_RISK_MONTHLY_RATE) {
bump(lowAttendanceCountByGroup, groupId);
}
const current = worstRiskByGroup.get(groupId) ?? 'NONE'; const current = worstRiskByGroup.get(groupId) ?? 'NONE';
if ( if (
riskLevel === 'HIGH' || riskLevel === 'HIGH' ||
@@ -119,12 +159,94 @@ export class GetGroupsRiskOverview {
groupId: group.id, groupId: group.id,
groupName: group.name, groupName: group.name,
riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE', riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE',
absenceStreakCount: absenceStreakCountByGroup.get(group.id) ?? 0,
lowAttendanceCount: lowAttendanceCountByGroup.get(group.id) ?? 0,
...buildSummaryFields(group, attendees, sessionsByGroup, streamByAttendee, now),
})); }));
return ok({ items }); return ok({ items });
} }
} }
/**
* El resumen por nivel que consumen la tarjeta del listado y la sección de
* seguimiento del Inicio. Sale de `getGroupAttendanceSummary`, la misma función
* de dominio que se prueba en `test/attendance-risk.test.ts`, para que la regla
* no tenga dos copias: una acá y otra en el cliente.
*
* `libres` y `enEspera` salen de acá y no del conteo de `Attendee`: el resumen
* cuenta los miembros del grupo y la tarjeta necesita los lugares del cupo
* para pintar el indicador.
*/
function buildSummaryFields(
group: GroupRow,
attendees: AttendeeRow[],
sessionsByGroup: Map<string, SessionRow[]>,
attendanceByAttendee: Map<string, AttendanceRow[]>,
now: Date,
) {
const resumen = getGroupAttendanceSummary({
groupId: group.id,
capacity: group.capacity,
waitlistCount: group._count.waitlist,
now,
members: attendees
.filter((attendee) => attendee.groupId === group.id)
.map((attendee) => {
const attendeeAttendances = attendanceByAttendee.get(attendee.id) ?? [];
// Si el alumno tiene asistencias previas a su fecha de alta en la BD (ej.
// creado hoy pero con clases pasadas registradas), su fecha efectiva de
// incorporación es la de la primera clase a la que se le tomó asistencia.
const earliestAttendance = attendeeAttendances.reduce<Date | null>(
(earliest, att) =>
!earliest || att.classSession.startsAt < earliest
? att.classSession.startsAt
: earliest,
null,
);
const enrolledAt =
earliestAttendance && earliestAttendance < attendee.createdAt
? earliestAttendance
: attendee.createdAt;
return {
attendeeId: attendee.id,
fullName: attendee.fullName,
enrolledAt: enrolledAt.toISOString(),
sessions: memberSessions(
sessionsByGroup.get(group.id) ?? [],
attendeeAttendances,
),
};
}),
});
const urgentes: UrgentMemberSummary[] = resumen.urgentes
.slice(0, URGENT_MEMBERS_LIMIT)
.map((urgente) => ({
attendeeId: urgente.attendeeId,
fullName: urgente.fullName,
level: urgente.level,
consecutiveAbsences: urgente.consecutiveAbsences,
daysSinceLastAttendance: urgente.daysSinceLastAttendance,
attendanceRate: urgente.attendanceRate,
}));
return {
riesgoAlto: resumen.riesgoAlto,
atencion: resumen.atencion,
ok: resumen.ok,
libres: resumen.libres,
enEspera: resumen.enEspera,
asistencia: resumen.asistencia,
urgentes,
};
}
function bump(counter: Map<string, number>, key: string) {
counter.set(key, (counter.get(key) ?? 0) + 1);
}
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> { function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
const byAttendee = new Map<string, AttendanceRow[]>(); const byAttendee = new Map<string, AttendanceRow[]>();
for (const row of rows) { for (const row of rows) {
@@ -133,4 +255,26 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, Attendanc
byAttendee.set(row.attendeeId, list); byAttendee.set(row.attendeeId, list);
} }
return byAttendee; return byAttendee;
}
/* El universo de clases es el del grupo, no el de las filas de `Attendance`.
La asistencia se carga alumno por alumno y solo cuando alguien la marca, así
que "esta clase pasó y no hay registro de este alumno" es un estado real y
frecuente, no una falta. Si la lista se armara desde las filas de asistencia
esas clases no existirían y la racha no se cortaría: dos faltas separadas por
una clase sin marcar se contarían como tres seguidas.
El dominio ya las trata como neutras (`status: null`), así que acá solo hay
que elegir bien el universo y dejar el criterio en un solo lado.
`sessions` viene de más reciente a más antigua, así que quedarse con las
primeras `MEMBER_HISTORY_LIMIT` es quedarse con las clases recientes. El
recorte va por alumno y no global para que un grupo con mucha historia no le
robe ventana a los grupos que se listan después. */
function memberSessions(sessions: SessionRow[], attendances: AttendanceRow[]): MemberClassSession[] {
const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status]));
return sessions.slice(0, MEMBER_HISTORY_LIMIT).map((session) => ({
sessionId: session.id,
startsAt: session.startsAt.toISOString(),
status: statusBySession.get(session.id) ?? null,
}));
} }

View File

@@ -5,6 +5,12 @@ export type AttendanceStreamEntry = {
export type RiskLevel = 'HIGH' | 'MEDIUM'; export type RiskLevel = 'HIGH' | 'MEDIUM';
/** Racha mínima de faltas sin justificar que ya dispara riesgo. */
export const MIN_RISK_ABSENCE_STREAK = 2;
/** Asistencia mensual (ventana de 30 días) por debajo de la cual hay riesgo. */
export const MIN_RISK_MONTHLY_RATE = 50;
// Cuenta las ausencias consecutivas sin justificar desde la clase más reciente. // Cuenta las ausencias consecutivas sin justificar desde la clase más reciente.
// Recibe la lista ordenada de más reciente a más antigua; PRESENT y EXCUSED rompen la cadena. // Recibe la lista ordenada de más reciente a más antigua; PRESENT y EXCUSED rompen la cadena.
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number { export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
@@ -46,10 +52,10 @@ export function classifyRisk(
consecutiveAbsences: number, consecutiveAbsences: number,
monthlyRate: number, monthlyRate: number,
): RiskLevel | null { ): RiskLevel | null {
if (consecutiveAbsences >= 3) { if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK + 1) {
return 'HIGH'; return 'HIGH';
} }
if (consecutiveAbsences === 2 || monthlyRate < 50) { if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK || monthlyRate < MIN_RISK_MONTHLY_RATE) {
return 'MEDIUM'; return 'MEDIUM';
} }
return null; return null;

View File

@@ -1,10 +1,10 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import type { AttendeeList, AttendeeQuery, ProblemDetails, Result } from '@gruperly/shared'; import type { AttendeeList, AttendeeQuery, ProblemDetails, Result } from '@gruperly/shared';
import { ok } from '@gruperly/shared'; import { ok, RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { type AttendeeRecord, toAttendeeDto } from '../../lib/helpers'; import { toAttendeeListItemDto } from '../../lib/helpers';
type ListAttendeesDeps = { type ListAttendeesDeps = {
db?: Pick<PrismaClient, 'attendee'>; db?: Pick<PrismaClient, 'attendee'>;
@@ -18,18 +18,37 @@ export class ListAttendees {
const where = query.groupId ? { groupId: query.groupId } : undefined; const where = query.groupId ? { groupId: query.groupId } : undefined;
const [records, total] = await Promise.all([ const [records, total] = await Promise.all([
/* El resumen de cada fila viaja en la misma consulta en vez de armarse con
una petición por miembro. Ambas relaciones vienen acotadas a propósito:
la tabla de pagos crece un renglón por mes y para siempre, y el listado
solo necesita el estado actual de cada persona. */
db.attendee.findMany({ db.attendee.findMany({
...(where ? { where } : {}), ...(where ? { where } : {}),
skip: getPaginationOffset(query), skip: getPaginationOffset(query),
take: query.pageSize, take: query.pageSize,
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
include: {
// Por fecha de la clase, no por `markedAt`: marcar la asistencia
// tarde no debe cambiar qué clase cuenta como reciente.
attendances: {
orderBy: { classSession: { startsAt: 'desc' } },
take: RECENT_ATTENDANCE_LIMIT,
select: { status: true },
},
payments: {
where: { status: { not: 'CANCELLED' } },
orderBy: { dueDate: 'desc' },
take: 3,
select: { status: true, dueDate: true },
},
},
}), }),
where ? db.attendee.count({ where }) : db.attendee.count(), where ? db.attendee.count({ where }) : db.attendee.count(),
]); ]);
return ok({ return ok({
data: records.map((r) => toAttendeeDto(r as AttendeeRecord)), data: records.map((record) => toAttendeeListItemDto(record)),
pagination: getPaginationMetadata(query, total), pagination: getPaginationMetadata(query, total),
}); });
} }
} }

View File

@@ -1,4 +1,4 @@
import type { AttendeeDto } from '@gruperly/shared'; import type { AttendeeDto, AttendeeListItem } from '@gruperly/shared';
export type AttendeeRecord = { export type AttendeeRecord = {
id: string; id: string;
@@ -14,6 +14,15 @@ export type AttendeeRecord = {
updatedAt: Date; updatedAt: Date;
}; };
/** Item del listado con el resumen de asistencia y cobro ya resuelto. */
export type AttendeeListItemRecord = AttendeeRecord & {
attendances: { status: AttendeeListItem['recentAttendance'][number] }[];
payments: {
status: NonNullable<AttendeeListItem['payment']>['status'];
dueDate: Date;
}[];
};
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto { export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
return { return {
id: record.id, id: record.id,
@@ -30,6 +39,37 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
}; };
} }
/* El renglón que resume el cobro vigente. Si hay algo impago manda el de
vencimiento más antiguo: quien arrastra un cargo viejo tiene que ver cuántos
días lleva atras, no el vencimiento de un cargo nuevo. Si no queda nada
impago, el último pago cerrado sirve para marcar la fila como al día. */
function pickRelevantPayment(
payments: AttendeeListItemRecord['payments'],
): AttendeeListItem['payment'] {
// CANCELLED no es un cobro. La consulta ya los deja fuera, pero descartarlos
// acá también evita que un cargo anulado gane la fila por ser el más antiguo.
const byDueDate = payments
.filter((payment) => payment.status !== 'CANCELLED')
.sort((a, b) => a.dueDate.getTime() - b.dueDate.getTime());
const outstanding = byDueDate.find((payment) => payment.status !== 'PAID');
const relevant = outstanding ?? byDueDate[byDueDate.length - 1];
if (!relevant) {
return null;
}
return { status: relevant.status, dueDate: relevant.dueDate.toISOString() };
}
/* La consulta viene en orden descendente; la fila los muestra de más antigua a
más reciente para que el punto de la derecha sea el último hecho. */
export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeListItem {
return {
...toAttendeeDto(record),
recentAttendance: [...record.attendances].reverse().map((attendance) => attendance.status),
payment: pickRelevantPayment(record.payments),
};
}
/** /**
* Normaliza números de teléfono eliminando espacios, guiones, paréntesis y puntos. * Normaliza números de teléfono eliminando espacios, guiones, paréntesis y puntos.
* Conserva el '+' si lo tiene al inicio para números internacionales. * Conserva el '+' si lo tiene al inicio para números internacionales.

View File

@@ -8,17 +8,30 @@ import type {
import { ok } from '@gruperly/shared'; import { ok } from '@gruperly/shared';
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { DEFAULT_TIME_ZONE, nextClassOccurrence } from '@/modules/home/lib/scheduler';
import { import {
buildGroupWhereForUser, buildGroupWhereForUser,
type GroupDb, type GroupDb,
type GroupRecord, type GroupListRecord,
toGroupDto, toGroupListItemDto,
} from '../../lib'; } from '../../lib';
type ListGroupsDeps = { type ListGroupsDeps = {
db?: Pick<GroupDb, 'group'>; db?: Pick<GroupDb, 'group'>;
now?: Date;
}; };
const OCCUPANCY_COUNT_INCLUDE = {
_count: {
select: {
// Miembros del grupo. Sin filtro de estado, igual que cuenta el detalle.
attendees: true,
// Lista de espera: los que todavía esperan cupo (los revisados salen).
waitlist: { where: { status: 'PENDING' as const } },
},
},
} satisfies Prisma.GroupInclude;
export class ListGroups { export class ListGroups {
constructor(private readonly deps: ListGroupsDeps = {}) {} constructor(private readonly deps: ListGroupsDeps = {}) {}
@@ -27,21 +40,59 @@ export class ListGroups {
userId: string, userId: string,
): Promise<Result<GroupList, ProblemDetails>> { ): Promise<Result<GroupList, ProblemDetails>> {
const db = this.deps.db ?? prisma; const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput; const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput;
const [records, total] = await Promise.all([ // Traemos los grupos del usuario con sus contadores y los ordenamos acá:
db.group.findMany({ // la próxima clase se deriva de días + hora, no hay columna por la que
where, // ordenar en la base. Es el mismo motor que usa el resumen de home, con la
skip: getPaginationOffset(query), // zona horaria de la persona (o la del servidor si no viaja).
take: query.pageSize, const records: GroupListRecord[] = await db.group.findMany({
orderBy: { createdAt: 'desc' }, where,
}), include: OCCUPANCY_COUNT_INCLUDE,
db.group.count({ where }), });
]);
const timeZone = query.timeZone ?? DEFAULT_TIME_ZONE;
const withNextClass = records.map((record) => ({
record,
nextAt: nextOccurrenceAt(record, now, timeZone),
}));
/* Un grupo sin horario no tiene clase que comparar, así que va al final;
entre grupos con la misma clase (o sin horario) desempata el más nuevo,
que era el criterio anterior de la lista. */
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({ return ok({
data: records.map((record: GroupRecord) => toGroupDto(record)), data: page.map(({ record }) => toGroupListItemDto(record)),
pagination: getPaginationMetadata(query, total), 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;
}

View File

@@ -1,5 +1,5 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import type { BillingType, GroupDto, WeekDay } from '@gruperly/shared'; import type { BillingType, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared';
export type GroupDb = Pick<PrismaClient, 'group' | 'groupMember'>; export type GroupDb = Pick<PrismaClient, 'group' | 'groupMember'>;
@@ -21,6 +21,14 @@ export type GroupRecord = {
inviteToken?: string | null; inviteToken?: string | null;
}; };
/* El listado suma los contadores de ocupación a cada grupo para que la card los
muestre sin pedir un endpoint por grupo. Los trae el `_count` de la misma
consulta: los miembros van todos (igual que cuenta el detalle) y la lista de
espera solo los que siguen esperando cupo (PENDING). */
export type GroupListRecord = GroupRecord & {
_count?: { attendees: number; waitlist: number };
};
export function toGroupDto(record: GroupRecord): GroupDto { export function toGroupDto(record: GroupRecord): GroupDto {
return { return {
id: record.id, id: record.id,
@@ -39,6 +47,14 @@ export function toGroupDto(record: GroupRecord): GroupDto {
}; };
} }
export function toGroupListItemDto(record: GroupListRecord): GroupListItem {
return {
...toGroupDto(record),
attendeesCount: record._count?.attendees ?? 0,
waitlistCount: record._count?.waitlist ?? 0,
};
}
export function buildGroupWhereForUser(userId: string) { export function buildGroupWhereForUser(userId: string) {
return { return {
OR: [ OR: [

View File

@@ -60,39 +60,346 @@ describe('GET /groups-risk/overview', () => {
}); });
it('marca HIGH a un grupo con un alumno con 3 ausencias consecutivas', async () => { it('marca HIGH a un grupo con un alumno con 3 ausencias consecutivas', async () => {
prismaFetchGroupFindMany([ prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]);
{ id: 'group-1', name: 'Funcional' }, prismaFetchAttendeeFindMany([attendee('a-1', 'group-1'), attendee('a-2', 'group-2')]);
{ id: 'group-2', name: 'Yoga' },
]);
prismaFetchAttendeeFindMany([
{ id: 'a-1', groupId: 'group-1' },
{ id: 'a-2', groupId: 'group-2' },
]);
prismaFetchClassSessionFindMany([ prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(-1) }, { id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(-2) }, { id: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(-3) }, { id: 's3', groupId: 'group-1', startsAt: at(3) },
{ id: 's4', groupId: 'group-2', startsAt: at(-1) }, { id: 's4', groupId: 'group-2', startsAt: at(1) },
]); ]);
prismaFetchAttendanceFindMany([ prismaFetchAttendanceFindMany([
attendance('a-1', 'ABSENT', at(-1)), attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 'ABSENT', at(-2)), attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 'ABSENT', at(-3)), attendance('a-1', 's3', 'ABSENT', at(3)),
attendance('a-2', 'PRESENT', at(-1)), attendance('a-2', 's4', 'PRESENT', at(1)),
]); ]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview'); const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200); expect(res.status).toBe(200);
expect(await res.json()).toEqual({ // `toMatchObject` porque el item ahora arrastra también el resumen por nivel
// que consume la tarjeta; acá se está probando el semáforo de siempre.
expect(await res.json()).toMatchObject({
items: [ items: [
{ groupId: 'group-1', groupName: 'Funcional', riskLevel: 'HIGH' }, {
{ groupId: 'group-2', groupName: 'Yoga', riskLevel: 'NONE' }, groupId: 'group-1',
groupName: 'Funcional',
riskLevel: 'HIGH',
absenceStreakCount: 1,
lowAttendanceCount: 0,
},
{
groupId: 'group-2',
groupName: 'Yoga',
riskLevel: 'NONE',
absenceStreakCount: 0,
lowAttendanceCount: 0,
},
],
});
});
it('cuenta el motivo: faltas seguidas y asistencia baja, sin repetir alumnos', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]);
prismaFetchAttendeeFindMany([
attendee('a-1', 'group-1'),
attendee('a-2', 'group-1'),
attendee('a-3', 'group-1'),
attendee('b-1', 'group-2'),
]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
{ id: 's4', groupId: 'group-1', startsAt: at(4) },
{ id: 's5', groupId: 'group-2', startsAt: at(1) },
{ id: 's6', groupId: 'group-2', startsAt: at(2) },
]);
prismaFetchAttendanceFindMany([
// Dos faltas seguidas: cuenta en el motivo de faltas.
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 's3', 'PRESENT', at(3)),
// Sin racha, pero asiste menos de la mitad de las clases del mes.
attendance('a-2', 's1', 'PRESENT', at(1)),
attendance('a-2', 's2', 'ABSENT', at(2)),
attendance('a-2', 's3', 'ABSENT', at(3)),
attendance('a-2', 's4', 'ABSENT', at(4)),
// Al día.
attendance('a-3', 's1', 'PRESENT', at(1)),
attendance('a-3', 's2', 'PRESENT', at(2)),
attendance('a-3', 's3', 'PRESENT', at(3)),
attendance('a-3', 's4', 'PRESENT', at(4)),
// Otra vez por racha, en el otro grupo.
attendance('b-1', 's5', 'ABSENT', at(1)),
attendance('b-1', 's6', 'ABSENT', at(2)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({
items: [
{
groupId: 'group-1',
groupName: 'Funcional',
riskLevel: 'MEDIUM',
absenceStreakCount: 1,
lowAttendanceCount: 1,
},
{
groupId: 'group-2',
groupName: 'Yoga',
riskLevel: 'MEDIUM',
absenceStreakCount: 1,
lowAttendanceCount: 0,
},
], ],
}); });
}); });
}); });
/* Lo que consume la tarjeta del listado. El semáforo de arriba ya tenía sus
tests; lo que faltaba era fijar el payload nuevo contra el mismo endpoint,
porque es el contrato que el frontend lee. */
it('devuelve el resumen por nivel que consume la tarjeta, no solo el semáforo', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional', 5, 2)]);
prismaFetchAttendeeFindMany([
attendee('a-1', 'group-1', 'Sofía Díaz'),
attendee('a-2', 'group-1', 'Diego Soto'),
attendee('a-3', 'group-1', 'Ana Ruiz'),
]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
]);
// El mock ignora el `orderBy`, así que las filas van de la más reciente a la
// más antigua como las devolvería Prisma: de ese orden depende la racha.
// `at(n)` son n días hacia atrás; el resumen descarta lo que no ocurrió, así
// que las fechas tienen que estar en el pasado y no en el futuro.
prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 's3', 'ABSENT', at(3)),
attendance('a-2', 's1', 'ABSENT', at(1)),
attendance('a-2', 's2', 'ABSENT', at(2)),
attendance('a-2', 's3', 'PRESENT', at(3)),
attendance('a-3', 's1', 'PRESENT', at(1)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0]).toMatchObject({
riesgoAlto: 1,
atencion: 1,
ok: 1,
// El cupo es de 5 y hay 3 miembros, no 2: los lugares libres se calculan
// contra el cupo y no como "los que no tienen ninguna señal".
libres: 2,
enEspera: 2,
// Promedio de las tasas ya redondeadas por persona: 0, 33 y 100 → 44.
asistencia: 44,
});
expect(items[0].urgentes).toEqual([
{
attendeeId: 'a-1',
fullName: 'Sofía Díaz',
level: 'riesgo_alto',
consecutiveAbsences: 3,
daysSinceLastAttendance: 1,
attendanceRate: 0,
},
{
attendeeId: 'a-2',
fullName: 'Diego Soto',
level: 'atencion',
consecutiveAbsences: 2,
// Cuenta desde su última clase con presencia, no desde la más
// reciente del grupo: la suya fue hace 3 días.
daysSinceLastAttendance: 3,
attendanceRate: 33,
},
{
attendeeId: 'a-3',
fullName: 'Ana Ruiz',
level: 'ok',
consecutiveAbsences: 0,
daysSinceLastAttendance: 1,
attendanceRate: 100,
},
]);
});
it('un grupo sin capacidad declarada no inventa lugares libres', async () => {
prismaFetchGroupFindMany([group('group-1', 'Sin cupo', null)]);
prismaFetchAttendeeFindMany([]);
prismaFetchClassSessionFindMany([]);
prismaFetchAttendanceFindMany([]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({
items: [
{
riskLevel: 'NONE',
riesgoAlto: 0,
atencion: 0,
ok: 0,
libres: 0,
enEspera: 0,
asistencia: null,
urgentes: [],
},
],
});
});
it('una clase sin registro corta la racha: no son faltas seguidas', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional')]);
prismaFetchAttendeeFindMany([attendee('a-1', 'group-1', 'Sofía Díaz')]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
]);
// Falta, clase sin marcar, falta. Leyendo solo las filas de `Attendance` esto
// parecería una racha de 2 y el grupo saldría en atención; la clase del medio
// pasó y no tiene registro, así que la racha real es de 1.
prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's3', 'ABSENT', at(3)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0].riesgoAlto).toBe(0);
expect(items[0].atencion).toBe(0);
expect(items[0].ok).toBe(1);
expect(items[0].urgentes).toEqual([
{
attendeeId: 'a-1',
fullName: 'Sofía Díaz',
level: 'ok',
consecutiveAbsences: 1,
daysSinceLastAttendance: 1,
// Las dos clases con dato fueron falta; la del medio no entra al promedio.
attendanceRate: 0,
},
]);
});
it('las faltas pegadas hasta la última clase sí cuentan como racha', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional')]);
prismaFetchAttendeeFindMany([attendee('a-1', 'group-1', 'Sofía Díaz')]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
]);
// La racha se cuenta hacia atrás desde la clase más reciente, así que llegan
// justo hasta el final: s1 y s2 pegadas, y la de hace 3 días sin registrar,
// que queda antes de la racha y no la toca.
prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(2)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0].atencion).toBe(1);
expect(items[0].urgentes).toEqual([
{
attendeeId: 'a-1',
fullName: 'Sofía Díaz',
level: 'atencion',
consecutiveAbsences: 2,
daysSinceLastAttendance: 1,
attendanceRate: 0,
},
]);
});
it('una clase sin registrar después de las faltas las borra: la racha mira hasta la última clase', async () => {
prismaFetchGroupFindMany([group('group-1', 'Funcional')]);
prismaFetchAttendeeFindMany([attendee('a-1', 'group-1', 'Sofía Díaz')]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(2) },
{ id: 's3', groupId: 'group-1', startsAt: at(3) },
]);
// Mismas dos faltas pegadas del caso anterior, pero la clase más reciente
// (s1) es la que no tiene registro. Como la racha se cuenta desde el final y
// "sin dato" no es ausencia, no hay racha: se ve la asimetría a propósito,
// porque es lo mismo que ya pasa con una clase justificada.
prismaFetchAttendanceFindMany([
attendance('a-1', 's2', 'ABSENT', at(2)),
attendance('a-1', 's3', 'ABSENT', at(3)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0].atencion).toBe(0);
expect(items[0].riesgoAlto).toBe(0);
expect(items[0].ok).toBe(1);
expect(items[0].urgentes).toEqual([
{
attendeeId: 'a-1',
fullName: 'Sofía Díaz',
level: 'ok',
consecutiveAbsences: 0,
daysSinceLastAttendance: 1,
attendanceRate: 0,
},
]);
});
it('reconoce asistencias previas a la fecha de alta del alumno como historial válido', async () => {
prismaFetchGroupFindMany([group('group-1', 'Natación', 30)]);
// El alumno fue creado hoy (offset 0), pero tiene 3 faltas en clases de hace 7, 3 y 1 días.
prismaFetchAttendeeFindMany([{ id: 'a-1', groupId: 'group-1', fullName: 'Abril Ortiz', createdAt: at(0) }]);
prismaFetchClassSessionFindMany([
{ id: 's1', groupId: 'group-1', startsAt: at(1) },
{ id: 's2', groupId: 'group-1', startsAt: at(3) },
{ id: 's3', groupId: 'group-1', startsAt: at(7) },
]);
prismaFetchAttendanceFindMany([
attendance('a-1', 's1', 'ABSENT', at(1)),
attendance('a-1', 's2', 'ABSENT', at(3)),
attendance('a-1', 's3', 'ABSENT', at(7)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
const { items } = (await res.json()) as { items: Record<string, unknown>[] };
expect(items[0].riesgoAlto).toBe(1);
expect(items[0].riskLevel).toBe('HIGH');
expect(items[0].absenceStreakCount).toBe(1);
});
/* El use-case pide `capacity` y el conteo de lista de espera para poder calcular
los lugares libres, y `fullName` + `createdAt` de cada alumno para el resumen
por nivel. Los fixtures los dan para que los tests viejos no tengan que
saber de eso. */
function group(id: string, name: string, capacity: number | null = 10, waiting = 0) {
return { id, name, capacity, _count: { waitlist: waiting } };
}
function attendee(id: string, groupId: string, fullName = id) {
return { id, groupId, fullName, createdAt: at(90) };
}
function prismaFetchGroupFindMany(rows: unknown[]) { function prismaFetchGroupFindMany(rows: unknown[]) {
db.group.findMany.mockResolvedValue(rows); db.group.findMany.mockResolvedValue(rows);
} }
@@ -109,6 +416,9 @@ function prismaFetchAttendanceFindMany(rows: unknown[]) {
db.attendance.findMany.mockResolvedValue(rows); db.attendance.findMany.mockResolvedValue(rows);
} }
function attendance(attendeeId: string, status: string, startsAt: string) { /* El `classSessionId` importa: el resumen se arma cruzando las clases del grupo
return { attendeeId, status, classSession: { startsAt } }; con las filas de asistencia, y sin ese cruce toda clase quedaría sin registro
para todo el mundo. */
function attendance(attendeeId: string, sessionId: string, status: string, startsAt: Date) {
return { attendeeId, classSessionId: sessionId, status, classSession: { startsAt } };
} }

View File

@@ -0,0 +1,305 @@
import { describe, expect, it } from 'bun:test';
import {
ATTENDANCE_RISK_RULES,
getGroupAttendanceSummary,
getMemberAttendanceRisk,
type MemberAttendance,
type MemberClassSession,
summarizeMemberAttendance,
} from '@gruperly/shared';
/* La regla de riesgo es de negocio, no de pantalla: estos tests la fijan para
que cambiar un umbral o refactorizar el filtro de clases no mueva el
semáforo de la lista de grupos en silencio.
Dos helpers de armazón:
- `dense` mete las clases en días consecutivos, para que "hace cuánto no lo
vemos" quede siempre cerca y el caso aísle la regla que dice probar (una
clase por semana haría saltar el umbral de inactividad en casi todo).
- `series` respeta los offsets que se le pasan, para los casos que sí
necesitan huecos.
Todas las fechas se cuelgan de un `NOW` fijo: la función recibe el momento
como argumento justamente para poder testear sin reloj. */
const DAY_MS = 24 * 60 * 60 * 1000;
const NOW = new Date('2026-09-30T20:00:00.000Z');
/** Días hacia atrás desde `NOW`, en ISO. Negativo = clase futura. */
const daysAgo = (days: number) => new Date(NOW.getTime() - days * DAY_MS).toISOString();
type Status = MemberClassSession['status'];
/** Clases en días consecutivos, de la más antigua a la más reciente. */
function dense(statuses: Status[]): MemberClassSession[] {
return statuses.map((status, index) => ({
sessionId: `ses_${statuses.length - index}`,
startsAt: daysAgo(statuses.length - index),
status,
}));
}
/** Clases con los offsets que se le pasen, en cualquier orden. */
function series(rows: [Status, number][]): MemberClassSession[] {
return rows.map(([status, offsetDays], index) => ({
sessionId: `ses_${index}`,
startsAt: daysAgo(offsetDays),
status,
}));
}
function member(sessions: MemberClassSession[], enrolledDaysAgo = 365): MemberAttendance {
return {
attendeeId: 'at_1',
fullName: 'Sofía Ramírez',
enrolledAt: daysAgo(enrolledDaysAgo),
sessions,
};
}
describe('getMemberAttendanceRisk', () => {
it('un alumno nuevo sin clases no genera ninguna alerta', () => {
expect(getMemberAttendanceRisk(member([]), NOW)).toBe('ok');
});
it('no lo penaliza por clases anteriores a su alta en el grupo', () => {
const rejo = member(series([['ABSENT', 28], ['ABSENT', 21], ['ABSENT', 14]]), 2);
expect(getMemberAttendanceRisk(rejo, NOW)).toBe('ok');
});
it('no cuenta clases que todavía no ocurrieron', () => {
// Asistió a las tres últimas y falta a las tres siguientes: nadie se está yendo.
const alumno = member(series([['PRESENT', 7], ['PRESENT', 14], ['PRESENT', 21], ['ABSENT', -7], ['ABSENT', -14]]));
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok');
});
it('tres o más faltas consecutivas dan riesgo alto', () => {
const alumno = member(dense(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT']));
const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.consecutiveAbsences).toBe(3);
// 4 días sin aparecer: el nivel viene de la racha, no del tiempo sin venir.
expect(señales.daysSinceLastAttendance).toBe(4);
expect(señales.level).toBe('riesgo_alto');
});
it('una racha larguísima sin ninguna clase con presencia igual es riesgo alto', () => {
// Nunca asistió a una clase elegible: la referencia para "hace cuánto no lo
// vemos" es la última clase, así que no queda en verde para siempre.
const alumno = member(dense(['ABSENT', 'ABSENT', 'ABSENT', 'ABSENT', 'ABSENT']));
const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.consecutiveAbsences).toBe(5);
expect(señales.daysSinceLastAttendance).toBe(1);
expect(señales.level).toBe('riesgo_alto');
});
it('dos faltas consecutivas dan atención y una sola no da nada', () => {
expect(getMemberAttendanceRisk(member(dense(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'])), NOW)).toBe('atencion');
expect(getMemberAttendanceRisk(member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'ABSENT'])), NOW)).toBe('ok');
});
it('más de 10 días sin aparecer es riesgo alto aunque no tenga racha', () => {
// Una sola falta, la más reciente: la racha no llega. El nivel lo dispara
// el tiempo sin aparecer.
const alumno = member(series([['ABSENT', 2], ['PRESENT', 30]]));
const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.consecutiveAbsences).toBe(1);
expect(señales.daysSinceLastAttendance).toBe(30);
expect(señales.level).toBe('riesgo_alto');
});
it('el umbral de inactividad es "más de" 10 días, no "desde" 10', () => {
const { highInactivityDays } = ATTENDANCE_RISK_RULES;
// Dos faltas de racha: la atención le llega por la racha, y los 10 días
// justos no mueven el nivel.
expect(
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays]])), NOW),
).toBe('atencion');
expect(
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays + 1]])), NOW),
).toBe('riesgo_alto');
});
it('una tendencia a la baja da atención', () => {
// 12 clases con dato. Las 4 anteriores al 100%, las 4 últimas al 50%, y la
// más reciente es un PRESENT: racha 0 y asistencia reciente, así que la
// tendencia es lo único que puede disparar la alerta.
const candidato = member(dense([
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
'ABSENT', 'PRESENT', 'ABSENT', 'PRESENT',
]));
const señales = summarizeMemberAttendance(candidato, NOW);
expect(señales.consecutiveAbsences).toBe(0);
expect(señales.daysSinceLastAttendance).toBe(1);
expect(señales.level).toBe('atencion');
});
it('perder una sola clase no es tendencia', () => {
// Mismo caso que el anterior con una clase menos perdida en la ventana
// reciente: 3 de 4 contra 4 de 4. Es ruido, no una caída.
const estable = member(dense([
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT',
]));
expect(getMemberAttendanceRisk(estable, NOW)).toBe('ok');
});
it('la tendencia necesita historia para las dos ventanas', () => {
// 5 clases con dato: la ventana anterior quedaría con una sola, así que no
// hay contra qué comparar.
const corto = member(dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT']));
expect(getMemberAttendanceRisk(corto, NOW)).toBe('ok');
});
it('la racha manda sobre la tendencia', () => {
// 16 clases: 4 anteriores al 100%, y las 4 últimas con 3 faltas seguidas
// una clase con presencia. La tendencia sola daría atención; las 3 faltas
// seguidas de punta dan riesgo alto, que es lo que tiene que ganar.
const alumno = member(dense([
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT',
'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'PRESENT', 'ABSENT', 'ABSENT', 'ABSENT',
]));
const señales = summarizeMemberAttendance(alumno, NOW);
expect(señales.consecutiveAbsences).toBe(3);
expect(señales.attendanceRate).toBe(81);
expect(señales.level).toBe('riesgo_alto');
});
it('una clase sin registro corta la racha: sin dato no hay ausencia', () => {
// Faltó, la de en medio no tiene registro, volvió a faltar. La racha real
// es de una, no de dos.
const conHueco = member(series([['ABSENT', 3], [null, 2], ['ABSENT', 1]]));
const señales = summarizeMemberAttendance(conHueco, NOW);
expect(señales.consecutiveAbsences).toBe(1);
expect(señales.markedClasses).toBe(2);
expect(señales.attendanceRate).toBe(0);
expect(señales.level).toBe('ok');
});
it('una clase justificada es la clase que no cuenta', () => {
// Faltó, avisó, volvió a faltar: la racha es de una, y el promedio ignora la
// clase justificada en vez de contarla como asistencia o como falta.
const justificada = member(series([['ABSENT', 3], ['EXCUSED', 2], ['ABSENT', 1]]));
const señales = summarizeMemberAttendance(justificada, NOW);
expect(señales.consecutiveAbsences).toBe(1);
expect(señales.markedClasses).toBe(2);
expect(señales.attendanceRate).toBe(0);
expect(señales.level).toBe('ok');
});
it('avisar de la falta tampoco encadena las de alrededor', () => {
const alumno = member(series([['ABSENT', 3], ['ABSENT', 2], ['EXCUSED', 1]]));
expect(summarizeMemberAttendance(alumno, NOW).consecutiveAbsences).toBe(0);
expect(getMemberAttendanceRisk(alumno, NOW)).toBe('ok');
});
it('no le importa el orden en que llegan las clases', () => {
const desordenado = member(series([['ABSENT', 1], ['PRESENT', 4], ['ABSENT', 2], ['ABSENT', 3]]));
expect(summarizeMemberAttendance(desordenado, NOW).consecutiveAbsences).toBe(3);
expect(getMemberAttendanceRisk(desordenado, NOW)).toBe('riesgo_alto');
});
});
describe('getGroupAttendanceSummary', () => {
const conNivel = (attendeeId: string, level: 'riesgo_alto' | 'atencion' | 'ok') => ({
attendeeId,
fullName: attendeeId,
enrolledAt: daysAgo(365),
sessions:
level === 'riesgo_alto'
? dense(['PRESENT', 'ABSENT', 'ABSENT', 'ABSENT'])
: level === 'atencion'
? dense(['PRESENT', 'PRESENT', 'ABSENT', 'ABSENT'])
: dense(['PRESENT', 'PRESENT', 'PRESENT', 'PRESENT']),
});
it('cuenta por nivel y calcula los lugares libres', () => {
const resumen = getGroupAttendanceSummary({
groupId: 'grp_1',
capacity: 10,
waitlistCount: 2,
members: [
conNivel('a', 'riesgo_alto'),
conNivel('b', 'riesgo_alto'),
conNivel('c', 'atencion'),
conNivel('d', 'ok'),
conNivel('e', 'ok'),
],
now: NOW,
});
expect(resumen).toMatchObject({ riesgoAlto: 2, atencion: 1, ok: 2, libres: 5, enEspera: 2 });
expect(resumen.peorNivel).toBe('riesgo_alto');
});
it('un grupo vacío no inventa niveles', () => {
const resumen = getGroupAttendanceSummary({
groupId: 'grp_vacio',
capacity: 5,
waitlistCount: 0,
members: [],
now: NOW,
});
expect(resumen).toMatchObject({ riesgoAlto: 0, atencion: 0, ok: 0, libres: 5, enEspera: 0 });
expect(resumen.peorNivel).toBeNull();
expect(resumen.urgentes).toEqual([]);
expect(resumen.asistencia).toBeNull();
});
it('más miembros que lugares da 0 libres, nunca negativos', () => {
const resumen = getGroupAttendanceSummary({
groupId: 'grp_lleno',
capacity: 2,
waitlistCount: 3,
members: [conNivel('a', 'ok'), conNivel('b', 'ok'), conNivel('c', 'ok')],
now: NOW,
});
expect(resumen.libres).toBe(0);
expect(resumen.enEspera).toBe(3);
expect(resumen.ok).toBe(3);
});
it('sin cupo definido tampoco hay lugares libres que mostrar', () => {
const resumen = getGroupAttendanceSummary({
groupId: 'grp_sin_cupo',
capacity: null,
waitlistCount: 0,
members: [conNivel('a', 'ok')],
now: NOW,
});
expect(resumen.libres).toBe(0);
});
it('ordena los urgentes de peor a mejor', () => {
const resumen = getGroupAttendanceSummary({
groupId: 'grp_1',
capacity: 4,
waitlistCount: 0,
members: [conNivel('ok_1', 'ok'), conNivel('alto_1', 'riesgo_alto'), conNivel('aten_1', 'atencion'), conNivel('ok_2', 'ok')],
now: NOW,
});
expect(resumen.urgentes.map((urgente) => urgente.attendeeId)).toEqual(['alto_1', 'aten_1', 'ok_1', 'ok_2']);
});
it('la asistencia del grupo promedia solo a los que tienen clases con dato', () => {
const resumen = getGroupAttendanceSummary({
groupId: 'grp_1',
capacity: 4,
waitlistCount: 0,
members: [
conNivel('a', 'ok'),
{ attendeeId: 'b', fullName: 'b', enrolledAt: daysAgo(365), sessions: series([['PRESENT', 1], ['ABSENT', 2]]) },
// Recién Chess: sin clases con dato, no mueve el promedio.
{ attendeeId: 'c', fullName: 'c', enrolledAt: daysAgo(1), sessions: [] },
],
now: NOW,
});
expect(resumen.asistencia).toBe(75);
expect(resumen.ok).toBe(3);
});
});

View File

@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
import { Hono } from 'hono'; import { Hono } from 'hono';
const db = { const db = {
@@ -463,6 +464,8 @@ describe('attendee incorporation & invite-token in groups', () => {
notes: null, notes: null,
createdAt: new Date('2026-09-18T10:00:00.000Z'), createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'), updatedAt: new Date('2026-09-18T10:00:00.000Z'),
attendances: [],
payments: [],
}, },
] as never); ] as never);
prisma.attendee.count.mockResolvedValue(1); prisma.attendee.count.mockResolvedValue(1);
@@ -474,11 +477,28 @@ describe('attendee incorporation & invite-token in groups', () => {
const data = await res.json(); const data = await res.json();
expect(data.data.length).toBe(1); expect(data.data.length).toBe(1);
expect(data.data[0].fullName).toBe('Ana García'); expect(data.data[0].fullName).toBe('Ana García');
expect(data.data[0].recentAttendance).toEqual([]);
expect(data.data[0].payment).toBeNull();
expect(prisma.attendee.findMany).toHaveBeenCalledWith({ expect(prisma.attendee.findMany).toHaveBeenCalledWith({
where: { groupId: 'group-1' }, where: { groupId: 'group-1' },
skip: 0, skip: 0,
take: 10, take: 10,
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
// El resumen de la fila se pide en la misma consulta: una petición por
// miembro sería N+1 sobre un listado de hasta 100.
include: {
attendances: {
orderBy: { classSession: { startsAt: 'desc' } },
take: RECENT_ATTENDANCE_LIMIT,
select: { status: true },
},
payments: {
where: { status: { not: 'CANCELLED' } },
orderBy: { dueDate: 'desc' },
take: 3,
select: { status: true, dueDate: true },
},
},
}); });
}); });
}); });

View File

@@ -0,0 +1,98 @@
import { describe, expect, it } from 'bun:test';
import type { AttendeeListItemRecord } from '@/modules/attendees/lib/helpers';
import { toAttendeeListItemDto } from '@/modules/attendees/lib/helpers';
/* El resumen de la fila se arma en memoria: qué clase cuenta como reciente y
qué cobro se muestra. Son las dos decisiones que la fila leen. */
function record(
overrides: Partial<AttendeeListItemRecord> = {},
): AttendeeListItemRecord {
return {
id: 'att-1',
groupId: 'group-1',
fullName: 'Ana Pérez',
email: null,
phone: null,
guardianName: null,
guardianPhone: null,
notes: null,
notifyToken: null,
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
attendances: [],
payments: [],
...overrides,
};
}
const day = (iso: string) => new Date(`${iso}T00:00:00.000Z`);
describe('toAttendeeListItemDto', () => {
it('invierte la asistencia para que la clase más reciente quede a la derecha', () => {
const dto = toAttendeeListItemDto(
record({
// Llega de más reciente a más antigua.
attendances: [{ status: 'PRESENT' }, { status: 'EXCUSED' }, { status: 'ABSENT' }],
}),
);
expect(dto.recentAttendance).toEqual(['ABSENT', 'EXCUSED', 'PRESENT']);
});
it('deja la lista vacía cuando no hay ninguna clase registrada', () => {
expect(toAttendeeListItemDto(record()).recentAttendance).toEqual([]);
});
it('no inventa cobro cuando no hay pagos', () => {
expect(toAttendeeListItemDto(record()).payment).toBeNull();
});
it('arranca en cero los pagos impagos y descarta los cancelados', () => {
const dto = toAttendeeListItemDto(
record({
payments: [
{ status: 'CANCELLED', dueDate: day('2026-01-05') },
{ status: 'PAID', dueDate: day('2026-08-10') },
{ status: 'PENDING', dueDate: day('2026-09-10') },
],
}),
);
expect(dto.payment).toEqual({ status: 'PENDING', dueDate: '2026-09-10T00:00:00.000Z' });
});
it('manda el impago más antiguo: los días de atraso son los que hay que ver', () => {
const dto = toAttendeeListItemDto(
record({
payments: [
{ status: 'PENDING', dueDate: day('2026-09-10') },
{ status: 'OVERDUE', dueDate: day('2026-04-10') },
],
}),
);
expect(dto.payment).toEqual({ status: 'OVERDUE', dueDate: '2026-04-10T00:00:00.000Z' });
});
it('cae al último pago cerrado cuando no queda nada impago', () => {
const dto = toAttendeeListItemDto(
record({
payments: [
{ status: 'PAID', dueDate: day('2026-08-10') },
{ status: 'PAID', dueDate: day('2026-09-10') },
],
}),
);
expect(dto.payment).toEqual({ status: 'PAID', dueDate: '2026-09-10T00:00:00.000Z' });
});
it('conserva los campos del DTO plano', () => {
const dto = toAttendeeListItemDto(record({ phone: '22222222' }));
expect(dto.fullName).toBe('Ana Pérez');
expect(dto.phone).toBe('22222222');
expect(dto.createdAt).toBe('2026-08-01T10:00:00.000Z');
});
});

View File

@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
import { Hono } from 'hono'; import { Hono } from 'hono';
mock.module('@/lib/prisma', () => ({ mock.module('@/lib/prisma', () => ({
@@ -18,7 +19,7 @@ import { attendeesRoutes } from '@/modules/attendees';
const app = new Hono(); const app = new Hono();
app.route('/attendees', attendeesRoutes); app.route('/attendees', attendeesRoutes);
const attendee = { const attendeeRow = {
id: 'attendee-1', id: 'attendee-1',
groupId: 'group-1', groupId: 'group-1',
fullName: 'Ana Pérez', fullName: 'Ana Pérez',
@@ -32,6 +33,13 @@ const attendee = {
updatedAt: new Date('2026-08-01T10:00:00.000Z'), updatedAt: new Date('2026-08-01T10:00:00.000Z'),
}; };
// Lo que devuelve el mock de Prisma: la fila más las relaciones del resumen.
const attendee = {
...attendeeRow,
attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }],
payments: [{ status: 'OVERDUE', dueDate: new Date('2026-09-10T00:00:00.000Z') }],
};
describe('attendees routes', () => { describe('attendees routes', () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
@@ -47,9 +55,13 @@ describe('attendees routes', () => {
expect(await res.json()).toEqual({ expect(await res.json()).toEqual({
data: [ data: [
{ {
...attendee, ...attendeeRow,
createdAt: attendee.createdAt.toISOString(), createdAt: attendeeRow.createdAt.toISOString(),
updatedAt: attendee.updatedAt.toISOString(), updatedAt: attendeeRow.updatedAt.toISOString(),
// La consulta viene de más reciente a más antigua; la fila los
// muestra al revés, con la clase más reciente a la derecha.
recentAttendance: ['PRESENT', 'PRESENT', 'ABSENT'],
payment: { status: 'OVERDUE', dueDate: '2026-09-10T00:00:00.000Z' },
}, },
], ],
pagination: { page: 2, pageSize: 10, total: 21, totalPages: 3 }, pagination: { page: 2, pageSize: 10, total: 21, totalPages: 3 },
@@ -58,6 +70,19 @@ describe('attendees routes', () => {
skip: 10, skip: 10,
take: 10, take: 10,
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
include: {
attendances: {
orderBy: { classSession: { startsAt: 'desc' } },
take: RECENT_ATTENDANCE_LIMIT,
select: { status: true },
},
payments: {
where: { status: { not: 'CANCELLED' } },
orderBy: { dueDate: 'desc' },
take: 3,
select: { status: true, dueDate: true },
},
},
}); });
expect(prisma.attendee.count).toHaveBeenCalledWith(); expect(prisma.attendee.count).toHaveBeenCalledWith();
}); });

View File

@@ -26,6 +26,7 @@ mock.module('@/lib/prisma', () => ({
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { groupsRoutes } from '@/modules/groups'; import { groupsRoutes } from '@/modules/groups';
import { ListGroups } from '@/modules/groups/features/get-all/use-case';
const userId = 'user-1'; const userId = 'user-1';
const group = { const group = {
@@ -60,7 +61,9 @@ describe('groups routes', () => {
}); });
it('lists groups scoped to the current user', async () => { it('lists groups scoped to the current user', async () => {
prisma.group.findMany.mockResolvedValue([group]); prisma.group.findMany.mockResolvedValue([
{ ...group, _count: { attendees: 4, waitlist: 1 } },
]);
prisma.group.count.mockResolvedValue(1); prisma.group.count.mockResolvedValue(1);
const res = await makeApp({ id: userId }).request('/groups'); const res = await makeApp({ id: userId }).request('/groups');
@@ -72,6 +75,8 @@ describe('groups routes', () => {
...group, ...group,
createdAt: group.createdAt.toISOString(), createdAt: group.createdAt.toISOString(),
updatedAt: group.updatedAt.toISOString(), updatedAt: group.updatedAt.toISOString(),
attendeesCount: 4,
waitlistCount: 1,
}, },
], ],
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 }, pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
@@ -79,13 +84,16 @@ describe('groups routes', () => {
const where = { const where = {
OR: [{ createdById: userId }, { members: { some: { userId } } }], OR: [{ createdById: userId }, { members: { some: { userId } } }],
}; };
// Los contadores de ocupación viajan en la misma consulta; la lista de
// espera cuenta solo los PENDING, los que siguen esperando cupo.
expect(prisma.group.findMany).toHaveBeenCalledWith({ expect(prisma.group.findMany).toHaveBeenCalledWith({
where, where,
skip: 0, include: {
take: 10, _count: {
orderBy: { createdAt: 'desc' }, select: { attendees: true, waitlist: { where: { status: 'PENDING' } } },
},
},
}); });
expect(prisma.group.count).toHaveBeenCalledWith({ where });
}); });
it('rejects listing groups without a session', async () => { it('rejects listing groups without a session', async () => {
@@ -101,6 +109,67 @@ describe('groups routes', () => {
expect(res.status).toBe(400); expect(res.status).toBe(400);
}); });
it('rejects an invalid time zone', async () => {
const res = await makeApp({ id: userId }).request('/groups?timeZone=Marte/Olympus');
expect(res.status).toBe(400);
});
it('ordena los grupos por la clase más cercana y deja al final los sin horario', async () => {
prisma.group.findMany.mockResolvedValue([
{ ...group, id: 'sin-horario', name: 'Sin horario' },
{ ...group, id: 'proxima-semana', name: 'Próxima semana', days: ['MONDAY'], time: '08:00' },
{ ...group, id: 'manana', name: 'Mañana', days: ['TUESDAY'], time: '09:00' },
{ ...group, id: 'hoy-tarde', name: 'Hoy a la tarde', days: ['MONDAY'], time: '18:00' },
{
...group,
id: 'hoy-tarde-viejo',
name: 'Hoy a la tarde (viejo)',
days: ['MONDAY'],
time: '18:00',
createdAt: new Date('2026-07-01T10:00:00.000Z'),
},
]);
// Lunes 2026-01-05 al mediodía en Ciudad de México: la clase de las 18:00
// todavía no empieza, así que ese grupo va primero.
const result = await new ListGroups({
db,
now: new Date('2026-01-05T18:00:00.000Z'),
}).execute({ page: 1, pageSize: 10, timeZone: 'America/Mexico_City' }, userId);
expect(result.ok).toBe(true);
if (!result.ok) return;
// A igual clase se pone delante el más nuevo, que era el criterio anterior.
expect(result.value.data.map((item) => item.id)).toEqual([
'hoy-tarde',
'hoy-tarde-viejo',
'manana',
'proxima-semana',
'sin-horario',
]);
expect(result.value.pagination).toEqual({ page: 1, pageSize: 10, total: 5, totalPages: 1 });
});
it('pagina la lista ya ordenada por próxima clase', async () => {
prisma.group.findMany.mockResolvedValue([
{ ...group, id: 'a', name: 'A', days: ['MONDAY'], time: '10:00' },
{ ...group, id: 'b', name: 'B', days: ['WEDNESDAY'], time: '10:00' },
]);
// Lunes al mediodía: la clase de las 10:00 de A ya pasó, así que su
// próxima ocurrencia es el lunes que viene y B (miércoles) va primero.
const result = await new ListGroups({
db,
now: new Date('2026-01-05T18:00:00.000Z'),
}).execute({ page: 2, pageSize: 1, timeZone: 'UTC' }, userId);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.data.map((item) => item.id)).toEqual(['a']);
expect(result.value.pagination).toEqual({ page: 2, pageSize: 1, total: 2, totalPages: 2 });
});
it('creates a group with billing configuration', async () => { it('creates a group with billing configuration', async () => {
prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'merchant-1', userId }); prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'merchant-1', userId });
prisma.group.create.mockResolvedValue({ prisma.group.create.mockResolvedValue({

View File

@@ -1,7 +1,7 @@
import { forwardRef, type HTMLAttributes } from 'react' import { forwardRef, type HTMLAttributes } from 'react'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
export type BadgeVariant = 'success' | 'warning' | 'danger' | 'neutral' export type BadgeVariant = 'success' | 'warning' | 'danger' | 'neutral' | 'info'
export type BadgeProps = HTMLAttributes<HTMLSpanElement> & { export type BadgeProps = HTMLAttributes<HTMLSpanElement> & {
variant?: BadgeVariant variant?: BadgeVariant
@@ -12,6 +12,11 @@ const variants: Record<BadgeVariant, string> = {
warning: 'bg-warning-soft text-warning', warning: 'bg-warning-soft text-warning',
danger: 'bg-danger-soft text-danger', danger: 'bg-danger-soft text-danger',
neutral: 'bg-primary-soft text-primary', neutral: 'bg-primary-soft text-primary',
/* Estado informativo que no es alerta: lista de espera, cupos libres. Usa la
tinta de acento legible (`accent-fg` es el azul claro en tema oscuro,
7.1:1 sobre la tarjeta) y no el `accent` directo, que en oscuro da 2.2:1
y no alcanza el mínimo de 3:1 para contenido no textual. */
info: 'bg-accent-soft text-accent-fg',
} }
export const Badge = forwardRef<HTMLSpanElement, BadgeProps>( export const Badge = forwardRef<HTMLSpanElement, BadgeProps>(

View File

@@ -0,0 +1,77 @@
import { useId, useState } from 'react'
import { Check, Copy, MessageCircle } from 'lucide-react'
import { cn } from '../../lib/utils'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
import { Section } from './Section'
import { useCopyToClipboard } from './useCopyToClipboard'
export function AbsenceLinkSection() {
const { attendee } = useAttendeeDetail()
const { copied, copy } = useCopyToClipboard()
const [isOpen, setIsOpen] = useState(false)
const panelId = useId()
const token = attendee?.notifyToken
const url = token ? `${window.location.origin}/report-absence/${token}` : null
if (!attendee || !url) return null
const phoneDigits = attendee.phone?.replace(/\D/g, '') ?? ''
const shareUrl = phoneDigits
? `https://wa.me/${phoneDigits}?text=${encodeURIComponent(
`Hola ${attendee.fullName.split(' ')[0]}, desde este link podés avisar tus ausencias en ${url}`,
)}`
: null
return (
<Section
title="Link de ausencias"
toggle={{ isOpen, panelId, onToggle: () => setIsOpen((value) => !value) }}
>
{/* El panel queda en el DOM pero oculto: `aria-controls` siempre resuelve y
el texto de "Link copiado" no se pierde al plegar y desplegar. */}
<div id={panelId} hidden={!isOpen}>
<p className="px-3 text-sm text-foreground">
Mandales este link para que avisen cuando no puedan venir.
</p>
{/* Apiladas y a ancho completo: al 50% los rótulos ("Enviar por WhatsApp")
se partían en dos líneas y quedaban por debajo del mínimo táctil.
Copiar queda arriba, pegado a su confirmación, y la acción principal
se distingue por el relleno de acento. */}
<div className="mt-2.5 flex flex-col gap-2">
<button
type="button"
onClick={() => copy(url)}
className={cn(ACTION_BUTTON_CLASS, 'w-full')}
>
<Copy className="size-4" aria-hidden="true" />
Copiar link
</button>
{shareUrl ? (
<a
href={shareUrl}
target="_blank"
rel="noopener noreferrer"
aria-label={`Enviar el link por WhatsApp a ${attendee.fullName}`}
className={PRIMARY_ACTION_CLASS}
>
<MessageCircle className="size-4" aria-hidden="true" />
Enviar por WhatsApp
</a>
) : null}
</div>
<p
aria-live="polite"
className="flex min-h-5 items-center gap-1.5 px-3 pt-2 text-xs font-medium text-success"
>
{copied ? (
<>
<Check className="size-3.5" aria-hidden="true" />
Link copiado
</>
) : null}
</p>
</div>
</Section>
)
}

View File

@@ -0,0 +1,120 @@
import { useEffect, useId, useRef, useState } from 'react'
import type { KeyboardEvent, RefObject } from 'react'
import { Ellipsis, UserMinus } from 'lucide-react'
import { useAttendeeDetail } from './AttendeeDetailProvider'
const ITEM_CLASS =
'flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-sm font-medium text-primary transition-colors hover:bg-danger-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
/** Menú "⋯" de la ficha del miembro.
*
* Por ahora solo guarda "Quitar del grupo": el backend no tiene forma de
* regenerar el token de ausencias, así que la opción no se muestra antes que
* exista el endpoint (ver `apps/backend/prisma/models/domain.prisma`, campo
* `notifyToken`). Cuando exista, es un `<button role="menuitem">` más en la
* lista de abajo.
*
* La etiqueta va en `text-primary` y el ícono lleva el `text-danger`: el rojo
* de `danger` sobre blanco queda en 3.7:1 y no llega a AA para texto normal. */
export function AttendeeActionsMenu({
triggerRef,
}: {
/** Se lo pasa la pantalla para que el diálogo de confirmación le devuelva el
* foco cuando se cierra. */
triggerRef: RefObject<HTMLButtonElement | null>
}) {
const { openRemoveDialog } = useAttendeeDetail()
const [isOpen, setIsOpen] = useState(false)
const menuRef = useRef<HTMLDivElement>(null)
const itemRef = useRef<HTMLButtonElement>(null)
const menuId = useId()
useEffect(() => {
if (isOpen) itemRef.current?.focus()
}, [isOpen])
useEffect(() => {
if (!isOpen) return
const handlePointerDown = (event: PointerEvent) => {
const target = event.target as Node
if (menuRef.current?.contains(target) || triggerRef.current?.contains(target)) return
setIsOpen(false)
}
document.addEventListener('pointerdown', handlePointerDown)
return () => document.removeEventListener('pointerdown', handlePointerDown)
}, [isOpen, triggerRef])
const close = (restoreFocus = false) => {
setIsOpen(false)
if (restoreFocus) triggerRef.current?.focus()
}
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'Escape') {
event.stopPropagation()
close(true)
return
}
if (event.key === 'Tab') {
close()
return
}
if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return
event.preventDefault()
const items = Array.from(
menuRef.current?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? [],
)
if (items.length === 0) return
const current = items.indexOf(document.activeElement as HTMLElement)
const next =
event.key === 'Home'
? 0
: event.key === 'End'
? items.length - 1
: (current + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length
items[next]?.focus()
}
return (
<div className="relative shrink-0">
<button
ref={triggerRef}
type="button"
onClick={() => setIsOpen((value) => !value)}
aria-haspopup="menu"
aria-expanded={isOpen}
aria-controls={isOpen ? menuId : undefined}
aria-label="Más acciones"
className="inline-flex size-11 items-center justify-center rounded-xl text-primary transition-colors hover:bg-primary-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<Ellipsis className="size-5" aria-hidden="true" />
</button>
{isOpen ? (
<div
ref={menuRef}
id={menuId}
role="menu"
aria-label="Acciones del miembro"
onKeyDown={handleKeyDown}
className="absolute right-0 top-full z-40 mt-1 w-60 rounded-xl bg-primary-soft p-1.5 shadow-lg"
>
<button
ref={itemRef}
type="button"
role="menuitem"
className={ITEM_CLASS}
onClick={() => {
close()
openRemoveDialog()
}}
>
<UserMinus className="size-4 shrink-0 text-danger" aria-hidden="true" />
Quitar del grupo
</button>
</div>
) : null}
</div>
)
}

View File

@@ -0,0 +1,126 @@
import { useState } from 'react'
import type { AttendanceStatus } from '@gruperly/shared'
import { Check, ChevronDown, Loader2, Megaphone, Minus, X } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { Button } from '../../components/ui'
import { cn } from '../../lib/utils'
import {
attendanceStatusClass,
attendanceStatusLabel,
attendanceSummary,
formatSessionShortDate,
HISTORY_LIMIT,
HISTORY_PREVIEW,
visibleSessions,
type AttendanceSession,
} from './attendance'
import { Section } from './Section'
import { useAttendeeDetail } from './AttendeeDetailProvider'
const STATUS_ICONS: Record<AttendanceStatus | 'UNMARKED', LucideIcon> = {
PRESENT: Check,
ABSENT: X,
EXCUSED: Megaphone,
UNMARKED: Minus,
}
function iconFor(status: AttendanceSession['status']): LucideIcon {
return STATUS_ICONS[status ?? 'UNMARKED']
}
export function AttendeeAttendanceSection() {
const { history, historyPending, historyFailed } = useAttendeeDetail()
const [showAll, setShowAll] = useState(false)
if (historyPending) {
return (
<Section title="Asistencia" trailing="—">
<div className="flex items-center justify-center py-5">
<Loader2 className="size-5 animate-spin text-accent" />
</div>
</Section>
)
}
if (historyFailed) {
return (
<Section title="Asistencia">
<p className="py-3 text-sm text-foreground">
No pudimos cargar la asistencia de este miembro.
</p>
</Section>
)
}
const sessions = history?.sessions ?? []
if (sessions.length === 0) {
return (
<Section title="Asistencia">
<p className="py-3 text-sm text-foreground">
Todavía no hay clases registradas.
</p>
</Section>
)
}
const visible = visibleSessions(sessions, showAll)
const hasMore = sessions.length > HISTORY_PREVIEW
const isCapped = sessions.length >= HISTORY_LIMIT
const summary = attendanceSummary(visible)
return (
<Section title="Asistencia" trailing={summary.label}>
<ul className="divide-y divide-border/60">
{visible.map((session) => {
const Icon = iconFor(session.status)
return (
<li
key={session.classSessionId}
className="flex items-center justify-between gap-3 px-3 py-2"
>
<span className="truncate text-sm text-primary">
{formatSessionShortDate(session.startsAt)}
</span>
<span
className={cn(
'flex shrink-0 items-center gap-1.5 text-xs font-semibold',
attendanceStatusClass(session.status),
)}
>
<Icon className="size-3.5" aria-hidden="true" />
{attendanceStatusLabel(session.status)}
</span>
</li>
)
})}
</ul>
{/* Las clases sin registro no son ausencias: se avisa aparte y en voz baja
para que el "1 de 1" de arriba no se lea como un fallo. */}
{summary.unmarkedLabel ? (
<p className="px-3 pt-2 text-right text-xs text-foreground">{summary.unmarkedLabel}</p>
) : null}
{showAll && isCapped ? (
<p className="px-3 pt-2 text-xs text-foreground">
El historial guarda las últimas {HISTORY_LIMIT} clases.
</p>
) : null}
{hasMore ? (
<div className="mt-1 flex justify-end">
<Button
variant="ghost"
onClick={() => setShowAll((value) => !value)}
aria-expanded={showAll}
className="h-11 gap-1 px-3 text-sm text-accent-fg hover:text-primary"
>
{showAll ? 'Ver menos' : `Ver todas (${sessions.length})`}
<ChevronDown className={cn('size-4 transition-transform', showAll && 'rotate-180')} />
</Button>
</div>
) : null}
</Section>
)
}

View File

@@ -0,0 +1,42 @@
import { MessageCircle, Phone } from 'lucide-react'
import { formatPhoneDisplay } from '../../lib/format'
import { cn } from '../../lib/utils'
import { ACTION_BUTTON_CLASS } from './actionButton'
import { useAttendeeDetail } from './AttendeeDetailProvider'
export function AttendeeContactActions() {
const { attendee } = useAttendeeDetail()
const phone = attendee?.phone
if (!phone) return null
// Los links van con los dígitos crudos: wa.me y tel: no entienden formatos.
const digits = phone.replace(/\D/g, '')
const label = formatPhoneDisplay(phone) ?? phone
return (
<div className="flex gap-2.5">
{/* Los íconos van con `accent-fg` y no con `accent`: el azul de `accent` es
el mismo en los dos temas y sobre `primary-soft` oscuro queda en 2.2:1.
`accent-fg` da 6.2:1 en claro y 7.1:1 en oscuro. */}
<a
href={`https://wa.me/${digits}`}
target="_blank"
rel="noopener noreferrer"
aria-label={`Abrir WhatsApp con ${label}`}
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
>
<MessageCircle className="size-4 text-accent-fg" aria-hidden="true" />
WhatsApp
</a>
<a
href={`tel:${digits}`}
aria-label={`Llamar a ${label}`}
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
>
<Phone className="size-4 text-accent-fg" aria-hidden="true" />
Llamar
</a>
</div>
)
}

View File

@@ -0,0 +1,42 @@
import { Mail } from 'lucide-react'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { Section } from './Section'
/* `px-3` interno: la banda de hover sigue a sangre hasta el borde de la sección
(la separa del texto, no al revés) y las notas de abajo suman el mismo para
que el email y ellas caigan en la misma columna. */
const ROW_CLASS =
'flex w-full min-h-11 items-center justify-between gap-3 rounded-lg px-3 py-2.5 transition-colors hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
/** Email y notas del miembro. El teléfono no va acá: ya está en el subtítulo y
* detrás de los botones de WhatsApp y Llamar, y repetirlo llenaba la pantalla
* de un dato que ya estaba a la vista.
*
* Sin datos no se dibuja la sección: no hay filas con "Sin email"/"Sin notas".
* Aparece sola en cuanto el miembro tenga alguno (hoy el email puede llegar al
* aprobar una preinscripción; las notas, cuando exista la edición). */
export function AttendeeContactSection() {
const { attendee } = useAttendeeDetail()
if (!attendee) return null
const { email, notes } = attendee
if (!email && !notes) return null
return (
<Section title="Contacto">
<div className="divide-y divide-border/60">
{email ? (
<a href={`mailto:${email}`} className={ROW_CLASS}>
<span className="truncate text-sm text-primary">{email}</span>
<Mail className="size-4 shrink-0 text-foreground" aria-hidden="true" />
</a>
) : null}
{notes ? (
<p className="whitespace-pre-line px-3 py-2 text-sm leading-relaxed text-primary">{notes}</p>
) : null}
</div>
</Section>
)
}

View File

@@ -2,10 +2,9 @@ import { createContext, useContext, useState } from 'react'
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router' import { useNavigate } from '@tanstack/react-router'
import type { AttendeeDto, AttendeeStats, GroupWaitlistEntryDto } from '@gruperly/shared' import type { AttendeeDto, AttendeeHistory, GroupWaitlistEntryDto } from '@gruperly/shared'
import { useToast } from '../../../components/ui' import { getAttendeeHistory, getGroup, getGroupAttendee, getGroupWaitlist } from '../../lib/api'
import { getAttendeeStats, getGroup, getGroupAttendee, getGroupWaitlist } from '../../../lib/api' import { useRemoveAttendee } from '../groups/detail/useRemoveAttendee'
import { useRemoveAttendee } from './useRemoveAttendee'
type AttendeeDetailContextValue = { type AttendeeDetailContextValue = {
groupId: string groupId: string
@@ -13,18 +12,17 @@ type AttendeeDetailContextValue = {
attendee: AttendeeDto | undefined attendee: AttendeeDto | undefined
attendeePending: boolean attendeePending: boolean
attendeeFailed: boolean attendeeFailed: boolean
attendeeStats: AttendeeStats | undefined history: AttendeeHistory | undefined
attendeeStatsPending: boolean historyPending: boolean
attendeeStatsFailed: boolean historyFailed: boolean
firstWaitlistEntry: GroupWaitlistEntryDto | null firstWaitlistEntry: GroupWaitlistEntryDto | null
waitlistTotal: number waitlistTotal: number
waitlistPending: boolean waitlistPending: boolean
isRemoveModalOpen: boolean isRemoveDialogOpen: boolean
openRemoveModal: () => void openRemoveDialog: () => void
closeRemoveModal: () => void closeRemoveDialog: () => void
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
isSubmittingRemoval: boolean isSubmittingRemoval: boolean
copyAbsenceNotifyUrl: (url: string) => void
} }
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null) const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
@@ -38,9 +36,8 @@ export function AttendeeDetailProvider({
attendeeId: string attendeeId: string
children: ReactNode children: ReactNode
}) { }) {
const toast = useToast()
const navigate = useNavigate() const navigate = useNavigate()
const [isRemoveModalOpen, setIsRemoveModalOpen] = useState(false) const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false)
const groupQuery = useQuery({ const groupQuery = useQuery({
queryKey: ['group', groupId], queryKey: ['group', groupId],
@@ -54,16 +51,20 @@ export function AttendeeDetailProvider({
enabled: Boolean(groupId && attendeeId), enabled: Boolean(groupId && attendeeId),
}) })
const attendeeStatsQuery = useQuery({ // Misma clave que usa la pantalla de estadísticas: las dos leen el mismo
queryKey: ['attendee-stats', groupId, attendeeId], // historial y no se pisan la caché.
queryFn: () => getAttendeeStats(groupId, attendeeId), const historyQuery = useQuery({
queryKey: ['attendee-history', groupId, attendeeId],
queryFn: () => getAttendeeHistory(groupId, attendeeId),
enabled: Boolean(groupId && attendeeId), enabled: Boolean(groupId && attendeeId),
}) })
// La lista de espera solo hace falta para el diálogo de quitar, así que no se
// pide hasta que el usuario lo abre.
const waitlistQuery = useQuery({ const waitlistQuery = useQuery({
queryKey: ['group-waitlist', groupId], queryKey: ['group-waitlist', groupId],
queryFn: () => getGroupWaitlist(groupId, 1, 100), queryFn: () => getGroupWaitlist(groupId, 1, 100),
enabled: Boolean(groupId && isRemoveModalOpen), enabled: Boolean(groupId && isRemoveDialogOpen),
}) })
const waitlistEntries = waitlistQuery.data?.data ?? [] const waitlistEntries = waitlistQuery.data?.data ?? []
@@ -73,38 +74,31 @@ export function AttendeeDetailProvider({
const { removeAttendee, isRemovingAttendee } = useRemoveAttendee({ const { removeAttendee, isRemovingAttendee } = useRemoveAttendee({
groupId, groupId,
onRemoved: () => { onRemoved: () => {
setIsRemoveModalOpen(false) setIsRemoveDialogOpen(false)
void navigate({ to: '/groups/$groupId', params: { groupId } }) void navigate({ to: '/groups/$groupId', params: { groupId } })
}, },
}) })
const copyAbsenceNotifyUrl = (url: string) => {
void navigator.clipboard.writeText(url).then(() => {
toast.success('Link copiado al portapapeles.')
})
}
const value: AttendeeDetailContextValue = { const value: AttendeeDetailContextValue = {
groupId, groupId,
groupName: groupQuery.data?.name, groupName: groupQuery.data?.name,
attendee: attendeeQuery.data, attendee: attendeeQuery.data,
attendeePending: attendeeQuery.isPending, attendeePending: attendeeQuery.isPending,
attendeeFailed: attendeeQuery.isError, attendeeFailed: attendeeQuery.isError,
attendeeStats: attendeeStatsQuery.data, history: historyQuery.data,
attendeeStatsPending: attendeeStatsQuery.isPending, historyPending: historyQuery.isPending,
attendeeStatsFailed: attendeeStatsQuery.isError, historyFailed: historyQuery.isError,
firstWaitlistEntry, firstWaitlistEntry,
waitlistTotal, waitlistTotal,
waitlistPending: waitlistQuery.isPending, waitlistPending: waitlistQuery.isPending,
isRemoveModalOpen, isRemoveDialogOpen,
openRemoveModal: () => setIsRemoveModalOpen(true), openRemoveDialog: () => setIsRemoveDialogOpen(true),
closeRemoveModal: () => setIsRemoveModalOpen(false), closeRemoveDialog: () => setIsRemoveDialogOpen(false),
confirmRemoveAttendee: (promoteFromWaitlist) => { confirmRemoveAttendee: (promoteFromWaitlist) => {
if (!attendeeQuery.data) return if (!attendeeQuery.data) return
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist }) removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
}, },
isSubmittingRemoval: isRemovingAttendee, isSubmittingRemoval: isRemovingAttendee,
copyAbsenceNotifyUrl,
} }
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider> return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>

View File

@@ -0,0 +1,90 @@
import { useRef } from 'react'
import { Link, useNavigate } from '@tanstack/react-router'
import { ArrowLeft, Loader2 } from 'lucide-react'
import { Button } from '../../components/ui'
import { AbsenceLinkSection } from './AbsenceLinkSection'
import { AttendeeActionsMenu } from './AttendeeActionsMenu'
import { AttendeeAttendanceSection } from './AttendeeAttendanceSection'
import { AttendeeContactActions } from './AttendeeContactActions'
import { AttendeeContactSection } from './AttendeeContactSection'
import { AttendeePhoneLine } from './AttendeePhoneLine'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
import { formatMemberSince } from './attendance'
export function AttendeeDetailView() {
const { groupId, groupName, attendee, attendeePending, attendeeFailed } = useAttendeeDetail()
const navigate = useNavigate()
const menuTriggerRef = useRef<HTMLButtonElement>(null)
if (attendeePending) {
return (
<div className="flex items-center justify-center py-20">
<Loader2 className="size-8 animate-spin text-accent" />
</div>
)
}
if (attendeeFailed || !attendee) {
return (
<div className="animate-fade-in rounded-2xl bg-danger-soft p-6">
{/* El título lleva el rojo (a 18px ya cuenta como texto grande y llega a
los 3:1) y el cuerpo usa `text-primary`: en `danger-soft` el rojo no
pasa los 4.5:1 que necesita un `text-sm`. */}
<h1 className="text-lg font-bold text-danger">Miembro no encontrado</h1>
<p className="mt-2 text-sm text-primary">
No se pudo cargar la información de este miembro.
</p>
<Button
variant="ghost"
className="mt-4 px-0 text-accent-fg hover:bg-transparent hover:text-primary"
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
>
Volver al grupo
</Button>
</div>
)
}
return (
<section className="animate-fade-in">
<div className="flex items-center justify-between gap-2">
<Link
to="/groups/$groupId"
params={{ groupId }}
className="flex min-h-11 min-w-0 items-center gap-1.5 rounded-lg py-2 text-sm text-foreground transition-colors hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<ArrowLeft className="size-4 shrink-0" aria-hidden="true" />
<span className="truncate">{groupName ?? 'Grupo'}</span>
</Link>
<AttendeeActionsMenu triggerRef={menuTriggerRef} />
</div>
<div className="mt-1">
<h1 className="text-balance text-2xl font-bold leading-tight tracking-tight text-primary">
{attendee.fullName}
</h1>
<p className="mt-1 whitespace-nowrap text-sm text-foreground">
Miembro desde {formatMemberSince(attendee.createdAt)}
</p>
<AttendeePhoneLine />
</div>
<div className="mt-3">
<AttendeeContactActions />
</div>
{/* Orden por frecuencia de uso. Sumar Pagos es insertar un bloque más
arriba de Asistencia; cada sección lleva su propio aire, así que el
layout no se toca. */}
<div className="mt-5">
<AttendeeAttendanceSection />
<AttendeeContactSection />
<AbsenceLinkSection />
</div>
<ConfirmRemoveAttendeeDialog returnFocusRef={menuTriggerRef} />
</section>
)
}

View File

@@ -0,0 +1,45 @@
import { Check } from 'lucide-react'
import { formatPhoneDisplay } from '../../lib/format'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useCopyToClipboard } from './useCopyToClipboard'
/** Teléfono como segunda línea del subtítulo.
*
* Vivía en una sección "Contacto" con una sola fila que repetía el número que
* ya está a la vista detrás de los botones de WhatsApp y Llamar. Acá acompaña
* al "Miembro desde…", se copia con un toque y tiene 44px de alto aunque el
* texto sea de 14px: es un control, no un dato decorativo. */
export function AttendeePhoneLine() {
const { attendee } = useAttendeeDetail()
const { copied, copy } = useCopyToClipboard()
const phone = attendee?.phone
const label = formatPhoneDisplay(phone)
if (!phone || !label) return null
return (
<>
<button
type="button"
onClick={() => copy(phone)}
className="flex min-h-11 max-w-fit items-center gap-2 rounded-lg text-left transition-colors hover:bg-primary-soft active:scale-[0.98] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<span className="truncate text-sm text-foreground">{label}</span>
{/* `aria-hidden`: la confirmación se anuncia desde la región viva de
abajo, así no se cuela en el nombre del botón. */}
{copied ? (
<span
aria-hidden="true"
className="flex shrink-0 items-center gap-1 text-xs font-medium text-accent-fg"
>
<Check className="size-3.5" />
Número copiado
</span>
) : null}
</button>
<span aria-live="polite" className="sr-only">
{copied ? 'Número copiado al portapapeles' : ''}
</span>
</>
)
}

View File

@@ -0,0 +1,170 @@
import { useEffect, useRef } from 'react'
import type { RefObject } from 'react'
import type { LucideIcon } from 'lucide-react'
import { History, Link2, Loader2, Trash2, UserPlus, Users } from 'lucide-react'
import { Button, Modal } from '../../components/ui'
import { useAttendeeDetail } from './AttendeeDetailProvider'
type Consequence = { key: string; icon: LucideIcon; text: string }
export function ConfirmRemoveAttendeeDialog({
returnFocusRef,
}: {
/** Elemento al que vuelve el foco al cerrarse (el botón "⋯"). */
returnFocusRef: RefObject<HTMLButtonElement | null>
}) {
const {
attendee,
groupName,
firstWaitlistEntry,
waitlistTotal,
waitlistPending,
isSubmittingRemoval,
isRemoveDialogOpen,
closeRemoveDialog,
confirmRemoveAttendee,
} = useAttendeeDetail()
const wasOpen = useRef(false)
const contentRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (isRemoveDialogOpen) {
wasOpen.current = true
return
}
if (!wasOpen.current) return
wasOpen.current = false
returnFocusRef.current?.focus()
}, [isRemoveDialogOpen, returnFocusRef])
useEffect(() => {
if (!isRemoveDialogOpen) return
return trapTabWithin(contentRef)
}, [isRemoveDialogOpen])
if (!attendee) return null
const waiting = waitlistTotal > 0
const canPromote = !waitlistPending && firstWaitlistEntry !== null
const consequences: Consequence[] = [
{
key: 'historial',
icon: History,
text: 'Se borra su historial: las clases registradas y las ausencias que avisó dejan de existir.',
},
]
if (attendee.notifyToken) {
consequences.push({ key: 'link', icon: Link2, text: 'El link de ausencias deja de funcionar.' })
}
consequences.push({
key: 'lugar',
icon: Users,
text: waiting
? `Se libera 1 lugar. Hay ${waitlistTotal} ${
waitlistTotal === 1 ? 'persona' : 'personas'
} en lista de espera.`
: 'Se libera 1 lugar en el grupo.',
})
return (
<Modal
isOpen={isRemoveDialogOpen}
onClose={closeRemoveDialog}
title="Quitar del grupo"
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
maxWidth="sm"
>
<div ref={contentRef} className="space-y-4">
<ul className="space-y-2.5">
{consequences.map(({ icon: Icon, key, text }) => (
<li key={key} className="flex items-start gap-2.5 text-sm text-foreground">
<Icon className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
<span>{text}</span>
</li>
))}
</ul>
<p className="text-xs text-foreground">
Si tiene cobros registrados no se va a poder quitar: primero hay que gestionarlos.
</p>
{canPromote && firstWaitlistEntry ? (
<div className="rounded-xl bg-accent-soft p-3.5">
<p className="text-sm text-foreground">
Si lo quitás, podés darle el lugar a{' '}
<strong className="text-primary">{firstWaitlistEntry.fullName}</strong>, el primero
de la lista de espera.
</p>
<Button
variant="primary"
onClick={() => confirmRemoveAttendee(true)}
disabled={isSubmittingRemoval}
className="mt-2.5 w-full gap-2"
>
{isSubmittingRemoval ? (
<Loader2 className="size-4 animate-spin" />
) : (
<UserPlus className="size-4" />
)}
<span>Pasar a {firstWaitlistEntry.fullName} al grupo</span>
</Button>
</div>
) : null}
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
<Button variant="ghost" onClick={closeRemoveDialog} autoFocus>
Cancelar
</Button>
{/* Etiqueta en negro sobre el relleno `danger`: es la única forma de
llegar a AA con el mismo rojo en los dos temas (4.9:1 claro,
6.7:1 oscuro); en blanco quedan 3.7:1 y 2.7:1. */}
<Button
onClick={() => confirmRemoveAttendee(false)}
disabled={isSubmittingRemoval}
className="gap-2 bg-danger text-black hover:bg-danger/90"
>
{isSubmittingRemoval ? (
<Loader2 className="size-4 animate-spin" />
) : (
<Trash2 className="size-4" />
)}
<span>Quitar del grupo</span>
</Button>
</div>
</div>
</Modal>
)
}
/** El `Modal` de la app no atrapa el foco; este diálogo sí, para que el Tab no
* se vaya detrás del overlay. Solo cicla entre los controles del contenido: si
* el foco está en otro lado (la X del `Modal`, que se sigue cerrando con
* Escape) lo deja seguir su curso normal. */
function trapTabWithin(contentRef: RefObject<HTMLDivElement | null>) {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Tab') return
const container = contentRef.current
if (!container?.contains(document.activeElement)) return
const focusable = Array.from(container.querySelectorAll<HTMLElement>('button:not([disabled])'))
if (focusable.length === 0) return
const first = focusable[0]
const last = focusable[focusable.length - 1]
const active = document.activeElement
if (event.shiftKey && active === first) {
event.preventDefault()
last.focus()
} else if (!event.shiftKey && active === last) {
event.preventDefault()
first.focus()
}
}
document.addEventListener('keydown', handleKeyDown)
return () => document.removeEventListener('keydown', handleKeyDown)
}

View File

@@ -0,0 +1,86 @@
import { useId } from 'react'
import type { ReactNode } from 'react'
import { ChevronDown } from 'lucide-react'
import { cn } from '../../lib/utils'
/* El gris va sin opacidad: sobre el fondo oscuro `text-foreground/50` cae a
~2.7:1 y `/80` a ~4.2:1, los dos por debajo de AA. El token entero sí pasa. */
export const SECTION_TITLE_CLASS = 'text-[11px] font-semibold uppercase tracking-wide text-foreground'
/* La fila que despliega la sección es un botón, no un título: por eso lleva
superficie de hover y presión, se pinta en `primary` para que se lea
distinta de los títulos fijos, y el chevron cae al borde derecho de la fila
en vez de pegado al texto.
El `px-3` es interno: la banda de hover sigue a sangre hasta el borde de la
sección y lo que se separa del borde es el contenido (el `px-3` del `h2` y
del `trailing` de abajo alinea rótulo y resumen con esta fila). */
const TOGGLE_ROW_CLASS = cn(
SECTION_TITLE_CLASS,
'flex min-h-11 w-full items-center justify-between gap-2 rounded-lg px-3 text-left text-primary',
'transition-colors hover:bg-primary-soft active:scale-[0.98] motion-reduce:active:scale-100',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent',
)
type SectionProps = {
/** Título de la sección. Un string por lo general. */
title: ReactNode
/** A la derecha del título: el resumen de asistencia, por ejemplo. */
trailing?: ReactNode
/** Cuando está, el título entero es el disparador del contenido y `title` es
* solo su rótulo: el `<h2>` sigue siendo el encabezado de la sección y el
* botón ocupa la fila completa. */
toggle?: { isOpen: boolean; panelId: string; onToggle: () => void }
children: ReactNode
}
/** Bloque de sección: separador fino sobre el fondo, título chico en
* mayúsculas y contenido sin padding propio (el de la pantalla).
*
* El aire vive acá y no en la pantalla: cada sección cierra con su propio
* padding, así que el separador queda siempre a la misma distancia del
* contenido de arriba. Sumar otra sección (Pagos, por ejemplo) es insertar
* otro bloque y nada más. */
export function Section({ title, trailing, toggle, children }: SectionProps) {
const headingId = useId()
return (
<section aria-labelledby={headingId} className="border-t border-border/70 py-4">
<div className="flex items-center justify-between gap-3">
{toggle ? (
// El botón vive dentro del `<h2>`: el encabezado no se pierde y el
// disparador sigue siendo un control de verdad (Enter, Espacio y foco
// visible por teclado).
<h2 id={headingId} className="min-w-0 flex-1">
<button
type="button"
aria-expanded={toggle.isOpen}
aria-controls={toggle.panelId}
onClick={toggle.onToggle}
className={TOGGLE_ROW_CLASS}
>
<span className="truncate">{title}</span>
<ChevronDown
className={cn(
'size-4 shrink-0 transition-transform',
toggle.isOpen && 'rotate-180',
)}
aria-hidden="true"
/>
</button>
</h2>
) : (
<h2 id={headingId} className={cn(SECTION_TITLE_CLASS, 'px-3')}>
{title}
</h2>
)}
{trailing ? (
<div className="shrink-0 px-3 text-xs font-semibold tabular-nums text-foreground">
{trailing}
</div>
) : null}
</div>
<div className="mt-2">{children}</div>
</section>
)
}

View File

@@ -0,0 +1,15 @@
/** Botón de acción de la pantalla (WhatsApp, Llamar, Copiar link).
*
* Relleno `primary-soft`, que es la misma superficie rellena que usa el detalle
* de grupo: un borde fino sobre `surface` en tema claro es invisible porque
* `surface` y `background` son el mismo blanco. 44px de alto para el dedo, y
* el mismo anillo de foco y feedback de presión que el `Button` de la app. */
export const ACTION_BUTTON_CLASS =
'inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-primary-soft px-3 text-sm font-medium text-primary transition-colors hover:bg-accent-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
/** Acción principal de un panel (Enviar por WhatsApp). Misma superficie que el
* `Button` `primary` de la app —relleno `accent` con texto `on-accent`, que
* da 6.8:1 en los dos temas— pero a ancho completo porque sola en la columna:
* al lado de la secundaria al 50% los rótulos largos se parten en dos líneas. */
export const PRIMARY_ACTION_CLASS =
'inline-flex h-11 w-full items-center justify-center gap-2 rounded-xl bg-accent px-4 text-sm font-medium text-on-accent transition-colors hover:bg-accent-strong active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'

View File

@@ -0,0 +1,103 @@
import type { AttendanceHistoryItem } from '@gruperly/shared'
/* El endpoint de historial corta en 20 sesiones (HISTORY_SESSIONS_LIMIT en el
backend). Es el techo real de lo que esta pantalla puede mostrar, así que
"Ver todas" no promete más de lo que hay. */
export const HISTORY_PREVIEW = 5
export const HISTORY_LIMIT = 20
export type AttendanceSession = AttendanceHistoryItem
export function formatSessionShortDate(iso: string): string {
const date = new Date(iso)
const weekday = date.toLocaleDateString('es-MX', { weekday: 'short' })
const day = date.toLocaleDateString('es-MX', { day: 'numeric' })
const month = date.toLocaleDateString('es-MX', { month: 'short' })
return `${weekday} ${day} ${month}`
}
export function attendanceStatusLabel(status: AttendanceSession['status']): string {
switch (status) {
case 'PRESENT':
return 'Asistió'
case 'ABSENT':
return 'Faltó'
case 'EXCUSED':
return 'Faltó (avisó)'
default:
return 'Sin registrar'
}
}
/* El estado se lee por texto e ícono, no solo por color: los tokens de estado
están pensados como texto sobre superficies oscuras y el verde sobre blanco
queda justo por debajo de AA, así que la fila lleva las tres señales. */
export function attendanceStatusClass(status: AttendanceSession['status']): string {
switch (status) {
case 'PRESENT':
return 'text-success'
case 'ABSENT':
return 'text-danger'
case 'EXCUSED':
return 'text-warning'
default:
return 'text-foreground'
}
}
/** "28 sep 2026". Es la fecha corta de siempre: entra en una línea en móvil. */
export function formatMemberSince(iso: string): string {
return new Date(iso).toLocaleDateString('es-MX', {
day: 'numeric',
month: 'short',
year: 'numeric',
})
}
/** "1 clase" / "2 clases". */
export function classCountLabel(count: number): string {
return count === 1 ? '1 clase' : `${count} clases`
}
/** Lo que se muestra: de la más reciente a la más antigua, con las últimas
* `HISTORY_PREVIEW` como vista previa. El endpoint devuelve el orden
* contrario (más antigua → más reciente). */
export function visibleSessions(
sessions: AttendanceSession[],
showAll: boolean,
): AttendanceSession[] {
const ordered = [...sessions].reverse()
return showAll ? ordered : ordered.slice(0, HISTORY_PREVIEW)
}
/** Clases con asistencia registrada: asistió, faltó o faltó con aviso. Las
* "Sin registrar" no cuentan: sin dato no hay ni asistencia ni ausencia, y
* meterlas en el denominador hacía que "1 de 3" se leyera como dos ausencias. */
function markedSessions(sessions: AttendanceSession[]): AttendanceSession[] {
return sessions.filter((session) => session.status != null)
}
export type AttendanceSummary = {
/** "1 de 1 clase", o "Sin clases registradas" si no hay ninguna con dato. */
label: string
/** "2 sin registrar", o `null` si no hay clases sin registro. */
unmarkedLabel: string | null
}
/** Resumen de las filas que se están mostrando: cuántas clases registró la
* persona sobre cuántas hay con dato, y cuántas quedaron sin registrar.
*
* El texto de las "sin registrar" se apaga cuando no hay ninguna clase
* registrada: el resumen ya dice que no hay datos y los dos textos dirían lo
* mismo dos veces. */
export function attendanceSummary(sessions: AttendanceSession[]): AttendanceSummary {
const marked = markedSessions(sessions)
if (marked.length === 0) return { label: 'Sin clases registradas', unmarkedLabel: null }
const present = marked.filter((session) => session.status === 'PRESENT').length
const unmarked = sessions.length - marked.length
return {
label: `${present} de ${classCountLabel(marked.length)}`,
unmarkedLabel: unmarked > 0 ? `${unmarked} sin registrar` : null,
}
}

View File

@@ -0,0 +1,33 @@
import { useEffect, useRef, useState } from 'react'
const FEEDBACK_MS = 1800
/** Copia al portapapeles y avisa en el mismo lugar donde se apretó, que es
* donde sigue la vista: un toast encima obliga a volver a buscar el control. */
export function useCopyToClipboard() {
const [copied, setCopied] = useState(false)
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
useEffect(
() => () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current)
},
[],
)
const copy = (text: string) => {
if (!navigator.clipboard) return
void navigator.clipboard
.writeText(text)
.then(() => {
setCopied(true)
if (timeoutRef.current) clearTimeout(timeoutRef.current)
timeoutRef.current = setTimeout(() => setCopied(false), FEEDBACK_MS)
})
// Si el navegador rechaza la escritura no hay nada que confirmar: se
// deja el control como estaba en vez de dejar la promesa sin manejar.
.catch(() => setCopied(false))
}
return { copied, copy }
}

View File

@@ -0,0 +1,185 @@
import type { CapacityCounts, RiskTone } from './card'
import { cn } from '../../lib/utils'
/**
* Indicador único de cupo y asistencia: una barra que junta "cuánta gente hay"
* con "cómo viene esa gente". Reemplaza al badge de baja asistencia y a la
* barrita de ocupación, que contaban dos cosas distintas y competían por el
* mismo lugar en la tarjeta.
*
* ── Qué se está midiendo ───────────────────────────────────────────────────
* `capacity` es el total contra el que se reparten los bloques, y `places` dice
* si ese total son lugares del cupo o la matrícula. Sin cupo declarado el
* grupo no tiene lugares, pero sí tiene gente en riesgo, así que la barra
* mide a los miembros (`places: false`) en vez de desaparecer.
*
* ── Dos modos ──────────────────────────────────────────────────────────────
* Con total chico (<= `SEGMENTED_CAPACITY_MAX`) hay un segmento por unidad y se
* ve exactamente qué posiciones están ocupadas y de qué color. Con total grande
* eso ya no se distingue, así que se pasa a bloques proporcionales. Ambos modos
* conservan la misma medida visual para que la lista se pueda escanear en
* vertical; importa la proporción, no que los grupos chicos queden diminutos.
*
* ── Lectura ────────────────────────────────────────────────────────────────
* El color solo no alcanza. El bloque va con `role="img"` y un `aria-label` que
* dice todo ("4 de 5 lugares ocupados: 2 en riesgo alto, 2 en atención"), que es
* lo que lee el lector de pantalla; y la tarjeta repite lo esencial en texto
* ("3 en riesgo alto · 4 en atención") abajo. Los tres niveles van siempre en el
* mismo orden, de peor a mejor, para que la barra se lea igual en todas las
* tarjetas y el ojo aprenda a escanearlas.
*
* ── Contraste ──────────────────────────────────────────────────────────────
* Todo sale de tokens, nada hardcodeado. Los rellenos miden 5.74:1 (rojo),
* 4.58:1 (ámbar) y 6.20:1 (azul) contra la tarjeta en tema claro, y 5.44, 10.15
* y 7.10:1 en oscuro: los tres pasan el 3:1 que pide WCAG para contenido no
* textual y el 4.5:1 que necesita la línea de texto que los acompaña. El rojo
* usa `danger-fg` y no `danger` justamente por eso: `danger` en tema claro da
* 3.35:1 y no alcanzaría como texto.
*
* El contorno de los lugares libres NO puede usar `border`, que en tema oscuro
* vale lo mismo que la tarjeta (1.00:1 y no se ve); usa `foreground` al 70%,
* que da 3.42:1 en claro y 3.55:1 en oscuro.
*/
type Level = keyof Pick<CapacityCounts, 'riesgoAlto' | 'atencion' | 'ok' | 'libres'>
/* De peor a mejor. Es el orden fijo de la barra: si mañana se agrega un nivel
entra en esta lista y no hay que tocar el componente. */
const LEVELS: Level[] = ['riesgoAlto', 'atencion', 'ok', 'libres']
const OCCUPIED_LEVELS: Level[] = ['riesgoAlto', 'atencion', 'ok']
/* El lugar libre no es un estado de la persona: es ausencia de gente. Por eso
es el único que no lleva relleno. */
const FILL: Record<Level, string> = {
riesgoAlto: 'bg-attendance-high',
atencion: 'bg-attendance-attention',
ok: 'bg-attendance-ok',
libres: '',
}
const OUTLINE = 'border-[1.5px] border-border dark:border-foreground/50'
/** Frase larga del `aria-label`: toda la información del bloque en una línea. */
export function capacityIndicatorLabel(
counts: CapacityCounts,
capacity: number,
places = true,
): string {
const { riesgoAlto, atencion, ok, libres } = counts
const ocupados = riesgoAlto + atencion + ok
const niveles = [
`${riesgoAlto} en riesgo alto`,
`${atencion} en atención`,
`${ok} en ok`,
].filter((parte, index) => {
const valor = [riesgoAlto, atencion, ok][index]
return valor > 0
})
const detalle = niveles.length > 0 ? `: ${niveles.join(', ')}` : ''
/* Sin cupo declarado no hay lugares que ocupar ni libres que contar: la
barra es un reparto de la matrícula y decirlo con esas palabras sería
inventar un cupo que el grupo no tiene. */
if (!places) {
return `${ocupados} ${ocupados === 1 ? 'miembro' : 'miembros'}${detalle}`
}
const libresTexto = libres > 0 ? `, ${libres} libre${libres === 1 ? '' : 's'}` : ''
return `${ocupados} de ${capacity} lugares ocupados${detalle}${libresTexto}`
}
export function AttendanceCapacityIndicator({
counts,
capacity,
segmented,
places = true,
className,
}: {
counts: CapacityCounts
/** Total contra el que se reparte la barra: el cupo, o la matrícula si el
* grupo no tiene cupo declarado. */
capacity: number
/** `true` cuando el total es chico y va un segmento por unidad. */
segmented: boolean
/** `false` cuando `capacity` son miembros y no lugares del cupo. */
places?: boolean
className?: string
}) {
const label = capacityIndicatorLabel(counts, capacity, places)
if (segmented) {
return (
<span
role="img"
aria-label={label}
title={label}
className={cn('flex h-3.5 min-w-0 items-center gap-1.5', className)}
>
{Array.from({ length: capacity }, (_, index) => (
<LevelSegment
key={index}
level={levelAt(counts, index)}
className="h-3.5 w-[50px] shrink-0"
/>
))}
</span>
)
}
return (
<span
role="img"
aria-label={label}
title={label}
className={cn(
'flex h-3.5 min-w-0 flex-1 items-stretch overflow-hidden rounded-full bg-surface',
OUTLINE,
className,
)}
>
{OCCUPIED_LEVELS.map((level) =>
counts[level] > 0 ? (
<span
key={level}
className={cn('h-full min-w-1.5', FILL[level])}
style={{ width: capacitySegmentWidth(counts[level], capacity) }}
/>
) : null,
)}
</span>
)
}
export function capacitySegmentWidth(count: number, capacity: number): string {
if (capacity <= 0) return '0%'
return `${((count / capacity) * 100).toFixed(4)}%`
}
/** Un segmento es una persona: el color es el del nivel de ese lugar. */
function LevelSegment({ level, className }: { level: Level; className?: string }) {
if (level === 'libres') return <span className={cn(OUTLINE, 'rounded-full', className)} />
return <span className={cn('rounded-full', FILL[level], className)} />
}
/** El lugar `index` lo ocupa la persona de peor nivel que todavía entra. */
function levelAt(counts: CapacityCounts, index: number): Level {
let restante = index
for (const level of LEVELS) {
if (restante < counts[level]) return level
restante -= counts[level]
}
return 'libres'
}
/** Color del texto según el peor nivel: la línea de estado no puede quedar
* desalineada con la barra. `danger-fg` y no `danger` porque el primero es la
* versión legible (5.7:1 en claro, 5.4:1 en oscuro) y el segundo se queda en
* 3.35:1 como texto. */
export const TONE_TEXT: Record<RiskTone, string> = {
riesgo_alto: 'text-danger-fg',
atencion: 'text-warning',
ok: 'text-secondary',
}

View File

@@ -1,82 +1,95 @@
import type { GroupDto, GroupRiskLevel } from '@gruperly/shared' import type { GroupListItem, GroupRiskSummary } from '@gruperly/shared'
import { useNavigate } from '@tanstack/react-router' import { Link } from '@tanstack/react-router'
import { CalendarClock, Users } from 'lucide-react' import { TriangleAlert } from 'lucide-react'
import { Badge, Button, Tooltip } from '../../components/ui' import { AttendanceCapacityIndicator } from './AttendanceCapacityIndicator'
import { BILLING_LABELS, formatPrice, formatSchedule } from '../../lib/format' import {
import { cn } from '../../lib/utils' SEGMENTED_CAPACITY_MAX,
import { RISK_HINT, RISK_LABELS } from './constants' alertTextFromMembers,
capacityCountsFromMembers,
membersFromGroupAndRisk,
type GroupMember,
} from './card'
export function GroupCard({ const CARD_CLASS_NAME =
group, 'block rounded-2xl border border-border/80 bg-surface px-7 py-5 shadow-none transition-[border-color,background-color,transform] duration-150 ease-out hover:border-accent/35 hover:bg-primary-soft/35 focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none active:scale-[0.995] active:bg-primary-soft/55'
riskLevel,
}: { export type GroupCardProps = {
group: GroupDto id?: string
riskLevel: GroupRiskLevel name?: string
}) { capacity?: number
const navigate = useNavigate() members?: GroupMember[]
const hasSchedule = (group.days?.length ?? 0) > 0 group?: GroupListItem
const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM' risk?: GroupRiskSummary | undefined
link?: boolean
}
export function GroupCard({ link = true, ...props }: GroupCardProps) {
const linkId = props.id ?? props.group?.id
if (link && linkId) {
return (
<Link
to="/groups/$groupId"
params={{ groupId: linkId }}
className={CARD_CLASS_NAME}
>
<GroupCardContent {...props} />
</Link>
)
}
return ( return (
<article className="rounded-xl border border-border bg-surface p-5 transition-all hover:border-accent/40"> <div className={CARD_CLASS_NAME}>
<div className="flex items-start justify-between gap-3"> <GroupCardContent {...props} />
<div className="min-w-0"> </div>
<h3 className="truncate text-base font-semibold text-primary">{group.name}</h3>
{group.description ? (
<p className="mt-0.5 truncate text-sm text-foreground/60">{group.description}</p>
) : null}
</div>
<div className="flex flex-col items-end gap-1.5">
{hasRisk ? (
// Mismo tooltip que en el detalle: el badge es corto y la
// explicación (abandono, no cobranza) la da el tooltip.
<Tooltip content={RISK_HINT} tooltipClassName="left-auto right-0">
<Badge variant={riskLevel === 'HIGH' ? 'danger' : 'warning'} className="gap-1.5">
<span
className={cn(
'size-2 rounded-full',
riskLevel === 'HIGH' ? 'bg-danger' : 'bg-warning',
)}
aria-hidden="true"
/>
{RISK_LABELS[riskLevel]}
</Badge>
</Tooltip>
) : null}
<Badge variant="success">Activo</Badge>
</div>
</div>
{hasSchedule ? (
<dl className="mt-4 space-y-2 text-sm">
<div className="flex items-center gap-2 text-foreground/70">
<CalendarClock className="size-4 shrink-0 text-accent" />
<span>{formatSchedule(group.days ?? [], group.time)}</span>
</div>
<div className="flex items-center gap-2 text-foreground/70">
<Users className="size-4 shrink-0 text-accent" />
<span>
Cupo {group.capacity ?? '—'} miembros
{group.price != null
? ` · ${formatPrice(group.price)}${group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''}`
: ''}
{group.dueDay != null ? ` · vence el día ${group.dueDay}` : ''}
</span>
</div>
</dl>
) : (
<p className="mt-4 text-sm text-foreground/50">Aún sin plan de cobro configurado.</p>
)}
<div className="mt-4 flex items-center justify-end gap-2 border-t border-border pt-3">
<Button
variant="outline"
size="sm"
onClick={() => void navigate({ to: `/groups/${group.id}` })}
>
Gestionar Miembros
</Button>
</div>
</article>
) )
} }
export function GroupCardContent(props: GroupCardProps) {
const name = props.name ?? props.group?.name ?? ''
const members =
props.members ??
(props.group ? membersFromGroupAndRisk(props.group, props.risk) : [])
const capacity =
props.capacity ??
props.group?.capacity ??
props.group?.attendeesCount ??
members.length
const counts = capacityCountsFromMembers(members, capacity)
const alertText = alertTextFromMembers(members)
const segmented = capacity <= SEGMENTED_CAPACITY_MAX
return (
<>
<h3 className="min-w-0 text-2xl leading-tight font-semibold tracking-tight text-primary">
{name}
</h3>
<div className="mt-5 flex min-w-0 items-center gap-3">
<AttendanceCapacityIndicator
counts={counts}
capacity={capacity}
segmented={segmented}
places={true}
/>
<span className="shrink-0 whitespace-nowrap text-lg tabular-nums text-secondary">
{members.length}/{capacity} {capacity === 1 ? 'miembro' : 'miembros'}
</span>
</div>
{alertText ? (
<p className="mt-3 flex min-w-0 items-center gap-2.5 text-base leading-6 font-medium text-[#8B1A1A] dark:text-[#f87171]">
<TriangleAlert
className="size-4 shrink-0 text-[#8B1A1A] dark:text-[#f87171]"
strokeWidth={2}
aria-hidden="true"
/>
<span className="min-w-0">{alertText}</span>
</p>
) : null}
</>
)
}

View File

@@ -1,9 +1,11 @@
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router' import { useNavigate } from '@tanstack/react-router'
import { Loader2, Plus } from 'lucide-react' import { CalendarPlus, Loader2, Plus } from 'lucide-react'
import { useState } from 'react'
import { Button } from '../../components/ui' import { Button } from '../../components/ui'
import { getGroups, getGroupsRiskOverview } from '../../lib/api' import { getGroups, getGroupsRiskOverview } from '../../lib/api'
import { GroupCard } from './GroupCard' import { GroupCard } from './GroupCard'
import { MOCK_TEST_CASES } from './card'
export function GroupsView() { export function GroupsView() {
const navigate = useNavigate() const navigate = useNavigate()
@@ -16,26 +18,49 @@ export function GroupsView() {
queryFn: getGroupsRiskOverview, queryFn: getGroupsRiskOverview,
}) })
const [showExamples, setShowExamples] = useState(() => {
if (typeof window !== 'undefined') {
return new URLSearchParams(window.location.search).get('mock') === 'true'
}
return false
})
const riskByGroup = new Map( const riskByGroup = new Map(
(riskQuery.data?.items ?? []).map((item) => [item.groupId, item.riskLevel]), (riskQuery.data?.items ?? []).map((item) => [item.groupId, item]),
) )
const hasGroups = groupsQuery.isSuccess && groupsQuery.data.data.length > 0
return ( return (
<section> <section>
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
<div> <h1 className="text-2xl font-bold text-primary">Grupos</h1>
<h1 className="text-2xl font-bold text-primary">Grupos</h1> <div className="flex items-center gap-2">
<p className="mt-2 text-sm text-foreground/60">Tus grupos de cobranza.</p> {!hasGroups && groupsQuery.isSuccess ? (
<Button
variant="outline"
size="sm"
className="h-11"
onClick={() => setShowExamples((prev) => !prev)}
>
{showExamples ? 'Ocultar ejemplos' : 'Ver ejemplos'}
</Button>
) : null}
<Button
variant="primary"
className="h-11"
onClick={() => void navigate({ to: '/groups/new' })}
>
<Plus className="size-4" />
Nuevo grupo
</Button>
</div> </div>
<Button variant="primary" onClick={() => void navigate({ to: '/groups/new' })}>
<Plus className="size-4" />
Crear
</Button>
</div> </div>
{groupsQuery.isPending ? ( {groupsQuery.isPending ? (
<div className="mt-8 flex items-center justify-center py-16"> <div className="mt-8 flex items-center justify-center py-16" role="status">
<Loader2 className="size-6 animate-spin text-foreground/40" /> <Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
<span className="sr-only">Cargando grupos</span>
</div> </div>
) : null} ) : null}
@@ -48,34 +73,57 @@ export function GroupsView() {
</div> </div>
) : null} ) : null}
{groupsQuery.isSuccess && groupsQuery.data.data.length === 0 ? ( {showExamples ? (
<div className="mt-8 rounded-xl border border-dashed border-border bg-surface px-4 py-12 text-center"> <div className="mt-6 grid gap-4">
<p className="font-medium text-primary">Todavía no tenés grupos</p> {MOCK_TEST_CASES.map((group) => (
<p className="mt-1 text-sm text-foreground/60"> <GroupCard key={group.id} {...group} />
Crea tu primer grupo para empezar a cobrar. ))}
</p>
<Button
variant="primary"
className="mt-5"
onClick={() => void navigate({ to: '/groups/new' })}
>
<Plus className="size-4" />
Crear tu primer grupo
</Button>
</div> </div>
) : null} ) : null}
{groupsQuery.isSuccess && groupsQuery.data.data.length > 0 ? ( {groupsQuery.isSuccess && groupsQuery.data.data.length === 0 && !showExamples ? (
/* Un ícono solo, con un punto focal, y el texto en secundario: la
pantalla vacía compite con la acción y no puede ganar. */
<div className="mt-8 rounded-xl bg-primary-soft px-5 py-12 text-center">
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg">
<CalendarPlus className="size-7" aria-hidden="true" />
</span>
<p className="mt-4 text-base font-semibold text-primary">Todavía no tenés grupos</p>
<p className="mx-auto mt-1.5 max-w-[30ch] text-sm leading-relaxed text-secondary">
Creá tu primer grupo y empezá a cobrar las cuotas de tus alumnos.
</p>
<div className="mt-6 flex items-center justify-center gap-3">
<Button
variant="outline"
className="h-11"
onClick={() => setShowExamples(true)}
>
Ver tarjetas de ejemplo
</Button>
<Button
variant="primary"
className="h-11"
onClick={() => void navigate({ to: '/groups/new' })}
>
<Plus className="size-4" />
Crear primer grupo
</Button>
</div>
</div>
) : null}
{hasGroups && !showExamples ? (
<div className="mt-6 grid gap-4"> <div className="mt-6 grid gap-4">
{groupsQuery.data.data.map((group) => ( {groupsQuery.data.data.map((group) => (
<GroupCard <GroupCard
key={group.id} key={group.id}
group={group} group={group}
riskLevel={riskByGroup.get(group.id) ?? 'NONE'} risk={riskByGroup.get(group.id)}
/> />
))} ))}
</div> </div>
) : null} ) : null}
</section> </section>
) )
} }

View File

@@ -0,0 +1,341 @@
import type { GroupListItem, GroupRiskSummary, UrgentMemberSummary } from '@gruperly/shared'
/* Derivaciones de la tarjeta del listado de grupos. La tarjeta no consulta
nada: decide acá qué se ve, con qué tono y con qué peso visual, para que el
JSX solo arme el layout y las reglas se puedan testear sueltas.
Los conteos por nivel y los miembros urgentes no se calculan en el cliente:
los trae `GET /groups-risk/overview`, que corre la misma función de dominio
(`getGroupAttendanceSummary` en packages/shared) que va a usar la sección de
seguimiento del Inicio. Acá solo se adapta esa respuesta a lo que la
tarjeta necesita pintar, y se decide cómo se lee. */
export type GroupLike = Pick<GroupListItem, 'attendeesCount' | 'capacity'>
/** A partir de este cupo el indicador deja de ser un segmento por lugar: con
* más de diez segmentos no se distinguen entre sí y pasan a ser bloques
* proporcionales. */
export const SEGMENTED_CAPACITY_MAX = 10
export type MemberStatus = 'high_risk' | 'attention' | 'ok'
export type GroupMember = {
id: string
name: string
status: MemberStatus
absences: number
}
export type CapacityCounts = {
riesgoAlto: number
atencion: number
ok: number
libres: number
}
/**
* Conteos derivados directamente de una lista de miembros y el cupo.
*/
export function capacityCountsFromMembers(
members: GroupMember[],
capacity: number,
): CapacityCounts {
let riesgoAlto = 0
let atencion = 0
let ok = 0
for (const m of members) {
if (m.status === 'high_risk') riesgoAlto++
else if (m.status === 'attention') atencion++
else ok++
}
const libres = Math.max(capacity - members.length, 0)
return {
riesgoAlto,
atencion,
ok,
libres,
}
}
/**
* Reglas de texto de alerta a partir de los miembros:
* - 1 en riesgo alto: "{Nombre}: {N} faltas" + (si hay atención > 0) " · {K} en atención"
* - 2 o más en riesgo alto: "{N} en riesgo alto" + (si hay atención > 0) " · {K} en atención"
* - 0 en riesgo alto pero atención > 0: "{K} en atención"
* - Ninguno: null
*/
export function alertTextFromMembers(members: GroupMember[]): string | null {
const highRisk = members.filter((m) => m.status === 'high_risk')
const attention = members.filter((m) => m.status === 'attention')
const kAtencion = attention.length > 0 ? ` · ${attention.length} en atención` : ''
if (highRisk.length === 1) {
const first = highRisk[0]
const nombre = firstName(first.name)
const faltas = `${first.absences} ${first.absences === 1 ? 'falta' : 'faltas'}`
return `${nombre}: ${faltas}${kAtencion}`
}
if (highRisk.length >= 2) {
return `${highRisk.length} en riesgo alto${kAtencion}`
}
if (attention.length > 0) {
return `${attention.length} en atención`
}
return null
}
/**
* Convierte un GroupListItem y GroupRiskSummary en una lista de GroupMember
* para unificar la representación interna.
*/
export function membersFromGroupAndRisk(
group: Pick<GroupListItem, 'attendeesCount' | 'capacity'>,
risk: GroupRiskSummary | undefined,
): GroupMember[] {
const members: GroupMember[] = []
const urgentes = risk?.urgentes ?? []
for (const u of urgentes) {
if (u.level === 'riesgo_alto') {
members.push({
id: u.attendeeId,
name: u.fullName,
status: 'high_risk',
absences: u.consecutiveAbsences,
})
} else if (u.level === 'atencion') {
members.push({
id: u.attendeeId,
name: u.fullName,
status: 'attention',
absences: u.consecutiveAbsences,
})
}
}
const currentHigh = members.filter((m) => m.status === 'high_risk').length
const remainingHigh = Math.max((risk?.riesgoAlto ?? 0) - currentHigh, 0)
for (let i = 0; i < remainingHigh; i++) {
members.push({
id: `high-risk-extra-${i}`,
name: `Alumno ${members.length + 1}`,
status: 'high_risk',
absences: 1,
})
}
const currentAttention = members.filter((m) => m.status === 'attention').length
const remainingAttention = Math.max((risk?.atencion ?? 0) - currentAttention, 0)
for (let i = 0; i < remainingAttention; i++) {
members.push({
id: `attention-extra-${i}`,
name: `Alumno ${members.length + 1}`,
status: 'attention',
absences: 0,
})
}
const remainingOk = Math.max(group.attendeesCount - members.length, 0)
for (let i = 0; i < remainingOk; i++) {
members.push({
id: `ok-${i}`,
name: `Alumno ${members.length + 1}`,
status: 'ok',
absences: 0,
})
}
return members
}
/**
* Conteos que consume el indicador de cupo y asistencia.
*
* `ok` es la diferencia, no un número de la API: el resumen de riesgo solo
* nombra a los que hay que mirar, y el resto de la matrícula es lo que queda
* bien. Se acota a 0 porque el resumen cuenta los miembros activos y la tarjeta
* muestra todos.
*
* Sin resumen todavía (o si la consulta falla) todos los miembros caen en `ok`.
* Es el estado en calma: el resumen puede seguir cargando y la tarjeta tiene
* que poder pintar igual.
*/
export function capacityCounts(group: GroupLike, risk: GroupRiskSummary | undefined): CapacityCounts {
const riesgoAlto = risk?.riesgoAlto ?? 0
const atencion = risk?.atencion ?? 0
const libres = group.capacity === null ? 0 : Math.max(group.capacity - group.attendeesCount, 0)
return {
riesgoAlto,
atencion,
ok: Math.max(group.attendeesCount - riesgoAlto - atencion, 0),
libres,
}
}
/** Tono de la línea de estado y del indicador: el peor nivel presente. */
export type RiskTone = 'riesgo_alto' | 'atencion' | 'ok'
export function riskTone(counts: CapacityCounts): RiskTone {
if (counts.riesgoAlto > 0) return 'riesgo_alto'
if (counts.atencion > 0) return 'atencion'
return 'ok'
}
export type StatusLine = {
text: string
tone: RiskTone
}
/**
* La cuarta fila de la tarjeta: qué está pasando con la asistencia.
*
* Con una sola persona en riesgo alto se muestra su nombre y cantidad de
* faltas. Con dos o más se resume por nivel. Cuando no hay nada que reportar,
* el componente omite esta línea por completo.
*/
export function statusLine(group: GroupLike, risk: GroupRiskSummary | undefined): StatusLine {
const counts = capacityCounts(group, risk)
const tone = riskTone(counts)
const urgentes = risk?.urgentes.filter((miembro) => miembro.level !== 'ok') ?? []
if (tone !== 'ok') {
const conNombre = counts.riesgoAlto === 1 ? namedHighRiskMember(urgentes, counts) : ''
return { text: conNombre || countedLevels(counts), tone }
}
if (risk?.asistencia != null) return { text: `Asistencia ${risk.asistencia}%`, tone: 'ok' }
return { text: 'Sin clases registradas', tone: 'ok' }
}
/**
* El total con el que se mide el indicador.
*
* Cuando el grupo no tiene cupo declarado la barra no desaparece: pasa a
* medir a la matrícula, un segmento (o bloque) por miembro, con los lugares
* libres en cero. Un grupo sin cupo no tiene "lugares libres" que mostrar, pero
* sí tiene gente en riesgo, y esa es justo la señal que la barra existe para
* comunicar. Lo que sí desaparece es la barra de un grupo vacío: sin miembros no
* hay nada que repartir.
*/
export function barCapacity(group: GroupLike): number {
return group.capacity ?? group.attendeesCount
}
/** ¿El indicador va con un segmento por lugar, o con bloques proporcionales? */
export function isSegmentedCapacity(capacity: number): boolean {
return capacity > 0 && capacity <= SEGMENTED_CAPACITY_MAX
}
/** "5/10 miembros", o "5 miembros" cuando el grupo no tiene cupo definido. */
export function occupancyLabel(group: GroupLike): string {
if (group.capacity === null) return membersLabel(group.attendeesCount)
return `${group.attendeesCount}/${group.capacity} ${group.capacity === 1 ? 'miembro' : 'miembros'}`
}
/** Nombra a la única persona en riesgo alto y agrega el total en atención. */
function namedHighRiskMember(
urgentes: UrgentMemberSummary[],
counts: CapacityCounts,
): string {
const urgente = urgentes.find((miembro) => miembro.level === 'riesgo_alto')
if (!urgente) return ''
const motivo = absenceReason(urgente)
if (!motivo) return ''
const nombre = `${firstName(urgente.fullName)}: ${motivo}`
return counts.atencion > 0 ? `${nombre} · ${counts.atencion} en atención` : nombre
}
/** Grupo grande: los conteos por nivel, y solo de los que hay algo que decir. */
function countedLevels(counts: CapacityCounts): string {
const partes: string[] = []
if (counts.riesgoAlto > 0) partes.push(`${counts.riesgoAlto} en riesgo alto`)
if (counts.atencion > 0) partes.push(`${counts.atencion} en atención`)
return partes.join(' · ')
}
/* El motivo que mejor explica por qué alguien está en la línea de estado, en el
orden en que la regla los considera: primero la racha de faltas (algo que se
está yendo), después el tiempo sin aparecer, y por último la asistencia. Con
una sola falta y al día se devuelve null: no alcanza para nombrar a nadie. */
function absenceReason(miembro: UrgentMemberSummary): string | null {
const { consecutiveAbsences: faltas, daysSinceLastAttendance: dias, attendanceRate: asistencia } = miembro
if (faltas > 0) return `${faltas} ${faltas === 1 ? 'falta' : 'faltas'}`
if (dias != null && dias > 0) return `${dias} ${dias === 1 ? 'día' : 'días'} sin venir`
if (asistencia != null && asistencia < 100) return `asistencia ${asistencia}%`
return null
}
/* Solo el primer nombre: en una línea de 360px "Sofía Ramírez: 4 faltas" no
entra, y entre dos personas con el mismo nombre la ficha las distingue. */
function firstName(fullName: string): string {
return fullName.trim().split(/\s+/)[0] || fullName
}
function membersLabel(count: number): string {
return count === 1 ? '1 miembro' : `${count} miembros`
}
/**
* Casos de prueba solicitados para verificación contra la imagen de referencia.
*/
export const MOCK_TEST_CASES = [
{
id: 'mock-tai-chi',
name: 'Tai Chi Martes',
capacity: 5,
members: [
{ id: 'tc-1', name: 'Sofía Ramírez', status: 'high_risk' as const, absences: 4 },
{ id: 'tc-2', name: 'Lucas Rossi', status: 'attention' as const, absences: 1 },
{ id: 'tc-3', name: 'Martín Paz', status: 'ok' as const, absences: 0 },
{ id: 'tc-4', name: 'Elena Gómez', status: 'ok' as const, absences: 0 },
],
},
{
id: 'mock-pilates',
name: 'Pilates Sábado',
capacity: 15,
members: [
{ id: 'p-1', name: 'Sofía Ramírez', status: 'high_risk' as const, absences: 4 },
{ id: 'p-2', name: 'Lucas Rossi', status: 'attention' as const, absences: 1 },
{ id: 'p-3', name: 'Mateo Díaz', status: 'attention' as const, absences: 1 },
...Array.from({ length: 9 }, (_, i) => ({
id: `p-ok-${i}`,
name: `Alumno ${i + 1}`,
status: 'ok' as const,
absences: 0,
})),
],
},
{
id: 'mock-natacion',
name: 'Natación Adultos',
capacity: 30,
members: [
{ id: 'n-1', name: 'Alumno 1', status: 'high_risk' as const, absences: 3 },
{ id: 'n-2', name: 'Alumno 2', status: 'high_risk' as const, absences: 2 },
{ id: 'n-3', name: 'Alumno 3', status: 'high_risk' as const, absences: 4 },
{ id: 'n-4', name: 'Alumno 4', status: 'attention' as const, absences: 1 },
{ id: 'n-5', name: 'Alumno 5', status: 'attention' as const, absences: 1 },
{ id: 'n-6', name: 'Alumno 6', status: 'attention' as const, absences: 2 },
{ id: 'n-7', name: 'Alumno 7', status: 'attention' as const, absences: 1 },
...Array.from({ length: 15 }, (_, i) => ({
id: `n-ok-${i}`,
name: `Alumno ${i + 8}`,
status: 'ok' as const,
absences: 0,
})),
],
},
]

View File

@@ -8,4 +8,8 @@ export const RISK_LABELS: Record<Exclude<GroupRiskLevel, 'NONE'>, string> = {
/* El badge solo dice "Riesgo moderado"; esta frase explica de qué habla /* El badge solo dice "Riesgo moderado"; esta frase explica de qué habla
(abandono de un miembro, no fraude ni cobranza) y vive en el tooltip. */ (abandono de un miembro, no fraude ni cobranza) y vive en el tooltip. */
export const RISK_HINT = export const RISK_HINT =
'Riesgo de abandono: probabilidad estimada de que algún miembro abandone el grupo.' 'Riesgo de abandono: probabilidad estimada de que algún miembro abandone el grupo.'
/* El motivo concreto ("4 miembros con faltas seguidas") ya no se calcula acá:
vive en `card.ts`, que además decide el peso visual del badge. Esto quedó
con la copia estática de la ficha del grupo. */

View File

@@ -1,106 +0,0 @@
import { Loader2 } from 'lucide-react'
import { cn } from '../../../lib/utils'
import { useAttendeeDetail } from './AttendeeDetailProvider'
type RateTone = 'good' | 'mid' | 'low' | 'none'
function rateTone(rate: number, totalMarked: number): RateTone {
if (totalMarked === 0) return 'none'
if (rate >= 75) return 'good'
if (rate >= 50) return 'mid'
return 'low'
}
const barTone: Record<RateTone, string> = {
good: 'bg-success',
mid: 'bg-warning',
low: 'bg-danger',
none: 'bg-border',
}
const valueTone: Record<RateTone, string> = {
good: 'text-success',
mid: 'text-warning',
low: 'text-danger',
none: 'text-foreground/40',
}
export function AttendeeAttendanceStats() {
const { attendeeStats, attendeeStatsPending, attendeeStatsFailed } = useAttendeeDetail()
if (attendeeStatsPending) {
return (
<div className="flex items-center justify-center rounded-xl border border-border bg-primary-soft/30 py-8">
<Loader2 className="size-5 animate-spin text-accent" />
</div>
)
}
if (attendeeStatsFailed || !attendeeStats) {
return (
<div className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
No pudimos cargar la asistencia de este participante.
</div>
)
}
const { presentCount, absentCount, excusedCount, totalMarked, attendanceRate } = attendeeStats
const tone = rateTone(attendanceRate, totalMarked)
return (
<div className="space-y-3 rounded-xl border border-border bg-primary-soft/30 p-3 sm:p-4">
<div className="flex items-end justify-between gap-3">
<div className="min-w-0">
<p className="text-[11px] font-medium uppercase tracking-wide text-foreground/50">
Asistencia
</p>
<p className="text-xs text-foreground/50">
{totalMarked > 0
? `Sobre ${totalMarked} clases registradas`
: 'Sin clases registradas todavía'}
</p>
</div>
<p className={cn('text-2xl font-bold tabular-nums', valueTone[tone])}>
{totalMarked > 0 ? `${attendanceRate}%` : '—'}
</p>
</div>
<div
className="h-1.5 overflow-hidden rounded-full bg-border"
role="presentation"
aria-hidden="true"
>
<div
className={cn(
'h-full rounded-full transition-[width] duration-500 ease-out',
barTone[tone],
)}
style={{ width: `${attendanceRate}%` }}
/>
</div>
<dl className="grid grid-cols-3 gap-1.5 sm:gap-2">
<StatCounter value={presentCount} label="Clases asistidas" valueClass="text-success" />
<StatCounter value={absentCount} label="Clases ausentes" valueClass="text-danger" />
<StatCounter value={excusedCount} label="Avisó ausencia" valueClass="text-warning" />
</dl>
</div>
)
}
function StatCounter({
value,
label,
valueClass,
}: {
value: number
label: string
valueClass: string
}) {
return (
<div className="min-w-0 rounded-lg bg-surface px-2 py-2">
<dt className="text-[11px] font-medium uppercase leading-tight text-foreground/50">{label}</dt>
<dd className={cn('text-lg font-bold tabular-nums', valueClass)}>{value}</dd>
</div>
)
}

View File

@@ -1,213 +0,0 @@
import { Link, useNavigate } from '@tanstack/react-router'
import {
ArrowLeft,
Copy,
Loader2,
Mail,
MessageCircle,
Phone,
ShieldCheck,
StickyNote,
UserMinus,
} from 'lucide-react'
import { Button } from '../../../components/ui'
import { formatPhoneDisplay } from '../../../lib/format'
import { AttendeeAttendanceStats } from './AttendeeAttendanceStats'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { DetailRow } from './DetailRow'
import { RemoveAttendeeModal } from './RemoveAttendeeModal'
export function AttendeeDetailPage() {
const {
groupId,
groupName,
attendee,
attendeePending,
attendeeFailed,
openRemoveModal,
isRemoveModalOpen,
closeRemoveModal,
confirmRemoveAttendee,
firstWaitlistEntry,
waitlistTotal,
waitlistPending,
isSubmittingRemoval,
copyAbsenceNotifyUrl,
} = useAttendeeDetail()
const navigate = useNavigate()
if (attendeePending) {
return (
<div className="flex items-center justify-center py-20">
<Loader2 className="size-8 animate-spin text-accent" />
</div>
)
}
if (attendeeFailed || !attendee) {
return (
<div className="rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
<h2 className="text-lg font-semibold">Participante no encontrado</h2>
<p className="mt-2 text-sm">No se pudo cargar la información de este participante.</p>
<Button
variant="outline"
className="mt-4"
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
>
Volver al grupo
</Button>
</div>
)
}
const absenceNotifyUrl = attendee.notifyToken
? `${window.location.origin}/report-absence/${attendee.notifyToken}`
: null
return (
<section className="animate-fade-in space-y-5">
<Link
to="/groups/$groupId"
params={{ groupId }}
className="hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
>
<ArrowLeft className="size-4" />
<span>Volver al grupo</span>
</Link>
<div className="flex items-center gap-3">
<div className="flex size-14 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xl font-bold text-accent">
{attendee.fullName.charAt(0).toUpperCase()}
</div>
<div className="min-w-0">
<h1 className="truncate text-xl font-bold text-primary">{attendee.fullName}</h1>
<p className="text-xs text-foreground/50">
{groupName ? `${groupName} · ` : ''}Incorporado el{' '}
{new Date(attendee.createdAt).toLocaleDateString('es-ES', {
day: 'numeric',
month: 'long',
year: 'numeric',
})}
</p>
</div>
</div>
<AttendeeAttendanceStats />
<div className="space-y-1 divide-y divide-border rounded-xl border border-border bg-primary-soft/30">
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
{attendee.phone ? (
<div className="flex items-center gap-2">
<span className="text-primary">{formatPhoneDisplay(attendee.phone)}</span>
<a
href={`https://wa.me/${attendee.phone.replace(/\D/g, '')}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
>
<MessageCircle className="size-3.5" />
<span>WhatsApp</span>
</a>
</div>
) : (
<span className="text-foreground/40">Sin teléfono</span>
)}
</DetailRow>
<DetailRow icon={<Mail className="size-4 text-accent" />} label="Email">
{attendee.email ? (
<a
href={`mailto:${attendee.email}`}
className="text-primary transition-colors hover:text-accent"
>
{attendee.email}
</a>
) : (
<span className="text-foreground/40">Sin email</span>
)}
</DetailRow>
{attendee.guardianName || attendee.guardianPhone ? (
<>
<DetailRow icon={<ShieldCheck className="size-4 text-accent" />} label="Responsable">
<span className="text-primary">
{attendee.guardianName || <span className="text-foreground/40">—</span>}
</span>
</DetailRow>
{attendee.guardianPhone ? (
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Tel. Responsable">
<div className="flex items-center gap-2">
<span className="text-primary">{formatPhoneDisplay(attendee.guardianPhone)}</span>
<a
href={`https://wa.me/${attendee.guardianPhone.replace(/\D/g, '')}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
>
<MessageCircle className="size-3.5" />
</a>
</div>
</DetailRow>
) : null}
</>
) : null}
<DetailRow icon={<StickyNote className="size-4 text-accent" />} label="Notas">
{attendee.notes ? (
<span className="text-xs leading-relaxed text-primary">{attendee.notes}</span>
) : (
<span className="text-foreground/40">Sin notas</span>
)}
</DetailRow>
</div>
{absenceNotifyUrl ? (
<div className="space-y-2 rounded-xl border border-border p-4">
<p className="text-xs font-medium text-foreground/60">Link para avisar ausencias</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 truncate rounded-lg bg-primary-soft px-2 py-1.5 text-xs text-primary">
{absenceNotifyUrl}
</code>
<Button variant="outline" size="sm" onClick={() => copyAbsenceNotifyUrl(absenceNotifyUrl)}>
<Copy className="size-3.5" />
Copiar
</Button>
</div>
{attendee.phone ? (
<a
href={`https://wa.me/${attendee.phone.replace(/\D/g, '')}?text=${encodeURIComponent(`Hola ${attendee.fullName.split(' ')[0]}, desde este link podés avisar tus ausencias en ${absenceNotifyUrl}`)}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
>
<MessageCircle className="size-3.5" />
<span>Enviar por WhatsApp</span>
</a>
) : null}
</div>
) : null}
<div className="border-t border-border pt-2">
<Button
variant="ghost"
onClick={openRemoveModal}
className="w-full gap-2 border border-danger/20 text-danger hover:bg-danger/10 hover:text-danger"
>
<UserMinus className="size-4" />
Quitar del grupo
</Button>
</div>
<RemoveAttendeeModal
attendee={isRemoveModalOpen ? attendee : null}
groupName={groupName}
firstWaitlistEntry={firstWaitlistEntry}
waitlistTotal={waitlistTotal}
isResolvingWaitlist={isRemoveModalOpen && waitlistPending}
isSubmitting={isSubmittingRemoval}
onCancel={closeRemoveModal}
onConfirm={confirmRemoveAttendee}
/>
</section>
)
}

View File

@@ -3,6 +3,7 @@ import type { ReactNode } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { import type {
AttendeeDto, AttendeeDto,
AttendeeListItem,
GroupDto, GroupDto,
GroupPreRegistrationDto, GroupPreRegistrationDto,
GroupWaitlistEntryDto, GroupWaitlistEntryDto,
@@ -29,9 +30,11 @@ export type ListSection = 'members' | 'pending'
type GroupDetailContextValue = { type GroupDetailContextValue = {
groupId: string groupId: string
group: GroupDto | undefined group: GroupDto | undefined
/** Nombre para el título grande: dato real, caché o "Grupo" mientras carga. */
groupTitle: string
groupQueryPending: boolean groupQueryPending: boolean
riskLevel: GroupRiskLevel riskLevel: GroupRiskLevel
attendees: AttendeeDto[] attendees: AttendeeListItem[]
attendeesTotal: number attendeesTotal: number
attendeesPending: boolean attendeesPending: boolean
waitlistEntries: GroupWaitlistEntryDto[] waitlistEntries: GroupWaitlistEntryDto[]
@@ -47,6 +50,9 @@ type GroupDetailContextValue = {
whatsappMessage: string whatsappMessage: string
searchFilter: string searchFilter: string
setSearchFilter: (value: string) => void setSearchFilter: (value: string) => void
/** La lista de miembros se reduce a quienes tienen el cobro vencido. */
overdueOnly: boolean
setOverdueOnly: (value: boolean) => void
listSection: ListSection listSection: ListSection
setListSection: (value: ListSection) => void setListSection: (value: ListSection) => void
isInviteModalOpen: boolean isInviteModalOpen: boolean
@@ -88,12 +94,14 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null) const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
const [selectedPreRegistration, setSelectedPreRegistration] = useState<GroupPreRegistrationDto | null>(null) const [selectedPreRegistration, setSelectedPreRegistration] = useState<GroupPreRegistrationDto | null>(null)
const [searchFilter, setSearchFilter] = useState('') const [searchFilter, setSearchFilter] = useState('')
const [overdueOnly, setOverdueOnly] = useState(false)
// La búsqueda pertenece a la vista que la abrió: al cambiar de pestaña se // Los controles de la lista pertenecen a la vista que los abrió: al cambiar de
// limpia para no heredar un filtro sin coincidencias. // pestaña se limpian para no heredar un filtro sin coincidencias.
const setListSection = (value: ListSection) => { const setListSection = (value: ListSection) => {
setListSectionState(value) setListSectionState(value)
setSearchFilter('') setSearchFilter('')
setOverdueOnly(false)
} }
const groupQuery = useQuery({ const groupQuery = useQuery({
@@ -283,9 +291,16 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer') window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer')
} }
// El título grande va siempre, incluso cargando: es lo que da altura a la
// barra immersive y evita que el layout salte. Al llegar desde la ficha del
// grupo el nombre ya está en caché; en la primera carga cae a "Grupo".
const cachedGroupName = queryClient.getQueryData<GroupDto>(['group', groupId])?.name
const groupTitle = group?.name ?? cachedGroupName ?? 'Grupo'
const value: GroupDetailContextValue = { const value: GroupDetailContextValue = {
groupId, groupId,
group, group,
groupTitle,
groupQueryPending: groupQuery.isPending, groupQueryPending: groupQuery.isPending,
riskLevel: riskOverviewQuery.data?.items.find((item) => item.groupId === groupId)?.riskLevel ?? 'NONE', riskLevel: riskOverviewQuery.data?.items.find((item) => item.groupId === groupId)?.riskLevel ?? 'NONE',
attendees, attendees,
@@ -304,6 +319,8 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
whatsappMessage, whatsappMessage,
searchFilter, searchFilter,
setSearchFilter, setSearchFilter,
overdueOnly,
setOverdueOnly,
listSection, listSection,
setListSection, setListSection,
isInviteModalOpen, isInviteModalOpen,

View File

@@ -23,31 +23,34 @@ export function GroupDetailView() {
} = useGroupDetail() } = useGroupDetail()
const navigate = useNavigate() const navigate = useNavigate()
if (groupQueryPending) {
return (
<div className="flex items-center justify-center py-20">
<Loader2 className="size-8 animate-spin text-accent" />
</div>
)
}
if (!group) {
return (
<div className="rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
<h2 className="text-lg font-semibold">Grupo no encontrado</h2>
<p className="mt-2 text-sm">No se pudo cargar la información de este grupo.</p>
<Button variant="outline" className="mt-4" onClick={() => void navigate({ to: '/groups' })}>
Volver a Grupos
</Button>
</div>
)
}
return ( return (
<section className="animate-fade-in space-y-5 sm:space-y-6"> <section className="animate-fade-in space-y-5 sm:space-y-6">
{/* El título grande va siempre, incluso cargando: es lo que da altura a
la barra immersive y evita que el layout salte cuando llegan los datos. */}
<GroupHeader /> <GroupHeader />
<GroupInfoCard />
<MembersWaitlistSection /> {groupQueryPending ? (
<div className="flex items-center justify-center py-20">
<Loader2 className="size-8 animate-spin text-accent" />
</div>
) : !group ? (
<div className="rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
<h2 className="text-lg font-semibold">Grupo no encontrado</h2>
<p className="mt-2 text-sm">No se pudo cargar la información de este grupo.</p>
<Button
variant="outline"
className="mt-4"
onClick={() => void navigate({ to: '/groups' })}
>
Volver a Grupos
</Button>
</div>
) : (
<>
<GroupInfoCard />
<MembersWaitlistSection />
</>
)}
<InviteLinkModal /> <InviteLinkModal />
<RemoveAttendeeModal <RemoveAttendeeModal

View File

@@ -9,6 +9,7 @@ import { useGroupDetail } from './GroupDetailProvider'
export function GroupHeader() { export function GroupHeader() {
const { const {
group, group,
groupTitle,
groupId, groupId,
riskLevel, riskLevel,
openInviteModal, openInviteModal,
@@ -29,10 +30,14 @@ export function GroupHeader() {
const isEmptyGroup = const isEmptyGroup =
!listLoading && attendeesTotal === 0 && preRegistrationsTotal === 0 && waitlistTotal === 0 !listLoading && attendeesTotal === 0 && preRegistrationsTotal === 0 && waitlistTotal === 0
// Sin grupo todavía solo se pinta el título: los badges, la descripción y las
// acciones necesitan datos, y mostrarlos a medias daría un header parpadeante.
const hasGroup = Boolean(group)
return ( return (
<div> <div>
<LargeTitle <LargeTitle
title={group?.name ?? ''} title={groupTitle}
leading={ leading={
<Link <Link
to="/groups" to="/groups"
@@ -45,31 +50,33 @@ export function GroupHeader() {
> >
{/* Los estados cuelgan del título y no de la barra: en la barra {/* Los estados cuelgan del título y no de la barra: en la barra
colapsada solo va el nombre, que es lo que se usa para orientarse. */} colapsada solo va el nombre, que es lo que se usa para orientarse. */}
<div className="mt-3 flex flex-wrap items-center gap-2"> {hasGroup ? (
<Badge variant="success" className="gap-1.5 text-[11px]"> <div className="mt-3 flex flex-wrap items-center gap-2">
<span className="size-1.5 rounded-full bg-success" aria-hidden="true" /> <Badge variant="success" className="gap-1.5 text-[11px]">
Activo <span className="size-1.5 rounded-full bg-success" aria-hidden="true" />
</Badge> Activo
{hasRisk ? ( </Badge>
// El badge no puede llevar texto largo sin ensuciar el header: la {hasRisk ? (
// explicación (riesgo de abandono, no de cobranza) vive en el tooltip. // El badge no puede llevar texto largo sin ensuciar el header: la
<Tooltip content={RISK_HINT}> // explicación (riesgo de abandono, no de cobranza) vive en el tooltip.
<Badge <Tooltip content={RISK_HINT}>
variant={riskLevel === 'HIGH' ? 'danger' : 'warning'} <Badge
className="gap-1.5 text-[11px]" variant={riskLevel === 'HIGH' ? 'danger' : 'warning'}
> className="gap-1.5 text-[11px]"
<span >
className={cn( <span
'size-1.5 rounded-full', className={cn(
riskLevel === 'HIGH' ? 'bg-danger' : 'bg-warning', 'size-1.5 rounded-full',
)} riskLevel === 'HIGH' ? 'bg-danger' : 'bg-warning',
aria-hidden="true" )}
/> aria-hidden="true"
{RISK_LABELS[riskLevel]} />
</Badge> {RISK_LABELS[riskLevel]}
</Tooltip> </Badge>
) : null} </Tooltip>
</div> ) : null}
</div>
) : null}
{group?.description ? ( {group?.description ? (
<p className="mt-2 text-pretty text-sm leading-relaxed text-foreground/80"> <p className="mt-2 text-pretty text-sm leading-relaxed text-foreground/80">
@@ -78,47 +85,52 @@ export function GroupHeader() {
) : null} ) : null}
</LargeTitle> </LargeTitle>
<div className="mt-4 grid grid-cols-2 gap-2.5 sm:mt-5 sm:flex sm:flex-wrap sm:items-center sm:justify-end sm:gap-2.5"> {hasGroup ? (
{/* `h-11` (44px) para todos: objetivo táctil mínimo. */} // Una sola fila en mobile: el primario toma el ancho que sobra y las dos
{!isEmptyGroup ? ( // acciones de apoyo se pliegan a iconos de 44px. En sm+ recuperan el
// Un solo primario por pantalla: "Agregar" encabeza la jerarquía y // texto porque hay ancho de sobra y el rótulo hace más claro el destino.
// las acciones de apoyo quedan debajo en outline. <div className="mt-4 flex items-center gap-2.5 sm:mt-5 sm:justify-end">
<Button {!isEmptyGroup ? (
variant="primary" // Un solo primario por pantalla: "Agregar" encabeza la jerarquía y
onClick={() => // las acciones de apoyo quedan al lado, en outline.
void navigate({ to: '/groups/$groupId/attendees/new', params: { groupId } }) <Button
} variant="primary"
className="col-span-2 h-11 w-full justify-center sm:w-auto" onClick={() =>
> void navigate({ to: '/groups/$groupId/attendees/new', params: { groupId } })
<UserPlus className="size-4" /> }
<span>Agregar miembro</span> className="h-11 flex-1 justify-center sm:flex-none sm:w-auto"
</Button> >
) : null} <UserPlus className="size-4" />
<Button <span>Agregar miembro</span>
variant="outline" </Button>
onClick={() => void navigate({ to: '/groups/$groupId/analytics', params: { groupId } })} ) : null}
className={cn(
'h-11 w-full justify-center border-border sm:w-auto',
// En grupo vacío es la única acción del header: ocupa la fila entera.
isEmptyGroup && 'col-span-2',
)}
>
<BarChart3 className="size-4 text-accent" />
<span>Estadísticas</span>
</Button>
{!isEmptyGroup ? (
<Button <Button
variant="outline" variant="outline"
onClick={openInviteModal} onClick={() => void navigate({ to: '/groups/$groupId/analytics', params: { groupId } })}
className="h-11 w-full justify-center border-border sm:w-auto" aria-label="Estadísticas"
className={cn(
'h-11 shrink-0 justify-center border-border',
// En grupo vacío es la única acción del header: ocupa la fila entera.
isEmptyGroup && 'w-full sm:w-auto',
!isEmptyGroup && 'w-11 sm:w-auto sm:px-4',
)}
> >
<Share2 className="size-4 text-accent" /> <BarChart3 className="size-4 text-accent" />
<span> <span className="hidden sm:inline">Estadísticas</span>
Compartir <span className="hidden sm:inline">Link</span>
</span>
</Button> </Button>
) : null} {!isEmptyGroup ? (
</div> <Button
variant="outline"
onClick={openInviteModal}
aria-label="Compartir enlace"
className="h-11 w-11 shrink-0 justify-center border-border sm:w-auto sm:px-4"
>
<Share2 className="size-4 text-accent" />
<span className="hidden sm:inline">Compartir</span>
</Button>
) : null}
</div>
) : null}
</div> </div>
) )
} }

View File

@@ -1,4 +1,4 @@
import { CalendarClock, Users } from 'lucide-react' import { CalendarClock, CircleDollarSign, Users } from 'lucide-react'
import { import {
formatBillingMeta, formatBillingMeta,
formatPrice, formatPrice,
@@ -88,9 +88,7 @@ export function GroupInfoCard() {
</div> </div>
<div className={cn(CELL_CLASS, 'md:pl-6')}> <div className={cn(CELL_CLASS, 'md:pl-6')}>
<div className="mt-0.5 flex size-5 shrink-0 items-center justify-center text-sm font-bold leading-none text-accent"> <CircleDollarSign className="mt-0.5 size-5 shrink-0 text-accent" />
$
</div>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className={LABEL_CLASS}>Cobro</p> <p className={LABEL_CLASS}>Cobro</p>
<p className="mt-0.5 text-base font-semibold tabular-nums text-primary"> <p className="mt-0.5 text-base font-semibold tabular-nums text-primary">

View File

@@ -0,0 +1,109 @@
import type { AttendeeListItem, AttendanceStatus } from '@gruperly/shared'
import { Link } from '@tanstack/react-router'
import { Check } from 'lucide-react'
import { cn } from '../../../lib/utils'
import { dotClass, statusLabel } from '../analytics/format'
import { useGroupDetail } from './GroupDetailProvider'
import {
type PaymentState,
paymentStateLabel,
resolvePaymentState,
summarizeAttendance,
} from './member-row'
/* Solo lo excepcional se pinta. "Al día" queda en el tono base y con un check
para que el estado se lea sin depender del color; vencido es el único que
sube de peso. */
const PAYMENT_TONE: Record<PaymentState['kind'], string> = {
settled: 'text-foreground',
dueSoon: 'font-medium text-warning',
overdue: 'font-semibold text-danger',
}
function PaymentLabel({ state }: { state: PaymentState }) {
return (
<span className={cn('flex shrink-0 items-center gap-1 text-xs', PAYMENT_TONE[state.kind])}>
{state.kind === 'settled' ? (
<Check className="size-3 shrink-0" aria-hidden="true" />
) : null}
{paymentStateLabel(state)}
</span>
)
}
function AttendanceStrip({ recent }: { recent: AttendanceStatus[] }) {
const summary = summarizeAttendance(recent)
if (summary.recorded === 0) {
return <p className="mt-0.5 text-xs text-foreground">{summary.label}</p>
}
return (
<div className="mt-0.5 flex items-center gap-2">
{/* Cada punto lleva su propio nombre accesible: el color solo es el
refuerzo visual, no la única forma de saber qué pasó. */}
<span className="flex items-center gap-1">
{summary.dots.map((status, index) => (
<span
key={index}
role="img"
aria-label={`Clase ${index + 1} de ${summary.recorded}: ${statusLabel(status).toLowerCase()}`}
className={cn('size-2 rounded-full', dotClass(status))}
/>
))}
</span>
<span className="text-xs text-foreground">{summary.label}</span>
</div>
)
}
function MemberRow({
attendee,
groupId,
}: {
attendee: AttendeeListItem
groupId: string
}) {
const paymentState = resolvePaymentState(attendee.payment)
return (
<Link
to="/groups/$groupId/attendees/$attendeeId"
params={{ groupId, attendeeId: attendee.id }}
// `min-h-14` (56px) es el piso táctil cómodo. La fila entera es el link, así
// que no hace falta chevron ni fila con tabIndex: hereda el rol y el
// teclado del <a>, y además sirve el href real al abrir en otra pestaña.
className={cn(
'flex min-h-14 items-center border-b border-foreground/10 px-3 py-2.5',
'transition-colors duration-150 hover:bg-surface/60 active:bg-surface',
'focus-visible:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent',
)}
>
<div className="min-w-0 flex-1">
<div className="flex items-baseline justify-between gap-3">
<span className="min-w-0 truncate font-medium text-primary" title={attendee.fullName}>
{attendee.fullName}
</span>
{paymentState ? <PaymentLabel state={paymentState} /> : null}
</div>
<AttendanceStrip recent={attendee.recentAttendance} />
</div>
</Link>
)
}
export function MembersList({ attendees }: { attendees: AttendeeListItem[] }) {
// El groupId se lee una vez y se pasa: suscribir cada fila al contexto entero
// hace que un cambio de estado del provider re-renderice N filas sin motivo.
const { groupId } = useGroupDetail()
return (
<ul>
{attendees.map((attendee) => (
<li key={attendee.id}>
<MemberRow attendee={attendee} groupId={groupId} />
</li>
))}
</ul>
)
}

View File

@@ -1,74 +0,0 @@
import type { AttendeeDto } from '@gruperly/shared'
import { useNavigate } from '@tanstack/react-router'
import { ChevronRight } from 'lucide-react'
import { formatPhoneDisplay } from '../../../lib/format'
import { useGroupDetail } from './GroupDetailProvider'
export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) {
const { groupId } = useGroupDetail()
const navigate = useNavigate()
const openAttendee = (attendeeId: string) => {
void navigate({ to: '/groups/$groupId/attendees/$attendeeId', params: { groupId, attendeeId } })
}
return (
<table className="w-full table-fixed text-left text-sm">
<thead>
<tr className="border-b border-border/70 text-xs font-semibold text-foreground/80">
<th scope="col" className="w-[47%] px-2 pb-1.5">Nombre</th>
<th scope="col" className="px-2 pb-1.5">Teléfono</th>
<th scope="col" className="w-8 px-1 pb-1.5">
<span className="sr-only">Detalle</span>
</th>
</tr>
</thead>
<tbody>
{attendees.map((attendee) => (
<tr
key={attendee.id}
tabIndex={0}
className="group cursor-pointer border-b border-border/70 transition-colors last:border-b-0 hover:bg-primary-soft/60 focus-visible:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
onClick={() => openAttendee(attendee.id)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
openAttendee(attendee.id)
}
}}
>
<td className="px-2 py-2">
<div className="flex min-w-0 items-center gap-2">
<div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">
{attendee.fullName.charAt(0).toUpperCase()}
</div>
{/* `truncate` solo recorta lo pintado: el texto completo sigue en
el DOM para lectores de pantalla, y `title` lo muestra al hover. */}
<span
className="min-w-0 truncate font-semibold text-primary"
title={attendee.fullName}
>
{attendee.fullName}
</span>
</div>
</td>
{/* El nombre manda; el teléfono es un dato secundario: un nivel
más abajo en la escala de color, en un tamaño menor. */}
<td className="min-w-0 px-2 py-2 text-xs text-foreground/70">
{attendee.phone ? (
<span className="block truncate tabular-nums" title={attendee.phone}>
{formatPhoneDisplay(attendee.phone)}
</span>
) : (
<span className="text-foreground/60">—</span>
)}
</td>
<td className="w-8 px-1 py-2 text-foreground/50">
<ChevronRight className="ml-auto size-4 transition-colors group-hover:text-accent" />
</td>
</tr>
))}
</tbody>
</table>
)
}

View File

@@ -1,22 +1,70 @@
import { useNavigate } from '@tanstack/react-router' import { useNavigate } from '@tanstack/react-router'
import { Loader2, Plus, Share2, Users } from 'lucide-react' import { Loader2, Plus, Share2, Users, X } from 'lucide-react'
import { Button } from '../../../components/ui' import { Button } from '../../../components/ui'
import { cn } from '../../../lib/utils'
import { useGroupDetail } from './GroupDetailProvider' import { useGroupDetail } from './GroupDetailProvider'
import { MembersTable } from './MembersTable' import { MembersList } from './MembersList'
import { byFullName, isOverdue, resolvePaymentState } from './member-row'
function OverdueFilter({ count }: { count: number }) {
const { overdueOnly, setOverdueOnly } = useGroupDetail()
return (
<div className="px-3 pb-1.5">
<button
type="button"
aria-pressed={overdueOnly}
onClick={() => setOverdueOnly(!overdueOnly)}
className={cn(
// min-h-11 (44px): objetivo táctil mínimo, igual que los chips de sección.
'inline-flex min-h-11 items-center gap-1.5 rounded-full border px-3.5 text-xs font-semibold',
'transition-[background-color,color,border-color,box-shadow] duration-150',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-primary-soft',
overdueOnly
? 'border-transparent bg-danger-soft text-danger'
: 'border-border bg-surface text-foreground hover:border-danger/40 hover:text-danger',
)}
>
{/* La ✕ solo aparece con el filtro puesto: es la señal de que tocarlo
lo saca, sin tener que decirlo. */}
{overdueOnly ? <X className="size-3.5 shrink-0" aria-hidden="true" /> : null}
<span className="whitespace-nowrap">{count} con pago vencido</span>
</button>
</div>
)
}
export function MembersView() { export function MembersView() {
const { groupId, attendees, attendeesPending, searchFilter, openInviteModal } = useGroupDetail() const {
groupId,
attendees,
attendeesPending,
searchFilter,
overdueOnly,
openInviteModal,
} = useGroupDetail()
const navigate = useNavigate() const navigate = useNavigate()
const query = searchFilter.trim().toLowerCase() const query = searchFilter.trim().toLowerCase()
const filtered = query // El teléfono no se muestra en la fila, pero sigue siendo una vía de búsqueda:
? attendees.filter( // es como la mayoría conoce a los alumnos del grupo.
(a) => const matchesQuery = (attendee: (typeof attendees)[number]) =>
a.fullName.toLowerCase().includes(query) || !query ||
(a.phone && a.phone.includes(query)) || attendee.fullName.toLowerCase().includes(query) ||
(a.email && a.email.toLowerCase().includes(query)), (attendee.phone != null && attendee.phone.includes(query)) ||
) (attendee.email != null && attendee.email.toLowerCase().includes(query))
: attendees
const overdueCount = attendees.filter((attendee) =>
isOverdue(resolvePaymentState(attendee.payment)),
).length
const visible = attendees
.filter((attendee) => !overdueOnly || isOverdue(resolvePaymentState(attendee.payment)))
.filter(matchesQuery)
// Orden alfabético fijo: si se ordenara por cobro o asistencia las filas
// saltarían de lugar cada vez que alguien paga o falta, y el nombre es la
// única columna estable de la lista.
.sort(byFullName)
if (attendeesPending) { if (attendeesPending) {
return ( return (
@@ -28,7 +76,7 @@ export function MembersView() {
if (attendees.length === 0) { if (attendees.length === 0) {
return ( return (
<div className="rounded-lg bg-primary-soft/50 px-4 py-10 text-center"> <div className="bg-surface px-4 py-10 text-center">
<Users className="mx-auto mb-2 size-10 text-foreground/40" /> <Users className="mx-auto mb-2 size-10 text-foreground/40" />
<p className="text-sm font-semibold text-primary"> <p className="text-sm font-semibold text-primary">
Todavía no hay miembros en este grupo Todavía no hay miembros en este grupo
@@ -40,7 +88,7 @@ export function MembersView() {
<div className="mt-4 flex flex-col gap-2.5 sm:flex-row sm:items-center sm:justify-center sm:gap-3"> <div className="mt-4 flex flex-col gap-2.5 sm:flex-row sm:items-center sm:justify-center sm:gap-3">
<Button variant="outline" onClick={openInviteModal} className="h-11 w-full sm:w-auto"> <Button variant="outline" onClick={openInviteModal} className="h-11 w-full sm:w-auto">
<Share2 className="size-4" /> <Share2 className="size-4" />
Compartir Enlace Compartir enlace
</Button> </Button>
<Button <Button
variant="primary" variant="primary"
@@ -50,20 +98,34 @@ export function MembersView() {
className="h-11 w-full sm:w-auto" className="h-11 w-full sm:w-auto"
> >
<Plus className="size-4" /> <Plus className="size-4" />
Agregar Miembros Agregar miembros
</Button> </Button>
</div> </div>
</div> </div>
) )
} }
if (filtered.length === 0) { const filterBar = overdueCount > 0 ? <OverdueFilter count={overdueCount} /> : null
if (visible.length === 0) {
// El filtro de vencidos nunca queda vacío por sí solo (el chip no se muestra
// si no hay vencidos), así que un vacío acá es siempre la búsqueda.
return ( return (
<div className="py-8 text-center text-sm text-foreground/80"> <>
No se encontraron miembros que coincidan con la búsqueda. {filterBar}
</div> <div className="px-4 py-8 text-center text-sm text-foreground">
{overdueOnly
? 'Ningún miembro con pago vencido coincide con la búsqueda.'
: 'No se encontraron miembros que coincidan con la búsqueda.'}
</div>
</>
) )
} }
return <MembersTable attendees={filtered} /> return (
<>
{filterBar}
<MembersList attendees={visible} />
</>
)
} }

View File

@@ -1,46 +1,58 @@
import { Search } from 'lucide-react' import { Search } from 'lucide-react'
import { Input } from '../../../components/ui' import { Input } from '../../../components/ui'
import { MEMBER_SEARCH_MIN } from './constants'
import { useGroupDetail } from './GroupDetailProvider' import { useGroupDetail } from './GroupDetailProvider'
import { MembersView } from './MembersView' import { MembersView } from './MembersView'
import { PendingView } from './PendingView' import { PendingView } from './PendingView'
import { SectionChips } from './SectionChips' import { SectionChips } from './SectionChips'
export function MembersWaitlistSection() { export function MembersWaitlistSection() {
const { listSection, searchFilter, setSearchFilter } = useGroupDetail() const { listSection, searchFilter, setSearchFilter, attendeesTotal } = useGroupDetail()
// Con pocos miembros el buscador es ruido: se alcanza con recorrer la lista.
// Se quita del árbol en vez de esconderse, para no dejar un hueco en la fila.
// En Pendientes no cambia nada: ahí el volumen es el que es.
const showSearch = listSection === 'pending' || attendeesTotal > MEMBER_SEARCH_MIN
return ( return (
// Radios concéntricos: `rounded-2xl` (16px) con `p-2` (8px) deja a las // Una sola superficie: la lista va directo sobre el lavado, como la info
// superficies interiores un radio de 16 - 8 = 8px, o sea `rounded-lg`. // card de arriba, en vez de anidarse en una caja más clara. La separación
// Sin bordes: el lavado `bg-primary-soft` separa la sección del fondo. // entre controles y datos la dan los propios divisores de fila, el tono
<div className="rounded-2xl bg-primary-soft p-2"> // propio del input y el borde de los chips; una caja intermedia solo
<div className="space-y-2 p-2 sm:p-3"> // sumaba un nivel de contención y padding horizontal.
// `overflow-hidden` recorta el hover de las filas y el borde inferior
// contra el radio del panel: las filas son full-bleed.
<div className="overflow-hidden rounded-2xl bg-primary-soft">
<div className="space-y-2 p-3">
<div className="flex flex-col gap-2.5 lg:flex-row lg:items-center lg:justify-between"> <div className="flex flex-col gap-2.5 lg:flex-row lg:items-center lg:justify-between">
<SectionChips /> <SectionChips />
<div className="relative w-full sm:w-72 lg:shrink-0"> {showSearch ? (
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/70" /> <div className="relative w-full sm:w-72 lg:shrink-0">
<Input <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/70" />
placeholder="Buscar por nombre o teléfono..." <Input
value={searchFilter} placeholder="Buscar por nombre o teléfono..."
onChange={(e) => setSearchFilter(e.target.value)} value={searchFilter}
aria-label="Buscar en el listado" onChange={(e) => setSearchFilter(e.target.value)}
className="h-11 rounded-lg border-transparent pl-9 shadow-xs placeholder:text-foreground/80" aria-label="Buscar en el listado"
/> className="h-11 rounded-lg border-transparent pl-9 shadow-xs"
</div> />
</div>
) : null}
</div> </div>
{/* Copia de apoyo: un solo bloque, ancho acotado y sin competir con {/* Solo Pendientes lleva copia de apoyo: explica la diferencia entre
los datos. Explica la diferencia entre ambos estados. */} pre-inscripción y lista de espera, que no se deduce de los nombres.
<p className="max-w-2xl text-xs leading-snug text-foreground/80"> En Miembros los rótulos de columna ya dicen todo. */}
{listSection === 'members' {listSection === 'pending' ? (
? 'Listado de todos los miembros incorporados al grupo.' <p className="max-w-2xl text-xs leading-snug text-foreground/80">
: 'Pre-inscripciones que esperan tu aprobación y personas en lista de espera por un cupo libre.'} Pre-inscripciones que esperan tu aprobación y personas en lista de espera por un cupo
</p> libre.
</p>
) : null}
</div> </div>
<div className="rounded-lg bg-surface p-1 shadow-xs sm:p-2"> {listSection === 'members' ? <MembersView /> : <PendingView />}
{listSection === 'members' ? <MembersView /> : <PendingView />}
</div>
</div> </div>
) )
} }

View File

@@ -37,7 +37,10 @@ export function PendingView() {
if (!hasAnyEntry && !query) { if (!hasAnyEntry && !query) {
return ( return (
<div className="rounded-lg bg-primary-soft/50 px-4 py-10 text-center"> // Full-bleed y sin radio propio: el `overflow-hidden` del panel lo recorta
// contra la silueta redondeada. `surface` sobre `primary-soft` hunde el
// bloque; con el lavado anterior se camuflaba.
<div className="bg-surface px-4 py-10 text-center">
<Inbox className="mx-auto mb-2 size-10 text-foreground/40" /> <Inbox className="mx-auto mb-2 size-10 text-foreground/40" />
<p className="text-sm font-semibold text-primary">No hay pendientes</p> <p className="text-sm font-semibold text-primary">No hay pendientes</p>
<p className="mx-auto mt-1 max-w-sm text-sm text-foreground/80"> <p className="mx-auto mt-1 max-w-sm text-sm text-foreground/80">
@@ -47,7 +50,7 @@ export function PendingView() {
<div className="mt-4 flex justify-center"> <div className="mt-4 flex justify-center">
<Button variant="primary" onClick={openInviteModal} className="h-11 w-full sm:w-auto"> <Button variant="primary" onClick={openInviteModal} className="h-11 w-full sm:w-auto">
<Share2 className="size-4" /> <Share2 className="size-4" />
Compartir Enlace Compartir enlace
</Button> </Button>
</div> </div>
</div> </div>
@@ -94,7 +97,7 @@ export function PendingView() {
return ( return (
<section key={section.key} aria-labelledby={titleId}> <section key={section.key} aria-labelledby={titleId}>
<div className="flex items-center gap-2 border-b border-border/70 px-3 pb-1.5 pt-2"> <div className="flex items-center gap-2 border-b border-foreground/10 px-3 pb-1.5 pt-2">
<Icon className="size-4 shrink-0 text-accent" aria-hidden="true" /> <Icon className="size-4 shrink-0 text-accent" aria-hidden="true" />
<h3 <h3
id={titleId} id={titleId}
@@ -108,7 +111,7 @@ export function PendingView() {
'ml-auto inline-flex items-center justify-center rounded-full px-1.5 py-0.5 text-[10px] font-bold leading-none tabular-nums', 'ml-auto inline-flex items-center justify-center rounded-full px-1.5 py-0.5 text-[10px] font-bold leading-none tabular-nums',
section.attention section.attention
? 'bg-warning-soft text-warning' ? 'bg-warning-soft text-warning'
: 'bg-primary-soft text-foreground/70', : 'bg-surface text-foreground/70',
)} )}
> >
{section.count} {section.count}

View File

@@ -9,11 +9,13 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
return ( return (
<table className="w-full table-fixed text-left text-sm"> <table className="w-full table-fixed text-left text-sm">
<thead> <thead>
<tr className="border-b border-border/70 text-xs font-semibold text-foreground/80"> {/* `border-foreground/10` y no `border`: en dark `--border` es igual a
<th scope="col" className="w-[47%] px-2 pb-1.5">Nombre</th> `primary-soft`, el fondo de la fila, y el separador desaparecería. */}
<th scope="col" className="px-2 pb-1.5">Teléfono</th> <tr className="border-b border-foreground/10 text-xs font-semibold text-foreground/80">
<th scope="col" className="w-[47%] px-3 pb-1.5">Nombre</th>
<th scope="col" className="px-3 pb-1.5">Teléfono</th>
{/* En móvil el teléfono manda: la fecha vive en el detalle. */} {/* En móvil el teléfono manda: la fecha vive en el detalle. */}
<th scope="col" className="hidden px-2 pb-1.5 sm:table-cell">Solicitado</th> <th scope="col" className="hidden px-3 pb-1.5 sm:table-cell">Solicitado</th>
<th scope="col" className="w-8 px-1 pb-1.5"> <th scope="col" className="w-8 px-1 pb-1.5">
<span className="sr-only">Detalle</span> <span className="sr-only">Detalle</span>
</th> </th>
@@ -24,7 +26,8 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
<tr <tr
key={entry.id} key={entry.id}
tabIndex={0} tabIndex={0}
className="group cursor-pointer border-b border-border/70 transition-colors last:border-b-0 hover:bg-primary-soft/60 focus-visible:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent" // El hover va a `surface` porque la fila ya vive sobre `primary-soft`.
className="group cursor-pointer border-b border-foreground/10 transition-colors last:border-b-0 hover:bg-surface/60 focus-visible:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
onClick={() => setSelectedPreRegistration(entry)} onClick={() => setSelectedPreRegistration(entry)}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') { if (e.key === 'Enter' || e.key === ' ') {
@@ -33,7 +36,9 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
} }
}} }}
> >
<td className="px-2 py-2"> {/* `px-3` alinea el texto con el chips y el search de arriba: es el
mismo eje izquierdo de 12px en toda la sección. */}
<td className="px-3 py-2">
<div className="flex min-w-0 items-center gap-2"> <div className="flex min-w-0 items-center gap-2">
<div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent"> <div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">
{entry.fullName.charAt(0).toUpperCase()} {entry.fullName.charAt(0).toUpperCase()}
@@ -50,12 +55,12 @@ export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrati
</div> </div>
</div> </div>
</td> </td>
<td className="min-w-0 px-2 py-2 text-xs text-foreground/70"> <td className="min-w-0 px-3 py-2 text-xs text-foreground/70">
<span className="block truncate tabular-nums" title={entry.phone}> <span className="block truncate tabular-nums" title={entry.phone}>
{formatPhoneDisplay(entry.phone)} {formatPhoneDisplay(entry.phone)}
</span> </span>
</td> </td>
<td className="hidden min-w-0 px-2 py-2 text-xs text-foreground/70 sm:table-cell"> <td className="hidden min-w-0 px-3 py-2 text-xs text-foreground/70 sm:table-cell">
{new Date(entry.createdAt).toLocaleDateString('es-ES', { {new Date(entry.createdAt).toLocaleDateString('es-ES', {
day: 'numeric', day: 'numeric',
month: 'short', month: 'short',

View File

@@ -9,9 +9,11 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
return ( return (
<table className="w-full table-fixed text-left text-sm"> <table className="w-full table-fixed text-left text-sm">
<thead> <thead>
<tr className="border-b border-border/70 text-xs font-semibold text-foreground/80"> {/* `border-foreground/10` y no `border`: en dark `--border` es igual a
<th scope="col" className="w-[47%] px-2 pb-1.5">Nombre</th> `primary-soft`, el fondo de la fila, y el separador desaparecería. */}
<th scope="col" className="px-2 pb-1.5">Teléfono</th> <tr className="border-b border-foreground/10 text-xs font-semibold text-foreground/80">
<th scope="col" className="w-[47%] px-3 pb-1.5">Nombre</th>
<th scope="col" className="px-3 pb-1.5">Teléfono</th>
<th scope="col" className="w-8 px-1 pb-1.5"> <th scope="col" className="w-8 px-1 pb-1.5">
<span className="sr-only">Detalle</span> <span className="sr-only">Detalle</span>
</th> </th>
@@ -22,7 +24,8 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
<tr <tr
key={entry.id} key={entry.id}
tabIndex={0} tabIndex={0}
className="group cursor-pointer border-b border-border/70 transition-colors last:border-b-0 hover:bg-primary-soft/60 focus-visible:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent" // El hover va a `surface` porque la fila ya vive sobre `primary-soft`.
className="group cursor-pointer border-b border-foreground/10 transition-colors last:border-b-0 hover:bg-surface/60 focus-visible:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
onClick={() => setSelectedWaitlistEntry(entry)} onClick={() => setSelectedWaitlistEntry(entry)}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') { if (e.key === 'Enter' || e.key === ' ') {
@@ -31,7 +34,9 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
} }
}} }}
> >
<td className="px-2 py-2"> {/* `px-3` alinea el texto con el chips y el search de arriba: es el
mismo eje izquierdo de 12px en toda la sección. */}
<td className="px-3 py-2">
<div className="flex min-w-0 items-center gap-2"> <div className="flex min-w-0 items-center gap-2">
<div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent"> <div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">
{entry.fullName.charAt(0).toUpperCase()} {entry.fullName.charAt(0).toUpperCase()}
@@ -48,7 +53,7 @@ export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] })
</div> </div>
</div> </div>
</td> </td>
<td className="min-w-0 px-2 py-2 text-xs text-foreground/70"> <td className="min-w-0 px-3 py-2 text-xs text-foreground/70">
{entry.phone ? ( {entry.phone ? (
<span className="block truncate tabular-nums" title={entry.phone}> <span className="block truncate tabular-nums" title={entry.phone}>
{formatPhoneDisplay(entry.phone)} {formatPhoneDisplay(entry.phone)}

View File

@@ -0,0 +1,11 @@
/* Ajustes de la lista de miembros de la ficha de grupo. Viven acá y no
incrustados en el componente porque son decisiones de producto, no de estilo:
cambiarlas no debería obligar a tocar la fila. */
/* A partir de cuántos días para el vencimiento el cobro pasa a kuning y la fila
avisa. Más atrás ya no es "pronto": o se pagó o quedó en el pasado. */
export const PAYMENT_DUE_SOON_DAYS = 3
/* El buscador se muestra a partir de cierta cantidad de miembros. Con pocos, es
más ruido que ayuda: alcanza con mirar la lista. */
export const MEMBER_SEARCH_MIN = 8

View File

@@ -0,0 +1,103 @@
import type { AttendeeListItem, AttendanceStatus } from '@gruperly/shared'
import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'
import { PAYMENT_DUE_SOON_DAYS } from './constants'
/* La fila del listado no pide al backend juicios de presentación: pide los
datos crudos (últimas clases, cobro vigente) y de acá sale el texto. Los
días que faltan cambian según cuándo se mira, así que no pueden venir
guardados desde el servidor. */
/** Días calendario entre dos fechas, sin horas: "vence el día 10" no tiene hora. */
function calendarDaysBetween(from: Date, to: Date): number {
const startOf = (date: Date) =>
new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()
return Math.round((startOf(to) - startOf(from)) / 86_400_000)
}
export type PaymentState =
| { kind: 'settled' }
| { kind: 'dueSoon'; days: number }
| { kind: 'overdue'; days: number }
/**
* Qué hay que marcarle al cobro en la fila.
*
* Devuelve `null` cuando no hay nada que avisar: o el miembro no tiene ningún
* cobro registrado, o el que tiene vence más adelante que la ventana de aviso y
* todavía no venció. No es lo mismo que "al día", que es un pago cerrado.
*
* Un `PENDING` con vencimiento ya pasado cuenta como vencido, igual que un
* `OVERDUE`: el estado guardado suele quedarse en PENDING hasta que alguien lo
* actualiza a mano y la fila no puede depender de esa disciplina.
*/
export function resolvePaymentState(
payment: AttendeeListItem['payment'],
today: Date = new Date(),
): PaymentState | null {
if (!payment) return null
if (payment.status === 'PAID') return { kind: 'settled' }
const days = calendarDaysBetween(today, new Date(payment.dueDate))
if (payment.status === 'OVERDUE' || days < 0) {
return { kind: 'overdue', days: Math.abs(days) }
}
if (days <= PAYMENT_DUE_SOON_DAYS) {
return { kind: 'dueSoon', days }
}
return null
}
export function isOverdue(state: PaymentState | null): boolean {
return state?.kind === 'overdue'
}
export function paymentStateLabel(state: PaymentState): string {
switch (state.kind) {
case 'settled':
return 'Al día'
case 'dueSoon':
// "Vence en 0 d" no es español de persona: hoy y mañana tienen palabras.
if (state.days === 0) return 'Vence hoy'
if (state.days === 1) return 'Vence mañana'
return `Vence en ${state.days} d`
case 'overdue':
return `Vencido · ${state.days} d`
}
}
export type AttendanceSummary = {
/** Estados a dibujar, del más antiguo al más reciente. */
dots: AttendanceStatus[]
attended: number
recorded: number
/** "Sin clases aún" cuando no hay nada registrado. */
label: string
}
/** Los últimos puntos de clase registrados, contados sobre esa misma ventana. */
export function summarizeAttendance(
recentAttendance: AttendanceStatus[],
): AttendanceSummary {
// La ventana la fija el backend; el corte final evita que una fila se alargue
// si el contrato llegara con más clases de las previstas.
const dots = recentAttendance.slice(-RECENT_ATTENDANCE_LIMIT)
const recorded = dots.length
if (recorded === 0) {
return { dots, attended: 0, recorded: 0, label: 'Sin clases aún' }
}
const attended = dots.filter((status) => status === 'PRESENT').length
return {
dots,
attended,
recorded,
label: `${attended} de ${recorded} ${recorded === 1 ? 'clase' : 'clases'}`,
}
}
/** Orden alfabético fijo del listado. */
export function byFullName(a: AttendeeListItem, b: AttendeeListItem): number {
return a.fullName.localeCompare(b.fullName, 'es', { sensitivity: 'base' })
}

View File

@@ -49,6 +49,7 @@
--color-primary: var(--primary); --color-primary: var(--primary);
--color-primary-soft: var(--primary-soft); --color-primary-soft: var(--primary-soft);
--color-foreground: var(--foreground); --color-foreground: var(--foreground);
--color-secondary: var(--secondary);
--color-accent: var(--accent); --color-accent: var(--accent);
--color-accent-strong: var(--accent-strong); --color-accent-strong: var(--accent-strong);
--color-accent-soft: var(--accent-soft); --color-accent-soft: var(--accent-soft);
@@ -60,8 +61,14 @@
--color-success-soft: var(--success-soft); --color-success-soft: var(--success-soft);
--color-warning: var(--warning); --color-warning: var(--warning);
--color-warning-soft: var(--warning-soft); --color-warning-soft: var(--warning-soft);
--color-warning-strong: var(--warning-strong);
--color-warning-strong-soft: var(--warning-strong-soft);
--color-danger: var(--danger); --color-danger: var(--danger);
--color-danger-soft: var(--danger-soft); --color-danger-soft: var(--danger-soft);
--color-danger-fg: var(--danger-fg);
--color-attendance-high: var(--attendance-high);
--color-attendance-attention: var(--attendance-attention);
--color-attendance-ok: var(--attendance-ok);
/* Border radius por defecto */ /* Border radius por defecto */
--radius-xl: 0.75rem; --radius-xl: 0.75rem;
@@ -116,6 +123,12 @@
--primary: #0f172a; --primary: #0f172a;
--primary-soft: #f1f5f9; --primary-soft: #f1f5f9;
--foreground: #475569; --foreground: #475569;
/* Texto secundario sobre superficies suaves (tarjetas). En tema claro el
gris de `foreground` ya da 6.9:1 sobre `primary-soft` y 7.6:1 sobre
`background`, así que acá no hay que mover nada: mismo valor, mismo
contrato. El token existe igual para que "secundario" sea un nombre y no
una coincidencia de color. */
--secondary: #475569;
--accent: #2544ea; --accent: #2544ea;
--accent-strong: #1d33d8; --accent-strong: #1d33d8;
--accent-soft: #eef4ff; --accent-soft: #eef4ff;
@@ -127,8 +140,22 @@
--success-soft: #ecfdf5; --success-soft: #ecfdf5;
--warning: #b45309; --warning: #b45309;
--warning-soft: #fffbeb; --warning-soft: #fffbeb;
/* naranja: escalón de severidad para la misma familia de alertas (aviso por
asistencia, cupos). Sobre `warning-strong-soft` da 4.9:1 y sobre la
tarjeta 4.4:1, así que sirve para texto y para un borde tenue. */
--warning-strong: #c2410c;
--warning-strong-soft: #fff7ed;
--danger: #f43f5e; --danger: #f43f5e;
--danger-soft: #fff1f2; --danger-soft: #fff1f2;
/* Rojo legible como TEXTO. `--danger` da 3.35:1 sobre la tarjeta en tema
claro, así que como texto no llega al 4.5:1 de AA (sí sirve como relleno,
donde el mínimo es 3:1). Es el mismo patrón que `accent` / `accent-fg`: un
color para superficies grandes y su versión legible para rotular. Este
#be123c da 5.74:1 sobre la tarjeta y 5.72:1 sobre `danger-soft`. */
--danger-fg: #be123c;
--attendance-high: #d63b3b;
--attendance-attention: #f5a623;
--attendance-ok: #2b7bd6;
} }
.dark { .dark {
@@ -140,6 +167,11 @@
--primary: #f1f5f9; --primary: #f1f5f9;
--primary-soft: #1e293b; --primary-soft: #1e293b;
--foreground: #94a3b8; --foreground: #94a3b8;
/* El secundario se sube un escalón sobre `foreground`: 7.1:1 sobre la
tarjeta (#1e293b) y 9.8:1 sobre el fondo, contra 5.7:1 del gris anterior.
El salto importa en las superficies suaves, que son las que dominan las
tarjetas de la lista: el texto de apoyo ahí es el que más se pierde. */
--secondary: #a8b6c8;
--accent: #2544ea; --accent: #2544ea;
--accent-strong: #1d33d8; --accent-strong: #1d33d8;
--accent-soft: color-mix(in srgb, var(--brand-500) 15%, transparent); --accent-soft: color-mix(in srgb, var(--brand-500) 15%, transparent);
@@ -151,8 +183,16 @@
--success-soft: color-mix(in srgb, var(--success) 15%, transparent); --success-soft: color-mix(in srgb, var(--success) 15%, transparent);
--warning: #fcd34d; --warning: #fcd34d;
--warning-soft: color-mix(in srgb, var(--warning) 15%, transparent); --warning-soft: color-mix(in srgb, var(--warning) 15%, transparent);
/* En oscuro el "naranja" tiene que subir de luminosidad para alcanzar el
mismo contraste que su versión clara: #fb923c da 4.7:1 sobre el fondo
translúcido del badge, contra 4.1:1 del #f97316 de la paleta estándar. */
--warning-strong: #fb923c;
--warning-strong-soft: color-mix(in srgb, var(--warning-strong) 18%, transparent);
--danger: #fb7185; --danger: #fb7185;
--danger-soft: color-mix(in srgb, var(--danger) 15%, transparent); --danger-soft: color-mix(in srgb, var(--danger) 15%, transparent);
/* En oscuro `#fb7185` ya da 5.44:1 sobre la tarjeta: legible como texto y de
sobra como relleno, así que acá no hay que mover nada. */
--danger-fg: var(--danger);
} }
@layer base { @layer base {
@@ -180,4 +220,4 @@
font-size: 16px !important; font-size: 16px !important;
} }
} }
} }

View File

@@ -46,6 +46,8 @@ import type {
UpdateStudentStatusResult, UpdateStudentStatusResult,
} from '@gruperly/shared' } from '@gruperly/shared'
import { browserTimezone } from './region'
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:4000' const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:4000'
export class ApiError extends Error { export class ApiError extends Error {
@@ -106,15 +108,23 @@ export const createGroup = (payload: CreateFirstGroup) =>
body: JSON.stringify(payload), body: JSON.stringify(payload),
}) })
export const getGroups = () => apiFetch<GroupList>('/api/v1/groups') /* La pantalla de grupos no tiene paginación: se pide el máximo permitido para
que ningún grupo quede fuera de la lista, y la zona horaria del browser para
que el backend ordene por la próxima clase en la hora local de la persona. */
const GROUPS_PAGE_SIZE = 100
export const getGroups = () => {
const params = new URLSearchParams({ pageSize: String(GROUPS_PAGE_SIZE) })
const timeZone = browserTimezone()
if (timeZone) {
params.set('timeZone', timeZone)
}
return apiFetch<GroupList>(`/api/v1/groups?${params.toString()}`)
}
function timeZoneParam(): string { function timeZoneParam(): string {
try { const timeZone = browserTimezone()
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone return timeZone ? `?timeZone=${encodeURIComponent(timeZone)}` : ''
return timeZone ? `?timeZone=${encodeURIComponent(timeZone)}` : ''
} catch {
return ''
}
} }
export const getHomeSummary = () => export const getHomeSummary = () =>

View File

@@ -148,9 +148,26 @@ export function formatPhoneDisplay(
const withCallingCode = formatWithCallingCode(digits) const withCallingCode = formatWithCallingCode(digits)
if (withCallingCode) return withCallingCode if (withCallingCode) return withCallingCode
if (hasPlus || hasDoubleZero) return `+${digits}` // Número de una región que no agrupamos: al menos se separa en bloques de a
// 3 para que no se lea como un muro de dígitos. El `+` se conserva si lo había.
if (hasPlus || hasDoubleZero) return `+${groupByThrees(digits)}`
return formatNational(digits, appRegion(countryOf(locale ?? browserLocale())), false) ?? raw return (
formatNational(digits, appRegion(countryOf(locale ?? browserLocale())), false) ??
groupByThrees(digits)
)
}
/** Bloques de a 3 desde la derecha: el sobrante de 1-2 dígitos queda a la izquierda. */
function groupByThrees(digits: string): string {
const groups: string[] = []
let rest = digits
while (rest.length > 3) {
groups.unshift(rest.slice(-3))
rest = rest.slice(0, -3)
}
if (rest) groups.unshift(rest)
return groups.join(' ')
} }
/** Prueba el prefijo de país solo si lo que sigue encaja en sus reglas. */ /** Prueba el prefijo de país solo si lo que sigue encaja en sus reglas. */

View File

@@ -1,7 +1,7 @@
import { useParams } from '@tanstack/react-router' import { useParams } from '@tanstack/react-router'
import { createFileRoute } from '@tanstack/react-router' import { createFileRoute } from '@tanstack/react-router'
import { AttendeeDetailPage } from '../../../../../features/groups/detail/AttendeeDetailPage' import { AttendeeDetailProvider } from '../../../../../features/attendee-detail/AttendeeDetailProvider'
import { AttendeeDetailProvider } from '../../../../../features/groups/detail/AttendeeDetailProvider' import { AttendeeDetailView } from '../../../../../features/attendee-detail/AttendeeDetailView'
export const Route = createFileRoute('/_authenticated/groups/$groupId/attendees/$attendeeId')({ export const Route = createFileRoute('/_authenticated/groups/$groupId/attendees/$attendeeId')({
component: () => { component: () => {
@@ -10,7 +10,7 @@ export const Route = createFileRoute('/_authenticated/groups/$groupId/attendees/
}) })
return ( return (
<AttendeeDetailProvider groupId={groupId} attendeeId={attendeeId}> <AttendeeDetailProvider groupId={groupId} attendeeId={attendeeId}>
<AttendeeDetailPage /> <AttendeeDetailView />
</AttendeeDetailProvider> </AttendeeDetailProvider>
) )
}, },

View File

@@ -0,0 +1,131 @@
import { describe, expect, test } from 'bun:test'
import type { AttendanceStatus } from '@gruperly/shared'
import {
attendanceStatusLabel,
attendanceSummary,
classCountLabel,
formatMemberSince,
formatSessionShortDate,
HISTORY_LIMIT,
HISTORY_PREVIEW,
visibleSessions,
type AttendanceSession,
} from '../src/features/attendee-detail/attendance'
/* La sección de asistencia no lee estos valores de la API: los deriva. Todo lo
que decide qué se muestra —cuántas filas, el plural, el orden— vive acá. */
const fecha = (day: number) => new Date(2026, 8, day, 12).toISOString()
const sesion = (
day: number,
status: AttendanceStatus | null = 'PRESENT',
): AttendanceSession => ({
classSessionId: `s-${day}`,
startsAt: fecha(day),
status,
})
// El endpoint devuelve de la más antigua a la más reciente.
const historial = [
sesion(1, 'PRESENT'),
sesion(2, 'ABSENT'),
sesion(3, 'EXCUSED'),
sesion(4, 'PRESENT'),
sesion(5, null),
sesion(6, 'PRESENT'),
]
describe('classCountLabel', () => {
test('una clase en singular, dos en plural', () => {
expect(classCountLabel(1)).toBe('1 clase')
expect(classCountLabel(2)).toBe('2 clases')
expect(classCountLabel(0)).toBe('0 clases')
})
})
describe('attendanceStatusLabel', () => {
test('el estado se escribe, no se insinúa con el color', () => {
expect(attendanceStatusLabel('PRESENT')).toBe('Asistió')
expect(attendanceStatusLabel('ABSENT')).toBe('Faltó')
expect(attendanceStatusLabel('EXCUSED')).toBe('Faltó (avisó)')
})
test('una clase sin marcar no se cuenta como asistencia', () => {
expect(attendanceStatusLabel(null)).toBe('Sin registrar')
})
})
describe('attendanceSummary', () => {
test('el denominador son las clases registradas, no todas las filas', () => {
// La vista previa son 5 filas, pero una quedó sin registrar: el resumen
// cuenta 4, no 5, porque sin dato no hay ni asistencia ni ausencia.
const { label } = attendanceSummary(visibleSessions(historial, false))
expect(label).toBe('2 de 4 clases')
})
test('las clases sin registro se avisan aparte, no mezcladas en el total', () => {
expect(attendanceSummary(visibleSessions(historial, false)).unmarkedLabel).toBe('1 sin registrar')
})
test('con una sola clase el total va en singular', () => {
expect(attendanceSummary([sesion(6, 'PRESENT')]).label).toBe('1 de 1 clase')
})
test('sin nada registrado lo dice, en vez de "0 de 0"', () => {
const sinRegistrar = [sesion(5, null), sesion(6, null)]
expect(attendanceSummary(sinRegistrar)).toEqual({
label: 'Sin clases registradas',
unmarkedLabel: null,
})
expect(attendanceSummary([])).toEqual({
label: 'Sin clases registradas',
unmarkedLabel: null,
})
})
test('faltó y faltó con aviso también cuentan como clases registradas', () => {
const marcadas = [sesion(1, 'ABSENT'), sesion(2, 'EXCUSED')]
expect(attendanceSummary(marcadas)).toEqual({ label: '0 de 2 clases', unmarkedLabel: null })
})
})
describe('visibleSessions', () => {
test('la vista previa son las últimas, de la más reciente a la más antigua', () => {
const visibles = visibleSessions(historial, false)
expect(visibles).toHaveLength(HISTORY_PREVIEW)
expect(visibles.map((item) => item.classSessionId)).toEqual([
's-6',
's-5',
's-4',
's-3',
's-2',
])
})
test('"ver todas" muestra el historial entero, sin inventar clases', () => {
expect(visibleSessions(historial, true)).toHaveLength(historial.length)
expect(visibleSessions([], true)).toEqual([])
})
test('con menos de 5 clases se muestran todas y no hace falta el toggle', () => {
const pocas = historial.slice(0, 3)
expect(visibleSessions(pocas, false)).toHaveLength(3)
})
test('el tope es el del endpoint: 20 sesiones', () => {
expect(HISTORY_LIMIT).toBe(20)
})
})
describe('formatSessionShortDate', () => {
test('fecha corta con día de la semana', () => {
expect(formatSessionShortDate(fecha(28))).toBe('lun 28 sep')
})
})
describe('formatMemberSince', () => {
test('fecha abreviada con año, en una sola línea', () => {
expect(formatMemberSince(fecha(18))).toBe('18 sep 2026')
})
})

View File

@@ -258,8 +258,9 @@ describe('formatPhoneDisplay — región del número y país del browser', () =>
expect(formatPhoneDisplay('2983649550', 'es-AR')).toBe('2983 64-9550') expect(formatPhoneDisplay('2983649550', 'es-AR')).toBe('2983 64-9550')
}) })
test('número irreconocible se devuelve tal cual', () => { test('número irreconocible se agrupa en bloques de a 3', () => {
expect(formatPhoneDisplay('3209872223344', 'es-AR')).toBe('3209872223344') expect(formatPhoneDisplay('3209872223344', 'es-AR')).toBe('3 209 872 223 344')
expect(formatPhoneDisplay('320987223344', 'es-AR')).toBe('320 987 223 344')
expect(formatPhoneDisplay('12345', 'es-AR')).toBe('12345') expect(formatPhoneDisplay('12345', 'es-AR')).toBe('12345')
expect(formatPhoneDisplay(null)).toBeNull() expect(formatPhoneDisplay(null)).toBeNull()
expect(formatPhoneDisplay('')).toBeNull() expect(formatPhoneDisplay('')).toBeNull()
@@ -287,9 +288,9 @@ describe('formatPhoneDisplay — región del número y país del browser', () =>
expect(formatPhoneDisplay('+5492954667788', 'en-US')).toBe('+54 9 2954 66-7788') expect(formatPhoneDisplay('+5492954667788', 'en-US')).toBe('+54 9 2954 66-7788')
}) })
test('región sin reglas propias cae a E.164', () => { test('región sin reglas propias conserva el prefijo y agrupa el resto', () => {
expect(formatPhoneDisplay('+331234567890', 'es-AR')).toBe('+331234567890') expect(formatPhoneDisplay('+331234567890', 'es-AR')).toBe('+331 234 567 890')
expect(formatPhoneDisplay('00331234567890', 'es-AR')).toBe('+331234567890') expect(formatPhoneDisplay('00331234567890', 'es-AR')).toBe('+331 234 567 890')
}) })
test('por defecto usa el país del browser', () => { test('por defecto usa el país del browser', () => {

View File

@@ -0,0 +1,438 @@
import { describe, expect, test } from 'bun:test'
import type { GroupRiskSummary, UrgentMemberSummary } from '@gruperly/shared'
import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import {
alertTextFromMembers,
barCapacity,
capacityCounts,
capacityCountsFromMembers,
isSegmentedCapacity,
MOCK_TEST_CASES,
occupancyLabel,
riskTone,
SEGMENTED_CAPACITY_MAX,
statusLine,
type GroupMember,
} from '../src/features/groups/card'
import {
capacityIndicatorLabel,
capacitySegmentWidth,
} from '../src/features/groups/AttendanceCapacityIndicator'
import { GroupCard, GroupCardContent } from '../src/features/groups/GroupCard'
/* La tarjeta del listado no calcula el riesgo: lo recibe de
`GET /groups-risk/overview`, que corre la función de dominio del backend. Lo
que se prueba acá es la traducción de esa respuesta a la tarjeta: qué se
cuenta, qué se nombra y cuándo la card se tiñe. Todo sin montar React. */
const risk = (
riesgoAlto: number,
atencion: number,
extra: Partial<GroupRiskSummary> = {},
): GroupRiskSummary => ({
groupId: 'grp_1',
groupName: 'Pilates',
riskLevel: riesgoAlto > 0 ? 'HIGH' : atencion > 0 ? 'MEDIUM' : 'NONE',
absenceStreakCount: riesgoAlto,
lowAttendanceCount: atencion,
riesgoAlto,
atencion,
ok: 0,
libres: 0,
enEspera: 0,
asistencia: 100,
urgentes: [],
...extra,
})
const urgente = (extra: Partial<UrgentMemberSummary> = {}): UrgentMemberSummary => ({
attendeeId: 'at_1',
fullName: 'Sofía Ramírez',
level: 'riesgo_alto',
consecutiveAbsences: 0,
daysSinceLastAttendance: null,
attendanceRate: null,
...extra,
})
const grupo = (attendeesCount: number, capacity: number | null) => ({ attendeesCount, capacity })
describe('GroupCard - Casos de prueba de referencia', () => {
test('Caso 1: Tai Chi Martes (cupo 5, 4/5 miembros, 5 píldoras, alerta Sofía)', () => {
const markup = renderToStaticMarkup(createElement(GroupCard, { ...MOCK_TEST_CASES[0], link: false }))
// Fila 1: el nombre solo. El cupo no se repite: ya está en "4/5 miembros"
expect(markup).toContain('Tai Chi Martes')
expect(markup).not.toContain('whitespace-nowrap text-base tabular-nums text-secondary')
// Fila 2: 4/5 miembros en una sola línea y 5 píldoras individuales
expect(markup).toContain('4/5 miembros')
expect(markup).toContain('whitespace-nowrap text-lg tabular-nums text-secondary">4/5 miembros')
// Píldoras individuales (Modo A: cupo <= 10)
// 1 rojo (high), 1 ámbar (attention), 2 azul (ok), 1 vacía (libres)
expect(markup).toContain('w-[50px] shrink-0')
expect(markup).toContain('bg-attendance-high')
expect(markup).toContain('bg-attendance-attention')
expect(markup).toContain('bg-attendance-ok')
// Fila 3: alerta roja con ícono de cuadrado
expect(markup).toContain('Sofía: 4 faltas · 1 en atención')
expect(markup).toContain('text-[#8B1A1A]')
})
test('Caso 2: Pilates Sábado (cupo 15, 12/15 miembros, barra continua, alerta Sofía)', () => {
const markup = renderToStaticMarkup(createElement(GroupCard, { ...MOCK_TEST_CASES[1], link: false }))
// Fila 1: el nombre solo
expect(markup).toContain('Pilates Sábado')
// Fila 2
expect(markup).toContain('12/15 miembros')
// Modo B: barra continua (overflow-hidden rounded-full)
expect(markup).toContain('overflow-hidden rounded-full')
// Fila 3: alerta
expect(markup).toContain('Sofía: 4 faltas · 2 en atención')
expect(markup).toContain('text-[#8B1A1A]')
})
test('Caso 3: Natación Adultos (cupo 30, 22/30 miembros, barra continua, alerta múltiple)', () => {
const markup = renderToStaticMarkup(createElement(GroupCard, { ...MOCK_TEST_CASES[2], link: false }))
// Fila 1: el nombre solo
expect(markup).toContain('Natación Adultos')
// Fila 2
expect(markup).toContain('22/30 miembros')
// Modo B: barra continua
expect(markup).toContain('overflow-hidden rounded-full')
// Fila 3: alerta con 3 en riesgo alto y 4 en atención
expect(markup).toContain('3 en riesgo alto · 4 en atención')
expect(markup).toContain('text-[#8B1A1A]')
})
})
describe('alertTextFromMembers', () => {
test('con exactamente 1 miembro en riesgo alto muestra su nombre y faltas', () => {
const members: GroupMember[] = [
{ id: '1', name: 'Sofía Ramírez', status: 'high_risk', absences: 4 },
{ id: '2', name: 'Lucas', status: 'attention', absences: 1 },
{ id: '3', name: 'Martín', status: 'ok', absences: 0 },
]
expect(alertTextFromMembers(members)).toBe('Sofía: 4 faltas · 1 en atención')
})
test('con exactamente 1 miembro en riesgo alto y sin atención', () => {
const members: GroupMember[] = [
{ id: '1', name: 'Sofía', status: 'high_risk', absences: 1 },
{ id: '2', name: 'Martín', status: 'ok', absences: 0 },
]
expect(alertTextFromMembers(members)).toBe('Sofía: 1 falta')
})
test('con 2 o más en riesgo alto resume por cantidad', () => {
const members: GroupMember[] = [
{ id: '1', name: 'Sofía', status: 'high_risk', absences: 4 },
{ id: '2', name: 'Mateo', status: 'high_risk', absences: 2 },
{ id: '3', name: 'Lucas', status: 'attention', absences: 1 },
]
expect(alertTextFromMembers(members)).toBe('2 en riesgo alto · 1 en atención')
})
test('sin riesgo alto pero con atención muestra solo atención', () => {
const members: GroupMember[] = [
{ id: '1', name: 'Lucas', status: 'attention', absences: 1 },
{ id: '2', name: 'Elena', status: 'attention', absences: 1 },
{ id: '3', name: 'Martín', status: 'ok', absences: 0 },
]
expect(alertTextFromMembers(members)).toBe('2 en atención')
})
test('sin riesgo alto ni atención devuelve null y no renderiza fila de alerta', () => {
const members: GroupMember[] = [
{ id: '1', name: 'Lucas', status: 'ok', absences: 0 },
{ id: '2', name: 'Martín', status: 'ok', absences: 0 },
]
expect(alertTextFromMembers(members)).toBeNull()
const markup = renderToStaticMarkup(
createElement(GroupCard, {
name: 'Yoga Tranquilo',
capacity: 10,
members,
}),
)
expect(markup).not.toContain('text-[#8B1A1A]')
})
})
describe('capacityCounts', () => {
test('los lugares libres son los que faltan del cupo', () => {
expect(capacityCounts(grupo(4, 5), undefined).libres).toBe(1)
expect(capacityCounts(grupo(12, 20), undefined).libres).toBe(8)
})
test('lleno o de más da 0 libres, nunca negativos', () => {
expect(capacityCounts(grupo(5, 5), undefined).libres).toBe(0)
expect(capacityCounts(grupo(7, 5), undefined).libres).toBe(0)
})
test('sin cupo definido no hay lugares que repartir', () => {
expect(capacityCounts(grupo(3, null), undefined).libres).toBe(0)
})
test('ok es la diferencia: el resumen solo nombra a los que hay que mirar', () => {
const counts = capacityCounts(grupo(10, 20), risk(2, 3))
expect(counts).toEqual({ riesgoAlto: 2, atencion: 3, ok: 5, libres: 10 })
})
test('sin resumen, todo el grupo queda en calma y la barra se puede pintar', () => {
expect(capacityCounts(grupo(4, 5), undefined)).toEqual({
riesgoAlto: 0,
atencion: 0,
ok: 4,
libres: 1,
})
})
test('ok no se vuelve negativo si el resumen contara más gente que la matrícula', () => {
expect(capacityCounts(grupo(2, 5), risk(3, 1)).ok).toBe(0)
})
})
describe('isSegmentedCapacity', () => {
test('hasta 10 lugares va un segmento por lugar', () => {
expect(isSegmentedCapacity(4)).toBe(true)
expect(isSegmentedCapacity(5)).toBe(true)
expect(isSegmentedCapacity(10)).toBe(true)
})
test('de 11 para arriba pasa a bloques proporcionales', () => {
expect(isSegmentedCapacity(11)).toBe(false)
expect(isSegmentedCapacity(30)).toBe(false)
expect(isSegmentedCapacity(100)).toBe(false)
})
test('sin matrícula ni cupo no hay nada que repartir', () => {
expect(isSegmentedCapacity(0)).toBe(false)
})
})
describe('barCapacity', () => {
test('con cupo declarado, el indicador mide los lugares del cupo', () => {
expect(barCapacity(grupo(4, 5))).toBe(5)
expect(barCapacity(grupo(0, 30))).toBe(30)
})
test('sin cupo, el indicador mide a la matrícula en vez de desaparecer', () => {
expect(barCapacity(grupo(4, null))).toBe(4)
expect(barCapacity(grupo(30, null))).toBe(30)
})
test('un grupo sin cupo y sin gente no inventa un total', () => {
expect(barCapacity(grupo(0, null))).toBe(0)
expect(isSegmentedCapacity(barCapacity(grupo(0, null)))).toBe(false)
})
})
describe('riskTone', () => {
test('manda el peor nivel presente', () => {
expect(riskTone({ riesgoAlto: 1, atencion: 4, ok: 0, libres: 0 })).toBe('riesgo_alto')
expect(riskTone({ riesgoAlto: 0, atencion: 1, ok: 0, libres: 0 })).toBe('atencion')
expect(riskTone({ riesgoAlto: 0, atencion: 0, ok: 9, libres: 0 })).toBe('ok')
})
})
describe('statusLine', () => {
test('grupo chico: nombra al caso más urgente y resume los demás', () => {
const resumen = risk(1, 1, {
urgentes: [
urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 }),
urgente({
attendeeId: 'at_2',
fullName: 'Diego Soto',
level: 'atencion',
consecutiveAbsences: 2,
}),
],
})
expect(statusLine(grupo(4, 5), resumen)).toEqual({
text: 'Sofía: 4 faltas · 1 en atención',
tone: 'riesgo_alto',
})
})
test('con tres personas en riesgo alto resume el total aunque el grupo sea chico', () => {
const resumen = risk(3, 0, {
urgentes: [
urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 }),
urgente({ attendeeId: 'at_2', fullName: 'Diego Soto', consecutiveAbsences: 3 }),
urgente({ attendeeId: 'at_3', fullName: 'Ana Ruiz', consecutiveAbsences: 3 }),
],
})
expect(statusLine(grupo(4, 5), resumen).text).toBe('3 en riesgo alto')
})
test('grupo grande: el conteo por nivel en vez de nombres', () => {
const resumen = risk(3, 4, { urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })] })
expect(statusLine(grupo(18, 20), resumen)).toEqual({
text: '3 en riesgo alto · 4 en atención',
tone: 'riesgo_alto',
})
})
test('con exactamente una persona en riesgo alto la nombra, sin importar el cupo', () => {
const resumen = risk(1, 2, {
urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })],
})
expect(statusLine(grupo(12, 15), resumen).text).toBe('Sofía: 4 faltas · 2 en atención')
})
test('con dos personas en riesgo alto resume por cantidad', () => {
const resumen = risk(2, 3, {
urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })],
})
expect(statusLine(grupo(12, 15), resumen).text).toBe('2 en riesgo alto · 3 en atención')
})
test('el singular se corrige solo', () => {
expect(statusLine(grupo(18, 20), risk(1, 0)).text).toBe('1 en riesgo alto')
})
test('un grupo chico sin cupo también nombra a la gente', () => {
// Sin cupo la barra mide a la matrícula, así que 4 miembros dan 4 segmentos
// y la línea puede usar nombres igual que un grupo con cupo chico.
const resumen = risk(1, 0, {
urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })],
})
expect(statusLine(grupo(4, null), resumen)).toEqual({
text: 'Sofía: 4 faltas',
tone: 'riesgo_alto',
})
})
test('un grupo grande sin cupo cae al conteo', () => {
const resumen = risk(3, 4, {
urgentes: [urgente({ fullName: 'Sofía Ramírez', consecutiveAbsences: 4 })],
})
expect(statusLine(grupo(18, null), resumen).text).toBe('3 en riesgo alto · 4 en atención')
})
test('el motivo más útil va primero: las faltas, después el tiempo, después la asistencia', () => {
const resumen = risk(2, 1, {
urgentes: [
urgente({ consecutiveAbsences: 2, daysSinceLastAttendance: 30, attendanceRate: 40 }),
urgente({
attendeeId: 'at_2',
fullName: 'Diego Soto',
level: 'atencion',
consecutiveAbsences: 0,
daysSinceLastAttendance: 14,
attendanceRate: 60,
}),
urgente({
attendeeId: 'at_3',
fullName: 'Ana Ruiz',
level: 'atencion',
consecutiveAbsences: 0,
daysSinceLastAttendance: 0,
attendanceRate: 55,
}),
],
})
expect(statusLine(grupo(4, 5), resumen).text).toBe('2 en riesgo alto · 1 en atención')
})
test('sin riesgo la línea se apaga con la asistencia', () => {
const resumen = risk(0, 0, { asistencia: 94 })
expect(statusLine(grupo(18, 20), resumen)).toEqual({ text: 'Asistencia 94%', tone: 'ok' })
})
test('un grupo sin clases registradas no muestra un 100% inventado', () => {
expect(statusLine(grupo(4, 5), risk(0, 0, { asistencia: null })).text).toBe('Sin clases registradas')
// Todavía sin resumen: la tarjeta tiene que poder pintar igual.
expect(statusLine(grupo(4, 5), undefined).text).toBe('Sin clases registradas')
})
test('si el resumen no trajo a quién nombrar, el grupo chico cae al conteo', () => {
// Los urgentes vienen truncados a 5: si hay más gente en riesgo que eso,
// la línea no puede quedarse en blanco.
expect(statusLine(grupo(4, 5), risk(2, 0, { urgentes: [] })).text).toBe('2 en riesgo alto')
})
})
describe('occupancyLabel', () => {
test('con cupo muestra el uso sobre el total', () => {
expect(occupancyLabel(grupo(4, 5))).toBe('4/5 miembros')
expect(occupancyLabel(grupo(12, 20))).toBe('12/20 miembros')
})
test('1/5 se lee en plural: la unidad es el lugar, no la persona', () => {
expect(occupancyLabel(grupo(1, 5))).toBe('1/5 miembros')
})
test('sin cupo el texto es el conteo, y el singular se corrige', () => {
expect(occupancyLabel(grupo(3, null))).toBe('3 miembros')
expect(occupancyLabel(grupo(1, null))).toBe('1 miembro')
expect(occupancyLabel(grupo(0, null))).toBe('0 miembros')
})
test('un grupo vacío con cupo se lee como cualquier otro', () => {
expect(occupancyLabel(grupo(0, 5))).toBe('0/5 miembros')
})
})
describe('capacitySegmentWidth', () => {
test('calcula cada segmento sobre el cupo y conserva el espacio libre', () => {
expect(capacitySegmentWidth(2, 15)).toBe('13.3333%')
expect(capacitySegmentWidth(3, 15)).toBe('20.0000%')
expect(capacitySegmentWidth(7, 15)).toBe('46.6667%')
})
})
describe('capacityIndicatorLabel', () => {
test('el aria-label repite toda la información de la barra', () => {
expect(capacityIndicatorLabel({ riesgoAlto: 2, atencion: 2, ok: 0, libres: 1 }, 5)).toBe(
'4 de 5 lugares ocupados: 2 en riesgo alto, 2 en atención, 1 libre',
)
})
test('omite los niveles que están en cero y el plural de libre', () => {
expect(capacityIndicatorLabel({ riesgoAlto: 1, atencion: 0, ok: 3, libres: 1 }, 5)).toBe(
'4 de 5 lugares ocupados: 1 en riesgo alto, 3 en ok, 1 libre',
)
expect(capacityIndicatorLabel({ riesgoAlto: 0, atencion: 0, ok: 5, libres: 0 }, 5)).toBe(
'5 de 5 lugares ocupados: 5 en ok',
)
})
test('un grupo vacío se anuncia sin niveles, no como un error', () => {
expect(capacityIndicatorLabel({ riesgoAlto: 0, atencion: 0, ok: 0, libres: 10 }, 10)).toBe(
'0 de 10 lugares ocupados, 10 libres',
)
})
test('sin cupo declarado se anuncia por miembros, no por lugares inventados', () => {
expect(capacityIndicatorLabel({ riesgoAlto: 1, atencion: 2, ok: 1, libres: 0 }, 4, false)).toBe(
'4 miembros: 1 en riesgo alto, 2 en atención, 1 en ok',
)
expect(capacityIndicatorLabel({ riesgoAlto: 0, atencion: 0, ok: 1, libres: 0 }, 1, false)).toBe(
'1 miembro: 1 en ok',
)
})
})

View File

@@ -0,0 +1,149 @@
import { describe, expect, test } from 'bun:test'
import type { AttendeeListItem } from '@gruperly/shared'
import {
byFullName,
isOverdue,
paymentStateLabel,
resolvePaymentState,
summarizeAttendance,
} from '../src/features/groups/detail/member-row'
/* La fila del listado no lee estos valores de la API: los deriva. Todo lo que
decide qué se muestra —qué día es "vencido", cuántas clases hay— vive acá. */
type PaymentStatus = NonNullable<AttendeeListItem['payment']>['status']
const HOY = new Date(2026, 8, 30) // 30 de septiembre de 2026, hora local
const dias = (offset: number) => new Date(2026, 8, 30 + offset)
const payment = (status: PaymentStatus, dueDate: Date): AttendeeListItem['payment'] => ({
status,
dueDate: dueDate.toISOString(),
})
const member = (fullName: string) => ({ fullName }) as AttendeeListItem
const nombres = (members: AttendeeListItem[]) => members.map((m) => m.fullName)
describe('resolvePaymentState', () => {
test('sin cobros registrados no inventa un estado', () => {
expect(resolvePaymentState(null, HOY)).toBeNull()
})
test('un pago cerrado es "al día"', () => {
expect(resolvePaymentState(payment('PAID', dias(-10)), HOY)).toEqual({ kind: 'settled' })
expect(resolvePaymentState(payment('PAID', dias(10)), HOY)).toEqual({ kind: 'settled' })
})
test('avisa cuando faltan 3 días o menos, que es el umbral', () => {
expect(resolvePaymentState(payment('PENDING', dias(0)), HOY)).toEqual({
kind: 'dueSoon',
days: 0,
})
expect(resolvePaymentState(payment('PENDING', dias(1)), HOY)).toEqual({
kind: 'dueSoon',
days: 1,
})
expect(resolvePaymentState(payment('PENDING', dias(3)), HOY)).toEqual({
kind: 'dueSoon',
days: 3,
})
})
test('más allá del umbral no molesta: todavía no toca pagar', () => {
expect(resolvePaymentState(payment('PENDING', dias(4)), HOY)).toBeNull()
})
test('un PENDING ya vencido cuenta como vencido, no como "al día"', () => {
expect(resolvePaymentState(payment('PENDING', dias(-1)), HOY)).toEqual({
kind: 'overdue',
days: 1,
})
})
test('OVERDUE está vencido aunque su vencimiento siga en el futuro', () => {
expect(resolvePaymentState(payment('OVERDUE', dias(5)), HOY)).toEqual({
kind: 'overdue',
days: 5,
})
})
test('el atraso va en días calendario, sin horas', () => {
// 23:59 de ayer y 00:01 de hoy son un solo día para el docente: 1 de atraso.
const ayerTarde = new Date(2026, 8, 29, 23, 59)
const hoyTemprano = new Date(2026, 8, 30, 0, 1)
expect(resolvePaymentState(payment('PENDING', ayerTarde), hoyTemprano)).toEqual({
kind: 'overdue',
days: 1,
})
})
})
describe('paymentStateLabel', () => {
test('el estado quieto se dice, no se calla', () => {
expect(paymentStateLabel({ kind: 'settled' })).toBe('Al día')
})
test('hoy y mañana tienen palabras: "Vence en 0 d" no es español', () => {
expect(paymentStateLabel({ kind: 'dueSoon', days: 0 })).toBe('Vence hoy')
expect(paymentStateLabel({ kind: 'dueSoon', days: 1 })).toBe('Vence mañana')
expect(paymentStateLabel({ kind: 'dueSoon', days: 3 })).toBe('Vence en 3 d')
})
test('el atraso va con el número de días', () => {
expect(paymentStateLabel({ kind: 'overdue', days: 12 })).toBe('Vencido · 12 d')
})
})
describe('isOverdue', () => {
test('solo el vencido cuenta como deudor', () => {
expect(isOverdue({ kind: 'overdue', days: 4 })).toBe(true)
expect(isOverdue({ kind: 'dueSoon', days: 0 })).toBe(false)
expect(isOverdue({ kind: 'settled' })).toBe(false)
expect(isOverdue(null)).toBe(false)
})
})
describe('summarizeAttendance', () => {
test('sin clases registradas dice "Sin clases aún"', () => {
expect(summarizeAttendance([])).toEqual({
dots: [],
attended: 0,
recorded: 0,
label: 'Sin clases aún',
})
})
test('cuenta asistidas sobre las registradas de la ventana', () => {
const summary = summarizeAttendance(['PRESENT', 'ABSENT', 'EXCUSED', 'PRESENT', 'PRESENT'])
expect(summary.attended).toBe(3)
expect(summary.recorded).toBe(5)
expect(summary.label).toBe('3 de 5 clases')
})
test('"clases" concuerda en singular', () => {
expect(summarizeAttendance(['PRESENT']).label).toBe('1 de 1 clase')
})
test('no rellena con puntos vacíos cuando hay menos de 5 clases', () => {
expect(summarizeAttendance(['ABSENT', 'PRESENT']).dots).toEqual(['ABSENT', 'PRESENT'])
})
test('el aviso cuenta como clase registrada pero no como asistencia', () => {
const summary = summarizeAttendance(['EXCUSED'])
expect(summary.recorded).toBe(1)
expect(summary.attended).toBe(0)
})
})
describe('byFullName', () => {
test('ordena alfabéticamente sin depender de mayúsculas ni acentos', () => {
const sueltos = [member('Zoe Ruiz'), member('ángel Díaz'), member('Bruno Díaz'), member('Ana López')]
expect(nombres([...sueltos].sort(byFullName))).toEqual([
'Ana López',
'ángel Díaz',
'Bruno Díaz',
'Zoe Ruiz',
])
})
})

View File

@@ -1,3 +1,4 @@
export * from './lib/attendance-risk.js';
export * from './lib/problem-details.js'; export * from './lib/problem-details.js';
export * from './lib/result.js'; export * from './lib/result.js';
export * from './schemas/analytics.js'; export * from './schemas/analytics.js';

View File

@@ -0,0 +1,313 @@
import type { AttendanceRiskLevelDto, AttendanceStatus } from '../schemas/attendance.js';
/* Riesgo de abandono de un alumno, derivado del historial de asistencia.
Vive en `shared` y no importa nada de UI: lo usan el resumen por grupo del
backend, la tarjeta del listado y la sección de seguimiento del Inicio.
Los umbrales viven todos acá, en un solo objeto. La regla es de negocio
("3 faltas seguidas = alguien se está yendo"), no de pantalla, así que un
componente nunca debería escribir el número crudo.
── Qué clase se considera ────────────────────────────────────────────────
El modelo actual guarda la asistencia como `Attendance` (una fila por alumno
y clase, con `PRESENT` / `ABSENT` / `EXCUSED`) colgando de un `ClassSession`
que tiene `startsAt`. No existe columna de "clase cancelada", así que las
dos señales de que una clase no computa son:
- `status: null` — la clase pasó y nadie registró asistencia. Sin dato no hay
ni asistencia ni ausencia: no entra en el promedio y **corta** la racha (si
no, un alumno con una clase sin registrar entre dos faltas tendría una
racha que nunca ocurrió).
- `status: 'EXCUSED'` — el alumno avisó la ausencia con anticipación y le
liberaron el lugar (`SlotRelease`). Es la clase que "no cuenta": corta la
racha igual que `PRESENT` y tampoco entra en el promedio.
Sólo entran al cálculo las clases que (a) ya ocurrieron, `startsAt <= now`, y
(b) son posteriores al alta del alumno, `startsAt >= enrolledAt`. Un alumno
recién incorporado no es penalizado por clases en las que todavía no estaba
inscripto. */
/** El mismo tipo que valida `attendanceRiskLevelSchema` cuando el nivel viaja
* por la API: una sola definición para el dominio y el transporte. */
export type AttendanceRiskLevel = AttendanceRiskLevelDto;
/**
* Umbrales de la regla de riesgo. Mover estos números cambia el semáforo de
* toda la app, así que son la única fuente: nada más los hardcodea.
*/
export const ATTENDANCE_RISK_RULES = {
/** Faltas consecutivas sin justificar desde las cuales el riesgo es alto. */
highAbsenceStreak: 3,
/** Faltas consecutivas sin justificar desde las cuales hay que mirar. */
attentionAbsenceStreak: 2,
/** Días sin aparecer a una clase desde los cuales el riesgo es alto. */
highInactivityDays: 10,
/** Tamaño de cada ventana de la tendencia: 4 clases recientes vs 4 anteriores. */
trendWindowSize: 4,
/** Clases con dato necesarias para evaluar la tendencia. Con menos que esto
* (6 = 4 + 2) cualquier movimiento es ruido, no tendencia. */
trendMinClasses: 6,
/** Cuántas clases hay que haber perdido entre una ventana y la otra para que
* la tendencia cuente como "claramente" a la baja. Se cuenta en clases y no
* en puntos porcentuales a propósito: con ventana de 4 el salto más chico
* posible ya es de 25 puntos, así que un umbral en puntos no distinguiría
* "se le cayó una clase" de "se está yendo". Dos clases sí lo distingue. */
trendDropClasses: 2,
} as const;
/** Una clase del grupo, vista desde un alumno. */
export type MemberClassSession = {
sessionId: string;
/** Instante real de la clase (ISO). */
startsAt: string;
/** `null` cuando la clase pasó y no hay registro de asistencia. */
status: AttendanceStatus | null;
};
export type MemberAttendance = {
attendeeId: string;
fullName: string;
/** Momento del alta en el grupo (`Attendee.createdAt`), ISO. */
enrolledAt: string;
/** Clases del grupo. Las funciones no asumen orden ni completitud. */
sessions: MemberClassSession[];
};
export type GroupAttendanceInput = {
groupId: string;
/** `null` cuando el grupo no tiene cupo definido. */
capacity: number | null;
/** Miembros esperando cupo (`GroupWaitlistEntry` en PENDING). */
waitlistCount: number;
members: MemberAttendance[];
/** Momento de referencia. Por defecto `new Date()`. */
now?: Date;
};
export type MemberRiskSignals = {
level: AttendanceRiskLevel;
/** Faltas consecutivas sin justificar, contadas desde la clase más reciente. */
consecutiveAbsences: number;
/** Días desde la última clase con presencia, o `null` si nunca asistió a
* ninguna clase elegible. */
daysSinceLastAttendance: number | null;
/** Asistencia 0..100 sobre las clases con dato, o `null` si no hay ninguna. */
attendanceRate: number | null;
/** Clase con dato sobre las cuales se puede emitir un juicio. */
markedClasses: number;
};
export type UrgentMember = MemberRiskSignals & {
attendeeId: string;
fullName: string;
};
export type GroupAttendanceSummary = {
riesgoAlto: number;
atencion: number;
ok: number;
/** Lugares del cupo sin ocupar. Con el grupo lleno o sin cupo, 0. */
libres: number;
/** Miembros esperando cupo. */
enEspera: number;
/** Miembros que hay que mirar primero, ordenados de peor a mejor. */
urgentes: UrgentMember[];
/** El peor nivel presente en el grupo, o `null` si el grupo está vacío. */
peorNivel: AttendanceRiskLevel | null;
/** Asistencia promedio del grupo 0..100 sobre las clases con dato, o `null`. */
asistencia: number | null;
};
const DAY_MS = 24 * 60 * 60 * 1000;
/**
* Nivel de riesgo de un alumno. Es el atajo a `summarizeMemberAttendance` para
* cuando solo hace falta el semáforo.
*/
export function getMemberAttendanceRisk(
member: MemberAttendance,
now: Date = new Date(),
): AttendanceRiskLevel {
return summarizeMemberAttendance(member, now).level;
}
/** Todas las señales de un alumno, no solo el veredicto. */
export function summarizeMemberAttendance(
member: MemberAttendance,
now: Date = new Date(),
): MemberRiskSignals {
const sessions = eligibleSessions(member, now);
// `eligibleSessions` devuelve de la más antigua a la más reciente, así que la
// racha se cuenta desde el final. PRESENT, EXCUSED y las clases sin registro
// cortan la cadena: una clase justificada o sin dato no es una falta más.
let consecutiveAbsences = 0;
for (let index = sessions.length - 1; index >= 0; index -= 1) {
if (sessions[index].status !== 'ABSENT') break;
consecutiveAbsences += 1;
}
// `eligibleSessions` devuelve de la más antigua a la más reciente, así que
// "la última clase con presencia" es la primera que aparece yendo desde el
// final. (Se recorre al revés y no con `findLast` porque el target del repo es
// ES2022 y ese método es ES2023.)
const lastAttendedAt = lastPresentAt(sessions);
// Si nunca asistió a ninguna clase elegible, la referencia es la última clase
// que tuvo: "hace cuánto no lo vemos" sigue siendo cierto, y evita que un
// alumno con dos faltas de hace dos meses quede en verde para siempre.
const reference = lastAttendedAt ?? sessions.at(-1)?.startsAt;
const daysSinceLastAttendance = reference
? Math.floor((now.getTime() - new Date(reference).getTime()) / DAY_MS)
: null;
const marked = sessions.filter(isMarked);
const present = marked.filter((session) => session.status === 'PRESENT').length;
const attendanceRate = marked.length ? Math.round((present / marked.length) * 100) : null;
const level = classify(consecutiveAbsences, daysSinceLastAttendance, marked);
return {
level,
consecutiveAbsences,
daysSinceLastAttendance,
attendanceRate,
markedClasses: marked.length,
};
}
/** Veredicto: primero la racha y la inactividad, después la tendencia. */
function classify(
consecutiveAbsences: number,
daysSinceLastAttendance: number | null,
markedSessions: MemberClassSession[],
): AttendanceRiskLevel {
const rules = ATTENDANCE_RISK_RULES;
if (
consecutiveAbsences >= rules.highAbsenceStreak ||
(daysSinceLastAttendance !== null && daysSinceLastAttendance > rules.highInactivityDays)
) {
return 'riesgo_alto';
}
if (consecutiveAbsences >= rules.attentionAbsenceStreak) {
return 'atencion';
}
return isDeclining(markedSessions) ? 'atencion' : 'ok';
}
/**
* Conteo por nivel del grupo, lugares libres y los miembros más urgentes.
*
* `libres` se acota a 0 porque el detalle cuenta todos los miembros, sin
* filtro de estado: un grupo con más miembros que lugares (o con el cupo sin
* definir) tiene 0 libres, nunca negativos. Un grupo vacío tiene los tres
* conteos en 0, `libres` igual al cupo y `peorNivel` en `null`.
*/
export function getGroupAttendanceSummary(
group: GroupAttendanceInput,
): GroupAttendanceSummary {
const now = group.now ?? new Date();
const urgentes = group.members
.map((member) => ({ attendeeId: member.attendeeId, fullName: member.fullName, ...summarizeMemberAttendance(member, now) }))
.sort(byUrgency);
const riesgoAlto = urgentes.filter((member) => member.level === 'riesgo_alto').length;
const atencion = urgentes.filter((member) => member.level === 'atencion').length;
// Una parte de los miembros ya tiene señal: el promedio entre los que sí
// tienen. Los alumnos sin ninguna clase registrada no mueven la aguja.
const rates = urgentes
.map((member) => member.attendanceRate)
.filter((rate): rate is number => rate !== null);
const asistencia = rates.length
? Math.round(rates.reduce((total, rate) => total + rate, 0) / rates.length)
: null;
const occupied = group.members.length;
return {
riesgoAlto,
atencion,
ok: occupied - riesgoAlto - atencion,
libres: group.capacity === null ? 0 : Math.max(group.capacity - occupied, 0),
enEspera: group.waitlistCount,
urgentes,
peorNivel: riesgoAlto > 0 ? 'riesgo_alto' : atencion > 0 ? 'atencion' : null,
asistencia,
};
/* Orden de urgencia: peor nivel primero; dentro del mismo nivel, quien
tiene más faltas seguidas, después quien hace más que no aparece, después
quien tiene menos asistencia. El nombre nunca desempata: dos personas con
la misma señal mantienen el orden en que llegaron. */
function byUrgency(a: UrgentMember, b: UrgentMember): number {
const level = levelWeight(b.level) - levelWeight(a.level);
if (level !== 0) return level;
if (a.consecutiveAbsences !== b.consecutiveAbsences) {
return b.consecutiveAbsences - a.consecutiveAbsences;
}
const inactivity = (b.daysSinceLastAttendance ?? 0) - (a.daysSinceLastAttendance ?? 0);
if (inactivity !== 0) return inactivity;
return (a.attendanceRate ?? 101) - (b.attendanceRate ?? 101);
}
}
/**
* Asistencia de las últimas 4 clases con dato contra las 4 anteriores. Solo se
* declara la caída cuando hay historia para las dos ventanas: con una sola no
* hay contra qué comparar, y adivinar sería marcar alumnos que recién empiezan.
*
* Con ventana de 4, la diferencia mínima no nula es de una clase, que es ruido:
* por eso el umbral es de `trendDropClasses` clases perdidas y no de "cualquier
* descenso".
*/
function isDeclining(sessions: MemberClassSession[]): boolean {
const { trendWindowSize: size, trendMinClasses: minClasses, trendDropClasses: dropClasses } =
ATTENDANCE_RISK_RULES;
if (sessions.length < minClasses) return false;
// `sessions` viene de más antigua a más reciente, así que la ventana
// reciente es la cola.
const recent = sessions.slice(-size);
const previous = sessions.slice(-size * 2, -size);
if (previous.length === 0 || recent.length === 0) return false;
return present(previous) - present(recent) >= dropClasses;
function present(window: MemberClassSession[]): number {
return window.filter((session) => session.status === 'PRESENT').length;
}
}
/** Inicio de la clase con presencia más reciente, o `undefined` si no tiene ninguna. */
function lastPresentAt(sessions: MemberClassSession[]): string | undefined {
for (let index = sessions.length - 1; index >= 0; index -= 1) {
if (sessions[index].status === 'PRESENT') return sessions[index].startsAt;
}
return undefined;
}
/** Clases que ya ocurrieron y en las que el alumno ya estaba inscripto. */
function eligibleSessions(member: MemberAttendance, now: Date): MemberClassSession[] {
const enrolledAt = new Date(member.enrolledAt).getTime();
const nowMs = now.getTime();
return member.sessions
.filter((session) => {
const startsAt = new Date(session.startsAt).getTime();
return startsAt <= nowMs && startsAt >= enrolledAt;
})
.sort((a, b) => new Date(a.startsAt).getTime() - new Date(b.startsAt).getTime());
}
/** Clase con dato: sin `EXCUSED` (no computa) y sin nula (no hay registro). */
function isMarked(session: MemberClassSession): boolean {
return session.status === 'PRESENT' || session.status === 'ABSENT';
}
function levelWeight(level: AttendanceRiskLevel): number {
if (level === 'riesgo_alto') return 2;
if (level === 'atencion') return 1;
return 0;
}

View File

@@ -1,5 +1,5 @@
import { z } from 'zod'; import { z } from 'zod';
import { attendanceStatusSchema } from './attendance.js'; import { attendanceRiskLevelSchema, attendanceStatusSchema } from './attendance.js';
const isoDateTimeSchema = z.string().datetime(); const isoDateTimeSchema = z.string().datetime();
@@ -69,10 +69,44 @@ export type UpdateStudentStatusResult = z.output<typeof UpdateStudentStatusResul
export const groupRiskLevelSchema = z.enum(['NONE', 'MEDIUM', 'HIGH']); export const groupRiskLevelSchema = z.enum(['NONE', 'MEDIUM', 'HIGH']);
export type GroupRiskLevel = z.output<typeof groupRiskLevelSchema>; export type GroupRiskLevel = z.output<typeof groupRiskLevelSchema>;
/** Cuántos miembros van en la lista de urgentes del resumen. La tarjeta del
* listado solo nombra al primero o dos; el detalle tiene su propia pantalla
* de alumnos en riesgo, así que el resumen no necesita arrastrar al grupo
* entero por la red. */
export const URGENT_MEMBERS_LIMIT = 5;
export const UrgentMemberSummarySchema = z.object({
attendeeId: z.string(),
fullName: z.string(),
level: attendanceRiskLevelSchema,
consecutiveAbsences: z.number().int().min(0),
daysSinceLastAttendance: z.number().int().min(0).nullable(),
attendanceRate: z.number().min(0).max(100).nullable(),
});
export type UrgentMemberSummary = z.output<typeof UrgentMemberSummarySchema>;
/* El nivel es el peor alumno del grupo; los dos contadores dicen por qué se
dispara, para que la lista pueda nombrar el motivo en vez de un "riesgo".
Son disjuntos: un miembro con racha de faltas va solo en el primero, y el
segundo agrupa a los que solo cruzan por asistencia baja. */
export const GroupRiskSummarySchema = z.object({ export const GroupRiskSummarySchema = z.object({
groupId: z.string(), groupId: z.string(),
groupName: z.string(), groupName: z.string(),
riskLevel: groupRiskLevelSchema, riskLevel: groupRiskLevelSchema,
absenceStreakCount: z.number().int().min(0),
lowAttendanceCount: z.number().int().min(0),
/* Lo que come la tarjeta del listado y la sección de seguimiento del Inicio.
Sale de `getGroupAttendanceSummary` (packages/shared/src/lib/attendance-risk.ts),
que ya recibe todo el historial en memoria: el resumen por nivel no se puede
derivar de los dos contadores de arriba, porque "ok" es la diferencia y los
lugares libres salen del cupo, no de la asistencia. */
riesgoAlto: z.number().int().min(0),
atencion: z.number().int().min(0),
ok: z.number().int().min(0),
libres: z.number().int().min(0),
enEspera: z.number().int().min(0),
asistencia: z.number().min(0).max(100).nullable(),
urgentes: z.array(UrgentMemberSummarySchema).max(URGENT_MEMBERS_LIMIT),
}); });
export type GroupRiskSummary = z.output<typeof GroupRiskSummarySchema>; export type GroupRiskSummary = z.output<typeof GroupRiskSummarySchema>;

View File

@@ -6,6 +6,12 @@ const isoDateTimeSchema = z.string().datetime();
export const attendanceStatusSchema = z.enum(['PRESENT', 'ABSENT', 'EXCUSED']); export const attendanceStatusSchema = z.enum(['PRESENT', 'ABSENT', 'EXCUSED']);
export type AttendanceStatus = z.output<typeof attendanceStatusSchema>; export type AttendanceStatus = z.output<typeof attendanceStatusSchema>;
/* Los tres niveles del semáforo de asistencia, en el orden de la regla (de
mejor a peor). El dominio los usa como tipo y este schema los valida cuando
viajan por la API, así que hay una sola definición. */
export const attendanceRiskLevelSchema = z.enum(['ok', 'atencion', 'riesgo_alto']);
export type AttendanceRiskLevelDto = z.output<typeof attendanceRiskLevelSchema>;
export const attendeePaymentStatusSchema = z.enum(['UP_TO_DATE', 'PENDING']); export const attendeePaymentStatusSchema = z.enum(['UP_TO_DATE', 'PENDING']);
export type AttendeePaymentStatus = z.output<typeof attendeePaymentStatusSchema>; export type AttendeePaymentStatus = z.output<typeof attendeePaymentStatusSchema>;

View File

@@ -1,5 +1,7 @@
import { z } from 'zod'; import { z } from 'zod';
import { attendanceStatusSchema } from './attendance.js';
import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js'; import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js';
import { paymentStatusSchema } from './payments.js';
import { GroupWaitlistEntryDtoSchema } from './waitlist.js'; import { GroupWaitlistEntryDtoSchema } from './waitlist.js';
const isoDateTimeSchema = z.string().datetime(); const isoDateTimeSchema = z.string().datetime();
@@ -7,6 +9,11 @@ const pageSchema = createPageSchema();
const pageSizeSchema = createPageSizeSchema(10); const pageSizeSchema = createPageSizeSchema(10);
const paginationSchema = createPaginationSchema(); const paginationSchema = createPaginationSchema();
/* Cuántas clases recientes viajan por miembro en el listado. Es el tamaño de la
tira de puntos del roster, no una ventana de análisis: la analítica pide
HISTORY_SESSIONS_LIMIT clases aparte. */
export const RECENT_ATTENDANCE_LIMIT = 5;
export const AttendeeDtoSchema = z.object({ export const AttendeeDtoSchema = z.object({
id: z.string(), id: z.string(),
groupId: z.string(), groupId: z.string(),
@@ -41,8 +48,33 @@ export const AttendeeQuerySchema = z.object({
}); });
export type AttendeeQuery = z.output<typeof AttendeeQuerySchema>; export type AttendeeQuery = z.output<typeof AttendeeQuerySchema>;
/**
* Cobro del período vigente, tal como está en la base: sin columna
* desnormalizada y sin veredicto calculado. El backend devuelve el pago
* impago más reciente; el cliente decide cómo presentarlo.
*/
export const AttendeePaymentSummarySchema = z.object({
status: paymentStatusSchema,
dueDate: isoDateTimeSchema,
});
export type AttendeePaymentSummary = z.output<typeof AttendeePaymentSummarySchema>;
/**
* Item del listado de miembros: `AttendeeDto` más el resumen que la fila
* necesita para no vaciarse de datos. Es un superconjunto, así que todo
* consumidor del DTO plano sigue sirviéndose sin cambios; solo los listados
* verían estos dos campos extra.
*/
export const AttendeeListItemSchema = AttendeeDtoSchema.extend({
/** Últimas clases de más antigua a más reciente. Vacío si nunca se registró ninguna. */
recentAttendance: z.array(attendanceStatusSchema).max(RECENT_ATTENDANCE_LIMIT),
/** `null` si no hay ningún cobro impago registrado. */
payment: AttendeePaymentSummarySchema.nullable(),
});
export type AttendeeListItem = z.output<typeof AttendeeListItemSchema>;
export const AttendeeListSchema = z.object({ export const AttendeeListSchema = z.object({
data: z.array(AttendeeDtoSchema), data: z.array(AttendeeListItemSchema),
pagination: paginationSchema, pagination: paginationSchema,
}); });
export type AttendeeList = z.output<typeof AttendeeListSchema>; export type AttendeeList = z.output<typeof AttendeeListSchema>;

View File

@@ -1,5 +1,6 @@
import { z } from 'zod'; import { z } from 'zod';
import { billingTypeSchema, weekdaySchema } from './enums.js'; import { billingTypeSchema, weekdaySchema } from './enums.js';
import { timeZoneSchema } from './home.js';
import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js'; import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js';
const isoDateTimeSchema = z.string().datetime(); const isoDateTimeSchema = z.string().datetime();
@@ -44,14 +45,27 @@ export const InviteTokenResultSchema = z.object({
}); });
export type InviteTokenResult = z.output<typeof InviteTokenResultSchema>; export type InviteTokenResult = z.output<typeof InviteTokenResultSchema>;
/* En el listado cada grupo viaja con sus dos contadores de ocupación porque la
card los muestra: `attendeesCount` son los miembros del grupo (todos, igual
que cuenta el detalle) y `waitlistCount` los que están en lista de espera
esperando cupo (PENDING). La lista de pre-inscriptos es otra cosa y no
entra acá. */
export const GroupListItemSchema = GroupDtoSchema.extend({
attendeesCount: z.number().int().min(0),
waitlistCount: z.number().int().min(0),
});
export type GroupListItem = z.output<typeof GroupListItemSchema>;
export const GroupQuerySchema = z.object({ export const GroupQuerySchema = z.object({
page: pageSchema, page: pageSchema,
pageSize: pageSizeSchema, pageSize: pageSizeSchema,
// Zona de la persona: el listado se ordena por la próxima clase en su hora local.
timeZone: timeZoneSchema.optional(),
}); });
export type GroupQuery = z.output<typeof GroupQuerySchema>; export type GroupQuery = z.output<typeof GroupQuerySchema>;
export const GroupListSchema = z.object({ export const GroupListSchema = z.object({
data: z.array(GroupDtoSchema), data: z.array(GroupListItemSchema),
pagination: paginationSchema, pagination: paginationSchema,
}); });
export type GroupList = z.output<typeof GroupListSchema>; export type GroupList = z.output<typeof GroupListSchema>;

View File

@@ -19,6 +19,12 @@
"skillPath": "skills/clean-code-principles/SKILL.md", "skillPath": "skills/clean-code-principles/SKILL.md",
"computedHash": "4c22dca6110d58f1454523dc3f192ef20d91f538233da9132b407edd041a4762" "computedHash": "4c22dca6110d58f1454523dc3f192ef20d91f538233da9132b407edd041a4762"
}, },
"frontend-design": {
"source": "anthropics/skills",
"sourceType": "github",
"skillPath": "skills/frontend-design/SKILL.md",
"computedHash": "89496d5dd00f4810205f351759594fc2742bf8eea85a2f2b2d1de59f4bd91576"
},
"hono": { "hono": {
"source": "honojs/skills", "source": "honojs/skills",
"sourceType": "github", "sourceType": "github",