development #14

Merged
jselesan merged 102 commits from development into main 2026-11-07 13:21:43 +00:00
646 changed files with 57092 additions and 1199 deletions
Showing only changes of commit b12ffdda37 - Show all commits

View File

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

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,27 +40,27 @@ 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>
)

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

View File

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