- Acceso del alumno o tutor con link de un solo uso (hash SHA-256, consumo atómico, el GET no consume), sesión propia de 90 días deslizante, passkeys opcionales (SimpleWebAuthn) y mail de recuperación con rate limit. - Lado alumno (/i/:token, /acceso, /alumno/*): inicio, clases, avisar falta, pagos, informar pago con comprobante (S3 privado, magic bytes) y perfil. - Lado profe: acceso a la app en la ficha del alumno (invitar/reinvitar), "Pagos para verificar" en Cobros con badge, faltas avisadas en la ficha de grupo y datos para transferir en Ajustes. - "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas informadas. - Zona horaria por defecto: Buenos Aires. - Migración add_student_access, tests contra Postgres real (test:db) y docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
116 lines
3.9 KiB
TypeScript
116 lines
3.9 KiB
TypeScript
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' },
|
|
// Already reported by the student: the teacher is reviewing it.
|
|
reportedItems: { none: { reportedPayment: { status: 'REPORTED' } } },
|
|
},
|
|
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;
|
|
}
|
|
}
|