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:
@@ -42,7 +42,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
||||||
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
||||||
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). No hay webhook: la reconciliación es por polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
|
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). No hay webhook: la reconciliación es por polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
|
||||||
- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
|
- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
|
||||||
1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`.
|
1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`.
|
||||||
2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.
|
2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.
|
||||||
3. El callback de Kapso no confía en la query: exige el `setupLinkId` guardado y que Kapso confirme que el número es del customer del profesor.
|
3. El callback de Kapso no confía en la query: exige el `setupLinkId` guardado y que Kapso confirme que el número es del customer del profesor.
|
||||||
|
|||||||
@@ -157,7 +157,7 @@ Las dos se prenden por grupo (ficha del grupo → "Mensajes automáticos por Wha
|
|||||||
|
|
||||||
El envío pasa por un proveedor intercambiable (`WHATSAPP_PROVIDER`):
|
El envío pasa por un proveedor intercambiable (`WHATSAPP_PROVIDER`):
|
||||||
|
|
||||||
- **`openwa`** (MVP, default): gateway self-hosted. El profesor escanea un QR y los mensajes son texto libre. No es oficial y hay riesgo de bloqueo del número.
|
- **`openwa`** (MVP, default): gateway self-hosted. El profesor lo vincula escaneando un QR o, desde el teléfono, con un código para su número; los mensajes son texto libre. No es oficial y hay riesgo de bloqueo del número.
|
||||||
- **`kapso`**: API oficial de Meta. La vinculación es un setup link y los mensajes usan templates aprobados.
|
- **`kapso`**: API oficial de Meta. La vinculación es un setup link y los mensajes usan templates aprobados.
|
||||||
|
|
||||||
El código vive en `apps/backend/src/modules/whatsapp/`.
|
El código vive en `apps/backend/src/modules/whatsapp/`.
|
||||||
|
|||||||
@@ -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. */
|
/** The WhatsApp gateway refused the request, or could not be reached. */
|
||||||
export function whatsappProviderErrorProblem(): ProblemDetails {
|
export function whatsappProviderErrorProblem(): ProblemDetails {
|
||||||
return {
|
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,
|
account: WhatsappAccountRecord,
|
||||||
): Promise<Result<ConnectionSnapshot, ProblemDetails>>;
|
): 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
|
* Finishes a redirect-based linking from the callback query. Only providers
|
||||||
* whose `startConnection` answers `redirect` implement it.
|
* whose `startConnection` answers `redirect` implement it.
|
||||||
|
|||||||
@@ -83,6 +83,15 @@ export class OpenWaClient {
|
|||||||
return response.qrCode ?? null;
|
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(
|
createWebhook(
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
body: { url: string; events: string[]; secret: string; retryCount: number },
|
body: { url: string; events: string[]; secret: string; retryCount: number },
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import type { ProblemDetails, Result, WhatsappReadiness } from '@gruperly/shared';
|
import type { ProblemDetails, Result, WhatsappReadiness } from '@gruperly/shared';
|
||||||
import { err, ok } 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 { logger } from '@/logger';
|
||||||
|
import { sleep } from '../../lib/dispatch';
|
||||||
import { verifyHmacSha256 } from '../../lib/hmac';
|
import { verifyHmacSha256 } from '../../lib/hmac';
|
||||||
import { renderMessage } from '../../lib/render-message';
|
import { renderMessage } from '../../lib/render-message';
|
||||||
import type {
|
import type {
|
||||||
@@ -34,6 +35,14 @@ const WEBHOOK_RETRY_COUNT = 3;
|
|||||||
/** The global throttler's 429 carries no `retryAfterSeconds`; it clears in seconds. */
|
/** The global throttler's 429 carries no `retryAfterSeconds`; it clears in seconds. */
|
||||||
const DEFAULT_RATE_LIMIT_MS = 60_000;
|
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']);
|
const PENDING_STATUSES = new Set(['created', 'initializing', 'qr_ready', 'authenticating']);
|
||||||
|
|
||||||
/** One OpenWA session per teacher. Names allow letters, digits and hyphens (3-50). */
|
/** 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);
|
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.
|
* OpenWA (self-hosted, unofficial WhatsApp Web gateway) for the MVP.
|
||||||
@@ -54,12 +63,14 @@ type OpenWaProviderDeps = { fetch?: OpenWaFetch };
|
|||||||
export class OpenWaProvider implements MessagingProvider {
|
export class OpenWaProvider implements MessagingProvider {
|
||||||
readonly id = 'OPENWA' as const;
|
readonly id = 'OPENWA' as const;
|
||||||
private readonly client: OpenWaClient;
|
private readonly client: OpenWaClient;
|
||||||
|
private readonly sleep: (ms: number) => Promise<void>;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly config: OpenWaConfig,
|
private readonly config: OpenWaConfig,
|
||||||
deps: OpenWaProviderDeps = {},
|
deps: OpenWaProviderDeps = {},
|
||||||
) {
|
) {
|
||||||
this.client = new OpenWaClient(config, deps.fetch);
|
this.client = new OpenWaClient(config, deps.fetch);
|
||||||
|
this.sleep = deps.sleep ?? sleep;
|
||||||
}
|
}
|
||||||
|
|
||||||
async startConnection(
|
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>> {
|
async disconnect(account: WhatsappAccountRecord): Promise<Result<void, ProblemDetails>> {
|
||||||
if (!account.externalId) return ok(undefined);
|
if (!account.externalId) return ok(undefined);
|
||||||
const sessionId = account.externalId;
|
const sessionId = account.externalId;
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Hono } from 'hono';
|
|||||||
import callbackRoute from './features/callback/route';
|
import callbackRoute from './features/callback/route';
|
||||||
import connectRoute from './features/connect/route';
|
import connectRoute from './features/connect/route';
|
||||||
import disconnectRoute from './features/disconnect/route';
|
import disconnectRoute from './features/disconnect/route';
|
||||||
|
import pairingCodeRoute from './features/pairing-code/route';
|
||||||
import statusRoute from './features/status/route';
|
import statusRoute from './features/status/route';
|
||||||
import webhookRoute from './features/webhook/route';
|
import webhookRoute from './features/webhook/route';
|
||||||
|
|
||||||
@@ -11,6 +12,7 @@ const routes = new Hono();
|
|||||||
// it on `/connect` gives the RESTful `DELETE /whatsapp/connect`.
|
// it on `/connect` gives the RESTful `DELETE /whatsapp/connect`.
|
||||||
routes.route('/connect', connectRoute);
|
routes.route('/connect', connectRoute);
|
||||||
routes.route('/connect', disconnectRoute);
|
routes.route('/connect', disconnectRoute);
|
||||||
|
routes.route('/connect/pairing-code', pairingCodeRoute);
|
||||||
routes.route('/status', statusRoute);
|
routes.route('/status', statusRoute);
|
||||||
routes.route('/callback', callbackRoute);
|
routes.route('/callback', callbackRoute);
|
||||||
routes.route('/webhooks', webhookRoute);
|
routes.route('/webhooks', webhookRoute);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { ok } from '@gruperly/shared';
|
|||||||
import { CompleteWhatsappSetup } from '@/modules/whatsapp/features/callback/use-case';
|
import { CompleteWhatsappSetup } from '@/modules/whatsapp/features/callback/use-case';
|
||||||
import { StartWhatsappConnection } from '@/modules/whatsapp/features/connect/use-case';
|
import { StartWhatsappConnection } from '@/modules/whatsapp/features/connect/use-case';
|
||||||
import { DisconnectWhatsapp } from '@/modules/whatsapp/features/disconnect/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 { GetWhatsappStatus } from '@/modules/whatsapp/features/status/use-case';
|
||||||
import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case';
|
import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case';
|
||||||
import { HandleWhatsappWebhook } from '@/modules/whatsapp/features/webhook/use-case';
|
import { HandleWhatsappWebhook } from '@/modules/whatsapp/features/webhook/use-case';
|
||||||
@@ -73,6 +74,9 @@ function makeDb() {
|
|||||||
findUnique: mock(),
|
findUnique: mock(),
|
||||||
update: 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', () => {
|
describe('disconnect', () => {
|
||||||
it('unlinks on the provider and frees the number locally', async () => {
|
it('unlinks on the provider and frees the number locally', async () => {
|
||||||
db.whatsappAccount.findUnique.mockResolvedValue(account({ status: 'ACTIVE' }));
|
db.whatsappAccount.findUnique.mockResolvedValue(account({ status: 'ACTIVE' }));
|
||||||
|
|||||||
@@ -262,6 +262,47 @@ describe('OpenWA provider', () => {
|
|||||||
expect(openWaSessionName('cmh1x2y3z0000abcd')).toBe('gruperly-cmh1x2y3z0000abcd');
|
expect(openWaSessionName('cmh1x2y3z0000abcd')).toBe('gruperly-cmh1x2y3z0000abcd');
|
||||||
expect(openWaSessionName('weird_id.with@chars')).toBe('gruperly-weirdidwithchars');
|
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 = {
|
const kapsoConfig = {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
linksWithQr,
|
linksWithQr,
|
||||||
useStartWhatsappConnection,
|
useStartWhatsappConnection,
|
||||||
useWhatsappStatus,
|
useWhatsappStatus,
|
||||||
WhatsappQrModal,
|
WhatsappLinkModal,
|
||||||
whatsappCallbackErrorMessage,
|
whatsappCallbackErrorMessage,
|
||||||
whatsappStatusBadgeVariant,
|
whatsappStatusBadgeVariant,
|
||||||
whatsappStatusErrorMessage,
|
whatsappStatusErrorMessage,
|
||||||
@@ -80,7 +80,7 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {
|
|||||||
) : (
|
) : (
|
||||||
<p className="text-sm text-foreground/60">
|
<p className="text-sm text-foreground/60">
|
||||||
{usesQr
|
{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.'}{' '}
|
: 'Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.'}{' '}
|
||||||
Los envíos automáticos los prendés después en cada grupo.
|
Los envíos automáticos los prendés después en cada grupo.
|
||||||
</p>
|
</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>
|
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{connection.error}</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<WhatsappQrModal
|
<WhatsappLinkModal
|
||||||
isOpen={connection.isQrOpen}
|
isOpen={connection.isQrOpen}
|
||||||
onClose={connection.closeQr}
|
onClose={connection.closeQr}
|
||||||
initialQrCode={connection.initialQrCode}
|
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 { useDisconnectWhatsapp } from './useDisconnectWhatsapp'
|
||||||
import { useStartWhatsappConnection } from './useStartWhatsappConnection'
|
import { useStartWhatsappConnection } from './useStartWhatsappConnection'
|
||||||
import { useWhatsappStatus } from './useWhatsappStatus'
|
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
|
* WhatsApp en Ajustes: vincular el número desde el que salen los recordatorios
|
||||||
@@ -120,7 +120,7 @@ export function WhatsappStatusCard() {
|
|||||||
</p>
|
</p>
|
||||||
<p className="text-xs text-foreground/50">
|
<p className="text-xs text-foreground/50">
|
||||||
{linksWithQr(data.provider)
|
{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.'}
|
: 'Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.'}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</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>
|
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{connection.error}</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<WhatsappQrModal
|
<WhatsappLinkModal
|
||||||
isOpen={connection.isQrOpen}
|
isOpen={connection.isQrOpen}
|
||||||
onClose={connection.closeQr}
|
onClose={connection.closeQr}
|
||||||
initialQrCode={connection.initialQrCode}
|
initialQrCode={connection.initialQrCode}
|
||||||
|
|||||||
@@ -115,6 +115,28 @@ export function linksWithQr(provider: WhatsappProvider): boolean {
|
|||||||
return provider === 'OPENWA'
|
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
|
* 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.
|
* usar. Se puede apagar siempre: lo que se bloquea es prenderla sin WhatsApp.
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
export {
|
export {
|
||||||
automationBlockedReason,
|
automationBlockedReason,
|
||||||
|
defaultLinkMethod,
|
||||||
|
formatPairingCode,
|
||||||
|
linksWithPairingCode,
|
||||||
linksWithQr,
|
linksWithQr,
|
||||||
readinessLabel,
|
readinessLabel,
|
||||||
readWhatsappCallbackFeedback,
|
readWhatsappCallbackFeedback,
|
||||||
WEEKLY_SEND_LABEL,
|
WEEKLY_SEND_LABEL,
|
||||||
|
type WhatsappLinkMethod,
|
||||||
type WhatsappCallbackFeedback,
|
type WhatsappCallbackFeedback,
|
||||||
whatsappCallbackErrorMessage,
|
whatsappCallbackErrorMessage,
|
||||||
whatsappStatusBadgeVariant,
|
whatsappStatusBadgeVariant,
|
||||||
@@ -13,5 +17,5 @@ export {
|
|||||||
export { useDisconnectWhatsapp } from './useDisconnectWhatsapp'
|
export { useDisconnectWhatsapp } from './useDisconnectWhatsapp'
|
||||||
export { useStartWhatsappConnection } from './useStartWhatsappConnection'
|
export { useStartWhatsappConnection } from './useStartWhatsappConnection'
|
||||||
export { useWhatsappStatus, whatsappStatusQueryKey } from './useWhatsappStatus'
|
export { useWhatsappStatus, whatsappStatusQueryKey } from './useWhatsappStatus'
|
||||||
export { WhatsappQrModal } from './WhatsappQrModal'
|
export { WhatsappLinkModal } from './WhatsappLinkModal'
|
||||||
export { WhatsappStatusCard } from './WhatsappStatusCard'
|
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,
|
WhatsappConnectResultDto,
|
||||||
WhatsappDisconnectResultDto,
|
WhatsappDisconnectResultDto,
|
||||||
WhatsappReturnTo,
|
WhatsappReturnTo,
|
||||||
|
WhatsappPairingCodeDto,
|
||||||
WhatsappStatusDto,
|
WhatsappStatusDto,
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
|
|
||||||
@@ -138,6 +139,12 @@ export const startWhatsappConnection = (returnTo: WhatsappReturnTo) =>
|
|||||||
body: JSON.stringify({ returnTo }),
|
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 getWhatsappStatus = () => apiFetch<WhatsappStatusDto>('/api/v1/whatsapp/status')
|
||||||
|
|
||||||
export const disconnectWhatsapp = () =>
|
export const disconnectWhatsapp = () =>
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ import type { WhatsappStatusDto } from '@gruperly/shared'
|
|||||||
import { describe, expect, test } from 'bun:test'
|
import { describe, expect, test } from 'bun:test'
|
||||||
import {
|
import {
|
||||||
automationBlockedReason,
|
automationBlockedReason,
|
||||||
|
defaultLinkMethod,
|
||||||
|
formatPairingCode,
|
||||||
|
linksWithPairingCode,
|
||||||
linksWithQr,
|
linksWithQr,
|
||||||
readinessLabel,
|
readinessLabel,
|
||||||
readWhatsappCallbackFeedback,
|
readWhatsappCallbackFeedback,
|
||||||
@@ -90,3 +93,21 @@ describe('whatsappStatusErrorMessage', () => {
|
|||||||
expect(whatsappStatusErrorMessage(null)).not.toContain('error')
|
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')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ El envío pasa por un **proveedor intercambiable**:
|
|||||||
| | **OpenWA** (MVP, default) | **Kapso** (fase 2) |
|
| | **OpenWA** (MVP, default) | **Kapso** (fase 2) |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Qué es | Gateway self-hosted ([rmyndharis/OpenWA](https://github.com/rmyndharis/OpenWA), MIT) sobre WhatsApp Web | Plataforma sobre la **API oficial** de WhatsApp Cloud (Meta) |
|
| Qué es | Gateway self-hosted ([rmyndharis/OpenWA](https://github.com/rmyndharis/OpenWA), MIT) sobre WhatsApp Web | Plataforma sobre la **API oficial** de WhatsApp Cloud (Meta) |
|
||||||
| Vinculación | El profesor escanea un **QR** dentro de Gruperly ("dispositivo vinculado") | El profesor va a un **setup link** de Meta (Facebook login + verificación del número) y vuelve |
|
| Vinculación | "Dispositivo vinculado": el profesor escanea un **QR** dentro de Gruperly o ingresa en WhatsApp un **código** que le damos para su número (lo único que funciona desde el mismo teléfono) | El profesor va a un **setup link** de Meta (Facebook login + verificación del número) y vuelve |
|
||||||
| Mensajes | Texto libre | **Templates** aprobados por Meta por cada cuenta |
|
| Mensajes | Texto libre | **Templates** aprobados por Meta por cada cuenta |
|
||||||
| Costo | Infraestructura propia | Plan de Kapso + tarifa de Meta por mensaje (la paga el profesor) |
|
| Costo | Infraestructura propia | Plan de Kapso + tarifa de Meta por mensaje (la paga el profesor) |
|
||||||
| Riesgo | **No oficial**: viola los términos de WhatsApp; el número se puede bloquear | Ninguno de ToS |
|
| Riesgo | **No oficial**: viola los términos de WhatsApp; el número se puede bloquear | Ninguno de ToS |
|
||||||
@@ -39,6 +39,7 @@ apps/backend/src/modules/whatsapp/
|
|||||||
│ ├── hmac.ts, period.ts, format.ts
|
│ ├── hmac.ts, period.ts, format.ts
|
||||||
├── features/
|
├── features/
|
||||||
│ ├── connect/ # POST /whatsapp/connect → { start: qr | redirect }
|
│ ├── connect/ # POST /whatsapp/connect → { start: qr | redirect }
|
||||||
|
│ ├── pairing-code/ # POST /whatsapp/connect/pairing-code → { pairingCode } (solo OpenWA)
|
||||||
│ ├── status/ # GET /whatsapp/status (hace polling al proveedor si está PENDING)
|
│ ├── status/ # GET /whatsapp/status (hace polling al proveedor si está PENDING)
|
||||||
│ ├── disconnect/ # DELETE /whatsapp/connect
|
│ ├── disconnect/ # DELETE /whatsapp/connect
|
||||||
│ ├── callback/ # GET /whatsapp/callback (solo Kapso; siempre 302)
|
│ ├── callback/ # GET /whatsapp/callback (solo Kapso; siempre 302)
|
||||||
@@ -53,6 +54,7 @@ apps/backend/src/modules/whatsapp/
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `startConnection` | Crea/adopta la sesión `gruperly-<userId>`, registra su webhook, la arranca y devuelve `{ type: 'qr' }` | Crea el customer (una vez) y un setup link `customer_managed`; devuelve `{ type: 'redirect' }` |
|
| `startConnection` | Crea/adopta la sesión `gruperly-<userId>`, registra su webhook, la arranca y devuelve `{ type: 'qr' }` | Crea el customer (una vez) y un setup link `customer_managed`; devuelve `{ type: 'redirect' }` |
|
||||||
| `refreshConnection` | `GET /sessions/:id` (QR nuevo, `ready`, `failed`) | No hay QR: `pending` hasta el callback o el webhook |
|
| `refreshConnection` | `GET /sessions/:id` (QR nuevo, `ready`, `failed`) | No hay QR: `pending` hasta el callback o el webhook |
|
||||||
|
| `requestPairingCode` (opcional) | `POST /sessions/:id/pairing-code` con el número en dígitos; reintenta el `409` mientras la sesión arranca | — (no lo implementa) |
|
||||||
| `completeRedirect` | — | Valida `setup_link_id` y que el número sea del customer del profesor |
|
| `completeRedirect` | — | Valida `setup_link_id` y que el número sea del customer del profesor |
|
||||||
| `onConnected` | — | Suscribe el webhook del número y envía los templates a Meta |
|
| `onConnected` | — | Suscribe el webhook del número y envía los templates a Meta |
|
||||||
| `readiness(kind)` | `ready` si la cuenta está activa | `ready` solo con el template `APPROVED` |
|
| `readiness(kind)` | `ready` si la cuenta está activa | `ready` solo con el template `APPROVED` |
|
||||||
@@ -79,6 +81,13 @@ OpenWA (QR)
|
|||||||
qr_ready → QR nuevo · ready → ACTIVE (se cierra el modal)
|
qr_ready → QR nuevo · ready → ACTIVE (se cierra el modal)
|
||||||
(en paralelo, si hay webhook: session.authenticated → ACTIVE)
|
(en paralelo, si hay webhook: session.authenticated → ACTIVE)
|
||||||
|
|
||||||
|
OpenWA (número de teléfono, la opción por defecto en mobile)
|
||||||
|
mismo POST /whatsapp/connect (la sesión queda arrancada) y el modal muestra "Con tu número"
|
||||||
|
POST /whatsapp/connect/pairing-code { phoneNumber } ─▶ toWhatsappE164 (país del profesor)
|
||||||
|
─▶ OpenWA POST /sessions/:id/pairing-code ─▶ { pairingCode: 'ABCD1234' }
|
||||||
|
el profesor toca la notificación de WhatsApp (o Dispositivos vinculados → Vincular con el número
|
||||||
|
de teléfono) e ingresa el código; el status y el webhook terminan igual que con el QR
|
||||||
|
|
||||||
Kapso (redirect)
|
Kapso (redirect)
|
||||||
POST /whatsapp/connect ─▶ Kapso: customer + setup link ─▶ { start: { type: 'redirect', url } }
|
POST /whatsapp/connect ─▶ Kapso: customer + setup link ─▶ { start: { type: 'redirect', url } }
|
||||||
navegador ─▶ Meta (login + verificación) ─▶ GET /whatsapp/callback?setup_link_id&phone_number_id…
|
navegador ─▶ Meta (login + verificación) ─▶ GET /whatsapp/callback?setup_link_id&phone_number_id…
|
||||||
@@ -268,6 +277,7 @@ Kapso reintenta si no recibe un 200 en 10 s.
|
|||||||
| Endpoint | Qué hace |
|
| Endpoint | Qué hace |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `POST /api/v1/whatsapp/connect` | Body `{ returnTo: 'onboarding' \| 'settings' }`. Responde `{ start: { type: 'qr', qrCode } \| { type: 'redirect', url } }` |
|
| `POST /api/v1/whatsapp/connect` | Body `{ returnTo: 'onboarding' \| 'settings' }`. Responde `{ start: { type: 'qr', qrCode } \| { type: 'redirect', url } }` |
|
||||||
|
| `POST /api/v1/whatsapp/connect/pairing-code` | Solo OpenWA, con una vinculación `PENDING`. Body `{ phoneNumber }` (nacional o internacional; se normaliza con el país del profesor). Responde `{ pairingCode }`. `409 whatsapp_linking_not_started` sin `connect` previo, `409 whatsapp_pairing_not_ready` si la sesión no arrancó tras ~10 s, `409 whatsapp_pairing_unsupported` con Kapso, `400` si el número no se puede normalizar |
|
||||||
| `GET /api/v1/whatsapp/status` | `{ status, provider, displayPhoneNumber, connectedAt, qrCode, readiness: { PAYMENT_REMINDER, REENGAGEMENT } }`. Con la cuenta `PENDING` consulta al proveedor (para el modal del QR) |
|
| `GET /api/v1/whatsapp/status` | `{ status, provider, displayPhoneNumber, connectedAt, qrCode, readiness: { PAYMENT_REMINDER, REENGAGEMENT } }`. Con la cuenta `PENDING` consulta al proveedor (para el modal del QR) |
|
||||||
| `DELETE /api/v1/whatsapp/connect` | Desvincula: con OpenWA hace logout del teléfono y borra la sesión. Localmente la fila queda `DISCONNECTED`, sin número |
|
| `DELETE /api/v1/whatsapp/connect` | Desvincula: con OpenWA hace logout del teléfono y borra la sesión. Localmente la fila queda `DISCONNECTED`, sin número |
|
||||||
| `GET /api/v1/whatsapp/callback` | Solo Kapso. Siempre responde `302` |
|
| `GET /api/v1/whatsapp/callback` | Solo Kapso. Siempre responde `302` |
|
||||||
@@ -284,8 +294,9 @@ Kapso reintenta si no recibe un 200 en 10 s.
|
|||||||
|
|
||||||
1. Levantar OpenWA (`docker run`, ver **Local**), crear la key OPERATOR y cargar `OPENWA_*` en `apps/backend/.env`. Después `bun dev`.
|
1. Levantar OpenWA (`docker run`, ver **Local**), crear la key OPERATOR y cargar `OPENWA_*` en `apps/backend/.env`. Después `bun dev`.
|
||||||
2. **Onboarding**:
|
2. **Onboarding**:
|
||||||
- Cuenta nueva → paso "WhatsApp" → "Vincular WhatsApp" abre el QR.
|
- Cuenta nueva → paso "WhatsApp" → "Vincular WhatsApp" abre el modal: en desktop arranca por el QR, en el teléfono por "Con tu número".
|
||||||
- Escanearlo desde WhatsApp → Dispositivos vinculados.
|
- QR: escanearlo desde WhatsApp → Dispositivos vinculados.
|
||||||
|
- Número: escribirlo, "Obtener código" e ingresar el código en WhatsApp (notificación, o Dispositivos vinculados → Vincular con el número de teléfono).
|
||||||
- El modal se cierra solo y el paso muestra el número.
|
- El modal se cierra solo y el paso muestra el número.
|
||||||
- "Lo hago después" deja seguir sin vincular.
|
- "Lo hago después" deja seguir sin vincular.
|
||||||
3. **Ajustes → WhatsApp**: muestra "Vinculado", el número y "Listo para enviar" en los dos mensajes. "Desvincular" pide confirmación y el dispositivo desaparece del teléfono.
|
3. **Ajustes → WhatsApp**: muestra "Vinculado", el número y "Listo para enviar" en los dos mensajes. "Desvincular" pide confirmación y el dispositivo desaparece del teléfono.
|
||||||
@@ -325,7 +336,9 @@ Kapso reintenta si no recibe un 200 en 10 s.
|
|||||||
**Con OpenWA (hoy):**
|
**Con OpenWA (hoy):**
|
||||||
|
|
||||||
1. En Gruperly: Ajustes → WhatsApp → **Vincular** (o el paso "WhatsApp" del onboarding).
|
1. En Gruperly: Ajustes → WhatsApp → **Vincular** (o el paso "WhatsApp" del onboarding).
|
||||||
2. En el teléfono: WhatsApp → **Dispositivos vinculados** → **Vincular un dispositivo** → escanear el código.
|
2. Elegí cómo vincular:
|
||||||
|
- **Con tu número** (si usás Gruperly desde el mismo teléfono): escribí tu número, tocá **Obtener código** y abrí WhatsApp. Tocá la notificación para vincular un dispositivo (o **Dispositivos vinculados** → **Vincular un dispositivo** → **Vincular con el número de teléfono**) e ingresá el código.
|
||||||
|
- **Con código QR** (desde la computadora): en el teléfono, WhatsApp → **Dispositivos vinculados** → **Vincular un dispositivo** → escanear el código.
|
||||||
3. En cada grupo, prender los mensajes automáticos que quieras. Salen los lunes a las 10:00, desde tu número, y las respuestas de tus alumnos te llegan a tu WhatsApp de siempre.
|
3. En cada grupo, prender los mensajes automáticos que quieras. Salen los lunes a las 10:00, desde tu número, y las respuestas de tus alumnos te llegan a tu WhatsApp de siempre.
|
||||||
4. Para cortar: Ajustes → WhatsApp → Desvincular, o quitar el dispositivo desde el teléfono.
|
4. Para cortar: Ajustes → WhatsApp → Desvincular, o quitar el dispositivo desde el teléfono.
|
||||||
|
|
||||||
|
|||||||
@@ -49,6 +49,22 @@ export const WhatsappConnectResultDtoSchema = z.object({
|
|||||||
});
|
});
|
||||||
export type WhatsappConnectResultDto = z.output<typeof WhatsappConnectResultDtoSchema>;
|
export type WhatsappConnectResultDto = z.output<typeof WhatsappConnectResultDtoSchema>;
|
||||||
|
|
||||||
|
// Linking by phone number instead of QR (OpenWA): the teacher types their own
|
||||||
|
// number and enters the code WhatsApp asks for on that phone. It is the only
|
||||||
|
// way to link from the same phone the app is running on, where a QR cannot be
|
||||||
|
// scanned. National or international format; the server normalizes it with the
|
||||||
|
// teacher's country.
|
||||||
|
export const WhatsappPairingCodeSchema = z.strictObject({
|
||||||
|
phoneNumber: z.string().trim().min(6, 'Ingresá tu número de WhatsApp').max(30),
|
||||||
|
});
|
||||||
|
export type WhatsappPairingCode = z.output<typeof WhatsappPairingCodeSchema>;
|
||||||
|
|
||||||
|
export const WhatsappPairingCodeDtoSchema = z.object({
|
||||||
|
// 8 characters, as WhatsApp shows them (e.g. `ABCD1234`).
|
||||||
|
pairingCode: z.string(),
|
||||||
|
});
|
||||||
|
export type WhatsappPairingCodeDto = z.output<typeof WhatsappPairingCodeDtoSchema>;
|
||||||
|
|
||||||
export const WhatsappStatusDtoSchema = z.object({
|
export const WhatsappStatusDtoSchema = z.object({
|
||||||
status: whatsappAccountStatusSchema,
|
status: whatsappAccountStatusSchema,
|
||||||
provider: whatsappProviderSchema,
|
provider: whatsappProviderSchema,
|
||||||
|
|||||||
Reference in New Issue
Block a user