diff --git a/.agents/skills/frontend-design/LICENSE.txt b/.agents/skills/frontend-design/LICENSE.txt new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/.agents/skills/frontend-design/LICENSE.txt @@ -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 diff --git a/.agents/skills/frontend-design/SKILL.md b/.agents/skills/frontend-design/SKILL.md new file mode 100644 index 0000000..a533345 --- /dev/null +++ b/.agents/skills/frontend-design/SKILL.md @@ -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. diff --git a/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts index 6fbd966..fcec039 100644 --- a/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts +++ b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts @@ -4,19 +4,30 @@ import type { GroupRiskLevel, GroupRiskSummary, GroupsRiskOverview, + MemberClassSession, ProblemDetails, Result, + UrgentMemberSummary, } from '@gruperly/shared'; -import { ok } from '@gruperly/shared'; +import { getGroupAttendanceSummary, ok, URGENT_MEMBERS_LIMIT } from '@gruperly/shared'; import prisma from '@/lib/prisma'; import { buildGroupWhereForUser } from '@/modules/groups/lib'; import { classifyRisk, + MIN_RISK_ABSENCE_STREAK, + MIN_RISK_MONTHLY_RATE, monthlyAttendanceRate, trailingAbsentStreak, } from '../../lib/risk'; 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 = { db?: { group: Prisma.GroupDelegate; @@ -27,18 +38,26 @@ type GetGroupsRiskOverviewDeps = { now?: Date; }; -type GroupRow = { id: string; name: string }; -type AttendeeRow = { id: string; groupId: string }; -type SessionRow = { id: string; groupId: string }; +type GroupRow = { + id: 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 = { attendeeId: string; + classSessionId: string; status: AttendanceStatus; classSession: { startsAt: Date }; }; // 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 -// 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 { constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {} @@ -49,30 +68,39 @@ export class GetGroupsRiskOverview { const groups = (await db.group.findMany({ where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput, - select: { id: true, name: true }, - })) as GroupRow[]; + select: { + id: true, + name: true, + capacity: true, + _count: { select: { waitlist: { where: { status: 'PENDING' } } } }, + }, + })) as unknown as GroupRow[]; if (groups.length === 0) { return ok({ items: [] }); } const groupIds = groups.map((group) => group.id); - const attendeeGroup = new Map(); - const sessionCountByGroup = new Map(); const [attendees, sessions, attendances] = await Promise.all([ db.attendee.findMany({ where: { groupId: { in: groupIds }, status: 'ACTIVE' }, - select: { id: true, groupId: true }, + select: { id: true, groupId: true, fullName: true, createdAt: true }, }) as Promise, db.classSession.findMany({ where: { groupId: { in: groupIds }, startsAt: { gte: since } }, - select: { id: true, groupId: true }, + select: { id: true, groupId: true, startsAt: true }, + orderBy: { startsAt: 'desc' }, }) as Promise, + /* 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({ where: { attendee: { groupId: { in: groupIds } } }, select: { attendeeId: true, + classSessionId: true, status: true, classSession: { select: { startsAt: true } }, }, @@ -80,18 +108,24 @@ export class GetGroupsRiskOverview { }) as Promise, ]); - for (const attendee of attendees) { - attendeeGroup.set(attendee.id, attendee.groupId); - } + const sessionsByGroup = new Map(); 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 worstRiskByGroup = new Map(); + // 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(); + const lowAttendanceCountByGroup = new Map(); + for (const attendee of attendees) { - const groupId = attendeeGroup.get(attendee.id)!; + const groupId = attendee.groupId; const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({ status: row.status, occurredAt: row.classSession.startsAt, @@ -99,13 +133,19 @@ export class GetGroupsRiskOverview { const streak = trailingAbsentStreak(stream); const monthlyRate = monthlyAttendanceRate( stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()), - sessionCountByGroup.get(groupId) ?? 0, + sessionsByGroup.get(groupId)?.length ?? 0, ); const riskLevel = classifyRisk(streak, monthlyRate); if (!riskLevel) { 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'; if ( riskLevel === 'HIGH' || @@ -119,12 +159,94 @@ export class GetGroupsRiskOverview { groupId: group.id, groupName: group.name, 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 }); } } +/** + * 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, + attendanceByAttendee: Map, + 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( + (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, key: string) { + counter.set(key, (counter.get(key) ?? 0) + 1); +} + function groupAttendanceByAttendee(rows: AttendanceRow[]): Map { const byAttendee = new Map(); for (const row of rows) { @@ -133,4 +255,26 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map [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, + })); } \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/lib/risk.ts b/apps/backend/src/modules/analytics/lib/risk.ts index dc1a2af..affd8bc 100644 --- a/apps/backend/src/modules/analytics/lib/risk.ts +++ b/apps/backend/src/modules/analytics/lib/risk.ts @@ -5,6 +5,12 @@ export type AttendanceStreamEntry = { 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. // Recibe la lista ordenada de más reciente a más antigua; PRESENT y EXCUSED rompen la cadena. export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number { @@ -46,10 +52,10 @@ export function classifyRisk( consecutiveAbsences: number, monthlyRate: number, ): RiskLevel | null { - if (consecutiveAbsences >= 3) { + if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK + 1) { return 'HIGH'; } - if (consecutiveAbsences === 2 || monthlyRate < 50) { + if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK || monthlyRate < MIN_RISK_MONTHLY_RATE) { return 'MEDIUM'; } return null; diff --git a/apps/backend/src/modules/attendees/features/get-all/use-case.ts b/apps/backend/src/modules/attendees/features/get-all/use-case.ts index 0a3dd6c..c3f81a4 100644 --- a/apps/backend/src/modules/attendees/features/get-all/use-case.ts +++ b/apps/backend/src/modules/attendees/features/get-all/use-case.ts @@ -1,10 +1,10 @@ import type { PrismaClient } from '@generated/prisma/client'; 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 prisma from '@/lib/prisma'; -import { type AttendeeRecord, toAttendeeDto } from '../../lib/helpers'; +import { toAttendeeListItemDto } from '../../lib/helpers'; type ListAttendeesDeps = { db?: Pick; @@ -18,18 +18,37 @@ export class ListAttendees { const where = query.groupId ? { groupId: query.groupId } : undefined; 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({ ...(where ? { where } : {}), skip: getPaginationOffset(query), take: query.pageSize, 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(), ]); return ok({ - data: records.map((r) => toAttendeeDto(r as AttendeeRecord)), + data: records.map((record) => toAttendeeListItemDto(record)), pagination: getPaginationMetadata(query, total), }); } -} \ No newline at end of file +} diff --git a/apps/backend/src/modules/attendees/lib/helpers.ts b/apps/backend/src/modules/attendees/lib/helpers.ts index 61c8c95..7a6cde9 100644 --- a/apps/backend/src/modules/attendees/lib/helpers.ts +++ b/apps/backend/src/modules/attendees/lib/helpers.ts @@ -1,4 +1,4 @@ -import type { AttendeeDto } from '@gruperly/shared'; +import type { AttendeeDto, AttendeeListItem } from '@gruperly/shared'; export type AttendeeRecord = { id: string; @@ -14,6 +14,15 @@ export type AttendeeRecord = { 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['status']; + dueDate: Date; + }[]; +}; + export function toAttendeeDto(record: AttendeeRecord): AttendeeDto { return { 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. * Conserva el '+' si lo tiene al inicio para números internacionales. diff --git a/apps/backend/src/modules/groups/features/get-all/use-case.ts b/apps/backend/src/modules/groups/features/get-all/use-case.ts index 5da6ee2..e174ad6 100644 --- a/apps/backend/src/modules/groups/features/get-all/use-case.ts +++ b/apps/backend/src/modules/groups/features/get-all/use-case.ts @@ -8,17 +8,30 @@ import type { import { ok } from '@gruperly/shared'; import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; import prisma from '@/lib/prisma'; +import { DEFAULT_TIME_ZONE, nextClassOccurrence } from '@/modules/home/lib/scheduler'; import { buildGroupWhereForUser, type GroupDb, - type GroupRecord, - toGroupDto, + type GroupListRecord, + toGroupListItemDto, } from '../../lib'; type ListGroupsDeps = { db?: Pick; + 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 { constructor(private readonly deps: ListGroupsDeps = {}) {} @@ -27,21 +40,59 @@ export class ListGroups { userId: string, ): Promise> { const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput; - const [records, total] = await Promise.all([ - db.group.findMany({ - where, - skip: getPaginationOffset(query), - take: query.pageSize, - orderBy: { createdAt: 'desc' }, - }), - db.group.count({ where }), - ]); + // Traemos los grupos del usuario con sus contadores y los ordenamos acá: + // la próxima clase se deriva de días + hora, no hay columna por la que + // ordenar en la base. Es el mismo motor que usa el resumen de home, con la + // zona horaria de la persona (o la del servidor si no viaja). + const records: GroupListRecord[] = await db.group.findMany({ + where, + include: OCCUPANCY_COUNT_INCLUDE, + }); + + 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({ - data: records.map((record: GroupRecord) => toGroupDto(record)), - pagination: getPaginationMetadata(query, total), + data: page.map(({ record }) => toGroupListItemDto(record)), + pagination: getPaginationMetadata(query, ordered.length), }); } -} \ No newline at end of file +} + +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; +} diff --git a/apps/backend/src/modules/groups/lib/helpers.ts b/apps/backend/src/modules/groups/lib/helpers.ts index 958e7ad..52b37e4 100644 --- a/apps/backend/src/modules/groups/lib/helpers.ts +++ b/apps/backend/src/modules/groups/lib/helpers.ts @@ -1,5 +1,5 @@ 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; @@ -21,6 +21,14 @@ export type GroupRecord = { 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 { return { 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) { return { OR: [ diff --git a/apps/backend/test/analytics-groups-risk.test.ts b/apps/backend/test/analytics-groups-risk.test.ts index 2a8a2a3..5ef740f 100644 --- a/apps/backend/test/analytics-groups-risk.test.ts +++ b/apps/backend/test/analytics-groups-risk.test.ts @@ -60,39 +60,346 @@ describe('GET /groups-risk/overview', () => { }); it('marca HIGH a un grupo con un alumno con 3 ausencias consecutivas', async () => { - prismaFetchGroupFindMany([ - { id: 'group-1', name: 'Funcional' }, - { id: 'group-2', name: 'Yoga' }, - ]); - prismaFetchAttendeeFindMany([ - { id: 'a-1', groupId: 'group-1' }, - { id: 'a-2', groupId: 'group-2' }, - ]); + prismaFetchGroupFindMany([group('group-1', 'Funcional'), group('group-2', 'Yoga')]); + prismaFetchAttendeeFindMany([attendee('a-1', 'group-1'), attendee('a-2', '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-2', startsAt: at(-1) }, + { 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-2', startsAt: at(1) }, ]); prismaFetchAttendanceFindMany([ - attendance('a-1', 'ABSENT', at(-1)), - attendance('a-1', 'ABSENT', at(-2)), - attendance('a-1', 'ABSENT', at(-3)), - attendance('a-2', 'PRESENT', at(-1)), + attendance('a-1', 's1', 'ABSENT', at(1)), + attendance('a-1', 's2', 'ABSENT', at(2)), + attendance('a-1', 's3', 'ABSENT', at(3)), + attendance('a-2', 's4', 'PRESENT', at(1)), ]); const res = await makeApp({ id: userId }).request('/groups-risk/overview'); 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: [ - { 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[] }; + 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[] }; + 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[] }; + 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[] }; + 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[] }; + 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[]) { db.group.findMany.mockResolvedValue(rows); } @@ -109,6 +416,9 @@ function prismaFetchAttendanceFindMany(rows: unknown[]) { db.attendance.findMany.mockResolvedValue(rows); } -function attendance(attendeeId: string, status: string, startsAt: string) { - return { attendeeId, status, classSession: { startsAt } }; +/* El `classSessionId` importa: el resumen se arma cruzando las clases del grupo + 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 } }; } \ No newline at end of file diff --git a/apps/backend/test/attendance-risk.test.ts b/apps/backend/test/attendance-risk.test.ts new file mode 100644 index 0000000..fccd9d0 --- /dev/null +++ b/apps/backend/test/attendance-risk.test.ts @@ -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); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/attendees-incorporation.test.ts b/apps/backend/test/attendees-incorporation.test.ts index 582124b..e2608c7 100644 --- a/apps/backend/test/attendees-incorporation.test.ts +++ b/apps/backend/test/attendees-incorporation.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'; import { Hono } from 'hono'; const db = { @@ -463,6 +464,8 @@ describe('attendee incorporation & invite-token in groups', () => { notes: null, createdAt: new Date('2026-09-18T10:00:00.000Z'), updatedAt: new Date('2026-09-18T10:00:00.000Z'), + attendances: [], + payments: [], }, ] as never); prisma.attendee.count.mockResolvedValue(1); @@ -474,11 +477,28 @@ describe('attendee incorporation & invite-token in groups', () => { const data = await res.json(); expect(data.data.length).toBe(1); 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({ where: { groupId: 'group-1' }, skip: 0, take: 10, 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 }, + }, + }, }); }); }); diff --git a/apps/backend/test/attendees-list-item.test.ts b/apps/backend/test/attendees-list-item.test.ts new file mode 100644 index 0000000..4bfae10 --- /dev/null +++ b/apps/backend/test/attendees-list-item.test.ts @@ -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 { + 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'); + }); +}); diff --git a/apps/backend/test/attendees.test.ts b/apps/backend/test/attendees.test.ts index ca49895..1aa7cb0 100644 --- a/apps/backend/test/attendees.test.ts +++ b/apps/backend/test/attendees.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared'; import { Hono } from 'hono'; mock.module('@/lib/prisma', () => ({ @@ -18,7 +19,7 @@ import { attendeesRoutes } from '@/modules/attendees'; const app = new Hono(); app.route('/attendees', attendeesRoutes); -const attendee = { +const attendeeRow = { id: 'attendee-1', groupId: 'group-1', fullName: 'Ana Pérez', @@ -32,6 +33,13 @@ const attendee = { 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', () => { beforeEach(() => { vi.clearAllMocks(); @@ -47,9 +55,13 @@ describe('attendees routes', () => { expect(await res.json()).toEqual({ data: [ { - ...attendee, - createdAt: attendee.createdAt.toISOString(), - updatedAt: attendee.updatedAt.toISOString(), + ...attendeeRow, + createdAt: attendeeRow.createdAt.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 }, @@ -58,6 +70,19 @@ describe('attendees routes', () => { skip: 10, take: 10, 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(); }); diff --git a/apps/backend/test/groups.test.ts b/apps/backend/test/groups.test.ts index eaa1a53..cf9332b 100644 --- a/apps/backend/test/groups.test.ts +++ b/apps/backend/test/groups.test.ts @@ -26,6 +26,7 @@ mock.module('@/lib/prisma', () => ({ import prisma from '@/lib/prisma'; import { groupsRoutes } from '@/modules/groups'; +import { ListGroups } from '@/modules/groups/features/get-all/use-case'; const userId = 'user-1'; const group = { @@ -60,7 +61,9 @@ describe('groups routes', () => { }); 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); const res = await makeApp({ id: userId }).request('/groups'); @@ -72,6 +75,8 @@ describe('groups routes', () => { ...group, createdAt: group.createdAt.toISOString(), updatedAt: group.updatedAt.toISOString(), + attendeesCount: 4, + waitlistCount: 1, }, ], pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 }, @@ -79,13 +84,16 @@ describe('groups routes', () => { const where = { 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({ where, - skip: 0, - take: 10, - orderBy: { createdAt: 'desc' }, + include: { + _count: { + select: { attendees: true, waitlist: { where: { status: 'PENDING' } } }, + }, + }, }); - expect(prisma.group.count).toHaveBeenCalledWith({ where }); }); it('rejects listing groups without a session', async () => { @@ -101,6 +109,67 @@ describe('groups routes', () => { 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 () => { prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'merchant-1', userId }); prisma.group.create.mockResolvedValue({ diff --git a/apps/web/src/components/ui/badge.tsx b/apps/web/src/components/ui/badge.tsx index 0e559b2..31689fa 100644 --- a/apps/web/src/components/ui/badge.tsx +++ b/apps/web/src/components/ui/badge.tsx @@ -1,7 +1,7 @@ import { forwardRef, type HTMLAttributes } from 'react' import { cn } from '../../lib/utils' -export type BadgeVariant = 'success' | 'warning' | 'danger' | 'neutral' +export type BadgeVariant = 'success' | 'warning' | 'danger' | 'neutral' | 'info' export type BadgeProps = HTMLAttributes & { variant?: BadgeVariant @@ -12,6 +12,11 @@ const variants: Record = { warning: 'bg-warning-soft text-warning', danger: 'bg-danger-soft text-danger', 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( diff --git a/apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx b/apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx new file mode 100644 index 0000000..ff35aa1 --- /dev/null +++ b/apps/web/src/features/attendee-detail/AbsenceLinkSection.tsx @@ -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 ( +
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. */} + +
+ ) +} diff --git a/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx b/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx new file mode 100644 index 0000000..e378450 --- /dev/null +++ b/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx @@ -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 ` + + {isOpen ? ( + + ) : null} + + ) +} diff --git a/apps/web/src/features/attendee-detail/AttendeeAttendanceSection.tsx b/apps/web/src/features/attendee-detail/AttendeeAttendanceSection.tsx new file mode 100644 index 0000000..e13bea5 --- /dev/null +++ b/apps/web/src/features/attendee-detail/AttendeeAttendanceSection.tsx @@ -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 = { + 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 ( +
+
+ +
+
+ ) + } + + if (historyFailed) { + return ( +
+

+ No pudimos cargar la asistencia de este miembro. +

+
+ ) + } + + const sessions = history?.sessions ?? [] + + if (sessions.length === 0) { + return ( +
+

+ Todavía no hay clases registradas. +

+
+ ) + } + + const visible = visibleSessions(sessions, showAll) + const hasMore = sessions.length > HISTORY_PREVIEW + const isCapped = sessions.length >= HISTORY_LIMIT + const summary = attendanceSummary(visible) + + return ( +
+
    + {visible.map((session) => { + const Icon = iconFor(session.status) + return ( +
  • + + {formatSessionShortDate(session.startsAt)} + + + +
  • + ) + })} +
+ + {/* 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 ? ( +

{summary.unmarkedLabel}

+ ) : null} + + {showAll && isCapped ? ( +

+ El historial guarda las últimas {HISTORY_LIMIT} clases. +

+ ) : null} + + {hasMore ? ( +
+ +
+ ) : null} +
+ ) +} diff --git a/apps/web/src/features/attendee-detail/AttendeeContactActions.tsx b/apps/web/src/features/attendee-detail/AttendeeContactActions.tsx new file mode 100644 index 0000000..18d9f91 --- /dev/null +++ b/apps/web/src/features/attendee-detail/AttendeeContactActions.tsx @@ -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 ( +
+ {/* 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. */} + + + + +
+ ) +} diff --git a/apps/web/src/features/attendee-detail/AttendeeContactSection.tsx b/apps/web/src/features/attendee-detail/AttendeeContactSection.tsx new file mode 100644 index 0000000..b59ed94 --- /dev/null +++ b/apps/web/src/features/attendee-detail/AttendeeContactSection.tsx @@ -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 ( +
+
+ {email ? ( + + {email} + + ) : null} + + {notes ? ( +

{notes}

+ ) : null} +
+
+ ) +} diff --git a/apps/web/src/features/groups/detail/AttendeeDetailProvider.tsx b/apps/web/src/features/attendee-detail/AttendeeDetailProvider.tsx similarity index 65% rename from apps/web/src/features/groups/detail/AttendeeDetailProvider.tsx rename to apps/web/src/features/attendee-detail/AttendeeDetailProvider.tsx index c6ee77f..1ca56eb 100644 --- a/apps/web/src/features/groups/detail/AttendeeDetailProvider.tsx +++ b/apps/web/src/features/attendee-detail/AttendeeDetailProvider.tsx @@ -2,10 +2,9 @@ import { createContext, useContext, useState } from 'react' import type { ReactNode } from 'react' import { useQuery } from '@tanstack/react-query' import { useNavigate } from '@tanstack/react-router' -import type { AttendeeDto, AttendeeStats, GroupWaitlistEntryDto } from '@gruperly/shared' -import { useToast } from '../../../components/ui' -import { getAttendeeStats, getGroup, getGroupAttendee, getGroupWaitlist } from '../../../lib/api' -import { useRemoveAttendee } from './useRemoveAttendee' +import type { AttendeeDto, AttendeeHistory, GroupWaitlistEntryDto } from '@gruperly/shared' +import { getAttendeeHistory, getGroup, getGroupAttendee, getGroupWaitlist } from '../../lib/api' +import { useRemoveAttendee } from '../groups/detail/useRemoveAttendee' type AttendeeDetailContextValue = { groupId: string @@ -13,18 +12,17 @@ type AttendeeDetailContextValue = { attendee: AttendeeDto | undefined attendeePending: boolean attendeeFailed: boolean - attendeeStats: AttendeeStats | undefined - attendeeStatsPending: boolean - attendeeStatsFailed: boolean + history: AttendeeHistory | undefined + historyPending: boolean + historyFailed: boolean firstWaitlistEntry: GroupWaitlistEntryDto | null waitlistTotal: number waitlistPending: boolean - isRemoveModalOpen: boolean - openRemoveModal: () => void - closeRemoveModal: () => void + isRemoveDialogOpen: boolean + openRemoveDialog: () => void + closeRemoveDialog: () => void confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void isSubmittingRemoval: boolean - copyAbsenceNotifyUrl: (url: string) => void } const AttendeeDetailContext = createContext(null) @@ -38,9 +36,8 @@ export function AttendeeDetailProvider({ attendeeId: string children: ReactNode }) { - const toast = useToast() const navigate = useNavigate() - const [isRemoveModalOpen, setIsRemoveModalOpen] = useState(false) + const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false) const groupQuery = useQuery({ queryKey: ['group', groupId], @@ -54,16 +51,20 @@ export function AttendeeDetailProvider({ enabled: Boolean(groupId && attendeeId), }) - const attendeeStatsQuery = useQuery({ - queryKey: ['attendee-stats', groupId, attendeeId], - queryFn: () => getAttendeeStats(groupId, attendeeId), + // Misma clave que usa la pantalla de estadísticas: las dos leen el mismo + // historial y no se pisan la caché. + const historyQuery = useQuery({ + queryKey: ['attendee-history', groupId, attendeeId], + queryFn: () => getAttendeeHistory(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({ queryKey: ['group-waitlist', groupId], queryFn: () => getGroupWaitlist(groupId, 1, 100), - enabled: Boolean(groupId && isRemoveModalOpen), + enabled: Boolean(groupId && isRemoveDialogOpen), }) const waitlistEntries = waitlistQuery.data?.data ?? [] @@ -73,38 +74,31 @@ export function AttendeeDetailProvider({ const { removeAttendee, isRemovingAttendee } = useRemoveAttendee({ groupId, onRemoved: () => { - setIsRemoveModalOpen(false) + setIsRemoveDialogOpen(false) 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 = { groupId, groupName: groupQuery.data?.name, attendee: attendeeQuery.data, attendeePending: attendeeQuery.isPending, attendeeFailed: attendeeQuery.isError, - attendeeStats: attendeeStatsQuery.data, - attendeeStatsPending: attendeeStatsQuery.isPending, - attendeeStatsFailed: attendeeStatsQuery.isError, + history: historyQuery.data, + historyPending: historyQuery.isPending, + historyFailed: historyQuery.isError, firstWaitlistEntry, waitlistTotal, waitlistPending: waitlistQuery.isPending, - isRemoveModalOpen, - openRemoveModal: () => setIsRemoveModalOpen(true), - closeRemoveModal: () => setIsRemoveModalOpen(false), + isRemoveDialogOpen, + openRemoveDialog: () => setIsRemoveDialogOpen(true), + closeRemoveDialog: () => setIsRemoveDialogOpen(false), confirmRemoveAttendee: (promoteFromWaitlist) => { if (!attendeeQuery.data) return removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist }) }, isSubmittingRemoval: isRemovingAttendee, - copyAbsenceNotifyUrl, } return {children} diff --git a/apps/web/src/features/attendee-detail/AttendeeDetailView.tsx b/apps/web/src/features/attendee-detail/AttendeeDetailView.tsx new file mode 100644 index 0000000..cd8d48d --- /dev/null +++ b/apps/web/src/features/attendee-detail/AttendeeDetailView.tsx @@ -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(null) + + if (attendeePending) { + return ( +
+ +
+ ) + } + + if (attendeeFailed || !attendee) { + return ( +
+ {/* 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`. */} +

Miembro no encontrado

+

+ No se pudo cargar la información de este miembro. +

+ +
+ ) + } + + return ( +
+
+ +
+ +
+

+ {attendee.fullName} +

+

+ Miembro desde {formatMemberSince(attendee.createdAt)} +

+ +
+ +
+ +
+ + {/* 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. */} +
+ + + +
+ + +
+ ) +} diff --git a/apps/web/src/features/attendee-detail/AttendeePhoneLine.tsx b/apps/web/src/features/attendee-detail/AttendeePhoneLine.tsx new file mode 100644 index 0000000..b8b07d9 --- /dev/null +++ b/apps/web/src/features/attendee-detail/AttendeePhoneLine.tsx @@ -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 ( + <> + + + {copied ? 'Número copiado al portapapeles' : ''} + + + ) +} diff --git a/apps/web/src/features/attendee-detail/ConfirmRemoveAttendeeDialog.tsx b/apps/web/src/features/attendee-detail/ConfirmRemoveAttendeeDialog.tsx new file mode 100644 index 0000000..5b0bffa --- /dev/null +++ b/apps/web/src/features/attendee-detail/ConfirmRemoveAttendeeDialog.tsx @@ -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 +}) { + const { + attendee, + groupName, + firstWaitlistEntry, + waitlistTotal, + waitlistPending, + isSubmittingRemoval, + isRemoveDialogOpen, + closeRemoveDialog, + confirmRemoveAttendee, + } = useAttendeeDetail() + + const wasOpen = useRef(false) + const contentRef = useRef(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 ( + +
+
    + {consequences.map(({ icon: Icon, key, text }) => ( +
  • +
  • + ))} +
+ +

+ Si tiene cobros registrados no se va a poder quitar: primero hay que gestionarlos. +

+ + {canPromote && firstWaitlistEntry ? ( +
+

+ Si lo quitás, podés darle el lugar a{' '} + {firstWaitlistEntry.fullName}, el primero + de la lista de espera. +

+ +
+ ) : null} + +
+ + {/* 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. */} + +
+
+
+ ) +} + +/** 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) { + 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('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) +} diff --git a/apps/web/src/features/attendee-detail/Section.tsx b/apps/web/src/features/attendee-detail/Section.tsx new file mode 100644 index 0000000..638c943 --- /dev/null +++ b/apps/web/src/features/attendee-detail/Section.tsx @@ -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 `

` 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 ( +
+
+ {toggle ? ( + // El botón vive dentro del `

`: el encabezado no se pierde y el + // disparador sigue siendo un control de verdad (Enter, Espacio y foco + // visible por teclado). +

+ +

+ ) : ( +

+ {title} +

+ )} + {trailing ? ( +
+ {trailing} +
+ ) : null} +
+
{children}
+
+ ) +} diff --git a/apps/web/src/features/attendee-detail/actionButton.ts b/apps/web/src/features/attendee-detail/actionButton.ts new file mode 100644 index 0000000..fd7a01b --- /dev/null +++ b/apps/web/src/features/attendee-detail/actionButton.ts @@ -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' diff --git a/apps/web/src/features/attendee-detail/attendance.ts b/apps/web/src/features/attendee-detail/attendance.ts new file mode 100644 index 0000000..8d3e2aa --- /dev/null +++ b/apps/web/src/features/attendee-detail/attendance.ts @@ -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, + } +} diff --git a/apps/web/src/features/attendee-detail/useCopyToClipboard.ts b/apps/web/src/features/attendee-detail/useCopyToClipboard.ts new file mode 100644 index 0000000..bb59666 --- /dev/null +++ b/apps/web/src/features/attendee-detail/useCopyToClipboard.ts @@ -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 | 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 } +} diff --git a/apps/web/src/features/groups/AttendanceCapacityIndicator.tsx b/apps/web/src/features/groups/AttendanceCapacityIndicator.tsx new file mode 100644 index 0000000..ca7164d --- /dev/null +++ b/apps/web/src/features/groups/AttendanceCapacityIndicator.tsx @@ -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 + +/* 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 = { + 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 ( + + {Array.from({ length: capacity }, (_, index) => ( + + ))} + + ) + } + + return ( + + {OCCUPIED_LEVELS.map((level) => + counts[level] > 0 ? ( + + ) : null, + )} + + ) +} + +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 + return +} + +/** 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 = { + riesgo_alto: 'text-danger-fg', + atencion: 'text-warning', + ok: 'text-secondary', +} diff --git a/apps/web/src/features/groups/GroupCard.tsx b/apps/web/src/features/groups/GroupCard.tsx index fa96934..f1a0fbd 100644 --- a/apps/web/src/features/groups/GroupCard.tsx +++ b/apps/web/src/features/groups/GroupCard.tsx @@ -1,82 +1,95 @@ -import type { GroupDto, GroupRiskLevel } from '@gruperly/shared' -import { useNavigate } from '@tanstack/react-router' -import { CalendarClock, Users } from 'lucide-react' -import { Badge, Button, Tooltip } from '../../components/ui' -import { BILLING_LABELS, formatPrice, formatSchedule } from '../../lib/format' -import { cn } from '../../lib/utils' -import { RISK_HINT, RISK_LABELS } from './constants' +import type { GroupListItem, GroupRiskSummary } from '@gruperly/shared' +import { Link } from '@tanstack/react-router' +import { TriangleAlert } from 'lucide-react' +import { AttendanceCapacityIndicator } from './AttendanceCapacityIndicator' +import { + SEGMENTED_CAPACITY_MAX, + alertTextFromMembers, + capacityCountsFromMembers, + membersFromGroupAndRisk, + type GroupMember, +} from './card' -export function GroupCard({ - group, - riskLevel, -}: { - group: GroupDto - riskLevel: GroupRiskLevel -}) { - const navigate = useNavigate() - const hasSchedule = (group.days?.length ?? 0) > 0 - const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM' +const CARD_CLASS_NAME = + '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' + +export type GroupCardProps = { + id?: string + name?: string + capacity?: number + members?: GroupMember[] + group?: GroupListItem + risk?: GroupRiskSummary | undefined + link?: boolean +} + +export function GroupCard({ link = true, ...props }: GroupCardProps) { + const linkId = props.id ?? props.group?.id + + if (link && linkId) { + return ( + + + + ) + } return ( -
-
-
-

{group.name}

- {group.description ? ( -

{group.description}

- ) : null} -
-
- {hasRisk ? ( - // Mismo tooltip que en el detalle: el badge es corto y la - // explicación (abandono, no cobranza) la da el tooltip. - - - - - ) : null} - Activo -
-
- - {hasSchedule ? ( -
-
- - {formatSchedule(group.days ?? [], group.time)} -
-
- - - 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}` : ''} - -
-
- ) : ( -

Aún sin plan de cobro configurado.

- )} - -
- -
-
+
+ +
) -} \ No newline at end of file +} + +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 ( + <> +

+ {name} +

+ +
+ + + + {members.length}/{capacity} {capacity === 1 ? 'miembro' : 'miembros'} + +
+ + {alertText ? ( +

+

+ ) : null} + + ) +} + diff --git a/apps/web/src/features/groups/GroupsView.tsx b/apps/web/src/features/groups/GroupsView.tsx index 76d0ab1..321d889 100644 --- a/apps/web/src/features/groups/GroupsView.tsx +++ b/apps/web/src/features/groups/GroupsView.tsx @@ -1,9 +1,11 @@ import { useQuery } from '@tanstack/react-query' 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 { getGroups, getGroupsRiskOverview } from '../../lib/api' import { GroupCard } from './GroupCard' +import { MOCK_TEST_CASES } from './card' export function GroupsView() { const navigate = useNavigate() @@ -16,26 +18,49 @@ export function GroupsView() { 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( - (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 (
-
-

Grupos

-

Tus grupos de cobranza.

+

Grupos

+
+ {!hasGroups && groupsQuery.isSuccess ? ( + + ) : null} +
-
{groupsQuery.isPending ? ( -
- +
+
) : null} @@ -48,34 +73,57 @@ export function GroupsView() {
) : null} - {groupsQuery.isSuccess && groupsQuery.data.data.length === 0 ? ( -
-

Todavía no tenés grupos

-

- Crea tu primer grupo para empezar a cobrar. -

- + {showExamples ? ( +
+ {MOCK_TEST_CASES.map((group) => ( + + ))}
) : 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. */ +
+ + +

Todavía no tenés grupos

+

+ Creá tu primer grupo y empezá a cobrar las cuotas de tus alumnos. +

+
+ + +
+
+ ) : null} + + {hasGroups && !showExamples ? (
{groupsQuery.data.data.map((group) => ( ))}
) : null}
) -} \ No newline at end of file +} + diff --git a/apps/web/src/features/groups/card.ts b/apps/web/src/features/groups/card.ts new file mode 100644 index 0000000..764234a --- /dev/null +++ b/apps/web/src/features/groups/card.ts @@ -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 + +/** 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, + 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, + })), + ], + }, +] + diff --git a/apps/web/src/features/groups/constants.ts b/apps/web/src/features/groups/constants.ts index 8b5a273..13ef940 100644 --- a/apps/web/src/features/groups/constants.ts +++ b/apps/web/src/features/groups/constants.ts @@ -8,4 +8,8 @@ export const RISK_LABELS: Record, string> = { /* 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. */ export const RISK_HINT = - 'Riesgo de abandono: probabilidad estimada de que algún miembro abandone el grupo.' \ No newline at end of file + '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. */ diff --git a/apps/web/src/features/groups/detail/AttendeeAttendanceStats.tsx b/apps/web/src/features/groups/detail/AttendeeAttendanceStats.tsx deleted file mode 100644 index cea2ad4..0000000 --- a/apps/web/src/features/groups/detail/AttendeeAttendanceStats.tsx +++ /dev/null @@ -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 = { - good: 'bg-success', - mid: 'bg-warning', - low: 'bg-danger', - none: 'bg-border', -} - -const valueTone: Record = { - good: 'text-success', - mid: 'text-warning', - low: 'text-danger', - none: 'text-foreground/40', -} - -export function AttendeeAttendanceStats() { - const { attendeeStats, attendeeStatsPending, attendeeStatsFailed } = useAttendeeDetail() - - if (attendeeStatsPending) { - return ( -
- -
- ) - } - - if (attendeeStatsFailed || !attendeeStats) { - return ( -
- No pudimos cargar la asistencia de este participante. -
- ) - } - - const { presentCount, absentCount, excusedCount, totalMarked, attendanceRate } = attendeeStats - const tone = rateTone(attendanceRate, totalMarked) - - return ( -
-
-
-

- Asistencia -

-

- {totalMarked > 0 - ? `Sobre ${totalMarked} clases registradas` - : 'Sin clases registradas todavía'} -

-
-

- {totalMarked > 0 ? `${attendanceRate}%` : '—'} -

-
- - - ) -} - -function StatCounter({ - value, - label, - valueClass, -}: { - value: number - label: string - valueClass: string -}) { - return ( -
-
{label}
-
{value}
-
- ) -} diff --git a/apps/web/src/features/groups/detail/AttendeeDetailPage.tsx b/apps/web/src/features/groups/detail/AttendeeDetailPage.tsx deleted file mode 100644 index 6fe07c9..0000000 --- a/apps/web/src/features/groups/detail/AttendeeDetailPage.tsx +++ /dev/null @@ -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 ( -
- -
- ) - } - - if (attendeeFailed || !attendee) { - return ( -
-

Participante no encontrado

-

No se pudo cargar la información de este participante.

- -
- ) - } - - const absenceNotifyUrl = attendee.notifyToken - ? `${window.location.origin}/report-absence/${attendee.notifyToken}` - : null - - return ( -
- - - Volver al grupo - - -
-
- {attendee.fullName.charAt(0).toUpperCase()} -
-
-

{attendee.fullName}

-

- {groupName ? `${groupName} · ` : ''}Incorporado el{' '} - {new Date(attendee.createdAt).toLocaleDateString('es-ES', { - day: 'numeric', - month: 'long', - year: 'numeric', - })} -

-
-
- - - -
- } label="Teléfono"> - {attendee.phone ? ( -
- {formatPhoneDisplay(attendee.phone)} - - - WhatsApp - -
- ) : ( - Sin teléfono - )} -
- - } label="Email"> - {attendee.email ? ( - - {attendee.email} - - ) : ( - Sin email - )} - - - {attendee.guardianName || attendee.guardianPhone ? ( - <> - } label="Responsable"> - - {attendee.guardianName || —} - - - {attendee.guardianPhone ? ( - } label="Tel. Responsable"> -
- {formatPhoneDisplay(attendee.guardianPhone)} - - - -
-
- ) : null} - - ) : null} - - } label="Notas"> - {attendee.notes ? ( - {attendee.notes} - ) : ( - Sin notas - )} - -
- - {absenceNotifyUrl ? ( -
-

Link para avisar ausencias

-
- - {absenceNotifyUrl} - - -
- {attendee.phone ? ( - - - Enviar por WhatsApp - - ) : null} -
- ) : null} - -
- -
- - -
- ) -} diff --git a/apps/web/src/features/groups/detail/GroupDetailProvider.tsx b/apps/web/src/features/groups/detail/GroupDetailProvider.tsx index 0e6befe..cfeb5f9 100644 --- a/apps/web/src/features/groups/detail/GroupDetailProvider.tsx +++ b/apps/web/src/features/groups/detail/GroupDetailProvider.tsx @@ -3,6 +3,7 @@ import type { ReactNode } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import type { AttendeeDto, + AttendeeListItem, GroupDto, GroupPreRegistrationDto, GroupWaitlistEntryDto, @@ -29,9 +30,11 @@ export type ListSection = 'members' | 'pending' type GroupDetailContextValue = { groupId: string group: GroupDto | undefined + /** Nombre para el título grande: dato real, caché o "Grupo" mientras carga. */ + groupTitle: string groupQueryPending: boolean riskLevel: GroupRiskLevel - attendees: AttendeeDto[] + attendees: AttendeeListItem[] attendeesTotal: number attendeesPending: boolean waitlistEntries: GroupWaitlistEntryDto[] @@ -47,6 +50,9 @@ type GroupDetailContextValue = { whatsappMessage: string searchFilter: string setSearchFilter: (value: string) => void + /** La lista de miembros se reduce a quienes tienen el cobro vencido. */ + overdueOnly: boolean + setOverdueOnly: (value: boolean) => void listSection: ListSection setListSection: (value: ListSection) => void isInviteModalOpen: boolean @@ -88,12 +94,14 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState(null) const [selectedPreRegistration, setSelectedPreRegistration] = useState(null) 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 - // limpia para no heredar un filtro sin coincidencias. + // Los controles de la lista pertenecen a la vista que los abrió: al cambiar de + // pestaña se limpian para no heredar un filtro sin coincidencias. const setListSection = (value: ListSection) => { setListSectionState(value) setSearchFilter('') + setOverdueOnly(false) } const groupQuery = useQuery({ @@ -283,9 +291,16 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch 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(['group', groupId])?.name + const groupTitle = group?.name ?? cachedGroupName ?? 'Grupo' + const value: GroupDetailContextValue = { groupId, group, + groupTitle, groupQueryPending: groupQuery.isPending, riskLevel: riskOverviewQuery.data?.items.find((item) => item.groupId === groupId)?.riskLevel ?? 'NONE', attendees, @@ -304,6 +319,8 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch whatsappMessage, searchFilter, setSearchFilter, + overdueOnly, + setOverdueOnly, listSection, setListSection, isInviteModalOpen, diff --git a/apps/web/src/features/groups/detail/GroupDetailView.tsx b/apps/web/src/features/groups/detail/GroupDetailView.tsx index 0443279..e8c56eb 100644 --- a/apps/web/src/features/groups/detail/GroupDetailView.tsx +++ b/apps/web/src/features/groups/detail/GroupDetailView.tsx @@ -23,31 +23,34 @@ export function GroupDetailView() { } = useGroupDetail() const navigate = useNavigate() - if (groupQueryPending) { - return ( -
- -
- ) - } - - if (!group) { - return ( -
-

Grupo no encontrado

-

No se pudo cargar la información de este grupo.

- -
- ) - } - return (
+ {/* 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. */} - - + + {groupQueryPending ? ( +
+ +
+ ) : !group ? ( +
+

Grupo no encontrado

+

No se pudo cargar la información de este grupo.

+ +
+ ) : ( + <> + + + + )} {/* 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. */} -
- - - {hasRisk ? ( - // El badge no puede llevar texto largo sin ensuciar el header: la - // explicación (riesgo de abandono, no de cobranza) vive en el tooltip. - - - - - ) : null} -
+ {hasGroup ? ( +
+ + + {hasRisk ? ( + // El badge no puede llevar texto largo sin ensuciar el header: la + // explicación (riesgo de abandono, no de cobranza) vive en el tooltip. + + + + + ) : null} +
+ ) : null} {group?.description ? (

@@ -78,47 +85,52 @@ export function GroupHeader() { ) : null} -

- {/* `h-11` (44px) para todos: objetivo táctil mínimo. */} - {!isEmptyGroup ? ( - // Un solo primario por pantalla: "Agregar" encabeza la jerarquía y - // las acciones de apoyo quedan debajo en outline. - - ) : null} - - {!isEmptyGroup ? ( + {hasGroup ? ( + // Una sola fila en mobile: el primario toma el ancho que sobra y las dos + // acciones de apoyo se pliegan a iconos de 44px. En sm+ recuperan el + // texto porque hay ancho de sobra y el rótulo hace más claro el destino. +
+ {!isEmptyGroup ? ( + // Un solo primario por pantalla: "Agregar" encabeza la jerarquía y + // las acciones de apoyo quedan al lado, en outline. + + ) : null} - ) : null} -
+ {!isEmptyGroup ? ( + + ) : null} +
+ ) : null}
) } diff --git a/apps/web/src/features/groups/detail/GroupInfoCard.tsx b/apps/web/src/features/groups/detail/GroupInfoCard.tsx index 440aa09..27e5116 100644 --- a/apps/web/src/features/groups/detail/GroupInfoCard.tsx +++ b/apps/web/src/features/groups/detail/GroupInfoCard.tsx @@ -1,4 +1,4 @@ -import { CalendarClock, Users } from 'lucide-react' +import { CalendarClock, CircleDollarSign, Users } from 'lucide-react' import { formatBillingMeta, formatPrice, @@ -88,9 +88,7 @@ export function GroupInfoCard() {
-
- $ -
+

Cobro

diff --git a/apps/web/src/features/groups/detail/MembersList.tsx b/apps/web/src/features/groups/detail/MembersList.tsx new file mode 100644 index 0000000..1186f30 --- /dev/null +++ b/apps/web/src/features/groups/detail/MembersList.tsx @@ -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 = { + settled: 'text-foreground', + dueSoon: 'font-medium text-warning', + overdue: 'font-semibold text-danger', +} + +function PaymentLabel({ state }: { state: PaymentState }) { + return ( + + {state.kind === 'settled' ? ( + + ) +} + +function AttendanceStrip({ recent }: { recent: AttendanceStatus[] }) { + const summary = summarizeAttendance(recent) + + if (summary.recorded === 0) { + return

{summary.label}

+ } + + return ( +
+ {/* Cada punto lleva su propio nombre accesible: el color solo es el + refuerzo visual, no la única forma de saber qué pasó. */} + + {summary.dots.map((status, index) => ( + + ))} + + {summary.label} +
+ ) +} + +function MemberRow({ + attendee, + groupId, +}: { + attendee: AttendeeListItem + groupId: string +}) { + const paymentState = resolvePaymentState(attendee.payment) + + return ( + , 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', + )} + > +
+
+ + {attendee.fullName} + + {paymentState ? : null} +
+ +
+ + ) +} + +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 ( +
    + {attendees.map((attendee) => ( +
  • + +
  • + ))} +
+ ) +} diff --git a/apps/web/src/features/groups/detail/MembersTable.tsx b/apps/web/src/features/groups/detail/MembersTable.tsx deleted file mode 100644 index 7bbef5c..0000000 --- a/apps/web/src/features/groups/detail/MembersTable.tsx +++ /dev/null @@ -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 ( - - - - - - - - - - {attendees.map((attendee) => ( - openAttendee(attendee.id)} - onKeyDown={(e) => { - if (e.key === 'Enter' || e.key === ' ') { - e.preventDefault() - openAttendee(attendee.id) - } - }} - > - - {/* 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. */} - - - - ))} - -
NombreTeléfono - Detalle -
-
-
- {attendee.fullName.charAt(0).toUpperCase()} -
- {/* `truncate` solo recorta lo pintado: el texto completo sigue en - el DOM para lectores de pantalla, y `title` lo muestra al hover. */} - - {attendee.fullName} - -
-
- {attendee.phone ? ( - - {formatPhoneDisplay(attendee.phone)} - - ) : ( - — - )} - - -
- ) -} diff --git a/apps/web/src/features/groups/detail/MembersView.tsx b/apps/web/src/features/groups/detail/MembersView.tsx index 4aafdfc..e0f1f7f 100644 --- a/apps/web/src/features/groups/detail/MembersView.tsx +++ b/apps/web/src/features/groups/detail/MembersView.tsx @@ -1,22 +1,70 @@ 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 { cn } from '../../../lib/utils' 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 ( +
+ +
+ ) +} export function MembersView() { - const { groupId, attendees, attendeesPending, searchFilter, openInviteModal } = useGroupDetail() + const { + groupId, + attendees, + attendeesPending, + searchFilter, + overdueOnly, + openInviteModal, + } = useGroupDetail() const navigate = useNavigate() const query = searchFilter.trim().toLowerCase() - const filtered = query - ? attendees.filter( - (a) => - a.fullName.toLowerCase().includes(query) || - (a.phone && a.phone.includes(query)) || - (a.email && a.email.toLowerCase().includes(query)), - ) - : attendees + // El teléfono no se muestra en la fila, pero sigue siendo una vía de búsqueda: + // es como la mayoría conoce a los alumnos del grupo. + const matchesQuery = (attendee: (typeof attendees)[number]) => + !query || + attendee.fullName.toLowerCase().includes(query) || + (attendee.phone != null && attendee.phone.includes(query)) || + (attendee.email != null && attendee.email.toLowerCase().includes(query)) + + 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) { return ( @@ -28,7 +76,7 @@ export function MembersView() { if (attendees.length === 0) { return ( -
+

Todavía no hay miembros en este grupo @@ -40,7 +88,7 @@ export function MembersView() {

) } - if (filtered.length === 0) { + const filterBar = overdueCount > 0 ? : 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 ( -
- No se encontraron miembros que coincidan con la búsqueda. -
+ <> + {filterBar} +
+ {overdueOnly + ? 'Ningún miembro con pago vencido coincide con la búsqueda.' + : 'No se encontraron miembros que coincidan con la búsqueda.'} +
+ ) } - return + return ( + <> + {filterBar} + + + ) } diff --git a/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx b/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx index b2ec9a8..2999c26 100644 --- a/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx +++ b/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx @@ -1,46 +1,58 @@ import { Search } from 'lucide-react' import { Input } from '../../../components/ui' +import { MEMBER_SEARCH_MIN } from './constants' import { useGroupDetail } from './GroupDetailProvider' import { MembersView } from './MembersView' import { PendingView } from './PendingView' import { SectionChips } from './SectionChips' 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 ( - // Radios concéntricos: `rounded-2xl` (16px) con `p-2` (8px) deja a las - // superficies interiores un radio de 16 - 8 = 8px, o sea `rounded-lg`. - // Sin bordes: el lavado `bg-primary-soft` separa la sección del fondo. -
-
+ // Una sola superficie: la lista va directo sobre el lavado, como la info + // card de arriba, en vez de anidarse en una caja más clara. La separación + // entre controles y datos la dan los propios divisores de fila, el tono + // propio del input y el borde de los chips; una caja intermedia solo + // 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. +
+
-
- - setSearchFilter(e.target.value)} - aria-label="Buscar en el listado" - className="h-11 rounded-lg border-transparent pl-9 shadow-xs placeholder:text-foreground/80" - /> -
+ {showSearch ? ( +
+ + setSearchFilter(e.target.value)} + aria-label="Buscar en el listado" + className="h-11 rounded-lg border-transparent pl-9 shadow-xs" + /> +
+ ) : null}
- {/* Copia de apoyo: un solo bloque, ancho acotado y sin competir con - los datos. Explica la diferencia entre ambos estados. */} -

- {listSection === 'members' - ? 'Listado de todos los miembros incorporados al grupo.' - : 'Pre-inscripciones que esperan tu aprobación y personas en lista de espera por un cupo libre.'} -

+ {/* Solo Pendientes lleva copia de apoyo: explica la diferencia entre + pre-inscripción y lista de espera, que no se deduce de los nombres. + En Miembros los rótulos de columna ya dicen todo. */} + {listSection === 'pending' ? ( +

+ Pre-inscripciones que esperan tu aprobación y personas en lista de espera por un cupo + libre. +

+ ) : null}
-
- {listSection === 'members' ? : } -
+ {listSection === 'members' ? : }
) } diff --git a/apps/web/src/features/groups/detail/PendingView.tsx b/apps/web/src/features/groups/detail/PendingView.tsx index adbb80b..4c008a1 100644 --- a/apps/web/src/features/groups/detail/PendingView.tsx +++ b/apps/web/src/features/groups/detail/PendingView.tsx @@ -37,7 +37,10 @@ export function PendingView() { if (!hasAnyEntry && !query) { return ( -
+ // 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. +

No hay pendientes

@@ -47,7 +50,7 @@ export function PendingView() {

@@ -94,7 +97,7 @@ export function PendingView() { return (
-
+