feat(whatsapp): mensajes automáticos semanales con proveedor intercambiable

- Puerto MessagingProvider con adaptadores OpenWA (MVP, QR) y Kapso
  (setup link de Meta + templates), elegido con WHATSAPP_PROVIDER.
- Vinculación del WhatsApp del profesor en el onboarding y en Ajustes.
- Job semanal (lunes 10:00 AR): recordatorio de pago y reenganche a
  alumnos en riesgo (cooldown 14 días), con switches por grupo.
- Idempotencia por (kind, attendee, semana ISO), webhooks firmados con
  HMAC y deduplicados, normalización de teléfonos a E.164.
- Servicio openwa en docker-compose y guía en docs/whatsapp.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-22 08:38:09 -03:00
parent 8c5caecdda
commit ec65c2198d
90 changed files with 6784 additions and 117 deletions

View File

@@ -0,0 +1,113 @@
import type { PrismaClient } from '@generated/prisma/client';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import {
addTotals,
type DispatchItem,
type DispatchTotals,
dispatchForAccount,
emptyTotals,
sendIntervalFromEnv,
sleep,
} from '../lib/dispatch';
import { formatAmount, formatDueDate } from '../lib/format';
import { getMessagingProvider } from '../providers';
import type { MessagingProvider } from '../providers/messaging-provider';
import { findEligibleAccounts } from './eligible-accounts';
/** Only charges that are due within the coming week (or already overdue). */
const DUE_HORIZON_MS = 7 * 24 * 60 * 60 * 1000;
type SendPaymentRemindersDeps = {
db?: Pick<PrismaClient, 'group' | 'payment' | 'outboundMessage'>;
provider?: MessagingProvider;
now?: Date;
intervalMs?: number;
sleep?: (ms: number) => Promise<void>;
};
/**
* Weekly reminder to members with a PENDING or OVERDUE charge that already has
* a Checkout Pro link, in groups whose owner turned the automation on.
*
* One reminder per member per week even with several open charges: the oldest
* one goes in the message (the rest are in the same Cobros screen anyway).
*/
export class SendPaymentReminders {
constructor(private readonly deps: SendPaymentRemindersDeps = {}) {}
async execute(): Promise<DispatchTotals> {
const providerResult = this.deps.provider ? { ok: true as const, value: this.deps.provider } : getMessagingProvider();
if (!providerResult.ok) {
logger.warn('WhatsApp is not configured; payment reminders skipped');
return emptyTotals();
}
const provider = providerResult.value;
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const totals = emptyTotals();
const accounts = await findEligibleAccounts(db, provider, 'autoPaymentReminders', 'PAYMENT_REMINDER');
for (const { account, country, groups } of accounts) {
const items: DispatchItem[] = [];
for (const group of groups) {
const payments = await db.payment.findMany({
where: {
groupId: group.id,
status: { in: ['PENDING', 'OVERDUE'] },
checkoutUrl: { not: null },
dueDate: { lte: new Date(now.getTime() + DUE_HORIZON_MS) },
attendee: { status: 'ACTIVE' },
},
select: {
id: true,
amount: true,
currency: true,
dueDate: true,
checkoutUrl: true,
attendee: { select: { id: true, fullName: true, phone: true, guardianPhone: true } },
},
orderBy: { dueDate: 'asc' },
});
const seen = new Set<string>();
for (const payment of payments) {
if (seen.has(payment.attendee.id) || !payment.checkoutUrl) continue;
seen.add(payment.attendee.id);
items.push({
groupId: group.id,
attendeeId: payment.attendee.id,
paymentId: payment.id,
rawPhone: payment.attendee.phone ?? payment.attendee.guardianPhone,
message: {
kind: 'PAYMENT_REMINDER',
studentName: payment.attendee.fullName,
groupName: group.name,
amount: formatAmount(Number(payment.amount.toString()), payment.currency, country),
dueDate: formatDueDate(payment.dueDate, country),
paymentLink: payment.checkoutUrl,
},
});
}
}
const result = await dispatchForAccount(
{
db,
provider,
now,
intervalMs: this.deps.intervalMs ?? sendIntervalFromEnv(),
sleep: this.deps.sleep ?? sleep,
},
account,
country,
items,
);
addTotals(totals, result);
}
return totals;
}
}