- Teacher picks a day of the month in Settings; an hourly job creates the fees of all monthly groups on that day in the teacher's time zone (one run per teacher and month, partial unique index per attendee/period). - One Mercado Pago link per payer (PaymentCheckout): the adult in charge bundles their kids and their own fees; external_reference chk_<id>, dedicated webhook and reconciliation mark every fee PAID at once. - Person.payWithMercadoPago toggle (default on): off creates the fee without a link so the student pays by transfer. - A fee paid some other way supersedes its combined link and expires the preference; renewing rebuilds the combined link or a single one. - Optional WhatsApp delivery (PAYMENT_LINK kind, new Kapso template); weekly reminders now go once per combined link. - Web: auto charge settings card, per-student toggle, combined link label in Cobros and "Pay all" in the student app, in the four locales. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
187 lines
6.0 KiB
TypeScript
187 lines
6.0 KiB
TypeScript
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;
|
|
}
|
|
| {
|
|
/** The monthly combined link, to whoever pays (the adult for kids). */
|
|
kind: 'PAYMENT_LINK';
|
|
studentName: string;
|
|
/** What it pays, e.g. "Yoga (Juan) y Natación (Ana)". */
|
|
detail: string;
|
|
amount: string;
|
|
dueDate: string;
|
|
paymentLink: 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>>;
|
|
|
|
/**
|
|
* Asks for a code to link by phone number instead of scanning the QR, for a
|
|
* linking already started with `startConnection`. `phoneDigits` is the
|
|
* teacher's number in international format, digits only. Only providers that
|
|
* link a WhatsApp Web session (OpenWA) implement it.
|
|
*/
|
|
requestPairingCode?(
|
|
account: WhatsappAccountRecord,
|
|
phoneDigits: string,
|
|
): Promise<Result<string, 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>;
|
|
}
|