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>
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "PaymentRunStatus" AS ENUM ('RUNNING', 'DONE', 'SKIPPED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "PaymentCheckoutStatus" AS ENUM ('OPEN', 'PAID', 'SUPERSEDED');
|
||||
|
||||
-- AlterEnum
|
||||
ALTER TYPE "WhatsappMessageKind" ADD VALUE 'PAYMENT_LINK';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "outbound_messages" ADD COLUMN "checkout_id" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "payments" ADD COLUMN "checkout_id" TEXT,
|
||||
ADD COLUMN "period_key" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "people" ADD COLUMN "pay_with_mercado_pago" BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "auto_charge_settings" (
|
||||
"id" TEXT NOT NULL,
|
||||
"owner_id" TEXT NOT NULL,
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"charge_day" INTEGER NOT NULL DEFAULT 1,
|
||||
"due_in_days" INTEGER NOT NULL DEFAULT 10,
|
||||
"send_whatsapp" BOOLEAN NOT NULL DEFAULT false,
|
||||
"enabled_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "auto_charge_settings_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "payment_runs" (
|
||||
"id" TEXT NOT NULL,
|
||||
"owner_id" TEXT NOT NULL,
|
||||
"period_key" TEXT NOT NULL,
|
||||
"status" "PaymentRunStatus" NOT NULL DEFAULT 'RUNNING',
|
||||
"skip_reason" TEXT,
|
||||
"fees" INTEGER NOT NULL DEFAULT 0,
|
||||
"checkouts" INTEGER NOT NULL DEFAULT 0,
|
||||
"linked" INTEGER NOT NULL DEFAULT 0,
|
||||
"failed" INTEGER NOT NULL DEFAULT 0,
|
||||
"sent" INTEGER NOT NULL DEFAULT 0,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"finished_at" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "payment_runs_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "payment_checkouts" (
|
||||
"id" TEXT NOT NULL,
|
||||
"owner_id" TEXT NOT NULL,
|
||||
"payer_person_id" TEXT NOT NULL,
|
||||
"run_id" TEXT,
|
||||
"amount" DECIMAL(10,2) NOT NULL,
|
||||
"currency" TEXT NOT NULL,
|
||||
"due_date" TIMESTAMP(3) NOT NULL,
|
||||
"checkout_url" TEXT,
|
||||
"mp_preference_id" TEXT,
|
||||
"mp_payment_id" TEXT,
|
||||
"status" "PaymentCheckoutStatus" NOT NULL DEFAULT 'OPEN',
|
||||
"paid_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "payment_checkouts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "auto_charge_settings_owner_id_key" ON "auto_charge_settings"("owner_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "payment_runs_owner_id_period_key_key" ON "payment_runs"("owner_id", "period_key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "payment_checkouts_mp_preference_id_key" ON "payment_checkouts"("mp_preference_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "payment_checkouts_status_created_at_idx" ON "payment_checkouts"("status", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "payment_checkouts_owner_id_idx" ON "payment_checkouts"("owner_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "payments_checkout_id_idx" ON "payments"("checkout_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "payments" ADD CONSTRAINT "payments_checkout_id_fkey" FOREIGN KEY ("checkout_id") REFERENCES "payment_checkouts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "auto_charge_settings" ADD CONSTRAINT "auto_charge_settings_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "payment_runs" ADD CONSTRAINT "payment_runs_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "payment_checkouts" ADD CONSTRAINT "payment_checkouts_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "payment_checkouts" ADD CONSTRAINT "payment_checkouts_payer_person_id_fkey" FOREIGN KEY ("payer_person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "payment_checkouts" ADD CONSTRAINT "payment_checkouts_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "payment_runs"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_checkout_id_fkey" FOREIGN KEY ("checkout_id") REFERENCES "payment_checkouts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- One automatic fee per member and month (hand-written: Prisma does not model
|
||||
-- partial indexes). Manual fees have no period and stay out of it.
|
||||
CREATE UNIQUE INDEX "payments_attendee_period_key" ON "payments"("attendee_id", "period_key") WHERE "period_key" IS NOT NULL;
|
||||
@@ -31,6 +31,9 @@ model User {
|
||||
subscription BillingSubscription?
|
||||
studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
|
||||
people Person[] @relation("OwnerPeople")
|
||||
autoCharge AutoChargeSettings?
|
||||
paymentRuns PaymentRun[]
|
||||
checkouts PaymentCheckout[]
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
// Domain models
|
||||
|
||||
model Group {
|
||||
id String @id @default(cuid())
|
||||
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")
|
||||
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")
|
||||
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")
|
||||
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[]
|
||||
@@ -85,18 +85,23 @@ enum AttendeeStatus {
|
||||
// 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?
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
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.
|
||||
@@ -184,16 +189,25 @@ model Payment {
|
||||
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")
|
||||
}
|
||||
|
||||
|
||||
91
apps/backend/prisma/models/payments.prisma
Normal file
91
apps/backend/prisma/models/payments.prisma
Normal file
@@ -0,0 +1,91 @@
|
||||
// Automatic monthly charges and combined Mercado Pago links.
|
||||
//
|
||||
// On the teacher's day of the month a run creates the fee of every active
|
||||
// member of their monthly groups and one Checkout Pro link per payer: the adult
|
||||
// in charge for kids, the person themselves otherwise. The link covers all the
|
||||
// payer's fees (`PaymentCheckout` + `Payment.checkoutId`); its
|
||||
// `external_reference` is `chk_<checkout id>`.
|
||||
|
||||
// One per teacher. Off until the teacher turns it on.
|
||||
model AutoChargeSettings {
|
||||
id String @id @default(cuid())
|
||||
ownerId String @unique @map("owner_id")
|
||||
enabled Boolean @default(false)
|
||||
// Day of the month (1-28) in the teacher's time zone.
|
||||
chargeDay Int @default(1) @map("charge_day")
|
||||
dueInDays Int @default(10) @map("due_in_days")
|
||||
sendWhatsapp Boolean @default(false) @map("send_whatsapp")
|
||||
// Last time `enabled` went on: a month whose day already passed is skipped.
|
||||
enabledAt DateTime? @map("enabled_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@map("auto_charge_settings")
|
||||
}
|
||||
|
||||
enum PaymentRunStatus {
|
||||
RUNNING
|
||||
DONE
|
||||
SKIPPED
|
||||
}
|
||||
|
||||
// One automatic run per teacher and month: the unique key is what makes a
|
||||
// second tick of the job (or a second server) a no-op.
|
||||
model PaymentRun {
|
||||
id String @id @default(cuid())
|
||||
ownerId String @map("owner_id")
|
||||
periodKey String @map("period_key")
|
||||
status PaymentRunStatus @default(RUNNING)
|
||||
skipReason String? @map("skip_reason")
|
||||
fees Int @default(0)
|
||||
checkouts Int @default(0)
|
||||
linked Int @default(0)
|
||||
failed Int @default(0)
|
||||
sent Int @default(0)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
finishedAt DateTime? @map("finished_at")
|
||||
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
checkoutsList PaymentCheckout[]
|
||||
|
||||
@@unique([ownerId, periodKey])
|
||||
@@map("payment_runs")
|
||||
}
|
||||
|
||||
enum PaymentCheckoutStatus {
|
||||
OPEN
|
||||
PAID
|
||||
// A fee was paid some other way (e.g. a confirmed transfer): the link is
|
||||
// expired and the remaining fees get links of their own.
|
||||
SUPERSEDED
|
||||
}
|
||||
|
||||
// One Mercado Pago link covering several fees of the same payer.
|
||||
model PaymentCheckout {
|
||||
id String @id @default(cuid())
|
||||
ownerId String @map("owner_id")
|
||||
payerPersonId String @map("payer_person_id")
|
||||
runId String? @map("run_id")
|
||||
amount Decimal @db.Decimal(10, 2)
|
||||
currency String
|
||||
dueDate DateTime @map("due_date")
|
||||
checkoutUrl String? @map("checkout_url")
|
||||
mpPreferenceId String? @unique @map("mp_preference_id")
|
||||
mpPaymentId String? @map("mp_payment_id")
|
||||
status PaymentCheckoutStatus @default(OPEN)
|
||||
paidAt DateTime? @map("paid_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||
payer Person @relation(fields: [payerPersonId], references: [id], onDelete: Cascade)
|
||||
run PaymentRun? @relation(fields: [runId], references: [id], onDelete: SetNull)
|
||||
payments Payment[]
|
||||
outboundMessages OutboundMessage[]
|
||||
|
||||
@@index([status, createdAt])
|
||||
@@index([ownerId])
|
||||
@@map("payment_checkouts")
|
||||
}
|
||||
@@ -19,6 +19,8 @@ enum WhatsappAccountStatus {
|
||||
enum WhatsappMessageKind {
|
||||
PAYMENT_REMINDER
|
||||
REENGAGEMENT
|
||||
// The monthly combined payment link, sent when it is generated.
|
||||
PAYMENT_LINK
|
||||
}
|
||||
|
||||
enum OutboundMessageStatus {
|
||||
@@ -92,9 +94,10 @@ model OutboundMessage {
|
||||
groupId String @map("group_id")
|
||||
attendeeId String @map("attendee_id")
|
||||
paymentId String? @map("payment_id")
|
||||
checkoutId String? @map("checkout_id")
|
||||
kind WhatsappMessageKind
|
||||
provider MessagingProviderId
|
||||
// ISO week the job ran for, e.g. "2026-W43".
|
||||
// ISO week the job ran for, e.g. "2026-W43"; the month ("2026-12") for PAYMENT_LINK.
|
||||
periodKey String @map("period_key")
|
||||
toPhone String @map("to_phone")
|
||||
providerMessageId String? @map("provider_message_id")
|
||||
@@ -105,9 +108,10 @@ model OutboundMessage {
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "outbound_messages_groupId_fkey")
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "outbound_messages_attendeeId_fkey")
|
||||
payment Payment? @relation(fields: [paymentId], references: [id], onDelete: SetNull, map: "outbound_messages_paymentId_fkey")
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "outbound_messages_groupId_fkey")
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "outbound_messages_attendeeId_fkey")
|
||||
payment Payment? @relation(fields: [paymentId], references: [id], onDelete: SetNull, map: "outbound_messages_paymentId_fkey")
|
||||
checkout PaymentCheckout? @relation(fields: [checkoutId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@unique([kind, attendeeId, periodKey], map: "outbound_messages_kind_attendeeId_periodKey_key")
|
||||
@@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key")
|
||||
|
||||
Reference in New Issue
Block a user