feat(api): add timezone support for group fetching and increase page size

feat(attendance): refactor attendance summary logic and update tests

feat(analytics): extend GroupRiskSummary schema with absence and attendance counts

feat(groups): enhance group schema with attendee and waitlist counts

chore(skills): add frontend design skill with guidelines and license

feat(attendee-detail): implement AttendeePhoneLine component for phone display

feat(groups): create AttendanceBadge and CapacityIndicator components for group cards

feat(groups): add card utility functions for attendance alerts and capacity summaries

test(groups): implement tests for attendance alert and capacity summary logic
This commit is contained in:
Jose Selesan
2026-09-30 17:39:13 -03:00
parent 4e86096653
commit 454f20ed25
31 changed files with 1323 additions and 250 deletions

View File

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

View File

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

View File

@@ -12,6 +12,8 @@ import prisma from '@/lib/prisma';
import { buildGroupWhereForUser } from '@/modules/groups/lib'; import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { import {
classifyRisk, classifyRisk,
MIN_RISK_ABSENCE_STREAK,
MIN_RISK_MONTHLY_RATE,
monthlyAttendanceRate, monthlyAttendanceRate,
trailingAbsentStreak, trailingAbsentStreak,
} from '../../lib/risk'; } from '../../lib/risk';
@@ -38,7 +40,8 @@ type AttendanceRow = {
// Resumen de semáforo de riesgo por grupo para la lista de grupos. // Resumen de semáforo de riesgo por grupo para la lista de grupos.
// Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si // Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si
// alguno en riesgo moderado y NONE en caso contrario. // alguno en riesgo moderado y NONE en caso contrario. Los contadores dicen el
// motivo (faltas seguidas o asistencia baja) para que la lista pueda nombrarlo.
export class GetGroupsRiskOverview { export class GetGroupsRiskOverview {
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {} constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
@@ -90,6 +93,12 @@ export class GetGroupsRiskOverview {
const streamByAttendee = groupAttendanceByAttendee(attendances); const streamByAttendee = groupAttendanceByAttendee(attendances);
const worstRiskByGroup = new Map<string, GroupRiskLevel>(); const worstRiskByGroup = new Map<string, GroupRiskLevel>();
// Por qué hay riesgo, en la misma pasada: un miembro con racha de faltas
// cuenta en el primero y solo en ese; el segundo agrupa a los que no llegan
// a racha y aun así quedan por debajo del mínimo de asistencia.
const absenceStreakCountByGroup = new Map<string, number>();
const lowAttendanceCountByGroup = new Map<string, number>();
for (const attendee of attendees) { for (const attendee of attendees) {
const groupId = attendeeGroup.get(attendee.id)!; const groupId = attendeeGroup.get(attendee.id)!;
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({ const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
@@ -106,6 +115,12 @@ export class GetGroupsRiskOverview {
continue; continue;
} }
if (streak >= MIN_RISK_ABSENCE_STREAK) {
bump(absenceStreakCountByGroup, groupId);
} else if (monthlyRate < MIN_RISK_MONTHLY_RATE) {
bump(lowAttendanceCountByGroup, groupId);
}
const current = worstRiskByGroup.get(groupId) ?? 'NONE'; const current = worstRiskByGroup.get(groupId) ?? 'NONE';
if ( if (
riskLevel === 'HIGH' || riskLevel === 'HIGH' ||
@@ -119,12 +134,18 @@ export class GetGroupsRiskOverview {
groupId: group.id, groupId: group.id,
groupName: group.name, groupName: group.name,
riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE', riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE',
absenceStreakCount: absenceStreakCountByGroup.get(group.id) ?? 0,
lowAttendanceCount: lowAttendanceCountByGroup.get(group.id) ?? 0,
})); }));
return ok({ items }); return ok({ items });
} }
} }
function bump(counter: Map<string, number>, key: string) {
counter.set(key, (counter.get(key) ?? 0) + 1);
}
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> { function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
const byAttendee = new Map<string, AttendanceRow[]>(); const byAttendee = new Map<string, AttendanceRow[]>();
for (const row of rows) { for (const row of rows) {

View File

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

View File

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

View File

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

View File

@@ -86,8 +86,82 @@ describe('GET /groups-risk/overview', () => {
expect(res.status).toBe(200); expect(res.status).toBe(200);
expect(await res.json()).toEqual({ expect(await res.json()).toEqual({
items: [ items: [
{ groupId: 'group-1', groupName: 'Funcional', riskLevel: 'HIGH' }, {
{ groupId: 'group-2', groupName: 'Yoga', riskLevel: 'NONE' }, groupId: 'group-1',
groupName: 'Funcional',
riskLevel: 'HIGH',
absenceStreakCount: 1,
lowAttendanceCount: 0,
},
{
groupId: 'group-2',
groupName: 'Yoga',
riskLevel: 'NONE',
absenceStreakCount: 0,
lowAttendanceCount: 0,
},
],
});
});
it('cuenta el motivo: faltas seguidas y asistencia baja, sin repetir alumnos', async () => {
prismaFetchGroupFindMany([
{ id: 'group-1', name: 'Funcional' },
{ id: 'group-2', name: 'Yoga' },
]);
prismaFetchAttendeeFindMany([
{ id: 'a-1', groupId: 'group-1' },
{ id: 'a-2', groupId: 'group-1' },
{ id: 'a-3', groupId: 'group-1' },
{ id: 'b-1', groupId: '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', 'ABSENT', at(-1)),
attendance('a-1', 'ABSENT', at(-2)),
attendance('a-1', 'PRESENT', at(-3)),
// Sin racha, pero asiste menos de la mitad de las clases del mes.
attendance('a-2', 'PRESENT', at(-1)),
attendance('a-2', 'ABSENT', at(-2)),
attendance('a-2', 'ABSENT', at(-3)),
attendance('a-2', 'ABSENT', at(-4)),
// Al día.
attendance('a-3', 'PRESENT', at(-1)),
attendance('a-3', 'PRESENT', at(-2)),
attendance('a-3', 'PRESENT', at(-3)),
attendance('a-3', 'PRESENT', at(-4)),
// Otra vez por racha, en el otro grupo.
attendance('b-1', 'ABSENT', at(-1)),
attendance('b-1', 'ABSENT', at(-2)),
]);
const res = await makeApp({ id: userId }).request('/groups-risk/overview');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
items: [
{
groupId: 'group-1',
groupName: 'Funcional',
riskLevel: 'MEDIUM',
absenceStreakCount: 1,
lowAttendanceCount: 1,
},
{
groupId: 'group-2',
groupName: 'Yoga',
riskLevel: 'MEDIUM',
absenceStreakCount: 1,
lowAttendanceCount: 0,
},
], ],
}); });
}); });

View File

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

View File

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

View File

@@ -1,9 +1,9 @@
import { useId, useState } from 'react' import { useId, useState } from 'react'
import { Check, ChevronDown, Copy, MessageCircle } from 'lucide-react' import { Check, Copy, MessageCircle } from 'lucide-react'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { useAttendeeDetail } from './AttendeeDetailProvider' import { useAttendeeDetail } from './AttendeeDetailProvider'
import { ACTION_BUTTON_CLASS } from './actionButton' import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
import { SECTION_TITLE_CLASS, Section } from './Section' import { Section } from './Section'
import { useCopyToClipboard } from './useCopyToClipboard' import { useCopyToClipboard } from './useCopyToClipboard'
export function AbsenceLinkSection() { export function AbsenceLinkSection() {
@@ -25,66 +25,52 @@ export function AbsenceLinkSection() {
return ( return (
<Section <Section
title={ title="Link de ausencias"
<button toggle={{ isOpen, panelId, onToggle: () => setIsOpen((value) => !value) }}
type="button"
onClick={() => setIsOpen((value) => !value)}
aria-expanded={isOpen}
aria-controls={panelId}
className={cn(
SECTION_TITLE_CLASS,
'flex min-h-11 w-full items-center gap-1.5 text-left',
)}
>
Link de ausencias
<ChevronDown
className={cn('size-4 transition-transform', isOpen && 'rotate-180')}
aria-hidden="true"
/>
</button>
}
> >
{/* El panel queda en el DOM pero oculto: `aria-controls` siempre resuelve y {/* 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. */} el texto de "Link copiado" no se pierde al plegar y desplegar. */}
<div id={panelId} hidden={!isOpen}> <div id={panelId} hidden={!isOpen}>
<div className="pt-1"> <p className="text-sm text-foreground">
<p className="text-sm text-foreground"> Mandales este link para que avisen cuando no puedan venir.
Mandales este link para que avisen cuando no puedan venir. </p>
</p> {/* Apiladas y a ancho completo: al 50% los rótulos ("Enviar por WhatsApp")
<div className="mt-2.5 flex flex-col gap-2 sm:flex-row"> se partían en dos líneas y quedaban por debajo del mínimo táctil.
<button Copiar queda arriba, pegado a su confirmación, y la acción principal
type="button" se distingue por el relleno de acento. */}
onClick={() => copy(url)} <div className="mt-2.5 flex flex-col gap-2">
className={cn(ACTION_BUTTON_CLASS, 'flex-1')} <button
> type="button"
<Copy className="size-4" aria-hidden="true" /> onClick={() => copy(url)}
Copiar link className={cn(ACTION_BUTTON_CLASS, 'w-full')}
</button>
{shareUrl ? (
<a
href={shareUrl}
target="_blank"
rel="noopener noreferrer"
aria-label={`Enviar el link por WhatsApp a ${attendee.fullName}`}
className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
>
<MessageCircle className="size-4" aria-hidden="true" />
Enviar por WhatsApp
</a>
) : null}
</div>
<p
aria-live="polite"
className="flex min-h-5 items-center gap-1.5 pt-2 text-xs font-medium text-success"
> >
{copied ? ( <Copy className="size-4" aria-hidden="true" />
<> Copiar link
<Check className="size-3.5" aria-hidden="true" /> </button>
Link copiado {shareUrl ? (
</> <a
) : null} href={shareUrl}
</p> target="_blank"
rel="noopener noreferrer"
aria-label={`Enviar el link por WhatsApp a ${attendee.fullName}`}
className={PRIMARY_ACTION_CLASS}
>
<MessageCircle className="size-4" aria-hidden="true" />
Enviar por WhatsApp
</a>
) : null}
</div> </div>
<p
aria-live="polite"
className="flex min-h-5 items-center gap-1.5 pt-2 text-xs font-medium text-success"
>
{copied ? (
<>
<Check className="size-3.5" aria-hidden="true" />
Link copiado
</>
) : null}
</p>
</div> </div>
</Section> </Section>
) )

View File

@@ -7,7 +7,7 @@ import { cn } from '../../lib/utils'
import { import {
attendanceStatusClass, attendanceStatusClass,
attendanceStatusLabel, attendanceStatusLabel,
attendanceSummaryLabel, attendanceSummary,
formatSessionShortDate, formatSessionShortDate,
HISTORY_LIMIT, HISTORY_LIMIT,
HISTORY_PREVIEW, HISTORY_PREVIEW,
@@ -67,14 +67,15 @@ export function AttendeeAttendanceSection() {
const visible = visibleSessions(sessions, showAll) const visible = visibleSessions(sessions, showAll)
const hasMore = sessions.length > HISTORY_PREVIEW const hasMore = sessions.length > HISTORY_PREVIEW
const isCapped = sessions.length >= HISTORY_LIMIT const isCapped = sessions.length >= HISTORY_LIMIT
const summary = attendanceSummary(visible)
return ( return (
<Section title="Asistencia" trailing={attendanceSummaryLabel(visible)}> <Section title="Asistencia" trailing={summary.label}>
<ul className="divide-y divide-border/60"> <ul className="divide-y divide-border/60">
{visible.map((session) => { {visible.map((session) => {
const Icon = iconFor(session.status) const Icon = iconFor(session.status)
return ( return (
<li key={session.classSessionId} className="flex items-center justify-between gap-3 py-2.5"> <li key={session.classSessionId} className="flex items-center justify-between gap-3 py-2">
<span className="truncate text-sm text-primary"> <span className="truncate text-sm text-primary">
{formatSessionShortDate(session.startsAt)} {formatSessionShortDate(session.startsAt)}
</span> </span>
@@ -92,6 +93,12 @@ export function AttendeeAttendanceSection() {
})} })}
</ul> </ul>
{/* Las clases sin registro no son ausencias: se avisa aparte y en voz baja
para que el "1 de 1" de arriba no se lea como un fallo. */}
{summary.unmarkedLabel ? (
<p className="pt-2 text-right text-xs text-foreground">{summary.unmarkedLabel}</p>
) : null}
{showAll && isCapped ? ( {showAll && isCapped ? (
<p className="pt-2 text-xs text-foreground"> <p className="pt-2 text-xs text-foreground">
El historial guarda las últimas {HISTORY_LIMIT} clases. El historial guarda las últimas {HISTORY_LIMIT} clases.
@@ -104,7 +111,7 @@ export function AttendeeAttendanceSection() {
variant="ghost" variant="ghost"
onClick={() => setShowAll((value) => !value)} onClick={() => setShowAll((value) => !value)}
aria-expanded={showAll} aria-expanded={showAll}
className="h-11 gap-1 px-2 text-sm text-accent hover:text-accent-strong" className="h-11 gap-1 px-2 text-sm text-accent-fg hover:text-primary"
> >
{showAll ? 'Ver menos' : `Ver todas (${sessions.length})`} {showAll ? 'Ver menos' : `Ver todas (${sessions.length})`}
<ChevronDown className={cn('size-4 transition-transform', showAll && 'rotate-180')} /> <ChevronDown className={cn('size-4 transition-transform', showAll && 'rotate-180')} />

View File

@@ -16,6 +16,9 @@ export function AttendeeContactActions() {
return ( return (
<div className="flex gap-2.5"> <div className="flex gap-2.5">
{/* Los íconos van con `accent-fg` y no con `accent`: el azul de `accent` es
el mismo en los dos temas y sobre `primary-soft` oscuro queda en 2.2:1.
`accent-fg` da 6.2:1 en claro y 7.1:1 en oscuro. */}
<a <a
href={`https://wa.me/${digits}`} href={`https://wa.me/${digits}`}
target="_blank" target="_blank"
@@ -23,7 +26,7 @@ export function AttendeeContactActions() {
aria-label={`Abrir WhatsApp con ${label}`} aria-label={`Abrir WhatsApp con ${label}`}
className={cn(ACTION_BUTTON_CLASS, 'flex-1')} className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
> >
<MessageCircle className="size-4 text-accent" aria-hidden="true" /> <MessageCircle className="size-4 text-accent-fg" aria-hidden="true" />
WhatsApp WhatsApp
</a> </a>
<a <a
@@ -31,7 +34,7 @@ export function AttendeeContactActions() {
aria-label={`Llamar a ${label}`} aria-label={`Llamar a ${label}`}
className={cn(ACTION_BUTTON_CLASS, 'flex-1')} className={cn(ACTION_BUTTON_CLASS, 'flex-1')}
> >
<Phone className="size-4 text-accent" aria-hidden="true" /> <Phone className="size-4 text-accent-fg" aria-hidden="true" />
Llamar Llamar
</a> </a>
</div> </div>

View File

@@ -1,64 +1,37 @@
import { Check, Copy, Mail } from 'lucide-react' import { Mail } from 'lucide-react'
import { cn } from '../../lib/utils'
import { formatPhoneDisplay } from '../../lib/format'
import { useAttendeeDetail } from './AttendeeDetailProvider' import { useAttendeeDetail } from './AttendeeDetailProvider'
import { Section } from './Section' import { Section } from './Section'
import { useCopyToClipboard } from './useCopyToClipboard'
const ROW_CLASS = const ROW_CLASS =
'flex w-full min-h-11 items-center justify-between gap-3 rounded-lg py-2.5 transition-colors hover:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent' 'flex w-full min-h-11 items-center justify-between gap-3 rounded-lg 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() { export function AttendeeContactSection() {
const { attendee } = useAttendeeDetail() const { attendee } = useAttendeeDetail()
const { copied, copy } = useCopyToClipboard()
if (!attendee) return null if (!attendee) return null
const phone = attendee.phone
const phoneLabel = formatPhoneDisplay(phone)
const { email, notes } = attendee const { email, notes } = attendee
// Sin datos no hay sección: no se dibujan filas con "Sin email"/"Sin notas". if (!email && !notes) return null
if (!phoneLabel && !email && !notes) return null
return ( return (
<Section title="Contacto"> <Section title="Contacto">
<div className="divide-y divide-border/60"> <div className="divide-y divide-border/60">
{phone && phoneLabel ? (
<div className="flex items-center gap-3">
<button
type="button"
onClick={() => copy(phone)}
className={cn(ROW_CLASS, 'min-w-0 flex-1 text-left')}
>
<span className="truncate text-base text-primary">{phoneLabel}</span>
<span className="flex shrink-0 items-center gap-1.5 text-xs font-medium text-foreground">
{copied ? (
<Check className="size-4 text-success" aria-hidden="true" />
) : (
<Copy className="size-4" aria-hidden="true" />
)}
{copied ? 'Copiado' : 'Copiar'}
</span>
</button>
{/* La confirmación visible no se anuncia sola: va en una región viva
aparte para no ensuciar el nombre accesible del botón. */}
<span aria-live="polite" className="sr-only">
{copied ? 'Teléfono copiado al portapapeles' : ''}
</span>
</div>
) : null}
{email ? ( {email ? (
<a href={`mailto:${email}`} className={ROW_CLASS}> <a href={`mailto:${email}`} className={ROW_CLASS}>
<span className="truncate text-base text-primary">{email}</span> <span className="truncate text-sm text-primary">{email}</span>
<Mail className="size-4 shrink-0 text-foreground" aria-hidden="true" /> <Mail className="size-4 shrink-0 text-foreground" aria-hidden="true" />
</a> </a>
) : null} ) : null}
{notes ? ( {notes ? (
<p className="whitespace-pre-line py-2.5 text-sm leading-relaxed text-primary"> <p className="whitespace-pre-line py-2 text-sm leading-relaxed text-primary">{notes}</p>
{notes}
</p>
) : null} ) : null}
</div> </div>
</Section> </Section>

View File

@@ -7,6 +7,7 @@ import { AttendeeActionsMenu } from './AttendeeActionsMenu'
import { AttendeeAttendanceSection } from './AttendeeAttendanceSection' import { AttendeeAttendanceSection } from './AttendeeAttendanceSection'
import { AttendeeContactActions } from './AttendeeContactActions' import { AttendeeContactActions } from './AttendeeContactActions'
import { AttendeeContactSection } from './AttendeeContactSection' import { AttendeeContactSection } from './AttendeeContactSection'
import { AttendeePhoneLine } from './AttendeePhoneLine'
import { useAttendeeDetail } from './AttendeeDetailProvider' import { useAttendeeDetail } from './AttendeeDetailProvider'
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog' import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
import { formatMemberSince } from './attendance' import { formatMemberSince } from './attendance'
@@ -36,7 +37,7 @@ export function AttendeeDetailView() {
</p> </p>
<Button <Button
variant="ghost" variant="ghost"
className="mt-4 px-0 text-accent hover:bg-transparent hover:text-accent-strong" className="mt-4 px-0 text-accent-fg hover:bg-transparent hover:text-primary"
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })} onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
> >
Volver al grupo Volver al grupo
@@ -67,15 +68,17 @@ export function AttendeeDetailView() {
<p className="mt-1 whitespace-nowrap text-sm text-foreground"> <p className="mt-1 whitespace-nowrap text-sm text-foreground">
Miembro desde {formatMemberSince(attendee.createdAt)} Miembro desde {formatMemberSince(attendee.createdAt)}
</p> </p>
<AttendeePhoneLine />
</div> </div>
<div className="mt-4"> <div className="mt-3">
<AttendeeContactActions /> <AttendeeContactActions />
</div> </div>
{/* Orden por frecuencia de uso. Sumar Pagos es insertar un bloque más {/* Orden por frecuencia de uso. Sumar Pagos es insertar un bloque más
arriba de Asistencia; el layout no se toca. */} arriba de Asistencia; cada sección lleva su propio aire, así que el
<div className="mt-6 space-y-5"> layout no se toca. */}
<div className="mt-5">
<AttendeeAttendanceSection /> <AttendeeAttendanceSection />
<AttendeeContactSection /> <AttendeeContactSection />
<AbsenceLinkSection /> <AbsenceLinkSection />

View File

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

View File

@@ -1,40 +1,82 @@
import { useId } from 'react' import { useId } from 'react'
import type { ReactNode } 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 /* 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. */ ~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' 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. */
const TOGGLE_ROW_CLASS = cn(
SECTION_TITLE_CLASS,
'flex min-h-11 w-full items-center justify-between gap-2 rounded-lg 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 = { type SectionProps = {
/** Título de la sección. Un string por lo general; un botón cuando la /** Título de la sección. Un string por lo general. */
* sección se despliega desde el propio título (ver Link de ausencias). */
title: ReactNode title: ReactNode
/** A la derecha del título: el resumen de asistencia, por ejemplo. */ /** A la derecha del título: el resumen de asistencia, por ejemplo. */
trailing?: ReactNode trailing?: ReactNode
/** Cuando está, el título entero es el disparador del contenido y `title` es
* solo su rótulo: el `<h2>` sigue siendo el encabezado de la sección y el
* botón ocupa la fila completa. */
toggle?: { isOpen: boolean; panelId: string; onToggle: () => void }
children: ReactNode children: ReactNode
} }
/** Bloque de sección: separador fino sobre el fondo, título chico en /** Bloque de sección: separador fino sobre el fondo, título chico en
* mayúsculas y contenido sin padding propio (el de la pantalla). * mayúsculas y contenido sin padding propio (el de la pantalla).
* *
* La pantalla se arma apilando secciones en este orden, así que sumar una * El aire vive acá y no en la pantalla: cada sección cierra con su propio
* nueva (Pagos, por ejemplo) es insertar otro bloque y nada más. */ * padding, así que el separador queda siempre a la misma distancia del
export function Section({ title, trailing, children }: SectionProps) { * 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() const headingId = useId()
return ( return (
<section aria-labelledby={headingId} className="border-t border-border/70 pt-5"> <section aria-labelledby={headingId} className="border-t border-border/70 py-4">
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
<h2 id={headingId} className={SECTION_TITLE_CLASS}> {toggle ? (
{title} // El botón vive dentro del `<h2>`: el encabezado no se pierde y el
</h2> // disparador sigue siendo un control de verdad (Enter, Espacio y foco
// visible por teclado).
<h2 id={headingId} className="min-w-0 flex-1">
<button
type="button"
aria-expanded={toggle.isOpen}
aria-controls={toggle.panelId}
onClick={toggle.onToggle}
className={TOGGLE_ROW_CLASS}
>
<span className="truncate">{title}</span>
<ChevronDown
className={cn(
'size-4 shrink-0 transition-transform',
toggle.isOpen && 'rotate-180',
)}
aria-hidden="true"
/>
</button>
</h2>
) : (
<h2 id={headingId} className={SECTION_TITLE_CLASS}>
{title}
</h2>
)}
{trailing ? ( {trailing ? (
<div className="shrink-0 text-xs font-semibold tabular-nums text-foreground"> <div className="shrink-0 text-xs font-semibold tabular-nums text-foreground">
{trailing} {trailing}
</div> </div>
) : null} ) : null}
</div> </div>
<div className="mt-2.5">{children}</div> <div className="mt-2">{children}</div>
</section> </section>
) )
} }

View File

@@ -6,3 +6,10 @@
* el mismo anillo de foco y feedback de presión que el `Button` de la app. */ * el mismo anillo de foco y feedback de presión que el `Button` de la app. */
export const ACTION_BUTTON_CLASS = 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' 'inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-primary-soft px-3 text-sm font-medium text-primary transition-colors hover:bg-accent-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
/** Acción principal de un panel (Enviar por WhatsApp). Misma superficie que el
* `Button` `primary` de la app —relleno `accent` con texto `on-accent`, que
* da 6.8:1 en los dos temas— pero a ancho completo porque sola en la columna:
* al lado de la secundaria al 50% los rótulos largos se parten en dos líneas. */
export const PRIMARY_ACTION_CLASS =
'inline-flex h-11 w-full items-center justify-center gap-2 rounded-xl bg-accent px-4 text-sm font-medium text-on-accent transition-colors hover:bg-accent-strong active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'

View File

@@ -70,8 +70,34 @@ export function visibleSessions(
return showAll ? ordered : ordered.slice(0, HISTORY_PREVIEW) return showAll ? ordered : ordered.slice(0, HISTORY_PREVIEW)
} }
/** "3 de 5 clases", contando solo las sesiones que se están mostrando. */ /** Clases con asistencia registrada: asistió, faltó o faltó con aviso. Las
export function attendanceSummaryLabel(sessions: AttendanceSession[]): string { * "Sin registrar" no cuentan: sin dato no hay ni asistencia ni ausencia, y
const present = sessions.filter((session) => session.status === 'PRESENT').length * meterlas en el denominador hacía que "1 de 3" se leyera como dos ausencias. */
return `${present} de ${classCountLabel(sessions.length)}` function markedSessions(sessions: AttendanceSession[]): AttendanceSession[] {
return sessions.filter((session) => session.status != null)
}
export type AttendanceSummary = {
/** "1 de 1 clase", o "Sin clases registradas" si no hay ninguna con dato. */
label: string
/** "2 sin registrar", o `null` si no hay clases sin registro. */
unmarkedLabel: string | null
}
/** Resumen de las filas que se están mostrando: cuántas clases registró la
* persona sobre cuántas hay con dato, y cuántas quedaron sin registrar.
*
* El texto de las "sin registrar" se apaga cuando no hay ninguna clase
* registrada: el resumen ya dice que no hay datos y los dos textos dirían lo
* mismo dos veces. */
export function attendanceSummary(sessions: AttendanceSession[]): AttendanceSummary {
const marked = markedSessions(sessions)
if (marked.length === 0) return { label: 'Sin clases registradas', unmarkedLabel: null }
const present = marked.filter((session) => session.status === 'PRESENT').length
const unmarked = sessions.length - marked.length
return {
label: `${present} de ${classCountLabel(marked.length)}`,
unmarkedLabel: unmarked > 0 ? `${unmarked} sin registrar` : null,
}
} }

View File

@@ -0,0 +1,45 @@
import { TriangleAlert } from 'lucide-react'
import { cn } from '../../lib/utils'
import type { AttendanceAlert } from './card'
/**
* Badge compacto de alerta de asistencia: ícono de advertencia + la cantidad
* de miembros afectados.
*
* El número solo no se explica: en el caso grave se le suma el motivo corto
* ("bajo 50%", "con faltas"), porque un "⚠ 6" suelto al lado de "12/20 miembros"
* se lee como otro dato del cupo. El caso leve se queda con el número —la
* tarjeta es una lista, no un informe— y la frase entera vive en el `title`
* y en el nombre accesible.
*
* Nunca lleva relleno sólido: los dos casos son translúcidos, y lo que los
* diferencia es el tono (ámbar `warning` vs naranja `warning-strong`) y ese
* texto extra. Contraste del texto sobre su propio fondo: 7.0:1 en oscuro y
* 4.8:1 en claro.
*
* El badge NO usa el `Tooltip` del repo: ese envuelve al disparador en un
* `<button>` y acá el disparador es el padre, un link que ocupa toda la
* tarjeta (un botón dentro de un link no es HTML válido y rompe la
* navegación). En su lugar el texto completo viaja como `aria-label` (con
* `role="img"`, que reemplaza lo visible por la frase al calcular el nombre
* accesible del enlace) y como `title` para el puntero de ratón.
*/
export function AttendanceBadge({ alert }: { alert: AttendanceAlert }) {
const severe = alert.severity === 'high'
return (
<span
role="img"
aria-label={alert.label}
title={alert.label}
className={cn(
'inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium tabular-nums',
severe ? 'bg-warning-strong-soft text-warning-strong' : 'bg-warning-soft text-warning',
)}
>
<TriangleAlert className="size-3 shrink-0" aria-hidden="true" />
{alert.count}
{severe ? <span>{alert.short}</span> : null}
</span>
)
}

View File

@@ -0,0 +1,72 @@
import { Users } from 'lucide-react'
import { Badge } from '../../components/ui'
import { capacitySummary } from './card'
/**
* Bloque de metadatos de la tarjeta: texto de ocupación, barrita fina y el
* badge neutro de lista de espera. Va con `shrink-0` porque la fila de arriba
* hace wrap: si algo tiene que bajar de línea, que sea el badge de alerta,
* no un número de cupo recortado.
*
* El texto "12/20 miembros" es el que se lee de verdad y el que queda en el
* nombre accesible del enlace; la barrita está para que la proporcion se
* escanee de un vistazo sin tener que restar. Por eso el track va al 30% y no
* al 20%: así se ve la parte que falta (1.9:1 contra la tarjeta) sin que el
* relleno pierda su contraste contra el fondo de la barra (3.8:1).
*
* Nada de esto se pinta de amarillo: el amarillo es solo para la alerta de
* asistencia, así que el cupo lleno se lee por el "20/20" y, cuando hay gente
* esperando, por el badge. Los colores salen de `accent-fg`, que es la tinta
* de acento legible (7.1:1 en oscuro, 6.2:1 en claro); el `accent` directo
* sobre la tarjeta oscura da 2.2:1 y no alcanza el mínimo de 3:1.
*/
export function CapacityIndicator({
attendeesCount,
capacity,
waitlistCount,
}: {
attendeesCount: number
capacity: number | null
waitlistCount: number
}) {
const { label, occupancy, hasCapacity, isFull, waitlistCount: waiting } = capacitySummary(
attendeesCount,
capacity,
waitlistCount,
)
return (
<div className="flex shrink-0 items-center gap-2">
<Users className="size-4 shrink-0 text-accent-fg" aria-hidden="true" />
<span className="shrink-0 text-sm tabular-nums text-secondary">{label}</span>
{hasCapacity ? (
/* Va `aria-hidden` a propósito: el texto de al lado ya dice "12/20
miembros" y es el que tiene que leerse (y annonce el enlace entero).
Anunciarlo también como progressbar solo sumaba "12 de 20 lugares
ocupados" al nombre accesible de la tarjeta, que es toda la card. */
<span
aria-hidden="true"
className="h-1.5 w-14 shrink-0 overflow-hidden rounded-full bg-accent-fg/30"
>
<span
className="block h-full rounded-full bg-accent-fg transition-[width] duration-300 ease-out"
style={{ width: `${Math.round(occupancy * 100)}%` }}
/>
</span>
) : null}
{waiting > 0 ? (
<Badge
variant="info"
title={`${waiting} ${waiting === 1 ? 'persona' : 'personas'} en lista de espera`}
>
{waiting} en espera
</Badge>
) : null}
{isFull && waiting === 0 ? <span className="sr-only">Cupo completo</span> : null}
</div>
)
}

View File

@@ -1,82 +1,93 @@
import type { GroupDto, GroupRiskLevel } from '@gruperly/shared' import type { GroupListItem, GroupRiskSummary } from '@gruperly/shared'
import { useNavigate } from '@tanstack/react-router' import { Link } from '@tanstack/react-router'
import { CalendarClock, Users } from 'lucide-react' import { CalendarClock, ChevronRight } from 'lucide-react'
import { Badge, Button, Tooltip } from '../../components/ui' import { formatPrice, formatSchedule } from '../../lib/format'
import { BILLING_LABELS, formatPrice, formatSchedule } from '../../lib/format'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { RISK_HINT, RISK_LABELS } from './constants' import { AttendanceBadge } from './AttendanceBadge'
import { CapacityIndicator } from './CapacityIndicator'
import { attendanceAlert, billingSuffix } from './card'
/* Toda la card es el link al grupo: nombre, horario y cupo quedan dentro, así
que el nombre accesible del enlace ya los anuncia y no hace falta un
aria-label aparte. La superficie va rellena (la misma `primary-soft` que la
ficha del grupo) porque el borde fino sobre el fondo se perdía en tema
oscuro.
El borde derecho es un riel rígido de tres pistas —`1fr · auto · 1rem`— en
vez de posiciones absolutas: el precio y la flecha comparten el mismo
track, así que su límite derecho es idéntico en todas las tarjetas sin
importar cuánto mida el nombre o el precio. El precio se alinea con la
primera línea (junto al nombre) y la flecha también, para que la fila se
lea como una sola cosa.
La fila de metadatos hace wrap: con cupo de dos dígitos, gente en espera y
la alerta, no entra en 360px y preferimos que el badge baje de línea antes
que recortar un número. El bloque de cupo va con `shrink-0` para que sea
siempre el último en caer. */
export function GroupCard({ export function GroupCard({
group, group,
riskLevel, risk,
}: { }: {
group: GroupDto group: GroupListItem
riskLevel: GroupRiskLevel risk: GroupRiskSummary | undefined
}) { }) {
const navigate = useNavigate() const days = group.days ?? []
const hasSchedule = (group.days?.length ?? 0) > 0 const hasSchedule = days.length > 0
const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM' const hasPrice = group.price != null
const suffix = billingSuffix(group.billingType)
const alert = attendanceAlert(risk, group.attendeesCount)
// La misma regla que usa el badge para el color: cuando media matrícula o
// más está atrasada, la tarjeta entera se marca. El anillo va `inset` (no
// agrega borde ni cambia el alto) y al 40% porque un trazo fuerte rompe el
// tono de la lista — es refuerzo visual, el que se lee sin color es el
// badge, que ya pasa 4.5:1.
const severe = alert?.severity === 'high'
return ( return (
<article className="rounded-xl border border-border bg-surface p-5 transition-all hover:border-accent/40"> <Link
<div className="flex items-start justify-between gap-3"> to="/groups/$groupId"
<div className="min-w-0"> params={{ groupId: group.id }}
<h3 className="truncate text-base font-semibold text-primary">{group.name}</h3> className={cn(
{group.description ? ( 'block rounded-xl bg-primary-soft p-4 transition-colors duration-150 ease-out hover:bg-accent-soft focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none active:bg-accent-soft/60',
<p className="mt-0.5 truncate text-sm text-foreground/60">{group.description}</p> severe && 'ring-1 ring-warning-strong/40 ring-inset',
) : null}
</div>
<div className="flex flex-col items-end gap-1.5">
{hasRisk ? (
// Mismo tooltip que en el detalle: el badge es corto y la
// explicación (abandono, no cobranza) la da el tooltip.
<Tooltip content={RISK_HINT} tooltipClassName="left-auto right-0">
<Badge variant={riskLevel === 'HIGH' ? 'danger' : 'warning'} className="gap-1.5">
<span
className={cn(
'size-2 rounded-full',
riskLevel === 'HIGH' ? 'bg-danger' : 'bg-warning',
)}
aria-hidden="true"
/>
{RISK_LABELS[riskLevel]}
</Badge>
</Tooltip>
) : null}
<Badge variant="success">Activo</Badge>
</div>
</div>
{hasSchedule ? (
<dl className="mt-4 space-y-2 text-sm">
<div className="flex items-center gap-2 text-foreground/70">
<CalendarClock className="size-4 shrink-0 text-accent" />
<span>{formatSchedule(group.days ?? [], group.time)}</span>
</div>
<div className="flex items-center gap-2 text-foreground/70">
<Users className="size-4 shrink-0 text-accent" />
<span>
Cupo {group.capacity ?? '—'} miembros
{group.price != null
? ` · ${formatPrice(group.price)}${group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''}`
: ''}
{group.dueDay != null ? ` · vence el día ${group.dueDay}` : ''}
</span>
</div>
</dl>
) : (
<p className="mt-4 text-sm text-foreground/50">Aún sin plan de cobro configurado.</p>
)} )}
>
<div className="grid grid-cols-[minmax(0,1fr)_auto_1rem] items-start gap-x-2">
<h3 className="col-start-1 row-start-1 truncate text-base font-semibold text-primary">
{group.name}
</h3>
<div className="mt-4 flex items-center justify-end gap-2 border-t border-border pt-3"> {hasPrice ? (
<Button <p className="col-start-2 row-start-1 whitespace-nowrap text-base font-semibold tabular-nums text-primary">
variant="outline" {formatPrice(group.price)}
size="sm" {suffix ? (
onClick={() => void navigate({ to: `/groups/${group.id}` })} <span className="text-sm font-medium text-secondary">{suffix}</span>
> ) : null}
Gestionar Miembros </p>
</Button> ) : null}
<ChevronRight
className="col-start-3 row-start-1 mt-1 size-4 shrink-0 text-secondary/50"
aria-hidden="true"
/>
<p className="col-start-1 row-start-2 mt-1 flex min-w-0 items-center gap-2 text-sm text-secondary">
<CalendarClock className="size-4 shrink-0 text-accent-fg" aria-hidden="true" />
<span className="truncate">
{hasSchedule ? formatSchedule(days, group.time) : 'Sin horario definido'}
</span>
</p>
<div className="col-span-3 row-start-3 mt-2 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1.5">
<CapacityIndicator
attendeesCount={group.attendeesCount}
capacity={group.capacity}
waitlistCount={group.waitlistCount}
/>
{alert ? <AttendanceBadge alert={alert} /> : null}
</div>
</div> </div>
</article> </Link>
) )
} }

View File

@@ -1,6 +1,6 @@
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router' import { useNavigate } from '@tanstack/react-router'
import { Loader2, Plus } from 'lucide-react' import { CalendarPlus, Loader2, Plus } from 'lucide-react'
import { Button } from '../../components/ui' import { Button } from '../../components/ui'
import { getGroups, getGroupsRiskOverview } from '../../lib/api' import { getGroups, getGroupsRiskOverview } from '../../lib/api'
import { GroupCard } from './GroupCard' import { GroupCard } from './GroupCard'
@@ -17,25 +17,30 @@ export function GroupsView() {
}) })
const riskByGroup = new Map( const riskByGroup = new Map(
(riskQuery.data?.items ?? []).map((item) => [item.groupId, item.riskLevel]), (riskQuery.data?.items ?? []).map((item) => [item.groupId, item]),
) )
return ( return (
<section> <section>
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
<div> <h1 className="text-2xl font-bold text-primary">Grupos</h1>
<h1 className="text-2xl font-bold text-primary">Grupos</h1> {/* `h-11` arriba del `md` del primitivo: son 40px y el mínimo táctil es
<p className="mt-2 text-sm text-foreground/60">Tus grupos de cobranza.</p> 44. Se sube acá y no en `Button` porque cambiar la altura del
</div> primitivo mueve todas las pantallas de la app de un golpe. */}
<Button variant="primary" onClick={() => void navigate({ to: '/groups/new' })}> <Button
variant="primary"
className="h-11"
onClick={() => void navigate({ to: '/groups/new' })}
>
<Plus className="size-4" /> <Plus className="size-4" />
Crear Nuevo grupo
</Button> </Button>
</div> </div>
{groupsQuery.isPending ? ( {groupsQuery.isPending ? (
<div className="mt-8 flex items-center justify-center py-16"> <div className="mt-8 flex items-center justify-center py-16" role="status">
<Loader2 className="size-6 animate-spin text-foreground/40" /> <Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
<span className="sr-only">Cargando grupos</span>
</div> </div>
) : null} ) : null}
@@ -49,29 +54,34 @@ export function GroupsView() {
) : null} ) : null}
{groupsQuery.isSuccess && groupsQuery.data.data.length === 0 ? ( {groupsQuery.isSuccess && groupsQuery.data.data.length === 0 ? (
<div className="mt-8 rounded-xl border border-dashed border-border bg-surface px-4 py-12 text-center"> /* Un ícono solo, con un punto focal, y el texto en secundario: la
<p className="font-medium text-primary">Todavía no tenés grupos</p> pantalla vacía compite con la acción y no puede ganar. */
<p className="mt-1 text-sm text-foreground/60"> <div className="mt-8 rounded-xl bg-primary-soft px-5 py-12 text-center">
Crea tu primer grupo para empezar a cobrar. <span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg">
<CalendarPlus className="size-7" aria-hidden="true" />
</span>
<p className="mt-4 text-base font-semibold text-primary">Todavía no tenés grupos</p>
<p className="mx-auto mt-1.5 max-w-[30ch] text-sm leading-relaxed text-secondary">
Creá tu primer grupo y empezá a cobrar las cuotas de tus alumnos.
</p> </p>
<Button <Button
variant="primary" variant="primary"
className="mt-5" className="mt-6 h-11"
onClick={() => void navigate({ to: '/groups/new' })} onClick={() => void navigate({ to: '/groups/new' })}
> >
<Plus className="size-4" /> <Plus className="size-4" />
Crear tu primer grupo Crear primer grupo
</Button> </Button>
</div> </div>
) : null} ) : null}
{groupsQuery.isSuccess && groupsQuery.data.data.length > 0 ? ( {groupsQuery.isSuccess && groupsQuery.data.data.length > 0 ? (
<div className="mt-6 grid gap-4"> <div className="mt-6 grid gap-3">
{groupsQuery.data.data.map((group) => ( {groupsQuery.data.data.map((group) => (
<GroupCard <GroupCard
key={group.id} key={group.id}
group={group} group={group}
riskLevel={riskByGroup.get(group.id) ?? 'NONE'} risk={riskByGroup.get(group.id)}
/> />
))} ))}
</div> </div>

View File

@@ -0,0 +1,129 @@
import type { BillingType, GroupRiskSummary } 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.
La API manda dos contadores disjuntos por grupo (`absenceStreakCount` y
`lowAttendanceCount`): miembros que acumulan 2+ faltas seguidas sin
justificar, o que cruzan el mínimo mensual de asistencia. Ver
`apps/backend/src/modules/analytics/lib/risk.ts`. */
export type AttendanceAlert = {
/** Miembros que disparan la regla. Es el número que va en el badge. */
count: number
/** Frase entera: "4 miembros con asistencia menor al 50%". Va como nombre accesible y title. */
label: string
severity: AttendanceSeverity
/** Texto corto que acompaña al número cuando el caso es grave: "bajo 50%", "con faltas". */
short: string
}
/* Umbral de severidad: desde la mitad de los miembros el problema ya no es de
una persona suelta sino del grupo, y por eso el badge cambia de color y la
tarjeta se tiñe. Antes de ese umbral alcanza con marcarlo sin robarle el
foco a la tarjeta. Se compara contra la matrícula, no contra el cupo: el
cupo puede no estar definido o ser mucho mayor que la cantidad real de
miembros. */
const PROMINENT_SHARE = 0.5
export type AttendanceSeverity = 'low' | 'high'
/**
* Única fuente de la regla de severidad: la usan la tarjeta (para el borde) y
* el badge (para el color y el texto), así que no pueden desincronizarse.
*/
export function getAttendanceSeverity(
affectedCount: number,
attendeesCount: number,
): AttendanceSeverity {
if (attendeesCount <= 0) return 'low'
return affectedCount / attendeesCount >= PROMINENT_SHARE ? 'high' : 'low'
}
/**
* Qué alerta de asistencia corresponde al grupo, si alguna.
*
* Cuando hay miembros de los dos tipos solo se reporta el de faltas seguidas:
* es la señal más accionable (alguien se está yendo) y en un badge chico una
* sola frase alcanza para explicar el ícono. La ficha del grupo y las
* estadísticas sí muestran las dos.
*/
export function attendanceAlert(
risk: GroupRiskSummary | undefined,
attendeesCount: number,
): AttendanceAlert | null {
const reason = dominantReason(risk)
if (!reason || attendeesCount <= 0) return null
return {
count: reason.count,
label: `${membersLabel(reason.count)} ${reason.text}`,
severity: getAttendanceSeverity(reason.count, attendeesCount),
short: reason.short,
}
}
/* `short` es el texto que se suma al número cuando el caso es grave: el número
solo no dice por qué, y la versión larga se reserva para el title y para el
nombre accesible. El detalle entero vive en la ficha del grupo. */
function dominantReason(
risk: GroupRiskSummary | undefined,
): { count: number; short: string; text: string } | null {
if (!risk) return null
if (risk.absenceStreakCount > 0) {
return {
count: risk.absenceStreakCount,
short: 'con faltas',
text: 'con faltas seguidas',
}
}
if (risk.lowAttendanceCount > 0) {
return {
count: risk.lowAttendanceCount,
short: 'bajo 50%',
text: 'con asistencia menor al 50%',
}
}
return null
}
export type CapacitySummary = {
/** "4/5 miembros", o "1 miembro" cuando el grupo no tiene cupo definido. */
label: string
/** 0..1, para la barrita de ocupación. 0 cuando no hay cupo. */
occupancy: number
hasCapacity: boolean
isFull: boolean
waitlistCount: number
}
export function capacitySummary(
attendeesCount: number,
capacity: number | null,
waitlistCount: number,
): CapacitySummary {
const hasCapacity = capacity != null
return {
// Con cupo la unidad es el lugar ("1/5 miembros"), así que el plural no
// depende de cuánta gente haya: depende del denominador.
label: hasCapacity ? `${attendeesCount}/${capacity} miembros` : membersLabel(attendeesCount),
occupancy: hasCapacity && capacity > 0 ? Math.min(attendeesCount / capacity, 1) : 0,
hasCapacity,
isFull: hasCapacity && attendeesCount >= capacity,
waitlistCount,
}
}
/** Sufijo del precio según cómo se cobra: "/mes" o "/clase". */
export function billingSuffix(billingType: BillingType | null): string | null {
if (billingType === 'MONTHLY') return '/mes'
if (billingType === 'PER_CLASS') return '/clase'
return null
}
function membersLabel(count: number): string {
return count === 1 ? '1 miembro' : `${count} miembros`
}

View File

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

View File

@@ -49,6 +49,7 @@
--color-primary: var(--primary); --color-primary: var(--primary);
--color-primary-soft: var(--primary-soft); --color-primary-soft: var(--primary-soft);
--color-foreground: var(--foreground); --color-foreground: var(--foreground);
--color-secondary: var(--secondary);
--color-accent: var(--accent); --color-accent: var(--accent);
--color-accent-strong: var(--accent-strong); --color-accent-strong: var(--accent-strong);
--color-accent-soft: var(--accent-soft); --color-accent-soft: var(--accent-soft);
@@ -60,6 +61,8 @@
--color-success-soft: var(--success-soft); --color-success-soft: var(--success-soft);
--color-warning: var(--warning); --color-warning: var(--warning);
--color-warning-soft: var(--warning-soft); --color-warning-soft: var(--warning-soft);
--color-warning-strong: var(--warning-strong);
--color-warning-strong-soft: var(--warning-strong-soft);
--color-danger: var(--danger); --color-danger: var(--danger);
--color-danger-soft: var(--danger-soft); --color-danger-soft: var(--danger-soft);
@@ -116,6 +119,12 @@
--primary: #0f172a; --primary: #0f172a;
--primary-soft: #f1f5f9; --primary-soft: #f1f5f9;
--foreground: #475569; --foreground: #475569;
/* Texto secundario sobre superficies suaves (tarjetas). En tema claro el
gris de `foreground` ya da 6.9:1 sobre `primary-soft` y 7.6:1 sobre
`background`, así que acá no hay que mover nada: mismo valor, mismo
contrato. El token existe igual para que "secundario" sea un nombre y no
una coincidencia de color. */
--secondary: #475569;
--accent: #2544ea; --accent: #2544ea;
--accent-strong: #1d33d8; --accent-strong: #1d33d8;
--accent-soft: #eef4ff; --accent-soft: #eef4ff;
@@ -127,6 +136,11 @@
--success-soft: #ecfdf5; --success-soft: #ecfdf5;
--warning: #b45309; --warning: #b45309;
--warning-soft: #fffbeb; --warning-soft: #fffbeb;
/* naranja: escalón de severidad para la misma familia de alertas (aviso por
asistencia, cupos). Sobre `warning-strong-soft` da 4.9:1 y sobre la
tarjeta 4.4:1, así que sirve para texto y para un borde tenue. */
--warning-strong: #c2410c;
--warning-strong-soft: #fff7ed;
--danger: #f43f5e; --danger: #f43f5e;
--danger-soft: #fff1f2; --danger-soft: #fff1f2;
} }
@@ -140,6 +154,11 @@
--primary: #f1f5f9; --primary: #f1f5f9;
--primary-soft: #1e293b; --primary-soft: #1e293b;
--foreground: #94a3b8; --foreground: #94a3b8;
/* El secundario se sube un escalón sobre `foreground`: 7.1:1 sobre la
tarjeta (#1e293b) y 9.8:1 sobre el fondo, contra 5.7:1 del gris anterior.
El salto importa en las superficies suaves, que son las que dominan las
tarjetas de la lista: el texto de apoyo ahí es el que más se pierde. */
--secondary: #a8b6c8;
--accent: #2544ea; --accent: #2544ea;
--accent-strong: #1d33d8; --accent-strong: #1d33d8;
--accent-soft: color-mix(in srgb, var(--brand-500) 15%, transparent); --accent-soft: color-mix(in srgb, var(--brand-500) 15%, transparent);
@@ -151,6 +170,11 @@
--success-soft: color-mix(in srgb, var(--success) 15%, transparent); --success-soft: color-mix(in srgb, var(--success) 15%, transparent);
--warning: #fcd34d; --warning: #fcd34d;
--warning-soft: color-mix(in srgb, var(--warning) 15%, transparent); --warning-soft: color-mix(in srgb, var(--warning) 15%, transparent);
/* En oscuro el "naranja" tiene que subir de luminosidad para alcanzar el
mismo contraste que su versión clara: #fb923c da 4.7:1 sobre el fondo
translúcido del badge, contra 4.1:1 del #f97316 de la paleta estándar. */
--warning-strong: #fb923c;
--warning-strong-soft: color-mix(in srgb, var(--warning-strong) 18%, transparent);
--danger: #fb7185; --danger: #fb7185;
--danger-soft: color-mix(in srgb, var(--danger) 15%, transparent); --danger-soft: color-mix(in srgb, var(--danger) 15%, transparent);
} }

View File

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

View File

@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'
import type { AttendanceStatus } from '@gruperly/shared' import type { AttendanceStatus } from '@gruperly/shared'
import { import {
attendanceStatusLabel, attendanceStatusLabel,
attendanceSummaryLabel, attendanceSummary,
classCountLabel, classCountLabel,
formatMemberSince, formatMemberSince,
formatSessionShortDate, formatSessionShortDate,
@@ -56,17 +56,37 @@ describe('attendanceStatusLabel', () => {
}) })
}) })
describe('attendanceSummaryLabel', () => { describe('attendanceSummary', () => {
test('cuenta solo las asistidas de las filas que se ven', () => { test('el denominador son las clases registradas, no todas las filas', () => {
expect(attendanceSummaryLabel(visibleSessions(historial, false))).toBe('2 de 5 clases') // La vista previa son 5 filas, pero una quedó sin registrar: el resumen
// cuenta 4, no 5, porque sin dato no hay ni asistencia ni ausencia.
const { label } = attendanceSummary(visibleSessions(historial, false))
expect(label).toBe('2 de 4 clases')
})
test('las clases sin registro se avisan aparte, no mezcladas en el total', () => {
expect(attendanceSummary(visibleSessions(historial, false)).unmarkedLabel).toBe('1 sin registrar')
}) })
test('con una sola clase el total va en singular', () => { test('con una sola clase el total va en singular', () => {
expect(attendanceSummaryLabel([sesion(6, 'PRESENT')])).toBe('1 de 1 clase') expect(attendanceSummary([sesion(6, 'PRESENT')]).label).toBe('1 de 1 clase')
}) })
test('sin clases no inventa una asistencia', () => { test('sin nada registrado lo dice, en vez de "0 de 0"', () => {
expect(attendanceSummaryLabel([])).toBe('0 de 0 clases') const sinRegistrar = [sesion(5, null), sesion(6, null)]
expect(attendanceSummary(sinRegistrar)).toEqual({
label: 'Sin clases registradas',
unmarkedLabel: null,
})
expect(attendanceSummary([])).toEqual({
label: 'Sin clases registradas',
unmarkedLabel: null,
})
})
test('faltó y faltó con aviso también cuentan como clases registradas', () => {
const marcadas = [sesion(1, 'ABSENT'), sesion(2, 'EXCUSED')]
expect(attendanceSummary(marcadas)).toEqual({ label: '0 de 2 clases', unmarkedLabel: null })
}) })
}) })

View File

@@ -0,0 +1,140 @@
import { describe, expect, test } from 'bun:test'
import type { GroupRiskSummary } from '@gruperly/shared'
import {
attendanceAlert,
billingSuffix,
capacitySummary,
getAttendanceSeverity,
} from '../src/features/groups/card'
/* La tarjeta del listado no lee estos valores de la API: los deriva. Todo lo
que decide qué se ve —qué alerta sale, si es leve o grave, cómo se rotula el
cupo— vive acá y se prueba sin montar React. */
const risk = (
absenceStreakCount: number,
lowAttendanceCount: number,
): GroupRiskSummary => ({
groupId: 'grp_1',
groupName: 'Pilates',
riskLevel: absenceStreakCount >= 3 ? 'HIGH' : lowAttendanceCount > 0 ? 'MEDIUM' : 'NONE',
absenceStreakCount,
lowAttendanceCount,
})
describe('getAttendanceSeverity', () => {
test('menos de la mitad del grupo es un caso leve', () => {
expect(getAttendanceSeverity(1, 10)).toBe('low')
expect(getAttendanceSeverity(2, 5)).toBe('low')
})
test('la mitad exacta del grupo ya es un problema del grupo', () => {
expect(getAttendanceSeverity(2, 4)).toBe('high')
expect(getAttendanceSeverity(3, 4)).toBe('high')
})
test('sin matrícula no hay grupo que se pueda tanningar', () => {
expect(getAttendanceSeverity(3, 0)).toBe('low')
})
})
describe('attendanceAlert', () => {
test('sin riesgo no hay badge', () => {
expect(attendanceAlert(undefined, 10)).toBeNull()
expect(attendanceAlert(risk(0, 0), 10)).toBeNull()
})
test('con riesgo nombra la regla y la cantidad en una sola frase', () => {
const alert = attendanceAlert(risk(0, 4), 10)
expect(alert?.count).toBe(4)
expect(alert?.label).toBe('4 miembros con asistencia menor al 50%')
})
test('el singular se corrige solo', () => {
expect(attendanceAlert(risk(0, 1), 10)?.label).toBe(
'1 miembro con asistencia menor al 50%',
)
})
test('las faltas seguidas pisan a la asistencia baja', () => {
// El backend manda los dos contadores disjuntos. Si llegan los dos, solo
// se reporta el más accionable para que el badge no tenga dos frases.
expect(attendanceAlert(risk(2, 4), 10)?.label).toBe('2 miembros con faltas seguidas')
})
test('el texto corto acompaña a cada regla, no es uno genérico', () => {
// El número solo no se explica: "bajo 50%" y "con faltas" son motivos
// distintos y el badge tiene que poder dizer cuál sin abrir el title.
expect(attendanceAlert(risk(0, 4), 4)?.short).toBe('bajo 50%')
expect(attendanceAlert(risk(3, 0), 4)?.short).toBe('con faltas')
})
test('la severidad viaja en la alerta y sale de la misma regla', () => {
const leve = attendanceAlert(risk(0, 2), 10)
const grave = attendanceAlert(risk(0, 6), 10)
expect(leve?.severity).toBe('low')
expect(grave?.severity).toBe('high')
expect(grave?.severity).toBe(getAttendanceSeverity(6, 10))
})
test('la severidad se mide contra la matrícula, no contra el cupo', () => {
// 2 de 4 miembros es la mitad del grupo aunque el cupo sea 20: la función
// ni recibe el cupo, así que la ocupación no puede empujar la severidad.
expect(attendanceAlert(risk(0, 2), 4)?.severity).toBe('high')
expect(capacitySummary(2, 20, 0).occupancy).toBe(0.1)
})
test('un grupo sin miembros no inventa severidad', () => {
expect(attendanceAlert(risk(0, 3), 0)).toBeNull()
})
})
describe('capacitySummary', () => {
test('con cupo muestra el uso sobre el total', () => {
const summary = capacitySummary(4, 5, 0)
expect(summary.label).toBe('4/5 miembros')
expect(summary.occupancy).toBe(0.8)
expect(summary.isFull).toBe(false)
})
test('lleno o de más se cuenta como lleno y la barrita no se pasa', () => {
expect(capacitySummary(5, 5, 2).isFull).toBe(true)
expect(capacitySummary(7, 5, 0).occupancy).toBe(1)
})
test('1/5 se lee en plural: la unidad es el lugar, no la persona', () => {
expect(capacitySummary(1, 5, 0).label).toBe('1/5 miembros')
})
test('sin cupo el texto es el conteo y la ocupación no aplica', () => {
const summary = capacitySummary(3, null, 1)
expect(summary.label).toBe('3 miembros')
expect(summary.hasCapacity).toBe(false)
expect(summary.occupancy).toBe(0)
expect(summary.waitlistCount).toBe(1)
})
test('el singular sin cupo también se corrige', () => {
expect(capacitySummary(1, null, 0).label).toBe('1 miembro')
})
test('los cupos de dos dígitos se leen enteros', () => {
expect(capacitySummary(12, 20, 3).label).toBe('12/20 miembros')
expect(capacitySummary(12, 20, 3).occupancy).toBe(0.6)
})
})
describe('billingSuffix', () => {
test('el sufijo sigue la forma de cobro', () => {
expect(billingSuffix('MONTHLY')).toBe('/mes')
expect(billingSuffix('PER_CLASS')).toBe('/clase')
})
test('sin forma de cobro conocida, el precio queda sin sufijo', () => {
expect(billingSuffix(null)).toBeNull()
})
})

View File

@@ -69,10 +69,16 @@ export type UpdateStudentStatusResult = z.output<typeof UpdateStudentStatusResul
export const groupRiskLevelSchema = z.enum(['NONE', 'MEDIUM', 'HIGH']); export const groupRiskLevelSchema = z.enum(['NONE', 'MEDIUM', 'HIGH']);
export type GroupRiskLevel = z.output<typeof groupRiskLevelSchema>; export type GroupRiskLevel = z.output<typeof groupRiskLevelSchema>;
/* El nivel es el peor alumno del grupo; los dos contadores dicen por qué se
dispara, para que la lista pueda nombrar el motivo en vez de un "riesgo".
Son disjuntos: un miembro con racha de faltas va solo en el primero, y el
segundo agrupa a los que solo cruzan por asistencia baja. */
export const GroupRiskSummarySchema = z.object({ export const GroupRiskSummarySchema = z.object({
groupId: z.string(), groupId: z.string(),
groupName: z.string(), groupName: z.string(),
riskLevel: groupRiskLevelSchema, riskLevel: groupRiskLevelSchema,
absenceStreakCount: z.number().int().min(0),
lowAttendanceCount: z.number().int().min(0),
}); });
export type GroupRiskSummary = z.output<typeof GroupRiskSummarySchema>; export type GroupRiskSummary = z.output<typeof GroupRiskSummarySchema>;

View File

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

View File

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