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:
@@ -139,6 +139,29 @@ export function whatsappNumberInUseProblem(): ProblemDetails {
|
||||
});
|
||||
}
|
||||
|
||||
export function whatsappLinkingNotStartedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Empezá la vinculación de WhatsApp antes de pedir el código.',
|
||||
code: 'whatsapp_linking_not_started',
|
||||
});
|
||||
}
|
||||
|
||||
/** The provider links by QR or redirect only (Kapso). */
|
||||
export function whatsappPairingUnsupportedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Este proveedor de WhatsApp no permite vincular con el número de teléfono.',
|
||||
code: 'whatsapp_pairing_unsupported',
|
||||
});
|
||||
}
|
||||
|
||||
/** The session is not ready to hand out a code yet; retryable in seconds. */
|
||||
export function whatsappPairingNotReadyProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'WhatsApp todavía está preparando la vinculación. Intentá de nuevo en unos segundos.',
|
||||
code: 'whatsapp_pairing_not_ready',
|
||||
});
|
||||
}
|
||||
|
||||
/** The WhatsApp gateway refused the request, or could not be reached. */
|
||||
export function whatsappProviderErrorProblem(): ProblemDetails {
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { WhatsappPairingCode } from '@gruperly/shared';
|
||||
import { WhatsappPairingCodeSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { RequestWhatsappPairingCode } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/', validate.json(WhatsappPairingCodeSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const { phoneNumber } = c.req.valid('json') as WhatsappPairingCode;
|
||||
|
||||
const useCase = new RequestWhatsappPairingCode();
|
||||
const result = await useCase.execute(user.id, phoneNumber);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result, WhatsappPairingCodeDto } from '@gruperly/shared';
|
||||
import { countryCodeSchema, err, ok, toWhatsappE164 } from '@gruperly/shared';
|
||||
import {
|
||||
validationProblem,
|
||||
whatsappLinkingNotStartedProblem,
|
||||
whatsappPairingUnsupportedProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { getMessagingProvider } from '../../providers';
|
||||
import type { MessagingProvider } from '../../providers/messaging-provider';
|
||||
|
||||
type RequestWhatsappPairingCodeDeps = {
|
||||
db?: Pick<PrismaClient, 'whatsappAccount' | 'user'>;
|
||||
provider?: MessagingProvider;
|
||||
};
|
||||
|
||||
/**
|
||||
* Links the teacher's WhatsApp by phone number instead of QR: WhatsApp shows a
|
||||
* prompt on that phone and the teacher types the code we return. It is what
|
||||
* makes linking possible from the phone the app is running on.
|
||||
*
|
||||
* The linking must have been started with `POST /whatsapp/connect` (the account
|
||||
* is PENDING with a live session); the code completes that same linking, so the
|
||||
* status polling and the webhook finish it as with a QR.
|
||||
*/
|
||||
export class RequestWhatsappPairingCode {
|
||||
constructor(private readonly deps: RequestWhatsappPairingCodeDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
ownerId: string,
|
||||
phoneNumber: string,
|
||||
): Promise<Result<WhatsappPairingCodeDto, ProblemDetails>> {
|
||||
const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider();
|
||||
if (!providerResult.ok) return providerResult;
|
||||
const provider = providerResult.value;
|
||||
if (!provider.requestPairingCode) return err(whatsappPairingUnsupportedProblem());
|
||||
|
||||
const db = this.deps.db ?? prisma;
|
||||
const account = await db.whatsappAccount.findUnique({ where: { ownerId } });
|
||||
if (!account || account.provider !== provider.id || account.status !== 'PENDING') {
|
||||
return err(whatsappLinkingNotStartedProblem());
|
||||
}
|
||||
|
||||
// Typed the way people write their own number (`11 2345-6789`): the
|
||||
// teacher's country settles the calling code, as for the attendees.
|
||||
const owner = await db.user.findUnique({ where: { id: ownerId }, select: { country: true } });
|
||||
const country = countryCodeSchema.safeParse(owner?.country);
|
||||
const e164 = toWhatsappE164(phoneNumber, country.success ? country.data : null);
|
||||
if (!e164) {
|
||||
return err(
|
||||
validationProblem({
|
||||
detail: 'Revisá el número: escribilo con el código de área.',
|
||||
errors: { phoneNumber: ['Número inválido'] },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const code = await provider.requestPairingCode(account, e164.slice(1));
|
||||
if (!code.ok) return code;
|
||||
return ok({ pairingCode: code.value });
|
||||
}
|
||||
}
|
||||
@@ -129,6 +129,17 @@ export interface MessagingProvider {
|
||||
account: WhatsappAccountRecord,
|
||||
): Promise<Result<ConnectionSnapshot, ProblemDetails>>;
|
||||
|
||||
/**
|
||||
* Asks for a code to link by phone number instead of scanning the QR, for a
|
||||
* linking already started with `startConnection`. `phoneDigits` is the
|
||||
* teacher's number in international format, digits only. Only providers that
|
||||
* link a WhatsApp Web session (OpenWA) implement it.
|
||||
*/
|
||||
requestPairingCode?(
|
||||
account: WhatsappAccountRecord,
|
||||
phoneDigits: string,
|
||||
): Promise<Result<string, ProblemDetails>>;
|
||||
|
||||
/**
|
||||
* Finishes a redirect-based linking from the callback query. Only providers
|
||||
* whose `startConnection` answers `redirect` implement it.
|
||||
|
||||
@@ -83,6 +83,15 @@ export class OpenWaClient {
|
||||
return response.qrCode ?? null;
|
||||
}
|
||||
|
||||
requestPairingCode(
|
||||
sessionId: string,
|
||||
phoneNumber: string,
|
||||
): Promise<{ pairingCode: string; status?: string }> {
|
||||
return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/pairing-code`, {
|
||||
phoneNumber,
|
||||
});
|
||||
}
|
||||
|
||||
createWebhook(
|
||||
sessionId: string,
|
||||
body: { url: string; events: string[]; secret: string; retryCount: number },
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { ProblemDetails, Result, WhatsappReadiness } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { whatsappProviderErrorProblem } from '@/http/problem-builders';
|
||||
import { whatsappPairingNotReadyProblem, whatsappProviderErrorProblem } from '@/http/problem-builders';
|
||||
import { logger } from '@/logger';
|
||||
import { sleep } from '../../lib/dispatch';
|
||||
import { verifyHmacSha256 } from '../../lib/hmac';
|
||||
import { renderMessage } from '../../lib/render-message';
|
||||
import type {
|
||||
@@ -34,6 +35,14 @@ const WEBHOOK_RETRY_COUNT = 3;
|
||||
/** The global throttler's 429 carries no `retryAfterSeconds`; it clears in seconds. */
|
||||
const DEFAULT_RATE_LIMIT_MS = 60_000;
|
||||
|
||||
/**
|
||||
* Right after `start` the session is still `initializing` and OpenWA answers a
|
||||
* pairing-code request with 409 until it reads `qr_ready` (on Baileys also for
|
||||
* up to 30 s while a socket closes). Retried here so the teacher's click works.
|
||||
*/
|
||||
const PAIRING_ATTEMPTS = 6;
|
||||
const PAIRING_RETRY_MS = 2_000;
|
||||
|
||||
const PENDING_STATUSES = new Set(['created', 'initializing', 'qr_ready', 'authenticating']);
|
||||
|
||||
/** One OpenWA session per teacher. Names allow letters, digits and hyphens (3-50). */
|
||||
@@ -41,7 +50,7 @@ export function openWaSessionName(ownerId: string): string {
|
||||
return `gruperly-${ownerId.replace(/[^a-zA-Z0-9-]/g, '')}`.slice(0, 50);
|
||||
}
|
||||
|
||||
type OpenWaProviderDeps = { fetch?: OpenWaFetch };
|
||||
type OpenWaProviderDeps = { fetch?: OpenWaFetch; sleep?: (ms: number) => Promise<void> };
|
||||
|
||||
/**
|
||||
* OpenWA (self-hosted, unofficial WhatsApp Web gateway) for the MVP.
|
||||
@@ -54,12 +63,14 @@ type OpenWaProviderDeps = { fetch?: OpenWaFetch };
|
||||
export class OpenWaProvider implements MessagingProvider {
|
||||
readonly id = 'OPENWA' as const;
|
||||
private readonly client: OpenWaClient;
|
||||
private readonly sleep: (ms: number) => Promise<void>;
|
||||
|
||||
constructor(
|
||||
private readonly config: OpenWaConfig,
|
||||
deps: OpenWaProviderDeps = {},
|
||||
) {
|
||||
this.client = new OpenWaClient(config, deps.fetch);
|
||||
this.sleep = deps.sleep ?? sleep;
|
||||
}
|
||||
|
||||
async startConnection(
|
||||
@@ -138,6 +149,29 @@ export class OpenWaProvider implements MessagingProvider {
|
||||
}
|
||||
}
|
||||
|
||||
async requestPairingCode(
|
||||
account: WhatsappAccountRecord,
|
||||
phoneDigits: string,
|
||||
): Promise<Result<string, ProblemDetails>> {
|
||||
if (!account.externalId) return err(whatsappProviderErrorProblem());
|
||||
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try {
|
||||
const response = await this.client.requestPairingCode(account.externalId, phoneDigits);
|
||||
return ok(response.pairingCode);
|
||||
} catch (error) {
|
||||
const notReady = error instanceof OpenWaApiError && error.status === 409;
|
||||
if (notReady && attempt < PAIRING_ATTEMPTS) {
|
||||
await this.sleep(PAIRING_RETRY_MS);
|
||||
continue;
|
||||
}
|
||||
if (notReady) return err(whatsappPairingNotReadyProblem());
|
||||
logger.warn({ err: describe(error) }, 'OpenWA pairing code request failed');
|
||||
return err(whatsappProviderErrorProblem());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async disconnect(account: WhatsappAccountRecord): Promise<Result<void, ProblemDetails>> {
|
||||
if (!account.externalId) return ok(undefined);
|
||||
const sessionId = account.externalId;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Hono } from 'hono';
|
||||
import callbackRoute from './features/callback/route';
|
||||
import connectRoute from './features/connect/route';
|
||||
import disconnectRoute from './features/disconnect/route';
|
||||
import pairingCodeRoute from './features/pairing-code/route';
|
||||
import statusRoute from './features/status/route';
|
||||
import webhookRoute from './features/webhook/route';
|
||||
|
||||
@@ -11,6 +12,7 @@ const routes = new Hono();
|
||||
// it on `/connect` gives the RESTful `DELETE /whatsapp/connect`.
|
||||
routes.route('/connect', connectRoute);
|
||||
routes.route('/connect', disconnectRoute);
|
||||
routes.route('/connect/pairing-code', pairingCodeRoute);
|
||||
routes.route('/status', statusRoute);
|
||||
routes.route('/callback', callbackRoute);
|
||||
routes.route('/webhooks', webhookRoute);
|
||||
|
||||
@@ -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' }));
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
linksWithQr,
|
||||
useStartWhatsappConnection,
|
||||
useWhatsappStatus,
|
||||
WhatsappQrModal,
|
||||
WhatsappLinkModal,
|
||||
whatsappCallbackErrorMessage,
|
||||
whatsappStatusBadgeVariant,
|
||||
whatsappStatusErrorMessage,
|
||||
@@ -80,7 +80,7 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {
|
||||
) : (
|
||||
<p className="text-sm text-foreground/60">
|
||||
{usesQr
|
||||
? 'Vas a escanear un código QR desde WhatsApp, como cuando usás WhatsApp Web.'
|
||||
? 'Lo vinculás con tu número de teléfono o escaneando un código QR, como WhatsApp Web.'
|
||||
: 'Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.'}{' '}
|
||||
Los envíos automáticos los prendés después en cada grupo.
|
||||
</p>
|
||||
@@ -110,7 +110,7 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {
|
||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{connection.error}</p>
|
||||
) : null}
|
||||
|
||||
<WhatsappQrModal
|
||||
<WhatsappLinkModal
|
||||
isOpen={connection.isQrOpen}
|
||||
onClose={connection.closeQr}
|
||||
initialQrCode={connection.initialQrCode}
|
||||
|
||||
127
apps/web/src/features/whatsapp/WhatsappLinkModal.tsx
Normal file
127
apps/web/src/features/whatsapp/WhatsappLinkModal.tsx
Normal file
@@ -0,0 +1,127 @@
|
||||
import { Loader2, QrCode, Smartphone } from 'lucide-react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Modal, useToast } from '../../components/ui'
|
||||
import { useIsMobile } from '../../hooks/useIsMobile'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { defaultLinkMethod, linksWithPairingCode, type WhatsappLinkMethod } from './copy'
|
||||
import { useWhatsappStatus } from './useWhatsappStatus'
|
||||
import { WhatsappPairingCodePanel } from './WhatsappPairingCodePanel'
|
||||
|
||||
type WhatsappLinkModalProps = {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
/** QR de la respuesta de `connect`; se reemplaza por el del estado apenas llega. */
|
||||
initialQrCode: string | null
|
||||
}
|
||||
|
||||
const METHOD_LABELS: Record<WhatsappLinkMethod, string> = {
|
||||
phone: 'Con tu número',
|
||||
qr: 'Con código QR',
|
||||
}
|
||||
|
||||
/**
|
||||
* Vinculación de WhatsApp como "dispositivo vinculado", por QR o con el número
|
||||
* de teléfono. En el teléfono arranca por el número (no se puede escanear la
|
||||
* propia pantalla) y en desktop por el QR; las dos opciones quedan a mano.
|
||||
*
|
||||
* El estado se consulta cada 2 s mientras está pendiente: el QR se renueva y el
|
||||
* modal se cierra solo al vincularse, sea cual sea el método.
|
||||
*/
|
||||
export function WhatsappLinkModal({ isOpen, onClose, initialQrCode }: WhatsappLinkModalProps) {
|
||||
const toast = useToast()
|
||||
const isMobile = useIsMobile()
|
||||
const statusQuery = useWhatsappStatus({ enabled: isOpen })
|
||||
const status = statusQuery.data?.status
|
||||
const qrCode = statusQuery.data?.qrCode ?? initialQrCode
|
||||
const canUsePhone = statusQuery.data ? linksWithPairingCode(statusQuery.data.provider) : true
|
||||
const [method, setMethod] = useState<WhatsappLinkMethod>(() => defaultLinkMethod(isMobile))
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) setMethod(defaultLinkMethod(isMobile))
|
||||
}, [isOpen, isMobile])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
if (status === 'active') {
|
||||
toast.success('¡Listo! Tu WhatsApp quedó vinculado.')
|
||||
onClose()
|
||||
} else if (status === 'disconnected') {
|
||||
toast.error('La vinculación no se completó. Volvé a intentarlo.')
|
||||
onClose()
|
||||
}
|
||||
}, [isOpen, status, onClose, toast])
|
||||
|
||||
const activeMethod = canUsePhone ? method : 'qr'
|
||||
const methods: WhatsappLinkMethod[] = isMobile ? ['phone', 'qr'] : ['qr', 'phone']
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title="Vinculá tu WhatsApp"
|
||||
description={
|
||||
activeMethod === 'phone'
|
||||
? 'Te damos un código para ingresar en WhatsApp, en el teléfono donde lo usás.'
|
||||
: 'Escaneá el código con el teléfono donde usás WhatsApp.'
|
||||
}
|
||||
maxWidth="sm"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{canUsePhone ? (
|
||||
<div className="grid grid-cols-2 gap-1 rounded-xl bg-primary-soft p-1" role="tablist">
|
||||
{methods.map((option) => (
|
||||
<button
|
||||
key={option}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeMethod === option}
|
||||
onClick={() => setMethod(option)}
|
||||
className={cn(
|
||||
'flex items-center justify-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors',
|
||||
activeMethod === option
|
||||
? 'bg-surface text-primary shadow-sm'
|
||||
: 'text-foreground/60 hover:text-primary',
|
||||
)}
|
||||
>
|
||||
{option === 'phone' ? (
|
||||
<Smartphone className="size-4" />
|
||||
) : (
|
||||
<QrCode className="size-4" />
|
||||
)}
|
||||
{METHOD_LABELS[option]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{activeMethod === 'phone' ? (
|
||||
<WhatsappPairingCodePanel />
|
||||
) : (
|
||||
<>
|
||||
<div className="mx-auto flex size-64 items-center justify-center rounded-xl border border-border bg-white p-2">
|
||||
{qrCode ? (
|
||||
<img src={qrCode} alt="Código QR para vincular WhatsApp" className="size-full" />
|
||||
) : (
|
||||
<Loader2 className="size-8 animate-spin text-foreground/40" />
|
||||
)}
|
||||
</div>
|
||||
<ol className="space-y-1.5 text-sm text-foreground/70">
|
||||
<li>1. Abrí WhatsApp en tu teléfono.</li>
|
||||
<li>
|
||||
2. Tocá <span className="font-medium text-primary">Dispositivos vinculados</span> y
|
||||
después <span className="font-medium text-primary">Vincular un dispositivo</span>.
|
||||
</li>
|
||||
<li>3. Apuntá la cámara a este código.</li>
|
||||
</ol>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="flex items-start gap-2 rounded-xl bg-primary-soft px-3 py-2 text-xs text-foreground/70">
|
||||
<Smartphone className="mt-0.5 size-4 shrink-0 text-accent" />
|
||||
Los mensajes van a salir desde tu número. Podés desvincularlo cuando quieras desde
|
||||
Ajustes o desde tu teléfono.
|
||||
</p>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
106
apps/web/src/features/whatsapp/WhatsappPairingCodePanel.tsx
Normal file
106
apps/web/src/features/whatsapp/WhatsappPairingCodePanel.tsx
Normal file
@@ -0,0 +1,106 @@
|
||||
import { Check, Copy, KeyRound, Loader2 } from 'lucide-react'
|
||||
import { type FormEvent, useState } from 'react'
|
||||
import { Button, Input, Label } from '../../components/ui'
|
||||
import { formatPairingCode } from './copy'
|
||||
import { useRequestWhatsappPairingCode } from './useRequestWhatsappPairingCode'
|
||||
|
||||
/**
|
||||
* Vinculación con el número de teléfono: el profesor escribe su número,
|
||||
* WhatsApp le avisa en ese teléfono y ahí ingresa el código que mostramos. Es
|
||||
* la forma de vincular desde el mismo teléfono en el que usa Gruperly.
|
||||
*/
|
||||
export function WhatsappPairingCodePanel() {
|
||||
const { requestCode, pairingCode, isRequesting, error, reset } = useRequestWhatsappPairingCode()
|
||||
const [phoneNumber, setPhoneNumber] = useState('')
|
||||
const [copied, setCopied] = useState(false)
|
||||
|
||||
const handleSubmit = (event: FormEvent) => {
|
||||
event.preventDefault()
|
||||
if (phoneNumber.trim()) requestCode(phoneNumber)
|
||||
}
|
||||
|
||||
const handleCopy = async (code: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(code)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
} catch {
|
||||
// Sin permiso de portapapeles: el código igual está a la vista.
|
||||
}
|
||||
}
|
||||
|
||||
if (pairingCode) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-center gap-2 rounded-xl border border-border bg-primary-soft/50 px-4 py-5">
|
||||
<p className="select-all font-mono text-3xl font-bold tracking-widest text-primary">
|
||||
{formatPairingCode(pairingCode)}
|
||||
</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label="Copiar código"
|
||||
onClick={() => void handleCopy(pairingCode)}
|
||||
>
|
||||
{copied ? <Check className="size-4 text-success" /> : <Copy className="size-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
<ol className="space-y-1.5 text-sm text-foreground/70">
|
||||
<li>
|
||||
1. Abrí WhatsApp. Te va a llegar una notificación para vincular un dispositivo:
|
||||
tocala.
|
||||
</li>
|
||||
<li>
|
||||
2. Si no te llega, tocá <span className="font-medium text-primary">Dispositivos vinculados</span>{' '}
|
||||
→ <span className="font-medium text-primary">Vincular un dispositivo</span> →{' '}
|
||||
<span className="font-medium text-primary">Vincular con el número de teléfono</span>.
|
||||
</li>
|
||||
<li>3. Ingresá este código. Esta pantalla se actualiza sola.</li>
|
||||
</ol>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<p className="flex items-center gap-2 text-xs text-foreground/50">
|
||||
<Loader2 className="size-3.5 animate-spin" />
|
||||
Esperando el código…
|
||||
</p>
|
||||
<Button variant="ghost" size="sm" onClick={reset}>
|
||||
Usar otro número
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="space-y-3" onSubmit={handleSubmit}>
|
||||
<div>
|
||||
<Label htmlFor="whatsapp-pairing-phone">Tu número de WhatsApp</Label>
|
||||
<Input
|
||||
id="whatsapp-pairing-phone"
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
autoComplete="tel"
|
||||
autoFocus
|
||||
placeholder="11 2345-6789"
|
||||
value={phoneNumber}
|
||||
invalid={Boolean(error)}
|
||||
onChange={(event) => setPhoneNumber(event.target.value)}
|
||||
/>
|
||||
<p className="mt-1 text-xs text-foreground/50">
|
||||
El del teléfono donde usás WhatsApp, con el código de área.
|
||||
</p>
|
||||
</div>
|
||||
{error ? (
|
||||
<p className="rounded-xl bg-danger-soft px-3 py-2 text-sm text-danger">{error}</p>
|
||||
) : null}
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
className="w-full"
|
||||
disabled={isRequesting || !phoneNumber.trim()}
|
||||
>
|
||||
{isRequesting ? <Loader2 className="size-4 animate-spin" /> : <KeyRound className="size-4" />}
|
||||
{isRequesting ? 'Pidiendo código…' : 'Obtener código'}
|
||||
</Button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import { Loader2, Smartphone } from 'lucide-react'
|
||||
import { useEffect } from 'react'
|
||||
import { Modal, useToast } from '../../components/ui'
|
||||
import { useWhatsappStatus } from './useWhatsappStatus'
|
||||
|
||||
type WhatsappQrModalProps = {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
/** QR de la respuesta de `connect`; se reemplaza por el del estado apenas llega. */
|
||||
initialQrCode: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Vinculación por QR: el profesor lo escanea desde su teléfono como un
|
||||
* "dispositivo vinculado". El estado se consulta cada 2 s mientras está
|
||||
* pendiente, así que el QR se renueva y el modal se cierra solo al vincularse.
|
||||
*/
|
||||
export function WhatsappQrModal({ isOpen, onClose, initialQrCode }: WhatsappQrModalProps) {
|
||||
const toast = useToast()
|
||||
const statusQuery = useWhatsappStatus({ enabled: isOpen })
|
||||
const status = statusQuery.data?.status
|
||||
const qrCode = statusQuery.data?.qrCode ?? initialQrCode
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
if (status === 'active') {
|
||||
toast.success('¡Listo! Tu WhatsApp quedó vinculado.')
|
||||
onClose()
|
||||
} else if (status === 'disconnected') {
|
||||
toast.error('La vinculación no se completó. Volvé a intentarlo.')
|
||||
onClose()
|
||||
}
|
||||
}, [isOpen, status, onClose, toast])
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title="Vinculá tu WhatsApp"
|
||||
description="Escaneá el código con el teléfono donde usás WhatsApp."
|
||||
maxWidth="sm"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<div className="mx-auto flex size-64 items-center justify-center rounded-xl border border-border bg-white p-2">
|
||||
{qrCode ? (
|
||||
<img src={qrCode} alt="Código QR para vincular WhatsApp" className="size-full" />
|
||||
) : (
|
||||
<Loader2 className="size-8 animate-spin text-foreground/40" />
|
||||
)}
|
||||
</div>
|
||||
<ol className="space-y-1.5 text-sm text-foreground/70">
|
||||
<li>1. Abrí WhatsApp en tu teléfono.</li>
|
||||
<li>
|
||||
2. Tocá <span className="font-medium text-primary">Dispositivos vinculados</span> y
|
||||
después <span className="font-medium text-primary">Vincular un dispositivo</span>.
|
||||
</li>
|
||||
<li>3. Apuntá la cámara a este código.</li>
|
||||
</ol>
|
||||
<p className="flex items-start gap-2 rounded-xl bg-primary-soft px-3 py-2 text-xs text-foreground/70">
|
||||
<Smartphone className="mt-0.5 size-4 shrink-0 text-accent" />
|
||||
Los mensajes van a salir desde tu número. Podés desvincularlo cuando quieras desde
|
||||
Ajustes o desde tu teléfono.
|
||||
</p>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
import { useDisconnectWhatsapp } from './useDisconnectWhatsapp'
|
||||
import { useStartWhatsappConnection } from './useStartWhatsappConnection'
|
||||
import { useWhatsappStatus } from './useWhatsappStatus'
|
||||
import { WhatsappQrModal } from './WhatsappQrModal'
|
||||
import { WhatsappLinkModal } from './WhatsappLinkModal'
|
||||
|
||||
/**
|
||||
* WhatsApp en Ajustes: vincular el número desde el que salen los recordatorios
|
||||
@@ -120,7 +120,7 @@ export function WhatsappStatusCard() {
|
||||
</p>
|
||||
<p className="text-xs text-foreground/50">
|
||||
{linksWithQr(data.provider)
|
||||
? 'Escaneás un código QR desde WhatsApp, como en WhatsApp Web.'
|
||||
? 'Lo vinculás con tu número o con un código QR, como WhatsApp Web.'
|
||||
: 'Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.'}
|
||||
</p>
|
||||
</div>
|
||||
@@ -145,7 +145,7 @@ export function WhatsappStatusCard() {
|
||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{connection.error}</p>
|
||||
) : null}
|
||||
|
||||
<WhatsappQrModal
|
||||
<WhatsappLinkModal
|
||||
isOpen={connection.isQrOpen}
|
||||
onClose={connection.closeQr}
|
||||
initialQrCode={connection.initialQrCode}
|
||||
|
||||
@@ -115,6 +115,28 @@ export function linksWithQr(provider: WhatsappProvider): boolean {
|
||||
return provider === 'OPENWA'
|
||||
}
|
||||
|
||||
/**
|
||||
* Si además del QR se puede vincular con el número de teléfono. Es lo que
|
||||
* permite vincular desde el mismo teléfono en el que se usa la app, donde no hay
|
||||
* cómo escanear el QR.
|
||||
*/
|
||||
export function linksWithPairingCode(provider: WhatsappProvider): boolean {
|
||||
return provider === 'OPENWA'
|
||||
}
|
||||
|
||||
export type WhatsappLinkMethod = 'phone' | 'qr'
|
||||
|
||||
/** En el teléfono no se puede escanear la propia pantalla: arranca por el número. */
|
||||
export function defaultLinkMethod(isMobile: boolean): WhatsappLinkMethod {
|
||||
return isMobile ? 'phone' : 'qr'
|
||||
}
|
||||
|
||||
/** El código como lo muestra WhatsApp: dos grupos de cuatro (`ABCD-1234`). */
|
||||
export function formatPairingCode(code: string): string {
|
||||
const clean = code.replace(/[^0-9A-Za-z]/g, '').toUpperCase()
|
||||
return clean.length === 8 ? `${clean.slice(0, 4)}-${clean.slice(4)}` : clean
|
||||
}
|
||||
|
||||
/**
|
||||
* Por qué un switch de automatización está deshabilitado, o null si se puede
|
||||
* usar. Se puede apagar siempre: lo que se bloquea es prenderla sin WhatsApp.
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
export {
|
||||
automationBlockedReason,
|
||||
defaultLinkMethod,
|
||||
formatPairingCode,
|
||||
linksWithPairingCode,
|
||||
linksWithQr,
|
||||
readinessLabel,
|
||||
readWhatsappCallbackFeedback,
|
||||
WEEKLY_SEND_LABEL,
|
||||
type WhatsappLinkMethod,
|
||||
type WhatsappCallbackFeedback,
|
||||
whatsappCallbackErrorMessage,
|
||||
whatsappStatusBadgeVariant,
|
||||
@@ -13,5 +17,5 @@ export {
|
||||
export { useDisconnectWhatsapp } from './useDisconnectWhatsapp'
|
||||
export { useStartWhatsappConnection } from './useStartWhatsappConnection'
|
||||
export { useWhatsappStatus, whatsappStatusQueryKey } from './useWhatsappStatus'
|
||||
export { WhatsappQrModal } from './WhatsappQrModal'
|
||||
export { WhatsappLinkModal } from './WhatsappLinkModal'
|
||||
export { WhatsappStatusCard } from './WhatsappStatusCard'
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { requestWhatsappPairingCode } from '../../lib/api'
|
||||
|
||||
/**
|
||||
* Pide el código para vincular con el número de teléfono. La vinculación ya
|
||||
* está empezada (`connect`): el código la completa igual que el QR, así que el
|
||||
* estado se sigue consultando y el modal se cierra solo al vincularse.
|
||||
*/
|
||||
export function useRequestWhatsappPairingCode() {
|
||||
const mutation = useMutation({ mutationFn: requestWhatsappPairingCode })
|
||||
|
||||
return {
|
||||
requestCode: (phoneNumber: string) => mutation.mutate(phoneNumber),
|
||||
pairingCode: mutation.data?.pairingCode ?? null,
|
||||
isRequesting: mutation.isPending,
|
||||
error: mutation.error ? mutation.error.message || 'No pudimos pedir el código.' : null,
|
||||
reset: mutation.reset,
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,7 @@ import type {
|
||||
WhatsappConnectResultDto,
|
||||
WhatsappDisconnectResultDto,
|
||||
WhatsappReturnTo,
|
||||
WhatsappPairingCodeDto,
|
||||
WhatsappStatusDto,
|
||||
} from '@gruperly/shared'
|
||||
|
||||
@@ -138,6 +139,12 @@ export const startWhatsappConnection = (returnTo: WhatsappReturnTo) =>
|
||||
body: JSON.stringify({ returnTo }),
|
||||
})
|
||||
|
||||
export const requestWhatsappPairingCode = (phoneNumber: string) =>
|
||||
apiFetch<WhatsappPairingCodeDto>('/api/v1/whatsapp/connect/pairing-code', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ phoneNumber }),
|
||||
})
|
||||
|
||||
export const getWhatsappStatus = () => apiFetch<WhatsappStatusDto>('/api/v1/whatsapp/status')
|
||||
|
||||
export const disconnectWhatsapp = () =>
|
||||
|
||||
@@ -2,6 +2,9 @@ import type { WhatsappStatusDto } from '@gruperly/shared'
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import {
|
||||
automationBlockedReason,
|
||||
defaultLinkMethod,
|
||||
formatPairingCode,
|
||||
linksWithPairingCode,
|
||||
linksWithQr,
|
||||
readinessLabel,
|
||||
readWhatsappCallbackFeedback,
|
||||
@@ -90,3 +93,21 @@ describe('whatsappStatusErrorMessage', () => {
|
||||
expect(whatsappStatusErrorMessage(null)).not.toContain('error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('vinculación con el número', () => {
|
||||
test('solo OpenWA ofrece el código', () => {
|
||||
expect(linksWithPairingCode('OPENWA')).toBe(true)
|
||||
expect(linksWithPairingCode('KAPSO')).toBe(false)
|
||||
})
|
||||
|
||||
test('en el teléfono arranca por el número; en desktop, por el QR', () => {
|
||||
expect(defaultLinkMethod(true)).toBe('phone')
|
||||
expect(defaultLinkMethod(false)).toBe('qr')
|
||||
})
|
||||
|
||||
test('muestra el código en dos grupos de cuatro', () => {
|
||||
expect(formatPairingCode('abcd1234')).toBe('ABCD-1234')
|
||||
expect(formatPairingCode('ABCD-1234')).toBe('ABCD-1234')
|
||||
expect(formatPairingCode('XYZ')).toBe('XYZ')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user