import { beforeEach, describe, expect, it, mock } from 'bun:test'; import { ok, toWhatsappE164 } from '@gruperly/shared'; import { SendPaymentReminders, SendReengagementMessages } from '@/modules/whatsapp/jobs'; import { isoWeekKey } from '@/modules/whatsapp/lib/period'; import { renderMessage } from '@/modules/whatsapp/lib/render-message'; import type { MessagingProvider } from '@/modules/whatsapp/providers/messaging-provider'; /* The weekly jobs, with the provider faked through constructor deps. */ const now = new Date('2026-10-19T13:00:00.000Z'); // Monday const ownerId = 'user-1'; const activeAccount = { id: 'wa-1', ownerId, provider: 'OPENWA', status: 'ACTIVE', externalId: 'session-1', displayPhoneNumber: '+5491100000000', providerData: null, }; function eligibleGroup(overrides: Record = {}) { return { id: 'group-1', name: 'Yoga Martes', createdById: ownerId, owner: { country: 'AR', whatsappAccount: activeAccount }, ...overrides, }; } function payment(id: string, attendee: Record, overrides: Record = {}) { return { id, amount: { toString: () => '25000' }, currency: 'ARS', dueDate: new Date('2026-10-20T15:00:00.000Z'), checkoutUrl: `https://mpago.la/${id}`, attendee: { id: attendee.id, person: { phone: null, ...attendee } }, ...overrides, }; } function fakeProvider(overrides: Partial = {}): MessagingProvider { return { id: 'OPENWA', startConnection: mock(), refreshConnection: mock(), disconnect: mock(), readiness: mock(async () => 'ready' as const), resolveRecipient: mock(async (_account, e164: string) => ({ ok: true as const, to: `${e164.slice(1)}@c.us`, })), send: mock(async () => ({ ok: true as const, providerMessageId: 'wamid-1' })), parseWebhook: mock(() => ok({ dedupeKey: 'k', events: [] })), ...overrides, } as MessagingProvider; } function makeDb() { let counter = 0; return { group: { findMany: mock(async () => [eligibleGroup()]) }, payment: { findMany: mock(async () => [] as unknown[]) }, attendee: { findMany: mock(async () => [] as unknown[]) }, classSession: { findMany: mock(async () => [] as unknown[]) }, attendance: { findMany: mock(async () => [] as unknown[]) }, outboundMessage: { create: mock(async () => ({ id: `msg-${++counter}` })), update: mock(async () => ({})), delete: mock(async () => ({})), findMany: mock(async () => [] as unknown[]), }, }; } let db: ReturnType; const sleep = mock(async () => undefined); beforeEach(() => { db = makeDb(); sleep.mockClear(); }); function reminders(provider: MessagingProvider) { return new SendPaymentReminders({ db: db as never, provider, now, intervalMs: 5000, sleep }); } function reengagement(provider: MessagingProvider) { return new SendReengagementMessages({ db: db as never, provider, now, intervalMs: 5000, sleep }); } describe('payment reminders', () => { it('only looks at groups with the automation on and an active account of this provider', async () => { await reminders(fakeProvider()).execute(); expect(db.group.findMany.mock.calls[0]?.[0]).toMatchObject({ where: { autoPaymentReminders: true, owner: { whatsappAccount: { is: { provider: 'OPENWA', status: 'ACTIVE' } } }, }, }); }); it('asks for open charges with a link due within a week', async () => { await reminders(fakeProvider()).execute(); expect(db.payment.findMany.mock.calls[0]?.[0]).toMatchObject({ where: { groupId: 'group-1', status: { in: ['PENDING', 'OVERDUE'] }, checkoutUrl: { not: null }, dueDate: { lte: new Date('2026-10-26T13:00:00.000Z') }, attendee: { status: 'ACTIVE' }, }, orderBy: { dueDate: 'asc' }, }); }); it('sends one reminder per member, logged before the send and keyed by the row id', async () => { db.payment.findMany.mockResolvedValue([ payment('pay-1', { id: 'att-1', fullName: 'Ana López', phone: '11 2345-6789' }), payment('pay-2', { id: 'att-1', fullName: 'Ana López', phone: '11 2345-6789' }), ]); const provider = fakeProvider(); const totals = await reminders(provider).execute(); expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 }); expect(db.outboundMessage.create).toHaveBeenCalledWith({ data: { ownerId, groupId: 'group-1', attendeeId: 'att-1', paymentId: 'pay-1', kind: 'PAYMENT_REMINDER', provider: 'OPENWA', periodKey: '2026-W43', toPhone: '+5491123456789', status: 'QUEUED', }, select: { id: true }, }); const [, to, message, key] = (provider.send as ReturnType).mock.calls[0] ?? []; expect(to).toBe('5491123456789@c.us'); expect(key).toBe('msg-1'); expect(message).toMatchObject({ kind: 'PAYMENT_REMINDER', studentName: 'Ana López', groupName: 'Yoga Martes', dueDate: '20/10', paymentLink: 'https://mpago.la/pay-1', }); expect(db.outboundMessage.update).toHaveBeenCalledWith({ where: { id: 'msg-1' }, data: expect.objectContaining({ status: 'SENT', providerMessageId: 'wamid-1' }), }); }); it('skips a member already handled this week', async () => { db.payment.findMany.mockResolvedValue([ payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456789' }), ]); db.outboundMessage.create.mockRejectedValueOnce(Object.assign(new Error('dup'), { code: 'P2002' })); const provider = fakeProvider(); const totals = await reminders(provider).execute(); expect(totals).toEqual({ sent: 0, skipped: 1, failed: 0 }); expect(provider.send).not.toHaveBeenCalled(); }); it('falls back to the guardian phone and skips members without a usable one', async () => { db.payment.findMany.mockResolvedValue([ payment('pay-1', { id: 'att-1', fullName: 'Nene', guardians: [{ guardian: { phone: '1123456789' } }] }), payment('pay-2', { id: 'att-2', fullName: 'Sin tel' }), ]); const totals = await reminders(fakeProvider()).execute(); expect(totals).toEqual({ sent: 1, skipped: 1, failed: 0 }); expect(db.outboundMessage.create.mock.calls[1]?.[0]).toMatchObject({ data: { attendeeId: 'att-2', status: 'SKIPPED', errorCode: 'invalid_phone' }, }); }); it('logs numbers without WhatsApp as skipped', async () => { db.payment.findMany.mockResolvedValue([payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456789' })]); const provider = fakeProvider({ resolveRecipient: mock(async () => ({ ok: false as const, code: 'no_whatsapp' as const })), }); const totals = await reminders(provider).execute(); expect(totals).toEqual({ sent: 0, skipped: 1, failed: 0 }); expect(db.outboundMessage.create.mock.calls[0]?.[0]).toMatchObject({ data: { status: 'SKIPPED', errorCode: 'no_whatsapp' }, }); expect(provider.send).not.toHaveBeenCalled(); }); it('skips owners whose templates are not approved yet', async () => { db.payment.findMany.mockResolvedValue([payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456789' })]); const provider = fakeProvider({ readiness: mock(async () => 'pending' as const) }); const totals = await reminders(provider).execute(); expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 }); expect(db.payment.findMany).not.toHaveBeenCalled(); }); it('paces sends and keeps going after a failure', async () => { db.payment.findMany.mockResolvedValue([ payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456781' }), payment('pay-2', { id: 'att-2', fullName: 'Beto', phone: '1123456782' }), payment('pay-3', { id: 'att-3', fullName: 'Caro', phone: '1123456783' }), ]); const send = mock(async () => ({ ok: true as const, providerMessageId: 'wamid' })); send.mockResolvedValueOnce({ ok: true, providerMessageId: 'wamid-a' }); send.mockResolvedValueOnce({ ok: false, retryable: true, code: 'http_500', message: 'engine error', } as never); const provider = fakeProvider({ send }); const totals = await reminders(provider).execute(); expect(totals).toEqual({ sent: 2, skipped: 0, failed: 1 }); expect(sleep).toHaveBeenCalledTimes(2); expect(sleep).toHaveBeenCalledWith(5000); expect(db.outboundMessage.update).toHaveBeenCalledWith({ where: { id: 'msg-2' }, data: { status: 'FAILED', errorCode: 'http_500', errorMessage: 'engine error' }, }); }); it('stops the account when the gateway rate limits it, freeing the unsent row', async () => { db.payment.findMany.mockResolvedValue([ payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456781' }), payment('pay-2', { id: 'att-2', fullName: 'Beto', phone: '1123456782' }), ]); const send = mock(async () => ({ ok: false as const, retryable: true, rateLimitedForMs: 60_000, code: 'SEND_PACING_LIMITED', message: 'cap', })); const provider = fakeProvider({ send }); const totals = await reminders(provider).execute(); expect(totals).toEqual({ sent: 0, skipped: 1, failed: 0 }); expect(send).toHaveBeenCalledTimes(1); expect(db.outboundMessage.delete).toHaveBeenCalledWith({ where: { id: 'msg-1' } }); }); it('does nothing when no group has the automation on', async () => { db.group.findMany.mockResolvedValue([]); const provider = fakeProvider(); const totals = await reminders(provider).execute(); expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 }); expect(provider.readiness).not.toHaveBeenCalled(); }); }); describe('re-engagement messages', () => { function atRiskGroup() { // Two sessions in the window, both missed by att-1: a streak of 2 (MEDIUM). const s1 = new Date('2026-10-16T10:00:00Z'); const s2 = new Date('2026-10-14T10:00:00Z'); const enrolled = new Date('2026-09-01T10:00:00Z'); db.classSession.findMany.mockResolvedValue([ { id: 's1', startsAt: s1 }, { id: 's2', startsAt: s2 }, ]); db.attendee.findMany .mockResolvedValueOnce([ { id: 'att-1', person: { fullName: 'Ana López', phone: '1123456789' }, createdAt: enrolled }, { id: 'att-2', person: { fullName: 'Beto', phone: '1198765432' }, createdAt: enrolled }, ]) .mockResolvedValueOnce([ { id: 'att-1', person: { phone: '1123456789', guardianPhone: null } }, ]); db.attendance.findMany.mockResolvedValue([ { attendeeId: 'att-1', classSessionId: 's1', status: 'ABSENT', classSession: { startsAt: s1 } }, { attendeeId: 'att-1', classSessionId: 's2', status: 'ABSENT', classSession: { startsAt: s2 } }, { attendeeId: 'att-2', classSessionId: 's1', status: 'PRESENT', classSession: { startsAt: s1 } }, { attendeeId: 'att-2', classSessionId: 's2', status: 'PRESENT', classSession: { startsAt: s2 } }, ]); } it('writes to the members at risk, with the copy of the manual button', async () => { atRiskGroup(); const provider = fakeProvider(); const totals = await reengagement(provider).execute(); expect(db.group.findMany.mock.calls[0]?.[0]).toMatchObject({ where: { autoReengagement: true } }); expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 }); const [, , message] = (provider.send as ReturnType).mock.calls[0] ?? []; expect(message).toEqual({ kind: 'REENGAGEMENT', studentName: 'Ana López', groupName: 'Yoga Martes' }); }); it('leaves alone members written to in the last 14 days', async () => { atRiskGroup(); db.outboundMessage.findMany.mockResolvedValue([{ attendeeId: 'att-1' }]); const provider = fakeProvider(); const totals = await reengagement(provider).execute(); expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 }); expect(db.outboundMessage.findMany.mock.calls[0]?.[0]).toMatchObject({ where: { kind: 'REENGAGEMENT', attendeeId: { in: ['att-1'] }, status: { in: ['SENT', 'DELIVERED', 'READ'] }, createdAt: { gte: new Date('2026-10-05T13:00:00.000Z') }, }, }); expect(provider.send).not.toHaveBeenCalled(); }); }); describe('helpers', () => { it('keys messages by ISO week', () => { expect(isoWeekKey(new Date('2026-10-19T13:00:00Z'))).toBe('2026-W43'); expect(isoWeekKey(new Date('2026-10-25T23:59:00Z'))).toBe('2026-W43'); expect(isoWeekKey(new Date('2027-01-01T10:00:00Z'))).toBe('2026-W53'); expect(isoWeekKey(new Date('2025-12-29T10:00:00Z'))).toBe('2026-W01'); }); it('renders the free-text messages with the first name', () => { expect( renderMessage({ kind: 'PAYMENT_REMINDER', studentName: 'Ana López', groupName: 'Yoga', amount: '$ 25.000', dueDate: '20/10', paymentLink: 'https://mpago.la/x', }), ).toBe( '¡Hola Ana! Te recordamos el pago de Yoga por $ 25.000, con vencimiento el 20/10. ' + 'Podés pagarlo desde este link: https://mpago.la/x', ); expect(renderMessage({ kind: 'REENGAGEMENT', studentName: 'Ana López', groupName: 'Yoga' })).toStartWith( '¡Hola Ana! 👋 Te extrañamos en Yoga.', ); }); }); describe('toWhatsappE164', () => { it.each([ ['11 2345-6789', 'AR', '+5491123456789'], ['011 15 2345-6789', 'AR', '+5491123456789'], ['0351 15 123-4567', 'AR', '+5493511234567'], ['9 11 2345 6789', 'AR', '+5491123456789'], ['5491123456789', 'AR', '+5491123456789'], ['+54 11 2345 6789', 'AR', '+5491123456789'], ['+34 612 345 678', 'AR', '+34612345678'], ['0034612345678', 'AR', '+34612345678'], ['(11) 98765-4321', 'BR', '+5511987654321'], ['9 8765 4321', 'CL', '+56987654321'], ['300 123 4567', 'CO', '+573001234567'], ['55 1234 5678', 'MX', '+525512345678'], ['987 654 321', 'PE', '+51987654321'], ['099 123 456', 'UY', '+59899123456'], ] as const)('%s (%s) → %s', (input, country, expected) => { expect(toWhatsappE164(input, country)).toBe(expected); }); it.each([['', 'AR'], ['1234', 'AR'], ['12 3456', 'MX'], ['abc', 'UY']] as const)( 'rejects %p (%s)', (input, country) => { expect(toWhatsappE164(input, country)).toBeNull(); }, ); it('assumes Argentina when the teacher has no country yet', () => { expect(toWhatsappE164('11 2345 6789', null)).toBe('+5491123456789'); }); });