4 Commits

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:08:48 -03:00
Jose Selesan
5b3a035dcf feat(student-portal): student account belongs to the adult in charge
- Inviting a kid with an adult in charge links the account to the adult
  (a legacy account linked to the kid moves to the adult and is renamed).
- `linkedPersonWhere` lets the account reach the kids of a linked adult, so
  the adult sees and manages all their kids, including ones added later.
- /me, link info and access status follow the adult; siblings share state.
- Web: greeting uses the account holder, profile lists each kid's group, and
  the invitation sheet/message address the adult.
- DB tests for the adult account flow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:04:25 -03:00
Jose Selesan
9383841513 feat(web): WhatsApp and call actions on attendee phone rows
The phone row in the attendee contact and guardian sections was a single
tel: link. It now shows WhatsApp and call icon buttons for that number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:37:55 -03:00
Jose Selesan
58c776e18c feat(groups): kids groups with an adult in charge
- Add the `kidsGroups` plan feature (Pro) and `Group.audience` (ADULTS | KIDS);
  creating or switching a group to KIDS requires the feature, existing KIDS
  groups keep working after a downgrade.
- Model the adult in charge as a Person linked through `person_guardians`;
  migrate the old guardian_name/guardian_phone columns and drop them.
- Kids quick add: kid + guardian form, guardian lookup by phone to pick an
  existing kid or add a sibling; backend rejects KIDS adds without guardian.
- Attendee page: "Adulto a cargo" section with siblings, editable via
  PATCH /groups/:gid/attendees/:aid/guardian.
- Contact phone (WhatsApp jobs, attention, student access invite, students at
  risk, attendee actions) prefers the guardian's phone.
- Edit group screen (PATCH /groups/:gid, owner only); switching back to ADULTS
  is blocked while kids have no phone of their own.
- Hide bulk import in KIDS groups until it carries guardian data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:27:13 -03:00
172 changed files with 4843 additions and 284 deletions

View File

@@ -43,6 +43,12 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`. - **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness. - **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). Cada link lleva `notification_url` a `POST /payments/webhooks/mp/:paymentId` (público; solo si `API_PUBLIC_URL` es HTTPS pública): el aviso no se lee, se le pregunta a MP con el token del dueño vía `confirmMpPayment`, la misma regla del polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), que sigue de respaldo, y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**. - **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). Cada link lleva `notification_url` a `POST /payments/webhooks/mp/:paymentId` (público; solo si `API_PUBLIC_URL` es HTTPS pública): el aviso no se lee, se le pregunta a MP con el token del dueño vía `confirmMpPayment`, la misma regla del polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), que sigue de respaldo, y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
- **Cobro automático (`modules/payments/features/auto-charge*`)**: el profe elige en Ajustes un día del mes (1–28, `auto_charge_settings`) y el cron horario `RunAutoCharges` (`7 * * * *` UTC) corre `GenerateMonthlyCharges` cuando es ese día en **su** zona (`teacherTimeZone`), desde las 9 y con 3 días de tolerancia; si se prendió después del día, arranca el mes siguiente (`enabledAt`). Ojo con esto:
1. Idempotencia: `payment_runs` con `@@unique([ownerId, periodKey])` (mes `"2026-12"`), y además un índice único **parcial** a mano `payments_attendee_period_key` (`attendee_id, period_key WHERE period_key IS NOT NULL`); las cuotas manuales no llevan `periodKey`.
2. Un link por **pagador** (`PaymentCheckout`): el adulto a cargo (`primaryGuardian`) junta a sus chicos y lo suyo; si no, la persona. La preferencia lleva un ítem por cuota y `external_reference = chk_<checkoutId>` (nunca un payment id); el webhook es `POST /payments/webhooks/mp/checkout/:checkoutId` y `confirmMpCheckout` marca `PAID` todas sus cuotas. Las cuotas copian el `checkoutUrl` del checkout pero **no** su `mpPreferenceId`.
3. `Person.payWithMercadoPago` (default `true`, se edita en la ficha del alumno): apagado, la cuota se crea igual pero sin link (paga por transferencia).
4. Si una cuota de un checkout `OPEN` se paga por otra vía (confirmar transferencia), `supersedeCheckoutsOf` lo pasa a `SUPERSEDED`, borra el link de sus cuotas y expira la preferencia en MP (best effort); renovar una de esas cuotas crea un link individual y la saca del checkout. La reconciliación sigue mirando los `SUPERSEDED` 7 días. Renovar una cuota de un checkout `OPEN` sin link regenera el link **combinado**.
5. Con `sendWhatsapp`, los links salen enseguida por WhatsApp (`SendPaymentLinks`, kind `PAYMENT_LINK`, mismo gate que las automatizaciones: Pro + cuenta activa + template aprobado); el recordatorio semanal manda uno por checkout, no uno por chico.
- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto: - **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`. 1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`.
2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre. 2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.
@@ -70,7 +76,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
2. Tokens de 32 bytes base64url; **en la base solo el SHA-256**. Invitación 72 h, recuperación 15 min, confirmación de mail 24 h. El **GET del link no consume** (vistas previas de WhatsApp); el POST consume con `updateMany` condicional (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now`) y `count === 1` gana. Todo link inválido responde el mismo `{ status: 'invalid' }` / 410. 2. Tokens de 32 bytes base64url; **en la base solo el SHA-256**. Invitación 72 h, recuperación 15 min, confirmación de mail 24 h. El **GET del link no consume** (vistas previas de WhatsApp); el POST consume con `updateMany` condicional (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now`) y `count === 1` gana. Todo link inválido responde el mismo `{ status: 'invalid' }` / 410.
3. **Reinvitar reinicia el acceso**: revoca tokens pendientes y sesiones, **borra las passkeys** y resetea `welcomed_at`. 3. **Reinvitar reinicia el acceso**: revoca tokens pendientes y sesiones, **borra las passkeys** y resetea `welcomed_at`.
4. CSRF: `studentOriginGuard` exige `Origin === WEB_URL` (o `WEBAUTHN_ORIGIN`) en todo POST/PUT/DELETE, además de `SameSite=Lax`. 4. CSRF: `studentOriginGuard` exige `Origin === WEB_URL` (o `WEBAUTHN_ORIGIN`) en todo POST/PUT/DELETE, además de `SameSite=Lax`.
5. Autorización: todo pasa por `findLinkedAttendee` (attendee cuya **persona** está vinculada a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. La cuenta se vincula a la persona (`student_account_people`), no a la membresía: ve todos sus grupos, también los que se sumen después, y es **una cuenta por persona** (invitar desde cualquier grupo la reutiliza). Vincular tutores a varios hijos (N:N) es solo del lado profe y **todavía no tiene UI**. 5. Autorización: todo pasa por `findLinkedAttendee` (attendee cuya **persona** está vinculada a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. La cuenta se vincula a la persona (`student_account_people`), no a la membresía: ve todos sus grupos, también los que se sumen después, y es **una cuenta por persona** (invitar desde cualquier grupo la reutiliza). En grupos de chicos la cuenta es del **adulto a cargo** (`person_guardians`): invitar a un chico vincula al adulto (y pasa al adulto una cuenta vieja del chico), y `linkedPersonWhere` le da acceso a todos sus chicos, también a los que se sumen después, sin reinvitar.
6. "Pedir un link a mi mail": respuesta idéntica exista o no el mail; rate limit en `rate_limit_events` (3 por mail y 10 por IP cada 15 min). La IP sale de `X-Forwarded-For` contando `TRUSTED_PROXY_HOPS` desde el final. El envío corre después de responder, para no filtrar por tiempo. 6. "Pedir un link a mi mail": respuesta idéntica exista o no el mail; rate limit en `rate_limit_events` (3 por mail y 10 por IP cada 15 min). La IP sale de `X-Forwarded-For` contando `TRUSTED_PROXY_HOPS` desde el final. El envío corre después de responder, para no filtrar por tiempo.
7. Avisar falta reutiliza `registerAbsence` (EXCUSED + liberación de cupo); `AbsenceNotice` tiene índice único **parcial** (`cancelled_at IS NULL`, escrito a mano en la migración: Prisma no lo modela). Solo antes del inicio de la clase y solo en ocurrencias reales del grupo, en la zona del profe (`COUNTRY_TIME_ZONES[user.country]`, default `APP_TIMEZONE` = Buenos Aires). 7. Avisar falta reutiliza `registerAbsence` (EXCUSED + liberación de cupo); `AbsenceNotice` tiene índice único **parcial** (`cancelled_at IS NULL`, escrito a mano en la migración: Prisma no lo modela). Solo antes del inicio de la clase y solo en ocurrencias reales del grupo, en la zona del profe (`COUNTRY_TIME_ZONES[user.country]`, default `APP_TIMEZONE` = Buenos Aires).
8. Pago informado: `Payment.status` **no cambia** hasta que el profe confirma. "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas con un `ReportedPayment` `REPORTED` (`reportedItems: { none: … }`); si se rechaza, vuelven. Confirmar marca `PAID` con `paid_at = reviewed_at`; "Deshacer" (10 min) revierte solo esas filas (sin `mp_payment_id`). El mail al alumno sale 60 s después, solo si la revisión sigue en pie y el mail está confirmado. 8. Pago informado: `Payment.status` **no cambia** hasta que el profe confirma. "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas con un `ReportedPayment` `REPORTED` (`reportedItems: { none: … }`); si se rechaza, vuelven. Confirmar marca `PAID` con `paid_at = reviewed_at`; "Deshacer" (10 min) revierte solo esas filas (sin `mp_payment_id`). El mail al alumno sale 60 s después, solo si la revisión sigue en pie y el mail está confirmado.

View File

@@ -0,0 +1,11 @@
-- CreateEnum
CREATE TYPE "GroupAudience" AS ENUM ('ADULTS', 'KIDS');
-- AlterTable
ALTER TABLE "groups" ADD COLUMN "audience" "GroupAudience" NOT NULL DEFAULT 'ADULTS';
-- AlterTable
ALTER TABLE "plan_configs" ADD COLUMN "kids_groups" BOOLEAN NOT NULL DEFAULT false;
-- Pro includes kids groups from the start; Free keeps the default (false).
UPDATE "plan_configs" SET "kids_groups" = true WHERE "plan" = 'PRO';

View File

@@ -0,0 +1,52 @@
-- CreateTable
CREATE TABLE "person_guardians" (
"child_id" TEXT NOT NULL,
"guardian_id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "person_guardians_pkey" PRIMARY KEY ("child_id","guardian_id")
);
-- CreateIndex
CREATE INDEX "person_guardians_guardian_id_idx" ON "person_guardians"("guardian_id");
-- AddForeignKey
ALTER TABLE "person_guardians" ADD CONSTRAINT "person_guardians_child_id_fkey" FOREIGN KEY ("child_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "person_guardians" ADD CONSTRAINT "person_guardians_guardian_id_fkey" FOREIGN KEY ("guardian_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- The old guardian_name / guardian_phone become an adult of their own: an
-- existing person of the same teacher with that phone, or a new one (one per
-- teacher and phone, so siblings end up sharing it).
INSERT INTO "people" ("id", "created_by_id", "full_name", "phone", "created_at", "updated_at")
SELECT DISTINCT ON (k."created_by_id", k."guardian_phone")
gen_random_uuid()::text,
k."created_by_id",
COALESCE(NULLIF(TRIM(k."guardian_name"), ''), 'Adulto a cargo'),
k."guardian_phone",
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
FROM (
SELECT "created_by_id", TRIM("guardian_phone") AS "guardian_phone", "guardian_name", "created_at"
FROM "people"
WHERE NULLIF(TRIM("guardian_phone"), '') IS NOT NULL
) k
WHERE NOT EXISTS (
SELECT 1 FROM "people" p
WHERE p."created_by_id" = k."created_by_id" AND p."phone" = k."guardian_phone"
)
ORDER BY k."created_by_id", k."guardian_phone", k."created_at";
INSERT INTO "person_guardians" ("child_id", "guardian_id")
SELECT c."id", g."id"
FROM "people" c
JOIN "people" g
ON g."created_by_id" = c."created_by_id"
AND g."phone" = TRIM(c."guardian_phone")
AND g."id" <> c."id"
WHERE NULLIF(TRIM(c."guardian_phone"), '') IS NOT NULL;
-- AlterTable
ALTER TABLE "people" DROP COLUMN "guardian_name",
DROP COLUMN "guardian_phone";

View File

@@ -0,0 +1,114 @@
-- CreateEnum
CREATE TYPE "PaymentRunStatus" AS ENUM ('RUNNING', 'DONE', 'SKIPPED');
-- CreateEnum
CREATE TYPE "PaymentCheckoutStatus" AS ENUM ('OPEN', 'PAID', 'SUPERSEDED');
-- AlterEnum
ALTER TYPE "WhatsappMessageKind" ADD VALUE 'PAYMENT_LINK';
-- AlterTable
ALTER TABLE "outbound_messages" ADD COLUMN "checkout_id" TEXT;
-- AlterTable
ALTER TABLE "payments" ADD COLUMN "checkout_id" TEXT,
ADD COLUMN "period_key" TEXT;
-- AlterTable
ALTER TABLE "people" ADD COLUMN "pay_with_mercado_pago" BOOLEAN NOT NULL DEFAULT true;
-- CreateTable
CREATE TABLE "auto_charge_settings" (
"id" TEXT NOT NULL,
"owner_id" TEXT NOT NULL,
"enabled" BOOLEAN NOT NULL DEFAULT false,
"charge_day" INTEGER NOT NULL DEFAULT 1,
"due_in_days" INTEGER NOT NULL DEFAULT 10,
"send_whatsapp" BOOLEAN NOT NULL DEFAULT false,
"enabled_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "auto_charge_settings_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "payment_runs" (
"id" TEXT NOT NULL,
"owner_id" TEXT NOT NULL,
"period_key" TEXT NOT NULL,
"status" "PaymentRunStatus" NOT NULL DEFAULT 'RUNNING',
"skip_reason" TEXT,
"fees" INTEGER NOT NULL DEFAULT 0,
"checkouts" INTEGER NOT NULL DEFAULT 0,
"linked" INTEGER NOT NULL DEFAULT 0,
"failed" INTEGER NOT NULL DEFAULT 0,
"sent" INTEGER NOT NULL DEFAULT 0,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"finished_at" TIMESTAMP(3),
CONSTRAINT "payment_runs_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "payment_checkouts" (
"id" TEXT NOT NULL,
"owner_id" TEXT NOT NULL,
"payer_person_id" TEXT NOT NULL,
"run_id" TEXT,
"amount" DECIMAL(10,2) NOT NULL,
"currency" TEXT NOT NULL,
"due_date" TIMESTAMP(3) NOT NULL,
"checkout_url" TEXT,
"mp_preference_id" TEXT,
"mp_payment_id" TEXT,
"status" "PaymentCheckoutStatus" NOT NULL DEFAULT 'OPEN',
"paid_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "payment_checkouts_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "auto_charge_settings_owner_id_key" ON "auto_charge_settings"("owner_id");
-- CreateIndex
CREATE UNIQUE INDEX "payment_runs_owner_id_period_key_key" ON "payment_runs"("owner_id", "period_key");
-- CreateIndex
CREATE UNIQUE INDEX "payment_checkouts_mp_preference_id_key" ON "payment_checkouts"("mp_preference_id");
-- CreateIndex
CREATE INDEX "payment_checkouts_status_created_at_idx" ON "payment_checkouts"("status", "created_at");
-- CreateIndex
CREATE INDEX "payment_checkouts_owner_id_idx" ON "payment_checkouts"("owner_id");
-- CreateIndex
CREATE INDEX "payments_checkout_id_idx" ON "payments"("checkout_id");
-- AddForeignKey
ALTER TABLE "payments" ADD CONSTRAINT "payments_checkout_id_fkey" FOREIGN KEY ("checkout_id") REFERENCES "payment_checkouts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "auto_charge_settings" ADD CONSTRAINT "auto_charge_settings_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "payment_runs" ADD CONSTRAINT "payment_runs_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "payment_checkouts" ADD CONSTRAINT "payment_checkouts_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "payment_checkouts" ADD CONSTRAINT "payment_checkouts_payer_person_id_fkey" FOREIGN KEY ("payer_person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "payment_checkouts" ADD CONSTRAINT "payment_checkouts_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "payment_runs"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_checkout_id_fkey" FOREIGN KEY ("checkout_id") REFERENCES "payment_checkouts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- One automatic fee per member and month (hand-written: Prisma does not model
-- partial indexes). Manual fees have no period and stay out of it.
CREATE UNIQUE INDEX "payments_attendee_period_key" ON "payments"("attendee_id", "period_key") WHERE "period_key" IS NOT NULL;

View File

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

View File

@@ -102,6 +102,7 @@ model PlanConfig {
maxAttendees Int? @map("max_attendees") maxAttendees Int? @map("max_attendees")
whatsappAutomations Boolean @map("whatsapp_automations") whatsappAutomations Boolean @map("whatsapp_automations")
mpCharges Boolean @map("mp_charges") mpCharges Boolean @map("mp_charges")
kidsGroups Boolean @default(false) @map("kids_groups")
updatedById String? @map("updated_by_id") updatedById String? @map("updated_by_id")
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")

View File

@@ -1,22 +1,24 @@
// Domain models // Domain models
model Group { model Group {
id String @id @default(cuid()) id String @id @default(cuid())
name String name String
description String? description String?
days WeekDay[] days WeekDay[]
time String? time String?
capacity Int? capacity Int?
price Decimal? @db.Decimal(10, 2) price Decimal? @db.Decimal(10, 2)
billingType BillingType? @map("billing_type") billingType BillingType? @map("billing_type")
dueDay Int? @map("due_day") dueDay Int? @map("due_day")
// Weekly WhatsApp automations, off until the teacher turns them on. // Weekly WhatsApp automations, off until the teacher turns them on.
autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders") autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
autoReengagement Boolean @default(false) @map("auto_reengagement") autoReengagement Boolean @default(false) @map("auto_reengagement")
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token") // KIDS: each student is a kid and the contact is the adult in charge.
createdById String @map("created_by_id") audience GroupAudience @default(ADULTS)
createdAt DateTime @default(now()) @map("created_at") inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
updatedAt DateTime @updatedAt @map("updated_at") 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") owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey")
members GroupMember[] members GroupMember[]
@@ -31,6 +33,11 @@ model Group {
@@map("groups") @@map("groups")
} }
enum GroupAudience {
ADULTS
KIDS
}
enum WeekDay { enum WeekDay {
MONDAY MONDAY
TUESDAY TUESDAY
@@ -78,25 +85,48 @@ enum AttendeeStatus {
// teacher through a hand-written partial index (`people_owner_phone_key`, // teacher through a hand-written partial index (`people_owner_phone_key`,
// `WHERE phone IS NOT NULL`): Prisma does not model it. // `WHERE phone IS NOT NULL`): Prisma does not model it.
model Person { model Person {
id String @id @default(cuid()) id String @id @default(cuid())
createdById String @map("created_by_id") createdById String @map("created_by_id")
fullName String @map("full_name") fullName String @map("full_name")
email String? email String?
phone String? phone String?
guardianName String? @map("guardian_name") notes String?
guardianPhone String? @map("guardian_phone") // Automatic monthly charges only build a Mercado Pago link for people with
notes String? // this on. Off: they prefer to transfer (the fee is still created).
createdAt DateTime @default(now()) @map("created_at") payWithMercadoPago Boolean @default(true) @map("pay_with_mercado_pago")
updatedAt DateTime @updatedAt @map("updated_at") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade) owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade)
attendees Attendee[] attendees Attendee[]
studentAccounts StudentAccountPerson[] studentAccounts StudentAccountPerson[]
// As the payer of combined Mercado Pago links (themselves or their kids).
checkouts PaymentCheckout[]
// As a kid: the adult in charge (one in v1, enforced by the code).
guardians PersonGuardian[] @relation("GuardianChild")
// As the adult in charge: their kids. An adult has no memberships of their own.
children PersonGuardian[] @relation("GuardianAdult")
@@index([createdById]) @@index([createdById])
@@map("people") @@map("people")
} }
// A kid (`child`) and the adult in charge (`guardian`), both people of the same
// teacher. The adult is who gets the messages and signs in to the student app;
// siblings share the same adult, so their phone is not duplicated on each kid.
model PersonGuardian {
childId String @map("child_id")
guardianId String @map("guardian_id")
createdAt DateTime @default(now()) @map("created_at")
child Person @relation("GuardianChild", fields: [childId], references: [id], onDelete: Cascade)
guardian Person @relation("GuardianAdult", fields: [guardianId], references: [id], onDelete: Cascade)
@@id([childId, guardianId])
@@index([guardianId])
@@map("person_guardians")
}
// Membership of a person in a group. Status, attendance, fees and the absence // Membership of a person in a group. Status, attendance, fees and the absence
// link (`notifyToken`) are per group. // link (`notifyToken`) are per group.
model Attendee { model Attendee {
@@ -159,16 +189,25 @@ model Payment {
mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id") mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
mpPaymentId String? @map("mp_payment_id") mpPaymentId String? @map("mp_payment_id")
paidAt DateTime? @map("paid_at") paidAt DateTime? @map("paid_at")
// Combined link (automatic monthly charges): the fee is paid through it and
// `checkoutUrl` is a copy of the checkout's link.
checkoutId String? @map("checkout_id")
// Month of an automatic charge ("2026-12"). Unique per attendee through a
// hand-written partial index (`payments_attendee_period_key`,
// `WHERE period_key IS NOT NULL`): Prisma does not model it.
periodKey String? @map("period_key")
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey") group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey") attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
checkout PaymentCheckout? @relation(fields: [checkoutId], references: [id], onDelete: SetNull)
outboundMessages OutboundMessage[] outboundMessages OutboundMessage[]
reportedItems ReportedPaymentItem[] reportedItems ReportedPaymentItem[]
@@index([groupId], map: "payments_groupId_idx") @@index([groupId], map: "payments_groupId_idx")
@@index([attendeeId], map: "payments_attendeeId_idx") @@index([attendeeId], map: "payments_attendeeId_idx")
@@index([checkoutId])
@@map("payments") @@map("payments")
} }

View File

@@ -0,0 +1,91 @@
// Automatic monthly charges and combined Mercado Pago links.
//
// On the teacher's day of the month a run creates the fee of every active
// member of their monthly groups and one Checkout Pro link per payer: the adult
// in charge for kids, the person themselves otherwise. The link covers all the
// payer's fees (`PaymentCheckout` + `Payment.checkoutId`); its
// `external_reference` is `chk_<checkout id>`.
// One per teacher. Off until the teacher turns it on.
model AutoChargeSettings {
id String @id @default(cuid())
ownerId String @unique @map("owner_id")
enabled Boolean @default(false)
// Day of the month (1-28) in the teacher's time zone.
chargeDay Int @default(1) @map("charge_day")
dueInDays Int @default(10) @map("due_in_days")
sendWhatsapp Boolean @default(false) @map("send_whatsapp")
// Last time `enabled` went on: a month whose day already passed is skipped.
enabledAt DateTime? @map("enabled_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
@@map("auto_charge_settings")
}
enum PaymentRunStatus {
RUNNING
DONE
SKIPPED
}
// One automatic run per teacher and month: the unique key is what makes a
// second tick of the job (or a second server) a no-op.
model PaymentRun {
id String @id @default(cuid())
ownerId String @map("owner_id")
periodKey String @map("period_key")
status PaymentRunStatus @default(RUNNING)
skipReason String? @map("skip_reason")
fees Int @default(0)
checkouts Int @default(0)
linked Int @default(0)
failed Int @default(0)
sent Int @default(0)
createdAt DateTime @default(now()) @map("created_at")
finishedAt DateTime? @map("finished_at")
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
checkoutsList PaymentCheckout[]
@@unique([ownerId, periodKey])
@@map("payment_runs")
}
enum PaymentCheckoutStatus {
OPEN
PAID
// A fee was paid some other way (e.g. a confirmed transfer): the link is
// expired and the remaining fees get links of their own.
SUPERSEDED
}
// One Mercado Pago link covering several fees of the same payer.
model PaymentCheckout {
id String @id @default(cuid())
ownerId String @map("owner_id")
payerPersonId String @map("payer_person_id")
runId String? @map("run_id")
amount Decimal @db.Decimal(10, 2)
currency String
dueDate DateTime @map("due_date")
checkoutUrl String? @map("checkout_url")
mpPreferenceId String? @unique @map("mp_preference_id")
mpPaymentId String? @map("mp_payment_id")
status PaymentCheckoutStatus @default(OPEN)
paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
payer Person @relation(fields: [payerPersonId], references: [id], onDelete: Cascade)
run PaymentRun? @relation(fields: [runId], references: [id], onDelete: SetNull)
payments Payment[]
outboundMessages OutboundMessage[]
@@index([status, createdAt])
@@index([ownerId])
@@map("payment_checkouts")
}

View File

@@ -19,6 +19,8 @@ enum WhatsappAccountStatus {
enum WhatsappMessageKind { enum WhatsappMessageKind {
PAYMENT_REMINDER PAYMENT_REMINDER
REENGAGEMENT REENGAGEMENT
// The monthly combined payment link, sent when it is generated.
PAYMENT_LINK
} }
enum OutboundMessageStatus { enum OutboundMessageStatus {
@@ -92,9 +94,10 @@ model OutboundMessage {
groupId String @map("group_id") groupId String @map("group_id")
attendeeId String @map("attendee_id") attendeeId String @map("attendee_id")
paymentId String? @map("payment_id") paymentId String? @map("payment_id")
checkoutId String? @map("checkout_id")
kind WhatsappMessageKind kind WhatsappMessageKind
provider MessagingProviderId provider MessagingProviderId
// ISO week the job ran for, e.g. "2026-W43". // ISO week the job ran for, e.g. "2026-W43"; the month ("2026-12") for PAYMENT_LINK.
periodKey String @map("period_key") periodKey String @map("period_key")
toPhone String @map("to_phone") toPhone String @map("to_phone")
providerMessageId String? @map("provider_message_id") providerMessageId String? @map("provider_message_id")
@@ -105,9 +108,10 @@ model OutboundMessage {
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "outbound_messages_groupId_fkey") group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "outbound_messages_groupId_fkey")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "outbound_messages_attendeeId_fkey") attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "outbound_messages_attendeeId_fkey")
payment Payment? @relation(fields: [paymentId], references: [id], onDelete: SetNull, map: "outbound_messages_paymentId_fkey") payment Payment? @relation(fields: [paymentId], references: [id], onDelete: SetNull, map: "outbound_messages_paymentId_fkey")
checkout PaymentCheckout? @relation(fields: [checkoutId], references: [id], onDelete: SetNull)
@@unique([kind, attendeeId, periodKey], map: "outbound_messages_kind_attendeeId_periodKey_key") @@unique([kind, attendeeId, periodKey], map: "outbound_messages_kind_attendeeId_periodKey_key")
@@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key") @@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key")

View File

@@ -1,4 +1,4 @@
import type { ProblemDetails } from '@gruperly/shared'; import type { PlanFeature, ProblemDetails } from '@gruperly/shared';
import { notFoundProblem } from './problem-details'; import { notFoundProblem } from './problem-details';
import { PROBLEM_DOMAIN } from './problem-domain'; import { PROBLEM_DOMAIN } from './problem-domain';
@@ -248,13 +248,16 @@ export function planLimitReachedProblem(limit: PlanLimitKind, max: number): Prob
}); });
} }
/** A Pro-only feature: charging students with Mercado Pago or WhatsApp automations. */ const PLAN_FEATURE_DETAIL: Record<PlanFeature, string> = {
export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutomations'): ProblemDetails { mpCharges: 'Cobrar con Mercado Pago está disponible en el plan Pro.',
whatsappAutomations: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
kidsGroups: 'Los grupos de chicos con adulto a cargo están disponibles en el plan Pro.',
};
/** A feature the owner's plan does not include (Mercado Pago, WhatsApp automations, kids groups). */
export function planFeatureRequiredProblem(feature: PlanFeature): ProblemDetails {
return paymentRequiredProblem({ return paymentRequiredProblem({
detail: detail: PLAN_FEATURE_DETAIL[feature],
feature === 'mpCharges'
? 'Cobrar con Mercado Pago está disponible en el plan Pro.'
: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
code: 'plan_feature_required', code: 'plan_feature_required',
params: { feature }, params: { feature },
}); });

View File

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

View File

@@ -9,6 +9,7 @@ import type {
import { ok, summarizeMemberAttendance } from '@gruperly/shared'; import { ok, summarizeMemberAttendance } from '@gruperly/shared';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { flattenPerson } from '@/modules/attendees/lib/helpers'; import { flattenPerson } from '@/modules/attendees/lib/helpers';
import { contactPhone, guardianSelect } from '@/modules/people/lib/people';
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance'; import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk'; import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
@@ -74,7 +75,7 @@ export async function findStudentsAtRisk(
}), }),
db.attendee.findMany({ db.attendee.findMany({
where: { groupId, status: 'ACTIVE' }, where: { groupId, status: 'ACTIVE' },
select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true } } }, select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true, ...guardianSelect } } },
}).then((rows) => rows.map(flattenPerson)), }).then((rows) => rows.map(flattenPerson)),
db.attendance.findMany({ db.attendance.findMany({
where: { attendee: { groupId } }, where: { attendee: { groupId } },
@@ -111,7 +112,8 @@ export async function findStudentsAtRisk(
atRisk.push({ atRisk.push({
attendeeId: attendee.id, attendeeId: attendee.id,
fullName: attendee.fullName, fullName: attendee.fullName,
phone: attendee.phone, // The number to reach them on: the adult in charge for a kid.
phone: contactPhone(attendee),
riskLevel, riskLevel,
consecutiveAbsences, consecutiveAbsences,
lastAttendedAt: attendedAt ? attendedAt.toISOString() : null, lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,

View File

@@ -1,5 +1,5 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import type { CreateAttendee, CreateAttendeeResult, ProblemDetails, Result } from '@gruperly/shared'; import type { CreateAttendee, CreateAttendeeResult, GuardianInput, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared';
import { import {
alreadyWaitlistedProblem, alreadyWaitlistedProblem,
@@ -11,9 +11,13 @@ import prisma from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { import {
alreadyInGroupProblem, alreadyInGroupProblem,
contactPhone,
findPersonByPhone, findPersonByPhone,
guardianRequiredProblem,
guardianSelect,
isUniqueViolation, isUniqueViolation,
personExistsProblem, personExistsProblem,
type WithGuardians,
} from '@/modules/people/lib/people'; } from '@/modules/people/lib/people';
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers'; import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
@@ -54,27 +58,51 @@ export class CreateAttendeeUseCase {
return err(noGroupAccessProblem()); return err(noGroupAccessProblem());
} }
const phone = normalizePhone(payload.phone); const isKidsGroup = group.audience === 'KIDS';
if (isKidsGroup && !payload.personId && !payload.guardian) {
return err(guardianRequiredProblem());
}
// A kid may have no phone of their own: the adult in charge is the contact.
const phone = payload.phone ? normalizePhone(payload.phone) : null;
/* The person: the one the form picked (`personId`, after the "ya existe" /* The person: the one the form picked (`personId`, after the "ya existe"
hint) or a new one. A phone the teacher already has is never duplicated. */ hint) or a new one. A phone the teacher already has is never duplicated. */
let person: { id: string; fullName: string } | null = null; let person: ({ id: string; fullName: string; phone: string | null } & WithGuardians) | null = null;
// Kids groups: the adult in charge, already one of the teacher's people or new.
let guardian: { id: string } | null = null;
if (payload.personId) { if (payload.personId) {
person = await db.person.findFirst({ person = await db.person.findFirst({
where: { id: payload.personId, createdById: group.createdById }, where: { id: payload.personId, createdById: group.createdById },
select: { id: true, fullName: true }, select: { id: true, fullName: true, phone: true, ...guardianSelect },
}); });
if (!person) { if (!person) {
return err(notFoundResourceProblem('Person', payload.personId)); return err(notFoundResourceProblem('Person', payload.personId));
} }
} else { } else {
const samePhone = await findPersonByPhone(db, group.createdById, payload.phone); if (payload.phone) {
if (samePhone) { // The raw phone: its variants also match older rows stored as typed.
return err( const samePhone = await findPersonByPhone(db, group.createdById, payload.phone);
samePhone.attendees.some((membership) => membership.groupId === groupId) if (samePhone) {
? alreadyInGroupProblem() return err(
: personExistsProblem(), samePhone.attendees.some((membership) => membership.groupId === groupId)
); ? alreadyInGroupProblem()
: personExistsProblem(),
);
}
}
if (payload.guardian) {
guardian = await findPersonByPhone(db, group.createdById, payload.guardian.phone);
// The same kid of the same adult (same name) is that kid, not a twin.
if (guardian) {
person = await db.person.findFirst({
where: {
createdById: group.createdById,
fullName: { equals: kidFullName(payload), mode: 'insensitive' },
guardians: { some: { guardianId: guardian.id } },
},
select: { id: true, fullName: true, phone: true, ...guardianSelect },
});
}
} }
} }
@@ -86,7 +114,12 @@ export class CreateAttendeeUseCase {
return err(alreadyInGroupProblem()); return err(alreadyInGroupProblem());
} }
const fullName = person?.fullName ?? `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim(); const fullName = person?.fullName ?? kidFullName(payload);
// Who the waitlist row (and later the messages) reaches.
const reachPhone =
(person ? contactPhone(person) : null) ??
phone ??
(payload.guardian ? normalizePhone(payload.guardian.phone) : null);
if (group.capacity !== null) { if (group.capacity !== null) {
const currentCount = await db.attendee.count({ const currentCount = await db.attendee.count({
@@ -99,9 +132,9 @@ export class CreateAttendeeUseCase {
} }
if (!isOwner) { if (!isOwner) {
const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({ const existingWaitlistEntry = reachPhone
where: { groupId, phone }, ? await db.groupWaitlistEntry.findFirst({ where: { groupId, phone: reachPhone } })
}); : null;
if (existingWaitlistEntry) { if (existingWaitlistEntry) {
return err(alreadyWaitlistedProblem()); return err(alreadyWaitlistedProblem());
@@ -111,7 +144,7 @@ export class CreateAttendeeUseCase {
data: { data: {
groupId, groupId,
fullName, fullName,
phone, phone: reachPhone ?? '',
email: payload.email?.trim() || null, email: payload.email?.trim() || null,
notes: payload.notes?.trim() || null, notes: payload.notes?.trim() || null,
}, },
@@ -157,6 +190,7 @@ export class CreateAttendeeUseCase {
phone, phone,
email: payload.email?.trim() || null, email: payload.email?.trim() || null,
notes: payload.notes?.trim() || null, notes: payload.notes?.trim() || null,
...(payload.guardian ? { guardians: { create: guardianLink(group.createdById, payload.guardian, guardian) } } : {}),
}, },
}, },
}, },
@@ -173,3 +207,24 @@ export class CreateAttendeeUseCase {
} }
} }
} }
function kidFullName(payload: CreateAttendee): string {
return `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
}
/* Nested create of the kid's link to the adult in charge: the existing adult,
or a new person with the adult's data. */
function guardianLink(ownerId: string, input: GuardianInput, existing: { id: string } | null) {
return {
guardian: existing
? { connect: { id: existing.id } }
: {
create: {
createdById: ownerId,
fullName: input.fullName.trim(),
phone: normalizePhone(input.phone),
email: input.email?.trim() || null,
},
},
};
}

View File

@@ -4,11 +4,11 @@ import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders'; import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { personMembershipsSelect, toMemberships } from '@/modules/people/lib/people'; import { personMembershipsSelect, primaryGuardian, toMemberships } from '@/modules/people/lib/people';
import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers'; import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers';
type GetAttendeeDeps = { type GetAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>; db?: Pick<PrismaClient, 'group' | 'attendee' | 'personGuardian'>;
now?: () => Date; now?: () => Date;
}; };
@@ -48,11 +48,21 @@ export class GetAttendee {
} }
const { attendees: memberships, ...person } = attendee.person; const { attendees: memberships, ...person } = attendee.person;
// The other kids of the same adult in charge.
const guardian = primaryGuardian(person);
const siblings = guardian
? await db.personGuardian.findMany({
where: { guardianId: guardian.id, childId: { not: person.id } },
orderBy: { createdAt: 'asc' },
select: { child: { select: { id: true, fullName: true } } },
})
: [];
return ok( return ok(
toAttendeeDetailDto({ toAttendeeDetailDto({
...attendee, ...attendee,
person, person,
otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)), otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)),
siblings: siblings.map(({ child }) => ({ personId: child.id, fullName: child.fullName })),
}), }),
); );
} }

View File

@@ -0,0 +1,24 @@
import type { GuardianInput } from '@gruperly/shared';
import { GuardianInputSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { UpdateAttendeeGuardian } from './use-case';
/** `PATCH /groups/:groupId/attendees/:attendeeId/guardian`. */
const route = new Hono();
route.patch('/:groupId/attendees/:attendeeId/guardian', validate.json(GuardianInputSchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const result = await new UpdateAttendeeGuardian().execute({
groupId: c.req.param('groupId'),
attendeeId: c.req.param('attendeeId'),
userId: user.id,
input: c.req.valid('json') as GuardianInput,
});
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,75 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { AttendeeDto, GuardianInput, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import {
findOrCreateGuardian,
guardianSelect,
isUniqueViolation,
personPhoneTakenProblem,
primaryGuardian,
} from '@/modules/people/lib/people';
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type UpdateGuardianDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'person' | 'personGuardian'>;
};
type UpdateGuardianCommand = {
groupId: string;
attendeeId: string;
userId: string;
input: GuardianInput;
};
/**
* The adult in charge of a kid, from the kid's page. With an adult already
* linked it edits that adult (a person of their own, so it shows on every
* sibling); without one it links the adult with that phone, or a new one.
*/
export class UpdateAttendeeGuardian {
constructor(private readonly deps: UpdateGuardianDeps = {}) {}
async execute(command: UpdateGuardianCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
const { groupId, attendeeId, userId, input } = command;
const db = this.deps.db ?? prisma;
const access = await findGroupForUser(db, groupId, userId);
if (!access.ok) return access;
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
select: { personId: true, person: { select: { id: true, phone: true, ...guardianSelect } } },
});
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
const current = primaryGuardian(attendee.person);
try {
if (current) {
await db.person.update({
where: { id: current.id },
data: {
fullName: input.fullName.trim(),
phone: normalizePhone(input.phone),
email: input.email?.trim() || null,
},
});
} else {
const guardian = await findOrCreateGuardian(db, access.value.createdById, input);
// The kid's own phone is not an adult in charge of themselves.
if (guardian.id === attendee.personId) return err(personPhoneTakenProblem());
await db.personGuardian.create({ data: { childId: attendee.personId, guardianId: guardian.id } });
}
} catch (error) {
if (isUniqueViolation(error)) return err(personPhoneTakenProblem());
throw error;
}
const updated = await db.attendee.findUniqueOrThrow({
where: { id: attendeeId },
include: attendeeWithPerson,
});
return ok(toAttendeeDto(updated));
}
}

View File

@@ -1,4 +1,5 @@
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared'; import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
import { type GuardianContact, guardianSelect, primaryGuardian } from '@/modules/people/lib/guardians';
/* Contact data of the person behind an attendee (shared by all their groups). */ /* Contact data of the person behind an attendee (shared by all their groups). */
export const personContactSelect = { export const personContactSelect = {
@@ -6,9 +7,9 @@ export const personContactSelect = {
fullName: true, fullName: true,
email: true, email: true,
phone: true, phone: true,
guardianName: true,
guardianPhone: true,
notes: true, notes: true,
payWithMercadoPago: true,
...guardianSelect,
} as const; } as const;
/* `include` for any attendee query that ends up in `toAttendeeDto`. */ /* `include` for any attendee query that ends up in `toAttendeeDto`. */
@@ -19,9 +20,9 @@ export type PersonContactRecord = {
fullName: string; fullName: string;
email: string | null; email: string | null;
phone: string | null; phone: string | null;
guardianName: string | null;
guardianPhone: string | null;
notes: string | null; notes: string | null;
payWithMercadoPago?: boolean;
guardians?: { guardian: GuardianContact }[];
}; };
export type AttendeeRecord = { export type AttendeeRecord = {
@@ -46,8 +47,20 @@ export type AttendeeListItemRecord = AttendeeRecord & {
export type AttendeeDetailRecord = AttendeeRecord & { export type AttendeeDetailRecord = AttendeeRecord & {
payments: AttendeeListItemRecord['payments']; payments: AttendeeListItemRecord['payments'];
otherGroups: AttendeeDetailDto['otherGroups']; otherGroups: AttendeeDetailDto['otherGroups'];
siblings?: AttendeeDetailDto['siblings'];
}; };
/* The adult in charge, flattened into the attendee DTO (all null when none). */
export function guardianFields(person: { guardians?: { guardian: GuardianContact }[] }) {
const guardian = primaryGuardian(person);
return {
guardianPersonId: guardian?.id ?? null,
guardianName: guardian?.fullName ?? null,
guardianPhone: guardian?.phone ?? null,
guardianEmail: guardian?.email ?? null,
};
}
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto { export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
return { return {
id: record.id, id: record.id,
@@ -56,9 +69,9 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
fullName: record.person.fullName, fullName: record.person.fullName,
email: record.person.email, email: record.person.email,
phone: record.person.phone, phone: record.person.phone,
guardianName: record.person.guardianName, ...guardianFields(record.person),
guardianPhone: record.person.guardianPhone,
notes: record.person.notes, notes: record.person.notes,
payWithMercadoPago: record.person.payWithMercadoPago ?? true,
notifyToken: record.notifyToken ?? null, notifyToken: record.notifyToken ?? null,
createdAt: record.createdAt.toISOString(), createdAt: record.createdAt.toISOString(),
updatedAt: record.updatedAt.toISOString(), updatedAt: record.updatedAt.toISOString(),
@@ -91,6 +104,7 @@ export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetai
...toAttendeeDto(record), ...toAttendeeDto(record),
payment: pickRelevantPayment(record.payments), payment: pickRelevantPayment(record.payments),
otherGroups: record.otherGroups, otherGroups: record.otherGroups,
siblings: record.siblings ?? [],
}; };
} }

View File

@@ -13,7 +13,7 @@ import prisma from '@/lib/prisma';
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance'; import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
import { flattenPerson } from '@/modules/attendees/lib/helpers'; import { flattenPerson } from '@/modules/attendees/lib/helpers';
import { buildGroupWhereForUser } from '@/modules/groups/lib'; import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { contactPhone } from '@/modules/people/lib/people'; import { contactPhone, guardianSelect } from '@/modules/people/lib/people';
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind'; import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
type GetAttentionOverviewDeps = { type GetAttentionOverviewDeps = {
@@ -35,7 +35,7 @@ type AttendeeRow = {
groupId: string; groupId: string;
fullName: string; fullName: string;
phone: string | null; phone: string | null;
guardianPhone: string | null; guardians?: { guardian: { phone: string | null } }[];
createdAt: Date; createdAt: Date;
}; };
type SessionRow = { id: string; groupId: string; startsAt: Date }; type SessionRow = { id: string; groupId: string; startsAt: Date };
@@ -88,7 +88,7 @@ export class GetAttentionOverview {
id: true, id: true,
groupId: true, groupId: true,
createdAt: true, createdAt: true,
person: { select: { fullName: true, phone: true, guardianPhone: true } }, person: { select: { fullName: true, phone: true, ...guardianSelect } },
}, },
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)), }).then((rows): AttendeeRow[] => rows.map(flattenPerson)),

View File

@@ -58,6 +58,7 @@ export class PlanCatalog {
maxAttendees: config.maxAttendees, maxAttendees: config.maxAttendees,
whatsappAutomations: config.whatsappAutomations, whatsappAutomations: config.whatsappAutomations,
mpCharges: config.mpCharges, mpCharges: config.mpCharges,
kidsGroups: config.kidsGroups,
}; };
} }
for (const price of prices) { for (const price of prices) {

View File

@@ -13,7 +13,7 @@ import { type GroupRecord, toGroupDto } from '../../lib';
type CreateGroupDeps = { type CreateGroupDeps = {
unitOfWork?: UnitOfWork; unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canCreateGroup'>; planGuard?: Pick<PlanGuard, 'canCreateGroup' | 'requireFeature'>;
}; };
export class CreateGroup { export class CreateGroup {
@@ -25,10 +25,15 @@ export class CreateGroup {
): Promise<Result<CreateGroupResult, ProblemDetails>> { ): Promise<Result<CreateGroupResult, ProblemDetails>> {
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId); const planGuard = this.deps.planGuard ?? new PlanGuard();
const allowed = await planGuard.canCreateGroup(userId);
if (!allowed.ok) { if (!allowed.ok) {
return allowed; return allowed;
} }
if (data.audience === 'KIDS') {
const kidsAllowed = await planGuard.requireFeature(userId, 'kidsGroups');
if (!kidsAllowed.ok) return kidsAllowed;
}
const transaction = unitOfWork.executeResult( const transaction = unitOfWork.executeResult(
async (tx: Prisma.TransactionClient) => { async (tx: Prisma.TransactionClient) => {
@@ -42,6 +47,7 @@ export class CreateGroup {
price: data.price, price: data.price,
billingType: data.billingType, billingType: data.billingType,
dueDay: data.dueDay, dueDay: data.dueDay,
audience: data.audience,
}, },
}); });

View File

@@ -0,0 +1,20 @@
import type { UpdateGroup } from '@gruperly/shared';
import { UpdateGroupSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { UpdateGroupUseCase } from './use-case';
/** `PATCH /groups/:groupId` ("Editar grupo"). */
const route = new Hono();
route.patch('/:groupId', validate.json(UpdateGroupSchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const input = c.req.valid('json') as UpdateGroup;
const result = await new UpdateGroupUseCase().execute(c.req.param('groupId'), user.id, input);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,66 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { GroupDto, ProblemDetails, Result, UpdateGroup } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { conflictProblem, forbiddenProblem, notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { type GroupRecord, toGroupDto } from '../../lib';
type UpdateGroupDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>;
planGuard?: Pick<PlanGuard, 'requireFeature'>;
};
/**
* "Editar grupo": name, schedule, capacity, billing and who it is for. Only
* the owner can. A lower capacity than the current members is allowed: it only
* stops new additions.
*
* Who it is for: turning it into a kids group needs the `kidsGroups` plan
* feature (a kids group that already exists keeps working after a downgrade);
* going back to adults is blocked while a member has no phone of their own,
* since without the adult in charge nobody could be reached.
*/
export class UpdateGroupUseCase {
constructor(private readonly deps: UpdateGroupDeps = {}) {}
async execute(groupId: string, userId: string, input: UpdateGroup): Promise<Result<GroupDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const group = await db.group.findUnique({
where: { id: groupId },
select: { id: true, createdById: true, audience: true },
});
if (!group) return err(notFoundResourceProblem('Group', groupId));
if (group.createdById !== userId) {
return err(
forbiddenProblem({
detail: 'Solo quien creó el grupo puede editarlo.',
code: 'group_owner_required',
}),
);
}
if (input.audience === 'KIDS' && group.audience !== 'KIDS') {
const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature(userId, 'kidsGroups');
if (!allowed.ok) return allowed;
}
if (input.audience === 'ADULTS' && group.audience === 'KIDS') {
const withoutPhone = await db.attendee.count({
where: { groupId, status: { not: 'DROPPED' }, person: { phone: null } },
});
if (withoutPhone > 0) {
return err(
conflictProblem({
detail: 'Hay chicos sin teléfono propio: cargales uno antes de pasar el grupo a adultos.',
code: 'group_has_kids_without_phone',
params: { count: withoutPhone },
}),
);
}
}
const updated = await db.group.update({ where: { id: groupId }, data: input });
return ok(toGroupDto(updated as GroupRecord));
}
}

View File

@@ -1,5 +1,5 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import type { BillingType, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared'; import type { BillingType, GroupAudience, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared';
export type GroupDb = Pick<PrismaClient, 'group' | 'groupMember'>; export type GroupDb = Pick<PrismaClient, 'group' | 'groupMember'>;
@@ -21,6 +21,7 @@ export type GroupRecord = {
inviteToken?: string | null; inviteToken?: string | null;
autoPaymentReminders?: boolean; autoPaymentReminders?: boolean;
autoReengagement?: boolean; autoReengagement?: boolean;
audience?: GroupAudience;
}; };
/* The listing adds the occupancy counters to each group so the card can show /* The listing adds the occupancy counters to each group so the card can show
@@ -49,6 +50,7 @@ export function toGroupDto(record: GroupRecord): GroupDto {
inviteToken: record.inviteToken ?? null, inviteToken: record.inviteToken ?? null,
autoPaymentReminders: record.autoPaymentReminders ?? false, autoPaymentReminders: record.autoPaymentReminders ?? false,
autoReengagement: record.autoReengagement ?? false, autoReengagement: record.autoReengagement ?? false,
audience: record.audience ?? 'ADULTS',
}; };
} }

View File

@@ -9,6 +9,7 @@ import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
import moveAttendeeRoute from '../attendees/features/move/route'; import moveAttendeeRoute from '../attendees/features/move/route';
import removeAttendeeRoute from '../attendees/features/remove/route'; import removeAttendeeRoute from '../attendees/features/remove/route';
import updateAttendeeRoute from '../attendees/features/update/route'; import updateAttendeeRoute from '../attendees/features/update/route';
import updateAttendeeGuardianRoute from '../attendees/features/update-guardian/route';
import groupPreRegistrationRoutes from '../group-preregistrations/routes'; import groupPreRegistrationRoutes from '../group-preregistrations/routes';
import groupWaitlistRoutes from '../group-waitlist/routes'; import groupWaitlistRoutes from '../group-waitlist/routes';
import createPaymentsBatchRoute from '../payments/features/create-batch/route'; import createPaymentsBatchRoute from '../payments/features/create-batch/route';
@@ -19,6 +20,7 @@ import getAllRoute from './features/get-all/route';
import getByIdRoute from './features/get-by-id/route'; import getByIdRoute from './features/get-by-id/route';
import inviteTokenRoute from './features/invite-token/route'; import inviteTokenRoute from './features/invite-token/route';
import listAttendeesRoute from './features/list-attendees/route'; import listAttendeesRoute from './features/list-attendees/route';
import updateGroupRoute from './features/update/route';
const routes = new Hono(); const routes = new Hono();
@@ -31,12 +33,14 @@ routes.route('/', bulkCreateAttendeesRoute);
routes.route('/', getByIdRoute); routes.route('/', getByIdRoute);
routes.route('/', createPaymentsBatchRoute); routes.route('/', createPaymentsBatchRoute);
routes.route('/', updateGroupAutomationsRoute); routes.route('/', updateGroupAutomationsRoute);
routes.route('/', updateGroupRoute);
routes.route('/', addToGroupWaitlistRoute); routes.route('/', addToGroupWaitlistRoute);
routes.route('/', groupWaitlistRoutes); routes.route('/', groupWaitlistRoutes);
routes.route('/', groupPreRegistrationRoutes); routes.route('/', groupPreRegistrationRoutes);
routes.route('/', analyticsRoutes); routes.route('/', analyticsRoutes);
routes.route('/', getAttendeeRoute); routes.route('/', getAttendeeRoute);
routes.route('/', updateAttendeeRoute); routes.route('/', updateAttendeeRoute);
routes.route('/', updateAttendeeGuardianRoute);
routes.route('/', getAttendeeStatsRoute); routes.route('/', getAttendeeStatsRoute);
routes.route('/', removeAttendeeRoute); routes.route('/', removeAttendeeRoute);
routes.route('/', moveAttendeeRoute); routes.route('/', moveAttendeeRoute);

View File

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

View File

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

View File

@@ -16,7 +16,7 @@ import { toOnboardingGroupDto } from '../../lib';
type CreateFirstGroupDeps = { type CreateFirstGroupDeps = {
db?: Pick<PrismaClient, 'user'>; db?: Pick<PrismaClient, 'user'>;
unitOfWork?: UnitOfWork; unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canCreateGroup'>; planGuard?: Pick<PlanGuard, 'canCreateGroup' | 'requireFeature'>;
}; };
export class CreateFirstGroup { export class CreateFirstGroup {
@@ -41,10 +41,15 @@ export class CreateFirstGroup {
return err(planNotSelectedProblem()); return err(planNotSelectedProblem());
} }
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId); const planGuard = this.deps.planGuard ?? new PlanGuard();
const allowed = await planGuard.canCreateGroup(userId);
if (!allowed.ok) { if (!allowed.ok) {
return allowed; return allowed;
} }
if (data.audience === 'KIDS') {
const kidsAllowed = await planGuard.requireFeature(userId, 'kidsGroups');
if (!kidsAllowed.ok) return kidsAllowed;
}
const transaction = unitOfWork.executeResult( const transaction = unitOfWork.executeResult(
async (tx: Prisma.TransactionClient) => { async (tx: Prisma.TransactionClient) => {
@@ -58,6 +63,7 @@ export class CreateFirstGroup {
price: data.price, price: data.price,
billingType: data.billingType, billingType: data.billingType,
dueDay: data.dueDay, dueDay: data.dueDay,
audience: data.audience,
}, },
}); });

View File

@@ -1,4 +1,4 @@
import type { BillingType, OnboardingGroupDto, WeekDay } from '@gruperly/shared'; import type { BillingType, GroupAudience, OnboardingGroupDto, WeekDay } from '@gruperly/shared';
type PriceLike = { toString(): string }; type PriceLike = { toString(): string };
@@ -17,6 +17,7 @@ export type OnboardingGroupRecord = {
dueDay: number | null; dueDay: number | null;
autoPaymentReminders?: boolean; autoPaymentReminders?: boolean;
autoReengagement?: boolean; autoReengagement?: boolean;
audience?: GroupAudience;
}; };
export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingGroupDto { export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingGroupDto {
@@ -35,5 +36,6 @@ export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingG
dueDay: record.dueDay, dueDay: record.dueDay,
autoPaymentReminders: record.autoPaymentReminders ?? false, autoPaymentReminders: record.autoPaymentReminders ?? false,
autoReengagement: record.autoReengagement ?? false, autoReengagement: record.autoReengagement ?? false,
audience: record.audience ?? 'ADULTS',
}; };
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,21 @@
/* Kept apart from `people.ts` (no imports): `attendees/lib/helpers.ts` spreads
`guardianSelect` at load time and `people.ts` imports from it. */
/* The adult in charge of a kid (`PersonGuardian`). One per kid in v1: the
oldest link wins if there were ever more. */
export const guardianSelect = {
guardians: {
take: 1,
orderBy: { createdAt: 'asc' },
select: { guardian: { select: { id: true, fullName: true, phone: true, email: true } } },
},
} as const;
export type GuardianContact = { id: string; fullName: string; phone: string | null; email: string | null };
export type WithGuardians = { guardians?: { guardian: Partial<GuardianContact> & { phone: string | null } }[] };
export function primaryGuardian<T extends { phone: string | null }>(person: {
guardians?: { guardian: T }[];
}): T | null {
return person.guardians?.[0]?.guardian ?? null;
}

View File

@@ -1,7 +1,11 @@
import { Prisma, type PrismaClient } from '@generated/prisma/client'; import { Prisma, type PrismaClient } from '@generated/prisma/client';
import type { PersonMembership, PersonSummary, ProblemDetails } from '@gruperly/shared'; import type { PersonMembership, PersonSummary, ProblemDetails } from '@gruperly/shared';
import { conflictProblem } from '@/http/problem-builders'; import { conflictProblem } from '@/http/problem-builders';
import { problemDetails } from '@/http/problem-details';
import { normalizePhone } from '@/modules/attendees/lib/helpers'; import { normalizePhone } from '@/modules/attendees/lib/helpers';
import { primaryGuardian, type WithGuardians } from './guardians';
export { type GuardianContact, guardianSelect, primaryGuardian, type WithGuardians } from './guardians';
/* A person is the teacher's contact (student, or a guardian's child); their /* A person is the teacher's contact (student, or a guardian's child); their
`attendees` are the memberships in each group. The phone is unique per `attendees` are the memberships in each group. The phone is unique per
@@ -60,12 +64,27 @@ export async function findPersonSummaryByPhone(
): Promise<PersonSummary | null> { ): Promise<PersonSummary | null> {
const person = await findPersonByPhone(db, ownerId, rawPhone); const person = await findPersonByPhone(db, ownerId, rawPhone);
if (!person) return null; if (!person) return null;
// When the phone is an adult in charge, the add form offers their kids.
const links = await db.person.findUnique({
where: { id: person.id },
select: {
children: {
orderBy: { createdAt: 'asc' },
select: { child: { select: { id: true, fullName: true, ...personMembershipsSelect } } },
},
},
});
return { return {
id: person.id, id: person.id,
fullName: person.fullName, fullName: person.fullName,
email: person.email, email: person.email,
phone: person.phone, phone: person.phone,
groups: toMemberships(person.attendees), groups: toMemberships(person.attendees),
children: (links?.children ?? []).map(({ child }) => ({
id: child.id,
fullName: child.fullName,
groups: toMemberships(child.attendees),
})),
}; };
} }
@@ -109,9 +128,24 @@ export async function countsAsNewStudent(db: PeopleDb, ownerId: string, rawPhone
return !person?.attendees.some((membership) => membership.status === 'ACTIVE'); return !person?.attendees.some((membership) => membership.status === 'ACTIVE');
} }
/* The number the teacher reaches the person on: theirs, or the guardian's. */ /* The number the teacher reaches the person on: the adult in charge when there
export function contactPhone(person: { phone: string | null; guardianPhone: string | null }): string | null { is one (a kid's own phone, if any, is not who answers for them), else theirs. */
return person.phone ?? person.guardianPhone; export function contactPhone(person: { phone: string | null } & WithGuardians): string | null {
return primaryGuardian(person)?.phone ?? person.phone;
}
/* The adult in charge, found by phone among the teacher's people (their stored
data wins, like any other person) or created. */
export async function findOrCreateGuardian(
db: PeopleDb,
ownerId: string,
data: { fullName: string; phone: string; email?: string | null },
): Promise<{ id: string; created: boolean }> {
return findOrCreatePerson(db, ownerId, {
fullName: data.fullName.trim(),
phone: normalizePhone(data.phone),
email: data.email?.trim() || null,
});
} }
export function isUniqueViolation(error: unknown): boolean { export function isUniqueViolation(error: unknown): boolean {
@@ -134,6 +168,16 @@ export function personExistsProblem(): ProblemDetails {
}); });
} }
/* A kids group: each new kid needs the adult in charge. */
export function guardianRequiredProblem(): ProblemDetails {
return problemDetails({
title: 'Bad Request',
status: 400,
detail: 'En un grupo de chicos tenés que cargar al adulto a cargo.',
code: 'guardian_required',
});
}
export function personPhoneTakenProblem(): ProblemDetails { export function personPhoneTakenProblem(): ProblemDetails {
return conflictProblem({ return conflictProblem({
detail: 'Otra persona que tenés registrada ya usa este número de teléfono.', detail: 'Otra persona que tenés registrada ya usa este número de teléfono.',

View File

@@ -4,6 +4,7 @@ import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders'; import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { guardianSelect } from '@/modules/people/lib/guardians';
import { computeStudentAccess } from '../../lib/status'; import { computeStudentAccess } from '../../lib/status';
type GetStudentAccessDeps = { type GetStudentAccessDeps = {
@@ -23,9 +24,14 @@ export class GetStudentAccess {
const access = await findGroupForUser(db, groupId, userId); const access = await findGroupForUser(db, groupId, userId);
if (!access.ok) return access; if (!access.ok) return access;
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { personId: true } }); const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
select: { personId: true, person: { select: guardianSelect } },
});
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
return ok(await computeStudentAccess(db, attendee.personId, this.deps.now ?? new Date())); // A kid with an adult in charge uses the adult's account (shared by siblings).
const ownerId = attendee.person.guardians[0]?.guardian.id ?? attendee.personId;
return ok(await computeStudentAccess(db, ownerId, this.deps.now ?? new Date()));
} }
} }

View File

@@ -1,10 +1,10 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, StudentInvitationDto } from '@gruperly/shared'; import type { ProblemDetails, Result, StudentInvitationDto } from '@gruperly/shared';
import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from '@gruperly/shared'; import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders'; import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma, { UnitOfWork } from '@/lib/prisma'; import prisma, { UnitOfWork } from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { contactPhone } from '@/modules/people/lib/people'; import { contactPhone, guardianSelect, primaryGuardian } from '@/modules/people/lib/people';
import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib'; import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
import { computeStudentAccess } from '../../lib/status'; import { computeStudentAccess } from '../../lib/status';
@@ -38,36 +38,25 @@ export class InviteStudent {
select: { select: {
id: true, id: true,
personId: true, personId: true,
person: { select: { fullName: true, phone: true, guardianPhone: true } }, person: { select: { fullName: true, phone: true, ...guardianSelect } },
group: { select: { owner: { select: { country: true } } } }, group: { select: { owner: { select: { country: true } } } },
}, },
}); });
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
// The account belongs to the adult in charge when the kid has one: it
// reaches all of their kids.
const guardian = primaryGuardian(attendee.person);
const owner = guardian
? { personId: guardian.id, fullName: guardian.fullName }
: { personId: attendee.personId, fullName: attendee.person.fullName };
const token = generateAccessToken(); const token = generateAccessToken();
const expiresAt = new Date(now.getTime() + INVITATION_TTL_HOURS * 60 * 60 * 1000); const expiresAt = new Date(now.getTime() + INVITATION_TTL_HOURS * 60 * 60 * 1000);
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
const issued = await unitOfWork.executeResult(async (tx) => { const issued = await unitOfWork.executeResult(async (tx) => {
// One account per person: inviting from any of their groups reuses it. const accountId = await resolveAccount(tx, owner, userId);
const link = await tx.studentAccountPerson.findFirst({
where: { personId: attendee.personId },
orderBy: { createdAt: 'asc' },
select: { accountId: true },
});
const accountId =
link?.accountId
?? (
await tx.studentAccount.create({
data: {
name: attendee.person.fullName,
createdById: userId,
people: { create: { personId: attendee.personId } },
},
select: { id: true },
})
).id;
await tx.studentAccessToken.updateMany({ await tx.studentAccessToken.updateMany({
where: { accountId, usedAt: null, revokedAt: null }, where: { accountId, usedAt: null, revokedAt: null },
data: { revokedAt: now }, data: { revokedAt: now },
@@ -96,7 +85,7 @@ export class InviteStudent {
url: studentLinkUrl(token), url: studentLinkUrl(token),
expiresAt: expiresAt.toISOString(), expiresAt: expiresAt.toISOString(),
whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country), whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country),
access: await computeStudentAccess(db, attendee.personId, now), access: await computeStudentAccess(db, owner.personId, now),
}); });
} }
} }
@@ -104,3 +93,52 @@ export class InviteStudent {
function toWhatsappPhone(phone: string | null, country: string | null): string | null { function toWhatsappPhone(phone: string | null, country: string | null): string | null {
return phone ? toWhatsappE164(phone, country as CountryCode | null) : null; return phone ? toWhatsappE164(phone, country as CountryCode | null) : null;
} }
type AccountOwner = { personId: string; fullName: string };
/* One account per person: inviting from any of their groups (or, for an adult
in charge, from any of their kids) reuses it. Accounts made before kids
groups were linked to the kid: the oldest one of the adult's kids moves to
the adult, and the kids stop being linked one by one (they are reached
through `person_guardians`). */
async function resolveAccount(tx: Prisma.TransactionClient, owner: AccountOwner, userId: string): Promise<string> {
const kids = await tx.personGuardian.findMany({ where: { guardianId: owner.personId }, select: { childId: true } });
const kidIds = kids.map((kid) => kid.childId);
const own = await tx.studentAccountPerson.findFirst({
where: { personId: owner.personId },
orderBy: { createdAt: 'asc' },
select: { accountId: true },
});
const legacy =
own || kidIds.length === 0
? null
: await tx.studentAccountPerson.findFirst({
where: { personId: { in: kidIds } },
orderBy: { createdAt: 'asc' },
select: { accountId: true },
});
let accountId: string;
if (own) {
accountId = own.accountId;
} else if (legacy) {
accountId = legacy.accountId;
await tx.studentAccount.update({
where: { id: accountId },
data: { name: owner.fullName, people: { create: { personId: owner.personId } } },
});
} else {
accountId = (
await tx.studentAccount.create({
data: { name: owner.fullName, createdById: userId, people: { create: { personId: owner.personId } } },
select: { id: true },
})
).id;
}
if (kidIds.length > 0) {
await tx.studentAccountPerson.deleteMany({ where: { personId: { in: kidIds } } });
}
return accountId;
}

View File

@@ -13,6 +13,7 @@ import { occurrencesBetween } from '@/modules/home/lib/scheduler';
import { import {
classAlreadyStartedProblem, classAlreadyStartedProblem,
findLinkedAttendee, findLinkedAttendee,
linkedPersonWhere,
studentAttendeeNotFoundProblem, studentAttendeeNotFoundProblem,
teacherTimeZone, teacherTimeZone,
} from '../../lib'; } from '../../lib';
@@ -127,7 +128,7 @@ export class CancelStudentAbsence {
where: { where: {
id: noticeId, id: noticeId,
cancelledAt: null, cancelledAt: null,
attendee: { status: { not: 'DROPPED' }, person: { studentAccounts: { some: { accountId } } } }, attendee: { status: { not: 'DROPPED' }, person: linkedPersonWhere(accountId) },
}, },
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } }, select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
}); });

View File

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

View File

@@ -1,4 +1,4 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, StudentLinkInfo } from '@gruperly/shared'; import type { ProblemDetails, Result, StudentLinkInfo } from '@gruperly/shared';
import { ok } from '@gruperly/shared'; import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
@@ -9,6 +9,13 @@ type GetStudentLinkInfoDeps = {
now?: Date; now?: Date;
}; };
const firstGroupSelect = {
where: { status: { not: 'DROPPED' } },
orderBy: { createdAt: 'asc' },
take: 1,
select: { group: { select: { name: true, owner: { select: { name: true } } } } },
} satisfies Prisma.Person$attendeesArgs;
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/; const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
/* GET of the link: only reads, never consumes (WhatsApp previews and link /* GET of the link: only reads, never consumes (WhatsApp previews and link
@@ -38,10 +45,12 @@ export class GetStudentLinkInfo {
select: { select: {
person: { person: {
select: { select: {
attendees: { attendees: firstGroupSelect,
// An adult in charge has no groups of their own: their kids' count.
children: {
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
take: 1, take: 1,
select: { group: { select: { name: true, owner: { select: { name: true } } } } }, select: { child: { select: { attendees: firstGroupSelect } } },
}, },
}, },
}, },
@@ -62,7 +71,9 @@ export class GetStudentLinkInfo {
return ok({ status: 'invalid' }); return ok({ status: 'invalid' });
} }
const group = row.account.people[0]?.person.attendees[0]?.group ?? null; const person = row.account.people[0]?.person;
const group =
person?.attendees[0]?.group ?? person?.children[0]?.child.attendees[0]?.group ?? null;
return ok({ return ok({
status: 'valid', status: 'valid',
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery', kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',

View File

@@ -1,9 +1,44 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, StudentMe } from '@gruperly/shared'; import type { ProblemDetails, Result, StudentMe } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared';
import { unauthorizedProblem } from '@/http/problem-details'; import { unauthorizedProblem } from '@/http/problem-details';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
const personGroupsSelect = {
fullName: true,
attendees: {
where: { status: { not: 'DROPPED' } },
orderBy: { createdAt: 'asc' },
select: {
id: true,
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
},
},
} satisfies Prisma.PersonSelect;
type PersonGroups = Prisma.PersonGetPayload<{ select: typeof personGroupsSelect }>;
/* One entry per membership; a kid reached twice (linked and through the adult)
shows up once. */
function studentsOf(people: PersonGroups[]): StudentMe['students'] {
const seen = new Set<string>();
return people.flatMap((person) =>
person.attendees.flatMap((attendee) => {
if (seen.has(attendee.id)) return [];
seen.add(attendee.id);
return [
{
attendeeId: attendee.id,
fullName: person.fullName,
groupId: attendee.group.id,
groupName: attendee.group.name,
teacherName: attendee.group.owner.name,
},
];
}),
);
}
type StudentMeDeps = { db?: Pick<PrismaClient, 'studentAccount'>; now?: Date }; type StudentMeDeps = { db?: Pick<PrismaClient, 'studentAccount'>; now?: Date };
export class GetStudentMe { export class GetStudentMe {
@@ -20,21 +55,15 @@ export class GetStudentMe {
pendingRecoveryEmail: true, pendingRecoveryEmail: true,
welcomedAt: true, welcomedAt: true,
_count: { select: { passkeys: true } }, _count: { select: { passkeys: true } },
// Linked people, and every group each of them is in. // Linked people (and the kids of a linked adult in charge), and every
// group each of them is in.
people: { people: {
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
select: { select: {
person: { person: {
select: { select: {
fullName: true, ...personGroupsSelect,
attendees: { children: { orderBy: { createdAt: 'asc' }, select: { child: { select: personGroupsSelect } } },
where: { status: { not: 'DROPPED' } },
orderBy: { createdAt: 'asc' },
select: {
id: true,
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
},
},
}, },
}, },
}, },
@@ -52,15 +81,7 @@ export class GetStudentMe {
hasPasskey: account._count.passkeys > 0, hasPasskey: account._count.passkeys > 0,
welcomed: account.welcomedAt !== null, welcomed: account.welcomedAt !== null,
}, },
students: account.people.flatMap(({ person }) => students: studentsOf(account.people.flatMap(({ person }) => [person, ...person.children.map(({ child }) => child)])),
person.attendees.map((attendee) => ({
attendeeId: attendee.id,
fullName: person.fullName,
groupId: attendee.group.id,
groupName: attendee.group.name,
teacherName: attendee.group.owner.name,
})),
),
}); });
} }
} }

View File

@@ -2,17 +2,29 @@ import type { Prisma } from '@generated/prisma/client';
export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate }; export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate };
/* The people a student account reaches: the ones linked to it and the kids of
a linked adult in charge (kids groups). Kids are not linked one by one, so a
kid added later shows up without a new invitation. */
export function linkedPersonWhere(accountId: string): Prisma.PersonWhereInput {
return {
OR: [
{ studentAccounts: { some: { accountId } } },
{ guardians: { some: { guardian: { studentAccounts: { some: { accountId } } } } } },
],
};
}
/* The authorization rule of every student endpoint: an attendee (membership) /* The authorization rule of every student endpoint: an attendee (membership)
of a person linked to the session's account, with what the student screens of a person linked to the session's account, with what the student screens
need from the group. The account is linked to the person, so every group need from the group. The account is linked to the person (or to their adult
they are in shows up. null for anything else (or DROPPED; PAUSED keeps in charge), so every group they are in shows up. null for anything else (or DROPPED; PAUSED keeps
access): routes answer 404, the same as for an id that doesn't exist. */ access): routes answer 404, the same as for an id that doesn't exist. */
export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) { export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) {
return db.attendee.findFirst({ return db.attendee.findFirst({
where: { where: {
id: attendeeId, id: attendeeId,
status: { not: 'DROPPED' }, status: { not: 'DROPPED' },
person: { studentAccounts: { some: { accountId } } }, person: linkedPersonWhere(accountId),
}, },
select: { select: {
id: true, id: true,

View File

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

View File

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

View File

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

View File

@@ -5,7 +5,7 @@ import {
findStudentsAtRisk, findStudentsAtRisk,
type StudentsAtRiskDb, type StudentsAtRiskDb,
} from '@/modules/analytics/features/get-students-at-risk/use-case'; } from '@/modules/analytics/features/get-students-at-risk/use-case';
import { contactPhone } from '@/modules/people/lib/people'; import { contactPhone, guardianSelect } from '@/modules/people/lib/people';
import { import {
addTotals, addTotals,
type DispatchItem, type DispatchItem,
@@ -70,7 +70,7 @@ export class SendReengagementMessages {
}), }),
db.attendee.findMany({ db.attendee.findMany({
where: { id: { in: ids } }, where: { id: { in: ids } },
select: { id: true, person: { select: { phone: true, guardianPhone: true } } }, select: { id: true, person: { select: { phone: true, ...guardianSelect } } },
}), }),
]); ]);
const coolingDown = new Set(recent.map((row) => row.attendeeId)); const coolingDown = new Set(recent.map((row) => row.attendeeId));

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -8,6 +8,9 @@ const db = {
attendee: { attendee: {
findFirst: mock(), findFirst: mock(),
}, },
personGuardian: {
findMany: mock(),
},
}; };
mock.module('@/lib/prisma', () => ({ mock.module('@/lib/prisma', () => ({
@@ -44,9 +47,9 @@ const attendee = {
fullName: 'Ana Pérez', fullName: 'Ana Pérez',
email: 'ana@example.com', email: 'ana@example.com',
phone: '5512345678', phone: '5512345678',
guardianName: 'Luis Pérez',
guardianPhone: null,
notes: null, notes: null,
// The adult in charge, a person of their own.
guardians: [{ guardian: { id: 'person-9', fullName: 'Luis Pérez', phone: '5598765432', email: null } }],
// Every membership of the person: this one and another group. // Every membership of the person: this one and another group.
attendees: [ attendees: [
{ id: 'a-1', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Funcional' } }, { id: 'a-1', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Funcional' } },
@@ -69,6 +72,7 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
it('devuelve el participante del grupo', async () => { it('devuelve el participante del grupo', async () => {
prisma.group.findUnique.mockResolvedValue(makeGroup()); prisma.group.findUnique.mockResolvedValue(makeGroup());
prisma.attendee.findFirst.mockResolvedValue(attendee); prisma.attendee.findFirst.mockResolvedValue(attendee);
prisma.personGuardian.findMany.mockResolvedValue([{ child: { id: 'person-2', fullName: 'Tomás Pérez' } }]);
const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1'); const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1');
@@ -80,15 +84,22 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
fullName: 'Ana Pérez', fullName: 'Ana Pérez',
email: 'ana@example.com', email: 'ana@example.com',
phone: '5512345678', phone: '5512345678',
guardianPersonId: 'person-9',
guardianName: 'Luis Pérez', guardianName: 'Luis Pérez',
guardianPhone: null, guardianPhone: '5598765432',
guardianEmail: null,
notes: null, notes: null,
payWithMercadoPago: true,
notifyToken: 'token-1', notifyToken: 'token-1',
createdAt: '2026-08-01T10:00:00.000Z', createdAt: '2026-08-01T10:00:00.000Z',
updatedAt: '2026-08-01T10:00:00.000Z', updatedAt: '2026-08-01T10:00:00.000Z',
payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' }, payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' },
otherGroups: [{ attendeeId: 'a-2', groupId: 'group-2', groupName: 'Yoga', status: 'PAUSED' }], otherGroups: [{ attendeeId: 'a-2', groupId: 'group-2', groupName: 'Yoga', status: 'PAUSED' }],
siblings: [{ personId: 'person-2', fullName: 'Tomás Pérez' }],
}); });
expect(prisma.personGuardian.findMany).toHaveBeenCalledWith(
expect.objectContaining({ where: { guardianId: 'person-9', childId: { not: 'person-1' } } }),
);
expect(prisma.attendee.findFirst).toHaveBeenCalledWith({ expect(prisma.attendee.findFirst).toHaveBeenCalledWith({
where: { id: 'a-1', groupId: 'group-1' }, where: { id: 'a-1', groupId: 'group-1' },
include: { include: {

View File

@@ -218,7 +218,7 @@ describe('attendee incorporation & invite-token in groups', () => {
expect(res.status).toBe(201); expect(res.status).toBe(201);
expect(prisma.person.findFirst).toHaveBeenCalledWith({ expect(prisma.person.findFirst).toHaveBeenCalledWith({
where: { id: 'person-1', createdById: teacherId }, where: { id: 'person-1', createdById: teacherId },
select: { id: true, fullName: true }, select: expect.objectContaining({ id: true, fullName: true }),
}); });
expect(prisma.attendee.create).toHaveBeenCalledWith({ expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { group: { connect: { id: 'group-1' } }, person: { connect: { id: 'person-1' } } }, data: { group: { connect: { id: 'group-1' } }, person: { connect: { id: 'person-1' } } },

View File

@@ -24,9 +24,13 @@ const personSelect = {
fullName: true, fullName: true,
email: true, email: true,
phone: true, phone: true,
guardianName: true,
guardianPhone: true,
notes: true, notes: true,
payWithMercadoPago: true,
guardians: {
take: 1,
orderBy: { createdAt: 'asc' },
select: { guardian: { select: { id: true, fullName: true, phone: true, email: true } } },
},
}; };
const person = { const person = {
@@ -34,9 +38,8 @@ const person = {
fullName: 'Ana Pérez', fullName: 'Ana Pérez',
email: 'ana@example.com', email: 'ana@example.com',
phone: null, phone: null,
guardianName: 'Luis Pérez',
guardianPhone: null,
notes: null, notes: null,
guardians: [{ guardian: { id: 'person-9', fullName: 'Luis Pérez', phone: '1199990000', email: null } }],
}; };
const attendeeRow = { const attendeeRow = {
@@ -75,9 +78,12 @@ describe('attendees routes', () => {
fullName: person.fullName, fullName: person.fullName,
email: person.email, email: person.email,
phone: person.phone, phone: person.phone,
guardianName: person.guardianName, guardianPersonId: 'person-9',
guardianPhone: person.guardianPhone, guardianName: 'Luis Pérez',
guardianPhone: '1199990000',
guardianEmail: null,
notes: person.notes, notes: person.notes,
payWithMercadoPago: true,
createdAt: attendeeRow.createdAt.toISOString(), createdAt: attendeeRow.createdAt.toISOString(),
updatedAt: attendeeRow.updatedAt.toISOString(), updatedAt: attendeeRow.updatedAt.toISOString(),
// The query comes most recent first; the row shows them // The query comes most recent first; the row shows them

View File

@@ -39,9 +39,9 @@ describe('GetAttentionOverview', () => {
db.user.findUnique.mockResolvedValue({ country: 'AR' }); db.user.findUnique.mockResolvedValue({ country: 'AR' });
db.group.findMany.mockResolvedValue([{ id: 'g1', name: 'Natación', capacity: 30 }]); db.group.findMany.mockResolvedValue([{ id: 'g1', name: 'Natación', capacity: 30 }]);
db.attendee.findMany.mockResolvedValue([ db.attendee.findMany.mockResolvedValue([
{ id: 'a1', groupId: 'g1', fullName: 'Agustina', phone: '1155550000', guardianPhone: null, createdAt: at(90) }, { id: 'a1', groupId: 'g1', fullName: 'Agustina', phone: '1155550000', createdAt: at(90) },
{ id: 'a2', groupId: 'g1', fullName: 'Valentina', phone: null, guardianPhone: '1166660000', createdAt: at(90) }, { id: 'a2', groupId: 'g1', fullName: 'Valentina', phone: null, guardians: [{ guardian: { phone: '1166660000' } }], createdAt: at(90) },
{ id: 'a3', groupId: 'g1', fullName: 'Felipe', phone: null, guardianPhone: null, createdAt: at(90) }, { id: 'a3', groupId: 'g1', fullName: 'Felipe', phone: null, createdAt: at(90) },
]); ]);
db.classSession.findMany.mockResolvedValue([ db.classSession.findMany.mockResolvedValue([
{ id: 's1', groupId: 'g1', startsAt: at(1) }, { id: 's1', groupId: 'g1', startsAt: at(1) },

View File

@@ -1,11 +1,12 @@
import { describe, expect, it, mock } from 'bun:test'; import { describe, expect, it, mock } from 'bun:test';
import { err } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared';
import { import {
planFeatureRequiredProblem, planFeatureRequiredProblem,
planLimitReachedProblem, planLimitReachedProblem,
} from '@/http/problem-builders'; } from '@/http/problem-builders';
import { BulkCreateAttendeesUseCase } from '@/modules/attendees/features/bulk-create/use-case'; import { BulkCreateAttendeesUseCase } from '@/modules/attendees/features/bulk-create/use-case';
import { CreateGroup } from '@/modules/groups/features/create/use-case'; import { CreateGroup } from '@/modules/groups/features/create/use-case';
import { UpdateGroupUseCase } from '@/modules/groups/features/update/use-case';
import { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case'; import { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case';
import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case'; import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case';
@@ -14,7 +15,10 @@ const ownerId = 'owner-1';
describe('plan guards in the use cases', () => { describe('plan guards in the use cases', () => {
it('does not create a group past the Free limit', async () => { it('does not create a group past the Free limit', async () => {
const unitOfWork = { executeResult: mock() }; const unitOfWork = { executeResult: mock() };
const planGuard = { canCreateGroup: mock(async () => err(planLimitReachedProblem('groups', 1))) }; const planGuard = {
canCreateGroup: mock(async () => err(planLimitReachedProblem('groups', 1))),
requireFeature: mock(async () => ok(undefined)),
};
const result = await new CreateGroup({ unitOfWork: unitOfWork as never, planGuard }).execute( const result = await new CreateGroup({ unitOfWork: unitOfWork as never, planGuard }).execute(
{} as never, {} as never,
@@ -92,4 +96,100 @@ describe('plan guards in the use cases', () => {
expect(off.ok).toBe(true); expect(off.ok).toBe(true);
expect(db.group.update).toHaveBeenCalled(); expect(db.group.update).toHaveBeenCalled();
}); });
it('needs the kidsGroups feature to create a kids group, not a regular one', async () => {
const unitOfWork = { executeResult: mock(async () => err({ status: 500 } as never)) };
const planGuard = {
canCreateGroup: mock(async () => ok(undefined)),
requireFeature: mock(async () => err(planFeatureRequiredProblem('kidsGroups'))),
};
const useCase = new CreateGroup({ unitOfWork: unitOfWork as never, planGuard });
const kids = await useCase.execute({ audience: 'KIDS' } as never, ownerId);
expect(kids.ok).toBe(false);
if (!kids.ok) expect(kids.error).toMatchObject({ status: 402, code: 'plan_feature_required', params: { feature: 'kidsGroups' } });
expect(planGuard.requireFeature).toHaveBeenCalledWith(ownerId, 'kidsGroups');
expect(unitOfWork.executeResult).not.toHaveBeenCalled();
planGuard.requireFeature.mockClear();
await useCase.execute({ audience: 'ADULTS' } as never, ownerId);
expect(planGuard.requireFeature).not.toHaveBeenCalled();
expect(unitOfWork.executeResult).toHaveBeenCalled();
});
it('needs the kidsGroups feature to turn a group into a kids group, never to go back', async () => {
const db = {
group: {
findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, audience: 'ADULTS' })),
update: mock(async () => groupRow({ audience: 'ADULTS' })),
},
attendee: { count: mock(async () => 0) },
};
const planGuard = { requireFeature: mock(async () => err(planFeatureRequiredProblem('kidsGroups'))) };
const useCase = new UpdateGroupUseCase({ db: db as never, planGuard });
const toKids = await useCase.execute('g1', ownerId, { audience: 'KIDS' });
expect(toKids.ok).toBe(false);
expect(db.group.update).not.toHaveBeenCalled();
// An existing kids group keeps working after a downgrade: editing it does
// not ask for the feature again, and it can go back to adults.
db.group.findUnique.mockResolvedValue({ id: 'g1', createdById: ownerId, audience: 'KIDS' });
const rename = await useCase.execute('g1', ownerId, { name: 'Natación chicos', audience: 'KIDS' });
expect(rename.ok).toBe(true);
const toAdults = await useCase.execute('g1', ownerId, { audience: 'ADULTS' });
expect(toAdults.ok).toBe(true);
expect(planGuard.requireFeature).toHaveBeenCalledTimes(1);
expect(db.group.update).toHaveBeenLastCalledWith({ where: { id: 'g1' }, data: { audience: 'ADULTS' } });
});
it('does not turn a kids group back into adults while a kid has no phone of their own', async () => {
const db = {
group: {
findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, audience: 'KIDS' })),
update: mock(),
},
attendee: { count: mock(async () => 2) },
};
const result = await new UpdateGroupUseCase({ db: db as never }).execute('g1', ownerId, { audience: 'ADULTS' });
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toMatchObject({ status: 409, code: 'group_has_kids_without_phone', params: { count: 2 } });
}
expect(db.attendee.count).toHaveBeenCalledWith({
where: { groupId: 'g1', status: { not: 'DROPPED' }, person: { phone: null } },
});
expect(db.group.update).not.toHaveBeenCalled();
});
it('only lets the owner edit the group', async () => {
const db = {
group: { findUnique: mock(async () => ({ id: 'g1', createdById: 'someone-else', audience: 'ADULTS' })), update: mock() },
attendee: { count: mock() },
};
const result = await new UpdateGroupUseCase({ db: db as never }).execute('g1', ownerId, { name: 'Otro' });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatchObject({ status: 403, code: 'group_owner_required' });
expect(db.group.update).not.toHaveBeenCalled();
});
}); });
function groupRow(overrides: Record<string, unknown> = {}) {
const at = new Date('2026-11-01T00:00:00.000Z');
return {
id: 'g1',
name: 'Natación',
description: null,
createdById: ownerId,
createdAt: at,
updatedAt: at,
days: ['MONDAY'],
time: '18:00',
capacity: 10,
price: 1000,
billingType: 'MONTHLY',
dueDay: 1,
...overrides,
};
}

View File

@@ -0,0 +1,140 @@
/* Kids groups against a real Postgres: the student account belongs to the
adult in charge and reaches all of their kids. Skipped unless DB_TESTS=1
(`bun run test:db`). Creates its own teacher/groups/people and deletes them. */
import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
import { PrismaClient } from '@generated/prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';
import { GetStudentAccess } from '@/modules/student-access/features/get-status/use-case';
import { InviteStudent } from '@/modules/student-access/features/invite/use-case';
import { GetStudentLinkInfo } from '@/modules/student-portal/features/link-info/use-case';
import { GetStudentMe } from '@/modules/student-portal/features/me/use-case';
import { findLinkedAttendee } from '@/modules/student-portal/lib/access';
const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined;
const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
describe.skipIf(!url)('cuenta del adulto a cargo (real database)', () => {
let db: PrismaClient;
let unitOfWork: { executeResult: unknown };
const ids = {
user: `test-user-${suffix}`,
swim: `test-swim-${suffix}`,
art: `test-art-${suffix}`,
ana: `test-ana-${suffix}`,
juan: `test-juan-${suffix}`,
sofi: `test-sofi-${suffix}`,
tomi: `test-tomi-${suffix}`,
other: `test-other-${suffix}`,
juanSwim: `test-juan-swim-${suffix}`,
sofiArt: `test-sofi-art-${suffix}`,
tomiArt: `test-tomi-art-${suffix}`,
otherSwim: `test-other-swim-${suffix}`,
};
beforeAll(async () => {
db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) });
unitOfWork = {
executeResult: (async (callback: (tx: unknown) => Promise<{ ok: boolean }>) => {
const rollback = Symbol('rollback');
try {
return await db.$transaction(async (tx) => {
const result = await callback(tx);
if (!result.ok) throw { [rollback]: result };
return result;
});
} catch (error) {
if (error && typeof error === 'object' && rollback in error) {
return (error as Record<symbol, unknown>)[rollback];
}
throw error;
}
}) as never,
};
await db.user.create({ data: { id: ids.user, name: 'Profe Test', email: `${ids.user}@test.local` } });
await db.group.create({ data: { id: ids.swim, name: 'Natación', audience: 'KIDS', createdById: ids.user } });
await db.group.create({ data: { id: ids.art, name: 'Plástica', audience: 'KIDS', createdById: ids.user } });
await db.person.create({ data: { id: ids.ana, createdById: ids.user, fullName: 'Ana Pérez', phone: `11${suffix.slice(-8)}` } });
for (const [id, fullName] of [
[ids.juan, 'Juan Pérez'],
[ids.sofi, 'Sofi Pérez'],
] as const) {
await db.person.create({
data: { id, createdById: ids.user, fullName, guardians: { create: { guardianId: ids.ana } } },
});
}
await db.person.create({ data: { id: ids.other, createdById: ids.user, fullName: 'Otro Chico' } });
await db.attendee.create({ data: { id: ids.juanSwim, groupId: ids.swim, personId: ids.juan } });
await db.attendee.create({ data: { id: ids.sofiArt, groupId: ids.art, personId: ids.sofi } });
await db.attendee.create({ data: { id: ids.otherSwim, groupId: ids.swim, personId: ids.other } });
// A legacy account linked to the kid (before kids groups).
await db.studentAccount.create({
data: { name: 'Juan Pérez', createdById: ids.user, people: { create: { personId: ids.juan } } },
});
});
afterAll(async () => {
await db.studentAccount.deleteMany({ where: { createdById: ids.user } });
await db.user.deleteMany({ where: { id: ids.user } });
await db.$disconnect();
});
const invite = (groupId: string, attendeeId: string) =>
new InviteStudent({ db, unitOfWork: unitOfWork as never }).execute(groupId, attendeeId, ids.user);
const accountOf = async (personId: string) =>
(await db.studentAccountPerson.findFirst({ where: { personId } }))?.accountId ?? null;
it('invitar a un chico pasa su cuenta vieja al adulto', async () => {
const legacy = await accountOf(ids.juan);
const result = await invite(ids.swim, ids.juanSwim);
if (!result.ok) throw new Error('invite failed');
expect(await accountOf(ids.ana)).toBe(legacy);
expect(await accountOf(ids.juan)).toBeNull();
const account = await db.studentAccount.findUniqueOrThrow({ where: { id: legacy as string } });
expect(account.name).toBe('Ana Pérez');
const token = result.value.url.split('/i/')[1] as string;
expect(await new GetStudentLinkInfo({ db }).execute(token)).toMatchObject({
ok: true,
value: { status: 'valid', name: 'Ana Pérez', groupName: 'Natación' },
});
});
it('invitar a un hermano reutiliza la cuenta del adulto', async () => {
const accountId = await accountOf(ids.ana);
const result = await invite(ids.art, ids.sofiArt);
if (!result.ok) throw new Error('invite failed');
expect(await db.studentAccountPerson.count({ where: { personId: ids.ana } })).toBe(1);
expect(await accountOf(ids.ana)).toBe(accountId);
const juan = await new GetStudentAccess({ db }).execute(ids.swim, ids.juanSwim, ids.user);
const sofi = await new GetStudentAccess({ db }).execute(ids.art, ids.sofiArt, ids.user);
expect(juan).toMatchObject({ ok: true, value: { status: 'invited' } });
expect(sofi).toEqual(juan);
});
it('la cuenta del adulto ve a todos sus chicos, también uno nuevo, y a nadie más', async () => {
const accountId = (await accountOf(ids.ana)) as string;
// A kid added after the invitation shows up without reinviting.
await db.person.create({
data: { id: ids.tomi, createdById: ids.user, fullName: 'Tomi Pérez', guardians: { create: { guardianId: ids.ana } } },
});
await db.attendee.create({ data: { id: ids.tomiArt, groupId: ids.art, personId: ids.tomi } });
const me = await new GetStudentMe({ db }).execute(accountId);
if (!me.ok) throw new Error('me failed');
expect(me.value.account.name).toBe('Ana Pérez');
expect(me.value.students.map((s) => [s.fullName, s.groupName])).toEqual([
['Juan Pérez', 'Natación'],
['Sofi Pérez', 'Plástica'],
['Tomi Pérez', 'Plástica'],
]);
for (const attendeeId of [ids.juanSwim, ids.sofiArt, ids.tomiArt]) {
expect(await findLinkedAttendee(db, accountId, attendeeId)).not.toBeNull();
}
expect(await findLinkedAttendee(db, accountId, ids.otherSwim)).toBeNull();
});
});

View File

@@ -42,6 +42,7 @@ const group = {
inviteToken: null, inviteToken: null,
autoPaymentReminders: false, autoPaymentReminders: false,
autoReengagement: false, autoReengagement: false,
audience: 'ADULTS',
}; };
function makeApp(userValue: unknown) { function makeApp(userValue: unknown) {
@@ -223,6 +224,7 @@ describe('groups routes', () => {
price: 500, price: 500,
billingType: 'MONTHLY', billingType: 'MONTHLY',
dueDay: 5, dueDay: 5,
audience: 'ADULTS',
}, },
}); });
expect(prisma.groupMember.create).toHaveBeenCalledWith({ expect(prisma.groupMember.create).toHaveBeenCalledWith({

View File

@@ -0,0 +1,219 @@
import { describe, expect, it, mock } from 'bun:test';
import { ok } from '@gruperly/shared';
import { CreateAttendeeUseCase } from '@/modules/attendees/features/create/use-case';
import { UpdateAttendeeGuardian } from '@/modules/attendees/features/update-guardian/use-case';
import { contactPhone, findPersonSummaryByPhone } from '@/modules/people/lib/people';
const ownerId = 'owner-1';
const at = new Date('2026-11-01T00:00:00.000Z');
function kidsGroup(overrides: Record<string, unknown> = {}) {
return { id: 'g1', createdById: ownerId, capacity: null, audience: 'KIDS', members: [], ...overrides };
}
function createdAttendee(guardian = { id: 'adult-1', fullName: 'Ana Pérez', phone: '1155550000', email: null }) {
return {
id: 'att-1',
groupId: 'g1',
personId: 'kid-1',
notifyToken: null,
createdAt: at,
updatedAt: at,
person: { id: 'kid-1', fullName: 'Juan Pérez', email: null, phone: null, notes: null, guardians: [{ guardian }] },
};
}
function makeDb(overrides: { adult?: unknown; sameNameKid?: unknown } = {}) {
return {
group: { findUnique: mock(async () => kidsGroup()) },
person: {
// 1st call: the adult by phone. 2nd: a kid of that adult with the same name.
findFirst: mock()
.mockResolvedValueOnce(overrides.adult ?? null)
.mockResolvedValueOnce(overrides.sameNameKid ?? null),
},
attendee: {
findFirst: mock(async () => null),
count: mock(async () => 0),
create: mock(async () => createdAttendee()),
update: mock(),
},
groupWaitlistEntry: { findFirst: mock(), create: mock() },
};
}
const planGuard = { canAddAttendees: mock(async () => ok(undefined)) };
const guardian = { fullName: 'Ana Pérez', phone: '11 5555-0000' };
describe('kids groups: adding a kid', () => {
it('asks for the adult in charge', async () => {
const db = makeDb();
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
firstName: 'Juan',
lastName: 'Pérez',
phone: '1144440000',
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatchObject({ status: 400, code: 'guardian_required' });
expect(db.attendee.create).not.toHaveBeenCalled();
});
it('creates the kid with no phone and a new adult in charge', async () => {
const db = makeDb();
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
firstName: 'Juan',
lastName: 'Pérez',
guardian,
});
expect(result.ok).toBe(true);
if (result.ok && result.value.outcome === 'created') {
expect(result.value.attendee).toMatchObject({ guardianName: 'Ana Pérez', guardianPhone: '1155550000', phone: null });
}
expect(db.attendee.create).toHaveBeenCalledWith(
expect.objectContaining({
data: {
group: { connect: { id: 'g1' } },
person: {
create: {
createdById: ownerId,
fullName: 'Juan Pérez',
phone: null,
email: null,
notes: null,
guardians: {
create: {
guardian: { create: { createdById: ownerId, fullName: 'Ana Pérez', phone: '1155550000', email: null } },
},
},
},
},
},
}),
);
});
it('links a sibling to the adult the teacher already has (same phone)', async () => {
const db = makeDb({ adult: { id: 'adult-1', fullName: 'Ana Pérez', email: null, phone: '1155550000', attendees: [] } });
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
firstName: 'Sofía',
lastName: 'Pérez',
guardian,
});
expect(result.ok).toBe(true);
// The sibling lookup: same adult, same name, case-insensitive.
expect(db.person.findFirst.mock.calls[1]?.[0]).toMatchObject({
where: {
createdById: ownerId,
fullName: { equals: 'Sofía Pérez', mode: 'insensitive' },
guardians: { some: { guardianId: 'adult-1' } },
},
});
expect(db.attendee.create.mock.calls[0]?.[0]).toMatchObject({
data: { person: { create: { fullName: 'Sofía Pérez', guardians: { create: { guardian: { connect: { id: 'adult-1' } } } } } } },
});
});
it('recognizes the same kid of the same adult instead of creating a twin', async () => {
const db = makeDb({
adult: { id: 'adult-1', fullName: 'Ana Pérez', email: null, phone: '1155550000', attendees: [] },
sameNameKid: { id: 'kid-1', fullName: 'Juan Pérez', phone: null, guardians: [] },
});
db.attendee.findFirst.mockResolvedValue({ id: 'att-1', status: 'ACTIVE' } as never);
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
firstName: 'juan',
lastName: 'pérez',
guardian,
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatchObject({ code: 'attendee_already_registered' });
expect(db.attendee.create).not.toHaveBeenCalled();
});
it('keeps asking for a phone in an adults group', async () => {
const db = makeDb();
db.group.findUnique.mockResolvedValue(kidsGroup({ audience: 'ADULTS' }));
const result = await new CreateAttendeeUseCase({ db: db as never, planGuard }).execute('g1', ownerId, {
firstName: 'Ana',
lastName: '',
});
expect(result.ok).toBe(true);
expect(db.attendee.create.mock.calls[0]?.[0]).toMatchObject({ data: { person: { create: { phone: null } } } });
});
});
describe('kids groups: contact', () => {
it('reaches a kid through the adult in charge', () => {
expect(contactPhone({ phone: '1144440000', guardians: [{ guardian: { phone: '1155550000' } }] })).toBe('1155550000');
expect(contactPhone({ phone: '1144440000', guardians: [] })).toBe('1144440000');
expect(contactPhone({ phone: null })).toBeNull();
});
it('the lookup by phone offers the kids of that adult', async () => {
const db = {
person: {
findFirst: mock(async () => ({ id: 'adult-1', fullName: 'Ana Pérez', email: null, phone: '1155550000', attendees: [] })),
findUnique: mock(async () => ({
children: [
{
child: {
id: 'kid-1',
fullName: 'Juan Pérez',
attendees: [{ id: 'att-1', groupId: 'g1', status: 'ACTIVE', group: { name: 'Natación' } }],
},
},
],
})),
},
};
const summary = await findPersonSummaryByPhone(db as never, ownerId, '1155550000');
expect(summary?.children).toEqual([
{ id: 'kid-1', fullName: 'Juan Pérez', groups: [{ attendeeId: 'att-1', groupId: 'g1', groupName: 'Natación', status: 'ACTIVE' }] },
]);
});
});
describe('kids groups: editing the adult in charge', () => {
function guardianDb(person: Record<string, unknown>) {
return {
group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, members: [] })) },
attendee: {
findFirst: mock(async () => ({ personId: 'kid-1', person: { id: 'kid-1', ...person } })),
findUniqueOrThrow: mock(async () => createdAttendee()),
},
person: { update: mock(), findFirst: mock(async () => null), create: mock(async () => ({ id: 'adult-2' })) },
personGuardian: { create: mock() },
};
}
it('edits the adult the kid already has (shared with the siblings)', async () => {
const db = guardianDb({ phone: null, guardians: [{ guardian: { id: 'adult-1', fullName: 'Ana', phone: '1155550000', email: null } }] });
const result = await new UpdateAttendeeGuardian({ db: db as never }).execute({
groupId: 'g1',
attendeeId: 'att-1',
userId: ownerId,
input: { fullName: 'Ana Pérez', phone: '11 5555-0001', email: 'ana@example.com' },
});
expect(result.ok).toBe(true);
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'adult-1' },
data: { fullName: 'Ana Pérez', phone: '1155550001', email: 'ana@example.com' },
});
expect(db.personGuardian.create).not.toHaveBeenCalled();
});
it('links a new adult when the kid had none', async () => {
const db = guardianDb({ phone: null, guardians: [] });
const result = await new UpdateAttendeeGuardian({ db: db as never }).execute({
groupId: 'g1',
attendeeId: 'att-1',
userId: ownerId,
input: { fullName: 'Ana Pérez', phone: '1155550000' },
});
expect(result.ok).toBe(true);
expect(db.personGuardian.create).toHaveBeenCalledWith({ data: { childId: 'kid-1', guardianId: 'adult-2' } });
});
});

View File

@@ -207,6 +207,7 @@ describe('onboarding routes', () => {
dueDay: 5, dueDay: 5,
autoPaymentReminders: false, autoPaymentReminders: false,
autoReengagement: false, autoReengagement: false,
audience: 'ADULTS',
}, },
onboardingCompleted: true, onboardingCompleted: true,
}); });
@@ -220,6 +221,7 @@ describe('onboarding routes', () => {
price: 150.5, price: 150.5,
billingType: 'MONTHLY', billingType: 'MONTHLY',
dueDay: 5, dueDay: 5,
audience: 'ADULTS',
}, },
}); });
expect(prisma.groupMember.create).toHaveBeenCalledWith({ expect(prisma.groupMember.create).toHaveBeenCalledWith({

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -37,7 +37,7 @@ function payment(id: string, attendee: Record<string, unknown>, overrides: Recor
currency: 'ARS', currency: 'ARS',
dueDate: new Date('2026-10-20T15:00:00.000Z'), dueDate: new Date('2026-10-20T15:00:00.000Z'),
checkoutUrl: `https://mpago.la/${id}`, checkoutUrl: `https://mpago.la/${id}`,
attendee: { id: attendee.id, person: { phone: null, guardianPhone: null, ...attendee } }, attendee: { id: attendee.id, person: { phone: null, ...attendee } },
...overrides, ...overrides,
}; };
} }
@@ -93,6 +93,36 @@ function reengagement(provider: MessagingProvider) {
} }
describe('payment reminders', () => { describe('payment reminders', () => {
it('reminds a combined link once, to whoever pays it, with the total', async () => {
const checkout = {
id: 'chk-1',
status: 'OPEN',
amount: { toString: () => '40000' },
payer: { id: 'g-1', fullName: 'Laura Gómez', phone: '11 2345-6789' },
payments: [
{ group: { name: 'Yoga Martes' }, attendee: { person: { id: 'p-1', fullName: 'Juan Gómez' } } },
{ group: { name: 'Yoga Martes' }, attendee: { person: { id: 'p-2', fullName: 'Ana Gómez' } } },
],
};
db.payment.findMany.mockResolvedValue([
payment('pay-1', { id: 'att-1', fullName: 'Juan Gómez' }, { checkout, checkoutUrl: 'https://mpago.la/chk' }),
payment('pay-2', { id: 'att-2', fullName: 'Ana Gómez' }, { checkout, checkoutUrl: 'https://mpago.la/chk' }),
]);
const provider = fakeProvider();
const totals = await reminders(provider).execute();
expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 });
const [, , message] = (provider.send as ReturnType<typeof mock>).mock.calls[0] ?? [];
expect(message).toMatchObject({
kind: 'PAYMENT_REMINDER',
studentName: 'Laura Gómez',
groupName: 'Yoga Martes (Juan) y Yoga Martes (Ana)',
paymentLink: 'https://mpago.la/chk',
});
expect((message as { amount: string }).amount).toContain('40.000');
});
it('only looks at groups with the automation on and an active account of this provider', async () => { it('only looks at groups with the automation on and an active account of this provider', async () => {
await reminders(fakeProvider()).execute(); await reminders(fakeProvider()).execute();
@@ -135,6 +165,7 @@ describe('payment reminders', () => {
groupId: 'group-1', groupId: 'group-1',
attendeeId: 'att-1', attendeeId: 'att-1',
paymentId: 'pay-1', paymentId: 'pay-1',
checkoutId: null,
kind: 'PAYMENT_REMINDER', kind: 'PAYMENT_REMINDER',
provider: 'OPENWA', provider: 'OPENWA',
periodKey: '2026-W43', periodKey: '2026-W43',
@@ -174,7 +205,7 @@ describe('payment reminders', () => {
it('falls back to the guardian phone and skips members without a usable one', async () => { it('falls back to the guardian phone and skips members without a usable one', async () => {
db.payment.findMany.mockResolvedValue([ db.payment.findMany.mockResolvedValue([
payment('pay-1', { id: 'att-1', fullName: 'Nene', guardianPhone: '1123456789' }), payment('pay-1', { id: 'att-1', fullName: 'Nene', guardians: [{ guardian: { phone: '1123456789' } }] }),
payment('pay-2', { id: 'att-2', fullName: 'Sin tel' }), payment('pay-2', { id: 'att-2', fullName: 'Sin tel' }),
]); ]);

View File

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

View File

@@ -62,6 +62,11 @@ export function PlanLimitsCard({ plan, limits }: { plan: Plan; limits: PlanLimit
checked={draft.whatsappAutomations} checked={draft.whatsappAutomations}
onChange={(whatsappAutomations) => setDraft({ ...draft, whatsappAutomations })} onChange={(whatsappAutomations) => setDraft({ ...draft, whatsappAutomations })}
/> />
<FeatureSwitch
label={t('plans.limits.kidsGroups')}
checked={draft.kidsGroups}
onChange={(kidsGroups) => setDraft({ ...draft, kidsGroups })}
/>
<LimitsImpact plan={plan} draft={draft} current={limits} /> <LimitsImpact plan={plan} draft={draft} current={limits} />

View File

@@ -2,6 +2,7 @@ import { useId, useState } from 'react'
import { Check, Copy, MessageCircle } from 'lucide-react' import { Check, Copy, MessageCircle } from 'lucide-react'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { useAttendeeDetail } from './AttendeeDetailProvider' import { useAttendeeDetail } from './AttendeeDetailProvider'
import { reachPhone } from './detail'
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton' import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
import { Section } from './Section' import { Section } from './Section'
import { useCopyToClipboard } from './useCopyToClipboard' import { useCopyToClipboard } from './useCopyToClipboard'
@@ -18,7 +19,7 @@ export function AbsenceLinkSection() {
const url = token ? `${window.location.origin}/report-absence/${token}` : null const url = token ? `${window.location.origin}/report-absence/${token}` : null
if (!attendee || !url) return null if (!attendee || !url) return null
const phoneDigits = attendee.phone?.replace(/\D/g, '') ?? '' const phoneDigits = reachPhone(attendee)?.replace(/\D/g, '') ?? ''
const shareUrl = phoneDigits const shareUrl = phoneDigits
? `https://wa.me/${phoneDigits}?text=${encodeURIComponent( ? `https://wa.me/${phoneDigits}?text=${encodeURIComponent(
t('absenceLink.message', { name: attendee.fullName.split(' ')[0], url }), t('absenceLink.message', { name: attendee.fullName.split(' ')[0], url }),

View File

@@ -3,15 +3,16 @@ import { formatPhoneDisplay } from '../../lib/format'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton' import { ACTION_BUTTON_CLASS, PRIMARY_ACTION_CLASS } from './actionButton'
import { useAttendeeDetail } from './AttendeeDetailProvider' import { useAttendeeDetail } from './AttendeeDetailProvider'
import { reachPhone } from './detail'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
export function AttendeeContactActions() { export function AttendeeContactActions() {
const { attendee } = useAttendeeDetail() const { attendee } = useAttendeeDetail()
const { t } = useTranslation(['attendeeDetail', 'common']) const { t } = useTranslation(['attendeeDetail', 'common'])
const phone = attendee?.phone const phone = attendee ? reachPhone(attendee) : null
const digits = phone?.replace(/\D/g, '') ?? '' const digits = phone?.replace(/\D/g, '') ?? ''
const label = formatPhoneDisplay(phone) ?? attendee?.fullName ?? t('actions.theMember') const label = attendee?.guardianName ?? formatPhoneDisplay(phone) ?? attendee?.fullName ?? t('actions.theMember')
return ( return (
<div> <div>

View File

@@ -1,10 +1,11 @@
import { useEffect, useState } from 'react' import { type ReactNode, useEffect, useState } from 'react'
import { Mail, Phone } from 'lucide-react' import { Mail, Phone } from 'lucide-react'
import { ApiError } from '../../lib/api' import { ApiError } from '../../lib/api'
import { formatPhoneDisplay } from '../../lib/format' import { formatPhoneDisplay } from '../../lib/format'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { AttendeeContactForm } from './AttendeeContactForm' import { AttendeeContactForm } from './AttendeeContactForm'
import { contactEmailError } from './detail' import { contactEmailError } from './detail'
import { PhoneRowActions } from './PhoneRowActions'
import { Section } from './Section' import { Section } from './Section'
import { useAttendeeDetail } from './AttendeeDetailProvider' import { useAttendeeDetail } from './AttendeeDetailProvider'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
@@ -99,8 +100,12 @@ export function AttendeeContactSection() {
icon={Phone} icon={Phone}
label={t('contact.phone')} label={t('contact.phone')}
value={formatPhoneDisplay(attendee.phone) ?? t('contact.addPhone')} value={formatPhoneDisplay(attendee.phone) ?? t('contact.addPhone')}
href={attendee.phone ? `tel:${attendee.phone.replace(/\D/g, '')}` : undefined}
placeholder={!attendee.phone} placeholder={!attendee.phone}
actions={
attendee.phone ? (
<PhoneRowActions phone={attendee.phone} name={attendee.fullName} />
) : undefined
}
/> />
<ContactRow <ContactRow
icon={Mail} icon={Mail}
@@ -121,9 +126,11 @@ type ContactRowProps = {
value: string value: string
href?: string href?: string
placeholder: boolean placeholder: boolean
/** Acciones a la derecha (p. ej. WhatsApp y Llamar): la fila deja de ser un link. */
actions?: ReactNode
} }
function ContactRow({ icon: Icon, label, value, href, placeholder }: ContactRowProps) { export function ContactRow({ icon: Icon, label, value, href, placeholder, actions }: ContactRowProps) {
const content = ( const content = (
<> <>
<Icon className="size-4 shrink-0 text-secondary" aria-hidden="true" /> <Icon className="size-4 shrink-0 text-secondary" aria-hidden="true" />
@@ -133,11 +140,12 @@ function ContactRow({ icon: Icon, label, value, href, placeholder }: ContactRowP
{value} {value}
</span> </span>
</span> </span>
{actions}
</> </>
) )
const className = 'flex min-h-14 items-center gap-3 rounded-lg px-3 py-2' const className = 'flex min-h-14 items-center gap-3 rounded-lg px-3 py-2'
return href ? ( return href && !actions ? (
<a href={href} className={cn(className, 'transition-colors hover:bg-primary-soft')}> <a href={href} className={cn(className, 'transition-colors hover:bg-primary-soft')}>
{content} {content}
</a> </a>

View File

@@ -8,6 +8,7 @@ import type {
GroupListItem, GroupListItem,
GroupWaitlistEntryDto, GroupWaitlistEntryDto,
UpdateAttendee, UpdateAttendee,
GuardianInput,
} from '@gruperly/shared' } from '@gruperly/shared'
import { errorMessage } from '../../i18n' import { errorMessage } from '../../i18n'
import { i18n } from '../../i18n/instance' import { i18n } from '../../i18n/instance'
@@ -18,6 +19,7 @@ import {
getAttendeeHistory, getAttendeeHistory,
getGroup, getGroup,
getGroupAttendee, getGroupAttendee,
updateAttendeeGuardian,
getGroups, getGroups,
getGroupWaitlist, getGroupWaitlist,
moveGroupAttendee, moveGroupAttendee,
@@ -42,6 +44,10 @@ type AttendeeDetailContextValue = {
endContactEdit: () => void endContactEdit: () => void
saveAttendee: (input: UpdateAttendee) => Promise<void> saveAttendee: (input: UpdateAttendee) => Promise<void>
isUpdatingAttendee: boolean isUpdatingAttendee: boolean
/** KIDS: el contacto del chico es su adulto a cargo. */
isKidsGroup: boolean
saveGuardian: (input: GuardianInput) => Promise<void>
isUpdatingGuardian: boolean
isRemoveDialogOpen: boolean isRemoveDialogOpen: boolean
openRemoveDialog: () => void openRemoveDialog: () => void
closeRemoveDialog: () => void closeRemoveDialog: () => void
@@ -106,6 +112,19 @@ export function AttendeeDetailProvider({
}, },
}) })
const guardianMutation = useMutation({
mutationFn: (input: GuardianInput) => updateAttendeeGuardian(groupId, attendeeId, input),
onSuccess: (updated) => {
queryClient.setQueryData<AttendeeDetailDto>(
['group-attendee', groupId, attendeeId],
(current) => (current ? { ...current, ...updated } : current),
)
// El adulto es de todos sus chicos: cambia también en las fichas de los hermanos.
void queryClient.invalidateQueries({ queryKey: ['group-attendees'] })
void queryClient.invalidateQueries({ queryKey: ['group-attendee'] })
},
})
// Same key the analytics screen uses: both read the same history and do not // Same key the analytics screen uses: both read the same history and do not
// clobber each other's cache. // clobber each other's cache.
const historyQuery = useQuery({ const historyQuery = useQuery({
@@ -218,6 +237,11 @@ export function AttendeeDetailProvider({
await updateMutation.mutateAsync(input) await updateMutation.mutateAsync(input)
}, },
isUpdatingAttendee: updateMutation.isPending, isUpdatingAttendee: updateMutation.isPending,
isKidsGroup: groupQuery.data?.audience === 'KIDS',
saveGuardian: async (input) => {
await guardianMutation.mutateAsync(input)
},
isUpdatingGuardian: guardianMutation.isPending,
isRemoveDialogOpen, isRemoveDialogOpen,
openRemoveDialog: () => setIsRemoveDialogOpen(true), openRemoveDialog: () => setIsRemoveDialogOpen(true),
closeRemoveDialog: () => setIsRemoveDialogOpen(false), closeRemoveDialog: () => setIsRemoveDialogOpen(false),

View File

@@ -10,6 +10,7 @@ import { AttendeeContactActions } from './AttendeeContactActions'
import { AttendeeContactSection } from './AttendeeContactSection' import { AttendeeContactSection } from './AttendeeContactSection'
import { AttendeeNotesSection } from './AttendeeNotesSection' import { AttendeeNotesSection } from './AttendeeNotesSection'
import { AttendeePaymentsSection } from './AttendeePaymentsSection' import { AttendeePaymentsSection } from './AttendeePaymentsSection'
import { GuardianSection } from './GuardianSection'
import { OtherGroupsSection } from './OtherGroupsSection' import { OtherGroupsSection } from './OtherGroupsSection'
import { useAttendeeDetail } from './AttendeeDetailProvider' import { useAttendeeDetail } from './AttendeeDetailProvider'
import { ChangeGroupDialog } from './ChangeGroupDialog' import { ChangeGroupDialog } from './ChangeGroupDialog'
@@ -91,6 +92,7 @@ export function AttendeeDetailView() {
<div className="mt-6"> <div className="mt-6">
<AttendeeContactSection /> <AttendeeContactSection />
<GuardianSection />
<OtherGroupsSection /> <OtherGroupsSection />
<StudentAccessSection /> <StudentAccessSection />
<AttendeePaymentsSection /> <AttendeePaymentsSection />

View File

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

View File

@@ -1,6 +1,7 @@
import { Check } from 'lucide-react' import { Check } from 'lucide-react'
import { formatPhoneDisplay } from '../../lib/format' import { formatPhoneDisplay } from '../../lib/format'
import { useAttendeeDetail } from './AttendeeDetailProvider' import { useAttendeeDetail } from './AttendeeDetailProvider'
import { reachPhone } from './detail'
import { useCopyToClipboard } from './useCopyToClipboard' import { useCopyToClipboard } from './useCopyToClipboard'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
@@ -15,7 +16,7 @@ export function AttendeePhoneLine() {
const { copied, copy } = useCopyToClipboard() const { copied, copy } = useCopyToClipboard()
const { t } = useTranslation(['attendeeDetail', 'common']) const { t } = useTranslation(['attendeeDetail', 'common'])
const phone = attendee?.phone const phone = attendee ? reachPhone(attendee) : null
const label = formatPhoneDisplay(phone) const label = formatPhoneDisplay(phone)
if (!phone || !label) return null if (!phone || !label) return null

View File

@@ -0,0 +1,153 @@
import { useState } from 'react'
import { Loader2, Mail, Phone, UserRound, Users } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Button, Input } from '../../components/ui'
import { ApiError } from '../../lib/api'
import { formatPhoneDisplay } from '../../lib/format'
import { ContactRow } from './AttendeeContactSection'
import { useAttendeeDetail } from './AttendeeDetailProvider'
import { contactEmailError } from './detail'
import { PhoneRowActions } from './PhoneRowActions'
import { Section } from './Section'
/* El adulto a cargo de un chico: es una persona propia (compartida entre
hermanos), así que editarlo cambia en la ficha de todos sus chicos. Se
muestra si el chico tiene adulto o si el grupo es de chicos (para cargarlo). */
export function GuardianSection() {
const { attendee, isKidsGroup, saveGuardian, isUpdatingGuardian } = useAttendeeDetail()
const { t } = useTranslation(['attendeeDetail', 'common'])
const [isEditing, setIsEditing] = useState(false)
const [fullName, setFullName] = useState('')
const [phone, setPhone] = useState('')
const [email, setEmail] = useState('')
const [error, setError] = useState<string | null>(null)
if (!attendee || (!attendee.guardianPersonId && !isKidsGroup)) return null
const hasGuardian = Boolean(attendee.guardianPersonId)
const beginEdit = () => {
setFullName(attendee.guardianName ?? '')
setPhone(attendee.guardianPhone ?? '')
setEmail(attendee.guardianEmail ?? '')
setError(null)
setIsEditing(true)
}
const save = async () => {
if (!fullName.trim() || phone.replace(/\D/g, '').length < 6) {
setError(t('guardian.required'))
return
}
const emailError = contactEmailError(email)
if (emailError) {
setError(emailError)
return
}
try {
await saveGuardian({ fullName: fullName.trim(), phone: phone.trim(), email: email.trim() || undefined })
setIsEditing(false)
} catch (err) {
setError(
err instanceof ApiError && err.problem?.code === 'person_phone_taken'
? t('contact.phoneTaken')
: t('contact.saveError'),
)
}
}
const siblings = attendee.siblings.map((sibling) => sibling.fullName).join(', ')
return (
<Section
id="attendee-guardian"
title={t('guardian.title')}
trailing={
!isEditing ? (
<button
type="button"
onClick={beginEdit}
className="min-h-11 rounded-lg px-2 text-sm font-medium text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
{hasGuardian ? t('contact.edit') : t('guardian.add')}
</button>
) : null
}
>
{isEditing ? (
<div className="space-y-3 px-3 pb-1">
<Input
value={fullName}
onChange={(event) => setFullName(event.target.value)}
autoFocus
autoComplete="name"
placeholder={t('guardian.namePlaceholder')}
aria-label={t('guardian.name')}
/>
<Input
type="tel"
value={phone}
onChange={(event) => setPhone(event.target.value)}
autoComplete="tel"
placeholder={t('contact.phone')}
aria-label={t('contact.phone')}
/>
<Input
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
autoComplete="email"
placeholder={t('contact.email')}
aria-label={t('contact.email')}
/>
{hasGuardian && attendee.siblings.length > 0 ? (
<p className="text-xs text-secondary">{t('guardian.shared')}</p>
) : null}
{error ? (
<p role="alert" className="text-sm text-danger-fg">
{error}
</p>
) : null}
<div className="flex justify-end gap-2 pt-1">
<Button variant="ghost" onClick={() => setIsEditing(false)} disabled={isUpdatingGuardian}>
{t('common:actions.cancel')}
</Button>
<Button variant="primary" onClick={() => void save()} disabled={isUpdatingGuardian}>
{isUpdatingGuardian ? <Loader2 className="size-4 animate-spin" /> : null}
{t('common:actions.save')}
</Button>
</div>
</div>
) : hasGuardian ? (
<div className="divide-y divide-border/60">
<ContactRow icon={UserRound} label={t('guardian.name')} value={attendee.guardianName ?? ''} placeholder={false} />
<ContactRow
icon={Phone}
label={t('contact.phone')}
value={formatPhoneDisplay(attendee.guardianPhone) ?? t('contact.addPhone')}
placeholder={!attendee.guardianPhone}
actions={
attendee.guardianPhone ? (
<PhoneRowActions
phone={attendee.guardianPhone}
name={attendee.guardianName ?? attendee.fullName}
/>
) : undefined
}
/>
<ContactRow
icon={Mail}
label={t('contact.email')}
value={attendee.guardianEmail ?? t('contact.addEmail')}
href={attendee.guardianEmail ? `mailto:${attendee.guardianEmail}` : undefined}
placeholder={!attendee.guardianEmail}
/>
{siblings ? (
<ContactRow icon={Users} label={t('guardian.siblings')} value={siblings} placeholder={false} />
) : null}
</div>
) : (
<p className="px-3 text-sm text-secondary">{t('guardian.missing')}</p>
)}
</Section>
)
}

View File

@@ -16,6 +16,8 @@ type InviteToAppSheetProps = {
groupName: string groupName: string
attendeeId: string attendeeId: string
fullName: string fullName: string
/** Kids groups: the account (and the message) belong to the adult in charge. */
guardianName?: string | null
hasPhone: boolean hasPhone: boolean
/** Reinviting closes the current access: the copy says so. */ /** Reinviting closes the current access: the copy says so. */
reinvite: boolean reinvite: boolean
@@ -31,6 +33,7 @@ export function InviteToAppSheet({
groupName, groupName,
attendeeId, attendeeId,
fullName, fullName,
guardianName,
hasPhone, hasPhone,
reinvite, reinvite,
}: InviteToAppSheetProps) { }: InviteToAppSheetProps) {
@@ -39,6 +42,7 @@ export function InviteToAppSheet({
const [invitation, setInvitation] = useState<StudentInvitationDto | null>(null) const [invitation, setInvitation] = useState<StudentInvitationDto | null>(null)
const [copied, setCopied] = useState(false) const [copied, setCopied] = useState(false)
const firstName = fullName.split(' ')[0] ?? fullName const firstName = fullName.split(' ')[0] ?? fullName
const guardianFirstName = guardianName ? (guardianName.split(' ')[0] ?? guardianName) : null
const mutation = useMutation({ const mutation = useMutation({
mutationFn: () => inviteStudent(groupId, attendeeId), mutationFn: () => inviteStudent(groupId, attendeeId),
@@ -63,7 +67,7 @@ export function InviteToAppSheet({
const popup = window.open('', '_blank') const popup = window.open('', '_blank')
try { try {
const result = await ensureInvitation() const result = await ensureInvitation()
const text = encodeURIComponent(invitationMessage(firstName, groupName, result.url)) const text = encodeURIComponent(invitationMessage(firstName, groupName, result.url, guardianFirstName))
const target = result.whatsappPhone const target = result.whatsappPhone
? `https://wa.me/${result.whatsappPhone.replace(/\D/g, '')}?text=${text}` ? `https://wa.me/${result.whatsappPhone.replace(/\D/g, '')}?text=${text}`
: `https://wa.me/?text=${text}` : `https://wa.me/?text=${text}`
@@ -91,7 +95,12 @@ export function InviteToAppSheet({
} }
} }
const preview = invitationMessage(firstName, groupName, invitation?.url ?? t('inviteSheet.linkPlaceholder')) const preview = invitationMessage(
firstName,
groupName,
invitation?.url ?? t('inviteSheet.linkPlaceholder'),
guardianFirstName,
)
return ( return (
<Sheet <Sheet
@@ -100,8 +109,10 @@ export function InviteToAppSheet({
title={reinvite ? t('inviteSheet.titleReinvite') : t('inviteSheet.title')} title={reinvite ? t('inviteSheet.titleReinvite') : t('inviteSheet.title')}
description={ description={
reinvite reinvite
? t('inviteSheet.descriptionReinvite', { name: firstName }) ? t('inviteSheet.descriptionReinvite', { name: guardianFirstName ?? firstName })
: t('inviteSheet.description', { name: firstName }) : guardianFirstName
? t('inviteSheet.descriptionGuardian', { guardian: guardianFirstName, name: firstName })
: t('inviteSheet.description', { name: firstName })
} }
> >
<div className="space-y-4"> <div className="space-y-4">

View File

@@ -0,0 +1,36 @@
import { MessageCircle, Phone } from 'lucide-react'
import { useTranslation } from 'react-i18next'
const ICON_ACTION_CLASS =
'inline-flex size-11 shrink-0 items-center justify-center rounded-lg text-accent-fg transition-colors hover:bg-primary-soft hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent'
/* WhatsApp y Llamar al número de la fila. Los dígitos se arman igual que en
`AttendeeContactActions`, así los dos lugares abren el mismo número. */
export function PhoneRowActions({ phone, name }: { phone: string; name: string }) {
const { t } = useTranslation('attendeeDetail')
const digits = phone.replace(/\D/g, '')
if (!digits) return null
return (
<div className="ml-auto flex shrink-0 items-center gap-1">
<a
href={`https://wa.me/${digits}`}
target="_blank"
rel="noopener noreferrer"
aria-label={t('actions.whatsappLabel', { name })}
title={t('actions.whatsappLabel', { name })}
className={ICON_ACTION_CLASS}
>
<MessageCircle className="size-4" aria-hidden="true" />
</a>
<a
href={`tel:${digits}`}
aria-label={t('actions.callLabel', { name })}
title={t('actions.callLabel', { name })}
className={ICON_ACTION_CLASS}
>
<Phone className="size-4" aria-hidden="true" />
</a>
</div>
)
}

View File

@@ -76,6 +76,7 @@ export function StudentAccessSection() {
groupName={groupName ?? t('access.yourGroup')} groupName={groupName ?? t('access.yourGroup')}
attendeeId={attendee.id} attendeeId={attendee.id}
fullName={attendee.fullName} fullName={attendee.fullName}
guardianName={attendee.guardianName}
hasPhone={hasPhone} hasPhone={hasPhone}
reinvite={invited} reinvite={invited}
/> />

View File

@@ -3,6 +3,12 @@ import { UpdateAttendeeSchema } from '@gruperly/shared'
import { validationMessage } from '../../i18n/validation' import { validationMessage } from '../../i18n/validation'
import { i18n } from '../../i18n/instance' import { i18n } from '../../i18n/instance'
/* El número por el que se contacta al miembro: el del adulto a cargo si es un
chico (es quien responde por él), si no el suyo. Misma regla que el backend. */
export function reachPhone(attendee: { phone: string | null; guardianPhone: string | null }): string | null {
return attendee.guardianPhone ?? attendee.phone
}
export function contactEmailError(email: string): string | null { export function contactEmailError(email: string): string | null {
const result = UpdateAttendeeSchema.safeParse({ email }) const result = UpdateAttendeeSchema.safeParse({ email })
if (result.success) return null if (result.success) return null

View File

@@ -38,6 +38,19 @@ export function formatSince(iso: string): string {
return new Date(iso).toLocaleDateString(i18n.language, { day: 'numeric', month: 'long' }) return new Date(iso).toLocaleDateString(i18n.language, { day: 'numeric', month: 'long' })
} }
export function invitationMessage(firstName: string, groupName: string, url: string): string { /* With an adult in charge the message goes to the adult, about the kid. */
return i18n.t('attendeeDetail:inviteSheet.message', { name: firstName, group: groupName, url }) export function invitationMessage(
firstName: string,
groupName: string,
url: string,
guardianFirstName?: string | null,
): string {
return guardianFirstName
? i18n.t('attendeeDetail:inviteSheet.messageGuardian', {
guardian: guardianFirstName,
name: firstName,
group: groupName,
url,
})
: i18n.t('attendeeDetail:inviteSheet.message', { name: firstName, group: groupName, url })
} }

View File

@@ -50,6 +50,7 @@ export function planFeatureList(limits: PlanLimits): { label: string; included:
}, },
{ label: i18n.t('billing:features.mpCharges'), included: limits.mpCharges }, { label: i18n.t('billing:features.mpCharges'), included: limits.mpCharges },
{ label: i18n.t('billing:features.whatsapp'), included: limits.whatsappAutomations }, { label: i18n.t('billing:features.whatsapp'), included: limits.whatsappAutomations },
{ label: i18n.t('billing:features.kidsGroups'), included: limits.kidsGroups },
] ]
} }

View File

@@ -0,0 +1,78 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Link, useNavigate } from '@tanstack/react-router'
import type { CreateFirstGroup, GroupDto } from '@gruperly/shared'
import { ChevronLeft, Loader2 } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { errorMessage } from '../../i18n'
import { getGroup, updateGroup } from '../../lib/api'
import { GroupForm } from './GroupForm'
/* "Editar grupo": el mismo formulario que el alta, con los datos del grupo. */
export function EditGroupView({ groupId }: { groupId: string }) {
const navigate = useNavigate()
const { t } = useTranslation('groups')
const queryClient = useQueryClient()
const groupQuery = useQuery({
queryKey: ['group', groupId],
queryFn: () => getGroup(groupId),
})
const update = useMutation({
// El país vive en el usuario, no en el grupo: el formulario lo trae pero no se manda.
mutationFn: ({ country: _country, ...values }: CreateFirstGroup) => updateGroup(groupId, values),
onSuccess: (group) => {
queryClient.setQueryData<GroupDto>(['group', groupId], (current) => (current ? { ...current, ...group } : group))
void queryClient.invalidateQueries({ queryKey: ['groups'] })
void navigate({ to: '/groups/$groupId', params: { groupId } })
},
})
const group = groupQuery.data
return (
<section className="mx-auto w-full max-w-md">
<Link
to="/groups/$groupId"
params={{ groupId }}
className="mb-6 hidden items-center gap-1 text-sm font-medium text-foreground/70 transition-colors hover:text-primary lg:inline-flex"
>
<ChevronLeft className="size-4" />
{group?.name ?? t('title')}
</Link>
{group ? (
<GroupForm
heading={t('edit.heading')}
description={t('edit.description')}
submitLabel={t('edit.submit')}
isSubmitting={update.isPending}
errorMessage={update.isError ? errorMessage(update.error, t('edit.error')) : null}
initialValues={toFormValues(group)}
onSubmit={(values) => update.mutate(values)}
/>
) : groupQuery.isError ? (
<p role="alert" className="text-sm text-danger-fg">
{errorMessage(groupQuery.error, t('edit.loadError'))}
</p>
) : (
<div className="flex justify-center py-20">
<Loader2 className="size-8 animate-spin text-accent" />
</div>
)}
</section>
)
}
function toFormValues(group: GroupDto): Partial<CreateFirstGroup> {
return {
name: group.name,
days: group.days ?? [],
time: group.time ?? '09:00',
capacity: group.capacity ?? undefined,
price: group.price ?? undefined,
billingType: group.billingType ?? 'MONTHLY',
dueDay: group.dueDay ?? 1,
audience: group.audience,
}
}

View File

@@ -1,16 +1,19 @@
import { type DefaultValues, useForm } from 'react-hook-form' import { type DefaultValues, useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from '@hookform/resolvers/zod'
import type { BillingType, CountryCode, CreateFirstGroup, WeekDay } from '@gruperly/shared' import type { BillingType, CountryCode, CreateFirstGroup, GroupAudience, WeekDay } from '@gruperly/shared'
import { COUNTRY_CURRENCY, CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared' import { COUNTRY_CURRENCY, CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared'
import { ArrowLeft, Check, Loader2 } from 'lucide-react' import { ArrowLeft, Check, Loader2 } from 'lucide-react'
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { useId } from 'react' import { useId, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { currencySymbol, sortWeekDays } from '../../lib/format' import { currencySymbol, sortWeekDays } from '../../lib/format'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { Button, FieldError, Input, Label } from '../../components/ui' import { Badge, Button, FieldError, Input, Label } from '../../components/ui'
import { hasPlanFeature, planFeatureRequiredMessage, useBillingStatus } from '../billing'
import { BILLING_TYPES, WEEK_DAYS } from '../onboarding/constants' import { BILLING_TYPES, WEEK_DAYS } from '../onboarding/constants'
const AUDIENCES: readonly GroupAudience[] = ['ADULTS', 'KIDS']
type GroupFormProps = { type GroupFormProps = {
heading: string heading: string
description: string description: string
@@ -23,6 +26,8 @@ type GroupFormProps = {
country?: CountryCode country?: CountryCode
onSubmit: (values: CreateFirstGroup) => void onSubmit: (values: CreateFirstGroup) => void
onBack?: () => void onBack?: () => void
/** Editar grupo: arranca con los datos del grupo. */
initialValues?: Partial<CreateFirstGroup>
} }
export function GroupForm({ export function GroupForm({
@@ -35,6 +40,7 @@ export function GroupForm({
country, country,
onSubmit, onSubmit,
onBack, onBack,
initialValues,
}: GroupFormProps) { }: GroupFormProps) {
const { t } = useTranslation(['groups', 'common']) const { t } = useTranslation(['groups', 'common'])
// The price starts empty on purpose: a pre-filled $0 got submitted as is and // The price starts empty on purpose: a pre-filled $0 got submitted as is and
@@ -48,12 +54,20 @@ export function GroupForm({
billingType: 'MONTHLY', billingType: 'MONTHLY',
dueDay: 1, dueDay: 1,
country: country ?? DEFAULT_COUNTRY, country: country ?? DEFAULT_COUNTRY,
audience: 'ADULTS',
...initialValues,
} }
// Con país (onboarding) el símbolo sale de su moneda; sin país, del navegador, // Con país (onboarding) el símbolo sale de su moneda; sin país, del navegador,
// igual que el resto de los montos de la app. // igual que el resto de los montos de la app.
const symbol = currencySymbol(country ? COUNTRY_CURRENCY[country] : undefined) const symbol = currencySymbol(country ? COUNTRY_CURRENCY[country] : undefined)
const daysLabelId = useId() const daysLabelId = useId()
const billingLabelId = useId() const billingLabelId = useId()
const audienceLabelId = useId()
const billingQuery = useBillingStatus()
// Un grupo que ya es de chicos sigue siéndolo aunque el plan ya no lo incluya.
const kidsIncluded = initialValues?.audience === 'KIDS' || hasPlanFeature(billingQuery.data, 'kidsGroups')
// Se avisa inline y no con el aviso global de Pro: el onboarding no lo monta.
const [kidsLocked, setKidsLocked] = useState(false)
const { const {
register, register,
@@ -70,6 +84,7 @@ export function GroupForm({
const days = watch('days') const days = watch('days')
const billingType = watch('billingType') const billingType = watch('billingType')
const dueDay = watch('dueDay') const dueDay = watch('dueDay')
const audience = watch('audience')
const toggleDay = (day: WeekDay) => { const toggleDay = (day: WeekDay) => {
const next = days.includes(day) ? days.filter((d) => d !== day) : sortWeekDays([...days, day]) const next = days.includes(day) ? days.filter((d) => d !== day) : sortWeekDays([...days, day])
@@ -80,6 +95,15 @@ export function GroupForm({
setValue('billingType', type, { shouldValidate: true }) setValue('billingType', type, { shouldValidate: true })
} }
const selectAudience = (value: GroupAudience) => {
if (value === 'KIDS' && !kidsIncluded) {
setKidsLocked(true)
return
}
setKidsLocked(false)
setValue('audience', value, { shouldValidate: true })
}
return ( return (
<form onSubmit={handleSubmit(onSubmit)} noValidate className="space-y-5"> <form onSubmit={handleSubmit(onSubmit)} noValidate className="space-y-5">
<header className="space-y-1"> <header className="space-y-1">
@@ -99,6 +123,42 @@ export function GroupForm({
<FieldError message={errors.name?.message} /> <FieldError message={errors.name?.message} />
</div> </div>
<div>
<Label id={audienceLabelId}>{t('form.audience')}</Label>
<div role="group" aria-labelledby={audienceLabelId} className="grid grid-cols-2 gap-2">
{AUDIENCES.map((value) => {
const isActive = audience === value
return (
<button
key={value}
type="button"
aria-pressed={isActive}
onClick={() => selectAudience(value)}
className={cn(
'rounded-xl border px-3 py-2.5 text-left transition-colors',
isActive
? 'border-accent bg-accent-soft'
: 'border-border bg-surface hover:bg-primary-soft',
)}
>
<span className="flex items-center gap-2">
<span className={cn('text-sm font-semibold', isActive ? 'text-accent' : 'text-primary')}>
{t(`form.audienceOption.${value}`)}
</span>
{value === 'KIDS' && !kidsIncluded ? <Badge variant="info">Pro</Badge> : null}
</span>
<span className="block text-xs text-foreground/50">{t(`form.audienceHint.${value}`)}</span>
</button>
)
})}
</div>
{kidsLocked ? (
<p role="status" className="mt-2 text-xs text-foreground/60">
{planFeatureRequiredMessage('kidsGroups')}
</p>
) : null}
</div>
<fieldset className="space-y-4"> <fieldset className="space-y-4">
<legend className="mb-3 text-base font-semibold text-primary"> <legend className="mb-3 text-base font-semibold text-primary">
{t('form.whenLegend')} {t('form.whenLegend')}

View File

@@ -6,6 +6,7 @@ import { useAddAttendee } from './AddAttendeeProvider'
import { BulkCapacityModal } from './BulkCapacityModal' import { BulkCapacityModal } from './BulkCapacityModal'
import { BulkImportPanel } from './BulkImportPanel' import { BulkImportPanel } from './BulkImportPanel'
import { CapacityModal } from './CapacityModal' import { CapacityModal } from './CapacityModal'
import { KidQuickAddForm } from './KidQuickAddForm'
import { QuickAddForm } from './QuickAddForm' import { QuickAddForm } from './QuickAddForm'
const TABS = [ const TABS = [
@@ -14,8 +15,10 @@ const TABS = [
] ]
export function AddAttendeePage() { export function AddAttendeePage() {
const { groupId, groupName, attendeesTotal, capacity, groupPending, activeTab, setActiveTab } = const { groupId, groupName, groupAudience, attendeesTotal, capacity, groupPending, activeTab, setActiveTab } =
useAddAttendee() useAddAttendee()
// La carga masiva todavía no lleva los datos del adulto a cargo.
const isKidsGroup = groupAudience === 'KIDS'
const { t } = useTranslation('groupAdd') const { t } = useTranslation('groupAdd')
if (groupPending) { if (groupPending) {
@@ -59,6 +62,7 @@ export function AddAttendeePage() {
</header> </header>
<div className="rounded-xl border border-border bg-surface p-4 sm:p-5"> <div className="rounded-xl border border-border bg-surface p-4 sm:p-5">
{isKidsGroup ? null : (
<div className="mb-5 flex items-center rounded-xl bg-primary-soft p-1"> <div className="mb-5 flex items-center rounded-xl bg-primary-soft p-1">
{TABS.map((tab) => ( {TABS.map((tab) => (
<button <button
@@ -76,8 +80,9 @@ export function AddAttendeePage() {
</button> </button>
))} ))}
</div> </div>
)}
{activeTab === 'quick' ? <QuickAddForm /> : <BulkImportPanel />} {isKidsGroup ? <KidQuickAddForm /> : activeTab === 'quick' ? <QuickAddForm /> : <BulkImportPanel />}
</div> </div>
<CapacityModal /> <CapacityModal />

View File

@@ -7,6 +7,7 @@ import type {
CreateAttendee, CreateAttendee,
CreateAttendeeResult, CreateAttendeeResult,
CreateGroupWaitlistEntry, CreateGroupWaitlistEntry,
GroupAudience,
GroupWaitlistEntryDto, GroupWaitlistEntryDto,
GroupWaitlistList, GroupWaitlistList,
} from '@gruperly/shared' } from '@gruperly/shared'
@@ -38,6 +39,8 @@ export type AddAttendeeTab = 'quick' | 'bulk'
type AddAttendeeContextValue = { type AddAttendeeContextValue = {
groupId: string groupId: string
groupName: string | undefined groupName: string | undefined
/** KIDS: cada alta es un chico con su adulto a cargo. */
groupAudience: GroupAudience
groupPending: boolean groupPending: boolean
attendeesTotal: number attendeesTotal: number
capacity: number | null capacity: number | null
@@ -262,6 +265,7 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
const value: AddAttendeeContextValue = { const value: AddAttendeeContextValue = {
groupId, groupId,
groupName: group?.name, groupName: group?.name,
groupAudience: group?.audience ?? 'ADULTS',
groupPending: groupQuery.isPending, groupPending: groupQuery.isPending,
attendeesTotal, attendeesTotal,
capacity, capacity,
@@ -296,7 +300,14 @@ export function AddAttendeeProvider({ groupId, children }: { groupId: string; ch
}, },
submitWaitlistEntry: () => { submitWaitlistEntry: () => {
if (pendingCapacityPayload) { if (pendingCapacityPayload) {
addToWaitlistMutation.mutate({ ...pendingCapacityPayload }) // Un chico entra a la lista de espera con el teléfono del adulto a cargo
// (la lista de espera de grupos de chicos se completa en otra entrega).
const { guardian, personId: _personId, ...entry } = pendingCapacityPayload
addToWaitlistMutation.mutate({
...entry,
phone: entry.phone || guardian?.phone || '',
email: entry.email || guardian?.email || undefined,
})
} }
}, },
requestBulkImport, requestBulkImport,

Some files were not shown because too many files have changed in this diff Show More