Files
gruperly/apps/backend/test/whatsapp-core.test.ts
Jose Selesan ac98495a6e feat(payments): automatic monthly charges with combined links per payer
- Teacher picks a day of the month in Settings; an hourly job creates the
  fees of all monthly groups on that day in the teacher's time zone
  (one run per teacher and month, partial unique index per attendee/period).
- One Mercado Pago link per payer (PaymentCheckout): the adult in charge
  bundles their kids and their own fees; external_reference chk_<id>,
  dedicated webhook and reconciliation mark every fee PAID at once.
- Person.payWithMercadoPago toggle (default on): off creates the fee
  without a link so the student pays by transfer.
- A fee paid some other way supersedes its combined link and expires the
  preference; renewing rebuilds the combined link or a single one.
- Optional WhatsApp delivery (PAYMENT_LINK kind, new Kapso template);
  weekly reminders now go once per combined link.
- Web: auto charge settings card, per-student toggle, combined link label
  in Cobros and "Pay all" in the student app, in the four locales.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:08:48 -03:00

657 lines
23 KiB
TypeScript

import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { ok } from '@gruperly/shared';
import { CompleteWhatsappSetup } from '@/modules/whatsapp/features/callback/use-case';
import { StartWhatsappConnection } from '@/modules/whatsapp/features/connect/use-case';
import { DisconnectWhatsapp } from '@/modules/whatsapp/features/disconnect/use-case';
import { RequestWhatsappPairingCode } from '@/modules/whatsapp/features/pairing-code/use-case';
import { GetWhatsappStatus } from '@/modules/whatsapp/features/status/use-case';
import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case';
import { HandleWhatsappWebhook } from '@/modules/whatsapp/features/webhook/use-case';
import { toVisibleWhatsappStatus } from '@/modules/whatsapp/lib/account';
import type {
MessagingProvider,
NormalizedEvent,
} from '@/modules/whatsapp/providers/messaging-provider';
/* The domain side of WhatsApp, driven through a fake provider: these tests pin
what the use cases do with whatever any provider answers, so they do not
change when an adapter does. Dependencies go in through constructors (no
`mock.module`), as AGENTS.md asks for provider code. */
const ownerId = 'user-1';
const now = new Date('2026-10-19T13:00:00.000Z');
function fakeProvider(overrides: Partial<MessagingProvider> = {}): MessagingProvider {
return {
id: 'OPENWA',
startConnection: mock(async () =>
ok({
start: { type: 'qr' as const, qrCode: 'data:image/png;base64,QR1' },
externalId: 'session-1',
providerData: { sessionName: 'gruperly-user-1' },
}),
),
refreshConnection: mock(async () => ok({ state: 'pending' as const, qrCode: 'data:QR2' })),
disconnect: mock(async () => ok(undefined)),
readiness: mock(async () => 'ready' as const),
resolveRecipient: mock(async (_account, e164: string) => ({ ok: true as const, to: e164 })),
send: mock(async () => ({ ok: true as const, providerMessageId: 'wamid-1' })),
parseWebhook: mock(() => ok({ dedupeKey: 'delivery-1', events: [] as NormalizedEvent[] })),
...overrides,
} as MessagingProvider;
}
function account(overrides: Record<string, unknown> = {}) {
return {
id: 'wa-1',
ownerId,
provider: 'OPENWA',
status: 'PENDING',
externalId: 'session-1',
displayPhoneNumber: null,
providerData: { sessionName: 'gruperly-user-1' },
connectedAt: null,
...overrides,
};
}
function makeDb() {
return {
whatsappAccount: {
findUnique: mock(),
findFirst: mock(),
upsert: mock(async () => ({})),
update: mock(async ({ data }: { data: Record<string, unknown> }) => account({ ...data })),
},
whatsappWebhookEvent: {
create: mock(async () => ({})),
delete: mock(async () => ({})),
},
outboundMessage: {
updateMany: mock(async () => ({ count: 1 })),
},
group: {
findUnique: mock(),
update: mock(),
},
user: {
findUnique: mock(async () => ({ country: 'AR' })),
},
};
}
type Db = ReturnType<typeof makeDb>;
let db: Db;
beforeEach(() => {
db = makeDb();
});
describe('visible WhatsApp status', () => {
it('maps rows of the active provider', () => {
expect(toVisibleWhatsappStatus(null, 'OPENWA')).toBe('none');
expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'PENDING' }, 'OPENWA')).toBe('pending');
expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'ACTIVE' }, 'OPENWA')).toBe('active');
expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'DISCONNECTED' }, 'OPENWA')).toBe(
'disconnected',
);
});
it('asks to reconnect an account linked with another provider', () => {
expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'ACTIVE' }, 'KAPSO')).toBe(
'requires_reconnect',
);
expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'DISCONNECTED' }, 'KAPSO')).toBe('none');
});
});
describe('start connection', () => {
it('stores a PENDING account and hands the QR to the browser', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(null);
const provider = fakeProvider();
const result = await new StartWhatsappConnection({ db: db as never, provider }).execute(
{ id: ownerId, name: 'Ana Profe' },
'onboarding',
);
expect(result).toEqual({
ok: true,
value: { start: { type: 'qr', qrCode: 'data:image/png;base64,QR1' } },
});
expect(provider.startConnection).toHaveBeenCalledWith({
ownerId,
ownerName: 'Ana Profe',
returnTo: 'onboarding',
account: null,
});
const upsert = db.whatsappAccount.upsert.mock.calls[0]?.[0] as {
create: Record<string, unknown>;
update: Record<string, unknown>;
};
expect(upsert.create).toMatchObject({
ownerId,
provider: 'OPENWA',
status: 'PENDING',
externalId: 'session-1',
});
expect(upsert.update).toMatchObject({ status: 'PENDING', connectedAt: null });
});
it('passes the redirect through for hosted linkings', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(null);
const provider = fakeProvider({
id: 'KAPSO',
startConnection: mock(async () =>
ok({
start: { type: 'redirect' as const, url: 'https://app.kapso.ai/whatsapp/setup/abc' },
externalId: null,
providerData: { customerId: 'cust-1', setupLinkId: 'link-1' },
}),
),
});
const result = await new StartWhatsappConnection({ db: db as never, provider }).execute(
{ id: ownerId, name: 'Ana' },
'settings',
);
expect(result.ok && result.value.start).toEqual({
type: 'redirect',
url: 'https://app.kapso.ai/whatsapp/setup/abc',
});
});
it('does not touch the account when the provider fails', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(null);
const provider = fakeProvider({
startConnection: mock(async () => ({
ok: false as const,
error: { type: 'x', title: 'Bad Gateway', status: 502, code: 'whatsapp_provider_error' },
})),
});
const result = await new StartWhatsappConnection({ db: db as never, provider }).execute(
{ id: ownerId, name: 'Ana' },
'settings',
);
expect(result.ok).toBe(false);
expect(db.whatsappAccount.upsert).not.toHaveBeenCalled();
});
});
describe('status', () => {
it('reports no account', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(null);
const result = await new GetWhatsappStatus({ db: db as never, provider: fakeProvider() }).execute(
ownerId,
);
expect(result).toEqual({
ok: true,
value: {
status: 'none',
provider: 'OPENWA',
displayPhoneNumber: null,
connectedAt: null,
qrCode: null,
readiness: { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked', PAYMENT_LINK: 'blocked' },
},
});
});
it('returns the fresh QR while the linking is pending', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account());
const result = await new GetWhatsappStatus({ db: db as never, provider: fakeProvider() }).execute(
ownerId,
);
expect(result.ok && result.value).toMatchObject({ status: 'pending', qrCode: 'data:QR2' });
expect(db.whatsappAccount.update).not.toHaveBeenCalled();
});
it('activates the account once the provider reports it linked', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account());
const onConnected = mock(async () => undefined);
const provider = fakeProvider({
refreshConnection: mock(async () =>
ok({ state: 'active' as const, displayPhoneNumber: '+5491123456789' }),
),
onConnected,
});
const result = await new GetWhatsappStatus({ db: db as never, provider, now: () => now }).execute(
ownerId,
);
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' },
data: { status: 'ACTIVE', connectedAt: now, displayPhoneNumber: '+5491123456789' },
});
expect(onConnected).toHaveBeenCalledTimes(1);
expect(result.ok && result.value).toMatchObject({
status: 'active',
displayPhoneNumber: '+5491123456789',
connectedAt: now.toISOString(),
readiness: { PAYMENT_REMINDER: 'ready', REENGAGEMENT: 'ready' },
});
});
it('marks a failed linking as disconnected', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account());
const provider = fakeProvider({
refreshConnection: mock(async () => ok({ state: 'disconnected' as const, reason: 'failed' })),
});
const result = await new GetWhatsappStatus({ db: db as never, provider }).execute(ownerId);
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' },
data: { status: 'DISCONNECTED' },
});
expect(result.ok && result.value.status).toBe('disconnected');
});
it('does not poll the provider for an account linked elsewhere', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account({ provider: 'KAPSO', status: 'ACTIVE' }));
const provider = fakeProvider();
const result = await new GetWhatsappStatus({ db: db as never, provider }).execute(ownerId);
expect(provider.refreshConnection).not.toHaveBeenCalled();
expect(result.ok && result.value).toMatchObject({
status: 'requires_reconnect',
readiness: { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked' },
});
});
it('reports a template still under review', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account({ status: 'ACTIVE' }));
const provider = fakeProvider({
readiness: mock(async (_account, kind) => (kind === 'REENGAGEMENT' ? 'pending' : 'ready')),
});
const result = await new GetWhatsappStatus({ db: db as never, provider }).execute(ownerId);
expect(result.ok && result.value.readiness).toEqual({
PAYMENT_REMINDER: 'ready',
REENGAGEMENT: 'pending',
PAYMENT_LINK: 'ready',
});
});
});
describe('pairing code', () => {
const withPairing = () =>
fakeProvider({ requestPairingCode: mock(async () => ok('ABCD1234')) });
it('normalizes the number with the teacher country and returns the code', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account());
const provider = withPairing();
const result = await new RequestWhatsappPairingCode({ db: db as never, provider }).execute(
ownerId,
'011 15 2345-6789',
);
expect(result).toEqual({ ok: true, value: { pairingCode: 'ABCD1234' } });
expect(provider.requestPairingCode).toHaveBeenCalledWith(
expect.objectContaining({ id: 'wa-1' }),
'5491123456789',
);
});
it('needs a linking in progress with the active provider', async () => {
for (const current of [null, account({ status: 'ACTIVE' }), account({ provider: 'KAPSO' })]) {
db.whatsappAccount.findUnique.mockResolvedValue(current);
const provider = withPairing();
const result = await new RequestWhatsappPairingCode({ db: db as never, provider }).execute(
ownerId,
'1123456789',
);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.code).toBe('whatsapp_linking_not_started');
expect(provider.requestPairingCode).not.toHaveBeenCalled();
}
});
it('rejects a number it cannot normalize', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account());
const provider = withPairing();
const result = await new RequestWhatsappPairingCode({ db: db as never, provider }).execute(
ownerId,
'12345',
);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.status).toBe(400);
expect(provider.requestPairingCode).not.toHaveBeenCalled();
});
it('answers 409 when the provider only links by QR or redirect', async () => {
const result = await new RequestWhatsappPairingCode({
db: db as never,
provider: fakeProvider(),
}).execute(ownerId, '1123456789');
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.code).toBe('whatsapp_pairing_unsupported');
});
});
describe('disconnect', () => {
it('unlinks on the provider and frees the number locally', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account({ status: 'ACTIVE' }));
const provider = fakeProvider();
const result = await new DisconnectWhatsapp({ db: db as never, provider }).execute(ownerId);
expect(result).toEqual({ ok: true, value: { disconnected: true } });
expect(provider.disconnect).toHaveBeenCalledTimes(1);
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' },
data: { status: 'DISCONNECTED', externalId: null, displayPhoneNumber: null, connectedAt: null },
});
});
it('is a no-op without a linked account', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(null);
const result = await new DisconnectWhatsapp({ db: db as never, provider: fakeProvider() }).execute(
ownerId,
);
expect(result).toEqual({ ok: true, value: { disconnected: false } });
expect(db.whatsappAccount.update).not.toHaveBeenCalled();
});
});
describe('redirect callback', () => {
it('activates the account the provider confirmed', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(
account({ provider: 'KAPSO', externalId: null, providerData: { customerId: 'cust-1' } }),
);
const provider = fakeProvider({
id: 'KAPSO',
completeRedirect: mock(async () =>
ok({
externalId: 'phone-1',
displayPhoneNumber: '+5491100000000',
providerData: { businessAccountId: 'waba-1' },
}),
),
});
const outcome = await new CompleteWhatsappSetup({ db: db as never, provider, now: () => now }).execute(
ownerId,
{ setup_link_id: 'link-1', phone_number_id: 'phone-1', status: 'completed' },
);
expect(outcome).toEqual({ kind: 'success' });
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' },
data: {
status: 'ACTIVE',
connectedAt: now,
externalId: 'phone-1',
displayPhoneNumber: '+5491100000000',
providerData: { customerId: 'cust-1', businessAccountId: 'waba-1' },
},
});
});
it('reports a number already linked to someone else', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account({ provider: 'KAPSO' }));
db.whatsappAccount.update.mockRejectedValueOnce(Object.assign(new Error('unique'), { code: 'P2002' }));
const provider = fakeProvider({
id: 'KAPSO',
completeRedirect: mock(async () => ok({ externalId: 'phone-1', displayPhoneNumber: null })),
});
const outcome = await new CompleteWhatsappSetup({ db: db as never, provider }).execute(ownerId, {});
expect(outcome).toEqual({ kind: 'error', reason: 'number_in_use' });
});
it('refuses a provider without hosted linking', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account());
const outcome = await new CompleteWhatsappSetup({ db: db as never, provider: fakeProvider() }).execute(
ownerId,
{},
);
expect(outcome).toEqual({ kind: 'error', reason: 'invalid_setup' });
});
});
describe('webhook', () => {
const headers = new Headers();
it('rejects an invalid signature before touching the database', async () => {
const provider = fakeProvider({
parseWebhook: mock(() => ({ ok: false as const, error: 'invalid_signature' as const })),
});
const result = await new HandleWhatsappWebhook({ db: db as never, provider }).execute(
'OPENWA',
'{}',
headers,
);
expect(result).toEqual({ ok: false, error: 'invalid_signature' });
expect(db.whatsappWebhookEvent.create).not.toHaveBeenCalled();
});
it('ignores a delivery it already processed', async () => {
db.whatsappWebhookEvent.create.mockRejectedValueOnce(Object.assign(new Error('dup'), { code: 'P2002' }));
const provider = fakeProvider({
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-1',
events: [{ type: 'message_status' as const, providerMessageId: 'wamid-1', status: 'READ' as const }],
}),
),
});
const result = await new HandleWhatsappWebhook({ db: db as never, provider }).execute(
'OPENWA',
'{}',
headers,
);
expect(result).toEqual({ ok: true, value: { duplicate: true, applied: 0 } });
expect(db.outboundMessage.updateMany).not.toHaveBeenCalled();
});
it('advances a message status without moving it backwards', async () => {
const provider = fakeProvider({
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-2',
events: [{ type: 'message_status' as const, providerMessageId: 'wamid-1', status: 'DELIVERED' as const }],
}),
),
});
await new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers);
expect(db.whatsappWebhookEvent.create).toHaveBeenCalledWith({
data: { provider: 'OPENWA', dedupeKey: 'delivery-2' },
});
expect(db.outboundMessage.updateMany).toHaveBeenCalledWith({
where: {
provider: 'OPENWA',
providerMessageId: 'wamid-1',
status: { in: ['QUEUED', 'SENT'] },
},
data: { status: 'DELIVERED' },
});
});
it('records why a message failed', async () => {
const provider = fakeProvider({
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-3',
events: [
{
type: 'message_status' as const,
providerMessageId: 'wamid-1',
status: 'FAILED' as const,
errorCode: '131026',
errorMessage: 'Message undeliverable',
},
],
}),
),
});
await new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers);
expect(db.outboundMessage.updateMany.mock.calls[0]?.[0]).toMatchObject({
data: { status: 'FAILED', errorCode: '131026', errorMessage: 'Message undeliverable' },
});
});
it('activates the account a connection event names and runs the setup once', async () => {
db.whatsappAccount.findFirst.mockResolvedValueOnce(account());
const onConnected = mock(async () => undefined);
const provider = fakeProvider({
onConnected,
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-4',
events: [
{
type: 'connection' as const,
externalId: 'session-1',
status: 'active' as const,
displayPhoneNumber: '+5491123456789',
},
],
}),
),
});
const result = await new HandleWhatsappWebhook({ db: db as never, provider, now: () => now }).execute(
'OPENWA',
'{}',
headers,
);
expect(result).toEqual({ ok: true, value: { duplicate: false, applied: 1 } });
expect(db.whatsappAccount.update.mock.calls[0]?.[0]).toMatchObject({
where: { id: 'wa-1' },
data: { status: 'ACTIVE', connectedAt: now, externalId: 'session-1' },
});
expect(onConnected).toHaveBeenCalledTimes(1);
});
it('falls back to the owner reference when the number is new to us', async () => {
db.whatsappAccount.findFirst.mockResolvedValueOnce(null).mockResolvedValueOnce(account({ provider: 'KAPSO' }));
const provider = fakeProvider({
id: 'KAPSO',
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-5',
events: [{ type: 'connection' as const, externalId: 'phone-1', ownerId, status: 'active' as const }],
}),
),
});
await new HandleWhatsappWebhook({ db: db as never, provider }).execute('KAPSO', '{}', headers);
expect(db.whatsappAccount.findFirst.mock.calls[1]?.[0]).toEqual({
where: { provider: 'KAPSO', ownerId, status: { not: 'DISCONNECTED' } },
});
expect(db.whatsappAccount.update.mock.calls[0]?.[0]).toMatchObject({
data: { status: 'ACTIVE', externalId: 'phone-1' },
});
});
it('marks an unlinked number as disconnected', async () => {
db.whatsappAccount.findFirst.mockResolvedValueOnce(account({ status: 'ACTIVE' }));
const provider = fakeProvider({
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-6',
events: [{ type: 'connection' as const, externalId: 'session-1', status: 'disconnected' as const }],
}),
),
});
await new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers);
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' },
data: { status: 'DISCONNECTED' },
});
});
it('un-burns the delivery when applying it fails, so the retry gets through', async () => {
db.outboundMessage.updateMany.mockRejectedValueOnce(new Error('db down'));
const provider = fakeProvider({
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-7',
events: [{ type: 'message_status' as const, providerMessageId: 'wamid-1', status: 'READ' as const }],
}),
),
});
await expect(
new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers),
).rejects.toThrow('db down');
expect(db.whatsappWebhookEvent.delete).toHaveBeenCalledWith({
where: { provider_dedupeKey: { provider: 'OPENWA', dedupeKey: 'delivery-7' } },
});
});
});
describe('group automations', () => {
it('lets the owner turn an automation on', async () => {
db.group.findUnique.mockResolvedValue({ id: 'group-1', createdById: ownerId });
db.group.update.mockResolvedValue({ autoPaymentReminders: true, autoReengagement: false });
const result = await new UpdateGroupAutomationsUseCase({ db: db as never }).execute('group-1', ownerId, {
autoPaymentReminders: true,
});
expect(result).toEqual({ ok: true, value: { autoPaymentReminders: true, autoReengagement: false } });
expect(db.group.update).toHaveBeenCalledWith({
where: { id: 'group-1' },
data: { autoPaymentReminders: true },
select: { autoPaymentReminders: true, autoReengagement: true },
});
});
it('refuses anyone but the owner', async () => {
db.group.findUnique.mockResolvedValue({ id: 'group-1', createdById: 'someone-else' });
const result = await new UpdateGroupAutomationsUseCase({ db: db as never }).execute('group-1', ownerId, {
autoReengagement: true,
});
expect(result.ok).toBe(false);
expect(!result.ok && result.error.status).toBe(403);
expect(db.group.update).not.toHaveBeenCalled();
});
it('answers 404 for an unknown group', async () => {
db.group.findUnique.mockResolvedValue(null);
const result = await new UpdateGroupAutomationsUseCase({ db: db as never }).execute('nope', ownerId, {
autoReengagement: true,
});
expect(!result.ok && result.error.status).toBe(404);
});
});