181 lines
7.3 KiB
TypeScript
181 lines
7.3 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
|
|
import { publishOutboxEvent, type OutboxEventWriterTx, type OutboxPublisherTransaction } from "./outbox.js";
|
|
|
|
export const PRODUCT_ACQUISITION_PROVIDER_SIDE_EFFECT_EVENT =
|
|
"billing.product-acquisition.provider-side-effect" as const;
|
|
|
|
export const productAcquisitionProviderTerminalStatuses = [
|
|
"active",
|
|
"failed",
|
|
"cancelled",
|
|
"expired",
|
|
"refunded",
|
|
] as const;
|
|
|
|
export type ProductAcquisitionProviderTerminalStatus =
|
|
(typeof productAcquisitionProviderTerminalStatuses)[number];
|
|
|
|
export type ProductAcquisitionProviderSideEffectSource = {
|
|
readonly id: string;
|
|
readonly tenantId: string;
|
|
readonly productKind: "recurring_add_on" | "one_time_setup";
|
|
readonly status: ProductAcquisitionProviderTerminalStatus;
|
|
readonly providerAttempt: number;
|
|
readonly providerPaymentId?: string | null;
|
|
readonly invoiceExternalId?: string | null;
|
|
readonly lagoSubscriptionId?: string | null;
|
|
readonly lagoProviderSubscriptionId?: string | null;
|
|
readonly initialLagoInvoiceExternalId?: string | null;
|
|
};
|
|
|
|
export type ProductAcquisitionProviderSideEffectPayload = {
|
|
readonly acquisitionId: string;
|
|
readonly tenantId: string;
|
|
readonly productKind: "recurring_add_on" | "one_time_setup";
|
|
readonly acquisitionStatus: ProductAcquisitionProviderTerminalStatus;
|
|
readonly providerAttempt: number;
|
|
readonly providerPaymentId: string | null;
|
|
readonly paymentAttemptReference?: string | null;
|
|
readonly invoiceExternalId: string | null;
|
|
readonly lagoSubscriptionId: string | null;
|
|
readonly lagoProviderSubscriptionId?: string | null;
|
|
readonly action: "terminate_lago_subscription" | "mark_lago_invoice_succeeded" | "mark_lago_invoice_failed";
|
|
};
|
|
|
|
export type ProductAcquisitionProviderSideEffectEnvelope = {
|
|
readonly outboxEventId: string;
|
|
readonly deliveryGeneration: number;
|
|
readonly lockedUntil: string;
|
|
readonly tenantId: string;
|
|
readonly eventType: typeof PRODUCT_ACQUISITION_PROVIDER_SIDE_EFFECT_EVENT;
|
|
readonly dispatchKey: string;
|
|
readonly payload: ProductAcquisitionProviderSideEffectPayload;
|
|
};
|
|
|
|
export function buildProductAcquisitionProviderSideEffect(
|
|
source: ProductAcquisitionProviderSideEffectSource,
|
|
): ProductAcquisitionProviderSideEffectPayload | null {
|
|
return buildProductAcquisitionProviderSideEffects(source)[0] ?? null;
|
|
}
|
|
|
|
export function buildProductAcquisitionProviderSideEffects(
|
|
source: ProductAcquisitionProviderSideEffectSource,
|
|
): readonly ProductAcquisitionProviderSideEffectPayload[] {
|
|
const acquisitionId = requireIdentifier(source.id, "acquisition id");
|
|
const tenantId = requireIdentifier(source.tenantId, "tenant id");
|
|
const providerAttempt = Number.isSafeInteger(source.providerAttempt) && source.providerAttempt > 0
|
|
? source.providerAttempt
|
|
: 1;
|
|
const providerPaymentId = normalizeOptionalIdentifier(source.providerPaymentId);
|
|
const invoiceExternalId = normalizeOptionalIdentifier(source.invoiceExternalId);
|
|
const lagoSubscriptionId = normalizeOptionalIdentifier(source.lagoSubscriptionId);
|
|
const lagoProviderSubscriptionId = normalizeOptionalIdentifier(source.lagoProviderSubscriptionId);
|
|
const initialLagoInvoiceExternalId = normalizeOptionalIdentifier(source.initialLagoInvoiceExternalId);
|
|
|
|
if (source.productKind === "recurring_add_on") {
|
|
if (source.status === "active") {
|
|
// Lago finalizes the subscription-starting invoice asynchronously. The
|
|
// bounded reconciler republishes after it has persisted an exact match;
|
|
// activation itself must neither guess an invoice nor fail the payment.
|
|
if (!providerPaymentId || !invoiceExternalId || !lagoSubscriptionId || !lagoProviderSubscriptionId || !initialLagoInvoiceExternalId) return [];
|
|
return [{
|
|
acquisitionId,
|
|
tenantId,
|
|
productKind: source.productKind,
|
|
acquisitionStatus: source.status,
|
|
providerAttempt,
|
|
providerPaymentId,
|
|
paymentAttemptReference: invoiceExternalId,
|
|
invoiceExternalId: initialLagoInvoiceExternalId,
|
|
lagoSubscriptionId,
|
|
lagoProviderSubscriptionId,
|
|
action: "mark_lago_invoice_succeeded",
|
|
}];
|
|
}
|
|
if (!lagoSubscriptionId) {
|
|
throw new TypeError("Recurring acquisition side effect requires a Lago subscription id");
|
|
}
|
|
const effects: ProductAcquisitionProviderSideEffectPayload[] = [{
|
|
acquisitionId,
|
|
tenantId,
|
|
productKind: source.productKind,
|
|
acquisitionStatus: source.status,
|
|
providerAttempt,
|
|
providerPaymentId,
|
|
paymentAttemptReference: invoiceExternalId,
|
|
invoiceExternalId,
|
|
lagoSubscriptionId,
|
|
lagoProviderSubscriptionId,
|
|
action: "terminate_lago_subscription",
|
|
}];
|
|
// Once the starting invoice has been correlated, every terminal payment
|
|
// transition must converge both provider resources: stop the subscription
|
|
// and mark that exact invoice failed. Keeping these as separate durable
|
|
// events lets either provider mutation retry independently.
|
|
if (initialLagoInvoiceExternalId && (source.status === "failed" || source.status === "refunded")) {
|
|
effects.push({
|
|
acquisitionId,
|
|
tenantId,
|
|
productKind: source.productKind,
|
|
acquisitionStatus: source.status,
|
|
providerAttempt,
|
|
providerPaymentId,
|
|
paymentAttemptReference: invoiceExternalId,
|
|
invoiceExternalId: initialLagoInvoiceExternalId,
|
|
lagoSubscriptionId,
|
|
lagoProviderSubscriptionId,
|
|
action: "mark_lago_invoice_failed",
|
|
});
|
|
}
|
|
return effects;
|
|
}
|
|
|
|
if (!invoiceExternalId) {
|
|
throw new TypeError("One-time acquisition side effect requires an exact Lago invoice id");
|
|
}
|
|
return [{
|
|
acquisitionId,
|
|
tenantId,
|
|
productKind: source.productKind,
|
|
acquisitionStatus: source.status,
|
|
providerAttempt,
|
|
providerPaymentId,
|
|
paymentAttemptReference: null,
|
|
invoiceExternalId,
|
|
lagoSubscriptionId,
|
|
lagoProviderSubscriptionId,
|
|
action: source.status === "active" ? "mark_lago_invoice_succeeded" : "mark_lago_invoice_failed",
|
|
}];
|
|
}
|
|
|
|
export async function publishProductAcquisitionProviderSideEffect(
|
|
transaction: OutboxEventWriterTx,
|
|
source: ProductAcquisitionProviderSideEffectSource,
|
|
): Promise<void> {
|
|
for (const payload of buildProductAcquisitionProviderSideEffects(source)) {
|
|
const target = payload.action === "terminate_lago_subscription" ? payload.lagoSubscriptionId : payload.invoiceExternalId;
|
|
if (!target) throw new TypeError("Product acquisition provider side effect requires an exact provider target");
|
|
const targetHash = createHash("sha256").update(`${payload.action}:${target}`).digest("hex").slice(0, 20);
|
|
await publishOutboxEvent(transaction as OutboxPublisherTransaction, {
|
|
tenantId: payload.tenantId,
|
|
type: PRODUCT_ACQUISITION_PROVIDER_SIDE_EFFECT_EVENT,
|
|
dispatchKey: `billing-product:${payload.acquisitionId}:${payload.providerAttempt}:${payload.acquisitionStatus}:${targetHash}`,
|
|
payload,
|
|
});
|
|
}
|
|
}
|
|
|
|
function requireIdentifier(value: string, label: string): string {
|
|
const normalized = value.trim();
|
|
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{2,190}$/u.test(normalized)) {
|
|
throw new TypeError(`Invalid ${label}`);
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeOptionalIdentifier(value: string | null | undefined): string | null {
|
|
if (value == null) return null;
|
|
return requireIdentifier(value, "provider reference");
|
|
}
|