diff --git a/apps/backend/test/attendance-risk.test.ts b/apps/backend/test/attendance-risk.test.ts
index 5e94bac..5710fb0 100644
--- a/apps/backend/test/attendance-risk.test.ts
+++ b/apps/backend/test/attendance-risk.test.ts
@@ -108,18 +108,38 @@ describe('getMemberAttendanceRisk', () => {
expect(señales.level).toBe('riesgo_alto');
});
+ it('sin faltas después de la última presencia, la inactividad no cuenta', () => {
+ // The group stopped recording classes (or didn't meet): 30 days since the
+ // last presence, but the attendee missed nothing.
+ const alumno = member(series([['PRESENT', 30], [null, 20], [null, 12]]));
+ const señales = summarizeMemberAttendance(alumno, NOW);
+ expect(señales.consecutiveAbsences).toBe(0);
+ expect(señales.daysSinceLastAttendance).toBe(30);
+ expect(señales.level).toBe('ok');
+ });
+
it('el umbral de inactividad es "más de" 10 días, no "desde" 10', () => {
const { highInactivityDays } = ATTENDANCE_RISK_RULES;
- // Two streak absences: attention comes from the streak, and exactly 10 days
- // does not move the level.
- expect(
- getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays]])), NOW),
- ).toBe('atencion');
+ // Two streak absences, the latest one yesterday: attention comes from the
+ // streak. Inactivity is measured from the last presence to the latest
+ // missed class, so exactly 10 days there does not move the level.
expect(
getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays + 1]])), NOW),
+ ).toBe('atencion');
+ expect(
+ getMemberAttendanceRisk(member(series([['ABSENT', 1], ['ABSENT', 2], ['PRESENT', highInactivityDays + 2]])), NOW),
).toBe('riesgo_alto');
});
+ it('la inactividad se mide contra las clases que faltó, no contra hoy', () => {
+ // They missed one class 20 days ago and the group hasn't met since: 25 days
+ // without seeing them, but only 5 of those had a class they skipped.
+ const alumno = member(series([['ABSENT', 20], ['PRESENT', 25]]));
+ const señales = summarizeMemberAttendance(alumno, NOW);
+ expect(señales.daysSinceLastAttendance).toBe(25);
+ expect(señales.level).toBe('ok');
+ });
+
it('una tendencia a la baja da atención', () => {
// 12 marked classes. The 4 before those are at 100%, the last 4 at 50%, and the
// most recent is a PRESENT: streak 0 and recent attendance, so the trend is
diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsx
index b5177d9..8d3e070 100644
--- a/apps/web/src/components/ui/toast.tsx
+++ b/apps/web/src/components/ui/toast.tsx
@@ -88,7 +88,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
{/* Toast Container */}
{toasts.map((toast) => (
diff --git a/apps/web/src/features/groups/GroupForm.tsx b/apps/web/src/features/groups/GroupForm.tsx
index 43cf627..f482103 100644
--- a/apps/web/src/features/groups/GroupForm.tsx
+++ b/apps/web/src/features/groups/GroupForm.tsx
@@ -3,6 +3,7 @@ import { zodResolver } from '@hookform/resolvers/zod'
import type { BillingType, CountryCode, CreateFirstGroup, WeekDay } from '@gruperly/shared'
import { CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared'
import { ArrowLeft, Check, Loader2 } from 'lucide-react'
+import { sortWeekDays } from '../../lib/format'
import { cn } from '../../lib/utils'
import { Button, Input, Label } from '../../components/ui'
import { BILLING_TYPES, WEEK_DAY_CHIPS } from '../onboarding/constants'
@@ -57,7 +58,7 @@ export function GroupForm({
const dueDay = watch('dueDay')
const toggleDay = (day: WeekDay) => {
- const next = days.includes(day) ? days.filter((d) => d !== day) : [...days, day]
+ const next = days.includes(day) ? days.filter((d) => d !== day) : sortWeekDays([...days, day])
setValue('days', next, { shouldValidate: true })
}
diff --git a/apps/web/src/features/groups/card.ts b/apps/web/src/features/groups/card.ts
index 217c6e7..333f3b5 100644
--- a/apps/web/src/features/groups/card.ts
+++ b/apps/web/src/features/groups/card.ts
@@ -38,6 +38,9 @@ export type GroupMember = {
name: string
status: MemberStatus
absences: number
+ /** Why they are on the alert line ("3 faltas", "12 días sin venir"). When
+ * missing, the absences are used. */
+ reason?: string
}
export type CapacityCounts = {
@@ -90,8 +93,8 @@ export function alertTextFromMembers(members: GroupMember[]): string | null {
if (highRisk.length === 1) {
const first = highRisk[0]
const nombre = firstName(first.name)
- const faltas = `${first.absences} ${first.absences === 1 ? 'falta' : 'faltas'}`
- return `${nombre}: ${faltas}${kAtencion}`
+ const motivo = first.reason ?? `${first.absences} ${first.absences === 1 ? 'falta' : 'faltas'}`
+ return `${nombre}: ${motivo}${kAtencion}`
}
if (highRisk.length >= 2) {
@@ -123,6 +126,7 @@ export function membersFromGroupAndRisk(
name: u.fullName,
status: 'high_risk',
absences: u.consecutiveAbsences,
+ reason: absenceReason(u) ?? undefined,
})
} else if (u.level === 'atencion') {
members.push({
@@ -130,6 +134,7 @@ export function membersFromGroupAndRisk(
name: u.fullName,
status: 'attention',
absences: u.consecutiveAbsences,
+ reason: absenceReason(u) ?? undefined,
})
}
}
@@ -278,15 +283,16 @@ function countedLevels(counts: CapacityCounts): string {
}
/* The reason that best explains why someone is on the status line, in the order
- the rule considers them: first the streak of absences (something that is
- going away), then the time since last showing up, and last the attendance
- rate. With a single absence and ok it returns null: not enough to name
- anyone. */
-function absenceReason(miembro: UrgentMemberSummary): string | null {
+ the rule considers them: first a streak of absences (something that is going
+ away), then the time since last showing up, and last the attendance rate. A
+ single absence only names them when nothing else does: someone at high risk
+ for inactivity reads better as "12 días sin venir" than as "1 falta". */
+export function absenceReason(miembro: UrgentMemberSummary): string | null {
const { consecutiveAbsences: faltas, daysSinceLastAttendance: dias, attendanceRate: asistencia } = miembro
- if (faltas > 0) return `${faltas} ${faltas === 1 ? 'falta' : 'faltas'}`
+ if (faltas >= 2) return `${faltas} faltas`
if (dias != null && dias > 0) return `${dias} ${dias === 1 ? 'día' : 'días'} sin venir`
+ if (faltas === 1) return '1 falta'
if (asistencia != null && asistencia < 100) return `asistencia ${asistencia}%`
return null
}
diff --git a/apps/web/src/features/groups/detail/GroupInfoCard.tsx b/apps/web/src/features/groups/detail/GroupInfoCard.tsx
index 8bb6e1b..5e033fa 100644
--- a/apps/web/src/features/groups/detail/GroupInfoCard.tsx
+++ b/apps/web/src/features/groups/detail/GroupInfoCard.tsx
@@ -3,6 +3,7 @@ import {
formatBillingMeta,
formatPrice,
WEEK_DAY_FULL_LABELS,
+ sortWeekDays,
} from '../../../lib/format'
import { cn } from '../../../lib/utils'
import { useGroupDetail } from './GroupDetailProvider'
@@ -18,7 +19,7 @@ export function GroupInfoCard() {
const { group, attendeesTotal, attendeesPending, waitlistTotal } = useGroupDetail()
if (!group) return null
- const daysLabel = (group.days ?? []).map((day) => WEEK_DAY_FULL_LABELS[day]).join(', ')
+ const daysLabel = sortWeekDays(group.days ?? []).map((day) => WEEK_DAY_FULL_LABELS[day]).join(', ')
const capacity = group.capacity
const isFull = capacity != null && attendeesTotal >= capacity
const freeSpots = capacity != null ? Math.max(capacity - attendeesTotal, 0) : null
diff --git a/apps/web/src/features/home/AttentionList.tsx b/apps/web/src/features/home/AttentionList.tsx
new file mode 100644
index 0000000..74faf7c
--- /dev/null
+++ b/apps/web/src/features/home/AttentionList.tsx
@@ -0,0 +1,107 @@
+import { useQuery } from '@tanstack/react-query'
+import { Link } from '@tanstack/react-router'
+import { CheckCircle2, ChevronRight, Wallet } from 'lucide-react'
+import { Avatar } from '../../components/ui'
+import { getGroupsRiskOverview, getPayments } from '../../lib/api'
+import { absenceReason } from '../groups/card'
+
+/** How many at-risk people Home names; the rest is in each group's stats. */
+const MAX_AT_RISK = 4
+
+/* "Para atender": what the teacher has to act on today, across all groups.
+ Nothing is computed here: the at-risk people are the high-risk `urgentes` of
+ `GET /groups-risk/overview` (same query key as the group list, so the cache
+ is shared) and the overdue payments are just the total of the filtered list. */
+export function AttentionList() {
+ const riskQuery = useQuery({
+ queryKey: ['groups-risk-overview'],
+ queryFn: getGroupsRiskOverview,
+ })
+ const overdueQuery = useQuery({
+ queryKey: ['payments', { page: 1, pageSize: 1, status: 'OVERDUE' }],
+ queryFn: () => getPayments({ page: 1, pageSize: 1, status: 'OVERDUE' }),
+ })
+
+ if (riskQuery.isPending || overdueQuery.isPending) return null
+ // A failing secondary block shouldn't take Home down: it just isn't shown.
+ if (riskQuery.isError && overdueQuery.isError) return null
+
+ const groups = riskQuery.data?.items ?? []
+ const atRisk = groups
+ .flatMap((group) =>
+ group.urgentes
+ .filter((member) => member.level === 'riesgo_alto')
+ .map((member) => ({ ...member, groupId: group.groupId, groupName: group.groupName })),
+ )
+ .sort((a, b) => b.consecutiveAbsences - a.consecutiveAbsences)
+ const totalAtRisk = groups.reduce((total, group) => total + group.riesgoAlto, 0)
+ const overdue = overdueQuery.data?.pagination.total ?? 0
+
+ return (
+
+
Para atender
+
+ {atRisk.length === 0 && overdue === 0 ? (
+
+
+ Todo en orden: nadie en riesgo y sin cobros vencidos.
+
+ {/* The empty state says how to get out of it: without Mercado
+ Pago there is no way to create payment links. */}
+ {mpStatusQuery.data && mpStatusQuery.data.status !== 'active' ? (
+
+ Vinculá Mercado Pago para cobrar
+
+ ) : (
+
Los creás desde la ficha de cada grupo.
+ )}
+
)}
diff --git a/apps/web/src/features/home/SummaryStats.tsx b/apps/web/src/features/home/SummaryStats.tsx
index 4dfe454..94e8bcb 100644
--- a/apps/web/src/features/home/SummaryStats.tsx
+++ b/apps/web/src/features/home/SummaryStats.tsx
@@ -6,30 +6,33 @@ import { formatPrice } from '../../lib/format'
type StatTarget = '/groups' | '/payments'
+/* Three compact tiles in a row, also on mobile: they are reference numbers, not
+ the protagonists of the screen, and stacked they pushed "Próximos cobros"
+ below the fold. The value always goes with its label: the old tile swapped
+ the label for a sub-line and read "0 / 0 por cobrar". */
export function SummaryStats({ summary }: { summary: HomeSummaryDto }) {
const navigate = useNavigate()
+ const { pendingAmount, pendingPayments } = summary.stats
const stats: {
label: string
value: string
- sub?: string
icon: LucideIcon
to: StatTarget
}[] = [
{
- label: 'Grupos activos',
+ label: summary.stats.groups === 1 ? 'Grupo' : 'Grupos',
value: String(summary.stats.groups),
icon: Users,
to: '/groups',
},
{
- label: 'Cobros pendientes',
- value: summary.stats.pendingAmount > 0 ? formatPrice(summary.stats.pendingAmount) : '0',
- sub: `${summary.stats.pendingPayments} por cobrar`,
+ label: pendingPayments > 0 ? `Por cobrar · ${pendingPayments}` : 'Por cobrar',
+ value: formatPrice(pendingAmount),
icon: Wallet,
to: '/payments',
},
{
- label: 'Asistentes',
+ label: summary.stats.attendees === 1 ? 'Alumno' : 'Alumnos',
value: String(summary.stats.attendees),
icon: UserCheck,
to: '/groups',
@@ -37,31 +40,31 @@ export function SummaryStats({ summary }: { summary: HomeSummaryDto }) {
]
return (
-
+ {/* Only the done state earns a badge: "Por tomar" repeated what the
+ button below already says. */}
+ {item.hasAttendance ? Asistencia tomada : null}
+
)
-}
\ No newline at end of file
+}
diff --git a/apps/web/src/lib/format.ts b/apps/web/src/lib/format.ts
index 4403875..063f913 100644
--- a/apps/web/src/lib/format.ts
+++ b/apps/web/src/lib/format.ts
@@ -46,8 +46,16 @@ export function formatRelativeDateTime(iso: string, now: Date = new Date()): str
return `${label} · ${time}`
}
+const WEEK_DAY_ORDER = Object.keys(WEEK_DAY_FULL_LABELS) as WeekDay[]
+
+/** Days in calendar order (Monday first). The form stores them in the order
+ * they were tapped, so "Jue, Vie, Mié" could reach the screen as-is. */
+export function sortWeekDays(days: readonly WeekDay[]): WeekDay[] {
+ return [...days].sort((a, b) => WEEK_DAY_ORDER.indexOf(a) - WEEK_DAY_ORDER.indexOf(b))
+}
+
export function formatSchedule(days: readonly WeekDay[], time: string | null): string {
- const dayNames = days.map((day) => WEEK_DAY_FULL_LABELS[day])
+ const dayNames = sortWeekDays(days).map((day) => WEEK_DAY_FULL_LABELS[day])
return time ? `${dayNames.join(', ')} · ${time}` : dayNames.join(', ')
}
diff --git a/packages/shared/src/lib/attendance-risk.ts b/packages/shared/src/lib/attendance-risk.ts
index 6164e61..62031dd 100644
--- a/packages/shared/src/lib/attendance-risk.ts
+++ b/packages/shared/src/lib/attendance-risk.ts
@@ -168,7 +168,7 @@ export function summarizeMemberAttendance(
const present = marked.filter((session) => session.status === 'PRESENT').length;
const attendanceRate = marked.length ? Math.round((present / marked.length) * 100) : null;
- const level = classify(consecutiveAbsences, daysSinceLastAttendance, marked);
+ const level = classify(consecutiveAbsences, missedSpanDays(sessions, lastAttendedAt), marked);
return {
level,
@@ -182,15 +182,13 @@ export function summarizeMemberAttendance(
/** Verdict: first the streak and the inactivity, then the trend. */
function classify(
consecutiveAbsences: number,
- daysSinceLastAttendance: number | null,
+ missedDays: number | null,
markedSessions: MemberClassSession[],
): AttendanceRiskLevel {
const rules = ATTENDANCE_RISK_RULES;
+ const inactive = missedDays !== null && missedDays > rules.highInactivityDays;
- if (
- consecutiveAbsences >= rules.highAbsenceStreak ||
- (daysSinceLastAttendance !== null && daysSinceLastAttendance > rules.highInactivityDays)
- ) {
+ if (consecutiveAbsences >= rules.highAbsenceStreak || inactive) {
return 'riesgo_alto';
}
if (consecutiveAbsences >= rules.attentionAbsenceStreak) {
@@ -283,6 +281,32 @@ function isDeclining(sessions: MemberClassSession[]): boolean {
}
}
+/**
+ * Inactivity as the group lived it: days from the last presence (or, if they
+ * never came, from their first class) to the most recent class they missed.
+ * It is measured against the classes and not against today on purpose: if the
+ * group stopped meeting, or nobody recorded attendance, those days are the
+ * group's, not the attendee's. Without this, a group that went 10 days without
+ * recording a class turned all its members red at once. `null` when they have
+ * not missed any class since their last presence.
+ */
+function missedSpanDays(
+ sessions: MemberClassSession[],
+ lastAttendedAt: string | undefined,
+): number | null {
+ let lastMissedAt: string | undefined;
+ for (let index = sessions.length - 1; index >= 0; index -= 1) {
+ if (sessions[index].status === 'ABSENT') {
+ lastMissedAt = sessions[index].startsAt;
+ break;
+ }
+ }
+ const from = lastAttendedAt ?? sessions[0]?.startsAt;
+ if (!lastMissedAt || !from) return null;
+ const span = new Date(lastMissedAt).getTime() - new Date(from).getTime();
+ return span > 0 ? Math.floor(span / DAY_MS) : null;
+}
+
/** Start of the most recent class with presence, or `undefined` if they have none. */
function lastPresentAt(sessions: MemberClassSession[]): string | undefined {
for (let index = sessions.length - 1; index >= 0; index -= 1) {