feat(whatsapp): mensajes automáticos semanales con proveedor intercambiable

- Puerto MessagingProvider con adaptadores OpenWA (MVP, QR) y Kapso
  (setup link de Meta + templates), elegido con WHATSAPP_PROVIDER.
- Vinculación del WhatsApp del profesor en el onboarding y en Ajustes.
- Job semanal (lunes 10:00 AR): recordatorio de pago y reenganche a
  alumnos en riesgo (cooldown 14 días), con switches por grupo.
- Idempotencia por (kind, attendee, semana ISO), webhooks firmados con
  HMAC y deduplicados, normalización de teléfonos a E.164.
- Servicio openwa en docker-compose y guía en docs/whatsapp.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-22 08:38:09 -03:00
parent 8c5caecdda
commit ec65c2198d
90 changed files with 6784 additions and 117 deletions

View File

@@ -40,6 +40,8 @@ const group = {
billingType: null,
dueDay: null,
inviteToken: null,
autoPaymentReminders: false,
autoReengagement: false,
};
function makeApp(userValue: unknown) {

View File

@@ -9,6 +9,9 @@ const db = {
mpAccount: {
findUnique: mock(),
},
whatsappAccount: {
findUnique: mock(async () => null),
},
group: {
create: mock(),
},
@@ -54,6 +57,8 @@ const group = {
price: 150.5,
billingType: 'MONTHLY',
dueDay: 5,
autoPaymentReminders: false,
autoReengagement: false,
};
const firstGroupPayload = {
@@ -83,6 +88,7 @@ describe('onboarding routes', () => {
expect(await res.json()).toEqual({
step: 'NOT_STARTED',
paymentConnected: false,
whatsappConnected: false,
completed: false,
});
});
@@ -97,6 +103,7 @@ describe('onboarding routes', () => {
expect(await res.json()).toEqual({
step: 'PAYMENT_CONNECTED',
paymentConnected: true,
whatsappConnected: false,
completed: false,
});
});
@@ -115,6 +122,7 @@ describe('onboarding routes', () => {
expect(await res.json()).toEqual({
step: 'NOT_STARTED',
paymentConnected: false,
whatsappConnected: false,
completed: false,
});
});
@@ -128,6 +136,7 @@ describe('onboarding routes', () => {
expect(await res.json()).toEqual({
step: 'COMPLETED',
paymentConnected: true,
whatsappConnected: false,
completed: true,
});
});
@@ -166,6 +175,8 @@ describe('onboarding routes', () => {
price: 150.5,
billingType: 'MONTHLY',
dueDay: 5,
autoPaymentReminders: false,
autoReengagement: false,
},
onboardingCompleted: true,
});

View File

@@ -50,6 +50,17 @@ describe('session auth', () => {
).toBe(false);
});
it('classifies the WhatsApp provider webhooks as public (signature-based)', () => {
expect(isPublicApiRequest('POST', '/api/v1/whatsapp/webhooks/openwa')).toBe(true);
expect(isPublicApiRequest('POST', '/api/v1/whatsapp/webhooks/kapso/')).toBe(true);
// Everything else under /whatsapp needs the teacher's session.
expect(isPublicApiRequest('GET', '/api/v1/whatsapp/webhooks/openwa')).toBe(false);
expect(isPublicApiRequest('POST', '/api/v1/whatsapp/webhooks/other')).toBe(false);
expect(isPublicApiRequest('GET', '/api/v1/whatsapp/status')).toBe(false);
expect(isPublicApiRequest('POST', '/api/v1/whatsapp/connect')).toBe(false);
expect(isPublicApiRequest('GET', '/api/v1/whatsapp/callback')).toBe(false);
});
it('allows public requests without a session', async () => {
const app = new Hono();
app.use('*', sessionAuthMiddleware);

View File

@@ -0,0 +1,590 @@
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 { 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(),
},
};
}
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' },
},
});
});
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',
});
});
});
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);
});
});

View File

@@ -0,0 +1,383 @@
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<string, unknown> = {}) {
return {
id: 'group-1',
name: 'Yoga Martes',
createdById: ownerId,
owner: { country: 'AR', whatsappAccount: activeAccount },
...overrides,
};
}
function payment(id: string, attendee: Record<string, unknown>, overrides: Record<string, unknown> = {}) {
return {
id,
amount: { toString: () => '25000' },
currency: 'ARS',
dueDate: new Date('2026-10-20T15:00:00.000Z'),
checkoutUrl: `https://mpago.la/${id}`,
attendee: { phone: null, guardianPhone: null, ...attendee },
...overrides,
};
}
function fakeProvider(overrides: Partial<MessagingProvider> = {}): 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<typeof makeDb>;
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<typeof mock>).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', guardianPhone: '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).
db.classSession.findMany.mockResolvedValue([{ id: 's1' }, { id: 's2' }]);
db.attendee.findMany
.mockResolvedValueOnce([
{ id: 'att-1', fullName: 'Ana López', phone: '1123456789' },
{ id: 'att-2', fullName: 'Beto', phone: '1198765432' },
])
.mockResolvedValueOnce([
{ id: 'att-1', phone: '1123456789', guardianPhone: null },
]);
db.attendance.findMany.mockResolvedValue([
{ attendeeId: 'att-1', status: 'ABSENT', classSession: { startsAt: new Date('2026-10-16T10:00:00Z') } },
{ attendeeId: 'att-1', status: 'ABSENT', classSession: { startsAt: new Date('2026-10-14T10:00:00Z') } },
{ attendeeId: 'att-2', status: 'PRESENT', classSession: { startsAt: new Date('2026-10-16T10:00:00Z') } },
{ attendeeId: 'att-2', status: 'PRESENT', classSession: { startsAt: new Date('2026-10-14T10:00:00Z') } },
]);
}
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<typeof mock>).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');
});
});

View File

@@ -0,0 +1,600 @@
import { describe, expect, it, mock } from 'bun:test';
import { createHmac } from 'node:crypto';
import { KapsoProvider } from '@/modules/whatsapp/providers/kapso';
import type { WhatsappAccountRecord } from '@/modules/whatsapp/providers/messaging-provider';
import { OpenWaProvider, openWaSessionName } from '@/modules/whatsapp/providers/openwa';
/* Both adapters against a recorded `fetch`: the requests they make and how they
read the answers. No network, no `mock.module`. */
type Route = { method: string; path: string; status?: number; body?: unknown };
function fakeFetch(routes: Route[]) {
const calls: { method: string; url: string; headers: Record<string, string>; body: unknown }[] = [];
const fn = mock(async (url: string, init?: RequestInit) => {
const method = init?.method ?? 'GET';
calls.push({
method,
url,
headers: (init?.headers ?? {}) as Record<string, string>,
body: init?.body ? JSON.parse(String(init.body)) : undefined,
});
const route = routes.find((candidate) => candidate.method === method && url.endsWith(candidate.path));
if (!route) return new Response(JSON.stringify({ statusCode: 404 }), { status: 404 });
return new Response(route.body === undefined ? null : JSON.stringify(route.body), {
status: route.status ?? 200,
});
});
return { fn, calls };
}
const openWaConfig = {
apiUrl: 'http://openwa:2785/api',
apiKey: 'owa_k1_test',
webhookUrl: 'https://api.example.com/api/v1/whatsapp/webhooks/openwa',
webhookSecret: 'a-very-long-webhook-secret',
};
function openWaAccount(overrides: Partial<WhatsappAccountRecord> = {}): WhatsappAccountRecord {
return {
id: 'wa-1',
ownerId: 'user-1',
provider: 'OPENWA',
status: 'ACTIVE',
externalId: 'sess-1',
displayPhoneNumber: null,
providerData: { sessionName: 'gruperly-user-1', webhookId: 'wh-1' },
...overrides,
};
}
function sign(body: string, secret: string) {
return createHmac('sha256', secret).update(body).digest('hex');
}
describe('OpenWA provider', () => {
it('creates a session, subscribes the webhook, starts it and returns the QR', async () => {
const { fn, calls } = fakeFetch([
{
method: 'POST',
path: '/sessions',
status: 201,
body: { id: 'sess-1', name: 'gruperly-user-1', status: 'created', engineLoaded: false },
},
{ method: 'POST', path: '/sessions/sess-1/webhooks', status: 201, body: { id: 'wh-1' } },
{
method: 'POST',
path: '/sessions/sess-1/start',
body: { id: 'sess-1', name: 'gruperly-user-1', status: 'initializing', engineLoaded: true },
},
{ method: 'GET', path: '/sessions/sess-1/qr', body: { qrCode: 'data:image/png;base64,QR', status: 'qr_ready' } },
]);
const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
const result = await provider.startConnection({
ownerId: 'user-1',
ownerName: 'Ana',
returnTo: 'settings',
account: null,
});
expect(result).toEqual({
ok: true,
value: {
start: { type: 'qr', qrCode: 'data:image/png;base64,QR' },
externalId: 'sess-1',
providerData: { sessionName: 'gruperly-user-1', webhookId: 'wh-1' },
},
});
expect(calls[0]).toMatchObject({ method: 'POST', body: { name: 'gruperly-user-1' } });
expect(calls[0]?.headers['X-API-Key']).toBe('owa_k1_test');
expect(calls[1]?.body).toMatchObject({
url: openWaConfig.webhookUrl,
secret: openWaConfig.webhookSecret,
events: expect.arrayContaining(['message.ack', 'session.authenticated']),
});
});
it('adopts a session that already exists under the teacher name', async () => {
const { fn } = fakeFetch([
{ method: 'POST', path: '/sessions', status: 409, body: { statusCode: 409 } },
{
method: 'GET',
path: '/sessions?name=gruperly-user-1',
body: [{ id: 'sess-9', name: 'gruperly-user-1', status: 'qr_ready', engineLoaded: true }],
},
{ method: 'POST', path: '/sessions/sess-9/webhooks', status: 201, body: { id: 'wh-9' } },
{ method: 'GET', path: '/sessions/sess-9/qr', status: 400, body: { statusCode: 400 } },
]);
const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
const result = await provider.startConnection({
ownerId: 'user-1',
ownerName: 'Ana',
returnTo: 'settings',
account: null,
});
expect(result.ok && result.value).toMatchObject({
start: { type: 'qr', qrCode: null },
externalId: 'sess-9',
});
});
it('answers a provider problem when OpenWA is down', async () => {
const fn = mock(async () => {
throw new TypeError('fetch failed');
});
const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
const result = await provider.startConnection({
ownerId: 'user-1',
ownerName: 'Ana',
returnTo: 'settings',
account: null,
});
expect(!result.ok && result.error.code).toBe('whatsapp_provider_error');
});
it('maps session states', async () => {
const cases = [
[{ status: 'ready', phone: '5491123456789', engineLoaded: true }, { state: 'active', displayPhoneNumber: '+5491123456789' }],
[{ status: 'initializing', engineLoaded: true }, { state: 'pending', qrCode: null }],
[{ status: 'disconnected', engineLoaded: true }, { state: 'pending', qrCode: null }],
[{ status: 'failed', lastError: 'boom', engineLoaded: false }, { state: 'disconnected', reason: 'boom' }],
] as const;
for (const [session, expected] of cases) {
const { fn } = fakeFetch([{ method: 'GET', path: '/sessions/sess-1', body: { id: 'sess-1', ...session } }]);
const result = await new OpenWaProvider(openWaConfig, { fetch: fn }).refreshConnection(
openWaAccount({ status: 'PENDING' }),
);
expect(result).toEqual({ ok: true, value: expected as never });
}
});
it('resolves recipients through the contact check', async () => {
const { fn, calls } = fakeFetch([
{
method: 'GET',
path: '/sessions/sess-1/contacts/check/5491123456789',
body: { exists: true, whatsappId: '541123456789@c.us' },
},
]);
const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
expect(await provider.resolveRecipient(openWaAccount(), '+5491123456789')).toEqual({
ok: true,
to: '541123456789@c.us',
});
expect(calls).toHaveLength(1);
});
it('sends free text with an idempotency key', async () => {
const { fn, calls } = fakeFetch([
{
method: 'POST',
path: '/sessions/sess-1/messages/send-text',
status: 201,
body: { messageId: 'true_5491123456789@c.us_3EB0', timestamp: 1 },
},
]);
const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
const outcome = await provider.send(
openWaAccount(),
'5491123456789@c.us',
{ kind: 'REENGAGEMENT', studentName: 'Ana López', groupName: 'Yoga' },
'msg-1',
);
expect(outcome).toEqual({ ok: true, providerMessageId: 'true_5491123456789@c.us_3EB0' });
expect(calls[0]?.headers['Idempotency-Key']).toBe('msg-1');
expect(calls[0]?.body).toMatchObject({ chatId: '5491123456789@c.us' });
expect(String((calls[0]?.body as { text?: string } | undefined)?.text)).toStartWith('¡Hola Ana!');
});
it('turns send pacing into a rate limit for the account', async () => {
const { fn } = fakeFetch([
{
method: 'POST',
path: '/sessions/sess-1/messages/send-text',
status: 429,
body: { statusCode: 429, code: 'SEND_PACING_LIMITED', retryAfterSeconds: 120 },
},
]);
const outcome = await new OpenWaProvider(openWaConfig, { fetch: fn }).send(
openWaAccount(),
'x@c.us',
{ kind: 'REENGAGEMENT', studentName: 'Ana', groupName: 'Yoga' },
'msg-1',
);
expect(outcome).toMatchObject({ ok: false, rateLimitedForMs: 120_000, code: 'SEND_PACING_LIMITED' });
});
it('verifies the webhook signature and normalizes acks and session events', () => {
const provider = new OpenWaProvider(openWaConfig);
const ack = JSON.stringify({
event: 'message.ack',
sessionId: 'sess-1',
idempotencyKey: 'ack_sess-1_m1_read',
deliveryId: 'dlv_1',
data: { id: 'row', messageId: 'm1', status: 'read', ack: 3 },
});
const good = new Headers({
'X-OpenWA-Signature': `sha256=${sign(ack, openWaConfig.webhookSecret)}`,
'X-OpenWA-Idempotency-Key': 'ack_sess-1_m1_read',
});
expect(provider.parseWebhook(ack, good)).toEqual({
ok: true,
value: {
dedupeKey: 'ack_sess-1_m1_read',
events: [{ type: 'message_status', providerMessageId: 'm1', status: 'READ', errorCode: null }],
},
});
const tampered = new Headers({ 'X-OpenWA-Signature': `sha256=${sign(`${ack} `, openWaConfig.webhookSecret)}` });
expect(provider.parseWebhook(ack, tampered)).toEqual({ ok: false, error: 'invalid_signature' });
expect(provider.parseWebhook(ack, new Headers())).toEqual({ ok: false, error: 'invalid_signature' });
const auth = JSON.stringify({
event: 'session.authenticated',
sessionId: 'sess-1',
idempotencyKey: 'auth_1',
data: { sessionId: 'sess-1', phone: '5491123456789' },
});
const authHeaders = new Headers({ 'X-OpenWA-Signature': `sha256=${sign(auth, openWaConfig.webhookSecret)}` });
expect(provider.parseWebhook(auth, authHeaders)).toEqual({
ok: true,
value: {
dedupeKey: 'auth_1',
events: [
{ type: 'connection', externalId: 'sess-1', status: 'active', displayPhoneNumber: '+5491123456789' },
],
},
});
});
it('builds valid session names', () => {
expect(openWaSessionName('cmh1x2y3z0000abcd')).toBe('gruperly-cmh1x2y3z0000abcd');
expect(openWaSessionName('weird_id.with@chars')).toBe('gruperly-weirdidwithchars');
});
});
const kapsoConfig = {
apiUrl: 'https://api.kapso.ai',
apiKey: 'kapso-key',
callbackUrl: 'https://api.example.com/api/v1/whatsapp/callback',
webhookUrl: 'https://api.example.com/api/v1/whatsapp/webhooks/kapso',
webhookSecret: 'kapso-webhook-secret',
};
function kapsoAccount(overrides: Partial<WhatsappAccountRecord> = {}): WhatsappAccountRecord {
return {
id: 'wa-1',
ownerId: 'user-1',
provider: 'KAPSO',
status: 'PENDING',
externalId: null,
displayPhoneNumber: null,
providerData: { customerId: 'cust-1', setupLinkId: 'link-1' },
...overrides,
};
}
function kapsoDb() {
return {
whatsappAccount: { update: mock(async () => ({})) },
whatsappTemplate: {
findUnique: mock(async () => null as unknown),
findMany: mock(async () => [] as unknown[]),
create: mock(async () => ({})),
update: mock(async () => ({})),
},
};
}
describe('Kapso provider', () => {
it('creates the customer once and a customer-billed setup link', async () => {
const { fn, calls } = fakeFetch([
{ method: 'POST', path: '/platform/v1/customers', status: 201, body: { data: { id: 'cust-1' } } },
{
method: 'POST',
path: '/platform/v1/customers/cust-1/setup_links',
status: 201,
body: { data: { id: 'link-1', url: 'https://app.kapso.ai/whatsapp/setup/abc' } },
},
]);
const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn });
const result = await provider.startConnection({
ownerId: 'user-1',
ownerName: 'Ana Profe',
returnTo: 'onboarding',
account: null,
});
expect(result).toEqual({
ok: true,
value: {
start: { type: 'redirect', url: 'https://app.kapso.ai/whatsapp/setup/abc' },
externalId: null,
providerData: { customerId: 'cust-1', setupLinkId: 'link-1' },
},
});
expect(calls[0]?.body).toEqual({ customer: { name: 'Ana Profe', external_customer_id: 'user-1' } });
expect(calls[1]?.body).toMatchObject({
setup_link: {
success_redirect_url: `${kapsoConfig.callbackUrl}?returnTo=onboarding`,
meta_billing_mode: 'customer_managed',
language: 'es',
},
});
// Linking again reuses the customer.
const again = fakeFetch([
{
method: 'POST',
path: '/platform/v1/customers/cust-1/setup_links',
status: 201,
body: { data: { id: 'link-2', url: 'https://app.kapso.ai/whatsapp/setup/def' } },
},
]);
await new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: again.fn }).startConnection({
ownerId: 'user-1',
ownerName: 'Ana',
returnTo: 'settings',
account: kapsoAccount(),
});
expect(again.calls).toHaveLength(1);
});
it('does not trust the callback query', async () => {
const { fn } = fakeFetch([
{
method: 'GET',
path: '/platform/v1/whatsapp/phone_numbers/phone-1',
body: {
data: {
phone_number_id: 'phone-1',
business_account_id: 'waba-1',
display_phone_number: '+54 9 11 2345-6789',
customer_id: 'someone-else',
},
},
},
]);
const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn });
expect(
await provider.completeRedirect(kapsoAccount(), { setup_link_id: 'other', phone_number_id: 'phone-1' }),
).toEqual({ ok: false, error: 'invalid_setup' });
expect(
await provider.completeRedirect(kapsoAccount(), { setup_link_id: 'link-1', error_code: 'facebook_auth_failed' }),
).toEqual({ ok: false, error: 'setup_failed' });
expect(
await provider.completeRedirect(kapsoAccount(), {
setup_link_id: 'link-1',
status: 'completed',
phone_number_id: 'phone-1',
}),
).toEqual({ ok: false, error: 'invalid_setup' });
});
it('completes a setup confirmed by Kapso', async () => {
const { fn } = fakeFetch([
{
method: 'GET',
path: '/platform/v1/whatsapp/phone_numbers/phone-1',
body: {
data: {
phone_number_id: 'phone-1',
business_account_id: 'waba-1',
display_phone_number: '+54 9 11 2345-6789',
customer_id: 'cust-1',
},
},
},
]);
const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn });
expect(
await provider.completeRedirect(kapsoAccount(), {
setup_link_id: 'link-1',
status: 'completed',
phone_number_id: 'phone-1',
}),
).toEqual({
ok: true,
value: {
externalId: 'phone-1',
displayPhoneNumber: '+5491123456789',
providerData: { customerId: 'cust-1', setupLinkId: 'link-1', businessAccountId: 'waba-1' },
},
});
});
it('subscribes the number and submits both templates after connecting', async () => {
const { fn, calls } = fakeFetch([
{
method: 'POST',
path: '/platform/v1/whatsapp/phone_numbers/phone-1/webhooks',
status: 201,
body: { data: { id: 'wh-1' } },
},
{
method: 'POST',
path: '/meta/whatsapp/v24.0/waba-1/message_templates',
body: { id: 'tpl-1', status: 'PENDING', category: 'UTILITY' },
},
]);
const db = kapsoDb();
const provider = new KapsoProvider(kapsoConfig, { db: db as never, fetch: fn });
await provider.onConnected(
kapsoAccount({
status: 'ACTIVE',
externalId: 'phone-1',
providerData: { customerId: 'cust-1', businessAccountId: 'waba-1' },
}),
);
expect(calls[0]?.body).toMatchObject({
whatsapp_webhook: { url: kapsoConfig.webhookUrl, secret_key: kapsoConfig.webhookSecret, kind: 'kapso' },
});
const templates = calls.filter((call) => call.url.endsWith('/message_templates'));
expect(templates.map((call) => (call.body as { name: string; category: string }))).toEqual([
expect.objectContaining({ name: 'gruperly_payment_reminder', category: 'UTILITY' }),
expect.objectContaining({ name: 'gruperly_reengagement', category: 'MARKETING' }),
]);
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' },
data: { providerData: { customerId: 'cust-1', businessAccountId: 'waba-1', webhookId: 'wh-1' } },
});
expect(db.whatsappTemplate.create).toHaveBeenCalledTimes(2);
});
it('is ready only once the template is approved', async () => {
const db = kapsoDb();
const provider = new KapsoProvider(kapsoConfig, { db: db as never });
const active = kapsoAccount({ status: 'ACTIVE', externalId: 'phone-1' });
db.whatsappTemplate.findUnique.mockResolvedValueOnce(null);
expect(await provider.readiness(active, 'PAYMENT_REMINDER')).toBe('pending');
db.whatsappTemplate.findUnique.mockResolvedValueOnce({ status: 'APPROVED' });
expect(await provider.readiness(active, 'PAYMENT_REMINDER')).toBe('ready');
db.whatsappTemplate.findUnique.mockResolvedValueOnce({ status: 'REJECTED' });
expect(await provider.readiness(active, 'PAYMENT_REMINDER')).toBe('blocked');
expect(await provider.readiness(kapsoAccount(), 'PAYMENT_REMINDER')).toBe('blocked');
});
it('sends the approved template with named parameters', async () => {
const { fn, calls } = fakeFetch([
{
method: 'POST',
path: '/meta/whatsapp/v24.0/phone-1/messages',
body: { messaging_product: 'whatsapp', messages: [{ id: 'wamid.ABC' }] },
},
]);
const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn });
const outcome = await provider.send(
kapsoAccount({ status: 'ACTIVE', externalId: 'phone-1' }),
'5491123456789',
{
kind: 'PAYMENT_REMINDER',
studentName: 'Ana López',
groupName: 'Yoga',
amount: '$ 25.000',
dueDate: '20/10',
paymentLink: 'https://mpago.la/x',
},
'msg-1',
);
expect(outcome).toEqual({ ok: true, providerMessageId: 'wamid.ABC' });
expect(calls[0]?.body).toMatchObject({
to: '5491123456789',
type: 'template',
template: {
name: 'gruperly_payment_reminder',
language: { code: 'es_AR' },
components: [
{
type: 'body',
parameters: expect.arrayContaining([
{ type: 'text', parameter_name: 'student_name', text: 'Ana' },
{ type: 'text', parameter_name: 'payment_link', text: 'https://mpago.la/x' },
]),
},
],
},
});
});
it('does not retry a marketing opt-out', async () => {
const { fn } = fakeFetch([
{
method: 'POST',
path: '/meta/whatsapp/v24.0/phone-1/messages',
status: 422,
body: { error: { code: 'marketing_preference_stopped' } },
},
]);
const outcome = await new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn }).send(
kapsoAccount({ status: 'ACTIVE', externalId: 'phone-1' }),
'5491123456789',
{ kind: 'REENGAGEMENT', studentName: 'Ana', groupName: 'Yoga' },
'msg-1',
);
expect(outcome).toMatchObject({ ok: false, retryable: false, code: 'marketing_preference_stopped' });
});
it('verifies the webhook and normalizes number and message events', () => {
const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never });
const created = JSON.stringify({
phone_number_id: 'phone-1',
business_account_id: 'waba-1',
display_phone_number: '+54 9 11 2345 6789',
customer: { id: 'cust-1', external_id: 'user-1' },
});
const headers = new Headers({
'X-Webhook-Signature': sign(created, kapsoConfig.webhookSecret),
'X-Webhook-Event': 'whatsapp.phone_number.created',
'X-Idempotency-Key': 'idem-1',
});
expect(provider.parseWebhook(created, headers)).toEqual({
ok: true,
value: {
dedupeKey: 'idem-1',
events: [
{
type: 'connection',
externalId: 'phone-1',
ownerId: 'user-1',
status: 'active',
displayPhoneNumber: '+5491123456789',
providerData: { businessAccountId: 'waba-1' },
},
],
},
});
const failed = JSON.stringify({
phone_number_id: 'phone-1',
message: {
id: 'wamid.ABC',
kapso: { status: 'failed', statuses: [{ status: 'failed', errors: [{ code: 131026, title: 'Undeliverable' }] }] },
},
});
const failedHeaders = new Headers({
'X-Webhook-Signature': sign(failed, kapsoConfig.webhookSecret),
'X-Webhook-Event': 'whatsapp.message.failed',
'X-Idempotency-Key': 'idem-2',
});
expect(provider.parseWebhook(failed, failedHeaders)).toEqual({
ok: true,
value: {
dedupeKey: 'idem-2',
events: [
{
type: 'message_status',
providerMessageId: 'wamid.ABC',
status: 'FAILED',
errorCode: '131026',
errorMessage: 'Undeliverable',
},
],
},
});
expect(
provider.parseWebhook(created, new Headers({ 'X-Webhook-Signature': 'deadbeef', 'X-Idempotency-Key': 'x' })),
).toEqual({ ok: false, error: 'invalid_signature' });
});
});