Files
gruperly/apps/backend/prisma/models/student-access.prisma
Jose Selesan d21e1c3730 feat: un miembro puede pertenecer a más de un grupo
- Nuevo modelo `Person` (`people`): contacto y notas por profe, con
  teléfono único (índice parcial `people_owner_phone_key`). `Attendee`
  pasa a ser la membresía (`group_id` + `person_id`, único por grupo).
- La cuenta de la app de alumnos se vincula a la persona
  (`student_account_people`): una sola cuenta ve todos sus grupos.
- Migración unifica attendees del mismo profe y teléfono, y fusiona sus
  cuentas de alumno (conserva la usada más recientemente).
- `POST /groups/:gid/attendees/:aid/add-to-group` y
  `GET /people/lookup` para detectar personas existentes al cargar;
  el alta responde `409 person_exists` y acepta `personId`. Bulk, lista
  de espera y preinscripciones vinculan solas.
- El límite del plan cuenta personas con al menos un grupo activo.
- Web: "Agregar a otro grupo", sección "También está en" en la ficha y
  aviso "Ya tenés a esta persona" en el alta individual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 09:46:37 -03:00

241 lines
9.6 KiB
Plaintext

// Student access (attendees or their guardians), without passwords.
//
// The teacher sends a single-use invitation link over WhatsApp; consuming it
// creates a long sliding session on that device. Passkeys and a recovery email
// are optional and let the student get back in without the teacher. None of
// this goes through Better Auth: students have no mandatory email and their
// session must never pass the teacher's endpoints (separate cookie and
// middleware under /api/v1/student).
// The person who signs in: the attendee or a guardian. Linked to one or more
// attendees (a guardian may have several children), always by the teacher.
model StudentAccount {
id String @id @default(cuid())
name String
// Verified recovery email (the student loads it, optional).
recoveryEmail String? @map("recovery_email")
recoveryEmailVerifiedAt DateTime? @map("recovery_email_verified_at")
// Email waiting for its confirmation link; never used to recover.
pendingRecoveryEmail String? @map("pending_recovery_email")
// First sign-in done: the welcome screen is shown only once.
welcomedAt DateTime? @map("welcomed_at")
createdById String @map("created_by_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
createdBy User @relation("StudentAccountsCreated", fields: [createdById], references: [id], onDelete: Cascade)
people StudentAccountPerson[]
tokens StudentAccessToken[]
sessions StudentSession[]
passkeys StudentPasskey[]
challenges StudentWebauthnChallenge[]
absenceNotices AbsenceNotice[]
reportedPayments ReportedPayment[]
@@index([recoveryEmail])
@@index([createdById])
@@map("student_accounts")
}
// 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)
person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
@@id([accountId, personId])
@@index([personId])
@@map("student_account_people")
}
enum StudentTokenKind {
INVITATION
RECOVERY
EMAIL_CONFIRMATION
}
// Link token. Only its SHA-256 is stored. Consuming it is a conditional update
// (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now()`), so the
// first device wins and the link dies.
model StudentAccessToken {
id String @id @default(cuid())
tokenHash String @unique @map("token_hash")
accountId String @map("account_id")
kind StudentTokenKind
// EMAIL_CONFIRMATION only: the address being confirmed.
email String?
expiresAt DateTime @map("expires_at")
usedAt DateTime? @map("used_at")
// A new invitation revokes the account's pending tokens.
revokedAt DateTime? @map("revoked_at")
// Teacher who generated the invitation (null for recovery/confirmation).
createdById String? @map("created_by_id")
usedIp String? @map("used_ip")
usedUserAgent String? @map("used_user_agent")
createdAt DateTime @default(now()) @map("created_at")
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
@@index([accountId, kind])
@@map("student_access_tokens")
}
// Long sliding session (90 days, renewed on use). The cookie carries the raw
// token; only its hash is stored.
model StudentSession {
id String @id @default(cuid())
accountId String @map("account_id")
tokenHash String @unique @map("token_hash")
// Human readable, derived from the user agent ("iPhone · Safari").
device String
createdAt DateTime @default(now()) @map("created_at")
lastUsedAt DateTime @default(now()) @map("last_used_at")
expiresAt DateTime @map("expires_at")
revokedAt DateTime? @map("revoked_at")
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
@@index([accountId])
@@map("student_sessions")
}
model StudentPasskey {
id String @id @default(cuid())
accountId String @map("account_id")
credentialId String @unique @map("credential_id")
publicKey Bytes @map("public_key")
counter Int @default(0)
transports String[]
device String
createdAt DateTime @default(now()) @map("created_at")
lastUsedAt DateTime? @map("last_used_at")
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
@@index([accountId])
@@map("student_passkeys")
}
enum WebauthnChallengePurpose {
REGISTER
LOGIN
}
// Pending WebAuthn challenge, single use (deleted when verified), 5 minutes.
model StudentWebauthnChallenge {
id String @id @default(cuid())
challenge String
// Registration only: the signed-in account. Login is discoverable (no account).
accountId String? @map("account_id")
purpose WebauthnChallengePurpose
expiresAt DateTime @map("expires_at")
createdAt DateTime @default(now()) @map("created_at")
account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: Cascade)
@@index([expiresAt])
@@map("student_webauthn_challenges")
}
// Generic sliding-window rate limit: one row per hit, counted by key within
// the window (e.g. "recovery:email:<sha256>", "recovery:ip:<ip>").
model RateLimitEvent {
id String @id @default(cuid())
key String
createdAt DateTime @default(now()) @map("created_at")
@@index([key, createdAt])
@@map("rate_limit_events")
}
enum AbsenceReason {
HEALTH
TRAVEL
WORK_STUDY
OTHER
}
// Absence notice from the student. It only marks the attendance as EXCUSED
// (which already doesn't count for the attendance risk rules); the teacher
// sees it. At most one active (not cancelled) notice per attendee and class:
// enforced by a partial unique index in the migration.
model AbsenceNotice {
id String @id @default(cuid())
attendeeId String @map("attendee_id")
classSessionId String @map("class_session_id")
accountId String? @map("account_id")
reason AbsenceReason?
message String?
createdAt DateTime @default(now()) @map("created_at")
cancelledAt DateTime? @map("cancelled_at")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade)
account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: SetNull)
@@index([attendeeId, classSessionId])
@@index([classSessionId])
@@map("absence_notices")
}
enum ReportedPaymentStatus {
REPORTED
CONFIRMED
REJECTED
}
// Payment reported by the student with a receipt. It stays REPORTED until the
// teacher confirms it (the fees become PAID) or rejects it. `Payment.status` is
// not touched while REPORTED: the MP reconciliation and the overdue job keep
// working as before, and "Requiere atención" skips fees covered by a REPORTED
// report.
model ReportedPayment {
id String @id @default(cuid())
attendeeId String @map("attendee_id")
groupId String @map("group_id")
accountId String? @map("account_id")
totalAmount Decimal @map("total_amount") @db.Decimal(10, 2)
currency String
// Private object key in the storage; null once the retention policy deletes it.
receiptKey String? @map("receipt_key")
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")
rejectionReason String? @map("rejection_reason")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: SetNull)
items ReportedPaymentItem[]
@@index([groupId, status])
@@index([attendeeId])
@@map("reported_payments")
}
// Fees a report covers. A fee can't be in two REPORTED reports at once
// (checked in the use-case, inside the transaction).
model ReportedPaymentItem {
reportedPaymentId String @map("reported_payment_id")
paymentId String @map("payment_id")
reportedPayment ReportedPayment @relation(fields: [reportedPaymentId], references: [id], onDelete: Cascade)
payment Payment @relation(fields: [paymentId], references: [id], onDelete: Cascade)
@@id([reportedPaymentId, paymentId])
@@index([paymentId])
@@map("reported_payment_items")
}