feat(i18n): traducir Cobros

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-11-03 13:53:40 -03:00
parent 13723d5bb9
commit 7db9414f12
15 changed files with 344 additions and 66 deletions

View File

@@ -1,9 +1,11 @@
import { Link } from '@tanstack/react-router' import { Link } from '@tanstack/react-router'
import { Plus } from 'lucide-react' import { Plus } from 'lucide-react'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { useTranslation } from 'react-i18next'
/* Pie del selector de grupos de Cobros: lleva al alta de grupo. */ /* Pie del selector de grupos de Cobros: lleva al alta de grupo. */
export function CreateGroupLink({ compact = false }: { compact?: boolean }) { export function CreateGroupLink({ compact = false }: { compact?: boolean }) {
const { t } = useTranslation('payments')
return ( return (
<Link <Link
to="/groups/new" to="/groups/new"
@@ -13,7 +15,7 @@ export function CreateGroupLink({ compact = false }: { compact?: boolean }) {
)} )}
> >
<Plus className="size-4" aria-hidden="true" /> <Plus className="size-4" aria-hidden="true" />
Crear un grupo nuevo {t('groupFilter.create')}
</Link> </Link>
) )
} }

View File

@@ -5,6 +5,7 @@ import { cn } from '../../lib/utils'
import { CreateGroupLink } from './CreateGroupLink' import { CreateGroupLink } from './CreateGroupLink'
import { GroupOptionList } from './GroupOptionList' import { GroupOptionList } from './GroupOptionList'
import { usePayments } from './PaymentsProvider' import { usePayments } from './PaymentsProvider'
import { useTranslation } from 'react-i18next'
/* Mismo corte que la fila de filtros: debajo de `lg` la fila scrollea en /* Mismo corte que la fila de filtros: debajo de `lg` la fila scrollea en
horizontal y un popover absoluto quedaría recortado, así que ahí va el sheet. */ horizontal y un popover absoluto quedaría recortado, así que ahí va el sheet. */
@@ -26,6 +27,7 @@ function useIsDesktop() {
export function GroupFilter() { export function GroupFilter() {
const { groups, groupId, setGroupId } = usePayments() const { groups, groupId, setGroupId } = usePayments()
const [isOpen, setIsOpen] = useState(false) const [isOpen, setIsOpen] = useState(false)
const { t } = useTranslation('payments')
const isDesktop = useIsDesktop() const isDesktop = useIsDesktop()
const rootRef = useRef<HTMLDivElement>(null) const rootRef = useRef<HTMLDivElement>(null)
const chipRef = useRef<HTMLButtonElement>(null) const chipRef = useRef<HTMLButtonElement>(null)
@@ -72,7 +74,7 @@ export function GroupFilter() {
type="button" type="button"
aria-haspopup="listbox" aria-haspopup="listbox"
aria-expanded={isOpen} aria-expanded={isOpen}
aria-label={`Grupo: ${selected?.name ?? 'Todos los grupos'}`} aria-label={t('groupFilter.label', { name: selected?.name ?? t('groupFilter.all') })}
onClick={() => setIsOpen((open) => !open)} onClick={() => setIsOpen((open) => !open)}
className={cn( className={cn(
'flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm font-medium transition-colors', 'flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm font-medium transition-colors',
@@ -83,7 +85,7 @@ export function GroupFilter() {
)} )}
> >
<Users className="size-4 shrink-0" aria-hidden="true" /> <Users className="size-4 shrink-0" aria-hidden="true" />
<span className="max-w-[12rem] truncate">{selected?.name ?? 'Todos los grupos'}</span> <span className="max-w-[12rem] truncate">{selected?.name ?? t('groupFilter.all')}</span>
<ChevronDown <ChevronDown
className={cn( className={cn(
'size-4 shrink-0 transition-transform motion-reduce:transition-none', 'size-4 shrink-0 transition-transform motion-reduce:transition-none',
@@ -96,7 +98,7 @@ export function GroupFilter() {
{isDesktop ? ( {isDesktop ? (
isOpen ? ( isOpen ? (
<div className="absolute left-0 top-full z-40 mt-1.5 w-80 animate-fade-in rounded-xl border border-border bg-surface p-1.5 shadow-lg"> <div className="absolute left-0 top-full z-40 mt-1.5 w-80 animate-fade-in rounded-xl border border-border bg-surface p-1.5 shadow-lg">
<p className="px-2.5 py-1.5 text-xs font-medium text-foreground/50">Grupos</p> <p className="px-2.5 py-1.5 text-xs font-medium text-foreground/50">{t('groupFilter.groups')}</p>
<div className="max-h-80 overflow-y-auto">{list}</div> <div className="max-h-80 overflow-y-auto">{list}</div>
<div className="mt-1.5 border-t border-border pt-1.5"> <div className="mt-1.5 border-t border-border pt-1.5">
<CreateGroupLink compact /> <CreateGroupLink compact />
@@ -104,7 +106,7 @@ export function GroupFilter() {
</div> </div>
) : null ) : null
) : ( ) : (
<Sheet isOpen={isOpen} onClose={close} title="Elegir grupo"> <Sheet isOpen={isOpen} onClose={close} title={t('groupFilter.choose')}>
{list} {list}
<div className="mt-3 border-t border-border pt-2"> <div className="mt-3 border-t border-border pt-2">
<CreateGroupLink /> <CreateGroupLink />

View File

@@ -2,8 +2,10 @@ import type { GroupListItem } from '@gruperly/shared'
import { Check, LayoutGrid } from 'lucide-react' import { Check, LayoutGrid } from 'lucide-react'
import { useEffect, useRef, useState, type KeyboardEvent } from 'react' import { useEffect, useRef, useState, type KeyboardEvent } from 'react'
import { Avatar, Badge } from '../../components/ui' import { Avatar, Badge } from '../../components/ui'
import { i18n } from '../../i18n/instance'
import { formatPrice } from '../../lib/format' import { formatPrice } from '../../lib/format'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { useTranslation } from 'react-i18next'
type GroupOptionListProps = { type GroupOptionListProps = {
groups: GroupListItem[] groups: GroupListItem[]
@@ -20,26 +22,28 @@ type Option = {
unpaid: number unpaid: number
} }
function plural(count: number, singular: string, pluralForm: string): string {
return `${count} ${count === 1 ? singular : pluralForm}`
}
function groupSubtitle(group: GroupListItem): string { function groupSubtitle(group: GroupListItem): string {
const members = plural(group.attendeesCount, 'miembro', 'miembros') const members = i18n.t('payments:groupFilter.members', { count: group.attendeesCount })
if (group.price == null) return members if (group.price == null) return members
const unit = group.billingType === 'PER_CLASS' ? '/clase' : '/mes' const price = formatPrice(group.price)
return `${members} · ${formatPrice(group.price)}${unit}` const priced =
group.billingType === 'PER_CLASS'
? i18n.t('payments:groupFilter.perClass', { price })
: i18n.t('payments:groupFilter.perMonth', { price })
return `${members} · ${priced}`
} }
/* Lista de grupos del filtro de Cobros, compartida por el bottom sheet y el /* Lista de grupos del filtro de Cobros, compartida por el bottom sheet y el
dropdown. Foco "roving": la opción activa es la única tabulable y las flechas dropdown. Foco "roving": la opción activa es la única tabulable y las flechas
mueven el foco real, así el lector de pantalla lee cada opción. */ mueven el foco real, así el lector de pantalla lee cada opción. */
export function GroupOptionList({ groups, selectedId, onSelect, compact = false }: GroupOptionListProps) { export function GroupOptionList({ groups, selectedId, onSelect, compact = false }: GroupOptionListProps) {
const { t } = useTranslation('payments')
const options: Option[] = [ const options: Option[] = [
{ {
id: null, id: null,
name: 'Todos los grupos', name: t('groupFilter.all'),
subtitle: plural(groups.length, 'grupo', 'grupos'), subtitle: t('groupFilter.groupCount', { count: groups.length }),
unpaid: groups.reduce((sum, group) => sum + group.unpaidPaymentsCount, 0), unpaid: groups.reduce((sum, group) => sum + group.unpaidPaymentsCount, 0),
}, },
...groups.map((group) => ({ ...groups.map((group) => ({
@@ -93,7 +97,7 @@ export function GroupOptionList({ groups, selectedId, onSelect, compact = false
} }
return ( return (
<ul role="listbox" aria-label="Grupos" onKeyDown={handleKeyDown} className="space-y-0.5"> <ul role="listbox" aria-label={t('groupFilter.groups')} onKeyDown={handleKeyDown} className="space-y-0.5">
{options.map((option, index) => { {options.map((option, index) => {
const isSelected = option.id === selectedId const isSelected = option.id === selectedId
return ( return (
@@ -131,7 +135,7 @@ export function GroupOptionList({ groups, selectedId, onSelect, compact = false
<span className="block truncate text-xs text-foreground/60">{option.subtitle}</span> <span className="block truncate text-xs text-foreground/60">{option.subtitle}</span>
</span> </span>
{option.unpaid > 0 ? ( {option.unpaid > 0 ? (
<Badge variant="neutral" aria-label={plural(option.unpaid, 'cobro pendiente', 'cobros pendientes')}> <Badge variant="neutral" aria-label={t('groupFilter.unpaid', { count: option.unpaid })}>
{option.unpaid} {option.unpaid}
</Badge> </Badge>
) : null} ) : null}

View File

@@ -5,6 +5,7 @@ import { Badge, Button } from '../../components/ui'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { formatPrice, paymentStatusLabel } from '../../lib/format' import { formatPrice, paymentStatusLabel } from '../../lib/format'
import { paymentDateLabel, paymentPeriodLabel, PAYMENT_STATUS_BADGE } from './copy' import { paymentDateLabel, paymentPeriodLabel, PAYMENT_STATUS_BADGE } from './copy'
import { useTranslation } from 'react-i18next'
type PaymentRowProps = { type PaymentRowProps = {
payment: PaymentDto payment: PaymentDto
@@ -16,6 +17,7 @@ type PaymentRowProps = {
export function PaymentRow({ payment, showGroup, isRenewing, onRenew }: PaymentRowProps) { export function PaymentRow({ payment, showGroup, isRenewing, onRenew }: PaymentRowProps) {
const [copied, setCopied] = useState(false) const [copied, setCopied] = useState(false)
const { t } = useTranslation(['payments', 'common'])
const canCopy = Boolean(payment.checkoutUrl) const canCopy = Boolean(payment.checkoutUrl)
const canRenew = !payment.checkoutUrl || payment.status === 'CANCELLED' const canRenew = !payment.checkoutUrl || payment.status === 'CANCELLED'
@@ -61,7 +63,7 @@ export function PaymentRow({ payment, showGroup, isRenewing, onRenew }: PaymentR
) : ( ) : (
<Copy className="size-3.5 text-accent" /> <Copy className="size-3.5 text-accent" />
)} )}
{copied ? 'Copiado' : 'Copiar link'} {copied ? t('row.copied') : t('row.copyLink')}
</Button> </Button>
) : ( ) : (
<span <span
@@ -71,7 +73,7 @@ export function PaymentRow({ payment, showGroup, isRenewing, onRenew }: PaymentR
)} )}
> >
<Link2 className="size-3.5" /> <Link2 className="size-3.5" />
Sin link {t('row.noLink')}
</span> </span>
)} )}
@@ -88,7 +90,7 @@ export function PaymentRow({ payment, showGroup, isRenewing, onRenew }: PaymentR
) : ( ) : (
<RefreshCw className="size-3.5 text-accent" /> <RefreshCw className="size-3.5 text-accent" />
)} )}
Generar link {t('row.generate')}
</Button> </Button>
) : null} ) : null}
</div> </div>

View File

@@ -2,7 +2,9 @@ import type { GroupListItem, PaymentDto, PaymentQuery, PaymentStatus } from '@gr
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { createContext, useContext, useMemo, useState } from 'react' import { createContext, useContext, useMemo, useState } from 'react'
import { ApiError, getGroups, getPayments, renewPaymentLink } from '../../lib/api' import { errorMessage as apiErrorMessage } from '../../i18n'
import { i18n } from '../../i18n/instance'
import { getGroups, getPayments, renewPaymentLink } from '../../lib/api'
export type PaymentFilterStatus = PaymentStatus | 'ALL' export type PaymentFilterStatus = PaymentStatus | 'ALL'
@@ -85,9 +87,7 @@ export function PaymentsProvider({ children }: { children: ReactNode }) {
const pagination = data?.pagination const pagination = data?.pagination
const errorMessage = paymentsQuery.isError const errorMessage = paymentsQuery.isError
? paymentsQuery.error instanceof ApiError ? apiErrorMessage(paymentsQuery.error, i18n.t('payments:loadError'))
? paymentsQuery.error.problem?.detail ?? 'No pudimos cargar tus cobros.'
: 'No pudimos cargar tus cobros.'
: null : null
return ( return (

View File

@@ -6,14 +6,10 @@ import { GroupFilter } from './GroupFilter'
import { PaymentRow } from './PaymentRow' import { PaymentRow } from './PaymentRow'
import { ReportedPaymentsSection } from './ReportedPaymentsSection' import { ReportedPaymentsSection } from './ReportedPaymentsSection'
import { usePayments } from './PaymentsProvider' import { usePayments } from './PaymentsProvider'
import { useTranslation } from 'react-i18next'
const STATUS_FILTERS: readonly { value: 'ALL' | PaymentStatus; label: string }[] = [ /** Labels: `payments:filters.<value>`. */
{ value: 'ALL', label: 'Todos' }, const STATUS_FILTERS: readonly ('ALL' | PaymentStatus)[] = ['ALL', 'PENDING', 'PAID', 'OVERDUE', 'CANCELLED']
{ value: 'PENDING', label: 'Pendientes' },
{ value: 'PAID', label: 'Pagados' },
{ value: 'OVERDUE', label: 'Vencidos' },
{ value: 'CANCELLED', label: 'Anulados' },
]
export function PaymentsView() { export function PaymentsView() {
const { const {
@@ -33,13 +29,14 @@ export function PaymentsView() {
renew, renew,
isRenewing, isRenewing,
} = usePayments() } = usePayments()
const { t } = useTranslation(['payments', 'common'])
return ( return (
<section> <section>
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
<div> <div>
<h1 className="text-2xl font-bold text-primary">Cobros</h1> <h1 className="text-2xl font-bold text-primary">{t('title')}</h1>
<p className="mt-1 text-sm text-foreground/60">Seguí los pagos de tus grupos.</p> <p className="mt-1 text-sm text-foreground/60">{t('subtitle')}</p>
</div> </div>
</div> </div>
@@ -50,16 +47,16 @@ export function PaymentsView() {
<div className="mt-5 flex items-center gap-2 overflow-x-auto lg:flex-wrap lg:overflow-visible"> <div className="mt-5 flex items-center gap-2 overflow-x-auto lg:flex-wrap lg:overflow-visible">
<GroupFilter /> <GroupFilter />
<span className="h-6 w-px shrink-0 bg-border" aria-hidden="true" /> <span className="h-6 w-px shrink-0 bg-border" aria-hidden="true" />
<div role="tablist" aria-label="Filtrar por estado" className="flex gap-2 lg:flex-wrap"> <div role="tablist" aria-label={t('statusFilterLabel')} className="flex gap-2 lg:flex-wrap">
{STATUS_FILTERS.map((filter) => { {STATUS_FILTERS.map((filter) => {
const isActive = status === filter.value const isActive = status === filter
return ( return (
<button <button
key={filter.value} key={filter}
type="button" type="button"
role="tab" role="tab"
aria-selected={isActive} aria-selected={isActive}
onClick={() => setStatus(filter.value)} onClick={() => setStatus(filter)}
className={cn( className={cn(
'shrink-0 rounded-full border px-3.5 py-1.5 text-sm font-medium transition-colors', 'shrink-0 rounded-full border px-3.5 py-1.5 text-sm font-medium transition-colors',
isActive isActive
@@ -67,7 +64,7 @@ export function PaymentsView() {
: 'border-border bg-surface text-foreground/70 hover:text-primary', : 'border-border bg-surface text-foreground/70 hover:text-primary',
)} )}
> >
{filter.label} {t(`filters.${filter}`)}
</button> </button>
) )
})} })}
@@ -77,7 +74,7 @@ export function PaymentsView() {
{isPending ? ( {isPending ? (
<div className="mt-8 flex items-center justify-center py-16" role="status"> <div className="mt-8 flex items-center justify-center py-16" role="status">
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" /> <Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
<span className="sr-only">Cargando cobros</span> <span className="sr-only">{t('loading')}</span>
</div> </div>
) : null} ) : null}
@@ -85,7 +82,7 @@ export function PaymentsView() {
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger"> <div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
<p>{errorMessage}</p> <p>{errorMessage}</p>
<Button variant="outline" size="sm" onClick={retry}> <Button variant="outline" size="sm" onClick={retry}>
Reintentar {t('common:actions.retry')}
</Button> </Button>
</div> </div>
) : null} ) : null}
@@ -95,9 +92,9 @@ export function PaymentsView() {
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg"> <span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg">
<Wallet className="size-7" aria-hidden="true" /> <Wallet className="size-7" aria-hidden="true" />
</span> </span>
<p className="mt-4 text-base font-semibold text-primary">Todavía no hay cobros</p> <p className="mt-4 text-base font-semibold text-primary">{t('empty.title')}</p>
<p className="mx-auto mt-1.5 max-w-[34ch] text-sm leading-relaxed text-secondary"> <p className="mx-auto mt-1.5 max-w-[34ch] text-sm leading-relaxed text-secondary">
Entrá a un grupo, abrí la ficha y creá los links de cobro del período. {t('empty.description')}
</p> </p>
</div> </div>
) : null} ) : null}
@@ -124,10 +121,10 @@ export function PaymentsView() {
onClick={() => setPage(page - 1)} onClick={() => setPage(page - 1)}
> >
<ChevronLeft className="size-4" /> <ChevronLeft className="size-4" />
Anteriores {t('prev')}
</Button> </Button>
<p className="text-xs text-foreground/50"> <p className="text-xs text-foreground/50">
Página {page} de {totalPages} · {total} cobros {t('pageInfo', { page, pages: totalPages, count: total })}
</p> </p>
<Button <Button
variant="outline" variant="outline"
@@ -135,7 +132,7 @@ export function PaymentsView() {
disabled={page >= totalPages} disabled={page >= totalPages}
onClick={() => setPage(page + 1)} onClick={() => setPage(page + 1)}
> >
Siguientes {t('next')}
<ChevronRight className="size-4" /> <ChevronRight className="size-4" />
</Button> </Button>
</div> </div>
@@ -143,7 +140,7 @@ export function PaymentsView() {
{isFetching && page > 1 ? ( {isFetching && page > 1 ? (
<p className="flex items-center justify-center gap-2 py-4 text-sm text-foreground/50"> <p className="flex items-center justify-center gap-2 py-4 text-sm text-foreground/50">
<Loader2 className="size-4 animate-spin" /> <Loader2 className="size-4 animate-spin" />
Actualizando… {t('updating')}
</p> </p>
) : null} ) : null}
</> </>

View File

@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query'
import { ExternalLink, FileText, Loader2 } from 'lucide-react' import { ExternalLink, FileText, Loader2 } from 'lucide-react'
import { Sheet } from '../../components/ui' import { Sheet } from '../../components/ui'
import { getReceiptUrl } from '../../lib/api' import { getReceiptUrl } from '../../lib/api'
import { useTranslation } from 'react-i18next'
const INLINE_IMAGES = new Set(['image/jpeg', 'image/png', 'image/webp']) const INLINE_IMAGES = new Set(['image/jpeg', 'image/png', 'image/webp'])
@@ -9,6 +10,7 @@ type ReceiptViewerProps = { reportId: string | null; title: string; onClose: ()
/* The file is private: each open asks for a fresh signed URL (5 minutes). */ /* The file is private: each open asks for a fresh signed URL (5 minutes). */
export function ReceiptViewer({ reportId, title, onClose }: ReceiptViewerProps) { export function ReceiptViewer({ reportId, title, onClose }: ReceiptViewerProps) {
const { t } = useTranslation('payments')
const query = useQuery({ const query = useQuery({
queryKey: ['receipt-url', reportId], queryKey: ['receipt-url', reportId],
queryFn: () => getReceiptUrl(reportId as string), queryFn: () => getReceiptUrl(reportId as string),
@@ -18,21 +20,21 @@ export function ReceiptViewer({ reportId, title, onClose }: ReceiptViewerProps)
}) })
return ( return (
<Sheet isOpen={reportId !== null} onClose={onClose} title="Comprobante" description={title}> <Sheet isOpen={reportId !== null} onClose={onClose} title={t('reported.receipt')} description={title}>
{query.isPending ? ( {query.isPending ? (
<div className="flex justify-center py-10" role="status" aria-label="Cargando comprobante"> <div className="flex justify-center py-10" role="status" aria-label={t('reported.loadingReceipt')}>
<Loader2 className="size-6 animate-spin text-accent" aria-hidden="true" /> <Loader2 className="size-6 animate-spin text-accent" aria-hidden="true" />
</div> </div>
) : query.isError || !query.data ? ( ) : query.isError || !query.data ? (
<p role="alert" className="py-6 text-center text-sm text-danger-fg"> <p role="alert" className="py-6 text-center text-sm text-danger-fg">
No pudimos abrir el comprobante. {t('reported.receiptError')}
</p> </p>
) : ( ) : (
<div className="space-y-3"> <div className="space-y-3">
{INLINE_IMAGES.has(query.data.mime) ? ( {INLINE_IMAGES.has(query.data.mime) ? (
<img src={query.data.url} alt={`Comprobante: ${query.data.name}`} className="max-h-[60dvh] w-full rounded-xl object-contain" /> <img src={query.data.url} alt={t('reported.receiptAlt', { name: query.data.name })} className="max-h-[60dvh] w-full rounded-xl object-contain" />
) : query.data.mime === 'application/pdf' ? ( ) : query.data.mime === 'application/pdf' ? (
<iframe src={query.data.url} title={`Comprobante: ${query.data.name}`} className="h-[60dvh] w-full rounded-xl border border-border" /> <iframe src={query.data.url} title={t('reported.receiptAlt', { name: query.data.name })} className="h-[60dvh] w-full rounded-xl border border-border" />
) : ( ) : (
<div className="flex items-center gap-3 rounded-xl bg-primary-soft p-4 text-sm text-primary"> <div className="flex items-center gap-3 rounded-xl bg-primary-soft p-4 text-sm text-primary">
<FileText className="size-6 shrink-0" aria-hidden="true" /> <FileText className="size-6 shrink-0" aria-hidden="true" />
@@ -46,7 +48,7 @@ export function ReceiptViewer({ reportId, title, onClose }: ReceiptViewerProps)
className="flex min-h-11 items-center justify-center gap-2 rounded-xl border border-border text-sm font-medium text-primary hover:bg-primary-soft" className="flex min-h-11 items-center justify-center gap-2 rounded-xl border border-border text-sm font-medium text-primary hover:bg-primary-soft"
> >
<ExternalLink className="size-4" aria-hidden="true" /> <ExternalLink className="size-4" aria-hidden="true" />
Abrir en otra pestaña {t('reported.openTab')}
</a> </a>
</div> </div>
)} )}

View File

@@ -2,7 +2,10 @@ import { useEffect, useRef, useState } from 'react'
import type { ReportedPaymentDto } from '@gruperly/shared' import type { ReportedPaymentDto } from '@gruperly/shared'
import { Check, ChevronRight, FileText, Loader2, X } from 'lucide-react' import { Check, ChevronRight, FileText, Loader2, X } from 'lucide-react'
import { Avatar, Button, Input, Label } from '../../components/ui' import { Avatar, Button, Input, Label } from '../../components/ui'
import { i18n } from '../../i18n/instance'
import { useIntlLocale } from '../../i18n'
import { formatPrice } from '../../lib/format' import { formatPrice } from '../../lib/format'
import { useTranslation } from 'react-i18next'
const UNDO_MS = 6000 const UNDO_MS = 6000
@@ -20,12 +23,14 @@ type ReportedPaymentCardProps = {
function feeName(fee: ReportedPaymentDto['fees'][number]): string { function feeName(fee: ReportedPaymentDto['fees'][number]): string {
if (fee.description) return fee.description if (fee.description) return fee.description
const month = new Date(fee.dueDate).toLocaleDateString('es-AR', { month: 'long', timeZone: 'UTC' }) const month = new Date(fee.dueDate).toLocaleDateString(i18n.language, { month: 'long', timeZone: 'UTC' })
return month.charAt(0).toUpperCase() + month.slice(1) return month.charAt(0).toUpperCase() + month.slice(1)
} }
export function ReportedPaymentCard({ report, onOpenReceipt, onConfirm, onReject, onUndo, onSettled }: ReportedPaymentCardProps) { export function ReportedPaymentCard({ report, onOpenReceipt, onConfirm, onReject, onUndo, onSettled }: ReportedPaymentCardProps) {
const [outcome, setOutcome] = useState<Outcome | null>(null) const [outcome, setOutcome] = useState<Outcome | null>(null)
const { t } = useTranslation(['payments', 'common'])
const locale = useIntlLocale()
const [rejecting, setRejecting] = useState(false) const [rejecting, setRejecting] = useState(false)
const [reason, setReason] = useState('') const [reason, setReason] = useState('')
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
@@ -53,7 +58,7 @@ export function ReportedPaymentCard({ report, onOpenReceipt, onConfirm, onReject
} }
const amount = formatPrice(report.totalAmount, report.currency) const amount = formatPrice(report.totalAmount, report.currency)
const reportedAt = new Date(report.createdAt).toLocaleString('es-AR', { const reportedAt = new Date(report.createdAt).toLocaleString(locale, {
day: 'numeric', day: 'numeric',
month: 'short', month: 'short',
hour: '2-digit', hour: '2-digit',
@@ -71,11 +76,14 @@ export function ReportedPaymentCard({ report, onOpenReceipt, onConfirm, onReject
<X className="size-5 shrink-0 text-danger-fg" aria-hidden="true" /> <X className="size-5 shrink-0 text-danger-fg" aria-hidden="true" />
)} )}
<span className="truncate"> <span className="truncate">
{outcome === 'confirmed' ? 'Confirmado' : 'Rechazado'}: {report.attendee.fullName} · {amount} {t(outcome === 'confirmed' ? 'reported.confirmed' : 'reported.rejected', {
name: report.attendee.fullName,
amount,
})}
</span> </span>
</p> </p>
<Button variant="outline" className="h-11 shrink-0" onClick={() => void run(onUndo, null)} disabled={busy}> <Button variant="outline" className="h-11 shrink-0" onClick={() => void run(onUndo, null)} disabled={busy}>
Deshacer {t('reported.undo')}
</Button> </Button>
</li> </li>
) )
@@ -109,7 +117,7 @@ export function ReportedPaymentCard({ report, onOpenReceipt, onConfirm, onReject
</span> </span>
<span className="min-w-0 flex-1"> <span className="min-w-0 flex-1">
<span className="block text-sm font-medium text-primary"> <span className="block text-sm font-medium text-primary">
{report.receipt.available ? 'Ver comprobante' : 'Comprobante eliminado'} {report.receipt.available ? t('reported.viewReceipt') : t('reported.receiptDeleted')}
</span> </span>
<span className="block truncate text-xs text-secondary">{report.fees.map(feeName).join(', ')}</span> <span className="block truncate text-xs text-secondary">{report.fees.map(feeName).join(', ')}</span>
</span> </span>
@@ -118,7 +126,7 @@ export function ReportedPaymentCard({ report, onOpenReceipt, onConfirm, onReject
{report.note ? ( {report.note ? (
<p className="mt-3 whitespace-pre-line break-words rounded-xl border border-border px-3 py-2 text-sm text-primary"> <p className="mt-3 whitespace-pre-line break-words rounded-xl border border-border px-3 py-2 text-sm text-primary">
<span className="block text-xs font-medium text-secondary">Nota del alumno</span> <span className="block text-xs font-medium text-secondary">{t('reported.studentNote')}</span>
{report.note} {report.note}
</p> </p>
) : null} ) : null}
@@ -131,22 +139,22 @@ export function ReportedPaymentCard({ report, onOpenReceipt, onConfirm, onReject
void run(() => onReject(reason.trim() || null), 'rejected') void run(() => onReject(reason.trim() || null), 'rejected')
}} }}
> >
<Label htmlFor={`reject-${report.id}`}>Motivo (opcional, lo ve el alumno)</Label> <Label htmlFor={`reject-${report.id}`}>{t('reported.reason')}</Label>
<Input id={`reject-${report.id}`} autoFocus maxLength={300} value={reason} onChange={(event) => setReason(event.target.value)} className="h-11" /> <Input id={`reject-${report.id}`} autoFocus maxLength={300} value={reason} onChange={(event) => setReason(event.target.value)} className="h-11" />
<div className="flex gap-2"> <div className="flex gap-2">
<Button variant="ghost" className="h-11 flex-1" onClick={() => setRejecting(false)}> <Button variant="ghost" className="h-11 flex-1" onClick={() => setRejecting(false)}>
Cancelar {t('common:actions.cancel')}
</Button> </Button>
<Button type="submit" variant="outline" className="h-11 flex-1" disabled={busy}> <Button type="submit" variant="outline" className="h-11 flex-1" disabled={busy}>
{busy ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : null} {busy ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : null}
Rechazar pago {t('reported.rejectPayment')}
</Button> </Button>
</div> </div>
</form> </form>
) : ( ) : (
<div className="mt-3 flex gap-2"> <div className="mt-3 flex gap-2">
<Button variant="outline" className="h-11 flex-1" onClick={() => setRejecting(true)} disabled={busy}> <Button variant="outline" className="h-11 flex-1" onClick={() => setRejecting(true)} disabled={busy}>
Rechazar {t('reported.reject')}
</Button> </Button>
<Button <Button
// Light fill, `primary` text (the green on its soft tint misses 4.5:1); // Light fill, `primary` text (the green on its soft tint misses 4.5:1);
@@ -156,13 +164,13 @@ export function ReportedPaymentCard({ report, onOpenReceipt, onConfirm, onReject
disabled={busy} disabled={busy}
> >
{busy ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : <Check className="size-4 text-success" strokeWidth={3} aria-hidden="true" />} {busy ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : <Check className="size-4 text-success" strokeWidth={3} aria-hidden="true" />}
Confirmar {t('reported.confirm')}
</Button> </Button>
</div> </div>
)} )}
{failed ? ( {failed ? (
<p role="alert" className="mt-2 text-sm text-danger-fg"> <p role="alert" className="mt-2 text-sm text-danger-fg">
No pudimos guardar el cambio. Probá de nuevo. {t('reported.error')}
</p> </p>
) : null} ) : null}
</li> </li>

View File

@@ -5,12 +5,14 @@ import { confirmReportedPayment, rejectReportedPayment, undoPaymentReview } from
import { ReceiptViewer } from './ReceiptViewer' import { ReceiptViewer } from './ReceiptViewer'
import { ReportedPaymentCard } from './ReportedPaymentCard' import { ReportedPaymentCard } from './ReportedPaymentCard'
import { REPORTED_PAYMENTS_KEY, useReportedPayments } from './reportedPayments' import { REPORTED_PAYMENTS_KEY, useReportedPayments } from './reportedPayments'
import { useTranslation } from 'react-i18next'
/* "Pagos para verificar": receipts the students reported. Confirming marks the /* "Pagos para verificar": receipts the students reported. Confirming marks the
fees as paid; a reviewed card stays a few seconds with "Deshacer" before it fees as paid; a reviewed card stays a few seconds with "Deshacer" before it
leaves the list. */ leaves the list. */
export function ReportedPaymentsSection() { export function ReportedPaymentsSection() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const { t } = useTranslation('payments')
const { data } = useReportedPayments() const { data } = useReportedPayments()
const [viewing, setViewing] = useState<ReportedPaymentDto | null>(null) const [viewing, setViewing] = useState<ReportedPaymentDto | null>(null)
const reports = data?.data ?? [] const reports = data?.data ?? []
@@ -26,7 +28,7 @@ export function ReportedPaymentsSection() {
return ( return (
<section aria-labelledby="to-verify-title" className="mt-5 space-y-3"> <section aria-labelledby="to-verify-title" className="mt-5 space-y-3">
<h2 id="to-verify-title" className="flex items-center gap-2 text-base font-bold text-primary"> <h2 id="to-verify-title" className="flex items-center gap-2 text-base font-bold text-primary">
Pagos para verificar {t('reported.title')}
<span className="rounded-full bg-accent px-2 py-0.5 text-xs font-semibold text-on-accent">{reports.length}</span> <span className="rounded-full bg-accent px-2 py-0.5 text-xs font-semibold text-on-accent">{reports.length}</span>
</h2> </h2>
<ul className="space-y-3"> <ul className="space-y-3">

View File

@@ -1,5 +1,6 @@
import type { PaymentDto } from '@gruperly/shared' import type { PaymentDto } from '@gruperly/shared'
import type { BadgeVariant } from '../../components/ui' import type { BadgeVariant } from '../../components/ui'
import { i18n } from '../../i18n/instance'
export const PAYMENT_STATUS_BADGE: Record<PaymentDto['status'], BadgeVariant> = { export const PAYMENT_STATUS_BADGE: Record<PaymentDto['status'], BadgeVariant> = {
PENDING: 'neutral', PENDING: 'neutral',
@@ -14,9 +15,9 @@ export function paymentPeriodLabel(payment: PaymentDto): string {
export function paymentDateLabel(payment: PaymentDto): string { export function paymentDateLabel(payment: PaymentDto): string {
if (payment.status === 'PAID' && payment.paidAt) { if (payment.status === 'PAID' && payment.paidAt) {
return `Cobrada el ${formatDay(payment.paidAt)}` return i18n.t('payments:row.paidOn', { date: formatDay(payment.paidAt) })
} }
return `Vence el ${formatDay(payment.dueDate)}` return i18n.t('payments:row.dueOn', { date: formatDay(payment.dueDate) })
} }
/* Fechas sin hora: el vencimiento es un día, no un instante. */ /* Fechas sin hora: el vencimiento es un día, no un instante. */
@@ -24,7 +25,7 @@ function formatDay(iso: string): string {
const date = new Date(iso) const date = new Date(iso)
const today = new Date() const today = new Date()
const sameYear = date.getFullYear() === today.getFullYear() const sameYear = date.getFullYear() === today.getFullYear()
return date.toLocaleDateString('es-MX', { return date.toLocaleDateString(i18n.language, {
day: 'numeric', day: 'numeric',
month: 'short', month: 'short',
...(sameYear ? {} : { year: 'numeric' }), ...(sameYear ? {} : { year: 'numeric' }),

View File

@@ -13,6 +13,7 @@ import type analytics from './locales/es-AR/analytics.json'
import type attention from './locales/es-AR/attention.json' import type attention from './locales/es-AR/attention.json'
import type attendeeDetail from './locales/es-AR/attendeeDetail.json' import type attendeeDetail from './locales/es-AR/attendeeDetail.json'
import type classAttendance from './locales/es-AR/classAttendance.json' import type classAttendance from './locales/es-AR/classAttendance.json'
import type payments from './locales/es-AR/payments.json'
import type validation from './locales/es-AR/validation.json' import type validation from './locales/es-AR/validation.json'
// es-AR es la fuente: una clave que no exista ahí rompe el typecheck. // es-AR es la fuente: una clave que no exista ahí rompe el typecheck.
@@ -27,6 +28,7 @@ declare module 'i18next' {
pwa: typeof pwa pwa: typeof pwa
settings: typeof settings settings: typeof settings
validation: typeof validation validation: typeof validation
'payments': typeof payments
'classAttendance': typeof classAttendance 'classAttendance': typeof classAttendance
'attendeeDetail': typeof attendeeDetail 'attendeeDetail': typeof attendeeDetail
'attention': typeof attention 'attention': typeof attention

View File

@@ -0,0 +1,64 @@
{
"title": "Payments",
"subtitle": "Track your groups' payments.",
"statusFilterLabel": "Filter by status",
"filters": {
"ALL": "All",
"PENDING": "Pending",
"PAID": "Paid",
"OVERDUE": "Overdue",
"CANCELLED": "Cancelled"
},
"loading": "Loading payments",
"loadError": "We couldn't load your payments.",
"empty": {
"title": "No payments yet",
"description": "Open a group's page and create the payment links for the period."
},
"prev": "Previous",
"next": "Next",
"pageInfo": "Page {{page}} of {{pages}} · {{count}} payments",
"updating": "Updating…",
"row": {
"paidOn": "Paid on {{date}}",
"dueOn": "Due {{date}}",
"copied": "Copied",
"copyLink": "Copy link",
"noLink": "No link",
"generate": "Create link"
},
"groupFilter": {
"label": "Group: {{name}}",
"all": "All groups",
"groups": "Groups",
"choose": "Choose group",
"create": "Create a new group",
"groupCount_one": "{{count}} group",
"groupCount_other": "{{count}} groups",
"members_one": "{{count}} member",
"members_other": "{{count}} members",
"perClass": "{{price}}/class",
"perMonth": "{{price}}/month",
"unpaid_one": "{{count}} pending payment",
"unpaid_other": "{{count}} pending payments"
},
"reported": {
"title": "Payments to verify",
"receipt": "Receipt",
"loadingReceipt": "Loading receipt",
"receiptError": "We couldn't open the receipt.",
"receiptAlt": "Receipt: {{name}}",
"openTab": "Open in a new tab",
"confirmed": "Confirmed: {{name}} · {{amount}}",
"rejected": "Declined: {{name}} · {{amount}}",
"undo": "Undo",
"viewReceipt": "View receipt",
"receiptDeleted": "Receipt deleted",
"studentNote": "Student's note",
"reason": "Reason (optional, the student will see it)",
"rejectPayment": "Decline payment",
"reject": "Decline",
"confirm": "Confirm",
"error": "We couldn't save the change. Please try again."
}
}

View File

@@ -0,0 +1,64 @@
{
"title": "Cobros",
"subtitle": "Sigue los pagos de tus grupos.",
"statusFilterLabel": "Filtrar por estado",
"filters": {
"ALL": "Todos",
"PENDING": "Pendientes",
"PAID": "Pagados",
"OVERDUE": "Vencidos",
"CANCELLED": "Anulados"
},
"loading": "Cargando cobros",
"loadError": "No pudimos cargar tus cobros.",
"empty": {
"title": "Todavía no hay cobros",
"description": "Entra a un grupo, abre la ficha y crea los links de cobro del período."
},
"prev": "Anteriores",
"next": "Siguientes",
"pageInfo": "Página {{page}} de {{pages}} · {{count}} cobros",
"updating": "Actualizando…",
"row": {
"paidOn": "Cobrada el {{date}}",
"dueOn": "Vence el {{date}}",
"copied": "Copiado",
"copyLink": "Copiar link",
"noLink": "Sin link",
"generate": "Generar link"
},
"groupFilter": {
"label": "Grupo: {{name}}",
"all": "Todos los grupos",
"groups": "Grupos",
"choose": "Elegir grupo",
"create": "Crear un grupo nuevo",
"groupCount_one": "{{count}} grupo",
"groupCount_other": "{{count}} grupos",
"members_one": "{{count}} miembro",
"members_other": "{{count}} miembros",
"perClass": "{{price}}/clase",
"perMonth": "{{price}}/mes",
"unpaid_one": "{{count}} cobro pendiente",
"unpaid_other": "{{count}} cobros pendientes"
},
"reported": {
"title": "Pagos para verificar",
"receipt": "Comprobante",
"loadingReceipt": "Cargando comprobante",
"receiptError": "No pudimos abrir el comprobante.",
"receiptAlt": "Comprobante: {{name}}",
"openTab": "Abrir en otra pestaña",
"confirmed": "Confirmado: {{name}} · {{amount}}",
"rejected": "Rechazado: {{name}} · {{amount}}",
"undo": "Deshacer",
"viewReceipt": "Ver comprobante",
"receiptDeleted": "Comprobante eliminado",
"studentNote": "Nota del alumno",
"reason": "Motivo (opcional, lo ve el alumno)",
"rejectPayment": "Rechazar pago",
"reject": "Rechazar",
"confirm": "Confirmar",
"error": "No pudimos guardar el cambio. Inténtalo de nuevo."
}
}

View File

@@ -0,0 +1,64 @@
{
"title": "Cobros",
"subtitle": "Seguí los pagos de tus grupos.",
"statusFilterLabel": "Filtrar por estado",
"filters": {
"ALL": "Todos",
"PENDING": "Pendientes",
"PAID": "Pagados",
"OVERDUE": "Vencidos",
"CANCELLED": "Anulados"
},
"loading": "Cargando cobros",
"loadError": "No pudimos cargar tus cobros.",
"empty": {
"title": "Todavía no hay cobros",
"description": "Entrá a un grupo, abrí la ficha y creá los links de cobro del período."
},
"prev": "Anteriores",
"next": "Siguientes",
"pageInfo": "Página {{page}} de {{pages}} · {{count}} cobros",
"updating": "Actualizando…",
"row": {
"paidOn": "Cobrada el {{date}}",
"dueOn": "Vence el {{date}}",
"copied": "Copiado",
"copyLink": "Copiar link",
"noLink": "Sin link",
"generate": "Generar link"
},
"groupFilter": {
"label": "Grupo: {{name}}",
"all": "Todos los grupos",
"groups": "Grupos",
"choose": "Elegir grupo",
"create": "Crear un grupo nuevo",
"groupCount_one": "{{count}} grupo",
"groupCount_other": "{{count}} grupos",
"members_one": "{{count}} miembro",
"members_other": "{{count}} miembros",
"perClass": "{{price}}/clase",
"perMonth": "{{price}}/mes",
"unpaid_one": "{{count}} cobro pendiente",
"unpaid_other": "{{count}} cobros pendientes"
},
"reported": {
"title": "Pagos para verificar",
"receipt": "Comprobante",
"loadingReceipt": "Cargando comprobante",
"receiptError": "No pudimos abrir el comprobante.",
"receiptAlt": "Comprobante: {{name}}",
"openTab": "Abrir en otra pestaña",
"confirmed": "Confirmado: {{name}} · {{amount}}",
"rejected": "Rechazado: {{name}} · {{amount}}",
"undo": "Deshacer",
"viewReceipt": "Ver comprobante",
"receiptDeleted": "Comprobante eliminado",
"studentNote": "Nota del alumno",
"reason": "Motivo (opcional, lo ve el alumno)",
"rejectPayment": "Rechazar pago",
"reject": "Rechazar",
"confirm": "Confirmar",
"error": "No pudimos guardar el cambio. Probá de nuevo."
}
}

View File

@@ -0,0 +1,64 @@
{
"title": "Cobranças",
"subtitle": "Acompanhe os pagamentos dos seus grupos.",
"statusFilterLabel": "Filtrar por status",
"filters": {
"ALL": "Todas",
"PENDING": "Pendentes",
"PAID": "Pagas",
"OVERDUE": "Vencidas",
"CANCELLED": "Canceladas"
},
"loading": "Carregando cobranças",
"loadError": "Não conseguimos carregar suas cobranças.",
"empty": {
"title": "Ainda não há cobranças",
"description": "Entre em um grupo, abra a página dele e crie os links de cobrança do período."
},
"prev": "Anteriores",
"next": "Próximas",
"pageInfo": "Página {{page}} de {{pages}} · {{count}} cobranças",
"updating": "Atualizando…",
"row": {
"paidOn": "Paga em {{date}}",
"dueOn": "Vence em {{date}}",
"copied": "Copiado",
"copyLink": "Copiar link",
"noLink": "Sem link",
"generate": "Gerar link"
},
"groupFilter": {
"label": "Grupo: {{name}}",
"all": "Todos os grupos",
"groups": "Grupos",
"choose": "Escolher grupo",
"create": "Criar um novo grupo",
"groupCount_one": "{{count}} grupo",
"groupCount_other": "{{count}} grupos",
"members_one": "{{count}} membro",
"members_other": "{{count}} membros",
"perClass": "{{price}}/aula",
"perMonth": "{{price}}/mês",
"unpaid_one": "{{count}} cobrança pendente",
"unpaid_other": "{{count}} cobranças pendentes"
},
"reported": {
"title": "Pagamentos para verificar",
"receipt": "Comprovante",
"loadingReceipt": "Carregando comprovante",
"receiptError": "Não conseguimos abrir o comprovante.",
"receiptAlt": "Comprovante: {{name}}",
"openTab": "Abrir em outra aba",
"confirmed": "Confirmado: {{name}} · {{amount}}",
"rejected": "Recusado: {{name}} · {{amount}}",
"undo": "Desfazer",
"viewReceipt": "Ver comprovante",
"receiptDeleted": "Comprovante excluído",
"studentNote": "Observação do aluno",
"reason": "Motivo (opcional, o aluno vai ver)",
"rejectPayment": "Recusar pagamento",
"reject": "Recusar",
"confirm": "Confirmar",
"error": "Não conseguimos salvar a alteração. Tente novamente."
}
}