Files
gruperly/apps/backend/prisma/models/domain.prisma
Jose Selesan ac98495a6e feat(payments): automatic monthly charges with combined links per payer
- Teacher picks a day of the month in Settings; an hourly job creates the
  fees of all monthly groups on that day in the teacher's time zone
  (one run per teacher and month, partial unique index per attendee/period).
- One Mercado Pago link per payer (PaymentCheckout): the adult in charge
  bundles their kids and their own fees; external_reference chk_<id>,
  dedicated webhook and reconciliation mark every fee PAID at once.
- Person.payWithMercadoPago toggle (default on): off creates the fee
  without a link so the student pays by transfer.
- A fee paid some other way supersedes its combined link and expires the
  preference; renewing rebuilds the combined link or a single one.
- Optional WhatsApp delivery (PAYMENT_LINK kind, new Kapso template);
  weekly reminders now go once per combined link.
- Web: auto charge settings card, per-student toggle, combined link label
  in Cobros and "Pay all" in the student app, in the four locales.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:08:48 -03:00

332 lines
13 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")
// KIDS: each student is a kid and the contact is the adult in charge.
audience GroupAudience @default(ADULTS)
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 GroupAudience {
ADULTS
KIDS
}
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?
notes String?
// Automatic monthly charges only build a Mercado Pago link for people with
// this on. Off: they prefer to transfer (the fee is still created).
payWithMercadoPago Boolean @default(true) @map("pay_with_mercado_pago")
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[]
// As the payer of combined Mercado Pago links (themselves or their kids).
checkouts PaymentCheckout[]
// As a kid: the adult in charge (one in v1, enforced by the code).
guardians PersonGuardian[] @relation("GuardianChild")
// As the adult in charge: their kids. An adult has no memberships of their own.
children PersonGuardian[] @relation("GuardianAdult")
@@index([createdById])
@@map("people")
}
// A kid (`child`) and the adult in charge (`guardian`), both people of the same
// teacher. The adult is who gets the messages and signs in to the student app;
// siblings share the same adult, so their phone is not duplicated on each kid.
model PersonGuardian {
childId String @map("child_id")
guardianId String @map("guardian_id")
createdAt DateTime @default(now()) @map("created_at")
child Person @relation("GuardianChild", fields: [childId], references: [id], onDelete: Cascade)
guardian Person @relation("GuardianAdult", fields: [guardianId], references: [id], onDelete: Cascade)
@@id([childId, guardianId])
@@index([guardianId])
@@map("person_guardians")
}
// 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")
// Combined link (automatic monthly charges): the fee is paid through it and
// `checkoutUrl` is a copy of the checkout's link.
checkoutId String? @map("checkout_id")
// Month of an automatic charge ("2026-12"). Unique per attendee through a
// hand-written partial index (`payments_attendee_period_key`,
// `WHERE period_key IS NOT NULL`): Prisma does not model it.
periodKey String? @map("period_key")
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")
checkout PaymentCheckout? @relation(fields: [checkoutId], references: [id], onDelete: SetNull)
outboundMessages OutboundMessage[]
reportedItems ReportedPaymentItem[]
@@index([groupId], map: "payments_groupId_idx")
@@index([attendeeId], map: "payments_attendeeId_idx")
@@index([checkoutId])
@@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")
}