1 Commits

Author SHA1 Message Date
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
87 changed files with 2648 additions and 106 deletions

View File

@@ -43,6 +43,12 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`. - **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness. - **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). Cada link lleva `notification_url` a `POST /payments/webhooks/mp/:paymentId` (público; solo si `API_PUBLIC_URL` es HTTPS pública): el aviso no se lee, se le pregunta a MP con el token del dueño vía `confirmMpPayment`, la misma regla del polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), que sigue de respaldo, y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**. - **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). Cada link lleva `notification_url` a `POST /payments/webhooks/mp/:paymentId` (público; solo si `API_PUBLIC_URL` es HTTPS pública): el aviso no se lee, se le pregunta a MP con el token del dueño vía `confirmMpPayment`, la misma regla del polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), que sigue de respaldo, y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
- **Cobro automático (`modules/payments/features/auto-charge*`)**: el profe elige en Ajustes un día del mes (1–28, `auto_charge_settings`) y el cron horario `RunAutoCharges` (`7 * * * *` UTC) corre `GenerateMonthlyCharges` cuando es ese día en **su** zona (`teacherTimeZone`), desde las 9 y con 3 días de tolerancia; si se prendió después del día, arranca el mes siguiente (`enabledAt`). Ojo con esto:
1. Idempotencia: `payment_runs` con `@@unique([ownerId, periodKey])` (mes `"2026-12"`), y además un índice único **parcial** a mano `payments_attendee_period_key` (`attendee_id, period_key WHERE period_key IS NOT NULL`); las cuotas manuales no llevan `periodKey`.
2. Un link por **pagador** (`PaymentCheckout`): el adulto a cargo (`primaryGuardian`) junta a sus chicos y lo suyo; si no, la persona. La preferencia lleva un ítem por cuota y `external_reference = chk_<checkoutId>` (nunca un payment id); el webhook es `POST /payments/webhooks/mp/checkout/:checkoutId` y `confirmMpCheckout` marca `PAID` todas sus cuotas. Las cuotas copian el `checkoutUrl` del checkout pero **no** su `mpPreferenceId`.
3. `Person.payWithMercadoPago` (default `true`, se edita en la ficha del alumno): apagado, la cuota se crea igual pero sin link (paga por transferencia).
4. Si una cuota de un checkout `OPEN` se paga por otra vía (confirmar transferencia), `supersedeCheckoutsOf` lo pasa a `SUPERSEDED`, borra el link de sus cuotas y expira la preferencia en MP (best effort); renovar una de esas cuotas crea un link individual y la saca del checkout. La reconciliación sigue mirando los `SUPERSEDED` 7 días. Renovar una cuota de un checkout `OPEN` sin link regenera el link **combinado**.
5. Con `sendWhatsapp`, los links salen enseguida por WhatsApp (`SendPaymentLinks`, kind `PAYMENT_LINK`, mismo gate que las automatizaciones: Pro + cuenta activa + template aprobado); el recordatorio semanal manda uno por checkout, no uno por chico.
- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto: - **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`. 1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`.
2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre. 2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.

View File

@@ -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;

View File

@@ -31,6 +31,9 @@ model User {
subscription BillingSubscription? subscription BillingSubscription?
studentAccounts StudentAccount[] @relation("StudentAccountsCreated") studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
people Person[] @relation("OwnerPeople") people Person[] @relation("OwnerPeople")
autoCharge AutoChargeSettings?
paymentRuns PaymentRun[]
checkouts PaymentCheckout[]
@@map("users") @@map("users")
} }

View File

@@ -1,24 +1,24 @@
// Domain models // Domain models
model Group { model Group {
id String @id @default(cuid()) id String @id @default(cuid())
name String name String
description String? description String?
days WeekDay[] days WeekDay[]
time String? time String?
capacity Int? capacity Int?
price Decimal? @db.Decimal(10, 2) price Decimal? @db.Decimal(10, 2)
billingType BillingType? @map("billing_type") billingType BillingType? @map("billing_type")
dueDay Int? @map("due_day") dueDay Int? @map("due_day")
// Weekly WhatsApp automations, off until the teacher turns them on. // Weekly WhatsApp automations, off until the teacher turns them on.
autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders") autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
autoReengagement Boolean @default(false) @map("auto_reengagement") autoReengagement Boolean @default(false) @map("auto_reengagement")
// KIDS: each student is a kid and the contact is the adult in charge. // KIDS: each student is a kid and the contact is the adult in charge.
audience GroupAudience @default(ADULTS) audience GroupAudience @default(ADULTS)
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token") inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
createdById String @map("created_by_id") createdById String @map("created_by_id")
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")
owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey") owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey")
members GroupMember[] members GroupMember[]
@@ -85,18 +85,23 @@ enum AttendeeStatus {
// teacher through a hand-written partial index (`people_owner_phone_key`, // teacher through a hand-written partial index (`people_owner_phone_key`,
// `WHERE phone IS NOT NULL`): Prisma does not model it. // `WHERE phone IS NOT NULL`): Prisma does not model it.
model Person { model Person {
id String @id @default(cuid()) id String @id @default(cuid())
createdById String @map("created_by_id") createdById String @map("created_by_id")
fullName String @map("full_name") fullName String @map("full_name")
email String? email String?
phone String? phone String?
notes String? notes String?
createdAt DateTime @default(now()) @map("created_at") // Automatic monthly charges only build a Mercado Pago link for people with
updatedAt DateTime @updatedAt @map("updated_at") // 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) owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade)
attendees Attendee[] attendees Attendee[]
studentAccounts StudentAccountPerson[] 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). // As a kid: the adult in charge (one in v1, enforced by the code).
guardians PersonGuardian[] @relation("GuardianChild") guardians PersonGuardian[] @relation("GuardianChild")
// As the adult in charge: their kids. An adult has no memberships of their own. // 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") mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
mpPaymentId String? @map("mp_payment_id") mpPaymentId String? @map("mp_payment_id")
paidAt DateTime? @map("paid_at") 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") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey") 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") attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
checkout PaymentCheckout? @relation(fields: [checkoutId], references: [id], onDelete: SetNull)
outboundMessages OutboundMessage[] outboundMessages OutboundMessage[]
reportedItems ReportedPaymentItem[] reportedItems ReportedPaymentItem[]
@@index([groupId], map: "payments_groupId_idx") @@index([groupId], map: "payments_groupId_idx")
@@index([attendeeId], map: "payments_attendeeId_idx") @@index([attendeeId], map: "payments_attendeeId_idx")
@@index([checkoutId])
@@map("payments") @@map("payments")
} }

View 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")
}

View File

@@ -19,6 +19,8 @@ enum WhatsappAccountStatus {
enum WhatsappMessageKind { enum WhatsappMessageKind {
PAYMENT_REMINDER PAYMENT_REMINDER
REENGAGEMENT REENGAGEMENT
// The monthly combined payment link, sent when it is generated.
PAYMENT_LINK
} }
enum OutboundMessageStatus { enum OutboundMessageStatus {
@@ -92,9 +94,10 @@ model OutboundMessage {
groupId String @map("group_id") groupId String @map("group_id")
attendeeId String @map("attendee_id") attendeeId String @map("attendee_id")
paymentId String? @map("payment_id") paymentId String? @map("payment_id")
checkoutId String? @map("checkout_id")
kind WhatsappMessageKind kind WhatsappMessageKind
provider MessagingProviderId 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") periodKey String @map("period_key")
toPhone String @map("to_phone") toPhone String @map("to_phone")
providerMessageId String? @map("provider_message_id") providerMessageId String? @map("provider_message_id")
@@ -105,9 +108,10 @@ model OutboundMessage {
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "outbound_messages_groupId_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") 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") 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([kind, attendeeId, periodKey], map: "outbound_messages_kind_attendeeId_periodKey_key")
@@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key") @@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key")

View File

@@ -49,7 +49,7 @@ export function isPublicApiRequest(method: string, path: string): boolean {
} }
// Mercado Pago notifications about a Checkout Pro payment: no session; the // Mercado Pago notifications about a Checkout Pro payment: no session; the
// owner's Mercado Pago account is asked before anything changes. // owner's Mercado Pago account is asked before anything changes.
if (method === 'POST' && /^\/api\/v1\/payments\/webhooks\/mp\/[A-Za-z0-9_-]+$/.test(normalizedPath)) { if (method === 'POST' && /^\/api\/v1\/payments\/webhooks\/mp\/(checkout\/)?[A-Za-z0-9_-]+$/.test(normalizedPath)) {
return true; return true;
} }
// Back from the Pro checkout: only redirects to the web, which has the session. // Back from the Pro checkout: only redirects to the web, which has the session.

View File

@@ -8,6 +8,7 @@ export const personContactSelect = {
email: true, email: true,
phone: true, phone: true,
notes: true, notes: true,
payWithMercadoPago: true,
...guardianSelect, ...guardianSelect,
} as const; } as const;
@@ -20,6 +21,7 @@ export type PersonContactRecord = {
email: string | null; email: string | null;
phone: string | null; phone: string | null;
notes: string | null; notes: string | null;
payWithMercadoPago?: boolean;
guardians?: { guardian: GuardianContact }[]; guardians?: { guardian: GuardianContact }[];
}; };
@@ -69,6 +71,7 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
phone: record.person.phone, phone: record.person.phone,
...guardianFields(record.person), ...guardianFields(record.person),
notes: record.person.notes, notes: record.person.notes,
payWithMercadoPago: record.person.payWithMercadoPago ?? true,
notifyToken: record.notifyToken ?? null, notifyToken: record.notifyToken ?? null,
createdAt: record.createdAt.toISOString(), createdAt: record.createdAt.toISOString(),
updatedAt: record.updatedAt.toISOString(), updatedAt: record.updatedAt.toISOString(),

View File

@@ -9,9 +9,11 @@ export {
} from './crypto'; } from './crypto';
export { export {
createCheckoutPreference, createCheckoutPreference,
expireCheckoutPreference,
MP_API_URL, MP_API_URL,
type MpCreatePreferenceInput, type MpCreatePreferenceInput,
type MpPreference, type MpPreference,
type MpPreferenceItem,
type MpSearchedPayment, type MpSearchedPayment,
searchMpPaymentByExternalReference, searchMpPaymentByExternalReference,
} from './mp-http'; } from './mp-http';

View File

@@ -6,9 +6,16 @@ export const MP_API_URL = 'https://api.mercadopago.com';
// Mercado Pago runs the seller's money straight into the professor's own // Mercado Pago runs the seller's money straight into the professor's own
// account: no platform_id of ours and no fee split. // account: no platform_id of ours and no fee split.
export type MpPreferenceItem = { title: string; unitPrice: number };
export type MpCreatePreferenceInput = { export type MpCreatePreferenceInput = {
title: string; title: string;
unitPrice: number; unitPrice: number;
/**
* Several lines in one link (a combined monthly charge). Without it the
* preference has the single `title` / `unitPrice` line.
*/
items?: MpPreferenceItem[];
currencyId: string; currencyId: string;
externalReference: string; externalReference: string;
/** Where the buyer lands after paying (pending/success/failure). */ /** Where the buyer lands after paying (pending/success/failure). */
@@ -58,14 +65,14 @@ export async function createCheckoutPreference(
Authorization: `Bearer ${accessToken}`, Authorization: `Bearer ${accessToken}`,
}, },
body: JSON.stringify({ body: JSON.stringify({
items: [ items: (input.items?.length ? input.items : [{ title: input.title, unitPrice: input.unitPrice }]).map(
{ (item) => ({
title: input.title, title: item.title,
currency_id: input.currencyId, currency_id: input.currencyId,
quantity: 1, quantity: 1,
unit_price: input.unitPrice, unit_price: item.unitPrice,
}, }),
], ),
external_reference: input.externalReference, external_reference: input.externalReference,
...(isPublicHttpsUrl(input.backUrl) ? { auto_return: 'approved' } : {}), ...(isPublicHttpsUrl(input.backUrl) ? { auto_return: 'approved' } : {}),
...(input.notificationUrl && isPublicHttpsUrl(input.notificationUrl) ...(input.notificationUrl && isPublicHttpsUrl(input.notificationUrl)
@@ -101,6 +108,38 @@ export async function createCheckoutPreference(
}; };
} }
/**
* Expires a preference so its link stops accepting payments (a combined link
* one of whose fees was paid some other way). Best effort: the caller decides
* what to do when Mercado Pago does not answer.
*/
export async function expireCheckoutPreference(
accessToken: string,
preferenceId: string,
now: Date = new Date(),
): Promise<void> {
let response: Response;
try {
response = await fetch(`${MP_API_URL}/checkout/preferences/${encodeURIComponent(preferenceId)}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({ expires: true, expiration_date_to: now.toISOString() }),
});
} catch (error) {
logger.error({ err: error }, 'Mercado Pago preferences endpoint unreachable');
throw new MpApiError(0, null);
}
if (!response.ok) {
logger.error({ status: response.status }, 'Mercado Pago preference expiration failed');
throw new MpApiError(response.status, null);
}
}
export type MpSearchedPayment = { export type MpSearchedPayment = {
id: string; id: string;
status: string; status: string;

View File

@@ -0,0 +1,23 @@
import type { UpdateAutoChargeSettings } from '@gruperly/shared';
import { UpdateAutoChargeSettingsSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { AutoChargeSettingsUseCase } from './use-case';
const route = new Hono();
route.get('/auto-charge', async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
return resultJson(c, await new AutoChargeSettingsUseCase().get(user.id));
});
route.put('/auto-charge', validate.json(UpdateAutoChargeSettingsSchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const input = c.req.valid('json') as UpdateAutoChargeSettings;
return resultJson(c, await new AutoChargeSettingsUseCase().update(user.id, input));
});
export default route;

View File

@@ -0,0 +1,90 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { AutoChargeSettingsDto, ProblemDetails, Result, UpdateAutoChargeSettings } from '@gruperly/shared';
import { AUTO_CHARGE_DEFAULT_DUE_IN_DAYS, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { teacherTimeZone } from '@/modules/student-portal/lib/schedule';
import { localDateIn, monthKey, nextAutoChargeDate } from '../../lib/auto-charge-schedule';
type AutoChargeSettingsDeps = {
db?: Pick<PrismaClient, 'autoChargeSettings' | 'paymentRun' | 'user'>;
planGuard?: Pick<PlanGuard, 'requireFeature'>;
now?: Date;
};
const DEFAULTS = { enabled: false, chargeDay: 1, dueInDays: AUTO_CHARGE_DEFAULT_DUE_IN_DAYS, sendWhatsapp: false, enabledAt: null };
/**
* Settings → "Cobro automático": the teacher's day of the month, due days and
* whether the links go out by WhatsApp. Turning something on goes through the
* plan (Mercado Pago charges; WhatsApp automations for the sending); turning it
* off always works.
*/
export class AutoChargeSettingsUseCase {
constructor(private readonly deps: AutoChargeSettingsDeps = {}) {}
private get db() {
return this.deps.db ?? prisma;
}
async get(ownerId: string): Promise<Result<AutoChargeSettingsDto, ProblemDetails>> {
return ok(await this.load(ownerId));
}
async update(ownerId: string, input: UpdateAutoChargeSettings): Promise<Result<AutoChargeSettingsDto, ProblemDetails>> {
const planGuard = this.deps.planGuard ?? new PlanGuard();
if (input.enabled === true) {
const allowed = await planGuard.requireFeature(ownerId, 'mpCharges');
if (!allowed.ok) return allowed;
}
if (input.sendWhatsapp === true) {
const allowed = await planGuard.requireFeature(ownerId, 'whatsappAutomations');
if (!allowed.ok) return allowed;
}
const current = await this.db.autoChargeSettings.findUnique({ where: { ownerId } });
const turningOn = input.enabled === true && !current?.enabled;
const data = {
...(input.enabled !== undefined ? { enabled: input.enabled } : {}),
...(input.chargeDay !== undefined ? { chargeDay: input.chargeDay } : {}),
...(input.dueInDays !== undefined ? { dueInDays: input.dueInDays } : {}),
...(input.sendWhatsapp !== undefined ? { sendWhatsapp: input.sendWhatsapp } : {}),
...(turningOn ? { enabledAt: this.deps.now ?? new Date() } : {}),
};
await this.db.autoChargeSettings.upsert({ where: { ownerId }, create: { ownerId, ...data }, update: data });
return ok(await this.load(ownerId));
}
private async load(ownerId: string): Promise<AutoChargeSettingsDto> {
const now = this.deps.now ?? new Date();
const [settings, owner, lastRun] = await Promise.all([
this.db.autoChargeSettings.findUnique({ where: { ownerId } }),
this.db.user.findUnique({ where: { id: ownerId }, select: { country: true } }),
this.db.paymentRun.findFirst({ where: { ownerId }, orderBy: { createdAt: 'desc' } }),
]);
const current = settings ?? DEFAULTS;
const timeZone = teacherTimeZone(owner?.country);
const ranThisMonth = lastRun?.periodKey === monthKey(localDateIn(now, timeZone));
return {
enabled: current.enabled,
chargeDay: current.chargeDay,
dueInDays: current.dueInDays,
sendWhatsapp: current.sendWhatsapp,
nextRunDate: current.enabled ? nextAutoChargeDate(current, now, timeZone, ranThisMonth) : null,
lastRun: lastRun
? {
periodKey: lastRun.periodKey,
status: lastRun.status,
skipReason: lastRun.skipReason,
fees: lastRun.fees,
checkouts: lastRun.checkouts,
linked: lastRun.linked,
failed: lastRun.failed,
sent: lastRun.sent,
createdAt: lastRun.createdAt.toISOString(),
}
: null,
};
}
}

View File

@@ -0,0 +1,195 @@
import type { PrismaClient } from '@generated/prisma/client';
import { type CountryCode, currencyForCountry } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { getApiPublicOrigin } from '@/lib/public-origin';
import { logger } from '@/logger';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { getMpAccessToken } from '@/modules/mp';
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
import { guardianSelect, primaryGuardian } from '@/modules/people/lib/people';
import { teacherTimeZone } from '@/modules/student-portal/lib/schedule';
import { SendPaymentLinks } from '@/modules/whatsapp/jobs/send-payment-links';
import { autoChargeDueDate, localDateIn, monthKey } from '../../lib/auto-charge-schedule';
import { buildCheckoutLink } from '../../lib/checkouts';
const UNIQUE_VIOLATION = 'P2002';
export type GenerateMonthlyChargesDeps = {
db?: PrismaClient;
getToken?: typeof getMpAccessToken;
createPreference?: typeof createCheckoutPreference;
planGuard?: Pick<PlanGuard, 'hasFeature'>;
/** Sends the generated links by WhatsApp; returns how many went out. */
sendLinks?: (ownerId: string, checkoutIds: string[]) => Promise<number>;
webOrigin?: string;
apiOrigin?: string;
now?: Date;
};
export type GenerateMonthlyChargesResult =
| { outcome: 'already_ran' }
| { outcome: 'skipped'; reason: string }
| { outcome: 'done'; fees: number; checkouts: number; linked: number; failed: number; sent: number };
/**
* The automatic monthly charge of one teacher.
*
* Every ACTIVE member of their monthly groups with a price gets this month's
* fee. Fees are bundled by payer (the adult in charge for kids, the person
* otherwise) into one Mercado Pago link with one line per fee; people who pay
* by transfer (`payWithMercadoPago` off) get the fee without a link.
*
* Rows first, links after, as in the manual batch: a link that fails leaves its
* checkout OPEN without a link and the teacher retries it with "Generar" from
* Cobros. The unique run per teacher and month makes a second call a no-op.
*/
export class GenerateMonthlyCharges {
constructor(private readonly deps: GenerateMonthlyChargesDeps = {}) {}
async execute(ownerId: string): Promise<GenerateMonthlyChargesResult> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const owner = await db.user.findUnique({
where: { id: ownerId },
select: { country: true, autoCharge: true },
});
if (!owner?.autoCharge) return { outcome: 'skipped', reason: 'not_configured' };
const settings = owner.autoCharge;
const local = localDateIn(now, teacherTimeZone(owner.country));
const periodKey = monthKey(local);
let runId: string;
try {
const run = await db.paymentRun.create({ data: { ownerId, periodKey }, select: { id: true } });
runId = run.id;
} catch (error) {
if ((error as { code?: string }).code === UNIQUE_VIOLATION) return { outcome: 'already_ran' };
throw error;
}
const skip = async (reason: string): Promise<GenerateMonthlyChargesResult> => {
await db.paymentRun.update({
where: { id: runId },
data: { status: 'SKIPPED', skipReason: reason, finishedAt: new Date() },
});
return { outcome: 'skipped', reason };
};
const planGuard = this.deps.planGuard ?? new PlanGuard();
if (!(await planGuard.hasFeature(ownerId, 'mpCharges'))) return skip('plan_feature_required');
const token = await (this.deps.getToken ?? getMpAccessToken)(ownerId);
if (!token.ok) return skip('mp_not_connected');
const groups = await db.group.findMany({
where: {
createdById: ownerId,
price: { not: null },
OR: [{ billingType: null }, { billingType: 'MONTHLY' }],
},
select: { id: true, price: true },
orderBy: { createdAt: 'asc' },
});
if (groups.length === 0) return skip('no_groups');
const priceOf = new Map(groups.map((group) => [group.id, group.price]));
const attendees = await db.attendee.findMany({
where: {
groupId: { in: groups.map((group) => group.id) },
status: 'ACTIVE',
// Already billed this month (a fee created by hand counts only if it has the period).
payments: { none: { periodKey } },
},
orderBy: { createdAt: 'asc' },
select: {
id: true,
groupId: true,
person: { select: { id: true, payWithMercadoPago: true, ...guardianSelect } },
},
});
const currency = currencyForCountry((owner.country as CountryCode | null) ?? null);
const dueDate = autoChargeDueDate(local, settings.dueInDays);
// Payer → their fees. Map keeps the first-seen order.
const byPayer = new Map<string, typeof attendees>();
for (const attendee of attendees) {
const payerId = primaryGuardian(attendee.person)?.id ?? attendee.person.id;
const list = byPayer.get(payerId) ?? [];
list.push(attendee);
byPayer.set(payerId, list);
}
let fees = 0;
const checkoutIds: string[] = [];
for (const [payerId, payerAttendees] of byPayer) {
const created = await db.$transaction(async (tx) => {
const viaMp = payerAttendees.filter((attendee) => attendee.person.payWithMercadoPago);
const total = viaMp.reduce((sum, attendee) => sum + Number(priceOf.get(attendee.groupId)?.toString() ?? 0), 0);
const checkout = viaMp.length
? await tx.paymentCheckout.create({
data: { ownerId, payerPersonId: payerId, runId, amount: total, currency, dueDate },
select: { id: true },
})
: null;
for (const attendee of payerAttendees) {
const price = priceOf.get(attendee.groupId);
if (price == null) continue;
await tx.payment.create({
data: {
groupId: attendee.groupId,
attendeeId: attendee.id,
amount: price,
currency,
dueDate,
periodKey,
status: 'PENDING',
checkoutId: attendee.person.payWithMercadoPago ? (checkout?.id ?? null) : null,
},
});
}
return { checkoutId: checkout?.id ?? null, fees: payerAttendees.length };
});
fees += created.fees;
if (created.checkoutId) checkoutIds.push(created.checkoutId);
}
const context = {
webOrigin: this.deps.webOrigin ?? getWebOrigin(),
apiOrigin: this.deps.apiOrigin ?? getApiPublicOrigin(),
accessToken: token.value.accessToken,
};
const linkedIds: string[] = [];
let failed = 0;
for (const checkoutId of checkoutIds) {
const link = await buildCheckoutLink(db, checkoutId, context, { createPreference: this.deps.createPreference });
if (link.ok) linkedIds.push(checkoutId);
else failed += 1;
}
let sent = 0;
if (settings.sendWhatsapp && linkedIds.length > 0) {
try {
sent = await (this.deps.sendLinks ?? defaultSendLinks)(ownerId, linkedIds);
} catch (error) {
// The fees and links are there: a WhatsApp failure must not undo the run.
logger.error({ err: error }, 'Sending the monthly payment links by WhatsApp failed');
}
}
const result = { fees, checkouts: checkoutIds.length, linked: linkedIds.length, failed, sent };
await db.paymentRun.update({
where: { id: runId },
data: { status: 'DONE', ...result, finishedAt: new Date() },
});
return { outcome: 'done', ...result };
}
}
async function defaultSendLinks(ownerId: string, checkoutIds: string[]): Promise<number> {
const totals = await new SendPaymentLinks().execute(ownerId, checkoutIds);
return totals.sent;
}

View File

@@ -37,6 +37,7 @@ export class ListPayments {
include: { include: {
group: { select: { name: true, price: true } }, group: { select: { name: true, price: true } },
attendee: { select: { person: { select: { fullName: true } } } }, attendee: { select: { person: { select: { fullName: true } } } },
checkout: { select: { _count: { select: { payments: true } } } },
}, },
skip: getPaginationOffset(query), skip: getPaginationOffset(query),
take: query.pageSize, take: query.pageSize,

View File

@@ -13,10 +13,17 @@ import { logger } from '@/logger';
import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { getMpAccessToken } from '@/modules/mp'; import { getMpAccessToken } from '@/modules/mp';
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib'; import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
import { CHECKOUT_BACK_PATH, type PaymentRecord, paymentNotificationUrl, toPaymentDto } from '../../lib'; import {
buildCheckoutLink,
CHECKOUT_BACK_PATH,
type PaymentRecord,
paymentDtoInclude,
paymentNotificationUrl,
toPaymentDto,
} from '../../lib';
type RenewDeps = { type RenewDeps = {
db?: Pick<PrismaClient, 'payment' | 'user'>; db?: Pick<PrismaClient, 'payment' | 'user' | 'paymentCheckout'>;
createPreference?: typeof createCheckoutPreference; createPreference?: typeof createCheckoutPreference;
getToken?: typeof getMpAccessToken; getToken?: typeof getMpAccessToken;
webOrigin?: string; webOrigin?: string;
@@ -39,6 +46,7 @@ export class RenewPaymentLink {
where: { id: paymentId }, where: { id: paymentId },
include: { include: {
attendee: { select: { person: { select: { fullName: true } } } }, attendee: { select: { person: { select: { fullName: true } } } },
checkout: { select: { status: true, _count: { select: { payments: true } } } },
group: { group: {
select: { select: {
name: true, name: true,
@@ -86,7 +94,23 @@ export class RenewPaymentLink {
return token; return token;
} }
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}${CHECKOUT_BACK_PATH}`; const webOrigin = this.deps.webOrigin ?? getWebOrigin();
const apiOrigin = this.deps.apiOrigin ?? getApiPublicOrigin();
// A fee of an open combined link gets that link back, covering all the
// payer's unpaid fees, instead of a single one.
if (payment.checkoutId && payment.checkout?.status === 'OPEN') {
const link = await buildCheckoutLink(
db,
payment.checkoutId,
{ webOrigin, apiOrigin, accessToken: token.value.accessToken },
{ createPreference: this.deps.createPreference },
);
if (!link.ok) return err(mpProviderErrorProblem());
return this.reload(payment.id);
}
const backUrl = `${webOrigin}${CHECKOUT_BACK_PATH}`;
const createPreference = this.deps.createPreference ?? createCheckoutPreference; const createPreference = this.deps.createPreference ?? createCheckoutPreference;
let preference: { initPoint: string; id: string }; let preference: { initPoint: string; id: string };
@@ -97,7 +121,7 @@ export class RenewPaymentLink {
currencyId: currency, currencyId: currency,
externalReference: payment.id, externalReference: payment.id,
backUrl, backUrl,
notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id), notificationUrl: paymentNotificationUrl(apiOrigin, payment.id),
}); });
} catch (error) { } catch (error) {
if (error instanceof Error) { if (error instanceof Error) {
@@ -108,13 +132,17 @@ export class RenewPaymentLink {
const updated = await db.payment.update({ const updated = await db.payment.update({
where: { id: payment.id }, where: { id: payment.id },
data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id }, // Out of a superseded combined link: from now on it is a single fee.
include: { data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id, checkoutId: null },
attendee: { select: { person: { select: { fullName: true } } } }, include: paymentDtoInclude,
group: { select: { name: true, price: true } },
},
}); });
return ok(toPaymentDto(updated as unknown as PaymentRecord)); return ok(toPaymentDto(updated as unknown as PaymentRecord));
} }
private async reload(paymentId: string): Promise<Result<PaymentDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const row = await db.payment.findUniqueOrThrow({ where: { id: paymentId }, include: paymentDtoInclude });
return ok(toPaymentDto(row as unknown as PaymentRecord));
}
} }

View File

@@ -7,6 +7,12 @@ import { type FileStorage, getFileStorage } from '@/lib/storage';
import { buildGroupWhereForUser } from '@/modules/groups/lib'; import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { storageNotAvailableProblem } from '@/modules/student-portal/lib/problems'; import { storageNotAvailableProblem } from '@/modules/student-portal/lib/problems';
import { OVERDUE_GRACE_MS } from '../../jobs/mark-overdue-payments'; import { OVERDUE_GRACE_MS } from '../../jobs/mark-overdue-payments';
import {
type ExpirePreferencesDeps,
expireSupersededPreferences,
type SupersededPreference,
supersedeCheckoutsOf,
} from '../../lib/checkouts';
import { type ReviewNotifier, scheduleReviewNotification } from '../../lib/review-notifications'; import { type ReviewNotifier, scheduleReviewNotification } from '../../lib/review-notifications';
export const RECEIPT_URL_TTL_SECONDS = 5 * 60; export const RECEIPT_URL_TTL_SECONDS = 5 * 60;
@@ -18,6 +24,7 @@ type ReportedDeps = {
storage?: FileStorage | null; storage?: FileStorage | null;
notify?: ReviewNotifier; notify?: ReviewNotifier;
now?: Date; now?: Date;
expirePreferences?: (preferences: SupersededPreference[], deps?: ExpirePreferencesDeps) => Promise<void>;
}; };
const reportSelect = { const reportSelect = {
@@ -155,6 +162,7 @@ export class ReportedPayments {
const now = this.now; const now = this.now;
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
let superseded: SupersededPreference[] = [];
const reviewed = await unitOfWork.executeResult(async (tx) => { const reviewed = await unitOfWork.executeResult(async (tx) => {
const claimed = await tx.reportedPayment.updateMany({ const claimed = await tx.reportedPayment.updateMany({
where: { id: reportId, ...accessible(userId), status: 'REPORTED' }, where: { id: reportId, ...accessible(userId), status: 'REPORTED' },
@@ -179,11 +187,17 @@ export class ReportedPayments {
where: { id: { in: items.map((item) => item.paymentId) }, status: { in: ['PENDING', 'OVERDUE'] } }, where: { id: { in: items.map((item) => item.paymentId) }, status: { in: ['PENDING', 'OVERDUE'] } },
data: { status: 'PAID', paidAt: now }, data: { status: 'PAID', paidAt: now },
}); });
// A combined link would charge these fees again.
superseded = await supersedeCheckoutsOf(tx, items.map((item) => item.paymentId));
} }
return ok(null); return ok(null);
}); });
if (!reviewed.ok) return reviewed; if (!reviewed.ok) return reviewed;
if (superseded.length > 0) {
void (this.deps.expirePreferences ?? expireSupersededPreferences)(superseded);
}
(this.deps.notify ?? scheduleReviewNotification)(reportId, now); (this.deps.notify ?? scheduleReviewNotification)(reportId, now);
return this.load(reportId); return this.load(reportId);
} }

View File

@@ -1,6 +1,6 @@
import { Hono } from 'hono'; import { Hono } from 'hono';
import { problemJson } from '@/http/problem-details'; import { problemJson } from '@/http/problem-details';
import { HandleMpPaymentNotification } from './use-case'; import { HandleMpCheckoutNotification, HandleMpPaymentNotification } from './use-case';
const route = new Hono(); const route = new Hono();
@@ -14,4 +14,11 @@ route.post('/webhooks/mp/:paymentId', async (c) => {
return c.json({ received: true }); return c.json({ received: true });
}); });
/** Same, for a combined link (`chk_<id>`): every fee of the payer at once. */
route.post('/webhooks/mp/checkout/:checkoutId', async (c) => {
const result = await new HandleMpCheckoutNotification().execute(c.req.param('checkoutId'));
if (!result.ok) return problemJson(c, result.error);
return c.json({ received: true });
});
export default route; export default route;

View File

@@ -5,7 +5,13 @@ import { mpProviderErrorProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { logger } from '@/logger'; import { logger } from '@/logger';
import { MpApiError } from '@/modules/mp/lib'; import { MpApiError } from '@/modules/mp/lib';
import { type ConfirmMpPaymentDeps, type ConfirmMpPaymentOutcome, confirmMpPayment } from '../../lib'; import {
type ConfirmMpCheckoutDeps,
type ConfirmMpPaymentDeps,
type ConfirmMpPaymentOutcome,
confirmMpCheckout,
confirmMpPayment,
} from '../../lib';
type HandleMpPaymentNotificationDeps = ConfirmMpPaymentDeps & { type HandleMpPaymentNotificationDeps = ConfirmMpPaymentDeps & {
db?: Pick<PrismaClient, 'payment'>; db?: Pick<PrismaClient, 'payment'>;
@@ -43,3 +49,32 @@ export class HandleMpPaymentNotification {
} }
} }
} }
type HandleMpCheckoutNotificationDeps = ConfirmMpCheckoutDeps & {
db?: Pick<PrismaClient, 'paymentCheckout' | '$transaction'>;
};
/** `HandleMpPaymentNotification` for a combined link. */
export class HandleMpCheckoutNotification {
constructor(private readonly deps: HandleMpCheckoutNotificationDeps = {}) {}
async execute(checkoutId: string): Promise<Result<{ outcome: MpPaymentNotificationOutcome }, ProblemDetails>> {
const db = this.deps.db ?? prisma;
// SUPERSEDED too: it may have been paid right before it was invalidated.
const checkout = await db.paymentCheckout.findFirst({
where: { id: checkoutId, status: { in: ['OPEN', 'SUPERSEDED'] }, mpPreferenceId: { not: null } },
select: { id: true, ownerId: true },
});
if (!checkout) return ok({ outcome: 'ignored' });
try {
const outcome = await confirmMpCheckout(db, checkout, this.deps);
return ok({ outcome });
} catch (error) {
if (!(error instanceof MpApiError)) throw error;
logger.warn({ checkoutId: checkout.id, status: error.status }, 'Could not confirm a notified Mercado Pago payment');
return err(mpProviderErrorProblem());
}
}
}

View File

@@ -6,4 +6,5 @@ export {
ReconcilePayments, ReconcilePayments,
type ReconcilePaymentsResult, type ReconcilePaymentsResult,
} from './reconcile-payments'; } from './reconcile-payments';
export { RunAutoCharges, type RunAutoChargesResult } from './run-auto-charges';
export { startPaymentJobs } from './schedule'; export { startPaymentJobs } from './schedule';

View File

@@ -3,7 +3,7 @@ import prisma from '@/lib/prisma';
import { logger } from '@/logger'; import { logger } from '@/logger';
import { getMpAccessToken } from '@/modules/mp'; import { getMpAccessToken } from '@/modules/mp';
import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib'; import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib';
import { confirmMpPayment } from '../lib'; import { confirmMpCheckout, confirmMpPayment } from '../lib';
/** /**
* Pulls payments from Mercado Pago. The notification * Pulls payments from Mercado Pago. The notification
@@ -13,6 +13,8 @@ import { confirmMpPayment } from '../lib';
*/ */
const RECONCILE_AFTER_MS = 5 * 60 * 1000; const RECONCILE_AFTER_MS = 5 * 60 * 1000;
const BATCH_LIMIT = 50; const BATCH_LIMIT = 50;
/** A superseded combined link is still checked for a while: it may have been paid right before. */
const SUPERSEDED_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
export type ReconcilePaymentsResult = { export type ReconcilePaymentsResult = {
paid: number; paid: number;
@@ -40,6 +42,8 @@ export class ReconcilePayments {
where: { where: {
status: 'PENDING', status: 'PENDING',
checkoutUrl: { not: null }, checkoutUrl: { not: null },
// Fees of a combined link are confirmed through their checkout below.
checkoutId: null,
createdAt: { lt: new Date(now.getTime() - RECONCILE_AFTER_MS) }, createdAt: { lt: new Date(now.getTime() - RECONCILE_AFTER_MS) },
}, },
include: { group: { select: { createdById: true } } }, include: { group: { select: { createdById: true } } },
@@ -67,6 +71,33 @@ export class ReconcilePayments {
} }
} }
const checkouts = await db.paymentCheckout.findMany({
where: {
mpPreferenceId: { not: null },
createdAt: { lt: new Date(now.getTime() - RECONCILE_AFTER_MS) },
OR: [
{ status: 'OPEN' },
{ status: 'SUPERSEDED', updatedAt: { gt: new Date(now.getTime() - SUPERSEDED_WINDOW_MS) } },
],
},
select: { id: true, ownerId: true },
orderBy: { createdAt: 'asc' },
take: BATCH_LIMIT,
});
for (const checkout of checkouts) {
try {
const outcome = await confirmMpCheckout(db, checkout, { getToken, search });
if (outcome === 'no_token') totals.skipped += 1;
if (outcome === 'paid') totals.paid += 1;
} catch (error) {
if (!(error instanceof MpApiError)) {
logger.error({ err: error }, 'Unexpected payment reconciliation failure');
}
totals.failed += 1;
}
}
return totals; return totals;
} }
} }

View File

@@ -0,0 +1,50 @@
import type { PrismaClient } from '@generated/prisma/client';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { teacherTimeZone } from '@/modules/student-portal/lib/schedule';
import { GenerateMonthlyCharges } from '../features/auto-charge/generate-monthly-charges';
import { isAutoChargeDue } from '../lib/auto-charge-schedule';
export type RunAutoChargesResult = { due: number; done: number; skipped: number; failed: number };
type RunAutoChargesDeps = {
db?: PrismaClient;
generator?: Pick<GenerateMonthlyCharges, 'execute'>;
now?: Date;
};
/**
* Hourly: runs the monthly charge of every teacher whose day it is on their
* own clock. Running every hour (and for a few days after the day) is what
* makes a restart or a failed tick harmless; the unique run per month keeps it
* to one.
*/
export class RunAutoCharges {
constructor(private readonly deps: RunAutoChargesDeps = {}) {}
async execute(): Promise<RunAutoChargesResult> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const generator = this.deps.generator ?? new GenerateMonthlyCharges({ db, now });
const settings = await db.autoChargeSettings.findMany({
where: { enabled: true },
select: { ownerId: true, chargeDay: true, enabledAt: true, owner: { select: { country: true } } },
});
const totals: RunAutoChargesResult = { due: 0, done: 0, skipped: 0, failed: 0 };
for (const entry of settings) {
if (!isAutoChargeDue(entry, now, teacherTimeZone(entry.owner.country))) continue;
totals.due += 1;
try {
const result = await generator.execute(entry.ownerId);
if (result.outcome === 'done') totals.done += 1;
if (result.outcome === 'skipped') totals.skipped += 1;
} catch (error) {
logger.error({ err: error, ownerId: entry.ownerId }, 'Automatic monthly charge failed');
totals.failed += 1;
}
}
return totals;
}
}

View File

@@ -1,9 +1,12 @@
import { logger } from '@/logger'; import { logger } from '@/logger';
import { MarkOverduePayments } from './mark-overdue-payments'; import { MarkOverduePayments } from './mark-overdue-payments';
import { ReconcilePayments } from './reconcile-payments'; import { ReconcilePayments } from './reconcile-payments';
import { RunAutoCharges } from './run-auto-charges';
const RECONCILE_CRON = '*/15 * * * *'; const RECONCILE_CRON = '*/15 * * * *';
const OVERDUE_CRON = '4 4 * * *'; const OVERDUE_CRON = '4 4 * * *';
// Hourly: each teacher's day of the month is on their own clock.
const AUTO_CHARGE_CRON = '7 * * * *';
/** /**
* Registers the payment background jobs. Called once from `server.ts`, following * Registers the payment background jobs. Called once from `server.ts`, following
@@ -37,4 +40,17 @@ export function startPaymentJobs(): void {
}, },
{ tz: 'UTC' }, { tz: 'UTC' },
).unref(); ).unref();
Bun.cron(
AUTO_CHARGE_CRON,
async () => {
try {
const totals = await new RunAutoCharges().execute();
if (totals.due > 0) logger.info(totals, 'Automatic monthly charges finished');
} catch (error) {
logger.error({ err: error }, 'Automatic monthly charges failed');
}
},
{ tz: 'UTC' },
).unref();
} }

View File

@@ -0,0 +1,84 @@
/*
* When the automatic monthly charge runs. Everything is on the teacher's clock
* (their country's time zone): the run of "December" is the one whose local
* date is in December.
*/
/** From `chargeDay` on, the run is tried for this many extra days (a server down that day). */
export const AUTO_CHARGE_CATCH_UP_DAYS = 3;
/** Local hour from which the run of the day goes out (nobody wants a link at 3 a.m.). */
export const AUTO_CHARGE_LOCAL_HOUR = 9;
export type LocalDate = { year: number; month: number; day: number; hour: number };
export function localDateIn(date: Date, timeZone: string): LocalDate {
const parts = new Intl.DateTimeFormat('en-US', {
timeZone,
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
hourCycle: 'h23',
}).formatToParts(date);
const value = (type: string) => Number(parts.find((part) => part.type === type)?.value ?? 0);
return { year: value('year'), month: value('month'), day: value('day'), hour: value('hour') };
}
/** "2026-12": the month a run (and its fees) belongs to. */
export function monthKey(local: Pick<LocalDate, 'year' | 'month'>): string {
return `${local.year}-${String(local.month).padStart(2, '0')}`;
}
function isoDay(year: number, month: number, day: number): string {
return new Date(Date.UTC(year, month - 1, day)).toISOString().slice(0, 10);
}
/** Due date of a fee created on `local`: `dueInDays` later, at noon UTC (a day, not an instant). */
export function autoChargeDueDate(local: LocalDate, dueInDays: number): Date {
return new Date(Date.UTC(local.year, local.month - 1, local.day + dueInDays, 12));
}
export type AutoChargeTiming = {
chargeDay: number;
/** When it was last turned on: a month whose day already passed by then is skipped. */
enabledAt: Date | null;
};
/**
* Whether this month's run is due right now (the caller still checks that it
* did not run yet: the unique run per month does that).
*/
export function isAutoChargeDue(settings: AutoChargeTiming, now: Date, timeZone: string): boolean {
const local = localDateIn(now, timeZone);
const { chargeDay } = settings;
if (local.day < chargeDay || local.day > chargeDay + AUTO_CHARGE_CATCH_UP_DAYS) return false;
if (local.day === chargeDay && local.hour < AUTO_CHARGE_LOCAL_HOUR) return false;
return !enabledAfterChargeDay(settings, local, timeZone);
}
function enabledAfterChargeDay(settings: AutoChargeTiming, local: LocalDate, timeZone: string): boolean {
if (!settings.enabledAt) return false;
const enabled = localDateIn(settings.enabledAt, timeZone);
return monthKey(enabled) === monthKey(local) && enabled.day > settings.chargeDay;
}
/**
* Local date (YYYY-MM-DD) of the next run: this month's day if it is still
* ahead (or due and not run yet), next month's otherwise.
*/
export function nextAutoChargeDate(
settings: AutoChargeTiming,
now: Date,
timeZone: string,
ranThisMonth: boolean,
): string {
const local = localDateIn(now, timeZone);
const thisMonthStillAhead =
!ranThisMonth
&& !enabledAfterChargeDay(settings, local, timeZone)
&& local.day <= settings.chargeDay + AUTO_CHARGE_CATCH_UP_DAYS;
if (thisMonthStillAhead) {
return isoDay(local.year, local.month, Math.max(settings.chargeDay, local.day));
}
return isoDay(local.year, local.month + 1, settings.chargeDay);
}

View File

@@ -0,0 +1,217 @@
import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { PrismaTransaction } from '@/lib/prisma';
import { logger } from '@/logger';
import { getMpAccessToken } from '@/modules/mp';
import {
createCheckoutPreference,
expireCheckoutPreference,
MpApiError,
searchMpPaymentByExternalReference,
} from '@/modules/mp/lib';
import { CHECKOUT_BACK_PATH } from './helpers';
/*
* Combined Mercado Pago links (`PaymentCheckout`): one Checkout Pro preference
* that pays every fee of the same payer. Its `external_reference` is
* `chk_<checkout id>`, never a payment id, so a combined payment can't be
* mistaken for a single fee's.
*/
const CHECKOUT_REFERENCE_PREFIX = 'chk_';
export function checkoutExternalReference(checkoutId: string): string {
return `${CHECKOUT_REFERENCE_PREFIX}${checkoutId}`;
}
/** Where Mercado Pago notifies a payment of a combined link (public: see `isPublicApiRequest`). */
export function checkoutNotificationUrl(apiOrigin: string, checkoutId: string): string {
return `${apiOrigin}/api/v1/payments/webhooks/mp/checkout/${encodeURIComponent(checkoutId)}?source_news=webhooks`;
}
/** One line per fee in the checkout page: "Yoga · Juan". */
export function checkoutItemTitle(groupName: string, studentName: string): string {
return `${groupName} · ${studentName}`;
}
export type CheckoutLinkDeps = {
getToken?: typeof getMpAccessToken;
createPreference?: typeof createCheckoutPreference;
};
type CheckoutDb = Pick<PrismaClient, 'paymentCheckout' | 'payment'>;
export type CheckoutLinkOutcome =
| { ok: true; checkoutUrl: string }
| { ok: false; reason: 'no_token' | 'empty' | 'mp_provider_error' | 'unknown_error' };
/**
* Creates (or recreates) the Mercado Pago link of an OPEN checkout, from the
* fees it still has unpaid, and copies it to those fees. Creating a link never
* charges anyone, so retrying it is safe.
*/
export async function buildCheckoutLink(
db: CheckoutDb,
checkoutId: string,
context: { webOrigin: string; apiOrigin: string; accessToken?: string },
deps: CheckoutLinkDeps = {},
): Promise<CheckoutLinkOutcome> {
const checkout = await db.paymentCheckout.findUnique({
where: { id: checkoutId },
select: {
id: true,
ownerId: true,
currency: true,
status: true,
payments: {
where: { status: { in: ['PENDING', 'OVERDUE'] } },
orderBy: { createdAt: 'asc' },
select: {
id: true,
amount: true,
group: { select: { name: true } },
attendee: { select: { person: { select: { fullName: true } } } },
},
},
},
});
if (checkout?.status !== 'OPEN' || checkout.payments.length === 0) {
return { ok: false, reason: 'empty' };
}
let accessToken = context.accessToken;
if (!accessToken) {
const token = await (deps.getToken ?? getMpAccessToken)(checkout.ownerId);
if (!token.ok) return { ok: false, reason: 'no_token' };
accessToken = token.value.accessToken;
}
const items = checkout.payments.map((payment) => ({
title: checkoutItemTitle(payment.group.name, payment.attendee.person.fullName),
unitPrice: Number(payment.amount.toString()),
}));
const total = items.reduce((sum, item) => sum + item.unitPrice, 0);
let preference: { id: string; initPoint: string };
try {
preference = await (deps.createPreference ?? createCheckoutPreference)(accessToken, {
title: items[0]?.title ?? '',
unitPrice: total,
items,
currencyId: checkout.currency,
externalReference: checkoutExternalReference(checkout.id),
backUrl: `${context.webOrigin}${CHECKOUT_BACK_PATH}`,
notificationUrl: checkoutNotificationUrl(context.apiOrigin, checkout.id),
});
} catch (error) {
if (error instanceof MpApiError) return { ok: false, reason: 'mp_provider_error' };
logger.error({ err: error }, 'Unexpected Mercado Pago combined preference failure');
return { ok: false, reason: 'unknown_error' };
}
await db.paymentCheckout.update({
where: { id: checkout.id },
data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id, amount: total },
});
await db.payment.updateMany({
where: { id: { in: checkout.payments.map((payment) => payment.id) } },
data: { checkoutUrl: preference.initPoint },
});
return { ok: true, checkoutUrl: preference.initPoint };
}
export type ConfirmMpCheckoutDeps = {
getToken?: typeof getMpAccessToken;
search?: typeof searchMpPaymentByExternalReference;
};
export type ConfirmMpCheckoutOutcome = 'paid' | 'unpaid' | 'no_token';
/**
* Same rule as `confirmMpPayment`, for a combined link: whatever triggered it
* is never trusted, the owner's account is. An approved payment marks the
* checkout and every fee of it still unpaid as PAID. A SUPERSEDED checkout is
* still checked (it may have been paid right before it was invalidated).
* Throws `MpApiError` when Mercado Pago cannot answer.
*/
export async function confirmMpCheckout(
db: Pick<PrismaClient, '$transaction'>,
checkout: { id: string; ownerId: string },
deps: ConfirmMpCheckoutDeps = {},
): Promise<ConfirmMpCheckoutOutcome> {
const token = await (deps.getToken ?? getMpAccessToken)(checkout.ownerId);
if (!token.ok) return 'no_token';
const reference = checkoutExternalReference(checkout.id);
const found = await (deps.search ?? searchMpPaymentByExternalReference)(token.value.accessToken, reference);
if (found?.status !== 'approved' || found.externalReference !== reference) return 'unpaid';
const paidAt = found.dateApproved ? new Date(found.dateApproved) : new Date();
await db.$transaction(async (tx) => {
await tx.paymentCheckout.update({
where: { id: checkout.id },
data: { status: 'PAID', mpPaymentId: found.id, paidAt },
});
await tx.payment.updateMany({
where: { checkoutId: checkout.id, status: { in: ['PENDING', 'OVERDUE'] } },
data: { status: 'PAID', mpPaymentId: found.id, paidAt },
});
});
return 'paid';
}
export type SupersededPreference = { ownerId: string; mpPreferenceId: string };
/**
* Some fees were paid outside their combined link (a confirmed transfer): the
* link would charge them again, so the checkout becomes SUPERSEDED and its fees
* lose the shared link (the teacher generates single ones from Cobros). Runs in
* the caller's transaction; the Mercado Pago preferences to expire are returned
* for `expireSupersededPreferences`, after the commit.
*/
export async function supersedeCheckoutsOf(
tx: Pick<PrismaTransaction, 'payment' | 'paymentCheckout'>,
paymentIds: string[],
): Promise<SupersededPreference[]> {
if (paymentIds.length === 0) return [];
const checkouts = await tx.paymentCheckout.findMany({
where: { status: 'OPEN', payments: { some: { id: { in: paymentIds } } } },
select: { id: true, ownerId: true, mpPreferenceId: true },
});
if (checkouts.length === 0) return [];
const ids = checkouts.map((checkout) => checkout.id);
await tx.paymentCheckout.updateMany({ where: { id: { in: ids }, status: 'OPEN' }, data: { status: 'SUPERSEDED' } });
await tx.payment.updateMany({ where: { checkoutId: { in: ids } }, data: { checkoutUrl: null } });
return checkouts.flatMap((checkout) =>
checkout.mpPreferenceId ? [{ ownerId: checkout.ownerId, mpPreferenceId: checkout.mpPreferenceId }] : [],
);
}
export type ExpirePreferencesDeps = {
getToken?: typeof getMpAccessToken;
expire?: typeof expireCheckoutPreference;
};
/** Best effort: a link that could not be expired is still caught by the reconciliation. */
export async function expireSupersededPreferences(
preferences: SupersededPreference[],
deps: ExpirePreferencesDeps = {},
): Promise<void> {
for (const preference of preferences) {
try {
const token = await (deps.getToken ?? getMpAccessToken)(preference.ownerId);
if (!token.ok) continue;
await (deps.expire ?? expireCheckoutPreference)(token.value.accessToken, preference.mpPreferenceId);
} catch (error) {
logger.warn({ err: error }, 'Could not expire a superseded Mercado Pago link');
}
}
}
export const checkoutSummarySelect = {
id: true,
amount: true,
status: true,
_count: { select: { payments: true } },
} satisfies Prisma.PaymentCheckoutSelect;

View File

@@ -1,9 +1,17 @@
import type { Prisma } from '@generated/prisma/client';
import type { PaymentDto } from '@gruperly/shared'; import type { PaymentDto } from '@gruperly/shared';
/* Where Mercado Pago sends whoever paid a Checkout Pro link: the student app /* Where Mercado Pago sends whoever paid a Checkout Pro link: the student app
(without a student session it falls through to /access). */ (without a student session it falls through to /access). */
export const CHECKOUT_BACK_PATH = '/student/payments'; export const CHECKOUT_BACK_PATH = '/student/payments';
/** What `toPaymentDto` reads besides the payment's own columns. */
export const paymentDtoInclude = {
attendee: { select: { person: { select: { fullName: true } } } },
group: { select: { name: true, price: true } },
checkout: { select: { _count: { select: { payments: true } } } },
} satisfies Prisma.PaymentInclude;
export type PaymentRecord = { export type PaymentRecord = {
id: string; id: string;
groupId: string; groupId: string;
@@ -13,6 +21,9 @@ export type PaymentRecord = {
status: PaymentDto['status']; status: PaymentDto['status'];
description: string | null; description: string | null;
checkoutUrl: string | null; checkoutUrl: string | null;
checkoutId?: string | null;
periodKey?: string | null;
checkout?: { _count: { payments: number } } | null;
dueDate: Date; dueDate: Date;
paidAt: Date | null; paidAt: Date | null;
createdAt: Date; createdAt: Date;
@@ -33,6 +44,9 @@ export function toPaymentDto(record: PaymentRecord): PaymentDto {
status: record.status, status: record.status,
description: record.description, description: record.description,
checkoutUrl: record.checkoutUrl, checkoutUrl: record.checkoutUrl,
checkoutId: record.checkoutId ?? null,
checkoutItemCount: record.checkout?._count.payments ?? null,
periodKey: record.periodKey ?? null,
dueDate: record.dueDate.toISOString(), dueDate: record.dueDate.toISOString(),
paidAt: record.paidAt ? record.paidAt.toISOString() : null, paidAt: record.paidAt ? record.paidAt.toISOString() : null,
createdAt: record.createdAt.toISOString(), createdAt: record.createdAt.toISOString(),

View File

@@ -1,7 +1,22 @@
export {
buildCheckoutLink,
type CheckoutLinkDeps,
type CheckoutLinkOutcome,
type ConfirmMpCheckoutDeps,
type ConfirmMpCheckoutOutcome,
checkoutExternalReference,
checkoutItemTitle,
checkoutNotificationUrl,
confirmMpCheckout,
type ExpirePreferencesDeps,
expireSupersededPreferences,
type SupersededPreference,
supersedeCheckoutsOf,
} from './checkouts';
export { export {
type ConfirmMpPaymentDeps, type ConfirmMpPaymentDeps,
type ConfirmMpPaymentOutcome, type ConfirmMpPaymentOutcome,
confirmMpPayment, confirmMpPayment,
paymentNotificationUrl, paymentNotificationUrl,
} from './confirm-mp-payment'; } from './confirm-mp-payment';
export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers'; export { CHECKOUT_BACK_PATH, type PaymentRecord, paymentDtoInclude, toPaymentDto } from './helpers';

View File

@@ -1,4 +1,5 @@
import { Hono } from 'hono'; import { Hono } from 'hono';
import autoChargeSettingsRoute from './features/auto-charge-settings/route';
import getAllRoute from './features/get-all/route'; import getAllRoute from './features/get-all/route';
import renewRoute from './features/renew/route'; import renewRoute from './features/renew/route';
import reportedRoute from './features/reported/route'; import reportedRoute from './features/reported/route';
@@ -8,6 +9,7 @@ import webhookRoute from './features/webhook/route';
const routes = new Hono(); const routes = new Hono();
routes.route('/', getAllRoute); routes.route('/', getAllRoute);
routes.route('/', autoChargeSettingsRoute);
routes.route('/', reportedRoute); routes.route('/', reportedRoute);
routes.route('/', transferDetailsRoute); routes.route('/', transferDetailsRoute);
routes.route('/', renewRoute); routes.route('/', renewRoute);

View File

@@ -40,6 +40,21 @@ export class GetStudentFees {
dueDate: true, dueDate: true,
status: true, status: true,
checkoutUrl: true, checkoutUrl: true,
periodKey: true,
checkout: {
select: {
status: true,
amount: true,
payments: {
where: { status: { in: ['PENDING', 'OVERDUE'] } },
orderBy: { createdAt: 'asc' },
select: {
group: { select: { name: true } },
attendee: { select: { person: { select: { fullName: true } } } },
},
},
},
},
reportedItems: { where: { reportedPayment: { status: 'REPORTED' } }, select: { paymentId: true } }, reportedItems: { where: { reportedPayment: { status: 'REPORTED' } }, select: { paymentId: true } },
}, },
}), }),
@@ -76,6 +91,17 @@ export class GetStudentFees {
dueDate: payment.dueDate.toISOString(), dueDate: payment.dueDate.toISOString(),
status, status,
checkoutUrl: payment.checkoutUrl, checkoutUrl: payment.checkoutUrl,
periodKey: payment.periodKey,
checkout:
payment.checkout?.status === 'OPEN' && payment.checkout.payments.length > 1
? {
total: payment.checkout.amount.toNumber(),
items: payment.checkout.payments.map((line) => ({
groupName: line.group.name,
studentName: line.attendee.person.fullName,
})),
}
: null,
}; };
}), }),
transfer: transferAlias ? { alias: transferAlias, holder: transferHolder } : null, transfer: transferAlias ? { alias: transferAlias, holder: transferHolder } : null,

View File

@@ -2,7 +2,6 @@ import type { PrismaClient } from '@generated/prisma/client';
import type { import type {
ProblemDetails, ProblemDetails,
Result, Result,
WhatsappReadiness,
WhatsappStatusDto, WhatsappStatusDto,
} from '@gruperly/shared'; } from '@gruperly/shared';
import { ok } from '@gruperly/shared'; import { ok } from '@gruperly/shared';
@@ -21,6 +20,7 @@ type GetWhatsappStatusDeps = {
const BLOCKED: WhatsappStatusDto['readiness'] = { const BLOCKED: WhatsappStatusDto['readiness'] = {
PAYMENT_REMINDER: 'blocked', PAYMENT_REMINDER: 'blocked',
REENGAGEMENT: 'blocked', REENGAGEMENT: 'blocked',
PAYMENT_LINK: 'blocked',
}; };
/** /**
@@ -80,6 +80,7 @@ export class GetWhatsappStatus {
? { ? {
PAYMENT_REMINDER: await provider.readiness(account, 'PAYMENT_REMINDER'), PAYMENT_REMINDER: await provider.readiness(account, 'PAYMENT_REMINDER'),
REENGAGEMENT: await provider.readiness(account, 'REENGAGEMENT'), REENGAGEMENT: await provider.readiness(account, 'REENGAGEMENT'),
PAYMENT_LINK: await provider.readiness(account, 'PAYMENT_LINK'),
} }
: BLOCKED; : BLOCKED;
@@ -91,7 +92,7 @@ function dto(
provider: MessagingProvider, provider: MessagingProvider,
account: WhatsappAccountRecord & { connectedAt?: Date | null } | null, account: WhatsappAccountRecord & { connectedAt?: Date | null } | null,
qrCode: string | null, qrCode: string | null,
readiness: Record<'PAYMENT_REMINDER' | 'REENGAGEMENT', WhatsappReadiness>, readiness: WhatsappStatusDto['readiness'],
): WhatsappStatusDto { ): WhatsappStatusDto {
const status = toVisibleWhatsappStatus(account, provider.id); const status = toVisibleWhatsappStatus(account, provider.id);
return { return {

View File

@@ -0,0 +1,128 @@
import type { PrismaClient } from '@generated/prisma/client';
import { countryCodeSchema } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { type DispatchItem, type DispatchTotals, dispatchForAccount, emptyTotals, sendIntervalFromEnv, sleep } from '../lib/dispatch';
import { formatAmount, formatDueDate } from '../lib/format';
import { firstNameOf } from '../lib/render-message';
import { getMessagingProvider } from '../providers';
import type { MessagingProvider } from '../providers/messaging-provider';
type SendPaymentLinksDeps = {
db?: Pick<PrismaClient, 'whatsappAccount' | 'paymentCheckout' | 'outboundMessage' | 'user'>;
provider?: MessagingProvider;
planGuard?: Pick<PlanGuard, 'hasFeature'>;
now?: Date;
intervalMs?: number;
sleep?: (ms: number) => Promise<void>;
};
/** "Yoga (Juan), Natación (Ana) y Pilates": what a combined link pays, in Spanish like the rest of the message. */
export function paymentLinkDetail(
payerId: string,
lines: { groupName: string; personId: string; fullName: string }[],
): string {
const parts = lines.map((line) =>
line.personId === payerId ? line.groupName : `${line.groupName} (${firstNameOf(line.fullName)})`,
);
if (parts.length <= 1) return parts[0] ?? '';
return `${parts.slice(0, -1).join(', ')} y ${parts.at(-1)}`;
}
/**
* Sends each payer the combined link of this month's automatic charge, right
* after it is generated. Same gates as the weekly automations: the teacher's
* WhatsApp linked with the active provider, the Pro plan and, for Kapso, the
* approved template. One message per checkout and month (`outbound_messages`).
*/
export class SendPaymentLinks {
constructor(private readonly deps: SendPaymentLinksDeps = {}) {}
async execute(ownerId: string, checkoutIds: string[]): Promise<DispatchTotals> {
if (checkoutIds.length === 0) return emptyTotals();
const providerResult = this.deps.provider ? { ok: true as const, value: this.deps.provider } : getMessagingProvider();
if (!providerResult.ok) {
logger.warn('WhatsApp is not configured; payment links not sent');
return emptyTotals();
}
const provider = providerResult.value;
const db = this.deps.db ?? prisma;
const account = await db.whatsappAccount.findFirst({
where: { ownerId, provider: provider.id, status: 'ACTIVE' },
});
if (!account) return emptyTotals();
if (!(await (this.deps.planGuard ?? new PlanGuard()).hasFeature(ownerId, 'whatsappAutomations'))) return emptyTotals();
if ((await provider.readiness(account, 'PAYMENT_LINK')) !== 'ready') return emptyTotals();
const owner = await db.user.findUnique({ where: { id: ownerId }, select: { country: true } });
const parsedCountry = countryCodeSchema.safeParse(owner?.country);
const country = parsedCountry.success ? parsedCountry.data : null;
const checkouts = await db.paymentCheckout.findMany({
where: { id: { in: checkoutIds }, ownerId, status: 'OPEN', checkoutUrl: { not: null } },
select: {
id: true,
amount: true,
currency: true,
dueDate: true,
checkoutUrl: true,
payer: { select: { id: true, fullName: true, phone: true } },
payments: {
orderBy: { createdAt: 'asc' },
select: {
groupId: true,
attendeeId: true,
periodKey: true,
group: { select: { name: true } },
attendee: { select: { person: { select: { id: true, fullName: true } } } },
},
},
},
});
const items: DispatchItem[] = [];
for (const checkout of checkouts) {
const first = checkout.payments[0];
if (!first || !checkout.checkoutUrl) continue;
items.push({
groupId: first.groupId,
attendeeId: first.attendeeId,
checkoutId: checkout.id,
// One per checkout and month: an attendee is in a single checkout a month.
periodKey: first.periodKey ?? undefined,
rawPhone: checkout.payer.phone,
message: {
kind: 'PAYMENT_LINK',
studentName: checkout.payer.fullName,
detail: paymentLinkDetail(
checkout.payer.id,
checkout.payments.map((payment) => ({
groupName: payment.group.name,
personId: payment.attendee.person.id,
fullName: payment.attendee.person.fullName,
})),
),
amount: formatAmount(Number(checkout.amount.toString()), checkout.currency, country),
dueDate: formatDueDate(checkout.dueDate, country),
paymentLink: checkout.checkoutUrl,
},
});
}
return dispatchForAccount(
{
db,
provider,
now: this.deps.now ?? new Date(),
intervalMs: this.deps.intervalMs ?? sendIntervalFromEnv(),
sleep: this.deps.sleep ?? sleep,
},
account,
country,
items,
);
}
}

View File

@@ -15,6 +15,7 @@ import { formatAmount, formatDueDate } from '../lib/format';
import { getMessagingProvider } from '../providers'; import { getMessagingProvider } from '../providers';
import type { MessagingProvider } from '../providers/messaging-provider'; import type { MessagingProvider } from '../providers/messaging-provider';
import { findEligibleAccounts } from './eligible-accounts'; import { findEligibleAccounts } from './eligible-accounts';
import { paymentLinkDetail } from './send-payment-links';
/** Only charges that are due within the coming week (or already overdue). */ /** Only charges that are due within the coming week (or already overdue). */
const DUE_HORIZON_MS = 7 * 24 * 60 * 60 * 1000; const DUE_HORIZON_MS = 7 * 24 * 60 * 60 * 1000;
@@ -32,7 +33,9 @@ type SendPaymentRemindersDeps = {
* a Checkout Pro link, in groups whose owner turned the automation on. * a Checkout Pro link, in groups whose owner turned the automation on.
* *
* One reminder per member per week even with several open charges: the oldest * One reminder per member per week even with several open charges: the oldest
* one goes in the message (the rest are in the same Cobros screen anyway). * one goes in the message (the rest are in the same Cobros screen anyway). A
* fee of a combined link is reminded once per link, to whoever pays it, with
* the link's total: an adult with two kids gets one message, not two.
*/ */
export class SendPaymentReminders { export class SendPaymentReminders {
constructor(private readonly deps: SendPaymentRemindersDeps = {}) {} constructor(private readonly deps: SendPaymentRemindersDeps = {}) {}
@@ -52,6 +55,7 @@ export class SendPaymentReminders {
for (const { account, country, groups } of accounts) { for (const { account, country, groups } of accounts) {
const items: DispatchItem[] = []; const items: DispatchItem[] = [];
const seenCheckouts = new Set<string>();
for (const group of groups) { for (const group of groups) {
const payments = await db.payment.findMany({ const payments = await db.payment.findMany({
@@ -70,6 +74,21 @@ export class SendPaymentReminders {
currency: true, currency: true,
dueDate: true, dueDate: true,
checkoutUrl: true, checkoutUrl: true,
checkout: {
select: {
id: true,
status: true,
amount: true,
payer: { select: { id: true, fullName: true, phone: true } },
payments: {
orderBy: { createdAt: 'asc' },
select: {
group: { select: { name: true } },
attendee: { select: { person: { select: { id: true, fullName: true } } } },
},
},
},
},
attendee: { attendee: {
select: { id: true, person: { select: { fullName: true, phone: true, ...guardianSelect } } }, select: { id: true, person: { select: { fullName: true, phone: true, ...guardianSelect } } },
}, },
@@ -81,6 +100,34 @@ export class SendPaymentReminders {
for (const payment of payments) { for (const payment of payments) {
if (seen.has(payment.attendee.id) || !payment.checkoutUrl) continue; if (seen.has(payment.attendee.id) || !payment.checkoutUrl) continue;
seen.add(payment.attendee.id); seen.add(payment.attendee.id);
const checkout = payment.checkout?.status === 'OPEN' ? payment.checkout : null;
if (checkout) {
if (seenCheckouts.has(checkout.id)) continue;
seenCheckouts.add(checkout.id);
items.push({
groupId: group.id,
attendeeId: payment.attendee.id,
paymentId: payment.id,
checkoutId: checkout.id,
rawPhone: checkout.payer.phone,
message: {
kind: 'PAYMENT_REMINDER',
studentName: checkout.payer.fullName,
groupName: paymentLinkDetail(
checkout.payer.id,
checkout.payments.map((line) => ({
groupName: line.group.name,
personId: line.attendee.person.id,
fullName: line.attendee.person.fullName,
})),
),
amount: formatAmount(Number(checkout.amount.toString()), payment.currency, country),
dueDate: formatDueDate(payment.dueDate, country),
paymentLink: payment.checkoutUrl,
},
});
continue;
}
items.push({ items.push({
groupId: group.id, groupId: group.id,
attendeeId: payment.attendee.id, attendeeId: payment.attendee.id,

View File

@@ -3,6 +3,7 @@ import prisma from '@/lib/prisma';
import { logger } from '@/logger'; import { logger } from '@/logger';
import { KapsoProvider } from '../providers'; import { KapsoProvider } from '../providers';
import { getKapsoConfig } from '../providers/kapso/config'; import { getKapsoConfig } from '../providers/kapso/config';
import { KAPSO_TEMPLATES } from '../providers/kapso/templates';
type SyncKapsoTemplatesDeps = { type SyncKapsoTemplatesDeps = {
db?: Pick<PrismaClient, 'whatsappAccount' | 'whatsappTemplate'>; db?: Pick<PrismaClient, 'whatsappAccount' | 'whatsappTemplate'>;
@@ -12,7 +13,7 @@ type SyncKapsoTemplatesDeps = {
export type SyncKapsoTemplatesResult = { checked: number; updated: number; failed: number }; export type SyncKapsoTemplatesResult = { checked: number; updated: number; failed: number };
/** How many templates each account should have (one per message kind). */ /** How many templates each account should have (one per message kind). */
const EXPECTED_TEMPLATES = 2; const EXPECTED_TEMPLATES = Object.keys(KAPSO_TEMPLATES).length;
/** /**
* Meta reviews templates on its own schedule (up to ~24h) and Kapso documents * Meta reviews templates on its own schedule (up to ~24h) and Kapso documents

View File

@@ -16,6 +16,10 @@ export type DispatchItem = {
groupId: string; groupId: string;
attendeeId: string; attendeeId: string;
paymentId?: string | null; paymentId?: string | null;
/** Combined link the message is about (PAYMENT_LINK). */
checkoutId?: string | null;
/** Overrides the ISO week: the month for the monthly payment link. */
periodKey?: string;
/** The member's phone, or their guardian's, as stored. */ /** The member's phone, or their guardian's, as stored. */
rawPhone: string | null; rawPhone: string | null;
message: WhatsappMessage; message: WhatsappMessage;
@@ -74,7 +78,7 @@ export async function dispatchForAccount(
items: DispatchItem[], items: DispatchItem[],
): Promise<DispatchTotals> { ): Promise<DispatchTotals> {
const totals = emptyTotals(); const totals = emptyTotals();
const periodKey = isoWeekKey(deps.now); const weekKey = isoWeekKey(deps.now);
let sentBefore = false; let sentBefore = false;
for (const item of items) { for (const item of items) {
@@ -83,9 +87,10 @@ export async function dispatchForAccount(
groupId: item.groupId, groupId: item.groupId,
attendeeId: item.attendeeId, attendeeId: item.attendeeId,
paymentId: item.paymentId ?? null, paymentId: item.paymentId ?? null,
checkoutId: item.checkoutId ?? null,
kind: item.message.kind as WhatsappMessageKind, kind: item.message.kind as WhatsappMessageKind,
provider: deps.provider.id, provider: deps.provider.id,
periodKey, periodKey: item.periodKey ?? weekKey,
}; };
const e164 = item.rawPhone ? toWhatsappE164(item.rawPhone, country) : null; const e164 = item.rawPhone ? toWhatsappE164(item.rawPhone, country) : null;
@@ -152,6 +157,7 @@ type RecordInput = {
groupId: string; groupId: string;
attendeeId: string; attendeeId: string;
paymentId: string | null; paymentId: string | null;
checkoutId: string | null;
kind: WhatsappMessageKind; kind: WhatsappMessageKind;
provider: MessagingProvider['id']; provider: MessagingProvider['id'];
periodKey: string; periodKey: string;

View File

@@ -18,6 +18,12 @@ export function renderMessage(message: WhatsappMessage): string {
`por ${message.amount}, con vencimiento el ${message.dueDate}. ` + `por ${message.amount}, con vencimiento el ${message.dueDate}. ` +
`Podés pagarlo desde este link: ${message.paymentLink}` `Podés pagarlo desde este link: ${message.paymentLink}`
); );
case 'PAYMENT_LINK':
return (
`¡Hola ${firstName}! Ya está disponible el pago de este mes: ${message.detail}, ` +
`por ${message.amount}, con vencimiento el ${message.dueDate}. ` +
`Podés pagarlo desde este link: ${message.paymentLink}`
);
case 'REENGAGEMENT': case 'REENGAGEMENT':
// Same copy the teacher sends by hand from "Alumnos en riesgo". // Same copy the teacher sends by hand from "Alumnos en riesgo".
return ( return (

View File

@@ -58,6 +58,41 @@ export const KAPSO_TEMPLATES: Record<WhatsappMessageKind, TemplateSpec> = {
] ]
: [], : [],
}, },
PAYMENT_LINK: {
definition: {
name: 'gruperly_payment_link',
language: TEMPLATE_LANGUAGE,
category: 'UTILITY',
parameter_format: 'NAMED',
components: [
{
type: 'BODY',
text:
'¡Hola {{student_name}}! Ya está disponible el pago de este mes: {{detail}}, por {{amount}}, ' +
'con vencimiento el {{due_date}}. Podés pagarlo desde este link: {{payment_link}} ¡Gracias!',
example: {
body_text_named_params: [
{ param_name: 'student_name', example: 'Laura' },
{ param_name: 'detail', example: 'Natación (Juan) y Yoga (Ana)' },
{ param_name: 'amount', example: '$ 50.000' },
{ param_name: 'due_date', example: '10/12' },
{ param_name: 'payment_link', example: 'https://mpago.la/2xYz123' },
],
},
},
],
},
parameters: (message) =>
message.kind === 'PAYMENT_LINK'
? [
{ name: 'student_name', text: firstNameOf(message.studentName) },
{ name: 'detail', text: message.detail },
{ name: 'amount', text: message.amount },
{ name: 'due_date', text: message.dueDate },
{ name: 'payment_link', text: message.paymentLink },
]
: [],
},
REENGAGEMENT: { REENGAGEMENT: {
definition: { definition: {
name: 'gruperly_reengagement', name: 'gruperly_reengagement',
@@ -80,10 +115,13 @@ export const KAPSO_TEMPLATES: Record<WhatsappMessageKind, TemplateSpec> = {
}, },
], ],
}, },
parameters: (message) => [ parameters: (message) =>
{ name: 'student_name', text: firstNameOf(message.studentName) }, message.kind === 'REENGAGEMENT'
{ name: 'group_name', text: message.groupName }, ? [
], { name: 'student_name', text: firstNameOf(message.studentName) },
{ name: 'group_name', text: message.groupName },
]
: [],
}, },
}; };

View File

@@ -40,6 +40,16 @@ export type WhatsappMessage =
kind: 'REENGAGEMENT'; kind: 'REENGAGEMENT';
studentName: string; studentName: string;
groupName: string; groupName: string;
}
| {
/** The monthly combined link, to whoever pays (the adult for kids). */
kind: 'PAYMENT_LINK';
studentName: string;
/** What it pays, e.g. "Yoga (Juan) y Natación (Ana)". */
detail: string;
amount: string;
dueDate: string;
paymentLink: string;
}; };
export type StartConnectionContext = { export type StartConnectionContext = {

View File

@@ -89,6 +89,7 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
guardianPhone: '5598765432', guardianPhone: '5598765432',
guardianEmail: null, guardianEmail: null,
notes: null, notes: null,
payWithMercadoPago: true,
notifyToken: 'token-1', notifyToken: 'token-1',
createdAt: '2026-08-01T10:00:00.000Z', createdAt: '2026-08-01T10:00:00.000Z',
updatedAt: '2026-08-01T10:00:00.000Z', updatedAt: '2026-08-01T10:00:00.000Z',

View File

@@ -25,6 +25,7 @@ const personSelect = {
email: true, email: true,
phone: true, phone: true,
notes: true, notes: true,
payWithMercadoPago: true,
guardians: { guardians: {
take: 1, take: 1,
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
@@ -82,6 +83,7 @@ describe('attendees routes', () => {
guardianPhone: '1199990000', guardianPhone: '1199990000',
guardianEmail: null, guardianEmail: null,
notes: person.notes, notes: person.notes,
payWithMercadoPago: true,
createdAt: attendeeRow.createdAt.toISOString(), createdAt: attendeeRow.createdAt.toISOString(),
updatedAt: attendeeRow.updatedAt.toISOString(), updatedAt: attendeeRow.updatedAt.toISOString(),
// The query comes most recent first; the row shows them // The query comes most recent first; the row shows them

View File

@@ -0,0 +1,290 @@
import { describe, expect, it, mock } from 'bun:test';
import { GenerateMonthlyCharges } from '@/modules/payments/features/auto-charge/generate-monthly-charges';
import { isAutoChargeDue, nextAutoChargeDate } from '@/modules/payments/lib/auto-charge-schedule';
import { paymentLinkDetail } from '@/modules/whatsapp/jobs/send-payment-links';
const ownerId = 'owner-1';
const BA = 'America/Argentina/Buenos_Aires';
// 2026-12-05 12:00 in Buenos Aires (UTC-3).
const NOW = new Date('2026-12-05T15:00:00.000Z');
type PersonRow = { id: string; payWithMercadoPago: boolean; guardian?: { id: string } };
type AttendeeRow = { id: string; groupId: string; person: PersonRow };
const decimal = (value: number) => ({ toString: () => String(value) });
/** In-memory stand-in for the Prisma calls the generator makes. */
function fakeDb(input: {
groups: { id: string; name: string; price: number }[];
attendees: AttendeeRow[];
people: Record<string, string>;
settings?: { dueInDays: number; sendWhatsapp: boolean } | null;
runExists?: boolean;
}) {
const payments: Record<string, unknown>[] = [];
const checkouts: Record<string, unknown>[] = [];
const runs: Record<string, unknown>[] = [];
let seq = 0;
const groupName = (id: string) => input.groups.find((group) => group.id === id)?.name ?? '';
const attendeeById = (id: string) => input.attendees.find((attendee) => attendee.id === id) as AttendeeRow;
const client = {
payments,
checkouts,
runs,
user: {
findUnique: mock(async () => ({
country: 'AR',
autoCharge:
input.settings === null
? null
: { enabled: true, chargeDay: 5, dueInDays: 10, sendWhatsapp: false, ...input.settings },
})),
},
paymentRun: {
create: mock(async ({ data }: { data: Record<string, unknown> }) => {
if (input.runExists) throw Object.assign(new Error('unique'), { code: 'P2002' });
const run = { id: `run-${++seq}`, ...data };
runs.push(run);
return run;
}),
update: mock(async ({ data }: { data: Record<string, unknown> }) => Object.assign(runs[0] ?? {}, data)),
},
group: {
findMany: mock(async () => input.groups.map((group) => ({ id: group.id, price: decimal(group.price) }))),
},
attendee: {
findMany: mock(async () =>
input.attendees.map((attendee) => ({
id: attendee.id,
groupId: attendee.groupId,
person: {
id: attendee.person.id,
payWithMercadoPago: attendee.person.payWithMercadoPago,
guardians: attendee.person.guardian
? [{ guardian: { id: attendee.person.guardian.id, fullName: '', phone: null, email: null } }]
: [],
},
})),
),
},
paymentCheckout: {
create: mock(async ({ data }: { data: Record<string, unknown> }) => {
const checkout = { id: `chk-${++seq}`, status: 'OPEN', ...data };
checkouts.push(checkout);
return { id: checkout.id };
}),
findUnique: mock(async ({ where }: { where: { id: string } }) => {
const checkout = checkouts.find((row) => row.id === where.id);
if (!checkout) return null;
return {
...checkout,
payments: payments
.filter((payment) => payment.checkoutId === checkout.id)
.map((payment) => ({
id: payment.id,
amount: payment.amount,
group: { name: groupName(payment.groupId as string) },
attendee: { person: { fullName: input.people[attendeeById(payment.attendeeId as string).person.id] } },
})),
};
}),
update: mock(async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) =>
Object.assign(checkouts.find((row) => row.id === where.id) ?? {}, data),
),
},
payment: {
create: mock(async ({ data }: { data: Record<string, unknown> }) => {
const payment = { id: `pay-${++seq}`, ...data };
payments.push(payment);
return payment;
}),
updateMany: mock(async ({ where, data }: { where: { id: { in: string[] } }; data: Record<string, unknown> }) => {
for (const payment of payments) if (where.id.in.includes(payment.id as string)) Object.assign(payment, data);
return { count: where.id.in.length };
}),
},
$transaction: mock(async (callback: (tx: unknown) => Promise<unknown>) => callback(client)),
};
return client;
}
const okToken = mock(async () => ({ ok: true as const, value: { accountId: 'acc', accessToken: 'token', expiresAt: new Date() } }));
const allowAll = { hasFeature: mock(async () => true) };
function generator(db: ReturnType<typeof fakeDb>, overrides: Record<string, unknown> = {}) {
let preference = 0;
const createPreference = mock(async () => ({ id: `pref-${++preference}`, initPoint: `https://mp.link/${preference}`, sandboxInitPoint: null }));
const sendLinks = mock(async (_owner: string, ids: string[]) => ids.length);
const instance = new GenerateMonthlyCharges({
db: db as never,
getToken: okToken as never,
createPreference,
planGuard: allowAll,
sendLinks,
webOrigin: 'https://app',
apiOrigin: 'https://api',
now: NOW,
...overrides,
});
return { instance, createPreference, sendLinks };
}
// A mother (guardian g-1) with two kids in two groups; she also takes Pilates herself.
// An adult (p-4) alone. A kid (p-5) of another adult (g-2) who pays by transfer.
const family = {
groups: [
{ id: 'swim', name: 'Natación', price: 20000 },
{ id: 'yoga', name: 'Yoga', price: 15000 },
{ id: 'pilates', name: 'Pilates', price: 10000 },
],
people: { 'p-1': 'Juan Gómez', 'p-2': 'Ana Gómez', 'g-1': 'Laura Gómez', 'p-4': 'Carlos Ruiz', 'p-5': 'Tomás Díaz' },
attendees: [
{ id: 'a-1', groupId: 'swim', person: { id: 'p-1', payWithMercadoPago: true, guardian: { id: 'g-1' } } },
{ id: 'a-2', groupId: 'yoga', person: { id: 'p-2', payWithMercadoPago: true, guardian: { id: 'g-1' } } },
{ id: 'a-3', groupId: 'pilates', person: { id: 'g-1', payWithMercadoPago: true } },
{ id: 'a-4', groupId: 'yoga', person: { id: 'p-4', payWithMercadoPago: true } },
{ id: 'a-5', groupId: 'swim', person: { id: 'p-5', payWithMercadoPago: false, guardian: { id: 'g-2' } } },
],
};
describe('automatic monthly charges', () => {
it('bundles the fees of each payer into one Mercado Pago link with the total', async () => {
const db = fakeDb(family);
const { instance, createPreference } = generator(db);
const result = await instance.execute(ownerId);
expect(result).toEqual({ outcome: 'done', fees: 5, checkouts: 2, linked: 2, failed: 0, sent: 0 });
expect(db.payments).toHaveLength(5);
expect(db.payments.every((payment) => payment.periodKey === '2026-12')).toBe(true);
// Due 10 days after the local charge date.
expect(db.payments[0]?.dueDate).toEqual(new Date('2026-12-15T12:00:00.000Z'));
const [mother, adult] = db.checkouts;
expect(mother).toMatchObject({ payerPersonId: 'g-1', amount: 45000, currency: 'ARS', checkoutUrl: 'https://mp.link/1' });
expect(adult).toMatchObject({ payerPersonId: 'p-4', amount: 15000 });
expect(createPreference).toHaveBeenCalledWith('token', {
title: 'Natación · Juan Gómez',
unitPrice: 45000,
items: [
{ title: 'Natación · Juan Gómez', unitPrice: 20000 },
{ title: 'Yoga · Ana Gómez', unitPrice: 15000 },
{ title: 'Pilates · Laura Gómez', unitPrice: 10000 },
],
currencyId: 'ARS',
externalReference: `chk_${mother?.id}`,
backUrl: 'https://app/student/payments',
notificationUrl: `https://api/api/v1/payments/webhooks/mp/checkout/${mother?.id}?source_news=webhooks`,
});
// Each fee carries the shared link.
const motherFees = db.payments.filter((payment) => payment.checkoutId === mother?.id);
expect(motherFees.map((payment) => payment.checkoutUrl)).toEqual(Array(3).fill('https://mp.link/1'));
});
it('creates the fee without a link for someone who pays by transfer', async () => {
const db = fakeDb(family);
await generator(db).instance.execute(ownerId);
const transfer = db.payments.find((payment) => payment.attendeeId === 'a-5');
expect(transfer).toMatchObject({ status: 'PENDING', checkoutId: null, periodKey: '2026-12' });
expect(transfer?.checkoutUrl).toBeUndefined();
// The other adult has nobody paying with Mercado Pago: no checkout for them.
expect(db.checkouts.some((checkout) => checkout.payerPersonId === 'g-2')).toBe(false);
});
it('sends the generated links by WhatsApp only when the teacher turned it on', async () => {
const off = fakeDb(family);
const quiet = generator(off);
await quiet.instance.execute(ownerId);
expect(quiet.sendLinks).not.toHaveBeenCalled();
const on = fakeDb({ ...family, settings: { dueInDays: 10, sendWhatsapp: true } });
const loud = generator(on);
const result = await loud.instance.execute(ownerId);
expect(loud.sendLinks).toHaveBeenCalledWith(ownerId, on.checkouts.map((checkout) => checkout.id));
expect(result).toMatchObject({ outcome: 'done', sent: 2 });
});
it('is a no-op the second time in the same month', async () => {
const db = fakeDb({ ...family, runExists: true });
const { instance, createPreference } = generator(db);
expect(await instance.execute(ownerId)).toEqual({ outcome: 'already_ran' });
expect(db.payments).toHaveLength(0);
expect(createPreference).not.toHaveBeenCalled();
});
it('skips the month when Mercado Pago is not linked', async () => {
const db = fakeDb(family);
const getToken = mock(async () => ({ ok: false as const, error: { status: 409, code: 'mp_not_connected' } }));
const result = await generator(db, { getToken }).instance.execute(ownerId);
expect(result).toEqual({ outcome: 'skipped', reason: 'mp_not_connected' });
expect(db.runs[0]).toMatchObject({ status: 'SKIPPED', skipReason: 'mp_not_connected' });
expect(db.payments).toHaveLength(0);
});
it('skips the month without the Mercado Pago charges plan feature', async () => {
const db = fakeDb(family);
const result = await generator(db, { planGuard: { hasFeature: mock(async () => false) } }).instance.execute(ownerId);
expect(result).toEqual({ outcome: 'skipped', reason: 'plan_feature_required' });
});
it('keeps going when one link fails: its checkout stays without a link', async () => {
const db = fakeDb(family);
let calls = 0;
const createPreference = mock(async () => {
calls += 1;
if (calls === 1) throw new (await import('@/modules/mp/lib/mp-oauth')).MpApiError(500, null);
return { id: 'pref-2', initPoint: 'https://mp.link/2', sandboxInitPoint: null };
});
const result = await generator(db, { createPreference }).instance.execute(ownerId);
expect(result).toMatchObject({ outcome: 'done', checkouts: 2, linked: 1, failed: 1 });
expect(db.checkouts[0]?.checkoutUrl).toBeUndefined();
expect(db.checkouts[1]?.checkoutUrl).toBe('https://mp.link/2');
});
});
describe('auto charge schedule', () => {
const settings = { chargeDay: 5, enabledAt: new Date('2026-11-01T12:00:00.000Z') };
it('is due from 9 a.m. local on the day, and for a few days after', () => {
expect(isAutoChargeDue(settings, new Date('2026-12-05T11:00:00.000Z'), BA)).toBe(false); // 8 a.m.
expect(isAutoChargeDue(settings, new Date('2026-12-05T12:00:00.000Z'), BA)).toBe(true); // 9 a.m.
expect(isAutoChargeDue(settings, new Date('2026-12-08T02:00:00.000Z'), BA)).toBe(true); // 7th, 11 p.m.
expect(isAutoChargeDue(settings, new Date('2026-12-09T12:00:00.000Z'), BA)).toBe(false);
expect(isAutoChargeDue(settings, new Date('2026-12-04T12:00:00.000Z'), BA)).toBe(false);
});
it('uses the teacher clock: 1 a.m. UTC on the 6th is still the 5th in Buenos Aires', () => {
const lateEnabled = { chargeDay: 6, enabledAt: null };
expect(isAutoChargeDue(lateEnabled, new Date('2026-12-06T01:00:00.000Z'), BA)).toBe(false);
});
it('does not bill a month whose day had passed when it was turned on', () => {
const late = { chargeDay: 5, enabledAt: new Date('2026-12-06T12:00:00.000Z') };
expect(isAutoChargeDue(late, new Date('2026-12-07T12:00:00.000Z'), BA)).toBe(false);
expect(nextAutoChargeDate(late, new Date('2026-12-07T12:00:00.000Z'), BA, false)).toBe('2027-01-05');
});
it('tells the next run date', () => {
expect(nextAutoChargeDate(settings, new Date('2026-12-02T12:00:00.000Z'), BA, false)).toBe('2026-12-05');
expect(nextAutoChargeDate(settings, new Date('2026-12-06T12:00:00.000Z'), BA, true)).toBe('2027-01-05');
expect(nextAutoChargeDate(settings, new Date('2026-12-20T12:00:00.000Z'), BA, false)).toBe('2027-01-05');
});
});
describe('payment link detail', () => {
it('names each kid and leaves the payer own group bare', () => {
expect(
paymentLinkDetail('g-1', [
{ groupName: 'Natación', personId: 'p-1', fullName: 'Juan Gómez' },
{ groupName: 'Yoga', personId: 'p-2', fullName: 'Ana Gómez' },
{ groupName: 'Pilates', personId: 'g-1', fullName: 'Laura Gómez' },
]),
).toBe('Natación (Juan), Yoga (Ana) y Pilates');
expect(paymentLinkDetail('p-4', [{ groupName: 'Yoga', personId: 'p-4', fullName: 'Carlos Ruiz' }])).toBe('Yoga');
});
});

View File

@@ -0,0 +1,239 @@
import { describe, expect, it, mock } from 'bun:test';
import { ok } from '@gruperly/shared';
import { AutoChargeSettingsUseCase } from '@/modules/payments/features/auto-charge-settings/use-case';
import { HandleMpCheckoutNotification } from '@/modules/payments/features/webhook/use-case';
import { buildCheckoutLink, supersedeCheckoutsOf } from '@/modules/payments/lib/checkouts';
import { SendPaymentLinks } from '@/modules/whatsapp/jobs/send-payment-links';
import type { MessagingProvider } from '@/modules/whatsapp/providers/messaging-provider';
const ownerId = 'owner-1';
describe('combined links (checkouts)', () => {
it('supersedes the open link of a fee paid some other way and drops the shared link', async () => {
const tx = {
paymentCheckout: {
findMany: mock(async () => [{ id: 'chk-1', ownerId, mpPreferenceId: 'pref-1' }]),
updateMany: mock(async () => ({ count: 1 })),
},
payment: { updateMany: mock(async () => ({ count: 3 })) },
};
const expired = await supersedeCheckoutsOf(tx as never, ['pay-1']);
expect(expired).toEqual([{ ownerId, mpPreferenceId: 'pref-1' }]);
expect(tx.paymentCheckout.updateMany).toHaveBeenCalledWith({
where: { id: { in: ['chk-1'] }, status: 'OPEN' },
data: { status: 'SUPERSEDED' },
});
expect(tx.payment.updateMany).toHaveBeenCalledWith({
where: { checkoutId: { in: ['chk-1'] } },
data: { checkoutUrl: null },
});
});
it('does nothing for fees outside a combined link', async () => {
const tx = {
paymentCheckout: { findMany: mock(async () => []), updateMany: mock() },
payment: { updateMany: mock() },
};
expect(await supersedeCheckoutsOf(tx as never, ['pay-1'])).toEqual([]);
expect(tx.paymentCheckout.updateMany).not.toHaveBeenCalled();
});
it('rebuilds the link only from the fees still unpaid', async () => {
const db = {
paymentCheckout: {
findUnique: mock(async () => ({
id: 'chk-1',
ownerId,
currency: 'ARS',
status: 'OPEN',
payments: [
{
id: 'pay-2',
amount: { toString: () => '15000' },
group: { name: 'Yoga' },
attendee: { person: { fullName: 'Ana' } },
},
],
})),
update: mock(async () => ({})),
},
payment: { updateMany: mock(async () => ({ count: 1 })) },
};
const createPreference = mock(async () => ({ id: 'pref-9', initPoint: 'https://mp.link/9', sandboxInitPoint: null }));
const outcome = await buildCheckoutLink(
db as never,
'chk-1',
{ webOrigin: 'https://app', apiOrigin: 'https://api', accessToken: 'token' },
{ createPreference },
);
expect(outcome).toEqual({ ok: true, checkoutUrl: 'https://mp.link/9' });
expect(db.paymentCheckout.update).toHaveBeenCalledWith({
where: { id: 'chk-1' },
data: { checkoutUrl: 'https://mp.link/9', mpPreferenceId: 'pref-9', amount: 15000 },
});
expect(db.payment.updateMany).toHaveBeenCalledWith({
where: { id: { in: ['pay-2'] } },
data: { checkoutUrl: 'https://mp.link/9' },
});
});
it('ignores a notification for an unknown or already paid link', async () => {
const db = { paymentCheckout: { findFirst: mock(async () => null) }, $transaction: mock() };
const result = await new HandleMpCheckoutNotification({ db: db as never }).execute('chk-x');
expect(result).toEqual(ok({ outcome: 'ignored' }));
});
});
describe('auto charge settings', () => {
function settingsDb(current: Record<string, unknown> | null = null) {
return {
autoChargeSettings: {
findUnique: mock(async () => current),
upsert: mock(async () => ({})),
},
paymentRun: { findFirst: mock(async () => null) },
user: { findUnique: mock(async () => ({ country: 'AR' })) },
};
}
it('starts off with the defaults', async () => {
const result = await new AutoChargeSettingsUseCase({ db: settingsDb() as never }).get(ownerId);
expect(result).toEqual(
ok({ enabled: false, chargeDay: 1, dueInDays: 10, sendWhatsapp: false, nextRunDate: null, lastRun: null }),
);
});
it('records when it is turned on', async () => {
const db = settingsDb();
const now = new Date('2026-12-02T12:00:00.000Z');
await new AutoChargeSettingsUseCase({ db: db as never, planGuard: { requireFeature: mock(async () => ok(undefined)) }, now }).update(
ownerId,
{ enabled: true, chargeDay: 5 },
);
expect(db.autoChargeSettings.upsert).toHaveBeenCalledWith({
where: { ownerId },
create: { ownerId, enabled: true, chargeDay: 5, enabledAt: now },
update: { enabled: true, chargeDay: 5, enabledAt: now },
});
});
it('asks the plan for WhatsApp automations before sending links', async () => {
const problem = { type: 'x', title: 'Payment Required', status: 402, detail: 'x', code: 'plan_feature_required' };
const requireFeature = mock(async (_owner: string, feature: string) =>
feature === 'whatsappAutomations' ? { ok: false as const, error: problem } : ok(undefined),
);
const db = settingsDb();
const result = await new AutoChargeSettingsUseCase({ db: db as never, planGuard: { requireFeature } }).update(ownerId, {
sendWhatsapp: true,
});
expect(result).toEqual({ ok: false, error: problem });
expect(db.autoChargeSettings.upsert).not.toHaveBeenCalled();
});
it('can always be turned off', async () => {
const requireFeature = mock();
const db = settingsDb({ enabled: true, chargeDay: 5, dueInDays: 10, sendWhatsapp: true, enabledAt: null });
await new AutoChargeSettingsUseCase({ db: db as never, planGuard: { requireFeature } }).update(ownerId, {
enabled: false,
sendWhatsapp: false,
});
expect(requireFeature).not.toHaveBeenCalled();
});
});
describe('sending the monthly links by WhatsApp', () => {
const account = { id: 'wa-1', ownerId, provider: 'OPENWA', status: 'ACTIVE', externalId: 's', displayPhoneNumber: null, providerData: null };
function provider(overrides: Partial<MessagingProvider> = {}): MessagingProvider {
return {
id: 'OPENWA',
readiness: mock(async () => 'ready' as const),
resolveRecipient: mock(async (_account, e164: string) => ({ ok: true as const, to: `${e164.slice(1)}@c.us` })),
send: mock(async () => ({ ok: true as const, providerMessageId: 'wamid-1' })),
...overrides,
} as unknown as MessagingProvider;
}
function linksDb() {
return {
whatsappAccount: { findFirst: mock(async () => account) },
user: { findUnique: mock(async () => ({ country: 'AR' })) },
paymentCheckout: {
findMany: mock(async () => [
{
id: 'chk-1',
amount: { toString: () => '35000' },
currency: 'ARS',
dueDate: new Date('2026-12-15T12:00:00.000Z'),
checkoutUrl: 'https://mp.link/1',
payer: { id: 'g-1', fullName: 'Laura Gómez', phone: '1123456789' },
payments: [
{ groupId: 'swim', attendeeId: 'a-1', periodKey: '2026-12', group: { name: 'Natación' }, attendee: { person: { id: 'p-1', fullName: 'Juan Gómez' } } },
{ groupId: 'yoga', attendeeId: 'a-2', periodKey: '2026-12', group: { name: 'Yoga' }, attendee: { person: { id: 'p-2', fullName: 'Ana Gómez' } } },
],
},
]),
},
outboundMessage: {
create: mock(async () => ({ id: 'msg-1' })),
update: mock(async () => ({})),
delete: mock(),
},
};
}
it('sends one message to the payer, keyed by the month, with what it pays', async () => {
const db = linksDb();
const fake = provider();
const totals = await new SendPaymentLinks({
db: db as never,
provider: fake,
planGuard: { hasFeature: mock(async () => true) },
intervalMs: 0,
}).execute(ownerId, ['chk-1']);
expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 });
expect(db.outboundMessage.create).toHaveBeenCalledWith({
data: expect.objectContaining({
attendeeId: 'a-1',
checkoutId: 'chk-1',
kind: 'PAYMENT_LINK',
periodKey: '2026-12',
toPhone: '+5491123456789',
}),
select: { id: true },
});
const [, , message] = (fake.send as ReturnType<typeof mock>).mock.calls[0] ?? [];
expect(message).toMatchObject({
kind: 'PAYMENT_LINK',
studentName: 'Laura Gómez',
detail: 'Natación (Juan) y Yoga (Ana)',
paymentLink: 'https://mp.link/1',
});
});
it('sends nothing while the template is not approved', async () => {
const db = linksDb();
const totals = await new SendPaymentLinks({
db: db as never,
provider: provider({ readiness: mock(async () => 'pending' as const) }),
planGuard: { hasFeature: mock(async () => true) },
}).execute(ownerId, ['chk-1']);
expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 });
expect(db.outboundMessage.create).not.toHaveBeenCalled();
});
it('sends nothing without WhatsApp automations in the plan', async () => {
const db = linksDb();
await new SendPaymentLinks({
db: db as never,
provider: provider(),
planGuard: { hasFeature: mock(async () => false) },
}).execute(ownerId, ['chk-1']);
expect(db.outboundMessage.create).not.toHaveBeenCalled();
});
});

View File

@@ -1,10 +1,19 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
const tx = {
paymentCheckout: { update: mock() },
payment: { updateMany: mock() },
};
const db = { const db = {
payment: { payment: {
findMany: mock(), findMany: mock(),
update: mock(), update: mock(),
}, },
paymentCheckout: {
findMany: mock(async () => [] as unknown[]),
},
$transaction: mock(async (callback: (client: typeof tx) => Promise<unknown>) => callback(tx)),
}; };
mock.module('@/lib/prisma', () => ({ mock.module('@/lib/prisma', () => ({
@@ -121,9 +130,54 @@ describe('reconcile payments', () => {
where: { where: {
status: 'PENDING', status: 'PENDING',
checkoutUrl: { not: null }, checkoutUrl: { not: null },
checkoutId: null,
createdAt: { lt: new Date('2026-10-01T11:55:00.000Z') }, createdAt: { lt: new Date('2026-10-01T11:55:00.000Z') },
}, },
}), }),
); );
}); });
it('marks every unpaid fee of an approved combined link as PAID', async () => {
prisma.payment.findMany.mockResolvedValue([]);
db.paymentCheckout.findMany.mockResolvedValueOnce([{ id: 'chk-1', ownerId }]);
const getToken = mock(async () => okAccount());
const search = mock(async () => ({
id: '777',
status: 'approved',
externalReference: 'chk_chk-1',
liveMode: true,
dateApproved: '2026-10-01T12:30:00.000Z',
}));
const result = await new ReconcilePayments({ getToken, search }).execute();
expect(result).toEqual({ paid: 1, skipped: 0, failed: 0 });
expect(search).toHaveBeenCalledWith('token-1', 'chk_chk-1');
const paidAt = new Date('2026-10-01T12:30:00.000Z');
expect(tx.paymentCheckout.update).toHaveBeenCalledWith({
where: { id: 'chk-1' },
data: { status: 'PAID', mpPaymentId: '777', paidAt },
});
expect(tx.payment.updateMany).toHaveBeenCalledWith({
where: { checkoutId: 'chk-1', status: { in: ['PENDING', 'OVERDUE'] } },
data: { status: 'PAID', mpPaymentId: '777', paidAt },
});
});
it('ignores a payment of a combined link whose reference is not the checkout', async () => {
prisma.payment.findMany.mockResolvedValue([]);
db.paymentCheckout.findMany.mockResolvedValueOnce([{ id: 'chk-1', ownerId }]);
const search = mock(async () => ({
id: '777',
status: 'approved',
externalReference: 'chk-1',
liveMode: true,
dateApproved: null,
}));
const result = await new ReconcilePayments({ getToken: mock(async () => okAccount()), search }).execute();
expect(result).toEqual({ paid: 0, skipped: 0, failed: 0 });
expect(tx.payment.updateMany).not.toHaveBeenCalled();
});
}); });

View File

@@ -106,10 +106,11 @@ describe('renew payment link', () => {
}); });
expect(prisma.payment.update).toHaveBeenCalledWith({ expect(prisma.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' }, where: { id: 'pay-1' },
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new' }, data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new', checkoutId: null },
include: { include: {
attendee: { select: { person: { select: { fullName: true } } } }, attendee: { select: { person: { select: { fullName: true } } } },
group: { select: { name: true, price: true } }, group: { select: { name: true, price: true } },
checkout: { select: { _count: { select: { payments: true } } } },
}, },
}); });
}); });

View File

@@ -75,6 +75,9 @@ describe('payments routes', () => {
status: 'PENDING', status: 'PENDING',
description: 'Mensualidad de Septiembre', description: 'Mensualidad de Septiembre',
checkoutUrl: payment.checkoutUrl, checkoutUrl: payment.checkoutUrl,
checkoutId: null,
checkoutItemCount: null,
periodKey: null,
dueDate: payment.dueDate.toISOString(), dueDate: payment.dueDate.toISOString(),
paidAt: null, paidAt: null,
createdAt: payment.createdAt.toISOString(), createdAt: payment.createdAt.toISOString(),
@@ -94,6 +97,7 @@ describe('payments routes', () => {
include: { include: {
group: { select: { name: true, price: true } }, group: { select: { name: true, price: true } },
attendee: { select: { person: { select: { fullName: true } } } }, attendee: { select: { person: { select: { fullName: true } } } },
checkout: { select: { _count: { select: { payments: true } } } },
}, },
skip: 0, skip: 0,
take: 10, take: 10,

View File

@@ -35,6 +35,9 @@ describe('session auth', () => {
expect(isPublicApiRequest('GET', '/api/v1/health')).toBe(true); expect(isPublicApiRequest('GET', '/api/v1/health')).toBe(true);
expect(isPublicApiRequest('POST', '/api/v1/auth/sign-in/email')).toBe(true); expect(isPublicApiRequest('POST', '/api/v1/auth/sign-in/email')).toBe(true);
expect(isPublicApiRequest('GET', '/api/v1/groups')).toBe(false); expect(isPublicApiRequest('GET', '/api/v1/groups')).toBe(false);
expect(isPublicApiRequest('POST', '/api/v1/payments/webhooks/mp/pay-1')).toBe(true);
expect(isPublicApiRequest('POST', '/api/v1/payments/webhooks/mp/checkout/chk-1')).toBe(true);
expect(isPublicApiRequest('POST', '/api/v1/payments/webhooks/mp/checkout/chk-1/extra')).toBe(false);
expect(isPublicApiRequest('GET', '/api/v1/attendees')).toBe(false); expect(isPublicApiRequest('GET', '/api/v1/attendees')).toBe(false);
}); });

View File

@@ -197,7 +197,7 @@ describe('status', () => {
displayPhoneNumber: null, displayPhoneNumber: null,
connectedAt: null, connectedAt: null,
qrCode: null, qrCode: null,
readiness: { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked' }, readiness: { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked', PAYMENT_LINK: 'blocked' },
}, },
}); });
}); });
@@ -279,6 +279,7 @@ describe('status', () => {
expect(result.ok && result.value.readiness).toEqual({ expect(result.ok && result.value.readiness).toEqual({
PAYMENT_REMINDER: 'ready', PAYMENT_REMINDER: 'ready',
REENGAGEMENT: 'pending', REENGAGEMENT: 'pending',
PAYMENT_LINK: 'ready',
}); });
}); });
}); });

View File

@@ -93,6 +93,36 @@ function reengagement(provider: MessagingProvider) {
} }
describe('payment reminders', () => { describe('payment reminders', () => {
it('reminds a combined link once, to whoever pays it, with the total', async () => {
const checkout = {
id: 'chk-1',
status: 'OPEN',
amount: { toString: () => '40000' },
payer: { id: 'g-1', fullName: 'Laura Gómez', phone: '11 2345-6789' },
payments: [
{ group: { name: 'Yoga Martes' }, attendee: { person: { id: 'p-1', fullName: 'Juan Gómez' } } },
{ group: { name: 'Yoga Martes' }, attendee: { person: { id: 'p-2', fullName: 'Ana Gómez' } } },
],
};
db.payment.findMany.mockResolvedValue([
payment('pay-1', { id: 'att-1', fullName: 'Juan Gómez' }, { checkout, checkoutUrl: 'https://mpago.la/chk' }),
payment('pay-2', { id: 'att-2', fullName: 'Ana Gómez' }, { checkout, checkoutUrl: 'https://mpago.la/chk' }),
]);
const provider = fakeProvider();
const totals = await reminders(provider).execute();
expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 });
const [, , message] = (provider.send as ReturnType<typeof mock>).mock.calls[0] ?? [];
expect(message).toMatchObject({
kind: 'PAYMENT_REMINDER',
studentName: 'Laura Gómez',
groupName: 'Yoga Martes (Juan) y Yoga Martes (Ana)',
paymentLink: 'https://mpago.la/chk',
});
expect((message as { amount: string }).amount).toContain('40.000');
});
it('only looks at groups with the automation on and an active account of this provider', async () => { it('only looks at groups with the automation on and an active account of this provider', async () => {
await reminders(fakeProvider()).execute(); await reminders(fakeProvider()).execute();
@@ -135,6 +165,7 @@ describe('payment reminders', () => {
groupId: 'group-1', groupId: 'group-1',
attendeeId: 'att-1', attendeeId: 'att-1',
paymentId: 'pay-1', paymentId: 'pay-1',
checkoutId: null,
kind: 'PAYMENT_REMINDER', kind: 'PAYMENT_REMINDER',
provider: 'OPENWA', provider: 'OPENWA',
periodKey: '2026-W43', periodKey: '2026-W43',

View File

@@ -490,12 +490,13 @@ describe('Kapso provider', () => {
expect(templates.map((call) => (call.body as { name: string; category: string }))).toEqual([ expect(templates.map((call) => (call.body as { name: string; category: string }))).toEqual([
expect.objectContaining({ name: 'gruperly_payment_reminder', category: 'UTILITY' }), expect.objectContaining({ name: 'gruperly_payment_reminder', category: 'UTILITY' }),
expect.objectContaining({ name: 'gruperly_reengagement', category: 'MARKETING' }), expect.objectContaining({ name: 'gruperly_reengagement', category: 'MARKETING' }),
expect.objectContaining({ name: 'gruperly_payment_link', category: 'UTILITY' }),
]); ]);
expect(db.whatsappAccount.update).toHaveBeenCalledWith({ expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' }, where: { id: 'wa-1' },
data: { providerData: { customerId: 'cust-1', businessAccountId: 'waba-1', webhookId: 'wh-1' } }, data: { providerData: { customerId: 'cust-1', businessAccountId: 'waba-1', webhookId: 'wh-1' } },
}); });
expect(db.whatsappTemplate.create).toHaveBeenCalledTimes(2); expect(db.whatsappTemplate.create).toHaveBeenCalledTimes(3);
}); });
it('is ready only once the template is approved', async () => { it('is ready only once the template is approved', async () => {

View File

@@ -1,11 +1,11 @@
import { Badge, useToast } from '../../components/ui' import { Badge, Switch, useToast } from '../../components/ui'
import { paymentPresentation } from './detail' import { paymentPresentation } from './detail'
import { Section } from './Section' import { Section } from './Section'
import { useAttendeeDetail } from './AttendeeDetailProvider' import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
export function AttendeePaymentsSection() { export function AttendeePaymentsSection() {
const { attendee } = useAttendeeDetail() const { attendee, saveAttendee, isUpdatingAttendee } = useAttendeeDetail()
const toast = useToast() const toast = useToast()
const { t } = useTranslation(['attendeeDetail', 'common']) const { t } = useTranslation(['attendeeDetail', 'common'])
if (!attendee) return null if (!attendee) return null
@@ -17,6 +17,16 @@ export function AttendeePaymentsSection() {
toast.info(t('payments.registerPending')) toast.info(t('payments.registerPending'))
} }
// Es de la persona: cambia en todos sus grupos, como el contacto.
const togglePayWithMp = async (payWithMercadoPago: boolean) => {
try {
await saveAttendee({ payWithMercadoPago })
toast.success(payWithMercadoPago ? t('payments.payWithMpOn') : t('payments.payWithMpOff'))
} catch {
toast.error(t('payments.payWithMpError'))
}
}
return ( return (
<Section title={t('payments.title')}> <Section title={t('payments.title')}>
<div className="flex min-h-14 items-center justify-between gap-3 px-3 py-1"> <div className="flex min-h-14 items-center justify-between gap-3 px-3 py-1">
@@ -36,6 +46,21 @@ export function AttendeePaymentsSection() {
{t('payments.register')} {t('payments.register')}
</button> </button>
</div> </div>
<div className="flex items-start justify-between gap-3 border-t border-border px-3 py-3">
<div className="min-w-0">
<p className="text-sm text-primary">{t('payments.payWithMp')}</p>
<p id="pay-with-mp-hint" className="text-xs text-secondary">
{t('payments.payWithMpHint')}
</p>
</div>
<Switch
checked={attendee.payWithMercadoPago}
disabled={isUpdatingAttendee}
aria-label={t('payments.payWithMp')}
aria-describedby="pay-with-mp-hint"
onCheckedChange={togglePayWithMp}
/>
</div>
</Section> </Section>
) )
} }

View File

@@ -49,6 +49,11 @@ export function PaymentRow({ payment, showGroup, isRenewing, onRenew }: PaymentR
<span className="text-xs text-foreground/50">{paymentPeriodLabel(payment)}</span> <span className="text-xs text-foreground/50">{paymentPeriodLabel(payment)}</span>
</p> </p>
<p className="mt-1 text-xs text-foreground/50">{paymentDateLabel(payment)}</p> <p className="mt-1 text-xs text-foreground/50">{paymentDateLabel(payment)}</p>
{payment.checkoutItemCount && payment.checkoutItemCount > 1 ? (
<p className="mt-1 text-xs text-foreground/50">
{t('row.combined', { count: payment.checkoutItemCount })}
</p>
) : null}
</div> </div>
<Badge variant={PAYMENT_STATUS_BADGE[payment.status]}> <Badge variant={PAYMENT_STATUS_BADGE[payment.status]}>
{paymentStatusLabel(payment.status)} {paymentStatusLabel(payment.status)}

View File

@@ -10,7 +10,20 @@ export const PAYMENT_STATUS_BADGE: Record<PaymentDto['status'], BadgeVariant> =
} }
export function paymentPeriodLabel(payment: PaymentDto): string { export function paymentPeriodLabel(payment: PaymentDto): string {
return payment.description ?? payment.groupName if (payment.description) return payment.description
if (payment.periodKey) return periodKeyLabel(payment.periodKey)
return payment.groupName
}
/* "2026-12" → "Diciembre 2026", en el idioma de la UI. */
export function periodKeyLabel(periodKey: string): string {
const [year, month] = periodKey.split('-').map(Number)
const text = new Date(Date.UTC(year ?? 2000, (month ?? 1) - 1, 15)).toLocaleDateString(i18n.language, {
month: 'long',
year: 'numeric',
timeZone: 'UTC',
})
return text.charAt(0).toUpperCase() + text.slice(1)
} }
export function paymentDateLabel(payment: PaymentDto): string { export function paymentDateLabel(payment: PaymentDto): string {

View File

@@ -0,0 +1,207 @@
import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { AutoChargeSettingsDto, PaymentRunDto, UpdateAutoChargeSettings } from '@gruperly/shared'
import { AUTO_CHARGE_MAX_DAY } from '@gruperly/shared'
import { CalendarClock } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Badge, Label, Switch, useToast } from '../../components/ui'
import { useIntlLocale } from '../../i18n'
import { errorMessage } from '../../i18n/errors'
import { getAutoChargeSettings, updateAutoChargeSettings } from '../../lib/api'
import { hasPlanFeature, useBillingStatus } from '../billing'
import { useMpStatus } from '../mp'
import { automationBlockedReason, useWhatsappStatus } from '../whatsapp'
export const autoChargeQueryKey = ['auto-charge'] as const
const DAYS = Array.from({ length: AUTO_CHARGE_MAX_DAY }, (_, index) => index + 1)
const DUE_OPTIONS = [3, 5, 7, 10, 15, 20, 30] as const
const selectClass =
'h-11 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30 disabled:opacity-50'
/*
* Cobro automático: el día del mes en que se generan las cuotas de todos los
* grupos mensuales, con un link de Mercado Pago por quien paga (el adulto a
* cargo junta a sus chicos), y si esos links salen por WhatsApp.
*/
export function AutoChargeSettingsCard() {
const { t } = useTranslation(['settings', 'common'])
const locale = useIntlLocale()
const toast = useToast()
const queryClient = useQueryClient()
const query = useQuery({ queryKey: autoChargeQueryKey, queryFn: getAutoChargeSettings })
const mpQuery = useMpStatus()
const whatsappQuery = useWhatsappStatus()
const billingQuery = useBillingStatus()
// Solo al prenderlo a mano aparece el formulario: ahí va el foco.
const [justEnabled, setJustEnabled] = useState(false)
const mutation = useMutation({
mutationFn: updateAutoChargeSettings,
onSuccess: (data) => {
queryClient.setQueryData<AutoChargeSettingsDto>(autoChargeQueryKey, data)
toast.success(t('autoCharge.saved'))
},
onError: (error) => toast.error(errorMessage(error, t('autoCharge.saveError'))),
})
const settings = query.data
const includedInPlan = hasPlanFeature(billingQuery.data, 'mpCharges')
const whatsappInPlan = hasPlanFeature(billingQuery.data, 'whatsappAutomations')
const mpLinked = mpQuery.data?.status === 'active'
const whatsappBlocked = automationBlockedReason(whatsappQuery.data, 'PAYMENT_LINK')
const busy = mutation.isPending || query.isPending
const save = (patch: UpdateAutoChargeSettings) => mutation.mutate(patch)
const formatDay = (isoDay: string) =>
new Date(`${isoDay}T12:00:00Z`).toLocaleDateString(locale, { day: 'numeric', month: 'long', timeZone: 'UTC' })
return (
<section className="rounded-xl border border-border bg-surface" aria-labelledby="auto-charge-title">
<div className="flex items-start gap-3 px-4 py-3">
<span className="rounded-lg bg-accent-soft p-2" aria-hidden="true">
<CalendarClock className="size-4 text-accent-fg" />
</span>
<div className="min-w-0 flex-1">
<p id="auto-charge-title" className="flex items-center gap-2 text-sm font-medium text-primary">
{t('autoCharge.title')}
{includedInPlan ? null : <Badge variant="info">Pro</Badge>}
</p>
<p id="auto-charge-description" className="text-xs text-secondary">
{t('autoCharge.description')}
</p>
{!mpLinked && !settings?.enabled ? (
<p className="mt-1 text-xs text-warning">{t('autoCharge.needsMp')}</p>
) : null}
</div>
<Switch
checked={settings?.enabled ?? false}
disabled={busy || (!settings?.enabled && (!includedInPlan || !mpLinked))}
aria-label={t('autoCharge.title')}
aria-describedby="auto-charge-description"
onCheckedChange={(enabled) => {
setJustEnabled(enabled)
save({ enabled })
}}
/>
</div>
{settings?.enabled ? (
<div className="space-y-4 border-t border-border px-4 py-4">
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label htmlFor="auto-charge-day">{t('autoCharge.day')}</Label>
<select
id="auto-charge-day"
autoFocus={justEnabled}
className={selectClass}
value={settings.chargeDay}
disabled={busy}
onChange={(event) => save({ chargeDay: Number(event.target.value) })}
>
{DAYS.map((day) => (
<option key={day} value={day}>
{t('autoCharge.dayOption', { day })}
</option>
))}
</select>
</div>
<div className="space-y-1.5">
<Label htmlFor="auto-charge-due">{t('autoCharge.due')}</Label>
<select
id="auto-charge-due"
className={selectClass}
value={settings.dueInDays}
disabled={busy}
onChange={(event) => save({ dueInDays: Number(event.target.value) })}
>
{(DUE_OPTIONS.includes(settings.dueInDays as (typeof DUE_OPTIONS)[number])
? DUE_OPTIONS
: [...DUE_OPTIONS, settings.dueInDays].sort((a, b) => a - b)
).map((days) => (
<option key={days} value={days}>
{t('autoCharge.dueOption', { count: days })}
</option>
))}
</select>
</div>
</div>
<div className="flex items-start gap-3">
<div className="min-w-0 flex-1">
<p className="flex items-center gap-2 text-sm text-primary">
{t('autoCharge.whatsapp')}
{whatsappInPlan ? null : <Badge variant="info">Pro</Badge>}
</p>
<p id="auto-charge-whatsapp-hint" className="text-xs text-secondary">
{t('autoCharge.whatsappDescription')}
{whatsappBlocked && !settings.sendWhatsapp ? (
<>
{' '}
<span className="text-warning">{whatsappBlocked}</span>
</>
) : null}
</p>
</div>
<Switch
checked={settings.sendWhatsapp}
disabled={busy || (!settings.sendWhatsapp && (whatsappBlocked !== null || !whatsappInPlan))}
aria-label={t('autoCharge.whatsapp')}
aria-describedby="auto-charge-whatsapp-hint"
onCheckedChange={(sendWhatsapp) => save({ sendWhatsapp })}
/>
</div>
<p className="text-xs text-secondary">{t('autoCharge.howItGroups')}</p>
{settings.nextRunDate ? (
<p className="text-sm text-primary">{t('autoCharge.next', { date: formatDay(settings.nextRunDate) })}</p>
) : null}
</div>
) : null}
{settings?.lastRun ? <LastRun run={settings.lastRun} /> : null}
</section>
)
}
function LastRun({ run }: { run: PaymentRunDto }) {
const { t } = useTranslation('settings')
const locale = useIntlLocale()
const [year, month] = run.periodKey.split('-').map(Number)
const period = new Date(Date.UTC(year ?? 2000, (month ?? 1) - 1, 15)).toLocaleDateString(locale, {
month: 'long',
year: 'numeric',
timeZone: 'UTC',
})
let summary: string
if (run.status === 'SKIPPED') {
summary = t(`autoCharge.skipped.${skipReasonKey(run.skipReason)}`)
} else if (run.status === 'RUNNING') {
summary = t('autoCharge.running')
} else {
summary = [
t('autoCharge.fees', { count: run.fees }),
t('autoCharge.links', { count: run.linked }),
run.failed > 0 ? t('autoCharge.failed', { count: run.failed }) : null,
run.sent > 0 ? t('autoCharge.sent', { count: run.sent }) : null,
]
.filter(Boolean)
.join(' · ')
}
return (
<p className="border-t border-border px-4 py-3 text-xs text-secondary">
{t('autoCharge.lastRun', { period })} {summary}
</p>
)
}
const SKIP_REASONS = ['mp_not_connected', 'plan_feature_required', 'no_groups'] as const
function skipReasonKey(reason: string | null): (typeof SKIP_REASONS)[number] | 'other' {
return SKIP_REASONS.find((known) => known === reason) ?? 'other'
}

View File

@@ -7,6 +7,7 @@ import { PlanSettingsCard } from '../billing'
import { MpStatusCard } from '../mp' import { MpStatusCard } from '../mp'
import { WhatsappStatusCard } from '../whatsapp' import { WhatsappStatusCard } from '../whatsapp'
import { AppearanceCard } from './AppearanceCard' import { AppearanceCard } from './AppearanceCard'
import { AutoChargeSettingsCard } from './AutoChargeSettingsCard'
import { LanguageCard } from './LanguageCard' import { LanguageCard } from './LanguageCard'
import { TransferDetailsSettingsCard } from './TransferDetailsSettingsCard' import { TransferDetailsSettingsCard } from './TransferDetailsSettingsCard'
import { useCallbackFeedbackToast } from './useCallbackFeedbackToast' import { useCallbackFeedbackToast } from './useCallbackFeedbackToast'
@@ -46,6 +47,8 @@ export function SettingsView() {
<MpStatusCard /> <MpStatusCard />
<AutoChargeSettingsCard />
<TransferDetailsSettingsCard /> <TransferDetailsSettingsCard />
<WhatsappStatusCard /> <WhatsappStatusCard />

View File

@@ -3,7 +3,7 @@ import type { StudentFee } from '@gruperly/shared'
import { ExternalLink, Receipt } from 'lucide-react' import { ExternalLink, Receipt } from 'lucide-react'
import { Badge } from '../../components/ui' import { Badge } from '../../components/ui'
import { formatPrice } from '../../lib/format' import { formatPrice } from '../../lib/format'
import { feeLabel } from './format' import { checkoutItemsLabel, feeLabel } from './format'
import { FeeStatusBadge } from './FeeStatusBadge' import { FeeStatusBadge } from './FeeStatusBadge'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
@@ -40,10 +40,19 @@ export function FeeCard({ fees }: { fees: StudentFee[] }) {
{toReport.length > 0 ? ( {toReport.length > 0 ? (
<div className="mt-4 space-y-2"> <div className="mt-4 space-y-2">
{single ? ( {single ? (
<a href={single.checkoutUrl ?? undefined} target="_blank" rel="noreferrer" className={primary}> <>
{t('fee.payMp')} <a href={single.checkoutUrl ?? undefined} target="_blank" rel="noreferrer" className={primary}>
<ExternalLink className="size-4" aria-hidden="true" /> {single.checkout
</a> ? t('fee.payAll', { amount: formatPrice(single.checkout.total, single.currency) })
: t('fee.payMp')}
<ExternalLink className="size-4" aria-hidden="true" />
</a>
{single.checkout ? (
<p className="text-center text-xs text-secondary">
{t('fee.includes', { items: checkoutItemsLabel(single.checkout) })}
</p>
) : null}
</>
) : payable.length > 1 ? ( ) : payable.length > 1 ? (
<Link to="/student/payments" className={primary}> <Link to="/student/payments" className={primary}>
{t('fee.payMp')} {t('fee.payMp')}

View File

@@ -4,7 +4,7 @@ import { ExternalLink, Loader2, Receipt } from 'lucide-react'
import { Badge } from '../../components/ui' import { Badge } from '../../components/ui'
import { formatPrice } from '../../lib/format' import { formatPrice } from '../../lib/format'
import { FeeStatusBadge } from './FeeStatusBadge' import { FeeStatusBadge } from './FeeStatusBadge'
import { feeLabel, formatDueDate } from './format' import { checkoutItemsLabel, feeLabel, formatDueDate } from './format'
import { useStudentApp } from './StudentAppProvider' import { useStudentApp } from './StudentAppProvider'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useIntlLocale } from '../../i18n' import { useIntlLocale } from '../../i18n'
@@ -57,15 +57,24 @@ export function StudentPaymentsView() {
</div> </div>
</div> </div>
{fee.checkoutUrl && fee.status !== 'reported' ? ( {fee.checkoutUrl && fee.status !== 'reported' ? (
<a <div>
href={fee.checkoutUrl} <a
target="_blank" href={fee.checkoutUrl}
rel="noreferrer" target="_blank"
className="inline-flex min-h-11 items-center gap-1 text-sm font-medium text-accent-fg hover:underline" rel="noreferrer"
> className="inline-flex min-h-11 items-center gap-1 text-sm font-medium text-accent-fg hover:underline"
{t('payments.payMp')} >
<ExternalLink className="size-4" aria-hidden="true" /> {fee.checkout
</a> ? t('payments.payAll', { amount: formatPrice(fee.checkout.total, fee.currency) })
: t('payments.payMp')}
<ExternalLink className="size-4" aria-hidden="true" />
</a>
{fee.checkout ? (
<p className="text-xs text-secondary">
{t('payments.includes', { items: checkoutItemsLabel(fee.checkout) })}
</p>
) : null}
</div>
) : null} ) : null}
</li> </li>
))} ))}

View File

@@ -51,11 +51,18 @@ export function dateParts(iso: string, timeZone: string): { day: string; month:
} }
} }
/** Fee title: its description, or the month it is due ("Noviembre"). */ /** Fee title: its description, its month (automatic charges) or the month it is due ("Noviembre"). */
export function feeLabel(fee: Pick<StudentFee, 'description' | 'dueDate'>): string { export function feeLabel(fee: Pick<StudentFee, 'description' | 'dueDate'> & { periodKey?: string | null }): string {
if (fee.description) return fee.description if (fee.description) return fee.description
const month = new Intl.DateTimeFormat(i18n.language, { month: 'long', timeZone: 'UTC' }).format(new Date(fee.dueDate)) const [year, month] = (fee.periodKey ?? '').split('-').map(Number)
return month.charAt(0).toUpperCase() + month.slice(1) const monthDate = year && month ? new Date(Date.UTC(year, month - 1, 15)) : new Date(fee.dueDate)
const monthName = new Intl.DateTimeFormat(i18n.language, { month: 'long', timeZone: 'UTC' }).format(monthDate)
return monthName.charAt(0).toUpperCase() + monthName.slice(1)
}
/** What a combined link pays: "Natación · Juan, Yoga · Ana". */
export function checkoutItemsLabel(checkout: NonNullable<StudentFee['checkout']>): string {
return checkout.items.map((item) => `${item.groupName} · ${firstName(item.studentName)}`).join(', ')
} }
export function formatDueDate(iso: string): string { export function formatDueDate(iso: string): string {

View File

@@ -106,6 +106,10 @@ export function WhatsappStatusCard() {
<dt className="text-foreground/60">{t('card.reengagement')}</dt> <dt className="text-foreground/60">{t('card.reengagement')}</dt>
<dd className="text-primary">{readinessLabel(data.readiness.REENGAGEMENT)}</dd> <dd className="text-primary">{readinessLabel(data.readiness.REENGAGEMENT)}</dd>
</div> </div>
<div className="flex items-center justify-between gap-3">
<dt className="text-foreground/60">{t('card.paymentLink')}</dt>
<dd className="text-primary">{readinessLabel(data.readiness.PAYMENT_LINK)}</dd>
</div>
<p className="pt-1 text-xs text-foreground/50"> <p className="pt-1 text-xs text-foreground/50">
{t('card.perGroup')} {weeklySendLabel()} {t('card.perGroup')} {weeklySendLabel()}
</p> </p>

View File

@@ -138,7 +138,7 @@ export function formatPairingCode(code: string): string {
*/ */
export function automationBlockedReason( export function automationBlockedReason(
status: WhatsappStatusDto | undefined, status: WhatsappStatusDto | undefined,
kind: 'PAYMENT_REMINDER' | 'REENGAGEMENT', kind: 'PAYMENT_REMINDER' | 'REENGAGEMENT' | 'PAYMENT_LINK',
): string | null { ): string | null {
if (!status || status.status !== 'active') { if (!status || status.status !== 'active') {
return i18n.t('whatsapp:blocked.notLinked') return i18n.t('whatsapp:blocked.notLinked')

View File

@@ -75,7 +75,12 @@
"registerPending": "Recording payments will be available once the payment flow is defined.", "registerPending": "Recording payments will be available once the payment flow is defined.",
"noCharge": "No charge on record", "noCharge": "No charge on record",
"upToDate": "Up to date", "upToDate": "Up to date",
"owes": "Owes {{month}}" "owes": "Owes {{month}}",
"payWithMp": "Pays with Mercado Pago",
"payWithMpHint": "Turn it off if they prefer to transfer: automatic billing creates their fee without a link.",
"payWithMpOn": "We will create Mercado Pago links for them",
"payWithMpOff": "They will pay by transfer",
"payWithMpError": "We could not save the change"
}, },
"attendance": { "attendance": {
"title": "Attendance", "title": "Attendance",

View File

@@ -25,7 +25,9 @@
"copied": "Copied", "copied": "Copied",
"copyLink": "Copy link", "copyLink": "Copy link",
"noLink": "No link", "noLink": "No link",
"generate": "Create link" "generate": "Create link",
"combined_one": "Combined link · {{count}} fee",
"combined_other": "Combined link · {{count}} fees"
}, },
"groupFilter": { "groupFilter": {
"label": "Group: {{name}}", "label": "Group: {{name}}",

View File

@@ -35,5 +35,37 @@
"callback": { "callback": {
"mpLinked": "Your Mercado Pago account is linked.", "mpLinked": "Your Mercado Pago account is linked.",
"whatsappLinked": "Your WhatsApp is linked." "whatsappLinked": "Your WhatsApp is linked."
},
"autoCharge": {
"title": "Automatic billing",
"description": "Every month it creates the fees of your monthly groups, with one Mercado Pago link per family.",
"needsMp": "Link Mercado Pago to use it.",
"day": "Day of the month",
"dayOption": "Day {{day}}",
"due": "Due",
"dueOption_one": "In {{count}} day",
"dueOption_other": "In {{count}} days",
"whatsapp": "Send the links by WhatsApp",
"whatsappDescription": "Everyone gets their link as soon as it is created.",
"howItGroups": "Kids of the same adult, and anyone in several groups, get a single link with the total. Students who pay by transfer get their fee without a link.",
"next": "Next run: {{date}}",
"lastRun": "Last billing ({{period}}):",
"running": "in progress.",
"fees_one": "{{count}} fee",
"fees_other": "{{count}} fees",
"links_one": "{{count}} link",
"links_other": "{{count}} links",
"failed_one": "{{count}} link not created",
"failed_other": "{{count}} links not created",
"sent_one": "{{count}} sent by WhatsApp",
"sent_other": "{{count}} sent by WhatsApp",
"skipped": {
"mp_not_connected": "not created because Mercado Pago was not linked.",
"plan_feature_required": "not created because your plan does not include Mercado Pago charges.",
"no_groups": "there were no monthly groups with a price.",
"other": "not created."
},
"saved": "Automatic billing updated",
"saveError": "We could not save automatic billing"
} }
} }

View File

@@ -51,7 +51,9 @@
"overdue": "Some are overdue", "overdue": "Some are overdue",
"payMp": "Pay with Mercado Pago", "payMp": "Pay with Mercado Pago",
"report": "Report payment", "report": "Report payment",
"awaiting": "Your teacher needs to confirm the payment you reported." "awaiting": "Your teacher needs to confirm the payment you reported.",
"payAll": "Pay all ({{amount}})",
"includes": "Includes: {{items}}"
}, },
"review": { "review": {
"confirmed": "Your teacher confirmed your {{amount}} payment.", "confirmed": "Your teacher confirmed your {{amount}} payment.",
@@ -84,7 +86,9 @@
"reported": "Reported", "reported": "Reported",
"confirmed": "Confirmed", "confirmed": "Confirmed",
"rejected": "Declined" "rejected": "Declined"
} },
"payAll": "Pay all ({{amount}})",
"includes": "Includes: {{items}}"
}, },
"notify": { "notify": {
"done": "Done, we let {{teacher}} know", "done": "Done, we let {{teacher}} know",

View File

@@ -50,7 +50,10 @@
"invalid": "Invalid time zone" "invalid": "Invalid time zone"
}, },
"payment": { "payment": {
"descriptionMax": "The description is too long" "descriptionMax": "The description is too long",
"chargeDayRange": "Choose a day between 1 and 28",
"dueInDaysRange": "Choose between 1 and 31 days",
"autoChargeRequired": "There is nothing to change"
}, },
"lastName": { "lastName": {
"required": "Last name is required" "required": "Last name is required"

View File

@@ -75,6 +75,7 @@
"qrHint": "Link it with your number or a QR code, like WhatsApp Web.", "qrHint": "Link it with your number or a QR code, like WhatsApp Web.",
"metaHint": "We'll take you to Meta to connect your WhatsApp Business account.", "metaHint": "We'll take you to Meta to connect your WhatsApp Business account.",
"opening": "Opening…", "opening": "Opening…",
"connect": "Link" "connect": "Link",
"paymentLink": "Monthly payment link"
} }
} }

View File

@@ -75,7 +75,12 @@
"registerPending": "Registrar pagos estará disponible cuando se defina el flujo de cobros.", "registerPending": "Registrar pagos estará disponible cuando se defina el flujo de cobros.",
"noCharge": "Sin cobro registrado", "noCharge": "Sin cobro registrado",
"upToDate": "Al día", "upToDate": "Al día",
"owes": "Debe {{month}}" "owes": "Debe {{month}}",
"payWithMp": "Paga con Mercado Pago",
"payWithMpHint": "Apágalo si prefiere transferir: el cobro automático le crea la cuota sin link.",
"payWithMpOn": "Le vamos a generar links de Mercado Pago",
"payWithMpOff": "Va a pagar por transferencia",
"payWithMpError": "No pudimos guardar el cambio"
}, },
"attendance": { "attendance": {
"title": "Asistencia", "title": "Asistencia",

View File

@@ -25,7 +25,9 @@
"copied": "Copiado", "copied": "Copiado",
"copyLink": "Copiar link", "copyLink": "Copiar link",
"noLink": "Sin link", "noLink": "Sin link",
"generate": "Generar link" "generate": "Generar link",
"combined_one": "Link combinado · {{count}} cuota",
"combined_other": "Link combinado · {{count}} cuotas"
}, },
"groupFilter": { "groupFilter": {
"label": "Grupo: {{name}}", "label": "Grupo: {{name}}",

View File

@@ -35,5 +35,37 @@
"callback": { "callback": {
"mpLinked": "Tu cuenta de Mercado Pago quedó vinculada.", "mpLinked": "Tu cuenta de Mercado Pago quedó vinculada.",
"whatsappLinked": "Tu WhatsApp quedó vinculado." "whatsappLinked": "Tu WhatsApp quedó vinculado."
},
"autoCharge": {
"title": "Cobro automático",
"description": "Cada mes genera las cuotas de tus grupos mensuales con un link de Mercado Pago por familia.",
"needsMp": "Vincula Mercado Pago para usarlo.",
"day": "Día del mes",
"dayOption": "Día {{day}}",
"due": "Vencimiento",
"dueOption_one": "A {{count}} día",
"dueOption_other": "A {{count}} días",
"whatsapp": "Enviar los links por WhatsApp",
"whatsappDescription": "Cada uno recibe su link apenas se genera.",
"howItGroups": "Los niños de un mismo adulto, y quien está en varios grupos, reciben un solo link con el total. Los alumnos que pagan por transferencia tienen su cuota sin link.",
"next": "Próxima generación: {{date}}",
"lastRun": "Último cobro ({{period}}):",
"running": "en curso.",
"fees_one": "{{count}} cuota",
"fees_other": "{{count}} cuotas",
"links_one": "{{count}} link",
"links_other": "{{count}} links",
"failed_one": "{{count}} link sin generar",
"failed_other": "{{count}} links sin generar",
"sent_one": "{{count}} enviado por WhatsApp",
"sent_other": "{{count}} enviados por WhatsApp",
"skipped": {
"mp_not_connected": "no se generó porque Mercado Pago no estaba vinculado.",
"plan_feature_required": "no se generó porque tu plan no incluye cobros con Mercado Pago.",
"no_groups": "no había grupos mensuales con precio.",
"other": "no se generó."
},
"saved": "Cobro automático actualizado",
"saveError": "No pudimos guardar el cobro automático"
} }
} }

View File

@@ -51,7 +51,9 @@
"overdue": "Hay vencidas", "overdue": "Hay vencidas",
"payMp": "Pagar con Mercado Pago", "payMp": "Pagar con Mercado Pago",
"report": "Informar pago", "report": "Informar pago",
"awaiting": "Tu profe tiene que confirmar el pago que informaste." "awaiting": "Tu profe tiene que confirmar el pago que informaste.",
"payAll": "Pagar todo ({{amount}})",
"includes": "Incluye: {{items}}"
}, },
"review": { "review": {
"confirmed": "Tu profe confirmó tu pago de {{amount}}.", "confirmed": "Tu profe confirmó tu pago de {{amount}}.",
@@ -84,7 +86,9 @@
"reported": "Informado", "reported": "Informado",
"confirmed": "Confirmado", "confirmed": "Confirmado",
"rejected": "Rechazado" "rejected": "Rechazado"
} },
"payAll": "Pagar todo ({{amount}})",
"includes": "Incluye: {{items}}"
}, },
"notify": { "notify": {
"done": "Listo, le avisamos a {{teacher}}", "done": "Listo, le avisamos a {{teacher}}",

View File

@@ -50,7 +50,10 @@
"invalid": "Zona horaria inválida" "invalid": "Zona horaria inválida"
}, },
"payment": { "payment": {
"descriptionMax": "La descripción es demasiado larga" "descriptionMax": "La descripción es demasiado larga",
"chargeDayRange": "Elige un día entre el 1 y el 28",
"dueInDaysRange": "Elige entre 1 y 31 días",
"autoChargeRequired": "No hay nada para cambiar"
}, },
"lastName": { "lastName": {
"required": "El apellido es obligatorio" "required": "El apellido es obligatorio"

View File

@@ -75,6 +75,7 @@
"qrHint": "Lo vinculas con tu número o con un código QR, como WhatsApp Web.", "qrHint": "Lo vinculas con tu número o con un código QR, como WhatsApp Web.",
"metaHint": "Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.", "metaHint": "Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.",
"opening": "Abriendo…", "opening": "Abriendo…",
"connect": "Vincular" "connect": "Vincular",
"paymentLink": "Link de pago mensual"
} }
} }

View File

@@ -75,7 +75,12 @@
"registerPending": "Registrar pagos estará disponible cuando se defina el flujo de cobros.", "registerPending": "Registrar pagos estará disponible cuando se defina el flujo de cobros.",
"noCharge": "Sin cobro registrado", "noCharge": "Sin cobro registrado",
"upToDate": "Al día", "upToDate": "Al día",
"owes": "Debe {{month}}" "owes": "Debe {{month}}",
"payWithMp": "Paga con Mercado Pago",
"payWithMpHint": "Apagalo si prefiere transferir: el cobro automático le crea la cuota sin link.",
"payWithMpOn": "Le vamos a generar links de Mercado Pago",
"payWithMpOff": "Va a pagar por transferencia",
"payWithMpError": "No pudimos guardar el cambio"
}, },
"attendance": { "attendance": {
"title": "Asistencia", "title": "Asistencia",

View File

@@ -25,7 +25,9 @@
"copied": "Copiado", "copied": "Copiado",
"copyLink": "Copiar link", "copyLink": "Copiar link",
"noLink": "Sin link", "noLink": "Sin link",
"generate": "Generar link" "generate": "Generar link",
"combined_one": "Link combinado · {{count}} cuota",
"combined_other": "Link combinado · {{count}} cuotas"
}, },
"groupFilter": { "groupFilter": {
"label": "Grupo: {{name}}", "label": "Grupo: {{name}}",

View File

@@ -35,5 +35,37 @@
"callback": { "callback": {
"mpLinked": "Tu cuenta de Mercado Pago quedó vinculada.", "mpLinked": "Tu cuenta de Mercado Pago quedó vinculada.",
"whatsappLinked": "Tu WhatsApp quedó vinculado." "whatsappLinked": "Tu WhatsApp quedó vinculado."
},
"autoCharge": {
"title": "Cobro automático",
"description": "Cada mes genera las cuotas de tus grupos mensuales con un link de Mercado Pago por familia.",
"needsMp": "Vinculá Mercado Pago para usarlo.",
"day": "Día del mes",
"dayOption": "Día {{day}}",
"due": "Vencimiento",
"dueOption_one": "A {{count}} día",
"dueOption_other": "A {{count}} días",
"whatsapp": "Enviar los links por WhatsApp",
"whatsappDescription": "Cada uno recibe su link apenas se genera.",
"howItGroups": "Los chicos de un mismo adulto, y quien está en varios grupos, reciben un solo link con el total. Los alumnos que pagan por transferencia tienen su cuota sin link.",
"next": "Próxima generación: {{date}}",
"lastRun": "Último cobro ({{period}}):",
"running": "en curso.",
"fees_one": "{{count}} cuota",
"fees_other": "{{count}} cuotas",
"links_one": "{{count}} link",
"links_other": "{{count}} links",
"failed_one": "{{count}} link sin generar",
"failed_other": "{{count}} links sin generar",
"sent_one": "{{count}} enviado por WhatsApp",
"sent_other": "{{count}} enviados por WhatsApp",
"skipped": {
"mp_not_connected": "no se generó porque Mercado Pago no estaba vinculado.",
"plan_feature_required": "no se generó porque tu plan no incluye cobros con Mercado Pago.",
"no_groups": "no había grupos mensuales con precio.",
"other": "no se generó."
},
"saved": "Cobro automático actualizado",
"saveError": "No pudimos guardar el cobro automático"
} }
} }

View File

@@ -51,7 +51,9 @@
"overdue": "Hay vencidas", "overdue": "Hay vencidas",
"payMp": "Pagar con Mercado Pago", "payMp": "Pagar con Mercado Pago",
"report": "Informar pago", "report": "Informar pago",
"awaiting": "Tu profe tiene que confirmar el pago que informaste." "awaiting": "Tu profe tiene que confirmar el pago que informaste.",
"payAll": "Pagar todo ({{amount}})",
"includes": "Incluye: {{items}}"
}, },
"review": { "review": {
"confirmed": "Tu profe confirmó tu pago de {{amount}}.", "confirmed": "Tu profe confirmó tu pago de {{amount}}.",
@@ -84,7 +86,9 @@
"reported": "Informado", "reported": "Informado",
"confirmed": "Confirmado", "confirmed": "Confirmado",
"rejected": "Rechazado" "rejected": "Rechazado"
} },
"payAll": "Pagar todo ({{amount}})",
"includes": "Incluye: {{items}}"
}, },
"notify": { "notify": {
"done": "Listo, le avisamos a {{teacher}}", "done": "Listo, le avisamos a {{teacher}}",

View File

@@ -50,7 +50,10 @@
"invalid": "Zona horaria inválida" "invalid": "Zona horaria inválida"
}, },
"payment": { "payment": {
"descriptionMax": "La descripción es demasiado larga" "descriptionMax": "La descripción es demasiado larga",
"chargeDayRange": "Elegí un día entre el 1 y el 28",
"dueInDaysRange": "Elegí entre 1 y 31 días",
"autoChargeRequired": "No hay nada para cambiar"
}, },
"lastName": { "lastName": {
"required": "El apellido es obligatorio" "required": "El apellido es obligatorio"

View File

@@ -75,6 +75,7 @@
"qrHint": "Lo vinculás con tu número o con un código QR, como WhatsApp Web.", "qrHint": "Lo vinculás con tu número o con un código QR, como WhatsApp Web.",
"metaHint": "Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.", "metaHint": "Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.",
"opening": "Abriendo…", "opening": "Abriendo…",
"connect": "Vincular" "connect": "Vincular",
"paymentLink": "Link de pago mensual"
} }
} }

View File

@@ -75,7 +75,12 @@
"registerPending": "Registrar pagamentos estará disponível quando o fluxo de cobranças for definido.", "registerPending": "Registrar pagamentos estará disponível quando o fluxo de cobranças for definido.",
"noCharge": "Nenhuma cobrança registrada", "noCharge": "Nenhuma cobrança registrada",
"upToDate": "Em dia", "upToDate": "Em dia",
"owes": "Deve {{month}}" "owes": "Deve {{month}}",
"payWithMp": "Paga com Mercado Pago",
"payWithMpHint": "Desative se preferir transferência: a cobrança automática cria a mensalidade sem link.",
"payWithMpOn": "Vamos gerar links do Mercado Pago",
"payWithMpOff": "Vai pagar por transferência",
"payWithMpError": "Não foi possível salvar a alteração"
}, },
"attendance": { "attendance": {
"title": "Presença", "title": "Presença",

View File

@@ -25,7 +25,9 @@
"copied": "Copiado", "copied": "Copiado",
"copyLink": "Copiar link", "copyLink": "Copiar link",
"noLink": "Sem link", "noLink": "Sem link",
"generate": "Gerar link" "generate": "Gerar link",
"combined_one": "Link combinado · {{count}} mensalidade",
"combined_other": "Link combinado · {{count}} mensalidades"
}, },
"groupFilter": { "groupFilter": {
"label": "Grupo: {{name}}", "label": "Grupo: {{name}}",

View File

@@ -35,5 +35,37 @@
"callback": { "callback": {
"mpLinked": "Sua conta do Mercado Pago foi vinculada.", "mpLinked": "Sua conta do Mercado Pago foi vinculada.",
"whatsappLinked": "Seu WhatsApp foi vinculado." "whatsappLinked": "Seu WhatsApp foi vinculado."
},
"autoCharge": {
"title": "Cobrança automática",
"description": "Todo mês gera as mensalidades dos seus grupos mensais com um link do Mercado Pago por família.",
"needsMp": "Vincule o Mercado Pago para usar.",
"day": "Dia do mês",
"dayOption": "Dia {{day}}",
"due": "Vencimento",
"dueOption_one": "Em {{count}} dia",
"dueOption_other": "Em {{count}} dias",
"whatsapp": "Enviar os links pelo WhatsApp",
"whatsappDescription": "Cada um recebe seu link assim que ele é gerado.",
"howItGroups": "As crianças de um mesmo adulto, e quem está em vários grupos, recebem um único link com o total. Alunos que pagam por transferência ficam com a mensalidade sem link.",
"next": "Próxima geração: {{date}}",
"lastRun": "Última cobrança ({{period}}):",
"running": "em andamento.",
"fees_one": "{{count}} mensalidade",
"fees_other": "{{count}} mensalidades",
"links_one": "{{count}} link",
"links_other": "{{count}} links",
"failed_one": "{{count}} link não gerado",
"failed_other": "{{count}} links não gerados",
"sent_one": "{{count}} enviado pelo WhatsApp",
"sent_other": "{{count}} enviados pelo WhatsApp",
"skipped": {
"mp_not_connected": "não foi gerada porque o Mercado Pago não estava vinculado.",
"plan_feature_required": "não foi gerada porque seu plano não inclui cobranças com Mercado Pago.",
"no_groups": "não havia grupos mensais com preço.",
"other": "não foi gerada."
},
"saved": "Cobrança automática atualizada",
"saveError": "Não foi possível salvar a cobrança automática"
} }
} }

View File

@@ -51,7 +51,9 @@
"overdue": "Há vencidas", "overdue": "Há vencidas",
"payMp": "Pagar com Mercado Pago", "payMp": "Pagar com Mercado Pago",
"report": "Informar pagamento", "report": "Informar pagamento",
"awaiting": "Seu professor precisa confirmar o pagamento que você informou." "awaiting": "Seu professor precisa confirmar o pagamento que você informou.",
"payAll": "Pagar tudo ({{amount}})",
"includes": "Inclui: {{items}}"
}, },
"review": { "review": {
"confirmed": "Seu professor confirmou seu pagamento de {{amount}}.", "confirmed": "Seu professor confirmou seu pagamento de {{amount}}.",
@@ -84,7 +86,9 @@
"reported": "Informado", "reported": "Informado",
"confirmed": "Confirmado", "confirmed": "Confirmado",
"rejected": "Recusado" "rejected": "Recusado"
} },
"payAll": "Pagar tudo ({{amount}})",
"includes": "Inclui: {{items}}"
}, },
"notify": { "notify": {
"done": "Pronto, avisamos {{teacher}}", "done": "Pronto, avisamos {{teacher}}",

View File

@@ -50,7 +50,10 @@
"invalid": "Fuso horário inválido" "invalid": "Fuso horário inválido"
}, },
"payment": { "payment": {
"descriptionMax": "A descrição é muito longa" "descriptionMax": "A descrição é muito longa",
"chargeDayRange": "Escolha um dia entre 1 e 28",
"dueInDaysRange": "Escolha entre 1 e 31 dias",
"autoChargeRequired": "Não há nada para alterar"
}, },
"lastName": { "lastName": {
"required": "O sobrenome é obrigatório" "required": "O sobrenome é obrigatório"

View File

@@ -75,6 +75,7 @@
"qrHint": "Você vincula com seu número ou com um QR code, como no WhatsApp Web.", "qrHint": "Você vincula com seu número ou com um QR code, como no WhatsApp Web.",
"metaHint": "Vamos te levar à Meta para conectar sua conta do WhatsApp Business.", "metaHint": "Vamos te levar à Meta para conectar sua conta do WhatsApp Business.",
"opening": "Abrindo…", "opening": "Abrindo…",
"connect": "Vincular" "connect": "Vincular",
"paymentLink": "Link de pagamento mensal"
} }
} }

View File

@@ -78,6 +78,8 @@ import type {
ReportedPaymentDto, ReportedPaymentDto,
ReceiptUrlDto, ReceiptUrlDto,
TransferDetailsDto, TransferDetailsDto,
AutoChargeSettingsDto,
UpdateAutoChargeSettings,
UpdateTransferDetails, UpdateTransferDetails,
TeacherAbsenceNoticeList, TeacherAbsenceNoticeList,
PersonSummary, PersonSummary,
@@ -621,6 +623,14 @@ export const rejectReportedPayment = (reportId: string, reason: string | null) =
export const undoPaymentReview = (reportId: string) => export const undoPaymentReview = (reportId: string) =>
apiFetch<ReportedPaymentDto>(`/api/v1/payments/reported/${reportId}/undo`, { method: 'POST' }) apiFetch<ReportedPaymentDto>(`/api/v1/payments/reported/${reportId}/undo`, { method: 'POST' })
export const getAutoChargeSettings = () => apiFetch<AutoChargeSettingsDto>('/api/v1/payments/auto-charge')
export const updateAutoChargeSettings = (payload: UpdateAutoChargeSettings) =>
apiFetch<AutoChargeSettingsDto>('/api/v1/payments/auto-charge', {
method: 'PUT',
body: JSON.stringify(payload),
})
export const getTransferDetails = () => apiFetch<TransferDetailsDto>('/api/v1/payments/transfer-details') export const getTransferDetails = () => apiFetch<TransferDetailsDto>('/api/v1/payments/transfer-details')
export const updateTransferDetails = (payload: UpdateTransferDetails) => export const updateTransferDetails = (payload: UpdateTransferDetails) =>

View File

@@ -2,7 +2,8 @@
Gruperly le escribe por WhatsApp a los miembros de un grupo **una vez por semana** (lunes 10:00, hora de Argentina), desde el **número del profesor** dueño del grupo: Gruperly le escribe por WhatsApp a los miembros de un grupo **una vez por semana** (lunes 10:00, hora de Argentina), desde el **número del profesor** dueño del grupo:
- **Recordatorio de pago**: a quien tenga un cobro `PENDING` u `OVERDUE` con link de Checkout Pro y vencimiento dentro de los próximos 7 días (o ya vencido). Va un mensaje por miembro con el cobro más viejo. - **Recordatorio de pago**: a quien tenga un cobro `PENDING` u `OVERDUE` con link de Checkout Pro y vencimiento dentro de los próximos 7 días (o ya vencido). Va un mensaje por miembro con el cobro más viejo; si la cuota es de un **link combinado** (cobro automático mensual), va **uno por link** a quien lo paga, con el total.
- **Link de pago mensual** (`PAYMENT_LINK`): no es semanal. Lo manda el **cobro automático** (Ajustes → "Cobro automático" → "Enviar los links por WhatsApp") apenas genera los links del mes, uno por pagador (el adulto a cargo junta a sus chicos). Idempotencia: `(PAYMENT_LINK, primer attendee del link, mes "2026-12")`.
- **Reenganche**: a los miembros que aparecen en **Alumnos en riesgo** (misma regla: 2+ faltas seguidas o menos de 50% de asistencia en 30 días). Como máximo uno cada 14 días por miembro. - **Reenganche**: a los miembros que aparecen en **Alumnos en riesgo** (misma regla: 2+ faltas seguidas o menos de 50% de asistencia en 30 días). Como máximo uno cada 14 días por miembro.
Cada automatización se prende **por grupo** (ficha del grupo → "Mensajes automáticos por WhatsApp"); vienen apagadas. El botón manual "Reenganchar por WhatsApp" de Alumnos en riesgo sigue funcionando igual (abre `wa.me`). Cada automatización se prende **por grupo** (ficha del grupo → "Mensajes automáticos por WhatsApp"); vienen apagadas. El botón manual "Reenganchar por WhatsApp" de Alumnos en riesgo sigue funcionando igual (abre `wa.me`).
@@ -235,12 +236,15 @@ En local, las dos URLs pasan por el mismo túnel que Mercado Pago (`ngrok http -
### Templates ### Templates
Meta solo deja escribir fuera de la ventana de 24 h con **templates aprobados**, y los aprueba **por cuenta** (WABA). Por eso, al vincular, se envían los dos de `providers/kapso/templates.ts` (`es_AR`, parámetros NAMED): Meta solo deja escribir fuera de la ventana de 24 h con **templates aprobados**, y los aprueba **por cuenta** (WABA). Por eso, al vincular, se envían los tres de `providers/kapso/templates.ts` (`es_AR`, parámetros NAMED):
| Template | Categoría | Parámetros | | Template | Categoría | Parámetros |
| --- | --- | --- | | --- | --- | --- |
| `gruperly_payment_reminder` | `UTILITY` | `student_name`, `group_name`, `amount`, `due_date`, `payment_link` | | `gruperly_payment_reminder` | `UTILITY` | `student_name`, `group_name`, `amount`, `due_date`, `payment_link` |
| `gruperly_reengagement` | `MARKETING` | `student_name`, `group_name` | | `gruperly_reengagement` | `MARKETING` | `student_name`, `group_name` |
| `gruperly_payment_link` | `UTILITY` | `student_name` (el pagador), `detail`, `amount`, `due_date`, `payment_link` |
Las cuentas vinculadas antes de que existiera `gruperly_payment_link` lo reciben solas: `SyncKapsoTemplates` reenvía mientras la cuenta tenga menos templates que `KAPSO_TEMPLATES`.
- La revisión tarda hasta unas 24 h. Mientras tanto, Ajustes muestra "En revisión por Meta" y el switch del grupo no se puede prender. - La revisión tarda hasta unas 24 h. Mientras tanto, Ajustes muestra "En revisión por Meta" y el switch del grupo no se puede prender.
- **No se editan**: cambiar el texto implica un nombre nuevo (`…_v2`) y otra revisión. El cuerpo sigue el copy de `lib/render-message.ts` (OpenWA); si cambia uno, cambiar el otro. - **No se editan**: cambiar el texto implica un nombre nuevo (`…_v2`) y otra revisión. El cuerpo sigue el copy de `lib/render-message.ts` (OpenWA); si cambia uno, cambiar el otro.

View File

@@ -30,6 +30,8 @@ export const AttendeeDtoSchema = z.object({
guardianPhone: z.string().nullable(), guardianPhone: z.string().nullable(),
guardianEmail: z.string().nullable(), guardianEmail: z.string().nullable(),
notes: z.string().nullable(), notes: z.string().nullable(),
/** Off: pays by transfer, so automatic charges create the fee without a Mercado Pago link. */
payWithMercadoPago: z.boolean(),
notifyToken: z.string().nullable().optional(), notifyToken: z.string().nullable().optional(),
createdAt: isoDateTimeSchema, createdAt: isoDateTimeSchema,
updatedAt: isoDateTimeSchema, updatedAt: isoDateTimeSchema,
@@ -93,6 +95,7 @@ const EditableAttendeeFieldsSchema = z.object({
.or(z.literal('')) .or(z.literal(''))
.nullable(), .nullable(),
notes: z.string().trim().nullable(), notes: z.string().trim().nullable(),
payWithMercadoPago: z.boolean(),
}); });
export const UpdateAttendeeSchema = EditableAttendeeFieldsSchema.partial().refine( export const UpdateAttendeeSchema = EditableAttendeeFieldsSchema.partial().refine(

View File

@@ -20,6 +20,11 @@ export const PaymentDtoSchema = z.object({
status: paymentStatusSchema, status: paymentStatusSchema,
description: z.string().nullable(), description: z.string().nullable(),
checkoutUrl: z.string().nullable(), checkoutUrl: z.string().nullable(),
// Combined link (automatic monthly charge): how many fees it pays at once.
checkoutId: z.string().nullable(),
checkoutItemCount: z.number().int().nullable(),
// Month of an automatic charge ("2026-12"); null for manual fees.
periodKey: z.string().nullable(),
dueDate: isoDateTimeSchema, dueDate: isoDateTimeSchema,
paidAt: isoDateTimeSchema.nullable(), paidAt: isoDateTimeSchema.nullable(),
createdAt: isoDateTimeSchema, createdAt: isoDateTimeSchema,
@@ -72,3 +77,53 @@ export const CreatePaymentsBatchResultSchema = z.object({
items: z.array(PaymentBatchItemSchema), items: z.array(PaymentBatchItemSchema),
}); });
export type CreatePaymentsBatchResult = z.output<typeof CreatePaymentsBatchResultSchema>; export type CreatePaymentsBatchResult = z.output<typeof CreatePaymentsBatchResultSchema>;
// Automatic monthly charges: on `chargeDay` (1-28, teacher's time zone) a fee
// for every active member of the teacher's monthly groups, with one Mercado
// Pago link per payer (the adult in charge for kids).
export const AUTO_CHARGE_MAX_DAY = 28;
export const AUTO_CHARGE_DEFAULT_DUE_IN_DAYS = 10;
export const AUTO_CHARGE_MAX_DUE_IN_DAYS = 31;
export const UpdateAutoChargeSettingsSchema = z
.strictObject({
enabled: z.boolean().optional(),
chargeDay: z.number().int().min(1, 'payment.chargeDayRange').max(AUTO_CHARGE_MAX_DAY, 'payment.chargeDayRange').optional(),
dueInDays: z
.number()
.int()
.min(1, 'payment.dueInDaysRange')
.max(AUTO_CHARGE_MAX_DUE_IN_DAYS, 'payment.dueInDaysRange')
.optional(),
sendWhatsapp: z.boolean().optional(),
})
.refine((value) => Object.values(value).some((field) => field !== undefined), {
message: 'payment.autoChargeRequired',
});
export type UpdateAutoChargeSettings = z.output<typeof UpdateAutoChargeSettingsSchema>;
export const paymentRunStatusSchema = z.enum(['RUNNING', 'DONE', 'SKIPPED']);
export type PaymentRunStatus = z.output<typeof paymentRunStatusSchema>;
export const PaymentRunDtoSchema = z.object({
periodKey: z.string(),
status: paymentRunStatusSchema,
skipReason: z.string().nullable(),
fees: z.number().int(),
checkouts: z.number().int(),
linked: z.number().int(),
failed: z.number().int(),
sent: z.number().int(),
createdAt: isoDateTimeSchema,
});
export type PaymentRunDto = z.output<typeof PaymentRunDtoSchema>;
export const AutoChargeSettingsDtoSchema = z.object({
enabled: z.boolean(),
chargeDay: z.number().int(),
dueInDays: z.number().int(),
sendWhatsapp: z.boolean(),
/** Local date (YYYY-MM-DD) of the next run; null while it is off. */
nextRunDate: z.string().nullable(),
lastRun: PaymentRunDtoSchema.nullable(),
});
export type AutoChargeSettingsDto = z.output<typeof AutoChargeSettingsDtoSchema>;

View File

@@ -181,6 +181,16 @@ export const StudentFeeSchema = z.object({
dueDate: isoDateTimeSchema, dueDate: isoDateTimeSchema,
status: studentFeeStatusSchema, status: studentFeeStatusSchema,
checkoutUrl: z.string().nullable(), checkoutUrl: z.string().nullable(),
// Month of an automatic charge ("2026-12"); null for fees created by hand.
periodKey: z.string().nullable(),
// The link pays this fee together with others of the same payer (siblings,
// other groups): its total and what it includes.
checkout: z
.object({
total: z.number(),
items: z.array(z.object({ groupName: z.string(), studentName: z.string() })),
})
.nullable(),
}); });
export type StudentFee = z.output<typeof StudentFeeSchema>; export type StudentFee = z.output<typeof StudentFeeSchema>;

View File

@@ -17,7 +17,7 @@ export const whatsappAccountStatusSchema = z.enum([
]); ]);
export type WhatsappAccountStatus = z.output<typeof whatsappAccountStatusSchema>; export type WhatsappAccountStatus = z.output<typeof whatsappAccountStatusSchema>;
export const whatsappMessageKindSchema = z.enum(['PAYMENT_REMINDER', 'REENGAGEMENT']); export const whatsappMessageKindSchema = z.enum(['PAYMENT_REMINDER', 'REENGAGEMENT', 'PAYMENT_LINK']);
export type WhatsappMessageKind = z.output<typeof whatsappMessageKindSchema>; export type WhatsappMessageKind = z.output<typeof whatsappMessageKindSchema>;
// Whether automated messages of one kind can go out right now. // Whether automated messages of one kind can go out right now.
@@ -75,6 +75,7 @@ export const WhatsappStatusDtoSchema = z.object({
readiness: z.object({ readiness: z.object({
PAYMENT_REMINDER: whatsappReadinessSchema, PAYMENT_REMINDER: whatsappReadinessSchema,
REENGAGEMENT: whatsappReadinessSchema, REENGAGEMENT: whatsappReadinessSchema,
PAYMENT_LINK: whatsappReadinessSchema,
}), }),
}); });
export type WhatsappStatusDto = z.output<typeof WhatsappStatusDtoSchema>; export type WhatsappStatusDto = z.output<typeof WhatsappStatusDtoSchema>;