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

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

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

View File

@@ -0,0 +1,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")
}