Files
gruperly/apps/backend/prisma/models/domain.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

293 lines
11 KiB
Plaintext

// Domain models
model Group {
id String @id @default(cuid())
name String
description String?
days WeekDay[]
time String?
capacity Int?
price Decimal? @db.Decimal(10, 2)
billingType BillingType? @map("billing_type")
dueDay Int? @map("due_day")
// Weekly WhatsApp automations, off until the teacher turns them on.
autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
autoReengagement Boolean @default(false) @map("auto_reengagement")
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
createdById String @map("created_by_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey")
members GroupMember[]
attendees Attendee[]
payments Payment[]
waitlist GroupWaitlistEntry[]
preRegistrations GroupPreRegistration[]
classSessions ClassSession[]
outboundMessages OutboundMessage[]
reportedPayments ReportedPayment[]
@@map("groups")
}
enum WeekDay {
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
}
enum BillingType {
MONTHLY
PER_CLASS
}
model GroupMember {
id String @id @default(cuid())
groupId String @map("group_id")
userId String @map("user_id")
role Role @default(MEMBER) // OWNER, ADMIN, MEMBER
joinedAt DateTime @default(now()) @map("joined_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_members_groupId_fkey")
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "group_members_userId_fkey")
@@unique([groupId, userId], map: "group_members_groupId_userId_key")
@@map("group_members")
}
enum Role {
OWNER
ADMIN
MEMBER
}
enum AttendeeStatus {
ACTIVE
PAUSED
DROPPED
}
// 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")
notes String?
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[]
absenceNotices AbsenceNotice[]
reportedPayments ReportedPayment[]
@@unique([groupId, personId])
@@index([groupId], map: "attendees_groupId_idx")
@@index([personId])
@@map("attendees")
}
enum StudentAlertKind {
ATTENDANCE
PAYMENT
}
// "Resuelto" on the "Requiere atención" screen. One row per attendee and kind:
// it hides the alert while its signature (last absence / overdue fees) stays
// the same, so a new absence or a new overdue fee brings it back on its own.
model AttendeeAlertResolution {
id String @id @default(cuid())
attendeeId String @map("attendee_id")
kind StudentAlertKind
signature String
resolvedById String @map("resolved_by_id")
resolvedAt DateTime @default(now()) @map("resolved_at")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
@@unique([attendeeId, kind])
@@map("attendee_alert_resolutions")
}
model Payment {
id String @id @default(cuid())
groupId String @map("group_id")
attendeeId String @map("attendee_id")
amount Decimal @db.Decimal(10, 2)
currency String @default("ARS")
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
dueDate DateTime @map("due_date")
description String? @map("description")
checkoutUrl String? @map("checkout_url")
mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
mpPaymentId String? @map("mp_payment_id")
paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
outboundMessages OutboundMessage[]
reportedItems ReportedPaymentItem[]
@@index([groupId], map: "payments_groupId_idx")
@@index([attendeeId], map: "payments_attendeeId_idx")
@@map("payments")
}
enum PaymentStatus {
PENDING
PAID
OVERDUE
CANCELLED
}
model WaitlistEntry {
id String @id @default(cuid())
email String
name String?
status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
userId String? @unique(map: "waitlist_entries_userId_key") @map("user_id")
user User? @relation(fields: [userId], references: [id], onDelete: SetNull, map: "waitlist_entries_userId_fkey")
@@unique([email])
@@map("waitlist_entries")
}
model GroupWaitlistEntry {
id String @id @default(cuid())
groupId String @map("group_id")
fullName String @map("full_name")
phone String
email String?
notes String?
status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_waitlist_entries_groupId_fkey")
@@unique([groupId, phone], map: "group_waitlist_entries_groupId_phone_key")
@@index([groupId], map: "group_waitlist_entries_groupId_idx")
@@map("group_waitlist_entries")
}
enum WaitlistStatus {
PENDING
INVITED
JOINED
DECLINED
}
enum PreRegistrationStatus {
PENDING
APPROVED
REJECTED
}
model GroupPreRegistration {
id String @id @default(cuid())
groupId String @map("group_id")
fullName String @map("full_name")
phone String
email String?
status PreRegistrationStatus @default(PENDING)
reviewedAt DateTime? @map("reviewed_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_pre_registrations_groupId_fkey")
@@unique([groupId, phone], map: "group_pre_registrations_groupId_phone_key")
@@index([groupId], map: "group_pre_registrations_groupId_idx")
@@map("group_pre_registrations")
}
enum MpAccountStatus {
ACTIVE
REQUIRES_REAUTH
REVOKED
}
// Mercado Pago account linked by a teacher through OAuth (Authorization Code + PKCE).
// Tokens are stored encrypted (AES-256-GCM); there is a single active account per
// teacher and a Mercado Pago user cannot be linked to two teachers.
model MpAccount {
id String @id @default(cuid())
ownerId String @unique(map: "mp_accounts_ownerId_key") @map("owner_id")
mpUserId String @unique(map: "mp_accounts_mpUserId_key") @map("mp_user_id")
accessTokenEnc String @map("access_token_enc")
refreshTokenEnc String @map("refresh_token_enc")
expiresAt DateTime @map("expires_at")
scope String?
liveMode Boolean @default(false) @map("live_mode")
status MpAccountStatus @default(ACTIVE)
connectedAt DateTime @default(now()) @map("connected_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "mp_accounts_ownerId_fkey")
// The daily refresh job looks for ACTIVE accounts expiring within 30 days.
@@index([status, expiresAt], map: "mp_accounts_status_expiresAt_idx")
@@map("mp_accounts")
}
// Pending OAuth authorization: the `state` sent to Mercado Pago plus the PKCE
// `code_verifier`. The `state` is the primary key because consuming it (deleting
// the row) is what makes it single use.
model MpOAuthState {
state String @id
ownerId String @map("owner_id")
codeVerifier String @map("code_verifier")
// Constrained to 'onboarding' | 'settings'; decides where the callback lands.
returnTo String @map("return_to")
expiresAt DateTime @map("expires_at")
createdAt DateTime @default(now()) @map("created_at")
// Expired rows are swept on every new authorization request.
@@index([expiresAt], map: "mp_oauth_states_expiresAt_idx")
@@map("mp_oauth_states")
}