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:
@@ -1,4 +1,5 @@
|
||||
export * from './lib/attendance-risk.js';
|
||||
export * from './lib/phone.js';
|
||||
export * from './lib/problem-details.js';
|
||||
export * from './lib/result.js';
|
||||
export * from './schemas/analytics.js';
|
||||
@@ -15,4 +16,5 @@ export * from './schemas/pagination.js';
|
||||
export * from './schemas/payments.js';
|
||||
export * from './schemas/preregistrations.js';
|
||||
export * from './schemas/problem-details.js';
|
||||
export * from './schemas/waitlist.js';
|
||||
export * from './schemas/waitlist.js';
|
||||
export * from './schemas/whatsapp.js';
|
||||
100
packages/shared/src/lib/phone.ts
Normal file
100
packages/shared/src/lib/phone.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import type { CountryCode } from '../schemas/country.js';
|
||||
|
||||
type CountryDialPlan = {
|
||||
callingCode: string;
|
||||
// Length of the national number once the trunk prefix ("0") is gone.
|
||||
nationalLengths: readonly number[];
|
||||
};
|
||||
|
||||
const DIAL_PLANS: Record<CountryCode, CountryDialPlan> = {
|
||||
// Argentina is special-cased below (mobile "9" and the local "15").
|
||||
AR: { callingCode: '54', nationalLengths: [10] },
|
||||
BR: { callingCode: '55', nationalLengths: [10, 11] },
|
||||
CL: { callingCode: '56', nationalLengths: [9] },
|
||||
CO: { callingCode: '57', nationalLengths: [10] },
|
||||
MX: { callingCode: '52', nationalLengths: [10] },
|
||||
PE: { callingCode: '51', nationalLengths: [9] },
|
||||
UY: { callingCode: '598', nationalLengths: [8] },
|
||||
};
|
||||
|
||||
const MIN_E164_DIGITS = 10;
|
||||
const MAX_E164_DIGITS = 15;
|
||||
|
||||
/**
|
||||
* Turns a phone number as the teacher typed it into the E.164 form WhatsApp
|
||||
* expects (`+5491123456789`), or `null` when it cannot tell which number it is.
|
||||
*
|
||||
* Attendee phones are stored the way they were entered (`normalizePhone` keeps
|
||||
* digits only), so most of them are national numbers: the country of the teacher
|
||||
* decides the calling code. A number that already starts with `+` or `00` is
|
||||
* international and is kept as is.
|
||||
*
|
||||
* Argentina needs extra care: WhatsApp numbers there are `54 9 <area> <number>`,
|
||||
* while people write them as `0<area> 15 <number>` or `<area> <number>`.
|
||||
*/
|
||||
export function toWhatsappE164(phone: string, country: CountryCode | null | undefined): string | null {
|
||||
const trimmed = phone.trim();
|
||||
if (!trimmed) return null;
|
||||
|
||||
const isInternational = trimmed.startsWith('+') || trimmed.startsWith('00');
|
||||
let digits = trimmed.replace(/\D/g, '');
|
||||
if (trimmed.startsWith('00')) digits = digits.slice(2);
|
||||
if (!digits) return null;
|
||||
|
||||
if (isInternational) {
|
||||
return finalize(digits.startsWith('54') ? argentinaInternational(digits) : digits);
|
||||
}
|
||||
|
||||
const plan = DIAL_PLANS[country ?? 'AR'];
|
||||
|
||||
// Written with the calling code but without "+" (e.g. "5491123456789").
|
||||
if (digits.startsWith(plan.callingCode)) {
|
||||
const rest = digits.slice(plan.callingCode.length);
|
||||
if (country === 'AR' || !country) {
|
||||
const national = argentinaNational(rest);
|
||||
if (national) return finalize(`54${national}`);
|
||||
} else if (plan.nationalLengths.includes(rest.length)) {
|
||||
return finalize(digits);
|
||||
}
|
||||
}
|
||||
|
||||
if (country === 'AR' || !country) {
|
||||
const national = argentinaNational(digits);
|
||||
return national ? finalize(`54${national}`) : null;
|
||||
}
|
||||
|
||||
const national = digits.startsWith('0') ? digits.slice(1) : digits;
|
||||
if (!plan.nationalLengths.includes(national.length)) return null;
|
||||
return finalize(`${plan.callingCode}${national}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Argentine national number to `9<area><number>` (11 digits), accepting the
|
||||
* trunk "0", the mobile "9" and the local "15" after the area code.
|
||||
*/
|
||||
function argentinaNational(input: string): string | null {
|
||||
let digits = input.startsWith('0') ? input.slice(1) : input;
|
||||
if (digits.length === 11 && digits.startsWith('9')) digits = digits.slice(1);
|
||||
|
||||
if (digits.length === 12) {
|
||||
// Area codes are 2 to 4 digits long; the "15" goes right after them.
|
||||
for (const areaLength of [2, 3, 4]) {
|
||||
if (digits.slice(areaLength, areaLength + 2) === '15') {
|
||||
digits = digits.slice(0, areaLength) + digits.slice(areaLength + 2);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return digits.length === 10 ? `9${digits}` : null;
|
||||
}
|
||||
|
||||
function argentinaInternational(digits: string): string {
|
||||
const national = argentinaNational(digits.slice(2));
|
||||
return national ? `54${national}` : digits;
|
||||
}
|
||||
|
||||
function finalize(digits: string): string | null {
|
||||
if (digits.length < MIN_E164_DIGITS || digits.length > MAX_E164_DIGITS) return null;
|
||||
return `+${digits}`;
|
||||
}
|
||||
@@ -23,6 +23,9 @@ export const GroupDtoSchema = z.object({
|
||||
billingType: billingTypeSchema.nullable(),
|
||||
dueDay: z.number().int().min(1).max(28).nullable(),
|
||||
inviteToken: z.string().nullable().optional(),
|
||||
// Weekly WhatsApp automations (payment reminder and re-engagement).
|
||||
autoPaymentReminders: z.boolean(),
|
||||
autoReengagement: z.boolean(),
|
||||
});
|
||||
export type GroupDto = z.output<typeof GroupDtoSchema>;
|
||||
|
||||
|
||||
@@ -62,6 +62,8 @@ export type OnboardingStep = z.output<typeof onboardingStepSchema>;
|
||||
export const OnboardingStatusDtoSchema = z.object({
|
||||
step: onboardingStepSchema,
|
||||
paymentConnected: z.boolean(),
|
||||
// WhatsApp is its own skippable step and does not move `step`.
|
||||
whatsappConnected: z.boolean(),
|
||||
completed: z.boolean(),
|
||||
});
|
||||
export type OnboardingStatusDto = z.output<typeof OnboardingStatusDtoSchema>;
|
||||
111
packages/shared/src/schemas/whatsapp.ts
Normal file
111
packages/shared/src/schemas/whatsapp.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
// Which gateway the server sends WhatsApp messages through. The teacher never
|
||||
// picks it: it is a deployment setting (`WHATSAPP_PROVIDER`).
|
||||
export const whatsappProviderSchema = z.enum(['OPENWA', 'KAPSO']);
|
||||
export type WhatsappProvider = z.output<typeof whatsappProviderSchema>;
|
||||
|
||||
// State of the teacher's WhatsApp, as the app sees it.
|
||||
// - `pending`: linking started (QR on screen, or the teacher is at Meta).
|
||||
// - `requires_reconnect`: linked with a provider the server no longer uses.
|
||||
export const whatsappAccountStatusSchema = z.enum([
|
||||
'none',
|
||||
'pending',
|
||||
'active',
|
||||
'disconnected',
|
||||
'requires_reconnect',
|
||||
]);
|
||||
export type WhatsappAccountStatus = z.output<typeof whatsappAccountStatusSchema>;
|
||||
|
||||
export const whatsappMessageKindSchema = z.enum(['PAYMENT_REMINDER', 'REENGAGEMENT']);
|
||||
export type WhatsappMessageKind = z.output<typeof whatsappMessageKindSchema>;
|
||||
|
||||
// Whether automated messages of one kind can go out right now.
|
||||
// `pending`: the account is linked but Meta has not approved the template yet.
|
||||
export const whatsappReadinessSchema = z.enum(['ready', 'pending', 'blocked']);
|
||||
export type WhatsappReadiness = z.output<typeof whatsappReadinessSchema>;
|
||||
|
||||
export const whatsappReturnToSchema = z.enum(['onboarding', 'settings']);
|
||||
export type WhatsappReturnTo = z.output<typeof whatsappReturnToSchema>;
|
||||
|
||||
export const WhatsappConnectSchema = z.strictObject({
|
||||
returnTo: whatsappReturnToSchema.default('settings'),
|
||||
});
|
||||
export type WhatsappConnect = z.output<typeof WhatsappConnectSchema>;
|
||||
|
||||
// How the browser continues the linking: show a QR code (OpenWA) or navigate to
|
||||
// the provider's hosted flow (Kapso). The UI handles both without knowing which
|
||||
// provider is behind.
|
||||
export const WhatsappConnectionStartSchema = z.discriminatedUnion('type', [
|
||||
// `qrCode` is null while the gateway is still generating it; the status
|
||||
// endpoint delivers it (and every refresh) as soon as it exists.
|
||||
z.object({ type: z.literal('qr'), qrCode: z.string().nullable() }),
|
||||
z.object({ type: z.literal('redirect'), url: z.string() }),
|
||||
]);
|
||||
export type WhatsappConnectionStart = z.output<typeof WhatsappConnectionStartSchema>;
|
||||
|
||||
export const WhatsappConnectResultDtoSchema = z.object({
|
||||
start: WhatsappConnectionStartSchema,
|
||||
});
|
||||
export type WhatsappConnectResultDto = z.output<typeof WhatsappConnectResultDtoSchema>;
|
||||
|
||||
export const WhatsappStatusDtoSchema = z.object({
|
||||
status: whatsappAccountStatusSchema,
|
||||
provider: whatsappProviderSchema,
|
||||
displayPhoneNumber: z.string().nullable(),
|
||||
connectedAt: z.string().nullable(),
|
||||
// Fresh QR code (data URL) while a QR linking is pending; null otherwise.
|
||||
qrCode: z.string().nullable(),
|
||||
readiness: z.object({
|
||||
PAYMENT_REMINDER: whatsappReadinessSchema,
|
||||
REENGAGEMENT: whatsappReadinessSchema,
|
||||
}),
|
||||
});
|
||||
export type WhatsappStatusDto = z.output<typeof WhatsappStatusDtoSchema>;
|
||||
|
||||
export const WhatsappDisconnectResultDtoSchema = z.object({
|
||||
disconnected: z.boolean(),
|
||||
});
|
||||
export type WhatsappDisconnectResultDto = z.output<typeof WhatsappDisconnectResultDtoSchema>;
|
||||
|
||||
// Why a redirect-based linking (Kapso) failed. Codes only, never messages.
|
||||
export const whatsappCallbackReasonSchema = z.enum([
|
||||
// The setup link is unknown, belongs to someone else or was already used.
|
||||
'invalid_setup',
|
||||
// The teacher could not finish at Meta (login, verification, limits).
|
||||
'setup_failed',
|
||||
// The provider refused the request or could not be reached.
|
||||
'provider_error',
|
||||
// That number is already linked to another teacher.
|
||||
'number_in_use',
|
||||
]);
|
||||
export type WhatsappCallbackReason = z.output<typeof whatsappCallbackReasonSchema>;
|
||||
|
||||
// Deliberately not `strictObject`: the provider writes this query (Kapso adds
|
||||
// `business_account_id`, `display_phone_number` and others), and a strict schema
|
||||
// would answer extra keys with a 400 in the browser instead of the redirect.
|
||||
export const WhatsappCallbackQuerySchema = z.object({
|
||||
// `catch` and not `default`: a mangled value still lands the teacher in Settings.
|
||||
returnTo: whatsappReturnToSchema.catch('settings'),
|
||||
setup_link_id: z.string().min(1).optional(),
|
||||
status: z.string().optional(),
|
||||
phone_number_id: z.string().min(1).optional(),
|
||||
error_code: z.string().optional(),
|
||||
});
|
||||
export type WhatsappCallbackQuery = z.output<typeof WhatsappCallbackQuerySchema>;
|
||||
|
||||
export const UpdateGroupAutomationsSchema = z
|
||||
.strictObject({
|
||||
autoPaymentReminders: z.boolean().optional(),
|
||||
autoReengagement: z.boolean().optional(),
|
||||
})
|
||||
.refine((value) => value.autoPaymentReminders !== undefined || value.autoReengagement !== undefined, {
|
||||
message: 'Indicá al menos una automatización',
|
||||
});
|
||||
export type UpdateGroupAutomations = z.output<typeof UpdateGroupAutomationsSchema>;
|
||||
|
||||
export const GroupAutomationsDtoSchema = z.object({
|
||||
autoPaymentReminders: z.boolean(),
|
||||
autoReengagement: z.boolean(),
|
||||
});
|
||||
export type GroupAutomationsDto = z.output<typeof GroupAutomationsDtoSchema>;
|
||||
Reference in New Issue
Block a user