From ac98495a6e31f6806d874e42128aa673ada27a6d Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Wed, 11 Nov 2026 15:08:48 -0300 Subject: [PATCH] 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_, 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 --- AGENTS.md | 6 + .../20261111172319_auto_charges/migration.sql | 114 +++++++ apps/backend/prisma/models/auth.prisma | 3 + apps/backend/prisma/models/domain.prisma | 50 +-- apps/backend/prisma/models/payments.prisma | 91 ++++++ apps/backend/prisma/models/whatsapp.prisma | 12 +- apps/backend/src/http/session-auth.ts | 2 +- .../src/modules/attendees/lib/helpers.ts | 3 + apps/backend/src/modules/mp/lib/index.ts | 2 + apps/backend/src/modules/mp/lib/mp-http.ts | 51 ++- .../features/auto-charge-settings/route.ts | 23 ++ .../features/auto-charge-settings/use-case.ts | 90 ++++++ .../auto-charge/generate-monthly-charges.ts | 195 ++++++++++++ .../payments/features/get-all/use-case.ts | 1 + .../payments/features/renew/use-case.ts | 46 ++- .../payments/features/reported/use-case.ts | 14 + .../payments/features/webhook/route.ts | 9 +- .../payments/features/webhook/use-case.ts | 37 ++- .../src/modules/payments/jobs/index.ts | 1 + .../payments/jobs/reconcile-payments.ts | 33 +- .../modules/payments/jobs/run-auto-charges.ts | 50 +++ .../src/modules/payments/jobs/schedule.ts | 16 + .../payments/lib/auto-charge-schedule.ts | 84 +++++ .../src/modules/payments/lib/checkouts.ts | 217 +++++++++++++ .../src/modules/payments/lib/helpers.ts | 14 + .../backend/src/modules/payments/lib/index.ts | 17 +- apps/backend/src/modules/payments/routes.ts | 2 + .../student-portal/features/fees/use-case.ts | 26 ++ .../whatsapp/features/status/use-case.ts | 5 +- .../whatsapp/jobs/send-payment-links.ts | 128 ++++++++ .../whatsapp/jobs/send-payment-reminders.ts | 49 ++- .../whatsapp/jobs/sync-kapso-templates.ts | 3 +- .../src/modules/whatsapp/lib/dispatch.ts | 10 +- .../modules/whatsapp/lib/render-message.ts | 6 + .../whatsapp/providers/kapso/templates.ts | 46 ++- .../whatsapp/providers/messaging-provider.ts | 10 + apps/backend/test/attendee-get-by-id.test.ts | 1 + apps/backend/test/attendees.test.ts | 2 + .../backend/test/payments-auto-charge.test.ts | 290 ++++++++++++++++++ apps/backend/test/payments-checkouts.test.ts | 239 +++++++++++++++ apps/backend/test/payments-reconcile.test.ts | 54 ++++ apps/backend/test/payments-renew.test.ts | 3 +- apps/backend/test/payments.test.ts | 4 + apps/backend/test/session-auth.test.ts | 3 + apps/backend/test/whatsapp-core.test.ts | 3 +- apps/backend/test/whatsapp-jobs.test.ts | 31 ++ apps/backend/test/whatsapp-providers.test.ts | 3 +- .../AttendeePaymentsSection.tsx | 29 +- apps/web/src/features/payments/PaymentRow.tsx | 5 + apps/web/src/features/payments/copy.ts | 15 +- .../settings/AutoChargeSettingsCard.tsx | 207 +++++++++++++ .../src/features/settings/SettingsView.tsx | 3 + apps/web/src/features/student-app/FeeCard.tsx | 19 +- .../student-app/StudentPaymentsView.tsx | 29 +- apps/web/src/features/student-app/format.ts | 15 +- .../features/whatsapp/WhatsappStatusCard.tsx | 4 + apps/web/src/features/whatsapp/copy.ts | 2 +- .../src/i18n/locales/en/attendeeDetail.json | 7 +- apps/web/src/i18n/locales/en/payments.json | 4 +- apps/web/src/i18n/locales/en/settings.json | 32 ++ apps/web/src/i18n/locales/en/student.json | 8 +- apps/web/src/i18n/locales/en/validation.json | 5 +- apps/web/src/i18n/locales/en/whatsapp.json | 3 +- .../i18n/locales/es-419/attendeeDetail.json | 7 +- .../web/src/i18n/locales/es-419/payments.json | 4 +- .../web/src/i18n/locales/es-419/settings.json | 32 ++ apps/web/src/i18n/locales/es-419/student.json | 8 +- .../src/i18n/locales/es-419/validation.json | 5 +- .../web/src/i18n/locales/es-419/whatsapp.json | 3 +- .../i18n/locales/es-AR/attendeeDetail.json | 7 +- apps/web/src/i18n/locales/es-AR/payments.json | 4 +- apps/web/src/i18n/locales/es-AR/settings.json | 32 ++ apps/web/src/i18n/locales/es-AR/student.json | 8 +- .../src/i18n/locales/es-AR/validation.json | 5 +- apps/web/src/i18n/locales/es-AR/whatsapp.json | 3 +- .../i18n/locales/pt-BR/attendeeDetail.json | 7 +- apps/web/src/i18n/locales/pt-BR/payments.json | 4 +- apps/web/src/i18n/locales/pt-BR/settings.json | 32 ++ apps/web/src/i18n/locales/pt-BR/student.json | 8 +- .../src/i18n/locales/pt-BR/validation.json | 5 +- apps/web/src/i18n/locales/pt-BR/whatsapp.json | 3 +- apps/web/src/lib/api.ts | 10 + docs/whatsapp.md | 8 +- packages/shared/src/schemas/attendees.ts | 3 + packages/shared/src/schemas/payments.ts | 57 +++- packages/shared/src/schemas/student-portal.ts | 10 + packages/shared/src/schemas/whatsapp.ts | 3 +- 87 files changed, 2648 insertions(+), 106 deletions(-) create mode 100644 apps/backend/prisma/migrations/20261111172319_auto_charges/migration.sql create mode 100644 apps/backend/prisma/models/payments.prisma create mode 100644 apps/backend/src/modules/payments/features/auto-charge-settings/route.ts create mode 100644 apps/backend/src/modules/payments/features/auto-charge-settings/use-case.ts create mode 100644 apps/backend/src/modules/payments/features/auto-charge/generate-monthly-charges.ts create mode 100644 apps/backend/src/modules/payments/jobs/run-auto-charges.ts create mode 100644 apps/backend/src/modules/payments/lib/auto-charge-schedule.ts create mode 100644 apps/backend/src/modules/payments/lib/checkouts.ts create mode 100644 apps/backend/src/modules/whatsapp/jobs/send-payment-links.ts create mode 100644 apps/backend/test/payments-auto-charge.test.ts create mode 100644 apps/backend/test/payments-checkouts.test.ts create mode 100644 apps/web/src/features/settings/AutoChargeSettingsCard.tsx diff --git a/AGENTS.md b/AGENTS.md index 2fc16e3..2f9d12c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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`. - **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**. +- **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_` (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: 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//`. 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. diff --git a/apps/backend/prisma/migrations/20261111172319_auto_charges/migration.sql b/apps/backend/prisma/migrations/20261111172319_auto_charges/migration.sql new file mode 100644 index 0000000..36214f4 --- /dev/null +++ b/apps/backend/prisma/migrations/20261111172319_auto_charges/migration.sql @@ -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; diff --git a/apps/backend/prisma/models/auth.prisma b/apps/backend/prisma/models/auth.prisma index c7cc6eb..633a3b2 100644 --- a/apps/backend/prisma/models/auth.prisma +++ b/apps/backend/prisma/models/auth.prisma @@ -31,6 +31,9 @@ model User { subscription BillingSubscription? studentAccounts StudentAccount[] @relation("StudentAccountsCreated") people Person[] @relation("OwnerPeople") + autoCharge AutoChargeSettings? + paymentRuns PaymentRun[] + checkouts PaymentCheckout[] @@map("users") } diff --git a/apps/backend/prisma/models/domain.prisma b/apps/backend/prisma/models/domain.prisma index bed0a6b..e99e0ab 100644 --- a/apps/backend/prisma/models/domain.prisma +++ b/apps/backend/prisma/models/domain.prisma @@ -1,24 +1,24 @@ // Domain models model Group { - id String @id @default(cuid()) + id String @id @default(cuid()) name String description String? days WeekDay[] time String? capacity Int? - price Decimal? @db.Decimal(10, 2) - billingType BillingType? @map("billing_type") - dueDay Int? @map("due_day") + price Decimal? @db.Decimal(10, 2) + billingType BillingType? @map("billing_type") + dueDay Int? @map("due_day") // Weekly WhatsApp automations, off until the teacher turns them on. - autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders") - autoReengagement Boolean @default(false) @map("auto_reengagement") + autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders") + autoReengagement Boolean @default(false) @map("auto_reengagement") // KIDS: each student is a kid and the contact is the adult in charge. audience GroupAudience @default(ADULTS) - inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token") - createdById String @map("created_by_id") - createdAt DateTime @default(now()) @map("created_at") - updatedAt DateTime @updatedAt @map("updated_at") + inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token") + createdById String @map("created_by_id") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey") members GroupMember[] @@ -85,18 +85,23 @@ enum AttendeeStatus { // teacher through a hand-written partial index (`people_owner_phone_key`, // `WHERE phone IS NOT NULL`): Prisma does not model it. model Person { - id String @id @default(cuid()) - createdById String @map("created_by_id") - fullName String @map("full_name") - email String? - phone String? - notes String? - createdAt DateTime @default(now()) @map("created_at") - updatedAt DateTime @updatedAt @map("updated_at") + id String @id @default(cuid()) + createdById String @map("created_by_id") + fullName String @map("full_name") + email String? + phone String? + notes String? + // Automatic monthly charges only build a Mercado Pago link for people with + // this on. Off: they prefer to transfer (the fee is still created). + payWithMercadoPago Boolean @default(true) @map("pay_with_mercado_pago") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade) attendees Attendee[] studentAccounts StudentAccountPerson[] + // As the payer of combined Mercado Pago links (themselves or their kids). + checkouts PaymentCheckout[] // As a kid: the adult in charge (one in v1, enforced by the code). guardians PersonGuardian[] @relation("GuardianChild") // As the adult in charge: their kids. An adult has no memberships of their own. @@ -184,16 +189,25 @@ model Payment { mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id") mpPaymentId String? @map("mp_payment_id") paidAt DateTime? @map("paid_at") + // Combined link (automatic monthly charges): the fee is paid through it and + // `checkoutUrl` is a copy of the checkout's link. + checkoutId String? @map("checkout_id") + // Month of an automatic charge ("2026-12"). Unique per attendee through a + // hand-written partial index (`payments_attendee_period_key`, + // `WHERE period_key IS NOT NULL`): Prisma does not model it. + periodKey String? @map("period_key") createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey") attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey") + checkout PaymentCheckout? @relation(fields: [checkoutId], references: [id], onDelete: SetNull) outboundMessages OutboundMessage[] reportedItems ReportedPaymentItem[] @@index([groupId], map: "payments_groupId_idx") @@index([attendeeId], map: "payments_attendeeId_idx") + @@index([checkoutId]) @@map("payments") } diff --git a/apps/backend/prisma/models/payments.prisma b/apps/backend/prisma/models/payments.prisma new file mode 100644 index 0000000..7a8d682 --- /dev/null +++ b/apps/backend/prisma/models/payments.prisma @@ -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_`. + +// 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") +} diff --git a/apps/backend/prisma/models/whatsapp.prisma b/apps/backend/prisma/models/whatsapp.prisma index e653073..90f0985 100644 --- a/apps/backend/prisma/models/whatsapp.prisma +++ b/apps/backend/prisma/models/whatsapp.prisma @@ -19,6 +19,8 @@ enum WhatsappAccountStatus { enum WhatsappMessageKind { PAYMENT_REMINDER REENGAGEMENT + // The monthly combined payment link, sent when it is generated. + PAYMENT_LINK } enum OutboundMessageStatus { @@ -92,9 +94,10 @@ model OutboundMessage { groupId String @map("group_id") attendeeId String @map("attendee_id") paymentId String? @map("payment_id") + checkoutId String? @map("checkout_id") kind WhatsappMessageKind provider MessagingProviderId - // ISO week the job ran for, e.g. "2026-W43". + // ISO week the job ran for, e.g. "2026-W43"; the month ("2026-12") for PAYMENT_LINK. periodKey String @map("period_key") toPhone String @map("to_phone") providerMessageId String? @map("provider_message_id") @@ -105,9 +108,10 @@ model OutboundMessage { createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") - group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "outbound_messages_groupId_fkey") - attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "outbound_messages_attendeeId_fkey") - payment Payment? @relation(fields: [paymentId], references: [id], onDelete: SetNull, map: "outbound_messages_paymentId_fkey") + group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "outbound_messages_groupId_fkey") + attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "outbound_messages_attendeeId_fkey") + payment Payment? @relation(fields: [paymentId], references: [id], onDelete: SetNull, map: "outbound_messages_paymentId_fkey") + checkout PaymentCheckout? @relation(fields: [checkoutId], references: [id], onDelete: SetNull) @@unique([kind, attendeeId, periodKey], map: "outbound_messages_kind_attendeeId_periodKey_key") @@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key") diff --git a/apps/backend/src/http/session-auth.ts b/apps/backend/src/http/session-auth.ts index bdb04bf..8657f32 100644 --- a/apps/backend/src/http/session-auth.ts +++ b/apps/backend/src/http/session-auth.ts @@ -49,7 +49,7 @@ export function isPublicApiRequest(method: string, path: string): boolean { } // Mercado Pago notifications about a Checkout Pro payment: no session; the // 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; } // Back from the Pro checkout: only redirects to the web, which has the session. diff --git a/apps/backend/src/modules/attendees/lib/helpers.ts b/apps/backend/src/modules/attendees/lib/helpers.ts index 4fa8664..8961541 100644 --- a/apps/backend/src/modules/attendees/lib/helpers.ts +++ b/apps/backend/src/modules/attendees/lib/helpers.ts @@ -8,6 +8,7 @@ export const personContactSelect = { email: true, phone: true, notes: true, + payWithMercadoPago: true, ...guardianSelect, } as const; @@ -20,6 +21,7 @@ export type PersonContactRecord = { email: string | null; phone: string | null; notes: string | null; + payWithMercadoPago?: boolean; guardians?: { guardian: GuardianContact }[]; }; @@ -69,6 +71,7 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto { phone: record.person.phone, ...guardianFields(record.person), notes: record.person.notes, + payWithMercadoPago: record.person.payWithMercadoPago ?? true, notifyToken: record.notifyToken ?? null, createdAt: record.createdAt.toISOString(), updatedAt: record.updatedAt.toISOString(), diff --git a/apps/backend/src/modules/mp/lib/index.ts b/apps/backend/src/modules/mp/lib/index.ts index bcacbf4..80c5801 100644 --- a/apps/backend/src/modules/mp/lib/index.ts +++ b/apps/backend/src/modules/mp/lib/index.ts @@ -9,9 +9,11 @@ export { } from './crypto'; export { createCheckoutPreference, + expireCheckoutPreference, MP_API_URL, type MpCreatePreferenceInput, type MpPreference, + type MpPreferenceItem, type MpSearchedPayment, searchMpPaymentByExternalReference, } from './mp-http'; diff --git a/apps/backend/src/modules/mp/lib/mp-http.ts b/apps/backend/src/modules/mp/lib/mp-http.ts index 7ddf40e..7aaaeb8 100644 --- a/apps/backend/src/modules/mp/lib/mp-http.ts +++ b/apps/backend/src/modules/mp/lib/mp-http.ts @@ -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 // account: no platform_id of ours and no fee split. +export type MpPreferenceItem = { title: string; unitPrice: number }; + export type MpCreatePreferenceInput = { title: string; 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; externalReference: string; /** Where the buyer lands after paying (pending/success/failure). */ @@ -58,14 +65,14 @@ export async function createCheckoutPreference( Authorization: `Bearer ${accessToken}`, }, body: JSON.stringify({ - items: [ - { - title: input.title, + items: (input.items?.length ? input.items : [{ title: input.title, unitPrice: input.unitPrice }]).map( + (item) => ({ + title: item.title, currency_id: input.currencyId, quantity: 1, - unit_price: input.unitPrice, - }, - ], + unit_price: item.unitPrice, + }), + ), external_reference: input.externalReference, ...(isPublicHttpsUrl(input.backUrl) ? { auto_return: 'approved' } : {}), ...(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 { + 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 = { id: string; status: string; diff --git a/apps/backend/src/modules/payments/features/auto-charge-settings/route.ts b/apps/backend/src/modules/payments/features/auto-charge-settings/route.ts new file mode 100644 index 0000000..a3e04c2 --- /dev/null +++ b/apps/backend/src/modules/payments/features/auto-charge-settings/route.ts @@ -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; diff --git a/apps/backend/src/modules/payments/features/auto-charge-settings/use-case.ts b/apps/backend/src/modules/payments/features/auto-charge-settings/use-case.ts new file mode 100644 index 0000000..7cd5d3c --- /dev/null +++ b/apps/backend/src/modules/payments/features/auto-charge-settings/use-case.ts @@ -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; + planGuard?: Pick; + 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> { + return ok(await this.load(ownerId)); + } + + async update(ownerId: string, input: UpdateAutoChargeSettings): Promise> { + 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 { + 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, + }; + } +} diff --git a/apps/backend/src/modules/payments/features/auto-charge/generate-monthly-charges.ts b/apps/backend/src/modules/payments/features/auto-charge/generate-monthly-charges.ts new file mode 100644 index 0000000..a4f4180 --- /dev/null +++ b/apps/backend/src/modules/payments/features/auto-charge/generate-monthly-charges.ts @@ -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; + /** Sends the generated links by WhatsApp; returns how many went out. */ + sendLinks?: (ownerId: string, checkoutIds: string[]) => Promise; + 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 { + 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 => { + 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(); + 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 { + const totals = await new SendPaymentLinks().execute(ownerId, checkoutIds); + return totals.sent; +} diff --git a/apps/backend/src/modules/payments/features/get-all/use-case.ts b/apps/backend/src/modules/payments/features/get-all/use-case.ts index 8552e41..90375c5 100644 --- a/apps/backend/src/modules/payments/features/get-all/use-case.ts +++ b/apps/backend/src/modules/payments/features/get-all/use-case.ts @@ -37,6 +37,7 @@ export class ListPayments { include: { group: { select: { name: true, price: true } }, attendee: { select: { person: { select: { fullName: true } } } }, + checkout: { select: { _count: { select: { payments: true } } } }, }, skip: getPaginationOffset(query), take: query.pageSize, diff --git a/apps/backend/src/modules/payments/features/renew/use-case.ts b/apps/backend/src/modules/payments/features/renew/use-case.ts index 755bf81..ba9f47e 100644 --- a/apps/backend/src/modules/payments/features/renew/use-case.ts +++ b/apps/backend/src/modules/payments/features/renew/use-case.ts @@ -13,10 +13,17 @@ import { logger } from '@/logger'; import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { getMpAccessToken } from '@/modules/mp'; 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 = { - db?: Pick; + db?: Pick; createPreference?: typeof createCheckoutPreference; getToken?: typeof getMpAccessToken; webOrigin?: string; @@ -39,6 +46,7 @@ export class RenewPaymentLink { where: { id: paymentId }, include: { attendee: { select: { person: { select: { fullName: true } } } }, + checkout: { select: { status: true, _count: { select: { payments: true } } } }, group: { select: { name: true, @@ -86,7 +94,23 @@ export class RenewPaymentLink { 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; let preference: { initPoint: string; id: string }; @@ -97,7 +121,7 @@ export class RenewPaymentLink { currencyId: currency, externalReference: payment.id, backUrl, - notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id), + notificationUrl: paymentNotificationUrl(apiOrigin, payment.id), }); } catch (error) { if (error instanceof Error) { @@ -108,13 +132,17 @@ export class RenewPaymentLink { const updated = await db.payment.update({ where: { id: payment.id }, - data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id }, - include: { - attendee: { select: { person: { select: { fullName: true } } } }, - group: { select: { name: true, price: true } }, - }, + // Out of a superseded combined link: from now on it is a single fee. + data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id, checkoutId: null }, + include: paymentDtoInclude, }); return ok(toPaymentDto(updated as unknown as PaymentRecord)); } + + private async reload(paymentId: string): Promise> { + 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)); + } } \ No newline at end of file diff --git a/apps/backend/src/modules/payments/features/reported/use-case.ts b/apps/backend/src/modules/payments/features/reported/use-case.ts index 10da111..c23b3e5 100644 --- a/apps/backend/src/modules/payments/features/reported/use-case.ts +++ b/apps/backend/src/modules/payments/features/reported/use-case.ts @@ -7,6 +7,12 @@ import { type FileStorage, getFileStorage } from '@/lib/storage'; import { buildGroupWhereForUser } from '@/modules/groups/lib'; import { storageNotAvailableProblem } from '@/modules/student-portal/lib/problems'; 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'; export const RECEIPT_URL_TTL_SECONDS = 5 * 60; @@ -18,6 +24,7 @@ type ReportedDeps = { storage?: FileStorage | null; notify?: ReviewNotifier; now?: Date; + expirePreferences?: (preferences: SupersededPreference[], deps?: ExpirePreferencesDeps) => Promise; }; const reportSelect = { @@ -155,6 +162,7 @@ export class ReportedPayments { const now = this.now; const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); + let superseded: SupersededPreference[] = []; const reviewed = await unitOfWork.executeResult(async (tx) => { const claimed = await tx.reportedPayment.updateMany({ 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'] } }, 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); }); if (!reviewed.ok) return reviewed; + if (superseded.length > 0) { + void (this.deps.expirePreferences ?? expireSupersededPreferences)(superseded); + } + (this.deps.notify ?? scheduleReviewNotification)(reportId, now); return this.load(reportId); } diff --git a/apps/backend/src/modules/payments/features/webhook/route.ts b/apps/backend/src/modules/payments/features/webhook/route.ts index 2f5ea7e..1b8f2e5 100644 --- a/apps/backend/src/modules/payments/features/webhook/route.ts +++ b/apps/backend/src/modules/payments/features/webhook/route.ts @@ -1,6 +1,6 @@ import { Hono } from 'hono'; import { problemJson } from '@/http/problem-details'; -import { HandleMpPaymentNotification } from './use-case'; +import { HandleMpCheckoutNotification, HandleMpPaymentNotification } from './use-case'; const route = new Hono(); @@ -14,4 +14,11 @@ route.post('/webhooks/mp/:paymentId', async (c) => { return c.json({ received: true }); }); +/** Same, for a combined link (`chk_`): 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; diff --git a/apps/backend/src/modules/payments/features/webhook/use-case.ts b/apps/backend/src/modules/payments/features/webhook/use-case.ts index 0f0a0bd..3d37464 100644 --- a/apps/backend/src/modules/payments/features/webhook/use-case.ts +++ b/apps/backend/src/modules/payments/features/webhook/use-case.ts @@ -5,7 +5,13 @@ import { mpProviderErrorProblem } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; import { logger } from '@/logger'; 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 & { db?: Pick; @@ -43,3 +49,32 @@ export class HandleMpPaymentNotification { } } } + +type HandleMpCheckoutNotificationDeps = ConfirmMpCheckoutDeps & { + db?: Pick; +}; + +/** `HandleMpPaymentNotification` for a combined link. */ +export class HandleMpCheckoutNotification { + constructor(private readonly deps: HandleMpCheckoutNotificationDeps = {}) {} + + async execute(checkoutId: string): Promise> { + 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()); + } + } +} diff --git a/apps/backend/src/modules/payments/jobs/index.ts b/apps/backend/src/modules/payments/jobs/index.ts index 5794244..d802781 100644 --- a/apps/backend/src/modules/payments/jobs/index.ts +++ b/apps/backend/src/modules/payments/jobs/index.ts @@ -6,4 +6,5 @@ export { ReconcilePayments, type ReconcilePaymentsResult, } from './reconcile-payments'; +export { RunAutoCharges, type RunAutoChargesResult } from './run-auto-charges'; export { startPaymentJobs } from './schedule'; \ No newline at end of file diff --git a/apps/backend/src/modules/payments/jobs/reconcile-payments.ts b/apps/backend/src/modules/payments/jobs/reconcile-payments.ts index 9e8877a..2abd164 100644 --- a/apps/backend/src/modules/payments/jobs/reconcile-payments.ts +++ b/apps/backend/src/modules/payments/jobs/reconcile-payments.ts @@ -3,7 +3,7 @@ import prisma from '@/lib/prisma'; import { logger } from '@/logger'; import { getMpAccessToken } from '@/modules/mp'; import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib'; -import { confirmMpPayment } from '../lib'; +import { confirmMpCheckout, confirmMpPayment } from '../lib'; /** * Pulls payments from Mercado Pago. The notification @@ -13,6 +13,8 @@ import { confirmMpPayment } from '../lib'; */ const RECONCILE_AFTER_MS = 5 * 60 * 1000; 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 = { paid: number; @@ -40,6 +42,8 @@ export class ReconcilePayments { where: { status: 'PENDING', 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) }, }, 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; } } \ No newline at end of file diff --git a/apps/backend/src/modules/payments/jobs/run-auto-charges.ts b/apps/backend/src/modules/payments/jobs/run-auto-charges.ts new file mode 100644 index 0000000..14011df --- /dev/null +++ b/apps/backend/src/modules/payments/jobs/run-auto-charges.ts @@ -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; + 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 { + 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; + } +} diff --git a/apps/backend/src/modules/payments/jobs/schedule.ts b/apps/backend/src/modules/payments/jobs/schedule.ts index 1c5c896..708e6fc 100644 --- a/apps/backend/src/modules/payments/jobs/schedule.ts +++ b/apps/backend/src/modules/payments/jobs/schedule.ts @@ -1,9 +1,12 @@ import { logger } from '@/logger'; import { MarkOverduePayments } from './mark-overdue-payments'; import { ReconcilePayments } from './reconcile-payments'; +import { RunAutoCharges } from './run-auto-charges'; const RECONCILE_CRON = '*/15 * * * *'; 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 @@ -37,4 +40,17 @@ export function startPaymentJobs(): void { }, { tz: 'UTC' }, ).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(); } \ No newline at end of file diff --git a/apps/backend/src/modules/payments/lib/auto-charge-schedule.ts b/apps/backend/src/modules/payments/lib/auto-charge-schedule.ts new file mode 100644 index 0000000..e15bf3a --- /dev/null +++ b/apps/backend/src/modules/payments/lib/auto-charge-schedule.ts @@ -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): 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); +} diff --git a/apps/backend/src/modules/payments/lib/checkouts.ts b/apps/backend/src/modules/payments/lib/checkouts.ts new file mode 100644 index 0000000..7c34986 --- /dev/null +++ b/apps/backend/src/modules/payments/lib/checkouts.ts @@ -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_`, 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; + +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 { + 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, + checkout: { id: string; ownerId: string }, + deps: ConfirmMpCheckoutDeps = {}, +): Promise { + 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, + paymentIds: string[], +): Promise { + 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 { + 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; diff --git a/apps/backend/src/modules/payments/lib/helpers.ts b/apps/backend/src/modules/payments/lib/helpers.ts index 3da80bd..8329c8e 100644 --- a/apps/backend/src/modules/payments/lib/helpers.ts +++ b/apps/backend/src/modules/payments/lib/helpers.ts @@ -1,9 +1,17 @@ +import type { Prisma } from '@generated/prisma/client'; import type { PaymentDto } from '@gruperly/shared'; /* Where Mercado Pago sends whoever paid a Checkout Pro link: the student app (without a student session it falls through to /access). */ 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 = { id: string; groupId: string; @@ -13,6 +21,9 @@ export type PaymentRecord = { status: PaymentDto['status']; description: string | null; checkoutUrl: string | null; + checkoutId?: string | null; + periodKey?: string | null; + checkout?: { _count: { payments: number } } | null; dueDate: Date; paidAt: Date | null; createdAt: Date; @@ -33,6 +44,9 @@ export function toPaymentDto(record: PaymentRecord): PaymentDto { status: record.status, description: record.description, checkoutUrl: record.checkoutUrl, + checkoutId: record.checkoutId ?? null, + checkoutItemCount: record.checkout?._count.payments ?? null, + periodKey: record.periodKey ?? null, dueDate: record.dueDate.toISOString(), paidAt: record.paidAt ? record.paidAt.toISOString() : null, createdAt: record.createdAt.toISOString(), diff --git a/apps/backend/src/modules/payments/lib/index.ts b/apps/backend/src/modules/payments/lib/index.ts index 6131111..2fee82a 100644 --- a/apps/backend/src/modules/payments/lib/index.ts +++ b/apps/backend/src/modules/payments/lib/index.ts @@ -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 { type ConfirmMpPaymentDeps, type ConfirmMpPaymentOutcome, confirmMpPayment, paymentNotificationUrl, } from './confirm-mp-payment'; -export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers'; +export { CHECKOUT_BACK_PATH, type PaymentRecord, paymentDtoInclude, toPaymentDto } from './helpers'; diff --git a/apps/backend/src/modules/payments/routes.ts b/apps/backend/src/modules/payments/routes.ts index 0545a6f..870197c 100644 --- a/apps/backend/src/modules/payments/routes.ts +++ b/apps/backend/src/modules/payments/routes.ts @@ -1,4 +1,5 @@ import { Hono } from 'hono'; +import autoChargeSettingsRoute from './features/auto-charge-settings/route'; import getAllRoute from './features/get-all/route'; import renewRoute from './features/renew/route'; import reportedRoute from './features/reported/route'; @@ -8,6 +9,7 @@ import webhookRoute from './features/webhook/route'; const routes = new Hono(); routes.route('/', getAllRoute); +routes.route('/', autoChargeSettingsRoute); routes.route('/', reportedRoute); routes.route('/', transferDetailsRoute); routes.route('/', renewRoute); diff --git a/apps/backend/src/modules/student-portal/features/fees/use-case.ts b/apps/backend/src/modules/student-portal/features/fees/use-case.ts index 677bc31..e58e24d 100644 --- a/apps/backend/src/modules/student-portal/features/fees/use-case.ts +++ b/apps/backend/src/modules/student-portal/features/fees/use-case.ts @@ -40,6 +40,21 @@ export class GetStudentFees { dueDate: true, status: 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 } }, }, }), @@ -76,6 +91,17 @@ export class GetStudentFees { dueDate: payment.dueDate.toISOString(), status, 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, diff --git a/apps/backend/src/modules/whatsapp/features/status/use-case.ts b/apps/backend/src/modules/whatsapp/features/status/use-case.ts index 7d392e2..ca3a8b9 100644 --- a/apps/backend/src/modules/whatsapp/features/status/use-case.ts +++ b/apps/backend/src/modules/whatsapp/features/status/use-case.ts @@ -2,7 +2,6 @@ import type { PrismaClient } from '@generated/prisma/client'; import type { ProblemDetails, Result, - WhatsappReadiness, WhatsappStatusDto, } from '@gruperly/shared'; import { ok } from '@gruperly/shared'; @@ -21,6 +20,7 @@ type GetWhatsappStatusDeps = { const BLOCKED: WhatsappStatusDto['readiness'] = { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked', + PAYMENT_LINK: 'blocked', }; /** @@ -80,6 +80,7 @@ export class GetWhatsappStatus { ? { PAYMENT_REMINDER: await provider.readiness(account, 'PAYMENT_REMINDER'), REENGAGEMENT: await provider.readiness(account, 'REENGAGEMENT'), + PAYMENT_LINK: await provider.readiness(account, 'PAYMENT_LINK'), } : BLOCKED; @@ -91,7 +92,7 @@ function dto( provider: MessagingProvider, account: WhatsappAccountRecord & { connectedAt?: Date | null } | null, qrCode: string | null, - readiness: Record<'PAYMENT_REMINDER' | 'REENGAGEMENT', WhatsappReadiness>, + readiness: WhatsappStatusDto['readiness'], ): WhatsappStatusDto { const status = toVisibleWhatsappStatus(account, provider.id); return { diff --git a/apps/backend/src/modules/whatsapp/jobs/send-payment-links.ts b/apps/backend/src/modules/whatsapp/jobs/send-payment-links.ts new file mode 100644 index 0000000..c9f4a15 --- /dev/null +++ b/apps/backend/src/modules/whatsapp/jobs/send-payment-links.ts @@ -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; + provider?: MessagingProvider; + planGuard?: Pick; + now?: Date; + intervalMs?: number; + sleep?: (ms: number) => Promise; +}; + +/** "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 { + 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, + ); + } +} diff --git a/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts b/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts index 42c916b..f4cc350 100644 --- a/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts +++ b/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts @@ -15,6 +15,7 @@ import { formatAmount, formatDueDate } from '../lib/format'; import { getMessagingProvider } from '../providers'; import type { MessagingProvider } from '../providers/messaging-provider'; import { findEligibleAccounts } from './eligible-accounts'; +import { paymentLinkDetail } from './send-payment-links'; /** Only charges that are due within the coming week (or already overdue). */ 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. * * 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 { constructor(private readonly deps: SendPaymentRemindersDeps = {}) {} @@ -52,6 +55,7 @@ export class SendPaymentReminders { for (const { account, country, groups } of accounts) { const items: DispatchItem[] = []; + const seenCheckouts = new Set(); for (const group of groups) { const payments = await db.payment.findMany({ @@ -70,6 +74,21 @@ export class SendPaymentReminders { currency: true, dueDate: 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: { select: { id: true, person: { select: { fullName: true, phone: true, ...guardianSelect } } }, }, @@ -81,6 +100,34 @@ export class SendPaymentReminders { for (const payment of payments) { if (seen.has(payment.attendee.id) || !payment.checkoutUrl) continue; 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({ groupId: group.id, attendeeId: payment.attendee.id, diff --git a/apps/backend/src/modules/whatsapp/jobs/sync-kapso-templates.ts b/apps/backend/src/modules/whatsapp/jobs/sync-kapso-templates.ts index a11d1f7..475bdcb 100644 --- a/apps/backend/src/modules/whatsapp/jobs/sync-kapso-templates.ts +++ b/apps/backend/src/modules/whatsapp/jobs/sync-kapso-templates.ts @@ -3,6 +3,7 @@ import prisma from '@/lib/prisma'; import { logger } from '@/logger'; import { KapsoProvider } from '../providers'; import { getKapsoConfig } from '../providers/kapso/config'; +import { KAPSO_TEMPLATES } from '../providers/kapso/templates'; type SyncKapsoTemplatesDeps = { db?: Pick; @@ -12,7 +13,7 @@ type SyncKapsoTemplatesDeps = { export type SyncKapsoTemplatesResult = { checked: number; updated: number; failed: number }; /** 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 diff --git a/apps/backend/src/modules/whatsapp/lib/dispatch.ts b/apps/backend/src/modules/whatsapp/lib/dispatch.ts index 541003e..59d7c4a 100644 --- a/apps/backend/src/modules/whatsapp/lib/dispatch.ts +++ b/apps/backend/src/modules/whatsapp/lib/dispatch.ts @@ -16,6 +16,10 @@ export type DispatchItem = { groupId: string; attendeeId: string; 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. */ rawPhone: string | null; message: WhatsappMessage; @@ -74,7 +78,7 @@ export async function dispatchForAccount( items: DispatchItem[], ): Promise { const totals = emptyTotals(); - const periodKey = isoWeekKey(deps.now); + const weekKey = isoWeekKey(deps.now); let sentBefore = false; for (const item of items) { @@ -83,9 +87,10 @@ export async function dispatchForAccount( groupId: item.groupId, attendeeId: item.attendeeId, paymentId: item.paymentId ?? null, + checkoutId: item.checkoutId ?? null, kind: item.message.kind as WhatsappMessageKind, provider: deps.provider.id, - periodKey, + periodKey: item.periodKey ?? weekKey, }; const e164 = item.rawPhone ? toWhatsappE164(item.rawPhone, country) : null; @@ -152,6 +157,7 @@ type RecordInput = { groupId: string; attendeeId: string; paymentId: string | null; + checkoutId: string | null; kind: WhatsappMessageKind; provider: MessagingProvider['id']; periodKey: string; diff --git a/apps/backend/src/modules/whatsapp/lib/render-message.ts b/apps/backend/src/modules/whatsapp/lib/render-message.ts index 7494565..4925847 100644 --- a/apps/backend/src/modules/whatsapp/lib/render-message.ts +++ b/apps/backend/src/modules/whatsapp/lib/render-message.ts @@ -18,6 +18,12 @@ export function renderMessage(message: WhatsappMessage): string { `por ${message.amount}, con vencimiento el ${message.dueDate}. ` + `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': // Same copy the teacher sends by hand from "Alumnos en riesgo". return ( diff --git a/apps/backend/src/modules/whatsapp/providers/kapso/templates.ts b/apps/backend/src/modules/whatsapp/providers/kapso/templates.ts index 30e1b15..d826179 100644 --- a/apps/backend/src/modules/whatsapp/providers/kapso/templates.ts +++ b/apps/backend/src/modules/whatsapp/providers/kapso/templates.ts @@ -58,6 +58,41 @@ export const KAPSO_TEMPLATES: Record = { ] : [], }, + 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: { definition: { name: 'gruperly_reengagement', @@ -80,10 +115,13 @@ export const KAPSO_TEMPLATES: Record = { }, ], }, - parameters: (message) => [ - { name: 'student_name', text: firstNameOf(message.studentName) }, - { name: 'group_name', text: message.groupName }, - ], + parameters: (message) => + message.kind === 'REENGAGEMENT' + ? [ + { name: 'student_name', text: firstNameOf(message.studentName) }, + { name: 'group_name', text: message.groupName }, + ] + : [], }, }; diff --git a/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts b/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts index 235cebc..44dc99a 100644 --- a/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts +++ b/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts @@ -40,6 +40,16 @@ export type WhatsappMessage = kind: 'REENGAGEMENT'; studentName: 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 = { diff --git a/apps/backend/test/attendee-get-by-id.test.ts b/apps/backend/test/attendee-get-by-id.test.ts index ec90df7..01a887b 100644 --- a/apps/backend/test/attendee-get-by-id.test.ts +++ b/apps/backend/test/attendee-get-by-id.test.ts @@ -89,6 +89,7 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => { guardianPhone: '5598765432', guardianEmail: null, notes: null, + payWithMercadoPago: true, notifyToken: 'token-1', createdAt: '2026-08-01T10:00:00.000Z', updatedAt: '2026-08-01T10:00:00.000Z', diff --git a/apps/backend/test/attendees.test.ts b/apps/backend/test/attendees.test.ts index b244ac7..f178ff2 100644 --- a/apps/backend/test/attendees.test.ts +++ b/apps/backend/test/attendees.test.ts @@ -25,6 +25,7 @@ const personSelect = { email: true, phone: true, notes: true, + payWithMercadoPago: true, guardians: { take: 1, orderBy: { createdAt: 'asc' }, @@ -82,6 +83,7 @@ describe('attendees routes', () => { guardianPhone: '1199990000', guardianEmail: null, notes: person.notes, + payWithMercadoPago: true, createdAt: attendeeRow.createdAt.toISOString(), updatedAt: attendeeRow.updatedAt.toISOString(), // The query comes most recent first; the row shows them diff --git a/apps/backend/test/payments-auto-charge.test.ts b/apps/backend/test/payments-auto-charge.test.ts new file mode 100644 index 0000000..c24a1b9 --- /dev/null +++ b/apps/backend/test/payments-auto-charge.test.ts @@ -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; + settings?: { dueInDays: number; sendWhatsapp: boolean } | null; + runExists?: boolean; +}) { + const payments: Record[] = []; + const checkouts: Record[] = []; + const runs: Record[] = []; + 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 }) => { + 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 }) => 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 }) => { + 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 }) => + Object.assign(checkouts.find((row) => row.id === where.id) ?? {}, data), + ), + }, + payment: { + create: mock(async ({ data }: { data: Record }) => { + const payment = { id: `pay-${++seq}`, ...data }; + payments.push(payment); + return payment; + }), + updateMany: mock(async ({ where, data }: { where: { id: { in: string[] } }; data: Record }) => { + 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) => 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, overrides: Record = {}) { + 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'); + }); +}); diff --git a/apps/backend/test/payments-checkouts.test.ts b/apps/backend/test/payments-checkouts.test.ts new file mode 100644 index 0000000..fe342c6 --- /dev/null +++ b/apps/backend/test/payments-checkouts.test.ts @@ -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 | 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 { + 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).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(); + }); +}); diff --git a/apps/backend/test/payments-reconcile.test.ts b/apps/backend/test/payments-reconcile.test.ts index f1842cb..4f628ba 100644 --- a/apps/backend/test/payments-reconcile.test.ts +++ b/apps/backend/test/payments-reconcile.test.ts @@ -1,10 +1,19 @@ import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +const tx = { + paymentCheckout: { update: mock() }, + payment: { updateMany: mock() }, +}; + const db = { payment: { findMany: mock(), update: mock(), }, + paymentCheckout: { + findMany: mock(async () => [] as unknown[]), + }, + $transaction: mock(async (callback: (client: typeof tx) => Promise) => callback(tx)), }; mock.module('@/lib/prisma', () => ({ @@ -121,9 +130,54 @@ describe('reconcile payments', () => { where: { status: 'PENDING', checkoutUrl: { not: null }, + checkoutId: null, 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(); + }); }); \ No newline at end of file diff --git a/apps/backend/test/payments-renew.test.ts b/apps/backend/test/payments-renew.test.ts index 5a3165f..7253cbf 100644 --- a/apps/backend/test/payments-renew.test.ts +++ b/apps/backend/test/payments-renew.test.ts @@ -106,10 +106,11 @@ describe('renew payment link', () => { }); expect(prisma.payment.update).toHaveBeenCalledWith({ 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: { attendee: { select: { person: { select: { fullName: true } } } }, group: { select: { name: true, price: true } }, + checkout: { select: { _count: { select: { payments: true } } } }, }, }); }); diff --git a/apps/backend/test/payments.test.ts b/apps/backend/test/payments.test.ts index 255f7db..302c3eb 100644 --- a/apps/backend/test/payments.test.ts +++ b/apps/backend/test/payments.test.ts @@ -75,6 +75,9 @@ describe('payments routes', () => { status: 'PENDING', description: 'Mensualidad de Septiembre', checkoutUrl: payment.checkoutUrl, + checkoutId: null, + checkoutItemCount: null, + periodKey: null, dueDate: payment.dueDate.toISOString(), paidAt: null, createdAt: payment.createdAt.toISOString(), @@ -94,6 +97,7 @@ describe('payments routes', () => { include: { group: { select: { name: true, price: true } }, attendee: { select: { person: { select: { fullName: true } } } }, + checkout: { select: { _count: { select: { payments: true } } } }, }, skip: 0, take: 10, diff --git a/apps/backend/test/session-auth.test.ts b/apps/backend/test/session-auth.test.ts index 2faca6f..0767252 100644 --- a/apps/backend/test/session-auth.test.ts +++ b/apps/backend/test/session-auth.test.ts @@ -35,6 +35,9 @@ describe('session auth', () => { expect(isPublicApiRequest('GET', '/api/v1/health')).toBe(true); expect(isPublicApiRequest('POST', '/api/v1/auth/sign-in/email')).toBe(true); 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); }); diff --git a/apps/backend/test/whatsapp-core.test.ts b/apps/backend/test/whatsapp-core.test.ts index 0bc2942..63caf84 100644 --- a/apps/backend/test/whatsapp-core.test.ts +++ b/apps/backend/test/whatsapp-core.test.ts @@ -197,7 +197,7 @@ describe('status', () => { displayPhoneNumber: null, connectedAt: 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({ PAYMENT_REMINDER: 'ready', REENGAGEMENT: 'pending', + PAYMENT_LINK: 'ready', }); }); }); diff --git a/apps/backend/test/whatsapp-jobs.test.ts b/apps/backend/test/whatsapp-jobs.test.ts index b477f33..f8cf6fd 100644 --- a/apps/backend/test/whatsapp-jobs.test.ts +++ b/apps/backend/test/whatsapp-jobs.test.ts @@ -93,6 +93,36 @@ function reengagement(provider: MessagingProvider) { } 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).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 () => { await reminders(fakeProvider()).execute(); @@ -135,6 +165,7 @@ describe('payment reminders', () => { groupId: 'group-1', attendeeId: 'att-1', paymentId: 'pay-1', + checkoutId: null, kind: 'PAYMENT_REMINDER', provider: 'OPENWA', periodKey: '2026-W43', diff --git a/apps/backend/test/whatsapp-providers.test.ts b/apps/backend/test/whatsapp-providers.test.ts index 25224f9..a97852a 100644 --- a/apps/backend/test/whatsapp-providers.test.ts +++ b/apps/backend/test/whatsapp-providers.test.ts @@ -490,12 +490,13 @@ describe('Kapso provider', () => { expect(templates.map((call) => (call.body as { name: string; category: string }))).toEqual([ expect.objectContaining({ name: 'gruperly_payment_reminder', category: 'UTILITY' }), expect.objectContaining({ name: 'gruperly_reengagement', category: 'MARKETING' }), + expect.objectContaining({ name: 'gruperly_payment_link', category: 'UTILITY' }), ]); expect(db.whatsappAccount.update).toHaveBeenCalledWith({ where: { id: 'wa-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 () => { diff --git a/apps/web/src/features/attendee-detail/AttendeePaymentsSection.tsx b/apps/web/src/features/attendee-detail/AttendeePaymentsSection.tsx index 6379223..0349e24 100644 --- a/apps/web/src/features/attendee-detail/AttendeePaymentsSection.tsx +++ b/apps/web/src/features/attendee-detail/AttendeePaymentsSection.tsx @@ -1,11 +1,11 @@ -import { Badge, useToast } from '../../components/ui' +import { Badge, Switch, useToast } from '../../components/ui' import { paymentPresentation } from './detail' import { Section } from './Section' import { useAttendeeDetail } from './AttendeeDetailProvider' import { useTranslation } from 'react-i18next' export function AttendeePaymentsSection() { - const { attendee } = useAttendeeDetail() + const { attendee, saveAttendee, isUpdatingAttendee } = useAttendeeDetail() const toast = useToast() const { t } = useTranslation(['attendeeDetail', 'common']) if (!attendee) return null @@ -17,6 +17,16 @@ export function AttendeePaymentsSection() { 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 (
@@ -36,6 +46,21 @@ export function AttendeePaymentsSection() { {t('payments.register')}
+
+
+

{t('payments.payWithMp')}

+

+ {t('payments.payWithMpHint')} +

+
+ +
) } diff --git a/apps/web/src/features/payments/PaymentRow.tsx b/apps/web/src/features/payments/PaymentRow.tsx index 5a24e1c..fb954b2 100644 --- a/apps/web/src/features/payments/PaymentRow.tsx +++ b/apps/web/src/features/payments/PaymentRow.tsx @@ -49,6 +49,11 @@ export function PaymentRow({ payment, showGroup, isRenewing, onRenew }: PaymentR {paymentPeriodLabel(payment)}

{paymentDateLabel(payment)}

+ {payment.checkoutItemCount && payment.checkoutItemCount > 1 ? ( +

+ {t('row.combined', { count: payment.checkoutItemCount })} +

+ ) : null} {paymentStatusLabel(payment.status)} diff --git a/apps/web/src/features/payments/copy.ts b/apps/web/src/features/payments/copy.ts index e13d9e4..b35920c 100644 --- a/apps/web/src/features/payments/copy.ts +++ b/apps/web/src/features/payments/copy.ts @@ -10,7 +10,20 @@ export const PAYMENT_STATUS_BADGE: Record = } 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 { diff --git a/apps/web/src/features/settings/AutoChargeSettingsCard.tsx b/apps/web/src/features/settings/AutoChargeSettingsCard.tsx new file mode 100644 index 0000000..8afe27a --- /dev/null +++ b/apps/web/src/features/settings/AutoChargeSettingsCard.tsx @@ -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(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 ( +
+
+ +
+

+ {t('autoCharge.title')} + {includedInPlan ? null : Pro} +

+

+ {t('autoCharge.description')} +

+ {!mpLinked && !settings?.enabled ? ( +

{t('autoCharge.needsMp')}

+ ) : null} +
+ { + setJustEnabled(enabled) + save({ enabled }) + }} + /> +
+ + {settings?.enabled ? ( +
+
+
+ + +
+
+ + +
+
+ +
+
+

+ {t('autoCharge.whatsapp')} + {whatsappInPlan ? null : Pro} +

+

+ {t('autoCharge.whatsappDescription')} + {whatsappBlocked && !settings.sendWhatsapp ? ( + <> + {' '} + {whatsappBlocked} + + ) : null} +

+
+ save({ sendWhatsapp })} + /> +
+ +

{t('autoCharge.howItGroups')}

+ + {settings.nextRunDate ? ( +

{t('autoCharge.next', { date: formatDay(settings.nextRunDate) })}

+ ) : null} +
+ ) : null} + + {settings?.lastRun ? : null} +
+ ) +} + +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 ( +

+ {t('autoCharge.lastRun', { period })} {summary} +

+ ) +} + +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' +} diff --git a/apps/web/src/features/settings/SettingsView.tsx b/apps/web/src/features/settings/SettingsView.tsx index bedeccf..ac4a8d4 100644 --- a/apps/web/src/features/settings/SettingsView.tsx +++ b/apps/web/src/features/settings/SettingsView.tsx @@ -7,6 +7,7 @@ import { PlanSettingsCard } from '../billing' import { MpStatusCard } from '../mp' import { WhatsappStatusCard } from '../whatsapp' import { AppearanceCard } from './AppearanceCard' +import { AutoChargeSettingsCard } from './AutoChargeSettingsCard' import { LanguageCard } from './LanguageCard' import { TransferDetailsSettingsCard } from './TransferDetailsSettingsCard' import { useCallbackFeedbackToast } from './useCallbackFeedbackToast' @@ -46,6 +47,8 @@ export function SettingsView() { + + diff --git a/apps/web/src/features/student-app/FeeCard.tsx b/apps/web/src/features/student-app/FeeCard.tsx index a04378a..a4df468 100644 --- a/apps/web/src/features/student-app/FeeCard.tsx +++ b/apps/web/src/features/student-app/FeeCard.tsx @@ -3,7 +3,7 @@ import type { StudentFee } from '@gruperly/shared' import { ExternalLink, Receipt } from 'lucide-react' import { Badge } from '../../components/ui' import { formatPrice } from '../../lib/format' -import { feeLabel } from './format' +import { checkoutItemsLabel, feeLabel } from './format' import { FeeStatusBadge } from './FeeStatusBadge' import { useTranslation } from 'react-i18next' @@ -40,10 +40,19 @@ export function FeeCard({ fees }: { fees: StudentFee[] }) { {toReport.length > 0 ? (
{single ? ( - - {t('fee.payMp')} - + <> + + {single.checkout + ? t('fee.payAll', { amount: formatPrice(single.checkout.total, single.currency) }) + : t('fee.payMp')} + + {single.checkout ? ( +

+ {t('fee.includes', { items: checkoutItemsLabel(single.checkout) })} +

+ ) : null} + ) : payable.length > 1 ? ( {t('fee.payMp')} diff --git a/apps/web/src/features/student-app/StudentPaymentsView.tsx b/apps/web/src/features/student-app/StudentPaymentsView.tsx index 5ad9fac..4807bec 100644 --- a/apps/web/src/features/student-app/StudentPaymentsView.tsx +++ b/apps/web/src/features/student-app/StudentPaymentsView.tsx @@ -4,7 +4,7 @@ import { ExternalLink, Loader2, Receipt } from 'lucide-react' import { Badge } from '../../components/ui' import { formatPrice } from '../../lib/format' import { FeeStatusBadge } from './FeeStatusBadge' -import { feeLabel, formatDueDate } from './format' +import { checkoutItemsLabel, feeLabel, formatDueDate } from './format' import { useStudentApp } from './StudentAppProvider' import { useTranslation } from 'react-i18next' import { useIntlLocale } from '../../i18n' @@ -57,15 +57,24 @@ export function StudentPaymentsView() {
{fee.checkoutUrl && fee.status !== 'reported' ? ( - - {t('payments.payMp')} - +
+ + {fee.checkout + ? t('payments.payAll', { amount: formatPrice(fee.checkout.total, fee.currency) }) + : t('payments.payMp')} + + {fee.checkout ? ( +

+ {t('payments.includes', { items: checkoutItemsLabel(fee.checkout) })} +

+ ) : null} +
) : null} ))} diff --git a/apps/web/src/features/student-app/format.ts b/apps/web/src/features/student-app/format.ts index 893b36b..2313d2e 100644 --- a/apps/web/src/features/student-app/format.ts +++ b/apps/web/src/features/student-app/format.ts @@ -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"). */ -export function feeLabel(fee: Pick): string { +/** Fee title: its description, its month (automatic charges) or the month it is due ("Noviembre"). */ +export function feeLabel(fee: Pick & { periodKey?: string | null }): string { if (fee.description) return fee.description - const month = new Intl.DateTimeFormat(i18n.language, { month: 'long', timeZone: 'UTC' }).format(new Date(fee.dueDate)) - return month.charAt(0).toUpperCase() + month.slice(1) + const [year, month] = (fee.periodKey ?? '').split('-').map(Number) + 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): string { + return checkout.items.map((item) => `${item.groupName} · ${firstName(item.studentName)}`).join(', ') } export function formatDueDate(iso: string): string { diff --git a/apps/web/src/features/whatsapp/WhatsappStatusCard.tsx b/apps/web/src/features/whatsapp/WhatsappStatusCard.tsx index 354f77d..a9c2e1f 100644 --- a/apps/web/src/features/whatsapp/WhatsappStatusCard.tsx +++ b/apps/web/src/features/whatsapp/WhatsappStatusCard.tsx @@ -106,6 +106,10 @@ export function WhatsappStatusCard() {
{t('card.reengagement')}
{readinessLabel(data.readiness.REENGAGEMENT)}
+
+
{t('card.paymentLink')}
+
{readinessLabel(data.readiness.PAYMENT_LINK)}
+

{t('card.perGroup')} {weeklySendLabel()}

diff --git a/apps/web/src/features/whatsapp/copy.ts b/apps/web/src/features/whatsapp/copy.ts index dfa5caf..67dc9ac 100644 --- a/apps/web/src/features/whatsapp/copy.ts +++ b/apps/web/src/features/whatsapp/copy.ts @@ -138,7 +138,7 @@ export function formatPairingCode(code: string): string { */ export function automationBlockedReason( status: WhatsappStatusDto | undefined, - kind: 'PAYMENT_REMINDER' | 'REENGAGEMENT', + kind: 'PAYMENT_REMINDER' | 'REENGAGEMENT' | 'PAYMENT_LINK', ): string | null { if (!status || status.status !== 'active') { return i18n.t('whatsapp:blocked.notLinked') diff --git a/apps/web/src/i18n/locales/en/attendeeDetail.json b/apps/web/src/i18n/locales/en/attendeeDetail.json index f38464f..fbf428b 100644 --- a/apps/web/src/i18n/locales/en/attendeeDetail.json +++ b/apps/web/src/i18n/locales/en/attendeeDetail.json @@ -75,7 +75,12 @@ "registerPending": "Recording payments will be available once the payment flow is defined.", "noCharge": "No charge on record", "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": { "title": "Attendance", diff --git a/apps/web/src/i18n/locales/en/payments.json b/apps/web/src/i18n/locales/en/payments.json index c90bc13..b028a57 100644 --- a/apps/web/src/i18n/locales/en/payments.json +++ b/apps/web/src/i18n/locales/en/payments.json @@ -25,7 +25,9 @@ "copied": "Copied", "copyLink": "Copy link", "noLink": "No link", - "generate": "Create link" + "generate": "Create link", + "combined_one": "Combined link · {{count}} fee", + "combined_other": "Combined link · {{count}} fees" }, "groupFilter": { "label": "Group: {{name}}", diff --git a/apps/web/src/i18n/locales/en/settings.json b/apps/web/src/i18n/locales/en/settings.json index cb823e4..e39a772 100644 --- a/apps/web/src/i18n/locales/en/settings.json +++ b/apps/web/src/i18n/locales/en/settings.json @@ -35,5 +35,37 @@ "callback": { "mpLinked": "Your Mercado Pago account 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" } } diff --git a/apps/web/src/i18n/locales/en/student.json b/apps/web/src/i18n/locales/en/student.json index 2467291..9d42766 100644 --- a/apps/web/src/i18n/locales/en/student.json +++ b/apps/web/src/i18n/locales/en/student.json @@ -51,7 +51,9 @@ "overdue": "Some are overdue", "payMp": "Pay with Mercado Pago", "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": { "confirmed": "Your teacher confirmed your {{amount}} payment.", @@ -84,7 +86,9 @@ "reported": "Reported", "confirmed": "Confirmed", "rejected": "Declined" - } + }, + "payAll": "Pay all ({{amount}})", + "includes": "Includes: {{items}}" }, "notify": { "done": "Done, we let {{teacher}} know", diff --git a/apps/web/src/i18n/locales/en/validation.json b/apps/web/src/i18n/locales/en/validation.json index 5909d6a..6a14155 100644 --- a/apps/web/src/i18n/locales/en/validation.json +++ b/apps/web/src/i18n/locales/en/validation.json @@ -50,7 +50,10 @@ "invalid": "Invalid time zone" }, "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": { "required": "Last name is required" diff --git a/apps/web/src/i18n/locales/en/whatsapp.json b/apps/web/src/i18n/locales/en/whatsapp.json index ab80315..4c04dc6 100644 --- a/apps/web/src/i18n/locales/en/whatsapp.json +++ b/apps/web/src/i18n/locales/en/whatsapp.json @@ -75,6 +75,7 @@ "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.", "opening": "Opening…", - "connect": "Link" + "connect": "Link", + "paymentLink": "Monthly payment link" } } diff --git a/apps/web/src/i18n/locales/es-419/attendeeDetail.json b/apps/web/src/i18n/locales/es-419/attendeeDetail.json index ac55432..ad7ac95 100644 --- a/apps/web/src/i18n/locales/es-419/attendeeDetail.json +++ b/apps/web/src/i18n/locales/es-419/attendeeDetail.json @@ -75,7 +75,12 @@ "registerPending": "Registrar pagos estará disponible cuando se defina el flujo de cobros.", "noCharge": "Sin cobro registrado", "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": { "title": "Asistencia", diff --git a/apps/web/src/i18n/locales/es-419/payments.json b/apps/web/src/i18n/locales/es-419/payments.json index 7ed6c7a..0735f6f 100644 --- a/apps/web/src/i18n/locales/es-419/payments.json +++ b/apps/web/src/i18n/locales/es-419/payments.json @@ -25,7 +25,9 @@ "copied": "Copiado", "copyLink": "Copiar link", "noLink": "Sin link", - "generate": "Generar link" + "generate": "Generar link", + "combined_one": "Link combinado · {{count}} cuota", + "combined_other": "Link combinado · {{count}} cuotas" }, "groupFilter": { "label": "Grupo: {{name}}", diff --git a/apps/web/src/i18n/locales/es-419/settings.json b/apps/web/src/i18n/locales/es-419/settings.json index c7f5104..dad8b01 100644 --- a/apps/web/src/i18n/locales/es-419/settings.json +++ b/apps/web/src/i18n/locales/es-419/settings.json @@ -35,5 +35,37 @@ "callback": { "mpLinked": "Tu cuenta de Mercado Pago quedó vinculada.", "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" } } diff --git a/apps/web/src/i18n/locales/es-419/student.json b/apps/web/src/i18n/locales/es-419/student.json index e917dc1..30fa6d3 100644 --- a/apps/web/src/i18n/locales/es-419/student.json +++ b/apps/web/src/i18n/locales/es-419/student.json @@ -51,7 +51,9 @@ "overdue": "Hay vencidas", "payMp": "Pagar con Mercado 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": { "confirmed": "Tu profe confirmó tu pago de {{amount}}.", @@ -84,7 +86,9 @@ "reported": "Informado", "confirmed": "Confirmado", "rejected": "Rechazado" - } + }, + "payAll": "Pagar todo ({{amount}})", + "includes": "Incluye: {{items}}" }, "notify": { "done": "Listo, le avisamos a {{teacher}}", diff --git a/apps/web/src/i18n/locales/es-419/validation.json b/apps/web/src/i18n/locales/es-419/validation.json index ce2114f..d043748 100644 --- a/apps/web/src/i18n/locales/es-419/validation.json +++ b/apps/web/src/i18n/locales/es-419/validation.json @@ -50,7 +50,10 @@ "invalid": "Zona horaria inválida" }, "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": { "required": "El apellido es obligatorio" diff --git a/apps/web/src/i18n/locales/es-419/whatsapp.json b/apps/web/src/i18n/locales/es-419/whatsapp.json index e7fc28c..46f1278 100644 --- a/apps/web/src/i18n/locales/es-419/whatsapp.json +++ b/apps/web/src/i18n/locales/es-419/whatsapp.json @@ -75,6 +75,7 @@ "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.", "opening": "Abriendo…", - "connect": "Vincular" + "connect": "Vincular", + "paymentLink": "Link de pago mensual" } } diff --git a/apps/web/src/i18n/locales/es-AR/attendeeDetail.json b/apps/web/src/i18n/locales/es-AR/attendeeDetail.json index 67128f6..f3e69a6 100644 --- a/apps/web/src/i18n/locales/es-AR/attendeeDetail.json +++ b/apps/web/src/i18n/locales/es-AR/attendeeDetail.json @@ -75,7 +75,12 @@ "registerPending": "Registrar pagos estará disponible cuando se defina el flujo de cobros.", "noCharge": "Sin cobro registrado", "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": { "title": "Asistencia", diff --git a/apps/web/src/i18n/locales/es-AR/payments.json b/apps/web/src/i18n/locales/es-AR/payments.json index fb2a1b1..1af934c 100644 --- a/apps/web/src/i18n/locales/es-AR/payments.json +++ b/apps/web/src/i18n/locales/es-AR/payments.json @@ -25,7 +25,9 @@ "copied": "Copiado", "copyLink": "Copiar link", "noLink": "Sin link", - "generate": "Generar link" + "generate": "Generar link", + "combined_one": "Link combinado · {{count}} cuota", + "combined_other": "Link combinado · {{count}} cuotas" }, "groupFilter": { "label": "Grupo: {{name}}", diff --git a/apps/web/src/i18n/locales/es-AR/settings.json b/apps/web/src/i18n/locales/es-AR/settings.json index f9e59d8..16e786e 100644 --- a/apps/web/src/i18n/locales/es-AR/settings.json +++ b/apps/web/src/i18n/locales/es-AR/settings.json @@ -35,5 +35,37 @@ "callback": { "mpLinked": "Tu cuenta de Mercado Pago quedó vinculada.", "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" } } diff --git a/apps/web/src/i18n/locales/es-AR/student.json b/apps/web/src/i18n/locales/es-AR/student.json index 0dcbab5..ca79942 100644 --- a/apps/web/src/i18n/locales/es-AR/student.json +++ b/apps/web/src/i18n/locales/es-AR/student.json @@ -51,7 +51,9 @@ "overdue": "Hay vencidas", "payMp": "Pagar con Mercado 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": { "confirmed": "Tu profe confirmó tu pago de {{amount}}.", @@ -84,7 +86,9 @@ "reported": "Informado", "confirmed": "Confirmado", "rejected": "Rechazado" - } + }, + "payAll": "Pagar todo ({{amount}})", + "includes": "Incluye: {{items}}" }, "notify": { "done": "Listo, le avisamos a {{teacher}}", diff --git a/apps/web/src/i18n/locales/es-AR/validation.json b/apps/web/src/i18n/locales/es-AR/validation.json index 7239b0e..01418b8 100644 --- a/apps/web/src/i18n/locales/es-AR/validation.json +++ b/apps/web/src/i18n/locales/es-AR/validation.json @@ -50,7 +50,10 @@ "invalid": "Zona horaria inválida" }, "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": { "required": "El apellido es obligatorio" diff --git a/apps/web/src/i18n/locales/es-AR/whatsapp.json b/apps/web/src/i18n/locales/es-AR/whatsapp.json index abbfc1d..263af81 100644 --- a/apps/web/src/i18n/locales/es-AR/whatsapp.json +++ b/apps/web/src/i18n/locales/es-AR/whatsapp.json @@ -75,6 +75,7 @@ "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.", "opening": "Abriendo…", - "connect": "Vincular" + "connect": "Vincular", + "paymentLink": "Link de pago mensual" } } diff --git a/apps/web/src/i18n/locales/pt-BR/attendeeDetail.json b/apps/web/src/i18n/locales/pt-BR/attendeeDetail.json index 6808279..61b58d4 100644 --- a/apps/web/src/i18n/locales/pt-BR/attendeeDetail.json +++ b/apps/web/src/i18n/locales/pt-BR/attendeeDetail.json @@ -75,7 +75,12 @@ "registerPending": "Registrar pagamentos estará disponível quando o fluxo de cobranças for definido.", "noCharge": "Nenhuma cobrança registrada", "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": { "title": "Presença", diff --git a/apps/web/src/i18n/locales/pt-BR/payments.json b/apps/web/src/i18n/locales/pt-BR/payments.json index a9bef5c..7c5d198 100644 --- a/apps/web/src/i18n/locales/pt-BR/payments.json +++ b/apps/web/src/i18n/locales/pt-BR/payments.json @@ -25,7 +25,9 @@ "copied": "Copiado", "copyLink": "Copiar link", "noLink": "Sem link", - "generate": "Gerar link" + "generate": "Gerar link", + "combined_one": "Link combinado · {{count}} mensalidade", + "combined_other": "Link combinado · {{count}} mensalidades" }, "groupFilter": { "label": "Grupo: {{name}}", diff --git a/apps/web/src/i18n/locales/pt-BR/settings.json b/apps/web/src/i18n/locales/pt-BR/settings.json index bd99b83..53d37d9 100644 --- a/apps/web/src/i18n/locales/pt-BR/settings.json +++ b/apps/web/src/i18n/locales/pt-BR/settings.json @@ -35,5 +35,37 @@ "callback": { "mpLinked": "Sua conta do Mercado Pago foi vinculada.", "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" } } diff --git a/apps/web/src/i18n/locales/pt-BR/student.json b/apps/web/src/i18n/locales/pt-BR/student.json index 738b539..98657be 100644 --- a/apps/web/src/i18n/locales/pt-BR/student.json +++ b/apps/web/src/i18n/locales/pt-BR/student.json @@ -51,7 +51,9 @@ "overdue": "Há vencidas", "payMp": "Pagar com Mercado Pago", "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": { "confirmed": "Seu professor confirmou seu pagamento de {{amount}}.", @@ -84,7 +86,9 @@ "reported": "Informado", "confirmed": "Confirmado", "rejected": "Recusado" - } + }, + "payAll": "Pagar tudo ({{amount}})", + "includes": "Inclui: {{items}}" }, "notify": { "done": "Pronto, avisamos {{teacher}}", diff --git a/apps/web/src/i18n/locales/pt-BR/validation.json b/apps/web/src/i18n/locales/pt-BR/validation.json index fa69565..c6f555d 100644 --- a/apps/web/src/i18n/locales/pt-BR/validation.json +++ b/apps/web/src/i18n/locales/pt-BR/validation.json @@ -50,7 +50,10 @@ "invalid": "Fuso horário inválido" }, "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": { "required": "O sobrenome é obrigatório" diff --git a/apps/web/src/i18n/locales/pt-BR/whatsapp.json b/apps/web/src/i18n/locales/pt-BR/whatsapp.json index 2b94bc0..9a2dbcd 100644 --- a/apps/web/src/i18n/locales/pt-BR/whatsapp.json +++ b/apps/web/src/i18n/locales/pt-BR/whatsapp.json @@ -75,6 +75,7 @@ "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.", "opening": "Abrindo…", - "connect": "Vincular" + "connect": "Vincular", + "paymentLink": "Link de pagamento mensal" } } diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index cd62e8d..d7501f3 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -78,6 +78,8 @@ import type { ReportedPaymentDto, ReceiptUrlDto, TransferDetailsDto, + AutoChargeSettingsDto, + UpdateAutoChargeSettings, UpdateTransferDetails, TeacherAbsenceNoticeList, PersonSummary, @@ -621,6 +623,14 @@ export const rejectReportedPayment = (reportId: string, reason: string | null) = export const undoPaymentReview = (reportId: string) => apiFetch(`/api/v1/payments/reported/${reportId}/undo`, { method: 'POST' }) +export const getAutoChargeSettings = () => apiFetch('/api/v1/payments/auto-charge') + +export const updateAutoChargeSettings = (payload: UpdateAutoChargeSettings) => + apiFetch('/api/v1/payments/auto-charge', { + method: 'PUT', + body: JSON.stringify(payload), + }) + export const getTransferDetails = () => apiFetch('/api/v1/payments/transfer-details') export const updateTransferDetails = (payload: UpdateTransferDetails) => diff --git a/docs/whatsapp.md b/docs/whatsapp.md index b21305d..b6ccd2a 100644 --- a/docs/whatsapp.md +++ b/docs/whatsapp.md @@ -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: -- **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. 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 -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 | | --- | --- | --- | | `gruperly_payment_reminder` | `UTILITY` | `student_name`, `group_name`, `amount`, `due_date`, `payment_link` | | `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. - **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. diff --git a/packages/shared/src/schemas/attendees.ts b/packages/shared/src/schemas/attendees.ts index 81f47be..b2d809d 100644 --- a/packages/shared/src/schemas/attendees.ts +++ b/packages/shared/src/schemas/attendees.ts @@ -30,6 +30,8 @@ export const AttendeeDtoSchema = z.object({ guardianPhone: z.string().nullable(), guardianEmail: 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(), createdAt: isoDateTimeSchema, updatedAt: isoDateTimeSchema, @@ -93,6 +95,7 @@ const EditableAttendeeFieldsSchema = z.object({ .or(z.literal('')) .nullable(), notes: z.string().trim().nullable(), + payWithMercadoPago: z.boolean(), }); export const UpdateAttendeeSchema = EditableAttendeeFieldsSchema.partial().refine( diff --git a/packages/shared/src/schemas/payments.ts b/packages/shared/src/schemas/payments.ts index e76e5a9..ef13e27 100644 --- a/packages/shared/src/schemas/payments.ts +++ b/packages/shared/src/schemas/payments.ts @@ -20,6 +20,11 @@ export const PaymentDtoSchema = z.object({ status: paymentStatusSchema, description: 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, paidAt: isoDateTimeSchema.nullable(), createdAt: isoDateTimeSchema, @@ -71,4 +76,54 @@ export const CreatePaymentsBatchResultSchema = z.object({ failed: z.number().int().min(0), items: z.array(PaymentBatchItemSchema), }); -export type CreatePaymentsBatchResult = z.output; \ No newline at end of file +export type CreatePaymentsBatchResult = z.output; +// 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; + +export const paymentRunStatusSchema = z.enum(['RUNNING', 'DONE', 'SKIPPED']); +export type PaymentRunStatus = z.output; + +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; + +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; diff --git a/packages/shared/src/schemas/student-portal.ts b/packages/shared/src/schemas/student-portal.ts index a3122db..5dc2e70 100644 --- a/packages/shared/src/schemas/student-portal.ts +++ b/packages/shared/src/schemas/student-portal.ts @@ -181,6 +181,16 @@ export const StudentFeeSchema = z.object({ dueDate: isoDateTimeSchema, status: studentFeeStatusSchema, 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; diff --git a/packages/shared/src/schemas/whatsapp.ts b/packages/shared/src/schemas/whatsapp.ts index ecf7644..c8034e5 100644 --- a/packages/shared/src/schemas/whatsapp.ts +++ b/packages/shared/src/schemas/whatsapp.ts @@ -17,7 +17,7 @@ export const whatsappAccountStatusSchema = z.enum([ ]); export type WhatsappAccountStatus = z.output; -export const whatsappMessageKindSchema = z.enum(['PAYMENT_REMINDER', 'REENGAGEMENT']); +export const whatsappMessageKindSchema = z.enum(['PAYMENT_REMINDER', 'REENGAGEMENT', 'PAYMENT_LINK']); export type WhatsappMessageKind = z.output; // Whether automated messages of one kind can go out right now. @@ -75,6 +75,7 @@ export const WhatsappStatusDtoSchema = z.object({ readiness: z.object({ PAYMENT_REMINDER: whatsappReadinessSchema, REENGAGEMENT: whatsappReadinessSchema, + PAYMENT_LINK: whatsappReadinessSchema, }), }); export type WhatsappStatusDto = z.output;