import type { PrismaClient } from '@generated/prisma/client'; import type { CountryCode } from '@gruperly/shared'; import { type EmailProvider, emailProvider } from '@/lib/email'; import prisma from '@/lib/prisma'; import { logger } from '@/logger'; import { formatAmount } from '@/modules/whatsapp/lib/format'; // Long enough to cover the "Deshacer" on the card: an undone review emails nothing. const NOTIFY_DELAY_MS = 60 * 1000; export type ReviewNotifier = (reportId: string, reviewedAt: Date) => void; /* Tells the student by email (only if they confirmed a recovery email) once the review settles. The in-app banner is the main channel; this is a courtesy, so an in-process timer lost on a restart is acceptable. */ export const scheduleReviewNotification: ReviewNotifier = (reportId, reviewedAt) => { const timer = setTimeout(() => { void sendReviewNotification(reportId, reviewedAt).catch((error) => logger.error({ error, reportId }, 'Payment review notification failed'), ); }, NOTIFY_DELAY_MS); timer.unref?.(); }; export async function sendReviewNotification( reportId: string, reviewedAt: Date, deps: { db?: Pick; email?: Pick } = {}, ): Promise { const db = deps.db ?? prisma; const report = await db.reportedPayment.findUnique({ where: { id: reportId }, select: { status: true, reviewedAt: true, rejectionReason: true, totalAmount: true, currency: true, group: { select: { owner: { select: { country: true } } } }, account: { select: { name: true, recoveryEmail: true, recoveryEmailVerifiedAt: true } }, }, }); // Undone or reviewed again since: this notification is stale. if (!report || report.status === 'REPORTED' || report.reviewedAt?.getTime() !== reviewedAt.getTime()) return false; const account = report.account; if (!account?.recoveryEmail || !account.recoveryEmailVerifiedAt) return false; await (deps.email ?? emailProvider).sendStudentPaymentReviewed({ email: account.recoveryEmail, name: account.name, confirmed: report.status === 'CONFIRMED', amount: formatAmount(report.totalAmount.toNumber(), report.currency, report.group.owner.country as CountryCode | null), reason: report.rejectionReason, }); return true; }