development #14

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

View File

@@ -84,11 +84,20 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
5. Editar contacto/notas escribe en la persona (cambia en todos sus grupos; choque de teléfono → `409 person_phone_taken`). Quitar la última membresía borra también a la persona.
6. El límite del plan cuenta **personas** con al menos una membresía `ACTIVE`; `canAddAttendees(owner, n)` recibe las personas nuevas (`countsAsNewStudent`).
7. Los DTOs de attendee siguen planos (`toAttendeeDto` aplana `person` y suma `personId`); para selects sueltos usá `attendeeWithPerson` / `flattenPerson` de `attendees/lib/helpers.ts`. El detalle trae `otherGroups`.
- **Multi idioma (`apps/web/src/i18n/`)**: i18next + react-i18next. Idiomas: `es-AR` (rioplatense, voseo; AR y UY), `es-419` (tuteo), `pt-BR` y `en`; la lista vive en `SUPPORTED_LOCALES` (`packages/shared/src/schemas/locale.ts`) y `resolveLocale` mapea los idiomas del dispositivo (cualquier otro `es-*` → `es-419`, cualquier `pt-*` → `pt-BR`, lo no soportado → `en`). Ojo con esto:
1. **`es-AR` es la fuente**: `i18next.d.ts` tipa las claves con sus JSON, así que una clave que no exista ahí rompe el typecheck. `test/i18n-keys.test.ts` exige las mismas claves (salvo sufijos de plural) y variables en los 4 idiomas. Un namespace nuevo = un JSON por idioma + `NAMESPACES` (`instance.ts`) + `i18next.d.ts`.
2. La preferencia es `'system' | AppLocale` en `localStorage['locale']`; para el profe también en `users.locale` (Better Auth `additionalFields`, validado con `appLocaleSchema`; `null` = idioma del dispositivo). `LocaleProfileSync` aplica el del perfil al iniciar sesión; `LanguageCard` lo guarda con `authClient.updateUser`. La app de alumnos solo usa `localStorage`.
3. `main.tsx` carga el idioma (más `en` de fallback) **antes** del primer render; los JSON se cargan lazy por `import.meta.glob` (solo existe en Vite: en `bun test` el preload `test/setup.ts` carga `es-AR` del disco, por eso los tests asertan el copy rioplatense).
4. Un componente que pinta texto traducido llama `useTranslation`, aunque el texto salga de un helper (`weekDayLabel`, `paymentStatusLabel`, `copy.ts` con `i18n.t`): es lo que lo re-renderiza al cambiar de idioma.
5. Fechas y nombres de días/meses van en el idioma de la UI (`useIntlLocale()` / `i18n.language`), **nunca** con `'es-AR'` fijo. Montos y teléfonos **no**: `formatPrice`/`formatPhoneDisplay` siguen al **país** (`lib/region.ts`).
6. Validación: los esquemas (shared y web) llevan **claves** (`'group.nameMin'`) en vez de texto; se pintan con `<FieldError message={errors.x?.message} />` (traduce contra el namespace `validation`). `installZodErrorMap` cubre los mensajes por defecto de Zod.
7. Errores de la API: `errorMessage(error, fallback)` traduce el `code` del Problem Details (namespace `errors`, `codes.*`; los de Better Auth en `auth.*`); los `params` del problema (`limit`, `feature`, `max`, `capacity`) eligen variante y plural. Con la UI en español cae al `detail` del backend; si no, al `fallback`. Un error nuevo del backend que la UI muestre tiene que llevar `code` y su traducción.
8. Mails y WhatsApp todavía salen solo en español (etapa 2: usar `users.locale`).
- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
## Convenciones repo-específicas
- **Frontend en español**: copy de UI, comentarios y textos en español.
- **Copy de UI traducido**: ningún texto visible va literal en JSX; va en `apps/web/src/i18n/locales/es-AR/<namespace>.json` (fuente, en rioplatense) y en el mismo cambio en `es-419`, `pt-BR` y `en` (ver gotcha **Multi idioma**). Los comentarios del frontend siguen en español. Hay features todavía sin migrar con copy literal en español: al tocarlas, migralas.
- **Paths de rutas en inglés**: aunque el copy esté en español, los segmentos de URL van siempre en inglés, tanto en la web (nombres de archivo en `apps/web/src/routes/`, `createFileRoute`, `to=`/`navigate`) como en la API y en los links que arma el backend (p. ej. `/student/payments`, no `/alumno/pagos`; `/access`, no `/acceso`).
- **Base de datos**: todas las tablas y columnas físicas usan **snake_case**. Los modelos declaran `@@map` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`) y todo campo Prisma camelCase que cree una columna debe declarar `@map("nombre_campo")` (p. ej. `createdAt @map("created_at")`). Al agregar un modelo o campo nuevo, incluir siempre el mapping correspondiente sin cambiar la API camelCase de Prisma Client.
- **API** responde errores en **Problem Details RFC 7807** (`application/problem+json`) y resultados como `{ data, pagination }`; los "use cases" devuelven `Result` y nunca lanzan excepciones de dominio.

View File

@@ -0,0 +1 @@
ALTER TABLE "users" ADD COLUMN "locale" TEXT;

View File

@@ -8,6 +8,8 @@ model User {
image String?
onboardingCompleted Boolean @default(false) @map("onboarding_completed")
country String? @map("country_code")
// UI language the person chose (es-AR, es-419, pt-BR, en); null follows the device.
locale String? @map("locale")
// When the professor chose Free or Pro in the onboarding (mandatory step).
planSelectedAt DateTime? @map("plan_selected_at")
// Bank transfer details shown to students when they report a payment.

View File

@@ -21,6 +21,7 @@ export function conflictProblem(params: {
detail: string;
code?: string;
instance?: string;
params?: ProblemDetails['params'];
}): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/conflict`,
@@ -29,6 +30,7 @@ export function conflictProblem(params: {
detail: params.detail,
instance: params.instance,
code: params.code,
...(params.params ? { params: params.params } : {}),
};
}
@@ -186,6 +188,7 @@ export function capacityReachedProblem(capacity: number | null): ProblemDetails
? `El grupo alcanzó su cupo máximo de ${capacity} miembros.`
: 'El grupo alcanzó su cupo máximo de miembros.',
code: 'group_capacity_reached',
...(capacity ? { params: { capacity } } : {}),
});
}
@@ -216,13 +219,18 @@ export function noAttendeesToBillProblem(): ProblemDetails {
code: 'no_attendees_to_bill',
});
}
function paymentRequiredProblem(params: { detail: string; code: string }): ProblemDetails {
function paymentRequiredProblem(params: {
detail: string;
code: string;
params?: ProblemDetails['params'];
}): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/plan`,
title: 'Payment Required',
status: 402,
detail: params.detail,
code: params.code,
...(params.params ? { params: params.params } : {}),
};
}
@@ -236,6 +244,7 @@ export function planLimitReachedProblem(limit: PlanLimitKind, max: number): Prob
? `El plan Free permite hasta ${max} ${max === 1 ? 'grupo' : 'grupos'}. Pasate a Pro para crear más.`
: `El plan Free permite hasta ${max} alumnos activos. Pasate a Pro para sumar más.`,
code: 'plan_limit_reached',
params: { limit, max },
});
}
@@ -247,6 +256,7 @@ export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutom
? 'Cobrar con Mercado Pago está disponible en el plan Pro.'
: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
code: 'plan_feature_required',
params: { feature },
});
}

View File

@@ -1,4 +1,5 @@
import { passkey } from '@better-auth/passkey';
import { appLocaleSchema } from '@gruperly/shared';
import { betterAuth } from 'better-auth';
import { prismaAdapter } from 'better-auth/adapters/prisma';
import { organization } from 'better-auth/plugins/organization';
@@ -11,6 +12,18 @@ export const auth = betterAuth({
database: prismaAdapter(getPrismaClient(), {
provider: 'postgresql',
}),
user: {
additionalFields: {
// UI language chosen in Ajustes; null means "follow the device". The web
// saves it with updateUser and reads it back from the session.
locale: {
type: 'string',
required: false,
input: true,
validator: { input: appLocaleSchema.nullable() },
},
},
},
emailAndPassword: {
enabled: true,
minPasswordLength: 8,

3
apps/web/bunfig.toml Normal file
View File

@@ -0,0 +1,3 @@
[test]
# Inicializa i18n en es-AR: los tests asertan el copy en español.
preload = ["./test/setup.ts"]

View File

@@ -21,10 +21,12 @@
"@tanstack/react-router": "^1.170.38",
"better-auth": "1.7.2",
"clsx": "^2.1.1",
"i18next": "^26.5.11",
"lucide-react": "^1.34.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-hook-form": "^7.54.0",
"react-i18next": "^17.1.9",
"tailwind-merge": "^3.6.0",
"zod": "3.24.2"
},

View File

@@ -1,15 +1,17 @@
import { Link, useLocation } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { cn } from '../../lib/utils'
import { NavBadge } from './NavBadge'
import { isNavItemActive, NAV_ITEMS } from './nav-items'
export function BottomNav() {
const location = useLocation()
const { t } = useTranslation('layout')
return (
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur lg:hidden">
<div className="mx-auto grid max-w-md grid-cols-4">
{NAV_ITEMS.map(({ label, to, icon: Icon, badge }) => {
{NAV_ITEMS.map(({ labelKey, to, icon: Icon, badge }) => {
const isActive = isNavItemActive(location.pathname, to)
return (
<Link
@@ -32,7 +34,7 @@ export function BottomNav() {
<Icon className="size-5" strokeWidth={isActive ? 2.25 : 2} />
{badge ? <NavBadge kind={badge} className="absolute -right-2.5 -top-1.5" /> : null}
</span>
<span className="leading-none">{label}</span>
<span className="leading-none">{t(labelKey)}</span>
</Link>
)
})}

View File

@@ -1,52 +1,55 @@
import { Link, useLocation } from '@tanstack/react-router'
import { ChevronRight } from 'lucide-react'
import { useTranslation } from 'react-i18next'
type Crumb = { label: string; to?: string }
type CrumbKey = 'home' | 'groups' | 'payments' | 'settings' | 'security' | 'profile'
type Crumb = { label: CrumbKey; to?: string }
const BREADCRUMBS: Record<string, Crumb[]> = {
'/': [{ label: 'Inicio' }],
'/': [{ label: 'home' }],
'/groups': [
{ label: 'Inicio', to: '/' },
{ label: 'Grupos' },
{ label: 'home', to: '/' },
{ label: 'groups' },
],
'/payments': [
{ label: 'Inicio', to: '/' },
{ label: 'Cobros' },
{ label: 'home', to: '/' },
{ label: 'payments' },
],
'/settings': [
{ label: 'Inicio', to: '/' },
{ label: 'Ajustes' },
{ label: 'home', to: '/' },
{ label: 'settings' },
],
'/security': [
{ label: 'Inicio', to: '/' },
{ label: 'Ajustes', to: '/settings' },
{ label: 'Seguridad' },
{ label: 'home', to: '/' },
{ label: 'settings', to: '/settings' },
{ label: 'security' },
],
'/profile': [
{ label: 'Inicio', to: '/' },
{ label: 'Mi perfil' },
{ label: 'home', to: '/' },
{ label: 'profile' },
],
}
export function Breadcrumb() {
const location = useLocation()
const crumbs = BREADCRUMBS[location.pathname] ?? [{ label: 'Inicio' }]
const { t } = useTranslation('layout')
const crumbs = BREADCRUMBS[location.pathname] ?? [{ label: 'home' }]
return (
<nav aria-label="Breadcrumb" className="hidden items-center gap-1.5 text-sm lg:flex">
<nav aria-label={t('breadcrumb')} className="hidden items-center gap-1.5 text-sm lg:flex">
{crumbs.map((crumb, i) => {
const isLast = i === crumbs.length - 1
return (
<span key={crumb.label} className="flex items-center gap-1.5">
{i > 0 ? <ChevronRight className="size-3.5 text-foreground/40" /> : null}
{isLast ? (
<span className="font-medium text-primary">{crumb.label}</span>
<span className="font-medium text-primary">{t(`nav.${crumb.label}`)}</span>
) : (
<Link
to={crumb.to!}
className="text-foreground/50 transition-colors hover:text-primary"
>
{crumb.label}
{t(`nav.${crumb.label}`)}
</Link>
)}
</span>

View File

@@ -1,10 +1,12 @@
import { Link } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { Logo } from '../brand'
import { Breadcrumb } from './Breadcrumb'
import { ThemeToggle } from './ThemeToggle'
import { UserMenu } from './UserMenu'
export function Header() {
const { t } = useTranslation('layout')
return (
<header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur">
<div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between px-4 lg:px-6">
@@ -12,7 +14,7 @@ export function Header() {
{/* `Link` and not `<a>`: on mobile the logo is the only way back to the
home screen and an anchor would reload the whole document, losing
the in-memory state (React Query cache, install event). */}
<Link to="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio">
<Link to="/" className="flex items-center lg:hidden" aria-label={t('homeLink')}>
<Logo className="h-8" />
</Link>
<Breadcrumb />

View File

@@ -1,10 +1,12 @@
import { useReportedPaymentsCount } from '../../features/payments/reportedPayments'
import { useTranslation } from 'react-i18next'
import { cn } from '../../lib/utils'
/* Counter of a nav item: today only "Pagos para verificar" on Cobros. The
number is in the accessible name too (sr-only), not only in the dot. */
export function NavBadge({ kind, className }: { kind: 'reported-payments'; className?: string }) {
const count = useReportedPaymentsCount()
const { t } = useTranslation('layout')
if (kind !== 'reported-payments' || count === 0) return null
return (
<span
@@ -13,8 +15,8 @@ export function NavBadge({ kind, className }: { kind: 'reported-payments'; class
className,
)}
>
{count > 99 ? '99+' : count}
<span className="sr-only"> pagos para verificar</span>
<span aria-hidden="true">{count > 99 ? '99+' : count}</span>
<span className="sr-only">{t('reportedPayments', { count })}</span>
</span>
)
}

View File

@@ -1,7 +1,10 @@
import { useTranslation } from 'react-i18next'
export function PublicFooter() {
const { t } = useTranslation('layout')
return (
<footer className="border-t border-border px-4 py-4 text-center text-xs text-foreground/40">
Gruperly — Gestión sencilla de cobros y grupos
{t('publicFooter')}
</footer>
)
}

View File

@@ -1,4 +1,5 @@
import { Link, useLocation } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { cn } from '../../lib/utils'
import { Logo } from '../brand'
import { NavBadge } from './NavBadge'
@@ -6,6 +7,7 @@ import { isNavItemActive, NAV_ITEMS } from './nav-items'
export function Sidebar({ immersive = false }: { immersive?: boolean }) {
const location = useLocation()
const { t } = useTranslation('layout')
return (
// Without the global header there's nothing to clear above: the sidebar
@@ -19,12 +21,12 @@ export function Sidebar({ immersive = false }: { immersive?: boolean }) {
>
{/* `Link` and not `<a>`: an anchor would reload the document and lose the
in-memory state (React Query cache, install event). */}
<Link to="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio">
<Link to="/" className="mb-8 flex items-center px-1" aria-label={t('homeLink')}>
<Logo className="h-10" />
</Link>
<nav className="flex flex-col gap-1">
{NAV_ITEMS.map(({ label, to, icon: Icon, badge }) => {
{NAV_ITEMS.map(({ labelKey, to, icon: Icon, badge }) => {
const isActive = isNavItemActive(location.pathname, to)
return (
<Link
@@ -39,7 +41,7 @@ export function Sidebar({ immersive = false }: { immersive?: boolean }) {
)}
>
<Icon className="size-5" strokeWidth={isActive ? 2.2 : 2} />
{label}
{t(labelKey)}
{badge ? <NavBadge kind={badge} className="ml-auto" /> : null}
</Link>
)

View File

@@ -1,14 +1,16 @@
import { Moon, Sun } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { useTheme } from '../../context/ThemeProvider'
export function ThemeToggle() {
const { isDark, setTheme } = useTheme()
const { t } = useTranslation('layout')
return (
<button
type="button"
onClick={() => setTheme(isDark ? 'light' : 'dark')}
aria-label={isDark ? 'Cambiar a tema claro' : 'Cambiar a tema oscuro'}
aria-label={isDark ? t('theme.toLight') : t('theme.toDark')}
className="flex size-9 items-center justify-center rounded-full border border-border text-foreground/70 transition-colors hover:bg-primary-soft hover:text-primary"
>
{isDark ? <Sun className="size-4" /> : <Moon className="size-4" />}

View File

@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { Link, useNavigate } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { ChevronDown, LogOut, Settings, ShieldCheck, UserRound, X } from 'lucide-react'
import { cn } from '../../lib/utils'
import { signOut } from '../../lib/auth-client'
@@ -18,6 +19,7 @@ export function UserMenu() {
const [open, setOpen] = useState(false)
const ref = useRef<HTMLDivElement>(null)
const navigate = useNavigate()
const { t } = useTranslation(['layout', 'common'])
// Solo el equipo de Gruperly ve el acceso al backoffice.
const isAdmin = useAdminAccess(!!user).data?.isAdmin ?? false
@@ -65,7 +67,7 @@ export function UserMenu() {
>
<Avatar name={user?.name} src={user?.image ?? undefined} className="size-8 lg:size-9" />
<span className="hidden max-w-40 flex-col items-start leading-tight lg:flex">
<span className="truncate text-sm font-medium text-primary">{user?.name ?? 'Usuario'}</span>
<span className="truncate text-sm font-medium text-primary">{user?.name ?? t('common:user.fallbackName')}</span>
</span>
<ChevronDown
className={cn(
@@ -88,7 +90,7 @@ export function UserMenu() {
<button
type="button"
onClick={() => setOpen(false)}
aria-label="Cerrar menú"
aria-label={t('userMenu.close')}
className="absolute right-4 top-4 z-20 rounded-full bg-surface/90 p-2 text-foreground/70 shadow-md backdrop-blur transition-colors hover:bg-surface"
>
<X className="size-5" />
@@ -102,7 +104,7 @@ export function UserMenu() {
/>
<div>
<p className="text-base font-semibold text-primary">
{user?.name ?? 'Usuario'}
{user?.name ?? t('common:user.fallbackName')}
</p>
<p className="text-sm text-foreground/50">{user?.email}</p>
</div>
@@ -116,7 +118,7 @@ export function UserMenu() {
className={cn(itemClass, 'py-3.5')}
>
<UserRound className="size-5 text-foreground/60" />
Mi perfil
{t('userMenu.profile')}
</Link>
<Link
role="menuitem"
@@ -125,7 +127,7 @@ export function UserMenu() {
className={cn(itemClass, 'py-3.5')}
>
<Settings className="size-5 text-foreground/60" />
Ajustes
{t('userMenu.settings')}
</Link>
{isAdmin ? (
<Link
@@ -135,7 +137,7 @@ export function UserMenu() {
className={cn(itemClass, 'py-3.5')}
>
<ShieldCheck className="size-5 text-foreground/60" />
Backoffice
{t('userMenu.admin')}
</Link>
) : null}
</div>
@@ -150,7 +152,7 @@ export function UserMenu() {
)}
>
<LogOut className="size-5 text-foreground/60" />
Cerrar sesión
{t('userMenu.signOut')}
</button>
</div>
</div>
@@ -164,28 +166,28 @@ export function UserMenu() {
className="absolute right-0 top-full z-50 mt-2 w-60 rounded-xl border border-border bg-surface p-1.5 shadow-lg"
>
<div className="px-3 py-2">
<p className="truncate text-sm font-semibold text-primary">{user?.name ?? 'Usuario'}</p>
<p className="truncate text-sm font-semibold text-primary">{user?.name ?? t('common:user.fallbackName')}</p>
<p className="truncate text-xs text-foreground/50">{user?.email}</p>
</div>
<div className="mx-3 my-1 h-px bg-border" />
<Link role="menuitem" to="/profile" onClick={() => setOpen(false)} className={itemClass}>
<UserRound className="size-4 text-foreground/60" />
Mi perfil
{t('userMenu.profile')}
</Link>
<Link role="menuitem" to="/settings" onClick={() => setOpen(false)} className={itemClass}>
<Settings className="size-4 text-foreground/60" />
Ajustes
{t('userMenu.settings')}
</Link>
{isAdmin ? (
<Link role="menuitem" to="/admin" onClick={() => setOpen(false)} className={itemClass}>
<ShieldCheck className="size-4 text-foreground/60" />
Backoffice
{t('userMenu.admin')}
</Link>
) : null}
<div className="mx-3 my-1 h-px bg-border" />
<button type="button" role="menuitem" onClick={handleSignOut} className={itemClass}>
<LogOut className="size-4 text-foreground/60" />
Cerrar sesión
{t('userMenu.signOut')}
</button>
</div>
) : null}

View File

@@ -1,7 +1,8 @@
import { Home, Users, Wallet, Settings, type LucideIcon } from 'lucide-react'
export type NavItem = {
label: string
/** Clave en el namespace `layout` (`nav.*`). */
labelKey: 'nav.home' | 'nav.groups' | 'nav.payments' | 'nav.settings'
to: string
icon: LucideIcon
/** Counter shown on the item (see NavBadge). */
@@ -9,10 +10,10 @@ export type NavItem = {
}
export const NAV_ITEMS: NavItem[] = [
{ label: 'Inicio', to: '/', icon: Home },
{ label: 'Grupos', to: '/groups', icon: Users },
{ label: 'Cobros', to: '/payments', icon: Wallet, badge: 'reported-payments' },
{ label: 'Ajustes', to: '/settings', icon: Settings },
{ labelKey: 'nav.home', to: '/', icon: Home },
{ labelKey: 'nav.groups', to: '/groups', icon: Users },
{ labelKey: 'nav.payments', to: '/payments', icon: Wallet, badge: 'reported-payments' },
{ labelKey: 'nav.settings', to: '/settings', icon: Settings },
]
/** A section stays active within its subroutes: on `/groups/abc` the active

View File

@@ -0,0 +1,19 @@
import { useTranslation } from 'react-i18next'
import { validationMessage } from '../../i18n'
import { cn } from '../../lib/utils'
type FieldErrorProps = {
/** El `message` del error del form: una clave de validación o un texto. */
message?: string
className?: string
}
/** Error de un campo, traducido. Los esquemas llevan claves (`email.invalid`)
* y acá se pasan al idioma de la UI. */
export function FieldError({ message, className }: FieldErrorProps) {
// Suscribe el componente al cambio de idioma.
useTranslation('validation')
const text = validationMessage(message)
if (!text) return null
return <p className={cn('mt-1 text-sm text-danger', className)}>{text}</p>
}

View File

@@ -9,3 +9,4 @@ export { Tooltip, type TooltipProps } from './tooltip'
export { Switch, type SwitchProps } from './switch'
export { Sheet, type SheetProps } from './sheet'
export { FieldError } from './field-error'

View File

@@ -1,6 +1,7 @@
import { useEffect, type ReactNode } from 'react';
import { X } from 'lucide-react';
import { cn } from '../../lib/utils';
import { i18n } from '../../i18n/instance';
export type ModalProps = {
isOpen: boolean;
@@ -78,7 +79,7 @@ export function Modal({
type="button"
onClick={onClose}
className="shrink-0 -mr-2 -mt-2 p-2 rounded-xl text-foreground/40 hover:text-foreground hover:bg-primary-soft transition-colors"
aria-label="Cerrar modal"
aria-label={i18n.t('actions.close')}
>
<X className="size-5" />
</button>

View File

@@ -1,6 +1,7 @@
import { useEffect, useId, useRef, type ReactNode } from 'react'
import { X } from 'lucide-react'
import { cn } from '../../lib/utils'
import { i18n } from '../../i18n/instance'
export type SheetProps = {
isOpen: boolean
@@ -72,7 +73,7 @@ export function Sheet({ isOpen, onClose, title, description, children, className
type="button"
onClick={onClose}
className="-mr-2 -mt-2 flex size-11 shrink-0 items-center justify-center rounded-xl text-foreground hover:bg-primary-soft hover:text-primary"
aria-label="Cerrar"
aria-label={i18n.t('actions.close')}
>
<X className="size-5" />
</button>

View File

@@ -8,6 +8,7 @@ import {
} from 'react';
import { AlertCircle, CheckCircle2, Info, X } from 'lucide-react';
import { cn } from '../../lib/utils';
import { i18n } from '../../i18n/instance';
export type ToastType = 'success' | 'error' | 'info';
@@ -126,7 +127,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
type="button"
onClick={() => removeToast(toast.id)}
className="shrink-0 -mr-1 -mt-1 p-1 rounded-lg text-foreground/40 hover:text-foreground hover:bg-primary-soft transition-colors"
aria-label="Cerrar notificación"
aria-label={i18n.t('toast.close')}
>
<X className="size-4" />
</button>

View File

@@ -1,10 +1,11 @@
import type { AttendeePaymentSummary } from '@gruperly/shared'
import { UpdateAttendeeSchema } from '@gruperly/shared'
import { validationMessage } from '../../i18n/validation'
export function contactEmailError(email: string): string | null {
const result = UpdateAttendeeSchema.safeParse({ email })
if (result.success) return null
return result.error.issues[0]?.message ?? 'Ingresá un email válido'
return validationMessage(result.error.issues[0]?.message ?? 'email.invalid') ?? null
}
export type PaymentPresentation = {

View File

@@ -5,11 +5,13 @@ import { zodResolver } from '@hookform/resolvers/zod'
import { Link, useSearch } from '@tanstack/react-router'
import { Loader2, MailCheck } from 'lucide-react'
import { authClient } from '../../lib/auth-client'
import { Button, Input, Label } from '../../components/ui'
import { Trans, useTranslation } from 'react-i18next'
import { Button, FieldError, Input, Label } from '../../components/ui'
import { errorMessage } from '../../i18n'
import { AuthShell } from './AuthShell'
const schema = z.object({
email: z.string().email('Ingresá un email válido'),
email: z.string().email('email.invalid'),
})
type FormValues = z.infer<typeof schema>
@@ -17,6 +19,7 @@ type FormValues = z.infer<typeof schema>
export function ForgotPasswordPage() {
const { email: initialEmail } = useSearch({ strict: false }) as { email?: string }
const [sentTo, setSentTo] = useState<string | null>(null)
const { t } = useTranslation('auth')
const {
register,
handleSubmit,
@@ -34,7 +37,7 @@ export function ForgotPasswordPage() {
redirectTo: `${window.location.origin}/reset-password`,
})
if (error) {
setError('root', { message: error.message ?? 'No se pudo enviar el email' })
setError('root', { message: errorMessage(error, t('forgot.error')) })
return
}
setSentTo(email)
@@ -42,15 +45,19 @@ export function ForgotPasswordPage() {
if (sentTo) {
return (
<AuthShell title="Revisá tu email">
<AuthShell title={t('forgot.sentTitle')}>
<div className="flex flex-col items-center gap-4 py-2 text-center">
<MailCheck className="size-10 text-success" />
<p className="text-sm text-foreground/60">
Si hay una cuenta con <span className="font-medium text-primary">{sentTo}</span>, te
enviamos un enlace para elegir una nueva contraseña. Vence en 1 hora.
<Trans
t={t}
i18nKey="forgot.sent"
values={{ email: sentTo }}
components={{ strong: <span className="font-medium text-primary" /> }}
/>
</p>
<Link to="/login" className="text-sm font-medium text-accent hover:underline">
Volver a iniciar sesión
{t('backToLogin')}
</Link>
</div>
</AuthShell>
@@ -59,34 +66,34 @@ export function ForgotPasswordPage() {
return (
<AuthShell
title="Recuperar contraseña"
subtitle="Te enviamos un enlace para elegir una nueva"
title={t('forgot.title')}
subtitle={t('forgot.subtitle')}
>
<form onSubmit={onSubmit} className="space-y-4">
<div>
<Label htmlFor="email">Email</Label>
<Label htmlFor="email">{t('email')}</Label>
<Input
id="email"
type="email"
autoComplete="email"
autoFocus
placeholder="vos@ejemplo.com"
placeholder={t('emailPlaceholder')}
invalid={!!errors.email}
{...register('email')}
/>
{errors.email ? <p className="mt-1 text-sm text-danger">{errors.email.message}</p> : null}
<FieldError message={errors.email?.message} />
</div>
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
{isSubmitting ? 'Enviando…' : 'Enviar enlace'}
{isSubmitting ? t('forgot.submitting') : t('forgot.submit')}
</Button>
<p className="text-center text-sm text-foreground/60">
<Link to="/login" className="font-medium text-accent hover:underline">
Volver a iniciar sesión
{t('backToLogin')}
</Link>
</p>
</form>

View File

@@ -4,18 +4,21 @@ import { zodResolver } from '@hookform/resolvers/zod'
import { Link, useNavigate, useSearch } from '@tanstack/react-router'
import { Fingerprint, Loader2 } from 'lucide-react'
import { authClient } from '../../lib/auth-client'
import { Button, Input, Label } from '../../components/ui'
import { useTranslation } from 'react-i18next'
import { Button, FieldError, Input, Label } from '../../components/ui'
import { errorMessage } from '../../i18n'
import { AuthShell } from './AuthShell'
const schema = z.object({
email: z.string().email('Ingresá un email válido'),
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
email: z.string().email('email.invalid'),
password: z.string().min(8, 'password.min'),
})
type FormValues = z.infer<typeof schema>
export function LoginPage() {
const navigate = useNavigate()
const { t } = useTranslation('auth')
const { reset } = useSearch({ strict: false }) as { reset?: 'ok' }
const {
register,
@@ -28,7 +31,7 @@ export function LoginPage() {
const onSubmit = handleSubmit(async ({ email, password }) => {
const { error } = await authClient.signIn.email({ email, password })
if (error) {
setError('root', { message: error.message ?? 'No se pudo iniciar sesión' })
setError('root', { message: errorMessage(error, t('login.error')) })
return
}
navigate({ to: '/' })
@@ -41,37 +44,37 @@ export function LoginPage() {
const handlePasskey = async () => {
const { error, data } = await authClient.signIn.passkey()
if (error) {
setError('root', { message: error.message ?? 'No se pudo autenticar con passkey' })
setError('root', { message: errorMessage(error, t('login.passkeyError')) })
return
}
if (data) navigate({ to: '/' })
}
return (
<AuthShell title="Iniciar sesión" subtitle="Accedé a tus cobros grupales">
<AuthShell title={t('login.title')} subtitle={t('login.subtitle')}>
<div className="space-y-4">
{reset === 'ok' ? (
<p className="rounded-xl bg-success-soft px-4 py-3 text-sm text-success">
Tu contraseña se actualizó. Ingresá con la nueva.
{t('login.resetOk')}
</p>
) : null}
<form onSubmit={onSubmit} className="space-y-4">
<div>
<Label htmlFor="email">Email</Label>
<Label htmlFor="email">{t('email')}</Label>
<Input
id="email"
type="email"
autoComplete="email"
placeholder="vos@ejemplo.com"
placeholder={t('emailPlaceholder')}
invalid={!!errors.email}
{...register('email')}
/>
{errors.email ? <p className="mt-1 text-sm text-danger">{errors.email.message}</p> : null}
<FieldError message={errors.email?.message} />
</div>
<div>
<Label htmlFor="password">Contraseña</Label>
<Label htmlFor="password">{t('password')}</Label>
<Input
id="password"
type="password"
@@ -80,16 +83,14 @@ export function LoginPage() {
invalid={!!errors.password}
{...register('password')}
/>
{errors.password ? (
<p className="mt-1 text-sm text-danger">{errors.password.message}</p>
) : null}
<FieldError message={errors.password?.message} />
<div className="mt-1 text-right">
<Link
to="/forgot-password"
search={{ email: watch('email') || undefined }}
className="text-sm text-accent hover:underline"
>
¿Olvidaste tu contraseña?
{t('login.forgot')}
</Link>
</div>
</div>
@@ -98,30 +99,30 @@ export function LoginPage() {
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
{isSubmitting ? 'Ingresando…' : 'Ingresar'}
{isSubmitting ? t('login.submitting') : t('login.submit')}
</Button>
</form>
<div className="flex items-center gap-3">
<div className="h-px flex-1 bg-border" />
<span className="text-xs uppercase tracking-wide text-foreground/40">o</span>
<span className="text-xs uppercase tracking-wide text-foreground/40">{t('or')}</span>
<div className="h-px flex-1 bg-border" />
</div>
<div className="grid gap-2">
<Button variant="outline" className="w-full" onClick={handleGoogle}>
Continuar con Google
{t('continueWithGoogle')}
</Button>
<Button variant="outline" className="w-full" onClick={handlePasskey}>
<Fingerprint className="size-4" />
Entrar con passkey
{t('login.passkey')}
</Button>
</div>
<p className="text-center text-sm text-foreground/60">
¿No tenés cuenta?{' '}
{t('login.noAccount')}{' '}
<Link to="/signup" className="font-medium text-accent hover:underline">
Registrate
{t('login.signUp')}
</Link>
</p>
</div>

View File

@@ -5,16 +5,18 @@ import { zodResolver } from '@hookform/resolvers/zod'
import { Link, useNavigate, useSearch } from '@tanstack/react-router'
import { Loader2, MailWarning } from 'lucide-react'
import { authClient } from '../../lib/auth-client'
import { Button, Input, Label } from '../../components/ui'
import { useTranslation } from 'react-i18next'
import { Button, FieldError, Input, Label } from '../../components/ui'
import { errorMessage } from '../../i18n'
import { AuthShell } from './AuthShell'
const schema = z
.object({
newPassword: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
newPassword: z.string().min(8, 'password.min'),
confirmPassword: z.string(),
})
.refine((v) => v.newPassword === v.confirmPassword, {
message: 'Las contraseñas no coinciden',
message: 'password.mismatch',
path: ['confirmPassword'],
})
@@ -23,6 +25,7 @@ type FormValues = z.infer<typeof schema>
export function ResetPasswordPage() {
const { token, error } = useSearch({ strict: false }) as { token?: string; error?: string }
const navigate = useNavigate()
const { t } = useTranslation('auth')
const [invalidLink, setInvalidLink] = useState(!token || !!error)
const {
register,
@@ -39,7 +42,7 @@ export function ResetPasswordPage() {
setInvalidLink(true)
return
}
setError('root', { message: error.message ?? 'No se pudo cambiar la contraseña' })
setError('root', { message: errorMessage(error, t('reset.error')) })
return
}
navigate({ to: '/login', search: { reset: 'ok' } })
@@ -47,14 +50,14 @@ export function ResetPasswordPage() {
if (invalidLink) {
return (
<AuthShell title="Vínculo inválido">
<AuthShell title={t('reset.invalidTitle')}>
<div className="flex flex-col items-center gap-4 py-2 text-center">
<MailWarning className="size-10 text-warning" />
<p className="text-sm text-foreground/60">
El enlace para restablecer la contraseña no es válido o venció.
{t('reset.invalid')}
</p>
<Link to="/forgot-password" className="text-sm font-medium text-accent hover:underline">
Pedir un enlace nuevo
{t('reset.requestNew')}
</Link>
</div>
</AuthShell>
@@ -62,10 +65,10 @@ export function ResetPasswordPage() {
}
return (
<AuthShell title="Nueva contraseña" subtitle="Elegí una contraseña para tu cuenta">
<AuthShell title={t('reset.title')} subtitle={t('reset.subtitle')}>
<form onSubmit={onSubmit} className="space-y-4">
<div>
<Label htmlFor="newPassword">Nueva contraseña</Label>
<Label htmlFor="newPassword">{t('reset.newPassword')}</Label>
<Input
id="newPassword"
type="password"
@@ -75,13 +78,11 @@ export function ResetPasswordPage() {
invalid={!!errors.newPassword}
{...register('newPassword')}
/>
{errors.newPassword ? (
<p className="mt-1 text-sm text-danger">{errors.newPassword.message}</p>
) : null}
<FieldError message={errors.newPassword?.message} />
</div>
<div>
<Label htmlFor="confirmPassword">Repetir contraseña</Label>
<Label htmlFor="confirmPassword">{t('reset.confirmPassword')}</Label>
<Input
id="confirmPassword"
type="password"
@@ -90,16 +91,14 @@ export function ResetPasswordPage() {
invalid={!!errors.confirmPassword}
{...register('confirmPassword')}
/>
{errors.confirmPassword ? (
<p className="mt-1 text-sm text-danger">{errors.confirmPassword.message}</p>
) : null}
<FieldError message={errors.confirmPassword?.message} />
</div>
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
{isSubmitting ? 'Guardando…' : 'Guardar contraseña'}
{isSubmitting ? t('reset.submitting') : t('reset.submit')}
</Button>
</form>
</AuthShell>

View File

@@ -4,18 +4,20 @@ import { zodResolver } from '@hookform/resolvers/zod'
import { Link, useNavigate } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react'
import { authClient } from '../../lib/auth-client'
import { Button, Input, Label } from '../../components/ui'
import { useTranslation } from 'react-i18next'
import { Button, FieldError, Input, Label } from '../../components/ui'
import { errorMessage } from '../../i18n'
import { AuthShell } from './AuthShell'
const schema = z
.object({
name: z.string().min(2, 'Ingresá tu nombre'),
email: z.string().email('Ingresá un email válido'),
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
name: z.string().min(2, 'name.enter'),
email: z.string().email('email.invalid'),
password: z.string().min(8, 'password.min'),
confirmPassword: z.string(),
})
.refine((v) => v.password === v.confirmPassword, {
message: 'Las contraseñas no coinciden',
message: 'password.mismatch',
path: ['confirmPassword'],
})
@@ -23,6 +25,7 @@ type FormValues = z.infer<typeof schema>
export function SignupPage() {
const navigate = useNavigate()
const { t } = useTranslation('auth')
const {
register,
handleSubmit,
@@ -40,7 +43,7 @@ export function SignupPage() {
},
)
if (error) {
setError('root', { message: error.message ?? 'No se pudo registrar' })
setError('root', { message: errorMessage(error, t('signup.error')) })
return
}
if (data?.token) {
@@ -55,51 +58,49 @@ export function SignupPage() {
}
return (
<AuthShell title="Crear cuenta" subtitle="Empezá a cobrar en grupo en minutos">
<AuthShell title={t('signup.title')} subtitle={t('signup.subtitle')}>
<div className="space-y-4">
<form onSubmit={onSubmit} className="space-y-4">
<div>
<Label htmlFor="name">Nombre</Label>
<Label htmlFor="name">{t('signup.name')}</Label>
<Input
id="name"
autoComplete="name"
placeholder="Nombre completo"
placeholder={t('signup.namePlaceholder')}
invalid={!!errors.name}
{...register('name')}
/>
{errors.name ? <p className="mt-1 text-sm text-danger">{errors.name.message}</p> : null}
<FieldError message={errors.name?.message} />
</div>
<div>
<Label htmlFor="email">Email</Label>
<Label htmlFor="email">{t('email')}</Label>
<Input
id="email"
type="email"
autoComplete="email"
placeholder="vos@ejemplo.com"
placeholder={t('emailPlaceholder')}
invalid={!!errors.email}
{...register('email')}
/>
{errors.email ? <p className="mt-1 text-sm text-danger">{errors.email.message}</p> : null}
<FieldError message={errors.email?.message} />
</div>
<div>
<Label htmlFor="password">Contraseña</Label>
<Label htmlFor="password">{t('password')}</Label>
<Input
id="password"
type="password"
autoComplete="new-password"
placeholder="Mínimo 8 caracteres"
placeholder={t('signup.passwordPlaceholder')}
invalid={!!errors.password}
{...register('password')}
/>
{errors.password ? (
<p className="mt-1 text-sm text-danger">{errors.password.message}</p>
) : null}
<FieldError message={errors.password?.message} />
</div>
<div>
<Label htmlFor="confirmPassword">Repetí la contraseña</Label>
<Label htmlFor="confirmPassword">{t('signup.confirmPassword')}</Label>
<Input
id="confirmPassword"
type="password"
@@ -108,33 +109,31 @@ export function SignupPage() {
invalid={!!errors.confirmPassword}
{...register('confirmPassword')}
/>
{errors.confirmPassword ? (
<p className="mt-1 text-sm text-danger">{errors.confirmPassword.message}</p>
) : null}
<FieldError message={errors.confirmPassword?.message} />
</div>
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
{isSubmitting ? 'Creando…' : 'Crear cuenta'}
{isSubmitting ? t('signup.submitting') : t('signup.submit')}
</Button>
</form>
<div className="flex items-center gap-3">
<div className="h-px flex-1 bg-border" />
<span className="text-xs uppercase tracking-wide text-foreground/40">o</span>
<span className="text-xs uppercase tracking-wide text-foreground/40">{t('or')}</span>
<div className="h-px flex-1 bg-border" />
</div>
<Button variant="outline" className="w-full" onClick={handleGoogle}>
Continuar con Google
{t('continueWithGoogle')}
</Button>
<p className="text-center text-sm text-foreground/60">
¿Ya tenés cuenta?{' '}
{t('signup.hasAccount')}{' '}
<Link to="/login" className="font-medium text-accent hover:underline">
Iniciá sesión
{t('signup.signIn')}
</Link>
</p>
</div>

View File

@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react'
import { Link, useNavigate, useSearch } from '@tanstack/react-router'
import { MailCheck, MailWarning, Loader2 } from 'lucide-react'
import { Trans, useTranslation } from 'react-i18next'
import { authClient } from '../../lib/auth-client'
import { AuthShell } from './AuthShell'
@@ -14,6 +15,7 @@ type Status = 'idle' | 'verifying' | 'success' | 'error'
export function VerifyEmailPage() {
const { token, email } = useSearch({ strict: false }) as SearchParams
const navigate = useNavigate()
const { t } = useTranslation('auth')
const [status, setStatus] = useState<Status>(token ? 'verifying' : 'idle')
useEffect(() => {
@@ -40,10 +42,10 @@ export function VerifyEmailPage() {
const title =
status === 'success'
? 'Email verificado'
? t('verify.successTitle')
: status === 'error'
? 'Vínculo inválido'
: 'Verificá tu email'
? t('verify.errorTitle')
: t('verify.title')
return (
<AuthShell title={title}>
@@ -58,16 +60,20 @@ export function VerifyEmailPage() {
{status === 'success' ? (
<p className="text-sm text-foreground/60">
Tu cuenta quedó verificada. Te estamos llevando a Gruperly…
{t('verify.success')}
</p>
) : status === 'error' ? (
<p className="text-sm text-foreground/60">
El vínculo de verificación no es válido o expiró.
{t('verify.error')}
</p>
) : (
<p className="text-sm text-foreground/60">
Te enviamos un correo a <span className="font-medium text-primary">{email}</span> para
confirmar tu cuenta.
<Trans
t={t}
i18nKey="verify.sent"
values={{ email }}
components={{ strong: <span className="font-medium text-primary" /> }}
/>
</p>
)}
@@ -76,13 +82,13 @@ export function VerifyEmailPage() {
to="/"
className="w-full rounded-xl bg-accent py-2 text-center text-sm font-medium text-on-accent hover:bg-accent-strong"
>
Ir a Gruperly
{t('verify.goToApp')}
</Link>
) : null}
{status === 'error' ? (
<Link to="/login" className="text-sm font-medium text-accent hover:underline">
Intentar iniciar sesión
{t('verify.tryLogin')}
</Link>
) : null}
</div>

View File

@@ -5,7 +5,7 @@ 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 { Button, FieldError, Input, Label } from '../../components/ui'
import { BILLING_TYPES, WEEK_DAY_CHIPS } from '../onboarding/constants'
type GroupFormProps = {
@@ -84,7 +84,7 @@ export function GroupForm({
invalid={!!errors.name}
{...register('name')}
/>
{errors.name ? <p className="mt-1 text-sm text-danger">{errors.name.message}</p> : null}
<FieldError message={errors.name?.message} />
</div>
<div>
@@ -110,7 +110,7 @@ export function GroupForm({
)
})}
</div>
{errors.days ? <p className="mt-1 text-sm text-danger">{errors.days.message}</p> : null}
<FieldError message={errors.days?.message} />
</div>
<div>
@@ -121,7 +121,7 @@ export function GroupForm({
invalid={!!errors.time}
{...register('time')}
/>
{errors.time ? <p className="mt-1 text-sm text-danger">{errors.time.message}</p> : null}
<FieldError message={errors.time?.message} />
</div>
<div className="grid grid-cols-2 gap-3">
@@ -136,9 +136,7 @@ export function GroupForm({
invalid={!!errors.capacity}
{...register('capacity', { valueAsNumber: true })}
/>
{errors.capacity ? (
<p className="mt-1 text-sm text-danger">{errors.capacity.message}</p>
) : null}
<FieldError message={errors.capacity?.message} />
</div>
<div>
@@ -159,9 +157,7 @@ export function GroupForm({
{...register('price', { valueAsNumber: true })}
/>
</div>
{errors.price ? (
<p className="mt-1 text-sm text-danger">{errors.price.message}</p>
) : null}
<FieldError message={errors.price?.message} />
</div>
</div>
@@ -213,9 +209,7 @@ export function GroupForm({
<p className="mt-1 text-xs text-foreground/50">
Los cobros vencerán el día {isFinite(dueDay) && dueDay ? dueDay : '1'} de cada mes.
</p>
{errors.dueDay ? (
<p className="mt-1 text-sm text-danger">{errors.dueDay.message}</p>
) : null}
<FieldError message={errors.dueDay?.message} />
</div>
{errorMessage ? (

View File

@@ -2,7 +2,7 @@ import { CalendarClock, CircleDollarSign, Users } from 'lucide-react'
import {
formatBillingMeta,
formatPrice,
WEEK_DAY_FULL_LABELS,
weekDayLabel,
sortWeekDays,
} from '../../../lib/format'
import { cn } from '../../../lib/utils'
@@ -19,7 +19,7 @@ export function GroupInfoCard() {
const { group, attendeesTotal, attendeesPending, waitlistTotal } = useGroupDetail()
if (!group) return null
const daysLabel = sortWeekDays(group.days ?? []).map((day) => WEEK_DAY_FULL_LABELS[day]).join(', ')
const daysLabel = sortWeekDays(group.days ?? []).map(weekDayLabel).join(', ')
const capacity = group.capacity
const isFull = capacity != null && attendeesTotal >= capacity
const freeSpots = capacity != null ? Math.max(capacity - attendeesTotal, 0) : null

View File

@@ -1,6 +1,6 @@
import type { UpcomingPaymentDto } from '@gruperly/shared'
import { Badge } from '../../components/ui'
import { formatPrice, formatRelativeDateTime, PAYMENT_STATUS_LABELS } from '../../lib/format'
import { formatPrice, formatRelativeDateTime, paymentStatusLabel } from '../../lib/format'
import { PAYMENT_BADGE_VARIANT } from './constants'
export function UpcomingPaymentRow({ payment }: { payment: UpcomingPaymentDto }) {
@@ -15,7 +15,7 @@ export function UpcomingPaymentRow({ payment }: { payment: UpcomingPaymentDto })
<div className="flex shrink-0 items-center gap-2">
<span className="text-sm font-semibold text-primary">{formatPrice(payment.amount)}</span>
<Badge variant={PAYMENT_BADGE_VARIANT[payment.status]}>
{PAYMENT_STATUS_LABELS[payment.status]}
{paymentStatusLabel(payment.status)}
</Badge>
</div>
</li>

View File

@@ -1,6 +1,6 @@
import { CalendarClock, GraduationCap, Users } from 'lucide-react'
import { Badge } from '../../components/ui'
import { BILLING_LABELS, formatPrice, formatSchedule } from '../../lib/format'
import { billingTypeLabel, formatPrice, formatSchedule } from '../../lib/format'
import { useJoinGroup } from './JoinGroupProvider'
export function GroupInviteSummary() {
@@ -32,7 +32,7 @@ export function GroupInviteSummary() {
{group.price != null ? (
<div className="inline-flex items-center gap-1.5 rounded-lg bg-primary-soft px-2.5 py-1 text-sm font-medium text-foreground/80">
<span>{formatPrice(group.price)}</span>
{group.billingType ? <span>· {BILLING_LABELS[group.billingType]}</span> : ''}
{group.billingType ? <span>· {billingTypeLabel(group.billingType)}</span> : ''}
</div>
) : null}

View File

@@ -7,7 +7,7 @@ import { useAuth } from '../../context/AuthProvider'
import { PLAN_NAMES } from '../billing'
import { MP_PROVIDER_NAME, useMpStatus } from '../mp'
import { useWhatsappStatus } from '../whatsapp'
import { BILLING_LABELS, formatPrice, formatSchedule } from './constants'
import { billingTypeLabel, formatPrice, formatSchedule } from './constants'
import { useOnboarding } from './OnboardingProvider'
type ConfirmationStepProps = {
@@ -59,7 +59,7 @@ export function ConfirmationStep({ group }: ConfirmationStepProps) {
<dt className="text-foreground/60">Precio</dt>
<dd className="font-semibold text-primary">
{formatPrice(group.price)}
{group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''}
{group.billingType ? ` · ${billingTypeLabel(group.billingType)}` : ''}
</dd>
</div>
<div className="flex items-center justify-between py-2.5">

View File

@@ -1,6 +1,6 @@
import type { BillingType, WeekDay } from '@gruperly/shared'
export { BILLING_LABELS, formatPrice, formatSchedule, WEEK_DAY_FULL_LABELS } from '../../lib/format'
export { billingTypeLabel, formatPrice, formatSchedule, weekDayLabel } from '../../lib/format'
export const WEEK_DAYS: readonly WeekDay[] = [
'MONDAY',

View File

@@ -3,7 +3,7 @@ import { Check, Copy, Link2, Loader2, RefreshCw } from 'lucide-react'
import { useState } from 'react'
import { Badge, Button } from '../../components/ui'
import { cn } from '../../lib/utils'
import { formatPrice, PAYMENT_STATUS_LABELS } from '../../lib/format'
import { formatPrice, paymentStatusLabel } from '../../lib/format'
import { paymentDateLabel, paymentPeriodLabel, PAYMENT_STATUS_BADGE } from './copy'
type PaymentRowProps = {
@@ -49,7 +49,7 @@ export function PaymentRow({ payment, showGroup, isRenewing, onRenew }: PaymentR
<p className="mt-1 text-xs text-foreground/50">{paymentDateLabel(payment)}</p>
</div>
<Badge variant={PAYMENT_STATUS_BADGE[payment.status]}>
{PAYMENT_STATUS_LABELS[payment.status]}
{paymentStatusLabel(payment.status)}
</Badge>
</div>

View File

@@ -1,4 +1,5 @@
import { Download, X } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Button } from '../../components/ui'
type InstallBannerProps = {
@@ -7,6 +8,7 @@ type InstallBannerProps = {
}
export function InstallBanner({ onInstall, onDismiss }: InstallBannerProps) {
const { t } = useTranslation('pwa')
return (
<div
className="fixed inset-x-0 z-30 px-4 lg:left-auto lg:right-6 lg:w-96 lg:px-0
@@ -15,17 +17,17 @@ export function InstallBanner({ onInstall, onDismiss }: InstallBannerProps) {
>
<div className="flex items-start gap-3 rounded-xl border border-border bg-surface p-4 shadow-lg">
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold text-primary">Instalá Gruperly</p>
<p className="text-sm font-semibold text-primary">{t('banner.title')}</p>
<p className="mt-0.5 text-xs leading-relaxed text-foreground/70">
Abrila directo desde tu pantalla de inicio, sin barra de navegador.
{t('banner.description')}
</p>
<div className="mt-3 flex items-center gap-2">
<Button variant="primary" size="sm" onClick={onInstall}>
<Download className="size-4" strokeWidth={2} />
Instalar app
{t('banner.install')}
</Button>
<Button variant="ghost" size="sm" onClick={onDismiss}>
Ahora no
{t('banner.later')}
</Button>
</div>
</div>
@@ -33,7 +35,7 @@ export function InstallBanner({ onInstall, onDismiss }: InstallBannerProps) {
<button
type="button"
onClick={onDismiss}
aria-label="Cerrar aviso de instalación"
aria-label={t('banner.close')}
className="shrink-0 rounded-lg p-1 text-foreground/40 transition-colors hover:bg-primary-soft hover:text-foreground"
>
<X className="size-4" />

View File

@@ -1,4 +1,5 @@
import { Share, X } from 'lucide-react'
import { Trans, useTranslation } from 'react-i18next'
type IosInstallHintProps = {
onDismiss: () => void
@@ -10,6 +11,7 @@ type IosInstallHintProps = {
* no action button.
*/
export function IosInstallHint({ onDismiss }: IosInstallHintProps) {
const { t } = useTranslation('pwa')
return (
<div
className="fixed inset-x-0 z-30 px-4 lg:left-auto lg:right-6 lg:w-96 lg:px-0
@@ -19,18 +21,16 @@ export function IosInstallHint({ onDismiss }: IosInstallHintProps) {
<Share className="mt-0.5 size-5 shrink-0 text-accent" strokeWidth={2} />
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold text-primary">Instalá Gruperly en el iPhone</p>
<p className="text-sm font-semibold text-primary">{t('ios.title')}</p>
<p className="mt-0.5 text-xs leading-relaxed text-foreground/70">
Tocá <span className="font-medium text-foreground">Compartir</span> y elegí{' '}
<span className="font-medium text-foreground">Agregar a pantalla de inicio</span> para
abrirla como app.
<Trans t={t} i18nKey="ios.description" components={{ strong: <span className="font-medium text-foreground" /> }} />
</p>
</div>
<button
type="button"
onClick={onDismiss}
aria-label="Cerrar aviso de instalación"
aria-label={t('banner.close')}
className="shrink-0 rounded-lg p-1 text-foreground/40 transition-colors hover:bg-primary-soft hover:text-foreground"
>
<X className="size-4" />

View File

@@ -11,6 +11,7 @@ import { registerSW } from 'virtual:pwa-register'
import { router } from '../../router'
import { useAuth } from '../../context/AuthProvider'
import { useToast } from '../../components/ui'
import { i18n } from '../../i18n/instance'
import { InstallPrompt } from './InstallPrompt'
/** `beforeinstallprompt` is not in lib.dom yet (Chromium >= 108). */
@@ -94,7 +95,7 @@ export function PwaProvider({ children }: { children: ReactNode }) {
registerSW({
immediate: true,
onOfflineReady() {
success('La app quedó lista para abrirse sin conexión', 'Ya podés usar Gruperly offline.')
success(i18n.t('pwa:offlineReady'), i18n.t('pwa:offlineReadyDetail'))
},
onRegisterError(error) {
console.error('No se pudo registrar el service worker', error)
@@ -153,14 +154,14 @@ export function PwaProvider({ children }: { children: ReactNode }) {
if (outcome === 'accepted') {
localStorage.setItem(DISMISSED_KEY, '1')
setDismissed(true)
success('App instalada', 'Ahora tenés Gruperly en tu pantalla de inicio.')
success(i18n.t('pwa:installed'), i18n.t('pwa:installedDetail'))
}
}, [installEvent, success])
const dismiss = useCallback(() => {
setDismissed(true)
localStorage.setItem(DISMISSED_KEY, '1')
info('Podés instalarla más adelante desde el menú del navegador.')
info(i18n.t('pwa:installLater'))
}, [info])
/**

View File

@@ -4,7 +4,7 @@ import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { Fingerprint, KeyRound, Loader2, Plus } from 'lucide-react'
import { authClient } from '../../lib/auth-client'
import { Button, Input, Label } from '../../components/ui'
import { Button, FieldError, Input, Label } from '../../components/ui'
import { PasskeyList } from './PasskeyList'
import { changePasswordSchema } from './schema'
import type { ChangePasswordValues } from './schema'
@@ -81,9 +81,7 @@ export function SecurityPage() {
invalid={!!errors.currentPassword}
{...register('currentPassword')}
/>
{errors.currentPassword ? (
<p className="mt-1 text-sm text-danger">{errors.currentPassword.message}</p>
) : null}
<FieldError message={errors.currentPassword?.message} />
</div>
<div>
<Label htmlFor="newPassword">Nueva contraseña</Label>
@@ -94,9 +92,7 @@ export function SecurityPage() {
invalid={!!errors.newPassword}
{...register('newPassword')}
/>
{errors.newPassword ? (
<p className="mt-1 text-sm text-danger">{errors.newPassword.message}</p>
) : null}
<FieldError message={errors.newPassword?.message} />
</div>
<Button type="submit" variant="primary" disabled={isSubmitting}>
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}

View File

@@ -1,16 +1,18 @@
import { Check } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { useTheme } from '../../context/ThemeProvider'
import { cn } from '../../lib/utils'
import { THEME_ICONS, THEME_OPTIONS } from './constants'
export function AppearanceCard() {
const { theme, setTheme } = useTheme()
const { t } = useTranslation('settings')
return (
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
<div className="px-4 py-3">
<p className="text-sm font-medium text-primary">Apariencia</p>
<p className="text-xs text-foreground/50">Tema claro u oscuro</p>
<p className="text-sm font-medium text-primary">{t('appearance.title')}</p>
<p className="text-xs text-foreground/50">{t('appearance.description')}</p>
</div>
{THEME_OPTIONS.map((option) => {
const Icon = THEME_ICONS[option.value]
@@ -29,9 +31,9 @@ export function AppearanceCard() {
</span>
<div className="min-w-0 flex-1">
<p className={cn('text-sm font-medium', isSelected ? 'text-accent-fg' : 'text-primary')}>
{option.label}
{t(option.label)}
</p>
<p className="text-xs text-foreground/50">{option.description}</p>
<p className="text-xs text-foreground/50">{t(option.description)}</p>
</div>
{isSelected ? <Check className="size-4 text-accent-fg" /> : null}
</button>

View File

@@ -0,0 +1,79 @@
import { SUPPORTED_LOCALES } from '@gruperly/shared'
import { Check, Languages } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { useToast } from '../../components/ui'
import { useAuth } from '../../context/AuthProvider'
import { useLocale, type LocalePreference } from '../../i18n'
import { LOCALE_NAMES } from '../../i18n/locales'
import { authClient } from '../../lib/auth-client'
import { cn } from '../../lib/utils'
const OPTIONS: LocalePreference[] = ['system', ...SUPPORTED_LOCALES]
type LanguageCardProps = {
/** Guarda la elección en la cuenta del profe (Better Auth). La app de
* alumnos no tiene esa sesión: ahí queda solo en el dispositivo. */
syncProfile?: boolean
}
export function LanguageCard({ syncProfile = false }: LanguageCardProps) {
const { t } = useTranslation('settings')
const { preference, device, setPreference } = useLocale()
const { user } = useAuth()
const toast = useToast()
const select = (next: LocalePreference) => {
if (next === preference) return
// Optimista: el idioma cambia ya; la cuenta se actualiza por detrás.
setPreference(next)
if (!syncProfile || !user) return
void authClient.updateUser({ locale: next === 'system' ? null : next }).then(({ error }) => {
if (error) toast.error(t('language.saveError'))
})
}
return (
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
<div className="flex items-start gap-3 px-4 py-3">
<span className="rounded-lg bg-primary-soft p-2" aria-hidden="true">
<Languages className="size-4 text-primary" />
</span>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-primary">{t('language.title')}</p>
<p className="text-xs text-foreground/50">{t('language.description')}</p>
</div>
</div>
<div role="radiogroup" aria-label={t('language.title')}>
{OPTIONS.map((option) => {
const isSelected = preference === option
const isSystem = option === 'system'
return (
<button
key={option}
type="button"
role="radio"
aria-checked={isSelected}
onClick={() => select(option)}
className="flex w-full items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-primary-soft"
>
<div className="min-w-0 flex-1">
<p
lang={isSystem ? undefined : option}
className={cn('text-sm font-medium', isSelected ? 'text-accent-fg' : 'text-primary')}
>
{isSystem ? t('language.system') : LOCALE_NAMES[option]}
</p>
{isSystem ? (
<p className="text-xs text-foreground/50">
{t('language.systemDescription', { language: LOCALE_NAMES[device] })}
</p>
) : null}
</div>
{isSelected ? <Check className="size-4 text-accent-fg" /> : null}
</button>
)
})}
</div>
</div>
)
}

View File

@@ -1,16 +1,19 @@
import { Link } from '@tanstack/react-router'
import { ChevronRight, Fingerprint } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Button } from '../../components/ui'
import { signOut } from '../../lib/auth-client'
import { PlanSettingsCard } from '../billing'
import { MpStatusCard } from '../mp'
import { WhatsappStatusCard } from '../whatsapp'
import { AppearanceCard } from './AppearanceCard'
import { LanguageCard } from './LanguageCard'
import { TransferDetailsSettingsCard } from './TransferDetailsSettingsCard'
import { useCallbackFeedbackToast } from './useCallbackFeedbackToast'
export function SettingsView() {
useCallbackFeedbackToast()
const { t } = useTranslation('settings')
const handleSignOut = async () => {
await signOut({
@@ -22,8 +25,8 @@ export function SettingsView() {
return (
<section className="space-y-6">
<div>
<h1 className="text-2xl font-bold text-primary">Ajustes</h1>
<p className="mt-1 text-sm text-foreground/60">Configurá tu cuenta y tus grupos.</p>
<h1 className="text-2xl font-bold text-primary">{t('title')}</h1>
<p className="mt-1 text-sm text-foreground/60">{t('subtitle')}</p>
</div>
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
@@ -32,8 +35,8 @@ export function SettingsView() {
<Fingerprint className="size-4 text-accent-fg" />
</span>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-primary">Seguridad</p>
<p className="text-xs text-foreground/50">Contraseña y passkeys</p>
<p className="text-sm font-medium text-primary">{t('security.title')}</p>
<p className="text-xs text-foreground/50">{t('security.description')}</p>
</div>
<ChevronRight className="size-4 text-foreground/40" />
</Link>
@@ -49,8 +52,10 @@ export function SettingsView() {
<AppearanceCard />
<LanguageCard syncProfile />
<Button variant="outline" onClick={handleSignOut}>
Cerrar sesión
{t('signOut')}
</Button>
</section>
)

View File

@@ -1,6 +1,7 @@
import { useState, type FormEvent } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Landmark, Loader2 } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Button, Input, Label, useToast } from '../../components/ui'
import { getTransferDetails, updateTransferDetails } from '../../lib/api'
@@ -11,6 +12,7 @@ const KEY = ['transfer-details'] as const
export function TransferDetailsSettingsCard() {
const queryClient = useQueryClient()
const toast = useToast()
const { t } = useTranslation(['settings', 'common'])
const query = useQuery({ queryKey: KEY, queryFn: getTransferDetails })
const [editing, setEditing] = useState(false)
const [alias, setAlias] = useState('')
@@ -21,9 +23,9 @@ export function TransferDetailsSettingsCard() {
onSuccess: (data) => {
queryClient.setQueryData(KEY, data)
setEditing(false)
toast.success('Datos para transferir guardados')
toast.success(t('transfer.saved'))
},
onError: () => toast.error('No pudimos guardar los datos'),
onError: () => toast.error(t('transfer.saveError')),
})
const startEditing = () => {
@@ -44,12 +46,12 @@ export function TransferDetailsSettingsCard() {
<Landmark className="size-4 text-primary" />
</span>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-primary">Datos para transferir</p>
<p className="text-xs text-secondary">Los ven tus alumnos cuando informan un pago</p>
<p className="text-sm font-medium text-primary">{t('transfer.title')}</p>
<p className="text-xs text-secondary">{t('transfer.description')}</p>
</div>
{!editing ? (
<Button variant="outline" size="sm" className="h-11 shrink-0" onClick={startEditing} disabled={query.isPending}>
{query.data?.alias ? 'Editar' : 'Agregar'}
{query.data?.alias ? t('common:actions.edit') : t('common:actions.add')}
</Button>
) : null}
</div>
@@ -57,32 +59,32 @@ export function TransferDetailsSettingsCard() {
{editing ? (
<form onSubmit={submit} className="space-y-3 border-t border-border px-4 py-4">
<div className="space-y-1.5">
<Label htmlFor="transfer-alias">Alias o CBU/CVU</Label>
<Label htmlFor="transfer-alias">{t('transfer.alias')}</Label>
<Input id="transfer-alias" autoFocus maxLength={60} value={alias} onChange={(event) => setAlias(event.target.value)} />
</div>
<div className="space-y-1.5">
<Label htmlFor="transfer-holder">Titular</Label>
<Label htmlFor="transfer-holder">{t('transfer.holder')}</Label>
<Input id="transfer-holder" maxLength={120} value={holder} onChange={(event) => setHolder(event.target.value)} />
</div>
<div className="flex gap-2">
<Button variant="ghost" className="h-11 flex-1" onClick={() => setEditing(false)}>
Cancelar
{t('common:actions.cancel')}
</Button>
<Button type="submit" variant="primary" className="h-11 flex-1" disabled={mutation.isPending}>
{mutation.isPending ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : null}
Guardar
{t('common:actions.save')}
</Button>
</div>
</form>
) : query.data?.alias ? (
<dl className="space-y-1 border-t border-border px-4 py-3 text-sm">
<div className="flex justify-between gap-3">
<dt className="text-secondary">Alias</dt>
<dt className="text-secondary">{t('transfer.aliasShort')}</dt>
<dd className="truncate font-mono font-medium text-primary">{query.data.alias}</dd>
</div>
{query.data.holder ? (
<div className="flex justify-between gap-3">
<dt className="text-secondary">Titular</dt>
<dt className="text-secondary">{t('transfer.holder')}</dt>
<dd className="truncate font-medium text-primary">{query.data.holder}</dd>
</div>
) : null}

View File

@@ -1,11 +1,12 @@
import { Monitor, Moon, Sun } from 'lucide-react'
import type { Theme } from '../../context/ThemeProvider'
export const THEME_OPTIONS: { value: Theme; label: string; description: string }[] = [
{ value: 'light', label: 'Claro', description: 'Interfaz en tonos claros' },
{ value: 'dark', label: 'Oscuro', description: 'Interfaz en tonos oscuros' },
{ value: 'system', label: 'Sistema', description: 'Sigue la preferencia de tu dispositivo' },
]
/** Claves en el namespace `settings` (`appearance.*`). */
export const THEME_OPTIONS = [
{ value: 'light', label: 'appearance.light', description: 'appearance.lightDescription' },
{ value: 'dark', label: 'appearance.dark', description: 'appearance.darkDescription' },
{ value: 'system', label: 'appearance.system', description: 'appearance.systemDescription' },
] as const satisfies readonly { value: Theme; label: string; description: string }[]
export const THEME_ICONS: Record<Theme, typeof Sun> = {
light: Sun,

View File

@@ -1,6 +1,7 @@
import { useQueryClient } from '@tanstack/react-query'
import { useNavigate, useSearch } from '@tanstack/react-router'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { useToast } from '../../components/ui'
import { mpCallbackErrorMessage, mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
import {
@@ -19,6 +20,7 @@ export function useCallbackFeedbackToast() {
const navigate = useNavigate()
const queryClient = useQueryClient()
const toast = useToast()
const { t } = useTranslation('settings')
useEffect(() => {
const mp = readMpCallbackFeedback(search.mp, search.reason)
@@ -26,12 +28,12 @@ export function useCallbackFeedbackToast() {
if (!mp && !wa) return
if (mp) {
if (mp.kind === 'success') toast.success('Tu cuenta de Mercado Pago quedó vinculada.')
if (mp.kind === 'success') toast.success(t('callback.mpLinked'))
else toast.error(mpCallbackErrorMessage(mp.reason))
void queryClient.invalidateQueries({ queryKey: mpStatusQueryKey })
}
if (wa) {
if (wa.kind === 'success') toast.success('Tu WhatsApp quedó vinculado.')
if (wa.kind === 'success') toast.success(t('callback.whatsappLinked'))
else toast.error(whatsappCallbackErrorMessage(wa.reason))
void queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
}

View File

@@ -1,8 +1,9 @@
import { CalendarDays, Home, User, Wallet } from 'lucide-react'
import type { NavItem } from '../../components/layout/nav-items'
import { CalendarDays, Home, User, Wallet, type LucideIcon } from 'lucide-react'
type StudentNavItem = { label: string; to: string; icon: LucideIcon }
// Bottom nav of the student app: the single source for StudentBottomNav.
export const STUDENT_NAV_ITEMS: NavItem[] = [
export const STUDENT_NAV_ITEMS: StudentNavItem[] = [
{ label: 'Inicio', to: '/student', icon: Home },
{ label: 'Clases', to: '/student/classes', icon: CalendarDays },
{ label: 'Pagos', to: '/student/payments', icon: Wallet },

View File

@@ -0,0 +1,63 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
import type { AppLocale } from '@gruperly/shared'
import { activateLocale } from './load'
import {
deviceLocale,
localeFor,
readStoredPreference,
storePreference,
type LocalePreference,
} from './preference'
type I18nContextValue = {
/** Lo que eligió la persona ('system' = idioma del dispositivo). */
preference: LocalePreference
/** El idioma en el que está la UI ahora. */
locale: AppLocale
/** El idioma del dispositivo, para la opción "Idioma del dispositivo". */
device: AppLocale
setPreference: (preference: LocalePreference) => void
}
const I18nContext = createContext<I18nContextValue | null>(null)
/** Se monta por fuera de AuthProvider: el login, la app de alumnos y las
* páginas públicas también se traducen. main.tsx activa el idioma inicial antes
* del primer render, así no se ve un flash en otro idioma. */
export function I18nProvider({ children }: { children: ReactNode }) {
const [preference, setPreferenceState] = useState<LocalePreference>(readStoredPreference)
const [device, setDevice] = useState<AppLocale>(deviceLocale)
const locale = preference === 'system' ? device : preference
useEffect(() => {
const update = () => setDevice(deviceLocale())
window.addEventListener('languagechange', update)
return () => window.removeEventListener('languagechange', update)
}, [])
useEffect(() => {
void activateLocale(locale)
}, [locale])
const setPreference = useCallback((next: LocalePreference) => {
storePreference(next)
setPreferenceState(next)
}, [])
const value = useMemo(
() => ({ preference, locale, device, setPreference }),
[preference, locale, device, setPreference],
)
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>
}
export function useLocale() {
const context = useContext(I18nContext)
if (!context) throw new Error('useLocale debe usarse dentro de <I18nProvider>')
return context
}
/** Idioma con el que arranca la app (antes de montar React). */
export function initialLocale(): AppLocale {
return localeFor(readStoredPreference())
}

View File

@@ -0,0 +1,37 @@
import { useEffect, useRef } from 'react'
import { appLocaleSchema } from '@gruperly/shared'
import { useAuth } from '../context/AuthProvider'
import { authClient } from '../lib/auth-client'
import { useLocale } from './I18nProvider'
/**
* Sincroniza el idioma con el perfil del profe al iniciar sesión:
* - si la cuenta tiene un idioma guardado, manda ese (sigue a la persona entre
* dispositivos);
* - si no tiene y en este dispositivo se eligió uno a mano, se guarda en la
* cuenta.
* Corre una vez por usuario; después los cambios se guardan desde Ajustes.
*/
export function LocaleProfileSync() {
const { user } = useAuth()
const { preference, setPreference } = useLocale()
const syncedUserId = useRef<string | null>(null)
useEffect(() => {
if (!user) {
syncedUserId.current = null
return
}
if (syncedUserId.current === user.id) return
syncedUserId.current = user.id
const stored = appLocaleSchema.safeParse(user.locale)
if (stored.success) {
if (stored.data !== preference) setPreference(stored.data)
} else if (preference !== 'system') {
void authClient.updateUser({ locale: preference })
}
}, [user, preference, setPreference])
return null
}

View File

@@ -0,0 +1,85 @@
import { ApiError } from '../lib/api'
import { i18n } from './instance'
type AuthClientError = { code?: string; message?: string; status?: number }
function isAuthClientError(error: unknown): error is AuthClientError {
return typeof error === 'object' && error !== null && 'code' in error && !(error instanceof ApiError)
}
type TranslateOptions = Record<string, unknown>
function translate(key: string, options: TranslateOptions = {}): string | null {
const opts = { ns: 'errors' as const, ...options }
return i18n.exists(key, opts) ? String(i18n.t(key as never, opts as never)) : null
}
/** Un `code` con `params` puede tener variante (`plan_limit_reached_groups`) y
* plural (`count` = el número del problema). Se prueba la variante y después
* la clave base. */
function translateCode(code: string, params: Record<string, string | number> = {}): string | null {
const variant = params.limit ?? params.feature
const count = params.max ?? params.capacity
const options: TranslateOptions = { ...params, ...(typeof count === 'number' ? { count } : {}) }
return (
(variant ? translate(`codes.${code}_${variant}`, options) : null) ??
translate(`codes.${code}`, options) ??
translate(`codes.${code}`)
)
}
/**
* Mensaje para mostrarle a la persona ante un error de la API o de Better Auth,
* en el idioma de la UI. Orden:
* 1. el `code` del Problem Details (o de Better Auth) traducido;
* 2. con la UI en español, el `detail` del backend (que está en español) si es
* un mensaje de dominio y no uno técnico;
* 3. el `fallback` de la pantalla, o uno genérico por status.
*
* Usa la instancia global: se llama desde callbacks (`onError`) y siempre toma
* el idioma vigente.
*/
export function errorMessage(error: unknown, fallback?: string): string {
if (error instanceof ApiError) {
const code = error.problem?.code
const byCode = code ? translateCode(code, error.problem?.params) : null
if (byCode) return byCode
const detail = error.problem?.detail
if (detail && isDomainDetail(error.status, detail) && i18n.language.startsWith('es')) return detail
return fallback ?? genericByStatus(error.status)
}
if (isAuthClientError(error) && error.code) {
const byCode = translate(`auth.${error.code}`)
if (byCode) return byCode
}
return fallback ?? i18n.t('generic', { ns: 'errors' })
}
/** El backend deja mensajes técnicos en inglés ("Invalid json data", "Group
* abc123") para validaciones de forma y 404: esos nunca se muestran. */
function isDomainDetail(status: number, detail: string): boolean {
if (status === 404 || status >= 500) return false
return !/^Invalid\b/.test(detail)
}
function genericByStatus(status: number): string {
const key =
status === 0
? 'network'
: status === 401
? 'status.unauthorized'
: status === 403
? 'status.forbidden'
: status === 404
? 'status.notFound'
: status === 429
? 'status.tooManyRequests'
: status >= 500
? 'status.server'
: 'generic'
return i18n.t(key as never, { ns: 'errors' })
}

24
apps/web/src/i18n/i18next.d.ts vendored Normal file
View File

@@ -0,0 +1,24 @@
import 'i18next'
import type auth from './locales/es-AR/auth.json'
import type common from './locales/es-AR/common.json'
import type errors from './locales/es-AR/errors.json'
import type layout from './locales/es-AR/layout.json'
import type pwa from './locales/es-AR/pwa.json'
import type settings from './locales/es-AR/settings.json'
import type validation from './locales/es-AR/validation.json'
// es-AR es la fuente: una clave que no exista ahí rompe el typecheck.
declare module 'i18next' {
interface CustomTypeOptions {
defaultNS: 'common'
resources: {
auth: typeof auth
common: typeof common
errors: typeof errors
layout: typeof layout
pwa: typeof pwa
settings: typeof settings
validation: typeof validation
}
}
}

View File

@@ -0,0 +1,7 @@
export { i18n, NAMESPACES, type Namespace } from './instance'
export { activateLocale } from './load'
export { I18nProvider, initialLocale, useLocale } from './I18nProvider'
export { useIntlLocale } from './useIntlLocale'
export { errorMessage } from './errors'
export { installZodErrorMap, validationMessage } from './validation'
export type { LocalePreference } from './preference'

View File

@@ -0,0 +1,35 @@
import i18next from 'i18next'
import { initReactI18next } from 'react-i18next'
import { FALLBACK_LOCALE } from '@gruperly/shared'
/** Namespaces: uno por feature. Sumar uno implica un JSON por idioma en
* `locales/<idioma>/` y una entrada en `i18next.d.ts`. */
export const NAMESPACES = [
'common',
'layout',
'settings',
'auth',
'pwa',
'errors',
'validation',
] as const
export type Namespace = (typeof NAMESPACES)[number]
/** Única instancia de i18next de la app. Los recursos se agregan por idioma al
* cargarlos (ver load.ts); los tests cargan es-AR de forma síncrona. */
export const i18n = i18next.createInstance()
void i18n.use(initReactI18next).init({
resources: {},
partialBundledLanguages: true,
lng: FALLBACK_LOCALE,
fallbackLng: FALLBACK_LOCALE,
ns: NAMESPACES,
defaultNS: 'common',
// Los tags son exactos (es-AR, es-419): que i18next no busque "es" a secas.
load: 'currentOnly',
interpolation: { escapeValue: false },
returnNull: false,
react: { useSuspense: false },
initAsync: false,
})

37
apps/web/src/i18n/load.ts Normal file
View File

@@ -0,0 +1,37 @@
import type { AppLocale } from '@gruperly/shared'
import { FALLBACK_LOCALE } from '@gruperly/shared'
import { i18n } from './instance'
type Bundle = Record<string, unknown>
// Vite separa cada JSON en su propio chunk: solo se baja el idioma activo (y el
// inglés de fallback). Workbox igual los precachea todos, así que cambiar de
// idioma funciona offline. Va dentro de una función porque `import.meta.glob`
// solo existe con Vite (en bun test este módulo se importa pero no se usa).
let bundles: Record<string, () => Promise<Bundle>> | undefined
function getBundles() {
bundles ??= import.meta.glob<Bundle>('./locales/*/*.json', { import: 'default' })
return bundles
}
const loaded = new Set<AppLocale>()
async function loadOne(locale: AppLocale): Promise<void> {
if (loaded.has(locale)) return
const prefix = `./locales/${locale}/`
const entries = Object.entries(getBundles()).filter(([path]) => path.startsWith(prefix))
await Promise.all(
entries.map(async ([path, load]) => {
const ns = path.slice(prefix.length, -'.json'.length)
i18n.addResourceBundle(locale, ns, await load(), true, true)
}),
)
loaded.add(locale)
}
/** Carga el idioma (más el inglés de fallback) y lo activa. */
export async function activateLocale(locale: AppLocale): Promise<void> {
await Promise.all([loadOne(locale), loadOne(FALLBACK_LOCALE)])
if (i18n.language !== locale) await i18n.changeLanguage(locale)
document.documentElement.lang = locale
}

View File

@@ -0,0 +1,10 @@
import type { AppLocale } from '@gruperly/shared'
/** Cada idioma se nombra en su propia lengua (así lo encuentra quien no
* entiende el idioma actual de la UI); no se traduce. */
export const LOCALE_NAMES: Record<AppLocale, string> = {
'es-AR': 'Español (Argentina y Uruguay)',
'es-419': 'Español (Latinoamérica)',
'pt-BR': 'Português (Brasil)',
en: 'English',
}

View File

@@ -0,0 +1,65 @@
{
"email": "Email",
"emailPlaceholder": "you@example.com",
"password": "Password",
"or": "or",
"continueWithGoogle": "Continue with Google",
"backToLogin": "Back to sign in",
"login": {
"title": "Sign in",
"subtitle": "Access your group payments",
"resetOk": "Your password was updated. Sign in with the new one.",
"forgot": "Forgot your password?",
"submit": "Sign in",
"submitting": "Signing in…",
"passkey": "Sign in with a passkey",
"noAccount": "Don't have an account?",
"signUp": "Sign up",
"error": "We couldn't sign you in",
"passkeyError": "We couldn't authenticate with your passkey"
},
"signup": {
"title": "Create account",
"subtitle": "Start collecting group payments in minutes",
"name": "Name",
"namePlaceholder": "Full name",
"passwordPlaceholder": "At least 8 characters",
"confirmPassword": "Repeat the password",
"submit": "Create account",
"submitting": "Creating…",
"hasAccount": "Already have an account?",
"signIn": "Sign in",
"error": "We couldn't create your account"
},
"forgot": {
"title": "Reset password",
"subtitle": "We'll send you a link to choose a new one",
"submit": "Send link",
"submitting": "Sending…",
"sentTitle": "Check your email",
"sent": "If there's an account for <strong>{{email}}</strong>, we sent you a link to choose a new password. It expires in 1 hour.",
"error": "We couldn't send the email"
},
"reset": {
"title": "New password",
"subtitle": "Choose a password for your account",
"newPassword": "New password",
"confirmPassword": "Repeat password",
"submit": "Save password",
"submitting": "Saving…",
"invalidTitle": "Invalid link",
"invalid": "The password reset link is invalid or has expired.",
"requestNew": "Request a new link",
"error": "We couldn't change the password"
},
"verify": {
"title": "Verify your email",
"successTitle": "Email verified",
"errorTitle": "Invalid link",
"success": "Your account is verified. Taking you to Gruperly…",
"error": "The verification link is invalid or has expired.",
"sent": "We sent an email to <strong>{{email}}</strong> to confirm your account.",
"goToApp": "Go to Gruperly",
"tryLogin": "Try signing in"
}
}

View File

@@ -0,0 +1,42 @@
{
"actions": {
"cancel": "Cancel",
"save": "Save",
"edit": "Edit",
"add": "Add",
"close": "Close",
"back": "Back",
"retry": "Try again"
},
"user": {
"fallbackName": "User"
},
"toast": {
"close": "Dismiss notification"
},
"weekDay": {
"MONDAY": "Monday",
"TUESDAY": "Tuesday",
"WEDNESDAY": "Wednesday",
"THURSDAY": "Thursday",
"FRIDAY": "Friday",
"SATURDAY": "Saturday",
"SUNDAY": "Sunday"
},
"billingType": {
"MONTHLY": "Monthly",
"PER_CLASS": "Per class"
},
"paymentStatus": {
"PENDING": "Pending",
"PAID": "Paid",
"OVERDUE": "Overdue",
"CANCELLED": "Cancelled"
},
"relativeDay": {
"today": "Today · {{time}}",
"tomorrow": "Tomorrow · {{time}}",
"other": "{{date}} · {{time}}"
},
"billingDueDay": "Due on day {{day}} of each month"
}

View File

@@ -0,0 +1,79 @@
{
"generic": "Something went wrong. Please try again.",
"network": "You're offline. Check your connection and try again.",
"status": {
"unauthorized": "Your session expired. Please sign in again.",
"forbidden": "You don't have permission to do this.",
"notFound": "We couldn't find what you were looking for.",
"tooManyRequests": "Too many requests in a row. Try again in a few minutes.",
"server": "We ran into a problem. Try again in a few minutes."
},
"codes": {
"admin_required": "Only the Gruperly team can access the back office.",
"already_waitlisted": "This phone number is already on the group's waitlist.",
"attendee_already_registered": "This person is already a member of this group.",
"attendee_has_payments": "This member has payments on record. Manage or cancel them before removing the member from the group.",
"attendee_same_group": "The member already belongs to this group.",
"billing_not_available": "The Pro subscription isn't available in your country yet.",
"billing_provider_error": "We couldn't reach the payment processor. Try again in a few minutes.",
"class_already_started": "The class has already started: notices can only be given or undone before it starts.",
"cross_origin_request": "Origin not allowed.",
"database_unavailable": "We ran into a problem. Try again in a few minutes.",
"group_access_denied": "You don't have access to this group.",
"group_capacity_reached": "The group is full.",
"group_capacity_reached_one": "The group is full ({{count}} member max).",
"group_capacity_reached_other": "The group is full ({{count}} members max).",
"group_owner_required": "Only the group's creator can change its automations.",
"group_without_price": "Set the group's price before creating payments.",
"mp_account_in_use": "That Mercado Pago account is already linked to another teacher.",
"mp_not_configured": "Linking with Mercado Pago isn't available right now.",
"mp_not_connected": "You don't have a Mercado Pago account linked.",
"mp_provider_error": "We couldn't finish linking with Mercado Pago.",
"mp_requires_reauth": "Your Mercado Pago account needs to be linked again.",
"no_active_subscription": "You don't have a subscription to cancel.",
"no_attendees_to_bill": "There are no active members with a pending payment in this group.",
"onboarding_already_completed": "You've already finished setting up Gruperly.",
"passkey_invalid": "We couldn't verify the passkey.",
"payment_already_reported": "You've already reported a payment for some of these fees.",
"payment_report_already_reviewed": "This payment has already been reviewed.",
"person_exists": "You already have someone registered with this phone number.",
"person_phone_taken": "Someone else you've registered already uses this phone number.",
"plan_feature_required": "This feature is available on the Pro plan.",
"plan_feature_required_mpCharges": "Collecting with Mercado Pago is available on the Pro plan.",
"plan_feature_required_whatsappAutomations": "Automatic WhatsApp messages are available on the Pro plan.",
"plan_limit_reached": "You've reached the Free plan's limit. Upgrade to Pro to keep growing.",
"plan_limit_reached_groups_one": "The Free plan allows up to {{count}} group. Upgrade to Pro to create more.",
"plan_limit_reached_groups_other": "The Free plan allows up to {{count}} groups. Upgrade to Pro to create more.",
"plan_limit_reached_attendees_one": "The Free plan allows up to {{count}} active student. Upgrade to Pro to add more.",
"plan_limit_reached_attendees_other": "The Free plan allows up to {{count}} active students. Upgrade to Pro to add more.",
"plan_not_selected": "Choose a plan before creating your first group.",
"plan_read_only": "Your account is read-only because it's over the Free plan's limits. Upgrade to Pro or reduce your usage to edit again.",
"pre_registration_already_reviewed": "This pre-registration has already been reviewed.",
"review_undo_expired": "It can no longer be undone.",
"storage_not_available": "Receipts can't be attached right now.",
"student_link_invalid": "This link has already been used or has expired.",
"subscription_already_active": "You already have an active Pro subscription.",
"too_many_requests": "Too many requests in a row. Try again in a few minutes.",
"unauthorized": "Your session expired. Please sign in again.",
"user_not_found": "User not found.",
"whatsapp_linking_not_started": "Start linking WhatsApp before requesting the code.",
"whatsapp_not_configured": "Linking with WhatsApp isn't available right now.",
"whatsapp_not_connected": "You don't have a WhatsApp linked.",
"whatsapp_number_in_use": "That WhatsApp number is already linked to another teacher.",
"whatsapp_pairing_not_ready": "WhatsApp is still getting ready to link. Try again in a few seconds.",
"whatsapp_pairing_unsupported": "This WhatsApp provider doesn't support linking by phone number.",
"whatsapp_provider_error": "We couldn't reach WhatsApp. Try again in a few minutes."
},
"auth": {
"INVALID_EMAIL_OR_PASSWORD": "The email or password is incorrect.",
"EMAIL_NOT_VERIFIED": "You haven't verified your email yet. Check your inbox.",
"USER_ALREADY_EXISTS": "There's already an account with that email.",
"USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL": "There's already an account with that email.",
"INVALID_EMAIL": "Enter a valid email.",
"PASSWORD_TOO_SHORT": "The password must be at least 8 characters.",
"PASSWORD_TOO_LONG": "The password is too long.",
"INVALID_PASSWORD": "Your current password is incorrect.",
"INVALID_TOKEN": "The link is invalid or has expired.",
"TOO_MANY_REQUESTS": "Too many requests in a row. Try again in a few minutes."
}
}

View File

@@ -0,0 +1,26 @@
{
"nav": {
"home": "Home",
"groups": "Groups",
"payments": "Payments",
"settings": "Settings",
"security": "Security",
"profile": "My profile"
},
"breadcrumb": "Breadcrumb",
"homeLink": "Gruperly home",
"reportedPayments_one": "{{count}} payment to verify",
"reportedPayments_other": "{{count}} payments to verify",
"theme": {
"toLight": "Switch to light theme",
"toDark": "Switch to dark theme"
},
"userMenu": {
"close": "Close menu",
"profile": "My profile",
"settings": "Settings",
"admin": "Back office",
"signOut": "Sign out"
},
"publicFooter": "Gruperly — Simple group billing and management"
}

View File

@@ -0,0 +1,18 @@
{
"banner": {
"title": "Install Gruperly",
"description": "Open it straight from your home screen, without the browser bar.",
"install": "Install app",
"later": "Not now",
"close": "Dismiss install prompt"
},
"ios": {
"title": "Install Gruperly on your iPhone",
"description": "Tap <strong>Share</strong> and choose <strong>Add to Home Screen</strong> to open it as an app."
},
"offlineReady": "The app is ready to open offline",
"offlineReadyDetail": "You can now use Gruperly offline.",
"installed": "App installed",
"installedDetail": "Gruperly is now on your home screen.",
"installLater": "You can install it later from your browser's menu."
}

View File

@@ -0,0 +1,39 @@
{
"title": "Settings",
"subtitle": "Set up your account and your groups.",
"security": {
"title": "Security",
"description": "Password and passkeys"
},
"signOut": "Sign out",
"appearance": {
"title": "Appearance",
"description": "Light or dark theme",
"light": "Light",
"lightDescription": "Light interface",
"dark": "Dark",
"darkDescription": "Dark interface",
"system": "System",
"systemDescription": "Follows your device's setting"
},
"language": {
"title": "Language",
"description": "The app's language",
"system": "Device language",
"systemDescription": "Currently: {{language}}",
"saveError": "We couldn't save the language to your account"
},
"transfer": {
"title": "Bank transfer details",
"description": "Your students see them when they report a payment",
"alias": "Account or payment alias",
"aliasShort": "Account",
"holder": "Account holder",
"saved": "Bank transfer details saved",
"saveError": "We couldn't save the details"
},
"callback": {
"mpLinked": "Your Mercado Pago account is linked.",
"whatsappLinked": "Your WhatsApp is linked."
}
}

View File

@@ -0,0 +1,52 @@
{
"zod": {
"required": "This field is required",
"invalidType": "This value isn't valid",
"invalid": "This value isn't valid",
"tooShort": "It's too short",
"tooLong": "It's too long",
"tooSmall": "The value is too low",
"tooBig": "The value is too high"
},
"email": {
"invalid": "Enter a valid email"
},
"phone": {
"invalid": "Enter a valid phone number"
},
"name": {
"required": "Name is required",
"enter": "Enter your name"
},
"password": {
"min": "The password must be at least 8 characters",
"mismatch": "The passwords don't match"
},
"update": {
"empty": "Send at least one field to update"
},
"group": {
"nameMin": "The name must be at least 3 characters",
"nameMax": "The name is too long (60 characters max)",
"daysMin": "Choose at least one class day",
"timeInvalid": "Choose a valid time (e.g. 09:00)",
"capacityInvalid": "Enter a valid capacity",
"capacityInt": "Capacity must be a whole number",
"capacityMin": "Capacity must be at least 1",
"priceInvalid": "Enter a valid price",
"priceMin": "The price can't be negative",
"dueDayInvalid": "Enter a valid day",
"dueDayInt": "The day must be a whole number",
"dueDayRange": "The due day must be between 1 and 28"
},
"whatsapp": {
"phoneRequired": "Enter your WhatsApp number",
"automationRequired": "Pick at least one automation"
},
"timezone": {
"invalid": "Invalid time zone"
},
"payment": {
"descriptionMax": "The description is too long"
}
}

View File

@@ -0,0 +1,65 @@
{
"email": "Email",
"emailPlaceholder": "tu@ejemplo.com",
"password": "Contraseña",
"or": "o",
"continueWithGoogle": "Continuar con Google",
"backToLogin": "Volver a iniciar sesión",
"login": {
"title": "Iniciar sesión",
"subtitle": "Accede a tus cobros grupales",
"resetOk": "Tu contraseña se actualizó. Ingresa con la nueva.",
"forgot": "¿Olvidaste tu contraseña?",
"submit": "Ingresar",
"submitting": "Ingresando…",
"passkey": "Entrar con passkey",
"noAccount": "¿No tienes cuenta?",
"signUp": "Regístrate",
"error": "No se pudo iniciar sesión",
"passkeyError": "No se pudo autenticar con passkey"
},
"signup": {
"title": "Crear cuenta",
"subtitle": "Empieza a cobrar en grupo en minutos",
"name": "Nombre",
"namePlaceholder": "Nombre completo",
"passwordPlaceholder": "Mínimo 8 caracteres",
"confirmPassword": "Repite la contraseña",
"submit": "Crear cuenta",
"submitting": "Creando…",
"hasAccount": "¿Ya tienes cuenta?",
"signIn": "Inicia sesión",
"error": "No se pudo registrar"
},
"forgot": {
"title": "Recuperar contraseña",
"subtitle": "Te enviamos un enlace para elegir una nueva",
"submit": "Enviar enlace",
"submitting": "Enviando…",
"sentTitle": "Revisa tu email",
"sent": "Si hay una cuenta con <strong>{{email}}</strong>, te enviamos un enlace para elegir una nueva contraseña. Vence en 1 hora.",
"error": "No se pudo enviar el email"
},
"reset": {
"title": "Nueva contraseña",
"subtitle": "Elige una contraseña para tu cuenta",
"newPassword": "Nueva contraseña",
"confirmPassword": "Repetir contraseña",
"submit": "Guardar contraseña",
"submitting": "Guardando…",
"invalidTitle": "Enlace inválido",
"invalid": "El enlace para restablecer la contraseña no es válido o venció.",
"requestNew": "Pedir un enlace nuevo",
"error": "No se pudo cambiar la contraseña"
},
"verify": {
"title": "Verifica tu email",
"successTitle": "Email verificado",
"errorTitle": "Enlace inválido",
"success": "Tu cuenta quedó verificada. Te estamos llevando a Gruperly…",
"error": "El enlace de verificación no es válido o expiró.",
"sent": "Te enviamos un correo a <strong>{{email}}</strong> para confirmar tu cuenta.",
"goToApp": "Ir a Gruperly",
"tryLogin": "Intentar iniciar sesión"
}
}

View File

@@ -0,0 +1,42 @@
{
"actions": {
"cancel": "Cancelar",
"save": "Guardar",
"edit": "Editar",
"add": "Agregar",
"close": "Cerrar",
"back": "Volver",
"retry": "Reintentar"
},
"user": {
"fallbackName": "Usuario"
},
"toast": {
"close": "Cerrar notificación"
},
"weekDay": {
"MONDAY": "Lunes",
"TUESDAY": "Martes",
"WEDNESDAY": "Miércoles",
"THURSDAY": "Jueves",
"FRIDAY": "Viernes",
"SATURDAY": "Sábado",
"SUNDAY": "Domingo"
},
"billingType": {
"MONTHLY": "Mensual",
"PER_CLASS": "Por clase"
},
"paymentStatus": {
"PENDING": "Pendiente",
"PAID": "Pagado",
"OVERDUE": "Vencido",
"CANCELLED": "Cancelado"
},
"relativeDay": {
"today": "Hoy · {{time}}",
"tomorrow": "Mañana · {{time}}",
"other": "{{date}} · {{time}}"
},
"billingDueDay": "Vence el día {{day}} de cada mes"
}

View File

@@ -0,0 +1,79 @@
{
"generic": "Algo salió mal. Inténtalo de nuevo.",
"network": "No hay conexión. Revisa tu internet e inténtalo de nuevo.",
"status": {
"unauthorized": "Tu sesión venció. Vuelve a iniciar sesión.",
"forbidden": "No tienes permiso para hacer esto.",
"notFound": "No encontramos lo que buscabas.",
"tooManyRequests": "Hiciste muchas solicitudes seguidas. Inténtalo de nuevo en unos minutos.",
"server": "Tuvimos un problema. Inténtalo de nuevo en unos minutos."
},
"codes": {
"admin_required": "Solo el equipo de Gruperly puede entrar al backoffice.",
"already_waitlisted": "Este número de teléfono ya está en la lista de espera del grupo.",
"attendee_already_registered": "Esta persona ya es miembro de este grupo.",
"attendee_has_payments": "Este miembro tiene cobros asociados. Gestiona o cancela sus cobros antes de quitarlo del grupo.",
"attendee_same_group": "El miembro ya pertenece a este grupo.",
"billing_not_available": "La suscripción a Pro todavía no está disponible en tu país.",
"billing_provider_error": "No pudimos comunicarnos con el procesador de pagos. Inténtalo de nuevo en unos minutos.",
"class_already_started": "La clase ya empezó: el aviso solo se puede dar o deshacer antes.",
"cross_origin_request": "Origen no permitido.",
"database_unavailable": "Tuvimos un problema. Inténtalo de nuevo en unos minutos.",
"group_access_denied": "No tienes acceso a este grupo.",
"group_capacity_reached": "El grupo alcanzó su cupo máximo de miembros.",
"group_capacity_reached_one": "El grupo alcanzó su cupo máximo de {{count}} miembro.",
"group_capacity_reached_other": "El grupo alcanzó su cupo máximo de {{count}} miembros.",
"group_owner_required": "Solo quien creó el grupo puede cambiar sus automatizaciones.",
"group_without_price": "Define el precio del grupo antes de generar los cobros.",
"mp_account_in_use": "Esa cuenta de Mercado Pago ya está vinculada a otro profesor.",
"mp_not_configured": "La vinculación con Mercado Pago no está disponible en este momento.",
"mp_not_connected": "No tienes una cuenta de Mercado Pago vinculada.",
"mp_provider_error": "No pudimos completar la vinculación con Mercado Pago.",
"mp_requires_reauth": "Tu cuenta de Mercado Pago necesita volver a vincularse.",
"no_active_subscription": "No tienes una suscripción para cancelar.",
"no_attendees_to_bill": "No hay miembros activos con un cobro pendiente para este grupo.",
"onboarding_already_completed": "Ya completaste la configuración inicial de Gruperly.",
"passkey_invalid": "No pudimos verificar la llave de acceso.",
"payment_already_reported": "Ya informaste el pago de alguna de estas cuotas.",
"payment_report_already_reviewed": "Este pago ya fue revisado.",
"person_exists": "Ya tienes registrada a una persona con este número de teléfono.",
"person_phone_taken": "Otra persona que tienes registrada ya usa este número de teléfono.",
"plan_feature_required": "Esta función está disponible en el plan Pro.",
"plan_feature_required_mpCharges": "Cobrar con Mercado Pago está disponible en el plan Pro.",
"plan_feature_required_whatsappAutomations": "Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.",
"plan_limit_reached": "Llegaste al límite del plan Free. Cámbiate a Pro para seguir creciendo.",
"plan_limit_reached_groups_one": "El plan Free permite hasta {{count}} grupo. Cámbiate a Pro para crear más.",
"plan_limit_reached_groups_other": "El plan Free permite hasta {{count}} grupos. Cámbiate a Pro para crear más.",
"plan_limit_reached_attendees_one": "El plan Free permite hasta {{count}} alumno activo. Cámbiate a Pro para sumar más.",
"plan_limit_reached_attendees_other": "El plan Free permite hasta {{count}} alumnos activos. Cámbiate a Pro para sumar más.",
"plan_not_selected": "Elige un plan antes de crear tu primer grupo.",
"plan_read_only": "Tu cuenta está en solo lectura porque superas los límites del plan Free. Cámbiate a Pro o reduce el uso para volver a editar.",
"pre_registration_already_reviewed": "Esta preinscripción ya fue revisada.",
"review_undo_expired": "Ya no se puede deshacer.",
"storage_not_available": "Por ahora no se pueden adjuntar comprobantes.",
"student_link_invalid": "Este enlace ya se usó o venció.",
"subscription_already_active": "Ya tienes una suscripción a Pro activa.",
"too_many_requests": "Hiciste muchas solicitudes seguidas. Inténtalo de nuevo en unos minutos.",
"unauthorized": "Tu sesión venció. Vuelve a iniciar sesión.",
"user_not_found": "Usuario no encontrado.",
"whatsapp_linking_not_started": "Empieza la vinculación de WhatsApp antes de pedir el código.",
"whatsapp_not_configured": "La vinculación con WhatsApp no está disponible en este momento.",
"whatsapp_not_connected": "No tienes un WhatsApp vinculado.",
"whatsapp_number_in_use": "Ese número de WhatsApp ya está vinculado a otro profesor.",
"whatsapp_pairing_not_ready": "WhatsApp todavía está preparando la vinculación. Inténtalo de nuevo en unos segundos.",
"whatsapp_pairing_unsupported": "Este proveedor de WhatsApp no permite vincular con el número de teléfono.",
"whatsapp_provider_error": "No pudimos comunicarnos con WhatsApp. Inténtalo de nuevo en unos minutos."
},
"auth": {
"INVALID_EMAIL_OR_PASSWORD": "El email o la contraseña no son correctos.",
"EMAIL_NOT_VERIFIED": "Todavía no verificaste tu email. Revisa tu correo.",
"USER_ALREADY_EXISTS": "Ya hay una cuenta con ese email.",
"USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL": "Ya hay una cuenta con ese email.",
"INVALID_EMAIL": "Ingresa un email válido.",
"PASSWORD_TOO_SHORT": "La contraseña debe tener al menos 8 caracteres.",
"PASSWORD_TOO_LONG": "La contraseña es demasiado larga.",
"INVALID_PASSWORD": "La contraseña actual no es correcta.",
"INVALID_TOKEN": "El enlace no es válido o venció.",
"TOO_MANY_REQUESTS": "Hiciste muchas solicitudes seguidas. Inténtalo de nuevo en unos minutos."
}
}

View File

@@ -0,0 +1,26 @@
{
"nav": {
"home": "Inicio",
"groups": "Grupos",
"payments": "Cobros",
"settings": "Ajustes",
"security": "Seguridad",
"profile": "Mi perfil"
},
"breadcrumb": "Ruta de navegación",
"homeLink": "Gruperly inicio",
"reportedPayments_one": "{{count}} pago por verificar",
"reportedPayments_other": "{{count}} pagos por verificar",
"theme": {
"toLight": "Cambiar a tema claro",
"toDark": "Cambiar a tema oscuro"
},
"userMenu": {
"close": "Cerrar menú",
"profile": "Mi perfil",
"settings": "Ajustes",
"admin": "Backoffice",
"signOut": "Cerrar sesión"
},
"publicFooter": "Gruperly — Gestión sencilla de cobros y grupos"
}

View File

@@ -0,0 +1,18 @@
{
"banner": {
"title": "Instala Gruperly",
"description": "Ábrela directo desde tu pantalla de inicio, sin barra del navegador.",
"install": "Instalar app",
"later": "Ahora no",
"close": "Cerrar aviso de instalación"
},
"ios": {
"title": "Instala Gruperly en el iPhone",
"description": "Toca <strong>Compartir</strong> y elige <strong>Agregar a pantalla de inicio</strong> para abrirla como app."
},
"offlineReady": "La app quedó lista para abrirse sin conexión",
"offlineReadyDetail": "Ya puedes usar Gruperly sin conexión.",
"installed": "App instalada",
"installedDetail": "Ahora tienes Gruperly en tu pantalla de inicio.",
"installLater": "Puedes instalarla más adelante desde el menú del navegador."
}

View File

@@ -0,0 +1,39 @@
{
"title": "Ajustes",
"subtitle": "Configura tu cuenta y tus grupos.",
"security": {
"title": "Seguridad",
"description": "Contraseña y passkeys"
},
"signOut": "Cerrar sesión",
"appearance": {
"title": "Apariencia",
"description": "Tema claro u oscuro",
"light": "Claro",
"lightDescription": "Interfaz en tonos claros",
"dark": "Oscuro",
"darkDescription": "Interfaz en tonos oscuros",
"system": "Sistema",
"systemDescription": "Sigue la preferencia de tu dispositivo"
},
"language": {
"title": "Idioma",
"description": "El idioma de la app",
"system": "Idioma del dispositivo",
"systemDescription": "Ahora: {{language}}",
"saveError": "No pudimos guardar el idioma en tu cuenta"
},
"transfer": {
"title": "Datos para transferencias",
"description": "Tus alumnos los ven cuando informan un pago",
"alias": "Alias, CLABE o número de cuenta",
"aliasShort": "Cuenta",
"holder": "Titular",
"saved": "Datos para transferencias guardados",
"saveError": "No pudimos guardar los datos"
},
"callback": {
"mpLinked": "Tu cuenta de Mercado Pago quedó vinculada.",
"whatsappLinked": "Tu WhatsApp quedó vinculado."
}
}

View File

@@ -0,0 +1,52 @@
{
"zod": {
"required": "Este campo es obligatorio",
"invalidType": "El valor no es válido",
"invalid": "El valor no es válido",
"tooShort": "Es demasiado corto",
"tooLong": "Es demasiado largo",
"tooSmall": "El valor es demasiado pequeño",
"tooBig": "El valor es demasiado grande"
},
"email": {
"invalid": "Ingresa un email válido"
},
"phone": {
"invalid": "Ingresa un número de teléfono válido"
},
"name": {
"required": "El nombre es obligatorio",
"enter": "Ingresa tu nombre"
},
"password": {
"min": "La contraseña debe tener al menos 8 caracteres",
"mismatch": "Las contraseñas no coinciden"
},
"update": {
"empty": "Envía al menos un campo para actualizar"
},
"group": {
"nameMin": "El nombre debe tener al menos 3 caracteres",
"nameMax": "El nombre es demasiado largo (máximo 60 caracteres)",
"daysMin": "Elige al menos un día de clase",
"timeInvalid": "Elige un horario válido (ej.: 09:00)",
"capacityInvalid": "Ingresa un cupo válido",
"capacityInt": "El cupo debe ser un número entero",
"capacityMin": "El cupo debe ser de al menos 1",
"priceInvalid": "Ingresa un precio válido",
"priceMin": "El precio no puede ser negativo",
"dueDayInvalid": "Ingresa un día válido",
"dueDayInt": "El día debe ser un número entero",
"dueDayRange": "El día de vencimiento debe estar entre 1 y 28"
},
"whatsapp": {
"phoneRequired": "Ingresa tu número de WhatsApp",
"automationRequired": "Indica al menos una automatización"
},
"timezone": {
"invalid": "Zona horaria inválida"
},
"payment": {
"descriptionMax": "La descripción es demasiado larga"
}
}

View File

@@ -0,0 +1,65 @@
{
"email": "Email",
"emailPlaceholder": "vos@ejemplo.com",
"password": "Contraseña",
"or": "o",
"continueWithGoogle": "Continuar con Google",
"backToLogin": "Volver a iniciar sesión",
"login": {
"title": "Iniciar sesión",
"subtitle": "Accedé a tus cobros grupales",
"resetOk": "Tu contraseña se actualizó. Ingresá con la nueva.",
"forgot": "¿Olvidaste tu contraseña?",
"submit": "Ingresar",
"submitting": "Ingresando…",
"passkey": "Entrar con passkey",
"noAccount": "¿No tenés cuenta?",
"signUp": "Registrate",
"error": "No se pudo iniciar sesión",
"passkeyError": "No se pudo autenticar con passkey"
},
"signup": {
"title": "Crear cuenta",
"subtitle": "Empezá a cobrar en grupo en minutos",
"name": "Nombre",
"namePlaceholder": "Nombre completo",
"passwordPlaceholder": "Mínimo 8 caracteres",
"confirmPassword": "Repetí la contraseña",
"submit": "Crear cuenta",
"submitting": "Creando…",
"hasAccount": "¿Ya tenés cuenta?",
"signIn": "Iniciá sesión",
"error": "No se pudo registrar"
},
"forgot": {
"title": "Recuperar contraseña",
"subtitle": "Te enviamos un enlace para elegir una nueva",
"submit": "Enviar enlace",
"submitting": "Enviando…",
"sentTitle": "Revisá tu email",
"sent": "Si hay una cuenta con <strong>{{email}}</strong>, te enviamos un enlace para elegir una nueva contraseña. Vence en 1 hora.",
"error": "No se pudo enviar el email"
},
"reset": {
"title": "Nueva contraseña",
"subtitle": "Elegí una contraseña para tu cuenta",
"newPassword": "Nueva contraseña",
"confirmPassword": "Repetir contraseña",
"submit": "Guardar contraseña",
"submitting": "Guardando…",
"invalidTitle": "Vínculo inválido",
"invalid": "El enlace para restablecer la contraseña no es válido o venció.",
"requestNew": "Pedir un enlace nuevo",
"error": "No se pudo cambiar la contraseña"
},
"verify": {
"title": "Verificá tu email",
"successTitle": "Email verificado",
"errorTitle": "Vínculo inválido",
"success": "Tu cuenta quedó verificada. Te estamos llevando a Gruperly…",
"error": "El vínculo de verificación no es válido o expiró.",
"sent": "Te enviamos un correo a <strong>{{email}}</strong> para confirmar tu cuenta.",
"goToApp": "Ir a Gruperly",
"tryLogin": "Intentar iniciar sesión"
}
}

View File

@@ -0,0 +1,42 @@
{
"actions": {
"cancel": "Cancelar",
"save": "Guardar",
"edit": "Editar",
"add": "Agregar",
"close": "Cerrar",
"back": "Volver",
"retry": "Reintentar"
},
"user": {
"fallbackName": "Usuario"
},
"toast": {
"close": "Cerrar notificación"
},
"weekDay": {
"MONDAY": "Lunes",
"TUESDAY": "Martes",
"WEDNESDAY": "Miércoles",
"THURSDAY": "Jueves",
"FRIDAY": "Viernes",
"SATURDAY": "Sábado",
"SUNDAY": "Domingo"
},
"billingType": {
"MONTHLY": "Mensual",
"PER_CLASS": "Por clase"
},
"paymentStatus": {
"PENDING": "Pendiente",
"PAID": "Pagado",
"OVERDUE": "Vencido",
"CANCELLED": "Cancelado"
},
"relativeDay": {
"today": "Hoy · {{time}}",
"tomorrow": "Mañana · {{time}}",
"other": "{{date}} · {{time}}"
},
"billingDueDay": "Vence el día {{day}} de cada mes"
}

View File

@@ -0,0 +1,79 @@
{
"generic": "Algo salió mal. Probá de nuevo.",
"network": "No hay conexión. Revisá tu internet y probá de nuevo.",
"status": {
"unauthorized": "Tu sesión venció. Volvé a iniciar sesión.",
"forbidden": "No tenés permiso para hacer esto.",
"notFound": "No encontramos lo que buscabas.",
"tooManyRequests": "Hiciste muchos pedidos seguidos. Probá de nuevo en unos minutos.",
"server": "Tuvimos un problema. Probá de nuevo en unos minutos."
},
"codes": {
"admin_required": "Solo el equipo de Gruperly puede entrar al backoffice.",
"already_waitlisted": "Este número de teléfono ya está en la lista de espera del grupo.",
"attendee_already_registered": "Esta persona ya es miembro de este grupo.",
"attendee_has_payments": "Este miembro tiene cobros asociados. Gestioná o cancelá sus cobros antes de quitarlo del grupo.",
"attendee_same_group": "El miembro ya pertenece a este grupo.",
"billing_not_available": "La suscripción a Pro todavía no está disponible en tu país.",
"billing_provider_error": "No pudimos comunicarnos con el procesador de pagos. Intentá de nuevo en unos minutos.",
"class_already_started": "La clase ya empezó: el aviso solo se puede dar o deshacer antes.",
"cross_origin_request": "Origen no permitido.",
"database_unavailable": "Tuvimos un problema. Probá de nuevo en unos minutos.",
"group_access_denied": "No tenés acceso a este grupo.",
"group_capacity_reached": "El grupo alcanzó su cupo máximo de miembros.",
"group_capacity_reached_one": "El grupo alcanzó su cupo máximo de {{count}} miembro.",
"group_capacity_reached_other": "El grupo alcanzó su cupo máximo de {{count}} miembros.",
"group_owner_required": "Solo quien creó el grupo puede cambiar sus automatizaciones.",
"group_without_price": "Definí el precio del grupo antes de generar los cobros.",
"mp_account_in_use": "Esa cuenta de Mercado Pago ya está vinculada a otro profesor.",
"mp_not_configured": "La vinculación con Mercado Pago no está disponible en este momento.",
"mp_not_connected": "No tenés una cuenta de Mercado Pago vinculada.",
"mp_provider_error": "No pudimos completar la vinculación con Mercado Pago.",
"mp_requires_reauth": "Tu cuenta de Mercado Pago necesita volver a vincularse.",
"no_active_subscription": "No tenés una suscripción para cancelar.",
"no_attendees_to_bill": "No hay miembros activos con un cobro pendiente para este grupo.",
"onboarding_already_completed": "Ya completaste el onboarding de Gruperly.",
"passkey_invalid": "No pudimos verificar la llave de acceso.",
"payment_already_reported": "Ya informaste el pago de alguna de estas cuotas.",
"payment_report_already_reviewed": "Este pago ya fue revisado.",
"person_exists": "Ya tenés registrada a una persona con este número de teléfono.",
"person_phone_taken": "Otra persona que tenés registrada ya usa este número de teléfono.",
"plan_feature_required": "Esta función está disponible en el plan Pro.",
"plan_feature_required_mpCharges": "Cobrar con Mercado Pago está disponible en el plan Pro.",
"plan_feature_required_whatsappAutomations": "Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.",
"plan_limit_reached": "Llegaste al límite del plan Free. Pasate a Pro para seguir creciendo.",
"plan_limit_reached_groups_one": "El plan Free permite hasta {{count}} grupo. Pasate a Pro para crear más.",
"plan_limit_reached_groups_other": "El plan Free permite hasta {{count}} grupos. Pasate a Pro para crear más.",
"plan_limit_reached_attendees_one": "El plan Free permite hasta {{count}} alumno activo. Pasate a Pro para sumar más.",
"plan_limit_reached_attendees_other": "El plan Free permite hasta {{count}} alumnos activos. Pasate a Pro para sumar más.",
"plan_not_selected": "Elegí un plan antes de crear tu primer grupo.",
"plan_read_only": "Tu cuenta está en solo lectura porque superás los límites del plan Free. Pasate a Pro o reducí el uso para volver a editar.",
"pre_registration_already_reviewed": "Esta pre-inscripción ya fue revisada.",
"review_undo_expired": "Ya no se puede deshacer.",
"storage_not_available": "Por ahora no se pueden adjuntar comprobantes.",
"student_link_invalid": "Este link ya fue usado o venció.",
"subscription_already_active": "Ya tenés una suscripción a Pro activa.",
"too_many_requests": "Hiciste muchos pedidos seguidos. Probá de nuevo en unos minutos.",
"unauthorized": "Tu sesión venció. Volvé a iniciar sesión.",
"user_not_found": "Usuario no encontrado.",
"whatsapp_linking_not_started": "Empezá la vinculación de WhatsApp antes de pedir el código.",
"whatsapp_not_configured": "La vinculación con WhatsApp no está disponible en este momento.",
"whatsapp_not_connected": "No tenés un WhatsApp vinculado.",
"whatsapp_number_in_use": "Ese número de WhatsApp ya está vinculado a otro profesor.",
"whatsapp_pairing_not_ready": "WhatsApp todavía está preparando la vinculación. Intentá de nuevo en unos segundos.",
"whatsapp_pairing_unsupported": "Este proveedor de WhatsApp no permite vincular con el número de teléfono.",
"whatsapp_provider_error": "No pudimos comunicarnos con WhatsApp. Intentá de nuevo en unos minutos."
},
"auth": {
"INVALID_EMAIL_OR_PASSWORD": "El email o la contraseña no son correctos.",
"EMAIL_NOT_VERIFIED": "Todavía no verificaste tu email. Revisá tu correo.",
"USER_ALREADY_EXISTS": "Ya hay una cuenta con ese email.",
"USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL": "Ya hay una cuenta con ese email.",
"INVALID_EMAIL": "Ingresá un email válido.",
"PASSWORD_TOO_SHORT": "La contraseña debe tener al menos 8 caracteres.",
"PASSWORD_TOO_LONG": "La contraseña es demasiado larga.",
"INVALID_PASSWORD": "La contraseña actual no es correcta.",
"INVALID_TOKEN": "El enlace no es válido o venció.",
"TOO_MANY_REQUESTS": "Hiciste muchos pedidos seguidos. Probá de nuevo en unos minutos."
}
}

View File

@@ -0,0 +1,26 @@
{
"nav": {
"home": "Inicio",
"groups": "Grupos",
"payments": "Cobros",
"settings": "Ajustes",
"security": "Seguridad",
"profile": "Mi perfil"
},
"breadcrumb": "Ruta de navegación",
"homeLink": "Gruperly inicio",
"reportedPayments_one": "{{count}} pago para verificar",
"reportedPayments_other": "{{count}} pagos para verificar",
"theme": {
"toLight": "Cambiar a tema claro",
"toDark": "Cambiar a tema oscuro"
},
"userMenu": {
"close": "Cerrar menú",
"profile": "Mi perfil",
"settings": "Ajustes",
"admin": "Backoffice",
"signOut": "Cerrar sesión"
},
"publicFooter": "Gruperly — Gestión sencilla de cobros y grupos"
}

View File

@@ -0,0 +1,18 @@
{
"banner": {
"title": "Instalá Gruperly",
"description": "Abrila directo desde tu pantalla de inicio, sin barra de navegador.",
"install": "Instalar app",
"later": "Ahora no",
"close": "Cerrar aviso de instalación"
},
"ios": {
"title": "Instalá Gruperly en el iPhone",
"description": "Tocá <strong>Compartir</strong> y elegí <strong>Agregar a pantalla de inicio</strong> para abrirla como app."
},
"offlineReady": "La app quedó lista para abrirse sin conexión",
"offlineReadyDetail": "Ya podés usar Gruperly offline.",
"installed": "App instalada",
"installedDetail": "Ahora tenés Gruperly en tu pantalla de inicio.",
"installLater": "Podés instalarla más adelante desde el menú del navegador."
}

View File

@@ -0,0 +1,39 @@
{
"title": "Ajustes",
"subtitle": "Configurá tu cuenta y tus grupos.",
"security": {
"title": "Seguridad",
"description": "Contraseña y passkeys"
},
"signOut": "Cerrar sesión",
"appearance": {
"title": "Apariencia",
"description": "Tema claro u oscuro",
"light": "Claro",
"lightDescription": "Interfaz en tonos claros",
"dark": "Oscuro",
"darkDescription": "Interfaz en tonos oscuros",
"system": "Sistema",
"systemDescription": "Sigue la preferencia de tu dispositivo"
},
"language": {
"title": "Idioma",
"description": "El idioma de la app",
"system": "Idioma del dispositivo",
"systemDescription": "Ahora: {{language}}",
"saveError": "No pudimos guardar el idioma en tu cuenta"
},
"transfer": {
"title": "Datos para transferir",
"description": "Los ven tus alumnos cuando informan un pago",
"alias": "Alias o CBU/CVU",
"aliasShort": "Alias",
"holder": "Titular",
"saved": "Datos para transferir guardados",
"saveError": "No pudimos guardar los datos"
},
"callback": {
"mpLinked": "Tu cuenta de Mercado Pago quedó vinculada.",
"whatsappLinked": "Tu WhatsApp quedó vinculado."
}
}

View File

@@ -0,0 +1,52 @@
{
"zod": {
"required": "Este campo es obligatorio",
"invalidType": "El valor no es válido",
"invalid": "El valor no es válido",
"tooShort": "Es demasiado corto",
"tooLong": "Es demasiado largo",
"tooSmall": "El valor es demasiado chico",
"tooBig": "El valor es demasiado grande"
},
"email": {
"invalid": "Ingresá un email válido"
},
"phone": {
"invalid": "Ingresá un número de teléfono válido"
},
"name": {
"required": "El nombre es obligatorio",
"enter": "Ingresá tu nombre"
},
"password": {
"min": "La contraseña debe tener al menos 8 caracteres",
"mismatch": "Las contraseñas no coinciden"
},
"update": {
"empty": "Enviá al menos un campo para actualizar"
},
"group": {
"nameMin": "El nombre debe tener al menos 3 caracteres",
"nameMax": "El nombre es demasiado largo (máximo 60 caracteres)",
"daysMin": "Elegí al menos un día de clase",
"timeInvalid": "Elegí un horario válido (ej: 09:00)",
"capacityInvalid": "Ingresá un cupo válido",
"capacityInt": "El cupo debe ser un número entero",
"capacityMin": "El cupo debe ser al menos 1",
"priceInvalid": "Ingresá un precio válido",
"priceMin": "El precio no puede ser negativo",
"dueDayInvalid": "Ingresá un día válido",
"dueDayInt": "El día debe ser un número entero",
"dueDayRange": "El día de vencimiento debe estar entre 1 y 28"
},
"whatsapp": {
"phoneRequired": "Ingresá tu número de WhatsApp",
"automationRequired": "Indicá al menos una automatización"
},
"timezone": {
"invalid": "Zona horaria inválida"
},
"payment": {
"descriptionMax": "La descripción es demasiado larga"
}
}

View File

@@ -0,0 +1,65 @@
{
"email": "E-mail",
"emailPlaceholder": "voce@exemplo.com",
"password": "Senha",
"or": "ou",
"continueWithGoogle": "Continuar com o Google",
"backToLogin": "Voltar para o login",
"login": {
"title": "Entrar",
"subtitle": "Acesse suas cobranças em grupo",
"resetOk": "Sua senha foi atualizada. Entre com a nova.",
"forgot": "Esqueceu sua senha?",
"submit": "Entrar",
"submitting": "Entrando…",
"passkey": "Entrar com passkey",
"noAccount": "Não tem uma conta?",
"signUp": "Cadastre-se",
"error": "Não foi possível entrar",
"passkeyError": "Não foi possível autenticar com a passkey"
},
"signup": {
"title": "Criar conta",
"subtitle": "Comece a cobrar seus grupos em minutos",
"name": "Nome",
"namePlaceholder": "Nome completo",
"passwordPlaceholder": "Mínimo de 8 caracteres",
"confirmPassword": "Repita a senha",
"submit": "Criar conta",
"submitting": "Criando…",
"hasAccount": "Já tem uma conta?",
"signIn": "Entre",
"error": "Não foi possível cadastrar"
},
"forgot": {
"title": "Recuperar senha",
"subtitle": "Enviamos um link para você escolher uma nova",
"submit": "Enviar link",
"submitting": "Enviando…",
"sentTitle": "Confira seu e-mail",
"sent": "Se houver uma conta com <strong>{{email}}</strong>, enviamos um link para escolher uma nova senha. Ele vence em 1 hora.",
"error": "Não foi possível enviar o e-mail"
},
"reset": {
"title": "Nova senha",
"subtitle": "Escolha uma senha para sua conta",
"newPassword": "Nova senha",
"confirmPassword": "Repetir senha",
"submit": "Salvar senha",
"submitting": "Salvando…",
"invalidTitle": "Link inválido",
"invalid": "O link para redefinir a senha não é válido ou expirou.",
"requestNew": "Pedir um novo link",
"error": "Não foi possível alterar a senha"
},
"verify": {
"title": "Confirme seu e-mail",
"successTitle": "E-mail confirmado",
"errorTitle": "Link inválido",
"success": "Sua conta foi confirmada. Estamos levando você ao Gruperly…",
"error": "O link de confirmação não é válido ou expirou.",
"sent": "Enviamos um e-mail para <strong>{{email}}</strong> para confirmar sua conta.",
"goToApp": "Ir para o Gruperly",
"tryLogin": "Tentar entrar"
}
}

View File

@@ -0,0 +1,42 @@
{
"actions": {
"cancel": "Cancelar",
"save": "Salvar",
"edit": "Editar",
"add": "Adicionar",
"close": "Fechar",
"back": "Voltar",
"retry": "Tentar novamente"
},
"user": {
"fallbackName": "Usuário"
},
"toast": {
"close": "Fechar notificação"
},
"weekDay": {
"MONDAY": "Segunda-feira",
"TUESDAY": "Terça-feira",
"WEDNESDAY": "Quarta-feira",
"THURSDAY": "Quinta-feira",
"FRIDAY": "Sexta-feira",
"SATURDAY": "Sábado",
"SUNDAY": "Domingo"
},
"billingType": {
"MONTHLY": "Mensal",
"PER_CLASS": "Por aula"
},
"paymentStatus": {
"PENDING": "Pendente",
"PAID": "Pago",
"OVERDUE": "Vencido",
"CANCELLED": "Cancelado"
},
"relativeDay": {
"today": "Hoje · {{time}}",
"tomorrow": "Amanhã · {{time}}",
"other": "{{date}} · {{time}}"
},
"billingDueDay": "Vence todo dia {{day}}"
}

View File

@@ -0,0 +1,79 @@
{
"generic": "Algo deu errado. Tente novamente.",
"network": "Sem conexão. Verifique sua internet e tente novamente.",
"status": {
"unauthorized": "Sua sessão expirou. Entre novamente.",
"forbidden": "Você não tem permissão para fazer isso.",
"notFound": "Não encontramos o que você procurava.",
"tooManyRequests": "Você fez muitas solicitações seguidas. Tente novamente em alguns minutos.",
"server": "Tivemos um problema. Tente novamente em alguns minutos."
},
"codes": {
"admin_required": "Só a equipe do Gruperly pode acessar o backoffice.",
"already_waitlisted": "Este número de telefone já está na lista de espera do grupo.",
"attendee_already_registered": "Esta pessoa já é membro deste grupo.",
"attendee_has_payments": "Este membro tem cobranças associadas. Gerencie ou cancele as cobranças antes de removê-lo do grupo.",
"attendee_same_group": "O membro já faz parte deste grupo.",
"billing_not_available": "A assinatura Pro ainda não está disponível no seu país.",
"billing_provider_error": "Não conseguimos falar com o processador de pagamentos. Tente novamente em alguns minutos.",
"class_already_started": "A aula já começou: o aviso só pode ser dado ou desfeito antes.",
"cross_origin_request": "Origem não permitida.",
"database_unavailable": "Tivemos um problema. Tente novamente em alguns minutos.",
"group_access_denied": "Você não tem acesso a este grupo.",
"group_capacity_reached": "O grupo atingiu o limite máximo de membros.",
"group_capacity_reached_one": "O grupo atingiu o limite máximo de {{count}} membro.",
"group_capacity_reached_other": "O grupo atingiu o limite máximo de {{count}} membros.",
"group_owner_required": "Só quem criou o grupo pode mudar as automações.",
"group_without_price": "Defina o preço do grupo antes de gerar as cobranças.",
"mp_account_in_use": "Essa conta do Mercado Pago já está vinculada a outro professor.",
"mp_not_configured": "A vinculação com o Mercado Pago não está disponível no momento.",
"mp_not_connected": "Você não tem uma conta do Mercado Pago vinculada.",
"mp_provider_error": "Não conseguimos concluir a vinculação com o Mercado Pago.",
"mp_requires_reauth": "Sua conta do Mercado Pago precisa ser vinculada novamente.",
"no_active_subscription": "Você não tem uma assinatura para cancelar.",
"no_attendees_to_bill": "Não há membros ativos com cobrança pendente neste grupo.",
"onboarding_already_completed": "Você já concluiu a configuração inicial do Gruperly.",
"passkey_invalid": "Não conseguimos verificar a chave de acesso.",
"payment_already_reported": "Você já informou o pagamento de alguma dessas parcelas.",
"payment_report_already_reviewed": "Este pagamento já foi revisado.",
"person_exists": "Você já tem uma pessoa cadastrada com este número de telefone.",
"person_phone_taken": "Outra pessoa cadastrada já usa este número de telefone.",
"plan_feature_required": "Este recurso está disponível no plano Pro.",
"plan_feature_required_mpCharges": "Cobrar pelo Mercado Pago está disponível no plano Pro.",
"plan_feature_required_whatsappAutomations": "As mensagens automáticas de WhatsApp estão disponíveis no plano Pro.",
"plan_limit_reached": "Você atingiu o limite do plano Free. Mude para o Pro para continuar crescendo.",
"plan_limit_reached_groups_one": "O plano Free permite até {{count}} grupo. Mude para o Pro para criar mais.",
"plan_limit_reached_groups_other": "O plano Free permite até {{count}} grupos. Mude para o Pro para criar mais.",
"plan_limit_reached_attendees_one": "O plano Free permite até {{count}} aluno ativo. Mude para o Pro para adicionar mais.",
"plan_limit_reached_attendees_other": "O plano Free permite até {{count}} alunos ativos. Mude para o Pro para adicionar mais.",
"plan_not_selected": "Escolha um plano antes de criar seu primeiro grupo.",
"plan_read_only": "Sua conta está somente leitura porque ultrapassa os limites do plano Free. Mude para o Pro ou reduza o uso para voltar a editar.",
"pre_registration_already_reviewed": "Esta pré-inscrição já foi revisada.",
"review_undo_expired": "Não é mais possível desfazer.",
"storage_not_available": "Por enquanto não é possível anexar comprovantes.",
"student_link_invalid": "Este link já foi usado ou expirou.",
"subscription_already_active": "Você já tem uma assinatura Pro ativa.",
"too_many_requests": "Você fez muitas solicitações seguidas. Tente novamente em alguns minutos.",
"unauthorized": "Sua sessão expirou. Entre novamente.",
"user_not_found": "Usuário não encontrado.",
"whatsapp_linking_not_started": "Comece a vinculação do WhatsApp antes de pedir o código.",
"whatsapp_not_configured": "A vinculação com o WhatsApp não está disponível no momento.",
"whatsapp_not_connected": "Você não tem um WhatsApp vinculado.",
"whatsapp_number_in_use": "Esse número de WhatsApp já está vinculado a outro professor.",
"whatsapp_pairing_not_ready": "O WhatsApp ainda está preparando a vinculação. Tente novamente em alguns segundos.",
"whatsapp_pairing_unsupported": "Este provedor de WhatsApp não permite vincular pelo número de telefone.",
"whatsapp_provider_error": "Não conseguimos falar com o WhatsApp. Tente novamente em alguns minutos."
},
"auth": {
"INVALID_EMAIL_OR_PASSWORD": "E-mail ou senha incorretos.",
"EMAIL_NOT_VERIFIED": "Você ainda não confirmou seu e-mail. Confira sua caixa de entrada.",
"USER_ALREADY_EXISTS": "Já existe uma conta com esse e-mail.",
"USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL": "Já existe uma conta com esse e-mail.",
"INVALID_EMAIL": "Informe um e-mail válido.",
"PASSWORD_TOO_SHORT": "A senha deve ter pelo menos 8 caracteres.",
"PASSWORD_TOO_LONG": "A senha é muito longa.",
"INVALID_PASSWORD": "A senha atual não está correta.",
"INVALID_TOKEN": "O link não é válido ou expirou.",
"TOO_MANY_REQUESTS": "Você fez muitas solicitações seguidas. Tente novamente em alguns minutos."
}
}

View File

@@ -0,0 +1,26 @@
{
"nav": {
"home": "Início",
"groups": "Grupos",
"payments": "Cobranças",
"settings": "Ajustes",
"security": "Segurança",
"profile": "Meu perfil"
},
"breadcrumb": "Trilha de navegação",
"homeLink": "Início do Gruperly",
"reportedPayments_one": "{{count}} pagamento para verificar",
"reportedPayments_other": "{{count}} pagamentos para verificar",
"theme": {
"toLight": "Mudar para tema claro",
"toDark": "Mudar para tema escuro"
},
"userMenu": {
"close": "Fechar menu",
"profile": "Meu perfil",
"settings": "Ajustes",
"admin": "Backoffice",
"signOut": "Sair"
},
"publicFooter": "Gruperly — Gestão simples de cobranças e grupos"
}

View File

@@ -0,0 +1,18 @@
{
"banner": {
"title": "Instale o Gruperly",
"description": "Abra direto da sua tela inicial, sem a barra do navegador.",
"install": "Instalar app",
"later": "Agora não",
"close": "Fechar aviso de instalação"
},
"ios": {
"title": "Instale o Gruperly no iPhone",
"description": "Toque em <strong>Compartilhar</strong> e escolha <strong>Adicionar à Tela de Início</strong> para abrir como app."
},
"offlineReady": "O app está pronto para abrir sem conexão",
"offlineReadyDetail": "Agora você pode usar o Gruperly offline.",
"installed": "App instalado",
"installedDetail": "Agora o Gruperly está na sua tela inicial.",
"installLater": "Você pode instalar mais tarde pelo menu do navegador."
}

View File

@@ -0,0 +1,39 @@
{
"title": "Ajustes",
"subtitle": "Configure sua conta e seus grupos.",
"security": {
"title": "Segurança",
"description": "Senha e passkeys"
},
"signOut": "Sair",
"appearance": {
"title": "Aparência",
"description": "Tema claro ou escuro",
"light": "Claro",
"lightDescription": "Interface em tons claros",
"dark": "Escuro",
"darkDescription": "Interface em tons escuros",
"system": "Sistema",
"systemDescription": "Segue a preferência do seu dispositivo"
},
"language": {
"title": "Idioma",
"description": "O idioma do app",
"system": "Idioma do dispositivo",
"systemDescription": "Agora: {{language}}",
"saveError": "Não conseguimos salvar o idioma na sua conta"
},
"transfer": {
"title": "Dados para transferência",
"description": "Seus alunos veem esses dados ao informar um pagamento",
"alias": "Chave Pix ou dados bancários",
"aliasShort": "Chave",
"holder": "Titular",
"saved": "Dados para transferência salvos",
"saveError": "Não conseguimos salvar os dados"
},
"callback": {
"mpLinked": "Sua conta do Mercado Pago foi vinculada.",
"whatsappLinked": "Seu WhatsApp foi vinculado."
}
}

View File

@@ -0,0 +1,52 @@
{
"zod": {
"required": "Este campo é obrigatório",
"invalidType": "O valor não é válido",
"invalid": "O valor não é válido",
"tooShort": "É muito curto",
"tooLong": "É muito longo",
"tooSmall": "O valor é muito baixo",
"tooBig": "O valor é muito alto"
},
"email": {
"invalid": "Informe um e-mail válido"
},
"phone": {
"invalid": "Informe um número de telefone válido"
},
"name": {
"required": "O nome é obrigatório",
"enter": "Informe seu nome"
},
"password": {
"min": "A senha deve ter pelo menos 8 caracteres",
"mismatch": "As senhas não coincidem"
},
"update": {
"empty": "Envie pelo menos um campo para atualizar"
},
"group": {
"nameMin": "O nome deve ter pelo menos 3 caracteres",
"nameMax": "O nome é muito longo (máximo de 60 caracteres)",
"daysMin": "Escolha pelo menos um dia de aula",
"timeInvalid": "Escolha um horário válido (ex.: 09:00)",
"capacityInvalid": "Informe um número de vagas válido",
"capacityInt": "O número de vagas deve ser inteiro",
"capacityMin": "O grupo deve ter pelo menos 1 vaga",
"priceInvalid": "Informe um preço válido",
"priceMin": "O preço não pode ser negativo",
"dueDayInvalid": "Informe um dia válido",
"dueDayInt": "O dia deve ser um número inteiro",
"dueDayRange": "O dia de vencimento deve estar entre 1 e 28"
},
"whatsapp": {
"phoneRequired": "Informe seu número de WhatsApp",
"automationRequired": "Indique pelo menos uma automação"
},
"timezone": {
"invalid": "Fuso horário inválido"
},
"payment": {
"descriptionMax": "A descrição é muito longa"
}
}

View File

@@ -0,0 +1,35 @@
import { appLocaleSchema, resolveLocale, type AppLocale } from '@gruperly/shared'
/** 'system' sigue los idiomas del dispositivo; si no, el idioma elegido. */
export type LocalePreference = 'system' | AppLocale
const STORAGE_KEY = 'locale'
export function readStoredPreference(): LocalePreference {
try {
const value = localStorage.getItem(STORAGE_KEY)
if (value === 'system') return 'system'
const parsed = appLocaleSchema.safeParse(value)
return parsed.success ? parsed.data : 'system'
} catch {
return 'system'
}
}
export function storePreference(preference: LocalePreference): void {
try {
localStorage.setItem(STORAGE_KEY, preference)
} catch {
// Modo privado o storage bloqueado: la elección dura hasta recargar.
}
}
export function deviceLocale(): AppLocale {
const nav = globalThis.navigator
const tags = nav?.languages?.length ? nav.languages : nav?.language ? [nav.language] : []
return resolveLocale(tags)
}
export function localeFor(preference: LocalePreference): AppLocale {
return preference === 'system' ? deviceLocale() : preference
}

View File

@@ -0,0 +1,8 @@
import { useLocale } from './I18nProvider'
/** Tag para `Intl` / `toLocale*`: las fechas y los nombres de días y meses van
* en el idioma de la UI. Los montos y teléfonos NO: siguen al país (ver
* lib/region.ts). */
export function useIntlLocale(): string {
return useLocale().locale
}

View File

@@ -0,0 +1,45 @@
import { z } from 'zod'
import { i18n } from './instance'
const KEY_PATTERN = /^[a-zA-Z][\w]*(\.[\w]+)+$/
/**
* Traduce un mensaje de validación. Los esquemas (los de `@gruperly/shared` y
* los de la web) llevan claves estables (`group.nameMin`) en vez de texto; un
* mensaje que no es una clave conocida se muestra tal cual.
*/
export function validationMessage(message: string | undefined | null): string | undefined {
if (!message) return undefined
if (KEY_PATTERN.test(message) && i18n.exists(message, { ns: 'validation' })) {
return i18n.t(message as never, { ns: 'validation' })
}
return message
}
/** Mensajes por defecto de Zod (cuando el esquema no trae uno propio) en el
* idioma de la UI. Devuelve claves: `validationMessage` las traduce al pintar,
* así un cambio de idioma con el form abierto también se refleja. */
const errorMap: z.ZodErrorMap = (issue, ctx) => {
switch (issue.code) {
case z.ZodIssueCode.invalid_type:
return {
message:
issue.received === 'undefined' || issue.received === 'null' ? 'zod.required' : 'zod.invalidType',
}
case z.ZodIssueCode.too_small:
if (issue.type === 'string') return { message: Number(issue.minimum) <= 1 ? 'zod.required' : 'zod.tooShort' }
return { message: 'zod.tooSmall' }
case z.ZodIssueCode.too_big:
return { message: issue.type === 'string' ? 'zod.tooLong' : 'zod.tooBig' }
case z.ZodIssueCode.invalid_string:
return { message: issue.validation === 'email' ? 'email.invalid' : 'zod.invalid' }
case z.ZodIssueCode.invalid_enum_value:
return { message: 'zod.invalid' }
default:
return { message: ctx.defaultError }
}
}
export function installZodErrorMap() {
z.setErrorMap(errorMap)
}

View File

@@ -1,11 +1,18 @@
import { createAuthClient } from 'better-auth/react'
import { organizationClient } from 'better-auth/client/plugins'
import { inferAdditionalFields, organizationClient } from 'better-auth/client/plugins'
import { passkeyClient } from '@better-auth/passkey/client'
export const authClient = createAuthClient({
baseURL: import.meta.env.VITE_API_URL ?? 'http://localhost:4000',
basePath: '/api/v1/auth',
plugins: [organizationClient(), passkeyClient()],
plugins: [
organizationClient(),
passkeyClient(),
// Debe coincidir con `user.additionalFields` del backend (modules/auth/auth.ts).
inferAdditionalFields({
user: { locale: { type: 'string', required: false } },
}),
],
})
export const {

View File

@@ -1,27 +1,31 @@
import type { BillingType, PaymentDto, WeekDay } from '@gruperly/shared'
import { i18n } from '../i18n/instance'
import { countryOf, currencyForRegion, localeForRegion } from './region'
export const WEEK_DAY_FULL_LABELS: Record<WeekDay, string> = {
MONDAY: 'Lunes',
TUESDAY: 'Martes',
WEDNESDAY: 'Miércoles',
THURSDAY: 'Jueves',
FRIDAY: 'Viernes',
SATURDAY: 'Sábado',
SUNDAY: 'Domingo',
const WEEK_DAY_ORDER: WeekDay[] = [
'MONDAY',
'TUESDAY',
'WEDNESDAY',
'THURSDAY',
'FRIDAY',
'SATURDAY',
'SUNDAY',
]
/* Labels in the UI language. They read the i18n instance on every call, so a
component that renders them follows a language change as soon as it
re-renders (the layouts subscribe to the language for that). */
export function weekDayLabel(day: WeekDay): string {
return i18n.t(`common:weekDay.${day}`)
}
export const BILLING_LABELS: Record<BillingType, string> = {
MONTHLY: 'Mensual',
PER_CLASS: 'Por clase',
export function billingTypeLabel(type: BillingType): string {
return i18n.t(`common:billingType.${type}`)
}
export const PAYMENT_STATUS_LABELS: Record<PaymentDto['status'], string> = {
PENDING: 'Pendiente',
PAID: 'Pagado',
OVERDUE: 'Vencido',
CANCELLED: 'Cancelado',
export function paymentStatusLabel(status: PaymentDto['status']): string {
return i18n.t(`common:paymentStatus.${status}`)
}
const DAY_MS = 86_400_000
@@ -31,23 +35,22 @@ function startOfDay(date: Date): number {
}
export function formatRelativeDateTime(iso: string, now: Date = new Date()): string {
const locale = i18n.language
const date = new Date(iso)
const time = date.toLocaleTimeString('es-MX', {
const time = date.toLocaleTimeString(locale, {
hour: '2-digit',
minute: '2-digit',
hour12: false,
})
const diffDays = Math.round((startOfDay(date) - startOfDay(now)) / DAY_MS)
if (diffDays === 0) return `Hoy · ${time}`
if (diffDays === 1) return `Mañana · ${time}`
if (diffDays === 0) return i18n.t('common:relativeDay.today', { time })
if (diffDays === 1) return i18n.t('common:relativeDay.tomorrow', { time })
const label = date.toLocaleDateString('es-MX', { weekday: 'short', day: 'numeric', month: 'short' })
return `${label} · ${time}`
const label = date.toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short' })
return i18n.t('common:relativeDay.other', { date: 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[] {
@@ -55,7 +58,7 @@ export function sortWeekDays(days: readonly WeekDay[]): WeekDay[] {
}
export function formatSchedule(days: readonly WeekDay[], time: string | null): string {
const dayNames = sortWeekDays(days).map((day) => WEEK_DAY_FULL_LABELS[day])
const dayNames = sortWeekDays(days).map(weekDayLabel)
return time ? `${dayNames.join(', ')} · ${time}` : dayNames.join(', ')
}
@@ -273,14 +276,15 @@ function formatMxNational(digits: string, withCountry: boolean): string | null {
}
// The due date is worded as a phrase ("Vence el día 10 de cada mes") instead of
// "Vence día 10": it reads as a promise, not as a bare fact.
// "Vence día 10": it reads as a promise, not as a bare fact. Each language
// keeps that same tone.
export function formatBillingMeta(
billingType: BillingType | null,
dueDay: number | null,
): string | null {
if (billingType === 'PER_CLASS') return BILLING_LABELS.PER_CLASS
if (billingType === 'PER_CLASS') return billingTypeLabel('PER_CLASS')
if (billingType === 'MONTHLY') {
return dueDay ? `Vence el día ${dueDay} de cada mes` : BILLING_LABELS.MONTHLY
return dueDay ? i18n.t('common:billingDueDay', { day: dueDay }) : billingTypeLabel('MONTHLY')
}
return null
}

View File

@@ -8,6 +8,8 @@ import { ThemeProvider } from './context/ThemeProvider'
import { ToastProvider } from './components/ui'
import { isPlanProblem, showPlanPrompt } from './features/billing'
import { PwaProvider } from './features/pwa'
import { activateLocale, errorMessage, I18nProvider, initialLocale, installZodErrorMap } from './i18n'
import { LocaleProfileSync } from './i18n/LocaleProfileSync'
import './index.css'
const queryClient = new QueryClient({
@@ -17,7 +19,7 @@ const queryClient = new QueryClient({
mutationCache: new MutationCache({
onError: (error) => {
if (isPlanProblem(error)) {
showPlanPrompt(error.problem?.detail ?? 'Esta función está disponible en el plan Pro.')
showPlanPrompt(errorMessage(error))
}
},
}),
@@ -26,18 +28,30 @@ const queryClient = new QueryClient({
},
})
ReactDOM.createRoot(document.getElementById('root')!).render(
installZodErrorMap()
// El idioma inicial se carga antes del primer render: así no se ve un flash en
// otro idioma. Si falla la carga (offline sin precache), se renderiza igual con
// las claves que haya.
void activateLocale(initialLocale())
.catch(() => undefined)
.then(() => {
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<I18nProvider>
<AuthProvider>
<LocaleProfileSync />
<ToastProvider>
<PwaProvider>
<RouterProvider router={router} />
</PwaProvider>
</ToastProvider>
</AuthProvider>
</I18nProvider>
</ThemeProvider>
</QueryClientProvider>
</React.StrictMode>,
)
)
})

View File

@@ -0,0 +1,69 @@
import { describe, expect, test } from 'bun:test'
import { readdirSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { SUPPORTED_LOCALES } from '@gruperly/shared'
import { NAMESPACES } from '../src/i18n/instance'
/* es-AR es la fuente. Cada idioma tiene que tener exactamente las mismas claves
(salvo las formas de plural, que dependen del idioma), sin textos vacíos y
con las mismas variables de interpolación. */
const root = join(import.meta.dir, '../src/i18n/locales')
const SOURCE = 'es-AR'
const PLURAL_SUFFIX = /_(zero|one|two|few|many|other)$/
type Tree = { [key: string]: string | Tree }
function load(locale: string, ns: string): Tree {
return JSON.parse(readFileSync(join(root, locale, `${ns}.json`), 'utf8')) as Tree
}
function flatten(tree: Tree, prefix = ''): Map<string, string> {
const out = new Map<string, string>()
for (const [key, value] of Object.entries(tree)) {
const path = prefix ? `${prefix}.${key}` : key
if (typeof value === 'string') out.set(path, value)
else for (const [k, v] of flatten(value, path)) out.set(k, v)
}
return out
}
/** Claves sin el sufijo de plural: `a_one` y `a_other` cuentan como `a`. */
function baseKeys(flat: Map<string, string>): Set<string> {
return new Set([...flat.keys()].map((key) => key.replace(PLURAL_SUFFIX, '')))
}
function variables(text: string): string[] {
return [...text.matchAll(/\{\{\s*(\w+)\s*\}\}/g)].map((m) => m[1]!).sort()
}
function variablesByBase(flat: Map<string, string>): Map<string, string> {
const out = new Map<string, Set<string>>()
for (const [key, text] of flat) {
const base = key.replace(PLURAL_SUFFIX, '')
const set = out.get(base) ?? new Set<string>()
for (const v of variables(text)) set.add(v)
out.set(base, set)
}
return new Map([...out].map(([k, v]) => [k, [...v].sort().join(',')]))
}
describe('traducciones', () => {
test('cada namespace declarado tiene su JSON en todos los idiomas', () => {
for (const locale of SUPPORTED_LOCALES) {
const files = readdirSync(join(root, locale)).filter((f) => f.endsWith('.json'))
expect(files.map((f) => f.slice(0, -5)).sort()).toEqual([...NAMESPACES].sort())
}
})
for (const ns of NAMESPACES) {
const source = flatten(load(SOURCE, ns))
for (const locale of SUPPORTED_LOCALES.filter((l) => l !== SOURCE)) {
test(`${locale}/${ns} tiene las mismas claves y variables que ${SOURCE}`, () => {
const target = flatten(load(locale, ns))
expect([...baseKeys(target)].sort()).toEqual([...baseKeys(source)].sort())
expect(Object.fromEntries(variablesByBase(target))).toEqual(Object.fromEntries(variablesByBase(source)))
for (const [key, text] of target) expect({ key, empty: text.trim() === '' }).toEqual({ key, empty: false })
})
}
}
})

View File

@@ -0,0 +1,39 @@
import { describe, expect, test } from 'bun:test'
import { matchLocale, resolveLocale } from '@gruperly/shared'
describe('resolveLocale', () => {
test('rioplatense para Argentina y Uruguay', () => {
expect(resolveLocale(['es-AR'])).toBe('es-AR')
expect(resolveLocale(['es-UY'])).toBe('es-AR')
expect(resolveLocale(['es_AR'])).toBe('es-AR')
})
test('cualquier otro español es latinoamericano', () => {
expect(resolveLocale(['es'])).toBe('es-419')
expect(resolveLocale(['es-MX'])).toBe('es-419')
expect(resolveLocale(['es-419'])).toBe('es-419')
expect(resolveLocale(['es-ES'])).toBe('es-419')
})
test('todo portugués va a pt-BR', () => {
expect(resolveLocale(['pt-BR'])).toBe('pt-BR')
expect(resolveLocale(['pt-PT'])).toBe('pt-BR')
expect(resolveLocale(['pt'])).toBe('pt-BR')
})
test('inglés y fallback', () => {
expect(resolveLocale(['en-US'])).toBe('en')
expect(resolveLocale(['fr-FR'])).toBe('en')
expect(resolveLocale([])).toBe('en')
})
test('respeta el orden de preferencia del dispositivo', () => {
expect(resolveLocale(['fr-FR', 'pt-BR', 'en'])).toBe('pt-BR')
expect(resolveLocale(['de', 'it'])).toBe('en')
})
test('matchLocale no inventa idiomas', () => {
expect(matchLocale('de-DE')).toBeNull()
expect(matchLocale('')).toBeNull()
})
})

14
apps/web/test/setup.ts Normal file
View File

@@ -0,0 +1,14 @@
import { readdirSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { i18n } from '../src/i18n/instance'
/* En los tests no hay `import.meta.glob` (es de Vite): se cargan los JSON de
es-AR del disco y se activa ese idioma, así el copy sale como en producción
para quien tiene la UI en rioplatense. */
const dir = join(import.meta.dir, '../src/i18n/locales/es-AR')
for (const file of readdirSync(dir)) {
if (!file.endsWith('.json')) continue
const ns = file.slice(0, -'.json'.length)
i18n.addResourceBundle('es-AR', ns, JSON.parse(readFileSync(join(dir, file), 'utf8')), true, true)
}
await i18n.changeLanguage('es-AR')

View File

@@ -50,10 +50,12 @@
"@tanstack/react-router": "^1.170.38",
"better-auth": "1.7.2",
"clsx": "^2.1.1",
"i18next": "^26.5.11",
"lucide-react": "^1.34.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-hook-form": "^7.54.0",
"react-i18next": "^17.1.9",
"tailwind-merge": "^3.6.0",
"zod": "3.24.2",
},
@@ -1012,6 +1014,10 @@
"hono": ["hono@4.13.7", "", {}, "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ=="],
"html-parse-stringify": ["html-parse-stringify@4.0.1", "", {}, "sha512-0zHsZJrK7S3K2aucXWL6ycoYJ/iNtIcFHC/nYQgFklPtrv5LpJctIiSCroWZWeuoXvuyFdzp6KzjJQ+OT5MfFw=="],
"i18next": ["i18next@26.5.11", "", { "peerDependencies": { "typescript": "^5 || ^6 || ^7" }, "optionalPeers": ["typescript"] }, "sha512-Wc0klBPKxqZ2tL2qdAnF8xvvnWgr1IMGSY2ikTiAvaFVbz7xiFARtkoU4RidBDw1SyziGROp0qxu6qnJ7l2Wug=="],
"iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="],
"idb": ["idb@7.1.1", "", {}, "sha512-gchesWBzyvGHRO9W8tzUWFDycow5gwjvFKfyV9FF32Y7F50yZMp7mP+T2mJIWFx49zicqyC4uefHM17o6xKIVQ=="],
@@ -1266,6 +1272,8 @@
"react-hook-form": ["react-hook-form@7.87.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17 || ^18 || ^19" } }, "sha512-zhFzWvLxNHH+8839OnZcUxgMZw88ah2jZWDWvKWgF3Tpbnd0vKL+dlcuU3nZVWESZQjd81EW8K+wU+cYfYAc0w=="],
"react-i18next": ["react-i18next@17.1.9", "", { "dependencies": { "@babel/runtime": "^7.29.7", "html-parse-stringify": "^4.0.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "i18next": ">= 26.2.0", "react": ">= 16.8.0", "react-dom": "*", "react-native": "*", "typescript": "^5 || ^6 || ^7" }, "optionalPeers": ["react-dom", "react-native", "typescript"] }, "sha512-OgYqIH13XHPlWTaaI795Dz+k2AdKnXcOxNQVnf750T8Ij0TYWp1nYvXRpoJBulPqlyk2OAbn1PM4tFKiIj/byA=="],
"react-refresh": ["react-refresh@0.17.0", "", {}, "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ=="],
"readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="],

View File

@@ -14,6 +14,7 @@ export * from './schemas/enums.js';
export * from './schemas/groups.js';
export * from './schemas/health-check.js';
export * from './schemas/home.js';
export * from './schemas/locale.js';
export * from './schemas/mp.js';
export * from './schemas/onboarding.js';
export * from './schemas/pagination.js';

View File

@@ -5,5 +5,8 @@ export type ProblemDetails = {
detail?: string;
instance?: string;
code?: string;
/** Values the client needs to word the error in its own language (e.g. the
* plan limit). `detail` keeps the server-side wording. */
params?: Record<string, string | number>;
errors?: Record<string, string[]>;
};

View File

@@ -84,7 +84,7 @@ const EditableAttendeeFieldsSchema = z.object({
email: z
.string()
.trim()
.email('Ingresá un email válido')
.email('email.invalid')
.or(z.literal(''))
.nullable(),
notes: z.string().trim().nullable(),
@@ -92,7 +92,7 @@ const EditableAttendeeFieldsSchema = z.object({
export const UpdateAttendeeSchema = EditableAttendeeFieldsSchema.partial().refine(
(value) => Object.keys(value).length > 0,
'Enviá al menos un campo para actualizar',
'update.empty',
);
export type UpdateAttendee = z.output<typeof UpdateAttendeeSchema>;
@@ -116,10 +116,10 @@ export const AttendeeListSchema = z.object({
export type AttendeeList = z.output<typeof AttendeeListSchema>;
export const CreateAttendeeSchema = z.object({
firstName: z.string().trim().min(1, 'El nombre es obligatorio'),
firstName: z.string().trim().min(1, 'name.required'),
lastName: z.string().trim().optional().default(''),
phone: z.string().trim().min(6, 'Ingresa un número de teléfono válido'),
email: z.string().trim().email('Email inválido').optional().or(z.literal('')),
phone: z.string().trim().min(6, 'phone.invalid'),
email: z.string().trim().email('email.invalid').optional().or(z.literal('')),
notes: z.string().trim().optional(),
/* Adds an existing person of the teacher (found by phone) instead of creating
a new one: the name/email fields are ignored then. */
@@ -140,10 +140,10 @@ export const CreateAttendeeResultSchema = z.discriminatedUnion('outcome', [
export type CreateAttendeeResult = z.output<typeof CreateAttendeeResultSchema>;
export const JoinGroupViaInviteSchema = z.object({
firstName: z.string().trim().min(1, 'El nombre es obligatorio'),
firstName: z.string().trim().min(1, 'name.required'),
lastName: z.string().trim().min(1, 'El apellido es obligatorio'),
phone: z.string().trim().min(6, 'Ingresa un número de teléfono válido'),
email: z.string().trim().email('Email inválido').optional().or(z.literal('')),
phone: z.string().trim().min(6, 'phone.invalid'),
email: z.string().trim().email('email.invalid').optional().or(z.literal('')),
});
export type JoinGroupViaInvite = z.output<typeof JoinGroupViaInviteSchema>;
@@ -155,11 +155,11 @@ export const JoinGroupViaInviteResultSchema = z.object({
export type JoinGroupViaInviteResult = z.output<typeof JoinGroupViaInviteResultSchema>;
export const BulkAttendeeItemSchema = z.object({
firstName: z.string().trim().min(1, 'El nombre es obligatorio'),
firstName: z.string().trim().min(1, 'name.required'),
lastName: z.string().trim().optional().default(''),
fullName: z.string().trim().optional(),
phone: z.string().trim().min(6, 'Ingresa un número de teléfono válido'),
email: z.string().trim().email('Email inválido').optional().or(z.literal('')),
phone: z.string().trim().min(6, 'phone.invalid'),
email: z.string().trim().email('email.invalid').optional().or(z.literal('')),
notes: z.string().trim().optional(),
});
export type BulkAttendeeItem = z.output<typeof BulkAttendeeItemSchema>;

View File

@@ -100,7 +100,7 @@ export type BillingStatusDto = z.output<typeof BillingStatusDtoSchema>;
// Mercado Pago requires the payer to log in with this exact email; Stripe asks
// for it in its own checkout, so it is only mandatory for Mercado Pago.
const payerEmailSchema = z.string().trim().email('Ingresá un email válido');
const payerEmailSchema = z.string().trim().email('email.invalid');
export const SubscribeInputSchema = z.strictObject({
payerEmail: payerEmailSchema.optional(),

View File

@@ -13,7 +13,7 @@ const timeZoneSchema = z
} catch {
return false;
}
}, 'Zona horaria IANA inválida');
}, 'timezone.invalid');
export { timeZoneSchema };

View File

@@ -0,0 +1,32 @@
import { z } from 'zod';
// UI languages. es-AR is rioplatense Spanish (Argentina and Uruguay, voseo),
// es-419 is neutral Latin American Spanish (tuteo). Anything else falls back
// to English.
export const SUPPORTED_LOCALES = ['es-AR', 'es-419', 'pt-BR', 'en'] as const;
export const appLocaleSchema = z.enum(SUPPORTED_LOCALES);
export type AppLocale = z.output<typeof appLocaleSchema>;
export const FALLBACK_LOCALE: AppLocale = 'en';
/** Maps one BCP 47 tag to a supported locale, or null if the language isn't
* supported. Any Spanish outside Argentina/Uruguay is es-419 (including
* es-ES), any Portuguese is pt-BR. */
export function matchLocale(tag: string): AppLocale | null {
const [language = '', ...rest] = tag.trim().toLowerCase().replace(/_/g, '-').split('-');
const region = rest.find((part) => /^([a-z]{2}|\d{3})$/.test(part));
if (language === 'es') return region === 'ar' || region === 'uy' ? 'es-AR' : 'es-419';
if (language === 'pt') return 'pt-BR';
if (language === 'en') return 'en';
return null;
}
/** First supported locale among the device's preferred languages, in order;
* English when none matches. */
export function resolveLocale(tags: readonly string[]): AppLocale {
for (const tag of tags) {
const match = matchLocale(tag);
if (match) return match;
}
return FALLBACK_LOCALE;
}

View File

@@ -17,25 +17,25 @@ export const CreateFirstGroupSchema = z.strictObject({
name: z
.string()
.trim()
.min(3, 'El nombre debe tener al menos 3 caracteres')
.max(60, 'El nombre es demasiado largo (máximo 60 caracteres)'),
days: z.array(weekdaySchema).min(1, 'Elegí al menos un día de clase'),
.min(3, 'group.nameMin')
.max(60, 'group.nameMax'),
days: z.array(weekdaySchema).min(1, 'group.daysMin'),
time: z
.string()
.regex(/^([01]?\d|2[0-3]):[0-5]\d$/, 'Elegí un horario válido (ej: 09:00)'),
.regex(/^([01]?\d|2[0-3]):[0-5]\d$/, 'group.timeInvalid'),
capacity: z
.number({ invalid_type_error: 'Ingresá un cupo válido' })
.int({ message: 'El cupo debe ser un número entero' })
.min(1, 'El cupo debe ser al menos 1'),
.number({ invalid_type_error: 'group.capacityInvalid' })
.int({ message: 'group.capacityInt' })
.min(1, 'group.capacityMin'),
price: z
.number({ invalid_type_error: 'Ingresá un precio válido' })
.min(0, 'El precio no puede ser negativo'),
.number({ invalid_type_error: 'group.priceInvalid' })
.min(0, 'group.priceMin'),
billingType: billingTypeSchema,
dueDay: z
.number({ invalid_type_error: 'Ingresá un día válido' })
.int({ message: 'El día debe ser un número entero' })
.min(1, 'El día de vencimiento debe estar entre 1 y 28')
.max(28, 'El día de vencimiento debe estar entre 1 y 28'),
.number({ invalid_type_error: 'group.dueDayInvalid' })
.int({ message: 'group.dueDayInt' })
.min(1, 'group.dueDayRange')
.max(28, 'group.dueDayRange'),
country: countryCodeSchema.default(DEFAULT_COUNTRY),
});
export type CreateFirstGroup = z.output<typeof CreateFirstGroupSchema>;

View File

@@ -45,7 +45,7 @@ export type PaymentList = z.output<typeof PaymentListSchema>;
// triggers it from the group page for a period (e.g. June's monthly fee).
export const CreatePaymentsBatchSchema = z.strictObject({
dueDate: isoDateTimeSchema,
description: z.string().trim().max(120, 'La descripción es demasiado larga').optional(),
description: z.string().trim().max(120, 'payment.descriptionMax').optional(),
attendeeIds: z.array(z.string().min(1)).min(1).optional(),
});
export type CreatePaymentsBatch = z.output<typeof CreatePaymentsBatchSchema>;

View File

@@ -8,5 +8,6 @@ export const ProblemDetailsSchema: z.ZodType<ProblemDetails> = z.object({
detail: z.string().optional(),
instance: z.string().optional(),
code: z.string().optional(),
params: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
errors: z.record(z.string(), z.array(z.string())).optional(),
});

Some files were not shown because too many files have changed in this diff Show More