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

@@ -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);