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; provider?: MessagingProvider; now?: Date; intervalMs?: number; sleep?: (ms: number) => Promise; }; /** * 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 { 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(); 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; } }