|
| 1 | +import { Injectable, Logger } from '@nestjs/common'; |
| 2 | +import { Processor, WorkerHost } from '@nestjs/bullmq'; |
| 3 | +import { Job } from 'bullmq'; |
| 4 | +import { InvoiceStatus, Prisma } from '@prisma/client'; |
| 5 | +import { PrismaService } from '../prisma/prisma.service'; |
| 6 | +import { NotificationsService } from '../notifications/notifications.service'; |
| 7 | +import { WebhooksService } from '../webhooks/webhooks.service'; |
| 8 | +import { ConfigService } from '@nestjs/config'; |
| 9 | + |
| 10 | +export const INVOICE_REMINDER_QUEUE = 'invoice-reminders'; |
| 11 | + |
| 12 | +export type ReminderType = 'before_due' | 'on_due' | 'after_due'; |
| 13 | + |
| 14 | +export interface ReminderJobData { |
| 15 | + invoiceId: string; |
| 16 | + merchantId: string; |
| 17 | + reminderType: ReminderType; |
| 18 | +} |
| 19 | + |
| 20 | +// Statuses that still need reminders (invoice hasn't been settled) |
| 21 | +const PENDING_STATUSES: InvoiceStatus[] = [ |
| 22 | + InvoiceStatus.SENT, |
| 23 | + InvoiceStatus.VIEWED, |
| 24 | + InvoiceStatus.PARTIALLY_PAID, |
| 25 | + InvoiceStatus.OVERDUE, |
| 26 | +]; |
| 27 | + |
| 28 | +@Injectable() |
| 29 | +@Processor(INVOICE_REMINDER_QUEUE) |
| 30 | +export class InvoicesReminderProcessor extends WorkerHost { |
| 31 | + private readonly logger = new Logger(InvoicesReminderProcessor.name); |
| 32 | + private readonly apiUrl: string; |
| 33 | + private readonly checkoutUrl: string; |
| 34 | + |
| 35 | + constructor( |
| 36 | + private readonly prisma: PrismaService, |
| 37 | + private readonly notifications: NotificationsService, |
| 38 | + private readonly webhooks: WebhooksService, |
| 39 | + private readonly config: ConfigService, |
| 40 | + ) { |
| 41 | + super(); |
| 42 | + this.apiUrl = this.config.get<string>('API_URL', 'http://localhost:3333'); |
| 43 | + this.checkoutUrl = this.config.get<string>( |
| 44 | + 'CHECKOUT_URL', |
| 45 | + 'http://localhost:3002', |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + async process(job: Job<ReminderJobData>): Promise<void> { |
| 50 | + const { invoiceId, merchantId, reminderType } = job.data; |
| 51 | + |
| 52 | + const invoice = await this.prisma.invoice.findUnique({ |
| 53 | + where: { id: invoiceId }, |
| 54 | + }); |
| 55 | + |
| 56 | + if (!invoice) { |
| 57 | + this.logger.warn(`Reminder skipped — invoice ${invoiceId} not found`); |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + // Skip if already settled |
| 62 | + if (!PENDING_STATUSES.includes(invoice.status)) { |
| 63 | + this.logger.log( |
| 64 | + `Reminder skipped — invoice ${invoiceId} status: ${invoice.status}`, |
| 65 | + ); |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + const merchant = await this.prisma.merchant.findUnique({ |
| 70 | + where: { id: merchantId }, |
| 71 | + select: { |
| 72 | + name: true, |
| 73 | + email: true, |
| 74 | + logoUrl: true, |
| 75 | + brandColor: true, |
| 76 | + companyName: true, |
| 77 | + }, |
| 78 | + }); |
| 79 | + |
| 80 | + if (!merchant) return; |
| 81 | + |
| 82 | + const amountDue = |
| 83 | + Number(invoice.total.toString()) - Number(invoice.amountPaid.toString()); |
| 84 | + |
| 85 | + const invoiceEmailData = { |
| 86 | + id: invoice.id, |
| 87 | + reference: invoice.invoiceNumber ?? invoice.id, |
| 88 | + amount: amountDue, |
| 89 | + currency: invoice.currency, |
| 90 | + dueDate: invoice.dueDate ?? new Date(), |
| 91 | + merchantName: merchant.companyName ?? merchant.name, |
| 92 | + merchantEmail: merchant.email, |
| 93 | + merchantLogo: merchant.logoUrl ?? undefined, |
| 94 | + merchantBrandColor: merchant.brandColor ?? undefined, |
| 95 | + customerName: invoice.customerName ?? undefined, |
| 96 | + checkoutUrl: `${this.checkoutUrl}/invoice/${invoice.id}`, |
| 97 | + }; |
| 98 | + |
| 99 | + // ── after_due: mark OVERDUE + fire webhook ───────────────────────────── |
| 100 | + if (reminderType === 'after_due') { |
| 101 | + if (invoice.status !== InvoiceStatus.OVERDUE) { |
| 102 | + await this.prisma.invoice.update({ |
| 103 | + where: { id: invoiceId }, |
| 104 | + data: { status: InvoiceStatus.OVERDUE }, |
| 105 | + }); |
| 106 | + |
| 107 | + await this.webhooks.dispatch(merchantId, 'invoice.overdue', { |
| 108 | + invoiceId, |
| 109 | + customerEmail: invoice.customerEmail, |
| 110 | + total: Number(invoice.total.toString()), |
| 111 | + amountPaid: Number(invoice.amountPaid.toString()), |
| 112 | + currency: invoice.currency, |
| 113 | + dueDate: invoice.dueDate?.toISOString(), |
| 114 | + }); |
| 115 | + |
| 116 | + this.logger.log(`Invoice ${invoiceId} marked OVERDUE`); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + // ── Send reminder email for all types ────────────────────────────────── |
| 121 | + try { |
| 122 | + await this.notifications.sendInvoiceReminder( |
| 123 | + invoice.customerEmail, |
| 124 | + invoiceEmailData as Parameters< |
| 125 | + NotificationsService['sendInvoiceReminder'] |
| 126 | + >[1], |
| 127 | + ); |
| 128 | + this.logger.log( |
| 129 | + `Sent ${reminderType} reminder for invoice ${invoiceId} to ${invoice.customerEmail}`, |
| 130 | + ); |
| 131 | + } catch (err) { |
| 132 | + this.logger.error( |
| 133 | + `Failed to send ${reminderType} reminder for invoice ${invoiceId}`, |
| 134 | + err, |
| 135 | + ); |
| 136 | + throw err; // let BullMQ retry |
| 137 | + } |
| 138 | + } |
| 139 | +} |
0 commit comments