feat(whatsapp): vincular con el número de teléfono además del QR

Desde el teléfono no se puede escanear el QR de la propia pantalla. Con
OpenWA el profesor ahora puede escribir su número y recibir un código de
8 caracteres para ingresar en WhatsApp (POST /whatsapp/connect/pairing-code).
En mobile el modal arranca por el número y en desktop por el QR.

- Puerto: requestPairingCode opcional (Kapso no lo implementa).
- OpenWA: reintenta el 409 mientras la sesión arranca.
- Número normalizado con el país del profesor (toWhatsappE164).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-22 19:15:02 -03:00
parent bef4056f8e
commit f4d2c26e29
23 changed files with 619 additions and 82 deletions

View File

@@ -3,6 +3,7 @@ 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';
@@ -73,6 +74,9 @@ function makeDb() {
findUnique: mock(),
update: mock(),
},
user: {
findUnique: mock(async () => ({ country: 'AR' })),
},
};
}
@@ -279,6 +283,67 @@ describe('status', () => {
});
});
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' }));

View File

@@ -262,6 +262,47 @@ describe('OpenWA provider', () => {
expect(openWaSessionName('cmh1x2y3z0000abcd')).toBe('gruperly-cmh1x2y3z0000abcd');
expect(openWaSessionName('weird_id.with@chars')).toBe('gruperly-weirdidwithchars');
});
it('asks OpenWA for a pairing code with the digits of the number', async () => {
const { fn, calls } = fakeFetch([
{
method: 'POST',
path: '/sessions/sess-1/pairing-code',
status: 201,
body: { pairingCode: 'ABCD1234', status: 'qr_ready' },
},
]);
const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
const result = await provider.requestPairingCode(openWaAccount({ status: 'PENDING' }), '5491123456789');
expect(result).toEqual({ ok: true, value: 'ABCD1234' });
expect(calls[0]?.body).toEqual({ phoneNumber: '5491123456789' });
});
it('waits while the session is not ready for a code, then gives up with 409', async () => {
let answered = 0;
const fn = mock(async () => {
answered += 1;
return answered < 3
? new Response(JSON.stringify({ statusCode: 409 }), { status: 409 })
: new Response(JSON.stringify({ pairingCode: 'WXYZ9876' }), { status: 201 });
});
const sleep = mock(async () => {});
const provider = new OpenWaProvider(openWaConfig, { fetch: fn, sleep });
const result = await provider.requestPairingCode(openWaAccount({ status: 'PENDING' }), '5491123456789');
expect(result).toEqual({ ok: true, value: 'WXYZ9876' });
expect(sleep).toHaveBeenCalledTimes(2);
const busy = mock(async () => new Response(JSON.stringify({ statusCode: 409 }), { status: 409 }));
const stuck = new OpenWaProvider(openWaConfig, { fetch: busy, sleep });
const failed = await stuck.requestPairingCode(openWaAccount({ status: 'PENDING' }), '5491123456789');
expect(failed.ok).toBe(false);
if (!failed.ok) expect(failed.error.code).toBe('whatsapp_pairing_not_ready');
});
});
const kapsoConfig = {