feat(payments): automatic monthly charges with combined links per payer

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-11-11 15:08:48 -03:00
parent 5b3a035dcf
commit ac98495a6e
87 changed files with 2648 additions and 106 deletions

View File

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

View File

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

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