Compare commits
34 Commits
feat/impro
...
4211d5cf39
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4211d5cf39 | ||
|
|
8cb5fe9b08 | ||
|
|
f4a6f2653f | ||
| bd7712b28e | |||
|
|
2d80af082f | ||
|
|
70ef049f34 | ||
|
|
f0bb02ab73 | ||
|
|
925f1a256d | ||
|
|
70702ba852 | ||
|
|
4d50b46399 | ||
|
|
486fbaf2ca | ||
|
|
b615c17a16 | ||
|
|
243530fab2 | ||
|
|
dfb6951d7c | ||
|
|
e2d9ddf569 | ||
|
|
700b9fb91d | ||
|
|
e3dca305a4 | ||
|
|
7db9414f12 | ||
|
|
13723d5bb9 | ||
|
|
8a5768e0c0 | ||
|
|
ecdbbbbca6 | ||
|
|
96661fb807 | ||
|
|
09647672b8 | ||
|
|
cb872eb8bc | ||
|
|
ff885bddfc | ||
|
|
d21e1c3730 | ||
|
|
f1829fb5a9 | ||
|
|
fc12ec3ae0 | ||
|
|
d397e9663c | ||
|
|
b6f22ae67d | ||
| b22b6da2e1 | |||
|
|
9e4d34b5d8 | ||
|
|
bc5f676cea | ||
| f6a7b7344e |
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
.gitignore
vendored
12
.gitignore
vendored
@@ -6,6 +6,7 @@ npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
.impeccable
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
@@ -149,3 +150,14 @@ apps/backend/generated/
|
||||
# env
|
||||
apps/backend/.env
|
||||
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
|
||||
# archify: solo se versionan el HTML final y el candidate.json; lo intermedio no
|
||||
.archify/**/*.browser-check.json
|
||||
.archify/**/*.delivery.json
|
||||
.archify/**/*.finalize.json
|
||||
.archify/**/*.finalize-summary.json
|
||||
.archify/**/candidate.before-review.json
|
||||
.archify/**/review-*/
|
||||
|
||||
28
AGENTS.md
28
AGENTS.md
@@ -61,26 +61,46 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
||||
3. Sin `BILLING_ENFORCEMENT=on` todo es Pro y los guards no tocan la base (por eso los tests viejos con prisma mockeado no necesitan `billingSubscription`).
|
||||
4. Los webhooks `POST /billing/webhooks/mp/:country` y `POST /billing/webhooks/stripe` son públicos (`isPublicApiRequest`): el adaptador verifica la firma (`x-signature` / `Stripe-Signature`) y solo dice qué suscripción sincronizar; se deduplica por `(source, dedupeKey)` y se le vuelve a pedir todo al proveedor. El polling (`ReconcileSubscriptions` + sync on-read en `GET /billing/status` si está `PENDING`) es el fallback.
|
||||
5. `402` con `plan_limit_reached` / `plan_feature_required` / `plan_read_only`: la web abre el aviso de Pro desde el `MutationCache` de `main.tsx`.
|
||||
6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp.
|
||||
6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp. El paso vive en `?step=` (el back del dispositivo retrocede un paso) y lo que pide la URL pasa por `effectiveStep`: sin plan no se pasa de Plan y con el grupo ya creado no se vuelve al formulario. Los callbacks (`?mp=`, `?wa=`, `?sub=`) navegan con `replace` al paso que corresponde.
|
||||
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
||||
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
|
||||
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).
|
||||
- **App de alumnos (`modules/student-portal`, `modules/student-access`, web `/i/$token`, `/acceso`, `/alumno/*`)**: acceso sin contraseña y sin datos obligatorios nuevos. Ojo con esto:
|
||||
- **App de alumnos (`modules/student-portal`, `modules/student-access`, web `/i/$token`, `/access`, `/student/*`)**: acceso sin contraseña y sin datos obligatorios nuevos. Ojo con esto:
|
||||
1. **No pasa por Better Auth**: tablas propias (`student_*`), cookie propia (`gruperly_student`, `__Host-` con HTTPS, 90 días deslizante, se reescribe como mucho cada 1 h) y middleware propio (`studentSession`). Todo `/api/v1/student-portal` está en `isPublicApiRequest` del profe; cada ruta privada declara `studentSession`. Así una sesión de alumno no llega a endpoints del profe y al revés. Nunca montes rutas del profe bajo `/student-portal`.
|
||||
2. Tokens de 32 bytes base64url; **en la base solo el SHA-256**. Invitación 72 h, recuperación 15 min, confirmación de mail 24 h. El **GET del link no consume** (vistas previas de WhatsApp); el POST consume con `updateMany` condicional (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now`) y `count === 1` gana. Todo link inválido responde el mismo `{ status: 'invalid' }` / 410.
|
||||
3. **Reinvitar reinicia el acceso**: revoca tokens pendientes y sesiones, **borra las passkeys** y resetea `welcomed_at`.
|
||||
4. CSRF: `studentOriginGuard` exige `Origin === WEB_URL` (o `WEBAUTHN_ORIGIN`) en todo POST/PUT/DELETE, además de `SameSite=Lax`.
|
||||
5. Autorización: todo pasa por `findLinkedAttendee` (attendee vinculado a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. Vincular tutores a varios hijos (N:N en `student_account_attendees`) es solo del lado profe y **todavía no tiene UI**.
|
||||
5. Autorización: todo pasa por `findLinkedAttendee` (attendee cuya **persona** está vinculada a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. La cuenta se vincula a la persona (`student_account_people`), no a la membresía: ve todos sus grupos, también los que se sumen después, y es **una cuenta por persona** (invitar desde cualquier grupo la reutiliza). Vincular tutores a varios hijos (N:N) es solo del lado profe y **todavía no tiene UI**.
|
||||
6. "Pedir un link a mi mail": respuesta idéntica exista o no el mail; rate limit en `rate_limit_events` (3 por mail y 10 por IP cada 15 min). La IP sale de `X-Forwarded-For` contando `TRUSTED_PROXY_HOPS` desde el final. El envío corre después de responder, para no filtrar por tiempo.
|
||||
7. Avisar falta reutiliza `registerAbsence` (EXCUSED + liberación de cupo); `AbsenceNotice` tiene índice único **parcial** (`cancelled_at IS NULL`, escrito a mano en la migración: Prisma no lo modela). Solo antes del inicio de la clase y solo en ocurrencias reales del grupo, en la zona del profe (`COUNTRY_TIME_ZONES[user.country]`, default `APP_TIMEZONE` = Buenos Aires).
|
||||
8. Pago informado: `Payment.status` **no cambia** hasta que el profe confirma. "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas con un `ReportedPayment` `REPORTED` (`reportedItems: { none: … }`); si se rechaza, vuelven. Confirmar marca `PAID` con `paid_at = reviewed_at`; "Deshacer" (10 min) revierte solo esas filas (sin `mp_payment_id`). El mail al alumno sale 60 s después, solo si la revisión sigue en pie y el mail está confirmado.
|
||||
9. Comprobantes: tipo real por magic bytes (`lib/file-type.ts`: JPG, PNG, WEBP, HEIC, PDF; 10 MB), storage S3 privado detrás de `FileStorage` (`lib/storage.ts`, `Bun.S3Client`, path-style para RustFS), URLs firmadas de 5 min. En los tests se inyecta `storage` por deps. Retención: `RECEIPT_RETENTION_DAYS` (job diario `startStudentAccessJobs`).
|
||||
10. Tests: los de `test/db/` van contra Postgres real (concurrencia del link, IDOR, revisión) y solo corren con `bun --filter @gruperly/backend test:db`; en `bun test` aparecen como `skip`.
|
||||
- **Personas y membresías (`Person` / `Attendee`)**: una persona puede estar en varios grupos del mismo profe. Ojo con esto:
|
||||
1. `Person` (`people`, del profe vía `created_by_id`) tiene los datos de contacto y las notas; `Attendee` es la **membresía** (`group_id` + `person_id` + `status` + `notify_token`), con `@@unique([groupId, personId])`. Asistencia, cuotas, alertas y mensajes siguen siendo por attendee (por grupo). (`Member` ya existe: es la organización de Better Auth.)
|
||||
2. El teléfono es único por profe con un índice **parcial** a mano (`people_owner_phone_key`, `WHERE phone IS NOT NULL`): Prisma no lo modela y un choque llega como `P2002` (`isUniqueViolation` en `modules/people/lib/people.ts`). Los teléfonos se guardan normalizados (`normalizePhone`, también al editar); `phoneVariants` cubre filas viejas.
|
||||
3. Las altas resuelven a la persona por teléfono: el alta individual sin `personId` con un teléfono existente responde `409 person_exists` (la web lo detecta antes con `GET /people/lookup?groupId=&phone=` y manda `personId`); bulk, lista de espera y preinscripciones vinculan solas (`findOrCreatePerson`). Ya estar en el grupo es `attendee_already_registered`; una membresía `DROPPED` se reactiva.
|
||||
4. `POST /groups/:gid/attendees/:aid/add-to-group` ("Agregar a otro grupo") crea otra membresía de la misma persona; `move` sigue cambiando el `groupId` de la misma membresía. Ambas validan con `checkCanJoinGroup(db, group, personId)`.
|
||||
5. Editar contacto/notas escribe en la persona (cambia en todos sus grupos; choque de teléfono → `409 person_phone_taken`). Quitar la última membresía borra también a la persona.
|
||||
6. El límite del plan cuenta **personas** con al menos una membresía `ACTIVE`; `canAddAttendees(owner, n)` recibe las personas nuevas (`countsAsNewStudent`).
|
||||
7. Los DTOs de attendee siguen planos (`toAttendeeDto` aplana `person` y suma `personId`); para selects sueltos usá `attendeeWithPerson` / `flattenPerson` de `attendees/lib/helpers.ts`. El detalle trae `otherGroups`.
|
||||
- **Multi idioma (`apps/web/src/i18n/`)**: i18next + react-i18next. Idiomas: `es-AR` (rioplatense, voseo; AR y UY), `es-419` (tuteo), `pt-BR` y `en`; la lista vive en `SUPPORTED_LOCALES` (`packages/shared/src/schemas/locale.ts`) y `resolveLocale` mapea los idiomas del dispositivo (cualquier otro `es-*` → `es-419`, cualquier `pt-*` → `pt-BR`, lo no soportado → `en`). Ojo con esto:
|
||||
1. **`es-AR` es la fuente**: `i18next.d.ts` tipa las claves con sus JSON, así que una clave que no exista ahí rompe el typecheck. `test/i18n-keys.test.ts` exige las mismas claves (salvo sufijos de plural) y variables en los 4 idiomas. Un namespace nuevo = un JSON por idioma + `NAMESPACES` (`instance.ts`) + `i18next.d.ts`.
|
||||
2. La preferencia es `'system' | AppLocale` en `localStorage['locale']`; para el profe también en `users.locale` (Better Auth `additionalFields`, validado con `appLocaleSchema`; `null` = idioma del dispositivo). `LocaleProfileSync` aplica el del perfil al iniciar sesión; `LanguageCard` lo guarda con `authClient.updateUser`. La app de alumnos solo usa `localStorage`.
|
||||
3. `main.tsx` carga el idioma (más `en` de fallback) **antes** del primer render; los JSON se cargan lazy por `import.meta.glob` (solo existe en Vite: en `bun test` el preload `test/setup.ts` carga `es-AR` del disco, por eso los tests asertan el copy rioplatense).
|
||||
4. Un componente que pinta texto traducido llama `useTranslation`, aunque el texto salga de un helper (`weekDayLabel`, `paymentStatusLabel`, `copy.ts` con `i18n.t`): es lo que lo re-renderiza al cambiar de idioma.
|
||||
5. Fechas y nombres de días/meses van en el idioma de la UI (`useIntlLocale()` / `i18n.language`), **nunca** con `'es-AR'` fijo. Montos y teléfonos **no**: `formatPrice`/`formatPhoneDisplay` siguen al **país** (`lib/region.ts`).
|
||||
6. Validación: los esquemas (shared y web) llevan **claves** (`'group.nameMin'`) en vez de texto; se pintan con `<FieldError message={errors.x?.message} />` (traduce contra el namespace `validation`). `installZodErrorMap` cubre los mensajes por defecto de Zod.
|
||||
7. Errores de la API: `errorMessage(error, fallback)` traduce el `code` del Problem Details (namespace `errors`, `codes.*`; los de Better Auth en `auth.*`); los `params` del problema (`limit`, `feature`, `max`, `capacity`) eligen variante y plural. Con la UI en español cae al `detail` del backend; si no, al `fallback`. Un error nuevo del backend que la UI muestre tiene que llevar `code` y su traducción.
|
||||
8. 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).
|
||||
|
||||
## Convenciones repo-específicas
|
||||
|
||||
- **Frontend en español**: copy de UI, comentarios y textos en español.
|
||||
- **Commits en inglés**: los mensajes de commit (título y cuerpo) van siempre en inglés, con prefijo Conventional Commits (`feat(i18n): …`, `fix: …`, `chore: …`). Los commits anteriores en español quedan como están.
|
||||
- **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`).
|
||||
- **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.
|
||||
- **Tailwind v4** con tokens en `@theme` dentro de `apps/web/src/index.css` (p. ej. `--color-accent: #1e90ff`). Se usan como clases auto-generadas: `text-accent`, `bg-success-soft`, etc. Radius por defecto `0.75rem` (`rounded-xl`).
|
||||
|
||||
@@ -206,9 +206,11 @@ Si falta alguna obligatoria, el compose aborta antes de construir, con el nombre
|
||||
|
||||
1. Creá una aplicación tipo **Compose** apuntando al repo (el `docker-compose.yml` de la raíz).
|
||||
2. En **Environment** cargá `DATABASE_URL`, `WEB_URL` y `BETTER_AUTH_SECRET` (deshabilitadas las que no uses). Guardá.
|
||||
3. En **General → Domains** asociá el dominio solo al servicio `web`, puerto **`80`**. Ojo: el puerto del dominio es el **puerto del contenedor**, no el del host. El compose publica `8080:80` — el `8080` es para probar en local; nginx escucha `80` adentro. Si ponés `8080` en el panel, Traefik marca la conexión y devuelve Bad Gateway.
|
||||
3. En **General → Domains** asociá el dominio solo al servicio `web`, puerto **`80`**. Ojo: el puerto del dominio es el **puerto del contenedor** (nginx escucha `80` adentro). El compose no publica puertos en el host: Traefik llega por `dokploy-network`.
|
||||
4. Deploy.
|
||||
|
||||
Se pueden tener varias apps Compose de este repo en el mismo server (p. ej. dev y prod): como no se publican puertos en el host no chocan, y nginx le pega a su propia API por el alias `gruperly-api`, que solo existe en la red de cada stack. Cada app necesita su dominio, su `WEB_URL`, su `DATABASE_URL` (otra base) y su `BETTER_AUTH_SECRET`.
|
||||
|
||||
En `DATABASE_URL` usá el host interno que muestra la base en Dokploy (ej. `piservices-db-llwatq:5432`), que solo resuelve dentro de `dokploy-network`.
|
||||
|
||||
Si la API no levanta, el motivo está en los logs del servicio `api` (pestaña **Logs**), que incluyen la salida de Prisma.
|
||||
@@ -226,7 +228,7 @@ Fuera de Dokploy hay que crear `dokploy-network` una vez, porque el compose la d
|
||||
```bash
|
||||
docker network create dokploy-network # una sola vez
|
||||
cp .env.example .env # completá DATABASE_URL, WEB_URL y BETTER_AUTH_SECRET
|
||||
docker compose up --build -d
|
||||
docker compose -f docker-compose.yml -f docker-compose.local.yml up --build -d # publica web en :8080
|
||||
docker compose logs api # debe salir "migrate: listo" y "Server running on ..."
|
||||
curl http://localhost:8080/api/v1/health
|
||||
```
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "reported_payments" ADD COLUMN "note" TEXT;
|
||||
@@ -0,0 +1,182 @@
|
||||
-- A person (contact data, per teacher) can now be in several groups: `attendees`
|
||||
-- becomes the membership and points to `people`. Existing attendees of the same
|
||||
-- teacher with the same phone (digits only) are merged into one person, and
|
||||
-- their student-app accounts into one account.
|
||||
|
||||
-- All or nothing: a half-applied data migration cannot be retried.
|
||||
BEGIN;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "people" (
|
||||
"id" TEXT NOT NULL,
|
||||
"created_by_id" TEXT NOT NULL,
|
||||
"full_name" TEXT NOT NULL,
|
||||
"email" TEXT,
|
||||
"phone" TEXT,
|
||||
"guardian_name" TEXT,
|
||||
"guardian_phone" TEXT,
|
||||
"notes" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "people_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "student_account_people" (
|
||||
"account_id" TEXT NOT NULL,
|
||||
"person_id" TEXT NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "student_account_people_pkey" PRIMARY KEY ("account_id","person_id")
|
||||
);
|
||||
|
||||
-- Grouping: same teacher + same phone digits. `group_rank` splits the (rare)
|
||||
-- rows that already shared a phone inside one group, which the per-group unique
|
||||
-- membership would reject: the extra ones become their own person.
|
||||
CREATE TEMP TABLE "_attendee_keys" AS
|
||||
SELECT
|
||||
a."id" AS attendee_id,
|
||||
a."group_id",
|
||||
a."created_at",
|
||||
g."created_by_id",
|
||||
NULLIF(regexp_replace(COALESCE(a."phone", ''), '\D', '', 'g'), '') AS phone_digits,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY g."created_by_id", a."group_id", NULLIF(regexp_replace(COALESCE(a."phone", ''), '\D', '', 'g'), '')
|
||||
ORDER BY a."created_at", a."id"
|
||||
) AS group_rank
|
||||
FROM "attendees" a
|
||||
JOIN "groups" g ON g."id" = a."group_id";
|
||||
|
||||
CREATE TEMP TABLE "_attendee_person" AS
|
||||
SELECT
|
||||
k.attendee_id,
|
||||
k.created_by_id,
|
||||
-- The person reuses the id of its oldest attendee.
|
||||
FIRST_VALUE(k.attendee_id) OVER (
|
||||
PARTITION BY k.created_by_id,
|
||||
CASE WHEN k.phone_digits IS NULL THEN k.attendee_id ELSE k.phone_digits || '#' || k.group_rank END
|
||||
ORDER BY k.created_at, k.attendee_id
|
||||
) AS person_id,
|
||||
(k.phone_digits IS NOT NULL AND k.group_rank > 1) AS phone_clash
|
||||
FROM "_attendee_keys" k;
|
||||
|
||||
INSERT INTO "people" ("id", "created_by_id", "full_name", "email", "phone", "guardian_name", "guardian_phone", "notes", "created_at", "updated_at")
|
||||
SELECT
|
||||
p.person_id,
|
||||
MIN(p.created_by_id),
|
||||
MIN(rep."full_name"),
|
||||
(ARRAY_AGG(a."email" ORDER BY a."created_at") FILTER (WHERE a."email" IS NOT NULL))[1],
|
||||
CASE WHEN BOOL_OR(p.phone_clash) THEN NULL ELSE NULLIF(TRIM(MIN(rep."phone")), '') END,
|
||||
(ARRAY_AGG(a."guardian_name" ORDER BY a."created_at") FILTER (WHERE a."guardian_name" IS NOT NULL))[1],
|
||||
(ARRAY_AGG(a."guardian_phone" ORDER BY a."created_at") FILTER (WHERE a."guardian_phone" IS NOT NULL))[1],
|
||||
NULLIF(CONCAT_WS(E'\n\n',
|
||||
STRING_AGG(DISTINCT NULLIF(TRIM(a."notes"), ''), E'\n\n'),
|
||||
CASE WHEN BOOL_OR(p.phone_clash) THEN 'Teléfono: ' || MIN(rep."phone") END
|
||||
), ''),
|
||||
MIN(a."created_at"),
|
||||
CURRENT_TIMESTAMP
|
||||
FROM "_attendee_person" p
|
||||
JOIN "attendees" a ON a."id" = p.attendee_id
|
||||
JOIN "attendees" rep ON rep."id" = p.person_id
|
||||
GROUP BY p.person_id;
|
||||
|
||||
-- AlterTable: attendees -> membership
|
||||
ALTER TABLE "attendees" ADD COLUMN "person_id" TEXT;
|
||||
UPDATE "attendees" a SET "person_id" = p.person_id FROM "_attendee_person" p WHERE p.attendee_id = a."id";
|
||||
ALTER TABLE "attendees" ALTER COLUMN "person_id" SET NOT NULL;
|
||||
|
||||
-- Student accounts: link them to the person instead of the membership.
|
||||
INSERT INTO "student_account_people" ("account_id", "person_id", "created_at")
|
||||
SELECT sa."account_id", p.person_id, MIN(sa."created_at")
|
||||
FROM "student_account_attendees" sa
|
||||
JOIN "_attendee_person" p ON p.attendee_id = sa."attendee_id"
|
||||
GROUP BY sa."account_id", p.person_id;
|
||||
|
||||
-- A merged person may end up with several accounts: keep the one used most
|
||||
-- recently (else the oldest) and fold the others into it.
|
||||
CREATE TEMP TABLE "_account_merge" AS
|
||||
WITH ranked AS (
|
||||
SELECT
|
||||
sap."person_id",
|
||||
sap."account_id",
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY sap."person_id"
|
||||
ORDER BY (
|
||||
SELECT MAX(s."last_used_at") FROM "student_sessions" s
|
||||
WHERE s."account_id" = sap."account_id" AND s."revoked_at" IS NULL
|
||||
) DESC NULLS LAST, acc."created_at", acc."id"
|
||||
) AS rn
|
||||
FROM "student_account_people" sap
|
||||
JOIN "student_accounts" acc ON acc."id" = sap."account_id"
|
||||
)
|
||||
SELECT DISTINCT ON (d."account_id") d."account_id" AS old_id, k."account_id" AS keep_id
|
||||
FROM ranked d
|
||||
JOIN ranked k ON k."person_id" = d."person_id" AND k.rn = 1
|
||||
WHERE d.rn > 1 AND d."account_id" <> k."account_id"
|
||||
ORDER BY d."account_id";
|
||||
|
||||
INSERT INTO "student_account_people" ("account_id", "person_id", "created_at")
|
||||
SELECT m.keep_id, sap."person_id", sap."created_at"
|
||||
FROM "student_account_people" sap
|
||||
JOIN "_account_merge" m ON m.old_id = sap."account_id"
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
UPDATE "absence_notices" n SET "account_id" = m.keep_id FROM "_account_merge" m WHERE n."account_id" = m.old_id;
|
||||
UPDATE "reported_payments" r SET "account_id" = m.keep_id FROM "_account_merge" m WHERE r."account_id" = m.old_id;
|
||||
|
||||
UPDATE "student_accounts" k
|
||||
SET "recovery_email" = o."recovery_email", "recovery_email_verified_at" = o."recovery_email_verified_at"
|
||||
FROM "_account_merge" m
|
||||
JOIN "student_accounts" o ON o."id" = m.old_id
|
||||
WHERE k."id" = m.keep_id AND k."recovery_email" IS NULL AND o."recovery_email" IS NOT NULL;
|
||||
|
||||
-- Sessions, tokens and passkeys of the folded accounts go with them (cascade);
|
||||
-- their links are removed by hand because that FK is created further down.
|
||||
DELETE FROM "student_account_people" WHERE "account_id" IN (SELECT old_id FROM "_account_merge");
|
||||
DELETE FROM "student_accounts" WHERE "id" IN (SELECT old_id FROM "_account_merge");
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "student_account_attendees";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "attendees"
|
||||
DROP COLUMN "full_name",
|
||||
DROP COLUMN "email",
|
||||
DROP COLUMN "phone",
|
||||
DROP COLUMN "guardian_name",
|
||||
DROP COLUMN "guardian_phone",
|
||||
DROP COLUMN "notes";
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "people_created_by_id_idx" ON "people"("created_by_id");
|
||||
|
||||
-- One person per phone and teacher. Partial: Prisma does not model it.
|
||||
CREATE UNIQUE INDEX "people_owner_phone_key" ON "people"("created_by_id", "phone") WHERE "phone" IS NOT NULL;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "student_account_people_person_id_idx" ON "student_account_people"("person_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "attendees_person_id_idx" ON "attendees"("person_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "attendees_group_id_person_id_key" ON "attendees"("group_id", "person_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "people" ADD CONSTRAINT "people_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "attendees" ADD CONSTRAINT "attendees_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "student_account_people" ADD CONSTRAINT "student_account_people_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "student_account_people" ADD CONSTRAINT "student_account_people_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
DROP TABLE "_account_merge";
|
||||
DROP TABLE "_attendee_person";
|
||||
DROP TABLE "_attendee_keys";
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "users" ADD COLUMN "locale" TEXT;
|
||||
@@ -8,6 +8,8 @@ model User {
|
||||
image String?
|
||||
onboardingCompleted Boolean @default(false) @map("onboarding_completed")
|
||||
country String? @map("country_code")
|
||||
// UI language the person chose (es-AR, es-419, pt-BR, en); null follows the device.
|
||||
locale String? @map("locale")
|
||||
// When the professor chose Free or Pro in the onboarding (mandatory step).
|
||||
planSelectedAt DateTime? @map("plan_selected_at")
|
||||
// Bank transfer details shown to students when they report a payment.
|
||||
@@ -28,6 +30,7 @@ model User {
|
||||
whatsappAccount WhatsappAccount?
|
||||
subscription BillingSubscription?
|
||||
studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
|
||||
people Person[] @relation("OwnerPeople")
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
@@ -72,31 +72,55 @@ enum AttendeeStatus {
|
||||
DROPPED
|
||||
}
|
||||
|
||||
model Attendee {
|
||||
id String @id @default(cuid())
|
||||
groupId String @map("group_id")
|
||||
fullName String @map("full_name")
|
||||
// A person the teacher works with (student, or the guardian's child). Contact
|
||||
// data lives here once; `Attendee` is their membership in each group, so one
|
||||
// person can be in several groups of the same teacher. The phone is unique per
|
||||
// teacher through a hand-written partial index (`people_owner_phone_key`,
|
||||
// `WHERE phone IS NOT NULL`): Prisma does not model it.
|
||||
model Person {
|
||||
id String @id @default(cuid())
|
||||
createdById String @map("created_by_id")
|
||||
fullName String @map("full_name")
|
||||
email String?
|
||||
phone String?
|
||||
guardianName String? @map("guardian_name")
|
||||
guardianPhone String? @map("guardian_phone")
|
||||
guardianName String? @map("guardian_name")
|
||||
guardianPhone String? @map("guardian_phone")
|
||||
notes String?
|
||||
notifyToken String? @unique(map: "attendees_notifyToken_key") @default(cuid()) @map("notify_token")
|
||||
status AttendeeStatus @default(ACTIVE)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade)
|
||||
attendees Attendee[]
|
||||
studentAccounts StudentAccountPerson[]
|
||||
|
||||
@@index([createdById])
|
||||
@@map("people")
|
||||
}
|
||||
|
||||
// Membership of a person in a group. Status, attendance, fees and the absence
|
||||
// link (`notifyToken`) are per group.
|
||||
model Attendee {
|
||||
id String @id @default(cuid())
|
||||
groupId String @map("group_id")
|
||||
personId String @map("person_id")
|
||||
notifyToken String? @unique(map: "attendees_notifyToken_key") @default(cuid()) @map("notify_token")
|
||||
status AttendeeStatus @default(ACTIVE)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
|
||||
person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
|
||||
payments Payment[]
|
||||
attendances Attendance[]
|
||||
slotReleases SlotRelease[]
|
||||
outboundMessages OutboundMessage[]
|
||||
alertResolutions AttendeeAlertResolution[]
|
||||
studentAccounts StudentAccountAttendee[]
|
||||
absenceNotices AbsenceNotice[]
|
||||
reportedPayments ReportedPayment[]
|
||||
|
||||
@@unique([groupId, personId])
|
||||
@@index([groupId], map: "attendees_groupId_idx")
|
||||
@@index([personId])
|
||||
@@map("attendees")
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ model StudentAccount {
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
createdBy User @relation("StudentAccountsCreated", fields: [createdById], references: [id], onDelete: Cascade)
|
||||
attendees StudentAccountAttendee[]
|
||||
people StudentAccountPerson[]
|
||||
tokens StudentAccessToken[]
|
||||
sessions StudentSession[]
|
||||
passkeys StudentPasskey[]
|
||||
@@ -37,17 +37,20 @@ model StudentAccount {
|
||||
@@map("student_accounts")
|
||||
}
|
||||
|
||||
model StudentAccountAttendee {
|
||||
accountId String @map("account_id")
|
||||
attendeeId String @map("attendee_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
// The account is linked to people, not to memberships: it sees every group the
|
||||
// person is in (also the ones added later). A guardian may be linked to several
|
||||
// children (N:N).
|
||||
model StudentAccountPerson {
|
||||
accountId String @map("account_id")
|
||||
personId String @map("person_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
||||
person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([accountId, attendeeId])
|
||||
@@index([attendeeId])
|
||||
@@map("student_account_attendees")
|
||||
@@id([accountId, personId])
|
||||
@@index([personId])
|
||||
@@map("student_account_people")
|
||||
}
|
||||
|
||||
enum StudentTokenKind {
|
||||
@@ -203,6 +206,8 @@ model ReportedPayment {
|
||||
receiptMime String @map("receipt_mime")
|
||||
receiptName String @map("receipt_name")
|
||||
receiptSize Int @map("receipt_size")
|
||||
// Optional message from the student to the teacher.
|
||||
note String?
|
||||
status ReportedPaymentStatus @default(REPORTED)
|
||||
reviewedById String? @map("reviewed_by_id")
|
||||
reviewedAt DateTime? @map("reviewed_at")
|
||||
|
||||
@@ -27,6 +27,7 @@ import { invitationsRoutes } from './modules/invitations';
|
||||
import { mpRoutes } from './modules/mp';
|
||||
import { onboardingRoutes } from './modules/onboarding';
|
||||
import { paymentsRoutes } from './modules/payments';
|
||||
import { peopleRoutes } from './modules/people';
|
||||
import { studentPortalRoutes } from './modules/student-portal';
|
||||
import { waitlistRoutes } from './modules/waitlist';
|
||||
import { whatsappRoutes } from './modules/whatsapp';
|
||||
@@ -68,6 +69,7 @@ api.route('/classes', classesRoutes);
|
||||
api.route('/students', studentStatusRoutes);
|
||||
api.route('/groups-risk', groupsRiskOverviewRoute);
|
||||
api.route('/attention', attentionRoutes);
|
||||
api.route('/people', peopleRoutes);
|
||||
api.route('/student-portal', studentPortalRoutes);
|
||||
|
||||
app.notFound((c) => {
|
||||
|
||||
@@ -21,6 +21,7 @@ export function conflictProblem(params: {
|
||||
detail: string;
|
||||
code?: string;
|
||||
instance?: string;
|
||||
params?: ProblemDetails['params'];
|
||||
}): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/conflict`,
|
||||
@@ -29,6 +30,7 @@ export function conflictProblem(params: {
|
||||
detail: params.detail,
|
||||
instance: params.instance,
|
||||
code: params.code,
|
||||
...(params.params ? { params: params.params } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -186,6 +188,7 @@ export function capacityReachedProblem(capacity: number | null): ProblemDetails
|
||||
? `El grupo alcanzó su cupo máximo de ${capacity} miembros.`
|
||||
: 'El grupo alcanzó su cupo máximo de miembros.',
|
||||
code: 'group_capacity_reached',
|
||||
...(capacity ? { params: { capacity } } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -216,13 +219,18 @@ export function noAttendeesToBillProblem(): ProblemDetails {
|
||||
code: 'no_attendees_to_bill',
|
||||
});
|
||||
}
|
||||
function paymentRequiredProblem(params: { detail: string; code: string }): ProblemDetails {
|
||||
function paymentRequiredProblem(params: {
|
||||
detail: string;
|
||||
code: string;
|
||||
params?: ProblemDetails['params'];
|
||||
}): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/plan`,
|
||||
title: 'Payment Required',
|
||||
status: 402,
|
||||
detail: params.detail,
|
||||
code: params.code,
|
||||
...(params.params ? { params: params.params } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -236,6 +244,7 @@ export function planLimitReachedProblem(limit: PlanLimitKind, max: number): Prob
|
||||
? `El plan Free permite hasta ${max} ${max === 1 ? 'grupo' : 'grupos'}. Pasate a Pro para crear más.`
|
||||
: `El plan Free permite hasta ${max} alumnos activos. Pasate a Pro para sumar más.`,
|
||||
code: 'plan_limit_reached',
|
||||
params: { limit, max },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -247,6 +256,7 @@ export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutom
|
||||
? 'Cobrar con Mercado Pago está disponible en el plan Pro.'
|
||||
: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
|
||||
code: 'plan_feature_required',
|
||||
params: { feature },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
||||
|
||||
export const HISTORY_SESSIONS_LIMIT = 20;
|
||||
@@ -33,8 +34,8 @@ export class GetAttendeeHistory {
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { id: true, fullName: true, createdAt: true },
|
||||
});
|
||||
select: { id: true, createdAt: true, person: { select: { fullName: true } } },
|
||||
}).then((row) => row && flattenPerson(row));
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
URGENT_MEMBERS_LIMIT,
|
||||
} from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||
@@ -76,8 +77,8 @@ export class GetGroupsRiskOverview {
|
||||
const [attendees, sessions, attendances] = await Promise.all([
|
||||
db.attendee.findMany({
|
||||
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
|
||||
select: { id: true, groupId: true, fullName: true, createdAt: true },
|
||||
}) as Promise<AttendeeRow[]>,
|
||||
select: { id: true, groupId: true, createdAt: true, person: { select: { fullName: true } } },
|
||||
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
|
||||
db.classSession.findMany({
|
||||
where: { groupId: { in: groupIds }, startsAt: { gte: since } },
|
||||
select: { id: true, groupId: true, startsAt: true },
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
} from '@gruperly/shared';
|
||||
import { ok, summarizeMemberAttendance } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
||||
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
|
||||
@@ -73,8 +74,8 @@ export async function findStudentsAtRisk(
|
||||
}),
|
||||
db.attendee.findMany({
|
||||
where: { groupId, status: 'ACTIVE' },
|
||||
select: { id: true, fullName: true, phone: true, createdAt: true },
|
||||
}),
|
||||
select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true } } },
|
||||
}).then((rows) => rows.map(flattenPerson)),
|
||||
db.attendance.findMany({
|
||||
where: { attendee: { groupId } },
|
||||
select: {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { AddAttendeeToGroup as AddAttendeeToGroupBody } from '@gruperly/shared';
|
||||
import { AddAttendeeToGroupSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { AddAttendeeToGroup } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/attendees/:attendeeId/add-to-group', validate.json(AddAttendeeToGroupSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new AddAttendeeToGroup();
|
||||
const result = await useCase.execute({
|
||||
groupId: c.req.param('groupId'),
|
||||
attendeeId: c.req.param('attendeeId'),
|
||||
userId: user.id,
|
||||
targetGroupId: (c.req.valid('json') as AddAttendeeToGroupBody).targetGroupId,
|
||||
});
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote';
|
||||
import { alreadyInGroupProblem, isUniqueViolation } from '@/modules/people/lib/people';
|
||||
import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type AddAttendeeToGroupDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||
};
|
||||
|
||||
type AddAttendeeToGroupCommand = {
|
||||
groupId: string;
|
||||
attendeeId: string;
|
||||
userId: string;
|
||||
targetGroupId: string;
|
||||
};
|
||||
|
||||
/* "Agregar a otro grupo": the same person gets a membership in another group of
|
||||
the teacher and keeps this one. It does not take a new student slot of the
|
||||
plan (the person is already counted) but the target's capacity applies. A
|
||||
former membership there (DROPPED) is reactivated, history included. */
|
||||
export class AddAttendeeToGroup {
|
||||
constructor(private readonly deps: AddAttendeeToGroupDeps = {}) {}
|
||||
|
||||
async execute(command: AddAttendeeToGroupCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
const { groupId, attendeeId, userId, targetGroupId } = command;
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
|
||||
const sourceResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!sourceResult.ok) return sourceResult;
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { personId: true },
|
||||
});
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
if (targetGroupId === groupId) {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'El miembro ya pertenece a este grupo.',
|
||||
code: 'attendee_same_group',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
|
||||
if (!targetResult.ok) return targetResult;
|
||||
const target = targetResult.value;
|
||||
|
||||
try {
|
||||
return await unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient): Promise<Result<AttendeeDto, ProblemDetails>> => {
|
||||
const former = await tx.attendee.findFirst({
|
||||
where: { groupId: targetGroupId, personId: attendee.personId },
|
||||
select: { id: true, status: true },
|
||||
});
|
||||
if (former && former.status !== 'DROPPED') return err(alreadyInGroupProblem());
|
||||
|
||||
const canJoin = await checkCanJoinGroup(tx, target, null);
|
||||
if (!canJoin.ok) return canJoin;
|
||||
|
||||
const membership = former
|
||||
? await tx.attendee.update({
|
||||
where: { id: former.id },
|
||||
data: { status: 'ACTIVE' },
|
||||
include: attendeeWithPerson,
|
||||
})
|
||||
: await tx.attendee.create({
|
||||
data: { groupId: targetGroupId, personId: attendee.personId },
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
return ok(toAttendeeDto(membership));
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
// Two clicks at once: the unique (group, person) lets only one through.
|
||||
if (isUniqueViolation(error)) return err(alreadyInGroupProblem());
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
notFoundResourceProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { phoneVariants } from '@/modules/people/lib/people';
|
||||
import { normalizePhone } from '../../lib/helpers';
|
||||
|
||||
type AddToGroupWaitlistDeps = {
|
||||
@@ -72,10 +73,7 @@ export class AddToGroupWaitlist {
|
||||
const existingAttendee = await db.attendee.findFirst({
|
||||
where: {
|
||||
groupId,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
person: { phone: { in: phoneVariants(payload.phone) } },
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -9,10 +9,10 @@ import { err, ok } from '@gruperly/shared';
|
||||
import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
import { type AttendeeRecord, attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type BulkCreateAttendeesDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'person'>;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
@@ -43,23 +43,29 @@ export class BulkCreateAttendeesUseCase {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
|
||||
// Load the group's existing phone numbers
|
||||
const existingAttendees = await db.attendee.findMany({
|
||||
where: { groupId },
|
||||
select: { phone: true },
|
||||
/* The teacher's people by phone: a row whose phone is already someone they
|
||||
have is added to this group as that person (linked), unless that person
|
||||
is already in the group (duplicate). */
|
||||
const people = await db.person.findMany({
|
||||
where: { createdById: group.createdById, phone: { not: null } },
|
||||
select: {
|
||||
id: true,
|
||||
phone: true,
|
||||
attendees: { select: { groupId: true, status: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const existingPhones = new Set<string>();
|
||||
for (const a of existingAttendees) {
|
||||
if (a.phone) {
|
||||
existingPhones.add(normalizePhone(a.phone));
|
||||
}
|
||||
const peopleByPhone = new Map<string, (typeof people)[number]>();
|
||||
for (const person of people) {
|
||||
if (person.phone) peopleByPhone.set(normalizePhone(person.phone), person);
|
||||
}
|
||||
|
||||
let duplicatesCount = 0;
|
||||
let invalidCount = 0;
|
||||
const toCreateData: Array<{
|
||||
groupId: string;
|
||||
// Only people not active in any group take a new slot of the plan.
|
||||
let newlyCounted = 0;
|
||||
const seenPhones = new Set<string>();
|
||||
const toLink: string[] = [];
|
||||
const toCreate: Array<{
|
||||
fullName: string;
|
||||
phone: string;
|
||||
email: string | null;
|
||||
@@ -75,14 +81,21 @@ export class BulkCreateAttendeesUseCase {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (existingPhones.has(phone)) {
|
||||
const existing = peopleByPhone.get(phone);
|
||||
if (seenPhones.has(phone) || existing?.attendees.some((membership) => membership.groupId === groupId)) {
|
||||
duplicatesCount++;
|
||||
continue;
|
||||
}
|
||||
seenPhones.add(phone);
|
||||
|
||||
existingPhones.add(phone);
|
||||
toCreateData.push({
|
||||
groupId,
|
||||
if (existing) {
|
||||
toLink.push(existing.id);
|
||||
if (!existing.attendees.some((membership) => membership.status === 'ACTIVE')) newlyCounted++;
|
||||
continue;
|
||||
}
|
||||
|
||||
newlyCounted++;
|
||||
toCreate.push({
|
||||
fullName: rawFullName,
|
||||
phone,
|
||||
email: item.email?.trim() || null,
|
||||
@@ -94,26 +107,44 @@ export class BulkCreateAttendeesUseCase {
|
||||
// reason about than a clear "your plan allows N".
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
|
||||
group.createdById,
|
||||
toCreateData.length,
|
||||
newlyCounted,
|
||||
);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
const createdRecords: AttendeeRecord[] = [];
|
||||
for (const data of toCreateData) {
|
||||
const record = await db.attendee.create({ data });
|
||||
createdRecords.push(record as unknown as AttendeeRecord);
|
||||
for (const personId of toLink) {
|
||||
createdRecords.push(
|
||||
await db.attendee.create({
|
||||
data: { groupId, personId },
|
||||
include: attendeeWithPerson,
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const data of toCreate) {
|
||||
createdRecords.push(
|
||||
await db.attendee.create({
|
||||
data: {
|
||||
group: { connect: { id: groupId } },
|
||||
person: { create: { ...data, createdById: group.createdById } },
|
||||
},
|
||||
include: attendeeWithPerson,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const createdCount = createdRecords.length;
|
||||
const linkedCount = toLink.length;
|
||||
const linkedNote = linkedCount > 0 ? ` (${linkedCount} ya estaban en otros de tus grupos)` : '';
|
||||
const message = duplicatesCount > 0
|
||||
? `${createdCount} alumnos agregados con éxito, ${duplicatesCount} duplicados omitidos.`
|
||||
: `${createdCount} alumnos agregados con éxito.`;
|
||||
? `${createdCount} alumnos agregados con éxito${linkedNote}, ${duplicatesCount} duplicados omitidos.`
|
||||
: `${createdCount} alumnos agregados con éxito${linkedNote}.`;
|
||||
|
||||
return ok({
|
||||
totalProcessed: payload.attendees.length,
|
||||
createdCount,
|
||||
linkedCount,
|
||||
duplicatesCount,
|
||||
invalidCount,
|
||||
message,
|
||||
|
||||
@@ -4,16 +4,21 @@ import { err, ok } from '@gruperly/shared';
|
||||
import {
|
||||
alreadyWaitlistedProblem,
|
||||
capacityReachedProblem,
|
||||
conflictProblem,
|
||||
noGroupAccessProblem,
|
||||
notFoundResourceProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
import {
|
||||
alreadyInGroupProblem,
|
||||
findPersonByPhone,
|
||||
isUniqueViolation,
|
||||
personExistsProblem,
|
||||
} from '@/modules/people/lib/people';
|
||||
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type CreateAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
@@ -50,26 +55,38 @@ export class CreateAttendeeUseCase {
|
||||
}
|
||||
|
||||
const phone = normalizePhone(payload.phone);
|
||||
const existing = await db.attendee.findFirst({
|
||||
where: {
|
||||
groupId,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.',
|
||||
code: 'attendee_already_registered',
|
||||
}),
|
||||
);
|
||||
/* The person: the one the form picked (`personId`, after the "ya existe"
|
||||
hint) or a new one. A phone the teacher already has is never duplicated. */
|
||||
let person: { id: string; fullName: string } | null = null;
|
||||
if (payload.personId) {
|
||||
person = await db.person.findFirst({
|
||||
where: { id: payload.personId, createdById: group.createdById },
|
||||
select: { id: true, fullName: true },
|
||||
});
|
||||
if (!person) {
|
||||
return err(notFoundResourceProblem('Person', payload.personId));
|
||||
}
|
||||
} else {
|
||||
const samePhone = await findPersonByPhone(db, group.createdById, payload.phone);
|
||||
if (samePhone) {
|
||||
return err(
|
||||
samePhone.attendees.some((membership) => membership.groupId === groupId)
|
||||
? alreadyInGroupProblem()
|
||||
: personExistsProblem(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||
// A former member (DROPPED) comes back on the same membership: history included.
|
||||
const membership = person
|
||||
? await db.attendee.findFirst({ where: { groupId, personId: person.id }, select: { id: true, status: true } })
|
||||
: null;
|
||||
if (membership && membership.status !== 'DROPPED') {
|
||||
return err(alreadyInGroupProblem());
|
||||
}
|
||||
|
||||
const fullName = person?.fullName ?? `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||
|
||||
if (group.capacity !== null) {
|
||||
const currentCount = await db.attendee.count({
|
||||
@@ -108,25 +125,51 @@ export class CreateAttendeeUseCase {
|
||||
}
|
||||
}
|
||||
|
||||
// The owner's plan pays for the attendee, whoever adds it.
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(group.createdById);
|
||||
// The owner's plan pays for the attendee, whoever adds it. It counts people:
|
||||
// someone already active in another group does not take a new slot.
|
||||
const alreadyCounted = person
|
||||
? (await db.attendee.count({ where: { personId: person.id, status: 'ACTIVE' } })) > 0
|
||||
: false;
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
|
||||
group.createdById,
|
||||
alreadyCounted ? 0 : 1,
|
||||
);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
const attendee = await db.attendee.create({
|
||||
data: {
|
||||
groupId,
|
||||
fullName,
|
||||
phone,
|
||||
email: payload.email?.trim() || null,
|
||||
notes: payload.notes?.trim() || null,
|
||||
},
|
||||
});
|
||||
try {
|
||||
const attendee = membership
|
||||
? await db.attendee.update({
|
||||
where: { id: membership.id },
|
||||
data: { status: 'ACTIVE' },
|
||||
include: attendeeWithPerson,
|
||||
})
|
||||
: await db.attendee.create({
|
||||
data: {
|
||||
group: { connect: { id: groupId } },
|
||||
person: person
|
||||
? { connect: { id: person.id } }
|
||||
: {
|
||||
create: {
|
||||
createdById: group.createdById,
|
||||
fullName,
|
||||
phone,
|
||||
email: payload.email?.trim() || null,
|
||||
notes: payload.notes?.trim() || null,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
|
||||
return ok({
|
||||
outcome: 'created',
|
||||
attendee: toAttendeeDto(attendee as unknown as AttendeeRecord),
|
||||
});
|
||||
return ok({ outcome: 'created', attendee: toAttendeeDto(attendee) });
|
||||
} catch (error) {
|
||||
// Lost a race: someone created that person or membership meanwhile.
|
||||
if (isUniqueViolation(error)) {
|
||||
return err(person ? alreadyInGroupProblem() : personExistsProblem());
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ok, RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
|
||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
import { toAttendeeListItemDto } from '../../lib/helpers';
|
||||
import { attendeeWithPerson, toAttendeeListItemDto } from '../../lib/helpers';
|
||||
|
||||
type ListAttendeesDeps = {
|
||||
db?: Pick<PrismaClient, 'attendee'>;
|
||||
@@ -28,6 +28,7 @@ export class ListAttendees {
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
...attendeeWithPerson,
|
||||
// By class date, not by `markedAt`: marking attendance late must not
|
||||
// change which class counts as recent.
|
||||
attendances: {
|
||||
|
||||
@@ -4,8 +4,8 @@ import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
|
||||
import { toAttendeeDetailDto } from '../../lib/helpers';
|
||||
import { personMembershipsSelect, toMemberships } from '@/modules/people/lib/people';
|
||||
import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers';
|
||||
|
||||
type GetAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
@@ -31,6 +31,7 @@ export class GetAttendee {
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
include: {
|
||||
person: { select: { ...personContactSelect, ...personMembershipsSelect } },
|
||||
payments: {
|
||||
where: {
|
||||
status: { not: 'CANCELLED' },
|
||||
@@ -46,7 +47,14 @@ export class GetAttendee {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
return ok(toAttendeeDetailDto(attendee));
|
||||
const { attendees: memberships, ...person } = attendee.person;
|
||||
return ok(
|
||||
toAttendeeDetailDto({
|
||||
...attendee,
|
||||
person,
|
||||
otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
24
apps/backend/src/modules/attendees/features/move/route.ts
Normal file
24
apps/backend/src/modules/attendees/features/move/route.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { MoveAttendee as MoveAttendeeBody } from '@gruperly/shared';
|
||||
import { MoveAttendeeSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { MoveAttendee } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/attendees/:attendeeId/move', validate.json(MoveAttendeeSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new MoveAttendee();
|
||||
const result = await useCase.execute({
|
||||
groupId: c.req.param('groupId'),
|
||||
attendeeId: c.req.param('attendeeId'),
|
||||
userId: user.id,
|
||||
targetGroupId: (c.req.valid('json') as MoveAttendeeBody).targetGroupId,
|
||||
});
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
77
apps/backend/src/modules/attendees/features/move/use-case.ts
Normal file
77
apps/backend/src/modules/attendees/features/move/use-case.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote';
|
||||
import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type MoveAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
type MoveAttendeeCommand = {
|
||||
groupId: string;
|
||||
attendeeId: string;
|
||||
userId: string;
|
||||
targetGroupId: string;
|
||||
};
|
||||
|
||||
/* Moves a member to another group of the same teacher. It is the same attendee
|
||||
with another `groupId`: past attendance, fees (they stay owed to the old
|
||||
group) and the student app access go with them. Only what was booked for
|
||||
the old group's future classes is undone: absence notices, the EXCUSED rows
|
||||
they left and the released slots. */
|
||||
export class MoveAttendee {
|
||||
constructor(private readonly deps: MoveAttendeeDeps = {}) {}
|
||||
|
||||
async execute(command: MoveAttendeeCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
const { groupId, attendeeId, userId, targetGroupId } = command;
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
const now = this.deps.now?.() ?? new Date();
|
||||
|
||||
const sourceResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!sourceResult.ok) return sourceResult;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
if (targetGroupId === groupId) {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'El miembro ya pertenece a este grupo.',
|
||||
code: 'attendee_same_group',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
|
||||
if (!targetResult.ok) return targetResult;
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient): Promise<Result<AttendeeDto, ProblemDetails>> => {
|
||||
const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.personId);
|
||||
if (!canJoin.ok) return canJoin;
|
||||
|
||||
const futureOldClasses = { classSession: { groupId, startsAt: { gt: now } } };
|
||||
await tx.absenceNotice.updateMany({
|
||||
where: { attendeeId, cancelledAt: null, ...futureOldClasses },
|
||||
data: { cancelledAt: now },
|
||||
});
|
||||
await tx.attendance.deleteMany({ where: { attendeeId, ...futureOldClasses } });
|
||||
await tx.slotRelease.deleteMany({ where: { attendeeId, isClaimed: false, ...futureOldClasses } });
|
||||
|
||||
const moved = await tx.attendee.update({
|
||||
where: { id: attendeeId },
|
||||
data: { groupId: targetGroupId },
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
return ok(toAttendeeDto(moved));
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,10 @@ export class RemoveAttendee {
|
||||
}
|
||||
const group = groupResult.value;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { personId: true },
|
||||
});
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
@@ -49,6 +52,10 @@ export class RemoveAttendee {
|
||||
return unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient): Promise<Result<RemoveAttendeeResult, ProblemDetails>> => {
|
||||
await tx.attendee.delete({ where: { id: attendeeId } });
|
||||
// Their last group: the person goes too (with their student app link).
|
||||
await tx.person.deleteMany({
|
||||
where: { id: attendee.personId, attendees: { none: {} } },
|
||||
});
|
||||
|
||||
if (!options.promoteFromWaitlist) {
|
||||
return ok({ removedAttendeeId: attendeeId, promoted: null });
|
||||
|
||||
@@ -4,10 +4,11 @@ import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { toAttendeeDto } from '../../lib/helpers';
|
||||
import { isUniqueViolation, personPhoneTakenProblem } from '@/modules/people/lib/people';
|
||||
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type UpdateAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'person'>;
|
||||
};
|
||||
|
||||
type UpdateAttendeeCommand = {
|
||||
@@ -26,12 +27,26 @@ export class UpdateAttendeeDetails {
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { personId: true },
|
||||
});
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
const updated = await db.attendee.update({
|
||||
// Contact data is the person's: the change shows in every group they are in.
|
||||
try {
|
||||
await db.person.update({
|
||||
where: { id: attendee.personId },
|
||||
data: normalizeEditableFields(input),
|
||||
});
|
||||
} catch (error) {
|
||||
if (isUniqueViolation(error)) return err(personPhoneTakenProblem());
|
||||
throw error;
|
||||
}
|
||||
|
||||
const updated = await db.attendee.findUniqueOrThrow({
|
||||
where: { id: attendeeId },
|
||||
data: normalizeEditableFields(input),
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
return ok(toAttendeeDto(updated));
|
||||
}
|
||||
@@ -39,6 +54,11 @@ export class UpdateAttendeeDetails {
|
||||
|
||||
function normalizeEditableFields(input: UpdateAttendee): UpdateAttendee {
|
||||
return Object.fromEntries(
|
||||
Object.entries(input).map(([key, value]) => [key, value === '' ? null : value]),
|
||||
Object.entries(input).map(([key, value]) => {
|
||||
if (value === '') return [key, null];
|
||||
// Same normalization as the add form, so the phone keeps matching.
|
||||
if (key === 'phone' && typeof value === 'string') return [key, normalizePhone(value)];
|
||||
return [key, value];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,17 +1,37 @@
|
||||
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
||||
|
||||
export type AttendeeRecord = {
|
||||
/* Contact data of the person behind an attendee (shared by all their groups). */
|
||||
export const personContactSelect = {
|
||||
id: true,
|
||||
fullName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
guardianName: true,
|
||||
guardianPhone: true,
|
||||
notes: true,
|
||||
} as const;
|
||||
|
||||
/* `include` for any attendee query that ends up in `toAttendeeDto`. */
|
||||
export const attendeeWithPerson = { person: { select: personContactSelect } } as const;
|
||||
|
||||
export type PersonContactRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
fullName: string;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
guardianName: string | null;
|
||||
guardianPhone: string | null;
|
||||
notes: string | null;
|
||||
};
|
||||
|
||||
export type AttendeeRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
personId: string;
|
||||
notifyToken?: string | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
person: PersonContactRecord;
|
||||
};
|
||||
|
||||
/** Listing item with the attendance and payment summary already resolved. */
|
||||
@@ -25,18 +45,20 @@ export type AttendeeListItemRecord = AttendeeRecord & {
|
||||
|
||||
export type AttendeeDetailRecord = AttendeeRecord & {
|
||||
payments: AttendeeListItemRecord['payments'];
|
||||
otherGroups: AttendeeDetailDto['otherGroups'];
|
||||
};
|
||||
|
||||
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
||||
return {
|
||||
id: record.id,
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
email: record.email,
|
||||
phone: record.phone,
|
||||
guardianName: record.guardianName,
|
||||
guardianPhone: record.guardianPhone,
|
||||
notes: record.notes,
|
||||
personId: record.personId,
|
||||
fullName: record.person.fullName,
|
||||
email: record.person.email,
|
||||
phone: record.person.phone,
|
||||
guardianName: record.person.guardianName,
|
||||
guardianPhone: record.person.guardianPhone,
|
||||
notes: record.person.notes,
|
||||
notifyToken: record.notifyToken ?? null,
|
||||
createdAt: record.createdAt.toISOString(),
|
||||
updatedAt: record.updatedAt.toISOString(),
|
||||
@@ -68,6 +90,7 @@ export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetai
|
||||
return {
|
||||
...toAttendeeDto(record),
|
||||
payment: pickRelevantPayment(record.payments),
|
||||
otherGroups: record.otherGroups,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -91,3 +114,13 @@ export function normalizePhone(rawPhone: string): string {
|
||||
const digitsOnly = trimmed.replace(/\D/g, '');
|
||||
return hasPlus ? `+${digitsOnly}` : digitsOnly;
|
||||
}
|
||||
|
||||
/* For queries that select a few person fields next to the attendee's: turns
|
||||
`{ id, person: { fullName } }` into `{ id, fullName }`, so the code reading
|
||||
flat rows stays as it was. */
|
||||
export function flattenPerson<TRow extends { person: object }>(
|
||||
row: TRow,
|
||||
): Omit<TRow, 'person'> & TRow['person'] {
|
||||
const { person, ...rest } = row;
|
||||
return { ...rest, ...person };
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ import type {
|
||||
import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import { contactPhone } from '@/modules/people/lib/people';
|
||||
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
|
||||
|
||||
type GetAttentionOverviewDeps = {
|
||||
@@ -82,9 +84,14 @@ export class GetAttentionOverview {
|
||||
db.user.findUnique({ where: { id: userId }, select: { country: true } }),
|
||||
db.attendee.findMany({
|
||||
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
|
||||
select: { id: true, groupId: true, fullName: true, phone: true, guardianPhone: true, createdAt: true },
|
||||
select: {
|
||||
id: true,
|
||||
groupId: true,
|
||||
createdAt: true,
|
||||
person: { select: { fullName: true, phone: true, guardianPhone: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}) as Promise<AttendeeRow[]>,
|
||||
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
|
||||
// Past classes only, most recent first: `toMemberAttendance` keeps the
|
||||
// last 20 per attendee, more than the 6-class window needs.
|
||||
db.classSession.findMany({
|
||||
@@ -154,7 +161,7 @@ export class GetAttentionOverview {
|
||||
firma: row.signature,
|
||||
}));
|
||||
|
||||
const phone = attendee.phone ?? attendee.guardianPhone;
|
||||
const phone = contactPhone(attendee);
|
||||
return {
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { passkey } from '@better-auth/passkey';
|
||||
import { appLocaleSchema } from '@gruperly/shared';
|
||||
import { betterAuth } from 'better-auth';
|
||||
import { prismaAdapter } from 'better-auth/adapters/prisma';
|
||||
import { organization } from 'better-auth/plugins/organization';
|
||||
@@ -11,6 +12,18 @@ export const auth = betterAuth({
|
||||
database: prismaAdapter(getPrismaClient(), {
|
||||
provider: 'postgresql',
|
||||
}),
|
||||
user: {
|
||||
additionalFields: {
|
||||
// UI language chosen in Ajustes; null means "follow the device". The web
|
||||
// saves it with updateUser and reads it back from the session.
|
||||
locale: {
|
||||
type: 'string',
|
||||
required: false,
|
||||
input: true,
|
||||
validator: { input: appLocaleSchema.nullable() },
|
||||
},
|
||||
},
|
||||
},
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
minPasswordLength: 8,
|
||||
|
||||
@@ -86,7 +86,7 @@ export type Entitlements = PlanResolution & {
|
||||
};
|
||||
|
||||
type PlanGuardDeps = {
|
||||
db?: Pick<PrismaClient, 'billingSubscription' | 'group' | 'attendee'>;
|
||||
db?: Pick<PrismaClient, 'billingSubscription' | 'group' | 'person'>;
|
||||
enforced?: boolean;
|
||||
graceDays?: number;
|
||||
now?: () => Date;
|
||||
@@ -116,7 +116,10 @@ export class PlanGuard {
|
||||
select: { status: true, authorizedAt: true, paidThrough: true },
|
||||
}),
|
||||
db.group.count({ where: { createdById: ownerId } }),
|
||||
db.attendee.count({ where: { status: 'ACTIVE', group: { createdById: ownerId } } }),
|
||||
// People, not memberships: someone in three groups is one student.
|
||||
db.person.count({
|
||||
where: { createdById: ownerId, attendees: { some: { status: 'ACTIVE' } } },
|
||||
}),
|
||||
]);
|
||||
|
||||
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());
|
||||
|
||||
@@ -32,6 +32,7 @@ export class GetAbsenceDetails {
|
||||
where: { notifyToken: query.token },
|
||||
include: {
|
||||
group: { select: { id: true, name: true, days: true, time: true } },
|
||||
person: { select: { fullName: true } },
|
||||
},
|
||||
});
|
||||
if (!attendee) {
|
||||
@@ -46,7 +47,7 @@ export class GetAbsenceDetails {
|
||||
if (candidates.length === 0) {
|
||||
return ok({
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
fullName: attendee.person.fullName,
|
||||
groupName: attendee.group.name,
|
||||
sessions: [],
|
||||
});
|
||||
@@ -75,7 +76,7 @@ export class GetAbsenceDetails {
|
||||
|
||||
return ok({
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
fullName: attendee.person.fullName,
|
||||
groupName: attendee.group.name,
|
||||
sessions: sessions.map((session) => {
|
||||
const attendanceStatus = attendanceBySession.get(session.id) ?? null;
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||
import { DEFAULT_TIME_ZONE, startOfDayInTimeZone } from '@/modules/home/lib/scheduler';
|
||||
import {
|
||||
type ClassesDb,
|
||||
@@ -60,8 +61,9 @@ export class GetSessionStudents {
|
||||
const [attendees, payments, attendances, releases] = await Promise.all([
|
||||
db.attendee.findMany({
|
||||
where: { groupId: session.groupId },
|
||||
orderBy: { fullName: 'asc' },
|
||||
}),
|
||||
orderBy: { person: { fullName: 'asc' } },
|
||||
include: { person: { select: { fullName: true } } },
|
||||
}).then((rows) => rows.map(flattenPerson)),
|
||||
db.payment.findMany({
|
||||
where: { groupId: session.groupId },
|
||||
select: { attendeeId: true, status: true, dueDate: true },
|
||||
|
||||
@@ -8,6 +8,7 @@ import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { countsAsNewStudent } from '@/modules/people/lib/people';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
type GroupWaitlistEntryRecord,
|
||||
@@ -17,7 +18,7 @@ import { promoteWaitlistEntryRecord } from '../../../group-waitlist/lib/promote'
|
||||
import { type GroupPreRegistrationRecord } from '../../lib/helpers';
|
||||
|
||||
type ApproveGroupPreRegistrationDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration' | 'person'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
@@ -53,7 +54,8 @@ export class ApproveGroupPreRegistration {
|
||||
);
|
||||
}
|
||||
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId);
|
||||
const isNewStudent = await countsAsNewStudent(db, userId, entry.phone);
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId, isNewStudent ? 1 : 0);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
@@ -1,19 +1,26 @@
|
||||
import { type PromoteGroupWaitlistEntry as PromoteBody, PromoteGroupWaitlistEntrySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { PromoteGroupWaitlistEntry } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/waitlist/:entryId/promote', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const groupId = c.req.param('groupId');
|
||||
const entryId = c.req.param('entryId');
|
||||
const useCase = new PromoteGroupWaitlistEntry();
|
||||
const result = await useCase.execute(groupId, entryId, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
route.post(
|
||||
'/:groupId/waitlist/:entryId/promote',
|
||||
validate.json(PromoteGroupWaitlistEntrySchema),
|
||||
async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const groupId = c.req.param('groupId');
|
||||
const entryId = c.req.param('entryId');
|
||||
const body = c.req.valid('json') as PromoteBody;
|
||||
const useCase = new PromoteGroupWaitlistEntry();
|
||||
const result = await useCase.execute(groupId, entryId, user.id, body.targetGroupId);
|
||||
return resultJson(c, result);
|
||||
},
|
||||
);
|
||||
|
||||
export default route;
|
||||
export default route;
|
||||
|
||||
@@ -4,6 +4,7 @@ import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { countsAsNewStudent } from '@/modules/people/lib/people';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
type GroupWaitlistEntryRecord,
|
||||
@@ -11,7 +12,7 @@ import {
|
||||
import { promoteWaitlistEntryRecord } from '../../lib/promote';
|
||||
|
||||
type PromoteGroupWaitlistEntryDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
@@ -23,6 +24,7 @@ export class PromoteGroupWaitlistEntry {
|
||||
groupId: string,
|
||||
entryId: string,
|
||||
userId: string,
|
||||
targetGroupId?: string,
|
||||
): Promise<Result<PromoteGroupWaitlistEntryResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
@@ -39,7 +41,19 @@ export class PromoteGroupWaitlistEntry {
|
||||
return err(notFoundResourceProblem('GroupWaitlistEntry', entryId));
|
||||
}
|
||||
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId);
|
||||
// The entry leaves the waitlist of its own group but can land in another
|
||||
// group of the same teacher (capacity and duplicates are checked there).
|
||||
let targetGroup = groupResult.value;
|
||||
if (targetGroupId && targetGroupId !== groupId) {
|
||||
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
|
||||
if (!targetResult.ok) {
|
||||
return targetResult;
|
||||
}
|
||||
targetGroup = targetResult.value;
|
||||
}
|
||||
|
||||
const isNewStudent = await countsAsNewStudent(db, userId, entry.phone);
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId, isNewStudent ? 1 : 0);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
@@ -48,7 +62,7 @@ export class PromoteGroupWaitlistEntry {
|
||||
async (tx: Prisma.TransactionClient) => {
|
||||
const promoteResult = await promoteWaitlistEntryRecord(
|
||||
tx,
|
||||
groupResult.value,
|
||||
targetGroup,
|
||||
entry as unknown as GroupWaitlistEntryRecord,
|
||||
);
|
||||
if (!promoteResult.ok) {
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { capacityReachedProblem, conflictProblem } from '@/http/problem-builders';
|
||||
import { type AttendeeRecord, toAttendeeDto } from '@/modules/attendees/lib/helpers';
|
||||
import { capacityReachedProblem } from '@/http/problem-builders';
|
||||
import { attendeeWithPerson, toAttendeeDto } from '@/modules/attendees/lib/helpers';
|
||||
import { alreadyInGroupProblem, findOrCreatePerson } from '@/modules/people/lib/people';
|
||||
import { type GroupWaitlistEntryRecord } from './helpers';
|
||||
|
||||
export type PromoteDb = Pick<PrismaClient, 'attendee' | 'groupWaitlistEntry'>;
|
||||
export type PromoteDb = Pick<PrismaClient, 'attendee' | 'groupWaitlistEntry' | 'person'>;
|
||||
|
||||
type PromoteGroup = {
|
||||
id: string;
|
||||
capacity: number | null;
|
||||
createdById: string;
|
||||
};
|
||||
|
||||
export async function findFirstPendingWaitlistEntry(
|
||||
@@ -23,11 +25,14 @@ export async function findFirstPendingWaitlistEntry(
|
||||
return record as GroupWaitlistEntryRecord | null;
|
||||
}
|
||||
|
||||
export async function promoteWaitlistEntryRecord(
|
||||
db: PromoteDb,
|
||||
group: PromoteGroup,
|
||||
entry: GroupWaitlistEntryRecord,
|
||||
): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
/* Whether someone can join `group`: free capacity (ACTIVE members) and the
|
||||
person (when there already is one) not being a member there yet. Shared by
|
||||
the waitlist promotion, the member move and "Agregar a otro grupo". */
|
||||
export async function checkCanJoinGroup(
|
||||
db: Pick<PrismaClient, 'attendee'>,
|
||||
group: Pick<PromoteGroup, 'id' | 'capacity'>,
|
||||
personId: string | null,
|
||||
): Promise<Result<void, ProblemDetails>> {
|
||||
if (group.capacity !== null) {
|
||||
const currentCount = await db.attendee.count({
|
||||
where: { groupId: group.id, status: 'ACTIVE' },
|
||||
@@ -37,29 +42,44 @@ export async function promoteWaitlistEntryRecord(
|
||||
}
|
||||
}
|
||||
|
||||
const existing = await db.attendee.findFirst({
|
||||
where: { groupId: group.id, phone: entry.phone },
|
||||
if (personId) {
|
||||
const existing = await db.attendee.findFirst({
|
||||
where: { groupId: group.id, personId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (existing) {
|
||||
return err(alreadyInGroupProblem());
|
||||
}
|
||||
}
|
||||
|
||||
return ok(undefined);
|
||||
}
|
||||
|
||||
/* The entry has its own contact data; if its phone is already one of the
|
||||
teacher's people, the new membership goes to that person. */
|
||||
export async function promoteWaitlistEntryRecord(
|
||||
db: PromoteDb,
|
||||
group: PromoteGroup,
|
||||
entry: GroupWaitlistEntryRecord,
|
||||
): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
const person = await findOrCreatePerson(db, group.createdById, {
|
||||
fullName: entry.fullName,
|
||||
phone: entry.phone,
|
||||
email: entry.email,
|
||||
notes: entry.notes,
|
||||
});
|
||||
if (existing) {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.',
|
||||
code: 'attendee_already_registered',
|
||||
}),
|
||||
);
|
||||
|
||||
const canJoin = await checkCanJoinGroup(db, group, person.created ? null : person.id);
|
||||
if (!canJoin.ok) {
|
||||
return canJoin;
|
||||
}
|
||||
|
||||
const attendee = await db.attendee.create({
|
||||
data: {
|
||||
groupId: group.id,
|
||||
fullName: entry.fullName,
|
||||
phone: entry.phone,
|
||||
email: entry.email,
|
||||
notes: entry.notes,
|
||||
},
|
||||
data: { groupId: group.id, personId: person.id },
|
||||
include: attendeeWithPerson,
|
||||
});
|
||||
|
||||
return ok(toAttendeeDto(attendee as unknown as AttendeeRecord));
|
||||
return ok(toAttendeeDto(attendee));
|
||||
}
|
||||
|
||||
export type PromoteFirstResult = {
|
||||
|
||||
@@ -21,13 +21,15 @@ type ListGroupsDeps = {
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
const OCCUPANCY_COUNT_INCLUDE = {
|
||||
const LIST_COUNT_INCLUDE = {
|
||||
_count: {
|
||||
select: {
|
||||
// Group members. No status filter, same as the detail page counts.
|
||||
attendees: true,
|
||||
// Waitlist: the ones still waiting for a spot (the reviewed ones drop out).
|
||||
waitlist: { where: { status: 'PENDING' as const } },
|
||||
// Payments still to collect: the ones pending and the overdue ones.
|
||||
payments: { where: { status: { in: ['PENDING' as const, 'OVERDUE' as const] } } },
|
||||
},
|
||||
},
|
||||
} satisfies Prisma.GroupInclude;
|
||||
@@ -49,7 +51,7 @@ export class ListGroups {
|
||||
// time zone (or the server's if it doesn't come along).
|
||||
const records: GroupListRecord[] = await db.group.findMany({
|
||||
where,
|
||||
include: OCCUPANCY_COUNT_INCLUDE,
|
||||
include: LIST_COUNT_INCLUDE,
|
||||
});
|
||||
|
||||
const timeZone = query.timeZone ?? DEFAULT_TIME_ZONE;
|
||||
|
||||
@@ -26,9 +26,10 @@ export type GroupRecord = {
|
||||
/* The listing adds the occupancy counters to each group so the card can show
|
||||
them without asking for one endpoint per group. They come from the `_count` of
|
||||
the same query: all the members (same as the detail page counts) and only the
|
||||
waitlist entries still waiting for a spot (PENDING). */
|
||||
waitlist entries still waiting for a spot (PENDING), plus the payments still
|
||||
to collect (PENDING and OVERDUE). */
|
||||
export type GroupListRecord = GroupRecord & {
|
||||
_count?: { attendees: number; waitlist: number };
|
||||
_count?: { attendees: number; waitlist: number; payments?: number };
|
||||
};
|
||||
|
||||
export function toGroupDto(record: GroupRecord): GroupDto {
|
||||
@@ -56,6 +57,7 @@ export function toGroupListItemDto(record: GroupListRecord): GroupListItem {
|
||||
...toGroupDto(record),
|
||||
attendeesCount: record._count?.attendees ?? 0,
|
||||
waitlistCount: record._count?.waitlist ?? 0,
|
||||
unpaidPaymentsCount: record._count?.payments ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { Hono } from 'hono';
|
||||
import analyticsRoutes from '../analytics/routes';
|
||||
import addAttendeeToGroupRoute from '../attendees/features/add-to-group/route';
|
||||
import addToGroupWaitlistRoute from '../attendees/features/add-to-waitlist/route';
|
||||
import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route';
|
||||
import createAttendeeRoute from '../attendees/features/create/route';
|
||||
import getAttendeeRoute from '../attendees/features/get-by-id/route';
|
||||
import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
||||
import moveAttendeeRoute from '../attendees/features/move/route';
|
||||
import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||
import updateAttendeeRoute from '../attendees/features/update/route';
|
||||
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||
@@ -37,6 +39,8 @@ routes.route('/', getAttendeeRoute);
|
||||
routes.route('/', updateAttendeeRoute);
|
||||
routes.route('/', getAttendeeStatsRoute);
|
||||
routes.route('/', removeAttendeeRoute);
|
||||
routes.route('/', moveAttendeeRoute);
|
||||
routes.route('/', addAttendeeToGroupRoute);
|
||||
routes.route('/', studentAccessRoutes);
|
||||
|
||||
export default routes;
|
||||
|
||||
@@ -74,7 +74,7 @@ export class GetHomeSummary {
|
||||
take: UPCOMING_PAYMENTS_LIMIT,
|
||||
include: {
|
||||
group: { select: { name: true } },
|
||||
attendee: { select: { fullName: true } },
|
||||
attendee: { select: { person: { select: { fullName: true } } } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
@@ -96,7 +96,7 @@ export class GetHomeSummary {
|
||||
dueDate: payment.dueDate.toISOString(),
|
||||
status: payment.status,
|
||||
groupName: payment.group.name,
|
||||
attendeeName: payment.attendee.fullName,
|
||||
attendeeName: payment.attendee.person.fullName,
|
||||
})),
|
||||
pendingPreRegistrations: groups
|
||||
.filter((group) => group._count.preRegistrations > 0)
|
||||
|
||||
@@ -4,6 +4,7 @@ import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
||||
import { phoneVariants } from '@/modules/people/lib/people';
|
||||
|
||||
type JoinViaInviteDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupPreRegistration'>;
|
||||
@@ -36,10 +37,7 @@ export class JoinViaInvite {
|
||||
const existing = await db.attendee.findFirst({
|
||||
where: {
|
||||
groupId: group.id,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
person: { phone: { in: phoneVariants(payload.phone) } },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -58,10 +56,7 @@ export class JoinViaInvite {
|
||||
const existingPreRegistration = await db.groupPreRegistration.findFirst({
|
||||
where: {
|
||||
groupId: group.id,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
phone: { in: phoneVariants(payload.phone) },
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import { logger } from '@/logger';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { getMpAccessToken } from '@/modules/mp';
|
||||
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
|
||||
import { CHECKOUT_BACK_PATH } from '../../lib';
|
||||
|
||||
type BatchDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
|
||||
@@ -80,6 +81,7 @@ export class CreatePaymentBatch {
|
||||
status: 'ACTIVE',
|
||||
...(input.attendeeIds ? { id: { in: input.attendeeIds } } : {}),
|
||||
},
|
||||
include: { person: { select: { fullName: true } } },
|
||||
});
|
||||
if (attendees.length === 0) {
|
||||
return err(noAttendeesToBillProblem());
|
||||
@@ -95,7 +97,7 @@ export class CreatePaymentBatch {
|
||||
return token;
|
||||
}
|
||||
|
||||
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}/payments`;
|
||||
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}${CHECKOUT_BACK_PATH}`;
|
||||
const dueDate = new Date(input.dueDate);
|
||||
const title = input.description?.trim() || group.name;
|
||||
const createPreference = this.deps.createPreference ?? createCheckoutPreference;
|
||||
@@ -149,7 +151,7 @@ export class CreatePaymentBatch {
|
||||
items.push({
|
||||
paymentId: payment.id,
|
||||
attendeeId: attendee.id,
|
||||
attendeeName: attendee.fullName,
|
||||
attendeeName: attendee.person.fullName,
|
||||
amount: unitPrice,
|
||||
currency,
|
||||
checkoutUrl: link?.initPoint ?? null,
|
||||
|
||||
@@ -36,7 +36,7 @@ export class ListPayments {
|
||||
where,
|
||||
include: {
|
||||
group: { select: { name: true, price: true } },
|
||||
attendee: { select: { fullName: true } },
|
||||
attendee: { select: { person: { select: { fullName: true } } } },
|
||||
},
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
|
||||
@@ -12,7 +12,7 @@ import { logger } from '@/logger';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { getMpAccessToken } from '@/modules/mp';
|
||||
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
|
||||
import { type PaymentRecord, toPaymentDto } from '../../lib';
|
||||
import { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from '../../lib';
|
||||
|
||||
type RenewDeps = {
|
||||
db?: Pick<PrismaClient, 'payment' | 'user'>;
|
||||
@@ -35,7 +35,7 @@ export class RenewPaymentLink {
|
||||
const payment = await db.payment.findUnique({
|
||||
where: { id: paymentId },
|
||||
include: {
|
||||
attendee: { select: { fullName: true } },
|
||||
attendee: { select: { person: { select: { fullName: true } } } },
|
||||
group: {
|
||||
select: {
|
||||
name: true,
|
||||
@@ -83,7 +83,7 @@ export class RenewPaymentLink {
|
||||
return token;
|
||||
}
|
||||
|
||||
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}/payments`;
|
||||
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}${CHECKOUT_BACK_PATH}`;
|
||||
const createPreference = this.deps.createPreference ?? createCheckoutPreference;
|
||||
|
||||
let preference: { initPoint: string; id: string };
|
||||
@@ -106,7 +106,7 @@ export class RenewPaymentLink {
|
||||
where: { id: payment.id },
|
||||
data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id },
|
||||
include: {
|
||||
attendee: { select: { fullName: true } },
|
||||
attendee: { select: { person: { select: { fullName: true } } } },
|
||||
group: { select: { name: true, price: true } },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -26,11 +26,12 @@ const reportSelect = {
|
||||
createdAt: true,
|
||||
totalAmount: true,
|
||||
currency: true,
|
||||
note: true,
|
||||
receiptKey: true,
|
||||
receiptMime: true,
|
||||
receiptName: true,
|
||||
receiptSize: true,
|
||||
attendee: { select: { id: true, fullName: true } },
|
||||
attendee: { select: { id: true, person: { select: { fullName: true } } } },
|
||||
group: { select: { id: true, name: true } },
|
||||
items: { select: { payment: { select: { id: true, description: true, dueDate: true, amount: true } } } },
|
||||
} satisfies Prisma.ReportedPaymentSelect;
|
||||
@@ -201,11 +202,12 @@ export class ReportedPayments {
|
||||
return {
|
||||
id: row.id,
|
||||
status: STATUS[row.status],
|
||||
attendee: row.attendee,
|
||||
attendee: { id: row.attendee.id, fullName: row.attendee.person.fullName },
|
||||
group: row.group,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
totalAmount: row.totalAmount.toNumber(),
|
||||
currency: row.currency,
|
||||
note: row.note,
|
||||
fees: row.items
|
||||
.map(({ payment }) => ({
|
||||
id: payment.id,
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { PaymentDto } from '@gruperly/shared';
|
||||
|
||||
/* Where Mercado Pago sends whoever paid a Checkout Pro link: the student app
|
||||
(without a student session it falls through to /access). */
|
||||
export const CHECKOUT_BACK_PATH = '/student/payments';
|
||||
|
||||
export type PaymentRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
@@ -14,7 +18,7 @@ export type PaymentRecord = {
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
group: { name: string; price: unknown };
|
||||
attendee: { fullName: string };
|
||||
attendee: { person: { fullName: string } };
|
||||
};
|
||||
|
||||
export function toPaymentDto(record: PaymentRecord): PaymentDto {
|
||||
@@ -23,7 +27,7 @@ export function toPaymentDto(record: PaymentRecord): PaymentDto {
|
||||
groupId: record.groupId,
|
||||
groupName: record.group.name,
|
||||
attendeeId: record.attendeeId,
|
||||
attendeeName: record.attendee.fullName,
|
||||
attendeeName: record.attendee.person.fullName,
|
||||
amount: Number(record.amount.toString()),
|
||||
currency: record.currency,
|
||||
status: record.status,
|
||||
|
||||
@@ -1 +1 @@
|
||||
export { type PaymentRecord, toPaymentDto } from './helpers';
|
||||
export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers';
|
||||
|
||||
18
apps/backend/src/modules/people/features/lookup/route.ts
Normal file
18
apps/backend/src/modules/people/features/lookup/route.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { PersonLookupQuery } from '@gruperly/shared';
|
||||
import { PersonLookupQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { LookupPerson } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/lookup', validate.query(PersonLookupQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const result = await new LookupPerson().execute(c.req.valid('query') as PersonLookupQuery, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
24
apps/backend/src/modules/people/features/lookup/use-case.ts
Normal file
24
apps/backend/src/modules/people/features/lookup/use-case.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { PersonLookupQuery, PersonSummary, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { findPersonSummaryByPhone } from '../../lib/people';
|
||||
|
||||
type LookupPersonDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'person'>;
|
||||
};
|
||||
|
||||
/* While the teacher types a phone in the add form: is it someone they already
|
||||
have? `null` when not. */
|
||||
export class LookupPerson {
|
||||
constructor(private readonly deps: LookupPersonDeps = {}) {}
|
||||
|
||||
async execute(query: PersonLookupQuery, userId: string): Promise<Result<PersonSummary | null, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const access = await findGroupForUser(db, query.groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
return ok(await findPersonSummaryByPhone(db, access.value.createdById, query.phone));
|
||||
}
|
||||
}
|
||||
1
apps/backend/src/modules/people/index.ts
Normal file
1
apps/backend/src/modules/people/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as peopleRoutes } from './routes';
|
||||
142
apps/backend/src/modules/people/lib/people.ts
Normal file
142
apps/backend/src/modules/people/lib/people.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { Prisma, type PrismaClient } from '@generated/prisma/client';
|
||||
import type { PersonMembership, PersonSummary, ProblemDetails } from '@gruperly/shared';
|
||||
import { conflictProblem } from '@/http/problem-builders';
|
||||
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
||||
|
||||
/* A person is the teacher's contact (student, or a guardian's child); their
|
||||
`attendees` are the memberships in each group. The phone is unique per
|
||||
teacher (partial index `people_owner_phone_key`), so it is how a new row is
|
||||
recognized as someone the teacher already has. */
|
||||
|
||||
export type PeopleDb = Pick<PrismaClient, 'person'>;
|
||||
|
||||
/* Phones are stored normalized, but older rows may keep what was typed. */
|
||||
export function phoneVariants(rawPhone: string): string[] {
|
||||
const normalized = normalizePhone(rawPhone);
|
||||
const trimmed = rawPhone.trim();
|
||||
return normalized === trimmed ? [normalized] : [normalized, trimmed];
|
||||
}
|
||||
|
||||
export const personMembershipsSelect = {
|
||||
attendees: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: { id: true, groupId: true, status: true, group: { select: { name: true } } },
|
||||
},
|
||||
} as const;
|
||||
|
||||
type MembershipRow = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
status: PersonMembership['status'];
|
||||
group: { name: string };
|
||||
};
|
||||
|
||||
export function toMemberships(rows: MembershipRow[]): PersonMembership[] {
|
||||
return rows.map((row) => ({
|
||||
attendeeId: row.id,
|
||||
groupId: row.groupId,
|
||||
groupName: row.group.name,
|
||||
status: row.status,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function findPersonByPhone(db: PeopleDb, ownerId: string, rawPhone: string) {
|
||||
return db.person.findFirst({
|
||||
where: { createdById: ownerId, phone: { in: phoneVariants(rawPhone) } },
|
||||
select: {
|
||||
id: true,
|
||||
fullName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
...personMembershipsSelect,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function findPersonSummaryByPhone(
|
||||
db: PeopleDb,
|
||||
ownerId: string,
|
||||
rawPhone: string,
|
||||
): Promise<PersonSummary | null> {
|
||||
const person = await findPersonByPhone(db, ownerId, rawPhone);
|
||||
if (!person) return null;
|
||||
return {
|
||||
id: person.id,
|
||||
fullName: person.fullName,
|
||||
email: person.email,
|
||||
phone: person.phone,
|
||||
groups: toMemberships(person.attendees),
|
||||
};
|
||||
}
|
||||
|
||||
export type NewPersonData = {
|
||||
fullName: string;
|
||||
phone: string | null;
|
||||
email?: string | null;
|
||||
notes?: string | null;
|
||||
};
|
||||
|
||||
/* Waitlist promotion, pre-registration approval and bulk import: the row has
|
||||
its own contact data, and if that phone is already one of the teacher's
|
||||
people the membership goes to that person (their data wins). */
|
||||
export async function findOrCreatePerson(
|
||||
db: PeopleDb,
|
||||
ownerId: string,
|
||||
data: NewPersonData,
|
||||
): Promise<{ id: string; created: boolean }> {
|
||||
if (data.phone) {
|
||||
const existing = await findPersonByPhone(db, ownerId, data.phone);
|
||||
if (existing) return { id: existing.id, created: false };
|
||||
}
|
||||
const person = await db.person.create({
|
||||
data: {
|
||||
createdById: ownerId,
|
||||
fullName: data.fullName,
|
||||
phone: data.phone,
|
||||
email: data.email ?? null,
|
||||
notes: data.notes ?? null,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return { id: person.id, created: true };
|
||||
}
|
||||
|
||||
/* Whether adding someone with this phone takes a new student slot of the plan:
|
||||
no when they are already an active member of another group. */
|
||||
export async function countsAsNewStudent(db: PeopleDb, ownerId: string, rawPhone: string | null): Promise<boolean> {
|
||||
if (!rawPhone) return true;
|
||||
const person = await findPersonByPhone(db, ownerId, rawPhone);
|
||||
return !person?.attendees.some((membership) => membership.status === 'ACTIVE');
|
||||
}
|
||||
|
||||
/* The number the teacher reaches the person on: theirs, or the guardian's. */
|
||||
export function contactPhone(person: { phone: string | null; guardianPhone: string | null }): string | null {
|
||||
return person.phone ?? person.guardianPhone;
|
||||
}
|
||||
|
||||
export function isUniqueViolation(error: unknown): boolean {
|
||||
return error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002';
|
||||
}
|
||||
|
||||
export function alreadyInGroupProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Esta persona ya es miembro de este grupo.',
|
||||
code: 'attendee_already_registered',
|
||||
});
|
||||
}
|
||||
|
||||
/* The phone belongs to someone the teacher already has: the web offers to add
|
||||
that person (`personId`) instead of creating a duplicate. */
|
||||
export function personExistsProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Ya tenés registrada a una persona con este número de teléfono.',
|
||||
code: 'person_exists',
|
||||
});
|
||||
}
|
||||
|
||||
export function personPhoneTakenProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Otra persona que tenés registrada ya usa este número de teléfono.',
|
||||
code: 'person_phone_taken',
|
||||
});
|
||||
}
|
||||
8
apps/backend/src/modules/people/routes.ts
Normal file
8
apps/backend/src/modules/people/routes.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Hono } from 'hono';
|
||||
import lookupRoute from './features/lookup/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', lookupRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -7,7 +7,7 @@ import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { computeStudentAccess } from '../../lib/status';
|
||||
|
||||
type GetStudentAccessDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountPerson'>;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
@@ -23,9 +23,9 @@ export class GetStudentAccess {
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { id: true } });
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { personId: true } });
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
return ok(await computeStudentAccess(db, attendeeId, this.deps.now ?? new Date()));
|
||||
return ok(await computeStudentAccess(db, attendee.personId, this.deps.now ?? new Date()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,11 +4,12 @@ import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { contactPhone } from '@/modules/people/lib/people';
|
||||
import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
|
||||
import { computeStudentAccess } from '../../lib/status';
|
||||
|
||||
type InviteStudentDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountPerson'>;
|
||||
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
|
||||
now?: Date;
|
||||
};
|
||||
@@ -36,9 +37,8 @@ export class InviteStudent {
|
||||
where: { id: attendeeId, groupId },
|
||||
select: {
|
||||
id: true,
|
||||
fullName: true,
|
||||
phone: true,
|
||||
guardianPhone: true,
|
||||
personId: true,
|
||||
person: { select: { fullName: true, phone: true, guardianPhone: true } },
|
||||
group: { select: { owner: { select: { country: true } } } },
|
||||
},
|
||||
});
|
||||
@@ -49,8 +49,9 @@ export class InviteStudent {
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||
|
||||
const issued = await unitOfWork.executeResult(async (tx) => {
|
||||
const link = await tx.studentAccountAttendee.findFirst({
|
||||
where: { attendeeId },
|
||||
// One account per person: inviting from any of their groups reuses it.
|
||||
const link = await tx.studentAccountPerson.findFirst({
|
||||
where: { personId: attendee.personId },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: { accountId: true },
|
||||
});
|
||||
@@ -58,7 +59,11 @@ export class InviteStudent {
|
||||
link?.accountId
|
||||
?? (
|
||||
await tx.studentAccount.create({
|
||||
data: { name: attendee.fullName, createdById: userId, attendees: { create: { attendeeId } } },
|
||||
data: {
|
||||
name: attendee.person.fullName,
|
||||
createdById: userId,
|
||||
people: { create: { personId: attendee.personId } },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
).id;
|
||||
@@ -90,8 +95,8 @@ export class InviteStudent {
|
||||
return ok({
|
||||
url: studentLinkUrl(token),
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
whatsappPhone: toWhatsappPhone(attendee.phone ?? attendee.guardianPhone, attendee.group.owner.country),
|
||||
access: await computeStudentAccess(db, attendeeId, now),
|
||||
whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country),
|
||||
access: await computeStudentAccess(db, attendee.personId, now),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ export class ListGroupAbsenceNotices {
|
||||
reason: true,
|
||||
message: true,
|
||||
createdAt: true,
|
||||
attendee: { select: { id: true, fullName: true } },
|
||||
attendee: { select: { id: true, person: { select: { fullName: true } } } },
|
||||
classSession: { select: { startsAt: true } },
|
||||
},
|
||||
});
|
||||
@@ -47,7 +47,7 @@ export class ListGroupAbsenceNotices {
|
||||
return ok({
|
||||
data: notices.map((notice) => ({
|
||||
id: notice.id,
|
||||
attendee: notice.attendee,
|
||||
attendee: { id: notice.attendee.id, fullName: notice.attendee.person.fullName },
|
||||
startsAt: notice.classSession.startsAt.toISOString(),
|
||||
reason: notice.reason ? REASON[notice.reason] : null,
|
||||
message: notice.message,
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { StudentAccessDto } from '@gruperly/shared';
|
||||
|
||||
export type StudentAccessStatusDb = Pick<PrismaClient, 'studentAccountAttendee'>;
|
||||
export type StudentAccessStatusDb = Pick<PrismaClient, 'studentAccountPerson'>;
|
||||
|
||||
/* Passive state for the attendee's card: active (a live session) > invited
|
||||
(a pending invitation) > expired (invited before, nothing alive) > not invited. */
|
||||
(a pending invitation) > expired (invited before, nothing alive) > not invited.
|
||||
It is the person's access, so every group of theirs shows the same state. */
|
||||
export async function computeStudentAccess(
|
||||
db: StudentAccessStatusDb,
|
||||
attendeeId: string,
|
||||
personId: string,
|
||||
now: Date,
|
||||
): Promise<StudentAccessDto> {
|
||||
const link = await db.studentAccountAttendee.findFirst({
|
||||
where: { attendeeId },
|
||||
const link = await db.studentAccountPerson.findFirst({
|
||||
where: { personId },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: {
|
||||
account: {
|
||||
|
||||
@@ -127,7 +127,7 @@ export class CancelStudentAbsence {
|
||||
where: {
|
||||
id: noticeId,
|
||||
cancelledAt: null,
|
||||
attendee: { status: { not: 'DROPPED' }, studentAccounts: { some: { accountId } } },
|
||||
attendee: { status: { not: 'DROPPED' }, person: { studentAccounts: { some: { accountId } } } },
|
||||
},
|
||||
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ route.get('/fees', studentSession, validate.query(StudentAttendeeQuerySchema), a
|
||||
return resultJson(c, await new GetStudentFees().execute(accountId, attendeeId));
|
||||
});
|
||||
|
||||
// multipart/form-data: attendeeId, paymentIds (repeated) and file.
|
||||
// multipart/form-data: attendeeId, paymentIds (repeated), file and an optional note.
|
||||
route.post('/payment-reports', studentSession, async (c) => {
|
||||
const { accountId } = currentStudent(c);
|
||||
// Reject oversized bodies before buffering them (10 MB + room for the fields).
|
||||
@@ -35,6 +35,7 @@ route.post('/payment-reports', studentSession, async (c) => {
|
||||
const attendeeId = form.get('attendeeId');
|
||||
const paymentIds = form.getAll('paymentIds').filter((value): value is string => typeof value === 'string' && value.length > 0);
|
||||
const file = form.get('file');
|
||||
const note = form.get('note');
|
||||
if (typeof attendeeId !== 'string' || paymentIds.length === 0 || !(file instanceof File)) {
|
||||
return problemJson(c, validationProblem({ detail: 'Elegí al menos una cuota y adjuntá el comprobante.' }));
|
||||
}
|
||||
@@ -42,6 +43,7 @@ route.post('/payment-reports', studentSession, async (c) => {
|
||||
const result = await new ReportStudentPayment().execute(accountId, {
|
||||
attendeeId,
|
||||
paymentIds,
|
||||
note: typeof note === 'string' ? note : null,
|
||||
file: { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()) },
|
||||
});
|
||||
return resultJson(c, result, { status: 201 });
|
||||
|
||||
@@ -54,6 +54,7 @@ export class GetStudentFees {
|
||||
status: true,
|
||||
createdAt: true,
|
||||
reviewedAt: true,
|
||||
note: true,
|
||||
rejectionReason: true,
|
||||
items: { select: { payment: { select: { id: true, description: true, dueDate: true } } } },
|
||||
},
|
||||
@@ -85,6 +86,7 @@ export class GetStudentFees {
|
||||
status: REPORT_STATUS[report.status],
|
||||
createdAt: report.createdAt.toISOString(),
|
||||
reviewedAt: report.reviewedAt?.toISOString() ?? null,
|
||||
note: report.note,
|
||||
rejectionReason: report.rejectionReason,
|
||||
fees: report.items.map(({ payment }) => ({
|
||||
id: payment.id,
|
||||
|
||||
@@ -32,10 +32,20 @@ export class GetStudentLinkInfo {
|
||||
account: {
|
||||
select: {
|
||||
name: true,
|
||||
attendees: {
|
||||
people: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
take: 1,
|
||||
select: { attendee: { select: { group: { select: { name: true, owner: { select: { name: true } } } } } } },
|
||||
select: {
|
||||
person: {
|
||||
select: {
|
||||
attendees: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
take: 1,
|
||||
select: { group: { select: { name: true, owner: { select: { name: true } } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -52,7 +62,7 @@ export class GetStudentLinkInfo {
|
||||
return ok({ status: 'invalid' });
|
||||
}
|
||||
|
||||
const group = row.account.attendees[0]?.attendee.group ?? null;
|
||||
const group = row.account.people[0]?.person.attendees[0]?.group ?? null;
|
||||
return ok({
|
||||
status: 'valid',
|
||||
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',
|
||||
|
||||
@@ -20,15 +20,21 @@ export class GetStudentMe {
|
||||
pendingRecoveryEmail: true,
|
||||
welcomedAt: true,
|
||||
_count: { select: { passkeys: true } },
|
||||
attendees: {
|
||||
where: { attendee: { status: { not: 'DROPPED' } } },
|
||||
// Linked people, and every group each of them is in.
|
||||
people: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: {
|
||||
attendee: {
|
||||
person: {
|
||||
select: {
|
||||
id: true,
|
||||
fullName: true,
|
||||
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
|
||||
attendees: {
|
||||
where: { status: { not: 'DROPPED' } },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: {
|
||||
id: true,
|
||||
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -46,13 +52,15 @@ export class GetStudentMe {
|
||||
hasPasskey: account._count.passkeys > 0,
|
||||
welcomed: account.welcomedAt !== null,
|
||||
},
|
||||
students: account.attendees.map(({ attendee }) => ({
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
groupId: attendee.group.id,
|
||||
groupName: attendee.group.name,
|
||||
teacherName: attendee.group.owner.name,
|
||||
})),
|
||||
students: account.people.flatMap(({ person }) =>
|
||||
person.attendees.map((attendee) => ({
|
||||
attendeeId: attendee.id,
|
||||
fullName: person.fullName,
|
||||
groupId: attendee.group.id,
|
||||
groupName: attendee.group.name,
|
||||
teacherName: attendee.group.owner.name,
|
||||
})),
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { Prisma, type PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { err, ok, REPORTED_PAYMENT_NOTE_MAX } from '@gruperly/shared';
|
||||
import { conflictProblem, validationProblem } from '@/http/problem-builders';
|
||||
import { detectReceiptType, RECEIPT_EXTENSIONS, RECEIPT_MAX_BYTES } from '@/lib/file-type';
|
||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||
@@ -19,6 +19,7 @@ type ReportPaymentDeps = {
|
||||
export type ReportPaymentInput = {
|
||||
attendeeId: string;
|
||||
paymentIds: string[];
|
||||
note?: string | null;
|
||||
file: { name: string; bytes: Uint8Array };
|
||||
};
|
||||
|
||||
@@ -37,6 +38,11 @@ export class ReportStudentPayment {
|
||||
const attendee = await findLinkedAttendee(db, accountId, input.attendeeId);
|
||||
if (!attendee) return err(studentAttendeeNotFoundProblem());
|
||||
|
||||
const note = input.note?.trim() || null;
|
||||
if (note && note.length > REPORTED_PAYMENT_NOTE_MAX) {
|
||||
return err(validationProblem({ detail: `La nota puede tener hasta ${REPORTED_PAYMENT_NOTE_MAX} caracteres.`, errors: { note: ['too_long'] } }));
|
||||
}
|
||||
|
||||
if (input.file.bytes.length === 0 || input.file.bytes.length > RECEIPT_MAX_BYTES) {
|
||||
return err(validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } }));
|
||||
}
|
||||
@@ -83,6 +89,7 @@ export class ReportStudentPayment {
|
||||
receiptMime: mime,
|
||||
receiptName: input.file.name.slice(0, 200) || `comprobante.${RECEIPT_EXTENSIONS[mime]}`,
|
||||
receiptSize: input.file.bytes.length,
|
||||
note,
|
||||
createdAt: now,
|
||||
items: { create: paymentIds.map((paymentId) => ({ paymentId })) },
|
||||
},
|
||||
|
||||
@@ -75,7 +75,7 @@ export class SetRecoveryEmail {
|
||||
await sender.sendStudentEmailConfirmation({
|
||||
email,
|
||||
name: account.name,
|
||||
url: `${webUrl()}/acceso/mail/${token}`,
|
||||
url: `${webUrl()}/access/email/${token}`,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error({ error, accountId }, 'Student recovery email confirmation could not be sent');
|
||||
|
||||
@@ -1,36 +1,21 @@
|
||||
import type { Prisma } from '@generated/prisma/client';
|
||||
|
||||
export type StudentAccessDb = {
|
||||
studentAccountAttendee: Prisma.StudentAccountAttendeeDelegate;
|
||||
};
|
||||
|
||||
/* The authorization rule of every student endpoint: only the attendees linked
|
||||
to the session's account. Anything else is a 404 (we don't confirm ids). */
|
||||
export async function linkedAttendeeIds(db: StudentAccessDb, accountId: string): Promise<string[]> {
|
||||
const links = await db.studentAccountAttendee.findMany({
|
||||
// A DROPPED attendee loses access; a PAUSED one keeps it.
|
||||
where: { accountId, attendee: { status: { not: 'DROPPED' } } },
|
||||
select: { attendeeId: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
return links.map((link) => link.attendeeId);
|
||||
}
|
||||
|
||||
export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate };
|
||||
|
||||
/* One attendee of the session, with what the student screens need from the
|
||||
group. null for an attendee not linked to the account (or DROPPED): routes
|
||||
answer 404, the same as for an id that doesn't exist. */
|
||||
/* The authorization rule of every student endpoint: an attendee (membership)
|
||||
of a person linked to the session's account, with what the student screens
|
||||
need from the group. The account is linked to the person, so every group
|
||||
they are in shows up. null for anything else (or DROPPED; PAUSED keeps
|
||||
access): routes answer 404, the same as for an id that doesn't exist. */
|
||||
export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) {
|
||||
return db.attendee.findFirst({
|
||||
where: {
|
||||
id: attendeeId,
|
||||
status: { not: 'DROPPED' },
|
||||
studentAccounts: { some: { accountId } },
|
||||
person: { studentAccounts: { some: { accountId } } },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
fullName: true,
|
||||
groupId: true,
|
||||
group: {
|
||||
select: {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { contactPhone } from '@/modules/people/lib/people';
|
||||
import {
|
||||
addTotals,
|
||||
type DispatchItem,
|
||||
@@ -69,7 +70,9 @@ export class SendPaymentReminders {
|
||||
currency: true,
|
||||
dueDate: true,
|
||||
checkoutUrl: true,
|
||||
attendee: { select: { id: true, fullName: true, phone: true, guardianPhone: true } },
|
||||
attendee: {
|
||||
select: { id: true, person: { select: { fullName: true, phone: true, guardianPhone: true } } },
|
||||
},
|
||||
},
|
||||
orderBy: { dueDate: 'asc' },
|
||||
});
|
||||
@@ -82,10 +85,10 @@ export class SendPaymentReminders {
|
||||
groupId: group.id,
|
||||
attendeeId: payment.attendee.id,
|
||||
paymentId: payment.id,
|
||||
rawPhone: payment.attendee.phone ?? payment.attendee.guardianPhone,
|
||||
rawPhone: contactPhone(payment.attendee.person),
|
||||
message: {
|
||||
kind: 'PAYMENT_REMINDER',
|
||||
studentName: payment.attendee.fullName,
|
||||
studentName: payment.attendee.person.fullName,
|
||||
groupName: group.name,
|
||||
amount: formatAmount(Number(payment.amount.toString()), payment.currency, country),
|
||||
dueDate: formatDueDate(payment.dueDate, country),
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
findStudentsAtRisk,
|
||||
type StudentsAtRiskDb,
|
||||
} from '@/modules/analytics/features/get-students-at-risk/use-case';
|
||||
import { contactPhone } from '@/modules/people/lib/people';
|
||||
import {
|
||||
addTotals,
|
||||
type DispatchItem,
|
||||
@@ -69,11 +70,11 @@ export class SendReengagementMessages {
|
||||
}),
|
||||
db.attendee.findMany({
|
||||
where: { id: { in: ids } },
|
||||
select: { id: true, phone: true, guardianPhone: true },
|
||||
select: { id: true, person: { select: { phone: true, guardianPhone: true } } },
|
||||
}),
|
||||
]);
|
||||
const coolingDown = new Set(recent.map((row) => row.attendeeId));
|
||||
const phones = new Map(contacts.map((row) => [row.id, row.phone ?? row.guardianPhone]));
|
||||
const phones = new Map(contacts.map((row) => [row.id, contactPhone(row.person)]));
|
||||
|
||||
for (const student of atRisk) {
|
||||
if (coolingDown.has(student.attendeeId)) continue;
|
||||
|
||||
175
apps/backend/test/attendee-add-to-group.test.ts
Normal file
175
apps/backend/test/attendee-add-to-group.test.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
const db = {
|
||||
group: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
attendee: {
|
||||
findFirst: mock(),
|
||||
count: mock(),
|
||||
create: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {
|
||||
executeResult = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
|
||||
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
|
||||
},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { groupsRoutes } from '@/modules/groups';
|
||||
|
||||
const teacherId = 'teacher-1';
|
||||
const group = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'group-1',
|
||||
name: 'Taller de Pintura',
|
||||
createdById: teacherId,
|
||||
capacity: 20,
|
||||
...overrides,
|
||||
});
|
||||
const targetGroup = (overrides: Record<string, unknown> = {}) =>
|
||||
group({ id: 'group-2', name: 'Taller de Cerámica', ...overrides });
|
||||
|
||||
const person = {
|
||||
id: 'person-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
};
|
||||
|
||||
const membership = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'att-2',
|
||||
groupId: 'group-2',
|
||||
personId: 'person-1',
|
||||
person,
|
||||
notifyToken: 'notify-2',
|
||||
status: 'ACTIVE',
|
||||
createdAt: new Date('2026-11-02T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-11-02T10:00:00.000Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function addRequest(targetGroupId: string, userId = teacherId) {
|
||||
const app = new Hono();
|
||||
app.use('*', async (c, next) => {
|
||||
c.set('user', { id: userId } as never);
|
||||
await next();
|
||||
});
|
||||
app.route('/groups', groupsRoutes);
|
||||
return app.request('/groups/group-1/attendees/att-1/add-to-group', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ targetGroupId }),
|
||||
});
|
||||
}
|
||||
|
||||
describe('POST /groups/:groupId/attendees/:attendeeId/add-to-group', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
prisma.group.findUnique.mockReset();
|
||||
prisma.attendee.findFirst.mockReset();
|
||||
prisma.group.findUnique
|
||||
.mockResolvedValueOnce(group() as never)
|
||||
.mockResolvedValueOnce(targetGroup() as never);
|
||||
prisma.attendee.count.mockResolvedValue(3);
|
||||
});
|
||||
|
||||
it('creates a membership of the same person in the target group', async () => {
|
||||
prisma.attendee.findFirst
|
||||
.mockResolvedValueOnce({ personId: 'person-1' } as never)
|
||||
.mockResolvedValueOnce(null);
|
||||
prisma.attendee.create.mockResolvedValue(membership() as never);
|
||||
|
||||
const res = await addRequest('group-2');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toMatchObject({
|
||||
id: 'att-2',
|
||||
groupId: 'group-2',
|
||||
personId: 'person-1',
|
||||
fullName: 'Martín Gómez',
|
||||
});
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
data: { groupId: 'group-2', personId: 'person-1' },
|
||||
include: { person: { select: expect.any(Object) } },
|
||||
});
|
||||
// The source membership is not touched.
|
||||
expect(prisma.attendee.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reactivates a former (DROPPED) membership in the target group', async () => {
|
||||
prisma.attendee.findFirst
|
||||
.mockResolvedValueOnce({ personId: 'person-1' } as never)
|
||||
.mockResolvedValueOnce({ id: 'att-old', status: 'DROPPED' } as never);
|
||||
prisma.attendee.update.mockResolvedValue(membership({ id: 'att-old' }) as never);
|
||||
|
||||
const res = await addRequest('group-2');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.attendee.update).toHaveBeenCalledWith({
|
||||
where: { id: 'att-old' },
|
||||
data: { status: 'ACTIVE' },
|
||||
include: { person: { select: expect.any(Object) } },
|
||||
});
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects with 409 when the person is already in the target group', async () => {
|
||||
prisma.attendee.findFirst
|
||||
.mockResolvedValueOnce({ personId: 'person-1' } as never)
|
||||
.mockResolvedValueOnce({ id: 'att-2', status: 'PAUSED' } as never);
|
||||
|
||||
const res = await addRequest('group-2');
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).code).toBe('attendee_already_registered');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects with 409 when the target group reached its capacity', async () => {
|
||||
prisma.group.findUnique.mockReset();
|
||||
prisma.group.findUnique
|
||||
.mockResolvedValueOnce(group() as never)
|
||||
.mockResolvedValueOnce(targetGroup({ capacity: 3 }) as never);
|
||||
prisma.attendee.findFirst
|
||||
.mockResolvedValueOnce({ personId: 'person-1' } as never)
|
||||
.mockResolvedValueOnce(null);
|
||||
|
||||
const res = await addRequest('group-2');
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).code).toBe('group_capacity_reached');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects adding to the same group', async () => {
|
||||
prisma.attendee.findFirst.mockResolvedValueOnce({ personId: 'person-1' } as never);
|
||||
|
||||
const res = await addRequest('group-1');
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).code).toBe('attendee_same_group');
|
||||
});
|
||||
|
||||
it('rejects a target group owned by another teacher', async () => {
|
||||
prisma.group.findUnique.mockReset();
|
||||
prisma.group.findUnique
|
||||
.mockResolvedValueOnce(group() as never)
|
||||
.mockResolvedValueOnce(targetGroup({ createdById: 'other-user' }) as never);
|
||||
prisma.attendee.findFirst.mockResolvedValueOnce({ personId: 'person-1' } as never);
|
||||
|
||||
const res = await addRequest('group-2');
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -38,12 +38,21 @@ function makeGroup(overrides: Record<string, unknown> = {}) {
|
||||
const attendee = {
|
||||
id: 'a-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Ana Pérez',
|
||||
email: 'ana@example.com',
|
||||
phone: '5512345678',
|
||||
guardianName: 'Luis Pérez',
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
personId: 'person-1',
|
||||
person: {
|
||||
id: 'person-1',
|
||||
fullName: 'Ana Pérez',
|
||||
email: 'ana@example.com',
|
||||
phone: '5512345678',
|
||||
guardianName: 'Luis Pérez',
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
// Every membership of the person: this one and another group.
|
||||
attendees: [
|
||||
{ id: 'a-1', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Funcional' } },
|
||||
{ id: 'a-2', groupId: 'group-2', status: 'PAUSED', group: { name: 'Yoga' } },
|
||||
],
|
||||
},
|
||||
notifyToken: 'token-1',
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
@@ -67,6 +76,7 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
|
||||
expect(await res.json()).toEqual({
|
||||
id: 'a-1',
|
||||
groupId: 'group-1',
|
||||
personId: 'person-1',
|
||||
fullName: 'Ana Pérez',
|
||||
email: 'ana@example.com',
|
||||
phone: '5512345678',
|
||||
@@ -77,10 +87,12 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
|
||||
createdAt: '2026-08-01T10:00:00.000Z',
|
||||
updatedAt: '2026-08-01T10:00:00.000Z',
|
||||
payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' },
|
||||
otherGroups: [{ attendeeId: 'a-2', groupId: 'group-2', groupName: 'Yoga', status: 'PAUSED' }],
|
||||
});
|
||||
expect(prisma.attendee.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: 'a-1', groupId: 'group-1' },
|
||||
include: {
|
||||
person: { select: expect.objectContaining({ fullName: true, attendees: expect.any(Object) }) },
|
||||
payments: {
|
||||
where: {
|
||||
status: { not: 'CANCELLED' },
|
||||
|
||||
220
apps/backend/test/attendee-move.test.ts
Normal file
220
apps/backend/test/attendee-move.test.ts
Normal file
@@ -0,0 +1,220 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
const db = {
|
||||
group: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
attendee: {
|
||||
findFirst: mock(),
|
||||
count: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
absenceNotice: {
|
||||
updateMany: mock(),
|
||||
},
|
||||
attendance: {
|
||||
deleteMany: mock(),
|
||||
},
|
||||
slotRelease: {
|
||||
deleteMany: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {
|
||||
executeResult = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
|
||||
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
|
||||
},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { groupsRoutes } from '@/modules/groups';
|
||||
|
||||
const teacherId = 'teacher-1';
|
||||
const group = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'group-1',
|
||||
name: 'Taller de Pintura',
|
||||
description: null,
|
||||
createdById: teacherId,
|
||||
inviteToken: null,
|
||||
createdAt: new Date('2026-09-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-01T10:00:00.000Z'),
|
||||
days: ['MONDAY'],
|
||||
time: '18:00',
|
||||
capacity: 20,
|
||||
price: 1500,
|
||||
billingType: 'MONTHLY',
|
||||
dueDay: 10,
|
||||
...overrides,
|
||||
});
|
||||
const targetGroup = (overrides: Record<string, unknown> = {}) =>
|
||||
group({ id: 'group-2', name: 'Taller de Cerámica', ...overrides });
|
||||
|
||||
const attendee = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'att-1',
|
||||
groupId: 'group-1',
|
||||
personId: 'person-1',
|
||||
person: {
|
||||
id: 'person-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
},
|
||||
notifyToken: 'notify-1',
|
||||
status: 'ACTIVE',
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function moveRequest(targetGroupId: string, userId = teacherId, attendeeId = 'att-1') {
|
||||
const app = new Hono();
|
||||
app.use('*', async (c, next) => {
|
||||
c.set('user', { id: userId } as never);
|
||||
await next();
|
||||
});
|
||||
app.route('/groups', groupsRoutes);
|
||||
return app.request(`/groups/group-1/attendees/${attendeeId}/move`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ targetGroupId }),
|
||||
});
|
||||
}
|
||||
|
||||
describe('POST /groups/:groupId/attendees/:attendeeId/move', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
prisma.group.findUnique.mockReset();
|
||||
});
|
||||
|
||||
it('moves the member to the target group and undoes the old group future bookings', async () => {
|
||||
prisma.group.findUnique
|
||||
.mockResolvedValueOnce(group() as never)
|
||||
.mockResolvedValueOnce(targetGroup() as never);
|
||||
prisma.attendee.findFirst.mockResolvedValueOnce(attendee() as never).mockResolvedValueOnce(null);
|
||||
prisma.attendee.count.mockResolvedValue(3);
|
||||
prisma.attendee.update.mockResolvedValue(attendee({ groupId: 'group-2' }) as never);
|
||||
|
||||
const res = await moveRequest('group-2');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.groupId).toBe('group-2');
|
||||
expect(prisma.attendee.update).toHaveBeenCalledWith({
|
||||
where: { id: 'att-1' },
|
||||
data: { groupId: 'group-2' },
|
||||
include: { person: { select: expect.any(Object) } },
|
||||
});
|
||||
const futureOldClasses = {
|
||||
classSession: { groupId: 'group-1', startsAt: { gt: expect.any(Date) } },
|
||||
};
|
||||
expect(prisma.absenceNotice.updateMany).toHaveBeenCalledWith({
|
||||
where: { attendeeId: 'att-1', cancelledAt: null, ...futureOldClasses },
|
||||
data: { cancelledAt: expect.any(Date) },
|
||||
});
|
||||
expect(prisma.attendance.deleteMany).toHaveBeenCalledWith({
|
||||
where: { attendeeId: 'att-1', ...futureOldClasses },
|
||||
});
|
||||
expect(prisma.slotRelease.deleteMany).toHaveBeenCalledWith({
|
||||
where: { attendeeId: 'att-1', isClaimed: false, ...futureOldClasses },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects moving to the same group', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(group() as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
|
||||
|
||||
const res = await moveRequest('group-1');
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).code).toBe('attendee_same_group');
|
||||
expect(prisma.attendee.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a target group owned by another teacher', async () => {
|
||||
prisma.group.findUnique
|
||||
.mockResolvedValueOnce(group() as never)
|
||||
.mockResolvedValueOnce(targetGroup({ createdById: 'other-user' }) as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
|
||||
|
||||
const res = await moveRequest('group-2');
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.attendee.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 404 when the target group does not exist', async () => {
|
||||
prisma.group.findUnique.mockResolvedValueOnce(group() as never).mockResolvedValueOnce(null);
|
||||
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
|
||||
|
||||
const res = await moveRequest('group-missing');
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
expect(prisma.attendee.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects with 409 when the target group reached its capacity', async () => {
|
||||
prisma.group.findUnique
|
||||
.mockResolvedValueOnce(group() as never)
|
||||
.mockResolvedValueOnce(targetGroup({ capacity: 5 }) as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
|
||||
const res = await moveRequest('group-2');
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).code).toBe('group_capacity_reached');
|
||||
expect(prisma.attendee.update).not.toHaveBeenCalled();
|
||||
expect(prisma.absenceNotice.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects with 409 when the person is already a member of the target group', async () => {
|
||||
prisma.group.findUnique
|
||||
.mockResolvedValueOnce(group() as never)
|
||||
.mockResolvedValueOnce(targetGroup() as never);
|
||||
prisma.attendee.findFirst
|
||||
.mockResolvedValueOnce(attendee() as never)
|
||||
.mockResolvedValueOnce({ id: 'att-existing' } as never);
|
||||
prisma.attendee.count.mockResolvedValue(3);
|
||||
|
||||
const res = await moveRequest('group-2');
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).code).toBe('attendee_already_registered');
|
||||
expect(prisma.attendee.findFirst).toHaveBeenLastCalledWith({
|
||||
where: { groupId: 'group-2', personId: 'person-1' },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(prisma.attendee.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 404 when the member is not in the group', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(group() as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
|
||||
const res = await moveRequest('group-2', teacherId, 'att-missing');
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('rejects a non-owner user', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(group() as never);
|
||||
|
||||
const res = await moveRequest('group-2', 'other-user');
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.attendee.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 400 without a target group', async () => {
|
||||
const res = await moveRequest('');
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'
|
||||
import { Prisma } from '@generated/prisma/client'
|
||||
import { Hono } from 'hono'
|
||||
|
||||
const db = {
|
||||
group: { findUnique: mock() },
|
||||
attendee: { findFirst: mock(), update: mock() },
|
||||
attendee: { findFirst: mock(), findUniqueOrThrow: mock() },
|
||||
person: { update: mock() },
|
||||
}
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
@@ -15,15 +17,20 @@ mock.module('@/lib/prisma', () => ({
|
||||
import updateAttendeeRoute from '@/modules/attendees/features/update/route'
|
||||
|
||||
const userId = 'user-1'
|
||||
const attendee = {
|
||||
id: 'a-1',
|
||||
groupId: 'group-1',
|
||||
const person = {
|
||||
id: 'person-1',
|
||||
fullName: 'Ana Pérez',
|
||||
email: null,
|
||||
phone: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: 'Llega temprano',
|
||||
}
|
||||
const attendee = {
|
||||
id: 'a-1',
|
||||
groupId: 'group-1',
|
||||
personId: 'person-1',
|
||||
person,
|
||||
notifyToken: 'token-1',
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-10-01T12:00:00.000Z'),
|
||||
@@ -51,11 +58,10 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
|
||||
db.attendee.findFirst.mockResolvedValue(attendee)
|
||||
})
|
||||
|
||||
it('actualiza contacto y conserva los campos vacíos como null', async () => {
|
||||
db.attendee.update.mockResolvedValue({
|
||||
it('actualiza el contacto de la persona y conserva los campos vacíos como null', async () => {
|
||||
db.attendee.findUniqueOrThrow.mockResolvedValue({
|
||||
...attendee,
|
||||
email: 'ana@example.com',
|
||||
phone: null,
|
||||
person: { ...person, email: 'ana@example.com' },
|
||||
})
|
||||
|
||||
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
|
||||
@@ -65,14 +71,49 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
|
||||
})
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(db.attendee.update).toHaveBeenCalledWith({
|
||||
where: { id: 'a-1' },
|
||||
expect(await response.json()).toMatchObject({ id: 'a-1', personId: 'person-1', email: 'ana@example.com' })
|
||||
// The person's row: the change shows in every group they are in.
|
||||
expect(db.person.update).toHaveBeenCalledWith({
|
||||
where: { id: 'person-1' },
|
||||
data: { email: 'ana@example.com', phone: null },
|
||||
})
|
||||
})
|
||||
|
||||
it('normaliza el teléfono como el alta', async () => {
|
||||
db.attendee.findUniqueOrThrow.mockResolvedValue(attendee)
|
||||
|
||||
await makeApp().request('/groups/group-1/attendees/a-1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ phone: '11 2345-6789' }),
|
||||
})
|
||||
|
||||
expect(db.person.update).toHaveBeenCalledWith({
|
||||
where: { id: 'person-1' },
|
||||
data: { phone: '1123456789' },
|
||||
})
|
||||
})
|
||||
|
||||
it('devuelve 409 si el teléfono ya es de otra persona del profe', async () => {
|
||||
db.person.update.mockRejectedValueOnce(
|
||||
new Prisma.PrismaClientKnownRequestError('Unique constraint failed', {
|
||||
code: 'P2002',
|
||||
clientVersion: 'test',
|
||||
}),
|
||||
)
|
||||
|
||||
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ phone: '1123456789' }),
|
||||
})
|
||||
|
||||
expect(response.status).toBe(409)
|
||||
expect(await response.json()).toMatchObject({ code: 'person_phone_taken' })
|
||||
})
|
||||
|
||||
it('actualiza una única nota', async () => {
|
||||
db.attendee.update.mockResolvedValue({ ...attendee, notes: 'Traer colchoneta' })
|
||||
db.attendee.findUniqueOrThrow.mockResolvedValue({ ...attendee, person: { ...person, notes: 'Traer colchoneta' } })
|
||||
|
||||
await makeApp().request('/groups/group-1/attendees/a-1', {
|
||||
method: 'PATCH',
|
||||
@@ -80,8 +121,8 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
|
||||
body: JSON.stringify({ notes: 'Traer colchoneta' }),
|
||||
})
|
||||
|
||||
expect(db.attendee.update).toHaveBeenCalledWith({
|
||||
where: { id: 'a-1' },
|
||||
expect(db.person.update).toHaveBeenCalledWith({
|
||||
where: { id: 'person-1' },
|
||||
data: { notes: 'Traer colchoneta' },
|
||||
})
|
||||
})
|
||||
@@ -94,6 +135,6 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
|
||||
})
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(db.attendee.update).not.toHaveBeenCalled()
|
||||
expect(db.person.update).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -15,6 +15,10 @@ const db = {
|
||||
create: mock(),
|
||||
count: mock(),
|
||||
},
|
||||
person: {
|
||||
findFirst: mock(),
|
||||
findMany: mock(),
|
||||
},
|
||||
groupWaitlistEntry: {
|
||||
findMany: mock(),
|
||||
findFirst: mock(),
|
||||
@@ -60,9 +64,34 @@ function makeApp(userValue: unknown) {
|
||||
return app;
|
||||
}
|
||||
|
||||
const personRow = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'person-1',
|
||||
fullName: 'Martín Gómez',
|
||||
email: 'martin@example.com',
|
||||
phone: '+5491133445566',
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: 'Viene con su hermano',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const attendeeRow = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'att-1',
|
||||
groupId: 'group-1',
|
||||
personId: 'person-1',
|
||||
person: personRow(),
|
||||
notifyToken: null,
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('attendee incorporation & invite-token in groups', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Nobody with that phone among the teacher's people, unless a test says so.
|
||||
prisma.person.findFirst.mockResolvedValue(null);
|
||||
prisma.person.findMany.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
describe('GET /groups/:groupId/invite-token', () => {
|
||||
@@ -109,18 +138,7 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
it('creates an attendee for the group', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.create.mockResolvedValue({
|
||||
id: 'att-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
email: 'martin@example.com',
|
||||
phone: '+5491133445566',
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: 'Viene con su hermano',
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
} as never);
|
||||
prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
|
||||
|
||||
const app = makeApp({ id: teacherId });
|
||||
const res = await app.request('/groups/group-1/attendees', {
|
||||
@@ -140,20 +158,95 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
expect(data.outcome).toBe('created');
|
||||
expect(data.attendee.fullName).toBe('Martín Gómez');
|
||||
expect(data.attendee.phone).toBe('+5491133445566');
|
||||
expect(data.attendee.personId).toBe('person-1');
|
||||
// A new person of the group owner, created with the membership.
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: 'martin@example.com',
|
||||
notes: 'Viene con su hermano',
|
||||
group: { connect: { id: 'group-1' } },
|
||||
person: {
|
||||
create: {
|
||||
createdById: teacherId,
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: 'martin@example.com',
|
||||
notes: 'Viene con su hermano',
|
||||
},
|
||||
},
|
||||
},
|
||||
include: { person: { select: expect.any(Object) } },
|
||||
});
|
||||
});
|
||||
|
||||
it('answers person_exists when the phone is already a person of another group', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.person.findFirst.mockResolvedValue({
|
||||
...personRow(),
|
||||
attendees: [{ id: 'att-9', groupId: 'group-9', status: 'ACTIVE', group: { name: 'Yoga' } }],
|
||||
} as never);
|
||||
|
||||
const app = makeApp({ id: teacherId });
|
||||
const res = await app.request('/groups/group-1/attendees', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ firstName: 'Martín', lastName: 'Gómez', phone: '+54 9 11 3344-5566' }),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).code).toBe('person_exists');
|
||||
expect(prisma.person.findFirst).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { createdById: teacherId, phone: { in: ['+5491133445566', '+54 9 11 3344-5566'] } },
|
||||
}),
|
||||
);
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('adds an existing person (personId) to the group without a new plan slot', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.person.findFirst.mockResolvedValue({ id: 'person-1', fullName: 'Martín Gómez' } as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.count.mockResolvedValue(1);
|
||||
prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
|
||||
|
||||
const app = makeApp({ id: teacherId });
|
||||
const res = await app.request('/groups/group-1/attendees', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ firstName: 'x', phone: '1133445566', personId: 'person-1' }),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(prisma.person.findFirst).toHaveBeenCalledWith({
|
||||
where: { id: 'person-1', createdById: teacherId },
|
||||
select: { id: true, fullName: true },
|
||||
});
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
data: { group: { connect: { id: 'group-1' } }, person: { connect: { id: 'person-1' } } },
|
||||
include: { person: { select: expect.any(Object) } },
|
||||
});
|
||||
});
|
||||
|
||||
it('returns 404 for a personId of another teacher', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.person.findFirst.mockResolvedValue(null);
|
||||
|
||||
const app = makeApp({ id: teacherId });
|
||||
const res = await app.request('/groups/group-1/attendees', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ firstName: 'x', phone: '1133445566', personId: 'person-other' }),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects duplicate phone number in individual add', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never);
|
||||
prisma.person.findFirst.mockResolvedValue({
|
||||
...personRow(),
|
||||
attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }],
|
||||
} as never);
|
||||
|
||||
const app = makeApp({ id: teacherId });
|
||||
const res = await app.request('/groups/group-1/attendees', {
|
||||
@@ -197,18 +290,7 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.count.mockResolvedValue(20);
|
||||
prisma.attendee.create.mockResolvedValue({
|
||||
id: 'att-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
email: null,
|
||||
phone: '+5491133445566',
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
} as never);
|
||||
prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
|
||||
|
||||
const app = makeApp({ id: teacherId });
|
||||
const res = await app.request('/groups/group-1/attendees?allowOverflow=true', {
|
||||
@@ -412,16 +494,19 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
describe('POST /groups/:groupId/attendees/bulk (bulk import)', () => {
|
||||
it('imports multiple attendees, skipping duplicates and reporting counts', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
// Simulate that an attendee with phone '11111111' already exists
|
||||
prisma.attendee.findMany.mockResolvedValue([
|
||||
{ phone: '11111111' },
|
||||
// The teacher's people: '11111111' is already in this group, '44444444'
|
||||
// is in another group only (and active there).
|
||||
prisma.person.findMany.mockResolvedValue([
|
||||
{ id: 'person-in-group', phone: '11111111', attendees: [{ groupId: 'group-1', status: 'ACTIVE' }] },
|
||||
{ id: 'person-elsewhere', phone: '44444444', attendees: [{ groupId: 'group-9', status: 'ACTIVE' }] },
|
||||
] as never);
|
||||
|
||||
prisma.attendee.create.mockImplementation(async ({ data }: { data: any }) => ({
|
||||
id: `att-${Math.random()}`,
|
||||
...data,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
groupId: 'group-1',
|
||||
personId: data.personId ?? 'person-new',
|
||||
notifyToken: null,
|
||||
person: personRow({ fullName: data.person?.create?.fullName ?? 'Existente' }),
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
}));
|
||||
@@ -434,19 +519,27 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
attendees: [
|
||||
{ firstName: 'Ana', lastName: 'García', phone: '22222222' },
|
||||
{ firstName: 'Pedro', lastName: 'López', phone: '33333333' },
|
||||
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the DB
|
||||
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the group
|
||||
{ firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicate within the batch
|
||||
{ firstName: 'Otra', lastName: 'Persona', phone: '44444444' }, // In another group: linked
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
const data = await res.json();
|
||||
expect(data.totalProcessed).toBe(4);
|
||||
expect(data.createdCount).toBe(2);
|
||||
expect(data.totalProcessed).toBe(5);
|
||||
expect(data.createdCount).toBe(3);
|
||||
expect(data.linkedCount).toBe(1);
|
||||
expect(data.duplicatesCount).toBe(2);
|
||||
expect(data.message).toBe('2 alumnos agregados con éxito, 2 duplicados omitidos.');
|
||||
expect(prisma.attendee.create).toHaveBeenCalledTimes(2);
|
||||
expect(data.message).toBe(
|
||||
'3 alumnos agregados con éxito (1 ya estaban en otros de tus grupos), 2 duplicados omitidos.',
|
||||
);
|
||||
expect(prisma.attendee.create).toHaveBeenCalledTimes(3);
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
data: { groupId: 'group-1', personId: 'person-elsewhere' },
|
||||
include: { person: { select: expect.any(Object) } },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -456,12 +549,8 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
{
|
||||
id: 'att-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Ana García',
|
||||
email: null,
|
||||
phone: '22222222',
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
personId: 'person-1',
|
||||
person: personRow({ fullName: 'Ana García', phone: '22222222', email: null, notes: null }),
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
attendances: [],
|
||||
@@ -487,6 +576,7 @@ describe('attendee incorporation & invite-token in groups', () => {
|
||||
// The row summary is requested in the same query: one request per
|
||||
// member would be N+1 over a listing of up to 100.
|
||||
include: {
|
||||
person: { select: expect.any(Object) },
|
||||
attendances: {
|
||||
orderBy: { classSession: { startsAt: 'desc' } },
|
||||
take: RECENT_ATTENDANCE_LIMIT,
|
||||
|
||||
@@ -11,12 +11,16 @@ function record(
|
||||
return {
|
||||
id: 'att-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Ana Pérez',
|
||||
email: null,
|
||||
phone: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
personId: 'person-1',
|
||||
person: {
|
||||
id: 'person-1',
|
||||
fullName: 'Ana Pérez',
|
||||
email: null,
|
||||
phone: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
},
|
||||
notifyToken: null,
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
@@ -89,10 +93,12 @@ describe('toAttendeeListItemDto', () => {
|
||||
});
|
||||
|
||||
it('conserva los campos del DTO plano', () => {
|
||||
const dto = toAttendeeListItemDto(record({ phone: '22222222' }));
|
||||
const base = record();
|
||||
const dto = toAttendeeListItemDto(record({ person: { ...base.person, phone: '22222222' } }));
|
||||
|
||||
expect(dto.fullName).toBe('Ana Pérez');
|
||||
expect(dto.phone).toBe('22222222');
|
||||
expect(dto.personId).toBe('person-1');
|
||||
expect(dto.createdAt).toBe('2026-08-01T10:00:00.000Z');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,15 +19,30 @@ import { attendeesRoutes } from '@/modules/attendees';
|
||||
const app = new Hono();
|
||||
app.route('/attendees', attendeesRoutes);
|
||||
|
||||
const attendeeRow = {
|
||||
id: 'attendee-1',
|
||||
groupId: 'group-1',
|
||||
const personSelect = {
|
||||
id: true,
|
||||
fullName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
guardianName: true,
|
||||
guardianPhone: true,
|
||||
notes: true,
|
||||
};
|
||||
|
||||
const person = {
|
||||
id: 'person-1',
|
||||
fullName: 'Ana Pérez',
|
||||
email: 'ana@example.com',
|
||||
phone: null,
|
||||
guardianName: 'Luis Pérez',
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
};
|
||||
|
||||
const attendeeRow = {
|
||||
id: 'attendee-1',
|
||||
groupId: 'group-1',
|
||||
personId: 'person-1',
|
||||
notifyToken: null,
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
@@ -36,6 +51,7 @@ const attendeeRow = {
|
||||
// What the Prisma mock returns: the row plus the summary relations.
|
||||
const attendee = {
|
||||
...attendeeRow,
|
||||
person,
|
||||
attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }],
|
||||
payments: [{ status: 'OVERDUE', dueDate: new Date('2026-09-10T00:00:00.000Z') }],
|
||||
};
|
||||
@@ -56,6 +72,12 @@ describe('attendees routes', () => {
|
||||
data: [
|
||||
{
|
||||
...attendeeRow,
|
||||
fullName: person.fullName,
|
||||
email: person.email,
|
||||
phone: person.phone,
|
||||
guardianName: person.guardianName,
|
||||
guardianPhone: person.guardianPhone,
|
||||
notes: person.notes,
|
||||
createdAt: attendeeRow.createdAt.toISOString(),
|
||||
updatedAt: attendeeRow.updatedAt.toISOString(),
|
||||
// The query comes most recent first; the row shows them
|
||||
@@ -71,6 +93,7 @@ describe('attendees routes', () => {
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
person: { select: personSelect },
|
||||
attendances: {
|
||||
orderBy: { classSession: { startsAt: 'desc' } },
|
||||
take: RECENT_ATTENDANCE_LIMIT,
|
||||
|
||||
@@ -12,7 +12,8 @@ function makeDb(params: {
|
||||
return {
|
||||
billingSubscription: { findUnique: mock(async () => params.subscription ?? null) },
|
||||
group: { count: mock(async () => params.groups ?? 0) },
|
||||
attendee: { count: mock(async () => params.attendees ?? 0) },
|
||||
// People with an active membership: someone in two groups counts once.
|
||||
person: { count: mock(async () => params.attendees ?? 0) },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,14 @@ describe('plan guards in the use cases', () => {
|
||||
it('checks a bulk import against the group owner, with the number of new attendees', async () => {
|
||||
const db = {
|
||||
group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, members: [{ userId: 'admin-1' }] })) },
|
||||
attendee: { findMany: mock(async () => [{ phone: '1111' }]), create: mock() },
|
||||
attendee: { create: mock() },
|
||||
// '1111' is already in this group; '4444' is active in another group.
|
||||
person: {
|
||||
findMany: mock(async () => [
|
||||
{ id: 'p1', phone: '1111', attendees: [{ groupId: 'g1', status: 'ACTIVE' }] },
|
||||
{ id: 'p4', phone: '4444', attendees: [{ groupId: 'g2', status: 'ACTIVE' }] },
|
||||
]),
|
||||
},
|
||||
};
|
||||
const planGuard = { canAddAttendees: mock(async () => err(planLimitReachedProblem('attendees', 15))) };
|
||||
|
||||
@@ -38,9 +45,11 @@ describe('plan guards in the use cases', () => {
|
||||
{ fullName: 'Ana', phone: '2222' },
|
||||
{ fullName: 'Beto', phone: '3333' },
|
||||
{ fullName: 'Repetido', phone: '1111' },
|
||||
{ fullName: 'De otro grupo', phone: '4444' },
|
||||
],
|
||||
} as never);
|
||||
|
||||
// Only the two new people: the one already active elsewhere takes no slot.
|
||||
expect(planGuard.canAddAttendees).toHaveBeenCalledWith(ownerId, 2);
|
||||
expect(result.ok).toBe(false);
|
||||
expect(db.attendee.create).not.toHaveBeenCalled();
|
||||
|
||||
@@ -159,8 +159,8 @@ describe('classes routes', () => {
|
||||
it('incluye estado de pago dinámico, asistencia y ausencia avisada', async () => {
|
||||
prisma.classSession.findUnique.mockResolvedValue(makeSession());
|
||||
prisma.attendee.findMany.mockResolvedValue([
|
||||
{ id: 'attendee-1', fullName: 'Ana Pérez' },
|
||||
{ id: 'attendee-2', fullName: 'Bruno Díaz' },
|
||||
{ id: 'attendee-1', person: { fullName: 'Ana Pérez' } },
|
||||
{ id: 'attendee-2', person: { fullName: 'Bruno Díaz' } },
|
||||
]);
|
||||
prisma.payment.findMany.mockResolvedValue([
|
||||
{ attendeeId: 'attendee-1', status: 'OVERDUE', dueDate: new Date('2026-09-01T00:00:00.000Z') },
|
||||
@@ -443,7 +443,7 @@ describe('classes routes', () => {
|
||||
|
||||
prisma.attendee.findUnique.mockResolvedValue({
|
||||
id: 'attendee-1',
|
||||
fullName: 'Ana Pérez',
|
||||
person: { fullName: 'Ana Pérez' },
|
||||
group: {
|
||||
id: 'group-1',
|
||||
name: 'Funcional',
|
||||
|
||||
@@ -63,7 +63,10 @@ describe.skipIf(!url)('payment review (real database)', () => {
|
||||
],
|
||||
});
|
||||
await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.teacher } });
|
||||
await db.attendee.create({ data: { id: ids.ana, groupId: ids.group, fullName: 'Ana', createdAt: new Date('2026-01-01T00:00:00Z') } });
|
||||
await db.person.create({ data: { id: `${ids.ana}-person`, createdById: ids.teacher, fullName: 'Ana' } });
|
||||
await db.attendee.create({
|
||||
data: { id: ids.ana, groupId: ids.group, personId: `${ids.ana}-person`, createdAt: new Date('2026-01-01T00:00:00Z') },
|
||||
});
|
||||
await db.studentAccount.create({
|
||||
data: {
|
||||
id: ids.account,
|
||||
@@ -71,7 +74,7 @@ describe.skipIf(!url)('payment review (real database)', () => {
|
||||
createdById: ids.teacher,
|
||||
recoveryEmail: 'ana@test.local',
|
||||
recoveryEmailVerifiedAt: NOW,
|
||||
attendees: { create: { attendeeId: ids.ana } },
|
||||
people: { create: { personId: `${ids.ana}-person` } },
|
||||
},
|
||||
});
|
||||
await db.payment.create({
|
||||
|
||||
@@ -19,7 +19,14 @@ describe.skipIf(!url)('student access (real database)', () => {
|
||||
// Same contract as UnitOfWork.executeResult, built on this file's own client
|
||||
// (other test files mock '@/lib/prisma').
|
||||
let unitOfWork: { executeResult: unknown };
|
||||
const ids = { user: `test-user-${suffix}`, group: `test-group-${suffix}`, attendee: `test-att-${suffix}` };
|
||||
const ids = {
|
||||
user: `test-user-${suffix}`,
|
||||
group: `test-group-${suffix}`,
|
||||
group2: `test-group2-${suffix}`,
|
||||
person: `test-person-${suffix}`,
|
||||
attendee: `test-att-${suffix}`,
|
||||
attendee2: `test-att2-${suffix}`,
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) });
|
||||
@@ -42,7 +49,11 @@ describe.skipIf(!url)('student access (real database)', () => {
|
||||
};
|
||||
await db.user.create({ data: { id: ids.user, name: 'Profe Test', email: `${ids.user}@test.local` } });
|
||||
await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.user } });
|
||||
await db.attendee.create({ data: { id: ids.attendee, groupId: ids.group, fullName: 'Ana Pérez' } });
|
||||
await db.group.create({ data: { id: ids.group2, name: 'Yoga', createdById: ids.user } });
|
||||
// One person in two groups of the teacher.
|
||||
await db.person.create({ data: { id: ids.person, createdById: ids.user, fullName: 'Ana Pérez' } });
|
||||
await db.attendee.create({ data: { id: ids.attendee, groupId: ids.group, personId: ids.person } });
|
||||
await db.attendee.create({ data: { id: ids.attendee2, groupId: ids.group2, personId: ids.person } });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
@@ -96,7 +107,7 @@ describe.skipIf(!url)('student access (real database)', () => {
|
||||
if (!loser.ok) expect(loser.error.status).toBe(410);
|
||||
}
|
||||
|
||||
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
|
||||
const account = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
|
||||
const sessions = await db.studentSession.findMany({ where: { accountId: account.accountId, revokedAt: null } });
|
||||
expect(sessions).toHaveLength(1);
|
||||
expect(sessions[0]?.device).toBe('iPhone · Safari');
|
||||
@@ -122,7 +133,7 @@ describe.skipIf(!url)('student access (real database)', () => {
|
||||
if (!first.ok) throw new Error('invite failed');
|
||||
const consumed = await consume(tokenOf(first.value.url));
|
||||
expect(consumed.ok).toBe(true);
|
||||
const linked = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
|
||||
const linked = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
|
||||
await db.studentPasskey.create({
|
||||
data: { accountId: linked.accountId, credentialId: `cred-${suffix}`, publicKey: new Uint8Array([1]), device: 'iPhone · Safari' },
|
||||
});
|
||||
@@ -141,9 +152,25 @@ describe.skipIf(!url)('student access (real database)', () => {
|
||||
expect((await consume(tokenOf(pendingOld.value.url))).ok).toBe(false);
|
||||
expect((await consume(tokenOf(reinvite.value.url))).ok).toBe(true);
|
||||
|
||||
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } });
|
||||
const account = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
|
||||
expect(await db.studentSession.count({ where: { accountId: account.accountId, revokedAt: null } })).toBe(1);
|
||||
const after = await new GetStudentAccess({ db }).execute(ids.group, ids.attendee, ids.user);
|
||||
expect(after).toMatchObject({ ok: true, value: { status: 'active' } });
|
||||
});
|
||||
|
||||
it('una sola cuenta por persona: invitar desde otro grupo la reutiliza', async () => {
|
||||
const fromFirst = await invite();
|
||||
if (!fromFirst.ok) throw new Error('invite failed');
|
||||
const fromSecond = await new InviteStudent({ db, unitOfWork: unitOfWork as never }).execute(
|
||||
ids.group2,
|
||||
ids.attendee2,
|
||||
ids.user,
|
||||
);
|
||||
if (!fromSecond.ok) throw new Error('invite failed');
|
||||
|
||||
expect(await db.studentAccountPerson.count({ where: { personId: ids.person } })).toBe(1);
|
||||
// Same state from both groups: it is the person's access.
|
||||
const fromGroup2 = await new GetStudentAccess({ db }).execute(ids.group2, ids.attendee2, ids.user);
|
||||
expect(fromGroup2).toMatchObject({ ok: true, value: { status: 'invited' } });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { FileStorage } from '@/lib/storage';
|
||||
import { CancelStudentAbsence, NotifyStudentAbsences } from '@/modules/student-portal/features/absences/use-case';
|
||||
import { GetStudentClasses } from '@/modules/student-portal/features/classes/use-case';
|
||||
import { GetStudentFees } from '@/modules/student-portal/features/fees/use-case';
|
||||
import { GetStudentMe } from '@/modules/student-portal/features/me/use-case';
|
||||
import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case';
|
||||
|
||||
const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined;
|
||||
@@ -30,7 +31,12 @@ describe.skipIf(!url)('student portal (real database)', () => {
|
||||
const ids = {
|
||||
user: `t-user-${suffix}`,
|
||||
group: `t-group-${suffix}`,
|
||||
yoga: `t-yoga-${suffix}`,
|
||||
personAna: `t-p-ana-${suffix}`,
|
||||
personBeto: `t-p-beto-${suffix}`,
|
||||
ana: `t-ana-${suffix}`,
|
||||
anaYoga: `t-ana-yoga-${suffix}`,
|
||||
betoYoga: `t-beto-yoga-${suffix}`,
|
||||
beto: `t-beto-${suffix}`,
|
||||
accountAna: `t-acc-ana-${suffix}`,
|
||||
accountBeto: `t-acc-beto-${suffix}`,
|
||||
@@ -50,17 +56,29 @@ describe.skipIf(!url)('student portal (real database)', () => {
|
||||
await db.group.create({
|
||||
data: { id: ids.group, name: 'Natación', createdById: ids.user, days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], time: '18:00' },
|
||||
});
|
||||
await db.group.create({
|
||||
data: { id: ids.yoga, name: 'Yoga', createdById: ids.user, days: ['TUESDAY'], time: '10:00' },
|
||||
});
|
||||
await db.person.createMany({
|
||||
data: [
|
||||
{ id: ids.personAna, createdById: ids.user, fullName: 'Ana' },
|
||||
{ id: ids.personBeto, createdById: ids.user, fullName: 'Beto' },
|
||||
],
|
||||
});
|
||||
// Ana and Beto are in both groups.
|
||||
await db.attendee.createMany({
|
||||
data: [
|
||||
{ id: ids.ana, groupId: ids.group, fullName: 'Ana' },
|
||||
{ id: ids.beto, groupId: ids.group, fullName: 'Beto' },
|
||||
{ id: ids.ana, groupId: ids.group, personId: ids.personAna },
|
||||
{ id: ids.beto, groupId: ids.group, personId: ids.personBeto },
|
||||
{ id: ids.anaYoga, groupId: ids.yoga, personId: ids.personAna },
|
||||
{ id: ids.betoYoga, groupId: ids.yoga, personId: ids.personBeto },
|
||||
],
|
||||
});
|
||||
await db.studentAccount.create({
|
||||
data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, attendees: { create: { attendeeId: ids.ana } } },
|
||||
data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, people: { create: { personId: ids.personAna } } },
|
||||
});
|
||||
await db.studentAccount.create({
|
||||
data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, attendees: { create: { attendeeId: ids.beto } } },
|
||||
data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, people: { create: { personId: ids.personBeto } } },
|
||||
});
|
||||
await db.payment.createMany({
|
||||
data: [
|
||||
@@ -117,6 +135,21 @@ describe.skipIf(!url)('student portal (real database)', () => {
|
||||
expect(!invented.ok && invented.error.status).toBe(400);
|
||||
});
|
||||
|
||||
it('la cuenta de la persona ve todos sus grupos, y solo los suyos', async () => {
|
||||
const me = await new GetStudentMe({ db }).execute(ids.accountAna);
|
||||
if (!me.ok) throw new Error('me failed');
|
||||
expect(me.value.students.map((student) => [student.attendeeId, student.groupName])).toEqual([
|
||||
[ids.ana, 'Natación'],
|
||||
[ids.anaYoga, 'Yoga'],
|
||||
]);
|
||||
|
||||
// Her membership in the second group is reachable; Beto's in that group is not.
|
||||
expect((await new GetStudentFees({ db }).execute(ids.accountAna, ids.anaYoga)).ok).toBe(true);
|
||||
const foreign = await new GetStudentFees({ db }).execute(ids.accountAna, ids.betoYoga);
|
||||
expect(foreign.ok).toBe(false);
|
||||
if (!foreign.ok) expect(foreign.error.status).toBe(404);
|
||||
});
|
||||
|
||||
it('IDOR: una cuenta no ve ni toca datos de otro alumno', async () => {
|
||||
expect((await new GetStudentClasses({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false);
|
||||
expect((await new GetStudentFees({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false);
|
||||
|
||||
@@ -61,7 +61,7 @@ describe('groups routes', () => {
|
||||
|
||||
it('lists groups scoped to the current user', async () => {
|
||||
prisma.group.findMany.mockResolvedValue([
|
||||
{ ...group, _count: { attendees: 4, waitlist: 1 } },
|
||||
{ ...group, _count: { attendees: 4, waitlist: 1, payments: 3 } },
|
||||
]);
|
||||
prisma.group.count.mockResolvedValue(1);
|
||||
|
||||
@@ -76,6 +76,7 @@ describe('groups routes', () => {
|
||||
updatedAt: group.updatedAt.toISOString(),
|
||||
attendeesCount: 4,
|
||||
waitlistCount: 1,
|
||||
unpaidPaymentsCount: 3,
|
||||
},
|
||||
],
|
||||
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
|
||||
@@ -89,7 +90,11 @@ describe('groups routes', () => {
|
||||
where,
|
||||
include: {
|
||||
_count: {
|
||||
select: { attendees: true, waitlist: { where: { status: 'PENDING' } } },
|
||||
select: {
|
||||
attendees: true,
|
||||
waitlist: { where: { status: 'PENDING' } },
|
||||
payments: { where: { status: { in: ['PENDING', 'OVERDUE'] } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -82,7 +82,7 @@ describe('GetHomeSummary', () => {
|
||||
dueDate: new Date('2026-09-25T12:00:00.000Z'),
|
||||
status: 'PENDING',
|
||||
group: { name: 'Cuadrilla A' },
|
||||
attendee: { fullName: 'Ana García' },
|
||||
attendee: { person: { fullName: 'Ana García' } },
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -130,7 +130,7 @@ describe('GetHomeSummary', () => {
|
||||
where: { groupId: { in: ['g2', 'g1'] }, status: { in: ['PENDING', 'OVERDUE'] } },
|
||||
orderBy: [{ dueDate: 'asc' }],
|
||||
take: 5,
|
||||
include: { group: { select: { name: true } }, attendee: { select: { fullName: true } } },
|
||||
include: { group: { select: { name: true } }, attendee: { select: { person: { select: { fullName: true } } } } },
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -81,8 +81,8 @@ describe('create payments batch', () => {
|
||||
prisma.group.findUnique.mockResolvedValue(groupOwner);
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
||||
prisma.attendee.findMany.mockResolvedValue([
|
||||
{ id: 'att-1', fullName: 'Juana' },
|
||||
{ id: 'att-2', fullName: 'Pedro' },
|
||||
{ id: 'att-1', person: { fullName: 'Juana' } },
|
||||
{ id: 'att-2', person: { fullName: 'Pedro' } },
|
||||
]);
|
||||
prisma.payment.create
|
||||
.mockResolvedValueOnce({ id: 'pay-1' })
|
||||
@@ -142,14 +142,14 @@ describe('create payments batch', () => {
|
||||
unitPrice: 120,
|
||||
currencyId: 'ARS',
|
||||
externalReference: 'pay-1',
|
||||
backUrl: `${webOrigin}/payments`,
|
||||
backUrl: `${webOrigin}/student/payments`,
|
||||
});
|
||||
});
|
||||
|
||||
it('derives the currency from the owner country and defaults when there is none', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: { toString: () => '80.00' } });
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, country: null });
|
||||
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-2', fullName: 'Pedro' }]);
|
||||
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-2', person: { fullName: 'Pedro' } }]);
|
||||
prisma.payment.create.mockResolvedValueOnce({ id: 'pay-2' });
|
||||
const useCase = batchUseCase();
|
||||
createPreference.mockResolvedValueOnce({
|
||||
@@ -169,13 +169,14 @@ describe('create payments batch', () => {
|
||||
expect(result.value.items[0]).toMatchObject({ attendeeId: 'att-2', currency: 'ARS' });
|
||||
expect(prisma.attendee.findMany).toHaveBeenCalledWith({
|
||||
where: { groupId: 'group-1', status: 'ACTIVE', id: { in: ['att-2'] } },
|
||||
include: { person: { select: { fullName: true } } },
|
||||
});
|
||||
});
|
||||
|
||||
it('propagates the not-connected problem and creates no rows', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(groupOwner);
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
||||
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', fullName: 'Juana' }]);
|
||||
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', person: { fullName: 'Juana' } }]);
|
||||
getToken = mock(async () => ({
|
||||
ok: false,
|
||||
error: {
|
||||
@@ -203,7 +204,7 @@ describe('create payments batch', () => {
|
||||
it('answers 409 over HTTP when the owner has no linked account', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(groupOwner);
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
||||
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', fullName: 'Juana' }]);
|
||||
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', person: { fullName: 'Juana' } }]);
|
||||
prisma.mpAccount.findUnique.mockResolvedValue(null);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {
|
||||
|
||||
@@ -49,7 +49,7 @@ function paymentWithoutLink(overrides: Record<string, unknown> = {}) {
|
||||
paidAt: null,
|
||||
createdAt: new Date('2026-10-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-10-01T10:00:00.000Z'),
|
||||
attendee: { fullName: 'Juana Pérez' },
|
||||
attendee: { person: { fullName: 'Juana Pérez' } },
|
||||
group: {
|
||||
name: 'Vinyasa',
|
||||
price: { toString: () => '120.00' },
|
||||
@@ -101,13 +101,13 @@ describe('renew payment link', () => {
|
||||
unitPrice: 120,
|
||||
currencyId: 'ARS',
|
||||
externalReference: 'pay-1',
|
||||
backUrl: `${webOrigin}/payments`,
|
||||
backUrl: `${webOrigin}/student/payments`,
|
||||
});
|
||||
expect(prisma.payment.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pay-1' },
|
||||
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new' },
|
||||
include: {
|
||||
attendee: { select: { fullName: true } },
|
||||
attendee: { select: { person: { select: { fullName: true } } } },
|
||||
group: { select: { name: true, price: true } },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -36,7 +36,7 @@ const payment = {
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
group: { name: 'Cuadrilla Alfa', price: 150.5 },
|
||||
attendee: { fullName: 'Juana Pérez' },
|
||||
attendee: { person: { fullName: 'Juana Pérez' } },
|
||||
};
|
||||
|
||||
function makeApp(userValue: unknown) {
|
||||
@@ -93,7 +93,7 @@ describe('payments routes', () => {
|
||||
where: { groupId: { in: ['group-1'] } },
|
||||
include: {
|
||||
group: { select: { name: true, price: true } },
|
||||
attendee: { select: { fullName: true } },
|
||||
attendee: { select: { person: { select: { fullName: true } } } },
|
||||
},
|
||||
skip: 0,
|
||||
take: 10,
|
||||
|
||||
@@ -10,6 +10,11 @@ const db = {
|
||||
count: mock(),
|
||||
create: mock(),
|
||||
},
|
||||
person: {
|
||||
findFirst: mock(),
|
||||
create: mock(),
|
||||
deleteMany: mock(),
|
||||
},
|
||||
groupWaitlistEntry: {
|
||||
findFirst: mock(),
|
||||
create: mock(),
|
||||
@@ -69,12 +74,16 @@ const preRegistration = (overrides: Record<string, unknown> = {}) => ({
|
||||
const attendee = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'att-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
personId: 'person-1',
|
||||
person: {
|
||||
id: 'person-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
},
|
||||
notifyToken: 'notify-1',
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
@@ -107,6 +116,9 @@ function makeApp(userValue: unknown) {
|
||||
describe('group pre-registrations', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// The phone is nobody the teacher has yet: promoting creates the person.
|
||||
prisma.person.findFirst.mockResolvedValue(null);
|
||||
prisma.person.create.mockResolvedValue({ id: 'person-1' } as never);
|
||||
});
|
||||
|
||||
describe('GET /groups/:groupId/preregistrations', () => {
|
||||
@@ -183,14 +195,19 @@ describe('group pre-registrations', () => {
|
||||
expect(body.outcome).toBe('added');
|
||||
expect(body.attendee.fullName).toBe('Martín Gómez');
|
||||
expect(body.waitlistEntry).toBeNull();
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
expect(prisma.person.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
createdById: teacherId,
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
notes: null,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
data: { groupId: 'group-1', personId: 'person-1' },
|
||||
include: { person: { select: expect.any(Object) } },
|
||||
});
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
@@ -255,7 +272,14 @@ describe('group pre-registrations', () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
|
||||
prisma.person.findFirst.mockResolvedValue({
|
||||
id: 'person-1',
|
||||
fullName: 'Martín Gómez',
|
||||
email: null,
|
||||
phone: '+5491133445566',
|
||||
attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }],
|
||||
} as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
|
||||
@@ -95,6 +95,8 @@ describe('computeStudentAlerts: pagos', () => {
|
||||
gravedad: 'vigilar',
|
||||
etiqueta: 'Cuota vencida',
|
||||
detalle: 'La cuota de octubre venció el 10/10.',
|
||||
razon: 'cuota',
|
||||
valores: { cuotas: 1, vencimientos: ['2026-10-10T12:00:00.000Z'] },
|
||||
firma: 'pay_1',
|
||||
peso: 1,
|
||||
},
|
||||
|
||||
@@ -74,7 +74,7 @@ describe('link del alumno', () => {
|
||||
expiresAt: new Date(NOW.getTime() + 1000),
|
||||
account: {
|
||||
name: 'Ana',
|
||||
attendees: [{ attendee: { group: { name: 'Natación', owner: { name: 'Caro' } } } }],
|
||||
people: [{ person: { attendees: [{ group: { name: 'Natación', owner: { name: 'Caro' } } }] } }],
|
||||
},
|
||||
})),
|
||||
updateMany: mock(),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { REPORTED_PAYMENT_NOTE_MAX } from '@gruperly/shared';
|
||||
import { detectReceiptType, RECEIPT_MAX_BYTES } from '@/lib/file-type';
|
||||
import type { FileStorage } from '@/lib/storage';
|
||||
import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler';
|
||||
@@ -45,6 +46,15 @@ describe('tipo real del comprobante (magic bytes)', () => {
|
||||
const noStorage = new ReportStudentPayment({ db: db as never, storage: null });
|
||||
const unavailable = await noStorage.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) } });
|
||||
expect(!unavailable.ok && unavailable.error.status).toBe(503);
|
||||
|
||||
const longNote = await useCase.execute('acc', {
|
||||
attendeeId: 'a1',
|
||||
paymentIds: ['p1'],
|
||||
note: 'x'.repeat(REPORTED_PAYMENT_NOTE_MAX + 1),
|
||||
file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) },
|
||||
});
|
||||
expect(!longNote.ok && longNote.error.errors).toEqual({ note: ['too_long'] });
|
||||
expect(puts).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -12,6 +12,11 @@ const db = {
|
||||
create: mock(),
|
||||
delete: mock(),
|
||||
},
|
||||
person: {
|
||||
findFirst: mock(),
|
||||
create: mock(),
|
||||
deleteMany: mock(),
|
||||
},
|
||||
groupWaitlistEntry: {
|
||||
findMany: mock(),
|
||||
findFirst: mock(),
|
||||
@@ -70,12 +75,16 @@ const waitlistEntry = (overrides: Record<string, unknown> = {}) => ({
|
||||
const attendee = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'att-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
personId: 'person-1',
|
||||
person: {
|
||||
id: 'person-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
},
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
...overrides,
|
||||
@@ -94,6 +103,9 @@ function makeApp(userValue: unknown) {
|
||||
describe('group waitlist management', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// The phone is nobody the teacher has yet: promoting creates the person.
|
||||
prisma.person.findFirst.mockResolvedValue(null);
|
||||
prisma.person.create.mockResolvedValue({ id: 'person-1' } as never);
|
||||
});
|
||||
|
||||
describe('GET /groups/:groupId/waitlist', () => {
|
||||
@@ -146,7 +158,12 @@ describe('group waitlist management', () => {
|
||||
const data = await res.json();
|
||||
expect(data.attendee.fullName).toBe('Martín Gómez');
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ groupId: 'group-1', fullName: 'Martín Gómez', phone: '+5491133445566' }),
|
||||
data: { groupId: 'group-1', personId: 'person-1' },
|
||||
include: { person: { select: expect.any(Object) } },
|
||||
});
|
||||
expect(prisma.person.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ createdById: teacherId, fullName: 'Martín Gómez', phone: '+5491133445566' }),
|
||||
select: { id: true },
|
||||
});
|
||||
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
|
||||
});
|
||||
@@ -167,10 +184,17 @@ describe('group waitlist management', () => {
|
||||
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects with 409 when the phone already belongs to an attendee', async () => {
|
||||
it('rejects with 409 when the person is already a member of the group', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
prisma.person.findFirst.mockResolvedValue({
|
||||
id: 'person-1',
|
||||
fullName: 'Martín Gómez',
|
||||
email: null,
|
||||
phone: '+5491133445566',
|
||||
attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }],
|
||||
} as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', {
|
||||
@@ -204,6 +228,72 @@ describe('group waitlist management', () => {
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const promoteTo = (targetGroupId: string) =>
|
||||
makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ targetGroupId }),
|
||||
});
|
||||
|
||||
it('places the entry in another group of the teacher and removes it from the origin waitlist', async () => {
|
||||
prisma.group.findUnique
|
||||
.mockResolvedValueOnce(mockGroup as never)
|
||||
.mockResolvedValueOnce({ ...mockGroup, id: 'group-2', name: 'Taller de Cerámica' } as never);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.create.mockResolvedValue(attendee({ groupId: 'group-2' }) as never);
|
||||
|
||||
const res = await promoteTo('group-2');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.group.findUnique).toHaveBeenLastCalledWith({ where: { id: 'group-2' } });
|
||||
expect(prisma.attendee.count).toHaveBeenCalledWith({ where: { groupId: 'group-2', status: 'ACTIVE' } });
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
data: { groupId: 'group-2', personId: 'person-1' },
|
||||
include: { person: { select: expect.any(Object) } },
|
||||
});
|
||||
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
|
||||
});
|
||||
|
||||
it('rejects a target group owned by another teacher', async () => {
|
||||
prisma.group.findUnique
|
||||
.mockResolvedValueOnce(mockGroup as never)
|
||||
.mockResolvedValueOnce({ ...mockGroup, id: 'group-2', createdById: 'other-user' } as never);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
|
||||
|
||||
const res = await promoteTo('group-2');
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 404 when the target group does not exist', async () => {
|
||||
prisma.group.findUnique.mockResolvedValueOnce(mockGroup as never).mockResolvedValueOnce(null);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
|
||||
|
||||
const res = await promoteTo('group-missing');
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects with 409 when the target group reached its capacity', async () => {
|
||||
prisma.group.findUnique
|
||||
.mockResolvedValueOnce(mockGroup as never)
|
||||
.mockResolvedValueOnce({ ...mockGroup, id: 'group-2', capacity: 5 } as never);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
|
||||
const res = await promoteTo('group-2');
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('group_capacity_reached');
|
||||
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /groups/:groupId/waitlist/:entryId', () => {
|
||||
@@ -260,6 +350,10 @@ describe('group waitlist management', () => {
|
||||
expect(body.removedAttendeeId).toBe('att-1');
|
||||
expect(body.promoted).toBeNull();
|
||||
expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } });
|
||||
// Their last group: the person goes too (no-op if they are in others).
|
||||
expect(prisma.person.deleteMany).toHaveBeenCalledWith({
|
||||
where: { id: 'person-1', attendees: { none: {} } },
|
||||
});
|
||||
});
|
||||
|
||||
it('removes an attendee and promotes the first pending waitlist entry atomically', async () => {
|
||||
@@ -288,8 +382,9 @@ describe('group waitlist management', () => {
|
||||
expect(body.promoted).toMatchObject({ id: 'wl-1', fullName: 'Sofía Ruiz' });
|
||||
expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } });
|
||||
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
expect(prisma.person.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ fullName: 'Sofía Ruiz', phone: '+5491133778899' }),
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ function payment(id: string, attendee: Record<string, unknown>, overrides: Recor
|
||||
currency: 'ARS',
|
||||
dueDate: new Date('2026-10-20T15:00:00.000Z'),
|
||||
checkoutUrl: `https://mpago.la/${id}`,
|
||||
attendee: { phone: null, guardianPhone: null, ...attendee },
|
||||
attendee: { id: attendee.id, person: { phone: null, guardianPhone: null, ...attendee } },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -282,11 +282,11 @@ describe('re-engagement messages', () => {
|
||||
]);
|
||||
db.attendee.findMany
|
||||
.mockResolvedValueOnce([
|
||||
{ id: 'att-1', fullName: 'Ana López', phone: '1123456789', createdAt: enrolled },
|
||||
{ id: 'att-2', fullName: 'Beto', phone: '1198765432', createdAt: enrolled },
|
||||
{ id: 'att-1', person: { fullName: 'Ana López', phone: '1123456789' }, createdAt: enrolled },
|
||||
{ id: 'att-2', person: { fullName: 'Beto', phone: '1198765432' }, createdAt: enrolled },
|
||||
])
|
||||
.mockResolvedValueOnce([
|
||||
{ id: 'att-1', phone: '1123456789', guardianPhone: null },
|
||||
{ id: 'att-1', person: { phone: '1123456789', guardianPhone: null } },
|
||||
]);
|
||||
db.attendance.findMany.mockResolvedValue([
|
||||
{ attendeeId: 'att-1', classSessionId: 's1', status: 'ABSENT', classSession: { startsAt: s1 } },
|
||||
|
||||
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"]
|
||||
@@ -3,8 +3,10 @@
|
||||
# Con el proxy, el navegador pega siempre al mismo origen: la cookie de sesión
|
||||
# es first-party y el CORS del backend queda como red de seguridad.
|
||||
|
||||
# DNS interno de Docker: resuelve `api` en cada request, así el proxy sobrevive
|
||||
# a un recreate del contenedor (que cambia la IP).
|
||||
# DNS interno de Docker: resuelve `gruperly-api` en cada request, así el proxy
|
||||
# sobrevive a un recreate del contenedor (que cambia la IP). Es un alias que el
|
||||
# compose define solo en la red propia del stack; `api` también existe en
|
||||
# dokploy-network y con dev y prod en el mismo server resolvería a cualquiera.
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
|
||||
server {
|
||||
@@ -18,7 +20,7 @@ server {
|
||||
|
||||
# ── API ────────────────────────────────────────────────────────────────────
|
||||
location /api/ {
|
||||
set $api http://api:4000;
|
||||
set $api http://gruperly-api:4000;
|
||||
proxy_pass $api$request_uri;
|
||||
|
||||
proxy_http_version 1.1;
|
||||
|
||||
@@ -21,10 +21,12 @@
|
||||
"@tanstack/react-router": "^1.170.38",
|
||||
"better-auth": "1.7.2",
|
||||
"clsx": "^2.1.1",
|
||||
"i18next": "^26.5.11",
|
||||
"lucide-react": "^1.34.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-hook-form": "^7.54.0",
|
||||
"react-i18next": "^17.1.9",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"zod": "3.24.2"
|
||||
},
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { Link, useLocation } from '@tanstack/react-router'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { NavBadge } from './NavBadge'
|
||||
import { isNavItemActive, NAV_ITEMS } from './nav-items'
|
||||
|
||||
export function BottomNav() {
|
||||
const location = useLocation()
|
||||
const { t } = useTranslation('layout')
|
||||
|
||||
return (
|
||||
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur lg:hidden">
|
||||
<div className="mx-auto grid max-w-md grid-cols-4">
|
||||
{NAV_ITEMS.map(({ label, to, icon: Icon, badge }) => {
|
||||
{NAV_ITEMS.map(({ labelKey, to, icon: Icon, badge }) => {
|
||||
const isActive = isNavItemActive(location.pathname, to)
|
||||
return (
|
||||
<Link
|
||||
@@ -32,7 +34,7 @@ export function BottomNav() {
|
||||
<Icon className="size-5" strokeWidth={isActive ? 2.25 : 2} />
|
||||
{badge ? <NavBadge kind={badge} className="absolute -right-2.5 -top-1.5" /> : null}
|
||||
</span>
|
||||
<span className="leading-none">{label}</span>
|
||||
<span className="leading-none">{t(labelKey)}</span>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -1,52 +1,55 @@
|
||||
import { Link, useLocation } from '@tanstack/react-router'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type Crumb = { label: string; to?: string }
|
||||
type CrumbKey = 'home' | 'groups' | 'payments' | 'settings' | 'security' | 'profile'
|
||||
type Crumb = { label: CrumbKey; to?: string }
|
||||
|
||||
const BREADCRUMBS: Record<string, Crumb[]> = {
|
||||
'/': [{ label: 'Inicio' }],
|
||||
'/': [{ label: 'home' }],
|
||||
'/groups': [
|
||||
{ label: 'Inicio', to: '/' },
|
||||
{ label: 'Grupos' },
|
||||
{ label: 'home', to: '/' },
|
||||
{ label: 'groups' },
|
||||
],
|
||||
'/payments': [
|
||||
{ label: 'Inicio', to: '/' },
|
||||
{ label: 'Cobros' },
|
||||
{ label: 'home', to: '/' },
|
||||
{ label: 'payments' },
|
||||
],
|
||||
'/settings': [
|
||||
{ label: 'Inicio', to: '/' },
|
||||
{ label: 'Ajustes' },
|
||||
{ label: 'home', to: '/' },
|
||||
{ label: 'settings' },
|
||||
],
|
||||
'/security': [
|
||||
{ label: 'Inicio', to: '/' },
|
||||
{ label: 'Ajustes', to: '/settings' },
|
||||
{ label: 'Seguridad' },
|
||||
{ label: 'home', to: '/' },
|
||||
{ label: 'settings', to: '/settings' },
|
||||
{ label: 'security' },
|
||||
],
|
||||
'/profile': [
|
||||
{ label: 'Inicio', to: '/' },
|
||||
{ label: 'Mi perfil' },
|
||||
{ label: 'home', to: '/' },
|
||||
{ label: 'profile' },
|
||||
],
|
||||
}
|
||||
|
||||
export function Breadcrumb() {
|
||||
const location = useLocation()
|
||||
const crumbs = BREADCRUMBS[location.pathname] ?? [{ label: 'Inicio' }]
|
||||
const { t } = useTranslation('layout')
|
||||
const crumbs = BREADCRUMBS[location.pathname] ?? [{ label: 'home' }]
|
||||
|
||||
return (
|
||||
<nav aria-label="Breadcrumb" className="hidden items-center gap-1.5 text-sm lg:flex">
|
||||
<nav aria-label={t('breadcrumb')} className="hidden items-center gap-1.5 text-sm lg:flex">
|
||||
{crumbs.map((crumb, i) => {
|
||||
const isLast = i === crumbs.length - 1
|
||||
return (
|
||||
<span key={crumb.label} className="flex items-center gap-1.5">
|
||||
{i > 0 ? <ChevronRight className="size-3.5 text-foreground/40" /> : null}
|
||||
{isLast ? (
|
||||
<span className="font-medium text-primary">{crumb.label}</span>
|
||||
<span className="font-medium text-primary">{t(`nav.${crumb.label}`)}</span>
|
||||
) : (
|
||||
<Link
|
||||
to={crumb.to!}
|
||||
className="text-foreground/50 transition-colors hover:text-primary"
|
||||
>
|
||||
{crumb.label}
|
||||
{t(`nav.${crumb.label}`)}
|
||||
</Link>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Logo } from '../brand'
|
||||
import { Breadcrumb } from './Breadcrumb'
|
||||
import { ThemeToggle } from './ThemeToggle'
|
||||
import { UserMenu } from './UserMenu'
|
||||
|
||||
export function Header() {
|
||||
const { t } = useTranslation('layout')
|
||||
return (
|
||||
<header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur">
|
||||
<div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between px-4 lg:px-6">
|
||||
@@ -12,7 +14,7 @@ export function Header() {
|
||||
{/* `Link` and not `<a>`: on mobile the logo is the only way back to the
|
||||
home screen and an anchor would reload the whole document, losing
|
||||
the in-memory state (React Query cache, install event). */}
|
||||
<Link to="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio">
|
||||
<Link to="/" className="flex items-center lg:hidden" aria-label={t('homeLink')}>
|
||||
<Logo className="h-8" />
|
||||
</Link>
|
||||
<Breadcrumb />
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useReportedPaymentsCount } from '../../features/payments/reportedPayments'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { cn } from '../../lib/utils'
|
||||
|
||||
/* Counter of a nav item: today only "Pagos para verificar" on Cobros. The
|
||||
number is in the accessible name too (sr-only), not only in the dot. */
|
||||
export function NavBadge({ kind, className }: { kind: 'reported-payments'; className?: string }) {
|
||||
const count = useReportedPaymentsCount()
|
||||
const { t } = useTranslation('layout')
|
||||
if (kind !== 'reported-payments' || count === 0) return null
|
||||
return (
|
||||
<span
|
||||
@@ -13,8 +15,8 @@ export function NavBadge({ kind, className }: { kind: 'reported-payments'; class
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{count > 99 ? '99+' : count}
|
||||
<span className="sr-only"> pagos para verificar</span>
|
||||
<span aria-hidden="true">{count > 99 ? '99+' : count}</span>
|
||||
<span className="sr-only">{t('reportedPayments', { count })}</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user