feat(web): rediseño de Inicio en mobile y criterio de inactividad por clases faltadas

- Inicio: saludo con fecha, estadísticas compactas en fila (arregla el
  "0 / 0 por cobrar"), sección "Para atender" (alumnos en riesgo alto y
  cobros vencidos), tarjeta de clase de hoy con CTA a todo el ancho y
  estado vacío de cobros que lleva a vincular Mercado Pago.
- Riesgo: la inactividad se mide desde la última presencia hasta la última
  clase faltada, no contra hoy; un grupo sin clases registradas ya no pone
  a todos sus miembros en riesgo alto.
- Tarjeta de grupo: el aviso usa el motivo real ("12 días sin venir") en
  vez de "0 faltas".
- Días del horario en orden de calendario (sortWeekDays).
- Toast por encima del BottomNav en mobile; ficha de alumno sin flecha de
  volver en mobile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-27 11:18:18 -03:00
parent 9617447e05
commit b12ffdda37
12 changed files with 283 additions and 88 deletions

View File

@@ -88,7 +88,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
{/* Toast Container */}
<div
aria-live="polite"
className="fixed bottom-4 right-4 z-50 flex max-w-sm w-full flex-col gap-2 pointer-events-none px-4 sm:px-0"
className="fixed bottom-[calc(6rem+env(safe-area-inset-bottom))] right-4 z-50 lg:bottom-4 flex max-w-sm w-full flex-col gap-2 pointer-events-none px-4 sm:px-0"
>
{toasts.map((toast) => (
<div

View File

@@ -31,7 +31,7 @@ export function AttendeeDetailView() {
to="/groups/$groupId"
params={{ groupId }}
aria-label="Volver al grupo"
className="relative z-10 inline-flex size-11 shrink-0 items-center justify-center rounded-xl text-primary transition-colors hover:bg-primary-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
className="relative z-10 hidden size-11 shrink-0 lg:inline-flex items-center justify-center rounded-xl text-primary transition-colors hover:bg-primary-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<ArrowLeft className="size-5" aria-hidden="true" />
</Link>

View File

@@ -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 })
}

View File

@@ -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
}

View File

@@ -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

View File

@@ -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 (
<div>
<h2 className="text-lg font-bold text-primary">Para atender</h2>
{atRisk.length === 0 && overdue === 0 ? (
<p className="mt-3 flex items-center gap-2 rounded-xl border border-border bg-surface px-4 py-3 text-sm text-foreground/70">
<CheckCircle2 className="size-4 shrink-0 text-success" aria-hidden="true" />
Todo en orden: nadie en riesgo y sin cobros vencidos.
</p>
) : (
<ul className="mt-3 divide-y divide-border overflow-hidden rounded-xl border border-border bg-surface">
{overdue > 0 ? (
<li>
<Link to="/payments" className={ROW_CLASS_NAME}>
<span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-danger-soft text-danger">
<Wallet className="size-5" aria-hidden="true" />
</span>
<span className="min-w-0 flex-1">
<span className="block text-sm font-semibold text-primary">
{overdue} {overdue === 1 ? 'cobro vencido' : 'cobros vencidos'}
</span>
<span className="block text-xs text-foreground/60">Revisalos en Cobros</span>
</span>
<ChevronRight className="size-4 shrink-0 text-foreground/40" aria-hidden="true" />
</Link>
</li>
) : null}
{atRisk.slice(0, MAX_AT_RISK).map((member) => (
<li key={member.attendeeId}>
<Link
to="/groups/$groupId/attendees/$attendeeId"
params={{ groupId: member.groupId, attendeeId: member.attendeeId }}
className={ROW_CLASS_NAME}
>
<Avatar name={member.fullName} className="size-10 rounded-full" />
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-semibold text-primary">
{member.fullName}
</span>
<span className="block truncate text-xs text-foreground/60">
{member.groupName}
{absenceReason(member) ? (
<>
{' · '}
<span className="text-danger">{absenceReason(member)}</span>
</>
) : null}
</span>
</span>
<ChevronRight className="size-4 shrink-0 text-foreground/40" aria-hidden="true" />
</Link>
</li>
))}
{totalAtRisk > MAX_AT_RISK ? (
<li className="px-4 py-3 text-xs text-foreground/60">
Y {totalAtRisk - MAX_AT_RISK} más en riesgo. Mirá las estadísticas de cada grupo.
</li>
) : null}
</ul>
)}
</div>
)
}
const ROW_CLASS_NAME =
'flex items-center gap-3 px-4 py-3 transition-colors hover:bg-primary-soft/50 active:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent'

View File

@@ -1,8 +1,11 @@
import { useQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { Link, useNavigate } from '@tanstack/react-router'
import { Loader2, Plus } from 'lucide-react'
import { Button } from '../../components/ui'
import { useAuth } from '../../context/AuthProvider'
import { getClassesToday, getHomeSummary } from '../../lib/api'
import { useMpStatus } from '../mp/useMpStatus'
import { AttentionList } from './AttentionList'
import { SummaryStats } from './SummaryStats'
import { TodayClassCard } from './TodayClassCard'
import { NextClassHero } from './NextClassHero'
@@ -10,6 +13,15 @@ import { UpcomingPaymentRow } from './UpcomingPaymentRow'
export function HomeView() {
const navigate = useNavigate()
const { user } = useAuth()
const mpStatusQuery = useMpStatus()
const firstName = user?.name?.trim().split(/\s+/)[0]
// "martes 27 de octubre": the date anchors "Clase de hoy" and the due dates below.
const today = new Date().toLocaleDateString('es-AR', {
weekday: 'long',
day: 'numeric',
month: 'long',
})
const summaryQuery = useQuery({
queryKey: ['home-summary'],
queryFn: getHomeSummary,
@@ -24,8 +36,10 @@ export function HomeView() {
return (
<section>
<div>
<h1 className="text-2xl font-bold text-primary">Inicio</h1>
<p className="mt-2 text-sm text-foreground/60">Tu actividad de cobros de un vistazo.</p>
<p className="text-sm font-medium first-letter:uppercase text-foreground/60">{today}</p>
<h1 className="mt-1 text-2xl font-bold text-primary">
{firstName ? `Hola, ${firstName}` : 'Hola'}
</h1>
</div>
{summaryQuery.isPending ? (
@@ -81,6 +95,8 @@ export function HomeView() {
<SummaryStats summary={summaryQuery.data} />
<AttentionList />
<div>
<div className="flex items-center justify-between gap-3">
<h2 className="text-lg font-bold text-primary">Próximos cobros</h2>
@@ -96,9 +112,21 @@ export function HomeView() {
))}
</ul>
) : (
<p className="mt-3 rounded-xl border border-dashed border-border bg-surface px-4 py-6 text-center text-sm text-foreground/60">
Sin cobros pendientes por ahora.
</p>
<div className="mt-3 rounded-xl border border-dashed border-border bg-surface px-4 py-6 text-center text-sm text-foreground/60">
<p>Sin cobros pendientes por ahora.</p>
{/* 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' ? (
<Link
to="/settings"
className="mt-2 inline-block font-medium text-accent hover:underline"
>
Vinculá Mercado Pago para cobrar
</Link>
) : (
<p className="mt-1 text-xs">Los creás desde la ficha de cada grupo.</p>
)}
</div>
)}
</div>
</div>

View File

@@ -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 (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<div className="grid grid-cols-3 gap-2 sm:gap-4">
{stats.map((stat) => {
const Icon = stat.icon
return (
<button
key={stat.label}
key={stat.to + stat.label}
type="button"
onClick={() => void navigate({ to: stat.to })}
className={cn(
'flex items-center gap-3 rounded-xl border border-border bg-surface p-4 text-left transition-all',
'hover:border-accent/40',
'flex min-w-0 flex-col items-start gap-2 rounded-xl border border-border bg-surface p-3 text-left transition-all sm:flex-row sm:items-center sm:gap-3 sm:p-4',
'hover:border-accent/40 active:scale-[0.98] motion-reduce:active:scale-100',
)}
>
<span className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-accent-soft text-accent">
<Icon className="size-5" />
<span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-accent-soft text-accent sm:size-10">
<Icon className="size-4 sm:size-5" />
</span>
<span className="min-w-0">
<span className="block text-xl font-bold leading-tight text-primary">{stat.value}</span>
<span className="block truncate text-xs text-foreground/60">
{stat.sub ?? stat.label}
<span className="min-w-0 max-w-full">
<span className="block truncate text-lg font-bold leading-tight text-primary tabular-nums sm:text-xl">
{stat.value}
</span>
<span className="block truncate text-xs text-foreground/60">{stat.label}</span>
</span>
</button>
)
})}
</div>
)
}
}

View File

@@ -1,6 +1,6 @@
import { useNavigate } from '@tanstack/react-router'
import { Link, useNavigate } from '@tanstack/react-router'
import type { ClassTodayDto } from '@gruperly/shared'
import { CalendarClock, ClipboardCheck } from 'lucide-react'
import { CalendarClock, ChevronRight, ClipboardCheck } from 'lucide-react'
import { Badge, Button } from '../../components/ui'
export function TodayClassCard({ item }: { item: ClassTodayDto }) {
@@ -13,46 +13,43 @@ export function TodayClassCard({ item }: { item: ClassTodayDto }) {
return (
<article className="relative overflow-hidden rounded-xl border border-accent/30 bg-surface p-5">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
<div className="min-w-0">
<p className="text-xs font-medium uppercase tracking-wide text-foreground/50">
Clase de hoy
</p>
<h2 className="mt-1 truncate text-xl font-bold text-primary">{item.groupName}</h2>
<div className="mt-2 flex items-center gap-2 text-sm text-foreground/70">
<CalendarClock className="size-4 shrink-0 text-accent" />
<span>Hoy · {time} hs</span>
</div>
<p className="mt-1 text-xs text-foreground/60">
{item.enrolledCount} inscrito{item.enrolledCount === 1 ? '' : 's'}
{item.availableSlots != null
? ` · ${item.availableSlots} cupo${item.availableSlots === 1 ? '' : 's'} disponible${item.availableSlots === 1 ? '' : 's'}`
: ''}
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
<Badge variant={item.hasAttendance ? 'success' : 'neutral'}>
{item.hasAttendance ? 'Asistencia tomada' : 'Por tomar'}
</Badge>
</div>
<div className="flex items-start justify-between gap-3">
<p className="text-xs font-medium uppercase tracking-wide text-foreground/50">
Clase de hoy
</p>
{/* Only the done state earns a badge: "Por tomar" repeated what the
button below already says. */}
{item.hasAttendance ? <Badge variant="success">Asistencia tomada</Badge> : null}
</div>
<div className="mt-4 flex justify-end gap-2 border-t border-border pt-3">
<Button
variant="outline"
size="sm"
onClick={() => void navigate({ to: `/groups/${item.groupId}` })}
>
Ver grupo
</Button>
<Button
variant="primary"
size="sm"
onClick={() => void navigate({ to: `/class/${item.sessionId}/attendance` })}
>
<ClipboardCheck className="size-4" />
Tomar Asistencia
</Button>
<Link
to="/groups/$groupId"
params={{ groupId: item.groupId }}
className="group mt-1 flex items-center gap-1 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
<h2 className="truncate text-xl font-bold text-primary">{item.groupName}</h2>
<ChevronRight
className="size-5 shrink-0 text-foreground/40 transition-transform group-hover:translate-x-0.5"
aria-hidden="true"
/>
</Link>
<div className="mt-2 flex items-center gap-2 text-sm text-foreground/70">
<CalendarClock className="size-4 shrink-0 text-accent" />
<span>Hoy · {time} hs</span>
</div>
<p className="mt-1 text-xs text-foreground/60">
{item.enrolledCount} inscrito{item.enrolledCount === 1 ? '' : 's'}
{item.availableSlots != null
? ` · ${item.availableSlots} cupo${item.availableSlots === 1 ? '' : 's'} disponible${item.availableSlots === 1 ? '' : 's'}`
: ''}
</p>
<Button
variant={item.hasAttendance ? 'outline' : 'primary'}
className="mt-4 w-full"
onClick={() => void navigate({ to: `/class/${item.sessionId}/attendance` })}
>
<ClipboardCheck className="size-4" />
{item.hasAttendance ? 'Ver asistencia' : 'Tomar asistencia'}
</Button>
</article>
)
}
}

View File

@@ -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(', ')
}