Compare commits
18 Commits
d21e1c3730
...
925f1a256d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
925f1a256d | ||
|
|
70702ba852 | ||
|
|
4d50b46399 | ||
|
|
486fbaf2ca | ||
|
|
b615c17a16 | ||
|
|
243530fab2 | ||
|
|
dfb6951d7c | ||
|
|
e2d9ddf569 | ||
|
|
700b9fb91d | ||
|
|
e3dca305a4 | ||
|
|
7db9414f12 | ||
|
|
13723d5bb9 | ||
|
|
8a5768e0c0 | ||
|
|
ecdbbbbca6 | ||
|
|
96661fb807 | ||
|
|
09647672b8 | ||
|
|
cb872eb8bc | ||
|
|
ff885bddfc |
File diff suppressed because one or more lines are too long
448
.archify/architecture-gruperly-20261103-121500/candidate.json
Normal file
448
.archify/architecture-gruperly-20261103-121500/candidate.json
Normal file
@@ -0,0 +1,448 @@
|
|||||||
|
{
|
||||||
|
"schema_version": 1,
|
||||||
|
"diagram_type": "architecture",
|
||||||
|
"meta": {
|
||||||
|
"title": "Arquitectura de Gruperly",
|
||||||
|
"locale": "es",
|
||||||
|
"output": ".archify/architecture-gruperly-20261103-121500/arquitectura-gruperly.html",
|
||||||
|
"quality_profile": "showcase",
|
||||||
|
"repository": {
|
||||||
|
"url": "https://git.2pidev.com/jselesan/gruperly.git",
|
||||||
|
"link_mode": "local-only",
|
||||||
|
"revision": "d21e1c37302d8d3f2ff8b0af05f4df21284bffe3"
|
||||||
|
},
|
||||||
|
"views": [
|
||||||
|
{
|
||||||
|
"id": "request",
|
||||||
|
"label": "Pedido del profe",
|
||||||
|
"focus": [
|
||||||
|
"teacher",
|
||||||
|
"web",
|
||||||
|
"nginx",
|
||||||
|
"guards",
|
||||||
|
"api",
|
||||||
|
"db"
|
||||||
|
],
|
||||||
|
"note": "Mismo dominio: nginx sirve el bundle y hace proxy de /api al contenedor api."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "students",
|
||||||
|
"label": "App de alumnos",
|
||||||
|
"focus": [
|
||||||
|
"student",
|
||||||
|
"web",
|
||||||
|
"guards",
|
||||||
|
"storage"
|
||||||
|
],
|
||||||
|
"note": "Sin Better Auth: cookie y middleware propios; comprobantes en S3 privado."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "integrations",
|
||||||
|
"label": "Integraciones",
|
||||||
|
"focus": [
|
||||||
|
"api",
|
||||||
|
"mp",
|
||||||
|
"stripe",
|
||||||
|
"whatsapp",
|
||||||
|
"smtp",
|
||||||
|
"storage"
|
||||||
|
],
|
||||||
|
"note": "Cada proveedor detrás de un puerto; sin credenciales responde 503 y el resto sigue andando."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"components": [
|
||||||
|
{
|
||||||
|
"id": "teacher",
|
||||||
|
"type": "external",
|
||||||
|
"label": "Profesor",
|
||||||
|
"sublabel": "navegador / PWA",
|
||||||
|
"icon": "person",
|
||||||
|
"pos": [
|
||||||
|
40,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"size": [
|
||||||
|
120,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/web/src/routes/_authenticated.tsx",
|
||||||
|
"line": 1
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "web",
|
||||||
|
"type": "frontend",
|
||||||
|
"label": "Web PWA",
|
||||||
|
"sublabel": "React 19 · Vite",
|
||||||
|
"pos": [
|
||||||
|
230,
|
||||||
|
56
|
||||||
|
],
|
||||||
|
"size": [
|
||||||
|
140,
|
||||||
|
68
|
||||||
|
],
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/web/vite.config.ts",
|
||||||
|
"line": 12,
|
||||||
|
"label": "VitePWA"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "student",
|
||||||
|
"type": "external",
|
||||||
|
"label": "Alumno / tutor",
|
||||||
|
"sublabel": "/i/:token · /student",
|
||||||
|
"icon": "person",
|
||||||
|
"pos": [
|
||||||
|
230,
|
||||||
|
240
|
||||||
|
],
|
||||||
|
"size": [
|
||||||
|
140,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/web/src/routes/i.$token.tsx",
|
||||||
|
"line": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "apps/web/src/routes/_student.tsx",
|
||||||
|
"line": 1
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "nginx",
|
||||||
|
"type": "cloud",
|
||||||
|
"label": "nginx",
|
||||||
|
"sublabel": "bundle + proxy /api",
|
||||||
|
"pos": [
|
||||||
|
450,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"size": [
|
||||||
|
140,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/web/nginx.conf",
|
||||||
|
"line": 14,
|
||||||
|
"end_line": 26
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "docker-compose.yml",
|
||||||
|
"line": 1,
|
||||||
|
"end_line": 8
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "guards",
|
||||||
|
"type": "security",
|
||||||
|
"label": "Guards de sesión",
|
||||||
|
"sublabel": "Better Auth · alumno",
|
||||||
|
"pos": [
|
||||||
|
680,
|
||||||
|
56
|
||||||
|
],
|
||||||
|
"size": [
|
||||||
|
150,
|
||||||
|
68
|
||||||
|
],
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/src/http/session-auth.ts",
|
||||||
|
"line": 23,
|
||||||
|
"end_line": 48
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "apps/backend/src/modules/student-portal/middleware.ts",
|
||||||
|
"line": 50
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "api",
|
||||||
|
"type": "backend",
|
||||||
|
"label": "API Hono + jobs",
|
||||||
|
"sublabel": "Bun.serve :4000 · cron",
|
||||||
|
"pos": [
|
||||||
|
880,
|
||||||
|
56
|
||||||
|
],
|
||||||
|
"size": [
|
||||||
|
150,
|
||||||
|
68
|
||||||
|
],
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/src/server.ts",
|
||||||
|
"line": 14,
|
||||||
|
"end_line": 23
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "apps/backend/src/app.ts",
|
||||||
|
"line": 44,
|
||||||
|
"end_line": 73
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "db",
|
||||||
|
"type": "database",
|
||||||
|
"label": "PostgreSQL",
|
||||||
|
"sublabel": "Prisma 7 · adapter-pg",
|
||||||
|
"pos": [
|
||||||
|
1090,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"size": [
|
||||||
|
140,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/src/lib/prisma.ts",
|
||||||
|
"line": 14,
|
||||||
|
"end_line": 18
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "mp",
|
||||||
|
"type": "external",
|
||||||
|
"label": "Mercado Pago",
|
||||||
|
"sublabel": "OAuth · Checkout Pro",
|
||||||
|
"pos": [
|
||||||
|
610,
|
||||||
|
320
|
||||||
|
],
|
||||||
|
"size": [
|
||||||
|
130,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/src/modules/mp/lib/mp-oauth.ts",
|
||||||
|
"line": 3,
|
||||||
|
"end_line": 4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "apps/backend/src/modules/mp/lib/mp-http.ts",
|
||||||
|
"line": 4
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "stripe",
|
||||||
|
"type": "external",
|
||||||
|
"label": "Stripe",
|
||||||
|
"sublabel": "Pro fuera de AR",
|
||||||
|
"pos": [
|
||||||
|
760,
|
||||||
|
320
|
||||||
|
],
|
||||||
|
"size": [
|
||||||
|
110,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/src/modules/billing/providers/index.ts",
|
||||||
|
"line": 24,
|
||||||
|
"end_line": 31
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "whatsapp",
|
||||||
|
"type": "external",
|
||||||
|
"label": "WhatsApp",
|
||||||
|
"sublabel": "OpenWA / Kapso",
|
||||||
|
"pos": [
|
||||||
|
890,
|
||||||
|
320
|
||||||
|
],
|
||||||
|
"size": [
|
||||||
|
130,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/src/modules/whatsapp/providers/index.ts",
|
||||||
|
"line": 26,
|
||||||
|
"end_line": 40
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "smtp",
|
||||||
|
"type": "external",
|
||||||
|
"label": "SMTP",
|
||||||
|
"sublabel": "mails",
|
||||||
|
"pos": [
|
||||||
|
1040,
|
||||||
|
320
|
||||||
|
],
|
||||||
|
"size": [
|
||||||
|
100,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/src/lib/email.ts",
|
||||||
|
"line": 181,
|
||||||
|
"end_line": 187
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "storage",
|
||||||
|
"type": "cloud",
|
||||||
|
"label": "S3 (RustFS)",
|
||||||
|
"sublabel": "comprobantes",
|
||||||
|
"pos": [
|
||||||
|
1160,
|
||||||
|
320
|
||||||
|
],
|
||||||
|
"size": [
|
||||||
|
130,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/src/lib/storage.ts",
|
||||||
|
"line": 38,
|
||||||
|
"end_line": 54
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"boundaries": [
|
||||||
|
{
|
||||||
|
"kind": "region",
|
||||||
|
"label": "Dokploy",
|
||||||
|
"wraps": [
|
||||||
|
"nginx",
|
||||||
|
"guards",
|
||||||
|
"api",
|
||||||
|
"db"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"kind": "security-group",
|
||||||
|
"label": "contenedor api",
|
||||||
|
"wraps": [
|
||||||
|
"guards",
|
||||||
|
"api"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"connections": [
|
||||||
|
{
|
||||||
|
"id": "teacher-web",
|
||||||
|
"from": "teacher",
|
||||||
|
"to": "web",
|
||||||
|
"label": "HTTPS",
|
||||||
|
"variant": "emphasis"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "student-web",
|
||||||
|
"from": "student",
|
||||||
|
"to": "web",
|
||||||
|
"label": "link de WhatsApp"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "web-nginx",
|
||||||
|
"from": "web",
|
||||||
|
"to": "nginx",
|
||||||
|
"label": "/api/v1",
|
||||||
|
"variant": "emphasis"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "nginx-guards",
|
||||||
|
"from": "nginx",
|
||||||
|
"to": "guards",
|
||||||
|
"label": "proxy_pass",
|
||||||
|
"variant": "emphasis"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "guards-api",
|
||||||
|
"from": "guards",
|
||||||
|
"to": "api",
|
||||||
|
"variant": "security"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "api-db",
|
||||||
|
"from": "api",
|
||||||
|
"to": "db",
|
||||||
|
"label": "SQL"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "api-mp",
|
||||||
|
"from": "api",
|
||||||
|
"to": "mp",
|
||||||
|
"label": "cobros"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "api-stripe",
|
||||||
|
"from": "api",
|
||||||
|
"to": "stripe",
|
||||||
|
"label": "Pro"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "api-whatsapp",
|
||||||
|
"from": "api",
|
||||||
|
"to": "whatsapp",
|
||||||
|
"label": "mensajes"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "api-smtp",
|
||||||
|
"from": "api",
|
||||||
|
"to": "smtp",
|
||||||
|
"label": "mails"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "api-storage",
|
||||||
|
"from": "api",
|
||||||
|
"to": "storage",
|
||||||
|
"label": "URLs firmadas"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"cards": [
|
||||||
|
{
|
||||||
|
"dot": "cyan",
|
||||||
|
"title": "Entrada",
|
||||||
|
"items": [
|
||||||
|
"Un solo dominio público en el contenedor web: nginx sirve la PWA y hace proxy de /api a api:4000, así la cookie de sesión es first-party.",
|
||||||
|
"Los alumnos entran por un link de invitación de un solo uso; no tienen contraseña."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"dot": "rose",
|
||||||
|
"title": "Seguridad",
|
||||||
|
"items": [
|
||||||
|
"sessionAuthMiddleware exige sesión de Better Auth salvo la whitelist pública (isPublicApiRequest).",
|
||||||
|
"/student-portal usa cookie y middleware propios (studentSession); una sesión de alumno no llega a rutas del profe.",
|
||||||
|
"Los webhooks de MP, Stripe y WhatsApp son públicos y se autentican por firma."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"dot": "emerald",
|
||||||
|
"title": "Jobs en el mismo proceso",
|
||||||
|
"items": [
|
||||||
|
"server.ts arranca los crons de MP, pagos, WhatsApp, billing y app de alumnos junto a Bun.serve.",
|
||||||
|
"La conciliación de pagos es por polling a Mercado Pago, sin webhook."
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
515
.archify/erd-personas-membresias-20261103-120000/candidate.json
Normal file
515
.archify/erd-personas-membresias-20261103-120000/candidate.json
Normal file
@@ -0,0 +1,515 @@
|
|||||||
|
{
|
||||||
|
"schema_version": 1,
|
||||||
|
"diagram_type": "erd",
|
||||||
|
"meta": {
|
||||||
|
"title": "Personas y membresías",
|
||||||
|
"locale": "es",
|
||||||
|
"output": ".archify/erd-personas-membresias-20261103-120000/personas-membresias.html",
|
||||||
|
"quality_profile": "standard",
|
||||||
|
"repository": {
|
||||||
|
"url": "https://git.2pidev.com/jselesan/gruperly.git",
|
||||||
|
"link_mode": "local-only",
|
||||||
|
"revision": "d21e1c37302d8d3f2ff8b0af05f4df21284bffe3"
|
||||||
|
},
|
||||||
|
"views": [
|
||||||
|
{
|
||||||
|
"id": "membership",
|
||||||
|
"label": "Persona y membresía",
|
||||||
|
"focus": [
|
||||||
|
"people",
|
||||||
|
"attendees",
|
||||||
|
"groups"
|
||||||
|
],
|
||||||
|
"note": "Una persona del profe, una fila de attendees por cada grupo en el que está."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "owner",
|
||||||
|
"label": "Todo cuelga del profe",
|
||||||
|
"focus": [
|
||||||
|
"users",
|
||||||
|
"groups",
|
||||||
|
"people",
|
||||||
|
"student_accounts"
|
||||||
|
],
|
||||||
|
"note": "Grupos, personas y cuentas de alumno tienen created_by_id al profe."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "student_app",
|
||||||
|
"label": "Una cuenta por persona",
|
||||||
|
"focus": [
|
||||||
|
"student_accounts",
|
||||||
|
"student_account_people",
|
||||||
|
"people"
|
||||||
|
],
|
||||||
|
"note": "La cuenta se vincula a la persona, así ve todos sus grupos."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"layout": {
|
||||||
|
"mode": "grid",
|
||||||
|
"gapX": 72,
|
||||||
|
"gapY": 40
|
||||||
|
},
|
||||||
|
"entities": [
|
||||||
|
{
|
||||||
|
"id": "groups",
|
||||||
|
"label": "groups",
|
||||||
|
"tag": "grupos",
|
||||||
|
"row": 0,
|
||||||
|
"col": 0,
|
||||||
|
"width": 256,
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/prisma/models/domain.prisma",
|
||||||
|
"line": 3,
|
||||||
|
"end_line": 32
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"attributes": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"key": "pk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "name",
|
||||||
|
"type": "text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "description",
|
||||||
|
"type": "text?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "days",
|
||||||
|
"type": "WeekDay[]"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "time",
|
||||||
|
"type": "text?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "capacity",
|
||||||
|
"type": "int?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "price",
|
||||||
|
"type": "numeric(10,2)?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "billing_type",
|
||||||
|
"type": "BillingType?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "due_day",
|
||||||
|
"type": "int?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "auto_payment_reminders",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "auto_reengagement",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "invite_token",
|
||||||
|
"type": "text?",
|
||||||
|
"key": "uk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_by_id",
|
||||||
|
"type": "text",
|
||||||
|
"key": "fk",
|
||||||
|
"references": "users.id"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "updated_at",
|
||||||
|
"type": "timestamp"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "attendees",
|
||||||
|
"label": "attendees",
|
||||||
|
"sublabel": "membresía",
|
||||||
|
"tag": "membresías",
|
||||||
|
"row": 0,
|
||||||
|
"col": 1,
|
||||||
|
"width": 250,
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/prisma/models/domain.prisma",
|
||||||
|
"line": 100,
|
||||||
|
"end_line": 125
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"attributes": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"key": "pk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "group_id",
|
||||||
|
"type": "text",
|
||||||
|
"key": [
|
||||||
|
"fk",
|
||||||
|
"uk"
|
||||||
|
],
|
||||||
|
"references": "groups.id"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "person_id",
|
||||||
|
"type": "text",
|
||||||
|
"key": [
|
||||||
|
"fk",
|
||||||
|
"uk"
|
||||||
|
],
|
||||||
|
"references": "people.id"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "notify_token",
|
||||||
|
"type": "text?",
|
||||||
|
"key": "uk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "status",
|
||||||
|
"type": "AttendeeStatus"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "updated_at",
|
||||||
|
"type": "timestamp"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "people",
|
||||||
|
"label": "people",
|
||||||
|
"sublabel": "persona del profe",
|
||||||
|
"tag": "personas",
|
||||||
|
"row": 0,
|
||||||
|
"col": 2,
|
||||||
|
"width": 250,
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/prisma/models/domain.prisma",
|
||||||
|
"line": 75,
|
||||||
|
"end_line": 98
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "apps/backend/prisma/migrations/20261102180000_add_people/migration.sql",
|
||||||
|
"line": 155,
|
||||||
|
"label": "índice parcial"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"attributes": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"key": "pk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_by_id",
|
||||||
|
"type": "text",
|
||||||
|
"key": [
|
||||||
|
"fk",
|
||||||
|
"uk"
|
||||||
|
],
|
||||||
|
"references": "users.id"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "full_name",
|
||||||
|
"type": "text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email",
|
||||||
|
"type": "text?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "phone",
|
||||||
|
"type": "text?",
|
||||||
|
"key": "uk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "guardian_name",
|
||||||
|
"type": "text?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "guardian_phone",
|
||||||
|
"type": "text?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "notes",
|
||||||
|
"type": "text?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "updated_at",
|
||||||
|
"type": "timestamp"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "users",
|
||||||
|
"label": "users",
|
||||||
|
"sublabel": "profesor",
|
||||||
|
"tag": "profesor",
|
||||||
|
"row": 1,
|
||||||
|
"col": 2,
|
||||||
|
"width": 250,
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/prisma/models/auth.prisma",
|
||||||
|
"line": 3,
|
||||||
|
"end_line": 34
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"attributes": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"key": "pk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "name",
|
||||||
|
"type": "text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email",
|
||||||
|
"type": "text",
|
||||||
|
"key": "uk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email_verified",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "image",
|
||||||
|
"type": "text?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "onboarding_completed",
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "country_code",
|
||||||
|
"type": "text?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "plan_selected_at",
|
||||||
|
"type": "timestamp?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "transfer_alias",
|
||||||
|
"type": "text?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "transfer_holder",
|
||||||
|
"type": "text?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "updated_at",
|
||||||
|
"type": "timestamp"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "student_account_people",
|
||||||
|
"label": "student_account_people",
|
||||||
|
"tag": "app de alumnos",
|
||||||
|
"row": 0,
|
||||||
|
"col": 3,
|
||||||
|
"width": 300,
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/prisma/models/student-access.prisma",
|
||||||
|
"line": 40,
|
||||||
|
"end_line": 54
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"attributes": [
|
||||||
|
{
|
||||||
|
"name": "account_id",
|
||||||
|
"type": "text",
|
||||||
|
"key": [
|
||||||
|
"pk",
|
||||||
|
"fk"
|
||||||
|
],
|
||||||
|
"references": "student_accounts.id"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "person_id",
|
||||||
|
"type": "text",
|
||||||
|
"key": [
|
||||||
|
"pk",
|
||||||
|
"fk"
|
||||||
|
],
|
||||||
|
"references": "people.id"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "student_accounts",
|
||||||
|
"label": "student_accounts",
|
||||||
|
"tag": "app de alumnos",
|
||||||
|
"row": 1,
|
||||||
|
"col": 3,
|
||||||
|
"width": 300,
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"path": "apps/backend/prisma/models/student-access.prisma",
|
||||||
|
"line": 10,
|
||||||
|
"end_line": 38
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"attributes": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"key": "pk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "name",
|
||||||
|
"type": "text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "recovery_email",
|
||||||
|
"type": "text?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "recovery_email_verified_at",
|
||||||
|
"type": "timestamp?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "pending_recovery_email",
|
||||||
|
"type": "text?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "welcomed_at",
|
||||||
|
"type": "timestamp?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_by_id",
|
||||||
|
"type": "text",
|
||||||
|
"key": "fk",
|
||||||
|
"references": "users.id"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "updated_at",
|
||||||
|
"type": "timestamp"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"relationships": [
|
||||||
|
{
|
||||||
|
"id": "attendee_group",
|
||||||
|
"from": "attendees",
|
||||||
|
"to": "groups",
|
||||||
|
"label": "en el grupo",
|
||||||
|
"fromCardinality": "many",
|
||||||
|
"fromOptional": true,
|
||||||
|
"toCardinality": "one"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "attendee_person",
|
||||||
|
"from": "attendees",
|
||||||
|
"to": "people",
|
||||||
|
"label": "membresía de",
|
||||||
|
"fromCardinality": "many",
|
||||||
|
"toCardinality": "one"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "person_owner",
|
||||||
|
"from": "people",
|
||||||
|
"to": "users",
|
||||||
|
"label": "del profe",
|
||||||
|
"fromCardinality": "many",
|
||||||
|
"fromOptional": true,
|
||||||
|
"toCardinality": "one"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "group_owner",
|
||||||
|
"from": "groups",
|
||||||
|
"to": "users",
|
||||||
|
"label": "dueño",
|
||||||
|
"fromCardinality": "many",
|
||||||
|
"fromOptional": true,
|
||||||
|
"toCardinality": "one"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "link_person",
|
||||||
|
"from": "student_account_people",
|
||||||
|
"to": "people",
|
||||||
|
"fromCardinality": "many",
|
||||||
|
"fromOptional": true,
|
||||||
|
"toCardinality": "one"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "link_account",
|
||||||
|
"from": "student_account_people",
|
||||||
|
"to": "student_accounts",
|
||||||
|
"fromCardinality": "many",
|
||||||
|
"toCardinality": "one"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "account_owner",
|
||||||
|
"from": "student_accounts",
|
||||||
|
"to": "users",
|
||||||
|
"label": "creada por",
|
||||||
|
"fromCardinality": "many",
|
||||||
|
"fromOptional": true,
|
||||||
|
"toCardinality": "one"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"cards": [
|
||||||
|
{
|
||||||
|
"dot": "cyan",
|
||||||
|
"title": "Unicidad",
|
||||||
|
"items": [
|
||||||
|
"attendees: @@unique(group_id, person_id), una persona está una sola vez en cada grupo.",
|
||||||
|
"people_owner_phone_key: (created_by_id, phone) WHERE phone IS NOT NULL, índice parcial escrito a mano (Prisma no lo modela; el choque llega como P2002)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"dot": "amber",
|
||||||
|
"title": "Qué es de quién",
|
||||||
|
"items": [
|
||||||
|
"people: contacto y notas; editarlos cambia en todos los grupos.",
|
||||||
|
"attendees: status y notify_token por grupo; asistencia, cuotas, alertas y mensajes cuelgan de esta fila (no dibujados).",
|
||||||
|
"El límite del plan cuenta personas con al menos una membresía ACTIVE."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"dot": "emerald",
|
||||||
|
"title": "Borrados",
|
||||||
|
"items": [
|
||||||
|
"Todas las FK son ON DELETE CASCADE.",
|
||||||
|
"Quitar la última membresía borra también la persona, y con ella el vínculo a la cuenta de alumno."
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
12
AGENTS.md
12
AGENTS.md
@@ -84,11 +84,21 @@ 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.
|
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`).
|
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`.
|
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. Lo que arma el backend en español y la UI muestra se redacta en la web a partir de datos estructurados: las alertas de `computeStudentAlerts` traen `razon` + `valores` (la web usa `alertLabel`/`alertDetail` de `features/attention/attention.ts`; `etiqueta`/`detalle` quedan para el backend), y los `message` de la API (importación masiva, preinscripción) se ignoran y se arman con los contadores. Nombres de país: `countryName` (`Intl.DisplayNames`), no `COUNTRY_LABELS`.
|
||||||
|
9. Pendiente: mails, WhatsApp y el manifest de la PWA (`vite.config.ts`) siguen 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).
|
- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
|
||||||
|
|
||||||
## Convenciones repo-específicas
|
## 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.
|
||||||
- **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`).
|
- **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.
|
- **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.
|
- **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.
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "users" ADD COLUMN "locale" TEXT;
|
||||||
@@ -8,6 +8,8 @@ model User {
|
|||||||
image String?
|
image String?
|
||||||
onboardingCompleted Boolean @default(false) @map("onboarding_completed")
|
onboardingCompleted Boolean @default(false) @map("onboarding_completed")
|
||||||
country String? @map("country_code")
|
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).
|
// When the professor chose Free or Pro in the onboarding (mandatory step).
|
||||||
planSelectedAt DateTime? @map("plan_selected_at")
|
planSelectedAt DateTime? @map("plan_selected_at")
|
||||||
// Bank transfer details shown to students when they report a payment.
|
// Bank transfer details shown to students when they report a payment.
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export function conflictProblem(params: {
|
|||||||
detail: string;
|
detail: string;
|
||||||
code?: string;
|
code?: string;
|
||||||
instance?: string;
|
instance?: string;
|
||||||
|
params?: ProblemDetails['params'];
|
||||||
}): ProblemDetails {
|
}): ProblemDetails {
|
||||||
return {
|
return {
|
||||||
type: `${PROBLEM_DOMAIN}/problems/conflict`,
|
type: `${PROBLEM_DOMAIN}/problems/conflict`,
|
||||||
@@ -29,6 +30,7 @@ export function conflictProblem(params: {
|
|||||||
detail: params.detail,
|
detail: params.detail,
|
||||||
instance: params.instance,
|
instance: params.instance,
|
||||||
code: params.code,
|
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 ${capacity} miembros.`
|
||||||
: 'El grupo alcanzó su cupo máximo de miembros.',
|
: 'El grupo alcanzó su cupo máximo de miembros.',
|
||||||
code: 'group_capacity_reached',
|
code: 'group_capacity_reached',
|
||||||
|
...(capacity ? { params: { capacity } } : {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,13 +219,18 @@ export function noAttendeesToBillProblem(): ProblemDetails {
|
|||||||
code: 'no_attendees_to_bill',
|
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 {
|
return {
|
||||||
type: `${PROBLEM_DOMAIN}/problems/plan`,
|
type: `${PROBLEM_DOMAIN}/problems/plan`,
|
||||||
title: 'Payment Required',
|
title: 'Payment Required',
|
||||||
status: 402,
|
status: 402,
|
||||||
detail: params.detail,
|
detail: params.detail,
|
||||||
code: params.code,
|
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} ${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.`,
|
: `El plan Free permite hasta ${max} alumnos activos. Pasate a Pro para sumar más.`,
|
||||||
code: 'plan_limit_reached',
|
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.'
|
? 'Cobrar con Mercado Pago está disponible en el plan Pro.'
|
||||||
: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
|
: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
|
||||||
code: 'plan_feature_required',
|
code: 'plan_feature_required',
|
||||||
|
params: { feature },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { passkey } from '@better-auth/passkey';
|
import { passkey } from '@better-auth/passkey';
|
||||||
|
import { appLocaleSchema } from '@gruperly/shared';
|
||||||
import { betterAuth } from 'better-auth';
|
import { betterAuth } from 'better-auth';
|
||||||
import { prismaAdapter } from 'better-auth/adapters/prisma';
|
import { prismaAdapter } from 'better-auth/adapters/prisma';
|
||||||
import { organization } from 'better-auth/plugins/organization';
|
import { organization } from 'better-auth/plugins/organization';
|
||||||
@@ -11,6 +12,18 @@ export const auth = betterAuth({
|
|||||||
database: prismaAdapter(getPrismaClient(), {
|
database: prismaAdapter(getPrismaClient(), {
|
||||||
provider: 'postgresql',
|
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: {
|
emailAndPassword: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
minPasswordLength: 8,
|
minPasswordLength: 8,
|
||||||
|
|||||||
@@ -95,6 +95,8 @@ describe('computeStudentAlerts: pagos', () => {
|
|||||||
gravedad: 'vigilar',
|
gravedad: 'vigilar',
|
||||||
etiqueta: 'Cuota vencida',
|
etiqueta: 'Cuota vencida',
|
||||||
detalle: 'La cuota de octubre venció el 10/10.',
|
detalle: 'La cuota de octubre venció el 10/10.',
|
||||||
|
razon: 'cuota',
|
||||||
|
valores: { cuotas: 1, vencimientos: ['2026-10-10T12:00:00.000Z'] },
|
||||||
firma: 'pay_1',
|
firma: 'pay_1',
|
||||||
peso: 1,
|
peso: 1,
|
||||||
},
|
},
|
||||||
|
|||||||
3
apps/web/bunfig.toml
Normal file
3
apps/web/bunfig.toml
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
[test]
|
||||||
|
# Inicializa i18n en es-AR: los tests asertan el copy en español.
|
||||||
|
preload = ["./test/setup.ts"]
|
||||||
@@ -21,10 +21,12 @@
|
|||||||
"@tanstack/react-router": "^1.170.38",
|
"@tanstack/react-router": "^1.170.38",
|
||||||
"better-auth": "1.7.2",
|
"better-auth": "1.7.2",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
"i18next": "^26.5.11",
|
||||||
"lucide-react": "^1.34.0",
|
"lucide-react": "^1.34.0",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
"react-hook-form": "^7.54.0",
|
"react-hook-form": "^7.54.0",
|
||||||
|
"react-i18next": "^17.1.9",
|
||||||
"tailwind-merge": "^3.6.0",
|
"tailwind-merge": "^3.6.0",
|
||||||
"zod": "3.24.2"
|
"zod": "3.24.2"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
import { Link, useLocation } from '@tanstack/react-router'
|
import { Link, useLocation } from '@tanstack/react-router'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { NavBadge } from './NavBadge'
|
import { NavBadge } from './NavBadge'
|
||||||
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
||||||
|
|
||||||
export function BottomNav() {
|
export function BottomNav() {
|
||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
|
const { t } = useTranslation('layout')
|
||||||
|
|
||||||
return (
|
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">
|
<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">
|
<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)
|
const isActive = isNavItemActive(location.pathname, to)
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
@@ -32,7 +34,7 @@ export function BottomNav() {
|
|||||||
<Icon className="size-5" strokeWidth={isActive ? 2.25 : 2} />
|
<Icon className="size-5" strokeWidth={isActive ? 2.25 : 2} />
|
||||||
{badge ? <NavBadge kind={badge} className="absolute -right-2.5 -top-1.5" /> : null}
|
{badge ? <NavBadge kind={badge} className="absolute -right-2.5 -top-1.5" /> : null}
|
||||||
</span>
|
</span>
|
||||||
<span className="leading-none">{label}</span>
|
<span className="leading-none">{t(labelKey)}</span>
|
||||||
</Link>
|
</Link>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -1,52 +1,55 @@
|
|||||||
import { Link, useLocation } from '@tanstack/react-router'
|
import { Link, useLocation } from '@tanstack/react-router'
|
||||||
import { ChevronRight } from 'lucide-react'
|
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[]> = {
|
const BREADCRUMBS: Record<string, Crumb[]> = {
|
||||||
'/': [{ label: 'Inicio' }],
|
'/': [{ label: 'home' }],
|
||||||
'/groups': [
|
'/groups': [
|
||||||
{ label: 'Inicio', to: '/' },
|
{ label: 'home', to: '/' },
|
||||||
{ label: 'Grupos' },
|
{ label: 'groups' },
|
||||||
],
|
],
|
||||||
'/payments': [
|
'/payments': [
|
||||||
{ label: 'Inicio', to: '/' },
|
{ label: 'home', to: '/' },
|
||||||
{ label: 'Cobros' },
|
{ label: 'payments' },
|
||||||
],
|
],
|
||||||
'/settings': [
|
'/settings': [
|
||||||
{ label: 'Inicio', to: '/' },
|
{ label: 'home', to: '/' },
|
||||||
{ label: 'Ajustes' },
|
{ label: 'settings' },
|
||||||
],
|
],
|
||||||
'/security': [
|
'/security': [
|
||||||
{ label: 'Inicio', to: '/' },
|
{ label: 'home', to: '/' },
|
||||||
{ label: 'Ajustes', to: '/settings' },
|
{ label: 'settings', to: '/settings' },
|
||||||
{ label: 'Seguridad' },
|
{ label: 'security' },
|
||||||
],
|
],
|
||||||
'/profile': [
|
'/profile': [
|
||||||
{ label: 'Inicio', to: '/' },
|
{ label: 'home', to: '/' },
|
||||||
{ label: 'Mi perfil' },
|
{ label: 'profile' },
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Breadcrumb() {
|
export function Breadcrumb() {
|
||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
const crumbs = BREADCRUMBS[location.pathname] ?? [{ label: 'Inicio' }]
|
const { t } = useTranslation('layout')
|
||||||
|
const crumbs = BREADCRUMBS[location.pathname] ?? [{ label: 'home' }]
|
||||||
|
|
||||||
return (
|
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) => {
|
{crumbs.map((crumb, i) => {
|
||||||
const isLast = i === crumbs.length - 1
|
const isLast = i === crumbs.length - 1
|
||||||
return (
|
return (
|
||||||
<span key={crumb.label} className="flex items-center gap-1.5">
|
<span key={crumb.label} className="flex items-center gap-1.5">
|
||||||
{i > 0 ? <ChevronRight className="size-3.5 text-foreground/40" /> : null}
|
{i > 0 ? <ChevronRight className="size-3.5 text-foreground/40" /> : null}
|
||||||
{isLast ? (
|
{isLast ? (
|
||||||
<span className="font-medium text-primary">{crumb.label}</span>
|
<span className="font-medium text-primary">{t(`nav.${crumb.label}`)}</span>
|
||||||
) : (
|
) : (
|
||||||
<Link
|
<Link
|
||||||
to={crumb.to!}
|
to={crumb.to!}
|
||||||
className="text-foreground/50 transition-colors hover:text-primary"
|
className="text-foreground/50 transition-colors hover:text-primary"
|
||||||
>
|
>
|
||||||
{crumb.label}
|
{t(`nav.${crumb.label}`)}
|
||||||
</Link>
|
</Link>
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { Logo } from '../brand'
|
import { Logo } from '../brand'
|
||||||
import { Breadcrumb } from './Breadcrumb'
|
import { Breadcrumb } from './Breadcrumb'
|
||||||
import { ThemeToggle } from './ThemeToggle'
|
import { ThemeToggle } from './ThemeToggle'
|
||||||
import { UserMenu } from './UserMenu'
|
import { UserMenu } from './UserMenu'
|
||||||
|
|
||||||
export function Header() {
|
export function Header() {
|
||||||
|
const { t } = useTranslation('layout')
|
||||||
return (
|
return (
|
||||||
<header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur">
|
<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">
|
<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
|
{/* `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
|
home screen and an anchor would reload the whole document, losing
|
||||||
the in-memory state (React Query cache, install event). */}
|
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" />
|
<Logo className="h-8" />
|
||||||
</Link>
|
</Link>
|
||||||
<Breadcrumb />
|
<Breadcrumb />
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { useReportedPaymentsCount } from '../../features/payments/reportedPayments'
|
import { useReportedPaymentsCount } from '../../features/payments/reportedPayments'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
|
|
||||||
/* Counter of a nav item: today only "Pagos para verificar" on Cobros. The
|
/* 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. */
|
number is in the accessible name too (sr-only), not only in the dot. */
|
||||||
export function NavBadge({ kind, className }: { kind: 'reported-payments'; className?: string }) {
|
export function NavBadge({ kind, className }: { kind: 'reported-payments'; className?: string }) {
|
||||||
const count = useReportedPaymentsCount()
|
const count = useReportedPaymentsCount()
|
||||||
|
const { t } = useTranslation('layout')
|
||||||
if (kind !== 'reported-payments' || count === 0) return null
|
if (kind !== 'reported-payments' || count === 0) return null
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
@@ -13,8 +15,8 @@ export function NavBadge({ kind, className }: { kind: 'reported-payments'; class
|
|||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{count > 99 ? '99+' : count}
|
<span aria-hidden="true">{count > 99 ? '99+' : count}</span>
|
||||||
<span className="sr-only"> pagos para verificar</span>
|
<span className="sr-only">{t('reportedPayments', { count })}</span>
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function PublicFooter() {
|
export function PublicFooter() {
|
||||||
|
const { t } = useTranslation('layout')
|
||||||
return (
|
return (
|
||||||
<footer className="border-t border-border px-4 py-4 text-center text-xs text-foreground/40">
|
<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>
|
</footer>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Link, useLocation } from '@tanstack/react-router'
|
import { Link, useLocation } from '@tanstack/react-router'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { Logo } from '../brand'
|
import { Logo } from '../brand'
|
||||||
import { NavBadge } from './NavBadge'
|
import { NavBadge } from './NavBadge'
|
||||||
@@ -6,6 +7,7 @@ import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
|||||||
|
|
||||||
export function Sidebar({ immersive = false }: { immersive?: boolean }) {
|
export function Sidebar({ immersive = false }: { immersive?: boolean }) {
|
||||||
const location = useLocation()
|
const location = useLocation()
|
||||||
|
const { t } = useTranslation('layout')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
// Without the global header there's nothing to clear above: the sidebar
|
// 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
|
{/* `Link` and not `<a>`: an anchor would reload the document and lose the
|
||||||
in-memory state (React Query cache, install event). */}
|
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" />
|
<Logo className="h-10" />
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
<nav className="flex flex-col gap-1">
|
<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)
|
const isActive = isNavItemActive(location.pathname, to)
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
@@ -39,7 +41,7 @@ export function Sidebar({ immersive = false }: { immersive?: boolean }) {
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<Icon className="size-5" strokeWidth={isActive ? 2.2 : 2} />
|
<Icon className="size-5" strokeWidth={isActive ? 2.2 : 2} />
|
||||||
{label}
|
{t(labelKey)}
|
||||||
{badge ? <NavBadge kind={badge} className="ml-auto" /> : null}
|
{badge ? <NavBadge kind={badge} className="ml-auto" /> : null}
|
||||||
</Link>
|
</Link>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
import { Moon, Sun } from 'lucide-react'
|
import { Moon, Sun } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useTheme } from '../../context/ThemeProvider'
|
import { useTheme } from '../../context/ThemeProvider'
|
||||||
|
|
||||||
export function ThemeToggle() {
|
export function ThemeToggle() {
|
||||||
const { isDark, setTheme } = useTheme()
|
const { isDark, setTheme } = useTheme()
|
||||||
|
const { t } = useTranslation('layout')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setTheme(isDark ? 'light' : 'dark')}
|
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"
|
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" />}
|
{isDark ? <Sun className="size-4" /> : <Moon className="size-4" />}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { createPortal } from 'react-dom'
|
import { createPortal } from 'react-dom'
|
||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
import { Link, useNavigate } from '@tanstack/react-router'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { ChevronDown, LogOut, Settings, ShieldCheck, UserRound, X } from 'lucide-react'
|
import { ChevronDown, LogOut, Settings, ShieldCheck, UserRound, X } from 'lucide-react'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { signOut } from '../../lib/auth-client'
|
import { signOut } from '../../lib/auth-client'
|
||||||
@@ -18,6 +19,7 @@ export function UserMenu() {
|
|||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const ref = useRef<HTMLDivElement>(null)
|
const ref = useRef<HTMLDivElement>(null)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { t } = useTranslation(['layout', 'common'])
|
||||||
// Solo el equipo de Gruperly ve el acceso al backoffice.
|
// Solo el equipo de Gruperly ve el acceso al backoffice.
|
||||||
const isAdmin = useAdminAccess(!!user).data?.isAdmin ?? false
|
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" />
|
<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="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>
|
</span>
|
||||||
<ChevronDown
|
<ChevronDown
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -88,7 +90,7 @@ export function UserMenu() {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setOpen(false)}
|
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"
|
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" />
|
<X className="size-5" />
|
||||||
@@ -102,7 +104,7 @@ export function UserMenu() {
|
|||||||
/>
|
/>
|
||||||
<div>
|
<div>
|
||||||
<p className="text-base font-semibold text-primary">
|
<p className="text-base font-semibold text-primary">
|
||||||
{user?.name ?? 'Usuario'}
|
{user?.name ?? t('common:user.fallbackName')}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-sm text-foreground/50">{user?.email}</p>
|
<p className="text-sm text-foreground/50">{user?.email}</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -116,7 +118,7 @@ export function UserMenu() {
|
|||||||
className={cn(itemClass, 'py-3.5')}
|
className={cn(itemClass, 'py-3.5')}
|
||||||
>
|
>
|
||||||
<UserRound className="size-5 text-foreground/60" />
|
<UserRound className="size-5 text-foreground/60" />
|
||||||
Mi perfil
|
{t('userMenu.profile')}
|
||||||
</Link>
|
</Link>
|
||||||
<Link
|
<Link
|
||||||
role="menuitem"
|
role="menuitem"
|
||||||
@@ -125,7 +127,7 @@ export function UserMenu() {
|
|||||||
className={cn(itemClass, 'py-3.5')}
|
className={cn(itemClass, 'py-3.5')}
|
||||||
>
|
>
|
||||||
<Settings className="size-5 text-foreground/60" />
|
<Settings className="size-5 text-foreground/60" />
|
||||||
Ajustes
|
{t('userMenu.settings')}
|
||||||
</Link>
|
</Link>
|
||||||
{isAdmin ? (
|
{isAdmin ? (
|
||||||
<Link
|
<Link
|
||||||
@@ -135,7 +137,7 @@ export function UserMenu() {
|
|||||||
className={cn(itemClass, 'py-3.5')}
|
className={cn(itemClass, 'py-3.5')}
|
||||||
>
|
>
|
||||||
<ShieldCheck className="size-5 text-foreground/60" />
|
<ShieldCheck className="size-5 text-foreground/60" />
|
||||||
Backoffice
|
{t('userMenu.admin')}
|
||||||
</Link>
|
</Link>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
@@ -150,7 +152,7 @@ export function UserMenu() {
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<LogOut className="size-5 text-foreground/60" />
|
<LogOut className="size-5 text-foreground/60" />
|
||||||
Cerrar sesión
|
{t('userMenu.signOut')}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</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"
|
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">
|
<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>
|
<p className="truncate text-xs text-foreground/50">{user?.email}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="mx-3 my-1 h-px bg-border" />
|
<div className="mx-3 my-1 h-px bg-border" />
|
||||||
<Link role="menuitem" to="/profile" onClick={() => setOpen(false)} className={itemClass}>
|
<Link role="menuitem" to="/profile" onClick={() => setOpen(false)} className={itemClass}>
|
||||||
<UserRound className="size-4 text-foreground/60" />
|
<UserRound className="size-4 text-foreground/60" />
|
||||||
Mi perfil
|
{t('userMenu.profile')}
|
||||||
</Link>
|
</Link>
|
||||||
<Link role="menuitem" to="/settings" onClick={() => setOpen(false)} className={itemClass}>
|
<Link role="menuitem" to="/settings" onClick={() => setOpen(false)} className={itemClass}>
|
||||||
<Settings className="size-4 text-foreground/60" />
|
<Settings className="size-4 text-foreground/60" />
|
||||||
Ajustes
|
{t('userMenu.settings')}
|
||||||
</Link>
|
</Link>
|
||||||
{isAdmin ? (
|
{isAdmin ? (
|
||||||
<Link role="menuitem" to="/admin" onClick={() => setOpen(false)} className={itemClass}>
|
<Link role="menuitem" to="/admin" onClick={() => setOpen(false)} className={itemClass}>
|
||||||
<ShieldCheck className="size-4 text-foreground/60" />
|
<ShieldCheck className="size-4 text-foreground/60" />
|
||||||
Backoffice
|
{t('userMenu.admin')}
|
||||||
</Link>
|
</Link>
|
||||||
) : null}
|
) : null}
|
||||||
<div className="mx-3 my-1 h-px bg-border" />
|
<div className="mx-3 my-1 h-px bg-border" />
|
||||||
<button type="button" role="menuitem" onClick={handleSignOut} className={itemClass}>
|
<button type="button" role="menuitem" onClick={handleSignOut} className={itemClass}>
|
||||||
<LogOut className="size-4 text-foreground/60" />
|
<LogOut className="size-4 text-foreground/60" />
|
||||||
Cerrar sesión
|
{t('userMenu.signOut')}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { Home, Users, Wallet, Settings, type LucideIcon } from 'lucide-react'
|
import { Home, Users, Wallet, Settings, type LucideIcon } from 'lucide-react'
|
||||||
|
|
||||||
export type NavItem = {
|
export type NavItem = {
|
||||||
label: string
|
/** Clave en el namespace `layout` (`nav.*`). */
|
||||||
|
labelKey: 'nav.home' | 'nav.groups' | 'nav.payments' | 'nav.settings'
|
||||||
to: string
|
to: string
|
||||||
icon: LucideIcon
|
icon: LucideIcon
|
||||||
/** Counter shown on the item (see NavBadge). */
|
/** Counter shown on the item (see NavBadge). */
|
||||||
@@ -9,10 +10,10 @@ export type NavItem = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const NAV_ITEMS: NavItem[] = [
|
export const NAV_ITEMS: NavItem[] = [
|
||||||
{ label: 'Inicio', to: '/', icon: Home },
|
{ labelKey: 'nav.home', to: '/', icon: Home },
|
||||||
{ label: 'Grupos', to: '/groups', icon: Users },
|
{ labelKey: 'nav.groups', to: '/groups', icon: Users },
|
||||||
{ label: 'Cobros', to: '/payments', icon: Wallet, badge: 'reported-payments' },
|
{ labelKey: 'nav.payments', to: '/payments', icon: Wallet, badge: 'reported-payments' },
|
||||||
{ label: 'Ajustes', to: '/settings', icon: Settings },
|
{ labelKey: 'nav.settings', to: '/settings', icon: Settings },
|
||||||
]
|
]
|
||||||
|
|
||||||
/** A section stays active within its subroutes: on `/groups/abc` the active
|
/** A section stays active within its subroutes: on `/groups/abc` the active
|
||||||
|
|||||||
19
apps/web/src/components/ui/field-error.tsx
Normal file
19
apps/web/src/components/ui/field-error.tsx
Normal 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>
|
||||||
|
}
|
||||||
@@ -9,3 +9,4 @@ export { Tooltip, type TooltipProps } from './tooltip'
|
|||||||
|
|
||||||
export { Switch, type SwitchProps } from './switch'
|
export { Switch, type SwitchProps } from './switch'
|
||||||
export { Sheet, type SheetProps } from './sheet'
|
export { Sheet, type SheetProps } from './sheet'
|
||||||
|
export { FieldError } from './field-error'
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, type ReactNode } from 'react';
|
import { useEffect, type ReactNode } from 'react';
|
||||||
import { X } from 'lucide-react';
|
import { X } from 'lucide-react';
|
||||||
import { cn } from '../../lib/utils';
|
import { cn } from '../../lib/utils';
|
||||||
|
import { i18n } from '../../i18n/instance';
|
||||||
|
|
||||||
export type ModalProps = {
|
export type ModalProps = {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
@@ -78,7 +79,7 @@ export function Modal({
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={onClose}
|
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"
|
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" />
|
<X className="size-5" />
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, useId, useRef, type ReactNode } from 'react'
|
import { useEffect, useId, useRef, type ReactNode } from 'react'
|
||||||
import { X } from 'lucide-react'
|
import { X } from 'lucide-react'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
|
|
||||||
export type SheetProps = {
|
export type SheetProps = {
|
||||||
isOpen: boolean
|
isOpen: boolean
|
||||||
@@ -72,7 +73,7 @@ export function Sheet({ isOpen, onClose, title, description, children, className
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={onClose}
|
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"
|
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" />
|
<X className="size-5" />
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
} from 'react';
|
} from 'react';
|
||||||
import { AlertCircle, CheckCircle2, Info, X } from 'lucide-react';
|
import { AlertCircle, CheckCircle2, Info, X } from 'lucide-react';
|
||||||
import { cn } from '../../lib/utils';
|
import { cn } from '../../lib/utils';
|
||||||
|
import { i18n } from '../../i18n/instance';
|
||||||
|
|
||||||
export type ToastType = 'success' | 'error' | 'info';
|
export type ToastType = 'success' | 'error' | 'info';
|
||||||
|
|
||||||
@@ -126,7 +127,7 @@ export function ToastProvider({ children }: { children: ReactNode }) {
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={() => removeToast(toast.id)}
|
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"
|
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" />
|
<X className="size-4" />
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { useMutation, useQuery } from '@tanstack/react-query'
|
|||||||
import type { AbsenceDetails } from '@gruperly/shared'
|
import type { AbsenceDetails } from '@gruperly/shared'
|
||||||
import { useToast } from '../../components/ui'
|
import { useToast } from '../../components/ui'
|
||||||
import { ApiError, getAbsenceDetails, publicNotifyAbsence } from '../../lib/api'
|
import { ApiError, getAbsenceDetails, publicNotifyAbsence } from '../../lib/api'
|
||||||
|
import { errorMessage } from '../../i18n'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
|
|
||||||
type AbsenceNotifyContextValue = {
|
type AbsenceNotifyContextValue = {
|
||||||
token: string
|
token: string
|
||||||
@@ -32,14 +34,14 @@ export function AbsenceNotifyProvider({ token, children }: { token: string; chil
|
|||||||
mutationFn: (sessionId: string) => publicNotifyAbsence({ token, classSessionId: sessionId }),
|
mutationFn: (sessionId: string) => publicNotifyAbsence({ token, classSessionId: sessionId }),
|
||||||
onSuccess: (_data, sessionId) => {
|
onSuccess: (_data, sessionId) => {
|
||||||
setLocallyNotified((prev) => [...prev, sessionId])
|
setLocallyNotified((prev) => [...prev, sessionId])
|
||||||
toast.success('Tu profesor ya tiene registrado el aviso. Gracias por avisar.', 'Ausencia avisada')
|
toast.success(i18n.t('public:absence.done'), i18n.t('public:absence.doneTitle'))
|
||||||
},
|
},
|
||||||
onError: (error: unknown) => {
|
onError: (error: unknown) => {
|
||||||
if (error instanceof ApiError && error.problem?.status === 404) {
|
if (error instanceof ApiError && error.problem?.status === 404) {
|
||||||
toast.error('Este enlace ya no es válido. Consultá a tu profesor.')
|
toast.error(i18n.t('public:absence.invalidLink'))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
toast.error(error instanceof Error ? error.message : 'No pudimos registrar el aviso.')
|
toast.error(errorMessage(error, i18n.t('public:absence.error')))
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ import { PublicFooter, PublicHeader } from '../../components/layout'
|
|||||||
import { Badge } from '../../components/ui'
|
import { Badge } from '../../components/ui'
|
||||||
import { AbsenceSessionRow } from './AbsenceSessionRow'
|
import { AbsenceSessionRow } from './AbsenceSessionRow'
|
||||||
import { useAbsenceNotify } from './AbsenceNotifyProvider'
|
import { useAbsenceNotify } from './AbsenceNotifyProvider'
|
||||||
|
import { Trans, useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function AbsenceNotifyView() {
|
export function AbsenceNotifyView() {
|
||||||
const { details, detailsPending, detailsFailed } = useAbsenceNotify()
|
const { details, detailsPending, detailsFailed } = useAbsenceNotify()
|
||||||
|
const { t } = useTranslation('public')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen flex-col justify-between bg-background text-primary selection:bg-accent selection:text-white">
|
<div className="flex min-h-screen flex-col justify-between bg-background text-primary selection:bg-accent selection:text-white">
|
||||||
@@ -16,15 +18,15 @@ export function AbsenceNotifyView() {
|
|||||||
{detailsPending ? (
|
{detailsPending ? (
|
||||||
<div className="flex flex-col items-center justify-center gap-3 py-20">
|
<div className="flex flex-col items-center justify-center gap-3 py-20">
|
||||||
<Loader2 className="size-8 animate-spin text-accent" />
|
<Loader2 className="size-8 animate-spin text-accent" />
|
||||||
<p className="text-sm text-foreground/60">Cargando tus clases...</p>
|
<p className="text-sm text-foreground/60">{t('absence.loading')}</p>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{detailsFailed || (!details && !detailsPending) ? (
|
{detailsFailed || (!details && !detailsPending) ? (
|
||||||
<div className="space-y-3 rounded-2xl border border-danger/20 bg-danger-soft p-6 text-center sm:p-8">
|
<div className="space-y-3 rounded-2xl border border-danger/20 bg-danger-soft p-6 text-center sm:p-8">
|
||||||
<h2 className="text-xl font-bold text-danger">Enlace no válido</h2>
|
<h2 className="text-xl font-bold text-danger">{t('absence.invalidTitle')}</h2>
|
||||||
<p className="mx-auto max-w-sm text-sm leading-relaxed text-foreground/70">
|
<p className="mx-auto max-w-sm text-sm leading-relaxed text-foreground/70">
|
||||||
No pudimos identificarte con este enlace. Consultá con tu profesor para solicitar uno nuevo.
|
{t('absence.invalidDescription')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -36,18 +38,22 @@ export function AbsenceNotifyView() {
|
|||||||
<CalendarX2 className="size-7" />
|
<CalendarX2 className="size-7" />
|
||||||
</div>
|
</div>
|
||||||
<Badge variant="neutral" className="mb-2">
|
<Badge variant="neutral" className="mb-2">
|
||||||
Aviso de ausencia
|
{t('absence.badge')}
|
||||||
</Badge>
|
</Badge>
|
||||||
<h1 className="text-2xl font-bold text-primary">Hola, {details.fullName}</h1>
|
<h1 className="text-2xl font-bold text-primary">{t('absence.greeting', { name: details.fullName })}</h1>
|
||||||
<p className="mt-1 text-sm font-medium text-foreground/80">
|
<p className="mt-1 text-sm font-medium text-foreground/80">
|
||||||
Grupo: <span className="text-primary">{details.groupName}</span>
|
<Trans
|
||||||
|
t={t}
|
||||||
|
i18nKey="absence.group"
|
||||||
|
values={{ group: details.groupName }}
|
||||||
|
components={{ strong: <span className="text-primary" /> }}
|
||||||
|
/>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{details.sessions.length === 0 ? (
|
{details.sessions.length === 0 ? (
|
||||||
<p className="rounded-xl border border-dashed border-border bg-primary-soft/40 px-4 py-8 text-center text-sm text-foreground/60">
|
<p className="rounded-xl border border-dashed border-border bg-primary-soft/40 px-4 py-8 text-center text-sm text-foreground/60">
|
||||||
No tenés clases programadas para hoy. Si necesitás avisar de todas formas, contactá a tu
|
{t('absence.noClasses')}
|
||||||
profesor.
|
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<ul className="space-y-3">
|
<ul className="space-y-3">
|
||||||
@@ -58,7 +64,7 @@ export function AbsenceNotifyView() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<p className="text-center text-xs leading-relaxed text-foreground/50">
|
<p className="text-center text-xs leading-relaxed text-foreground/50">
|
||||||
Si avisás con anticipación, tu cupo se libera para una clase de recuperación.
|
{t('absence.hint')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { CheckCircle2, Loader2 } from 'lucide-react'
|
import { CheckCircle2, Loader2 } from 'lucide-react'
|
||||||
import { Button } from '../../components/ui'
|
import { Button } from '../../components/ui'
|
||||||
import { useAbsenceNotify } from './AbsenceNotifyProvider'
|
import { useAbsenceNotify } from './AbsenceNotifyProvider'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
import { useIntlLocale } from '../../i18n'
|
||||||
|
|
||||||
type AbsenceSession = {
|
type AbsenceSession = {
|
||||||
sessionId: string
|
sessionId: string
|
||||||
@@ -11,22 +13,20 @@ type AbsenceSession = {
|
|||||||
|
|
||||||
export function AbsenceSessionRow({ session }: { session: AbsenceSession }) {
|
export function AbsenceSessionRow({ session }: { session: AbsenceSession }) {
|
||||||
const { isNotified, isNotifying, notify } = useAbsenceNotify()
|
const { isNotified, isNotifying, notify } = useAbsenceNotify()
|
||||||
const time = new Date(session.startsAt).toLocaleTimeString('es-MX', {
|
const { t } = useTranslation('public')
|
||||||
hour: '2-digit',
|
const locale = useIntlLocale()
|
||||||
minute: '2-digit',
|
const time = new Date(session.startsAt).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' })
|
||||||
hour12: false,
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<li className="flex items-center justify-between gap-3 rounded-xl border border-border bg-primary-soft/30 px-4 py-3">
|
<li className="flex items-center justify-between gap-3 rounded-xl border border-border bg-primary-soft/30 px-4 py-3">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<p className="text-sm font-semibold text-primary">Hoy · {time} hs</p>
|
<p className="text-sm font-semibold text-primary">{t('absence.today', { time })}</p>
|
||||||
<p className="truncate text-xs text-foreground/60">{session.groupName}</p>
|
<p className="truncate text-xs text-foreground/60">{session.groupName}</p>
|
||||||
</div>
|
</div>
|
||||||
{isNotified(session) ? (
|
{isNotified(session) ? (
|
||||||
<span className="inline-flex shrink-0 items-center gap-1.5 rounded-full bg-success-soft px-2.5 py-1 text-xs font-medium text-success">
|
<span className="inline-flex shrink-0 items-center gap-1.5 rounded-full bg-success-soft px-2.5 py-1 text-xs font-medium text-success">
|
||||||
<CheckCircle2 className="size-3.5" />
|
<CheckCircle2 className="size-3.5" />
|
||||||
Ya avisaste
|
{t('absence.notified')}
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<Button
|
<Button
|
||||||
@@ -36,7 +36,7 @@ export function AbsenceSessionRow({ session }: { session: AbsenceSession }) {
|
|||||||
onClick={() => notify(session.sessionId)}
|
onClick={() => notify(session.sessionId)}
|
||||||
>
|
>
|
||||||
{isNotifying(session.sessionId) ? <Loader2 className="size-4 animate-spin" /> : null}
|
{isNotifying(session.sessionId) ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
Avisar ausencia
|
{t('absence.notify')}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</li>
|
</li>
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { useQuery } from '@tanstack/react-query'
|
|||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
import { createContext, useContext } from 'react'
|
import { createContext, useContext } from 'react'
|
||||||
import { ApiError, getAdminAccount } from '../../lib/api'
|
import { ApiError, getAdminAccount } from '../../lib/api'
|
||||||
|
import { errorMessage as apiErrorMessage } from '../../i18n'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
|
|
||||||
type AdminAccountDetailContextValue = {
|
type AdminAccountDetailContextValue = {
|
||||||
account: AdminAccountDetail | null
|
account: AdminAccountDetail | null
|
||||||
@@ -30,9 +32,7 @@ export function AdminAccountDetailProvider({
|
|||||||
const error = accountQuery.error
|
const error = accountQuery.error
|
||||||
const isNotFound = error instanceof ApiError && error.status === 404
|
const isNotFound = error instanceof ApiError && error.status === 404
|
||||||
const errorMessage = accountQuery.isError
|
const errorMessage = accountQuery.isError
|
||||||
? error instanceof ApiError
|
? apiErrorMessage(error, i18n.t('admin:detail.loadError'))
|
||||||
? (error.problem?.detail ?? 'No pudimos cargar la cuenta.')
|
|
||||||
: 'No pudimos cargar la cuenta.'
|
|
||||||
: null
|
: null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -9,15 +9,17 @@ import { BILLING_PROVIDER_NAMES, formatBillingDate, formatUsage, subscriptionSta
|
|||||||
import { useAdminAccountDetail } from './AdminAccountDetailProvider'
|
import { useAdminAccountDetail } from './AdminAccountDetailProvider'
|
||||||
import {
|
import {
|
||||||
countryLabel,
|
countryLabel,
|
||||||
MP_STATUS_LABELS,
|
mpStatusLabel,
|
||||||
planLabel,
|
planLabel,
|
||||||
planVariant,
|
planVariant,
|
||||||
subscriptionVariant,
|
subscriptionVariant,
|
||||||
WHATSAPP_STATUS_LABELS,
|
whatsappStatusLabel,
|
||||||
} from './copy'
|
} from './copy'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function AdminAccountDetailView() {
|
export function AdminAccountDetailView() {
|
||||||
const { account, isPending, isError, isNotFound, errorMessage, retry } = useAdminAccountDetail()
|
const { account, isPending, isError, isNotFound, errorMessage, retry } = useAdminAccountDetail()
|
||||||
|
const { t } = useTranslation(['admin', 'common', 'billing'])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section>
|
<section>
|
||||||
@@ -26,26 +28,26 @@ export function AdminAccountDetailView() {
|
|||||||
className="hidden items-center gap-1.5 text-sm font-medium text-foreground/60 hover:text-primary lg:inline-flex"
|
className="hidden items-center gap-1.5 text-sm font-medium text-foreground/60 hover:text-primary lg:inline-flex"
|
||||||
>
|
>
|
||||||
<ArrowLeft className="size-4" aria-hidden="true" />
|
<ArrowLeft className="size-4" aria-hidden="true" />
|
||||||
Cuentas
|
{t('accounts')}
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
{/* El h1 va siempre, también cargando, para que el layout no salte. */}
|
{/* El h1 va siempre, también cargando, para que el layout no salte. */}
|
||||||
<h1 className="mt-2 truncate text-2xl font-bold text-primary">{account?.name ?? 'Cuenta'}</h1>
|
<h1 className="mt-2 truncate text-2xl font-bold text-primary">{account?.name ?? t('detail.fallback')}</h1>
|
||||||
{account ? <p className="mt-0.5 truncate text-sm text-foreground/60">{account.email}</p> : null}
|
{account ? <p className="mt-0.5 truncate text-sm text-foreground/60">{account.email}</p> : null}
|
||||||
|
|
||||||
{isPending ? (
|
{isPending ? (
|
||||||
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
||||||
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
||||||
<span className="sr-only">Cargando cuenta</span>
|
<span className="sr-only">{t('detail.loading')}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{isError ? (
|
{isError ? (
|
||||||
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
<p>{isNotFound ? 'Esta cuenta no existe.' : errorMessage}</p>
|
<p>{isNotFound ? t('detail.notFound') : errorMessage}</p>
|
||||||
{isNotFound ? null : (
|
{isNotFound ? null : (
|
||||||
<Button variant="outline" size="sm" onClick={retry}>
|
<Button variant="outline" size="sm" onClick={retry}>
|
||||||
Reintentar
|
{t('common:actions.retry')}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -59,65 +61,69 @@ export function AdminAccountDetailView() {
|
|||||||
function AccountDetail({ account }: { account: AdminAccountDetail }) {
|
function AccountDetail({ account }: { account: AdminAccountDetail }) {
|
||||||
const subscription = account.subscription
|
const subscription = account.subscription
|
||||||
const limits = PLAN_LIMITS[account.plan ?? 'FREE']
|
const limits = PLAN_LIMITS[account.plan ?? 'FREE']
|
||||||
|
const { t } = useTranslation(['admin', 'common', 'billing'])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mt-6 grid gap-4 lg:grid-cols-2">
|
<div className="mt-6 grid gap-4 lg:grid-cols-2">
|
||||||
<Card title="Cuenta">
|
<Card title={t('detail.account')}>
|
||||||
<Field label="País">{countryLabel(account.country)}</Field>
|
<Field label={t('detail.country')}>{countryLabel(account.country)}</Field>
|
||||||
<Field label="Alta">{formatBillingDate(account.createdAt)}</Field>
|
<Field label={t('detail.createdAt')}>{formatBillingDate(account.createdAt)}</Field>
|
||||||
<Field label="Onboarding">{account.onboardingCompleted ? 'Completo' : 'Sin terminar'}</Field>
|
<Field label={t('detail.onboarding')}>
|
||||||
<Field label="Mercado Pago">{MP_STATUS_LABELS[account.mpStatus ?? 'NONE']}</Field>
|
{account.onboardingCompleted ? t('detail.onboardingDone') : t('detail.onboardingPending')}
|
||||||
<Field label="WhatsApp">{WHATSAPP_STATUS_LABELS[account.whatsappStatus ?? 'NONE']}</Field>
|
</Field>
|
||||||
|
<Field label="Mercado Pago">{mpStatusLabel(account.mpStatus)}</Field>
|
||||||
|
<Field label="WhatsApp">{whatsappStatusLabel(account.whatsappStatus)}</Field>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card title="Plan">
|
<Card title={t('detail.plan')}>
|
||||||
<Field label="Plan">
|
<Field label={t('detail.plan')}>
|
||||||
<span className="inline-flex flex-wrap items-center gap-1.5">
|
<span className="inline-flex flex-wrap items-center gap-1.5">
|
||||||
<Badge variant={planVariant(account.plan)}>{planLabel(account.plan)}</Badge>
|
<Badge variant={planVariant(account.plan)}>{planLabel(account.plan)}</Badge>
|
||||||
{account.readOnly ? <Badge variant="danger">Solo lectura</Badge> : null}
|
{account.readOnly ? <Badge variant="danger">{t('detail.readOnly')}</Badge> : null}
|
||||||
</span>
|
</span>
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="Elegido el">{formatBillingDate(account.planSelectedAt) ?? '—'}</Field>
|
<Field label={t('detail.chosenOn')}>{formatBillingDate(account.planSelectedAt) ?? '—'}</Field>
|
||||||
<Field label="Suscripción">
|
<Field label={t('detail.subscription')}>
|
||||||
<Badge variant={subscriptionVariant(subscription?.status ?? null)}>
|
<Badge variant={subscriptionVariant(subscription?.status ?? null)}>
|
||||||
{subscriptionStatusLabel(subscription?.status ?? null)}
|
{subscriptionStatusLabel(subscription?.status ?? null)}
|
||||||
</Badge>
|
</Badge>
|
||||||
</Field>
|
</Field>
|
||||||
{subscription ? (
|
{subscription ? (
|
||||||
<>
|
<>
|
||||||
<Field label="Cobra">{BILLING_PROVIDER_NAMES[subscription.provider]}</Field>
|
<Field label={t('detail.provider')}>{BILLING_PROVIDER_NAMES[subscription.provider]}</Field>
|
||||||
<Field label="Precio">{formatPrice(subscription.amount, subscription.currency)} / mes</Field>
|
<Field label={t('detail.price')}>
|
||||||
<Field label="Pagado hasta">{formatBillingDate(subscription.paidThrough) ?? '—'}</Field>
|
{t('detail.perMonth', { price: formatPrice(subscription.amount, subscription.currency) })}
|
||||||
<Field label="Próximo cobro">{formatBillingDate(subscription.nextPaymentDate) ?? '—'}</Field>
|
</Field>
|
||||||
<Field label="Email de pago">{subscription.payerEmail}</Field>
|
<Field label={t('detail.paidThrough')}>{formatBillingDate(subscription.paidThrough) ?? '—'}</Field>
|
||||||
|
<Field label={t('detail.nextPayment')}>{formatBillingDate(subscription.nextPaymentDate) ?? '—'}</Field>
|
||||||
|
<Field label={t('detail.payerEmail')}>{subscription.payerEmail}</Field>
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
{account.graceUntil ? (
|
{account.graceUntil ? (
|
||||||
<Field label="En gracia hasta">{formatBillingDate(account.graceUntil)}</Field>
|
<Field label={t('detail.graceUntil')}>{formatBillingDate(account.graceUntil)}</Field>
|
||||||
) : null}
|
) : null}
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card title="Uso">
|
<Card title={t('detail.usage')}>
|
||||||
<Field label="Grupos">{formatUsage(account.groupsCount, limits.maxGroups)}</Field>
|
<Field label={t('detail.groups')}>{formatUsage(account.groupsCount, limits.maxGroups)}</Field>
|
||||||
<Field label="Alumnos activos">{formatUsage(account.attendeesCount, limits.maxAttendees)}</Field>
|
<Field label={t('detail.students')}>{formatUsage(account.attendeesCount, limits.maxAttendees)}</Field>
|
||||||
{account.groups.length > 0 ? (
|
{account.groups.length > 0 ? (
|
||||||
<ul className="mt-2 divide-y divide-border border-t border-border">
|
<ul className="mt-2 divide-y divide-border border-t border-border">
|
||||||
{account.groups.map((group) => (
|
{account.groups.map((group) => (
|
||||||
<li key={group.id} className="flex items-center justify-between gap-3 py-2 text-sm">
|
<li key={group.id} className="flex items-center justify-between gap-3 py-2 text-sm">
|
||||||
<span className="min-w-0 truncate text-primary">{group.name}</span>
|
<span className="min-w-0 truncate text-primary">{group.name}</span>
|
||||||
<span className="shrink-0 text-xs text-foreground/60">
|
<span className="shrink-0 text-xs text-foreground/60">
|
||||||
{group.attendeesCount} {group.attendeesCount === 1 ? 'alumno' : 'alumnos'} · desde{' '}
|
{t('detail.groupLine', { count: group.attendeesCount, date: formatBillingDate(group.createdAt) })}
|
||||||
{formatBillingDate(group.createdAt)}
|
|
||||||
</span>
|
</span>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
) : (
|
) : (
|
||||||
<p className="mt-2 text-sm text-foreground/60">Todavía no creó grupos.</p>
|
<p className="mt-2 text-sm text-foreground/60">{t('detail.noGroups')}</p>
|
||||||
)}
|
)}
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card title="Cobros de Gruperly">
|
<Card title={t('detail.charges')}>
|
||||||
{account.charges.length > 0 ? (
|
{account.charges.length > 0 ? (
|
||||||
<ul className="divide-y divide-border">
|
<ul className="divide-y divide-border">
|
||||||
{account.charges.map((charge) => (
|
{account.charges.map((charge) => (
|
||||||
@@ -135,7 +141,7 @@ function AccountDetail({ account }: { account: AdminAccountDetail }) {
|
|||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
) : (
|
) : (
|
||||||
<p className="text-sm text-foreground/60">Sin cobros registrados.</p>
|
<p className="text-sm text-foreground/60">{t('detail.noCharges')}</p>
|
||||||
)}
|
)}
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { Badge } from '../../components/ui'
|
|||||||
import { formatPrice } from '../../lib/format'
|
import { formatPrice } from '../../lib/format'
|
||||||
import { formatBillingDate, subscriptionStatusLabel } from '../billing'
|
import { formatBillingDate, subscriptionStatusLabel } from '../billing'
|
||||||
import { countryLabel, planLabel, planVariant, subscriptionVariant } from './copy'
|
import { countryLabel, planLabel, planVariant, subscriptionVariant } from './copy'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
/** Columnas de la grilla en `lg+`; el encabezado de `AdminAccountsView` usa las mismas. */
|
/** Columnas de la grilla en `lg+`; el encabezado de `AdminAccountsView` usa las mismas. */
|
||||||
export const ACCOUNT_GRID_COLUMNS =
|
export const ACCOUNT_GRID_COLUMNS =
|
||||||
@@ -13,6 +14,7 @@ export const ACCOUNT_GRID_COLUMNS =
|
|||||||
/* Una cuenta de la lista: tarjeta en móvil, fila de la grilla en escritorio. */
|
/* Una cuenta de la lista: tarjeta en móvil, fila de la grilla en escritorio. */
|
||||||
export function AdminAccountRow({ account }: { account: AdminAccountListItem }) {
|
export function AdminAccountRow({ account }: { account: AdminAccountListItem }) {
|
||||||
const subscription = account.subscription
|
const subscription = account.subscription
|
||||||
|
const { t } = useTranslation(['admin', 'common', 'billing'])
|
||||||
const status = subscription?.status ?? null
|
const status = subscription?.status ?? null
|
||||||
const paidThrough = formatBillingDate(subscription?.paidThrough ?? null)
|
const paidThrough = formatBillingDate(subscription?.paidThrough ?? null)
|
||||||
const planBadge = <Badge variant={planVariant(account.plan)}>{planLabel(account.plan)}</Badge>
|
const planBadge = <Badge variant={planVariant(account.plan)}>{planLabel(account.plan)}</Badge>
|
||||||
@@ -39,9 +41,8 @@ export function AdminAccountRow({ account }: { account: AdminAccountListItem })
|
|||||||
{statusBadge}
|
{statusBadge}
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-2 text-xs text-foreground/60">
|
<p className="mt-2 text-xs text-foreground/60">
|
||||||
{countryLabel(account.country)} · {account.groupsCount}{' '}
|
{countryLabel(account.country)} · {t('row.groups', { count: account.groupsCount })} ·{' '}
|
||||||
{account.groupsCount === 1 ? 'grupo' : 'grupos'} · {account.attendeesCount}{' '}
|
{t('row.students', { count: account.attendeesCount })}
|
||||||
{account.attendeesCount === 1 ? 'alumno' : 'alumnos'}
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -58,7 +59,7 @@ export function AdminAccountRow({ account }: { account: AdminAccountListItem })
|
|||||||
{subscription ? (
|
{subscription ? (
|
||||||
<p className="mt-1 truncate text-xs text-foreground/50">
|
<p className="mt-1 truncate text-xs text-foreground/50">
|
||||||
{formatPrice(subscription.amount, subscription.currency)}
|
{formatPrice(subscription.amount, subscription.currency)}
|
||||||
{paidThrough ? ` · hasta ${paidThrough}` : ''}
|
{paidThrough ? t('row.until', { date: paidThrough }) : ''}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import { useQuery } from '@tanstack/react-query'
|
|||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
|
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
|
||||||
import { ApiError, getAdminAccounts } from '../../lib/api'
|
import { ApiError, getAdminAccounts } from '../../lib/api'
|
||||||
|
import { errorMessage as apiErrorMessage } from '../../i18n'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
|
|
||||||
const PAGE_SIZE = 20
|
const PAGE_SIZE = 20
|
||||||
const SEARCH_DEBOUNCE_MS = 300
|
const SEARCH_DEBOUNCE_MS = 300
|
||||||
@@ -73,9 +75,7 @@ export function AdminAccountsProvider({ children }: { children: ReactNode }) {
|
|||||||
|
|
||||||
const data = accountsQuery.data
|
const data = accountsQuery.data
|
||||||
const errorMessage = accountsQuery.isError
|
const errorMessage = accountsQuery.isError
|
||||||
? accountsQuery.error instanceof ApiError
|
? apiErrorMessage(accountsQuery.error, i18n.t('admin:loadError'))
|
||||||
? (accountsQuery.error.problem?.detail ?? 'No pudimos cargar las cuentas.')
|
|
||||||
: 'No pudimos cargar las cuentas.'
|
|
||||||
: null
|
: null
|
||||||
|
|
||||||
// Cambiar un filtro vuelve a la primera página.
|
// Cambiar un filtro vuelve a la primera página.
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ import { Button, Input } from '../../components/ui'
|
|||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { ACCOUNT_GRID_COLUMNS, AdminAccountRow } from './AdminAccountRow'
|
import { ACCOUNT_GRID_COLUMNS, AdminAccountRow } from './AdminAccountRow'
|
||||||
import { useAdminAccounts } from './AdminAccountsProvider'
|
import { useAdminAccounts } from './AdminAccountsProvider'
|
||||||
import { COUNTRY_OPTIONS, PLAN_FILTER_OPTIONS, SUBSCRIPTION_FILTER_OPTIONS } from './copy'
|
import { countryOptions, planFilterOptions, subscriptionFilterOptions } from './copy'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
const selectClass =
|
const selectClass =
|
||||||
'h-10 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30'
|
'h-10 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30'
|
||||||
@@ -30,21 +31,22 @@ export function AdminAccountsView() {
|
|||||||
setPage,
|
setPage,
|
||||||
retry,
|
retry,
|
||||||
} = useAdminAccounts()
|
} = useAdminAccounts()
|
||||||
|
const { t } = useTranslation(['admin', 'common', 'billing'])
|
||||||
|
|
||||||
const hasFilters = !!search.trim() || !!country || !!plan || !!subscriptionStatus
|
const hasFilters = !!search.trim() || !!country || !!plan || !!subscriptionStatus
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section>
|
<section>
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-primary">Cuentas</h1>
|
<h1 className="text-2xl font-bold text-primary">{t('accounts')}</h1>
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
<p className="mt-1 text-sm text-foreground/60">
|
||||||
Profesores que usan Gruperly, con su plan y su uso.
|
{t('subtitle')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-[minmax(0,2fr)_repeat(3,minmax(0,1fr))]">
|
<div className="mt-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-[minmax(0,2fr)_repeat(3,minmax(0,1fr))]">
|
||||||
<label className="block sm:col-span-2 lg:col-span-1">
|
<label className="block sm:col-span-2 lg:col-span-1">
|
||||||
<span className="mb-1.5 block text-sm font-medium text-primary">Buscar</span>
|
<span className="mb-1.5 block text-sm font-medium text-primary">{t('filters.search')}</span>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Search
|
<Search
|
||||||
className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/40"
|
className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/40"
|
||||||
@@ -55,21 +57,21 @@ export function AdminAccountsView() {
|
|||||||
autoFocus
|
autoFocus
|
||||||
value={search}
|
value={search}
|
||||||
onChange={(event) => setSearch(event.target.value)}
|
onChange={(event) => setSearch(event.target.value)}
|
||||||
placeholder="Nombre o email"
|
placeholder={t('filters.searchPlaceholder')}
|
||||||
className="pl-9"
|
className="pl-9"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<label className="block">
|
<label className="block">
|
||||||
<span className="mb-1.5 block text-sm font-medium text-primary">País</span>
|
<span className="mb-1.5 block text-sm font-medium text-primary">{t('filters.country')}</span>
|
||||||
<select
|
<select
|
||||||
value={country ?? ''}
|
value={country ?? ''}
|
||||||
onChange={(event) => setCountry((event.target.value || null) as CountryCode | null)}
|
onChange={(event) => setCountry((event.target.value || null) as CountryCode | null)}
|
||||||
className={selectClass}
|
className={selectClass}
|
||||||
>
|
>
|
||||||
<option value="">Todos</option>
|
<option value="">{t('filters.all')}</option>
|
||||||
{COUNTRY_OPTIONS.map((option) => (
|
{countryOptions().map((option) => (
|
||||||
<option key={option.value} value={option.value}>
|
<option key={option.value} value={option.value}>
|
||||||
{option.label}
|
{option.label}
|
||||||
</option>
|
</option>
|
||||||
@@ -78,14 +80,14 @@ export function AdminAccountsView() {
|
|||||||
</label>
|
</label>
|
||||||
|
|
||||||
<label className="block">
|
<label className="block">
|
||||||
<span className="mb-1.5 block text-sm font-medium text-primary">Plan</span>
|
<span className="mb-1.5 block text-sm font-medium text-primary">{t('filters.plan')}</span>
|
||||||
<select
|
<select
|
||||||
value={plan ?? ''}
|
value={plan ?? ''}
|
||||||
onChange={(event) => setPlan((event.target.value || null) as AdminPlanFilter | null)}
|
onChange={(event) => setPlan((event.target.value || null) as AdminPlanFilter | null)}
|
||||||
className={selectClass}
|
className={selectClass}
|
||||||
>
|
>
|
||||||
<option value="">Todos</option>
|
<option value="">{t('filters.all')}</option>
|
||||||
{PLAN_FILTER_OPTIONS.map((option) => (
|
{planFilterOptions().map((option) => (
|
||||||
<option key={option.value} value={option.value}>
|
<option key={option.value} value={option.value}>
|
||||||
{option.label}
|
{option.label}
|
||||||
</option>
|
</option>
|
||||||
@@ -94,7 +96,7 @@ export function AdminAccountsView() {
|
|||||||
</label>
|
</label>
|
||||||
|
|
||||||
<label className="block">
|
<label className="block">
|
||||||
<span className="mb-1.5 block text-sm font-medium text-primary">Suscripción</span>
|
<span className="mb-1.5 block text-sm font-medium text-primary">{t('filters.subscription')}</span>
|
||||||
<select
|
<select
|
||||||
value={subscriptionStatus ?? ''}
|
value={subscriptionStatus ?? ''}
|
||||||
onChange={(event) =>
|
onChange={(event) =>
|
||||||
@@ -102,8 +104,8 @@ export function AdminAccountsView() {
|
|||||||
}
|
}
|
||||||
className={selectClass}
|
className={selectClass}
|
||||||
>
|
>
|
||||||
<option value="">Todas</option>
|
<option value="">{t('filters.allFem')}</option>
|
||||||
{SUBSCRIPTION_FILTER_OPTIONS.map((option) => (
|
{subscriptionFilterOptions().map((option) => (
|
||||||
<option key={option.value} value={option.value}>
|
<option key={option.value} value={option.value}>
|
||||||
{option.label}
|
{option.label}
|
||||||
</option>
|
</option>
|
||||||
@@ -115,7 +117,7 @@ export function AdminAccountsView() {
|
|||||||
{isPending ? (
|
{isPending ? (
|
||||||
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
||||||
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
||||||
<span className="sr-only">Cargando cuentas</span>
|
<span className="sr-only">{t('loading')}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
@@ -123,7 +125,7 @@ export function AdminAccountsView() {
|
|||||||
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
<p>{errorMessage}</p>
|
<p>{errorMessage}</p>
|
||||||
<Button variant="outline" size="sm" onClick={retry}>
|
<Button variant="outline" size="sm" onClick={retry}>
|
||||||
Reintentar
|
{t('common:actions.retry')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -134,11 +136,11 @@ export function AdminAccountsView() {
|
|||||||
<Users className="size-7" aria-hidden="true" />
|
<Users className="size-7" aria-hidden="true" />
|
||||||
</span>
|
</span>
|
||||||
<p className="mt-4 text-base font-semibold text-primary">
|
<p className="mt-4 text-base font-semibold text-primary">
|
||||||
{hasFilters ? 'Ninguna cuenta coincide' : 'Todavía no hay cuentas'}
|
{hasFilters ? t('noMatch') : t('empty')}
|
||||||
</p>
|
</p>
|
||||||
{hasFilters ? (
|
{hasFilters ? (
|
||||||
<p className="mx-auto mt-1.5 max-w-[34ch] text-sm leading-relaxed text-secondary">
|
<p className="mx-auto mt-1.5 max-w-[34ch] text-sm leading-relaxed text-secondary">
|
||||||
Probá con otra búsqueda o sacá algún filtro.
|
{t('noMatchHint')}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
@@ -158,12 +160,12 @@ export function AdminAccountsView() {
|
|||||||
ACCOUNT_GRID_COLUMNS,
|
ACCOUNT_GRID_COLUMNS,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<span>Cuenta</span>
|
<span>{t('columns.account')}</span>
|
||||||
<span>País</span>
|
<span>{t('columns.country')}</span>
|
||||||
<span>Plan</span>
|
<span>{t('columns.plan')}</span>
|
||||||
<span>Suscripción</span>
|
<span>{t('columns.subscription')}</span>
|
||||||
<span className="text-right">Grupos</span>
|
<span className="text-right">{t('columns.groups')}</span>
|
||||||
<span className="text-right">Alumnos</span>
|
<span className="text-right">{t('columns.students')}</span>
|
||||||
<span />
|
<span />
|
||||||
</div>
|
</div>
|
||||||
<ul className="space-y-3 lg:space-y-0">
|
<ul className="space-y-3 lg:space-y-0">
|
||||||
@@ -176,10 +178,10 @@ export function AdminAccountsView() {
|
|||||||
<div className="mt-6 flex items-center justify-between gap-3">
|
<div className="mt-6 flex items-center justify-between gap-3">
|
||||||
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage(page - 1)}>
|
<Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage(page - 1)}>
|
||||||
<ChevronLeft className="size-4" />
|
<ChevronLeft className="size-4" />
|
||||||
Anteriores
|
{t('prev')}
|
||||||
</Button>
|
</Button>
|
||||||
<p className="text-xs text-foreground/50">
|
<p className="text-xs text-foreground/50">
|
||||||
Página {page} de {totalPages} · {total} {total === 1 ? 'cuenta' : 'cuentas'}
|
{t('pageInfo', { page, pages: totalPages, count: total })}
|
||||||
</p>
|
</p>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@@ -187,7 +189,7 @@ export function AdminAccountsView() {
|
|||||||
disabled={page >= totalPages}
|
disabled={page >= totalPages}
|
||||||
onClick={() => setPage(page + 1)}
|
onClick={() => setPage(page + 1)}
|
||||||
>
|
>
|
||||||
Siguientes
|
{t('next')}
|
||||||
<ChevronRight className="size-4" />
|
<ChevronRight className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { Button } from '../../components/ui'
|
|||||||
import { useAuth } from '../../context/AuthProvider'
|
import { useAuth } from '../../context/AuthProvider'
|
||||||
import { AdminLayout } from './AdminLayout'
|
import { AdminLayout } from './AdminLayout'
|
||||||
import { useAdminAccess } from './useAdminAccess'
|
import { useAdminAccess } from './useAdminAccess'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
/* El backoffice cuelga de la raíz y no de `_authenticated`: un admin no tiene
|
/* El backoffice cuelga de la raíz y no de `_authenticated`: un admin no tiene
|
||||||
por qué completar el onboarding de profesor. La sesión y el permiso se
|
por qué completar el onboarding de profesor. La sesión y el permiso se
|
||||||
@@ -13,6 +14,7 @@ import { useAdminAccess } from './useAdminAccess'
|
|||||||
export function AdminGuard({ children }: { children: ReactNode }) {
|
export function AdminGuard({ children }: { children: ReactNode }) {
|
||||||
const { user, isPending } = useAuth()
|
const { user, isPending } = useAuth()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { t } = useTranslation(['admin', 'common', 'billing'])
|
||||||
const access = useAdminAccess(!!user)
|
const access = useAdminAccess(!!user)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -30,9 +32,9 @@ export function AdminGuard({ children }: { children: ReactNode }) {
|
|||||||
if (access.isError) {
|
if (access.isError) {
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-dvh flex-col items-center justify-center gap-3 px-4 text-center">
|
<div className="flex min-h-dvh flex-col items-center justify-center gap-3 px-4 text-center">
|
||||||
<p className="text-sm text-danger">No pudimos verificar tu acceso al backoffice.</p>
|
<p className="text-sm text-danger">{t('guard.error')}</p>
|
||||||
<Button variant="outline" size="sm" onClick={() => void access.refetch()}>
|
<Button variant="outline" size="sm" onClick={() => void access.refetch()}>
|
||||||
Reintentar
|
{t('common:actions.retry')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
@@ -45,13 +47,13 @@ export function AdminGuard({ children }: { children: ReactNode }) {
|
|||||||
<ShieldOff className="size-7" aria-hidden="true" />
|
<ShieldOff className="size-7" aria-hidden="true" />
|
||||||
</span>
|
</span>
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-lg font-semibold text-primary">No tenés acceso</h1>
|
<h1 className="text-lg font-semibold text-primary">{t('guard.noAccess')}</h1>
|
||||||
<p className="mt-1 max-w-[36ch] text-sm text-secondary">
|
<p className="mt-1 max-w-[36ch] text-sm text-secondary">
|
||||||
El backoffice es solo para el equipo de Gruperly.
|
{t('guard.noAccessHint')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Link to="/" className="text-sm font-medium text-accent-fg hover:underline">
|
<Link to="/" className="text-sm font-medium text-accent-fg hover:underline">
|
||||||
Ir a la app
|
{t('guard.goToApp')}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,16 +2,18 @@ import type { ReactNode } from 'react'
|
|||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { ArrowLeft } from 'lucide-react'
|
import { ArrowLeft } from 'lucide-react'
|
||||||
import { ThemeToggle } from '../../components/layout/ThemeToggle'
|
import { ThemeToggle } from '../../components/layout/ThemeToggle'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
/* Layout propio del backoffice: sin la navegación del profesor y pensado para
|
/* Layout propio del backoffice: sin la navegación del profesor y pensado para
|
||||||
escritorio, aunque en móvil se lee igual (columna única). */
|
escritorio, aunque en móvil se lee igual (columna única). */
|
||||||
export function AdminLayout({ children }: { children: ReactNode }) {
|
export function AdminLayout({ children }: { children: ReactNode }) {
|
||||||
|
const { t } = useTranslation(['admin', 'common', 'billing'])
|
||||||
return (
|
return (
|
||||||
<div className="min-h-dvh bg-background">
|
<div className="min-h-dvh bg-background">
|
||||||
<header className="sticky top-0 z-30 border-b border-border bg-surface/90 backdrop-blur">
|
<header className="sticky top-0 z-30 border-b border-border bg-surface/90 backdrop-blur">
|
||||||
<div className="mx-auto flex h-14 max-w-6xl items-center justify-between gap-3 px-4 lg:px-8">
|
<div className="mx-auto flex h-14 max-w-6xl items-center justify-between gap-3 px-4 lg:px-8">
|
||||||
<Link to="/admin" className="text-base font-bold text-primary">
|
<Link to="/admin" className="text-base font-bold text-primary">
|
||||||
Gruperly <span className="font-medium text-foreground/50">· Backoffice</span>
|
Gruperly <span className="font-medium text-foreground/50">· {t('brand')}</span>
|
||||||
</Link>
|
</Link>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<ThemeToggle />
|
<ThemeToggle />
|
||||||
@@ -20,7 +22,7 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
|||||||
className="hidden items-center gap-1.5 rounded-xl px-3 py-1.5 text-sm font-medium text-foreground/70 transition-colors hover:bg-primary-soft hover:text-primary lg:inline-flex"
|
className="hidden items-center gap-1.5 rounded-xl px-3 py-1.5 text-sm font-medium text-foreground/70 transition-colors hover:bg-primary-soft hover:text-primary lg:inline-flex"
|
||||||
>
|
>
|
||||||
<ArrowLeft className="size-4" aria-hidden="true" />
|
<ArrowLeft className="size-4" aria-hidden="true" />
|
||||||
Volver a la app
|
{t('backToApp')}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,38 +6,43 @@ import type {
|
|||||||
Plan,
|
Plan,
|
||||||
SubscriptionStatus,
|
SubscriptionStatus,
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
import { COUNTRY_LABELS } from '@gruperly/shared'
|
import { COUNTRY_CURRENCY } from '@gruperly/shared'
|
||||||
|
import { countryName } from '../../i18n/countries'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
import type { BadgeVariant } from '../../components/ui'
|
import type { BadgeVariant } from '../../components/ui'
|
||||||
import { PLAN_NAMES, subscriptionStatusLabel } from '../billing'
|
import { PLAN_NAMES, subscriptionStatusLabel } from '../billing'
|
||||||
|
|
||||||
/* Copy del backoffice. Los nombres de plan y de estado de suscripción salen de
|
/* Copy del backoffice. Los nombres de plan y de estado de suscripción salen de
|
||||||
billing, así el equipo ve lo mismo que el profesor en su pantalla del plan. */
|
billing, así el equipo ve lo mismo que el profesor en su pantalla del plan. */
|
||||||
|
|
||||||
export const PLAN_FILTER_OPTIONS: readonly { value: AdminPlanFilter; label: string }[] = [
|
export function planFilterOptions(): { value: AdminPlanFilter; label: string }[] {
|
||||||
{ value: 'PRO', label: PLAN_NAMES.PRO },
|
return [
|
||||||
{ value: 'FREE', label: PLAN_NAMES.FREE },
|
{ value: 'PRO', label: PLAN_NAMES.PRO },
|
||||||
{ value: 'NOT_SELECTED', label: 'Sin elegir' },
|
{ value: 'FREE', label: PLAN_NAMES.FREE },
|
||||||
]
|
{ value: 'NOT_SELECTED', label: i18n.t('admin:filters.notSelected') },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
export const SUBSCRIPTION_FILTER_OPTIONS: readonly { value: AdminSubscriptionFilter; label: string }[] = [
|
export function subscriptionFilterOptions(): { value: AdminSubscriptionFilter; label: string }[] {
|
||||||
{ value: 'AUTHORIZED', label: subscriptionStatusLabel('AUTHORIZED') },
|
return [
|
||||||
{ value: 'PENDING', label: subscriptionStatusLabel('PENDING') },
|
{ value: 'AUTHORIZED', label: subscriptionStatusLabel('AUTHORIZED') },
|
||||||
{ value: 'PAUSED', label: subscriptionStatusLabel('PAUSED') },
|
{ value: 'PENDING', label: subscriptionStatusLabel('PENDING') },
|
||||||
{ value: 'CANCELLED', label: subscriptionStatusLabel('CANCELLED') },
|
{ value: 'PAUSED', label: subscriptionStatusLabel('PAUSED') },
|
||||||
{ value: 'NONE', label: subscriptionStatusLabel(null) },
|
{ value: 'CANCELLED', label: subscriptionStatusLabel('CANCELLED') },
|
||||||
]
|
{ value: 'NONE', label: subscriptionStatusLabel(null) },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
export const COUNTRY_OPTIONS = (Object.keys(COUNTRY_LABELS) as CountryCode[]).map((code) => ({
|
export function countryOptions(): { value: CountryCode; label: string }[] {
|
||||||
value: code,
|
return (Object.keys(COUNTRY_CURRENCY) as CountryCode[]).map((code) => ({ value: code, label: countryName(code) }))
|
||||||
label: COUNTRY_LABELS[code],
|
}
|
||||||
}))
|
|
||||||
|
|
||||||
export function countryLabel(country: CountryCode | null): string {
|
export function countryLabel(country: CountryCode | null): string {
|
||||||
return country ? COUNTRY_LABELS[country] : 'Sin país'
|
return country ? countryName(country) : i18n.t('admin:noCountry')
|
||||||
}
|
}
|
||||||
|
|
||||||
export function planLabel(plan: Plan | null): string {
|
export function planLabel(plan: Plan | null): string {
|
||||||
return plan ? PLAN_NAMES[plan] : 'Sin elegir'
|
return plan ? PLAN_NAMES[plan] : i18n.t('admin:filters.notSelected')
|
||||||
}
|
}
|
||||||
|
|
||||||
export function planVariant(plan: Plan | null): BadgeVariant {
|
export function planVariant(plan: Plan | null): BadgeVariant {
|
||||||
@@ -60,16 +65,10 @@ export function subscriptionVariant(status: SubscriptionStatus | null): BadgeVar
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MP_STATUS_LABELS: Record<NonNullable<AdminAccountDetail['mpStatus']> | 'NONE', string> = {
|
export function mpStatusLabel(status: AdminAccountDetail['mpStatus']): string {
|
||||||
ACTIVE: 'Vinculada',
|
return i18n.t(`admin:mpStatus.${status ?? 'NONE'}`)
|
||||||
REQUIRES_REAUTH: 'Requiere volver a vincular',
|
|
||||||
REVOKED: 'Desvinculada',
|
|
||||||
NONE: 'Sin vincular',
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const WHATSAPP_STATUS_LABELS: Record<NonNullable<AdminAccountDetail['whatsappStatus']> | 'NONE', string> = {
|
export function whatsappStatusLabel(status: AdminAccountDetail['whatsappStatus']): string {
|
||||||
ACTIVE: 'Conectado',
|
return i18n.t(`admin:whatsappStatus.${status ?? 'NONE'}`)
|
||||||
PENDING: 'Conectando',
|
|
||||||
DISCONNECTED: 'Desconectado',
|
|
||||||
NONE: 'Sin conectar',
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ import { useAttendeeDetail } from './AttendeeDetailProvider'
|
|||||||
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
||||||
import { Section } from './Section'
|
import { Section } from './Section'
|
||||||
import { useCopyToClipboard } from './useCopyToClipboard'
|
import { useCopyToClipboard } from './useCopyToClipboard'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function AbsenceLinkSection() {
|
export function AbsenceLinkSection() {
|
||||||
const { attendee } = useAttendeeDetail()
|
const { attendee } = useAttendeeDetail()
|
||||||
const { copied, copy } = useCopyToClipboard()
|
const { copied, copy } = useCopyToClipboard()
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
const [isOpen, setIsOpen] = useState(false)
|
const [isOpen, setIsOpen] = useState(false)
|
||||||
const panelId = useId()
|
const panelId = useId()
|
||||||
|
|
||||||
@@ -19,14 +21,14 @@ export function AbsenceLinkSection() {
|
|||||||
const phoneDigits = attendee.phone?.replace(/\D/g, '') ?? ''
|
const phoneDigits = attendee.phone?.replace(/\D/g, '') ?? ''
|
||||||
const shareUrl = phoneDigits
|
const shareUrl = phoneDigits
|
||||||
? `https://wa.me/${phoneDigits}?text=${encodeURIComponent(
|
? `https://wa.me/${phoneDigits}?text=${encodeURIComponent(
|
||||||
`Hola ${attendee.fullName.split(' ')[0]}, desde este link podés avisar tus ausencias en ${url}`,
|
t('absenceLink.message', { name: attendee.fullName.split(' ')[0], url }),
|
||||||
)}`
|
)}`
|
||||||
: null
|
: null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Section
|
<Section
|
||||||
title="Link de ausencias"
|
title={t('absenceLink.title')}
|
||||||
description="Para que avise si no puede venir"
|
description={t('absenceLink.description')}
|
||||||
toggle={{ isOpen, panelId, onToggle: () => setIsOpen((value) => !value) }}
|
toggle={{ isOpen, panelId, onToggle: () => setIsOpen((value) => !value) }}
|
||||||
>
|
>
|
||||||
{/* The panel stays in the DOM but hidden: `aria-controls` always resolves and
|
{/* The panel stays in the DOM but hidden: `aria-controls` always resolves and
|
||||||
@@ -43,18 +45,18 @@ export function AbsenceLinkSection() {
|
|||||||
className={cn(ACTION_BUTTON_CLASS, 'w-full')}
|
className={cn(ACTION_BUTTON_CLASS, 'w-full')}
|
||||||
>
|
>
|
||||||
<Copy className="size-4" aria-hidden="true" />
|
<Copy className="size-4" aria-hidden="true" />
|
||||||
Copiar link
|
{t('absenceLink.copy')}
|
||||||
</button>
|
</button>
|
||||||
{shareUrl ? (
|
{shareUrl ? (
|
||||||
<a
|
<a
|
||||||
href={shareUrl}
|
href={shareUrl}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
aria-label={`Enviar el link por WhatsApp a ${attendee.fullName}`}
|
aria-label={t('absenceLink.sendLabel', { name: attendee.fullName })}
|
||||||
className={PRIMARY_ACTION_CLASS}
|
className={PRIMARY_ACTION_CLASS}
|
||||||
>
|
>
|
||||||
<MessageCircle className="size-4" aria-hidden="true" />
|
<MessageCircle className="size-4" aria-hidden="true" />
|
||||||
Enviar por WhatsApp
|
{t('absenceLink.send')}
|
||||||
</a>
|
</a>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
@@ -65,7 +67,7 @@ export function AbsenceLinkSection() {
|
|||||||
{copied ? (
|
{copied ? (
|
||||||
<>
|
<>
|
||||||
<Check className="size-3.5" aria-hidden="true" />
|
<Check className="size-3.5" aria-hidden="true" />
|
||||||
Link copiado
|
{t('absenceLink.copied')}
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type { KeyboardEvent, RefObject } from 'react'
|
|||||||
import { Ellipsis, MoveRight, Pause, Pencil, UserMinus, UserPlus } from 'lucide-react'
|
import { Ellipsis, MoveRight, Pause, Pencil, UserMinus, UserPlus } from 'lucide-react'
|
||||||
import { useToast } from '../../components/ui'
|
import { useToast } from '../../components/ui'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
const ITEM_CLASS =
|
const ITEM_CLASS =
|
||||||
'flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-sm font-medium text-primary transition-colors hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
'flex min-h-11 w-full items-center gap-2.5 rounded-lg px-3 text-left text-sm font-medium text-primary transition-colors hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
|
||||||
@@ -17,6 +18,7 @@ export function AttendeeActionsMenu({
|
|||||||
}) {
|
}) {
|
||||||
const { beginContactEdit, openRemoveDialog, openChangeGroupDialog, openAddToGroupDialog } = useAttendeeDetail()
|
const { beginContactEdit, openRemoveDialog, openChangeGroupDialog, openAddToGroupDialog } = useAttendeeDetail()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
const [isOpen, setIsOpen] = useState(false)
|
const [isOpen, setIsOpen] = useState(false)
|
||||||
const menuRef = useRef<HTMLDivElement>(null)
|
const menuRef = useRef<HTMLDivElement>(null)
|
||||||
const itemRef = useRef<HTMLButtonElement>(null)
|
const itemRef = useRef<HTMLButtonElement>(null)
|
||||||
@@ -72,7 +74,7 @@ export function AttendeeActionsMenu({
|
|||||||
const showPendingPause = () => {
|
const showPendingPause = () => {
|
||||||
close()
|
close()
|
||||||
// TODO(miembros): conectar la pausa cuando se defina su efecto sobre cupos y cobros.
|
// TODO(miembros): conectar la pausa cuando se defina su efecto sobre cupos y cobros.
|
||||||
toast.info('Pausar la membresía estará disponible cuando se confirme su lógica de negocio.')
|
toast.info(t('menu.pausePending'))
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -84,7 +86,7 @@ export function AttendeeActionsMenu({
|
|||||||
aria-haspopup="menu"
|
aria-haspopup="menu"
|
||||||
aria-expanded={isOpen}
|
aria-expanded={isOpen}
|
||||||
aria-controls={isOpen ? menuId : undefined}
|
aria-controls={isOpen ? menuId : undefined}
|
||||||
aria-label="Más acciones"
|
aria-label={t('menu.more')}
|
||||||
className="inline-flex size-11 items-center justify-center rounded-xl text-primary transition-colors hover:bg-primary-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
className="inline-flex size-11 items-center justify-center rounded-xl text-primary transition-colors hover:bg-primary-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
>
|
>
|
||||||
<Ellipsis className="size-5" aria-hidden="true" />
|
<Ellipsis className="size-5" aria-hidden="true" />
|
||||||
@@ -95,7 +97,7 @@ export function AttendeeActionsMenu({
|
|||||||
ref={menuRef}
|
ref={menuRef}
|
||||||
id={menuId}
|
id={menuId}
|
||||||
role="menu"
|
role="menu"
|
||||||
aria-label="Acciones del miembro"
|
aria-label={t('menu.label')}
|
||||||
onKeyDown={handleKeyDown}
|
onKeyDown={handleKeyDown}
|
||||||
className="absolute right-0 top-full z-40 mt-1 w-60 rounded-xl bg-primary-soft p-1.5 shadow-lg"
|
className="absolute right-0 top-full z-40 mt-1 w-60 rounded-xl bg-primary-soft p-1.5 shadow-lg"
|
||||||
>
|
>
|
||||||
@@ -110,7 +112,7 @@ export function AttendeeActionsMenu({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<MoveRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
<MoveRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||||
Cambiar de grupo
|
{t('menu.changeGroup')}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -122,7 +124,7 @@ export function AttendeeActionsMenu({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<UserPlus className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
<UserPlus className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||||
Agregar a otro grupo
|
{t('menu.addToGroup')}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -137,7 +139,7 @@ export function AttendeeActionsMenu({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Pencil className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
<Pencil className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||||
Editar contacto
|
{t('menu.editContact')}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -146,7 +148,7 @@ export function AttendeeActionsMenu({
|
|||||||
onClick={showPendingPause}
|
onClick={showPendingPause}
|
||||||
>
|
>
|
||||||
<Pause className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
<Pause className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||||
Pausar membresía
|
{t('menu.pause')}
|
||||||
</button>
|
</button>
|
||||||
<div className="my-1 border-t border-border/70" aria-hidden="true" />
|
<div className="my-1 border-t border-border/70" aria-hidden="true" />
|
||||||
<button
|
<button
|
||||||
@@ -159,7 +161,7 @@ export function AttendeeActionsMenu({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<UserMinus className="size-4 shrink-0" aria-hidden="true" />
|
<UserMinus className="size-4 shrink-0" aria-hidden="true" />
|
||||||
Quitar del grupo
|
{t('menu.remove')}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
} from './attendance'
|
} from './attendance'
|
||||||
import { Section } from './Section'
|
import { Section } from './Section'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
const STATUS_ICONS: Record<AttendanceStatus | 'UNMARKED', LucideIcon> = {
|
const STATUS_ICONS: Record<AttendanceStatus | 'UNMARKED', LucideIcon> = {
|
||||||
PRESENT: Check,
|
PRESENT: Check,
|
||||||
@@ -31,10 +32,11 @@ function iconFor(status: AttendanceSession['status']): LucideIcon {
|
|||||||
export function AttendeeAttendanceSection() {
|
export function AttendeeAttendanceSection() {
|
||||||
const { history, historyPending, historyFailed } = useAttendeeDetail()
|
const { history, historyPending, historyFailed } = useAttendeeDetail()
|
||||||
const [showAll, setShowAll] = useState(false)
|
const [showAll, setShowAll] = useState(false)
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
|
|
||||||
if (historyPending) {
|
if (historyPending) {
|
||||||
return (
|
return (
|
||||||
<Section title="Asistencia" trailing="—">
|
<Section title={t('attendance.title')} trailing="—">
|
||||||
<div className="flex items-center justify-center py-5">
|
<div className="flex items-center justify-center py-5">
|
||||||
<Loader2 className="size-5 animate-spin text-accent" />
|
<Loader2 className="size-5 animate-spin text-accent" />
|
||||||
</div>
|
</div>
|
||||||
@@ -44,9 +46,9 @@ export function AttendeeAttendanceSection() {
|
|||||||
|
|
||||||
if (historyFailed) {
|
if (historyFailed) {
|
||||||
return (
|
return (
|
||||||
<Section title="Asistencia">
|
<Section title={t('attendance.title')}>
|
||||||
<p className="py-3 text-sm text-foreground">
|
<p className="py-3 text-sm text-foreground">
|
||||||
No pudimos cargar la asistencia de este miembro.
|
{t('attendance.loadError')}
|
||||||
</p>
|
</p>
|
||||||
</Section>
|
</Section>
|
||||||
)
|
)
|
||||||
@@ -56,9 +58,9 @@ export function AttendeeAttendanceSection() {
|
|||||||
|
|
||||||
if (sessions.length === 0) {
|
if (sessions.length === 0) {
|
||||||
return (
|
return (
|
||||||
<Section title="Asistencia">
|
<Section title={t('attendance.title')}>
|
||||||
<p className="py-3 text-sm text-foreground">
|
<p className="py-3 text-sm text-foreground">
|
||||||
Todavía no hay clases registradas.
|
{t('attendance.empty')}
|
||||||
</p>
|
</p>
|
||||||
</Section>
|
</Section>
|
||||||
)
|
)
|
||||||
@@ -70,7 +72,7 @@ export function AttendeeAttendanceSection() {
|
|||||||
const summary = attendanceSummary(visible)
|
const summary = attendanceSummary(visible)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Section title="Asistencia" trailing={summary.label}>
|
<Section title={t('attendance.title')} trailing={summary.label}>
|
||||||
<ul className="divide-y divide-border/60">
|
<ul className="divide-y divide-border/60">
|
||||||
{visible.map((session) => {
|
{visible.map((session) => {
|
||||||
const Icon = iconFor(session.status)
|
const Icon = iconFor(session.status)
|
||||||
@@ -98,7 +100,7 @@ export function AttendeeAttendanceSection() {
|
|||||||
|
|
||||||
{showAll && isCapped ? (
|
{showAll && isCapped ? (
|
||||||
<p className="px-3 pt-2 text-xs text-foreground">
|
<p className="px-3 pt-2 text-xs text-foreground">
|
||||||
El historial guarda las últimas {HISTORY_LIMIT} clases.
|
{t('attendance.capped', { count: HISTORY_LIMIT })}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
@@ -110,7 +112,7 @@ export function AttendeeAttendanceSection() {
|
|||||||
aria-expanded={showAll}
|
aria-expanded={showAll}
|
||||||
className="h-11 gap-1 px-3 text-sm text-accent-fg hover:text-primary"
|
className="h-11 gap-1 px-3 text-sm text-accent-fg hover:text-primary"
|
||||||
>
|
>
|
||||||
{showAll ? 'Ver menos' : `Ver todas (${sessions.length})`}
|
{showAll ? t('attendance.showLess') : t('attendance.showAll', { count: sessions.length })}
|
||||||
<ChevronDown className={cn('size-4 transition-transform', showAll && 'rotate-180')} />
|
<ChevronDown className={cn('size-4 transition-transform', showAll && 'rotate-180')} />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,13 +3,15 @@ import { formatPhoneDisplay } from '../../lib/format'
|
|||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function AttendeeContactActions() {
|
export function AttendeeContactActions() {
|
||||||
const { attendee } = useAttendeeDetail()
|
const { attendee } = useAttendeeDetail()
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
|
|
||||||
const phone = attendee?.phone
|
const phone = attendee?.phone
|
||||||
const digits = phone?.replace(/\D/g, '') ?? ''
|
const digits = phone?.replace(/\D/g, '') ?? ''
|
||||||
const label = formatPhoneDisplay(phone) ?? attendee?.fullName ?? 'el miembro'
|
const label = formatPhoneDisplay(phone) ?? attendee?.fullName ?? t('actions.theMember')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -19,7 +21,7 @@ export function AttendeeContactActions() {
|
|||||||
href={`https://wa.me/${digits}`}
|
href={`https://wa.me/${digits}`}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
aria-label={`Abrir WhatsApp con ${label}`}
|
aria-label={t('actions.whatsappLabel', { name: label })}
|
||||||
className={PRIMARY_ACTION_CLASS}
|
className={PRIMARY_ACTION_CLASS}
|
||||||
>
|
>
|
||||||
<MessageCircle className="size-4" aria-hidden="true" />
|
<MessageCircle className="size-4" aria-hidden="true" />
|
||||||
@@ -39,11 +41,11 @@ export function AttendeeContactActions() {
|
|||||||
{phone ? (
|
{phone ? (
|
||||||
<a
|
<a
|
||||||
href={`tel:${digits}`}
|
href={`tel:${digits}`}
|
||||||
aria-label={`Llamar a ${label}`}
|
aria-label={t('actions.callLabel', { name: label })}
|
||||||
className={cn(ACTION_BUTTON_CLASS, 'w-full')}
|
className={cn(ACTION_BUTTON_CLASS, 'w-full')}
|
||||||
>
|
>
|
||||||
<Phone className="size-4 text-accent-fg" aria-hidden="true" />
|
<Phone className="size-4 text-accent-fg" aria-hidden="true" />
|
||||||
Llamar
|
{t('actions.call')}
|
||||||
</a>
|
</a>
|
||||||
) : (
|
) : (
|
||||||
<button
|
<button
|
||||||
@@ -53,13 +55,13 @@ export function AttendeeContactActions() {
|
|||||||
className={cn(ACTION_BUTTON_CLASS, 'w-full cursor-not-allowed opacity-45')}
|
className={cn(ACTION_BUTTON_CLASS, 'w-full cursor-not-allowed opacity-45')}
|
||||||
>
|
>
|
||||||
<Phone className="size-4 text-secondary" aria-hidden="true" />
|
<Phone className="size-4 text-secondary" aria-hidden="true" />
|
||||||
Llamar
|
{t('actions.call')}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{!phone ? (
|
{!phone ? (
|
||||||
<p id="missing-phone-feedback" className="mt-2 text-xs text-secondary">
|
<p id="missing-phone-feedback" className="mt-2 text-xs text-secondary">
|
||||||
Agregá un teléfono para usar estas acciones
|
{t('actions.missingPhone')}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
import { Loader2, Mail, Phone } from 'lucide-react'
|
import { Loader2, Mail, Phone } from 'lucide-react'
|
||||||
import { Button, Input } from '../../components/ui'
|
import { Button, Input } from '../../components/ui'
|
||||||
|
import { validationMessage } from '../../i18n'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
type AttendeeContactFormProps = {
|
type AttendeeContactFormProps = {
|
||||||
phone: string
|
phone: string
|
||||||
@@ -26,26 +28,27 @@ export function AttendeeContactForm({
|
|||||||
onCancel,
|
onCancel,
|
||||||
onSave,
|
onSave,
|
||||||
}: AttendeeContactFormProps) {
|
}: AttendeeContactFormProps) {
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
return (
|
return (
|
||||||
<div className="space-y-3 px-3 pb-1">
|
<div className="space-y-3 px-3 pb-1">
|
||||||
<ContactInput icon={Phone} label="Teléfono">
|
<ContactInput icon={Phone} label={t('contact.phone')}>
|
||||||
<Input
|
<Input
|
||||||
type="tel"
|
type="tel"
|
||||||
value={phone}
|
value={phone}
|
||||||
onChange={(event) => onPhoneChange(event.target.value)}
|
onChange={(event) => onPhoneChange(event.target.value)}
|
||||||
autoComplete="tel"
|
autoComplete="tel"
|
||||||
autoFocus
|
autoFocus
|
||||||
aria-label="Teléfono"
|
aria-label={t('contact.phone')}
|
||||||
/>
|
/>
|
||||||
</ContactInput>
|
</ContactInput>
|
||||||
<ContactInput icon={Mail} label="Email">
|
<ContactInput icon={Mail} label={t('contact.email')}>
|
||||||
<Input
|
<Input
|
||||||
type="email"
|
type="email"
|
||||||
value={email}
|
value={email}
|
||||||
invalid={error === 'Ingresá un email válido'}
|
invalid={error === validationMessage('email.invalid')}
|
||||||
onChange={(event) => onEmailChange(event.target.value)}
|
onChange={(event) => onEmailChange(event.target.value)}
|
||||||
autoComplete="email"
|
autoComplete="email"
|
||||||
aria-label="Email"
|
aria-label={t('contact.email')}
|
||||||
aria-describedby={error ? 'contact-error' : undefined}
|
aria-describedby={error ? 'contact-error' : undefined}
|
||||||
/>
|
/>
|
||||||
</ContactInput>
|
</ContactInput>
|
||||||
@@ -57,11 +60,11 @@ export function AttendeeContactForm({
|
|||||||
) : null}
|
) : null}
|
||||||
<div className="flex justify-end gap-2 pt-1">
|
<div className="flex justify-end gap-2 pt-1">
|
||||||
<Button variant="ghost" onClick={onCancel} disabled={isSaving}>
|
<Button variant="ghost" onClick={onCancel} disabled={isSaving}>
|
||||||
Cancelar
|
{t('common:actions.cancel')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="primary" onClick={onSave} disabled={isSaving}>
|
<Button variant="primary" onClick={onSave} disabled={isSaving}>
|
||||||
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
Guardar
|
{t('common:actions.save')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { AttendeeContactForm } from './AttendeeContactForm'
|
|||||||
import { contactEmailError } from './detail'
|
import { contactEmailError } from './detail'
|
||||||
import { Section } from './Section'
|
import { Section } from './Section'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function AttendeeContactSection() {
|
export function AttendeeContactSection() {
|
||||||
const {
|
const {
|
||||||
@@ -18,6 +19,7 @@ export function AttendeeContactSection() {
|
|||||||
isUpdatingAttendee,
|
isUpdatingAttendee,
|
||||||
} = useAttendeeDetail()
|
} = useAttendeeDetail()
|
||||||
const [phone, setPhone] = useState('')
|
const [phone, setPhone] = useState('')
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
const [email, setEmail] = useState('')
|
const [email, setEmail] = useState('')
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
@@ -47,8 +49,8 @@ export function AttendeeContactSection() {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(
|
setError(
|
||||||
err instanceof ApiError && err.problem?.code === 'person_phone_taken'
|
err instanceof ApiError && err.problem?.code === 'person_phone_taken'
|
||||||
? 'Ese teléfono ya es de otra persona que tenés registrada.'
|
? t('contact.phoneTaken')
|
||||||
: 'No pudimos guardar los cambios. Revisá tu conexión e intentá de nuevo.',
|
: t('contact.saveError'),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -56,7 +58,7 @@ export function AttendeeContactSection() {
|
|||||||
return (
|
return (
|
||||||
<Section
|
<Section
|
||||||
id="attendee-contact"
|
id="attendee-contact"
|
||||||
title="Contacto"
|
title={t('contact.title')}
|
||||||
trailing={
|
trailing={
|
||||||
!isEditingContact ? (
|
!isEditingContact ? (
|
||||||
<button
|
<button
|
||||||
@@ -64,7 +66,7 @@ export function AttendeeContactSection() {
|
|||||||
onClick={beginContactEdit}
|
onClick={beginContactEdit}
|
||||||
className="min-h-11 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
className="min-h-11 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
>
|
>
|
||||||
Editar
|
{t('contact.edit')}
|
||||||
</button>
|
</button>
|
||||||
) : null
|
) : null
|
||||||
}
|
}
|
||||||
@@ -76,7 +78,7 @@ export function AttendeeContactSection() {
|
|||||||
error={error}
|
error={error}
|
||||||
sharedNote={
|
sharedNote={
|
||||||
attendee.otherGroups.length > 0
|
attendee.otherGroups.length > 0
|
||||||
? 'El cambio se aplica en todos sus grupos.'
|
? t('contact.shared')
|
||||||
: null
|
: null
|
||||||
}
|
}
|
||||||
isSaving={isUpdatingAttendee}
|
isSaving={isUpdatingAttendee}
|
||||||
@@ -95,15 +97,15 @@ export function AttendeeContactSection() {
|
|||||||
<div className="divide-y divide-border/60">
|
<div className="divide-y divide-border/60">
|
||||||
<ContactRow
|
<ContactRow
|
||||||
icon={Phone}
|
icon={Phone}
|
||||||
label="Teléfono"
|
label={t('contact.phone')}
|
||||||
value={formatPhoneDisplay(attendee.phone) ?? 'Agregar teléfono'}
|
value={formatPhoneDisplay(attendee.phone) ?? t('contact.addPhone')}
|
||||||
href={attendee.phone ? `tel:${attendee.phone.replace(/\D/g, '')}` : undefined}
|
href={attendee.phone ? `tel:${attendee.phone.replace(/\D/g, '')}` : undefined}
|
||||||
placeholder={!attendee.phone}
|
placeholder={!attendee.phone}
|
||||||
/>
|
/>
|
||||||
<ContactRow
|
<ContactRow
|
||||||
icon={Mail}
|
icon={Mail}
|
||||||
label="Email"
|
label={t('contact.email')}
|
||||||
value={attendee.email ?? 'Agregar email'}
|
value={attendee.email ?? t('contact.addEmail')}
|
||||||
href={attendee.email ? `mailto:${attendee.email}` : undefined}
|
href={attendee.email ? `mailto:${attendee.email}` : undefined}
|
||||||
placeholder={!attendee.email}
|
placeholder={!attendee.email}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import type {
|
|||||||
GroupWaitlistEntryDto,
|
GroupWaitlistEntryDto,
|
||||||
UpdateAttendee,
|
UpdateAttendee,
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
|
import { errorMessage } from '../../i18n'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
import { useToast } from '../../components/ui'
|
import { useToast } from '../../components/ui'
|
||||||
import {
|
import {
|
||||||
addAttendeeToGroup,
|
addAttendeeToGroup,
|
||||||
@@ -143,8 +145,8 @@ export function AttendeeDetailProvider({
|
|||||||
const moveMutation = useMutation({
|
const moveMutation = useMutation({
|
||||||
mutationFn: (targetGroupId: string) => moveGroupAttendee(groupId, attendeeId, targetGroupId),
|
mutationFn: (targetGroupId: string) => moveGroupAttendee(groupId, attendeeId, targetGroupId),
|
||||||
onSuccess: (moved, targetGroupId) => {
|
onSuccess: (moved, targetGroupId) => {
|
||||||
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? 'otro grupo'
|
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? i18n.t('attendeeDetail:changeGroup.otherGroup')
|
||||||
toast.success(`${moved.fullName} pasó a ${targetName}.`)
|
toast.success(i18n.t('attendeeDetail:changeGroup.moved', { name: moved.fullName, group: targetName }))
|
||||||
for (const id of [groupId, targetGroupId]) {
|
for (const id of [groupId, targetGroupId]) {
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', id] })
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', id] })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group', id] })
|
void queryClient.invalidateQueries({ queryKey: ['group', id] })
|
||||||
@@ -163,11 +165,11 @@ export function AttendeeDetailProvider({
|
|||||||
onError: (err: Error) => {
|
onError: (err: Error) => {
|
||||||
const code = err instanceof ApiError ? err.problem?.code : undefined
|
const code = err instanceof ApiError ? err.problem?.code : undefined
|
||||||
if (code === 'group_capacity_reached') {
|
if (code === 'group_capacity_reached') {
|
||||||
toast.error('Ese grupo alcanzó su cupo. Elegí otro o liberá un lugar primero.')
|
toast.error(i18n.t('attendeeDetail:changeGroup.targetFull'))
|
||||||
} else if (code === 'attendee_already_registered') {
|
} else if (code === 'attendee_already_registered') {
|
||||||
toast.error('Esta persona ya es miembro de ese grupo.')
|
toast.error(i18n.t('attendeeDetail:changeGroup.alreadyMember'))
|
||||||
} else {
|
} else {
|
||||||
toast.error(err.message || 'No se pudo cambiar de grupo.')
|
toast.error(errorMessage(err, i18n.t('attendeeDetail:changeGroup.moveError')))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -175,8 +177,8 @@ export function AttendeeDetailProvider({
|
|||||||
const addToGroupMutation = useMutation({
|
const addToGroupMutation = useMutation({
|
||||||
mutationFn: (targetGroupId: string) => addAttendeeToGroup(groupId, attendeeId, targetGroupId),
|
mutationFn: (targetGroupId: string) => addAttendeeToGroup(groupId, attendeeId, targetGroupId),
|
||||||
onSuccess: (added, targetGroupId) => {
|
onSuccess: (added, targetGroupId) => {
|
||||||
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? 'otro grupo'
|
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? i18n.t('attendeeDetail:changeGroup.otherGroup')
|
||||||
toast.success(`${added.fullName} ahora también está en ${targetName}.`)
|
toast.success(i18n.t('attendeeDetail:changeGroup.added', { name: added.fullName, group: targetName }))
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', targetGroupId] })
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', targetGroupId] })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group', targetGroupId] })
|
void queryClient.invalidateQueries({ queryKey: ['group', targetGroupId] })
|
||||||
// "También está en" de esta ficha (y la de sus otros grupos).
|
// "También está en" de esta ficha (y la de sus otros grupos).
|
||||||
@@ -188,11 +190,11 @@ export function AttendeeDetailProvider({
|
|||||||
onError: (err: Error) => {
|
onError: (err: Error) => {
|
||||||
const code = err instanceof ApiError ? err.problem?.code : undefined
|
const code = err instanceof ApiError ? err.problem?.code : undefined
|
||||||
if (code === 'group_capacity_reached') {
|
if (code === 'group_capacity_reached') {
|
||||||
toast.error('Ese grupo alcanzó su cupo. Elegí otro o liberá un lugar primero.')
|
toast.error(i18n.t('attendeeDetail:changeGroup.targetFull'))
|
||||||
} else if (code === 'attendee_already_registered') {
|
} else if (code === 'attendee_already_registered') {
|
||||||
toast.error('Esta persona ya es miembro de ese grupo.')
|
toast.error(i18n.t('attendeeDetail:changeGroup.alreadyMember'))
|
||||||
} else {
|
} else {
|
||||||
toast.error(err.message || 'No se pudo agregar al grupo.')
|
toast.error(errorMessage(err, i18n.t('attendeeDetail:changeGroup.addError')))
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -17,23 +17,25 @@ import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
|
|||||||
import { formatMemberSince } from './attendance'
|
import { formatMemberSince } from './attendance'
|
||||||
import { paymentPresentation } from './detail'
|
import { paymentPresentation } from './detail'
|
||||||
import { StudentAccessSection } from './StudentAccessSection'
|
import { StudentAccessSection } from './StudentAccessSection'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function AttendeeDetailView() {
|
export function AttendeeDetailView() {
|
||||||
const { groupId, groupName, attendee, attendeePending, attendeeFailed } = useAttendeeDetail()
|
const { groupId, groupName, attendee, attendeePending, attendeeFailed } = useAttendeeDetail()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common', 'groupDetail'])
|
||||||
const menuTriggerRef = useRef<HTMLButtonElement>(null)
|
const menuTriggerRef = useRef<HTMLButtonElement>(null)
|
||||||
const payment = attendee ? paymentPresentation(attendee.payment) : null
|
const payment = attendee ? paymentPresentation(attendee.payment) : null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="mx-auto w-full max-w-md animate-fade-in lg:max-w-2xl">
|
<section className="mx-auto w-full max-w-md animate-fade-in lg:max-w-2xl">
|
||||||
<LargeTitle
|
<LargeTitle
|
||||||
title={attendee?.fullName ?? 'Miembro'}
|
title={attendee?.fullName ?? t('fallbackName')}
|
||||||
barContext={groupName ?? 'Grupo'}
|
barContext={groupName ?? t('groupDetail:fallbackTitle')}
|
||||||
leading={
|
leading={
|
||||||
<Link
|
<Link
|
||||||
to="/groups/$groupId"
|
to="/groups/$groupId"
|
||||||
params={{ groupId }}
|
params={{ groupId }}
|
||||||
aria-label="Volver al grupo"
|
aria-label={t('backToGroup')}
|
||||||
className="relative z-10 hidden size-11 shrink-0 lg:inline-flex items-center justify-center rounded-xl text-primary transition-colors hover:bg-primary-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
className="relative z-10 hidden size-11 shrink-0 lg:inline-flex items-center justify-center rounded-xl text-primary transition-colors hover:bg-primary-soft active:scale-[0.96] motion-reduce:active:scale-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
>
|
>
|
||||||
<ArrowLeft className="size-5" aria-hidden="true" />
|
<ArrowLeft className="size-5" aria-hidden="true" />
|
||||||
@@ -54,7 +56,7 @@ export function AttendeeDetailView() {
|
|||||||
<Badge variant={payment.isDue ? 'warning' : 'success'} className="text-[11px]">
|
<Badge variant={payment.isDue ? 'warning' : 'success'} className="text-[11px]">
|
||||||
{payment.chipLabel}
|
{payment.chipLabel}
|
||||||
</Badge>
|
</Badge>
|
||||||
<span>Desde {formatMemberSince(attendee.createdAt)}</span>
|
<span>{t('since', { date: formatMemberSince(attendee.createdAt) })}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</LargeTitle>
|
</LargeTitle>
|
||||||
@@ -67,16 +69,16 @@ export function AttendeeDetailView() {
|
|||||||
|
|
||||||
{attendeeFailed || (!attendeePending && !attendee) ? (
|
{attendeeFailed || (!attendeePending && !attendee) ? (
|
||||||
<div className="mt-6 rounded-2xl bg-danger-soft p-6">
|
<div className="mt-6 rounded-2xl bg-danger-soft p-6">
|
||||||
<h2 className="text-lg font-bold text-danger-fg">Miembro no encontrado</h2>
|
<h2 className="text-lg font-bold text-danger-fg">{t('notFound.title')}</h2>
|
||||||
<p className="mt-2 text-sm text-primary">
|
<p className="mt-2 text-sm text-primary">
|
||||||
No se pudo cargar la información de este miembro.
|
{t('notFound.description')}
|
||||||
</p>
|
</p>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
className="mt-4 px-0 text-accent-fg hover:bg-transparent hover:text-primary"
|
className="mt-4 px-0 text-accent-fg hover:bg-transparent hover:text-primary"
|
||||||
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
|
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
|
||||||
>
|
>
|
||||||
Volver al grupo
|
{t('backToGroup')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Loader2 } from 'lucide-react'
|
import { Loader2 } from 'lucide-react'
|
||||||
import { Button } from '../../components/ui'
|
import { Button } from '../../components/ui'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
type AttendeeNotesFormProps = {
|
type AttendeeNotesFormProps = {
|
||||||
draft: string
|
draft: string
|
||||||
@@ -18,6 +19,7 @@ export function AttendeeNotesForm({
|
|||||||
onCancel,
|
onCancel,
|
||||||
onSave,
|
onSave,
|
||||||
}: AttendeeNotesFormProps) {
|
}: AttendeeNotesFormProps) {
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
return (
|
return (
|
||||||
<div className="space-y-3 px-3 pb-1">
|
<div className="space-y-3 px-3 pb-1">
|
||||||
<textarea
|
<textarea
|
||||||
@@ -25,7 +27,7 @@ export function AttendeeNotesForm({
|
|||||||
onChange={(event) => onDraftChange(event.target.value)}
|
onChange={(event) => onDraftChange(event.target.value)}
|
||||||
rows={4}
|
rows={4}
|
||||||
autoFocus
|
autoFocus
|
||||||
aria-label="Notas del miembro"
|
aria-label={t('notes.label')}
|
||||||
className="w-full resize-y rounded-xl border border-border bg-surface px-3 py-2.5 text-base leading-relaxed text-primary placeholder:text-secondary transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 sm:text-sm"
|
className="w-full resize-y rounded-xl border border-border bg-surface px-3 py-2.5 text-base leading-relaxed text-primary placeholder:text-secondary transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 sm:text-sm"
|
||||||
/>
|
/>
|
||||||
{error ? (
|
{error ? (
|
||||||
@@ -35,11 +37,11 @@ export function AttendeeNotesForm({
|
|||||||
) : null}
|
) : null}
|
||||||
<div className="flex justify-end gap-2">
|
<div className="flex justify-end gap-2">
|
||||||
<Button variant="ghost" onClick={onCancel} disabled={isSaving}>
|
<Button variant="ghost" onClick={onCancel} disabled={isSaving}>
|
||||||
Cancelar
|
{t('common:actions.cancel')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="primary" onClick={onSave} disabled={isSaving}>
|
<Button variant="primary" onClick={onSave} disabled={isSaving}>
|
||||||
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
Guardar
|
{t('common:actions.save')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,10 +3,12 @@ import { AttendeeNotesForm } from './AttendeeNotesForm'
|
|||||||
import { formatNotesUpdatedAt } from './detail'
|
import { formatNotesUpdatedAt } from './detail'
|
||||||
import { Section } from './Section'
|
import { Section } from './Section'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function AttendeeNotesSection() {
|
export function AttendeeNotesSection() {
|
||||||
const { attendee, saveAttendee, isUpdatingAttendee } = useAttendeeDetail()
|
const { attendee, saveAttendee, isUpdatingAttendee } = useAttendeeDetail()
|
||||||
const [isEditing, setIsEditing] = useState(false)
|
const [isEditing, setIsEditing] = useState(false)
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
const [draft, setDraft] = useState('')
|
const [draft, setDraft] = useState('')
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
@@ -23,13 +25,13 @@ export function AttendeeNotesSection() {
|
|||||||
await saveAttendee({ notes: draft })
|
await saveAttendee({ notes: draft })
|
||||||
setIsEditing(false)
|
setIsEditing(false)
|
||||||
} catch {
|
} catch {
|
||||||
setError('No pudimos guardar la nota. Revisá tu conexión e intentá de nuevo.')
|
setError(t('notes.saveError'))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Section
|
<Section
|
||||||
title="Notas"
|
title={t('notes.title')}
|
||||||
trailing={
|
trailing={
|
||||||
!isEditing ? (
|
!isEditing ? (
|
||||||
<button
|
<button
|
||||||
@@ -37,7 +39,7 @@ export function AttendeeNotesSection() {
|
|||||||
onClick={beginEditing}
|
onClick={beginEditing}
|
||||||
className="min-h-11 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
className="min-h-11 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
>
|
>
|
||||||
Editar
|
{t('notes.edit')}
|
||||||
</button>
|
</button>
|
||||||
) : null
|
) : null
|
||||||
}
|
}
|
||||||
@@ -60,7 +62,7 @@ export function AttendeeNotesSection() {
|
|||||||
) : (
|
) : (
|
||||||
<div className="px-3 pb-1">
|
<div className="px-3 pb-1">
|
||||||
<p className="whitespace-pre-line text-sm leading-relaxed text-primary">
|
<p className="whitespace-pre-line text-sm leading-relaxed text-primary">
|
||||||
{attendee.notes || 'Sin notas todavía.'}
|
{attendee.notes || t('notes.empty')}
|
||||||
</p>
|
</p>
|
||||||
<p className="mt-1.5 text-xs text-secondary">{formatNotesUpdatedAt(attendee.updatedAt)}</p>
|
<p className="mt-1.5 text-xs text-secondary">{formatNotesUpdatedAt(attendee.updatedAt)}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,21 +2,23 @@ import { Badge, useToast } from '../../components/ui'
|
|||||||
import { paymentPresentation } from './detail'
|
import { paymentPresentation } from './detail'
|
||||||
import { Section } from './Section'
|
import { Section } from './Section'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function AttendeePaymentsSection() {
|
export function AttendeePaymentsSection() {
|
||||||
const { attendee } = useAttendeeDetail()
|
const { attendee } = useAttendeeDetail()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
if (!attendee) return null
|
if (!attendee) return null
|
||||||
|
|
||||||
const payment = paymentPresentation(attendee.payment)
|
const payment = paymentPresentation(attendee.payment)
|
||||||
|
|
||||||
const registerPayment = () => {
|
const registerPayment = () => {
|
||||||
// TODO(cobros): conectar esta acción cuando se confirme el flujo y el endpoint de pagos.
|
// TODO(cobros): conectar esta acción cuando se confirme el flujo y el endpoint de pagos.
|
||||||
toast.info('Registrar pagos estará disponible cuando se defina el flujo de cobros.')
|
toast.info(t('payments.registerPending'))
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Section title="Cobros">
|
<Section title={t('payments.title')}>
|
||||||
<div className="flex min-h-14 items-center justify-between gap-3 px-3 py-1">
|
<div className="flex min-h-14 items-center justify-between gap-3 px-3 py-1">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<p className="truncate text-sm font-medium text-primary">
|
<p className="truncate text-sm font-medium text-primary">
|
||||||
@@ -31,7 +33,7 @@ export function AttendeePaymentsSection() {
|
|||||||
onClick={registerPayment}
|
onClick={registerPayment}
|
||||||
className="min-h-11 shrink-0 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
className="min-h-11 shrink-0 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
>
|
>
|
||||||
Registrar pago
|
{t('payments.register')}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</Section>
|
</Section>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Check } from 'lucide-react'
|
|||||||
import { formatPhoneDisplay } from '../../lib/format'
|
import { formatPhoneDisplay } from '../../lib/format'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
import { useCopyToClipboard } from './useCopyToClipboard'
|
import { useCopyToClipboard } from './useCopyToClipboard'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
/** The phone as the subtitle's second line.
|
/** The phone as the subtitle's second line.
|
||||||
*
|
*
|
||||||
@@ -12,6 +13,7 @@ import { useCopyToClipboard } from './useCopyToClipboard'
|
|||||||
export function AttendeePhoneLine() {
|
export function AttendeePhoneLine() {
|
||||||
const { attendee } = useAttendeeDetail()
|
const { attendee } = useAttendeeDetail()
|
||||||
const { copied, copy } = useCopyToClipboard()
|
const { copied, copy } = useCopyToClipboard()
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
|
|
||||||
const phone = attendee?.phone
|
const phone = attendee?.phone
|
||||||
const label = formatPhoneDisplay(phone)
|
const label = formatPhoneDisplay(phone)
|
||||||
@@ -33,12 +35,12 @@ export function AttendeePhoneLine() {
|
|||||||
className="flex shrink-0 items-center gap-1 text-xs font-medium text-accent-fg"
|
className="flex shrink-0 items-center gap-1 text-xs font-medium text-accent-fg"
|
||||||
>
|
>
|
||||||
<Check className="size-3.5" />
|
<Check className="size-3.5" />
|
||||||
Número copiado
|
{t('phone.copied')}
|
||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
</button>
|
</button>
|
||||||
<span aria-live="polite" className="sr-only">
|
<span aria-live="polite" className="sr-only">
|
||||||
{copied ? 'Número copiado al portapapeles' : ''}
|
{copied ? t('phone.copiedLive') : ''}
|
||||||
</span>
|
</span>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import type { LucideIcon } from 'lucide-react'
|
|||||||
import { CalendarCheck, CalendarX, History, Loader2, MoveRight, UserPlus, Wallet } from 'lucide-react'
|
import { CalendarCheck, CalendarX, History, Loader2, MoveRight, UserPlus, Wallet } from 'lucide-react'
|
||||||
import { Button, Modal } from '../../components/ui'
|
import { Button, Modal } from '../../components/ui'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
type Consequence = { key: string; icon: LucideIcon; text: string }
|
type Consequence = { key: string; icon: LucideIcon; text: string }
|
||||||
|
|
||||||
@@ -39,6 +40,7 @@ export function ChangeGroupDialog({
|
|||||||
|
|
||||||
const [targetGroupId, setTargetGroupId] = useState('')
|
const [targetGroupId, setTargetGroupId] = useState('')
|
||||||
const wasOpen = useRef(false)
|
const wasOpen = useRef(false)
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
|
|
||||||
// Cada apertura arranca sin destino elegido; al cerrar, el foco vuelve al "⋯".
|
// Cada apertura arranca sin destino elegido; al cerrar, el foco vuelve al "⋯".
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -62,7 +64,7 @@ export function ChangeGroupDialog({
|
|||||||
.map((membership) => membership.groupId),
|
.map((membership) => membership.groupId),
|
||||||
)
|
)
|
||||||
const otherGroups = groups.filter((group) => group.id !== groupId && !blocked.has(group.id))
|
const otherGroups = groups.filter((group) => group.id !== groupId && !blocked.has(group.id))
|
||||||
const currentName = groupName ?? 'el grupo actual'
|
const currentName = groupName ?? t('changeGroup.currentGroup')
|
||||||
const isSubmitting = isAdd ? isAddingToGroup : isMovingAttendee
|
const isSubmitting = isAdd ? isAddingToGroup : isMovingAttendee
|
||||||
|
|
||||||
const consequences: Consequence[] = isAdd
|
const consequences: Consequence[] = isAdd
|
||||||
@@ -70,34 +72,34 @@ export function ChangeGroupDialog({
|
|||||||
{
|
{
|
||||||
key: 'sigue',
|
key: 'sigue',
|
||||||
icon: CalendarCheck,
|
icon: CalendarCheck,
|
||||||
text: `Sigue en ${currentName}: va a estar en los dos grupos.`,
|
text: t('changeGroup.addStays', { group: currentName }),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'datos',
|
key: 'datos',
|
||||||
icon: History,
|
icon: History,
|
||||||
text: 'Comparte el contacto, las notas y el acceso a la app de alumnos.',
|
text: t('changeGroup.addShares'),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'cuotas',
|
key: 'cuotas',
|
||||||
icon: Wallet,
|
icon: Wallet,
|
||||||
text: 'La asistencia y las cuotas se llevan por separado en cada grupo.',
|
text: t('changeGroup.addSeparate'),
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
: [
|
: [
|
||||||
{
|
{
|
||||||
key: 'historial',
|
key: 'historial',
|
||||||
icon: History,
|
icon: History,
|
||||||
text: 'Conserva su historial, sus cuotas y su acceso a la app de alumnos.',
|
text: t('changeGroup.moveKeeps'),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'cuotas',
|
key: 'cuotas',
|
||||||
icon: Wallet,
|
icon: Wallet,
|
||||||
text: `Las cuotas pendientes de ${currentName} siguen vigentes.`,
|
text: t('changeGroup.moveFees', { group: currentName }),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'faltas',
|
key: 'faltas',
|
||||||
icon: CalendarX,
|
icon: CalendarX,
|
||||||
text: `Se cancelan las faltas avisadas para clases futuras de ${currentName}.`,
|
text: t('changeGroup.moveNotices', { group: currentName }),
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -105,25 +107,27 @@ export function ChangeGroupDialog({
|
|||||||
<Modal
|
<Modal
|
||||||
isOpen={isOpen}
|
isOpen={isOpen}
|
||||||
onClose={closeGroupDialog}
|
onClose={closeGroupDialog}
|
||||||
title={isAdd ? 'Agregar a otro grupo' : 'Cambiar de grupo'}
|
title={isAdd ? t('changeGroup.titleAdd') : t('changeGroup.title')}
|
||||||
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
|
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
|
||||||
maxWidth="sm"
|
maxWidth="sm"
|
||||||
>
|
>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{groupsPending ? (
|
{groupsPending ? (
|
||||||
<div className="flex justify-center py-4">
|
<div className="flex justify-center py-4">
|
||||||
<Loader2 className="size-5 animate-spin text-foreground/60" aria-label="Cargando grupos" />
|
<Loader2 className="size-5 animate-spin text-foreground/60" aria-label={t('changeGroup.loadingGroups')} />
|
||||||
</div>
|
</div>
|
||||||
) : otherGroups.length === 0 ? (
|
) : otherGroups.length === 0 ? (
|
||||||
<p className="rounded-xl border border-border bg-primary-soft/30 px-4 py-3 text-sm text-foreground/70">
|
<p className="rounded-xl border border-border bg-primary-soft/30 px-4 py-3 text-sm text-foreground/70">
|
||||||
{groups.length > 1
|
{groups.length > 1
|
||||||
? 'Ya es miembro de todos tus otros grupos.'
|
? t('changeGroup.allGroups')
|
||||||
: `No tenés otros grupos. Creá uno para poder ${isAdd ? 'agregar' : 'mover'} a este miembro.`}
|
: isAdd
|
||||||
|
? t('changeGroup.noGroupsAdd')
|
||||||
|
: t('changeGroup.noGroupsMove')}
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<label className="block">
|
<label className="block">
|
||||||
<span className="mb-1.5 block text-sm font-medium text-primary">
|
<span className="mb-1.5 block text-sm font-medium text-primary">
|
||||||
{isAdd ? 'Agregar a' : 'Mover a'}
|
{isAdd ? t('changeGroup.addTo') : t('changeGroup.moveTo')}
|
||||||
</span>
|
</span>
|
||||||
<select
|
<select
|
||||||
autoFocus
|
autoFocus
|
||||||
@@ -132,14 +136,13 @@ export function ChangeGroupDialog({
|
|||||||
className="h-10 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
|
className="h-10 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
|
||||||
>
|
>
|
||||||
<option value="" disabled>
|
<option value="" disabled>
|
||||||
Elegí un grupo
|
{t('changeGroup.pick')}
|
||||||
</option>
|
</option>
|
||||||
{otherGroups.map((group) => {
|
{otherGroups.map((group) => {
|
||||||
const full = isFull(group)
|
const full = isFull(group)
|
||||||
return (
|
return (
|
||||||
<option key={group.id} value={group.id} disabled={full}>
|
<option key={group.id} value={group.id} disabled={full}>
|
||||||
{group.name}
|
{full ? t('changeGroup.full', { name: group.name }) : group.name}
|
||||||
{full ? ' (sin cupo)' : ''}
|
|
||||||
</option>
|
</option>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
@@ -158,7 +161,7 @@ export function ChangeGroupDialog({
|
|||||||
|
|
||||||
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
|
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
|
||||||
<Button variant="ghost" onClick={closeGroupDialog}>
|
<Button variant="ghost" onClick={closeGroupDialog}>
|
||||||
Cancelar
|
{t('common:actions.cancel')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
@@ -173,7 +176,7 @@ export function ChangeGroupDialog({
|
|||||||
) : (
|
) : (
|
||||||
<MoveRight className="size-4" />
|
<MoveRight className="size-4" />
|
||||||
)}
|
)}
|
||||||
<span>{isAdd ? 'Agregar' : 'Cambiar de grupo'}</span>
|
<span>{isAdd ? t('changeGroup.add') : t('changeGroup.move')}</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import type { LucideIcon } from 'lucide-react'
|
|||||||
import { History, Link2, Loader2, Trash2, UserPlus, Users } from 'lucide-react'
|
import { History, Link2, Loader2, Trash2, UserPlus, Users } from 'lucide-react'
|
||||||
import { Button, Modal } from '../../components/ui'
|
import { Button, Modal } from '../../components/ui'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { Trans, useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
type Consequence = { key: string; icon: LucideIcon; text: string }
|
type Consequence = { key: string; icon: LucideIcon; text: string }
|
||||||
|
|
||||||
@@ -26,6 +27,7 @@ export function ConfirmRemoveAttendeeDialog({
|
|||||||
} = useAttendeeDetail()
|
} = useAttendeeDetail()
|
||||||
|
|
||||||
const wasOpen = useRef(false)
|
const wasOpen = useRef(false)
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
const contentRef = useRef<HTMLDivElement>(null)
|
const contentRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -52,27 +54,23 @@ export function ConfirmRemoveAttendeeDialog({
|
|||||||
{
|
{
|
||||||
key: 'historial',
|
key: 'historial',
|
||||||
icon: History,
|
icon: History,
|
||||||
text: 'Se borra su historial: las clases registradas y las ausencias que avisó dejan de existir.',
|
text: t('remove.history'),
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
if (attendee.notifyToken) {
|
if (attendee.notifyToken) {
|
||||||
consequences.push({ key: 'link', icon: Link2, text: 'El link de ausencias deja de funcionar.' })
|
consequences.push({ key: 'link', icon: Link2, text: t('remove.link') })
|
||||||
}
|
}
|
||||||
consequences.push({
|
consequences.push({
|
||||||
key: 'lugar',
|
key: 'lugar',
|
||||||
icon: Users,
|
icon: Users,
|
||||||
text: waiting
|
text: waiting ? t('remove.spotWaiting', { count: waitlistTotal }) : t('remove.spot'),
|
||||||
? `Se libera 1 lugar. Hay ${waitlistTotal} ${
|
|
||||||
waitlistTotal === 1 ? 'persona' : 'personas'
|
|
||||||
} en lista de espera.`
|
|
||||||
: 'Se libera 1 lugar en el grupo.',
|
|
||||||
})
|
})
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
isOpen={isRemoveDialogOpen}
|
isOpen={isRemoveDialogOpen}
|
||||||
onClose={closeRemoveDialog}
|
onClose={closeRemoveDialog}
|
||||||
title="Quitar del grupo"
|
title={t('remove.title')}
|
||||||
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
|
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
|
||||||
maxWidth="sm"
|
maxWidth="sm"
|
||||||
>
|
>
|
||||||
@@ -87,15 +85,18 @@ export function ConfirmRemoveAttendeeDialog({
|
|||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<p className="text-xs text-foreground">
|
<p className="text-xs text-foreground">
|
||||||
Si tiene cobros registrados no se va a poder quitar: primero hay que gestionarlos.
|
{t('remove.paymentsNote')}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
{canPromote && firstWaitlistEntry ? (
|
{canPromote && firstWaitlistEntry ? (
|
||||||
<div className="rounded-xl bg-accent-soft p-3.5">
|
<div className="rounded-xl bg-accent-soft p-3.5">
|
||||||
<p className="text-sm text-foreground">
|
<p className="text-sm text-foreground">
|
||||||
Si lo quitás, podés darle el lugar a{' '}
|
<Trans
|
||||||
<strong className="text-primary">{firstWaitlistEntry.fullName}</strong>, el primero
|
t={t}
|
||||||
de la lista de espera.
|
i18nKey="remove.promote"
|
||||||
|
values={{ name: firstWaitlistEntry.fullName }}
|
||||||
|
components={{ strong: <strong className="text-primary" /> }}
|
||||||
|
/>
|
||||||
</p>
|
</p>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
@@ -108,14 +109,14 @@ export function ConfirmRemoveAttendeeDialog({
|
|||||||
) : (
|
) : (
|
||||||
<UserPlus className="size-4" />
|
<UserPlus className="size-4" />
|
||||||
)}
|
)}
|
||||||
<span>Pasar a {firstWaitlistEntry.fullName} al grupo</span>
|
<span>{t('remove.promoteAction', { name: firstWaitlistEntry.fullName })}</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
|
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
|
||||||
<Button variant="ghost" onClick={closeRemoveDialog} autoFocus>
|
<Button variant="ghost" onClick={closeRemoveDialog} autoFocus>
|
||||||
Cancelar
|
{t('common:actions.cancel')}
|
||||||
</Button>
|
</Button>
|
||||||
{/* Label in black on the `danger` fill: it is the only way to reach AA
|
{/* Label in black on the `danger` fill: it is the only way to reach AA
|
||||||
with the same red in both themes (4.9:1 light, 6.7:1 dark); in white
|
with the same red in both themes (4.9:1 light, 6.7:1 dark); in white
|
||||||
@@ -130,7 +131,7 @@ export function ConfirmRemoveAttendeeDialog({
|
|||||||
) : (
|
) : (
|
||||||
<Trash2 className="size-4" />
|
<Trash2 className="size-4" />
|
||||||
)}
|
)}
|
||||||
<span>Quitar del grupo</span>
|
<span>{t('remove.confirm')}</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { inviteStudent } from '../../lib/api'
|
|||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
||||||
import { invitationMessage } from './studentAccess'
|
import { invitationMessage } from './studentAccess'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
type InviteToAppSheetProps = {
|
type InviteToAppSheetProps = {
|
||||||
isOpen: boolean
|
isOpen: boolean
|
||||||
@@ -34,6 +35,7 @@ export function InviteToAppSheet({
|
|||||||
reinvite,
|
reinvite,
|
||||||
}: InviteToAppSheetProps) {
|
}: InviteToAppSheetProps) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
const [invitation, setInvitation] = useState<StudentInvitationDto | null>(null)
|
const [invitation, setInvitation] = useState<StudentInvitationDto | null>(null)
|
||||||
const [copied, setCopied] = useState(false)
|
const [copied, setCopied] = useState(false)
|
||||||
const firstName = fullName.split(' ')[0] ?? fullName
|
const firstName = fullName.split(' ')[0] ?? fullName
|
||||||
@@ -89,32 +91,32 @@ export function InviteToAppSheet({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const preview = invitationMessage(firstName, groupName, invitation?.url ?? '🔗 link personal')
|
const preview = invitationMessage(firstName, groupName, invitation?.url ?? t('inviteSheet.linkPlaceholder'))
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sheet
|
<Sheet
|
||||||
isOpen={isOpen}
|
isOpen={isOpen}
|
||||||
onClose={handleClose}
|
onClose={handleClose}
|
||||||
title={reinvite ? 'Reinvitar a la app' : 'Invitar a la app'}
|
title={reinvite ? t('inviteSheet.titleReinvite') : t('inviteSheet.title')}
|
||||||
description={
|
description={
|
||||||
reinvite
|
reinvite
|
||||||
? `Mandale un link nuevo a ${firstName}. El acceso anterior deja de funcionar.`
|
? t('inviteSheet.descriptionReinvite', { name: firstName })
|
||||||
: `${firstName} va a poder avisar faltas, informar pagos y ver sus próximas clases. Sin contraseñas ni datos nuevos.`
|
: t('inviteSheet.description', { name: firstName })
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="rounded-2xl rounded-tl-sm bg-success-soft px-4 py-3 text-sm text-primary break-words" aria-label="Vista previa del mensaje">
|
<div className="rounded-2xl rounded-tl-sm bg-success-soft px-4 py-3 text-sm text-primary break-words" aria-label={t('inviteSheet.preview')}>
|
||||||
{preview}
|
{preview}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p className="flex gap-2 rounded-xl bg-primary-soft px-3 py-2.5 text-xs leading-relaxed text-secondary">
|
<p className="flex gap-2 rounded-xl bg-primary-soft px-3 py-2.5 text-xs leading-relaxed text-secondary">
|
||||||
<Lock className="mt-0.5 size-4 shrink-0 text-primary" aria-hidden="true" />
|
<Lock className="mt-0.5 size-4 shrink-0 text-primary" aria-hidden="true" />
|
||||||
El link es personal, sirve una sola vez y vence en 72 horas. Queda conectado el primer teléfono que lo abra.
|
{t('inviteSheet.security')}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
{mutation.isError ? (
|
{mutation.isError ? (
|
||||||
<p role="alert" className="text-sm text-danger-fg">
|
<p role="alert" className="text-sm text-danger-fg">
|
||||||
No pudimos generar el link. Probá de nuevo.
|
{t('inviteSheet.error')}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
@@ -122,7 +124,7 @@ export function InviteToAppSheet({
|
|||||||
{hasPhone ? (
|
{hasPhone ? (
|
||||||
<button type="button" onClick={() => void sendWhatsapp()} disabled={mutation.isPending} className={PRIMARY_ACTION_CLASS}>
|
<button type="button" onClick={() => void sendWhatsapp()} disabled={mutation.isPending} className={PRIMARY_ACTION_CLASS}>
|
||||||
{mutation.isPending ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : <MessageCircle className="size-4" aria-hidden="true" />}
|
{mutation.isPending ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : <MessageCircle className="size-4" aria-hidden="true" />}
|
||||||
Enviar por WhatsApp
|
{t('inviteSheet.sendWhatsapp')}
|
||||||
</button>
|
</button>
|
||||||
) : null}
|
) : null}
|
||||||
<button
|
<button
|
||||||
@@ -132,7 +134,7 @@ export function InviteToAppSheet({
|
|||||||
className={cn(hasPhone ? ACTION_BUTTON_CLASS : PRIMARY_ACTION_CLASS, 'w-full')}
|
className={cn(hasPhone ? ACTION_BUTTON_CLASS : PRIMARY_ACTION_CLASS, 'w-full')}
|
||||||
>
|
>
|
||||||
{copied ? <Check className="size-4" aria-hidden="true" /> : <Copy className="size-4" aria-hidden="true" />}
|
{copied ? <Check className="size-4" aria-hidden="true" /> : <Copy className="size-4" aria-hidden="true" />}
|
||||||
<span aria-live="polite">{copied ? 'Link copiado' : 'Copiar link'}</span>
|
<span aria-live="polite">{copied ? t('inviteSheet.copied') : t('inviteSheet.copy')}</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,23 +4,25 @@ import type { PersonMembership } from '@gruperly/shared'
|
|||||||
import { Badge, type BadgeVariant } from '../../components/ui'
|
import { Badge, type BadgeVariant } from '../../components/ui'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
import { Section } from './Section'
|
import { Section } from './Section'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
type StatusBadge = { label: string; variant: BadgeVariant }
|
type StatusBadge = { label: 'otherGroups.PAUSED' | 'otherGroups.DROPPED'; variant: BadgeVariant }
|
||||||
|
|
||||||
const STATUS_BADGE: Record<PersonMembership['status'], StatusBadge | null> = {
|
const STATUS_BADGE: Record<PersonMembership['status'], StatusBadge | null> = {
|
||||||
ACTIVE: null,
|
ACTIVE: null,
|
||||||
PAUSED: { label: 'En pausa', variant: 'warning' },
|
PAUSED: { label: 'otherGroups.PAUSED', variant: 'warning' },
|
||||||
DROPPED: { label: 'Dado de baja', variant: 'neutral' },
|
DROPPED: { label: 'otherGroups.DROPPED', variant: 'neutral' },
|
||||||
}
|
}
|
||||||
|
|
||||||
/* La misma persona en otros grupos del profe: cada fila abre su ficha en ese
|
/* La misma persona en otros grupos del profe: cada fila abre su ficha en ese
|
||||||
grupo (asistencia y cuotas son de cada grupo; el contacto es compartido). */
|
grupo (asistencia y cuotas son de cada grupo; el contacto es compartido). */
|
||||||
export function OtherGroupsSection() {
|
export function OtherGroupsSection() {
|
||||||
const { attendee } = useAttendeeDetail()
|
const { attendee } = useAttendeeDetail()
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
if (!attendee || attendee.otherGroups.length === 0) return null
|
if (!attendee || attendee.otherGroups.length === 0) return null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Section title="También está en">
|
<Section title={t('otherGroups.title')}>
|
||||||
<ul className="divide-y divide-border/60">
|
<ul className="divide-y divide-border/60">
|
||||||
{attendee.otherGroups.map((membership) => {
|
{attendee.otherGroups.map((membership) => {
|
||||||
const badge = STATUS_BADGE[membership.status]
|
const badge = STATUS_BADGE[membership.status]
|
||||||
@@ -35,7 +37,7 @@ export function OtherGroupsSection() {
|
|||||||
<span className="min-w-0 flex-1 truncate text-sm text-primary">{membership.groupName}</span>
|
<span className="min-w-0 flex-1 truncate text-sm text-primary">{membership.groupName}</span>
|
||||||
{badge ? (
|
{badge ? (
|
||||||
<Badge variant={badge.variant} className="text-[11px]">
|
<Badge variant={badge.variant} className="text-[11px]">
|
||||||
{badge.label}
|
{t(badge.label)}
|
||||||
</Badge>
|
</Badge>
|
||||||
) : null}
|
) : null}
|
||||||
<ChevronRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
<ChevronRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||||
|
|||||||
@@ -8,12 +8,14 @@ import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
|
|||||||
import { InviteToAppSheet } from './InviteToAppSheet'
|
import { InviteToAppSheet } from './InviteToAppSheet'
|
||||||
import { Section } from './Section'
|
import { Section } from './Section'
|
||||||
import { accessBadge, formatAgo, formatSince } from './studentAccess'
|
import { accessBadge, formatAgo, formatSince } from './studentAccess'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
/* "Acceso a la app": passive state, nothing to manage. The only action is
|
/* "Acceso a la app": passive state, nothing to manage. The only action is
|
||||||
inviting (or reinviting, which closes the previous access). */
|
inviting (or reinviting, which closes the previous access). */
|
||||||
export function StudentAccessSection() {
|
export function StudentAccessSection() {
|
||||||
const { groupId, groupName, attendee } = useAttendeeDetail()
|
const { groupId, groupName, attendee } = useAttendeeDetail()
|
||||||
const [sheetOpen, setSheetOpen] = useState(false)
|
const [sheetOpen, setSheetOpen] = useState(false)
|
||||||
|
const { t } = useTranslation(['attendeeDetail', 'common'])
|
||||||
|
|
||||||
const accessQuery = useQuery({
|
const accessQuery = useQuery({
|
||||||
queryKey: ['student-access', groupId, attendee?.id],
|
queryKey: ['student-access', groupId, attendee?.id],
|
||||||
@@ -28,7 +30,7 @@ export function StudentAccessSection() {
|
|||||||
const hasPhone = Boolean(attendee.phone || attendee.guardianPhone)
|
const hasPhone = Boolean(attendee.phone || attendee.guardianPhone)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Section title="Acceso a la app" trailing={badge ? <Badge variant={badge.variant}>{badge.label}</Badge> : null}>
|
<Section title={t('access.title')} trailing={badge ? <Badge variant={badge.variant}>{badge.label}</Badge> : null}>
|
||||||
<div className="space-y-3 px-3">
|
<div className="space-y-3 px-3">
|
||||||
{access?.status === 'active'
|
{access?.status === 'active'
|
||||||
? access.devices.map((device) => (
|
? access.devices.map((device) => (
|
||||||
@@ -37,8 +39,8 @@ export function StudentAccessSection() {
|
|||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<p className="truncate text-sm font-medium text-primary">{device.device}</p>
|
<p className="truncate text-sm font-medium text-primary">{device.device}</p>
|
||||||
<p className="text-xs text-secondary">
|
<p className="text-xs text-secondary">
|
||||||
Desde el {formatSince(device.createdAt)} · último uso {formatAgo(device.lastUsedAt)}
|
{t('access.device', { since: formatSince(device.createdAt), ago: formatAgo(device.lastUsedAt) })}
|
||||||
{access.hasPasskey ? ' · Face ID' : ''}
|
{access.hasPasskey ? t('access.faceId') : ''}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -46,12 +48,12 @@ export function StudentAccessSection() {
|
|||||||
: null}
|
: null}
|
||||||
|
|
||||||
{access?.status === 'not_invited' ? (
|
{access?.status === 'not_invited' ? (
|
||||||
<p className="text-sm text-secondary">Para que avise faltas e informe pagos desde su teléfono.</p>
|
<p className="text-sm text-secondary">{t('access.pitch')}</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{invited ? (
|
{invited ? (
|
||||||
<p className="text-xs text-secondary">
|
<p className="text-xs text-secondary">
|
||||||
¿Te dice que no puede entrar? Mandale un link nuevo: cierra el acceso anterior.
|
{t('access.reinviteHint')}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
@@ -62,7 +64,7 @@ export function StudentAccessSection() {
|
|||||||
className={invited ? `${ACTION_BUTTON_CLASS} w-full` : PRIMARY_ACTION_CLASS}
|
className={invited ? `${ACTION_BUTTON_CLASS} w-full` : PRIMARY_ACTION_CLASS}
|
||||||
>
|
>
|
||||||
{invited ? <MessageCircle className="size-4" aria-hidden="true" /> : <UserPlus className="size-4" aria-hidden="true" />}
|
{invited ? <MessageCircle className="size-4" aria-hidden="true" /> : <UserPlus className="size-4" aria-hidden="true" />}
|
||||||
{invited ? (hasPhone ? 'Reinvitar por WhatsApp' : 'Reinvitar') : 'Invitar a la app'}
|
{invited ? (hasPhone ? t('access.reinviteWhatsapp') : t('access.reinvite')) : t('access.invite')}
|
||||||
</button>
|
</button>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
@@ -71,7 +73,7 @@ export function StudentAccessSection() {
|
|||||||
isOpen={sheetOpen}
|
isOpen={sheetOpen}
|
||||||
onClose={() => setSheetOpen(false)}
|
onClose={() => setSheetOpen(false)}
|
||||||
groupId={groupId}
|
groupId={groupId}
|
||||||
groupName={groupName ?? 'tu grupo'}
|
groupName={groupName ?? t('access.yourGroup')}
|
||||||
attendeeId={attendee.id}
|
attendeeId={attendee.id}
|
||||||
fullName={attendee.fullName}
|
fullName={attendee.fullName}
|
||||||
hasPhone={hasPhone}
|
hasPhone={hasPhone}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { AttendanceHistoryItem } from '@gruperly/shared'
|
import type { AttendanceHistoryItem } from '@gruperly/shared'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
|
|
||||||
/* The history endpoint cuts off at 20 sessions (HISTORY_SESSIONS_LIMIT on the
|
/* The history endpoint cuts off at 20 sessions (HISTORY_SESSIONS_LIMIT on the
|
||||||
backend). It is the real ceiling on what this screen can show, so "Ver todas"
|
backend). It is the real ceiling on what this screen can show, so "Ver todas"
|
||||||
@@ -10,22 +11,20 @@ export type AttendanceSession = AttendanceHistoryItem
|
|||||||
|
|
||||||
export function formatSessionShortDate(iso: string): string {
|
export function formatSessionShortDate(iso: string): string {
|
||||||
const date = new Date(iso)
|
const date = new Date(iso)
|
||||||
const weekday = date.toLocaleDateString('es-MX', { weekday: 'short' })
|
const weekday = date.toLocaleDateString(i18n.language, { weekday: 'short' })
|
||||||
const day = date.toLocaleDateString('es-MX', { day: 'numeric' })
|
const day = date.toLocaleDateString(i18n.language, { day: 'numeric' })
|
||||||
const month = date.toLocaleDateString('es-MX', { month: 'short' })
|
const month = date.toLocaleDateString(i18n.language, { month: 'short' })
|
||||||
return `${weekday} ${day} ${month}`
|
return `${weekday} ${day} ${month}`
|
||||||
}
|
}
|
||||||
|
|
||||||
export function attendanceStatusLabel(status: AttendanceSession['status']): string {
|
export function attendanceStatusLabel(status: AttendanceSession['status']): string {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case 'PRESENT':
|
case 'PRESENT':
|
||||||
return 'Asistió'
|
|
||||||
case 'ABSENT':
|
case 'ABSENT':
|
||||||
return 'Faltó'
|
|
||||||
case 'EXCUSED':
|
case 'EXCUSED':
|
||||||
return 'Faltó (avisó)'
|
return i18n.t(`attendeeDetail:attendance.${status}`)
|
||||||
default:
|
default:
|
||||||
return 'Sin registrar'
|
return i18n.t('attendeeDetail:attendance.NONE')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,7 +46,7 @@ export function attendanceStatusClass(status: AttendanceSession['status']): stri
|
|||||||
|
|
||||||
/** "28 sep 2026". It is the usual short date: it fits on one line on mobile. */
|
/** "28 sep 2026". It is the usual short date: it fits on one line on mobile. */
|
||||||
export function formatMemberSince(iso: string): string {
|
export function formatMemberSince(iso: string): string {
|
||||||
return new Date(iso).toLocaleDateString('es-MX', {
|
return new Date(iso).toLocaleDateString(i18n.language, {
|
||||||
day: 'numeric',
|
day: 'numeric',
|
||||||
month: 'short',
|
month: 'short',
|
||||||
year: 'numeric',
|
year: 'numeric',
|
||||||
@@ -56,7 +55,7 @@ export function formatMemberSince(iso: string): string {
|
|||||||
|
|
||||||
/** "1 clase" / "2 clases". */
|
/** "1 clase" / "2 clases". */
|
||||||
export function classCountLabel(count: number): string {
|
export function classCountLabel(count: number): string {
|
||||||
return count === 1 ? '1 clase' : `${count} clases`
|
return i18n.t('attendeeDetail:attendance.classes', { count })
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What is displayed: from the most recent to the oldest, with the last
|
/** What is displayed: from the most recent to the oldest, with the last
|
||||||
@@ -78,8 +77,8 @@ export type AttendanceSummary = {
|
|||||||
/** Summary of the rows being shown. The denominator deliberately includes
|
/** Summary of the rows being shown. The denominator deliberately includes
|
||||||
* unmarked sessions so the counter always matches the visible list. */
|
* unmarked sessions so the counter always matches the visible list. */
|
||||||
export function attendanceSummary(sessions: AttendanceSession[]): AttendanceSummary {
|
export function attendanceSummary(sessions: AttendanceSession[]): AttendanceSummary {
|
||||||
if (sessions.length === 0) return { label: 'Sin clases registradas' }
|
if (sessions.length === 0) return { label: i18n.t('attendeeDetail:attendance.noClasses') }
|
||||||
|
|
||||||
const present = sessions.filter((session) => session.status === 'PRESENT').length
|
const present = sessions.filter((session) => session.status === 'PRESENT').length
|
||||||
return { label: `${present} de ${classCountLabel(sessions.length)}` }
|
return { label: i18n.t('attendeeDetail:attendance.summary', { present, classes: classCountLabel(sessions.length) }) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import type { AttendeePaymentSummary } from '@gruperly/shared'
|
import type { AttendeePaymentSummary } from '@gruperly/shared'
|
||||||
import { UpdateAttendeeSchema } from '@gruperly/shared'
|
import { UpdateAttendeeSchema } from '@gruperly/shared'
|
||||||
|
import { validationMessage } from '../../i18n/validation'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
|
|
||||||
export function contactEmailError(email: string): string | null {
|
export function contactEmailError(email: string): string | null {
|
||||||
const result = UpdateAttendeeSchema.safeParse({ email })
|
const result = UpdateAttendeeSchema.safeParse({ email })
|
||||||
if (result.success) return null
|
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 = {
|
export type PaymentPresentation = {
|
||||||
@@ -20,47 +22,50 @@ export function paymentPresentation(
|
|||||||
): PaymentPresentation {
|
): PaymentPresentation {
|
||||||
const periodLabel = capitalize(formatMonthAndYear(today))
|
const periodLabel = capitalize(formatMonthAndYear(today))
|
||||||
if (!payment) {
|
if (!payment) {
|
||||||
return { periodLabel, statusLabel: 'Sin cobro registrado', chipLabel: 'Al día', isDue: false }
|
return {
|
||||||
|
periodLabel,
|
||||||
|
statusLabel: i18n.t('attendeeDetail:payments.noCharge'),
|
||||||
|
chipLabel: i18n.t('attendeeDetail:payments.upToDate'),
|
||||||
|
isDue: false,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const isDue = payment.status === 'PENDING' || payment.status === 'OVERDUE'
|
const isDue = payment.status === 'PENDING' || payment.status === 'OVERDUE'
|
||||||
return {
|
return {
|
||||||
periodLabel,
|
periodLabel,
|
||||||
statusLabel: paymentStatusLabel(payment.status),
|
statusLabel: paymentStatusLabel(payment.status),
|
||||||
chipLabel: isDue ? `Debe ${formatMonth(new Date(payment.dueDate))}` : 'Al día',
|
chipLabel: isDue
|
||||||
|
? i18n.t('attendeeDetail:payments.owes', { month: formatMonth(new Date(payment.dueDate)) })
|
||||||
|
: i18n.t('attendeeDetail:payments.upToDate'),
|
||||||
isDue,
|
isDue,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatNotesUpdatedAt(updatedAt: string, today = new Date()): string {
|
export function formatNotesUpdatedAt(updatedAt: string, today = new Date()): string {
|
||||||
const date = new Date(updatedAt)
|
const date = new Date(updatedAt)
|
||||||
if (sameCalendarDate(date, today)) return 'Editado hoy'
|
if (sameCalendarDate(date, today)) return i18n.t('attendeeDetail:notes.editedToday')
|
||||||
return `Editado ${date.toLocaleDateString('es-MX', {
|
return i18n.t('attendeeDetail:notes.edited', {
|
||||||
day: 'numeric',
|
date: date.toLocaleDateString(i18n.language, { day: 'numeric', month: 'short', year: 'numeric' }),
|
||||||
month: 'short',
|
})
|
||||||
year: 'numeric',
|
|
||||||
})}`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function paymentStatusLabel(status: AttendeePaymentSummary['status']): string {
|
function paymentStatusLabel(status: AttendeePaymentSummary['status']): string {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case 'PAID':
|
case 'PAID':
|
||||||
return 'Pagado'
|
|
||||||
case 'OVERDUE':
|
case 'OVERDUE':
|
||||||
return 'Vencido'
|
|
||||||
case 'CANCELLED':
|
case 'CANCELLED':
|
||||||
return 'Cancelado'
|
return i18n.t(`common:paymentStatus.${status}`)
|
||||||
default:
|
default:
|
||||||
return 'Pendiente'
|
return i18n.t('common:paymentStatus.PENDING')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatMonth(date: Date): string {
|
function formatMonth(date: Date): string {
|
||||||
return date.toLocaleDateString('es-MX', { month: 'long' })
|
return date.toLocaleDateString(i18n.language, { month: 'long' })
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatMonthAndYear(date: Date): string {
|
function formatMonthAndYear(date: Date): string {
|
||||||
const parts = new Intl.DateTimeFormat('es-MX', { month: 'long', year: 'numeric' }).formatToParts(date)
|
const parts = new Intl.DateTimeFormat(i18n.language, { month: 'long', year: 'numeric' }).formatToParts(date)
|
||||||
const month = parts.find((part) => part.type === 'month')?.value ?? ''
|
const month = parts.find((part) => part.type === 'month')?.value ?? ''
|
||||||
const year = parts.find((part) => part.type === 'year')?.value ?? ''
|
const year = parts.find((part) => part.type === 'year')?.value ?? ''
|
||||||
return `${month} ${year}`.trim()
|
return `${month} ${year}`.trim()
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { StudentAccessDto } from '@gruperly/shared'
|
import type { StudentAccessDto } from '@gruperly/shared'
|
||||||
import type { BadgeVariant } from '../../components/ui'
|
import type { BadgeVariant } from '../../components/ui'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
|
|
||||||
const HOUR_MS = 3_600_000
|
const HOUR_MS = 3_600_000
|
||||||
const DAY_MS = 24 * HOUR_MS
|
const DAY_MS = 24 * HOUR_MS
|
||||||
@@ -7,33 +8,36 @@ const DAY_MS = 24 * HOUR_MS
|
|||||||
export function accessBadge(access: StudentAccessDto, now: Date = new Date()): { label: string; variant: BadgeVariant } {
|
export function accessBadge(access: StudentAccessDto, now: Date = new Date()): { label: string; variant: BadgeVariant } {
|
||||||
switch (access.status) {
|
switch (access.status) {
|
||||||
case 'active':
|
case 'active':
|
||||||
return { label: 'Activo', variant: 'success' }
|
return { label: i18n.t('attendeeDetail:access.active'), variant: 'success' }
|
||||||
case 'invited': {
|
case 'invited': {
|
||||||
const hours = access.invitationExpiresAt
|
const hours = access.invitationExpiresAt
|
||||||
? Math.max(1, Math.ceil((Date.parse(access.invitationExpiresAt) - now.getTime()) / HOUR_MS))
|
? Math.max(1, Math.ceil((Date.parse(access.invitationExpiresAt) - now.getTime()) / HOUR_MS))
|
||||||
: null
|
: null
|
||||||
return { label: hours ? `Invitado · vence en ${hours} h` : 'Invitado', variant: 'info' }
|
return {
|
||||||
|
label: hours ? i18n.t('attendeeDetail:access.invitedExpires', { hours }) : i18n.t('attendeeDetail:access.invited'),
|
||||||
|
variant: 'info',
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case 'expired':
|
case 'expired':
|
||||||
return { label: 'Vencido', variant: 'warning' }
|
return { label: i18n.t('attendeeDetail:access.expired'), variant: 'warning' }
|
||||||
default:
|
default:
|
||||||
return { label: 'Sin invitar', variant: 'neutral' }
|
return { label: i18n.t('attendeeDetail:access.notInvited'), variant: 'neutral' }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** "hace 5 min", "hace 3 h", "ayer", "hace 4 días". */
|
/** "hace 5 min", "hace 3 h", "ayer", "hace 4 días". */
|
||||||
export function formatAgo(iso: string, now: Date = new Date()): string {
|
export function formatAgo(iso: string, now: Date = new Date()): string {
|
||||||
const diff = Math.max(0, now.getTime() - Date.parse(iso))
|
const diff = Math.max(0, now.getTime() - Date.parse(iso))
|
||||||
if (diff < HOUR_MS) return `hace ${Math.max(1, Math.round(diff / 60_000))} min`
|
if (diff < HOUR_MS) return i18n.t('attendeeDetail:access.agoMinutes', { count: Math.max(1, Math.round(diff / 60_000)) })
|
||||||
if (diff < DAY_MS) return `hace ${Math.round(diff / HOUR_MS)} h`
|
if (diff < DAY_MS) return i18n.t('attendeeDetail:access.agoHours', { count: Math.round(diff / HOUR_MS) })
|
||||||
const days = Math.round(diff / DAY_MS)
|
const days = Math.round(diff / DAY_MS)
|
||||||
return days === 1 ? 'ayer' : `hace ${days} días`
|
return days === 1 ? i18n.t('attendeeDetail:access.yesterday') : i18n.t('attendeeDetail:access.agoDays', { count: days })
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatSince(iso: string): string {
|
export function formatSince(iso: string): string {
|
||||||
return new Date(iso).toLocaleDateString('es-AR', { day: 'numeric', month: 'long' })
|
return new Date(iso).toLocaleDateString(i18n.language, { day: 'numeric', month: 'long' })
|
||||||
}
|
}
|
||||||
|
|
||||||
export function invitationMessage(firstName: string, groupName: string, url: string): string {
|
export function invitationMessage(firstName: string, groupName: string, url: string): string {
|
||||||
return `¡Hola ${firstName}! Te invito a gruperly para avisar faltas e informar pagos de ${groupName}. ${url}`
|
return i18n.t('attendeeDetail:inviteSheet.message', { name: firstName, group: groupName, url })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { Check } from 'lucide-react'
|
import { Check } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { AlertTag } from './AlertTag'
|
import { AlertTag } from './AlertTag'
|
||||||
import { reminderMessage, whatsappLink, type AttentionItem } from './attention'
|
import { alertDetail, alertLabel, reminderMessage, whatsappLink, type AttentionItem } from './attention'
|
||||||
import { SeverityAvatar } from './SeverityAvatar'
|
import { SeverityAvatar } from './SeverityAvatar'
|
||||||
|
|
||||||
const ACTION_CLASS =
|
const ACTION_CLASS =
|
||||||
@@ -15,10 +16,12 @@ type AttentionCardProps = {
|
|||||||
|
|
||||||
export function AttentionCard({ item, onResolve }: AttentionCardProps) {
|
export function AttentionCard({ item, onResolve }: AttentionCardProps) {
|
||||||
const { student, alert } = item
|
const { student, alert } = item
|
||||||
|
const { t } = useTranslation('attention')
|
||||||
|
const label = alertLabel(alert)
|
||||||
const urgent = alert.gravedad === 'urgente'
|
const urgent = alert.gravedad === 'urgente'
|
||||||
const isPayment = alert.tipo === 'pago'
|
const isPayment = alert.tipo === 'pago'
|
||||||
|
|
||||||
const actionLabel = isPayment ? 'Enviar recordatorio' : 'Contactar'
|
const actionLabel = isPayment ? t('card.remind') : t('card.contact')
|
||||||
const href = whatsappLink(student, isPayment ? reminderMessage(student) : undefined)
|
const href = whatsappLink(student, isPayment ? reminderMessage(student) : undefined)
|
||||||
// Urgent: light fill, the strongest action on screen. To watch: subtle gray.
|
// Urgent: light fill, the strongest action on screen. To watch: subtle gray.
|
||||||
const primaryTone = urgent
|
const primaryTone = urgent
|
||||||
@@ -39,10 +42,10 @@ export function AttentionCard({ item, onResolve }: AttentionCardProps) {
|
|||||||
</Link>
|
</Link>
|
||||||
<p className="truncate text-sm text-secondary">{student.groupName}</p>
|
<p className="truncate text-sm text-secondary">{student.groupName}</p>
|
||||||
</div>
|
</div>
|
||||||
<AlertTag severity={alert.gravedad}>{alert.etiqueta}</AlertTag>
|
<AlertTag severity={alert.gravedad}>{label}</AlertTag>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p className="mt-3 text-sm text-primary">{alert.detalle}</p>
|
<p className="mt-3 text-sm text-primary">{alertDetail(alert)}</p>
|
||||||
|
|
||||||
<div className="mt-3 grid grid-cols-2 gap-2">
|
<div className="mt-3 grid grid-cols-2 gap-2">
|
||||||
{href ? (
|
{href ? (
|
||||||
@@ -50,7 +53,7 @@ export function AttentionCard({ item, onResolve }: AttentionCardProps) {
|
|||||||
href={href}
|
href={href}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
aria-label={`${actionLabel} a ${student.fullName} por WhatsApp`}
|
aria-label={t('card.actionWhatsapp', { action: actionLabel, name: student.fullName })}
|
||||||
className={cn(ACTION_CLASS, primaryTone)}
|
className={cn(ACTION_CLASS, primaryTone)}
|
||||||
>
|
>
|
||||||
{actionLabel}
|
{actionLabel}
|
||||||
@@ -59,7 +62,7 @@ export function AttentionCard({ item, onResolve }: AttentionCardProps) {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
disabled
|
disabled
|
||||||
aria-label={`${actionLabel}: ${student.fullName} no tiene teléfono cargado`}
|
aria-label={t('card.noPhone', { action: actionLabel, name: student.fullName })}
|
||||||
className={cn(ACTION_CLASS, primaryTone, 'cursor-not-allowed opacity-45')}
|
className={cn(ACTION_CLASS, primaryTone, 'cursor-not-allowed opacity-45')}
|
||||||
>
|
>
|
||||||
{actionLabel}
|
{actionLabel}
|
||||||
@@ -68,11 +71,11 @@ export function AttentionCard({ item, onResolve }: AttentionCardProps) {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onResolve}
|
onClick={onResolve}
|
||||||
aria-label={`Marcar como resuelto: ${student.fullName}, ${alert.etiqueta}`}
|
aria-label={t('card.resolveLabel', { name: student.fullName, alert: label })}
|
||||||
className={cn(ACTION_CLASS, 'border border-border text-primary hover:bg-primary-soft')}
|
className={cn(ACTION_CLASS, 'border border-border text-primary hover:bg-primary-soft')}
|
||||||
>
|
>
|
||||||
<Check className="size-4" aria-hidden="true" />
|
<Check className="size-4" aria-hidden="true" />
|
||||||
Resuelto
|
{t('card.resolve')}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { ArrowLeft, ListFilter } from 'lucide-react'
|
import { ArrowLeft, ListFilter } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { createPortal } from 'react-dom'
|
import { createPortal } from 'react-dom'
|
||||||
import { useImmersiveBarHost } from '../../context/ImmersiveBarProvider'
|
import { useImmersiveBarHost } from '../../context/ImmersiveBarProvider'
|
||||||
|
|
||||||
@@ -10,18 +11,19 @@ import { useImmersiveBarHost } from '../../context/ImmersiveBarProvider'
|
|||||||
sticky box, like `LargeTitle`. */
|
sticky box, like `LargeTitle`. */
|
||||||
export function AttentionHeader({ subtitle }: { subtitle: string }) {
|
export function AttentionHeader({ subtitle }: { subtitle: string }) {
|
||||||
const host = useImmersiveBarHost()
|
const host = useImmersiveBarHost()
|
||||||
|
const { t } = useTranslation('attention')
|
||||||
|
|
||||||
const bar = (
|
const bar = (
|
||||||
<div className="flex h-full items-center gap-1 border-b border-border bg-background/90 px-2 backdrop-blur-md lg:px-0">
|
<div className="flex h-full items-center gap-1 border-b border-border bg-background/90 px-2 backdrop-blur-md lg:px-0">
|
||||||
<Link
|
<Link
|
||||||
to="/groups"
|
to="/groups"
|
||||||
aria-label="Volver"
|
aria-label={t('back')}
|
||||||
className="inline-flex size-11 shrink-0 items-center justify-center rounded-xl text-primary hover:bg-primary-soft focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none"
|
className="inline-flex size-11 shrink-0 items-center justify-center rounded-xl text-primary hover:bg-primary-soft focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none"
|
||||||
>
|
>
|
||||||
<ArrowLeft className="size-5" aria-hidden="true" />
|
<ArrowLeft className="size-5" aria-hidden="true" />
|
||||||
</Link>
|
</Link>
|
||||||
<div className="min-w-0 flex-1 px-1">
|
<div className="min-w-0 flex-1 px-1">
|
||||||
<h1 className="truncate text-base leading-tight font-semibold text-primary">Requiere atención</h1>
|
<h1 className="truncate text-base leading-tight font-semibold text-primary">{t('title')}</h1>
|
||||||
<p className="truncate text-xs text-secondary" aria-live="polite">
|
<p className="truncate text-xs text-secondary" aria-live="polite">
|
||||||
{subtitle}
|
{subtitle}
|
||||||
</p>
|
</p>
|
||||||
@@ -29,7 +31,7 @@ export function AttentionHeader({ subtitle }: { subtitle: string }) {
|
|||||||
{/* TODO: ordenar/filtrar por grupo. Por ahora no hace nada. */}
|
{/* TODO: ordenar/filtrar por grupo. Por ahora no hace nada. */}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
aria-label="Ordenar y filtrar"
|
aria-label={t('sortFilter')}
|
||||||
className="inline-flex size-11 shrink-0 items-center justify-center rounded-xl text-secondary hover:bg-primary-soft focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none"
|
className="inline-flex size-11 shrink-0 items-center justify-center rounded-xl text-secondary hover:bg-primary-soft focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none"
|
||||||
>
|
>
|
||||||
<ListFilter className="size-5" aria-hidden="true" />
|
<ListFilter className="size-5" aria-hidden="true" />
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { createContext, useContext, useMemo, useState } from 'react'
|
|||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import type { AttentionOverview, StudentAlert } from '@gruperly/shared'
|
import type { AttentionOverview, StudentAlert } from '@gruperly/shared'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
import { useToast } from '../../components/ui'
|
import { useToast } from '../../components/ui'
|
||||||
import { resolveAlert } from '../../lib/api'
|
import { resolveAlert } from '../../lib/api'
|
||||||
import {
|
import {
|
||||||
@@ -49,7 +50,7 @@ export function AttentionProvider({ children }: { children: ReactNode }) {
|
|||||||
},
|
},
|
||||||
onError: (_error, _variables, context) => {
|
onError: (_error, _variables, context) => {
|
||||||
if (context?.previous) queryClient.setQueryData(attentionQueryOptions.queryKey, context.previous)
|
if (context?.previous) queryClient.setQueryData(attentionQueryOptions.queryKey, context.previous)
|
||||||
toast.error('No pudimos marcarlo como resuelto. Probá de nuevo.')
|
toast.error(i18n.t('attention:card.resolveError'))
|
||||||
},
|
},
|
||||||
onSettled: () => {
|
onSettled: () => {
|
||||||
void queryClient.invalidateQueries({ queryKey: attentionQueryOptions.queryKey })
|
void queryClient.invalidateQueries({ queryKey: attentionQueryOptions.queryKey })
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import type { StudentAlertSeverity } from '@gruperly/shared'
|
import type { StudentAlertSeverity } from '@gruperly/shared'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { AttentionCard } from './AttentionCard'
|
import { AttentionCard } from './AttentionCard'
|
||||||
import type { AttentionItem } from './attention'
|
import type { AttentionItem } from './attention'
|
||||||
|
|
||||||
const SECTIONS: Record<StudentAlertSeverity, { title: string; dot: string; text: string }> = {
|
const SECTIONS: Record<StudentAlertSeverity, { dot: string; text: string }> = {
|
||||||
urgente: { title: 'Urgente', dot: 'bg-alert-urgent-ring', text: 'text-alert-urgent-fg' },
|
urgente: { dot: 'bg-alert-urgent-ring', text: 'text-alert-urgent-fg' },
|
||||||
vigilar: { title: 'A vigilar', dot: 'bg-alert-watch-ring', text: 'text-alert-watch-fg' },
|
vigilar: { dot: 'bg-alert-watch-ring', text: 'text-alert-watch-fg' },
|
||||||
}
|
}
|
||||||
|
|
||||||
type AttentionSectionProps = {
|
type AttentionSectionProps = {
|
||||||
@@ -16,6 +17,7 @@ type AttentionSectionProps = {
|
|||||||
|
|
||||||
/** One severity block. Not rendered when it is empty. */
|
/** One severity block. Not rendered when it is empty. */
|
||||||
export function AttentionSection({ severity, items, onResolve }: AttentionSectionProps) {
|
export function AttentionSection({ severity, items, onResolve }: AttentionSectionProps) {
|
||||||
|
const { t } = useTranslation('attention')
|
||||||
if (items.length === 0) return null
|
if (items.length === 0) return null
|
||||||
const section = SECTIONS[severity]
|
const section = SECTIONS[severity]
|
||||||
const headingId = `attention-${severity}`
|
const headingId = `attention-${severity}`
|
||||||
@@ -27,7 +29,7 @@ export function AttentionSection({ severity, items, onResolve }: AttentionSectio
|
|||||||
className={cn('flex items-center gap-2 text-xs font-semibold tracking-wider uppercase', section.text)}
|
className={cn('flex items-center gap-2 text-xs font-semibold tracking-wider uppercase', section.text)}
|
||||||
>
|
>
|
||||||
<span className={cn('size-2 rounded-full', section.dot)} aria-hidden="true" />
|
<span className={cn('size-2 rounded-full', section.dot)} aria-hidden="true" />
|
||||||
{section.title}
|
{t(`sections.${severity}`)}
|
||||||
<span aria-hidden="true">·</span>
|
<span aria-hidden="true">·</span>
|
||||||
<span className="tabular-nums">{items.length}</span>
|
<span className="tabular-nums">{items.length}</span>
|
||||||
</h2>
|
</h2>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Loader2 } from 'lucide-react'
|
import { Loader2 } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { Button } from '../../components/ui'
|
import { Button } from '../../components/ui'
|
||||||
import { AttentionHeader } from './AttentionHeader'
|
import { AttentionHeader } from './AttentionHeader'
|
||||||
import { AttentionSection } from './AttentionSection'
|
import { AttentionSection } from './AttentionSection'
|
||||||
@@ -9,6 +10,7 @@ import { FilterChips } from './FilterChips'
|
|||||||
|
|
||||||
export function AttentionView() {
|
export function AttentionView() {
|
||||||
const { items, isPending, isError, retry, filter, setFilter, resolve } = useAttention()
|
const { items, isPending, isError, retry, filter, setFilter, resolve } = useAttention()
|
||||||
|
const { t } = useTranslation(['attention', 'common'])
|
||||||
|
|
||||||
const visible = filterItems(items, filter)
|
const visible = filterItems(items, filter)
|
||||||
const { urgente, vigilar } = itemsBySeverity(visible)
|
const { urgente, vigilar } = itemsBySeverity(visible)
|
||||||
@@ -16,7 +18,7 @@ export function AttentionView() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="pb-6">
|
<section className="pb-6">
|
||||||
<AttentionHeader subtitle={isPending ? 'Cargando…' : attentionSubtitle(items)} />
|
<AttentionHeader subtitle={isPending ? t('loading') : attentionSubtitle(items)} />
|
||||||
|
|
||||||
{/* The chips stay under the bar (56px) while the cards scroll. */}
|
{/* The chips stay under the bar (56px) while the cards scroll. */}
|
||||||
<div className="sticky top-14 z-30 -mx-4 bg-background px-4 lg:mx-0 lg:px-0">
|
<div className="sticky top-14 z-30 -mx-4 bg-background px-4 lg:mx-0 lg:px-0">
|
||||||
@@ -26,13 +28,13 @@ export function AttentionView() {
|
|||||||
{isPending ? (
|
{isPending ? (
|
||||||
<div className="flex items-center justify-center py-16" role="status">
|
<div className="flex items-center justify-center py-16" role="status">
|
||||||
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
||||||
<span className="sr-only">Cargando alertas</span>
|
<span className="sr-only">{t('loadingAlerts')}</span>
|
||||||
</div>
|
</div>
|
||||||
) : isError ? (
|
) : isError ? (
|
||||||
<div className="mt-4 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
<div className="mt-4 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
<p>No pudimos cargar las alertas.</p>
|
<p>{t('loadError')}</p>
|
||||||
<Button variant="outline" size="sm" onClick={retry}>
|
<Button variant="outline" size="sm" onClick={retry}>
|
||||||
Reintentar
|
{t('common:actions.retry')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : visible.length === 0 ? (
|
) : visible.length === 0 ? (
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
import { Check } from 'lucide-react'
|
import { Check } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function EmptyAttention() {
|
export function EmptyAttention() {
|
||||||
|
const { t } = useTranslation('attention')
|
||||||
return (
|
return (
|
||||||
<div className="mt-10 flex flex-col items-center px-6 text-center" role="status">
|
<div className="mt-10 flex flex-col items-center px-6 text-center" role="status">
|
||||||
<span className="flex size-14 items-center justify-center rounded-full bg-success-soft text-success">
|
<span className="flex size-14 items-center justify-center rounded-full bg-success-soft text-success">
|
||||||
<Check className="size-7" strokeWidth={2.5} aria-hidden="true" />
|
<Check className="size-7" strokeWidth={2.5} aria-hidden="true" />
|
||||||
</span>
|
</span>
|
||||||
<p className="mt-4 text-base font-semibold text-primary">Todo en orden</p>
|
<p className="mt-4 text-base font-semibold text-primary">{t('empty.title')}</p>
|
||||||
<p className="mt-1 max-w-[32ch] text-sm text-secondary">
|
<p className="mt-1 max-w-[32ch] text-sm text-secondary">
|
||||||
No hay alumnos que requieran atención en este filtro.
|
{t('empty.description')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { ATTENTION_FILTERS, type AttentionFilter } from './attention'
|
import { ATTENTION_FILTERS, type AttentionFilter } from './attention'
|
||||||
|
|
||||||
@@ -8,16 +9,17 @@ type FilterChipsProps = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function FilterChips({ value, counts, onChange }: FilterChipsProps) {
|
export function FilterChips({ value, counts, onChange }: FilterChipsProps) {
|
||||||
|
const { t } = useTranslation('attention')
|
||||||
return (
|
return (
|
||||||
<div role="group" aria-label="Filtrar alertas" className="flex gap-2 overflow-x-auto py-3">
|
<div role="group" aria-label={t('filters.label')} className="flex gap-2 overflow-x-auto py-3">
|
||||||
{ATTENTION_FILTERS.map((filter) => {
|
{ATTENTION_FILTERS.map((filter) => {
|
||||||
const active = filter.id === value
|
const active = filter === value
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={filter.id}
|
key={filter}
|
||||||
type="button"
|
type="button"
|
||||||
aria-pressed={active}
|
aria-pressed={active}
|
||||||
onClick={() => onChange(filter.id)}
|
onClick={() => onChange(filter)}
|
||||||
className={cn(
|
className={cn(
|
||||||
'inline-flex min-h-11 shrink-0 items-center gap-1.5 rounded-full border px-4 text-sm font-semibold transition-colors focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none motion-reduce:transition-none',
|
'inline-flex min-h-11 shrink-0 items-center gap-1.5 rounded-full border px-4 text-sm font-semibold transition-colors focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none motion-reduce:transition-none',
|
||||||
active
|
active
|
||||||
@@ -25,9 +27,9 @@ export function FilterChips({ value, counts, onChange }: FilterChipsProps) {
|
|||||||
: 'border-border bg-surface text-primary hover:bg-primary-soft',
|
: 'border-border bg-surface text-primary hover:bg-primary-soft',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{filter.label}
|
{t(`filters.${filter}`)}
|
||||||
<span className={cn('tabular-nums', active ? 'text-background/70' : 'text-secondary')}>
|
<span className={cn('tabular-nums', active ? 'text-background/70' : 'text-secondary')}>
|
||||||
{counts[filter.id]}
|
{counts[filter]}
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import type {
|
|||||||
StudentAlertType,
|
StudentAlertType,
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
import { compareAlerts, compareByWorstAlert, worstAlert } from '@gruperly/shared'
|
import { compareAlerts, compareByWorstAlert, worstAlert } from '@gruperly/shared'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
import { formatPrice } from '../../lib/format'
|
import { formatPrice } from '../../lib/format'
|
||||||
|
|
||||||
/* Derivations for "Requiere atención" (the Grupos preview and the "Ver todos"
|
/* Derivations for "Requiere atención" (the Grupos preview and the "Ver todos"
|
||||||
@@ -16,11 +17,8 @@ import { formatPrice } from '../../lib/format'
|
|||||||
|
|
||||||
export type AttentionFilter = 'todos' | StudentAlertType
|
export type AttentionFilter = 'todos' | StudentAlertType
|
||||||
|
|
||||||
export const ATTENTION_FILTERS: { id: AttentionFilter; label: string }[] = [
|
/** Labels: `attention:filters.<id>`. */
|
||||||
{ id: 'todos', label: 'Todos' },
|
export const ATTENTION_FILTERS: AttentionFilter[] = ['todos', 'asistencia', 'pago']
|
||||||
{ id: 'asistencia', label: 'Asistencia' },
|
|
||||||
{ id: 'pago', label: 'Pagos' },
|
|
||||||
]
|
|
||||||
|
|
||||||
/** A student with at least one alert, with their group. */
|
/** A student with at least one alert, with their group. */
|
||||||
export type FlaggedStudent = AttentionMember & {
|
export type FlaggedStudent = AttentionMember & {
|
||||||
@@ -77,12 +75,12 @@ export function itemsBySeverity(items: AttentionItem[]): Record<StudentAlertSeve
|
|||||||
/** "7 alumnos · 3 urgentes", or "Nada pendiente". Students, not cards. */
|
/** "7 alumnos · 3 urgentes", or "Nada pendiente". Students, not cards. */
|
||||||
export function attentionSubtitle(items: AttentionItem[]): string {
|
export function attentionSubtitle(items: AttentionItem[]): string {
|
||||||
const students = new Set(items.map((item) => item.student.attendeeId))
|
const students = new Set(items.map((item) => item.student.attendeeId))
|
||||||
if (students.size === 0) return 'Nada pendiente'
|
if (students.size === 0) return i18n.t('attention:subtitle.none')
|
||||||
const urgent = new Set(
|
const urgent = new Set(
|
||||||
items.filter((item) => item.alert.gravedad === 'urgente').map((item) => item.student.attendeeId),
|
items.filter((item) => item.alert.gravedad === 'urgente').map((item) => item.student.attendeeId),
|
||||||
)
|
)
|
||||||
const parts = [`${students.size} ${students.size === 1 ? 'alumno' : 'alumnos'}`]
|
const parts = [i18n.t('attention:subtitle.students', { count: students.size })]
|
||||||
if (urgent.size > 0) parts.push(`${urgent.size} ${urgent.size === 1 ? 'urgente' : 'urgentes'}`)
|
if (urgent.size > 0) parts.push(i18n.t('attention:subtitle.urgent', { count: urgent.size }))
|
||||||
return parts.join(' · ')
|
return parts.join(' · ')
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,17 +117,74 @@ export function reminderMessage(student: FlaggedStudent): string {
|
|||||||
const amount = formatPrice(total, payments[0]?.currency)
|
const amount = formatPrice(total, payments[0]?.currency)
|
||||||
const owed =
|
const owed =
|
||||||
payments.length === 1
|
payments.length === 1
|
||||||
? `la cuota de ${student.groupName} (${amount}) que venció el ${shortDate(payments[0].dueDate)}`
|
? i18n.t('attention:reminder.one', { group: student.groupName, amount, date: shortDate(payments[0].dueDate) })
|
||||||
: `${payments.length} cuotas de ${student.groupName} (${amount} en total)`
|
: i18n.t('attention:reminder.many', { count: payments.length, group: student.groupName, amount })
|
||||||
const link = payments.find((payment) => payment.checkoutUrl)?.checkoutUrl
|
const link = payments.find((payment) => payment.checkoutUrl)?.checkoutUrl
|
||||||
return (
|
return (
|
||||||
`¡Hola ${firstName}! 👋 Te escribo para recordarte que quedó pendiente ${owed}.` +
|
i18n.t('attention:reminder.message', { name: firstName, owed }) +
|
||||||
(link ? ` Podés pagar acá: ${link}` : '') +
|
(link ? i18n.t('attention:reminder.pay', { link }) : '') +
|
||||||
' Cualquier cosa, avisame.'
|
i18n.t('attention:reminder.closing')
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Due dates are calendar days sent at 12:00 UTC: read in UTC so the day doesn't
|
||||||
|
shift with the time zone. */
|
||||||
function shortDate(iso: string): string {
|
function shortDate(iso: string): string {
|
||||||
const date = new Date(iso)
|
return new Intl.DateTimeFormat(i18n.language, { day: 'numeric', month: 'numeric', timeZone: 'UTC' }).format(
|
||||||
return `${date.getUTCDate()}/${date.getUTCMonth() + 1}`
|
new Date(iso),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function monthName(iso: string): string {
|
||||||
|
return new Intl.DateTimeFormat(i18n.language, { month: 'long', timeZone: 'UTC' }).format(new Date(iso))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The alert's short tag ("4 faltas") in the UI language. Alerts without
|
||||||
|
* `razon` (older API) keep the Spanish `etiqueta`. */
|
||||||
|
export function alertLabel(alert: StudentAlert): string {
|
||||||
|
const values = alert.valores ?? {}
|
||||||
|
switch (alert.razon) {
|
||||||
|
case 'racha':
|
||||||
|
return i18n.t('attention:alert.racha', { count: values.faltas })
|
||||||
|
case 'ventana':
|
||||||
|
case 'ultimas':
|
||||||
|
return i18n.t('attention:alert.ventana', { count: values.faltas })
|
||||||
|
case 'cuotas':
|
||||||
|
return i18n.t('attention:alert.cuotas', { count: values.cuotas })
|
||||||
|
case 'cuota':
|
||||||
|
return i18n.t('attention:alert.cuota')
|
||||||
|
default:
|
||||||
|
return alert.etiqueta
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The alert's sentence ("Faltó a 4 de las últimas 6 clases.") in the UI language. */
|
||||||
|
export function alertDetail(alert: StudentAlert): string {
|
||||||
|
const values = alert.valores ?? {}
|
||||||
|
const dueDates = values.vencimientos ?? []
|
||||||
|
switch (alert.razon) {
|
||||||
|
case 'racha':
|
||||||
|
return i18n.t('attention:alert.rachaDetail', { count: values.faltas })
|
||||||
|
case 'ventana':
|
||||||
|
return i18n.t('attention:alert.ventanaDetail', { count: values.faltas, classes: values.clases })
|
||||||
|
case 'ultimas':
|
||||||
|
return i18n.t('attention:alert.ultimasDetail', { count: values.faltas })
|
||||||
|
case 'cuotas': {
|
||||||
|
// Two fees in the same month (a re-created link) would read "las cuotas
|
||||||
|
// de octubre": fall back to the count.
|
||||||
|
const months = [...new Set(dueDates.map(monthName))]
|
||||||
|
if (months.length === dueDates.length && months.length > 0) {
|
||||||
|
const list = new Intl.ListFormat(i18n.language, { type: 'conjunction' }).format(months)
|
||||||
|
return i18n.t('attention:alert.cuotasMonthsDetail', { months: list })
|
||||||
|
}
|
||||||
|
return i18n.t('attention:alert.cuotasDetail', { count: values.cuotas })
|
||||||
|
}
|
||||||
|
case 'cuota': {
|
||||||
|
const [dueDate] = dueDates
|
||||||
|
if (!dueDate) return alert.detalle
|
||||||
|
return i18n.t('attention:alert.cuotaDetail', { month: monthName(dueDate), date: shortDate(dueDate) })
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return alert.detalle
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,13 @@ import { zodResolver } from '@hookform/resolvers/zod'
|
|||||||
import { Link, useSearch } from '@tanstack/react-router'
|
import { Link, useSearch } from '@tanstack/react-router'
|
||||||
import { Loader2, MailCheck } from 'lucide-react'
|
import { Loader2, MailCheck } from 'lucide-react'
|
||||||
import { authClient } from '../../lib/auth-client'
|
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'
|
import { AuthShell } from './AuthShell'
|
||||||
|
|
||||||
const schema = z.object({
|
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>
|
type FormValues = z.infer<typeof schema>
|
||||||
@@ -17,6 +19,7 @@ type FormValues = z.infer<typeof schema>
|
|||||||
export function ForgotPasswordPage() {
|
export function ForgotPasswordPage() {
|
||||||
const { email: initialEmail } = useSearch({ strict: false }) as { email?: string }
|
const { email: initialEmail } = useSearch({ strict: false }) as { email?: string }
|
||||||
const [sentTo, setSentTo] = useState<string | null>(null)
|
const [sentTo, setSentTo] = useState<string | null>(null)
|
||||||
|
const { t } = useTranslation('auth')
|
||||||
const {
|
const {
|
||||||
register,
|
register,
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
@@ -34,7 +37,7 @@ export function ForgotPasswordPage() {
|
|||||||
redirectTo: `${window.location.origin}/reset-password`,
|
redirectTo: `${window.location.origin}/reset-password`,
|
||||||
})
|
})
|
||||||
if (error) {
|
if (error) {
|
||||||
setError('root', { message: error.message ?? 'No se pudo enviar el email' })
|
setError('root', { message: errorMessage(error, t('forgot.error')) })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setSentTo(email)
|
setSentTo(email)
|
||||||
@@ -42,15 +45,19 @@ export function ForgotPasswordPage() {
|
|||||||
|
|
||||||
if (sentTo) {
|
if (sentTo) {
|
||||||
return (
|
return (
|
||||||
<AuthShell title="Revisá tu email">
|
<AuthShell title={t('forgot.sentTitle')}>
|
||||||
<div className="flex flex-col items-center gap-4 py-2 text-center">
|
<div className="flex flex-col items-center gap-4 py-2 text-center">
|
||||||
<MailCheck className="size-10 text-success" />
|
<MailCheck className="size-10 text-success" />
|
||||||
<p className="text-sm text-foreground/60">
|
<p className="text-sm text-foreground/60">
|
||||||
Si hay una cuenta con <span className="font-medium text-primary">{sentTo}</span>, te
|
<Trans
|
||||||
enviamos un enlace para elegir una nueva contraseña. Vence en 1 hora.
|
t={t}
|
||||||
|
i18nKey="forgot.sent"
|
||||||
|
values={{ email: sentTo }}
|
||||||
|
components={{ strong: <span className="font-medium text-primary" /> }}
|
||||||
|
/>
|
||||||
</p>
|
</p>
|
||||||
<Link to="/login" className="text-sm font-medium text-accent hover:underline">
|
<Link to="/login" className="text-sm font-medium text-accent hover:underline">
|
||||||
Volver a iniciar sesión
|
{t('backToLogin')}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</AuthShell>
|
</AuthShell>
|
||||||
@@ -59,34 +66,34 @@ export function ForgotPasswordPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthShell
|
<AuthShell
|
||||||
title="Recuperar contraseña"
|
title={t('forgot.title')}
|
||||||
subtitle="Te enviamos un enlace para elegir una nueva"
|
subtitle={t('forgot.subtitle')}
|
||||||
>
|
>
|
||||||
<form onSubmit={onSubmit} className="space-y-4">
|
<form onSubmit={onSubmit} className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="email">Email</Label>
|
<Label htmlFor="email">{t('email')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="email"
|
id="email"
|
||||||
type="email"
|
type="email"
|
||||||
autoComplete="email"
|
autoComplete="email"
|
||||||
autoFocus
|
autoFocus
|
||||||
placeholder="vos@ejemplo.com"
|
placeholder={t('emailPlaceholder')}
|
||||||
invalid={!!errors.email}
|
invalid={!!errors.email}
|
||||||
{...register('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>
|
||||||
|
|
||||||
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
|
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
|
||||||
|
|
||||||
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
|
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
|
||||||
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
{isSubmitting ? 'Enviando…' : 'Enviar enlace'}
|
{isSubmitting ? t('forgot.submitting') : t('forgot.submit')}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<p className="text-center text-sm text-foreground/60">
|
<p className="text-center text-sm text-foreground/60">
|
||||||
<Link to="/login" className="font-medium text-accent hover:underline">
|
<Link to="/login" className="font-medium text-accent hover:underline">
|
||||||
Volver a iniciar sesión
|
{t('backToLogin')}
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -4,18 +4,21 @@ import { zodResolver } from '@hookform/resolvers/zod'
|
|||||||
import { Link, useNavigate, useSearch } from '@tanstack/react-router'
|
import { Link, useNavigate, useSearch } from '@tanstack/react-router'
|
||||||
import { Fingerprint, Loader2 } from 'lucide-react'
|
import { Fingerprint, Loader2 } from 'lucide-react'
|
||||||
import { authClient } from '../../lib/auth-client'
|
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'
|
import { AuthShell } from './AuthShell'
|
||||||
|
|
||||||
const schema = z.object({
|
const schema = z.object({
|
||||||
email: z.string().email('Ingresá un email válido'),
|
email: z.string().email('email.invalid'),
|
||||||
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
|
password: z.string().min(8, 'password.min'),
|
||||||
})
|
})
|
||||||
|
|
||||||
type FormValues = z.infer<typeof schema>
|
type FormValues = z.infer<typeof schema>
|
||||||
|
|
||||||
export function LoginPage() {
|
export function LoginPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { t } = useTranslation('auth')
|
||||||
const { reset } = useSearch({ strict: false }) as { reset?: 'ok' }
|
const { reset } = useSearch({ strict: false }) as { reset?: 'ok' }
|
||||||
const {
|
const {
|
||||||
register,
|
register,
|
||||||
@@ -28,7 +31,7 @@ export function LoginPage() {
|
|||||||
const onSubmit = handleSubmit(async ({ email, password }) => {
|
const onSubmit = handleSubmit(async ({ email, password }) => {
|
||||||
const { error } = await authClient.signIn.email({ email, password })
|
const { error } = await authClient.signIn.email({ email, password })
|
||||||
if (error) {
|
if (error) {
|
||||||
setError('root', { message: error.message ?? 'No se pudo iniciar sesión' })
|
setError('root', { message: errorMessage(error, t('login.error')) })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
navigate({ to: '/' })
|
navigate({ to: '/' })
|
||||||
@@ -41,37 +44,37 @@ export function LoginPage() {
|
|||||||
const handlePasskey = async () => {
|
const handlePasskey = async () => {
|
||||||
const { error, data } = await authClient.signIn.passkey()
|
const { error, data } = await authClient.signIn.passkey()
|
||||||
if (error) {
|
if (error) {
|
||||||
setError('root', { message: error.message ?? 'No se pudo autenticar con passkey' })
|
setError('root', { message: errorMessage(error, t('login.passkeyError')) })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (data) navigate({ to: '/' })
|
if (data) navigate({ to: '/' })
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
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">
|
<div className="space-y-4">
|
||||||
{reset === 'ok' ? (
|
{reset === 'ok' ? (
|
||||||
<p className="rounded-xl bg-success-soft px-4 py-3 text-sm text-success">
|
<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>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<form onSubmit={onSubmit} className="space-y-4">
|
<form onSubmit={onSubmit} className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="email">Email</Label>
|
<Label htmlFor="email">{t('email')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="email"
|
id="email"
|
||||||
type="email"
|
type="email"
|
||||||
autoComplete="email"
|
autoComplete="email"
|
||||||
placeholder="vos@ejemplo.com"
|
placeholder={t('emailPlaceholder')}
|
||||||
invalid={!!errors.email}
|
invalid={!!errors.email}
|
||||||
{...register('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>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="password">Contraseña</Label>
|
<Label htmlFor="password">{t('password')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="password"
|
id="password"
|
||||||
type="password"
|
type="password"
|
||||||
@@ -80,16 +83,14 @@ export function LoginPage() {
|
|||||||
invalid={!!errors.password}
|
invalid={!!errors.password}
|
||||||
{...register('password')}
|
{...register('password')}
|
||||||
/>
|
/>
|
||||||
{errors.password ? (
|
<FieldError message={errors.password?.message} />
|
||||||
<p className="mt-1 text-sm text-danger">{errors.password.message}</p>
|
|
||||||
) : null}
|
|
||||||
<div className="mt-1 text-right">
|
<div className="mt-1 text-right">
|
||||||
<Link
|
<Link
|
||||||
to="/forgot-password"
|
to="/forgot-password"
|
||||||
search={{ email: watch('email') || undefined }}
|
search={{ email: watch('email') || undefined }}
|
||||||
className="text-sm text-accent hover:underline"
|
className="text-sm text-accent hover:underline"
|
||||||
>
|
>
|
||||||
¿Olvidaste tu contraseña?
|
{t('login.forgot')}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -98,30 +99,30 @@ export function LoginPage() {
|
|||||||
|
|
||||||
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
|
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
|
||||||
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
{isSubmitting ? 'Ingresando…' : 'Ingresar'}
|
{isSubmitting ? t('login.submitting') : t('login.submit')}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="h-px flex-1 bg-border" />
|
<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 className="h-px flex-1 bg-border" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
<Button variant="outline" className="w-full" onClick={handleGoogle}>
|
<Button variant="outline" className="w-full" onClick={handleGoogle}>
|
||||||
Continuar con Google
|
{t('continueWithGoogle')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="outline" className="w-full" onClick={handlePasskey}>
|
<Button variant="outline" className="w-full" onClick={handlePasskey}>
|
||||||
<Fingerprint className="size-4" />
|
<Fingerprint className="size-4" />
|
||||||
Entrar con passkey
|
{t('login.passkey')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p className="text-center text-sm text-foreground/60">
|
<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">
|
<Link to="/signup" className="font-medium text-accent hover:underline">
|
||||||
Registrate
|
{t('login.signUp')}
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,16 +5,18 @@ import { zodResolver } from '@hookform/resolvers/zod'
|
|||||||
import { Link, useNavigate, useSearch } from '@tanstack/react-router'
|
import { Link, useNavigate, useSearch } from '@tanstack/react-router'
|
||||||
import { Loader2, MailWarning } from 'lucide-react'
|
import { Loader2, MailWarning } from 'lucide-react'
|
||||||
import { authClient } from '../../lib/auth-client'
|
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'
|
import { AuthShell } from './AuthShell'
|
||||||
|
|
||||||
const schema = z
|
const schema = z
|
||||||
.object({
|
.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(),
|
confirmPassword: z.string(),
|
||||||
})
|
})
|
||||||
.refine((v) => v.newPassword === v.confirmPassword, {
|
.refine((v) => v.newPassword === v.confirmPassword, {
|
||||||
message: 'Las contraseñas no coinciden',
|
message: 'password.mismatch',
|
||||||
path: ['confirmPassword'],
|
path: ['confirmPassword'],
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -23,6 +25,7 @@ type FormValues = z.infer<typeof schema>
|
|||||||
export function ResetPasswordPage() {
|
export function ResetPasswordPage() {
|
||||||
const { token, error } = useSearch({ strict: false }) as { token?: string; error?: string }
|
const { token, error } = useSearch({ strict: false }) as { token?: string; error?: string }
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { t } = useTranslation('auth')
|
||||||
const [invalidLink, setInvalidLink] = useState(!token || !!error)
|
const [invalidLink, setInvalidLink] = useState(!token || !!error)
|
||||||
const {
|
const {
|
||||||
register,
|
register,
|
||||||
@@ -39,7 +42,7 @@ export function ResetPasswordPage() {
|
|||||||
setInvalidLink(true)
|
setInvalidLink(true)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setError('root', { message: error.message ?? 'No se pudo cambiar la contraseña' })
|
setError('root', { message: errorMessage(error, t('reset.error')) })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
navigate({ to: '/login', search: { reset: 'ok' } })
|
navigate({ to: '/login', search: { reset: 'ok' } })
|
||||||
@@ -47,14 +50,14 @@ export function ResetPasswordPage() {
|
|||||||
|
|
||||||
if (invalidLink) {
|
if (invalidLink) {
|
||||||
return (
|
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">
|
<div className="flex flex-col items-center gap-4 py-2 text-center">
|
||||||
<MailWarning className="size-10 text-warning" />
|
<MailWarning className="size-10 text-warning" />
|
||||||
<p className="text-sm text-foreground/60">
|
<p className="text-sm text-foreground/60">
|
||||||
El enlace para restablecer la contraseña no es válido o venció.
|
{t('reset.invalid')}
|
||||||
</p>
|
</p>
|
||||||
<Link to="/forgot-password" className="text-sm font-medium text-accent hover:underline">
|
<Link to="/forgot-password" className="text-sm font-medium text-accent hover:underline">
|
||||||
Pedir un enlace nuevo
|
{t('reset.requestNew')}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</AuthShell>
|
</AuthShell>
|
||||||
@@ -62,10 +65,10 @@ export function ResetPasswordPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
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">
|
<form onSubmit={onSubmit} className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="newPassword">Nueva contraseña</Label>
|
<Label htmlFor="newPassword">{t('reset.newPassword')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="newPassword"
|
id="newPassword"
|
||||||
type="password"
|
type="password"
|
||||||
@@ -75,13 +78,11 @@ export function ResetPasswordPage() {
|
|||||||
invalid={!!errors.newPassword}
|
invalid={!!errors.newPassword}
|
||||||
{...register('newPassword')}
|
{...register('newPassword')}
|
||||||
/>
|
/>
|
||||||
{errors.newPassword ? (
|
<FieldError message={errors.newPassword?.message} />
|
||||||
<p className="mt-1 text-sm text-danger">{errors.newPassword.message}</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="confirmPassword">Repetir contraseña</Label>
|
<Label htmlFor="confirmPassword">{t('reset.confirmPassword')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="confirmPassword"
|
id="confirmPassword"
|
||||||
type="password"
|
type="password"
|
||||||
@@ -90,16 +91,14 @@ export function ResetPasswordPage() {
|
|||||||
invalid={!!errors.confirmPassword}
|
invalid={!!errors.confirmPassword}
|
||||||
{...register('confirmPassword')}
|
{...register('confirmPassword')}
|
||||||
/>
|
/>
|
||||||
{errors.confirmPassword ? (
|
<FieldError message={errors.confirmPassword?.message} />
|
||||||
<p className="mt-1 text-sm text-danger">{errors.confirmPassword.message}</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
|
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
|
||||||
|
|
||||||
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
|
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
|
||||||
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
{isSubmitting ? 'Guardando…' : 'Guardar contraseña'}
|
{isSubmitting ? t('reset.submitting') : t('reset.submit')}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</AuthShell>
|
</AuthShell>
|
||||||
|
|||||||
@@ -4,18 +4,20 @@ import { zodResolver } from '@hookform/resolvers/zod'
|
|||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
import { Link, useNavigate } from '@tanstack/react-router'
|
||||||
import { Loader2 } from 'lucide-react'
|
import { Loader2 } from 'lucide-react'
|
||||||
import { authClient } from '../../lib/auth-client'
|
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'
|
import { AuthShell } from './AuthShell'
|
||||||
|
|
||||||
const schema = z
|
const schema = z
|
||||||
.object({
|
.object({
|
||||||
name: z.string().min(2, 'Ingresá tu nombre'),
|
name: z.string().min(2, 'name.enter'),
|
||||||
email: z.string().email('Ingresá un email válido'),
|
email: z.string().email('email.invalid'),
|
||||||
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
|
password: z.string().min(8, 'password.min'),
|
||||||
confirmPassword: z.string(),
|
confirmPassword: z.string(),
|
||||||
})
|
})
|
||||||
.refine((v) => v.password === v.confirmPassword, {
|
.refine((v) => v.password === v.confirmPassword, {
|
||||||
message: 'Las contraseñas no coinciden',
|
message: 'password.mismatch',
|
||||||
path: ['confirmPassword'],
|
path: ['confirmPassword'],
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -23,6 +25,7 @@ type FormValues = z.infer<typeof schema>
|
|||||||
|
|
||||||
export function SignupPage() {
|
export function SignupPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { t } = useTranslation('auth')
|
||||||
const {
|
const {
|
||||||
register,
|
register,
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
@@ -40,7 +43,7 @@ export function SignupPage() {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
if (error) {
|
if (error) {
|
||||||
setError('root', { message: error.message ?? 'No se pudo registrar' })
|
setError('root', { message: errorMessage(error, t('signup.error')) })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (data?.token) {
|
if (data?.token) {
|
||||||
@@ -55,51 +58,49 @@ export function SignupPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
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">
|
<div className="space-y-4">
|
||||||
<form onSubmit={onSubmit} className="space-y-4">
|
<form onSubmit={onSubmit} className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="name">Nombre</Label>
|
<Label htmlFor="name">{t('signup.name')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="name"
|
id="name"
|
||||||
autoComplete="name"
|
autoComplete="name"
|
||||||
placeholder="Nombre completo"
|
placeholder={t('signup.namePlaceholder')}
|
||||||
invalid={!!errors.name}
|
invalid={!!errors.name}
|
||||||
{...register('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>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="email">Email</Label>
|
<Label htmlFor="email">{t('email')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="email"
|
id="email"
|
||||||
type="email"
|
type="email"
|
||||||
autoComplete="email"
|
autoComplete="email"
|
||||||
placeholder="vos@ejemplo.com"
|
placeholder={t('emailPlaceholder')}
|
||||||
invalid={!!errors.email}
|
invalid={!!errors.email}
|
||||||
{...register('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>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="password">Contraseña</Label>
|
<Label htmlFor="password">{t('password')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="password"
|
id="password"
|
||||||
type="password"
|
type="password"
|
||||||
autoComplete="new-password"
|
autoComplete="new-password"
|
||||||
placeholder="Mínimo 8 caracteres"
|
placeholder={t('signup.passwordPlaceholder')}
|
||||||
invalid={!!errors.password}
|
invalid={!!errors.password}
|
||||||
{...register('password')}
|
{...register('password')}
|
||||||
/>
|
/>
|
||||||
{errors.password ? (
|
<FieldError message={errors.password?.message} />
|
||||||
<p className="mt-1 text-sm text-danger">{errors.password.message}</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="confirmPassword">Repetí la contraseña</Label>
|
<Label htmlFor="confirmPassword">{t('signup.confirmPassword')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="confirmPassword"
|
id="confirmPassword"
|
||||||
type="password"
|
type="password"
|
||||||
@@ -108,33 +109,31 @@ export function SignupPage() {
|
|||||||
invalid={!!errors.confirmPassword}
|
invalid={!!errors.confirmPassword}
|
||||||
{...register('confirmPassword')}
|
{...register('confirmPassword')}
|
||||||
/>
|
/>
|
||||||
{errors.confirmPassword ? (
|
<FieldError message={errors.confirmPassword?.message} />
|
||||||
<p className="mt-1 text-sm text-danger">{errors.confirmPassword.message}</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
|
{errors.root ? <p className="text-sm text-danger">{errors.root.message}</p> : null}
|
||||||
|
|
||||||
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
|
<Button type="submit" variant="primary" className="w-full" disabled={isSubmitting}>
|
||||||
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
{isSubmitting ? 'Creando…' : 'Crear cuenta'}
|
{isSubmitting ? t('signup.submitting') : t('signup.submit')}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="h-px flex-1 bg-border" />
|
<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 className="h-px flex-1 bg-border" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button variant="outline" className="w-full" onClick={handleGoogle}>
|
<Button variant="outline" className="w-full" onClick={handleGoogle}>
|
||||||
Continuar con Google
|
{t('continueWithGoogle')}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<p className="text-center text-sm text-foreground/60">
|
<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">
|
<Link to="/login" className="font-medium text-accent hover:underline">
|
||||||
Iniciá sesión
|
{t('signup.signIn')}
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { Link, useNavigate, useSearch } from '@tanstack/react-router'
|
import { Link, useNavigate, useSearch } from '@tanstack/react-router'
|
||||||
import { MailCheck, MailWarning, Loader2 } from 'lucide-react'
|
import { MailCheck, MailWarning, Loader2 } from 'lucide-react'
|
||||||
|
import { Trans, useTranslation } from 'react-i18next'
|
||||||
import { authClient } from '../../lib/auth-client'
|
import { authClient } from '../../lib/auth-client'
|
||||||
import { AuthShell } from './AuthShell'
|
import { AuthShell } from './AuthShell'
|
||||||
|
|
||||||
@@ -14,6 +15,7 @@ type Status = 'idle' | 'verifying' | 'success' | 'error'
|
|||||||
export function VerifyEmailPage() {
|
export function VerifyEmailPage() {
|
||||||
const { token, email } = useSearch({ strict: false }) as SearchParams
|
const { token, email } = useSearch({ strict: false }) as SearchParams
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { t } = useTranslation('auth')
|
||||||
const [status, setStatus] = useState<Status>(token ? 'verifying' : 'idle')
|
const [status, setStatus] = useState<Status>(token ? 'verifying' : 'idle')
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -40,10 +42,10 @@ export function VerifyEmailPage() {
|
|||||||
|
|
||||||
const title =
|
const title =
|
||||||
status === 'success'
|
status === 'success'
|
||||||
? 'Email verificado'
|
? t('verify.successTitle')
|
||||||
: status === 'error'
|
: status === 'error'
|
||||||
? 'Vínculo inválido'
|
? t('verify.errorTitle')
|
||||||
: 'Verificá tu email'
|
: t('verify.title')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthShell title={title}>
|
<AuthShell title={title}>
|
||||||
@@ -58,16 +60,20 @@ export function VerifyEmailPage() {
|
|||||||
|
|
||||||
{status === 'success' ? (
|
{status === 'success' ? (
|
||||||
<p className="text-sm text-foreground/60">
|
<p className="text-sm text-foreground/60">
|
||||||
Tu cuenta quedó verificada. Te estamos llevando a Gruperly…
|
{t('verify.success')}
|
||||||
</p>
|
</p>
|
||||||
) : status === 'error' ? (
|
) : status === 'error' ? (
|
||||||
<p className="text-sm text-foreground/60">
|
<p className="text-sm text-foreground/60">
|
||||||
El vínculo de verificación no es válido o expiró.
|
{t('verify.error')}
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<p className="text-sm text-foreground/60">
|
<p className="text-sm text-foreground/60">
|
||||||
Te enviamos un correo a <span className="font-medium text-primary">{email}</span> para
|
<Trans
|
||||||
confirmar tu cuenta.
|
t={t}
|
||||||
|
i18nKey="verify.sent"
|
||||||
|
values={{ email }}
|
||||||
|
components={{ strong: <span className="font-medium text-primary" /> }}
|
||||||
|
/>
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -76,13 +82,13 @@ export function VerifyEmailPage() {
|
|||||||
to="/"
|
to="/"
|
||||||
className="w-full rounded-xl bg-accent py-2 text-center text-sm font-medium text-on-accent hover:bg-accent-strong"
|
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>
|
</Link>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{status === 'error' ? (
|
{status === 'error' ? (
|
||||||
<Link to="/login" className="text-sm font-medium text-accent hover:underline">
|
<Link to="/login" className="text-sm font-medium text-accent hover:underline">
|
||||||
Intentar iniciar sesión
|
{t('verify.tryLogin')}
|
||||||
</Link>
|
</Link>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,8 +4,10 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|||||||
import { useNavigate, useSearch } from '@tanstack/react-router'
|
import { useNavigate, useSearch } from '@tanstack/react-router'
|
||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
import { createContext, useContext, useEffect, useRef, useState } from 'react'
|
import { createContext, useContext, useEffect, useRef, useState } from 'react'
|
||||||
|
import { errorMessage } from '../../i18n'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
import { useToast } from '../../components/ui'
|
import { useToast } from '../../components/ui'
|
||||||
import { ApiError, cancelSubscription, getBillingCharges } from '../../lib/api'
|
import { cancelSubscription, getBillingCharges } from '../../lib/api'
|
||||||
import { billingStatusQueryKey, useBillingStatus } from './useBillingStatus'
|
import { billingStatusQueryKey, useBillingStatus } from './useBillingStatus'
|
||||||
import { useSubscriptionReturnPolling } from './useSubscriptionReturnPolling'
|
import { useSubscriptionReturnPolling } from './useSubscriptionReturnPolling'
|
||||||
|
|
||||||
@@ -54,7 +56,7 @@ export function BillingProvider({ children }: { children: ReactNode }) {
|
|||||||
if (!polling.isPolling || announced.current) return
|
if (!polling.isPolling || announced.current) return
|
||||||
if (statusQuery.data?.status === 'AUTHORIZED') {
|
if (statusQuery.data?.status === 'AUTHORIZED') {
|
||||||
announced.current = true
|
announced.current = true
|
||||||
toast.success('¡Listo! Ya tenés Gruperly Pro.')
|
toast.success(i18n.t('billing:cancel.welcome'))
|
||||||
void queryClient.invalidateQueries({ queryKey: ['billing', 'charges'] })
|
void queryClient.invalidateQueries({ queryKey: ['billing', 'charges'] })
|
||||||
}
|
}
|
||||||
// `toast` cambia en cada aviso: el efecto depende solo del estado.
|
// `toast` cambia en cada aviso: el efecto depende solo del estado.
|
||||||
@@ -63,11 +65,11 @@ export function BillingProvider({ children }: { children: ReactNode }) {
|
|||||||
const cancelMutation = useMutation({
|
const cancelMutation = useMutation({
|
||||||
mutationFn: cancelSubscription,
|
mutationFn: cancelSubscription,
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
toast.success('Cancelaste tu suscripción. Seguís con Pro hasta el fin del período pago.')
|
toast.success(i18n.t('billing:cancel.done'))
|
||||||
void queryClient.invalidateQueries({ queryKey: billingStatusQueryKey })
|
void queryClient.invalidateQueries({ queryKey: billingStatusQueryKey })
|
||||||
},
|
},
|
||||||
onError: (error: Error) => {
|
onError: (error: Error) => {
|
||||||
toast.error(error instanceof ApiError ? error.message : 'No pudimos cancelar la suscripción.')
|
toast.error(errorMessage(error, i18n.t('billing:cancel.error')))
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -10,15 +10,19 @@ import { ChargesList } from './ChargesList'
|
|||||||
import { PlanOptionCard } from './PlanOptionCard'
|
import { PlanOptionCard } from './PlanOptionCard'
|
||||||
import { PlanSummaryCard } from './PlanSummaryCard'
|
import { PlanSummaryCard } from './PlanSummaryCard'
|
||||||
import { SubscribeModal } from './SubscribeModal'
|
import { SubscribeModal } from './SubscribeModal'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function BillingView() {
|
export function BillingView() {
|
||||||
const { statusQuery, openSubscribe, cancel, isCancelling } = useBilling()
|
const { statusQuery, openSubscribe, cancel, isCancelling } = useBilling()
|
||||||
const [isConfirmingCancel, setIsConfirmingCancel] = useState(false)
|
const [isConfirmingCancel, setIsConfirmingCancel] = useState(false)
|
||||||
|
const { t } = useTranslation(['billing', 'common'])
|
||||||
const status = statusQuery.data
|
const status = statusQuery.data
|
||||||
|
|
||||||
const subscribed = status?.status === 'AUTHORIZED' || status?.status === 'PAUSED'
|
const subscribed = status?.status === 'AUTHORIZED' || status?.status === 'PAUSED'
|
||||||
const pending = status?.status === 'PENDING'
|
const pending = status?.status === 'PENDING'
|
||||||
const proPrice = status ? `${formatPrice(status.priceAmount, status.currency)} / mes` : undefined
|
const proPrice = status
|
||||||
|
? t('view.perMonth', { price: formatPrice(status.priceAmount, status.currency) })
|
||||||
|
: undefined
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="space-y-6">
|
<section className="space-y-6">
|
||||||
@@ -28,10 +32,10 @@ export function BillingView() {
|
|||||||
className="mb-2 hidden items-center gap-1 text-sm text-foreground/60 hover:text-primary lg:inline-flex"
|
className="mb-2 hidden items-center gap-1 text-sm text-foreground/60 hover:text-primary lg:inline-flex"
|
||||||
>
|
>
|
||||||
<ChevronLeft className="size-4" />
|
<ChevronLeft className="size-4" />
|
||||||
Ajustes
|
{t('view.back')}
|
||||||
</Link>
|
</Link>
|
||||||
<h1 className="text-2xl font-bold text-primary">Tu plan</h1>
|
<h1 className="text-2xl font-bold text-primary">{t('view.title')}</h1>
|
||||||
<p className="mt-1 text-sm text-foreground/60">Elegí cómo usar Gruperly.</p>
|
<p className="mt-1 text-sm text-foreground/60">{t('view.subtitle')}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<PlanSummaryCard />
|
<PlanSummaryCard />
|
||||||
@@ -48,15 +52,15 @@ export function BillingView() {
|
|||||||
>
|
>
|
||||||
{subscribed ? (
|
{subscribed ? (
|
||||||
<Button variant="outline" className="w-full" onClick={() => setIsConfirmingCancel(true)}>
|
<Button variant="outline" className="w-full" onClick={() => setIsConfirmingCancel(true)}>
|
||||||
Cancelar suscripción
|
{t('cancel.confirm')}
|
||||||
</Button>
|
</Button>
|
||||||
) : status.availableInCountry ? (
|
) : status.availableInCountry ? (
|
||||||
<Button variant="primary" className="w-full" onClick={openSubscribe}>
|
<Button variant="primary" className="w-full" onClick={openSubscribe}>
|
||||||
<Sparkles className="size-4" />
|
<Sparkles className="size-4" />
|
||||||
{pending ? 'Reintentar el pago' : 'Pasar a Pro'}
|
{pending ? t('view.retry') : t('view.upgrade')}
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
<p className="text-xs text-foreground/50">Todavía no está disponible en tu país.</p>
|
<p className="text-xs text-foreground/50">{t('view.unavailable')}</p>
|
||||||
)}
|
)}
|
||||||
</PlanOptionCard>
|
</PlanOptionCard>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Loader2 } from 'lucide-react'
|
import { Loader2 } from 'lucide-react'
|
||||||
import { Button, Modal } from '../../components/ui'
|
import { Button, Modal } from '../../components/ui'
|
||||||
import { formatBillingDate } from './copy'
|
import { formatBillingDate } from './copy'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
type CancelSubscriptionModalProps = {
|
type CancelSubscriptionModalProps = {
|
||||||
isOpen: boolean
|
isOpen: boolean
|
||||||
@@ -19,25 +20,26 @@ export function CancelSubscriptionModal({
|
|||||||
onConfirm,
|
onConfirm,
|
||||||
}: CancelSubscriptionModalProps) {
|
}: CancelSubscriptionModalProps) {
|
||||||
const until = formatBillingDate(paidThrough)
|
const until = formatBillingDate(paidThrough)
|
||||||
|
const { t } = useTranslation(['billing', 'common'])
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
isOpen={isOpen}
|
isOpen={isOpen}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
title="Cancelar Pro"
|
title={t('cancel.title')}
|
||||||
description={
|
description={
|
||||||
until
|
until
|
||||||
? `No te vamos a cobrar más. Seguís con Pro hasta el ${until}; después tu cuenta pasa a Free.`
|
? t('cancel.descriptionUntil', { date: until })
|
||||||
: 'No te vamos a cobrar más y tu cuenta pasa a Free.'
|
: t('cancel.description')
|
||||||
}
|
}
|
||||||
maxWidth="sm"
|
maxWidth="sm"
|
||||||
>
|
>
|
||||||
<div className="flex justify-end gap-3">
|
<div className="flex justify-end gap-3">
|
||||||
<Button variant="outline" onClick={onClose}>
|
<Button variant="outline" onClick={onClose}>
|
||||||
Volver
|
{t('cancel.back')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="primary" disabled={isPending} onClick={onConfirm}>
|
<Button variant="primary" disabled={isPending} onClick={onConfirm}>
|
||||||
{isPending ? <Loader2 className="size-4 animate-spin" /> : null}
|
{isPending ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
Cancelar suscripción
|
{t('cancel.confirm')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|||||||
@@ -2,19 +2,15 @@ import { Button } from '../../components/ui'
|
|||||||
import { formatPrice } from '../../lib/format'
|
import { formatPrice } from '../../lib/format'
|
||||||
import { useBilling } from './BillingProvider'
|
import { useBilling } from './BillingProvider'
|
||||||
import { formatBillingDate } from './copy'
|
import { formatBillingDate } from './copy'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
const CHARGE_STATUS_LABELS: Record<string, string> = {
|
/** Mercado Pago / Stripe statuses with copy in `billing:charges.<status>`. */
|
||||||
approved: 'Pagado',
|
const KNOWN_CHARGE_STATUSES = new Set(['approved', 'rejected', 'pending', 'in_process', 'cancelled', 'refunded'])
|
||||||
rejected: 'Rechazado',
|
|
||||||
pending: 'Pendiente',
|
|
||||||
in_process: 'En proceso',
|
|
||||||
cancelled: 'Cancelado',
|
|
||||||
refunded: 'Devuelto',
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Historial de cobros de la suscripción a Pro. */
|
/** Historial de cobros de la suscripción a Pro. */
|
||||||
export function ChargesList() {
|
export function ChargesList() {
|
||||||
const { chargesQuery, chargesPage, setChargesPage } = useBilling()
|
const { chargesQuery, chargesPage, setChargesPage } = useBilling()
|
||||||
|
const { t } = useTranslation(['billing', 'common'])
|
||||||
const charges = chargesQuery.data?.data ?? []
|
const charges = chargesQuery.data?.data ?? []
|
||||||
const totalPages = chargesQuery.data?.pagination.totalPages ?? 0
|
const totalPages = chargesQuery.data?.pagination.totalPages ?? 0
|
||||||
|
|
||||||
@@ -22,7 +18,7 @@ export function ChargesList() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="space-y-2">
|
<section className="space-y-2">
|
||||||
<h2 className="text-sm font-semibold text-primary">Historial de pagos</h2>
|
<h2 className="text-sm font-semibold text-primary">{t('charges.title')}</h2>
|
||||||
<ul className="divide-y divide-border rounded-xl border border-border bg-surface">
|
<ul className="divide-y divide-border rounded-xl border border-border bg-surface">
|
||||||
{charges.map((charge) => (
|
{charges.map((charge) => (
|
||||||
<li key={charge.id} className="flex items-center justify-between gap-3 px-4 py-3">
|
<li key={charge.id} className="flex items-center justify-between gap-3 px-4 py-3">
|
||||||
@@ -33,7 +29,7 @@ export function ChargesList() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-xs text-foreground/60">
|
<span className="text-xs text-foreground/60">
|
||||||
{CHARGE_STATUS_LABELS[charge.status] ?? charge.status}
|
{KNOWN_CHARGE_STATUSES.has(charge.status) ? t(`charges.${charge.status}` as 'charges.approved') : charge.status}
|
||||||
</span>
|
</span>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
@@ -46,7 +42,7 @@ export function ChargesList() {
|
|||||||
disabled={chargesPage <= 1}
|
disabled={chargesPage <= 1}
|
||||||
onClick={() => setChargesPage(chargesPage - 1)}
|
onClick={() => setChargesPage(chargesPage - 1)}
|
||||||
>
|
>
|
||||||
Anteriores
|
{t('charges.prev')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -54,7 +50,7 @@ export function ChargesList() {
|
|||||||
disabled={chargesPage >= totalPages}
|
disabled={chargesPage >= totalPages}
|
||||||
onClick={() => setChargesPage(chargesPage + 1)}
|
onClick={() => setChargesPage(chargesPage + 1)}
|
||||||
>
|
>
|
||||||
Siguientes
|
{t('charges.next')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useAuth } from '../../context/AuthProvider'
|
|||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { planNoticeMessage } from './copy'
|
import { planNoticeMessage } from './copy'
|
||||||
import { useBillingStatus } from './useBillingStatus'
|
import { useBillingStatus } from './useBillingStatus'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Aviso global del plan: cuenta en solo lectura o Pro en período de gracia.
|
* Aviso global del plan: cuenta en solo lectura o Pro en período de gracia.
|
||||||
@@ -12,6 +13,7 @@ import { useBillingStatus } from './useBillingStatus'
|
|||||||
*/
|
*/
|
||||||
export function PlanNotice() {
|
export function PlanNotice() {
|
||||||
const { user } = useAuth()
|
const { user } = useAuth()
|
||||||
|
const { t } = useTranslation(['billing', 'common'])
|
||||||
const statusQuery = useBillingStatus({ enabled: !!user })
|
const statusQuery = useBillingStatus({ enabled: !!user })
|
||||||
const pathname = useLocation({ select: (location) => location.pathname })
|
const pathname = useLocation({ select: (location) => location.pathname })
|
||||||
|
|
||||||
@@ -36,7 +38,7 @@ export function PlanNotice() {
|
|||||||
danger ? 'text-danger' : 'text-warning',
|
danger ? 'text-danger' : 'text-warning',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
Ver plan
|
{t('notice.seePlan')}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import type { ReactNode } from 'react'
|
|||||||
import { Badge } from '../../components/ui'
|
import { Badge } from '../../components/ui'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { PLAN_NAMES, planFeatureList } from './copy'
|
import { PLAN_NAMES, planFeatureList } from './copy'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
type PlanOptionCardProps = {
|
type PlanOptionCardProps = {
|
||||||
plan: Plan
|
plan: Plan
|
||||||
@@ -18,6 +19,7 @@ type PlanOptionCardProps = {
|
|||||||
|
|
||||||
/** Una tarjeta de plan, igual en la pantalla del plan y en el onboarding. */
|
/** Una tarjeta de plan, igual en la pantalla del plan y en el onboarding. */
|
||||||
export function PlanOptionCard({ plan, limits, price, current, highlighted, children }: PlanOptionCardProps) {
|
export function PlanOptionCard({ plan, limits, price, current, highlighted, children }: PlanOptionCardProps) {
|
||||||
|
const { t } = useTranslation(['billing', 'common'])
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -27,9 +29,9 @@ export function PlanOptionCard({ plan, limits, price, current, highlighted, chil
|
|||||||
>
|
>
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="flex items-center justify-between gap-3">
|
||||||
<p className="text-base font-semibold text-primary">{PLAN_NAMES[plan]}</p>
|
<p className="text-base font-semibold text-primary">{PLAN_NAMES[plan]}</p>
|
||||||
{current ? <Badge variant="info">Tu plan</Badge> : null}
|
{current ? <Badge variant="info">{t('option.yourPlan')}</Badge> : null}
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-1 text-sm text-foreground/60">{price ?? 'Gratis'}</p>
|
<p className="mt-1 text-sm text-foreground/60">{price ?? t('option.free')}</p>
|
||||||
|
|
||||||
<ul className="mt-3 flex-1 space-y-1.5">
|
<ul className="mt-3 flex-1 space-y-1.5">
|
||||||
{planFeatureList(limits).map((feature) => (
|
{planFeatureList(limits).map((feature) => (
|
||||||
|
|||||||
@@ -3,10 +3,12 @@ import { ChevronRight, Sparkles } from 'lucide-react'
|
|||||||
import { Badge } from '../../components/ui'
|
import { Badge } from '../../components/ui'
|
||||||
import { PLAN_NAMES, planBadgeVariant } from './copy'
|
import { PLAN_NAMES, planBadgeVariant } from './copy'
|
||||||
import { useBillingStatus } from './useBillingStatus'
|
import { useBillingStatus } from './useBillingStatus'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
/** Entrada a la pantalla del plan desde Ajustes. */
|
/** Entrada a la pantalla del plan desde Ajustes. */
|
||||||
export function PlanSettingsCard() {
|
export function PlanSettingsCard() {
|
||||||
const statusQuery = useBillingStatus()
|
const statusQuery = useBillingStatus()
|
||||||
|
const { t } = useTranslation(['billing', 'common'])
|
||||||
const status = statusQuery.data
|
const status = statusQuery.data
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -16,12 +18,12 @@ export function PlanSettingsCard() {
|
|||||||
<Sparkles className="size-4 text-accent-fg" />
|
<Sparkles className="size-4 text-accent-fg" />
|
||||||
</span>
|
</span>
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<p className="text-sm font-medium text-primary">Plan</p>
|
<p className="text-sm font-medium text-primary">{t('settings.title')}</p>
|
||||||
<p className="text-xs text-foreground/50">Tu plan de Gruperly y tus pagos</p>
|
<p className="text-xs text-foreground/50">{t('settings.description')}</p>
|
||||||
</div>
|
</div>
|
||||||
{status ? (
|
{status ? (
|
||||||
<Badge variant={planBadgeVariant(status)}>
|
<Badge variant={planBadgeVariant(status)}>
|
||||||
{status.readOnly ? 'Solo lectura' : PLAN_NAMES[status.plan]}
|
{status.readOnly ? t('settings.readOnly') : PLAN_NAMES[status.plan]}
|
||||||
</Badge>
|
</Badge>
|
||||||
) : null}
|
) : null}
|
||||||
<ChevronRight className="size-4 text-foreground/40" />
|
<ChevronRight className="size-4 text-foreground/40" />
|
||||||
|
|||||||
@@ -11,17 +11,19 @@ import {
|
|||||||
planNoticeMessage,
|
planNoticeMessage,
|
||||||
subscriptionStatusLabel,
|
subscriptionStatusLabel,
|
||||||
} from './copy'
|
} from './copy'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
/** El plan actual: estado de la suscripción, próximo cobro y uso contra los límites. */
|
/** El plan actual: estado de la suscripción, próximo cobro y uso contra los límites. */
|
||||||
export function PlanSummaryCard() {
|
export function PlanSummaryCard() {
|
||||||
const { statusQuery } = useBilling()
|
const { statusQuery } = useBilling()
|
||||||
|
const { t } = useTranslation(['billing', 'common'])
|
||||||
const status = statusQuery.data
|
const status = statusQuery.data
|
||||||
|
|
||||||
if (!status) {
|
if (!status) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3">
|
<div className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3">
|
||||||
<Loader2 className="size-4 animate-spin text-foreground/40" />
|
<Loader2 className="size-4 animate-spin text-foreground/40" />
|
||||||
<p className="text-sm text-foreground/50">Consultando tu plan…</p>
|
<p className="text-sm text-foreground/50">{t('summary.loading')}</p>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -34,27 +36,27 @@ export function PlanSummaryCard() {
|
|||||||
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
|
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
|
||||||
<div className="px-4 py-3">
|
<div className="px-4 py-3">
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="flex items-center justify-between gap-3">
|
||||||
<p className="text-sm font-medium text-primary">Plan {PLAN_NAMES[status.plan]}</p>
|
<p className="text-sm font-medium text-primary">{t('summary.plan', { plan: PLAN_NAMES[status.plan] })}</p>
|
||||||
<Badge variant={planBadgeVariant(status)}>
|
<Badge variant={planBadgeVariant(status)}>
|
||||||
{status.readOnly ? 'Solo lectura' : subscriptionStatusLabel(status.status)}
|
{status.readOnly ? t('settings.readOnly') : subscriptionStatusLabel(status.status)}
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
{status.status === 'AUTHORIZED' && nextPayment ? (
|
{status.status === 'AUTHORIZED' && nextPayment ? (
|
||||||
<p className="mt-0.5 text-xs text-foreground/50">
|
<p className="mt-0.5 text-xs text-foreground/50">
|
||||||
Próximo cobro: {formatPrice(status.priceAmount, status.currency)} el {nextPayment}
|
{t('summary.next', { amount: formatPrice(status.priceAmount, status.currency), date: nextPayment })}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
{status.status === 'PENDING' ? (
|
{status.status === 'PENDING' ? (
|
||||||
<p className="mt-0.5 text-xs text-foreground/50">
|
<p className="mt-0.5 text-xs text-foreground/50">
|
||||||
Estamos esperando que {BILLING_PROVIDER_NAMES[status.provider]} confirme tu suscripción.
|
{t('summary.pending', { provider: BILLING_PROVIDER_NAMES[status.provider] })}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
{status.status === 'CANCELLED' && status.plan === 'PRO' && paidThrough ? (
|
{status.status === 'CANCELLED' && status.plan === 'PRO' && paidThrough ? (
|
||||||
<p className="mt-0.5 text-xs text-foreground/50">Pagado hasta el {paidThrough}.</p>
|
<p className="mt-0.5 text-xs text-foreground/50">{t('summary.paidThrough', { date: paidThrough })}</p>
|
||||||
) : null}
|
) : null}
|
||||||
{!status.enforced ? (
|
{!status.enforced ? (
|
||||||
<p className="mt-0.5 text-xs text-foreground/50">
|
<p className="mt-0.5 text-xs text-foreground/50">
|
||||||
Por ahora todas las funciones están habilitadas para todas las cuentas.
|
{t('summary.notEnforced')}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
@@ -73,13 +75,13 @@ export function PlanSummaryCard() {
|
|||||||
|
|
||||||
<dl className="grid grid-cols-2 gap-3 px-4 py-3">
|
<dl className="grid grid-cols-2 gap-3 px-4 py-3">
|
||||||
<div>
|
<div>
|
||||||
<dt className="text-xs text-foreground/50">Grupos</dt>
|
<dt className="text-xs text-foreground/50">{t('summary.groups')}</dt>
|
||||||
<dd className="text-sm font-medium text-primary">
|
<dd className="text-sm font-medium text-primary">
|
||||||
{formatUsage(status.usage.groups, status.limits.maxGroups)}
|
{formatUsage(status.usage.groups, status.limits.maxGroups)}
|
||||||
</dd>
|
</dd>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<dt className="text-xs text-foreground/50">Alumnos activos</dt>
|
<dt className="text-xs text-foreground/50">{t('summary.students')}</dt>
|
||||||
<dd className="text-sm font-medium text-primary">
|
<dd className="text-sm font-medium text-primary">
|
||||||
{formatUsage(status.usage.attendees, status.limits.maxAttendees)}
|
{formatUsage(status.usage.attendees, status.limits.maxAttendees)}
|
||||||
</dd>
|
</dd>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useNavigate } from '@tanstack/react-router'
|
|||||||
import { Sparkles } from 'lucide-react'
|
import { Sparkles } from 'lucide-react'
|
||||||
import { Button, Modal } from '../../components/ui'
|
import { Button, Modal } from '../../components/ui'
|
||||||
import { dismissPlanPrompt, usePlanPrompt } from './plan-prompt'
|
import { dismissPlanPrompt, usePlanPrompt } from './plan-prompt'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Aviso de "esto es de Pro". Lo dispara cualquier 402 de plan (ver el
|
* Aviso de "esto es de Pro". Lo dispara cualquier 402 de plan (ver el
|
||||||
@@ -10,19 +11,20 @@ import { dismissPlanPrompt, usePlanPrompt } from './plan-prompt'
|
|||||||
*/
|
*/
|
||||||
export function PlanUpgradePrompt() {
|
export function PlanUpgradePrompt() {
|
||||||
const detail = usePlanPrompt()
|
const detail = usePlanPrompt()
|
||||||
|
const { t } = useTranslation(['billing', 'common'])
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
isOpen={detail !== null}
|
isOpen={detail !== null}
|
||||||
onClose={dismissPlanPrompt}
|
onClose={dismissPlanPrompt}
|
||||||
title="Disponible en Pro"
|
title={t('upgrade.title')}
|
||||||
description={detail ?? undefined}
|
description={detail ?? undefined}
|
||||||
maxWidth="sm"
|
maxWidth="sm"
|
||||||
>
|
>
|
||||||
<div className="flex justify-end gap-3">
|
<div className="flex justify-end gap-3">
|
||||||
<Button variant="outline" onClick={dismissPlanPrompt}>
|
<Button variant="outline" onClick={dismissPlanPrompt}>
|
||||||
Ahora no
|
{t('upgrade.later')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
@@ -32,7 +34,7 @@ export function PlanUpgradePrompt() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Sparkles className="size-4" />
|
<Sparkles className="size-4" />
|
||||||
Ver planes
|
{t('upgrade.seePlans')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { Loader2 } from 'lucide-react'
|
|||||||
import { type FormEvent, useState } from 'react'
|
import { type FormEvent, useState } from 'react'
|
||||||
import { Button, Input, Label } from '../../components/ui'
|
import { Button, Input, Label } from '../../components/ui'
|
||||||
import { BILLING_PROVIDER_NAMES } from './copy'
|
import { BILLING_PROVIDER_NAMES } from './copy'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
type SubscribeFormProps = {
|
type SubscribeFormProps = {
|
||||||
provider: BillingProviderId
|
provider: BillingProviderId
|
||||||
@@ -26,11 +27,12 @@ export function SubscribeForm({
|
|||||||
defaultEmail,
|
defaultEmail,
|
||||||
isPending,
|
isPending,
|
||||||
error,
|
error,
|
||||||
submitLabel = `Ir a ${BILLING_PROVIDER_NAMES[provider]}`,
|
submitLabel,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
onCancel,
|
onCancel,
|
||||||
}: SubscribeFormProps) {
|
}: SubscribeFormProps) {
|
||||||
const [email, setEmail] = useState(defaultEmail)
|
const [email, setEmail] = useState(defaultEmail)
|
||||||
|
const { t } = useTranslation(['billing', 'common'])
|
||||||
const asksEmail = provider === 'MERCADO_PAGO'
|
const asksEmail = provider === 'MERCADO_PAGO'
|
||||||
|
|
||||||
const handleSubmit = (event: FormEvent) => {
|
const handleSubmit = (event: FormEvent) => {
|
||||||
@@ -42,7 +44,7 @@ export function SubscribeForm({
|
|||||||
<form className="space-y-4" onSubmit={handleSubmit}>
|
<form className="space-y-4" onSubmit={handleSubmit}>
|
||||||
{asksEmail ? (
|
{asksEmail ? (
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<Label htmlFor="payer-email">Email de tu cuenta de Mercado Pago</Label>
|
<Label htmlFor="payer-email">{t('subscribe.payerEmail')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="payer-email"
|
id="payer-email"
|
||||||
type="email"
|
type="email"
|
||||||
@@ -53,7 +55,7 @@ export function SubscribeForm({
|
|||||||
onChange={(event) => setEmail(event.target.value)}
|
onChange={(event) => setEmail(event.target.value)}
|
||||||
/>
|
/>
|
||||||
<p className="text-xs text-foreground/50">
|
<p className="text-xs text-foreground/50">
|
||||||
Tenés que entrar a Mercado Pago con este mismo email para autorizar el débito mensual.
|
{t('subscribe.payerEmailHint')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -63,12 +65,12 @@ export function SubscribeForm({
|
|||||||
<div className="flex justify-end gap-3">
|
<div className="flex justify-end gap-3">
|
||||||
{onCancel ? (
|
{onCancel ? (
|
||||||
<Button type="button" variant="outline" onClick={onCancel}>
|
<Button type="button" variant="outline" onClick={onCancel}>
|
||||||
Cancelar
|
{t('common:actions.cancel')}
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
<Button type="submit" variant="primary" disabled={isPending || (asksEmail && !email.trim())}>
|
<Button type="submit" variant="primary" disabled={isPending || (asksEmail && !email.trim())}>
|
||||||
{isPending ? <Loader2 className="size-4 animate-spin" /> : null}
|
{isPending ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
{isPending ? 'Abriendo…' : submitLabel}
|
{isPending ? t('subscribe.opening') : (submitLabel ?? t('subscribe.goTo', { provider: BILLING_PROVIDER_NAMES[provider] }))}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -4,9 +4,11 @@ import { useBilling } from './BillingProvider'
|
|||||||
import { subscribeDescription } from './copy'
|
import { subscribeDescription } from './copy'
|
||||||
import { SubscribeForm } from './SubscribeForm'
|
import { SubscribeForm } from './SubscribeForm'
|
||||||
import { useStartSubscription } from './useStartSubscription'
|
import { useStartSubscription } from './useStartSubscription'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function SubscribeModal() {
|
export function SubscribeModal() {
|
||||||
const { user } = useAuth()
|
const { user } = useAuth()
|
||||||
|
const { t } = useTranslation(['billing', 'common'])
|
||||||
const { isSubscribeOpen, closeSubscribe, statusQuery } = useBilling()
|
const { isSubscribeOpen, closeSubscribe, statusQuery } = useBilling()
|
||||||
const subscription = useStartSubscription()
|
const subscription = useStartSubscription()
|
||||||
const provider = statusQuery.data?.provider ?? 'MERCADO_PAGO'
|
const provider = statusQuery.data?.provider ?? 'MERCADO_PAGO'
|
||||||
@@ -15,7 +17,7 @@ export function SubscribeModal() {
|
|||||||
<Modal
|
<Modal
|
||||||
isOpen={isSubscribeOpen}
|
isOpen={isSubscribeOpen}
|
||||||
onClose={closeSubscribe}
|
onClose={closeSubscribe}
|
||||||
title="Pasate a Pro"
|
title={t('subscribe.title')}
|
||||||
description={subscribeDescription(provider)}
|
description={subscribeDescription(provider)}
|
||||||
maxWidth="sm"
|
maxWidth="sm"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import type {
|
|||||||
SubscriptionStatus,
|
SubscriptionStatus,
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
import type { BadgeVariant } from '../../components/ui'
|
import type { BadgeVariant } from '../../components/ui'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
|
|
||||||
/* Copy del plan de Gruperly en un solo lugar: Ajustes, la pantalla del plan, el
|
/* Copy del plan de Gruperly en un solo lugar: Ajustes, la pantalla del plan, el
|
||||||
paso del onboarding y los avisos tienen que decir lo mismo. Funciones puras,
|
paso del onboarding y los avisos tienen que decir lo mismo. Funciones puras,
|
||||||
@@ -14,8 +15,9 @@ import type { BadgeVariant } from '../../components/ui'
|
|||||||
|
|
||||||
export const PLAN_NAMES: Record<Plan, string> = { FREE: 'Free', PRO: 'Pro' }
|
export const PLAN_NAMES: Record<Plan, string> = { FREE: 'Free', PRO: 'Pro' }
|
||||||
|
|
||||||
export const SUBSCRIBE_ERROR_MESSAGE =
|
export function subscribeErrorMessage(): string {
|
||||||
'No pudimos abrir la página de pago. Revisá tu conexión e intentá de nuevo.'
|
return i18n.t('billing:subscribeError')
|
||||||
|
}
|
||||||
|
|
||||||
/* Quién cobra Pro: Mercado Pago en Argentina, Stripe en el resto. Es solo la
|
/* Quién cobra Pro: Mercado Pago en Argentina, Stripe en el resto. Es solo la
|
||||||
suscripción a Gruperly; los cobros a alumnos siguen siendo con Mercado Pago. */
|
suscripción a Gruperly; los cobros a alumnos siguen siendo con Mercado Pago. */
|
||||||
@@ -26,9 +28,7 @@ export const BILLING_PROVIDER_NAMES: Record<BillingProviderId, string> = {
|
|||||||
|
|
||||||
/** Qué pasa al tocar "Pasar a Pro", según quién cobra. */
|
/** Qué pasa al tocar "Pasar a Pro", según quién cobra. */
|
||||||
export function subscribeDescription(provider: BillingProviderId): string {
|
export function subscribeDescription(provider: BillingProviderId): string {
|
||||||
return provider === 'STRIPE'
|
return i18n.t(`billing:subscribeDescription.${provider}`)
|
||||||
? 'Te llevamos a Stripe para cargar tu tarjeta. El cobro es mensual y podés cancelarlo cuando quieras.'
|
|
||||||
: 'Te llevamos a Mercado Pago para autorizar el débito mensual. Podés cancelarlo cuando quieras.'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Lo que incluye cada plan, como lista para las tarjetas de comparación. */
|
/** Lo que incluye cada plan, como lista para las tarjetas de comparación. */
|
||||||
@@ -37,25 +37,25 @@ export function planFeatureList(limits: PlanLimits): { label: string; included:
|
|||||||
{
|
{
|
||||||
label:
|
label:
|
||||||
limits.maxGroups === null
|
limits.maxGroups === null
|
||||||
? 'Grupos ilimitados'
|
? i18n.t('billing:features.unlimitedGroups')
|
||||||
: `${limits.maxGroups} ${limits.maxGroups === 1 ? 'grupo' : 'grupos'}`,
|
: i18n.t('billing:features.groups', { count: limits.maxGroups }),
|
||||||
included: true,
|
included: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label:
|
label:
|
||||||
limits.maxAttendees === null
|
limits.maxAttendees === null
|
||||||
? 'Alumnos ilimitados'
|
? i18n.t('billing:features.unlimitedStudents')
|
||||||
: `Hasta ${limits.maxAttendees} alumnos activos`,
|
: i18n.t('billing:features.students', { count: limits.maxAttendees }),
|
||||||
included: true,
|
included: true,
|
||||||
},
|
},
|
||||||
{ label: 'Cobros con Mercado Pago', included: limits.mpCharges },
|
{ label: i18n.t('billing:features.mpCharges'), included: limits.mpCharges },
|
||||||
{ label: 'Mensajes automáticos por WhatsApp', included: limits.whatsappAutomations },
|
{ label: i18n.t('billing:features.whatsapp'), included: limits.whatsappAutomations },
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PLAN_FEATURE_REQUIRED_MESSAGES: Record<PlanFeature, string> = {
|
/** The same copy as the backend's `plan_feature_required` problem. */
|
||||||
mpCharges: 'Cobrar con Mercado Pago está disponible en el plan Pro.',
|
export function planFeatureRequiredMessage(feature: PlanFeature): string {
|
||||||
whatsappAutomations: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
|
return i18n.t(`errors:codes.plan_feature_required_${feature}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -69,15 +69,12 @@ export function hasPlanFeature(status: BillingStatusDto | undefined, feature: Pl
|
|||||||
export function subscriptionStatusLabel(status: SubscriptionStatus | null): string {
|
export function subscriptionStatusLabel(status: SubscriptionStatus | null): string {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
case 'AUTHORIZED':
|
case 'AUTHORIZED':
|
||||||
return 'Activa'
|
|
||||||
case 'PENDING':
|
case 'PENDING':
|
||||||
return 'Pendiente de pago'
|
|
||||||
case 'PAUSED':
|
case 'PAUSED':
|
||||||
return 'Pausada'
|
|
||||||
case 'CANCELLED':
|
case 'CANCELLED':
|
||||||
return 'Cancelada'
|
return i18n.t(`billing:subscriptionStatus.${status}`)
|
||||||
default:
|
default:
|
||||||
return 'Sin suscripción'
|
return i18n.t('billing:subscriptionStatus.NONE')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,14 +88,14 @@ export function formatBillingDate(iso: string | null): string | null {
|
|||||||
if (!iso) return null
|
if (!iso) return null
|
||||||
const date = new Date(iso)
|
const date = new Date(iso)
|
||||||
if (Number.isNaN(date.getTime())) return null
|
if (Number.isNaN(date.getTime())) return null
|
||||||
return new Intl.DateTimeFormat('es', { day: 'numeric', month: 'short', year: 'numeric' }).format(
|
return new Intl.DateTimeFormat(i18n.language, { day: 'numeric', month: 'short', year: 'numeric' }).format(
|
||||||
date,
|
date,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** "3 de 15": el uso contra el límite, o solo el uso cuando no hay límite. */
|
/** "3 de 15": el uso contra el límite, o solo el uso cuando no hay límite. */
|
||||||
export function formatUsage(used: number, limit: number | null): string {
|
export function formatUsage(used: number, limit: number | null): string {
|
||||||
return limit === null ? `${used}` : `${used} de ${limit}`
|
return limit === null ? `${used}` : i18n.t('billing:usage', { used, limit })
|
||||||
}
|
}
|
||||||
|
|
||||||
const PLAN_PROBLEM_CODES = ['plan_limit_reached', 'plan_feature_required', 'plan_read_only']
|
const PLAN_PROBLEM_CODES = ['plan_limit_reached', 'plan_feature_required', 'plan_read_only']
|
||||||
@@ -124,7 +121,7 @@ export function planNoticeMessage(status: BillingStatusDto): { tone: 'danger' |
|
|||||||
if (status.readOnly) {
|
if (status.readOnly) {
|
||||||
return {
|
return {
|
||||||
tone: 'danger',
|
tone: 'danger',
|
||||||
text: 'Tu cuenta está en solo lectura: superás los límites del plan Free. Pasate a Pro o reducí tus alumnos para volver a editar.',
|
text: i18n.t('billing:notice.readOnly'),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const graceUntil = formatBillingDate(status.graceUntil)
|
const graceUntil = formatBillingDate(status.graceUntil)
|
||||||
@@ -133,8 +130,11 @@ export function planNoticeMessage(status: BillingStatusDto): { tone: 'danger' |
|
|||||||
tone: 'warning',
|
tone: 'warning',
|
||||||
text:
|
text:
|
||||||
status.status === 'CANCELLED'
|
status.status === 'CANCELLED'
|
||||||
? `Cancelaste Pro: lo seguís teniendo hasta el ${graceUntil}.`
|
? i18n.t('billing:notice.cancelled', { date: graceUntil })
|
||||||
: `No pudimos cobrar tu suscripción a Pro. Revisá tu medio de pago en ${BILLING_PROVIDER_NAMES[status.provider]} antes del ${graceUntil}.`,
|
: i18n.t('billing:notice.paymentFailed', {
|
||||||
|
provider: BILLING_PROVIDER_NAMES[status.provider],
|
||||||
|
date: graceUntil,
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ export {
|
|||||||
formatUsage,
|
formatUsage,
|
||||||
hasPlanFeature,
|
hasPlanFeature,
|
||||||
isPlanProblem,
|
isPlanProblem,
|
||||||
PLAN_FEATURE_REQUIRED_MESSAGES,
|
planFeatureRequiredMessage,
|
||||||
PLAN_NAMES,
|
PLAN_NAMES,
|
||||||
planFeatureList,
|
planFeatureList,
|
||||||
planNoticeMessage,
|
planNoticeMessage,
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import type { BillingReturnTo } from '@gruperly/shared'
|
import type { BillingReturnTo } from '@gruperly/shared'
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { ApiError, subscribeToPro } from '../../lib/api'
|
import { subscribeToPro } from '../../lib/api'
|
||||||
import { SUBSCRIBE_ERROR_MESSAGE } from './copy'
|
import { errorMessage } from '../../i18n'
|
||||||
|
import { subscribeErrorMessage } from './copy'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Empieza la suscripción a Pro. Como la vinculación de Mercado Pago, no se
|
* Empieza la suscripción a Pro. Como la vinculación de Mercado Pago, no se
|
||||||
@@ -19,7 +20,7 @@ export function useStartSubscription() {
|
|||||||
const { checkoutUrl } = await subscribeToPro({ payerEmail, returnTo })
|
const { checkoutUrl } = await subscribeToPro({ payerEmail, returnTo })
|
||||||
window.location.assign(checkoutUrl)
|
window.location.assign(checkoutUrl)
|
||||||
} catch (caught) {
|
} catch (caught) {
|
||||||
setError(caught instanceof ApiError && caught.problem?.detail ? caught.problem.detail : SUBSCRIBE_ERROR_MESSAGE)
|
setError(errorMessage(caught, subscribeErrorMessage()))
|
||||||
setIsStarting(false)
|
setIsStarting(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import { useToast } from '../../components/ui'
|
|||||||
import { getSessionStudents, markAttendance } from '../../lib/api'
|
import { getSessionStudents, markAttendance } from '../../lib/api'
|
||||||
import { isAttendanceLocked } from './utils'
|
import { isAttendanceLocked } from './utils'
|
||||||
import type { AttendanceChoice } from './utils'
|
import type { AttendanceChoice } from './utils'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
import { errorMessage, useIntlLocale } from '../../i18n'
|
||||||
|
|
||||||
type AttendanceContextValue = {
|
type AttendanceContextValue = {
|
||||||
sessionId: string
|
sessionId: string
|
||||||
@@ -27,6 +29,8 @@ const AttendanceContext = createContext<AttendanceContextValue | null>(null)
|
|||||||
export function AttendanceProvider({ sessionId, children }: { sessionId: string; children: ReactNode }) {
|
export function AttendanceProvider({ sessionId, children }: { sessionId: string; children: ReactNode }) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
|
const { t } = useTranslation(['classAttendance', 'common'])
|
||||||
|
const locale = useIntlLocale()
|
||||||
|
|
||||||
const studentsQuery = useQuery({
|
const studentsQuery = useQuery({
|
||||||
queryKey: ['class-students', sessionId],
|
queryKey: ['class-students', sessionId],
|
||||||
@@ -73,22 +77,18 @@ export function AttendanceProvider({ sessionId, children }: { sessionId: string;
|
|||||||
return markAttendance(sessionId, { classSessionId: sessionId, records })
|
return markAttendance(sessionId, { classSessionId: sessionId, records })
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
toast.success('Asistencia guardada correctamente.', 'Listo')
|
toast.success(t('saved'), t('savedTitle'))
|
||||||
void queryClient.invalidateQueries({ queryKey: ['classes-today'] })
|
void queryClient.invalidateQueries({ queryKey: ['classes-today'] })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['class-students', sessionId] })
|
void queryClient.invalidateQueries({ queryKey: ['class-students', sessionId] })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['attendee-stats'] })
|
void queryClient.invalidateQueries({ queryKey: ['attendee-stats'] })
|
||||||
},
|
},
|
||||||
onError: (error: Error) => {
|
onError: (error: Error) => {
|
||||||
toast.error(error.message || 'No pudimos guardar la asistencia.')
|
toast.error(errorMessage(error, t('saveError')))
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const startTime = sessionInfo
|
const startTime = sessionInfo
|
||||||
? new Date(sessionInfo.startsAt).toLocaleTimeString('es-MX', {
|
? new Date(sessionInfo.startsAt).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' })
|
||||||
hour: '2-digit',
|
|
||||||
minute: '2-digit',
|
|
||||||
hour12: false,
|
|
||||||
})
|
|
||||||
: null
|
: null
|
||||||
|
|
||||||
const value: AttendanceContextValue = {
|
const value: AttendanceContextValue = {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Check, X } from 'lucide-react'
|
import { Check, X } from 'lucide-react'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import type { AttendanceChoice } from './utils'
|
import type { AttendanceChoice } from './utils'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function AttendanceToggle({
|
export function AttendanceToggle({
|
||||||
choice,
|
choice,
|
||||||
@@ -14,13 +15,14 @@ export function AttendanceToggle({
|
|||||||
fullName: string
|
fullName: string
|
||||||
}) {
|
}) {
|
||||||
const isPresent = choice === 'PRESENT'
|
const isPresent = choice === 'PRESENT'
|
||||||
|
const { t } = useTranslation('classAttendance')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
role="switch"
|
role="switch"
|
||||||
aria-checked={isPresent}
|
aria-checked={isPresent}
|
||||||
aria-label={`${isPresent ? 'Presente' : 'Ausente'}: ${fullName}`}
|
aria-label={t(`toggle.${choice}`, { name: fullName })}
|
||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
onClick={onToggle}
|
onClick={onToggle}
|
||||||
className={cn(
|
className={cn(
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { LargeTitle } from '../../components/layout/LargeTitle'
|
|||||||
import { Badge, Button } from '../../components/ui'
|
import { Badge, Button } from '../../components/ui'
|
||||||
import { useAttendance } from './AttendanceProvider'
|
import { useAttendance } from './AttendanceProvider'
|
||||||
import { StudentRow } from './StudentRow'
|
import { StudentRow } from './StudentRow'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function ClassAttendanceView() {
|
export function ClassAttendanceView() {
|
||||||
const {
|
const {
|
||||||
@@ -16,6 +17,7 @@ export function ClassAttendanceView() {
|
|||||||
saveAttendance,
|
saveAttendance,
|
||||||
isSaving,
|
isSaving,
|
||||||
} = useAttendance()
|
} = useAttendance()
|
||||||
|
const { t } = useTranslation(['classAttendance', 'common'])
|
||||||
|
|
||||||
const total = sessionInfo?.students.length ?? 0
|
const total = sessionInfo?.students.length ?? 0
|
||||||
|
|
||||||
@@ -25,14 +27,14 @@ export function ClassAttendanceView() {
|
|||||||
orients and gives the bar its anchor height. The present counter, on the
|
orients and gives the bar its anchor height. The present counter, on the
|
||||||
other hand, only shows once there are students on screen. */}
|
other hand, only shows once there are students on screen. */}
|
||||||
<LargeTitle
|
<LargeTitle
|
||||||
title={sessionInfo?.groupName ?? 'Asistencia'}
|
title={sessionInfo?.groupName ?? t('fallbackTitle')}
|
||||||
leading={
|
leading={
|
||||||
<Link
|
<Link
|
||||||
to="/"
|
to="/"
|
||||||
className="hidden shrink-0 items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
className="hidden shrink-0 items-center gap-1 text-sm text-foreground/80 transition-colors hover:text-primary lg:inline-flex"
|
||||||
>
|
>
|
||||||
<ArrowLeft className="size-4" />
|
<ArrowLeft className="size-4" />
|
||||||
<span>Volver al inicio</span>
|
<span>{t('backHome')}</span>
|
||||||
</Link>
|
</Link>
|
||||||
}
|
}
|
||||||
barTrailing={
|
barTrailing={
|
||||||
@@ -46,10 +48,10 @@ export function ClassAttendanceView() {
|
|||||||
{sessionInfo ? (
|
{sessionInfo ? (
|
||||||
<div className="mt-2 flex items-center justify-between gap-3">
|
<div className="mt-2 flex items-center justify-between gap-3">
|
||||||
<p className="text-sm text-foreground/60">
|
<p className="text-sm text-foreground/60">
|
||||||
{startTime ? `Hoy · ${startTime} hs` : 'Clase de hoy'}
|
{startTime ? t('today', { time: startTime }) : t('todayClass')}
|
||||||
</p>
|
</p>
|
||||||
<Badge variant="success" className="shrink-0 text-xs tabular-nums">
|
<Badge variant="success" className="shrink-0 text-xs tabular-nums">
|
||||||
{presentCount}/{total} presentes
|
{t('present', { present: presentCount, total })}
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -63,9 +65,9 @@ export function ClassAttendanceView() {
|
|||||||
|
|
||||||
{studentsFailed ? (
|
{studentsFailed ? (
|
||||||
<div className="mt-4 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
<div className="mt-4 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
<p>No pudimos cargar la lista de alumnos.</p>
|
<p>{t('loadError')}</p>
|
||||||
<Button variant="outline" size="sm" onClick={retryStudents}>
|
<Button variant="outline" size="sm" onClick={retryStudents}>
|
||||||
Reintentar
|
{t('common:actions.retry')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -74,9 +76,9 @@ export function ClassAttendanceView() {
|
|||||||
<>
|
<>
|
||||||
{total === 0 ? (
|
{total === 0 ? (
|
||||||
<div className="mt-6 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
<div className="mt-6 rounded-xl border border-dashed border-border bg-surface px-4 py-10 text-center">
|
||||||
<p className="text-sm font-medium text-primary">Este grupo no tiene alumnos</p>
|
<p className="text-sm font-medium text-primary">{t('emptyTitle')}</p>
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
<p className="mt-1 text-sm text-foreground/60">
|
||||||
Agregá miembros desde la ficha del grupo para tomar asistencia.
|
{t('emptyDescription')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -96,7 +98,7 @@ export function ClassAttendanceView() {
|
|||||||
onClick={saveAttendance}
|
onClick={saveAttendance}
|
||||||
>
|
>
|
||||||
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
{isSaving ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
Guardar Asistencia
|
{t('save')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -3,13 +3,20 @@ import { Avatar, Badge } from '../../components/ui'
|
|||||||
import { AttendanceToggle } from './AttendanceToggle'
|
import { AttendanceToggle } from './AttendanceToggle'
|
||||||
import { useAttendance } from './AttendanceProvider'
|
import { useAttendance } from './AttendanceProvider'
|
||||||
import { isAttendanceLocked } from './utils'
|
import { isAttendanceLocked } from './utils'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
function PaymentBadge({ status }: { status: SessionStudentDto['paymentStatus'] }) {
|
function PaymentBadge({ status }: { status: SessionStudentDto['paymentStatus'] }) {
|
||||||
return status === 'UP_TO_DATE' ? <Badge variant="success">Al día</Badge> : <Badge variant="danger">Pendiente</Badge>
|
const { t } = useTranslation('classAttendance')
|
||||||
|
return status === 'UP_TO_DATE' ? (
|
||||||
|
<Badge variant="success">{t('upToDate')}</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge variant="danger">{t('pending')}</Badge>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function StudentRow({ student }: { student: SessionStudentDto }) {
|
export function StudentRow({ student }: { student: SessionStudentDto }) {
|
||||||
const { choiceFor, toggleStudent } = useAttendance()
|
const { choiceFor, toggleStudent } = useAttendance()
|
||||||
|
const { t } = useTranslation('classAttendance')
|
||||||
const locked = isAttendanceLocked(student)
|
const locked = isAttendanceLocked(student)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -23,7 +30,7 @@ export function StudentRow({ student }: { student: SessionStudentDto }) {
|
|||||||
<p className="truncate text-sm font-semibold text-primary">{student.fullName}</p>
|
<p className="truncate text-sm font-semibold text-primary">{student.fullName}</p>
|
||||||
<div className="mt-1 flex flex-wrap items-center gap-1.5">
|
<div className="mt-1 flex flex-wrap items-center gap-1.5">
|
||||||
<PaymentBadge status={student.paymentStatus} />
|
<PaymentBadge status={student.paymentStatus} />
|
||||||
{locked ? <Badge variant="warning">Avisó ausencia</Badge> : null}
|
{locked ? <Badge variant="warning">{t('notified')}</Badge> : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<AttendanceToggle
|
<AttendanceToggle
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { ChevronRight } from 'lucide-react'
|
import { ChevronRight } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { AlertTag } from '../attention/AlertTag'
|
import { AlertTag } from '../attention/AlertTag'
|
||||||
import type { FlaggedStudent } from '../attention/attention'
|
import { alertLabel, type FlaggedStudent } from '../attention/attention'
|
||||||
import { SeverityAvatar } from '../attention/SeverityAvatar'
|
import { SeverityAvatar } from '../attention/SeverityAvatar'
|
||||||
|
|
||||||
const PREVIEW_LIMIT = 4
|
const PREVIEW_LIMIT = 4
|
||||||
|
|
||||||
/** "Requiere atención" on Grupos: the most urgent students, one row each. */
|
/** "Requiere atención" on Grupos: the most urgent students, one row each. */
|
||||||
export function AttentionPreview({ students }: { students: FlaggedStudent[] }) {
|
export function AttentionPreview({ students }: { students: FlaggedStudent[] }) {
|
||||||
|
const { t } = useTranslation('groups')
|
||||||
if (students.length === 0) return null
|
if (students.length === 0) return null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -17,18 +19,18 @@ export function AttentionPreview({ students }: { students: FlaggedStudent[] }) {
|
|||||||
id="attention-preview-title"
|
id="attention-preview-title"
|
||||||
className="flex items-center gap-2 text-xs font-semibold tracking-wider text-alert-urgent-fg uppercase"
|
className="flex items-center gap-2 text-xs font-semibold tracking-wider text-alert-urgent-fg uppercase"
|
||||||
>
|
>
|
||||||
Requiere atención
|
{t('attentionPreview.title')}
|
||||||
<span className="inline-flex min-w-5 items-center justify-center rounded-full bg-alert-urgent-soft px-1.5 py-0.5 text-[11px] leading-none tabular-nums">
|
<span className="inline-flex min-w-5 items-center justify-center rounded-full bg-alert-urgent-soft px-1.5 py-0.5 text-[11px] leading-none tabular-nums">
|
||||||
<span className="sr-only">: </span>
|
<span className="sr-only">: </span>
|
||||||
{students.length}
|
<span aria-hidden="true">{students.length}</span>
|
||||||
<span className="sr-only"> {students.length === 1 ? 'alumno' : 'alumnos'}</span>
|
<span className="sr-only">{t('attentionPreview.students', { count: students.length })}</span>
|
||||||
</span>
|
</span>
|
||||||
</h2>
|
</h2>
|
||||||
<Link
|
<Link
|
||||||
to="/groups/attention"
|
to="/groups/attention"
|
||||||
className="-mr-2 inline-flex min-h-11 items-center gap-0.5 rounded-xl px-2 text-sm font-medium text-accent-fg hover:underline focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none"
|
className="-mr-2 inline-flex min-h-11 items-center gap-0.5 rounded-xl px-2 text-sm font-medium text-accent-fg hover:underline focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none"
|
||||||
>
|
>
|
||||||
Ver todos
|
{t('attentionPreview.seeAll')}
|
||||||
<ChevronRight className="size-4" aria-hidden="true" />
|
<ChevronRight className="size-4" aria-hidden="true" />
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
@@ -51,8 +53,8 @@ export function AttentionPreview({ students }: { students: FlaggedStudent[] }) {
|
|||||||
<span className="block truncate font-semibold text-primary">{student.fullName}</span>
|
<span className="block truncate font-semibold text-primary">{student.fullName}</span>
|
||||||
<span className="block truncate text-sm text-secondary">{student.groupName}</span>
|
<span className="block truncate text-sm text-secondary">{student.groupName}</span>
|
||||||
</span>
|
</span>
|
||||||
<span className="sr-only">{student.worst.gravedad === 'urgente' ? 'Urgente:' : 'A vigilar:'}</span>
|
<span className="sr-only">{student.worst.gravedad === 'urgente' ? t('attentionPreview.urgent') : t('attentionPreview.watch')}</span>
|
||||||
<AlertTag severity={student.worst.gravedad}>{student.worst.etiqueta}</AlertTag>
|
<AlertTag severity={student.worst.gravedad}>{alertLabel(student.worst)}</AlertTag>
|
||||||
</Link>
|
</Link>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -2,11 +2,14 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
|
|||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
import { Link, useNavigate } from '@tanstack/react-router'
|
||||||
import type { CreateFirstGroup } from '@gruperly/shared'
|
import type { CreateFirstGroup } from '@gruperly/shared'
|
||||||
import { ChevronLeft } from 'lucide-react'
|
import { ChevronLeft } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
import { errorMessage } from '../../i18n'
|
||||||
import { createGroup } from '../../lib/api'
|
import { createGroup } from '../../lib/api'
|
||||||
import { GroupForm } from './GroupForm'
|
import { GroupForm } from './GroupForm'
|
||||||
|
|
||||||
export function CreateGroupView() {
|
export function CreateGroupView() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { t } = useTranslation('groups')
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
const create = useMutation({
|
const create = useMutation({
|
||||||
@@ -24,16 +27,16 @@ export function CreateGroupView() {
|
|||||||
className="mb-6 hidden items-center gap-1 text-sm font-medium text-foreground/70 transition-colors hover:text-primary lg:inline-flex"
|
className="mb-6 hidden items-center gap-1 text-sm font-medium text-foreground/70 transition-colors hover:text-primary lg:inline-flex"
|
||||||
>
|
>
|
||||||
<ChevronLeft className="size-4" />
|
<ChevronLeft className="size-4" />
|
||||||
Grupos
|
{t('title')}
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
<GroupForm
|
<GroupForm
|
||||||
heading="Nuevo grupo"
|
heading={t('create.heading')}
|
||||||
description="Definí los datos de la clase que vas a cobrar. Después siempre podés editarlos."
|
description={t('create.description')}
|
||||||
submitLabel="Crear grupo"
|
submitLabel={t('create.submit')}
|
||||||
isSubmitting={create.isPending}
|
isSubmitting={create.isPending}
|
||||||
errorMessage={
|
errorMessage={
|
||||||
create.isError ? 'No pudimos crear el grupo. Revisá los datos e intentá de nuevo.' : null
|
create.isError ? errorMessage(create.error, t('create.error')) : null
|
||||||
}
|
}
|
||||||
onSubmit={(values) => create.mutate(values)}
|
onSubmit={(values) => create.mutate(values)}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { AttentionMember, GroupListItem } from '@gruperly/shared'
|
import type { AttentionMember, GroupListItem } from '@gruperly/shared'
|
||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { AvatarRow } from './AvatarRow'
|
import { AvatarRow } from './AvatarRow'
|
||||||
import { groupStatus, type GroupStatus } from './card'
|
import { groupStatus, type GroupStatus } from './card'
|
||||||
@@ -22,11 +23,12 @@ type GroupCardProps = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function GroupCard({ group, members }: GroupCardProps) {
|
export function GroupCard({ group, members }: GroupCardProps) {
|
||||||
|
const { t } = useTranslation('groups')
|
||||||
const status = members ? groupStatus(members, group.capacity, group.attendeesCount) : null
|
const status = members ? groupStatus(members, group.capacity, group.attendeesCount) : null
|
||||||
const occupancy =
|
const occupancy =
|
||||||
group.capacity === null
|
group.capacity === null
|
||||||
? `${group.attendeesCount} ${group.attendeesCount === 1 ? 'alumno' : 'alumnos'}`
|
? t('card.students', { count: group.attendeesCount })
|
||||||
: `${group.attendeesCount} de ${group.capacity} lugares ocupados`
|
: t('card.occupancy', { count: group.attendeesCount, capacity: group.capacity })
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
|
|||||||
@@ -3,10 +3,11 @@ import { zodResolver } from '@hookform/resolvers/zod'
|
|||||||
import type { BillingType, CountryCode, CreateFirstGroup, WeekDay } from '@gruperly/shared'
|
import type { BillingType, CountryCode, CreateFirstGroup, WeekDay } from '@gruperly/shared'
|
||||||
import { CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared'
|
import { CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared'
|
||||||
import { ArrowLeft, Check, Loader2 } from 'lucide-react'
|
import { ArrowLeft, Check, Loader2 } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { sortWeekDays } from '../../lib/format'
|
import { sortWeekDays } from '../../lib/format'
|
||||||
import { cn } from '../../lib/utils'
|
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'
|
import { BILLING_TYPES, WEEK_DAYS } from '../onboarding/constants'
|
||||||
|
|
||||||
type GroupFormProps = {
|
type GroupFormProps = {
|
||||||
heading: string
|
heading: string
|
||||||
@@ -30,6 +31,7 @@ export function GroupForm({
|
|||||||
onSubmit,
|
onSubmit,
|
||||||
onBack,
|
onBack,
|
||||||
}: GroupFormProps) {
|
}: GroupFormProps) {
|
||||||
|
const { t } = useTranslation(['groups', 'common'])
|
||||||
// The price starts empty on purpose: a pre-filled $0 got submitted as is and
|
// The price starts empty on purpose: a pre-filled $0 got submitted as is and
|
||||||
// the group ended up unable to charge. The capacity starts at a typical
|
// the group ended up unable to charge. The capacity starts at a typical
|
||||||
// class size instead of 1, which had to be overwritten every time.
|
// class size instead of 1, which had to be overwritten every time.
|
||||||
@@ -76,21 +78,21 @@ export function GroupForm({
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="name">Nombre del grupo</Label>
|
<Label htmlFor="name">{t('form.name')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="name"
|
id="name"
|
||||||
autoFocus
|
autoFocus
|
||||||
placeholder="Ej: Yoga Vinyasa · Nivel 1"
|
placeholder={t('form.namePlaceholder')}
|
||||||
invalid={!!errors.name}
|
invalid={!!errors.name}
|
||||||
{...register('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>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label>Días de clase</Label>
|
<Label>{t('form.days')}</Label>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
{WEEK_DAY_CHIPS.map(({ value, label }) => {
|
{WEEK_DAYS.map((value) => {
|
||||||
const isActive = days.includes(value)
|
const isActive = days.includes(value)
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
@@ -105,28 +107,28 @@ export function GroupForm({
|
|||||||
: 'border-border bg-surface text-primary hover:bg-primary-soft',
|
: 'border-border bg-surface text-primary hover:bg-primary-soft',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{label}
|
{t(`common:weekDayShort.${value}`)}
|
||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
{errors.days ? <p className="mt-1 text-sm text-danger">{errors.days.message}</p> : null}
|
<FieldError message={errors.days?.message} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="time">Horario</Label>
|
<Label htmlFor="time">{t('form.time')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="time"
|
id="time"
|
||||||
type="time"
|
type="time"
|
||||||
invalid={!!errors.time}
|
invalid={!!errors.time}
|
||||||
{...register('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>
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
<div className="grid grid-cols-2 gap-3">
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="capacity">Cupo máximo</Label>
|
<Label htmlFor="capacity">{t('form.capacity')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="capacity"
|
id="capacity"
|
||||||
type="number"
|
type="number"
|
||||||
@@ -136,13 +138,11 @@ export function GroupForm({
|
|||||||
invalid={!!errors.capacity}
|
invalid={!!errors.capacity}
|
||||||
{...register('capacity', { valueAsNumber: true })}
|
{...register('capacity', { valueAsNumber: true })}
|
||||||
/>
|
/>
|
||||||
{errors.capacity ? (
|
<FieldError message={errors.capacity?.message} />
|
||||||
<p className="mt-1 text-sm text-danger">{errors.capacity.message}</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="price">Precio</Label>
|
<Label htmlFor="price">{t('form.price')}</Label>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-base text-foreground/50 sm:text-sm">
|
<span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-base text-foreground/50 sm:text-sm">
|
||||||
$
|
$
|
||||||
@@ -153,22 +153,20 @@ export function GroupForm({
|
|||||||
inputMode="decimal"
|
inputMode="decimal"
|
||||||
min={0}
|
min={0}
|
||||||
step="0.01"
|
step="0.01"
|
||||||
placeholder="Por alumno"
|
placeholder={t('form.pricePlaceholder')}
|
||||||
className="pl-7"
|
className="pl-7"
|
||||||
invalid={!!errors.price}
|
invalid={!!errors.price}
|
||||||
{...register('price', { valueAsNumber: true })}
|
{...register('price', { valueAsNumber: true })}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{errors.price ? (
|
<FieldError message={errors.price?.message} />
|
||||||
<p className="mt-1 text-sm text-danger">{errors.price.message}</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label>Tipo de cobro</Label>
|
<Label>{t('form.billingType')}</Label>
|
||||||
<div className="grid grid-cols-2 gap-2">
|
<div className="grid grid-cols-2 gap-2">
|
||||||
{BILLING_TYPES.map(({ value, label, hint }) => {
|
{BILLING_TYPES.map((value) => {
|
||||||
const isActive = billingType === value
|
const isActive = billingType === value
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
@@ -189,9 +187,9 @@ export function GroupForm({
|
|||||||
isActive ? 'text-accent' : 'text-primary',
|
isActive ? 'text-accent' : 'text-primary',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{label}
|
{t(`common:billingType.${value}`)}
|
||||||
</span>
|
</span>
|
||||||
<span className="block text-xs text-foreground/50">{hint}</span>
|
<span className="block text-xs text-foreground/50">{t(`common:billingTypeHint.${value}`)}</span>
|
||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
@@ -199,7 +197,7 @@ export function GroupForm({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="dueDay">Día de vencimiento</Label>
|
<Label htmlFor="dueDay">{t('form.dueDay')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="dueDay"
|
id="dueDay"
|
||||||
type="number"
|
type="number"
|
||||||
@@ -211,11 +209,9 @@ export function GroupForm({
|
|||||||
{...register('dueDay', { valueAsNumber: true })}
|
{...register('dueDay', { valueAsNumber: true })}
|
||||||
/>
|
/>
|
||||||
<p className="mt-1 text-xs text-foreground/50">
|
<p className="mt-1 text-xs text-foreground/50">
|
||||||
Los cobros vencerán el día {isFinite(dueDay) && dueDay ? dueDay : '1'} de cada mes.
|
{t('form.dueDayHint', { day: isFinite(dueDay) && dueDay ? dueDay : 1 })}
|
||||||
</p>
|
</p>
|
||||||
{errors.dueDay ? (
|
<FieldError message={errors.dueDay?.message} />
|
||||||
<p className="mt-1 text-sm text-danger">{errors.dueDay.message}</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{errorMessage ? (
|
{errorMessage ? (
|
||||||
@@ -226,12 +222,12 @@ export function GroupForm({
|
|||||||
{onBack ? (
|
{onBack ? (
|
||||||
<Button variant="outline" onClick={onBack} disabled={isSubmitting}>
|
<Button variant="outline" onClick={onBack} disabled={isSubmitting}>
|
||||||
<ArrowLeft className="size-4" />
|
<ArrowLeft className="size-4" />
|
||||||
Volver
|
{t('common:actions.back')}
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
<Button type="submit" variant="primary" className="flex-1" disabled={isSubmitting}>
|
<Button type="submit" variant="primary" className="flex-1" disabled={isSubmitting}>
|
||||||
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
||||||
{isSubmitting ? 'Creando…' : submitLabel}
|
{isSubmitting ? t('form.submitting') : submitLabel}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { CalendarPlus, Loader2, Plus } from 'lucide-react'
|
import { CalendarPlus, Loader2, Plus } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { Button } from '../../components/ui'
|
import { Button } from '../../components/ui'
|
||||||
import { getGroups } from '../../lib/api'
|
import { getGroups } from '../../lib/api'
|
||||||
import { flaggedStudents } from '../attention/attention'
|
import { flaggedStudents } from '../attention/attention'
|
||||||
@@ -12,6 +13,7 @@ import { NewGroupFab } from './NewGroupFab'
|
|||||||
|
|
||||||
export function GroupsView() {
|
export function GroupsView() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { t } = useTranslation(['groups', 'common'])
|
||||||
const groupsQuery = useQuery({
|
const groupsQuery = useQuery({
|
||||||
queryKey: ['groups'],
|
queryKey: ['groups'],
|
||||||
queryFn: getGroups,
|
queryFn: getGroups,
|
||||||
@@ -24,21 +26,21 @@ export function GroupsView() {
|
|||||||
return (
|
return (
|
||||||
// The FAB floats over the last card: 88px of room so it can be read.
|
// The FAB floats over the last card: 88px of room so it can be read.
|
||||||
<section className="pb-[88px]">
|
<section className="pb-[88px]">
|
||||||
<h1 className="text-2xl font-bold text-primary">Grupos</h1>
|
<h1 className="text-2xl font-bold text-primary">{t('title')}</h1>
|
||||||
{hasGroups ? <p className="mt-1 text-sm text-secondary">{groupsSummary(groups)}</p> : null}
|
{hasGroups ? <p className="mt-1 text-sm text-secondary">{groupsSummary(groups)}</p> : null}
|
||||||
|
|
||||||
{groupsQuery.isPending ? (
|
{groupsQuery.isPending ? (
|
||||||
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
||||||
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
||||||
<span className="sr-only">Cargando grupos</span>
|
<span className="sr-only">{t('loading')}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{groupsQuery.isError ? (
|
{groupsQuery.isError ? (
|
||||||
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
<p>No pudimos cargar tus grupos.</p>
|
<p>{t('loadError')}</p>
|
||||||
<Button variant="outline" size="sm" onClick={() => void groupsQuery.refetch()}>
|
<Button variant="outline" size="sm" onClick={() => void groupsQuery.refetch()}>
|
||||||
Reintentar
|
{t('common:actions.retry')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -50,9 +52,9 @@ export function GroupsView() {
|
|||||||
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg">
|
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg">
|
||||||
<CalendarPlus className="size-7" aria-hidden="true" />
|
<CalendarPlus className="size-7" aria-hidden="true" />
|
||||||
</span>
|
</span>
|
||||||
<p className="mt-4 text-base font-semibold text-primary">Todavía no tenés grupos</p>
|
<p className="mt-4 text-base font-semibold text-primary">{t('empty.title')}</p>
|
||||||
<p className="mx-auto mt-1.5 max-w-[30ch] text-sm leading-relaxed text-secondary">
|
<p className="mx-auto mt-1.5 max-w-[30ch] text-sm leading-relaxed text-secondary">
|
||||||
Creá tu primer grupo y empezá a cobrar las cuotas de tus alumnos.
|
{t('empty.description')}
|
||||||
</p>
|
</p>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
@@ -60,7 +62,7 @@ export function GroupsView() {
|
|||||||
onClick={() => void navigate({ to: '/groups/new' })}
|
onClick={() => void navigate({ to: '/groups/new' })}
|
||||||
>
|
>
|
||||||
<Plus className="size-4" />
|
<Plus className="size-4" />
|
||||||
Crear primer grupo
|
{t('empty.cta')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -74,7 +76,7 @@ export function GroupsView() {
|
|||||||
id="my-groups-title"
|
id="my-groups-title"
|
||||||
className="text-xs font-semibold tracking-wider text-secondary uppercase"
|
className="text-xs font-semibold tracking-wider text-secondary uppercase"
|
||||||
>
|
>
|
||||||
Mis grupos
|
{t('myGroups')}
|
||||||
</h2>
|
</h2>
|
||||||
<div className="mt-2 grid gap-3 lg:grid-cols-2">
|
<div className="mt-2 grid gap-3 lg:grid-cols-2">
|
||||||
{groups.map((group) => (
|
{groups.map((group) => (
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { Plus } from 'lucide-react'
|
import { Plus } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useCollapseOnScroll } from '../../hooks/useCollapseOnScroll'
|
import { useCollapseOnScroll } from '../../hooks/useCollapseOnScroll'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
|
|
||||||
@@ -9,11 +10,12 @@ import { cn } from '../../lib/utils'
|
|||||||
accessible name never changes. `motion-reduce` swaps without animating. */
|
accessible name never changes. `motion-reduce` swaps without animating. */
|
||||||
export function NewGroupFab() {
|
export function NewGroupFab() {
|
||||||
const collapsed = useCollapseOnScroll()
|
const collapsed = useCollapseOnScroll()
|
||||||
|
const { t } = useTranslation('groups')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
to="/groups/new"
|
to="/groups/new"
|
||||||
aria-label="Nuevo grupo"
|
aria-label={t('newGroup')}
|
||||||
className="fixed right-4 bottom-[calc(3.5rem+env(safe-area-inset-bottom)+1rem)] z-40 inline-flex h-14 items-center rounded-[18px] bg-accent px-4 font-semibold text-on-accent shadow-[0_10px_28px_-8px_rgb(37_68_234/0.65)] transition-colors hover:bg-accent-strong focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none lg:right-8 lg:bottom-8"
|
className="fixed right-4 bottom-[calc(3.5rem+env(safe-area-inset-bottom)+1rem)] z-40 inline-flex h-14 items-center rounded-[18px] bg-accent px-4 font-semibold text-on-accent shadow-[0_10px_28px_-8px_rgb(37_68_234/0.65)] transition-colors hover:bg-accent-strong focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none lg:right-8 lg:bottom-8"
|
||||||
>
|
>
|
||||||
<Plus className="size-6 shrink-0" strokeWidth={2.25} aria-hidden="true" />
|
<Plus className="size-6 shrink-0" strokeWidth={2.25} aria-hidden="true" />
|
||||||
@@ -24,7 +26,7 @@ export function NewGroupFab() {
|
|||||||
collapsed ? 'ml-0 max-w-0 opacity-0' : 'ml-2 max-w-40 opacity-100',
|
collapsed ? 'ml-0 max-w-0 opacity-0' : 'ml-2 max-w-40 opacity-100',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
Nuevo grupo
|
{t('newGroup')}
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { ArrowLeft, Loader2 } from 'lucide-react'
|
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||||
|
import { Trans, useTranslation } from 'react-i18next'
|
||||||
import { cn } from '../../../lib/utils'
|
import { cn } from '../../../lib/utils'
|
||||||
import { useAddAttendee } from './AddAttendeeProvider'
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
import { BulkCapacityModal } from './BulkCapacityModal'
|
import { BulkCapacityModal } from './BulkCapacityModal'
|
||||||
@@ -8,13 +9,14 @@ import { CapacityModal } from './CapacityModal'
|
|||||||
import { QuickAddForm } from './QuickAddForm'
|
import { QuickAddForm } from './QuickAddForm'
|
||||||
|
|
||||||
const TABS = [
|
const TABS = [
|
||||||
{ value: 'quick' as const, label: 'Carga Rápida (Individual)' },
|
{ value: 'quick' as const, label: 'tabs.quick' as const },
|
||||||
{ value: 'bulk' as const, label: 'Carga Masiva (CSV / Excel)' },
|
{ value: 'bulk' as const, label: 'tabs.bulk' as const },
|
||||||
]
|
]
|
||||||
|
|
||||||
export function AddAttendeePage() {
|
export function AddAttendeePage() {
|
||||||
const { groupId, groupName, attendeesTotal, capacity, groupPending, activeTab, setActiveTab } =
|
const { groupId, groupName, attendeesTotal, capacity, groupPending, activeTab, setActiveTab } =
|
||||||
useAddAttendee()
|
useAddAttendee()
|
||||||
|
const { t } = useTranslation('groupAdd')
|
||||||
|
|
||||||
if (groupPending) {
|
if (groupPending) {
|
||||||
return (
|
return (
|
||||||
@@ -32,24 +34,26 @@ export function AddAttendeePage() {
|
|||||||
className="hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
className="hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
||||||
>
|
>
|
||||||
<ArrowLeft className="size-4" />
|
<ArrowLeft className="size-4" />
|
||||||
<span>Volver al grupo</span>
|
<span>{t('back')}</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
<header className="space-y-1">
|
<header className="space-y-1">
|
||||||
<h1 className="text-2xl font-bold text-primary">Agregar miembros</h1>
|
<h1 className="text-2xl font-bold text-primary">{t('title')}</h1>
|
||||||
<p className="text-sm text-foreground/60">
|
<p className="text-sm text-foreground/60">
|
||||||
{groupName ? (
|
{groupName ? (
|
||||||
<>
|
<Trans
|
||||||
Sumá miembros a <span className="font-medium text-primary">{groupName}</span> de forma
|
t={t}
|
||||||
individual o masiva desde una lista.
|
i18nKey="subtitleGroup"
|
||||||
</>
|
values={{ group: groupName }}
|
||||||
|
components={{ strong: <span className="font-medium text-primary" /> }}
|
||||||
|
/>
|
||||||
) : (
|
) : (
|
||||||
'Sumá miembros de forma individual o masiva desde una lista.'
|
t('subtitle')
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
{capacity != null ? (
|
{capacity != null ? (
|
||||||
<p className="text-xs text-foreground/50">
|
<p className="text-xs text-foreground/50">
|
||||||
{attendeesTotal} de {capacity} lugares ocupados.
|
{t('occupancy', { count: attendeesTotal, capacity })}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</header>
|
</header>
|
||||||
@@ -68,7 +72,7 @@ export function AddAttendeePage() {
|
|||||||
: 'text-foreground/60 hover:text-primary',
|
: 'text-foreground/60 hover:text-primary',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{tab.label}
|
{t(tab.label)}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,13 +3,17 @@ import type { ReactNode } from 'react'
|
|||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import type {
|
import type {
|
||||||
|
BulkCreateAttendeesResult,
|
||||||
CreateAttendee,
|
CreateAttendee,
|
||||||
CreateAttendeeResult,
|
CreateAttendeeResult,
|
||||||
CreateGroupWaitlistEntry,
|
CreateGroupWaitlistEntry,
|
||||||
GroupWaitlistEntryDto,
|
GroupWaitlistEntryDto,
|
||||||
GroupWaitlistList,
|
GroupWaitlistList,
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { useToast } from '../../../components/ui'
|
import { useToast } from '../../../components/ui'
|
||||||
|
import { errorMessage } from '../../../i18n'
|
||||||
|
import { i18n } from '../../../i18n/instance'
|
||||||
import {
|
import {
|
||||||
addToGroupWaitlist,
|
addToGroupWaitlist,
|
||||||
ApiError,
|
ApiError,
|
||||||
@@ -72,6 +76,7 @@ const AddAttendeeContext = createContext<AddAttendeeContextValue | null>(null)
|
|||||||
export function AddAttendeeProvider({ groupId, children }: { groupId: string; children: ReactNode }) {
|
export function AddAttendeeProvider({ groupId, children }: { groupId: string; children: ReactNode }) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
|
useTranslation()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const [activeTab, setActiveTab] = useState<AddAttendeeTab>('quick')
|
const [activeTab, setActiveTab] = useState<AddAttendeeTab>('quick')
|
||||||
@@ -116,11 +121,12 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
|
|||||||
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleCreateSuccess = (result: CreateAttendeeResult) => {
|
const handleCreateSuccess = (result: CreateAttendeeResult, payload: CreateAttendee) => {
|
||||||
if (result.outcome === 'created') {
|
if (result.outcome === 'created') {
|
||||||
toast.success(`Miembro ${result.attendee.fullName} agregado con éxito.`)
|
toast.success(i18n.t('groupAdd:toast.created', { name: result.attendee.fullName }))
|
||||||
} else {
|
} else {
|
||||||
toast.info(result.message)
|
const name = `${payload.firstName} ${payload.lastName ?? ''}`.trim()
|
||||||
|
toast.info(i18n.t('groupAdd:toast.waitlisted', { name }))
|
||||||
}
|
}
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||||
// Si era alguien de otro grupo, su ficha allá ahora lo muestra también acá.
|
// Si era alguien de otro grupo, su ficha allá ahora lo muestra también acá.
|
||||||
@@ -142,10 +148,10 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
|
|||||||
// refresca la búsqueda para que aparezca la opción de agregar a esa persona.
|
// refresca la búsqueda para que aparezca la opción de agregar a esa persona.
|
||||||
if (err instanceof ApiError && err.problem?.code === 'person_exists') {
|
if (err instanceof ApiError && err.problem?.code === 'person_exists') {
|
||||||
void queryClient.invalidateQueries({ queryKey: ['person-lookup', groupId] })
|
void queryClient.invalidateQueries({ queryKey: ['person-lookup', groupId] })
|
||||||
toast.info('Ya tenés registrada a una persona con este teléfono. Podés agregarla a este grupo.')
|
toast.info(i18n.t('groupAdd:toast.personExists'))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
toast.error(err.message || 'Error al agregar miembro.')
|
toast.error(errorMessage(err, i18n.t('groupAdd:toast.addError')))
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -153,7 +159,7 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
|
|||||||
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload, { allowOverflow: true }),
|
mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload, { allowOverflow: true }),
|
||||||
onSuccess: handleCreateSuccess,
|
onSuccess: handleCreateSuccess,
|
||||||
onError: (err: Error) => {
|
onError: (err: Error) => {
|
||||||
toast.error(err.message || 'Error al agregar miembro.')
|
toast.error(errorMessage(err, i18n.t('groupAdd:toast.addError')))
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -187,7 +193,7 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
|
|||||||
return { previousWaitlist }
|
return { previousWaitlist }
|
||||||
},
|
},
|
||||||
onSuccess: (entry) => {
|
onSuccess: (entry) => {
|
||||||
toast.info(`${entry.fullName} fue agregado a la lista de espera del grupo.`)
|
toast.info(i18n.t('groupAdd:toast.waitlisted', { name: entry.fullName }))
|
||||||
invalidateGroupQueries()
|
invalidateGroupQueries()
|
||||||
goBackToGroup()
|
goBackToGroup()
|
||||||
},
|
},
|
||||||
@@ -196,9 +202,9 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
|
|||||||
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], context.previousWaitlist)
|
queryClient.setQueryData<GroupWaitlistList>(['group-waitlist', groupId], context.previousWaitlist)
|
||||||
}
|
}
|
||||||
if (err instanceof ApiError && err.problem?.code === 'already_waitlisted') {
|
if (err instanceof ApiError && err.problem?.code === 'already_waitlisted') {
|
||||||
toast.info('Este número ya está en la lista de espera del grupo.')
|
toast.info(i18n.t('groupAdd:toast.alreadyWaitlisted'))
|
||||||
} else {
|
} else {
|
||||||
toast.error(err.message || 'Error al agregar a la lista de espera.')
|
toast.error(errorMessage(err, i18n.t('groupAdd:toast.waitlistError')))
|
||||||
}
|
}
|
||||||
closeCapacityFlow()
|
closeCapacityFlow()
|
||||||
},
|
},
|
||||||
@@ -207,14 +213,14 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
|
|||||||
const bulkImportMutation = useMutation({
|
const bulkImportMutation = useMutation({
|
||||||
mutationFn: (rows: BulkAttendeeRow[]) => bulkCreateAttendees(groupId, { attendees: rows }),
|
mutationFn: (rows: BulkAttendeeRow[]) => bulkCreateAttendees(groupId, { attendees: rows }),
|
||||||
onSuccess: (res) => {
|
onSuccess: (res) => {
|
||||||
toast.success(res.message)
|
toast.success(importSummary(res))
|
||||||
setParsedContacts([])
|
setParsedContacts([])
|
||||||
setFileName(null)
|
setFileName(null)
|
||||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||||
goBackToGroup()
|
goBackToGroup()
|
||||||
},
|
},
|
||||||
onError: (err: Error) => {
|
onError: (err: Error) => {
|
||||||
toast.error(err.message || 'Error al importar miembros.')
|
toast.error(errorMessage(err, i18n.t('groupAdd:toast.importError')))
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -235,7 +241,7 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
|
|||||||
|
|
||||||
const runBulkImport = () => {
|
const runBulkImport = () => {
|
||||||
if (validRows.length === 0) {
|
if (validRows.length === 0) {
|
||||||
toast.error('No hay miembros válidos para importar.')
|
toast.error(i18n.t('groupAdd:bulk.noValidRows'))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
bulkImportMutation.mutate(validRows)
|
bulkImportMutation.mutate(validRows)
|
||||||
@@ -243,7 +249,7 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
|
|||||||
|
|
||||||
const requestBulkImport = () => {
|
const requestBulkImport = () => {
|
||||||
if (validRows.length === 0) {
|
if (validRows.length === 0) {
|
||||||
toast.error('No hay miembros válidos para importar.')
|
toast.error(i18n.t('groupAdd:bulk.noValidRows'))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (capacity != null && attendeesTotal + validRows.length > capacity) {
|
if (capacity != null && attendeesTotal + validRows.length > capacity) {
|
||||||
@@ -310,3 +316,16 @@ export function useAddAttendee() {
|
|||||||
}
|
}
|
||||||
return context
|
return context
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The bulk import summary, built from the counts (the API's `message` is Spanish only). */
|
||||||
|
function importSummary(result: BulkCreateAttendeesResult): string {
|
||||||
|
return [
|
||||||
|
i18n.t('groupAdd:toast.imported', { count: result.createdCount }),
|
||||||
|
result.linkedCount > 0 ? i18n.t('groupAdd:toast.importedLinked', { count: result.linkedCount }) : null,
|
||||||
|
result.duplicatesCount > 0
|
||||||
|
? i18n.t('groupAdd:toast.importedDuplicates', { count: result.duplicatesCount })
|
||||||
|
: null,
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ')
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Check } from 'lucide-react'
|
import { Check } from 'lucide-react'
|
||||||
|
import { Trans, useTranslation } from 'react-i18next'
|
||||||
import { Button, Modal } from '../../../components/ui'
|
import { Button, Modal } from '../../../components/ui'
|
||||||
import { useAddAttendee } from './AddAttendeeProvider'
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
|
|
||||||
@@ -12,24 +13,28 @@ export function BulkCapacityModal() {
|
|||||||
groupName,
|
groupName,
|
||||||
capacity,
|
capacity,
|
||||||
} = useAddAttendee()
|
} = useAddAttendee()
|
||||||
|
const { t } = useTranslation(['groupAdd', 'common'])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
isOpen={isBulkCapacityModalOpen}
|
isOpen={isBulkCapacityModalOpen}
|
||||||
onClose={closeBulkCapacityModal}
|
onClose={closeBulkCapacityModal}
|
||||||
title="Aviso de cupo"
|
title={t('bulkCapacity.title')}
|
||||||
description="La carga supera el cupo del grupo."
|
description={t('bulkCapacity.description')}
|
||||||
maxWidth="md"
|
maxWidth="md"
|
||||||
>
|
>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<p className="text-sm text-foreground/70">
|
<p className="text-sm text-foreground/70">
|
||||||
Estás por importar <strong className="text-primary">{validRowsCount}</strong> miembro(s), pero el
|
<Trans
|
||||||
grupo ya tiene <strong className="text-primary">{attendeesTotal}</strong> inscrito(s) y su cupo es
|
t={t}
|
||||||
de <strong className="text-primary">{capacity}</strong>. ¿Deseas importarlos de todos modos?
|
i18nKey="bulkCapacity.body"
|
||||||
|
values={{ rows: validRowsCount, current: attendeesTotal, capacity }}
|
||||||
|
components={{ strong: <strong className="text-primary" /> }}
|
||||||
|
/>
|
||||||
</p>
|
</p>
|
||||||
<div className="flex flex-col-reverse gap-2.5 pt-2 sm:flex-row sm:items-center sm:justify-end">
|
<div className="flex flex-col-reverse gap-2.5 pt-2 sm:flex-row sm:items-center sm:justify-end">
|
||||||
<Button variant="ghost" onClick={closeBulkCapacityModal} className="w-full sm:w-auto">
|
<Button variant="ghost" onClick={closeBulkCapacityModal} className="w-full sm:w-auto">
|
||||||
Cancelar
|
{t('common:actions.cancel')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
@@ -37,7 +42,7 @@ export function BulkCapacityModal() {
|
|||||||
className="w-full sm:w-auto"
|
className="w-full sm:w-auto"
|
||||||
>
|
>
|
||||||
<Check className="size-4" />
|
<Check className="size-4" />
|
||||||
Importar de todos modos
|
{t('bulkCapacity.confirm')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useRef } from 'react'
|
import { useRef } from 'react'
|
||||||
import { Check, Download, FileSpreadsheet, Loader2, Trash2, UploadCloud } from 'lucide-react'
|
import { Check, Download, FileSpreadsheet, Loader2, Trash2, UploadCloud } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
import { Badge, Button, useToast } from '../../../components/ui'
|
import { Badge, Button, useToast } from '../../../components/ui'
|
||||||
import {
|
import {
|
||||||
downloadAttendeeTemplateCsv,
|
downloadAttendeeTemplateCsv,
|
||||||
@@ -28,12 +29,13 @@ export function BulkImportPanel() {
|
|||||||
requestBulkImport,
|
requestBulkImport,
|
||||||
} = useAddAttendee()
|
} = useAddAttendee()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
|
const { t } = useTranslation(['groupAdd', 'common'])
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
const processFile = async (file: File) => {
|
const processFile = async (file: File) => {
|
||||||
const fileExtension = file.name.split('.').pop()?.toLowerCase()
|
const fileExtension = file.name.split('.').pop()?.toLowerCase()
|
||||||
if (!['csv', 'xlsx', 'xls', 'txt'].includes(fileExtension ?? '')) {
|
if (!['csv', 'xlsx', 'xls', 'txt'].includes(fileExtension ?? '')) {
|
||||||
toast.error('Formato no compatible. Sube un archivo .csv o .xlsx')
|
toast.error(t('bulk.unsupported'))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,14 +49,14 @@ export function BulkImportPanel() {
|
|||||||
|
|
||||||
const contacts = normalizeRowsToContacts(rawRows)
|
const contacts = normalizeRowsToContacts(rawRows)
|
||||||
if (contacts.length === 0) {
|
if (contacts.length === 0) {
|
||||||
toast.error('No se detectaron contactos en el archivo.')
|
toast.error(t('bulk.noContacts'))
|
||||||
} else {
|
} else {
|
||||||
setParsedContacts(contacts)
|
setParsedContacts(contacts)
|
||||||
const validCount = contacts.filter((c) => c.isValid).length
|
const validCount = contacts.filter((c) => c.isValid).length
|
||||||
toast.info(`Se detectaron ${contacts.length} filas (${validCount} válidas).`)
|
toast.info(t('bulk.detected', { count: contacts.length, valid: validCount }))
|
||||||
}
|
}
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
const message = err instanceof Error ? err.message : 'Error al procesar el archivo.'
|
const message = err instanceof Error ? err.message : t('bulk.processError')
|
||||||
toast.error(message)
|
toast.error(message)
|
||||||
} finally {
|
} finally {
|
||||||
setIsParsingFile(false)
|
setIsParsingFile(false)
|
||||||
@@ -103,9 +105,9 @@ export function BulkImportPanel() {
|
|||||||
/>
|
/>
|
||||||
<UploadCloud className="mb-2 size-10 text-accent" />
|
<UploadCloud className="mb-2 size-10 text-accent" />
|
||||||
<p className="text-sm font-semibold text-primary">
|
<p className="text-sm font-semibold text-primary">
|
||||||
Arrastra tu archivo aquí o haz clic para seleccionarlo
|
{t('bulk.dropzone')}
|
||||||
</p>
|
</p>
|
||||||
<p className="mt-1 text-xs text-foreground/60">Formatos soportados: CSV (.csv) o Excel (.xlsx)</p>
|
<p className="mt-1 text-xs text-foreground/60">{t('bulk.formats')}</p>
|
||||||
|
|
||||||
{fileName ? (
|
{fileName ? (
|
||||||
<div className="mt-3 flex items-center gap-2 rounded-lg border border-border bg-surface px-3 py-1.5 text-xs font-medium text-primary">
|
<div className="mt-3 flex items-center gap-2 rounded-lg border border-border bg-surface px-3 py-1.5 text-xs font-medium text-primary">
|
||||||
@@ -116,21 +118,21 @@ export function BulkImportPanel() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col items-start gap-1 px-1 text-xs sm:flex-row sm:items-center sm:justify-between">
|
<div className="flex flex-col items-start gap-1 px-1 text-xs sm:flex-row sm:items-center sm:justify-between">
|
||||||
<span className="text-foreground/60">¿No tienes el archivo listo? Usa nuestra plantilla.</span>
|
<span className="text-foreground/60">{t('bulk.templateHint')}</span>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={downloadAttendeeTemplateCsv}
|
onClick={downloadAttendeeTemplateCsv}
|
||||||
className="inline-flex shrink-0 items-center gap-1 whitespace-nowrap font-medium text-accent transition-colors hover:text-accent-strong"
|
className="inline-flex shrink-0 items-center gap-1 whitespace-nowrap font-medium text-accent transition-colors hover:text-accent-strong"
|
||||||
>
|
>
|
||||||
<Download className="size-3.5" />
|
<Download className="size-3.5" />
|
||||||
<span>Descargar plantilla CSV</span>
|
<span>{t('bulk.downloadTemplate')}</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isParsingFile ? (
|
{isParsingFile ? (
|
||||||
<div className="flex items-center justify-center gap-2 py-6 text-sm text-foreground/60">
|
<div className="flex items-center justify-center gap-2 py-6 text-sm text-foreground/60">
|
||||||
<Loader2 className="size-4 animate-spin text-accent" />
|
<Loader2 className="size-4 animate-spin text-accent" />
|
||||||
<span>Leyendo y analizando archivo...</span>
|
<span>{t('bulk.parsing')}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
@@ -138,9 +140,9 @@ export function BulkImportPanel() {
|
|||||||
<div className="space-y-3 pt-2">
|
<div className="space-y-3 pt-2">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div className="flex items-center gap-2 text-xs">
|
<div className="flex items-center gap-2 text-xs">
|
||||||
<span className="font-semibold text-primary">Vista Previa:</span>
|
<span className="font-semibold text-primary">{t('bulk.preview')}</span>
|
||||||
<Badge variant="success">{validRowsCount} listos para importar</Badge>
|
<Badge variant="success">{t('bulk.ready', { count: validRowsCount })}</Badge>
|
||||||
{invalidRowsCount > 0 ? <Badge variant="danger">{invalidRowsCount} con errores</Badge> : null}
|
{invalidRowsCount > 0 ? <Badge variant="danger">{t('bulk.withErrors', { count: invalidRowsCount })}</Badge> : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
@@ -152,7 +154,7 @@ export function BulkImportPanel() {
|
|||||||
}}
|
}}
|
||||||
className="h-7 px-2 text-xs text-foreground/50 hover:text-danger"
|
className="h-7 px-2 text-xs text-foreground/50 hover:text-danger"
|
||||||
>
|
>
|
||||||
Limpiar lista
|
{t('bulk.clear')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -160,10 +162,10 @@ export function BulkImportPanel() {
|
|||||||
<table className="w-full text-left text-xs">
|
<table className="w-full text-left text-xs">
|
||||||
<thead className="sticky top-0 border-b border-border bg-surface font-semibold text-foreground/70">
|
<thead className="sticky top-0 border-b border-border bg-surface font-semibold text-foreground/70">
|
||||||
<tr>
|
<tr>
|
||||||
<th className="px-3 py-2">Nombre</th>
|
<th className="px-3 py-2">{t('bulk.name')}</th>
|
||||||
<th className="px-3 py-2">Teléfono</th>
|
<th className="px-3 py-2">{t('bulk.phone')}</th>
|
||||||
<th className="px-3 py-2">Email</th>
|
<th className="px-3 py-2">{t('bulk.email')}</th>
|
||||||
<th className="px-3 py-2">Estado</th>
|
<th className="px-3 py-2">{t('bulk.status')}</th>
|
||||||
<th className="px-2 py-2 text-right" />
|
<th className="px-2 py-2 text-right" />
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -174,16 +176,16 @@ export function BulkImportPanel() {
|
|||||||
className={!contact.isValid ? 'bg-danger-soft/30' : 'hover:bg-primary-soft/30'}
|
className={!contact.isValid ? 'bg-danger-soft/30' : 'hover:bg-primary-soft/30'}
|
||||||
>
|
>
|
||||||
<td className="px-3 py-2 font-medium text-primary">
|
<td className="px-3 py-2 font-medium text-primary">
|
||||||
{contact.fullName || <span className="italic text-danger">Sin nombre</span>}
|
{contact.fullName || <span className="italic text-danger">{t('bulk.noName')}</span>}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-3 py-2 text-foreground/80">
|
<td className="px-3 py-2 text-foreground/80">
|
||||||
{contact.phone || <span className="italic text-danger">Sin teléfono</span>}
|
{contact.phone || <span className="italic text-danger">{t('bulk.noPhone')}</span>}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-3 py-2 text-foreground/60">{contact.email || '—'}</td>
|
<td className="px-3 py-2 text-foreground/60">{contact.email || '—'}</td>
|
||||||
<td className="px-3 py-2">
|
<td className="px-3 py-2">
|
||||||
{contact.isValid ? (
|
{contact.isValid ? (
|
||||||
<Badge variant="success" className="py-0 text-[10px]">
|
<Badge variant="success" className="py-0 text-[10px]">
|
||||||
Válido
|
{t('bulk.valid')}
|
||||||
</Badge>
|
</Badge>
|
||||||
) : (
|
) : (
|
||||||
<Badge variant="danger" className="py-0 text-[10px]" title={contact.error}>
|
<Badge variant="danger" className="py-0 text-[10px]" title={contact.error}>
|
||||||
@@ -196,7 +198,7 @@ export function BulkImportPanel() {
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={() => removeParsedContact(contact.id)}
|
onClick={() => removeParsedContact(contact.id)}
|
||||||
className="rounded p-1 text-foreground/40 transition-colors hover:text-danger"
|
className="rounded p-1 text-foreground/40 transition-colors hover:text-danger"
|
||||||
title="Eliminar fila"
|
title={t('bulk.removeRow')}
|
||||||
>
|
>
|
||||||
<Trash2 className="size-3.5" />
|
<Trash2 className="size-3.5" />
|
||||||
</button>
|
</button>
|
||||||
@@ -209,7 +211,7 @@ export function BulkImportPanel() {
|
|||||||
|
|
||||||
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:items-center sm:justify-end">
|
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:items-center sm:justify-end">
|
||||||
<Button variant="ghost" onClick={cancelAddAttendee} className="w-full sm:w-auto">
|
<Button variant="ghost" onClick={cancelAddAttendee} className="w-full sm:w-auto">
|
||||||
Cancelar
|
{t('common:actions.cancel')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
@@ -218,7 +220,7 @@ export function BulkImportPanel() {
|
|||||||
className="w-full sm:w-auto"
|
className="w-full sm:w-auto"
|
||||||
>
|
>
|
||||||
{isSubmittingBulkImport ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
{isSubmittingBulkImport ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
||||||
<span>Confirmar e Importar ({validRowsCount})</span>
|
<span>{t('bulk.confirm', { count: validRowsCount })}</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Clock, Loader2, UserPlus } from 'lucide-react'
|
import { Clock, Loader2, UserPlus } from 'lucide-react'
|
||||||
|
import { Trans, useTranslation } from 'react-i18next'
|
||||||
import { Button, Modal } from '../../../components/ui'
|
import { Button, Modal } from '../../../components/ui'
|
||||||
import { useAddAttendee } from './AddAttendeeProvider'
|
import { useAddAttendee } from './AddAttendeeProvider'
|
||||||
|
|
||||||
@@ -14,25 +15,30 @@ export function CapacityModal() {
|
|||||||
isSubmittingForcedAttendee,
|
isSubmittingForcedAttendee,
|
||||||
isSubmittingWaitlistEntry,
|
isSubmittingWaitlistEntry,
|
||||||
} = useAddAttendee()
|
} = useAddAttendee()
|
||||||
|
const { t } = useTranslation('groupAdd')
|
||||||
const isBusy = isSubmittingForcedAttendee || isSubmittingWaitlistEntry
|
const isBusy = isSubmittingForcedAttendee || isSubmittingWaitlistEntry
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
isOpen={isCapacityModalOpen}
|
isOpen={isCapacityModalOpen}
|
||||||
onClose={closeCapacityModal}
|
onClose={closeCapacityModal}
|
||||||
title="Cupo alcanzado"
|
title={t('capacity.title')}
|
||||||
description="El grupo llegó a su cupo máximo de miembros."
|
description={t('capacity.description')}
|
||||||
maxWidth="md"
|
maxWidth="md"
|
||||||
>
|
>
|
||||||
{capacityPayload ? (
|
{capacityPayload ? (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<p className="text-sm text-foreground/70">
|
<p className="text-sm text-foreground/70">
|
||||||
El grupo <strong className="text-primary">{groupName}</strong> ya alcanzó su cupo de{' '}
|
<Trans
|
||||||
<strong className="text-primary">{capacity}</strong> miembros. ¿Qué deseas hacer con{' '}
|
t={t}
|
||||||
<strong className="text-primary">
|
i18nKey="capacity.body"
|
||||||
{`${capacityPayload.firstName.trim()} ${(capacityPayload.lastName ?? '').trim()}`.trim()}
|
values={{
|
||||||
</strong>
|
group: groupName ?? '',
|
||||||
?
|
capacity,
|
||||||
|
name: `${capacityPayload.firstName.trim()} ${(capacityPayload.lastName ?? '').trim()}`.trim(),
|
||||||
|
}}
|
||||||
|
components={{ strong: <strong className="text-primary" /> }}
|
||||||
|
/>
|
||||||
</p>
|
</p>
|
||||||
<div className="flex flex-col gap-2.5">
|
<div className="flex flex-col gap-2.5">
|
||||||
<Button
|
<Button
|
||||||
@@ -46,7 +52,7 @@ export function CapacityModal() {
|
|||||||
) : (
|
) : (
|
||||||
<UserPlus className="size-4" />
|
<UserPlus className="size-4" />
|
||||||
)}
|
)}
|
||||||
<span>Agregar de todos modos</span>
|
<span>{t('capacity.force')}</span>
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@@ -59,11 +65,11 @@ export function CapacityModal() {
|
|||||||
) : (
|
) : (
|
||||||
<Clock className="size-4" />
|
<Clock className="size-4" />
|
||||||
)}
|
)}
|
||||||
<span>Sumar a la lista de espera</span>
|
<span>{t('capacity.waitlist')}</span>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-center text-[11px] text-foreground/50">
|
<p className="text-center text-[11px] text-foreground/50">
|
||||||
Si eliges agregarlo de todos modos, el grupo quedará por encima de su cupo.
|
{t('capacity.forceHint')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { UserCheck } from 'lucide-react'
|
import { UserCheck } from 'lucide-react'
|
||||||
|
import { Trans, useTranslation } from 'react-i18next'
|
||||||
import type { PersonSummary } from '@gruperly/shared'
|
import type { PersonSummary } from '@gruperly/shared'
|
||||||
import { Button } from '../../../components/ui'
|
import { Button } from '../../../components/ui'
|
||||||
|
|
||||||
@@ -22,12 +23,13 @@ export function ExistingPersonNotice({
|
|||||||
onUnlink,
|
onUnlink,
|
||||||
onChangePhone,
|
onChangePhone,
|
||||||
}: ExistingPersonNoticeProps) {
|
}: ExistingPersonNoticeProps) {
|
||||||
|
const { t } = useTranslation('groupAdd')
|
||||||
const groupNames = person.groups.map((group) => group.groupName).join(', ')
|
const groupNames = person.groups.map((group) => group.groupName).join(', ')
|
||||||
|
|
||||||
if (alreadyInGroup) {
|
if (alreadyInGroup) {
|
||||||
return (
|
return (
|
||||||
<div role="alert" className="mt-2 rounded-xl bg-danger-soft px-3 py-2.5 text-sm text-danger-fg">
|
<div role="alert" className="mt-2 rounded-xl bg-danger-soft px-3 py-2.5 text-sm text-danger-fg">
|
||||||
{person.fullName} ya es miembro de este grupo.
|
{t('existing.alreadyInGroup', { name: person.fullName })}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -38,30 +40,29 @@ export function ExistingPersonNotice({
|
|||||||
<UserCheck className="mt-0.5 size-4 shrink-0 text-accent-fg" aria-hidden="true" />
|
<UserCheck className="mt-0.5 size-4 shrink-0 text-accent-fg" aria-hidden="true" />
|
||||||
<p className="min-w-0">
|
<p className="min-w-0">
|
||||||
{isLinked ? (
|
{isLinked ? (
|
||||||
<>
|
<Trans t={t} i18nKey="existing.linked" values={{ name: person.fullName }} components={{ strong: <strong /> }} />
|
||||||
Vas a agregar a <strong>{person.fullName}</strong> a este grupo. Sus datos de contacto
|
|
||||||
y notas son los mismos que en sus otros grupos.
|
|
||||||
</>
|
|
||||||
) : (
|
) : (
|
||||||
<>
|
<Trans
|
||||||
Ya tenés a <strong>{person.fullName}</strong> con este teléfono
|
t={t}
|
||||||
{groupNames ? ` (en ${groupNames})` : ''}. ¿Es la misma persona?
|
i18nKey={groupNames ? 'existing.foundInGroups' : 'existing.found'}
|
||||||
</>
|
values={{ name: person.fullName, groups: groupNames }}
|
||||||
|
components={{ strong: <strong /> }}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-2.5 flex flex-wrap justify-end gap-2">
|
<div className="mt-2.5 flex flex-wrap justify-end gap-2">
|
||||||
{isLinked ? (
|
{isLinked ? (
|
||||||
<Button variant="ghost" onClick={onUnlink} size="sm">
|
<Button variant="ghost" onClick={onUnlink} size="sm">
|
||||||
No es esta persona
|
{t('existing.notThisPerson')}
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<Button variant="ghost" onClick={onChangePhone} size="sm">
|
<Button variant="ghost" onClick={onChangePhone} size="sm">
|
||||||
Usar otro teléfono
|
{t('existing.otherPhone')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="primary" onClick={onLink} size="sm">
|
<Button variant="primary" onClick={onLink} size="sm">
|
||||||
Sí, agregarla
|
{t('existing.confirm')}
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user