feat(i18n): traducir la ficha del alumno

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-11-03 12:30:11 -03:00
parent ecdbbbbca6
commit 8a5768e0c0
27 changed files with 856 additions and 164 deletions

View File

@@ -5,10 +5,12 @@ import { useAttendeeDetail } from './AttendeeDetailProvider'
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
import { Section } from './Section'
import { useCopyToClipboard } from './useCopyToClipboard'
import { useTranslation } from 'react-i18next'
export function AbsenceLinkSection() {
const { attendee } = useAttendeeDetail()
const { copied, copy } = useCopyToClipboard()
const { t } = useTranslation(['attendeeDetail', 'common'])
const [isOpen, setIsOpen] = useState(false)
const panelId = useId()
@@ -19,14 +21,14 @@ export function AbsenceLinkSection() {
const phoneDigits = attendee.phone?.replace(/\D/g, '') ?? ''
const shareUrl = phoneDigits
? `https://wa.me/${phoneDigits}?text=${encodeURIComponent(
`Hola ${attendee.fullName.split(' ')[0]}, desde este link podés avisar tus ausencias en ${url}`,
t('absenceLink.message', { name: attendee.fullName.split(' ')[0], url }),
)}`
: null
return (
<Section
title="Link de ausencias"
description="Para que avise si no puede venir"
title={t('absenceLink.title')}
description={t('absenceLink.description')}
toggle={{ isOpen, panelId, onToggle: () => setIsOpen((value) => !value) }}
>
{/* The panel stays in the DOM but hidden: `aria-controls` always resolves and
@@ -43,18 +45,18 @@ export function AbsenceLinkSection() {
className={cn(ACTION_BUTTON_CLASS, 'w-full')}
>
<Copy className="size-4" aria-hidden="true" />
Copiar link
{t('absenceLink.copy')}
</button>
{shareUrl ? (
<a
href={shareUrl}
target="_blank"
rel="noopener noreferrer"
aria-label={`Enviar el link por WhatsApp a ${attendee.fullName}`}
aria-label={t('absenceLink.sendLabel', { name: attendee.fullName })}
className={PRIMARY_ACTION_CLASS}
>
<MessageCircle className="size-4" aria-hidden="true" />
Enviar por WhatsApp
{t('absenceLink.send')}
</a>
) : null}
</div>
@@ -65,7 +67,7 @@ export function AbsenceLinkSection() {
{copied ? (
<>
<Check className="size-3.5" aria-hidden="true" />
Link copiado
{t('absenceLink.copied')}
</>
) : null}
</p>

View File

@@ -3,6 +3,7 @@ import type { KeyboardEvent, RefObject } from 'react'
import { Ellipsis, MoveRight, Pause, Pencil, UserMinus, UserPlus } from 'lucide-react'
import { useToast } from '../../components/ui'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useTranslation } from 'react-i18next'
const ITEM_CLASS =
'flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-sm font-medium text-primary transition-colors hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
@@ -17,6 +18,7 @@ export function AttendeeActionsMenu({
}) {
const { beginContactEdit, openRemoveDialog, openChangeGroupDialog, openAddToGroupDialog } = useAttendeeDetail()
const toast = useToast()
const { t } = useTranslation(['attendeeDetail', 'common'])
const [isOpen, setIsOpen] = useState(false)
const menuRef = useRef<HTMLDivElement>(null)
const itemRef = useRef<HTMLButtonElement>(null)
@@ -72,7 +74,7 @@ export function AttendeeActionsMenu({
const showPendingPause = () => {
close()
// TODO(miembros): conectar la pausa cuando se defina su efecto sobre cupos y cobros.
toast.info('Pausar la membresía estará disponible cuando se confirme su lógica de negocio.')
toast.info(t('menu.pausePending'))
}
return (
@@ -84,7 +86,7 @@ export function AttendeeActionsMenu({
aria-haspopup="menu"
aria-expanded={isOpen}
aria-controls={isOpen ? menuId : undefined}
aria-label="Más acciones"
aria-label={t('menu.more')}
className="inline-flex size-11 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"
>
<Ellipsis className="size-5" aria-hidden="true" />
@@ -95,7 +97,7 @@ export function AttendeeActionsMenu({
ref={menuRef}
id={menuId}
role="menu"
aria-label="Acciones del miembro"
aria-label={t('menu.label')}
onKeyDown={handleKeyDown}
className="absolute right-0 top-full z-40 mt-1 w-60 rounded-xl bg-primary-soft p-1.5 shadow-lg"
>
@@ -110,7 +112,7 @@ export function AttendeeActionsMenu({
}}
>
<MoveRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
Cambiar de grupo
{t('menu.changeGroup')}
</button>
<button
type="button"
@@ -122,7 +124,7 @@ export function AttendeeActionsMenu({
}}
>
<UserPlus className="size-4 shrink-0 text-secondary" aria-hidden="true" />
Agregar a otro grupo
{t('menu.addToGroup')}
</button>
<button
type="button"
@@ -137,7 +139,7 @@ export function AttendeeActionsMenu({
}}
>
<Pencil className="size-4 shrink-0 text-secondary" aria-hidden="true" />
Editar contacto
{t('menu.editContact')}
</button>
<button
type="button"
@@ -146,7 +148,7 @@ export function AttendeeActionsMenu({
onClick={showPendingPause}
>
<Pause className="size-4 shrink-0 text-secondary" aria-hidden="true" />
Pausar membresía
{t('menu.pause')}
</button>
<div className="my-1 border-t border-border/70" aria-hidden="true" />
<button
@@ -159,7 +161,7 @@ export function AttendeeActionsMenu({
}}
>
<UserMinus className="size-4 shrink-0" aria-hidden="true" />
Quitar del grupo
{t('menu.remove')}
</button>
</div>
) : null}

View File

@@ -16,6 +16,7 @@ import {
} from './attendance'
import { Section } from './Section'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useTranslation } from 'react-i18next'
const STATUS_ICONS: Record<AttendanceStatus | 'UNMARKED', LucideIcon> = {
PRESENT: Check,
@@ -31,10 +32,11 @@ function iconFor(status: AttendanceSession['status']): LucideIcon {
export function AttendeeAttendanceSection() {
const { history, historyPending, historyFailed } = useAttendeeDetail()
const [showAll, setShowAll] = useState(false)
const { t } = useTranslation(['attendeeDetail', 'common'])
if (historyPending) {
return (
<Section title="Asistencia" trailing="—">
<Section title={t('attendance.title')} trailing="—">
<div className="flex items-center justify-center py-5">
<Loader2 className="size-5 animate-spin text-accent" />
</div>
@@ -44,9 +46,9 @@ export function AttendeeAttendanceSection() {
if (historyFailed) {
return (
<Section title="Asistencia">
<Section title={t('attendance.title')}>
<p className="py-3 text-sm text-foreground">
No pudimos cargar la asistencia de este miembro.
{t('attendance.loadError')}
</p>
</Section>
)
@@ -56,9 +58,9 @@ export function AttendeeAttendanceSection() {
if (sessions.length === 0) {
return (
<Section title="Asistencia">
<Section title={t('attendance.title')}>
<p className="py-3 text-sm text-foreground">
Todavía no hay clases registradas.
{t('attendance.empty')}
</p>
</Section>
)
@@ -70,7 +72,7 @@ export function AttendeeAttendanceSection() {
const summary = attendanceSummary(visible)
return (
<Section title="Asistencia" trailing={summary.label}>
<Section title={t('attendance.title')} trailing={summary.label}>
<ul className="divide-y divide-border/60">
{visible.map((session) => {
const Icon = iconFor(session.status)
@@ -98,7 +100,7 @@ export function AttendeeAttendanceSection() {
{showAll && isCapped ? (
<p className="px-3 pt-2 text-xs text-foreground">
El historial guarda las últimas {HISTORY_LIMIT} clases.
{t('attendance.capped', { count: HISTORY_LIMIT })}
</p>
) : null}
@@ -110,7 +112,7 @@ export function AttendeeAttendanceSection() {
aria-expanded={showAll}
className="h-11 gap-1 px-3 text-sm text-accent-fg hover:text-primary"
>
{showAll ? 'Ver menos' : `Ver todas (${sessions.length})`}
{showAll ? t('attendance.showLess') : t('attendance.showAll', { count: sessions.length })}
<ChevronDown className={cn('size-4 transition-transform', showAll && 'rotate-180')} />
</Button>
</div>

View File

@@ -3,13 +3,15 @@ import { formatPhoneDisplay } from '../../lib/format'
import { cn } from '../../lib/utils'
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useTranslation } from 'react-i18next'
export function AttendeeContactActions() {
const { attendee } = useAttendeeDetail()
const { t } = useTranslation(['attendeeDetail', 'common'])
const phone = attendee?.phone
const digits = phone?.replace(/\D/g, '') ?? ''
const label = formatPhoneDisplay(phone) ?? attendee?.fullName ?? 'el miembro'
const label = formatPhoneDisplay(phone) ?? attendee?.fullName ?? t('actions.theMember')
return (
<div>
@@ -19,7 +21,7 @@ export function AttendeeContactActions() {
href={`https://wa.me/${digits}`}
target="_blank"
rel="noopener noreferrer"
aria-label={`Abrir WhatsApp con ${label}`}
aria-label={t('actions.whatsappLabel', { name: label })}
className={PRIMARY_ACTION_CLASS}
>
<MessageCircle className="size-4" aria-hidden="true" />
@@ -39,11 +41,11 @@ export function AttendeeContactActions() {
{phone ? (
<a
href={`tel:${digits}`}
aria-label={`Llamar a ${label}`}
aria-label={t('actions.callLabel', { name: label })}
className={cn(ACTION_BUTTON_CLASS, 'w-full')}
>
<Phone className="size-4 text-accent-fg" aria-hidden="true" />
Llamar
{t('actions.call')}
</a>
) : (
<button
@@ -53,13 +55,13 @@ export function AttendeeContactActions() {
className={cn(ACTION_BUTTON_CLASS, 'w-full cursor-not-allowed opacity-45')}
>
<Phone className="size-4 text-secondary" aria-hidden="true" />
Llamar
{t('actions.call')}
</button>
)}
</div>
{!phone ? (
<p id="missing-phone-feedback" className="mt-2 text-xs text-secondary">
Agregá un teléfono para usar estas acciones
{t('actions.missingPhone')}
</p>
) : null}
</div>

View File

@@ -1,6 +1,8 @@
import type { ReactNode } from 'react'
import { Loader2, Mail, Phone } from 'lucide-react'
import { Button, Input } from '../../components/ui'
import { validationMessage } from '../../i18n'
import { useTranslation } from 'react-i18next'
type AttendeeContactFormProps = {
phone: string
@@ -26,26 +28,27 @@ export function AttendeeContactForm({
onCancel,
onSave,
}: AttendeeContactFormProps) {
const { t } = useTranslation(['attendeeDetail', 'common'])
return (
<div className="space-y-3 px-3 pb-1">
<ContactInput icon={Phone} label="Teléfono">
<ContactInput icon={Phone} label={t('contact.phone')}>
<Input
type="tel"
value={phone}
onChange={(event) => onPhoneChange(event.target.value)}
autoComplete="tel"
autoFocus
aria-label="Teléfono"
aria-label={t('contact.phone')}
/>
</ContactInput>
<ContactInput icon={Mail} label="Email">
<ContactInput icon={Mail} label={t('contact.email')}>
<Input
type="email"
value={email}
invalid={error === 'Ingresá un email válido'}
invalid={error === validationMessage('email.invalid')}
onChange={(event) => onEmailChange(event.target.value)}
autoComplete="email"
aria-label="Email"
aria-label={t('contact.email')}
aria-describedby={error ? 'contact-error' : undefined}
/>
</ContactInput>
@@ -57,11 +60,11 @@ export function AttendeeContactForm({
) : null}
<div className="flex justify-end gap-2 pt-1">
<Button variant="ghost" onClick={onCancel} disabled={isSaving}>
Cancelar
{t('common:actions.cancel')}
</Button>
<Button variant="primary" onClick={onSave} disabled={isSaving}>
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
Guardar
{t('common:actions.save')}
</Button>
</div>
</div>

View File

@@ -7,6 +7,7 @@ import { AttendeeContactForm } from './AttendeeContactForm'
import { contactEmailError } from './detail'
import { Section } from './Section'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useTranslation } from 'react-i18next'
export function AttendeeContactSection() {
const {
@@ -18,6 +19,7 @@ export function AttendeeContactSection() {
isUpdatingAttendee,
} = useAttendeeDetail()
const [phone, setPhone] = useState('')
const { t } = useTranslation(['attendeeDetail', 'common'])
const [email, setEmail] = useState('')
const [error, setError] = useState<string | null>(null)
@@ -47,8 +49,8 @@ export function AttendeeContactSection() {
} catch (err) {
setError(
err instanceof ApiError && err.problem?.code === 'person_phone_taken'
? 'Ese teléfono ya es de otra persona que tenés registrada.'
: 'No pudimos guardar los cambios. Revisá tu conexión e intentá de nuevo.',
? t('contact.phoneTaken')
: t('contact.saveError'),
)
}
}
@@ -56,7 +58,7 @@ export function AttendeeContactSection() {
return (
<Section
id="attendee-contact"
title="Contacto"
title={t('contact.title')}
trailing={
!isEditingContact ? (
<button
@@ -64,7 +66,7 @@ export function AttendeeContactSection() {
onClick={beginContactEdit}
className="min-h-11 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
Editar
{t('contact.edit')}
</button>
) : null
}
@@ -76,7 +78,7 @@ export function AttendeeContactSection() {
error={error}
sharedNote={
attendee.otherGroups.length > 0
? 'El cambio se aplica en todos sus grupos.'
? t('contact.shared')
: null
}
isSaving={isUpdatingAttendee}
@@ -95,15 +97,15 @@ export function AttendeeContactSection() {
<div className="divide-y divide-border/60">
<ContactRow
icon={Phone}
label="Teléfono"
value={formatPhoneDisplay(attendee.phone) ?? 'Agregar teléfono'}
label={t('contact.phone')}
value={formatPhoneDisplay(attendee.phone) ?? t('contact.addPhone')}
href={attendee.phone ? `tel:${attendee.phone.replace(/\D/g, '')}` : undefined}
placeholder={!attendee.phone}
/>
<ContactRow
icon={Mail}
label="Email"
value={attendee.email ?? 'Agregar email'}
label={t('contact.email')}
value={attendee.email ?? t('contact.addEmail')}
href={attendee.email ? `mailto:${attendee.email}` : undefined}
placeholder={!attendee.email}
/>

View File

@@ -9,6 +9,8 @@ import type {
GroupWaitlistEntryDto,
UpdateAttendee,
} from '@gruperly/shared'
import { errorMessage } from '../../i18n'
import { i18n } from '../../i18n/instance'
import { useToast } from '../../components/ui'
import {
addAttendeeToGroup,
@@ -143,8 +145,8 @@ export function AttendeeDetailProvider({
const moveMutation = useMutation({
mutationFn: (targetGroupId: string) => moveGroupAttendee(groupId, attendeeId, targetGroupId),
onSuccess: (moved, targetGroupId) => {
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? 'otro grupo'
toast.success(`${moved.fullName} pasó a ${targetName}.`)
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? i18n.t('attendeeDetail:changeGroup.otherGroup')
toast.success(i18n.t('attendeeDetail:changeGroup.moved', { name: moved.fullName, group: targetName }))
for (const id of [groupId, targetGroupId]) {
void queryClient.invalidateQueries({ queryKey: ['group-attendees', id] })
void queryClient.invalidateQueries({ queryKey: ['group', id] })
@@ -163,11 +165,11 @@ export function AttendeeDetailProvider({
onError: (err: Error) => {
const code = err instanceof ApiError ? err.problem?.code : undefined
if (code === 'group_capacity_reached') {
toast.error('Ese grupo alcanzó su cupo. Elegí otro o liberá un lugar primero.')
toast.error(i18n.t('attendeeDetail:changeGroup.targetFull'))
} else if (code === 'attendee_already_registered') {
toast.error('Esta persona ya es miembro de ese grupo.')
toast.error(i18n.t('attendeeDetail:changeGroup.alreadyMember'))
} else {
toast.error(err.message || 'No se pudo cambiar de grupo.')
toast.error(errorMessage(err, i18n.t('attendeeDetail:changeGroup.moveError')))
}
},
})
@@ -175,8 +177,8 @@ export function AttendeeDetailProvider({
const addToGroupMutation = useMutation({
mutationFn: (targetGroupId: string) => addAttendeeToGroup(groupId, attendeeId, targetGroupId),
onSuccess: (added, targetGroupId) => {
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? 'otro grupo'
toast.success(`${added.fullName} ahora también está en ${targetName}.`)
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? i18n.t('attendeeDetail:changeGroup.otherGroup')
toast.success(i18n.t('attendeeDetail:changeGroup.added', { name: added.fullName, group: targetName }))
void queryClient.invalidateQueries({ queryKey: ['group-attendees', targetGroupId] })
void queryClient.invalidateQueries({ queryKey: ['group', targetGroupId] })
// "También está en" de esta ficha (y la de sus otros grupos).
@@ -188,11 +190,11 @@ export function AttendeeDetailProvider({
onError: (err: Error) => {
const code = err instanceof ApiError ? err.problem?.code : undefined
if (code === 'group_capacity_reached') {
toast.error('Ese grupo alcanzó su cupo. Elegí otro o liberá un lugar primero.')
toast.error(i18n.t('attendeeDetail:changeGroup.targetFull'))
} else if (code === 'attendee_already_registered') {
toast.error('Esta persona ya es miembro de ese grupo.')
toast.error(i18n.t('attendeeDetail:changeGroup.alreadyMember'))
} else {
toast.error(err.message || 'No se pudo agregar al grupo.')
toast.error(errorMessage(err, i18n.t('attendeeDetail:changeGroup.addError')))
}
},
})

View File

@@ -17,23 +17,25 @@ import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
import { formatMemberSince } from './attendance'
import { paymentPresentation } from './detail'
import { StudentAccessSection } from './StudentAccessSection'
import { useTranslation } from 'react-i18next'
export function AttendeeDetailView() {
const { groupId, groupName, attendee, attendeePending, attendeeFailed } = useAttendeeDetail()
const navigate = useNavigate()
const { t } = useTranslation(['attendeeDetail', 'common', 'groupDetail'])
const menuTriggerRef = useRef<HTMLButtonElement>(null)
const payment = attendee ? paymentPresentation(attendee.payment) : null
return (
<section className="mx-auto w-full max-w-md animate-fade-in lg:max-w-2xl">
<LargeTitle
title={attendee?.fullName ?? 'Miembro'}
barContext={groupName ?? 'Grupo'}
title={attendee?.fullName ?? t('fallbackName')}
barContext={groupName ?? t('groupDetail:fallbackTitle')}
leading={
<Link
to="/groups/$groupId"
params={{ groupId }}
aria-label="Volver al grupo"
aria-label={t('backToGroup')}
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" />
@@ -54,7 +56,7 @@ export function AttendeeDetailView() {
<Badge variant={payment.isDue ? 'warning' : 'success'} className="text-[11px]">
{payment.chipLabel}
</Badge>
<span>Desde {formatMemberSince(attendee.createdAt)}</span>
<span>{t('since', { date: formatMemberSince(attendee.createdAt) })}</span>
</div>
) : null}
</LargeTitle>
@@ -67,16 +69,16 @@ export function AttendeeDetailView() {
{attendeeFailed || (!attendeePending && !attendee) ? (
<div className="mt-6 rounded-2xl bg-danger-soft p-6">
<h2 className="text-lg font-bold text-danger-fg">Miembro no encontrado</h2>
<h2 className="text-lg font-bold text-danger-fg">{t('notFound.title')}</h2>
<p className="mt-2 text-sm text-primary">
No se pudo cargar la información de este miembro.
{t('notFound.description')}
</p>
<Button
variant="ghost"
className="mt-4 px-0 text-accent-fg hover:bg-transparent hover:text-primary"
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
>
Volver al grupo
{t('backToGroup')}
</Button>
</div>
) : null}

View File

@@ -1,5 +1,6 @@
import { Loader2 } from 'lucide-react'
import { Button } from '../../components/ui'
import { useTranslation } from 'react-i18next'
type AttendeeNotesFormProps = {
draft: string
@@ -18,6 +19,7 @@ export function AttendeeNotesForm({
onCancel,
onSave,
}: AttendeeNotesFormProps) {
const { t } = useTranslation(['attendeeDetail', 'common'])
return (
<div className="space-y-3 px-3 pb-1">
<textarea
@@ -25,7 +27,7 @@ export function AttendeeNotesForm({
onChange={(event) => onDraftChange(event.target.value)}
rows={4}
autoFocus
aria-label="Notas del miembro"
aria-label={t('notes.label')}
className="w-full resize-y rounded-xl border border-border bg-surface px-3 py-2.5 text-base leading-relaxed text-primary placeholder:text-secondary transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 sm:text-sm"
/>
{error ? (
@@ -35,11 +37,11 @@ export function AttendeeNotesForm({
) : null}
<div className="flex justify-end gap-2">
<Button variant="ghost" onClick={onCancel} disabled={isSaving}>
Cancelar
{t('common:actions.cancel')}
</Button>
<Button variant="primary" onClick={onSave} disabled={isSaving}>
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
Guardar
{t('common:actions.save')}
</Button>
</div>
</div>

View File

@@ -3,10 +3,12 @@ import { AttendeeNotesForm } from './AttendeeNotesForm'
import { formatNotesUpdatedAt } from './detail'
import { Section } from './Section'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useTranslation } from 'react-i18next'
export function AttendeeNotesSection() {
const { attendee, saveAttendee, isUpdatingAttendee } = useAttendeeDetail()
const [isEditing, setIsEditing] = useState(false)
const { t } = useTranslation(['attendeeDetail', 'common'])
const [draft, setDraft] = useState('')
const [error, setError] = useState<string | null>(null)
@@ -23,13 +25,13 @@ export function AttendeeNotesSection() {
await saveAttendee({ notes: draft })
setIsEditing(false)
} catch {
setError('No pudimos guardar la nota. Revisá tu conexión e intentá de nuevo.')
setError(t('notes.saveError'))
}
}
return (
<Section
title="Notas"
title={t('notes.title')}
trailing={
!isEditing ? (
<button
@@ -37,7 +39,7 @@ export function AttendeeNotesSection() {
onClick={beginEditing}
className="min-h-11 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
Editar
{t('notes.edit')}
</button>
) : null
}
@@ -60,7 +62,7 @@ export function AttendeeNotesSection() {
) : (
<div className="px-3 pb-1">
<p className="whitespace-pre-line text-sm leading-relaxed text-primary">
{attendee.notes || 'Sin notas todavía.'}
{attendee.notes || t('notes.empty')}
</p>
<p className="mt-1.5 text-xs text-secondary">{formatNotesUpdatedAt(attendee.updatedAt)}</p>
</div>

View File

@@ -2,21 +2,23 @@ import { Badge, useToast } from '../../components/ui'
import { paymentPresentation } from './detail'
import { Section } from './Section'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useTranslation } from 'react-i18next'
export function AttendeePaymentsSection() {
const { attendee } = useAttendeeDetail()
const toast = useToast()
const { t } = useTranslation(['attendeeDetail', 'common'])
if (!attendee) return null
const payment = paymentPresentation(attendee.payment)
const registerPayment = () => {
// TODO(cobros): conectar esta acción cuando se confirme el flujo y el endpoint de pagos.
toast.info('Registrar pagos estará disponible cuando se defina el flujo de cobros.')
toast.info(t('payments.registerPending'))
}
return (
<Section title="Cobros">
<Section title={t('payments.title')}>
<div className="flex min-h-14 items-center justify-between gap-3 px-3 py-1">
<div className="min-w-0">
<p className="truncate text-sm font-medium text-primary">
@@ -31,7 +33,7 @@ export function AttendeePaymentsSection() {
onClick={registerPayment}
className="min-h-11 shrink-0 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
Registrar pago
{t('payments.register')}
</button>
</div>
</Section>

View File

@@ -2,6 +2,7 @@ import { Check } from 'lucide-react'
import { formatPhoneDisplay } from '../../lib/format'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useCopyToClipboard } from './useCopyToClipboard'
import { useTranslation } from 'react-i18next'
/** The phone as the subtitle's second line.
*
@@ -12,6 +13,7 @@ import { useCopyToClipboard } from './useCopyToClipboard'
export function AttendeePhoneLine() {
const { attendee } = useAttendeeDetail()
const { copied, copy } = useCopyToClipboard()
const { t } = useTranslation(['attendeeDetail', 'common'])
const phone = attendee?.phone
const label = formatPhoneDisplay(phone)
@@ -33,12 +35,12 @@ export function AttendeePhoneLine() {
className="flex shrink-0 items-center gap-1 text-xs font-medium text-accent-fg"
>
<Check className="size-3.5" />
Número copiado
{t('phone.copied')}
</span>
) : null}
</button>
<span aria-live="polite" className="sr-only">
{copied ? 'Número copiado al portapapeles' : ''}
{copied ? t('phone.copiedLive') : ''}
</span>
</>
)

View File

@@ -5,6 +5,7 @@ import type { LucideIcon } from 'lucide-react'
import { CalendarCheck, CalendarX, History, Loader2, MoveRight, UserPlus, Wallet } from 'lucide-react'
import { Button, Modal } from '../../components/ui'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useTranslation } from 'react-i18next'
type Consequence = { key: string; icon: LucideIcon; text: string }
@@ -39,6 +40,7 @@ export function ChangeGroupDialog({
const [targetGroupId, setTargetGroupId] = useState('')
const wasOpen = useRef(false)
const { t } = useTranslation(['attendeeDetail', 'common'])
// Cada apertura arranca sin destino elegido; al cerrar, el foco vuelve al "⋯".
useEffect(() => {
@@ -62,7 +64,7 @@ export function ChangeGroupDialog({
.map((membership) => membership.groupId),
)
const otherGroups = groups.filter((group) => group.id !== groupId && !blocked.has(group.id))
const currentName = groupName ?? 'el grupo actual'
const currentName = groupName ?? t('changeGroup.currentGroup')
const isSubmitting = isAdd ? isAddingToGroup : isMovingAttendee
const consequences: Consequence[] = isAdd
@@ -70,34 +72,34 @@ export function ChangeGroupDialog({
{
key: 'sigue',
icon: CalendarCheck,
text: `Sigue en ${currentName}: va a estar en los dos grupos.`,
text: t('changeGroup.addStays', { group: currentName }),
},
{
key: 'datos',
icon: History,
text: 'Comparte el contacto, las notas y el acceso a la app de alumnos.',
text: t('changeGroup.addShares'),
},
{
key: 'cuotas',
icon: Wallet,
text: 'La asistencia y las cuotas se llevan por separado en cada grupo.',
text: t('changeGroup.addSeparate'),
},
]
: [
{
key: 'historial',
icon: History,
text: 'Conserva su historial, sus cuotas y su acceso a la app de alumnos.',
text: t('changeGroup.moveKeeps'),
},
{
key: 'cuotas',
icon: Wallet,
text: `Las cuotas pendientes de ${currentName} siguen vigentes.`,
text: t('changeGroup.moveFees', { group: currentName }),
},
{
key: 'faltas',
icon: CalendarX,
text: `Se cancelan las faltas avisadas para clases futuras de ${currentName}.`,
text: t('changeGroup.moveNotices', { group: currentName }),
},
]
@@ -105,25 +107,27 @@ export function ChangeGroupDialog({
<Modal
isOpen={isOpen}
onClose={closeGroupDialog}
title={isAdd ? 'Agregar a otro grupo' : 'Cambiar de grupo'}
title={isAdd ? t('changeGroup.titleAdd') : t('changeGroup.title')}
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
maxWidth="sm"
>
<div className="space-y-4">
{groupsPending ? (
<div className="flex justify-center py-4">
<Loader2 className="size-5 animate-spin text-foreground/60" aria-label="Cargando grupos" />
<Loader2 className="size-5 animate-spin text-foreground/60" aria-label={t('changeGroup.loadingGroups')} />
</div>
) : otherGroups.length === 0 ? (
<p className="rounded-xl border border-border bg-primary-soft/30 px-4 py-3 text-sm text-foreground/70">
{groups.length > 1
? 'Ya es miembro de todos tus otros grupos.'
: `No tenés otros grupos. Creá uno para poder ${isAdd ? 'agregar' : 'mover'} a este miembro.`}
? t('changeGroup.allGroups')
: isAdd
? t('changeGroup.noGroupsAdd')
: t('changeGroup.noGroupsMove')}
</p>
) : (
<label className="block">
<span className="mb-1.5 block text-sm font-medium text-primary">
{isAdd ? 'Agregar a' : 'Mover a'}
{isAdd ? t('changeGroup.addTo') : t('changeGroup.moveTo')}
</span>
<select
autoFocus
@@ -132,14 +136,13 @@ export function ChangeGroupDialog({
className="h-10 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
>
<option value="" disabled>
Elegí un grupo
{t('changeGroup.pick')}
</option>
{otherGroups.map((group) => {
const full = isFull(group)
return (
<option key={group.id} value={group.id} disabled={full}>
{group.name}
{full ? ' (sin cupo)' : ''}
{full ? t('changeGroup.full', { name: group.name }) : group.name}
</option>
)
})}
@@ -158,7 +161,7 @@ export function ChangeGroupDialog({
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
<Button variant="ghost" onClick={closeGroupDialog}>
Cancelar
{t('common:actions.cancel')}
</Button>
<Button
variant="primary"
@@ -173,7 +176,7 @@ export function ChangeGroupDialog({
) : (
<MoveRight className="size-4" />
)}
<span>{isAdd ? 'Agregar' : 'Cambiar de grupo'}</span>
<span>{isAdd ? t('changeGroup.add') : t('changeGroup.move')}</span>
</Button>
</div>
</div>

View File

@@ -4,6 +4,7 @@ import type { LucideIcon } from 'lucide-react'
import { History, Link2, Loader2, Trash2, UserPlus, Users } from 'lucide-react'
import { Button, Modal } from '../../components/ui'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { Trans, useTranslation } from 'react-i18next'
type Consequence = { key: string; icon: LucideIcon; text: string }
@@ -26,6 +27,7 @@ export function ConfirmRemoveAttendeeDialog({
} = useAttendeeDetail()
const wasOpen = useRef(false)
const { t } = useTranslation(['attendeeDetail', 'common'])
const contentRef = useRef<HTMLDivElement>(null)
useEffect(() => {
@@ -52,27 +54,23 @@ export function ConfirmRemoveAttendeeDialog({
{
key: 'historial',
icon: History,
text: 'Se borra su historial: las clases registradas y las ausencias que avisó dejan de existir.',
text: t('remove.history'),
},
]
if (attendee.notifyToken) {
consequences.push({ key: 'link', icon: Link2, text: 'El link de ausencias deja de funcionar.' })
consequences.push({ key: 'link', icon: Link2, text: t('remove.link') })
}
consequences.push({
key: 'lugar',
icon: Users,
text: waiting
? `Se libera 1 lugar. Hay ${waitlistTotal} ${
waitlistTotal === 1 ? 'persona' : 'personas'
} en lista de espera.`
: 'Se libera 1 lugar en el grupo.',
text: waiting ? t('remove.spotWaiting', { count: waitlistTotal }) : t('remove.spot'),
})
return (
<Modal
isOpen={isRemoveDialogOpen}
onClose={closeRemoveDialog}
title="Quitar del grupo"
title={t('remove.title')}
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
maxWidth="sm"
>
@@ -87,15 +85,18 @@ export function ConfirmRemoveAttendeeDialog({
</ul>
<p className="text-xs text-foreground">
Si tiene cobros registrados no se va a poder quitar: primero hay que gestionarlos.
{t('remove.paymentsNote')}
</p>
{canPromote && firstWaitlistEntry ? (
<div className="rounded-xl bg-accent-soft p-3.5">
<p className="text-sm text-foreground">
Si lo quitás, podés darle el lugar a{' '}
<strong className="text-primary">{firstWaitlistEntry.fullName}</strong>, el primero
de la lista de espera.
<Trans
t={t}
i18nKey="remove.promote"
values={{ name: firstWaitlistEntry.fullName }}
components={{ strong: <strong className="text-primary" /> }}
/>
</p>
<Button
variant="primary"
@@ -108,14 +109,14 @@ export function ConfirmRemoveAttendeeDialog({
) : (
<UserPlus className="size-4" />
)}
<span>Pasar a {firstWaitlistEntry.fullName} al grupo</span>
<span>{t('remove.promoteAction', { name: firstWaitlistEntry.fullName })}</span>
</Button>
</div>
) : null}
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
<Button variant="ghost" onClick={closeRemoveDialog} autoFocus>
Cancelar
{t('common:actions.cancel')}
</Button>
{/* Label in black on the `danger` fill: it is the only way to reach AA
with the same red in both themes (4.9:1 light, 6.7:1 dark); in white
@@ -130,7 +131,7 @@ export function ConfirmRemoveAttendeeDialog({
) : (
<Trash2 className="size-4" />
)}
<span>Quitar del grupo</span>
<span>{t('remove.confirm')}</span>
</Button>
</div>
</div>

View File

@@ -7,6 +7,7 @@ import { inviteStudent } from '../../lib/api'
import { cn } from '../../lib/utils'
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
import { invitationMessage } from './studentAccess'
import { useTranslation } from 'react-i18next'
type InviteToAppSheetProps = {
isOpen: boolean
@@ -34,6 +35,7 @@ export function InviteToAppSheet({
reinvite,
}: InviteToAppSheetProps) {
const queryClient = useQueryClient()
const { t } = useTranslation(['attendeeDetail', 'common'])
const [invitation, setInvitation] = useState<StudentInvitationDto | null>(null)
const [copied, setCopied] = useState(false)
const firstName = fullName.split(' ')[0] ?? fullName
@@ -89,32 +91,32 @@ export function InviteToAppSheet({
}
}
const preview = invitationMessage(firstName, groupName, invitation?.url ?? '🔗 link personal')
const preview = invitationMessage(firstName, groupName, invitation?.url ?? t('inviteSheet.linkPlaceholder'))
return (
<Sheet
isOpen={isOpen}
onClose={handleClose}
title={reinvite ? 'Reinvitar a la app' : 'Invitar a la app'}
title={reinvite ? t('inviteSheet.titleReinvite') : t('inviteSheet.title')}
description={
reinvite
? `Mandale un link nuevo a ${firstName}. El acceso anterior deja de funcionar.`
: `${firstName} va a poder avisar faltas, informar pagos y ver sus próximas clases. Sin contraseñas ni datos nuevos.`
? t('inviteSheet.descriptionReinvite', { name: firstName })
: t('inviteSheet.description', { name: firstName })
}
>
<div className="space-y-4">
<div className="rounded-2xl rounded-tl-sm bg-success-soft px-4 py-3 text-sm text-primary break-words" aria-label="Vista previa del mensaje">
<div className="rounded-2xl rounded-tl-sm bg-success-soft px-4 py-3 text-sm text-primary break-words" aria-label={t('inviteSheet.preview')}>
{preview}
</div>
<p className="flex gap-2 rounded-xl bg-primary-soft px-3 py-2.5 text-xs leading-relaxed text-secondary">
<Lock className="mt-0.5 size-4 shrink-0 text-primary" aria-hidden="true" />
El link es personal, sirve una sola vez y vence en 72 horas. Queda conectado el primer teléfono que lo abra.
{t('inviteSheet.security')}
</p>
{mutation.isError ? (
<p role="alert" className="text-sm text-danger-fg">
No pudimos generar el link. Probá de nuevo.
{t('inviteSheet.error')}
</p>
) : null}
@@ -122,7 +124,7 @@ export function InviteToAppSheet({
{hasPhone ? (
<button type="button" onClick={() => void sendWhatsapp()} disabled={mutation.isPending} className={PRIMARY_ACTION_CLASS}>
{mutation.isPending ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : <MessageCircle className="size-4" aria-hidden="true" />}
Enviar por WhatsApp
{t('inviteSheet.sendWhatsapp')}
</button>
) : null}
<button
@@ -132,7 +134,7 @@ export function InviteToAppSheet({
className={cn(hasPhone ? ACTION_BUTTON_CLASS : PRIMARY_ACTION_CLASS, 'w-full')}
>
{copied ? <Check className="size-4" aria-hidden="true" /> : <Copy className="size-4" aria-hidden="true" />}
<span aria-live="polite">{copied ? 'Link copiado' : 'Copiar link'}</span>
<span aria-live="polite">{copied ? t('inviteSheet.copied') : t('inviteSheet.copy')}</span>
</button>
</div>
</div>

View File

@@ -4,23 +4,25 @@ import type { PersonMembership } from '@gruperly/shared'
import { Badge, type BadgeVariant } from '../../components/ui'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { Section } from './Section'
import { useTranslation } from 'react-i18next'
type StatusBadge = { label: string; variant: BadgeVariant }
type StatusBadge = { label: 'otherGroups.PAUSED' | 'otherGroups.DROPPED'; variant: BadgeVariant }
const STATUS_BADGE: Record<PersonMembership['status'], StatusBadge | null> = {
ACTIVE: null,
PAUSED: { label: 'En pausa', variant: 'warning' },
DROPPED: { label: 'Dado de baja', variant: 'neutral' },
PAUSED: { label: 'otherGroups.PAUSED', variant: 'warning' },
DROPPED: { label: 'otherGroups.DROPPED', variant: 'neutral' },
}
/* La misma persona en otros grupos del profe: cada fila abre su ficha en ese
grupo (asistencia y cuotas son de cada grupo; el contacto es compartido). */
export function OtherGroupsSection() {
const { attendee } = useAttendeeDetail()
const { t } = useTranslation(['attendeeDetail', 'common'])
if (!attendee || attendee.otherGroups.length === 0) return null
return (
<Section title="También está en">
<Section title={t('otherGroups.title')}>
<ul className="divide-y divide-border/60">
{attendee.otherGroups.map((membership) => {
const badge = STATUS_BADGE[membership.status]
@@ -35,7 +37,7 @@ export function OtherGroupsSection() {
<span className="min-w-0 flex-1 truncate text-sm text-primary">{membership.groupName}</span>
{badge ? (
<Badge variant={badge.variant} className="text-[11px]">
{badge.label}
{t(badge.label)}
</Badge>
) : null}
<ChevronRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />

View File

@@ -8,12 +8,14 @@ import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
import { InviteToAppSheet } from './InviteToAppSheet'
import { Section } from './Section'
import { accessBadge, formatAgo, formatSince } from './studentAccess'
import { useTranslation } from 'react-i18next'
/* "Acceso a la app": passive state, nothing to manage. The only action is
inviting (or reinviting, which closes the previous access). */
export function StudentAccessSection() {
const { groupId, groupName, attendee } = useAttendeeDetail()
const [sheetOpen, setSheetOpen] = useState(false)
const { t } = useTranslation(['attendeeDetail', 'common'])
const accessQuery = useQuery({
queryKey: ['student-access', groupId, attendee?.id],
@@ -28,7 +30,7 @@ export function StudentAccessSection() {
const hasPhone = Boolean(attendee.phone || attendee.guardianPhone)
return (
<Section title="Acceso a la app" trailing={badge ? <Badge variant={badge.variant}>{badge.label}</Badge> : null}>
<Section title={t('access.title')} trailing={badge ? <Badge variant={badge.variant}>{badge.label}</Badge> : null}>
<div className="space-y-3 px-3">
{access?.status === 'active'
? access.devices.map((device) => (
@@ -37,8 +39,8 @@ export function StudentAccessSection() {
<div className="min-w-0">
<p className="truncate text-sm font-medium text-primary">{device.device}</p>
<p className="text-xs text-secondary">
Desde el {formatSince(device.createdAt)} · último uso {formatAgo(device.lastUsedAt)}
{access.hasPasskey ? ' · Face ID' : ''}
{t('access.device', { since: formatSince(device.createdAt), ago: formatAgo(device.lastUsedAt) })}
{access.hasPasskey ? t('access.faceId') : ''}
</p>
</div>
</div>
@@ -46,12 +48,12 @@ export function StudentAccessSection() {
: null}
{access?.status === 'not_invited' ? (
<p className="text-sm text-secondary">Para que avise faltas e informe pagos desde su teléfono.</p>
<p className="text-sm text-secondary">{t('access.pitch')}</p>
) : null}
{invited ? (
<p className="text-xs text-secondary">
¿Te dice que no puede entrar? Mandale un link nuevo: cierra el acceso anterior.
{t('access.reinviteHint')}
</p>
) : null}
@@ -62,7 +64,7 @@ export function StudentAccessSection() {
className={invited ? `${ACTION_BUTTON_CLASS} w-full` : PRIMARY_ACTION_CLASS}
>
{invited ? <MessageCircle className="size-4" aria-hidden="true" /> : <UserPlus className="size-4" aria-hidden="true" />}
{invited ? (hasPhone ? 'Reinvitar por WhatsApp' : 'Reinvitar') : 'Invitar a la app'}
{invited ? (hasPhone ? t('access.reinviteWhatsapp') : t('access.reinvite')) : t('access.invite')}
</button>
) : null}
</div>
@@ -71,7 +73,7 @@ export function StudentAccessSection() {
isOpen={sheetOpen}
onClose={() => setSheetOpen(false)}
groupId={groupId}
groupName={groupName ?? 'tu grupo'}
groupName={groupName ?? t('access.yourGroup')}
attendeeId={attendee.id}
fullName={attendee.fullName}
hasPhone={hasPhone}

View File

@@ -1,4 +1,5 @@
import type { AttendanceHistoryItem } from '@gruperly/shared'
import { i18n } from '../../i18n/instance'
/* The history endpoint cuts off at 20 sessions (HISTORY_SESSIONS_LIMIT on the
backend). It is the real ceiling on what this screen can show, so "Ver todas"
@@ -10,22 +11,20 @@ export type AttendanceSession = AttendanceHistoryItem
export function formatSessionShortDate(iso: string): string {
const date = new Date(iso)
const weekday = date.toLocaleDateString('es-MX', { weekday: 'short' })
const day = date.toLocaleDateString('es-MX', { day: 'numeric' })
const month = date.toLocaleDateString('es-MX', { month: 'short' })
const weekday = date.toLocaleDateString(i18n.language, { weekday: 'short' })
const day = date.toLocaleDateString(i18n.language, { day: 'numeric' })
const month = date.toLocaleDateString(i18n.language, { month: 'short' })
return `${weekday} ${day} ${month}`
}
export function attendanceStatusLabel(status: AttendanceSession['status']): string {
switch (status) {
case 'PRESENT':
return 'Asistió'
case 'ABSENT':
return 'Faltó'
case 'EXCUSED':
return 'Faltó (avisó)'
return i18n.t(`attendeeDetail:attendance.${status}`)
default:
return 'Sin registrar'
return i18n.t('attendeeDetail:attendance.NONE')
}
}
@@ -47,7 +46,7 @@ export function attendanceStatusClass(status: AttendanceSession['status']): stri
/** "28 sep 2026". It is the usual short date: it fits on one line on mobile. */
export function formatMemberSince(iso: string): string {
return new Date(iso).toLocaleDateString('es-MX', {
return new Date(iso).toLocaleDateString(i18n.language, {
day: 'numeric',
month: 'short',
year: 'numeric',
@@ -56,7 +55,7 @@ export function formatMemberSince(iso: string): string {
/** "1 clase" / "2 clases". */
export function classCountLabel(count: number): string {
return count === 1 ? '1 clase' : `${count} clases`
return i18n.t('attendeeDetail:attendance.classes', { count })
}
/** What is displayed: from the most recent to the oldest, with the last
@@ -78,8 +77,8 @@ export type AttendanceSummary = {
/** Summary of the rows being shown. The denominator deliberately includes
* unmarked sessions so the counter always matches the visible list. */
export function attendanceSummary(sessions: AttendanceSession[]): AttendanceSummary {
if (sessions.length === 0) return { label: 'Sin clases registradas' }
if (sessions.length === 0) return { label: i18n.t('attendeeDetail:attendance.noClasses') }
const present = sessions.filter((session) => session.status === 'PRESENT').length
return { label: `${present} de ${classCountLabel(sessions.length)}` }
return { label: i18n.t('attendeeDetail:attendance.summary', { present, classes: classCountLabel(sessions.length) }) }
}

View File

@@ -1,6 +1,7 @@
import type { AttendeePaymentSummary } from '@gruperly/shared'
import { UpdateAttendeeSchema } from '@gruperly/shared'
import { validationMessage } from '../../i18n/validation'
import { i18n } from '../../i18n/instance'
export function contactEmailError(email: string): string | null {
const result = UpdateAttendeeSchema.safeParse({ email })
@@ -21,47 +22,50 @@ export function paymentPresentation(
): PaymentPresentation {
const periodLabel = capitalize(formatMonthAndYear(today))
if (!payment) {
return { periodLabel, statusLabel: 'Sin cobro registrado', chipLabel: 'Al día', isDue: false }
return {
periodLabel,
statusLabel: i18n.t('attendeeDetail:payments.noCharge'),
chipLabel: i18n.t('attendeeDetail:payments.upToDate'),
isDue: false,
}
}
const isDue = payment.status === 'PENDING' || payment.status === 'OVERDUE'
return {
periodLabel,
statusLabel: paymentStatusLabel(payment.status),
chipLabel: isDue ? `Debe ${formatMonth(new Date(payment.dueDate))}` : 'Al día',
chipLabel: isDue
? i18n.t('attendeeDetail:payments.owes', { month: formatMonth(new Date(payment.dueDate)) })
: i18n.t('attendeeDetail:payments.upToDate'),
isDue,
}
}
export function formatNotesUpdatedAt(updatedAt: string, today = new Date()): string {
const date = new Date(updatedAt)
if (sameCalendarDate(date, today)) return 'Editado hoy'
return `Editado ${date.toLocaleDateString('es-MX', {
day: 'numeric',
month: 'short',
year: 'numeric',
})}`
if (sameCalendarDate(date, today)) return i18n.t('attendeeDetail:notes.editedToday')
return i18n.t('attendeeDetail:notes.edited', {
date: date.toLocaleDateString(i18n.language, { day: 'numeric', month: 'short', year: 'numeric' }),
})
}
function paymentStatusLabel(status: AttendeePaymentSummary['status']): string {
switch (status) {
case 'PAID':
return 'Pagado'
case 'OVERDUE':
return 'Vencido'
case 'CANCELLED':
return 'Cancelado'
return i18n.t(`common:paymentStatus.${status}`)
default:
return 'Pendiente'
return i18n.t('common:paymentStatus.PENDING')
}
}
function formatMonth(date: Date): string {
return date.toLocaleDateString('es-MX', { month: 'long' })
return date.toLocaleDateString(i18n.language, { month: 'long' })
}
function formatMonthAndYear(date: Date): string {
const parts = new Intl.DateTimeFormat('es-MX', { month: 'long', year: 'numeric' }).formatToParts(date)
const parts = new Intl.DateTimeFormat(i18n.language, { month: 'long', year: 'numeric' }).formatToParts(date)
const month = parts.find((part) => part.type === 'month')?.value ?? ''
const year = parts.find((part) => part.type === 'year')?.value ?? ''
return `${month} ${year}`.trim()

View File

@@ -1,5 +1,6 @@
import type { StudentAccessDto } from '@gruperly/shared'
import type { BadgeVariant } from '../../components/ui'
import { i18n } from '../../i18n/instance'
const HOUR_MS = 3_600_000
const DAY_MS = 24 * HOUR_MS
@@ -7,33 +8,36 @@ const DAY_MS = 24 * HOUR_MS
export function accessBadge(access: StudentAccessDto, now: Date = new Date()): { label: string; variant: BadgeVariant } {
switch (access.status) {
case 'active':
return { label: 'Activo', variant: 'success' }
return { label: i18n.t('attendeeDetail:access.active'), variant: 'success' }
case 'invited': {
const hours = access.invitationExpiresAt
? Math.max(1, Math.ceil((Date.parse(access.invitationExpiresAt) - now.getTime()) / HOUR_MS))
: null
return { label: hours ? `Invitado · vence en ${hours} h` : 'Invitado', variant: 'info' }
return {
label: hours ? i18n.t('attendeeDetail:access.invitedExpires', { hours }) : i18n.t('attendeeDetail:access.invited'),
variant: 'info',
}
}
case 'expired':
return { label: 'Vencido', variant: 'warning' }
return { label: i18n.t('attendeeDetail:access.expired'), variant: 'warning' }
default:
return { label: 'Sin invitar', variant: 'neutral' }
return { label: i18n.t('attendeeDetail:access.notInvited'), variant: 'neutral' }
}
}
/** "hace 5 min", "hace 3 h", "ayer", "hace 4 días". */
export function formatAgo(iso: string, now: Date = new Date()): string {
const diff = Math.max(0, now.getTime() - Date.parse(iso))
if (diff < HOUR_MS) return `hace ${Math.max(1, Math.round(diff / 60_000))} min`
if (diff < DAY_MS) return `hace ${Math.round(diff / HOUR_MS)} h`
if (diff < HOUR_MS) return i18n.t('attendeeDetail:access.agoMinutes', { count: Math.max(1, Math.round(diff / 60_000)) })
if (diff < DAY_MS) return i18n.t('attendeeDetail:access.agoHours', { count: Math.round(diff / HOUR_MS) })
const days = Math.round(diff / DAY_MS)
return days === 1 ? 'ayer' : `hace ${days} días`
return days === 1 ? i18n.t('attendeeDetail:access.yesterday') : i18n.t('attendeeDetail:access.agoDays', { count: days })
}
export function formatSince(iso: string): string {
return new Date(iso).toLocaleDateString('es-AR', { day: 'numeric', month: 'long' })
return new Date(iso).toLocaleDateString(i18n.language, { day: 'numeric', month: 'long' })
}
export function invitationMessage(firstName: string, groupName: string, url: string): string {
return `¡Hola ${firstName}! Te invito a gruperly para avisar faltas e informar pagos de ${groupName}. ${url}`
return i18n.t('attendeeDetail:inviteSheet.message', { name: firstName, group: groupName, url })
}