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

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

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

View File

@@ -0,0 +1,165 @@
import type { WhatsappAccount } from '@generated/prisma/client';
import type {
ProblemDetails,
Result,
WhatsappCallbackReason,
WhatsappConnectionStart,
WhatsappMessageKind,
WhatsappReadiness,
WhatsappReturnTo,
} from '@gruperly/shared';
/**
* The port every WhatsApp gateway implements. The domain (linking, the weekly
* jobs, the webhook) only talks to this interface; everything that knows about
* OpenWA or Kapso lives in `providers/<name>/`. Switching gateways is a matter of
* `WHATSAPP_PROVIDER` plus an adapter, never of touching the jobs or the UI.
*/
export type MessagingProviderId = 'OPENWA' | 'KAPSO';
export type WhatsappAccountRecord = Pick<
WhatsappAccount,
'id' | 'ownerId' | 'provider' | 'status' | 'externalId' | 'displayPhoneNumber' | 'providerData'
>;
/**
* What the teacher receives, in domain terms. Each provider turns it into its
* own wire format: free text (OpenWA) or a template with parameters (Kapso).
*/
export type WhatsappMessage =
| {
kind: 'PAYMENT_REMINDER';
studentName: string;
groupName: string;
amount: string;
dueDate: string;
paymentLink: string;
}
| {
kind: 'REENGAGEMENT';
studentName: string;
groupName: string;
};
export type StartConnectionContext = {
ownerId: string;
ownerName: string;
returnTo: WhatsappReturnTo;
/** The teacher's existing row, if any, to reuse provider-side resources. */
account: WhatsappAccountRecord | null;
};
export type StartConnectionResult = {
start: WhatsappConnectionStart;
/** OpenWA: the session id. Kapso: null until the setup finishes. */
externalId: string | null;
providerData?: Record<string, string> | null;
};
/** The live state of a linking, as the provider reports it. */
export type ConnectionSnapshot =
| { state: 'pending'; qrCode: string | null }
| { state: 'active'; displayPhoneNumber: string | null }
| { state: 'disconnected'; reason: string | null };
/** The provider-side result of finishing a redirect-based linking (Kapso). */
export type CompletedConnection = {
externalId: string;
displayPhoneNumber: string | null;
providerData?: Record<string, string> | null;
};
export type RecipientResolution =
| { ok: true; to: string }
| { ok: false; code: 'no_whatsapp' | 'provider_error' };
export type SendOutcome =
| { ok: true; providerMessageId: string }
| {
ok: false;
/** Worth trying again on the next run (5xx, network). */
retryable: boolean;
/** The gateway asked us to stop sending from this account for a while. */
rateLimitedForMs?: number;
code: string;
message: string;
};
export type MessageDeliveryStatus = 'SENT' | 'DELIVERED' | 'READ' | 'FAILED';
/** Webhook payloads reduced to the two things the domain cares about. */
export type NormalizedEvent =
| {
type: 'connection';
/** Session id (OpenWA) or phone_number_id (Kapso). */
externalId: string;
/** When the provider carries our own reference (Kapso's external customer id). */
ownerId?: string;
status: 'active' | 'disconnected';
displayPhoneNumber?: string | null;
providerData?: Record<string, string> | null;
}
| {
type: 'message_status';
providerMessageId: string;
status: MessageDeliveryStatus;
errorCode?: string | null;
errorMessage?: string | null;
};
export type ParsedWebhook = {
/** The delivery's idempotency key; burned before the events are applied. */
dedupeKey: string;
events: NormalizedEvent[];
};
export type WebhookParseError = 'invalid_signature' | 'invalid_payload';
export interface MessagingProvider {
readonly id: MessagingProviderId;
/** Starts (or restarts) linking the teacher's number. */
startConnection(
context: StartConnectionContext,
): Promise<Result<StartConnectionResult, ProblemDetails>>;
/** Asks the provider how the linking is going (fresh QR, linked, failed). */
refreshConnection(
account: WhatsappAccountRecord,
): Promise<Result<ConnectionSnapshot, ProblemDetails>>;
/**
* Finishes a redirect-based linking from the callback query. Only providers
* whose `startConnection` answers `redirect` implement it.
*/
completeRedirect?(
account: WhatsappAccountRecord,
query: Record<string, string | undefined>,
): Promise<Result<CompletedConnection, WhatsappCallbackReason>>;
/** Unlinks the number on the provider side. Best effort. */
disconnect(account: WhatsappAccountRecord): Promise<Result<void, ProblemDetails>>;
/** Runs once the account becomes ACTIVE (Kapso: templates and webhooks). */
onConnected?(account: WhatsappAccountRecord): Promise<void>;
/** Whether a message of this kind can be sent from the account right now. */
readiness(account: WhatsappAccountRecord, kind: WhatsappMessageKind): Promise<WhatsappReadiness>;
/** Turns an E.164 number into the provider's recipient id, or says it has no WhatsApp. */
resolveRecipient(account: WhatsappAccountRecord, e164: string): Promise<RecipientResolution>;
send(
account: WhatsappAccountRecord,
to: string,
message: WhatsappMessage,
idempotencyKey: string,
): Promise<SendOutcome>;
/** Verifies the signature over the raw body and normalizes the payload. */
parseWebhook(
rawBody: string,
headers: Headers,
): Result<ParsedWebhook, WebhookParseError>;
}