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

@@ -30,4 +30,28 @@ MP_CLIENT_SECRET=""
MP_REDIRECT_URI=""
# Clave de 32 bytes en base64 para cifrar los tokens de MP en reposo (AES-256-GCM).
# Generar con: openssl rand -base64 32
TOKEN_ENCRYPTION_KEY=""
TOKEN_ENCRYPTION_KEY=""
# WhatsApp: recordatorios de pago y reenganche semanales (ver docs/whatsapp.md).
# Proveedor: openwa (MVP, gateway self-hosted con QR) | kapso (API oficial de Meta).
WHATSAPP_PROVIDER="openwa"
# Pausa entre dos envíos del mismo profesor, en ms (OpenWA recomienda < 15 msg/min).
WHATSAPP_SEND_INTERVAL_MS="5000"
# OpenWA. En local: docker compose up openwa (o docker run, ver docs/whatsapp.md).
OPENWA_API_URL="http://localhost:2785/api"
# Key OPERATOR sin allowedSessions, creada con la key ADMIN de /app/data/.api-key.
OPENWA_API_KEY=""
# Opcional. Sin webhook la vinculación funciona (el status hace polling), pero no
# llegan las confirmaciones de entrega/lectura. Si lo cargás, el secreto es obligatorio.
OPENWA_WEBHOOK_URL=""
# 16+ caracteres. Generar con: openssl rand -hex 24
OPENWA_WEBHOOK_SECRET=""
# Kapso (WHATSAPP_PROVIDER="kapso"). Las URLs tienen que ser públicas (túnel en local).
KAPSO_API_KEY=""
KAPSO_CALLBACK_URL=""
KAPSO_WEBHOOK_URL=""
# El mismo secreto del project webhook configurado en el dashboard de Kapso.
KAPSO_WEBHOOK_SECRET=""
# KAPSO_API_URL="https://api.kapso.ai"

View File

@@ -0,0 +1,129 @@
-- WhatsApp messaging: linked accounts (provider-agnostic), Kapso templates,
-- outbound message log and webhook dedupe; plus the per-group automation switches.
-- CreateEnum
CREATE TYPE "MessagingProviderId" AS ENUM ('OPENWA', 'KAPSO');
-- CreateEnum
CREATE TYPE "WhatsappAccountStatus" AS ENUM ('PENDING', 'ACTIVE', 'DISCONNECTED');
-- CreateEnum
CREATE TYPE "WhatsappMessageKind" AS ENUM ('PAYMENT_REMINDER', 'REENGAGEMENT');
-- CreateEnum
CREATE TYPE "OutboundMessageStatus" AS ENUM ('QUEUED', 'SENT', 'DELIVERED', 'READ', 'FAILED', 'SKIPPED');
-- CreateEnum
CREATE TYPE "WhatsappTemplateStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED', 'DISABLED');
-- AlterTable
ALTER TABLE "groups" ADD COLUMN "auto_payment_reminders" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "auto_reengagement" BOOLEAN NOT NULL DEFAULT false;
-- AlterTable (pre-existing drift: the schema already declares this default)
ALTER TABLE "payments" ALTER COLUMN "currency" SET DEFAULT 'ARS';
-- CreateTable
CREATE TABLE "whatsapp_accounts" (
"id" TEXT NOT NULL,
"owner_id" TEXT NOT NULL,
"provider" "MessagingProviderId" NOT NULL,
"status" "WhatsappAccountStatus" NOT NULL DEFAULT 'PENDING',
"external_id" TEXT,
"display_phone_number" TEXT,
"provider_data" JSONB,
"connected_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "whatsapp_accounts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "whatsapp_templates" (
"id" TEXT NOT NULL,
"account_id" TEXT NOT NULL,
"kind" "WhatsappMessageKind" NOT NULL,
"name" TEXT NOT NULL,
"language" TEXT NOT NULL,
"meta_template_id" TEXT,
"status" "WhatsappTemplateStatus" NOT NULL DEFAULT 'PENDING',
"rejected_reason" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "whatsapp_templates_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "outbound_messages" (
"id" TEXT NOT NULL,
"owner_id" TEXT NOT NULL,
"group_id" TEXT NOT NULL,
"attendee_id" TEXT NOT NULL,
"payment_id" TEXT,
"kind" "WhatsappMessageKind" NOT NULL,
"provider" "MessagingProviderId" NOT NULL,
"period_key" TEXT NOT NULL,
"to_phone" TEXT NOT NULL,
"provider_message_id" TEXT,
"status" "OutboundMessageStatus" NOT NULL DEFAULT 'QUEUED',
"error_code" TEXT,
"error_message" TEXT,
"sent_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "outbound_messages_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "whatsapp_webhook_events" (
"provider" "MessagingProviderId" NOT NULL,
"dedupe_key" TEXT NOT NULL,
"received_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "whatsapp_webhook_events_pkey" PRIMARY KEY ("provider","dedupe_key")
);
-- CreateIndex
CREATE UNIQUE INDEX "whatsapp_accounts_ownerId_key" ON "whatsapp_accounts"("owner_id");
-- CreateIndex
CREATE UNIQUE INDEX "whatsapp_accounts_provider_externalId_key" ON "whatsapp_accounts"("provider", "external_id");
-- CreateIndex
CREATE INDEX "whatsapp_templates_status_idx" ON "whatsapp_templates"("status");
-- CreateIndex
CREATE UNIQUE INDEX "whatsapp_templates_accountId_kind_key" ON "whatsapp_templates"("account_id", "kind");
-- CreateIndex
CREATE INDEX "outbound_messages_attendeeId_kind_createdAt_idx" ON "outbound_messages"("attendee_id", "kind", "created_at");
-- CreateIndex
CREATE INDEX "outbound_messages_groupId_createdAt_idx" ON "outbound_messages"("group_id", "created_at");
-- CreateIndex
CREATE UNIQUE INDEX "outbound_messages_kind_attendeeId_periodKey_key" ON "outbound_messages"("kind", "attendee_id", "period_key");
-- CreateIndex
CREATE UNIQUE INDEX "outbound_messages_provider_providerMessageId_key" ON "outbound_messages"("provider", "provider_message_id");
-- CreateIndex
CREATE INDEX "whatsapp_webhook_events_receivedAt_idx" ON "whatsapp_webhook_events"("received_at");
-- AddForeignKey
ALTER TABLE "whatsapp_accounts" ADD CONSTRAINT "whatsapp_accounts_ownerId_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "whatsapp_templates" ADD CONSTRAINT "whatsapp_templates_accountId_fkey" FOREIGN KEY ("account_id") REFERENCES "whatsapp_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_groupId_fkey" FOREIGN KEY ("group_id") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_attendeeId_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_paymentId_fkey" FOREIGN KEY ("payment_id") REFERENCES "payments"("id") ON DELETE SET NULL ON UPDATE CASCADE;

View File

@@ -20,6 +20,7 @@ model User {
orgInvitations Invitation[] @relation("InvitedBy")
waitlist WaitlistEntry[]
mpAccount MpAccount?
whatsappAccount WhatsappAccount?
@@map("users")
}

View File

@@ -1,19 +1,22 @@
// Domain models
model Group {
id String @id @default(cuid())
name String
description String?
days WeekDay[]
time String?
capacity Int?
price Decimal? @db.Decimal(10, 2)
billingType BillingType? @map("billing_type")
dueDay Int? @map("due_day")
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
createdById String @map("created_by_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
id String @id @default(cuid())
name String
description String?
days WeekDay[]
time String?
capacity Int?
price Decimal? @db.Decimal(10, 2)
billingType BillingType? @map("billing_type")
dueDay Int? @map("due_day")
// Weekly WhatsApp automations, off until the teacher turns them on.
autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
autoReengagement Boolean @default(false) @map("auto_reengagement")
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
createdById String @map("created_by_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey")
members GroupMember[]
@@ -22,6 +25,7 @@ model Group {
waitlist GroupWaitlistEntry[]
preRegistrations GroupPreRegistration[]
classSessions ClassSession[]
outboundMessages OutboundMessage[]
@@map("groups")
}
@@ -81,33 +85,35 @@ model Attendee {
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
payments Payment[]
attendances Attendance[]
slotReleases SlotRelease[]
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
payments Payment[]
attendances Attendance[]
slotReleases SlotRelease[]
outboundMessages OutboundMessage[]
@@index([groupId], map: "attendees_groupId_idx")
@@map("attendees")
}
model Payment {
id String @id @default(cuid())
groupId String @map("group_id")
attendeeId String @map("attendee_id")
amount Decimal @db.Decimal(10, 2)
currency String @default("ARS")
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
dueDate DateTime @map("due_date")
description String? @map("description")
checkoutUrl String? @map("checkout_url")
mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
mpPaymentId String? @map("mp_payment_id")
paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
id String @id @default(cuid())
groupId String @map("group_id")
attendeeId String @map("attendee_id")
amount Decimal @db.Decimal(10, 2)
currency String @default("ARS")
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
dueDate DateTime @map("due_date")
description String? @map("description")
checkoutUrl String? @map("checkout_url")
mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
mpPaymentId String? @map("mp_payment_id")
paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
outboundMessages OutboundMessage[]
@@index([groupId], map: "payments_groupId_idx")
@@index([attendeeId], map: "payments_attendeeId_idx")

View File

@@ -0,0 +1,130 @@
// WhatsApp messaging (automated payment reminders and re-engagement).
//
// Nothing here is tied to one provider: the teacher links their own number
// through whichever `MessagingProvider` the server runs (OpenWA for the MVP,
// Kapso afterwards) and the row records which one it was linked with. Changing
// `WHATSAPP_PROVIDER` leaves the old rows behind as "requires reconnect".
enum MessagingProviderId {
OPENWA
KAPSO
}
enum WhatsappAccountStatus {
PENDING
ACTIVE
DISCONNECTED
}
enum WhatsappMessageKind {
PAYMENT_REMINDER
REENGAGEMENT
}
enum OutboundMessageStatus {
QUEUED
SENT
DELIVERED
READ
FAILED
SKIPPED
}
enum WhatsappTemplateStatus {
PENDING
APPROVED
REJECTED
DISABLED
}
// The teacher's linked WhatsApp. One per teacher.
model WhatsappAccount {
id String @id @default(cuid())
ownerId String @unique(map: "whatsapp_accounts_ownerId_key") @map("owner_id")
provider MessagingProviderId
status WhatsappAccountStatus @default(PENDING)
// OpenWA: session id. Kapso: phone_number_id (null until the setup finishes).
externalId String? @map("external_id")
displayPhoneNumber String? @map("display_phone_number")
// Provider-specific identifiers (Kapso: customerId, setupLinkId, businessAccountId).
// Never secrets: API keys and webhook secrets live in the environment.
providerData Json? @map("provider_data")
connectedAt DateTime? @map("connected_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "whatsapp_accounts_ownerId_fkey")
templates WhatsappTemplate[]
// A number (or session) cannot be linked to two teachers.
@@unique([provider, externalId], map: "whatsapp_accounts_provider_externalId_key")
@@map("whatsapp_accounts")
}
// Message templates submitted to Meta for one account (Kapso only: OpenWA sends
// free text). Meta approves them per WhatsApp Business Account.
model WhatsappTemplate {
id String @id @default(cuid())
accountId String @map("account_id")
kind WhatsappMessageKind
name String
language String
metaTemplateId String? @map("meta_template_id")
status WhatsappTemplateStatus @default(PENDING)
rejectedReason String? @map("rejected_reason")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
account WhatsappAccount @relation(fields: [accountId], references: [id], onDelete: Cascade, map: "whatsapp_templates_accountId_fkey")
@@unique([accountId, kind], map: "whatsapp_templates_accountId_kind_key")
@@index([status], map: "whatsapp_templates_status_idx")
@@map("whatsapp_templates")
}
// One automated message to one member. It is the send log and the idempotency
// key at once: the row is created before calling the provider, and the unique
// (kind, attendee, week) is what stops a second run of the weekly job from
// writing to the same person twice.
model OutboundMessage {
id String @id @default(cuid())
ownerId String @map("owner_id")
groupId String @map("group_id")
attendeeId String @map("attendee_id")
paymentId String? @map("payment_id")
kind WhatsappMessageKind
provider MessagingProviderId
// ISO week the job ran for, e.g. "2026-W43".
periodKey String @map("period_key")
toPhone String @map("to_phone")
providerMessageId String? @map("provider_message_id")
status OutboundMessageStatus @default(QUEUED)
errorCode String? @map("error_code")
errorMessage String? @map("error_message")
sentAt DateTime? @map("sent_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "outbound_messages_groupId_fkey")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "outbound_messages_attendeeId_fkey")
payment Payment? @relation(fields: [paymentId], references: [id], onDelete: SetNull, map: "outbound_messages_paymentId_fkey")
@@unique([kind, attendeeId, periodKey], map: "outbound_messages_kind_attendeeId_periodKey_key")
@@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key")
// Re-engagement cooldown: "was this member written to in the last 14 days?"
@@index([attendeeId, kind, createdAt], map: "outbound_messages_attendeeId_kind_createdAt_idx")
@@index([groupId, createdAt], map: "outbound_messages_groupId_createdAt_idx")
@@map("outbound_messages")
}
// Webhook deliveries already processed. Both providers deliver at least once and
// retry, so the delivery's idempotency key is burned here before applying it.
model WhatsappWebhookEvent {
provider MessagingProviderId
dedupeKey String @map("dedupe_key")
receivedAt DateTime @default(now()) @map("received_at")
@@id([provider, dedupeKey], map: "whatsapp_webhook_events_pkey")
@@index([receivedAt], map: "whatsapp_webhook_events_receivedAt_idx")
@@map("whatsapp_webhook_events")
}

View File

@@ -25,6 +25,7 @@ import { mpRoutes } from './modules/mp';
import { onboardingRoutes } from './modules/onboarding';
import { paymentsRoutes } from './modules/payments';
import { waitlistRoutes } from './modules/waitlist';
import { whatsappRoutes } from './modules/whatsapp';
const app = new Hono<BackendEnv>();
@@ -46,6 +47,7 @@ api.route('/groups', groupsRoutes);
api.route('/home', homeRoutes);
api.route('/onboarding', onboardingRoutes);
api.route('/mp', mpRoutes);
api.route('/whatsapp', whatsappRoutes);
api.route('/attendees', attendeesRoutes);
api.route('/payments', paymentsRoutes);
api.route('/waitlist', waitlistRoutes);

View File

@@ -114,6 +114,42 @@ export function mpProviderErrorProblem(): ProblemDetails {
};
}
/** The server is missing the variables of the active WhatsApp provider. */
export function whatsappNotConfiguredProblem(): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/whatsapp-not-configured`,
title: 'Service Unavailable',
status: 503,
detail: 'La vinculación con WhatsApp no está disponible en este momento.',
code: 'whatsapp_not_configured',
};
}
export function whatsappNotConnectedProblem(): ProblemDetails {
return conflictProblem({
detail: 'No tenés un WhatsApp vinculado.',
code: 'whatsapp_not_connected',
});
}
export function whatsappNumberInUseProblem(): ProblemDetails {
return conflictProblem({
detail: 'Ese número de WhatsApp ya está vinculado a otro profesor.',
code: 'whatsapp_number_in_use',
});
}
/** The WhatsApp gateway refused the request, or could not be reached. */
export function whatsappProviderErrorProblem(): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/whatsapp-unavailable`,
title: 'Bad Gateway',
status: 502,
detail: 'No pudimos comunicarnos con WhatsApp. Intentá de nuevo en unos minutos.',
code: 'whatsapp_provider_error',
};
}
export function onboardingAlreadyCompletedProblem(): ProblemDetails {
return conflictProblem({
detail: 'Ya completaste el onboarding de Gruperly.',

View File

@@ -34,6 +34,14 @@ export function isPublicApiRequest(method: string, path: string): boolean {
if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') {
return true;
}
// WhatsApp provider webhooks: no session, authenticated by their HMAC signature.
if (
method === 'POST'
&& (normalizedPath === '/api/v1/whatsapp/webhooks/openwa'
|| normalizedPath === '/api/v1/whatsapp/webhooks/kapso')
) {
return true;
}
return (
normalizedPath === '/api/v1/health'

View File

@@ -18,7 +18,7 @@ import {
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
type GetStudentsAtRiskDeps = {
db?: AnalyticsAccessDb & Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>;
db?: AnalyticsAccessDb & StudentsAtRiskDb;
now?: Date;
};
@@ -37,72 +37,13 @@ export class GetStudentsAtRisk {
): Promise<Result<StudentsAtRisk, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
const access = await findGroupForUser(db, groupId, userId);
if (!access.ok) {
return access;
}
const [windowSessions, attendees, attendances] = await Promise.all([
db.classSession.findMany({
where: { groupId, startsAt: { gte: since } },
select: { id: true },
}),
db.attendee.findMany({
where: { groupId, status: 'ACTIVE' },
select: { id: true, fullName: true, phone: true },
}),
db.attendance.findMany({
where: { attendee: { groupId } },
select: {
attendeeId: true,
status: true,
classSession: { select: { startsAt: true } },
},
orderBy: { classSession: { startsAt: 'desc' } },
}),
]);
const totalWindowSessions = windowSessions.length;
const streamByAttendee = groupAttendanceByAttendee(attendances);
const atRisk: StudentAtRisk[] = [];
for (const attendee of attendees) {
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
status: row.status,
occurredAt: row.classSession.startsAt,
}));
const consecutiveAbsences = trailingAbsentStreak(stream);
const attendedAt = lastAttendedAt(stream);
const monthlyRate = monthlyAttendanceRate(
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
totalWindowSessions,
);
const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate);
if (!riskLevel) {
continue;
}
atRisk.push({
attendeeId: attendee.id,
fullName: attendee.fullName,
phone: attendee.phone,
riskLevel,
consecutiveAbsences,
lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
monthlyAttendanceRate: monthlyRate,
});
}
atRisk.sort((a, b) => {
if (a.riskLevel !== b.riskLevel) {
return a.riskLevel === 'HIGH' ? -1 : 1;
}
if (a.consecutiveAbsences !== b.consecutiveAbsences) {
return b.consecutiveAbsences - a.consecutiveAbsences;
}
return a.monthlyAttendanceRate - b.monthlyAttendanceRate;
});
const atRisk = await findStudentsAtRisk(db, groupId, now);
return ok({
groupName: access.value.name,
@@ -111,6 +52,83 @@ export class GetStudentsAtRisk {
}
}
export type StudentsAtRiskDb = Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>;
/**
* The ACTIVE members of a group who are at risk, most urgent first. Shared by
* the "Alumnos en riesgo" screen and the weekly re-engagement job, so both
* agree on who is at risk. Does not check access: callers do.
*/
export async function findStudentsAtRisk(
db: StudentsAtRiskDb,
groupId: string,
now: Date,
): Promise<StudentAtRisk[]> {
const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
const [windowSessions, attendees, attendances] = await Promise.all([
db.classSession.findMany({
where: { groupId, startsAt: { gte: since } },
select: { id: true },
}),
db.attendee.findMany({
where: { groupId, status: 'ACTIVE' },
select: { id: true, fullName: true, phone: true },
}),
db.attendance.findMany({
where: { attendee: { groupId } },
select: {
attendeeId: true,
status: true,
classSession: { select: { startsAt: true } },
},
orderBy: { classSession: { startsAt: 'desc' } },
}),
]);
const totalWindowSessions = windowSessions.length;
const streamByAttendee = groupAttendanceByAttendee(attendances);
const atRisk: StudentAtRisk[] = [];
for (const attendee of attendees) {
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
status: row.status,
occurredAt: row.classSession.startsAt,
}));
const consecutiveAbsences = trailingAbsentStreak(stream);
const attendedAt = lastAttendedAt(stream);
const monthlyRate = monthlyAttendanceRate(
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
totalWindowSessions,
);
const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate);
if (!riskLevel) {
continue;
}
atRisk.push({
attendeeId: attendee.id,
fullName: attendee.fullName,
phone: attendee.phone,
riskLevel,
consecutiveAbsences,
lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
monthlyAttendanceRate: monthlyRate,
});
}
atRisk.sort((a, b) => {
if (a.riskLevel !== b.riskLevel) {
return a.riskLevel === 'HIGH' ? -1 : 1;
}
if (a.consecutiveAbsences !== b.consecutiveAbsences) {
return b.consecutiveAbsences - a.consecutiveAbsences;
}
return a.monthlyAttendanceRate - b.monthlyAttendanceRate;
});
return atRisk;
}
function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map<string, AttendanceStreamRow[]> {
const byAttendee = new Map<string, AttendanceStreamRow[]>();
for (const row of rows) {

View File

@@ -19,6 +19,8 @@ export type GroupRecord = {
billingType: BillingType | null;
dueDay: number | null;
inviteToken?: string | null;
autoPaymentReminders?: boolean;
autoReengagement?: boolean;
};
/* The listing adds the occupancy counters to each group so the card can show
@@ -44,6 +46,8 @@ export function toGroupDto(record: GroupRecord): GroupDto {
billingType: record.billingType,
dueDay: record.dueDay,
inviteToken: record.inviteToken ?? null,
autoPaymentReminders: record.autoPaymentReminders ?? false,
autoReengagement: record.autoReengagement ?? false,
};
}

View File

@@ -10,6 +10,7 @@ import updateAttendeeRoute from '../attendees/features/update/route';
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
import groupWaitlistRoutes from '../group-waitlist/routes';
import createPaymentsBatchRoute from '../payments/features/create-batch/route';
import updateGroupAutomationsRoute from '../whatsapp/features/update-automations/route';
import createGroupRoute from './features/create/route';
import getAllRoute from './features/get-all/route';
import getByIdRoute from './features/get-by-id/route';
@@ -26,6 +27,7 @@ routes.route('/', createAttendeeRoute);
routes.route('/', bulkCreateAttendeesRoute);
routes.route('/', getByIdRoute);
routes.route('/', createPaymentsBatchRoute);
routes.route('/', updateGroupAutomationsRoute);
routes.route('/', addToGroupWaitlistRoute);
routes.route('/', groupWaitlistRoutes);
routes.route('/', groupPreRegistrationRoutes);

View File

@@ -3,8 +3,11 @@ import type { OnboardingStatusDto, ProblemDetails, Result } from '@gruperly/shar
import { err, ok } from '@gruperly/shared';
import { problemDetails } from '@/http/problem-details';
import prisma from '@/lib/prisma';
import { isWhatsappAccountUsable } from '@/modules/whatsapp/lib/account';
type GetOnboardingStatusDeps = { db?: Pick<PrismaClient, 'user' | 'mpAccount'> };
type GetOnboardingStatusDeps = {
db?: Pick<PrismaClient, 'user' | 'mpAccount' | 'whatsappAccount'>;
};
export class GetOnboardingStatus {
constructor(private readonly deps: GetOnboardingStatusDeps = {}) {}
@@ -24,8 +27,11 @@ export class GetOnboardingStatus {
);
}
const whatsappAccount = await db.whatsappAccount.findUnique({ where: { ownerId: userId } });
const whatsappConnected = isWhatsappAccountUsable(whatsappAccount);
if (user.onboardingCompleted) {
return ok({ step: 'COMPLETED', paymentConnected: true, completed: true });
return ok({ step: 'COMPLETED', paymentConnected: true, whatsappConnected, completed: true });
}
// Linking Mercado Pago is optional, so `paymentConnected` here only resumes
@@ -33,9 +39,14 @@ export class GetOnboardingStatus {
// need to see the "Cobros" step again. A `revoked` row is not usable.
const mpAccount = await db.mpAccount.findUnique({ where: { ownerId: userId } });
if (mpAccount && mpAccount.status === 'ACTIVE') {
return ok({ step: 'PAYMENT_CONNECTED', paymentConnected: true, completed: false });
return ok({
step: 'PAYMENT_CONNECTED',
paymentConnected: true,
whatsappConnected,
completed: false,
});
}
return ok({ step: 'NOT_STARTED', paymentConnected: false, completed: false });
return ok({ step: 'NOT_STARTED', paymentConnected: false, whatsappConnected, completed: false });
}
}

View File

@@ -15,6 +15,8 @@ export type OnboardingGroupRecord = {
price: PriceLike | number | null;
billingType: BillingType | null;
dueDay: number | null;
autoPaymentReminders?: boolean;
autoReengagement?: boolean;
};
export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingGroupDto {
@@ -31,5 +33,7 @@ export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingG
price: record.price == null ? null : Number(record.price.toString()),
billingType: record.billingType,
dueDay: record.dueDay,
autoPaymentReminders: record.autoPaymentReminders ?? false,
autoReengagement: record.autoReengagement ?? false,
};
}

View File

@@ -0,0 +1,33 @@
import type { WhatsappCallbackQuery } from '@gruperly/shared';
import { WhatsappCallbackQuerySchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { validate } from '@/http/validate';
import { logger } from '@/logger';
import { getWebOrigin } from '@/modules/mp/lib';
import { buildWhatsappReturnUrl, CompleteWhatsappSetup } from './use-case';
/**
* The browser arrives here from the provider's hosted linking (Kapso), so this
* route always redirects back to the app and never returns a problem body.
*/
const route = new Hono();
route.get('/', validate.query(WhatsappCallbackQuerySchema), async (c) => {
const query = c.req.valid('query') as WhatsappCallbackQuery;
const user = c.get('user');
if (!user) {
// Without a session there is nobody to credit the number to.
logger.warn('WhatsApp setup callback arrived without a session');
return c.redirect(new URL('/login', getWebOrigin()).toString());
}
const outcome = await new CompleteWhatsappSetup().execute(user.id, query);
if (outcome.kind === 'error') {
logger.warn({ reason: outcome.reason }, 'WhatsApp setup callback failed');
}
return c.redirect(buildWhatsappReturnUrl(getWebOrigin(), query.returnTo, outcome));
});
export default route;

View File

@@ -0,0 +1,70 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { WhatsappCallbackReason, WhatsappReturnTo } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { activateWhatsappAccount } from '../../lib/activate-account';
import { getMessagingProvider } from '../../providers';
import type { MessagingProvider } from '../../providers/messaging-provider';
type CompleteWhatsappSetupDeps = {
db?: Pick<PrismaClient, 'whatsappAccount'>;
provider?: MessagingProvider;
now?: () => Date;
};
export type WhatsappCallbackOutcome =
| { kind: 'success' }
| { kind: 'error'; reason: WhatsappCallbackReason };
/**
* Finishes a redirect-based linking (Kapso's setup link). Never fails as a
* `Result`: whatever happens, the browser is sent back to the app with an
* outcome it can show.
*/
export class CompleteWhatsappSetup {
constructor(private readonly deps: CompleteWhatsappSetupDeps = {}) {}
async execute(
ownerId: string,
query: Record<string, string | undefined>,
): Promise<WhatsappCallbackOutcome> {
const providerResult = this.deps.provider ? { ok: true as const, value: this.deps.provider } : getMessagingProvider();
if (!providerResult.ok) return failure('provider_error');
const provider = providerResult.value;
if (!provider.completeRedirect) return failure('invalid_setup');
const db = this.deps.db ?? prisma;
const account = await db.whatsappAccount.findUnique({ where: { ownerId } });
if (!account || account.provider !== provider.id) return failure('invalid_setup');
const completed = await provider.completeRedirect(account, query);
if (!completed.ok) return failure(completed.error);
const activated = await activateWhatsappAccount(
db,
provider,
account,
completed.value,
this.deps.now?.() ?? new Date(),
);
return activated.ok ? { kind: 'success' } : failure('number_in_use');
}
}
function failure(reason: WhatsappCallbackReason): WhatsappCallbackOutcome {
return { kind: 'error', reason };
}
/**
* Where the callback sends the teacher back to. `returnTo` comes from the
* validated enum, so this cannot become an open redirect.
*/
export function buildWhatsappReturnUrl(
webUrl: string,
returnTo: WhatsappReturnTo,
outcome: WhatsappCallbackOutcome,
): string {
const url = new URL(`/${returnTo}`, webUrl);
url.searchParams.set('wa', outcome.kind);
if (outcome.kind === 'error') url.searchParams.set('reason', outcome.reason);
return url.toString();
}

View File

@@ -0,0 +1,21 @@
import type { WhatsappConnect } from '@gruperly/shared';
import { WhatsappConnectSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { StartWhatsappConnection } from './use-case';
const route = new Hono();
route.post('/', validate.json(WhatsappConnectSchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const { returnTo } = c.req.valid('json') as WhatsappConnect;
const useCase = new StartWhatsappConnection();
const result = await useCase.execute({ id: user.id, name: user.name }, returnTo);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,63 @@
import type { PrismaClient } from '@generated/prisma/client';
import type {
ProblemDetails,
Result,
WhatsappConnectResultDto,
WhatsappReturnTo,
} from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { getMessagingProvider } from '../../providers';
import type { MessagingProvider } from '../../providers/messaging-provider';
type StartWhatsappConnectionDeps = {
db?: Pick<PrismaClient, 'whatsappAccount'>;
provider?: MessagingProvider;
};
/**
* Starts linking the teacher's WhatsApp with the active provider. The answer
* tells the browser how to continue: show a QR code or navigate away.
*
* Linking again (another number, another provider) reuses the same row: the
* account goes back to PENDING until the provider confirms the new link.
*/
export class StartWhatsappConnection {
constructor(private readonly deps: StartWhatsappConnectionDeps = {}) {}
async execute(
owner: { id: string; name: string },
returnTo: WhatsappReturnTo,
): Promise<Result<WhatsappConnectResultDto, ProblemDetails>> {
const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider();
if (!providerResult.ok) return providerResult;
const provider = providerResult.value;
const db = this.deps.db ?? prisma;
const account = await db.whatsappAccount.findUnique({ where: { ownerId: owner.id } });
const started = await provider.startConnection({
ownerId: owner.id,
ownerName: owner.name,
returnTo,
account,
});
if (!started.ok) return err(started.error);
const data = {
provider: provider.id,
status: 'PENDING' as const,
externalId: started.value.externalId,
displayPhoneNumber: null,
providerData: started.value.providerData ?? undefined,
connectedAt: null,
};
await db.whatsappAccount.upsert({
where: { ownerId: owner.id },
create: { ownerId: owner.id, ...data },
update: data,
});
return ok({ start: started.value.start });
}
}

View File

@@ -0,0 +1,16 @@
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { DisconnectWhatsapp } from './use-case';
const route = new Hono();
route.delete('/', async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const useCase = new DisconnectWhatsapp();
const result = await useCase.execute(user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,53 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, WhatsappDisconnectResultDto } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getMessagingProvider } from '../../providers';
import type { MessagingProvider } from '../../providers/messaging-provider';
type DisconnectWhatsappDeps = {
db?: Pick<PrismaClient, 'whatsappAccount'>;
/** The provider the account was linked with; defaults to building it from the env. */
provider?: MessagingProvider;
};
/**
* Unlinks the teacher's WhatsApp. The provider side is best effort (OpenWA logs
* the device out of the phone; Kapso keeps the number at Meta); locally the row
* is kept as DISCONNECTED with no number, so it frees the number for a relink
* while keeping provider references (the Kapso customer) for next time.
*/
export class DisconnectWhatsapp {
constructor(private readonly deps: DisconnectWhatsappDeps = {}) {}
async execute(ownerId: string): Promise<Result<WhatsappDisconnectResultDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const account = await db.whatsappAccount.findUnique({ where: { ownerId } });
if (!account || account.status === 'DISCONNECTED') {
return ok({ disconnected: false });
}
const provider = this.deps.provider ?? resolveProvider(account.provider);
if (provider) {
const result = await provider.disconnect(account);
if (!result.ok) {
logger.warn({ code: result.error.code }, 'WhatsApp provider-side disconnect failed');
}
}
await db.whatsappAccount.update({
where: { id: account.id },
data: { status: 'DISCONNECTED', externalId: null, displayPhoneNumber: null, connectedAt: null },
});
return ok({ disconnected: true });
}
}
/** The adapter the row was linked with, if this deployment can still build it. */
function resolveProvider(id: 'OPENWA' | 'KAPSO'): MessagingProvider | null {
const result = getMessagingProvider(id);
return result.ok ? result.value : null;
}

View File

@@ -0,0 +1,16 @@
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { GetWhatsappStatus } from './use-case';
const route = new Hono();
route.get('/', async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const useCase = new GetWhatsappStatus();
const result = await useCase.execute(user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,105 @@
import type { PrismaClient } from '@generated/prisma/client';
import type {
ProblemDetails,
Result,
WhatsappReadiness,
WhatsappStatusDto,
} from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { toVisibleWhatsappStatus } from '../../lib/account';
import { activateWhatsappAccount } from '../../lib/activate-account';
import { getMessagingProvider } from '../../providers';
import type { MessagingProvider, WhatsappAccountRecord } from '../../providers/messaging-provider';
type GetWhatsappStatusDeps = {
db?: Pick<PrismaClient, 'whatsappAccount'>;
provider?: MessagingProvider;
now?: () => Date;
};
const BLOCKED: WhatsappStatusDto['readiness'] = {
PAYMENT_REMINDER: 'blocked',
REENGAGEMENT: 'blocked',
};
/**
* The teacher's WhatsApp, for Settings, the onboarding step and the group
* automations card.
*
* While a linking is PENDING this also asks the provider how it is going, so a
* QR linking completes (and the QR refreshes) by polling this endpoint alone,
* even where the provider's webhook cannot reach us (local development).
*/
export class GetWhatsappStatus {
constructor(private readonly deps: GetWhatsappStatusDeps = {}) {}
async execute(ownerId: string): Promise<Result<WhatsappStatusDto, ProblemDetails>> {
const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider();
if (!providerResult.ok) return providerResult;
const provider = providerResult.value;
const db = this.deps.db ?? prisma;
let account: WhatsappAccountRecord | null = await db.whatsappAccount.findUnique({
where: { ownerId },
});
if (!account) {
return ok(dto(provider, null, null, BLOCKED));
}
let qrCode: string | null = null;
if (account.provider === provider.id && account.status === 'PENDING') {
const snapshot = await provider.refreshConnection(account);
if (snapshot.ok) {
const live = snapshot.value;
if (live.state === 'pending') {
qrCode = live.qrCode;
} else if (live.state === 'active') {
const activated = await activateWhatsappAccount(
db,
provider,
account,
{ displayPhoneNumber: live.displayPhoneNumber },
this.deps.now?.() ?? new Date(),
);
if (activated.ok) account = activated.account;
} else {
account = await db.whatsappAccount.update({
where: { id: account.id },
data: { status: 'DISCONNECTED' },
});
}
}
// A failed lookup is not an answer: report what we have and let the next
// poll try again.
}
const readiness =
toVisibleWhatsappStatus(account, provider.id) === 'active'
? {
PAYMENT_REMINDER: await provider.readiness(account, 'PAYMENT_REMINDER'),
REENGAGEMENT: await provider.readiness(account, 'REENGAGEMENT'),
}
: BLOCKED;
return ok(dto(provider, account, qrCode, readiness));
}
}
function dto(
provider: MessagingProvider,
account: WhatsappAccountRecord & { connectedAt?: Date | null } | null,
qrCode: string | null,
readiness: Record<'PAYMENT_REMINDER' | 'REENGAGEMENT', WhatsappReadiness>,
): WhatsappStatusDto {
const status = toVisibleWhatsappStatus(account, provider.id);
return {
status,
provider: provider.id,
displayPhoneNumber: status === 'active' ? (account?.displayPhoneNumber ?? null) : null,
connectedAt: status === 'active' ? (account?.connectedAt?.toISOString() ?? null) : null,
qrCode,
readiness,
};
}

View File

@@ -0,0 +1,21 @@
import type { UpdateGroupAutomations } from '@gruperly/shared';
import { UpdateGroupAutomationsSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { UpdateGroupAutomationsUseCase } from './use-case';
/** Mounted from `modules/groups/routes.ts`: `PATCH /groups/:groupId/automations`. */
const route = new Hono();
route.patch('/:groupId/automations', validate.json(UpdateGroupAutomationsSchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const input = c.req.valid('json') as UpdateGroupAutomations;
const useCase = new UpdateGroupAutomationsUseCase();
const result = await useCase.execute(c.req.param('groupId'), user.id, input);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,58 @@
import type { PrismaClient } from '@generated/prisma/client';
import type {
GroupAutomationsDto,
ProblemDetails,
Result,
UpdateGroupAutomations,
} from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { forbiddenProblem, notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
type UpdateGroupAutomationsDeps = { db?: Pick<PrismaClient, 'group'> };
/**
* Turns the group's weekly WhatsApp automations on or off. Only the owner can:
* the messages go out from their own WhatsApp.
*
* Turning one on does not require a linked WhatsApp. The weekly job skips
* groups whose owner has nothing usable, and the UI explains why.
*/
export class UpdateGroupAutomationsUseCase {
constructor(private readonly deps: UpdateGroupAutomationsDeps = {}) {}
async execute(
groupId: string,
userId: string,
input: UpdateGroupAutomations,
): Promise<Result<GroupAutomationsDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const group = await db.group.findUnique({
where: { id: groupId },
select: { id: true, createdById: true },
});
if (!group) return err(notFoundResourceProblem('Group', groupId));
if (group.createdById !== userId) {
return err(
forbiddenProblem({
detail: 'Solo quien creó el grupo puede cambiar sus automatizaciones.',
code: 'group_owner_required',
}),
);
}
const updated = await db.group.update({
where: { id: groupId },
data: {
...(input.autoPaymentReminders !== undefined
? { autoPaymentReminders: input.autoPaymentReminders }
: {}),
...(input.autoReengagement !== undefined ? { autoReengagement: input.autoReengagement } : {}),
},
select: { autoPaymentReminders: true, autoReengagement: true },
});
return ok(updated);
}
}

View File

@@ -0,0 +1,32 @@
import { Hono } from 'hono';
import { logger } from '@/logger';
import type { MessagingProviderId } from '../../providers/messaging-provider';
import { HandleWhatsappWebhook } from './use-case';
const PROVIDERS: Record<string, MessagingProviderId> = { openwa: 'OPENWA', kapso: 'KAPSO' };
/**
* Public endpoint (see `isPublicApiRequest`): the provider calls it, not the
* browser, so there is no session. Authenticity comes from the HMAC signature,
* checked over the raw body before anything is parsed. Answers fast: Kapso
* retries a delivery that is not acknowledged within 10 seconds.
*/
const route = new Hono();
route.post('/:provider', async (c) => {
const providerId = PROVIDERS[c.req.param('provider')];
if (!providerId) return c.body(null, 404);
const rawBody = await c.req.text();
const result = await new HandleWhatsappWebhook().execute(providerId, rawBody, c.req.raw.headers);
if (!result.ok) {
logger.warn({ provider: providerId, reason: result.error }, 'WhatsApp webhook rejected');
const status = result.error === 'invalid_signature' ? 401 : result.error === 'not_configured' ? 503 : 400;
return c.body(null, status);
}
return c.json({ received: true, duplicate: result.value.duplicate });
});
export default route;

View File

@@ -0,0 +1,138 @@
import type { OutboundMessageStatus, PrismaClient } from '@generated/prisma/client';
import type { Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { activateWhatsappAccount } from '../../lib/activate-account';
import { getMessagingProvider } from '../../providers';
import type {
MessageDeliveryStatus,
MessagingProvider,
MessagingProviderId,
NormalizedEvent,
} from '../../providers/messaging-provider';
type HandleWhatsappWebhookDeps = {
db?: Pick<PrismaClient, 'whatsappAccount' | 'whatsappWebhookEvent' | 'outboundMessage'>;
provider?: MessagingProvider;
now?: () => Date;
};
export type WebhookFailure = 'not_configured' | 'invalid_signature' | 'invalid_payload';
/** Prisma's unique-constraint violation: this delivery was already processed. */
const UNIQUE_VIOLATION = 'P2002';
/**
* States a message may move to from each state. Receipts can arrive out of
* order (a `read` before its `delivered`), so a late one never moves it back.
*/
const ADVANCES_FROM: Record<MessageDeliveryStatus, OutboundMessageStatus[]> = {
SENT: ['QUEUED'],
DELIVERED: ['QUEUED', 'SENT'],
READ: ['QUEUED', 'SENT', 'DELIVERED'],
FAILED: ['QUEUED', 'SENT', 'DELIVERED'],
};
/**
* Applies one provider webhook delivery: verify, dedupe, then reduce to the two
* things we track (the account's link and each message's delivery status).
*/
export class HandleWhatsappWebhook {
constructor(private readonly deps: HandleWhatsappWebhookDeps = {}) {}
async execute(
providerId: MessagingProviderId,
rawBody: string,
headers: Headers,
): Promise<Result<{ duplicate: boolean; applied: number }, WebhookFailure>> {
const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider(providerId);
if (!providerResult.ok) return err('not_configured');
const provider = providerResult.value;
const parsed = provider.parseWebhook(rawBody, headers);
if (!parsed.ok) return err(parsed.error);
const db = this.deps.db ?? prisma;
const dedupe = { provider: provider.id, dedupeKey: parsed.value.dedupeKey };
try {
await db.whatsappWebhookEvent.create({ data: dedupe });
} catch (error) {
if ((error as { code?: string }).code === UNIQUE_VIOLATION) {
return ok({ duplicate: true, applied: 0 });
}
throw error;
}
try {
let applied = 0;
for (const event of parsed.value.events) {
applied += (await this.apply(db, provider, event)) ? 1 : 0;
}
return ok({ duplicate: false, applied });
} catch (error) {
// Un-burn the key so the provider's retry gets another chance.
await db.whatsappWebhookEvent
.delete({ where: { provider_dedupeKey: dedupe } })
.catch(() => undefined);
throw error;
}
}
private async apply(
db: NonNullable<HandleWhatsappWebhookDeps['db']>,
provider: MessagingProvider,
event: NormalizedEvent,
): Promise<boolean> {
if (event.type === 'message_status') {
const result = await db.outboundMessage.updateMany({
where: {
provider: provider.id,
providerMessageId: event.providerMessageId,
status: { in: ADVANCES_FROM[event.status] },
},
data: {
status: event.status,
...(event.status === 'FAILED'
? { errorCode: event.errorCode ?? 'delivery_failed', errorMessage: event.errorMessage ?? null }
: {}),
},
});
return result.count > 0;
}
const account =
(await db.whatsappAccount.findFirst({
where: { provider: provider.id, externalId: event.externalId },
})) ??
(event.ownerId
? await db.whatsappAccount.findFirst({
where: { provider: provider.id, ownerId: event.ownerId, status: { not: 'DISCONNECTED' } },
})
: null);
if (!account) return false;
if (event.status === 'disconnected') {
if (account.status === 'DISCONNECTED') return false;
await db.whatsappAccount.update({ where: { id: account.id }, data: { status: 'DISCONNECTED' } });
return true;
}
const activated = await activateWhatsappAccount(
db,
provider,
account,
{
externalId: event.externalId,
displayPhoneNumber: event.displayPhoneNumber,
providerData: event.providerData,
},
this.deps.now?.() ?? new Date(),
);
if (!activated.ok) {
logger.warn({ provider: provider.id }, 'WhatsApp number already linked to another teacher');
}
return activated.ok;
}
}

View File

@@ -0,0 +1,2 @@
export { startWhatsappJobs } from './jobs';
export { default as whatsappRoutes } from './routes';

View File

@@ -0,0 +1,59 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { CountryCode, WhatsappMessageKind } from '@gruperly/shared';
import { countryCodeSchema } from '@gruperly/shared';
import type { MessagingProvider, WhatsappAccountRecord } from '../providers/messaging-provider';
export type EligibleGroup = { id: string; name: string };
export type EligibleAccount = {
account: WhatsappAccountRecord;
country: CountryCode | null;
groups: EligibleGroup[];
};
type AutomationFlag = 'autoPaymentReminders' | 'autoReengagement';
/**
* Groups with the automation on, bundled by owner, keeping only owners whose
* WhatsApp is linked with the active provider and ready to send this kind of
* message (for Kapso: the template is approved).
*/
export async function findEligibleAccounts(
db: Pick<PrismaClient, 'group'>,
provider: MessagingProvider,
flag: AutomationFlag,
kind: WhatsappMessageKind,
): Promise<EligibleAccount[]> {
const groups = await db.group.findMany({
where: {
[flag]: true,
owner: { whatsappAccount: { is: { provider: provider.id, status: 'ACTIVE' } } },
},
select: {
id: true,
name: true,
createdById: true,
owner: { select: { country: true, whatsappAccount: true } },
},
orderBy: { createdAt: 'asc' },
});
const byOwner = new Map<string, EligibleAccount>();
for (const group of groups) {
const account = group.owner.whatsappAccount;
if (!account) continue;
let entry = byOwner.get(group.createdById);
if (!entry) {
const country = countryCodeSchema.safeParse(group.owner.country);
entry = { account, country: country.success ? country.data : null, groups: [] };
byOwner.set(group.createdById, entry);
}
entry.groups.push({ id: group.id, name: group.name });
}
const eligible: EligibleAccount[] = [];
for (const entry of byOwner.values()) {
if ((await provider.readiness(entry.account, kind)) === 'ready') eligible.push(entry);
}
return eligible;
}

View File

@@ -0,0 +1,4 @@
export { startWhatsappJobs } from './schedule';
export { SendPaymentReminders } from './send-payment-reminders';
export { SendReengagementMessages } from './send-reengagement-messages';
export { SyncKapsoTemplates } from './sync-kapso-templates';

View File

@@ -0,0 +1,63 @@
import { logger } from '@/logger';
import { getActiveProviderId } from '../providers';
import { SendPaymentReminders } from './send-payment-reminders';
import { SendReengagementMessages } from './send-reengagement-messages';
import { SyncKapsoTemplates } from './sync-kapso-templates';
/** Mondays 13:00 UTC = 10:00 in Argentina (UTC-3, no DST). */
export const WEEKLY_MESSAGES_CRON = '0 13 * * 1';
const TEMPLATE_SYNC_CRON = '*/30 * * * *';
/**
* Registers the WhatsApp jobs. Called once from `server.ts`, with the same
* guards as `startMpJobs`: Bun's cron turns a rejected promise into an
* unhandledRejection (which exits the process), and `unref` keeps the jobs from
* holding the process alive.
*
* Reminders run before re-engagement: if the gateway rate limits the account
* halfway, the message about money is the one that already went out.
*/
export function startWhatsappJobs(): void {
Bun.cron(
WEEKLY_MESSAGES_CRON,
async () => {
try {
const reminders = await new SendPaymentReminders().execute();
logger.info(reminders, 'WhatsApp payment reminders finished');
} catch (error) {
logger.error({ err: error }, 'WhatsApp payment reminders failed');
}
try {
const reengagement = await new SendReengagementMessages().execute();
logger.info(reengagement, 'WhatsApp re-engagement messages finished');
} catch (error) {
logger.error({ err: error }, 'WhatsApp re-engagement messages failed');
}
},
{ tz: 'UTC' },
).unref();
if (activeProviderIs('KAPSO')) {
Bun.cron(
TEMPLATE_SYNC_CRON,
async () => {
try {
const totals = await new SyncKapsoTemplates().execute();
if (totals.checked > 0) logger.info(totals, 'Kapso template sync finished');
} catch (error) {
logger.error({ err: error }, 'Kapso template sync failed');
}
},
{ tz: 'UTC' },
).unref();
}
}
function activeProviderIs(id: 'OPENWA' | 'KAPSO'): boolean {
try {
return getActiveProviderId() === id;
} catch (error) {
logger.error({ err: error }, 'Invalid WHATSAPP_PROVIDER');
return false;
}
}

View File

@@ -0,0 +1,113 @@
import type { PrismaClient } from '@generated/prisma/client';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import {
addTotals,
type DispatchItem,
type DispatchTotals,
dispatchForAccount,
emptyTotals,
sendIntervalFromEnv,
sleep,
} from '../lib/dispatch';
import { formatAmount, formatDueDate } from '../lib/format';
import { getMessagingProvider } from '../providers';
import type { MessagingProvider } from '../providers/messaging-provider';
import { findEligibleAccounts } from './eligible-accounts';
/** Only charges that are due within the coming week (or already overdue). */
const DUE_HORIZON_MS = 7 * 24 * 60 * 60 * 1000;
type SendPaymentRemindersDeps = {
db?: Pick<PrismaClient, 'group' | 'payment' | 'outboundMessage'>;
provider?: MessagingProvider;
now?: Date;
intervalMs?: number;
sleep?: (ms: number) => Promise<void>;
};
/**
* Weekly reminder to members with a PENDING or OVERDUE charge that already has
* a Checkout Pro link, in groups whose owner turned the automation on.
*
* One reminder per member per week even with several open charges: the oldest
* one goes in the message (the rest are in the same Cobros screen anyway).
*/
export class SendPaymentReminders {
constructor(private readonly deps: SendPaymentRemindersDeps = {}) {}
async execute(): Promise<DispatchTotals> {
const providerResult = this.deps.provider ? { ok: true as const, value: this.deps.provider } : getMessagingProvider();
if (!providerResult.ok) {
logger.warn('WhatsApp is not configured; payment reminders skipped');
return emptyTotals();
}
const provider = providerResult.value;
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const totals = emptyTotals();
const accounts = await findEligibleAccounts(db, provider, 'autoPaymentReminders', 'PAYMENT_REMINDER');
for (const { account, country, groups } of accounts) {
const items: DispatchItem[] = [];
for (const group of groups) {
const payments = await db.payment.findMany({
where: {
groupId: group.id,
status: { in: ['PENDING', 'OVERDUE'] },
checkoutUrl: { not: null },
dueDate: { lte: new Date(now.getTime() + DUE_HORIZON_MS) },
attendee: { status: 'ACTIVE' },
},
select: {
id: true,
amount: true,
currency: true,
dueDate: true,
checkoutUrl: true,
attendee: { select: { id: true, fullName: true, phone: true, guardianPhone: true } },
},
orderBy: { dueDate: 'asc' },
});
const seen = new Set<string>();
for (const payment of payments) {
if (seen.has(payment.attendee.id) || !payment.checkoutUrl) continue;
seen.add(payment.attendee.id);
items.push({
groupId: group.id,
attendeeId: payment.attendee.id,
paymentId: payment.id,
rawPhone: payment.attendee.phone ?? payment.attendee.guardianPhone,
message: {
kind: 'PAYMENT_REMINDER',
studentName: payment.attendee.fullName,
groupName: group.name,
amount: formatAmount(Number(payment.amount.toString()), payment.currency, country),
dueDate: formatDueDate(payment.dueDate, country),
paymentLink: payment.checkoutUrl,
},
});
}
}
const result = await dispatchForAccount(
{
db,
provider,
now,
intervalMs: this.deps.intervalMs ?? sendIntervalFromEnv(),
sleep: this.deps.sleep ?? sleep,
},
account,
country,
items,
);
addTotals(totals, result);
}
return totals;
}
}

View File

@@ -0,0 +1,106 @@
import type { PrismaClient } from '@generated/prisma/client';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import {
findStudentsAtRisk,
type StudentsAtRiskDb,
} from '@/modules/analytics/features/get-students-at-risk/use-case';
import {
addTotals,
type DispatchItem,
type DispatchTotals,
dispatchForAccount,
emptyTotals,
sendIntervalFromEnv,
sleep,
} from '../lib/dispatch';
import { getMessagingProvider } from '../providers';
import type { MessagingProvider } from '../providers/messaging-provider';
import { findEligibleAccounts } from './eligible-accounts';
/** A member who got a re-engagement message is left alone for two weeks. */
export const REENGAGEMENT_COOLDOWN_MS = 14 * 24 * 60 * 60 * 1000;
type SendReengagementMessagesDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'outboundMessage'> & StudentsAtRiskDb;
provider?: MessagingProvider;
now?: Date;
intervalMs?: number;
sleep?: (ms: number) => Promise<void>;
};
/**
* Weekly re-engagement message to the members the teacher sees in "Alumnos en
* riesgo" (same rule, `findStudentsAtRisk`), in groups with the automation on.
*/
export class SendReengagementMessages {
constructor(private readonly deps: SendReengagementMessagesDeps = {}) {}
async execute(): Promise<DispatchTotals> {
const providerResult = this.deps.provider ? { ok: true as const, value: this.deps.provider } : getMessagingProvider();
if (!providerResult.ok) {
logger.warn('WhatsApp is not configured; re-engagement messages skipped');
return emptyTotals();
}
const provider = providerResult.value;
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const totals = emptyTotals();
const accounts = await findEligibleAccounts(db, provider, 'autoReengagement', 'REENGAGEMENT');
for (const { account, country, groups } of accounts) {
const items: DispatchItem[] = [];
for (const group of groups) {
const atRisk = await findStudentsAtRisk(db, group.id, now);
if (atRisk.length === 0) continue;
const ids = atRisk.map((student) => student.attendeeId);
const [recent, contacts] = await Promise.all([
db.outboundMessage.findMany({
where: {
kind: 'REENGAGEMENT',
attendeeId: { in: ids },
status: { in: ['SENT', 'DELIVERED', 'READ'] },
createdAt: { gte: new Date(now.getTime() - REENGAGEMENT_COOLDOWN_MS) },
},
select: { attendeeId: true },
}),
db.attendee.findMany({
where: { id: { in: ids } },
select: { id: true, phone: true, guardianPhone: true },
}),
]);
const coolingDown = new Set(recent.map((row) => row.attendeeId));
const phones = new Map(contacts.map((row) => [row.id, row.phone ?? row.guardianPhone]));
for (const student of atRisk) {
if (coolingDown.has(student.attendeeId)) continue;
items.push({
groupId: group.id,
attendeeId: student.attendeeId,
rawPhone: phones.get(student.attendeeId) ?? null,
message: { kind: 'REENGAGEMENT', studentName: student.fullName, groupName: group.name },
});
}
}
const result = await dispatchForAccount(
{
db,
provider,
now,
intervalMs: this.deps.intervalMs ?? sendIntervalFromEnv(),
sleep: this.deps.sleep ?? sleep,
},
account,
country,
items,
);
addTotals(totals, result);
}
return totals;
}
}

View File

@@ -0,0 +1,52 @@
import type { PrismaClient } from '@generated/prisma/client';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { KapsoProvider } from '../providers';
import { getKapsoConfig } from '../providers/kapso/config';
type SyncKapsoTemplatesDeps = {
db?: Pick<PrismaClient, 'whatsappAccount' | 'whatsappTemplate'>;
provider?: KapsoProvider;
};
export type SyncKapsoTemplatesResult = { checked: number; updated: number; failed: number };
/** How many templates each account should have (one per message kind). */
const EXPECTED_TEMPLATES = 2;
/**
* Meta reviews templates on its own schedule (up to ~24h) and Kapso documents
* no webhook for the verdict, so this polls the accounts that are still waiting.
* Accounts missing a template (a submission that failed) get it resubmitted.
*/
export class SyncKapsoTemplates {
constructor(private readonly deps: SyncKapsoTemplatesDeps = {}) {}
async execute(): Promise<SyncKapsoTemplatesResult> {
const db = this.deps.db ?? prisma;
const provider = this.deps.provider ?? new KapsoProvider(getKapsoConfig(), { db });
const totals: SyncKapsoTemplatesResult = { checked: 0, updated: 0, failed: 0 };
const accounts = await db.whatsappAccount.findMany({
where: { provider: 'KAPSO', status: 'ACTIVE' },
include: { templates: { select: { status: true } } },
});
for (const account of accounts) {
const missing = account.templates.length < EXPECTED_TEMPLATES;
const pending = account.templates.some((template) => template.status === 'PENDING');
if (!missing && !pending) continue;
totals.checked += 1;
try {
if (missing) await provider.onConnected(account);
totals.updated += await provider.syncTemplates(account);
} catch (error) {
totals.failed += 1;
logger.warn({ err: error }, 'Kapso template sync failed for an account');
}
}
return totals;
}
}

View File

@@ -0,0 +1,43 @@
import type { WhatsappAccountStatus } from '@gruperly/shared';
import { getActiveProviderId } from '../providers/active';
import type { MessagingProviderId } from '../providers/messaging-provider';
type AccountLike = { provider: MessagingProviderId; status: 'PENDING' | 'ACTIVE' | 'DISCONNECTED' };
/**
* A row linked through another gateway is useless after `WHATSAPP_PROVIDER`
* changes: the session or phone number id means nothing to the new one. It is
* kept (so nothing is lost if the switch is rolled back) and shown as
* "requires reconnect".
*/
export function toVisibleWhatsappStatus(
account: AccountLike | null,
activeProvider: MessagingProviderId = getActiveProviderId(),
): WhatsappAccountStatus {
if (!account) return 'none';
if (account.provider !== activeProvider) {
return account.status === 'DISCONNECTED' ? 'none' : 'requires_reconnect';
}
switch (account.status) {
case 'PENDING':
return 'pending';
case 'ACTIVE':
return 'active';
case 'DISCONNECTED':
return 'disconnected';
}
}
/** Whether automated messages can go out from this account at all. */
export function isWhatsappAccountUsable(
account: AccountLike | null,
activeProvider?: MessagingProviderId,
): boolean {
if (!account) return false;
try {
return toVisibleWhatsappStatus(account, activeProvider) === 'active';
} catch {
// A bad WHATSAPP_PROVIDER must not break the screens that only ask "linked?".
return false;
}
}

View File

@@ -0,0 +1,74 @@
import type { Prisma, PrismaClient } from '@generated/prisma/client';
import { logger } from '@/logger';
import type { MessagingProvider, WhatsappAccountRecord } from '../providers/messaging-provider';
export type WhatsappAccountDb = Pick<PrismaClient, 'whatsappAccount'>;
/** Prisma's unique-constraint violation (here: the number is someone else's). */
const UNIQUE_VIOLATION = 'P2002';
export type ActivationInput = {
externalId?: string | null;
displayPhoneNumber?: string | null;
providerData?: Record<string, string> | null;
};
/**
* Marks the teacher's account ACTIVE and runs the provider's `onConnected`.
*
* The same activation arrives through three doors (the status poll, the Kapso
* callback and the webhooks) and possibly more than once; an account that is
* already ACTIVE is left alone so `onConnected` does not run on every poll.
*/
export async function activateWhatsappAccount(
db: WhatsappAccountDb,
provider: MessagingProvider,
account: WhatsappAccountRecord,
input: ActivationInput,
now: Date,
): Promise<{ ok: true; account: WhatsappAccountRecord } | { ok: false; reason: 'number_in_use' }> {
if (account.status === 'ACTIVE' && account.provider === provider.id) {
return { ok: true, account };
}
let updated: WhatsappAccountRecord;
try {
updated = await db.whatsappAccount.update({
where: { id: account.id },
data: {
status: 'ACTIVE',
connectedAt: now,
...(input.externalId ? { externalId: input.externalId } : {}),
...(input.displayPhoneNumber !== undefined ? { displayPhoneNumber: input.displayPhoneNumber } : {}),
...(input.providerData
? { providerData: mergeProviderData(account.providerData, input.providerData) }
: {}),
},
});
} catch (error) {
if ((error as { code?: string }).code === UNIQUE_VIOLATION) {
return { ok: false, reason: 'number_in_use' };
}
throw error;
}
if (provider.onConnected) {
try {
await provider.onConnected(updated);
} catch (error) {
// The account is linked either way; templates and webhooks are retried
// the next time the teacher links, and the sync job reports their state.
logger.error({ err: error, provider: provider.id }, 'WhatsApp post-connection setup failed');
}
}
return { ok: true, account: updated };
}
export function mergeProviderData(
current: unknown,
next: Record<string, string> | null | undefined,
): Prisma.InputJsonObject {
const base = current && typeof current === 'object' && !Array.isArray(current) ? current : {};
return { ...(base as Record<string, string>), ...(next ?? {}) };
}

View File

@@ -0,0 +1,171 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { CountryCode, WhatsappMessageKind } from '@gruperly/shared';
import { toWhatsappE164 } from '@gruperly/shared';
import { logger } from '@/logger';
import type {
MessagingProvider,
WhatsappAccountRecord,
WhatsappMessage,
} from '../providers/messaging-provider';
import { isoWeekKey } from './period';
export type DispatchDb = Pick<PrismaClient, 'outboundMessage'>;
/** One message the weekly job wants to send to one member. */
export type DispatchItem = {
groupId: string;
attendeeId: string;
paymentId?: string | null;
/** The member's phone, or their guardian's, as stored. */
rawPhone: string | null;
message: WhatsappMessage;
};
export type DispatchTotals = { sent: number; skipped: number; failed: number };
export type DispatcherDeps = {
db: DispatchDb;
provider: MessagingProvider;
now: Date;
/** Pause between two sends from the same account. */
intervalMs: number;
sleep: (ms: number) => Promise<void>;
};
/** Prisma's unique-constraint violation: already handled this week. */
const UNIQUE_VIOLATION = 'P2002';
export const DEFAULT_SEND_INTERVAL_MS = 5_000;
export function sendIntervalFromEnv(): number {
const value = Number(process.env.WHATSAPP_SEND_INTERVAL_MS);
return Number.isFinite(value) && value >= 0 ? value : DEFAULT_SEND_INTERVAL_MS;
}
export const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
export function emptyTotals(): DispatchTotals {
return { sent: 0, skipped: 0, failed: 0 };
}
export function addTotals(into: DispatchTotals, from: DispatchTotals): DispatchTotals {
into.sent += from.sent;
into.skipped += from.skipped;
into.failed += from.failed;
return into;
}
/**
* Sends one account's messages, one after the other.
*
* Every message is first written to `outbound_messages` (QUEUED) and only then
* handed to the provider: the unique (kind, attendee, week) makes a second run
* of the job skip it, and the row id doubles as the provider's idempotency key,
* so a retried HTTP call cannot deliver twice either.
*
* Sends are paced (`intervalMs`) and stop for the whole account when the
* provider says it is rate limited: hammering an unofficial gateway is how a
* number gets banned. What was not sent stays for next week.
*/
export async function dispatchForAccount(
deps: DispatcherDeps,
account: WhatsappAccountRecord,
country: CountryCode | null,
items: DispatchItem[],
): Promise<DispatchTotals> {
const totals = emptyTotals();
const periodKey = isoWeekKey(deps.now);
let sentBefore = false;
for (const item of items) {
const base = {
ownerId: account.ownerId,
groupId: item.groupId,
attendeeId: item.attendeeId,
paymentId: item.paymentId ?? null,
kind: item.message.kind as WhatsappMessageKind,
provider: deps.provider.id,
periodKey,
};
const e164 = item.rawPhone ? toWhatsappE164(item.rawPhone, country) : null;
if (!e164) {
await record(deps.db, { ...base, toPhone: item.rawPhone ?? '', status: 'SKIPPED', errorCode: 'invalid_phone' });
totals.skipped += 1;
continue;
}
const recipient = await deps.provider.resolveRecipient(account, e164);
if (!recipient.ok) {
if (recipient.code === 'no_whatsapp') {
await record(deps.db, { ...base, toPhone: e164, status: 'SKIPPED', errorCode: 'no_whatsapp' });
totals.skipped += 1;
} else {
// No row: the gateway could not tell, so next week tries again.
totals.failed += 1;
}
continue;
}
const row = await record(deps.db, { ...base, toPhone: e164, status: 'QUEUED' });
if (!row) {
totals.skipped += 1;
continue;
}
if (sentBefore && deps.intervalMs > 0) await deps.sleep(deps.intervalMs);
sentBefore = true;
const outcome = await deps.provider.send(account, recipient.to, item.message, row.id);
if (outcome.ok) {
await deps.db.outboundMessage.update({
where: { id: row.id },
data: { status: 'SENT', providerMessageId: outcome.providerMessageId, sentAt: new Date() },
});
totals.sent += 1;
continue;
}
if (outcome.rateLimitedForMs !== undefined) {
// Never sent: drop the row so this member is not marked as handled.
await deps.db.outboundMessage.delete({ where: { id: row.id } });
totals.skipped += 1;
logger.warn(
{ provider: deps.provider.id, retryInMs: outcome.rateLimitedForMs },
'WhatsApp account rate limited; stopping its sends for this run',
);
break;
}
await deps.db.outboundMessage.update({
where: { id: row.id },
data: { status: 'FAILED', errorCode: outcome.code, errorMessage: outcome.message.slice(0, 500) },
});
totals.failed += 1;
}
return totals;
}
type RecordInput = {
ownerId: string;
groupId: string;
attendeeId: string;
paymentId: string | null;
kind: WhatsappMessageKind;
provider: MessagingProvider['id'];
periodKey: string;
toPhone: string;
status: 'QUEUED' | 'SKIPPED';
errorCode?: string;
};
/** Creates the log row, or returns null when this member was already handled this week. */
async function record(db: DispatchDb, data: RecordInput): Promise<{ id: string } | null> {
try {
return await db.outboundMessage.create({ data, select: { id: true } });
} catch (error) {
if ((error as { code?: string }).code === UNIQUE_VIOLATION) return null;
throw error;
}
}

View File

@@ -0,0 +1,50 @@
import type { CountryCode } from '@gruperly/shared';
import { DEFAULT_COUNTRY } from '@gruperly/shared';
/* Amounts and dates go inside a WhatsApp message, so they are formatted the way
people in the teacher's country write them (the student is there too). */
const LOCALES: Record<CountryCode, string> = {
AR: 'es-AR',
BR: 'pt-BR',
CL: 'es-CL',
CO: 'es-CO',
MX: 'es-MX',
PE: 'es-PE',
UY: 'es-UY',
};
const TIME_ZONES: Record<CountryCode, string> = {
AR: 'America/Argentina/Buenos_Aires',
BR: 'America/Sao_Paulo',
CL: 'America/Santiago',
CO: 'America/Bogota',
MX: 'America/Mexico_City',
PE: 'America/Lima',
UY: 'America/Montevideo',
};
/** `25000` ARS → `$ 25.000`; cents only when there are any. */
export function formatAmount(
amount: number,
currency: string,
country: CountryCode | null | undefined,
): string {
const hasCents = !Number.isInteger(amount);
return new Intl.NumberFormat(LOCALES[country ?? DEFAULT_COUNTRY], {
style: 'currency',
currency,
minimumFractionDigits: hasCents ? 2 : 0,
maximumFractionDigits: 2,
}).format(amount);
}
/** Due date as day/month in the teacher's country, e.g. `10/11`. */
export function formatDueDate(date: Date, country: CountryCode | null | undefined): string {
const resolved = country ?? DEFAULT_COUNTRY;
return new Intl.DateTimeFormat(LOCALES[resolved], {
day: '2-digit',
month: '2-digit',
timeZone: TIME_ZONES[resolved],
}).format(date);
}

View File

@@ -0,0 +1,24 @@
import { createHmac, timingSafeEqual } from 'node:crypto';
/**
* Constant-time check of an HMAC-SHA256 hex signature computed over the raw
* request body. It has to be the raw text: re-serializing the parsed JSON can
* reorder keys or change whitespace and the signature would never match.
*
* `prefix` covers providers that send `sha256=<hex>` (OpenWA) instead of the
* bare hex (Kapso).
*/
export function verifyHmacSha256(
rawBody: string,
signature: string | null | undefined,
secret: string,
prefix = '',
): boolean {
if (typeof signature !== 'string' || !signature) return false;
const expected = prefix + createHmac('sha256', secret).update(rawBody).digest('hex');
const received = Buffer.from(signature.trim());
const wanted = Buffer.from(expected);
// `timingSafeEqual` throws on a length mismatch, so a forged short header fails first.
return received.length === wanted.length && timingSafeEqual(received, wanted);
}

View File

@@ -0,0 +1,16 @@
/**
* ISO-8601 week of a date in UTC, e.g. `2026-W43`.
*
* It is the `periodKey` of an automated message: one message of each kind per
* member per week, enforced by a unique index, so a job that runs twice (two
* API instances, a manual re-run) cannot write to the same person twice.
*/
export function isoWeekKey(date: Date): string {
const day = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
// Thursday of the same week decides the ISO year.
const weekday = day.getUTCDay() || 7;
day.setUTCDate(day.getUTCDate() + 4 - weekday);
const yearStart = new Date(Date.UTC(day.getUTCFullYear(), 0, 1));
const week = Math.ceil(((day.getTime() - yearStart.getTime()) / 86_400_000 + 1) / 7);
return `${day.getUTCFullYear()}-W${String(week).padStart(2, '0')}`;
}

View File

@@ -0,0 +1,33 @@
import type { WhatsappMessage } from '../providers/messaging-provider';
/**
* The Spanish copy of the automated messages, as free text.
*
* OpenWA sends exactly this. Kapso cannot (Meta only allows approved templates
* outside the 24h window), but its template bodies in `providers/kapso/templates.ts`
* are written from these same sentences: if one changes, change the other and
* submit a new template version.
*/
export function renderMessage(message: WhatsappMessage): string {
const firstName = firstNameOf(message.studentName);
switch (message.kind) {
case 'PAYMENT_REMINDER':
return (
`¡Hola ${firstName}! Te recordamos el pago de ${message.groupName} ` +
`por ${message.amount}, con vencimiento el ${message.dueDate}. ` +
`Podés pagarlo desde este link: ${message.paymentLink}`
);
case 'REENGAGEMENT':
// Same copy the teacher sends by hand from "Alumnos en riesgo".
return (
`¡Hola ${firstName}! 👋 Te extrañamos en ${message.groupName}. ` +
'Notamos que no asististe a las últimas clases y queremos que vuelvas. ' +
'Si tenés algún problema con tus horarios o tu membresía, escribinos y lo resolvemos juntos.'
);
}
}
export function firstNameOf(fullName: string): string {
return fullName.trim().split(/\s+/)[0] ?? fullName;
}

View File

@@ -0,0 +1,19 @@
import type { MessagingProviderId } from './messaging-provider';
const PROVIDERS: Record<string, MessagingProviderId> = {
openwa: 'OPENWA',
kapso: 'KAPSO',
};
/**
* The gateway this deployment sends through (`WHATSAPP_PROVIDER`, default
* `openwa`). An unknown value is a deployment mistake and fails loudly.
*/
export function getActiveProviderId(): MessagingProviderId {
const raw = process.env.WHATSAPP_PROVIDER?.trim().toLowerCase() || 'openwa';
const id = PROVIDERS[raw];
if (!id) {
throw new Error(`Unknown WHATSAPP_PROVIDER "${raw}". Use one of: ${Object.keys(PROVIDERS).join(', ')}.`);
}
return id;
}

View File

@@ -0,0 +1,40 @@
import type { ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { whatsappNotConfiguredProblem } from '@/http/problem-builders';
import { logger } from '@/logger';
import { getActiveProviderId } from './active';
import { KapsoProvider } from './kapso';
import { getKapsoConfig } from './kapso/config';
import type { MessagingProvider, MessagingProviderId } from './messaging-provider';
import { OpenWaProvider } from './openwa';
import { getOpenWaConfig } from './openwa/config';
export { getActiveProviderId } from './active';
export { KapsoProvider } from './kapso';
export type * from './messaging-provider';
export { OpenWaProvider } from './openwa';
/**
* The one place that maps a provider id to its adapter. Swapping gateways means
* changing `WHATSAPP_PROVIDER`; adding one means a new `providers/<name>/` that
* implements `MessagingProvider` plus a case here.
*
* A missing variable is answered as `whatsapp_not_configured` (503) instead of
* crashing, so the rest of the app (and the skippable onboarding step) keeps
* working on a deployment without WhatsApp.
*/
export function getMessagingProvider(
id?: MessagingProviderId,
): Result<MessagingProvider, ProblemDetails> {
try {
switch (id ?? getActiveProviderId()) {
case 'OPENWA':
return ok(new OpenWaProvider(getOpenWaConfig()));
case 'KAPSO':
return ok(new KapsoProvider(getKapsoConfig()));
}
} catch (error) {
logger.error({ err: error }, 'WhatsApp messaging is not configured');
return err(whatsappNotConfiguredProblem());
}
}

View File

@@ -0,0 +1,47 @@
export type KapsoConfig = {
/** `https://api.kapso.ai` unless overridden. */
apiUrl: string;
/** Project API key, sent as `X-API-Key`. */
apiKey: string;
/** Public URL of `/api/v1/whatsapp/callback` (setup link redirects). */
callbackUrl: string;
/** Public URL of `/api/v1/whatsapp/webhooks/kapso`. */
webhookUrl: string;
/** HMAC secret for the project webhook and every per-number webhook. */
webhookSecret: string;
};
const DEFAULT_API_URL = 'https://api.kapso.ai';
/**
* Reads the Kapso settings. Throws on a deployment mistake, naming the missing
* variables (never their values), like `getMpOAuthConfig()`.
*/
export function getKapsoConfig(): KapsoConfig {
const missing: string[] = [];
const read = (name: string): string => {
const value = process.env[name]?.trim();
if (!value) {
missing.push(name);
return '';
}
return value;
};
const apiKey = read('KAPSO_API_KEY');
const callbackUrl = read('KAPSO_CALLBACK_URL');
const webhookUrl = read('KAPSO_WEBHOOK_URL');
const webhookSecret = read('KAPSO_WEBHOOK_SECRET');
if (missing.length > 0) {
throw new Error(`Missing Kapso environment variables: ${missing.join(', ')}. See .env.example.`);
}
return {
apiUrl: (process.env.KAPSO_API_URL?.trim() || DEFAULT_API_URL).replace(/\/+$/, ''),
apiKey,
callbackUrl,
webhookUrl,
webhookSecret,
};
}

View File

@@ -0,0 +1,210 @@
import type { KapsoConfig } from './config';
/**
* Thin client for Kapso: the Platform API (customers, setup links, phone
* numbers, webhooks) and the Meta proxy (templates, messages). Plain `fetch`
* on purpose: `@kapso/whatsapp-cloud-api` brings its own Zod, and this repo
* pins zod 3.24 (see AGENTS.md).
*/
export const META_GRAPH_VERSION = 'v24.0';
export class KapsoApiError extends Error {
constructor(
readonly status: number,
/** Meta error code (e.g. `131047`) or Kapso's error string when there is one. */
readonly code: string | null,
) {
super(`Kapso request failed with ${status}${code ? ` (${code})` : ''}`);
this.name = 'KapsoApiError';
}
}
export type KapsoFetch = (input: string, init?: RequestInit) => Promise<Response>;
export type KapsoPhoneNumber = {
phone_number_id: string;
business_account_id: string | null;
display_phone_number: string | null;
customer_id: string | null;
status?: string | null;
};
export type MetaTemplate = {
id: string;
name: string;
language?: string;
status: string;
category?: string;
rejected_reason?: string | null;
};
export type MetaTemplateComponent = {
type: 'BODY';
text: string;
example?: { body_text_named_params: { param_name: string; example: string }[] };
};
export type MetaTemplateDefinition = {
name: string;
language: string;
category: 'UTILITY' | 'MARKETING';
parameter_format: 'NAMED';
components: MetaTemplateComponent[];
};
const REQUEST_TIMEOUT_MS = 30_000;
export class KapsoClient {
constructor(
private readonly config: KapsoConfig,
private readonly fetchFn: KapsoFetch = (input, init) => fetch(input, init),
) {}
async createCustomer(input: { name: string; externalId: string }): Promise<{ id: string }> {
const response = await this.request<{ data: { id: string } }>('POST', '/platform/v1/customers', {
customer: { name: input.name, external_customer_id: input.externalId },
});
return response.data;
}
async createSetupLink(
customerId: string,
input: { successRedirectUrl: string; failureRedirectUrl: string },
): Promise<{ id: string; url: string }> {
const response = await this.request<{ data: { id: string; url: string } }>(
'POST',
`/platform/v1/customers/${encodeURIComponent(customerId)}/setup_links`,
{
setup_link: {
success_redirect_url: input.successRedirectUrl,
failure_redirect_url: input.failureRedirectUrl,
allowed_connection_types: ['coexistence', 'dedicated'],
// The teacher pays Meta from their own Business account. Fixed at
// creation: Kapso cannot change it on an existing link.
meta_billing_mode: 'customer_managed',
language: 'es',
},
},
);
return response.data;
}
async getPhoneNumber(phoneNumberId: string): Promise<KapsoPhoneNumber> {
const response = await this.request<{ data: KapsoPhoneNumber }>(
'GET',
`/platform/v1/whatsapp/phone_numbers/${encodeURIComponent(phoneNumberId)}`,
);
return response.data;
}
async createPhoneWebhook(
phoneNumberId: string,
input: { url: string; secret: string; events: string[] },
): Promise<{ id: string }> {
const response = await this.request<{ data: { id: string } }>(
'POST',
`/platform/v1/whatsapp/phone_numbers/${encodeURIComponent(phoneNumberId)}/webhooks`,
{
whatsapp_webhook: {
url: input.url,
secret_key: input.secret,
events: input.events,
kind: 'kapso',
active: true,
},
},
);
return response.data;
}
createTemplate(
businessAccountId: string,
template: MetaTemplateDefinition,
): Promise<{ id: string; status: string; category?: string }> {
return this.request(
'POST',
`/meta/whatsapp/${META_GRAPH_VERSION}/${encodeURIComponent(businessAccountId)}/message_templates`,
template,
);
}
async listTemplates(businessAccountId: string, name?: string): Promise<MetaTemplate[]> {
const query = name ? `?name=${encodeURIComponent(name)}` : '';
const response = await this.request<{ data?: MetaTemplate[] }>(
'GET',
`/meta/whatsapp/${META_GRAPH_VERSION}/${encodeURIComponent(businessAccountId)}/message_templates${query}`,
);
return response.data ?? [];
}
async sendTemplate(
phoneNumberId: string,
input: {
to: string;
name: string;
language: string;
parameters: { name: string; text: string }[];
},
): Promise<{ messageId: string }> {
const response = await this.request<{ messages?: { id: string }[] }>(
'POST',
`/meta/whatsapp/${META_GRAPH_VERSION}/${encodeURIComponent(phoneNumberId)}/messages`,
{
messaging_product: 'whatsapp',
to: input.to,
type: 'template',
template: {
name: input.name,
language: { code: input.language },
components: [
{
type: 'body',
parameters: input.parameters.map((parameter) => ({
type: 'text',
parameter_name: parameter.name,
text: parameter.text,
})),
},
],
},
},
);
const messageId = response.messages?.[0]?.id;
if (!messageId) throw new KapsoApiError(502, 'missing_message_id');
return { messageId };
}
private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
const response = await this.fetchFn(`${this.config.apiUrl}${path}`, {
method,
headers: {
'X-API-Key': this.config.apiKey,
Accept: 'application/json',
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as {
error?: { code?: unknown; error_subcode?: unknown } | string;
code?: unknown;
} | null;
throw new KapsoApiError(response.status, errorCode(payload));
}
if (response.status === 204) return undefined as T;
return (await response.json()) as T;
}
}
function errorCode(
payload: { error?: { code?: unknown } | string; code?: unknown } | null,
): string | null {
if (!payload) return null;
if (typeof payload.error === 'string') return payload.error;
const code = payload.error?.code ?? payload.code;
return code === undefined || code === null ? null : String(code);
}

View File

@@ -0,0 +1,436 @@
import type { PrismaClient } from '@generated/prisma/client';
import type {
ProblemDetails,
Result,
WhatsappCallbackReason,
WhatsappMessageKind,
WhatsappReadiness,
} from '@gruperly/shared';
import { err, ok, whatsappMessageKindSchema } from '@gruperly/shared';
import { whatsappProviderErrorProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { verifyHmacSha256 } from '../../lib/hmac';
import type {
CompletedConnection,
ConnectionSnapshot,
MessageDeliveryStatus,
MessagingProvider,
NormalizedEvent,
ParsedWebhook,
RecipientResolution,
SendOutcome,
StartConnectionContext,
StartConnectionResult,
WebhookParseError,
WhatsappAccountRecord,
WhatsappMessage,
} from '../messaging-provider';
import type { KapsoConfig } from './config';
import { KapsoApiError, KapsoClient, type KapsoFetch } from './http';
import { KAPSO_TEMPLATES, TEMPLATE_LANGUAGE, toTemplateStatus } from './templates';
/** Message events each connected number reports to our webhook. */
export const KAPSO_MESSAGE_EVENTS = [
'whatsapp.message.sent',
'whatsapp.message.delivered',
'whatsapp.message.read',
'whatsapp.message.failed',
];
/**
* Errors where repeating the same send cannot help: 402 out of credits (only
* with partner billing), 131047 outside the 24h window (templates avoid it),
* the student opting out of marketing, or a number/account mismatch.
*/
const PERMANENT_SEND_ERRORS = new Set([
'131047',
'131050',
'marketing_preference_stopped',
'messaging_account_mismatch',
'insufficient_credits',
]);
export type KapsoProviderData = {
customerId?: string;
setupLinkId?: string;
businessAccountId?: string;
webhookId?: string;
};
type KapsoProviderDeps = {
db?: Pick<PrismaClient, 'whatsappAccount' | 'whatsappTemplate'>;
fetch?: KapsoFetch;
};
/**
* Kapso, on top of Meta's official WhatsApp Cloud API.
*
* Linking is a hosted flow: we create a Kapso customer for the teacher, send
* them to a setup link (Facebook login + number verification at Meta) and
* Kapso redirects back to our callback. Messages outside a conversation must
* be approved templates, which Meta reviews per WhatsApp Business Account, so
* a freshly linked account sends nothing until its templates are APPROVED.
*/
export class KapsoProvider implements MessagingProvider {
readonly id = 'KAPSO' as const;
private readonly client: KapsoClient;
constructor(
private readonly config: KapsoConfig,
private readonly deps: KapsoProviderDeps = {},
) {
this.client = new KapsoClient(config, deps.fetch);
}
private get db() {
return this.deps.db ?? prisma;
}
async startConnection(
context: StartConnectionContext,
): Promise<Result<StartConnectionResult, ProblemDetails>> {
const previous = context.account?.provider === 'KAPSO' ? readData(context.account.providerData) : {};
try {
// One Kapso customer per teacher, reused when they link again.
const customerId =
previous.customerId ??
(await this.client.createCustomer({ name: context.ownerName, externalId: context.ownerId })).id;
const returnUrl = `${this.config.callbackUrl}?returnTo=${context.returnTo}`;
const link = await this.client.createSetupLink(customerId, {
successRedirectUrl: returnUrl,
failureRedirectUrl: returnUrl,
});
return ok({
start: { type: 'redirect', url: link.url },
externalId: null,
providerData: { customerId, setupLinkId: link.id },
});
} catch (error) {
logger.error({ err: describe(error) }, 'Kapso could not create a setup link');
return err(whatsappProviderErrorProblem());
}
}
async refreshConnection(
account: WhatsappAccountRecord,
): Promise<Result<ConnectionSnapshot, ProblemDetails>> {
// A Kapso linking happens at Meta; there is no QR to refresh. Until the
// callback (or the `phone_number.created` webhook) lands it is just pending.
if (account.status === 'ACTIVE') {
return ok({ state: 'active', displayPhoneNumber: account.displayPhoneNumber });
}
return ok({ state: 'pending', qrCode: null });
}
async completeRedirect(
account: WhatsappAccountRecord,
query: Record<string, string | undefined>,
): Promise<Result<CompletedConnection, WhatsappCallbackReason>> {
const data = readData(account.providerData);
// Nothing in this query is trusted: anyone can type a URL. The setup link
// has to be the one we created for this teacher, and Kapso itself has to
// confirm that the number belongs to this teacher's customer.
if (!query.setup_link_id || query.setup_link_id !== data.setupLinkId || !data.customerId) {
return err('invalid_setup');
}
if (query.error_code || (query.status && query.status !== 'completed')) {
return err('setup_failed');
}
if (!query.phone_number_id) return err('invalid_setup');
try {
const phone = await this.client.getPhoneNumber(query.phone_number_id);
if (phone.customer_id !== data.customerId) return err('invalid_setup');
return ok({
externalId: phone.phone_number_id,
displayPhoneNumber: formatPhone(phone.display_phone_number),
providerData: {
...compact(data),
...(phone.business_account_id ? { businessAccountId: phone.business_account_id } : {}),
},
});
} catch (error) {
logger.error({ err: describe(error) }, 'Kapso phone number lookup failed');
return err('provider_error');
}
}
async disconnect(): Promise<Result<void, ProblemDetails>> {
// The number stays connected to the teacher's WhatsApp Business Account at
// Meta (they manage it there); unlinking here only stops Gruperly from
// sending through it. The Kapso customer is kept for a later relink.
return ok(undefined);
}
/**
* Subscribes our webhook to the number and submits the templates. Safe to run
* again: what already exists is skipped.
*/
async onConnected(account: WhatsappAccountRecord): Promise<void> {
if (!account.externalId) return;
const data = readData(account.providerData);
if (!data.businessAccountId) {
const phone = await this.client.getPhoneNumber(account.externalId);
if (phone.business_account_id) data.businessAccountId = phone.business_account_id;
}
if (!data.webhookId) {
try {
const webhook = await this.client.createPhoneWebhook(account.externalId, {
url: this.config.webhookUrl,
secret: this.config.webhookSecret,
events: KAPSO_MESSAGE_EVENTS,
});
data.webhookId = webhook.id;
} catch (error) {
// Only delivery receipts depend on it; sending still works.
logger.warn({ err: describe(error) }, 'Kapso per-number webhook registration failed');
}
}
await this.db.whatsappAccount.update({
where: { id: account.id },
data: { providerData: compact(data) },
});
if (data.businessAccountId) {
await this.submitTemplates(account.id, data.businessAccountId);
}
}
async readiness(
account: WhatsappAccountRecord,
kind: WhatsappMessageKind,
): Promise<WhatsappReadiness> {
if (account.status !== 'ACTIVE') return 'blocked';
const template = await this.db.whatsappTemplate.findUnique({
where: { accountId_kind: { accountId: account.id, kind } },
});
if (!template || template.status === 'PENDING') return 'pending';
return template.status === 'APPROVED' ? 'ready' : 'blocked';
}
async resolveRecipient(_account: WhatsappAccountRecord, e164: string): Promise<RecipientResolution> {
// The Cloud API takes the E.164 digits; it reports unknown numbers on send.
return { ok: true, to: e164.replace(/\D/g, '') };
}
async send(
account: WhatsappAccountRecord,
to: string,
message: WhatsappMessage,
): Promise<SendOutcome> {
if (!account.externalId) {
return { ok: false, retryable: false, code: 'no_phone_number', message: 'Account has no number' };
}
const spec = KAPSO_TEMPLATES[message.kind];
try {
const response = await this.client.sendTemplate(account.externalId, {
to,
name: spec.definition.name,
language: TEMPLATE_LANGUAGE,
parameters: spec.parameters(message),
});
return { ok: true, providerMessageId: response.messageId };
} catch (error) {
if (error instanceof KapsoApiError) {
const permanent =
error.status === 402 ||
(error.code !== null && PERMANENT_SEND_ERRORS.has(error.code)) ||
(error.status >= 400 && error.status < 500 && error.status !== 409 && error.status !== 429);
return {
ok: false,
retryable: !permanent,
...(error.status === 429 ? { rateLimitedForMs: 60_000 } : {}),
code: error.code ?? `http_${error.status}`,
message: error.message,
};
}
return { ok: false, retryable: true, code: 'network_error', message: describe(error).message };
}
}
parseWebhook(rawBody: string, headers: Headers): Result<ParsedWebhook, WebhookParseError> {
if (!verifyHmacSha256(rawBody, headers.get('X-Webhook-Signature'), this.config.webhookSecret)) {
return err('invalid_signature');
}
let payload: unknown;
try {
payload = JSON.parse(rawBody);
} catch {
return err('invalid_payload');
}
const dedupeKey = headers.get('X-Idempotency-Key');
if (!dedupeKey) return err('invalid_payload');
// Batched deliveries (`X-Webhook-Batch`) carry the events in `data[]`.
const headerEvent = headers.get('X-Webhook-Event');
const items = isRecord(payload) && Array.isArray(payload.data) ? payload.data : [payload];
const events = items.flatMap((item) => (isRecord(item) ? toEvents(item, headerEvent) : []));
return ok({ dedupeKey, events });
}
/** Pulls Meta's verdict for the account's pending templates. */
async syncTemplates(account: WhatsappAccountRecord): Promise<number> {
const data = readData(account.providerData);
if (!data.businessAccountId) return 0;
const pending = await this.db.whatsappTemplate.findMany({
where: { accountId: account.id, status: 'PENDING' },
});
let updated = 0;
for (const template of pending) {
const [remote] = await this.client.listTemplates(data.businessAccountId, template.name);
if (!remote) continue;
const status = toTemplateStatus(remote.status);
if (status === template.status) continue;
await this.db.whatsappTemplate.update({
where: { id: template.id },
data: { status, metaTemplateId: remote.id, rejectedReason: remote.rejected_reason ?? null },
});
updated += 1;
}
return updated;
}
private async submitTemplates(accountId: string, businessAccountId: string): Promise<void> {
for (const kind of whatsappMessageKindSchema.options) {
const existing = await this.db.whatsappTemplate.findUnique({
where: { accountId_kind: { accountId, kind } },
});
if (existing) continue;
const { definition } = KAPSO_TEMPLATES[kind];
let remote: { id: string; status: string } | null = null;
try {
remote = await this.client.createTemplate(businessAccountId, definition);
} catch (error) {
// Relinking the same Business Account: the template is already there.
const [found] = await this.client.listTemplates(businessAccountId, definition.name).catch(() => []);
if (!found) {
logger.error({ err: describe(error), kind }, 'Kapso template submission failed');
continue;
}
remote = found;
}
await this.db.whatsappTemplate.create({
data: {
accountId,
kind,
name: definition.name,
language: definition.language,
metaTemplateId: remote.id,
status: toTemplateStatus(remote.status),
},
});
}
}
}
const MESSAGE_STATUSES: Record<string, MessageDeliveryStatus> = {
'whatsapp.message.sent': 'SENT',
'whatsapp.message.delivered': 'DELIVERED',
'whatsapp.message.read': 'READ',
'whatsapp.message.failed': 'FAILED',
};
function toEvents(item: Record<string, unknown>, headerEvent: string | null): NormalizedEvent[] {
const event = headerEvent ?? (typeof item.event === 'string' ? item.event : null);
if (!event) return [];
const phoneNumberId = stringAt(item, 'phone_number_id') ?? stringAt(item, 'phone_number', 'phone_number_id');
if (event === 'whatsapp.phone_number.created') {
if (!phoneNumberId) return [];
const businessAccountId = stringAt(item, 'business_account_id');
return [
{
type: 'connection',
externalId: phoneNumberId,
ownerId: stringAt(item, 'customer', 'external_id') ?? undefined,
status: 'active',
displayPhoneNumber: formatPhone(stringAt(item, 'display_phone_number')),
providerData: businessAccountId ? { businessAccountId } : null,
},
];
}
if (
event === 'whatsapp.phone_number.deleted' ||
event === 'whatsapp.phone_number.disconnected' ||
event === 'whatsapp.phone_number.offboarded'
) {
return phoneNumberId ? [{ type: 'connection', externalId: phoneNumberId, status: 'disconnected' }] : [];
}
const status = MESSAGE_STATUSES[event];
const messageId = stringAt(item, 'message', 'id');
if (!status || !messageId) return [];
const errors = (isRecord(item.message) && isRecord(item.message.kapso) && Array.isArray(item.message.kapso.statuses)
? item.message.kapso.statuses
: []
).flatMap((entry) => (isRecord(entry) && Array.isArray(entry.errors) ? entry.errors : []));
const firstError = errors.find(isRecord);
return [
{
type: 'message_status',
providerMessageId: messageId,
status,
errorCode: status === 'FAILED' ? (firstError?.code != null ? String(firstError.code) : 'delivery_failed') : null,
errorMessage:
status === 'FAILED' && typeof firstError?.title === 'string' ? firstError.title : null,
},
];
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function stringAt(value: Record<string, unknown>, ...path: string[]): string | null {
let current: unknown = value;
for (const key of path) {
if (!isRecord(current)) return null;
current = current[key];
}
return typeof current === 'string' && current ? current : null;
}
function readData(value: unknown): KapsoProviderData {
return isRecord(value) ? { ...(value as KapsoProviderData) } : {};
}
function compact(data: KapsoProviderData): Record<string, string> {
return Object.fromEntries(
Object.entries(data).filter((entry): entry is [string, string] => typeof entry[1] === 'string'),
);
}
function formatPhone(phone: string | null | undefined): string | null {
if (!phone) return null;
const digits = phone.replace(/\D/g, '');
return digits ? `+${digits}` : null;
}
function describe(error: unknown): { name: string; message: string; status?: number } {
if (error instanceof KapsoApiError) {
return { name: error.name, message: error.message, status: error.status };
}
return error instanceof Error
? { name: error.name, message: error.message }
: { name: 'Unknown', message: String(error) };
}

View File

@@ -0,0 +1,104 @@
import type { WhatsappMessageKind } from '@gruperly/shared';
import { firstNameOf } from '../../lib/render-message';
import type { WhatsappMessage } from '../messaging-provider';
import type { MetaTemplateDefinition } from './http';
/**
* The message templates submitted to Meta for each teacher's WhatsApp Business
* Account. Their bodies follow `lib/render-message.ts` (the OpenWA copy).
*
* Rules Meta enforces and that are easy to break:
* - A submitted template cannot be edited. Changing the copy means a new name
* (`gruperly_payment_reminder_v2`) and a new approval round.
* - The payment reminder stays UTILITY only while it has no promotional
* content; anything that sells turns it into MARKETING (and Meta may
* re-categorize it on its own).
* - The body cannot start or end with a variable.
*/
export const TEMPLATE_LANGUAGE = 'es_AR';
type TemplateSpec = {
definition: MetaTemplateDefinition;
parameters: (message: WhatsappMessage) => { name: string; text: string }[];
};
export const KAPSO_TEMPLATES: Record<WhatsappMessageKind, TemplateSpec> = {
PAYMENT_REMINDER: {
definition: {
name: 'gruperly_payment_reminder',
language: TEMPLATE_LANGUAGE,
category: 'UTILITY',
parameter_format: 'NAMED',
components: [
{
type: 'BODY',
text:
'¡Hola {{student_name}}! Te recordamos el pago de {{group_name}} por {{amount}}, ' +
'con vencimiento el {{due_date}}. Podés pagarlo desde este link: {{payment_link}} ¡Gracias!',
example: {
body_text_named_params: [
{ param_name: 'student_name', example: 'Ana' },
{ param_name: 'group_name', example: 'Yoga Martes y Jueves' },
{ param_name: 'amount', example: '$ 25.000' },
{ param_name: 'due_date', example: '10/11' },
{ param_name: 'payment_link', example: 'https://mpago.la/2xYz123' },
],
},
},
],
},
parameters: (message) =>
message.kind === 'PAYMENT_REMINDER'
? [
{ name: 'student_name', text: firstNameOf(message.studentName) },
{ name: 'group_name', text: message.groupName },
{ name: 'amount', text: message.amount },
{ name: 'due_date', text: message.dueDate },
{ name: 'payment_link', text: message.paymentLink },
]
: [],
},
REENGAGEMENT: {
definition: {
name: 'gruperly_reengagement',
language: TEMPLATE_LANGUAGE,
category: 'MARKETING',
parameter_format: 'NAMED',
components: [
{
type: 'BODY',
text:
'¡Hola {{student_name}}! 👋 Te extrañamos en {{group_name}}. ' +
'Notamos que no asististe a las últimas clases y queremos que vuelvas. ' +
'Si tenés algún problema con tus horarios o tu membresía, escribinos y lo resolvemos juntos.',
example: {
body_text_named_params: [
{ param_name: 'student_name', example: 'Ana' },
{ param_name: 'group_name', example: 'Yoga Martes y Jueves' },
],
},
},
],
},
parameters: (message) => [
{ name: 'student_name', text: firstNameOf(message.studentName) },
{ name: 'group_name', text: message.groupName },
],
},
};
/** Meta's template status, mapped to ours. Unknown values stay PENDING. */
export function toTemplateStatus(status: string): 'PENDING' | 'APPROVED' | 'REJECTED' | 'DISABLED' {
switch (status.toUpperCase()) {
case 'APPROVED':
return 'APPROVED';
case 'REJECTED':
return 'REJECTED';
case 'DISABLED':
case 'PAUSED':
case 'ARCHIVED':
return 'DISABLED';
default:
return 'PENDING';
}
}

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>;
}

View File

@@ -0,0 +1,51 @@
export type OpenWaConfig = {
/** Base URL including `/api`, e.g. `http://openwa:2785/api`. */
apiUrl: string;
/** An OPERATOR key that is not scoped to specific sessions (it creates them). */
apiKey: string;
/**
* Public URL of `/api/v1/whatsapp/webhooks/openwa`. Optional: without it the
* linking still works (the status endpoint polls OpenWA) but delivery and
* read receipts never reach `outbound_messages`.
*/
webhookUrl: string | null;
/** HMAC secret registered with each session webhook (16+ characters). */
webhookSecret: string | null;
};
const MIN_SECRET_LENGTH = 16;
/**
* Reads the OpenWA settings. Throws on a deployment mistake, naming the
* variables (never their values), like `getMpOAuthConfig()`.
*/
export function getOpenWaConfig(): OpenWaConfig {
const missing: string[] = [];
const read = (name: string, required: boolean): string | null => {
const value = process.env[name]?.trim();
if (!value) {
if (required) missing.push(name);
return null;
}
return value;
};
const apiUrl = read('OPENWA_API_URL', true);
const apiKey = read('OPENWA_API_KEY', true);
const webhookUrl = read('OPENWA_WEBHOOK_URL', false);
const webhookSecret = read('OPENWA_WEBHOOK_SECRET', webhookUrl !== null);
if (missing.length > 0) {
throw new Error(`Missing OpenWA environment variables: ${missing.join(', ')}. See .env.example.`);
}
if (webhookSecret !== null && webhookSecret.length < MIN_SECRET_LENGTH) {
throw new Error(`OPENWA_WEBHOOK_SECRET must be at least ${MIN_SECRET_LENGTH} characters long.`);
}
return {
apiUrl: (apiUrl as string).replace(/\/+$/, ''),
apiKey: apiKey as string,
webhookUrl,
webhookSecret,
};
}

View File

@@ -0,0 +1,156 @@
import type { OpenWaConfig } from './config';
/**
* Thin client for the OpenWA REST gateway (rmyndharis/OpenWA). Plain `fetch`:
* responses are the raw resource (no `{ data }` envelope) and errors use the
* NestJS shape `{ statusCode, message, error, code? }`.
*/
export class OpenWaApiError extends Error {
constructor(
readonly status: number,
/** OpenWA's stable machine code when it sends one (e.g. `SEND_PACING_LIMITED`). */
readonly code: string | null,
readonly retryAfterSeconds: number | null = null,
) {
super(`OpenWA request failed with ${status}${code ? ` (${code})` : ''}`);
this.name = 'OpenWaApiError';
}
}
export type OpenWaSessionStatus =
| 'created'
| 'initializing'
| 'qr_ready'
| 'authenticating'
| 'ready'
| 'disconnected'
| 'action_required'
| 'failed';
export type OpenWaSession = {
id: string;
name: string;
status: OpenWaSessionStatus;
phone: string | null;
lastError: string | null;
engineLoaded: boolean;
};
export type OpenWaFetch = (input: string, init?: RequestInit) => Promise<Response>;
const REQUEST_TIMEOUT_MS = 30_000;
export class OpenWaClient {
constructor(
private readonly config: OpenWaConfig,
private readonly fetchFn: OpenWaFetch = (input, init) => fetch(input, init),
) {}
getSession(sessionId: string): Promise<OpenWaSession> {
return this.request('GET', `/sessions/${encodeURIComponent(sessionId)}`);
}
async findSessionByName(name: string): Promise<OpenWaSession | null> {
const sessions = await this.request<OpenWaSession[]>(
'GET',
`/sessions?name=${encodeURIComponent(name)}`,
);
return sessions[0] ?? null;
}
createSession(name: string): Promise<OpenWaSession> {
return this.request('POST', '/sessions', { name });
}
startSession(sessionId: string): Promise<OpenWaSession> {
return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/start`);
}
logoutSession(sessionId: string): Promise<OpenWaSession> {
return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/logout`);
}
async deleteSession(sessionId: string): Promise<void> {
await this.request('DELETE', `/sessions/${encodeURIComponent(sessionId)}`);
}
async getQrCode(sessionId: string): Promise<string | null> {
const response = await this.request<{ qrCode?: string | null }>(
'GET',
`/sessions/${encodeURIComponent(sessionId)}/qr`,
);
return response.qrCode ?? null;
}
createWebhook(
sessionId: string,
body: { url: string; events: string[]; secret: string; retryCount: number },
): Promise<{ id: string }> {
return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/webhooks`, body);
}
checkContact(
sessionId: string,
digits: string,
): Promise<{ exists: boolean; whatsappId: string | null }> {
return this.request(
'GET',
`/sessions/${encodeURIComponent(sessionId)}/contacts/check/${encodeURIComponent(digits)}`,
);
}
sendText(
sessionId: string,
body: { chatId: string; text: string },
idempotencyKey: string,
): Promise<{ messageId: string; timestamp?: number }> {
return this.request(
'POST',
`/sessions/${encodeURIComponent(sessionId)}/messages/send-text`,
body,
{ 'Idempotency-Key': idempotencyKey },
);
}
private async request<T>(
method: string,
path: string,
body?: unknown,
extraHeaders: Record<string, string> = {},
): Promise<T> {
const response = await this.fetchFn(`${this.config.apiUrl}${path}`, {
method,
headers: {
'X-API-Key': this.config.apiKey,
Accept: 'application/json',
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
...extraHeaders,
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as {
code?: unknown;
retryAfterSeconds?: unknown;
} | null;
const retryAfterHeader = Number(response.headers.get('Retry-After'));
const retryAfterSeconds =
typeof payload?.retryAfterSeconds === 'number'
? payload.retryAfterSeconds
: Number.isFinite(retryAfterHeader) && retryAfterHeader > 0
? retryAfterHeader
: null;
throw new OpenWaApiError(
response.status,
typeof payload?.code === 'string' ? payload.code : null,
retryAfterSeconds,
);
}
if (response.status === 204) return undefined as T;
return (await response.json()) as T;
}
}

View File

@@ -0,0 +1,374 @@
import type { ProblemDetails, Result, WhatsappReadiness } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { whatsappProviderErrorProblem } from '@/http/problem-builders';
import { logger } from '@/logger';
import { verifyHmacSha256 } from '../../lib/hmac';
import { renderMessage } from '../../lib/render-message';
import type {
ConnectionSnapshot,
MessageDeliveryStatus,
MessagingProvider,
NormalizedEvent,
ParsedWebhook,
RecipientResolution,
SendOutcome,
StartConnectionContext,
StartConnectionResult,
WebhookParseError,
WhatsappAccountRecord,
WhatsappMessage,
} from '../messaging-provider';
import type { OpenWaConfig } from './config';
import { OpenWaApiError, OpenWaClient, type OpenWaFetch, type OpenWaSession } from './http';
/** Events each session webhook subscribes to. */
export const OPENWA_WEBHOOK_EVENTS = [
'session.status',
'session.authenticated',
'session.disconnected',
'message.ack',
'message.failed',
];
const WEBHOOK_RETRY_COUNT = 3;
/** The global throttler's 429 carries no `retryAfterSeconds`; it clears in seconds. */
const DEFAULT_RATE_LIMIT_MS = 60_000;
const PENDING_STATUSES = new Set(['created', 'initializing', 'qr_ready', 'authenticating']);
/** One OpenWA session per teacher. Names allow letters, digits and hyphens (3-50). */
export function openWaSessionName(ownerId: string): string {
return `gruperly-${ownerId.replace(/[^a-zA-Z0-9-]/g, '')}`.slice(0, 50);
}
type OpenWaProviderDeps = { fetch?: OpenWaFetch };
/**
* OpenWA (self-hosted, unofficial WhatsApp Web gateway) for the MVP.
*
* The teacher links their own WhatsApp as a "linked device" by scanning a QR
* code shown inside Gruperly; messages are free text sent from that session.
* It is not Meta's official API: see `docs/whatsapp.md` for the ban risk and
* why sends are paced.
*/
export class OpenWaProvider implements MessagingProvider {
readonly id = 'OPENWA' as const;
private readonly client: OpenWaClient;
constructor(
private readonly config: OpenWaConfig,
deps: OpenWaProviderDeps = {},
) {
this.client = new OpenWaClient(config, deps.fetch);
}
async startConnection(
context: StartConnectionContext,
): Promise<Result<StartConnectionResult, ProblemDetails>> {
const previous =
context.account?.provider === 'OPENWA' ? context.account : null;
const previousData = readData(previous?.providerData);
try {
let session = previous?.externalId ? await this.findSession(previous.externalId) : null;
let webhookId = session ? previousData.webhookId ?? null : null;
if (!session) {
session = await this.createOrAdoptSession(openWaSessionName(context.ownerId));
webhookId = null;
}
if (!webhookId) {
webhookId = await this.registerWebhook(session.id);
}
// Linking again from an already linked session (e.g. to change number):
// unlink first so WhatsApp hands out a fresh QR code.
if (session.status === 'ready' && session.engineLoaded) {
session = await this.client.logoutSession(session.id).catch(() => session as OpenWaSession);
}
if (!session.engineLoaded || session.status === 'disconnected' || session.status === 'failed') {
session = await this.client.startSession(session.id).catch((error: unknown) => {
// 400 = already started / starting: fine, the QR is on its way.
if (error instanceof OpenWaApiError && error.status === 400) return session as OpenWaSession;
throw error;
});
}
return ok({
start: { type: 'qr', qrCode: await this.tryQrCode(session.id) },
externalId: session.id,
providerData: {
sessionName: session.name,
...(webhookId ? { webhookId } : {}),
},
});
} catch (error) {
logger.error({ err: describe(error) }, 'OpenWA could not start a session');
return err(whatsappProviderErrorProblem());
}
}
async refreshConnection(
account: WhatsappAccountRecord,
): Promise<Result<ConnectionSnapshot, ProblemDetails>> {
if (!account.externalId) return ok({ state: 'disconnected', reason: 'no_session' });
try {
const session = await this.findSession(account.externalId);
if (!session) return ok({ state: 'disconnected', reason: 'session_not_found' });
if (session.status === 'ready') {
return ok({ state: 'active', displayPhoneNumber: formatPhone(session.phone) });
}
if (PENDING_STATUSES.has(session.status)) {
const qrCode = session.status === 'qr_ready' ? await this.tryQrCode(session.id) : null;
return ok({ state: 'pending', qrCode });
}
// A `disconnected` session whose engine is still loaded is backing off
// before an automatic reconnect: not a failure yet.
if (session.status === 'disconnected' && session.engineLoaded) {
return ok({ state: 'pending', qrCode: null });
}
return ok({ state: 'disconnected', reason: session.lastError ?? session.status });
} catch (error) {
logger.warn({ err: describe(error) }, 'OpenWA session status lookup failed');
return err(whatsappProviderErrorProblem());
}
}
async disconnect(account: WhatsappAccountRecord): Promise<Result<void, ProblemDetails>> {
if (!account.externalId) return ok(undefined);
const sessionId = account.externalId;
// `logout` unlinks the device from the teacher's phone; `delete` alone
// would leave it listed under "Linked devices". Both are best effort: the
// local row is unlinked either way.
try {
await this.client.logoutSession(sessionId);
} catch (error) {
logger.warn({ err: describe(error) }, 'OpenWA logout did not complete');
}
try {
await this.client.deleteSession(sessionId);
} catch (error) {
if (!(error instanceof OpenWaApiError && error.status === 404)) {
logger.warn({ err: describe(error) }, 'OpenWA session delete did not complete');
}
}
return ok(undefined);
}
async readiness(account: WhatsappAccountRecord): Promise<WhatsappReadiness> {
return account.status === 'ACTIVE' ? 'ready' : 'blocked';
}
async resolveRecipient(
account: WhatsappAccountRecord,
e164: string,
): Promise<RecipientResolution> {
if (!account.externalId) return { ok: false, code: 'provider_error' };
try {
// The canonical id WhatsApp knows the number by. It also settles the
// Argentine "9" after the country code, which differs per account.
const contact = await this.client.checkContact(account.externalId, e164.replace(/\D/g, ''));
return contact.exists && contact.whatsappId
? { ok: true, to: contact.whatsappId }
: { ok: false, code: 'no_whatsapp' };
} catch (error) {
logger.warn({ err: describe(error) }, 'OpenWA contact check failed');
return { ok: false, code: 'provider_error' };
}
}
async send(
account: WhatsappAccountRecord,
to: string,
message: WhatsappMessage,
idempotencyKey: string,
): Promise<SendOutcome> {
if (!account.externalId) {
return { ok: false, retryable: false, code: 'no_session', message: 'Account has no session' };
}
try {
const response = await this.client.sendText(
account.externalId,
{ chatId: to, text: renderMessage(message) },
idempotencyKey,
);
return { ok: true, providerMessageId: response.messageId };
} catch (error) {
return toSendFailure(error);
}
}
parseWebhook(rawBody: string, headers: Headers): Result<ParsedWebhook, WebhookParseError> {
const secret = this.config.webhookSecret;
if (!secret || !verifyHmacSha256(rawBody, headers.get('X-OpenWA-Signature'), secret, 'sha256=')) {
return err('invalid_signature');
}
let payload: OpenWaWebhookPayload;
try {
payload = JSON.parse(rawBody) as OpenWaWebhookPayload;
} catch {
return err('invalid_payload');
}
const dedupeKey =
headers.get('X-OpenWA-Idempotency-Key') ?? payload.idempotencyKey ?? payload.deliveryId;
if (!dedupeKey || typeof payload.event !== 'string') return err('invalid_payload');
return ok({ dedupeKey, events: toEvents(payload) });
}
private async findSession(sessionId: string): Promise<OpenWaSession | null> {
try {
return await this.client.getSession(sessionId);
} catch (error) {
if (error instanceof OpenWaApiError && error.status === 404) return null;
throw error;
}
}
/** Creates the teacher's session, or adopts it if one with that name survived. */
private async createOrAdoptSession(name: string): Promise<OpenWaSession> {
try {
return await this.client.createSession(name);
} catch (error) {
if (error instanceof OpenWaApiError && error.status === 409) {
const existing = await this.client.findSessionByName(name);
if (existing) return existing;
}
throw error;
}
}
private async registerWebhook(sessionId: string): Promise<string | null> {
if (!this.config.webhookUrl || !this.config.webhookSecret) return null;
try {
const webhook = await this.client.createWebhook(sessionId, {
url: this.config.webhookUrl,
events: OPENWA_WEBHOOK_EVENTS,
secret: this.config.webhookSecret,
retryCount: WEBHOOK_RETRY_COUNT,
});
return webhook.id;
} catch (error) {
// Without the webhook the linking still works through polling; only the
// delivery receipts are lost. Not worth failing the teacher's click.
logger.warn({ err: describe(error) }, 'OpenWA webhook registration failed');
return null;
}
}
private async tryQrCode(sessionId: string): Promise<string | null> {
try {
return await this.client.getQrCode(sessionId);
} catch {
// 400 while the engine is still starting: the next status poll brings it.
return null;
}
}
}
type OpenWaWebhookPayload = {
event?: unknown;
sessionId?: string;
idempotencyKey?: string;
deliveryId?: string;
data?: Record<string, unknown>;
};
const ACK_STATUSES: Record<string, MessageDeliveryStatus> = {
sent: 'SENT',
delivered: 'DELIVERED',
read: 'READ',
played: 'READ',
failed: 'FAILED',
};
function toEvents(payload: OpenWaWebhookPayload): NormalizedEvent[] {
const data = payload.data ?? {};
const sessionId = (typeof data.sessionId === 'string' ? data.sessionId : null) ?? payload.sessionId;
switch (payload.event) {
case 'session.authenticated':
return sessionId
? [
{
type: 'connection',
externalId: sessionId,
status: 'active',
displayPhoneNumber: formatPhone(typeof data.phone === 'string' ? data.phone : null),
},
]
: [];
case 'session.status':
if (!sessionId) return [];
if (data.status === 'ready') return [{ type: 'connection', externalId: sessionId, status: 'active' }];
if (data.status === 'failed') {
return [{ type: 'connection', externalId: sessionId, status: 'disconnected' }];
}
return [];
case 'session.disconnected':
return sessionId ? [{ type: 'connection', externalId: sessionId, status: 'disconnected' }] : [];
case 'message.ack':
case 'message.failed': {
const status = ACK_STATUSES[String(data.status ?? (payload.event === 'message.failed' ? 'failed' : ''))];
const messageId = typeof data.messageId === 'string' ? data.messageId : null;
if (!status || !messageId) return [];
return [
{
type: 'message_status',
providerMessageId: messageId,
status,
errorCode: status === 'FAILED' ? 'delivery_failed' : null,
},
];
}
default:
return [];
}
}
function toSendFailure(error: unknown): SendOutcome {
if (error instanceof OpenWaApiError) {
if (error.status === 429) {
return {
ok: false,
retryable: true,
rateLimitedForMs: error.retryAfterSeconds ? error.retryAfterSeconds * 1000 : DEFAULT_RATE_LIMIT_MS,
code: error.code ?? 'rate_limited',
message: error.message,
};
}
// 4xx: the session is not active, the body was refused, the key reused…
// none of them gets better by repeating the same request.
const retryable = error.status >= 500 || error.status === 409;
return { ok: false, retryable, code: error.code ?? `http_${error.status}`, message: error.message };
}
return { ok: false, retryable: true, code: 'network_error', message: describe(error).message };
}
function readData(value: unknown): Record<string, string | undefined> {
return value && typeof value === 'object' ? (value as Record<string, string | undefined>) : {};
}
function formatPhone(phone: string | null | undefined): string | null {
if (!phone) return null;
const digits = phone.replace(/\D/g, '');
return digits ? `+${digits}` : null;
}
/** Errors are logged by name and status only: request bodies may hold phone numbers. */
function describe(error: unknown): { name: string; message: string; status?: number } {
if (error instanceof OpenWaApiError) {
return { name: error.name, message: error.message, status: error.status };
}
return error instanceof Error
? { name: error.name, message: error.message }
: { name: 'Unknown', message: String(error) };
}

View File

@@ -0,0 +1,18 @@
import { Hono } from 'hono';
import callbackRoute from './features/callback/route';
import connectRoute from './features/connect/route';
import disconnectRoute from './features/disconnect/route';
import statusRoute from './features/status/route';
import webhookRoute from './features/webhook/route';
const routes = new Hono();
// Same trick as `mp`: `disconnectRoute` only declares `DELETE /`, so mounting
// it on `/connect` gives the RESTful `DELETE /whatsapp/connect`.
routes.route('/connect', connectRoute);
routes.route('/connect', disconnectRoute);
routes.route('/status', statusRoute);
routes.route('/callback', callbackRoute);
routes.route('/webhooks', webhookRoute);
export default routes;

View File

@@ -3,6 +3,7 @@ import { getPrismaClient } from '@/lib/prisma';
import { logger } from '@/logger';
import { startMpJobs } from '@/modules/mp';
import { startPaymentJobs } from '@/modules/payments';
import { startWhatsappJobs } from '@/modules/whatsapp';
const port = Number(process.env.PORT ?? 4000);
@@ -15,6 +16,7 @@ const server = Bun.serve({
startMpJobs();
startPaymentJobs();
startWhatsappJobs();
async function shutdown(): Promise<void> {
server.stop(true);

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,590 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { ok } from '@gruperly/shared';
import { CompleteWhatsappSetup } from '@/modules/whatsapp/features/callback/use-case';
import { StartWhatsappConnection } from '@/modules/whatsapp/features/connect/use-case';
import { DisconnectWhatsapp } from '@/modules/whatsapp/features/disconnect/use-case';
import { GetWhatsappStatus } from '@/modules/whatsapp/features/status/use-case';
import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case';
import { HandleWhatsappWebhook } from '@/modules/whatsapp/features/webhook/use-case';
import { toVisibleWhatsappStatus } from '@/modules/whatsapp/lib/account';
import type {
MessagingProvider,
NormalizedEvent,
} from '@/modules/whatsapp/providers/messaging-provider';
/* The domain side of WhatsApp, driven through a fake provider: these tests pin
what the use cases do with whatever any provider answers, so they do not
change when an adapter does. Dependencies go in through constructors (no
`mock.module`), as AGENTS.md asks for provider code. */
const ownerId = 'user-1';
const now = new Date('2026-10-19T13:00:00.000Z');
function fakeProvider(overrides: Partial<MessagingProvider> = {}): MessagingProvider {
return {
id: 'OPENWA',
startConnection: mock(async () =>
ok({
start: { type: 'qr' as const, qrCode: 'data:image/png;base64,QR1' },
externalId: 'session-1',
providerData: { sessionName: 'gruperly-user-1' },
}),
),
refreshConnection: mock(async () => ok({ state: 'pending' as const, qrCode: 'data:QR2' })),
disconnect: mock(async () => ok(undefined)),
readiness: mock(async () => 'ready' as const),
resolveRecipient: mock(async (_account, e164: string) => ({ ok: true as const, to: e164 })),
send: mock(async () => ({ ok: true as const, providerMessageId: 'wamid-1' })),
parseWebhook: mock(() => ok({ dedupeKey: 'delivery-1', events: [] as NormalizedEvent[] })),
...overrides,
} as MessagingProvider;
}
function account(overrides: Record<string, unknown> = {}) {
return {
id: 'wa-1',
ownerId,
provider: 'OPENWA',
status: 'PENDING',
externalId: 'session-1',
displayPhoneNumber: null,
providerData: { sessionName: 'gruperly-user-1' },
connectedAt: null,
...overrides,
};
}
function makeDb() {
return {
whatsappAccount: {
findUnique: mock(),
findFirst: mock(),
upsert: mock(async () => ({})),
update: mock(async ({ data }: { data: Record<string, unknown> }) => account({ ...data })),
},
whatsappWebhookEvent: {
create: mock(async () => ({})),
delete: mock(async () => ({})),
},
outboundMessage: {
updateMany: mock(async () => ({ count: 1 })),
},
group: {
findUnique: mock(),
update: mock(),
},
};
}
type Db = ReturnType<typeof makeDb>;
let db: Db;
beforeEach(() => {
db = makeDb();
});
describe('visible WhatsApp status', () => {
it('maps rows of the active provider', () => {
expect(toVisibleWhatsappStatus(null, 'OPENWA')).toBe('none');
expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'PENDING' }, 'OPENWA')).toBe('pending');
expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'ACTIVE' }, 'OPENWA')).toBe('active');
expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'DISCONNECTED' }, 'OPENWA')).toBe(
'disconnected',
);
});
it('asks to reconnect an account linked with another provider', () => {
expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'ACTIVE' }, 'KAPSO')).toBe(
'requires_reconnect',
);
expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'DISCONNECTED' }, 'KAPSO')).toBe('none');
});
});
describe('start connection', () => {
it('stores a PENDING account and hands the QR to the browser', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(null);
const provider = fakeProvider();
const result = await new StartWhatsappConnection({ db: db as never, provider }).execute(
{ id: ownerId, name: 'Ana Profe' },
'onboarding',
);
expect(result).toEqual({
ok: true,
value: { start: { type: 'qr', qrCode: 'data:image/png;base64,QR1' } },
});
expect(provider.startConnection).toHaveBeenCalledWith({
ownerId,
ownerName: 'Ana Profe',
returnTo: 'onboarding',
account: null,
});
const upsert = db.whatsappAccount.upsert.mock.calls[0]?.[0] as {
create: Record<string, unknown>;
update: Record<string, unknown>;
};
expect(upsert.create).toMatchObject({
ownerId,
provider: 'OPENWA',
status: 'PENDING',
externalId: 'session-1',
});
expect(upsert.update).toMatchObject({ status: 'PENDING', connectedAt: null });
});
it('passes the redirect through for hosted linkings', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(null);
const provider = fakeProvider({
id: 'KAPSO',
startConnection: mock(async () =>
ok({
start: { type: 'redirect' as const, url: 'https://app.kapso.ai/whatsapp/setup/abc' },
externalId: null,
providerData: { customerId: 'cust-1', setupLinkId: 'link-1' },
}),
),
});
const result = await new StartWhatsappConnection({ db: db as never, provider }).execute(
{ id: ownerId, name: 'Ana' },
'settings',
);
expect(result.ok && result.value.start).toEqual({
type: 'redirect',
url: 'https://app.kapso.ai/whatsapp/setup/abc',
});
});
it('does not touch the account when the provider fails', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(null);
const provider = fakeProvider({
startConnection: mock(async () => ({
ok: false as const,
error: { type: 'x', title: 'Bad Gateway', status: 502, code: 'whatsapp_provider_error' },
})),
});
const result = await new StartWhatsappConnection({ db: db as never, provider }).execute(
{ id: ownerId, name: 'Ana' },
'settings',
);
expect(result.ok).toBe(false);
expect(db.whatsappAccount.upsert).not.toHaveBeenCalled();
});
});
describe('status', () => {
it('reports no account', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(null);
const result = await new GetWhatsappStatus({ db: db as never, provider: fakeProvider() }).execute(
ownerId,
);
expect(result).toEqual({
ok: true,
value: {
status: 'none',
provider: 'OPENWA',
displayPhoneNumber: null,
connectedAt: null,
qrCode: null,
readiness: { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked' },
},
});
});
it('returns the fresh QR while the linking is pending', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account());
const result = await new GetWhatsappStatus({ db: db as never, provider: fakeProvider() }).execute(
ownerId,
);
expect(result.ok && result.value).toMatchObject({ status: 'pending', qrCode: 'data:QR2' });
expect(db.whatsappAccount.update).not.toHaveBeenCalled();
});
it('activates the account once the provider reports it linked', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account());
const onConnected = mock(async () => undefined);
const provider = fakeProvider({
refreshConnection: mock(async () =>
ok({ state: 'active' as const, displayPhoneNumber: '+5491123456789' }),
),
onConnected,
});
const result = await new GetWhatsappStatus({ db: db as never, provider, now: () => now }).execute(
ownerId,
);
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' },
data: { status: 'ACTIVE', connectedAt: now, displayPhoneNumber: '+5491123456789' },
});
expect(onConnected).toHaveBeenCalledTimes(1);
expect(result.ok && result.value).toMatchObject({
status: 'active',
displayPhoneNumber: '+5491123456789',
connectedAt: now.toISOString(),
readiness: { PAYMENT_REMINDER: 'ready', REENGAGEMENT: 'ready' },
});
});
it('marks a failed linking as disconnected', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account());
const provider = fakeProvider({
refreshConnection: mock(async () => ok({ state: 'disconnected' as const, reason: 'failed' })),
});
const result = await new GetWhatsappStatus({ db: db as never, provider }).execute(ownerId);
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' },
data: { status: 'DISCONNECTED' },
});
expect(result.ok && result.value.status).toBe('disconnected');
});
it('does not poll the provider for an account linked elsewhere', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account({ provider: 'KAPSO', status: 'ACTIVE' }));
const provider = fakeProvider();
const result = await new GetWhatsappStatus({ db: db as never, provider }).execute(ownerId);
expect(provider.refreshConnection).not.toHaveBeenCalled();
expect(result.ok && result.value).toMatchObject({
status: 'requires_reconnect',
readiness: { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked' },
});
});
it('reports a template still under review', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account({ status: 'ACTIVE' }));
const provider = fakeProvider({
readiness: mock(async (_account, kind) => (kind === 'REENGAGEMENT' ? 'pending' : 'ready')),
});
const result = await new GetWhatsappStatus({ db: db as never, provider }).execute(ownerId);
expect(result.ok && result.value.readiness).toEqual({
PAYMENT_REMINDER: 'ready',
REENGAGEMENT: 'pending',
});
});
});
describe('disconnect', () => {
it('unlinks on the provider and frees the number locally', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account({ status: 'ACTIVE' }));
const provider = fakeProvider();
const result = await new DisconnectWhatsapp({ db: db as never, provider }).execute(ownerId);
expect(result).toEqual({ ok: true, value: { disconnected: true } });
expect(provider.disconnect).toHaveBeenCalledTimes(1);
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' },
data: { status: 'DISCONNECTED', externalId: null, displayPhoneNumber: null, connectedAt: null },
});
});
it('is a no-op without a linked account', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(null);
const result = await new DisconnectWhatsapp({ db: db as never, provider: fakeProvider() }).execute(
ownerId,
);
expect(result).toEqual({ ok: true, value: { disconnected: false } });
expect(db.whatsappAccount.update).not.toHaveBeenCalled();
});
});
describe('redirect callback', () => {
it('activates the account the provider confirmed', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(
account({ provider: 'KAPSO', externalId: null, providerData: { customerId: 'cust-1' } }),
);
const provider = fakeProvider({
id: 'KAPSO',
completeRedirect: mock(async () =>
ok({
externalId: 'phone-1',
displayPhoneNumber: '+5491100000000',
providerData: { businessAccountId: 'waba-1' },
}),
),
});
const outcome = await new CompleteWhatsappSetup({ db: db as never, provider, now: () => now }).execute(
ownerId,
{ setup_link_id: 'link-1', phone_number_id: 'phone-1', status: 'completed' },
);
expect(outcome).toEqual({ kind: 'success' });
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' },
data: {
status: 'ACTIVE',
connectedAt: now,
externalId: 'phone-1',
displayPhoneNumber: '+5491100000000',
providerData: { customerId: 'cust-1', businessAccountId: 'waba-1' },
},
});
});
it('reports a number already linked to someone else', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account({ provider: 'KAPSO' }));
db.whatsappAccount.update.mockRejectedValueOnce(Object.assign(new Error('unique'), { code: 'P2002' }));
const provider = fakeProvider({
id: 'KAPSO',
completeRedirect: mock(async () => ok({ externalId: 'phone-1', displayPhoneNumber: null })),
});
const outcome = await new CompleteWhatsappSetup({ db: db as never, provider }).execute(ownerId, {});
expect(outcome).toEqual({ kind: 'error', reason: 'number_in_use' });
});
it('refuses a provider without hosted linking', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account());
const outcome = await new CompleteWhatsappSetup({ db: db as never, provider: fakeProvider() }).execute(
ownerId,
{},
);
expect(outcome).toEqual({ kind: 'error', reason: 'invalid_setup' });
});
});
describe('webhook', () => {
const headers = new Headers();
it('rejects an invalid signature before touching the database', async () => {
const provider = fakeProvider({
parseWebhook: mock(() => ({ ok: false as const, error: 'invalid_signature' as const })),
});
const result = await new HandleWhatsappWebhook({ db: db as never, provider }).execute(
'OPENWA',
'{}',
headers,
);
expect(result).toEqual({ ok: false, error: 'invalid_signature' });
expect(db.whatsappWebhookEvent.create).not.toHaveBeenCalled();
});
it('ignores a delivery it already processed', async () => {
db.whatsappWebhookEvent.create.mockRejectedValueOnce(Object.assign(new Error('dup'), { code: 'P2002' }));
const provider = fakeProvider({
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-1',
events: [{ type: 'message_status' as const, providerMessageId: 'wamid-1', status: 'READ' as const }],
}),
),
});
const result = await new HandleWhatsappWebhook({ db: db as never, provider }).execute(
'OPENWA',
'{}',
headers,
);
expect(result).toEqual({ ok: true, value: { duplicate: true, applied: 0 } });
expect(db.outboundMessage.updateMany).not.toHaveBeenCalled();
});
it('advances a message status without moving it backwards', async () => {
const provider = fakeProvider({
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-2',
events: [{ type: 'message_status' as const, providerMessageId: 'wamid-1', status: 'DELIVERED' as const }],
}),
),
});
await new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers);
expect(db.whatsappWebhookEvent.create).toHaveBeenCalledWith({
data: { provider: 'OPENWA', dedupeKey: 'delivery-2' },
});
expect(db.outboundMessage.updateMany).toHaveBeenCalledWith({
where: {
provider: 'OPENWA',
providerMessageId: 'wamid-1',
status: { in: ['QUEUED', 'SENT'] },
},
data: { status: 'DELIVERED' },
});
});
it('records why a message failed', async () => {
const provider = fakeProvider({
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-3',
events: [
{
type: 'message_status' as const,
providerMessageId: 'wamid-1',
status: 'FAILED' as const,
errorCode: '131026',
errorMessage: 'Message undeliverable',
},
],
}),
),
});
await new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers);
expect(db.outboundMessage.updateMany.mock.calls[0]?.[0]).toMatchObject({
data: { status: 'FAILED', errorCode: '131026', errorMessage: 'Message undeliverable' },
});
});
it('activates the account a connection event names and runs the setup once', async () => {
db.whatsappAccount.findFirst.mockResolvedValueOnce(account());
const onConnected = mock(async () => undefined);
const provider = fakeProvider({
onConnected,
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-4',
events: [
{
type: 'connection' as const,
externalId: 'session-1',
status: 'active' as const,
displayPhoneNumber: '+5491123456789',
},
],
}),
),
});
const result = await new HandleWhatsappWebhook({ db: db as never, provider, now: () => now }).execute(
'OPENWA',
'{}',
headers,
);
expect(result).toEqual({ ok: true, value: { duplicate: false, applied: 1 } });
expect(db.whatsappAccount.update.mock.calls[0]?.[0]).toMatchObject({
where: { id: 'wa-1' },
data: { status: 'ACTIVE', connectedAt: now, externalId: 'session-1' },
});
expect(onConnected).toHaveBeenCalledTimes(1);
});
it('falls back to the owner reference when the number is new to us', async () => {
db.whatsappAccount.findFirst.mockResolvedValueOnce(null).mockResolvedValueOnce(account({ provider: 'KAPSO' }));
const provider = fakeProvider({
id: 'KAPSO',
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-5',
events: [{ type: 'connection' as const, externalId: 'phone-1', ownerId, status: 'active' as const }],
}),
),
});
await new HandleWhatsappWebhook({ db: db as never, provider }).execute('KAPSO', '{}', headers);
expect(db.whatsappAccount.findFirst.mock.calls[1]?.[0]).toEqual({
where: { provider: 'KAPSO', ownerId, status: { not: 'DISCONNECTED' } },
});
expect(db.whatsappAccount.update.mock.calls[0]?.[0]).toMatchObject({
data: { status: 'ACTIVE', externalId: 'phone-1' },
});
});
it('marks an unlinked number as disconnected', async () => {
db.whatsappAccount.findFirst.mockResolvedValueOnce(account({ status: 'ACTIVE' }));
const provider = fakeProvider({
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-6',
events: [{ type: 'connection' as const, externalId: 'session-1', status: 'disconnected' as const }],
}),
),
});
await new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers);
expect(db.whatsappAccount.update).toHaveBeenCalledWith({
where: { id: 'wa-1' },
data: { status: 'DISCONNECTED' },
});
});
it('un-burns the delivery when applying it fails, so the retry gets through', async () => {
db.outboundMessage.updateMany.mockRejectedValueOnce(new Error('db down'));
const provider = fakeProvider({
parseWebhook: mock(() =>
ok({
dedupeKey: 'delivery-7',
events: [{ type: 'message_status' as const, providerMessageId: 'wamid-1', status: 'READ' as const }],
}),
),
});
await expect(
new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers),
).rejects.toThrow('db down');
expect(db.whatsappWebhookEvent.delete).toHaveBeenCalledWith({
where: { provider_dedupeKey: { provider: 'OPENWA', dedupeKey: 'delivery-7' } },
});
});
});
describe('group automations', () => {
it('lets the owner turn an automation on', async () => {
db.group.findUnique.mockResolvedValue({ id: 'group-1', createdById: ownerId });
db.group.update.mockResolvedValue({ autoPaymentReminders: true, autoReengagement: false });
const result = await new UpdateGroupAutomationsUseCase({ db: db as never }).execute('group-1', ownerId, {
autoPaymentReminders: true,
});
expect(result).toEqual({ ok: true, value: { autoPaymentReminders: true, autoReengagement: false } });
expect(db.group.update).toHaveBeenCalledWith({
where: { id: 'group-1' },
data: { autoPaymentReminders: true },
select: { autoPaymentReminders: true, autoReengagement: true },
});
});
it('refuses anyone but the owner', async () => {
db.group.findUnique.mockResolvedValue({ id: 'group-1', createdById: 'someone-else' });
const result = await new UpdateGroupAutomationsUseCase({ db: db as never }).execute('group-1', ownerId, {
autoReengagement: true,
});
expect(result.ok).toBe(false);
expect(!result.ok && result.error.status).toBe(403);
expect(db.group.update).not.toHaveBeenCalled();
});
it('answers 404 for an unknown group', async () => {
db.group.findUnique.mockResolvedValue(null);
const result = await new UpdateGroupAutomationsUseCase({ db: db as never }).execute('nope', ownerId, {
autoReengagement: true,
});
expect(!result.ok && result.error.status).toBe(404);
});
});

View File

@@ -0,0 +1,383 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { ok, toWhatsappE164 } from '@gruperly/shared';
import { SendPaymentReminders, SendReengagementMessages } from '@/modules/whatsapp/jobs';
import { isoWeekKey } from '@/modules/whatsapp/lib/period';
import { renderMessage } from '@/modules/whatsapp/lib/render-message';
import type { MessagingProvider } from '@/modules/whatsapp/providers/messaging-provider';
/* The weekly jobs, with the provider faked through constructor deps. */
const now = new Date('2026-10-19T13:00:00.000Z'); // Monday
const ownerId = 'user-1';
const activeAccount = {
id: 'wa-1',
ownerId,
provider: 'OPENWA',
status: 'ACTIVE',
externalId: 'session-1',
displayPhoneNumber: '+5491100000000',
providerData: null,
};
function eligibleGroup(overrides: Record<string, unknown> = {}) {
return {
id: 'group-1',
name: 'Yoga Martes',
createdById: ownerId,
owner: { country: 'AR', whatsappAccount: activeAccount },
...overrides,
};
}
function payment(id: string, attendee: Record<string, unknown>, overrides: Record<string, unknown> = {}) {
return {
id,
amount: { toString: () => '25000' },
currency: 'ARS',
dueDate: new Date('2026-10-20T15:00:00.000Z'),
checkoutUrl: `https://mpago.la/${id}`,
attendee: { phone: null, guardianPhone: null, ...attendee },
...overrides,
};
}
function fakeProvider(overrides: Partial<MessagingProvider> = {}): MessagingProvider {
return {
id: 'OPENWA',
startConnection: mock(),
refreshConnection: mock(),
disconnect: mock(),
readiness: mock(async () => 'ready' as const),
resolveRecipient: mock(async (_account, e164: string) => ({
ok: true as const,
to: `${e164.slice(1)}@c.us`,
})),
send: mock(async () => ({ ok: true as const, providerMessageId: 'wamid-1' })),
parseWebhook: mock(() => ok({ dedupeKey: 'k', events: [] })),
...overrides,
} as MessagingProvider;
}
function makeDb() {
let counter = 0;
return {
group: { findMany: mock(async () => [eligibleGroup()]) },
payment: { findMany: mock(async () => [] as unknown[]) },
attendee: { findMany: mock(async () => [] as unknown[]) },
classSession: { findMany: mock(async () => [] as unknown[]) },
attendance: { findMany: mock(async () => [] as unknown[]) },
outboundMessage: {
create: mock(async () => ({ id: `msg-${++counter}` })),
update: mock(async () => ({})),
delete: mock(async () => ({})),
findMany: mock(async () => [] as unknown[]),
},
};
}
let db: ReturnType<typeof makeDb>;
const sleep = mock(async () => undefined);
beforeEach(() => {
db = makeDb();
sleep.mockClear();
});
function reminders(provider: MessagingProvider) {
return new SendPaymentReminders({ db: db as never, provider, now, intervalMs: 5000, sleep });
}
function reengagement(provider: MessagingProvider) {
return new SendReengagementMessages({ db: db as never, provider, now, intervalMs: 5000, sleep });
}
describe('payment reminders', () => {
it('only looks at groups with the automation on and an active account of this provider', async () => {
await reminders(fakeProvider()).execute();
expect(db.group.findMany.mock.calls[0]?.[0]).toMatchObject({
where: {
autoPaymentReminders: true,
owner: { whatsappAccount: { is: { provider: 'OPENWA', status: 'ACTIVE' } } },
},
});
});
it('asks for open charges with a link due within a week', async () => {
await reminders(fakeProvider()).execute();
expect(db.payment.findMany.mock.calls[0]?.[0]).toMatchObject({
where: {
groupId: 'group-1',
status: { in: ['PENDING', 'OVERDUE'] },
checkoutUrl: { not: null },
dueDate: { lte: new Date('2026-10-26T13:00:00.000Z') },
attendee: { status: 'ACTIVE' },
},
orderBy: { dueDate: 'asc' },
});
});
it('sends one reminder per member, logged before the send and keyed by the row id', async () => {
db.payment.findMany.mockResolvedValue([
payment('pay-1', { id: 'att-1', fullName: 'Ana López', phone: '11 2345-6789' }),
payment('pay-2', { id: 'att-1', fullName: 'Ana López', phone: '11 2345-6789' }),
]);
const provider = fakeProvider();
const totals = await reminders(provider).execute();
expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 });
expect(db.outboundMessage.create).toHaveBeenCalledWith({
data: {
ownerId,
groupId: 'group-1',
attendeeId: 'att-1',
paymentId: 'pay-1',
kind: 'PAYMENT_REMINDER',
provider: 'OPENWA',
periodKey: '2026-W43',
toPhone: '+5491123456789',
status: 'QUEUED',
},
select: { id: true },
});
const [, to, message, key] = (provider.send as ReturnType<typeof mock>).mock.calls[0] ?? [];
expect(to).toBe('5491123456789@c.us');
expect(key).toBe('msg-1');
expect(message).toMatchObject({
kind: 'PAYMENT_REMINDER',
studentName: 'Ana López',
groupName: 'Yoga Martes',
dueDate: '20/10',
paymentLink: 'https://mpago.la/pay-1',
});
expect(db.outboundMessage.update).toHaveBeenCalledWith({
where: { id: 'msg-1' },
data: expect.objectContaining({ status: 'SENT', providerMessageId: 'wamid-1' }),
});
});
it('skips a member already handled this week', async () => {
db.payment.findMany.mockResolvedValue([
payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456789' }),
]);
db.outboundMessage.create.mockRejectedValueOnce(Object.assign(new Error('dup'), { code: 'P2002' }));
const provider = fakeProvider();
const totals = await reminders(provider).execute();
expect(totals).toEqual({ sent: 0, skipped: 1, failed: 0 });
expect(provider.send).not.toHaveBeenCalled();
});
it('falls back to the guardian phone and skips members without a usable one', async () => {
db.payment.findMany.mockResolvedValue([
payment('pay-1', { id: 'att-1', fullName: 'Nene', guardianPhone: '1123456789' }),
payment('pay-2', { id: 'att-2', fullName: 'Sin tel' }),
]);
const totals = await reminders(fakeProvider()).execute();
expect(totals).toEqual({ sent: 1, skipped: 1, failed: 0 });
expect(db.outboundMessage.create.mock.calls[1]?.[0]).toMatchObject({
data: { attendeeId: 'att-2', status: 'SKIPPED', errorCode: 'invalid_phone' },
});
});
it('logs numbers without WhatsApp as skipped', async () => {
db.payment.findMany.mockResolvedValue([payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456789' })]);
const provider = fakeProvider({
resolveRecipient: mock(async () => ({ ok: false as const, code: 'no_whatsapp' as const })),
});
const totals = await reminders(provider).execute();
expect(totals).toEqual({ sent: 0, skipped: 1, failed: 0 });
expect(db.outboundMessage.create.mock.calls[0]?.[0]).toMatchObject({
data: { status: 'SKIPPED', errorCode: 'no_whatsapp' },
});
expect(provider.send).not.toHaveBeenCalled();
});
it('skips owners whose templates are not approved yet', async () => {
db.payment.findMany.mockResolvedValue([payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456789' })]);
const provider = fakeProvider({ readiness: mock(async () => 'pending' as const) });
const totals = await reminders(provider).execute();
expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 });
expect(db.payment.findMany).not.toHaveBeenCalled();
});
it('paces sends and keeps going after a failure', async () => {
db.payment.findMany.mockResolvedValue([
payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456781' }),
payment('pay-2', { id: 'att-2', fullName: 'Beto', phone: '1123456782' }),
payment('pay-3', { id: 'att-3', fullName: 'Caro', phone: '1123456783' }),
]);
const send = mock(async () => ({ ok: true as const, providerMessageId: 'wamid' }));
send.mockResolvedValueOnce({ ok: true, providerMessageId: 'wamid-a' });
send.mockResolvedValueOnce({
ok: false,
retryable: true,
code: 'http_500',
message: 'engine error',
} as never);
const provider = fakeProvider({ send });
const totals = await reminders(provider).execute();
expect(totals).toEqual({ sent: 2, skipped: 0, failed: 1 });
expect(sleep).toHaveBeenCalledTimes(2);
expect(sleep).toHaveBeenCalledWith(5000);
expect(db.outboundMessage.update).toHaveBeenCalledWith({
where: { id: 'msg-2' },
data: { status: 'FAILED', errorCode: 'http_500', errorMessage: 'engine error' },
});
});
it('stops the account when the gateway rate limits it, freeing the unsent row', async () => {
db.payment.findMany.mockResolvedValue([
payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456781' }),
payment('pay-2', { id: 'att-2', fullName: 'Beto', phone: '1123456782' }),
]);
const send = mock(async () => ({
ok: false as const,
retryable: true,
rateLimitedForMs: 60_000,
code: 'SEND_PACING_LIMITED',
message: 'cap',
}));
const provider = fakeProvider({ send });
const totals = await reminders(provider).execute();
expect(totals).toEqual({ sent: 0, skipped: 1, failed: 0 });
expect(send).toHaveBeenCalledTimes(1);
expect(db.outboundMessage.delete).toHaveBeenCalledWith({ where: { id: 'msg-1' } });
});
it('does nothing when no group has the automation on', async () => {
db.group.findMany.mockResolvedValue([]);
const provider = fakeProvider();
const totals = await reminders(provider).execute();
expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 });
expect(provider.readiness).not.toHaveBeenCalled();
});
});
describe('re-engagement messages', () => {
function atRiskGroup() {
// Two sessions in the window, both missed by att-1: a streak of 2 (MEDIUM).
db.classSession.findMany.mockResolvedValue([{ id: 's1' }, { id: 's2' }]);
db.attendee.findMany
.mockResolvedValueOnce([
{ id: 'att-1', fullName: 'Ana López', phone: '1123456789' },
{ id: 'att-2', fullName: 'Beto', phone: '1198765432' },
])
.mockResolvedValueOnce([
{ id: 'att-1', phone: '1123456789', guardianPhone: null },
]);
db.attendance.findMany.mockResolvedValue([
{ attendeeId: 'att-1', status: 'ABSENT', classSession: { startsAt: new Date('2026-10-16T10:00:00Z') } },
{ attendeeId: 'att-1', status: 'ABSENT', classSession: { startsAt: new Date('2026-10-14T10:00:00Z') } },
{ attendeeId: 'att-2', status: 'PRESENT', classSession: { startsAt: new Date('2026-10-16T10:00:00Z') } },
{ attendeeId: 'att-2', status: 'PRESENT', classSession: { startsAt: new Date('2026-10-14T10:00:00Z') } },
]);
}
it('writes to the members at risk, with the copy of the manual button', async () => {
atRiskGroup();
const provider = fakeProvider();
const totals = await reengagement(provider).execute();
expect(db.group.findMany.mock.calls[0]?.[0]).toMatchObject({ where: { autoReengagement: true } });
expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 });
const [, , message] = (provider.send as ReturnType<typeof mock>).mock.calls[0] ?? [];
expect(message).toEqual({ kind: 'REENGAGEMENT', studentName: 'Ana López', groupName: 'Yoga Martes' });
});
it('leaves alone members written to in the last 14 days', async () => {
atRiskGroup();
db.outboundMessage.findMany.mockResolvedValue([{ attendeeId: 'att-1' }]);
const provider = fakeProvider();
const totals = await reengagement(provider).execute();
expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 });
expect(db.outboundMessage.findMany.mock.calls[0]?.[0]).toMatchObject({
where: {
kind: 'REENGAGEMENT',
attendeeId: { in: ['att-1'] },
status: { in: ['SENT', 'DELIVERED', 'READ'] },
createdAt: { gte: new Date('2026-10-05T13:00:00.000Z') },
},
});
expect(provider.send).not.toHaveBeenCalled();
});
});
describe('helpers', () => {
it('keys messages by ISO week', () => {
expect(isoWeekKey(new Date('2026-10-19T13:00:00Z'))).toBe('2026-W43');
expect(isoWeekKey(new Date('2026-10-25T23:59:00Z'))).toBe('2026-W43');
expect(isoWeekKey(new Date('2027-01-01T10:00:00Z'))).toBe('2026-W53');
expect(isoWeekKey(new Date('2025-12-29T10:00:00Z'))).toBe('2026-W01');
});
it('renders the free-text messages with the first name', () => {
expect(
renderMessage({
kind: 'PAYMENT_REMINDER',
studentName: 'Ana López',
groupName: 'Yoga',
amount: '$ 25.000',
dueDate: '20/10',
paymentLink: 'https://mpago.la/x',
}),
).toBe(
'¡Hola Ana! Te recordamos el pago de Yoga por $ 25.000, con vencimiento el 20/10. ' +
'Podés pagarlo desde este link: https://mpago.la/x',
);
expect(renderMessage({ kind: 'REENGAGEMENT', studentName: 'Ana López', groupName: 'Yoga' })).toStartWith(
'¡Hola Ana! 👋 Te extrañamos en Yoga.',
);
});
});
describe('toWhatsappE164', () => {
it.each([
['11 2345-6789', 'AR', '+5491123456789'],
['011 15 2345-6789', 'AR', '+5491123456789'],
['0351 15 123-4567', 'AR', '+5493511234567'],
['9 11 2345 6789', 'AR', '+5491123456789'],
['5491123456789', 'AR', '+5491123456789'],
['+54 11 2345 6789', 'AR', '+5491123456789'],
['+34 612 345 678', 'AR', '+34612345678'],
['0034612345678', 'AR', '+34612345678'],
['(11) 98765-4321', 'BR', '+5511987654321'],
['9 8765 4321', 'CL', '+56987654321'],
['300 123 4567', 'CO', '+573001234567'],
['55 1234 5678', 'MX', '+525512345678'],
['987 654 321', 'PE', '+51987654321'],
['099 123 456', 'UY', '+59899123456'],
] as const)('%s (%s) → %s', (input, country, expected) => {
expect(toWhatsappE164(input, country)).toBe(expected);
});
it.each([['', 'AR'], ['1234', 'AR'], ['12 3456', 'MX'], ['abc', 'UY']] as const)(
'rejects %p (%s)',
(input, country) => {
expect(toWhatsappE164(input, country)).toBeNull();
},
);
it('assumes Argentina when the teacher has no country yet', () => {
expect(toWhatsappE164('11 2345 6789', null)).toBe('+5491123456789');
});
});

View File

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