Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,6 +1,8 @@
export * from "./types.js";
export * from "./lago.js";
export * from "./mollie.js";
export * from "./mollie-payment-policy.js";
export * from "./payment-reservation.js";
export * from "./sync-outbox.js";
export * from "./sandbox-flow.js";
export * from "./webhook.js";
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { createLagoBillingGateway, LagoBillingGatewayError, normalizeLagoApiUrl, redactLagoValue } from "./lago.js";
import { createLagoBillingGateway, ensureActiveLagoSubscription, LagoBillingGatewayError, normalizeLagoApiUrl, redactLagoValue } from "./lago.js";
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
@@ -96,6 +96,8 @@ describe("LagoBillingGateway", () => {
planCode: "business",
seatQuantity: 5,
subscriptionAt: new Date("2026-07-04T00:00:00Z"),
paymentMethodType: "manual",
consolidateInvoice: false,
});
expect(subscription).toMatchObject({
@@ -113,10 +115,455 @@ describe("LagoBillingGateway", () => {
plan_code: "business",
billing_time: "anniversary",
subscription_at: "2026-07-04T00:00:00.000Z",
payment_method: { payment_method_type: "manual" },
consolidate_invoice: false,
});
expect(request.subscription).not.toHaveProperty("seatQuantity");
});
it("reuses the exact active plan version for idempotent paid return and webhook races", async () => {
const subscription = {
provider: "lago" as const,
externalId: "hgco_1",
providerSubscriptionId: "lago_subscription_1",
externalCustomerId: "tenant_1",
planCode: "hg_price_swarm_123",
status: "active" as const,
name: "swarm (20 seats)",
currentBillingPeriodStartedAt: "2026-08-01T00:00:00Z",
currentBillingPeriodEndingAt: "2026-09-01T00:00:00Z",
createdAt: "2026-08-01T00:00:00Z",
};
const gateway = {
getSubscription: vi.fn(async () => subscription),
createSubscription: vi.fn(),
} as unknown as Parameters<typeof ensureActiveLagoSubscription>[0];
const input = {
tenantId: "tenant_1",
subscriptionExternalId: "hgco_1",
planCode: "hg_price_swarm_123",
seatQuantity: 20,
paymentMethodType: "manual" as const,
consolidateInvoice: false,
};
const [fromReturn, fromWebhook] = await Promise.all([ensureActiveLagoSubscription(gateway, input), ensureActiveLagoSubscription(gateway, input)]);
expect(fromReturn.providerSubscriptionId).toBe("lago_subscription_1");
expect(fromWebhook.providerSubscriptionId).toBe("lago_subscription_1");
expect(gateway.getSubscription).toHaveBeenCalledTimes(2);
expect(gateway.createSubscription).not.toHaveBeenCalled();
});
it("creates and assigns an immutable managed plan without premium plan overrides", async () => {
const managedPlan = {
code: "hg_price_2026_07_29_1_starter_annual_sepa_abcd1234",
name: "Core · 4 Büro · 8 Baustelle · Speicher: +500 GB Speicher",
invoiceDisplayName: "Core · 4 Büro · 8 Baustelle · Speicher: +500 GB Speicher",
description: "Core · HiveGrid Katalog 2026-07-29.1",
interval: "monthly" as const,
amountCents: 38_170,
currency: "EUR",
payInAdvance: true,
taxCodes: ["de-vat-19"],
metadata: {
hivegrid_catalog_version: "2026-07-29.1",
hivegrid_resource_kind: "selected_price",
},
};
const providerPlan = {
plan: {
code: managedPlan.code,
name: managedPlan.name,
invoice_display_name: managedPlan.invoiceDisplayName,
description: managedPlan.description,
interval: managedPlan.interval,
amount_cents: managedPlan.amountCents,
amount_currency: managedPlan.currency,
pay_in_advance: managedPlan.payInAdvance,
taxes: [{ code: "de-vat-19" }],
metadata: managedPlan.metadata,
},
};
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(new Response("{}", { status: 404 }))
.mockResolvedValueOnce(jsonResponse(providerPlan))
.mockResolvedValueOnce(
jsonResponse({
subscription: {
lago_id: "lago_subscription_1",
external_id: "sub_tenant_1_core",
external_customer_id: "tenant_1",
plan_code: managedPlan.code,
status: "active",
name: "Acme GmbH · Core",
current_billing_period_started_at: null,
current_billing_period_ending_at: null,
created_at: "2026-07-29T00:00:00Z",
},
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl,
});
await expect(
gateway.createSubscription({
tenantId: "tenant_1",
subscriptionExternalId: "sub_tenant_1_core",
planCode: "starter_annual_sepa",
seatQuantity: 12,
name: "Acme GmbH · Core",
managedPlan,
})
).resolves.toMatchObject({
planCode: managedPlan.code,
externalId: "sub_tenant_1_core",
});
expect(fetchImpl.mock.calls.map((call) => [call[0], call[1]?.method])).toEqual([
[`https://lago.example.test/api/v1/plans/${managedPlan.code}`, "GET"],
["https://lago.example.test/api/v1/plans", "POST"],
["https://lago.example.test/api/v1/subscriptions", "POST"],
]);
expect(JSON.parse(String(fetchImpl.mock.calls[1]?.[1]?.body))).toEqual({
plan: {
name: managedPlan.name,
code: managedPlan.code,
invoice_display_name: managedPlan.invoiceDisplayName,
description: managedPlan.description,
interval: "monthly",
amount_cents: 38_170,
amount_currency: "EUR",
pay_in_advance: true,
tax_codes: ["de-vat-19"],
metadata: {
hivegrid_catalog_version: "2026-07-29.1",
hivegrid_resource_kind: "selected_price",
},
},
});
const subscriptionRequest = JSON.parse(String(fetchImpl.mock.calls[2]?.[1]?.body));
expect(subscriptionRequest.subscription.plan_code).toBe(managedPlan.code);
expect(subscriptionRequest.subscription).not.toHaveProperty("plan_overrides");
});
it("activates only the pending subscription and keeps the paid commitment end", async () => {
const pendingResponse = {
subscription: {
lago_id: "lago_pending_1",
external_id: "checkout_1",
external_customer_id: "tenant_1",
plan_code: "swarm",
status: "pending",
name: "Swarm",
current_billing_period_started_at: null,
current_billing_period_ending_at: null,
created_at: "2026-07-31T18:00:00Z",
},
};
const activeResponse = {
subscription: {
...pendingResponse.subscription,
status: "active",
current_billing_period_started_at: "2026-07-31T18:30:00Z",
current_billing_period_ending_at: "2026-08-31T18:30:00Z",
},
};
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(jsonResponse(pendingResponse))
.mockResolvedValueOnce(jsonResponse(pendingResponse))
.mockResolvedValueOnce(jsonResponse(activeResponse));
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
await expect(
gateway.activatePendingSubscription(" checkout_1 ", new Date("2026-07-31T18:30:00Z"), new Date("2027-07-31T18:30:00Z"))
).resolves.toMatchObject({ externalId: "checkout_1", status: "active" });
expect(fetchImpl.mock.calls.map((call) => [call[0], call[1]?.method])).toEqual([
["https://lago.example.test/api/v1/subscriptions/checkout_1?status=pending", "GET"],
["https://lago.example.test/api/v1/subscriptions/checkout_1?status=pending", "PUT"],
["https://lago.example.test/api/v1/subscriptions/checkout_1?status=active", "GET"],
]);
expect(JSON.parse(String(fetchImpl.mock.calls[1]?.[1]?.body))).toEqual({
subscription: {
status: "pending",
subscription_at: "2026-07-31T18:30:00.000Z",
ending_at: "2027-07-31T18:30:00.000Z",
},
});
});
it("waits for the exact pending Lago version instead of accepting an older active plan version", async () => {
vi.useFakeTimers();
const pendingResponse = {
subscription: {
lago_id: "lago_pending_2",
external_id: "checkout_2",
external_customer_id: "tenant_1",
plan_code: "colony",
status: "pending",
name: "Colony",
current_billing_period_started_at: null,
current_billing_period_ending_at: null,
created_at: "2026-07-31T18:00:00Z",
},
};
const olderActiveResponse = {
subscription: {
...pendingResponse.subscription,
lago_id: "lago_active_old",
plan_code: "swarm",
status: "active",
},
};
const exactActiveResponse = {
subscription: {
...pendingResponse.subscription,
status: "active",
current_billing_period_started_at: "2026-07-31T18:30:00Z",
current_billing_period_ending_at: "2026-08-31T18:30:00Z",
},
};
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(jsonResponse(pendingResponse))
.mockResolvedValueOnce(jsonResponse(pendingResponse))
.mockResolvedValueOnce(jsonResponse(olderActiveResponse))
.mockResolvedValueOnce(jsonResponse(exactActiveResponse));
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
const activation = gateway.activatePendingSubscription("checkout_2", "2026-07-31T18:30:00Z");
await vi.runAllTimersAsync();
await expect(activation).resolves.toMatchObject({ providerSubscriptionId: "lago_pending_2", status: "active" });
expect(fetchImpl).toHaveBeenCalledTimes(4);
vi.useRealTimers();
});
it("treats an already-active subscription activation as an idempotent replay", async () => {
const activeResponse = {
subscription: {
lago_id: "lago_active_1",
external_id: "checkout_1",
external_customer_id: "tenant_1",
plan_code: "swarm",
status: "active",
name: "Swarm",
current_billing_period_started_at: "2026-07-31T18:30:00Z",
current_billing_period_ending_at: "2026-08-31T18:30:00Z",
created_at: "2026-07-31T18:00:00Z",
},
};
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(new Response("{}", { status: 404 }))
.mockResolvedValueOnce(jsonResponse(activeResponse));
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
await expect(gateway.activatePendingSubscription("checkout_1", "2026-07-31T18:30:00Z")).resolves.toMatchObject({ status: "active" });
expect(fetchImpl.mock.calls.map((call) => [call[0], call[1]?.method])).toEqual([
["https://lago.example.test/api/v1/subscriptions/checkout_1?status=pending", "GET"],
["https://lago.example.test/api/v1/subscriptions/checkout_1?status=active", "GET"],
]);
});
it("terminates only a pending checkout subscription", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
subscription: {
lago_id: "lago_pending_1",
external_id: "checkout_1",
external_customer_id: "tenant_1",
plan_code: "swarm",
status: "canceled",
name: "Swarm",
current_billing_period_started_at: null,
current_billing_period_ending_at: null,
created_at: "2026-07-31T18:00:00Z",
},
})
);
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
await expect(gateway.terminatePendingSubscription("checkout_1")).resolves.toMatchObject({ status: "canceled" });
expect(fetchImpl).toHaveBeenCalledWith(
"https://lago.example.test/api/v1/subscriptions/checkout_1?status=pending",
expect.objectContaining({ method: "DELETE" })
);
});
it("reuses an exact managed plan and rejects immutable price drift", async () => {
const managedPlan = {
code: "hg_price_starter_exact",
name: "Core · 2 Büro · 5 Baustelle",
invoiceDisplayName: "Core · 2 Büro · 5 Baustelle",
description: "Core · HiveGrid Katalog 2026-07-29.1",
interval: "monthly" as const,
amountCents: 19_900,
currency: "EUR",
payInAdvance: true,
taxCodes: ["de-vat-19"],
metadata: { hivegrid_catalog_version: "2026-07-29.1" },
};
const providerPlan = {
plan: {
code: managedPlan.code,
name: managedPlan.name,
invoice_display_name: managedPlan.invoiceDisplayName,
description: managedPlan.description,
interval: managedPlan.interval,
amount_cents: managedPlan.amountCents,
amount_currency: managedPlan.currency,
pay_in_advance: managedPlan.payInAdvance,
taxes: [{ code: "de-vat-19" }],
metadata: managedPlan.metadata,
},
};
const subscriptionResponse = {
subscription: {
lago_id: "lago_subscription_exact",
external_id: "sub_exact",
external_customer_id: "tenant_1",
plan_code: managedPlan.code,
status: "active",
name: managedPlan.name,
current_billing_period_started_at: null,
current_billing_period_ending_at: null,
created_at: null,
},
};
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValueOnce(jsonResponse(providerPlan)).mockResolvedValueOnce(jsonResponse(subscriptionResponse));
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
await expect(
gateway.createSubscription({
tenantId: "tenant_1",
subscriptionExternalId: "sub_exact",
planCode: "starter",
seatQuantity: 7,
managedPlan,
})
).resolves.toMatchObject({ planCode: managedPlan.code });
expect(fetchImpl).toHaveBeenCalledTimes(2);
expect(fetchImpl.mock.calls[0]?.[1]?.method).toBe("GET");
expect(fetchImpl.mock.calls[1]?.[1]?.method).toBe("POST");
const driftFetch = vi.fn<typeof fetch>(async () =>
jsonResponse({
plan: {
...providerPlan.plan,
amount_cents: 19_901,
},
})
);
const driftGateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl: driftFetch,
});
await expect(
driftGateway.createSubscription({
tenantId: "tenant_1",
subscriptionExternalId: "sub_drift",
planCode: "starter",
seatQuantity: 7,
managedPlan,
})
).rejects.toMatchObject({
code: "RESPONSE_INVALID",
message: "Managed Lago plan conflicts with the requested immutable pricing.",
});
expect(driftFetch).toHaveBeenCalledTimes(1);
});
it("creates one-off invoices through a Lago add-on fee", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
invoice: {
lago_id: "invoice_setup_1",
number: "LAG-SETUP-001",
external_customer_id: "tenant_1",
status: "finalized",
payment_status: "pending",
invoice_type: "one_off",
currency: "EUR",
total_amount_cents: 29999,
issuing_date: "2026-07-16",
file_url: null,
},
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl,
});
await expect(
gateway.createOneOffInvoice({
tenantId: " tenant_1 ",
addOnCode: " portal_domain_setup ",
amountCents: 29999,
currency: "eur",
quantity: 1,
description: "Portal domain setup",
taxCodes: ["de-vat-19"],
})
).resolves.toMatchObject({
providerInvoiceId: "invoice_setup_1",
externalCustomerId: "tenant_1",
invoiceType: "one_off",
totalAmountCents: 29999,
paymentStatus: "pending",
});
expect(fetchImpl).toHaveBeenCalledWith(
"https://lago.example.test/api/v1/invoices",
expect.objectContaining({
method: "POST",
body: JSON.stringify({
invoice: {
external_customer_id: "tenant_1",
currency: "EUR",
fees: [
{
add_on_code: "portal_domain_setup",
units: 1,
unit_amount_cents: 29999,
tax_codes: ["de-vat-19"],
description: "Portal domain setup",
},
],
},
}),
})
);
});
it("rejects invalid one-off invoice inputs before contacting Lago", async () => {
const fetchImpl = vi.fn<typeof fetch>();
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
await expect(gateway.createOneOffInvoice({ tenantId: "tenant_1", addOnCode: "setup", amountCents: 0, currency: "EUR" })).rejects.toMatchObject({
code: "CONFIG_INVALID",
});
await expect(gateway.createOneOffInvoice({ tenantId: "tenant_1", addOnCode: " ", amountCents: 29999, currency: "EUR" })).rejects.toMatchObject({
code: "CONFIG_INVALID",
});
await expect(gateway.createOneOffInvoice({ tenantId: "tenant_1", addOnCode: "setup", amountCents: 29999, currency: "EURO" })).rejects.toMatchObject({
code: "CONFIG_INVALID",
});
await expect(
gateway.createOneOffInvoice({ tenantId: "tenant_1", addOnCode: "setup", amountCents: 29999, currency: "EUR", taxCodes: ["de-vat-19", "de-vat-19"] })
).rejects.toMatchObject({ code: "CONFIG_INVALID" });
expect(fetchImpl).not.toHaveBeenCalled();
});
it("reads invoice status with optional tenant filter", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
@@ -132,6 +579,13 @@ describe("LagoBillingGateway", () => {
total_amount_cents: 4900,
issuing_date: "2026-07-04",
file_url: "https://files.example.test/invoice_1.pdf",
billing_periods: [
{
external_subscription_id: "checkout_1",
lago_subscription_id: "lago_subscription_1",
invoicing_reason: "subscription_periodic",
},
],
},
],
})
@@ -155,11 +609,75 @@ describe("LagoBillingGateway", () => {
totalAmountCents: 4900,
issuingDate: "2026-07-04",
fileUrl: "https://files.example.test/invoice_1.pdf",
billingPeriods: [
{
externalSubscriptionId: "checkout_1",
providerSubscriptionId: "lago_subscription_1",
invoicingReason: "subscription_periodic",
},
],
subscriptionExternalIds: ["checkout_1"],
subscriptionProviderIds: ["lago_subscription_1"],
},
]);
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://lago.example.test/api/v1/invoices?external_customer_id=tenant_1&page=2&per_page=10");
});
it("reads an invoice detail with its exact subscription correlation", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
invoice: {
lago_id: "invoice_1",
number: "LAG-001",
external_customer_id: "tenant_1",
status: "finalized",
payment_status: "pending",
invoice_type: "subscription",
currency: "EUR",
total_amount_cents: 4_900,
issuing_date: "2026-08-01",
file_url: null,
billing_periods: [
{
external_subscription_id: " checkout_1 ",
lago_subscription_id: " lago_subscription_1 ",
invoicing_reason: "subscription_starting",
},
{
external_subscription_id: "checkout_1",
lago_subscription_id: "lago_subscription_1",
invoicing_reason: "future_lago_reason",
},
],
},
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl,
});
await expect(gateway.getInvoice("invoice_1")).resolves.toMatchObject({
providerInvoiceId: "invoice_1",
billingPeriods: [
{
externalSubscriptionId: "checkout_1",
providerSubscriptionId: "lago_subscription_1",
invoicingReason: "subscription_starting",
},
{
externalSubscriptionId: "checkout_1",
providerSubscriptionId: "lago_subscription_1",
invoicingReason: null,
},
],
subscriptionExternalIds: ["checkout_1"],
subscriptionProviderIds: ["lago_subscription_1"],
});
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://lago.example.test/api/v1/invoices/invoice_1");
});
it("downloads an invoice and maps the generated file url", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
@@ -253,6 +771,43 @@ describe("LagoBillingGateway", () => {
});
});
it("terminates active subscriptions and falls back to the required pending-status endpoint", async () => {
const terminated = {
subscription: {
lago_id: "lago_subscription_1",
external_id: "acquisition_1",
external_customer_id: "tenant_1",
plan_code: "customer_portal_monthly",
status: "terminated",
name: "Customer Portal",
current_billing_period_started_at: null,
current_billing_period_ending_at: null,
created_at: null,
},
};
const activeFetch = vi.fn<typeof fetch>(async () => jsonResponse(terminated));
const activeGateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl: activeFetch });
await expect(activeGateway.terminateSubscription(" acquisition_1 ")).resolves.toMatchObject({ status: "terminated" });
expect(activeFetch).toHaveBeenCalledWith("https://lago.example.test/api/v1/subscriptions/acquisition_1", expect.objectContaining({ method: "DELETE" }));
const pendingFetch = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(new Response("{}", { status: 405 }))
.mockResolvedValueOnce(jsonResponse(terminated));
const pendingGateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl: pendingFetch });
await expect(pendingGateway.terminateSubscription("acquisition_1")).resolves.toMatchObject({ status: "terminated" });
expect(pendingFetch.mock.calls[1]?.[0]).toBe("https://lago.example.test/api/v1/subscriptions/acquisition_1?status=pending");
expect(pendingFetch.mock.calls[1]?.[1]).toMatchObject({ method: "DELETE" });
});
it("treats two termination 404s as an idempotent already-terminated result", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () => new Response("{}", { status: 404 }));
const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl });
await expect(gateway.terminateSubscription("acquisition_1")).resolves.toBeNull();
expect(fetchImpl).toHaveBeenCalledTimes(2);
});
it("rejects invalid configuration and invalid response shapes", async () => {
expect(() => normalizeLagoApiUrl("file:///tmp/lago")).toThrow(LagoBillingGatewayError);
expect(() => createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: " " })).toThrow(LagoBillingGatewayError);
@@ -5,10 +5,14 @@ import type {
BillingGatewayCustomer,
BillingGatewayCustomerInput,
BillingGatewayInvoice,
BillingGatewayInvoiceInvoicingReason,
BillingGatewayInvoiceListInput,
BillingGatewayOneOffInvoiceInput,
BillingGatewaySubscription,
BillingGatewaySubscriptionInput,
BillingGatewaySubscriptionStatus,
} from "./types.js";
import { readBillingJsonResponse } from "./provider-http.js";
const DEFAULT_LAGO_TIMEOUT_MS = 10_000;
const DEFAULT_LAGO_PER_PAGE = 20;
@@ -55,6 +59,23 @@ const lagoSubscriptionSchema = z.object({
created_at: nullableString,
});
const lagoPlanSchema = z.object({
code: z.string(),
name: z.string(),
invoice_display_name: nullableString,
description: nullableString,
interval: z.string(),
amount_cents: z.number().int(),
amount_currency: z.string(),
pay_in_advance: z.boolean(),
taxes: z.array(
z.object({
code: z.string(),
})
),
metadata: z.record(z.string(), z.unknown()).nullable().optional(),
});
const lagoInvoiceSchema = z.object({
lago_id: z.string(),
number: nullableString,
@@ -72,13 +93,36 @@ const lagoInvoiceSchema = z.object({
total_amount_cents: z.number().nullable().optional(),
issuing_date: nullableString,
file_url: nullableString,
billing_periods: z
.array(
z.object({
external_subscription_id: nullableString,
lago_subscription_id: nullableString,
invoicing_reason: nullableString,
})
)
.nullable()
.optional(),
metadata: z
.array(
z.object({
key: z.string(),
value: z.string(),
})
)
.nullable()
.optional(),
});
const customerResponseSchema = z.object({ customer: lagoCustomerSchema });
const subscriptionResponseSchema = z.object({ subscription: lagoSubscriptionSchema });
const planResponseSchema = z.object({ plan: lagoPlanSchema });
const invoiceResponseSchema = z.object({ invoice: lagoInvoiceSchema });
const invoicesResponseSchema = z.object({ invoices: z.array(lagoInvoiceSchema) });
const subscriptionActivationReadAttempts = 5;
const subscriptionActivationReadDelayMs = 100;
type LagoCustomer = z.infer<typeof lagoCustomerSchema>;
type LagoSubscription = z.infer<typeof lagoSubscriptionSchema>;
type LagoInvoice = z.infer<typeof lagoInvoiceSchema>;
@@ -147,15 +191,19 @@ class LagoBillingGateway implements BillingGateway {
async createSubscription(input: BillingGatewaySubscriptionInput): Promise<BillingGatewaySubscription> {
assertPositiveSeatQuantity(input.seatQuantity);
const managedPlan = normalizeManagedPlan(input.managedPlan);
if (managedPlan) await this.ensureManagedPlan(managedPlan);
const response = await this.request("/subscriptions", {
method: "POST",
body: {
subscription: {
external_customer_id: input.tenantId,
external_id: input.subscriptionExternalId,
plan_code: input.planCode,
plan_code: managedPlan?.code ?? input.planCode,
name: input.name ?? `${input.planCode} (${input.seatQuantity} seats)`,
billing_time: "anniversary",
...(input.paymentMethodType ? { payment_method: { payment_method_type: input.paymentMethodType } } : {}),
...(typeof input.consolidateInvoice === "boolean" ? { consolidate_invoice: input.consolidateInvoice } : {}),
...(input.subscriptionAt ? { subscription_at: toIsoString(input.subscriptionAt) } : {}),
...(input.endingAt ? { ending_at: toIsoString(input.endingAt) } : {}),
},
@@ -164,20 +212,178 @@ class LagoBillingGateway implements BillingGateway {
return toSubscription(parseLagoResponse(subscriptionResponseSchema, response));
}
async getSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null> {
const response = await this.request(`/subscriptions/${encodeURIComponent(subscriptionExternalId)}`, { method: "GET", allowNotFound: true });
async ensureManagedPlan(planInput: NonNullable<BillingGatewaySubscriptionInput["managedPlan"]>): Promise<void> {
const plan = normalizeManagedPlan(planInput);
if (!plan) {
throw new LagoBillingGatewayError("Managed plan is required.", "CONFIG_INVALID");
}
const path = `/plans/${encodeURIComponent(plan.code)}`;
let response = await this.request(path, { method: "GET", allowNotFound: true });
if (response === null) {
try {
response = await this.request("/plans", {
method: "POST",
body: {
plan: {
name: plan.name,
code: plan.code,
invoice_display_name: plan.invoiceDisplayName,
description: plan.description,
interval: plan.interval,
amount_cents: plan.amountCents,
amount_currency: plan.currency,
pay_in_advance: plan.payInAdvance,
tax_codes: plan.taxCodes,
metadata: plan.metadata,
},
},
});
} catch (error) {
if (!(error instanceof LagoBillingGatewayError) || (error.status !== 409 && error.status !== 422)) throw error;
response = await this.request(path, { method: "GET" });
}
}
assertManagedPlanMatches(plan, parseLagoResponse(planResponseSchema, response).plan);
}
async getSubscription(subscriptionExternalId: string, status?: BillingGatewaySubscriptionStatus): Promise<BillingGatewaySubscription | null> {
const id = normalizeSubscriptionExternalId(subscriptionExternalId);
const query = status ? `?status=${encodeURIComponent(status)}` : "";
const response = await this.request(`/subscriptions/${encodeURIComponent(id)}${query}`, { method: "GET", allowNotFound: true });
return response === null ? null : toSubscription(parseLagoResponse(subscriptionResponseSchema, response));
}
async activatePendingSubscription(
subscriptionExternalId: string,
activatedAt: Date | string,
endingAt?: Date | string | null
): Promise<BillingGatewaySubscription | null> {
const id = normalizeSubscriptionExternalId(subscriptionExternalId);
const pending = await this.getSubscription(id, "pending");
if (!pending) return this.getSubscription(id, "active");
const response = await this.request(`/subscriptions/${encodeURIComponent(id)}?status=pending`, {
method: "PUT",
allowNotFound: true,
body: {
subscription: {
status: "pending",
subscription_at: toIsoString(activatedAt),
...(endingAt === undefined ? {} : { ending_at: endingAt === null ? null : toIsoString(endingAt) }),
},
},
});
const updated = response === null ? null : toSubscription(parseLagoResponse(subscriptionResponseSchema, response));
if (updated?.status === "active" && updated.providerSubscriptionId === pending.providerSubscriptionId) return updated;
// Lago v1.50 may return the selected pending version even though moving
// subscription_at has already started the same provider version. Re-read
// the active view and require the exact Lago id so an older active version
// from a plan change can never satisfy this payment confirmation.
for (let attempt = 0; attempt < subscriptionActivationReadAttempts; attempt += 1) {
const active = await this.getSubscription(id, "active");
if (active?.providerSubscriptionId === pending.providerSubscriptionId) return active;
if (attempt < subscriptionActivationReadAttempts - 1) {
await new Promise((resolve) => setTimeout(resolve, subscriptionActivationReadDelayMs * (attempt + 1)));
}
}
return updated;
}
async terminatePendingSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null> {
const id = normalizeSubscriptionExternalId(subscriptionExternalId);
const response = await this.request(`/subscriptions/${encodeURIComponent(id)}?status=pending`, {
method: "DELETE",
allowNotFound: true,
});
return response === null ? null : toSubscription(parseLagoResponse(subscriptionResponseSchema, response));
}
async terminateSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null> {
const id = normalizeSubscriptionExternalId(subscriptionExternalId);
let active: unknown | null;
try {
active = await this.request(`/subscriptions/${encodeURIComponent(id)}`, { method: "DELETE", allowNotFound: true });
} catch (error) {
// Lago may answer 405 when the external id currently resolves only to a
// pending subscription. That case must be retried with status=pending.
if (!(error instanceof LagoBillingGatewayError) || error.status !== 405) throw error;
active = null;
}
if (active !== null) return toSubscription(parseLagoResponse(subscriptionResponseSchema, active));
// Lago requires an explicit status filter when the subscription has not
// started yet. A second 404 is an idempotent already-terminated result.
const pending = await this.request(`/subscriptions/${encodeURIComponent(id)}?status=pending`, {
method: "DELETE",
allowNotFound: true,
});
return pending === null ? null : toSubscription(parseLagoResponse(subscriptionResponseSchema, pending));
}
async createOneOffInvoice(input: BillingGatewayOneOffInvoiceInput): Promise<BillingGatewayInvoice> {
const tenantId = input.tenantId.trim();
const addOnCode = input.addOnCode.trim();
const quantity = input.quantity ?? 1;
const currency = input.currency.trim().toUpperCase();
if (!tenantId) throw new LagoBillingGatewayError("Tenant id is required.", "CONFIG_INVALID");
if (!addOnCode) throw new LagoBillingGatewayError("Add-on code is required.", "CONFIG_INVALID");
if (!Number.isInteger(quantity) || quantity < 1) {
throw new LagoBillingGatewayError("One-off invoice quantity must be a positive integer.", "CONFIG_INVALID");
}
if (!Number.isInteger(input.amountCents) || input.amountCents <= 0) {
throw new LagoBillingGatewayError("One-off invoice amount must be a positive cent integer.", "CONFIG_INVALID");
}
if (!/^[A-Z]{3}$/u.test(currency)) {
throw new LagoBillingGatewayError("One-off invoice currency must be a three-letter ISO code.", "CONFIG_INVALID");
}
const taxCodes = normalizeTaxCodes(input.taxCodes ?? [], "One-off invoice");
const metadata = normalizeInvoiceMetadata(input.metadata);
const response = await this.request("/invoices", {
method: "POST",
body: {
invoice: {
external_customer_id: tenantId,
currency,
fees: [
{
add_on_code: addOnCode,
units: quantity,
unit_amount_cents: input.amountCents,
...(taxCodes.length > 0 ? { tax_codes: taxCodes } : {}),
...(input.description?.trim() ? { description: input.description.trim() } : {}),
},
],
...(metadata.length > 0 ? { metadata } : {}),
},
},
});
return toInvoice(parseLagoResponse(invoiceResponseSchema, response).invoice);
}
async listInvoices(input: BillingGatewayInvoiceListInput = {}): Promise<BillingGatewayInvoice[]> {
const query = new URLSearchParams();
if (input.tenantId) query.set("external_customer_id", input.tenantId);
for (const [key, value] of Object.entries(input.metadata ?? {}).sort(([left], [right]) => left.localeCompare(right))) {
query.set(`metadata[${key}]`, value);
}
query.set("page", String(input.page ?? 1));
query.set("per_page", String(input.perPage ?? DEFAULT_LAGO_PER_PAGE));
const response = await this.request(`/invoices?${query.toString()}`, { method: "GET" });
return parseLagoResponse(invoicesResponseSchema, response).invoices.map(toInvoice);
}
async getInvoice(providerInvoiceId: string): Promise<BillingGatewayInvoice | null> {
const id = providerInvoiceId.trim();
if (!id) {
throw new LagoBillingGatewayError("Invoice id is required.", "CONFIG_INVALID");
}
const response = await this.request(`/invoices/${encodeURIComponent(id)}`, { method: "GET", allowNotFound: true });
return response === null ? null : toInvoice(parseLagoResponse(invoiceResponseSchema, response).invoice);
}
async downloadInvoice(providerInvoiceId: string): Promise<BillingGatewayInvoice | null> {
const id = providerInvoiceId.trim();
if (!id) {
@@ -206,7 +412,10 @@ class LagoBillingGateway implements BillingGateway {
return toInvoice(parseLagoResponse(invoiceResponseSchema, response).invoice);
}
private async request(path: string, options: { method: "GET" | "POST" | "PUT"; body?: unknown; allowNotFound?: boolean }): Promise<unknown | null> {
private async request(
path: string,
options: { method: "GET" | "POST" | "PUT" | "DELETE"; body?: unknown; allowNotFound?: boolean }
): Promise<unknown | null> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
try {
@@ -218,6 +427,7 @@ class LagoBillingGateway implements BillingGateway {
...(options.body ? { "content-type": "application/json" } : {}),
},
body: options.body ? JSON.stringify(options.body) : undefined,
redirect: "error",
signal: controller.signal,
});
if (response.status === 404 && options.allowNotFound) {
@@ -226,7 +436,7 @@ class LagoBillingGateway implements BillingGateway {
if (!response.ok) {
throw new LagoBillingGatewayError(`Lago request failed with status ${response.status}.`, "REQUEST_FAILED", response.status);
}
return await response.json();
return await readBillingJsonResponse(response);
} catch (error) {
if (error instanceof LagoBillingGatewayError) throw error;
throw new LagoBillingGatewayError("Lago request failed.", "REQUEST_FAILED");
@@ -236,6 +446,35 @@ class LagoBillingGateway implements BillingGateway {
}
}
const activeSubscriptionReadAttempts = 5;
const activeSubscriptionReadDelayMs = 100;
export async function ensureActiveLagoSubscription(
gateway: BillingGateway,
input: Omit<BillingGatewaySubscriptionInput, "subscriptionAt" | "managedPlan">
): Promise<BillingGatewaySubscription> {
const expectedPlanCode = input.planCode.trim();
const existing = await gateway.getSubscription(input.subscriptionExternalId, "active");
if (existing?.status === "active" && existing.planCode === expectedPlanCode) return existing;
try {
const created = await gateway.createSubscription(input);
if (created.status === "active" && created.planCode === expectedPlanCode) return created;
} catch (error) {
if (!(error instanceof LagoBillingGatewayError) || (error.status !== 409 && error.status !== 422)) throw error;
}
for (let attempt = 0; attempt < activeSubscriptionReadAttempts; attempt += 1) {
const active = await gateway.getSubscription(input.subscriptionExternalId, "active");
if (active?.status === "active" && active.planCode === expectedPlanCode) return active;
if (attempt < activeSubscriptionReadAttempts - 1) {
await new Promise((resolve) => setTimeout(resolve, activeSubscriptionReadDelayMs * (attempt + 1)));
}
}
throw new LagoBillingGatewayError("Lago subscription could not be created as the requested active version.", "REQUEST_FAILED");
}
function parseLagoResponse<T>(schema: z.ZodType<T>, response: unknown): T {
const result = schema.safeParse(response);
if (!result.success) {
@@ -274,6 +513,18 @@ function toSubscription(response: { subscription: LagoSubscription }): BillingGa
}
function toInvoice(invoice: LagoInvoice): BillingGatewayInvoice {
const metadata = Object.fromEntries((invoice.metadata ?? []).map((item) => [item.key, item.value]));
const billingPeriods = (invoice.billing_periods ?? []).map((period) => ({
externalSubscriptionId: normalizeOptionalString(period.external_subscription_id),
providerSubscriptionId: normalizeOptionalString(period.lago_subscription_id),
invoicingReason: normalizeInvoiceInvoicingReason(period.invoicing_reason),
}));
const subscriptionExternalIds = [
...new Set(billingPeriods.map((period) => period.externalSubscriptionId).filter((value): value is string => value !== null)),
];
const subscriptionProviderIds = [
...new Set(billingPeriods.map((period) => period.providerSubscriptionId).filter((value): value is string => value !== null)),
];
return {
provider: "lago",
providerInvoiceId: invoice.lago_id,
@@ -286,9 +537,37 @@ function toInvoice(invoice: LagoInvoice): BillingGatewayInvoice {
totalAmountCents: invoice.total_amount_cents ?? null,
issuingDate: invoice.issuing_date ?? null,
fileUrl: invoice.file_url ?? null,
...(billingPeriods.length > 0 ? { billingPeriods } : {}),
...(subscriptionExternalIds.length > 0 ? { subscriptionExternalIds } : {}),
...(subscriptionProviderIds.length > 0 ? { subscriptionProviderIds } : {}),
...(Object.keys(metadata).length > 0 ? { metadata } : {}),
};
}
function normalizeOptionalString(value: string | null | undefined): string | null {
const normalized = value?.trim();
return normalized ? normalized : null;
}
function normalizeInvoiceInvoicingReason(value: string | null | undefined): BillingGatewayInvoiceInvoicingReason | null {
const normalized = normalizeOptionalString(value);
if (normalized === "subscription_starting" || normalized === "subscription_periodic") return normalized;
return null;
}
function normalizeInvoiceMetadata(metadata: Readonly<Record<string, string>> | undefined): Array<{ key: string; value: string }> {
return Object.entries(metadata ?? {})
.sort(([left], [right]) => left.localeCompare(right))
.map(([rawKey, rawValue]) => {
const key = rawKey.trim();
const value = rawValue.trim();
if (!/^[A-Za-z0-9_.-]{1,20}$/u.test(key) || value.length < 1 || value.length > 255) {
throw new LagoBillingGatewayError("Invoice metadata is invalid.", "CONFIG_INVALID");
}
return { key, value };
});
}
function normalizeTimeout(timeoutMs: number | undefined): number {
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.trunc(timeoutMs) : DEFAULT_LAGO_TIMEOUT_MS;
}
@@ -299,6 +578,96 @@ function assertPositiveSeatQuantity(seatQuantity: number): void {
}
}
type NormalizedManagedPlan = NonNullable<BillingGatewaySubscriptionInput["managedPlan"]>;
function normalizeManagedPlan(value: BillingGatewaySubscriptionInput["managedPlan"]): NormalizedManagedPlan | null {
if (!value) return null;
const code = value.code.trim();
if (!/^[A-Za-z0-9_-]{1,120}$/u.test(code)) {
throw new LagoBillingGatewayError("Managed plan code is invalid.", "CONFIG_INVALID");
}
const name = normalizeManagedPlanText(value.name, "name");
const invoiceDisplayName = normalizeManagedPlanText(value.invoiceDisplayName, "invoice display name");
const description = normalizeManagedPlanText(value.description, "description");
if (!Number.isSafeInteger(value.amountCents) || value.amountCents <= 0) {
throw new LagoBillingGatewayError("Managed plan amount must be a positive cent integer.", "CONFIG_INVALID");
}
const currency = value.currency.trim().toUpperCase();
if (!/^[A-Z]{3}$/u.test(currency)) {
throw new LagoBillingGatewayError("Managed plan currency must be a three-letter ISO code.", "CONFIG_INVALID");
}
const taxCodes = normalizeTaxCodes(value.taxCodes, "Managed plan");
const metadata = Object.fromEntries(
Object.entries(value.metadata)
.sort(([left], [right]) => left.localeCompare(right))
.map(([rawKey, rawValue]) => {
const key = rawKey.trim();
const metadataValue = rawValue.trim();
if (!/^[A-Za-z0-9_.-]{1,64}$/u.test(key) || metadataValue.length < 1 || metadataValue.length > 255) {
throw new LagoBillingGatewayError("Managed plan metadata is invalid.", "CONFIG_INVALID");
}
return [key, metadataValue];
})
);
return {
code,
name,
invoiceDisplayName,
description,
interval: value.interval,
amountCents: value.amountCents,
currency,
payInAdvance: value.payInAdvance,
taxCodes,
metadata,
};
}
function normalizeTaxCodes(values: readonly string[], label: string): string[] {
const taxCodes = [...new Set(values.map((taxCode) => taxCode.trim()).filter(Boolean))].sort();
if (taxCodes.length !== values.length || taxCodes.some((taxCode) => !/^[A-Za-z0-9_-]{1,100}$/u.test(taxCode))) {
throw new LagoBillingGatewayError(`${label} tax codes are invalid.`, "CONFIG_INVALID");
}
return taxCodes;
}
function normalizeManagedPlanText(value: string, label: string): string {
const normalized = value.trim();
if (!normalized || normalized.length > 255) {
throw new LagoBillingGatewayError(`Managed plan ${label} is invalid.`, "CONFIG_INVALID");
}
return normalized;
}
function assertManagedPlanMatches(expected: NormalizedManagedPlan, actual: z.infer<typeof lagoPlanSchema>): void {
const actualMetadata = Object.fromEntries(
Object.entries(actual.metadata ?? {})
.filter((entry): entry is [string, string] => typeof entry[1] === "string")
.sort(([left], [right]) => left.localeCompare(right))
);
const actualTaxCodes = actual.taxes.map((tax) => tax.code).sort();
const matches =
actual.code === expected.code &&
actual.name === expected.name &&
(actual.invoice_display_name ?? "") === expected.invoiceDisplayName &&
(actual.description ?? "") === expected.description &&
actual.interval === expected.interval &&
actual.amount_cents === expected.amountCents &&
actual.amount_currency.toUpperCase() === expected.currency &&
actual.pay_in_advance === expected.payInAdvance &&
JSON.stringify(actualTaxCodes) === JSON.stringify(expected.taxCodes) &&
JSON.stringify(actualMetadata) === JSON.stringify(expected.metadata);
if (!matches) {
throw new LagoBillingGatewayError("Managed Lago plan conflicts with the requested immutable pricing.", "RESPONSE_INVALID");
}
}
function normalizeSubscriptionExternalId(value: string): string {
const id = value.trim();
if (!id) throw new LagoBillingGatewayError("Subscription external id is required.", "CONFIG_INVALID");
return id;
}
function toIsoString(value: Date | string): string {
return value instanceof Date ? value.toISOString() : value;
}
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vitest";
import {
defaultMollieFirstPaymentMethod,
MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS,
requiresMollieCardForAmount,
resolveMollieCheckoutPaymentMethodRequirement,
resolveMollieRecurringPaymentMethod,
selectMollieRecurringMandate,
} from "./mollie-payment-policy.js";
describe("Mollie payment policy", () => {
it("switches from SEPA to card only above the exact EUR 1,000 boundary", () => {
expect(requiresMollieCardForAmount({ amountCents: MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS, currency: "eur" })).toBe(false);
expect(requiresMollieCardForAmount({ amountCents: MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS + 1, currency: "EUR" })).toBe(true);
expect(
resolveMollieCheckoutPaymentMethodRequirement({
amountCents: MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS + 1,
currency: "EUR",
configuredRequirement: "sepa",
})
).toBe("card");
});
it("keeps the configured method contract at or below the boundary", () => {
expect(
resolveMollieCheckoutPaymentMethodRequirement({
amountCents: MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS,
currency: "EUR",
configuredRequirement: "sepa",
})
).toBe("sepa");
expect(resolveMollieCheckoutPaymentMethodRequirement({ amountCents: 29_900, currency: "EUR", configuredRequirement: "any" })).toBe("any");
});
it("pins high-value first and recurring payments to credit card", () => {
expect(defaultMollieFirstPaymentMethod("card", ["ideal"])).toBe("creditcard");
expect(resolveMollieRecurringPaymentMethod({ amountCents: 100_001, currency: "EUR", billingCadence: "monthly" })).toBe("creditcard");
expect(resolveMollieRecurringPaymentMethod({ amountCents: 100_000, currency: "EUR", billingCadence: "annual_sepa" })).toBeNull();
});
it("uses the latest valid customer-selected mandate below the boundary", () => {
expect(
selectMollieRecurringMandate({
amountCents: 100_000,
currency: "EUR",
mandates: [
{ provider: "mollie", providerMandateId: "mdt_sepa", status: "valid", method: "directdebit", createdAt: "2026-08-01T10:00:00.000Z" },
{ provider: "mollie", providerMandateId: "mdt_card", status: "valid", method: "creditcard", createdAt: "2026-08-02T10:00:00.000Z" },
],
})
).toMatchObject({ providerMandateId: "mdt_card", method: "creditcard" });
});
it("requires a valid card mandate above the boundary without SEPA fallback", () => {
const mandates = [
{ provider: "mollie" as const, providerMandateId: "mdt_sepa", status: "valid" as const, method: "directdebit" as const, createdAt: null },
{ provider: "mollie" as const, providerMandateId: "mdt_pending", status: "pending" as const, method: "creditcard" as const, createdAt: null },
];
expect(selectMollieRecurringMandate({ amountCents: 100_001, currency: "EUR", mandates })).toBeNull();
});
it("rejects malformed amounts and currencies before choosing a method", () => {
expect(() => requiresMollieCardForAmount({ amountCents: -1, currency: "EUR" })).toThrow("non-negative integer");
expect(() => requiresMollieCardForAmount({ amountCents: 100_001, currency: "EURO" })).toThrow("ISO 4217");
});
});
@@ -0,0 +1,63 @@
import type { MolliePaymentMethodId, MollieSepaFirstPaymentMethod, PaymentGatewayMandate } from "./types.js";
/** Mollie's documented default upper limit for one SEPA Direct Debit charge. */
export const MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS = 100_000;
export type MollieCheckoutPaymentMethodRequirement = "any" | "sepa" | "card";
type MollieAmountInput = {
readonly amountCents: number;
readonly currency: string;
};
function normalizeMollieAmount(input: MollieAmountInput): { amountCents: number; currency: string } {
if (!Number.isSafeInteger(input.amountCents) || input.amountCents < 0) {
throw new TypeError("Mollie payment amount must be a non-negative integer.");
}
const currency = input.currency.trim().toUpperCase();
if (!/^[A-Z]{3}$/u.test(currency)) {
throw new TypeError("Mollie payment currency must be an ISO 4217 code.");
}
return { amountCents: input.amountCents, currency };
}
export function requiresMollieCardForAmount(input: MollieAmountInput): boolean {
const normalized = normalizeMollieAmount(input);
return normalized.currency === "EUR" && normalized.amountCents > MOLLIE_SEPA_DIRECT_DEBIT_MAX_EUR_CENTS;
}
export function resolveMollieCheckoutPaymentMethodRequirement(
input: MollieAmountInput & { readonly configuredRequirement: MollieCheckoutPaymentMethodRequirement }
): MollieCheckoutPaymentMethodRequirement {
if (input.configuredRequirement === "card" || requiresMollieCardForAmount(input)) return "card";
return input.configuredRequirement;
}
export function defaultMollieFirstPaymentMethod(
requirement: MollieCheckoutPaymentMethodRequirement,
sepaFirstPaymentMethods: readonly MollieSepaFirstPaymentMethod[]
): MolliePaymentMethodId | readonly MollieSepaFirstPaymentMethod[] | null {
if (requirement === "card") return "creditcard";
if (requirement === "sepa") return sepaFirstPaymentMethods;
return null;
}
export function resolveMollieRecurringPaymentMethod(input: MollieAmountInput & { readonly billingCadence?: string }): MolliePaymentMethodId | null {
if (requiresMollieCardForAmount(input)) return "creditcard";
return null;
}
export function selectMollieRecurringMandate(
input: MollieAmountInput & { readonly mandates: readonly PaymentGatewayMandate[] }
): PaymentGatewayMandate | null {
const cardRequired = requiresMollieCardForAmount(input);
const eligible = input.mandates.filter(
(mandate) => mandate.status === "valid" && (cardRequired ? mandate.method === "creditcard" : mandate.method === "creditcard" || mandate.method === "directdebit")
);
return eligible.reduce<PaymentGatewayMandate | null>((latest, candidate) => {
if (!latest) return candidate;
const latestCreatedAt = latest.createdAt ? Date.parse(latest.createdAt) : Number.NEGATIVE_INFINITY;
const candidateCreatedAt = candidate.createdAt ? Date.parse(candidate.createdAt) : Number.NEGATIVE_INFINITY;
return candidateCreatedAt > latestCreatedAt ? candidate : latest;
}, null);
}
@@ -21,6 +21,7 @@ function jsonResponse(body: unknown, status = 200): Response {
function molliePayment(overrides: Record<string, unknown> = {}) {
return {
id: "tr_123",
customerId: null,
status: "open",
amount: { currency: "EUR", value: "49.00" },
amountRefunded: { currency: "EUR", value: "0.00" },
@@ -31,10 +32,14 @@ function molliePayment(overrides: Record<string, unknown> = {}) {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
paymentExternalId: "payment_1",
mollieCustomerId: null,
lagoCustomerId: null,
lagoSubscriptionId: null,
planCode: null,
seatQuantity: null,
trialEndsAt: null,
changeEffectiveAt: null,
changeEffectiveAtDate: null,
},
_links: {
checkout: { href: "https://www.mollie.com/checkout/select-method/tr_123" },
@@ -43,8 +48,178 @@ function molliePayment(overrides: Record<string, unknown> = {}) {
};
}
function mollieCustomer(overrides: Record<string, unknown> = {}) {
return {
id: "cst_123",
name: "Ada Lovelace",
email: "ada@example.test",
locale: "de_DE",
metadata: {
tenantId: "tenant_1",
},
createdAt: "2026-07-15T08:00:00+00:00",
...overrides,
};
}
describe("MolliePaymentGateway", () => {
it("creates checkout payments without HiveGrid domain data in the Mollie payload", async () => {
it("creates Mollie customers with PII only in the designated customer fields", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(mollieCustomer()));
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
fetchImpl,
});
await expect(
gateway.createCustomer({
tenantId: " tenant_1 ",
name: " Ada Lovelace ",
email: " ada@example.test ",
locale: " de_DE ",
})
).resolves.toEqual({
provider: "mollie",
providerCustomerId: "cst_123",
tenantId: "tenant_1",
name: "Ada Lovelace",
email: "ada@example.test",
locale: "de_DE",
createdAt: "2026-07-15T08:00:00+00:00",
});
expect(fetchImpl).toHaveBeenCalledWith("https://api.mollie.com/v2/customers", expect.objectContaining({ method: "POST" }));
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
expect(request).toEqual({
name: "Ada Lovelace",
email: "ada@example.test",
locale: "de_DE",
metadata: {
tenantId: "tenant_1",
},
});
expect(JSON.stringify(request.metadata)).not.toContain("Ada");
expect(JSON.stringify(request.metadata)).not.toContain("example.test");
});
it("forwards deterministic idempotency keys on customer and payment POST requests", async () => {
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValueOnce(jsonResponse(mollieCustomer())).mockResolvedValueOnce(jsonResponse(molliePayment()));
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
await gateway.createCustomer({
tenantId: "tenant_1",
name: "Ada Lovelace",
email: "ada@example.test",
idempotencyKey: "hivegrid-customer-acquisition-1",
});
await gateway.createPayment({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
amountCents: 4_900,
currency: "EUR",
redirectUrl: "https://app.hivegrid.de/return",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
idempotencyKey: "hivegrid-payment-acquisition-1",
});
expect(fetchImpl.mock.calls[0]?.[1]?.headers).toEqual(expect.objectContaining({ "idempotency-key": "hivegrid-customer-acquisition-1" }));
expect(fetchImpl.mock.calls[1]?.[1]?.headers).toEqual(expect.objectContaining({ "idempotency-key": "hivegrid-payment-acquisition-1" }));
});
it("recovers a customer payment by its stable external acquisition id", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
_embedded: {
payments: [
molliePayment({ id: "tr_other", metadata: { tenantId: "tenant_1", paymentExternalId: "other" } }),
molliePayment({
id: "tr_recovered",
metadata: {
tenantId: "tenant_1",
paymentExternalId: "acquisition_1",
productAcquisitionId: "acquisition_1",
},
}),
],
},
})
);
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
await expect(gateway.findCustomerPaymentByExternalId(" cst_123 ", " acquisition_1 ")).resolves.toMatchObject({
providerPaymentId: "tr_recovered",
externalId: "acquisition_1",
});
expect(fetchImpl).toHaveBeenCalledWith(
"https://api.mollie.com/v2/customers/cst_123/payments?limit=250&sort=desc",
expect.objectContaining({ method: "GET" })
);
});
it("exhausts Mollie customer-payment pagination before proving an attempt absent", async () => {
const fetchImpl = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
jsonResponse({
_embedded: {
payments: [molliePayment({ id: "tr_other", metadata: { tenantId: "tenant_1", paymentExternalId: "other" } })],
},
_links: {
next: { href: "https://api.mollie.com/v2/customers/cst_123/payments?limit=250&from=tr_other" },
},
})
)
.mockResolvedValueOnce(
jsonResponse({
_embedded: {
payments: [
molliePayment({
id: "tr_recovered",
metadata: {
tenantId: "tenant_1",
paymentExternalId: "acquisition_1:attempt:2",
productAcquisitionId: "acquisition_1",
},
}),
],
},
_links: { next: null },
})
);
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
await expect(gateway.findCustomerPaymentByExternalIdExhaustive("cst_123", "acquisition_1:attempt:2")).resolves.toMatchObject({
providerPaymentId: "tr_recovered",
});
expect(fetchImpl.mock.calls.map(([url]) => url)).toEqual([
"https://api.mollie.com/v2/customers/cst_123/payments?limit=250&sort=desc",
"https://api.mollie.com/v2/customers/cst_123/payments?limit=250&from=tr_other",
]);
});
it("fails closed when exhaustive payment lookup receives an off-collection next link", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
_embedded: { payments: [] },
_links: { next: { href: "https://attacker.example/v2/customers/cst_123/payments?from=tr_1" } },
})
);
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
await expect(gateway.findCustomerPaymentByExternalIdExhaustive("cst_123", "acquisition_1")).rejects.toMatchObject({ code: "RESPONSE_INVALID" });
expect(fetchImpl).toHaveBeenCalledOnce();
});
it("rejects malformed idempotency keys before sending a POST request", async () => {
const fetchImpl = vi.fn<typeof fetch>();
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
await expect(
gateway.createCustomer({ tenantId: "tenant_1", name: "Ada", email: "ada@example.test", idempotencyKey: "contains whitespace" })
).rejects.toMatchObject({ code: "CONFIG_INVALID" });
expect(fetchImpl).not.toHaveBeenCalled();
});
it("keeps omitted sequence types backwards-compatible as oneoff payments", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(molliePayment()));
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
@@ -93,6 +268,7 @@ describe("MolliePaymentGateway", () => {
description: "Invoice invoice_1",
redirectUrl: "https://app.hivegrid.de/admin/billing/return?invoice=invoice_1",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
sequenceType: "oneoff",
profileId: "pfl_123",
customerId: "cst_123",
metadata: {
@@ -106,12 +282,519 @@ describe("MolliePaymentGateway", () => {
expect(JSON.stringify(request)).not.toContain("billing@example.test");
});
it("creates zero-value first payments and preserves technical trial metadata", async () => {
const trialEndsAt = "2026-08-15T10:30:00.000Z";
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse(
molliePayment({
customerId: " cst_response ",
amount: { currency: "EUR", value: "0.00" },
amountRemaining: { currency: "EUR", value: "0.00" },
metadata: {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
paymentExternalId: "payment_1",
mollieCustomerId: "cst_metadata",
trialEndsAt,
},
})
)
);
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
fetchImpl,
});
await expect(
gateway.createPayment({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
paymentExternalId: "payment_1",
amountCents: 0,
currency: "EUR",
redirectUrl: "https://app.hivegrid.de/return",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
mollieCustomerId: " cst_input ",
sequenceType: "first",
trialEndsAt: "2026-08-15T12:30:00+02:00",
})
).resolves.toMatchObject({
amountCents: 0,
metadata: {
mollieCustomerId: "cst_response",
trialEndsAt,
},
});
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
expect(request).toMatchObject({
amount: { currency: "EUR", value: "0.00" },
customerId: "cst_input",
sequenceType: "first",
metadata: {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
paymentExternalId: "payment_1",
mollieCustomerId: "cst_input",
trialEndsAt,
},
});
});
it("restricts an annual first payment to methods that establish a SEPA mandate", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(molliePayment({ customerId: "cst_123" })));
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
fetchImpl,
});
const methods = ["bancontact", "belfius", "eps", "ideal", "kbc", "mybank", "paybybank"] as const;
await gateway.createPayment({
tenantId: "tenant_1",
invoiceExternalId: "invoice_annual_1",
amountCents: 45_422,
currency: "EUR",
redirectUrl: "https://app.hivegrid.de/return",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
mollieCustomerId: "cst_123",
sequenceType: "first",
method: methods,
});
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
expect(request).toMatchObject({
customerId: "cst_123",
sequenceType: "first",
method: methods,
});
});
it("loads enabled methods for the exact first-payment context", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
_embedded: {
methods: [
{ id: "creditcard", description: " Kreditkarte " },
{ id: "paypal", description: "PayPal" },
],
},
})
);
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
profileId: "pfl_123",
fetchImpl,
});
await expect(
gateway.listPaymentMethods({
amountCents: 17_731,
currency: "eur",
sequenceType: "first",
locale: "de_DE",
})
).resolves.toEqual([
{ provider: "mollie", id: "creditcard", description: "Kreditkarte" },
{ provider: "mollie", id: "paypal", description: "PayPal" },
]);
expect(fetchImpl).toHaveBeenCalledWith(
"https://api.mollie.com/v2/methods?sequenceType=first&locale=de_DE&amount%5Bvalue%5D=177.31&amount%5Bcurrency%5D=EUR&profileId=pfl_123",
expect.objectContaining({ method: "GET" })
);
});
it("loads and validates customer mandates without exposing payment details", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
_embedded: {
mandates: [
{ id: "mdt_card", status: "valid", method: "creditcard", createdAt: "2026-08-02T12:30:00+02:00" },
{ id: "mdt_sepa", status: "invalid", method: "directdebit", createdAt: null },
],
},
})
);
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
await expect(gateway.listCustomerMandates(" cst_123 ")).resolves.toEqual([
{
provider: "mollie",
providerMandateId: "mdt_card",
status: "valid",
method: "creditcard",
createdAt: "2026-08-02T10:30:00.000Z",
},
{ provider: "mollie", providerMandateId: "mdt_sepa", status: "invalid", method: "directdebit", createdAt: null },
]);
expect(fetchImpl).toHaveBeenCalledWith(
"https://api.mollie.com/v2/customers/cst_123/mandates?limit=250",
expect.objectContaining({ method: "GET" })
);
});
it("keeps a zero-value first-payment amount so Mollie can filter mandate methods safely", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
_embedded: {
methods: [{ id: "creditcard", description: "Credit card" }],
},
})
);
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
await gateway.listPaymentMethods({
amountCents: 0,
currency: "EUR",
sequenceType: "first",
locale: "en_GB",
});
expect(String(fetchImpl.mock.calls[0]?.[0])).toContain("amount%5Bvalue%5D=0.00");
expect(String(fetchImpl.mock.calls[0]?.[0])).toContain("amount%5Bcurrency%5D=EUR");
});
it("omits an unsupported checkout locale so Mollie can use browser detection", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse({ _embedded: { methods: [] } }));
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
await gateway.listPaymentMethods({ currency: "EUR", sequenceType: "first", locale: null });
expect(String(fetchImpl.mock.calls[0]?.[0])).toBe("https://api.mollie.com/v2/methods?sequenceType=first");
});
it("passes a selected method and locale into the hosted checkout", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(molliePayment({ customerId: "cst_123" })));
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
await gateway.createPayment({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
amountCents: 4_900,
currency: "EUR",
redirectUrl: "https://app.hivegrid.de/return",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
mollieCustomerId: "cst_123",
sequenceType: "first",
method: "creditcard",
locale: "de_DE",
});
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
expect(request).toMatchObject({
sequenceType: "first",
method: "creditcard",
locale: "de_DE",
});
});
it("rejects ambiguous method responses and unsupported method input", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
_embedded: {
methods: [
{ id: "paypal", description: "PayPal" },
{ id: "paypal", description: "PayPal duplicate" },
],
},
})
);
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
await expect(gateway.listPaymentMethods({ currency: "EUR", sequenceType: "first", locale: "de_DE" })).rejects.toMatchObject({ code: "RESPONSE_INVALID" });
await expect(
gateway.createPayment({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
amountCents: 4_900,
currency: "EUR",
redirectUrl: "https://app.hivegrid.de/return",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
mollieCustomerId: "cst_123",
sequenceType: "first",
method: "unsupported" as never,
})
).rejects.toMatchObject({ code: "CONFIG_INVALID", message: "Payment method is invalid." });
});
it("falls back to technical metadata when a Mollie payment omits customerId", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse(
molliePayment({
metadata: {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
mollieCustomerId: "cst_metadata",
},
})
)
);
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
fetchImpl,
});
await expect(gateway.getPayment("tr_123")).resolves.toMatchObject({
metadata: {
mollieCustomerId: "cst_metadata",
},
});
});
it("maps a paid Mollie response with omitted expiresAt to the terminal null contract", async () => {
const { expiresAt: _omittedExpiresAt, ...paidPayment } = molliePayment({
status: "paid",
paidAt: "2026-07-04T12:00:00+00:00",
});
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(paidPayment));
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
await expect(gateway.getPayment("tr_123")).resolves.toMatchObject({
status: "paid",
paidAt: "2026-07-04T12:00:00+00:00",
expiresAt: null,
});
});
it("round-trips deferred change metadata without putting PII into metadata", async () => {
const changeEffectiveAtDate = "2026-09-01T00:00:00.000Z";
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse(
molliePayment({
customerId: "cst_123",
metadata: {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
mollieCustomerId: "cst_123",
lagoPlanCode: "hg_price_business_yearly_123",
subscriptionPriceId: "price_business_yearly",
changeEffectiveAt: "period_end",
changeEffectiveAtDate: "2026-09-01T02:00:00+02:00",
billingFlow: "self_service_change",
},
})
)
);
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
fetchImpl,
});
await expect(
gateway.createPayment({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
amountCents: 4900,
currency: "EUR",
redirectUrl: "https://app.hivegrid.de/return",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
mollieCustomerId: "cst_123",
mandateId: "mdt_card",
method: "creditcard",
lagoPlanCode: "hg_price_business_yearly_123",
sequenceType: "recurring",
subscriptionPriceId: "price_business_yearly",
changeEffectiveAt: "period_end",
changeEffectiveAtDate: "2026-09-01T02:00:00+02:00",
billingFlow: "self_service_change",
})
).resolves.toMatchObject({
metadata: {
changeEffectiveAt: "period_end",
changeEffectiveAtDate,
lagoPlanCode: "hg_price_business_yearly_123",
subscriptionPriceId: "price_business_yearly",
billingFlow: "self_service_change",
},
});
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
expect(request).toMatchObject({ sequenceType: "recurring", method: "creditcard", mandateId: "mdt_card" });
expect(request.metadata).toMatchObject({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
mollieCustomerId: "cst_123",
lagoPlanCode: "hg_price_business_yearly_123",
subscriptionPriceId: "price_business_yearly",
changeEffectiveAt: "period_end",
changeEffectiveAtDate,
billingFlow: "self_service_change",
});
expect(JSON.stringify(request.metadata)).not.toContain("@");
});
it("round-trips product-acquisition identity without treating it as a base-plan flow", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse(
molliePayment({
customerId: "cst_123",
metadata: {
tenantId: "tenant_1",
invoiceExternalId: "invoice_portal_1",
paymentExternalId: "acq_1",
mollieCustomerId: "cst_123",
lagoCustomerId: "lago_customer_1",
lagoSubscriptionId: "acq_1",
subscriptionProductId: "product_portal",
subscriptionPriceId: "price_portal_monthly",
productAcquisitionId: "acq_1",
productKind: "recurring_add_on",
productScopeKey: "tenant",
billingFlow: "product_acquisition",
},
})
)
);
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
await expect(
gateway.createPayment({
tenantId: "tenant_1",
invoiceExternalId: "invoice_portal_1",
paymentExternalId: "acq_1",
amountCents: 1999,
currency: "EUR",
redirectUrl: "https://app.hivegrid.de/return",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
mollieCustomerId: "cst_123",
lagoCustomerId: "lago_customer_1",
lagoSubscriptionId: "acq_1",
subscriptionProductId: "product_portal",
subscriptionPriceId: "price_portal_monthly",
productAcquisitionId: "acq_1",
productKind: "recurring_add_on",
productScopeKey: "tenant",
billingFlow: "product_acquisition",
sequenceType: "first",
})
).resolves.toMatchObject({
metadata: {
productAcquisitionId: "acq_1",
productKind: "recurring_add_on",
productScopeKey: "tenant",
subscriptionProductId: "product_portal",
billingFlow: "product_acquisition",
},
});
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
expect(request.metadata).toMatchObject({
productAcquisitionId: "acq_1",
productKind: "recurring_add_on",
productScopeKey: "tenant",
subscriptionProductId: "product_portal",
billingFlow: "product_acquisition",
});
});
it("rejects incomplete or non-payable product-acquisition metadata", async () => {
const fetchImpl = vi.fn<typeof fetch>();
const gateway = createMolliePaymentGateway({ apiKey: "test_mollie_key", fetchImpl });
const base = {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
amountCents: 1999,
currency: "EUR",
redirectUrl: "https://app.hivegrid.de/return",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
billingFlow: "product_acquisition" as const,
};
await expect(gateway.createPayment(base)).rejects.toMatchObject({ code: "CONFIG_INVALID", message: "Product acquisition metadata is incomplete." });
await expect(
gateway.createPayment({
...base,
productAcquisitionId: "acq_1",
productKind: "contract_override",
productScopeKey: "tenant",
subscriptionProductId: "product_contract",
subscriptionPriceId: "price_contract",
})
).rejects.toMatchObject({ code: "CONFIG_INVALID", message: "Product acquisition kind is not payable." });
expect(fetchImpl).not.toHaveBeenCalled();
});
it("enforces amount and customer requirements for payment sequences", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(molliePayment()));
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
fetchImpl,
});
const baseInput = {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
currency: "EUR",
redirectUrl: "https://app.hivegrid.de/return",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
} as const;
await expect(gateway.createPayment({ ...baseInput, amountCents: 0 })).rejects.toMatchObject({ code: "CONFIG_INVALID" });
await expect(gateway.createPayment({ ...baseInput, amountCents: 0, sequenceType: "first" })).rejects.toMatchObject({
code: "CONFIG_INVALID",
message: "Mollie customer id is required for first and recurring payments.",
});
await expect(gateway.createPayment({ ...baseInput, amountCents: 100, sequenceType: "recurring" })).rejects.toMatchObject({
code: "CONFIG_INVALID",
message: "Mollie customer id is required for first and recurring payments.",
});
await expect(
gateway.createPayment({ ...baseInput, amountCents: 100, sequenceType: "recurring", mollieCustomerId: "cst_123", method: "creditcard" })
).rejects.toMatchObject({
code: "CONFIG_INVALID",
message: "Mollie mandate id is required for recurring payments.",
});
await expect(gateway.createPayment({ ...baseInput, amountCents: -1, sequenceType: "first", mollieCustomerId: "cst_123" })).rejects.toMatchObject({
code: "CONFIG_INVALID",
});
await expect(
gateway.createPayment({
...baseInput,
amountCents: 100,
sequenceType: "first",
mollieCustomerId: "cst_123",
method: "directdebit",
})
).rejects.toMatchObject({
code: "CONFIG_INVALID",
message: "Direct debit is valid only for recurring collection payments.",
});
await expect(
gateway.createPayment({
...baseInput,
amountCents: 0,
sequenceType: "first",
mollieCustomerId: "cst_123",
trialEndsAt: "15.08.2026",
})
).rejects.toMatchObject({
code: "CONFIG_INVALID",
message: "Trial end must be an ISO timestamp with timezone.",
});
await expect(
gateway.createPayment({
...baseInput,
amountCents: 100,
changeEffectiveAt: "period_end",
changeEffectiveAtDate: "next billing period",
})
).rejects.toMatchObject({
code: "CONFIG_INVALID",
message: "Change effective date must be an ISO timestamp with timezone.",
});
expect(fetchImpl).not.toHaveBeenCalled();
});
it("verifies classic Mollie webhooks by parsing the id and refetching payment status", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse(
molliePayment({
status: "paid",
paidAt: "2026-07-04T12:00:00+00:00",
metadata: {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
changeEffectiveAt: "period_end",
changeEffectiveAtDate: "2026-08-01T02:00:00+02:00",
},
})
)
);
@@ -126,6 +809,10 @@ describe("MolliePaymentGateway", () => {
providerPaymentId: "tr_123",
status: "paid",
paidAt: "2026-07-04T12:00:00+00:00",
metadata: {
changeEffectiveAt: "period_end",
changeEffectiveAtDate: "2026-08-01T00:00:00.000Z",
},
});
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://api.mollie.com/v2/payments/tr_123");
});
@@ -1,9 +1,35 @@
import { z } from "zod";
import type { PaymentGateway, PaymentGatewayCreatePaymentInput, PaymentGatewayPayment, PaymentGatewayPaymentStatus } from "./types.js";
import { readBillingJsonResponse } from "./provider-http.js";
import {
mollieLocales,
mollieMandatePaymentMethods,
molliePaymentMethodIds,
mollieSepaFirstPaymentMethods,
paymentBillingFlows,
subscriptionProductKinds,
} from "./types.js";
import type {
ExhaustiveCustomerPaymentGateway,
MollieLocale,
MolliePaymentMethodId,
MollieSepaFirstPaymentMethod,
PaymentGateway,
PaymentGatewayCreateCustomerInput,
PaymentGatewayCreatePaymentInput,
PaymentGatewayCustomer,
PaymentGatewayListMethodsInput,
PaymentGatewayMandate,
PaymentGatewayPayment,
PaymentGatewayPaymentMethod,
PaymentGatewayPaymentStatus,
PaymentBillingFlow,
SubscriptionProductKind,
} from "./types.js";
const DEFAULT_MOLLIE_API_URL = "https://api.mollie.com";
const DEFAULT_MOLLIE_TIMEOUT_MS = 10_000;
const MAX_EXHAUSTIVE_CUSTOMER_PAYMENT_PAGES = 1_000;
export type MolliePaymentGatewayConfig = {
apiKey: string;
@@ -39,16 +65,34 @@ const metadataSchema = z
tenantId: z.string().nullable().optional(),
invoiceExternalId: z.string().nullable().optional(),
paymentExternalId: z.string().nullable().optional(),
mollieCustomerId: z.string().nullable().optional(),
lagoCustomerId: z.string().nullable().optional(),
lagoSubscriptionId: z.string().nullable().optional(),
lagoProviderSubscriptionId: z.string().nullable().optional(),
lagoPlanCode: z.string().nullable().optional(),
planCode: z.string().nullable().optional(),
subscriptionPriceId: z.string().nullable().optional(),
seatQuantity: z.union([z.number(), z.string()]).nullable().optional(),
officeSeatQuantity: z.union([z.number(), z.string()]).nullable().optional(),
fieldSeatQuantity: z.union([z.number(), z.string()]).nullable().optional(),
billingCadence: z.string().nullable().optional(),
commitmentEndsAt: z.string().nullable().optional(),
storageAddOnCodes: z.array(z.string()).nullable().optional(),
trialEndsAt: z.string().nullable().optional(),
changeEffectiveAt: z.string().nullable().optional(),
changeEffectiveAtDate: z.string().nullable().optional(),
billingFlow: z.string().nullable().optional(),
productAcquisitionId: z.string().nullable().optional(),
productKind: z.string().nullable().optional(),
productScopeKey: z.string().nullable().optional(),
subscriptionProductId: z.string().nullable().optional(),
})
.nullable()
.optional();
const molliePaymentSchema = z.object({
id: z.string(),
customerId: z.string().nullable().optional(),
status: z.string().nullable().optional(),
amount: amountSchema.nullable().optional(),
amountRefunded: amountSchema.nullable().optional(),
@@ -69,9 +113,63 @@ const molliePaymentSchema = z.object({
.optional(),
});
type MolliePaymentResponse = z.infer<typeof molliePaymentSchema>;
const mollieCustomerSchema = z.object({
id: z.string(),
name: z.string().nullable().optional(),
email: z.string().nullable().optional(),
locale: z.string().nullable().optional(),
metadata: z
.object({
tenantId: z.string().nullable().optional(),
})
.nullable()
.optional(),
createdAt: z.string().nullable().optional(),
});
export function createMolliePaymentGateway(config: MolliePaymentGatewayConfig): PaymentGateway {
const mollieCustomerPaymentsSchema = z.object({
_embedded: z.object({ payments: z.array(molliePaymentSchema) }),
_links: z
.object({
next: z
.object({
href: z.string(),
})
.nullable()
.optional(),
})
.nullable()
.optional(),
});
const mollieMethodSchema = z.object({
id: z.enum(molliePaymentMethodIds),
description: z.string(),
});
const mollieMethodsSchema = z.object({
_embedded: z.object({
methods: z.array(mollieMethodSchema),
}),
});
const mollieMandateSchema = z.object({
id: z.string(),
status: z.enum(["valid", "pending", "invalid"]),
method: z.enum(mollieMandatePaymentMethods),
createdAt: z.string().nullable().optional(),
});
const mollieMandatesSchema = z.object({
_embedded: z.object({
mandates: z.array(mollieMandateSchema),
}),
});
type MolliePaymentResponse = z.infer<typeof molliePaymentSchema>;
type MollieCustomerResponse = z.infer<typeof mollieCustomerSchema>;
export function createMolliePaymentGateway(config: MolliePaymentGatewayConfig): ExhaustiveCustomerPaymentGateway {
return new MolliePaymentGateway(config);
}
@@ -104,7 +202,10 @@ export function parseMollieWebhookEvent(input: URLSearchParams | FormData | Reco
return { providerPaymentId: id };
}
export async function resolveMollieWebhookPayment(gateway: PaymentGateway, input: URLSearchParams | FormData | Record<string, unknown>): Promise<PaymentGatewayPayment> {
export async function resolveMollieWebhookPayment(
gateway: PaymentGateway,
input: URLSearchParams | FormData | Record<string, unknown>
): Promise<PaymentGatewayPayment> {
const event = parseMollieWebhookEvent(input);
const payment = await gateway.getPayment(event.providerPaymentId);
if (!payment) {
@@ -113,7 +214,7 @@ export async function resolveMollieWebhookPayment(gateway: PaymentGateway, input
return payment;
}
class MolliePaymentGateway implements PaymentGateway {
class MolliePaymentGateway implements ExhaustiveCustomerPaymentGateway {
private readonly apiUrl: string;
private readonly apiKey: string;
private readonly profileId: string | null;
@@ -131,34 +232,167 @@ class MolliePaymentGateway implements PaymentGateway {
this.fetchImpl = config.fetchImpl ?? fetch;
}
async createCustomer(input: PaymentGatewayCreateCustomerInput): Promise<PaymentGatewayCustomer> {
const normalizedInput = validateCreateCustomerInput(input);
const response = await this.request("/customers", {
method: "POST",
idempotencyKey: normalizeIdempotencyKey(input.idempotencyKey),
body: {
name: normalizedInput.name,
email: normalizedInput.email,
...(normalizedInput.locale ? { locale: normalizedInput.locale } : {}),
metadata: {
tenantId: normalizedInput.tenantId,
},
},
});
return toCustomer(parseMollieCustomerResponse(response));
}
async createPayment(input: PaymentGatewayCreatePaymentInput): Promise<PaymentGatewayPayment> {
validateCreatePaymentInput(input);
const normalizedInput = validateCreatePaymentInput(input);
const response = await this.request("/payments", {
method: "POST",
idempotencyKey: normalizeIdempotencyKey(input.idempotencyKey),
body: {
amount: {
currency: input.currency.toUpperCase(),
value: centsToMollieValue(input.amountCents),
},
description: input.description?.trim() || `Invoice ${input.invoiceExternalId}`,
redirectUrl: input.redirectUrl,
...(input.redirectUrl ? { redirectUrl: input.redirectUrl } : {}),
webhookUrl: input.webhookUrl,
sequenceType: normalizedInput.sequenceType,
...(normalizedInput.method ? { method: normalizedInput.method } : {}),
...(normalizedInput.mandateId ? { mandateId: normalizedInput.mandateId } : {}),
...(normalizedInput.locale ? { locale: normalizedInput.locale } : {}),
...(this.profileId ? { profileId: this.profileId } : {}),
...(input.mollieCustomerId ? { customerId: input.mollieCustomerId } : {}),
...(normalizedInput.mollieCustomerId ? { customerId: normalizedInput.mollieCustomerId } : {}),
metadata: {
tenantId: input.tenantId,
invoiceExternalId: input.invoiceExternalId,
...(input.paymentExternalId ? { paymentExternalId: input.paymentExternalId } : {}),
...(normalizedInput.mollieCustomerId ? { mollieCustomerId: normalizedInput.mollieCustomerId } : {}),
...(input.lagoCustomerId ? { lagoCustomerId: input.lagoCustomerId } : {}),
...(input.lagoSubscriptionId ? { lagoSubscriptionId: input.lagoSubscriptionId } : {}),
...(normalizedInput.lagoProviderSubscriptionId ? { lagoProviderSubscriptionId: normalizedInput.lagoProviderSubscriptionId } : {}),
...(normalizedInput.lagoPlanCode ? { lagoPlanCode: normalizedInput.lagoPlanCode } : {}),
...(input.planCode ? { planCode: input.planCode } : {}),
...(input.subscriptionPriceId ? { subscriptionPriceId: input.subscriptionPriceId } : {}),
...(input.seatQuantity ? { seatQuantity: input.seatQuantity } : {}),
...(input.officeSeatQuantity !== null && input.officeSeatQuantity !== undefined ? { officeSeatQuantity: input.officeSeatQuantity } : {}),
...(input.fieldSeatQuantity !== null && input.fieldSeatQuantity !== undefined ? { fieldSeatQuantity: input.fieldSeatQuantity } : {}),
...(input.billingCadence ? { billingCadence: input.billingCadence } : {}),
...(normalizedInput.commitmentEndsAt ? { commitmentEndsAt: normalizedInput.commitmentEndsAt } : {}),
...(normalizedInput.storageAddOnCodes.length > 0 ? { storageAddOnCodes: normalizedInput.storageAddOnCodes } : {}),
...(normalizedInput.trialEndsAt ? { trialEndsAt: normalizedInput.trialEndsAt } : {}),
...(normalizedInput.changeEffectiveAt ? { changeEffectiveAt: normalizedInput.changeEffectiveAt } : {}),
...(normalizedInput.changeEffectiveAtDate ? { changeEffectiveAtDate: normalizedInput.changeEffectiveAtDate } : {}),
...(normalizedInput.billingFlow ? { billingFlow: normalizedInput.billingFlow } : {}),
...(normalizedInput.productAcquisitionId ? { productAcquisitionId: normalizedInput.productAcquisitionId } : {}),
...(normalizedInput.productKind ? { productKind: normalizedInput.productKind } : {}),
...(normalizedInput.productScopeKey ? { productScopeKey: normalizedInput.productScopeKey } : {}),
...(normalizedInput.subscriptionProductId ? { subscriptionProductId: normalizedInput.subscriptionProductId } : {}),
},
},
});
return toPayment(parseMollieResponse(response));
}
async listPaymentMethods(input: PaymentGatewayListMethodsInput): Promise<PaymentGatewayPaymentMethod[]> {
const normalized = validateListPaymentMethodsInput(input);
const query = new URLSearchParams({ sequenceType: normalized.sequenceType });
if (normalized.locale) query.set("locale", normalized.locale);
if (normalized.amountCents !== null) {
query.set("amount[value]", centsToMollieValue(normalized.amountCents));
query.set("amount[currency]", normalized.currency);
}
if (this.profileId) query.set("profileId", this.profileId);
const response = await this.request(`/methods?${query.toString()}`, { method: "GET" });
const parsed = mollieMethodsSchema.safeParse(response);
if (!parsed.success) {
throw new MolliePaymentGatewayError("Mollie payment methods response shape is invalid.", "RESPONSE_INVALID");
}
const ids = parsed.data._embedded.methods.map((method) => method.id);
if (new Set(ids).size !== ids.length || parsed.data._embedded.methods.some((method) => !method.description.trim())) {
throw new MolliePaymentGatewayError("Mollie payment methods response is ambiguous.", "RESPONSE_INVALID");
}
return parsed.data._embedded.methods.map((method) => ({
provider: "mollie",
id: method.id,
description: method.description.trim(),
}));
}
async listCustomerMandates(mollieCustomerId: string): Promise<PaymentGatewayMandate[]> {
const customerId = mollieCustomerId.trim();
if (!customerId) throw new MolliePaymentGatewayError("Mollie customer id is required.", "CONFIG_INVALID");
const response = await this.request(`/customers/${encodeURIComponent(customerId)}/mandates?limit=250`, { method: "GET" });
const parsed = mollieMandatesSchema.safeParse(response);
if (!parsed.success) {
throw new MolliePaymentGatewayError("Mollie mandates response shape is invalid.", "RESPONSE_INVALID");
}
const ids = parsed.data._embedded.mandates.map((mandate) => mandate.id);
if (new Set(ids).size !== ids.length || ids.some((id) => !/^mdt_.+/u.test(id))) {
throw new MolliePaymentGatewayError("Mollie mandates response is ambiguous.", "RESPONSE_INVALID");
}
return parsed.data._embedded.mandates.map((mandate) => ({
provider: "mollie",
providerMandateId: mandate.id,
status: mandate.status,
method: mandate.method,
createdAt: normalizeProviderTimestamp(mandate.createdAt),
}));
}
async findCustomerPaymentByExternalId(mollieCustomerId: string, paymentExternalId: string): Promise<PaymentGatewayPayment | null> {
const customerId = mollieCustomerId.trim();
const externalId = paymentExternalId.trim();
if (!customerId) throw new MolliePaymentGatewayError("Mollie customer id is required.", "CONFIG_INVALID");
if (!externalId) throw new MolliePaymentGatewayError("Payment external id is required.", "CONFIG_INVALID");
const response = await this.request(`/customers/${encodeURIComponent(customerId)}/payments?limit=250&sort=desc`, { method: "GET" });
const parsed = mollieCustomerPaymentsSchema.safeParse(response);
if (!parsed.success) throw new MolliePaymentGatewayError("Mollie customer payments response shape is invalid.", "RESPONSE_INVALID");
const payment = parsed.data._embedded.payments.find((candidate) => {
const metadata = candidate.metadata ?? {};
return metadata.paymentExternalId === externalId || metadata.productAcquisitionId === externalId;
});
return payment ? toPayment(payment) : null;
}
async findCustomerPaymentByExternalIdExhaustive(mollieCustomerId: string, paymentExternalId: string): Promise<PaymentGatewayPayment | null> {
const customerId = mollieCustomerId.trim();
const externalId = paymentExternalId.trim();
if (!customerId) throw new MolliePaymentGatewayError("Mollie customer id is required.", "CONFIG_INVALID");
if (!externalId) throw new MolliePaymentGatewayError("Payment external id is required.", "CONFIG_INVALID");
const expectedPathPrefix = `/customers/${encodeURIComponent(customerId)}/payments`;
let path = `${expectedPathPrefix}?limit=250&sort=desc`;
const visited = new Set<string>();
for (let page = 0; page < MAX_EXHAUSTIVE_CUSTOMER_PAYMENT_PAGES; page += 1) {
if (visited.has(path)) {
throw new MolliePaymentGatewayError("Mollie customer payments pagination looped.", "RESPONSE_INVALID");
}
visited.add(path);
const response = await this.request(path, { method: "GET" });
const parsed = mollieCustomerPaymentsSchema.safeParse(response);
if (!parsed.success) {
throw new MolliePaymentGatewayError("Mollie customer payments response shape is invalid.", "RESPONSE_INVALID");
}
const payment = parsed.data._embedded.payments.find((candidate) => {
const metadata = candidate.metadata ?? {};
return metadata.paymentExternalId === externalId || metadata.productAcquisitionId === externalId;
});
if (payment) return toPayment(payment);
const nextHref = parsed.data._links?.next?.href;
if (!nextHref) return null;
path = normalizeMollieCustomerPaymentsNextPath(nextHref, this.apiUrl, expectedPathPrefix);
}
throw new MolliePaymentGatewayError("Mollie customer payments pagination exceeded its safety bound.", "RESPONSE_INVALID");
}
async getPayment(providerPaymentId: string): Promise<PaymentGatewayPayment | null> {
const id = providerPaymentId.trim();
if (!id) {
@@ -168,7 +402,10 @@ class MolliePaymentGateway implements PaymentGateway {
return response === null ? null : toPayment(parseMollieResponse(response));
}
private async request(path: string, options: { method: "GET" | "POST"; body?: unknown; allowNotFound?: boolean }): Promise<unknown | null> {
private async request(
path: string,
options: { method: "GET" | "POST"; body?: unknown; allowNotFound?: boolean; idempotencyKey?: string | null }
): Promise<unknown | null> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
try {
@@ -178,8 +415,10 @@ class MolliePaymentGateway implements PaymentGateway {
authorization: `Bearer ${this.apiKey}`,
accept: "application/json",
...(options.body ? { "content-type": "application/json" } : {}),
...(options.method === "POST" && options.idempotencyKey ? { "idempotency-key": options.idempotencyKey } : {}),
},
body: options.body ? JSON.stringify(options.body) : undefined,
redirect: "error",
signal: controller.signal,
});
if (response.status === 404 && options.allowNotFound) {
@@ -188,7 +427,7 @@ class MolliePaymentGateway implements PaymentGateway {
if (!response.ok) {
throw new MolliePaymentGatewayError(`Mollie request failed with status ${response.status}.`, "REQUEST_FAILED", response.status);
}
return await response.json();
return await readBillingJsonResponse(response);
} catch (error) {
if (error instanceof MolliePaymentGatewayError) throw error;
throw new MolliePaymentGatewayError("Mollie request failed.", "REQUEST_FAILED");
@@ -198,6 +437,21 @@ class MolliePaymentGateway implements PaymentGateway {
}
}
function normalizeMollieCustomerPaymentsNextPath(href: string, apiUrl: string, expectedPathPrefix: string): string {
let next: URL;
try {
next = new URL(href, `${apiUrl}/v2/`);
} catch {
throw new MolliePaymentGatewayError("Mollie customer payments next link is invalid.", "RESPONSE_INVALID");
}
const base = new URL(apiUrl);
const expectedPath = `/v2${expectedPathPrefix}`;
if (next.origin !== base.origin || next.pathname !== expectedPath) {
throw new MolliePaymentGatewayError("Mollie customer payments next link is outside the requested collection.", "RESPONSE_INVALID");
}
return `${expectedPathPrefix}${next.search}`;
}
function parseMollieResponse(response: unknown): MolliePaymentResponse {
const result = molliePaymentSchema.safeParse(response);
if (!result.success) {
@@ -206,13 +460,33 @@ function parseMollieResponse(response: unknown): MolliePaymentResponse {
return result.data;
}
function parseMollieCustomerResponse(response: unknown): MollieCustomerResponse {
const result = mollieCustomerSchema.safeParse(response);
if (!result.success) {
throw new MolliePaymentGatewayError("Mollie customer response shape is invalid.", "RESPONSE_INVALID");
}
return result.data;
}
function toCustomer(customer: MollieCustomerResponse): PaymentGatewayCustomer {
return {
provider: "mollie",
providerCustomerId: customer.id,
tenantId: customer.metadata?.tenantId ?? null,
name: customer.name ?? null,
email: customer.email ?? null,
locale: customer.locale ?? null,
createdAt: customer.createdAt ?? null,
};
}
function toPayment(payment: MolliePaymentResponse): PaymentGatewayPayment {
const metadata = payment.metadata ?? {};
return {
provider: "mollie",
providerPaymentId: payment.id,
externalId: metadata.paymentExternalId ?? null,
status: normalizePaymentStatus(payment.status, payment.amountRefunded?.value),
status: normalizePaymentStatus(payment.status, payment.amountRefunded?.value, payment.amount?.value),
amountCents: mollieValueToCents(payment.amount?.value),
amountRefundedCents: mollieValueToCents(payment.amountRefunded?.value),
amountRemainingCents: mollieValueToCents(payment.amountRemaining?.value),
@@ -224,10 +498,27 @@ function toPayment(payment: MolliePaymentResponse): PaymentGatewayPayment {
tenantId: metadata.tenantId ?? null,
invoiceExternalId: metadata.invoiceExternalId ?? null,
paymentExternalId: metadata.paymentExternalId ?? null,
mollieCustomerId: normalizeMetadataString(payment.customerId) ?? normalizeMetadataString(metadata.mollieCustomerId),
lagoCustomerId: metadata.lagoCustomerId ?? null,
lagoSubscriptionId: metadata.lagoSubscriptionId ?? null,
lagoProviderSubscriptionId: normalizeMetadataString(metadata.lagoProviderSubscriptionId),
lagoPlanCode: normalizeMetadataString(metadata.lagoPlanCode),
planCode: metadata.planCode ?? null,
subscriptionPriceId: normalizeMetadataString(metadata.subscriptionPriceId),
seatQuantity: normalizeMetadataSeatQuantity(metadata.seatQuantity),
officeSeatQuantity: normalizeMetadataNonNegativeSeatQuantity(metadata.officeSeatQuantity),
fieldSeatQuantity: normalizeMetadataNonNegativeSeatQuantity(metadata.fieldSeatQuantity),
billingCadence: normalizeMetadataString(metadata.billingCadence),
commitmentEndsAt: normalizeMetadataIsoTimestamp(metadata.commitmentEndsAt),
storageAddOnCodes: [...new Set((metadata.storageAddOnCodes ?? []).map((code) => code.trim()).filter(Boolean))],
trialEndsAt: normalizeMetadataIsoTimestamp(metadata.trialEndsAt),
changeEffectiveAt: normalizeChangeEffectiveAt(metadata.changeEffectiveAt),
changeEffectiveAtDate: normalizeMetadataIsoTimestamp(metadata.changeEffectiveAtDate),
billingFlow: normalizeBillingFlow(metadata.billingFlow),
productAcquisitionId: normalizeMetadataString(metadata.productAcquisitionId),
productKind: normalizeProductKind(metadata.productKind),
productScopeKey: normalizeMetadataString(metadata.productScopeKey),
subscriptionProductId: normalizeMetadataString(metadata.subscriptionProductId),
},
};
}
@@ -244,17 +535,236 @@ function normalizeMetadataSeatQuantity(value: string | number | null | undefined
return null;
}
function validateCreatePaymentInput(input: PaymentGatewayCreatePaymentInput): void {
function normalizeMetadataNonNegativeSeatQuantity(value: string | number | null | undefined): number | null {
if (typeof value === "number" && Number.isFinite(value)) {
const normalized = Math.trunc(value);
return normalized >= 0 ? normalized : null;
}
if (typeof value === "string" && value.trim()) {
const normalized = Number.parseInt(value, 10);
return Number.isFinite(normalized) && normalized >= 0 ? normalized : null;
}
return null;
}
function validateCreateCustomerInput(input: PaymentGatewayCreateCustomerInput): {
tenantId: string;
name: string;
email: string;
locale: string | null;
} {
const tenantId = input.tenantId.trim();
const name = input.name.trim();
const email = input.email.trim();
const locale = input.locale?.trim() || null;
if (!tenantId) throw new MolliePaymentGatewayError("Tenant id is required.", "CONFIG_INVALID");
if (!name) throw new MolliePaymentGatewayError("Customer name is required.", "CONFIG_INVALID");
if (!z.string().email().safeParse(email).success) {
throw new MolliePaymentGatewayError("Customer email must be valid.", "CONFIG_INVALID");
}
return { tenantId, name, email, locale };
}
function validateCreatePaymentInput(input: PaymentGatewayCreatePaymentInput): {
sequenceType: "oneoff" | "first" | "recurring";
method: MolliePaymentMethodId | readonly MollieSepaFirstPaymentMethod[] | null;
locale: MollieLocale | null;
mollieCustomerId: string | null;
mandateId: string | null;
trialEndsAt: string | null;
commitmentEndsAt: string | null;
storageAddOnCodes: readonly string[];
changeEffectiveAt: "immediate" | "period_end" | null;
changeEffectiveAtDate: string | null;
billingFlow: PaymentBillingFlow | null;
productAcquisitionId: string | null;
productKind: SubscriptionProductKind | null;
productScopeKey: string | null;
subscriptionProductId: string | null;
lagoProviderSubscriptionId: string | null;
lagoPlanCode: string | null;
} {
if (!input.tenantId.trim()) throw new MolliePaymentGatewayError("Tenant id is required.", "CONFIG_INVALID");
if (!input.invoiceExternalId.trim()) throw new MolliePaymentGatewayError("Invoice reference is required.", "CONFIG_INVALID");
if (!Number.isInteger(input.amountCents) || input.amountCents < 1) {
throw new MolliePaymentGatewayError("Amount must be a positive cent integer.", "CONFIG_INVALID");
const sequenceType = input.sequenceType ?? "oneoff";
if (sequenceType !== "oneoff" && sequenceType !== "first" && sequenceType !== "recurring") {
throw new MolliePaymentGatewayError("Payment sequence type is invalid.", "CONFIG_INVALID");
}
if (!Number.isInteger(input.amountCents) || input.amountCents < 0 || (input.amountCents === 0 && sequenceType !== "first")) {
throw new MolliePaymentGatewayError(
sequenceType === "first" ? "Amount must be a non-negative cent integer." : "Amount must be a positive cent integer.",
"CONFIG_INVALID"
);
}
if (!/^[A-Za-z]{3}$/u.test(input.currency)) {
throw new MolliePaymentGatewayError("Currency must be a three-letter ISO code.", "CONFIG_INVALID");
}
assertHttpUrl(input.redirectUrl, "Redirect URL");
const mollieCustomerId = input.mollieCustomerId?.trim() || null;
if ((sequenceType === "first" || sequenceType === "recurring") && !mollieCustomerId) {
throw new MolliePaymentGatewayError("Mollie customer id is required for first and recurring payments.", "CONFIG_INVALID");
}
const changeEffectiveAt = input.changeEffectiveAt ?? null;
if (changeEffectiveAt !== null && changeEffectiveAt !== "immediate" && changeEffectiveAt !== "period_end") {
throw new MolliePaymentGatewayError("Change effective mode is invalid.", "CONFIG_INVALID");
}
if (sequenceType === "recurring") {
if (input.redirectUrl) assertHttpUrl(input.redirectUrl, "Redirect URL");
} else {
if (!input.redirectUrl) {
throw new MolliePaymentGatewayError("Redirect URL is required.", "CONFIG_INVALID");
}
assertHttpUrl(input.redirectUrl, "Redirect URL");
}
assertHttpUrl(input.webhookUrl, "Webhook URL");
const billingFlow = normalizeBillingFlow(input.billingFlow);
const productAcquisitionId = normalizeMetadataString(input.productAcquisitionId);
const productKind = normalizeProductKind(input.productKind);
const productScopeKey = normalizeMetadataString(input.productScopeKey);
const subscriptionProductId = normalizeMetadataString(input.subscriptionProductId);
const lagoProviderSubscriptionId = normalizeMetadataString(input.lagoProviderSubscriptionId);
const lagoPlanCode = normalizeMetadataString(input.lagoPlanCode);
const method = normalizePaymentMethod(input.method, sequenceType);
const mandateId = normalizeMandateId(input.mandateId, sequenceType);
if (sequenceType === "recurring" && !mandateId) {
throw new MolliePaymentGatewayError("Mollie mandate id is required for recurring payments.", "CONFIG_INVALID");
}
const storageAddOnCodes = (input.storageAddOnCodes ?? []).map((code) => normalizeMetadataString(code));
if (storageAddOnCodes.some((code) => code === null) || new Set(storageAddOnCodes).size !== storageAddOnCodes.length) {
throw new MolliePaymentGatewayError("Storage add-on metadata is invalid.", "CONFIG_INVALID");
}
if (billingFlow === "product_acquisition") {
if (!productAcquisitionId || !productKind || !productScopeKey || !subscriptionProductId || !input.subscriptionPriceId?.trim()) {
throw new MolliePaymentGatewayError("Product acquisition metadata is incomplete.", "CONFIG_INVALID");
}
if (productKind === "base_plan" || productKind === "contract_override") {
throw new MolliePaymentGatewayError("Product acquisition kind is not payable.", "CONFIG_INVALID");
}
}
return {
sequenceType,
method,
locale: normalizeLocale(input.locale),
mollieCustomerId,
mandateId,
trialEndsAt: normalizeIsoTimestamp(input.trialEndsAt, "Trial end"),
commitmentEndsAt: normalizeIsoTimestamp(input.commitmentEndsAt, "Commitment end"),
storageAddOnCodes: storageAddOnCodes as string[],
changeEffectiveAt,
changeEffectiveAtDate: normalizeIsoTimestamp(input.changeEffectiveAtDate, "Change effective date"),
billingFlow,
productAcquisitionId,
productKind,
productScopeKey,
subscriptionProductId,
lagoProviderSubscriptionId,
lagoPlanCode,
};
}
function normalizePaymentMethod(
value: PaymentGatewayCreatePaymentInput["method"],
sequenceType: "oneoff" | "first" | "recurring"
): MolliePaymentMethodId | readonly MollieSepaFirstPaymentMethod[] | null {
if (value === null || value === undefined) return null;
if (typeof value === "string") {
if (!molliePaymentMethodIds.includes(value as MolliePaymentMethodId)) {
throw new MolliePaymentGatewayError("Payment method is invalid.", "CONFIG_INVALID");
}
if (sequenceType === "recurring" && value !== "directdebit" && value !== "creditcard" && value !== "paypal") {
throw new MolliePaymentGatewayError("Recurring collection method is invalid.", "CONFIG_INVALID");
}
if (sequenceType !== "recurring" && value === "directdebit") {
throw new MolliePaymentGatewayError("Direct debit is valid only for recurring collection payments.", "CONFIG_INVALID");
}
return value as MolliePaymentMethodId;
}
if (sequenceType !== "first" || value.length === 0) {
throw new MolliePaymentGatewayError("SEPA authorization methods are valid only for first payments.", "CONFIG_INVALID");
}
const allowed = new Set<string>(mollieSepaFirstPaymentMethods);
if (value.some((method) => !allowed.has(method)) || new Set(value).size !== value.length) {
throw new MolliePaymentGatewayError("SEPA authorization payment methods are invalid.", "CONFIG_INVALID");
}
return [...value];
}
function normalizeMandateId(value: string | null | undefined, sequenceType: "oneoff" | "first" | "recurring"): string | null {
if (value === null || value === undefined) return null;
const mandateId = value.trim();
if (sequenceType !== "recurring" || !/^mdt_[A-Za-z0-9]+$/u.test(mandateId)) {
throw new MolliePaymentGatewayError("Mollie mandate id is invalid.", "CONFIG_INVALID");
}
return mandateId;
}
function normalizeProviderTimestamp(value: string | null | undefined): string | null {
if (!value) return null;
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
}
function normalizeLocale(value: MollieLocale | null | undefined): MollieLocale | null {
if (value === null || value === undefined) return null;
if (!mollieLocales.includes(value)) {
throw new MolliePaymentGatewayError("Mollie locale is invalid.", "CONFIG_INVALID");
}
return value;
}
function validateListPaymentMethodsInput(input: PaymentGatewayListMethodsInput): {
amountCents: number | null;
currency: string;
sequenceType: "oneoff" | "first" | "recurring";
locale: MollieLocale | null;
} {
const currency = input.currency.trim().toUpperCase();
if (!/^[A-Z]{3}$/u.test(currency)) {
throw new MolliePaymentGatewayError("Currency must be a three-letter ISO code.", "CONFIG_INVALID");
}
if (input.sequenceType !== "oneoff" && input.sequenceType !== "first" && input.sequenceType !== "recurring") {
throw new MolliePaymentGatewayError("Payment sequence type is invalid.", "CONFIG_INVALID");
}
const amountCents = input.amountCents === null || input.amountCents === undefined ? null : input.amountCents;
if (amountCents !== null && (!Number.isSafeInteger(amountCents) || amountCents < 0)) {
throw new MolliePaymentGatewayError("Amount must be a non-negative cent integer.", "CONFIG_INVALID");
}
return {
amountCents,
currency,
sequenceType: input.sequenceType,
locale: normalizeLocale(input.locale),
};
}
function normalizeBillingFlow(value: string | null | undefined): PaymentBillingFlow | null {
return paymentBillingFlows.includes(value as PaymentBillingFlow) ? (value as PaymentBillingFlow) : null;
}
function normalizeProductKind(value: string | null | undefined): SubscriptionProductKind | null {
return subscriptionProductKinds.includes(value as SubscriptionProductKind) ? (value as SubscriptionProductKind) : null;
}
function normalizeIsoTimestamp(value: string | null | undefined, label: string): string | null {
if (value === null || value === undefined) return null;
const normalized = value.trim();
if (!z.string().datetime({ offset: true }).safeParse(normalized).success) {
throw new MolliePaymentGatewayError(`${label} must be an ISO timestamp with timezone.`, "CONFIG_INVALID");
}
return new Date(normalized).toISOString();
}
function normalizeChangeEffectiveAt(value: string | null | undefined): "immediate" | "period_end" | null {
return value === "immediate" || value === "period_end" ? value : null;
}
function normalizeMetadataString(value: string | null | undefined): string | null {
return value?.trim() || null;
}
function normalizeMetadataIsoTimestamp(value: string | null | undefined): string | null {
const normalized = normalizeMetadataString(value);
if (!normalized || !z.string().datetime({ offset: true }).safeParse(normalized).success) return null;
return new Date(normalized).toISOString();
}
function assertHttpUrl(value: string, label: string): void {
@@ -273,6 +783,15 @@ function normalizeTimeout(timeoutMs: number | undefined): number {
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.trunc(timeoutMs) : DEFAULT_MOLLIE_TIMEOUT_MS;
}
function normalizeIdempotencyKey(value: string | null | undefined): string | null {
if (value === null || value === undefined) return null;
const key = value.trim();
if (!key || key.length > 255 || !/^[\x21-\x7e]+$/u.test(key)) {
throw new MolliePaymentGatewayError("Idempotency key must contain 1 to 255 visible ASCII characters.", "CONFIG_INVALID");
}
return key;
}
function centsToMollieValue(amountCents: number): string {
return (amountCents / 100).toFixed(2);
}
@@ -284,9 +803,21 @@ function mollieValueToCents(value: string | null | undefined): number | null {
return Math.round(Number(normalized) * 100);
}
function normalizePaymentStatus(status: string | null | undefined, refundedValue: string | null | undefined): PaymentGatewayPaymentStatus {
function normalizePaymentStatus(
status: string | null | undefined,
refundedValue: string | null | undefined,
originalValue: string | null | undefined
): PaymentGatewayPaymentStatus {
const refundedCents = mollieValueToCents(refundedValue);
if (typeof refundedCents === "number" && refundedCents > 0) return "refunded";
const originalCents = mollieValueToCents(originalValue);
// Mollie exposes partial and full refunds through the same amountRefunded
// field. Only a full refund is a terminal payment state; a partial refund
// keeps the provider status (normally `paid`) so the product ledger can
// quarantine it for operator reconciliation without revoking the complete
// entitlement.
if (typeof refundedCents === "number" && typeof originalCents === "number" && originalCents > 0 && refundedCents >= originalCents) {
return "refunded";
}
if (
status === "open" ||
status === "pending" ||
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import { MAX_MOLLIE_PAYMENT_LIFETIME_MS, MOLLIE_RECONCILIATION_GRACE_MS, resolvePaymentReservation } from "./payment-reservation.js";
describe("Mollie product-acquisition reservation", () => {
const now = new Date("2026-07-17T12:00:00.000Z");
it("uses the provider expiry plus reconciliation grace", () => {
expect(resolvePaymentReservation({ expiresAt: "2026-07-30T12:00:00.000Z" }, now)).toEqual({
expiresAt: new Date("2026-08-01T12:00:00.000Z"),
trusted: true,
});
});
it.each([null, "invalid", "2026-07-17T11:59:59.000Z", "2027-01-01T00:00:00.000Z"])(
"quarantines an untrusted provider expiry %s under a bounded deadline",
(expiresAt) => {
expect(resolvePaymentReservation({ expiresAt }, now)).toEqual({
expiresAt: new Date(now.getTime() + MAX_MOLLIE_PAYMENT_LIFETIME_MS + MOLLIE_RECONCILIATION_GRACE_MS),
trusted: false,
});
},
);
});
@@ -0,0 +1,48 @@
import type { PaymentGatewayPayment } from "./types.js";
/**
* Longest normal hosted-checkout lifetime in HiveGrid's one-off EUR Mollie
* scope. SEPA bank transfer is documented as 12+2 calendar days; the two-day
* safety slack absorbs day-boundary/timezone rounding while keeping malformed
* provider timestamps bounded.
*/
export const MAX_MOLLIE_PAYMENT_LIFETIME_MS = 16 * 24 * 60 * 60 * 1000;
export const MOLLIE_RECONCILIATION_GRACE_MS = 48 * 60 * 60 * 1000;
export type PaymentReservation = {
readonly expiresAt: Date;
readonly trusted: boolean;
};
const ABSOLUTE_ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/u;
export function parsePaymentTimestamp(value: string | null | undefined): Date | null {
const normalized = value?.trim();
if (!normalized || !ABSOLUTE_ISO_TIMESTAMP.test(normalized)) return null;
const milliseconds = Date.parse(normalized);
return Number.isFinite(milliseconds) ? new Date(milliseconds) : null;
}
export function reservationFromProviderExpiry(expiresAt: Date | null): Date | null {
return expiresAt ? new Date(expiresAt.getTime() + MOLLIE_RECONCILIATION_GRACE_MS) : null;
}
export function resolvePaymentReservation(payment: Pick<PaymentGatewayPayment, "expiresAt">, now: Date): PaymentReservation {
const providerExpiry = parsePaymentTimestamp(payment.expiresAt);
const maximumProviderExpiry = new Date(now.getTime() + MAX_MOLLIE_PAYMENT_LIFETIME_MS);
if (
!providerExpiry ||
!Number.isFinite(providerExpiry.getTime()) ||
providerExpiry <= now ||
providerExpiry > maximumProviderExpiry
) {
return {
expiresAt: new Date(maximumProviderExpiry.getTime() + MOLLIE_RECONCILIATION_GRACE_MS),
trusted: false,
};
}
return {
expiresAt: new Date(providerExpiry.getTime() + MOLLIE_RECONCILIATION_GRACE_MS),
trusted: true,
};
}
@@ -0,0 +1,13 @@
import { describe, expect, it } from "vitest";
import { readBillingJsonResponse } from "./provider-http.js";
describe("billing provider response boundary", () => {
it("parses bounded JSON", async () => {
await expect(readBillingJsonResponse(new Response('{"ok":true}'))).resolves.toEqual({ ok: true });
});
it("rejects an oversized streamed response", async () => {
await expect(readBillingJsonResponse(new Response('{"large":true}'), 8)).rejects.toThrow("size limit");
});
});
@@ -0,0 +1,34 @@
export const BILLING_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
export async function readBillingJsonResponse(response: Response, maxBytes = BILLING_RESPONSE_MAX_BYTES): Promise<unknown> {
const contentLength = response.headers.get("content-length");
if (contentLength && /^\d+$/u.test(contentLength) && Number(contentLength) > maxBytes) {
await response.body?.cancel().catch(() => undefined);
throw new Error("Billing provider response exceeds the configured size limit.");
}
if (!response.body) {
throw new Error("Billing provider returned an empty JSON response.");
}
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let totalBytes = 0;
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
totalBytes += chunk.value.byteLength;
if (totalBytes > maxBytes) {
await reader.cancel().catch(() => undefined);
throw new Error("Billing provider response exceeds the configured size limit.");
}
chunks.push(chunk.value);
}
const bytes = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return JSON.parse(new TextDecoder().decode(bytes)) as unknown;
}
@@ -1,14 +1,5 @@
import {
applyLagoSubscriptionSync,
applyMolliePaymentSync,
type BillingSyncClient,
type BillingSyncResult,
} from "@hivegrid/db/billing-sync.server";
import {
resolveTenantBillingState,
type TenantBillingState,
type TenantBillingStateClient,
} from "@hivegrid/db/billing-domain.server";
import { applyLagoSubscriptionSync, applyMolliePaymentSync, type BillingSyncClient, type BillingSyncResult } from "@hivegrid/db/billing-sync.server";
import { resolveTenantBillingState, type TenantBillingState, type TenantBillingStateClient } from "@hivegrid/db/billing-domain.server";
import type {
BillingGateway,
@@ -121,7 +112,13 @@ type TenantSubscriptionProductUpdateManyArgs = Parameters<BillingSyncClient["ten
function normalizeRunId(value: string | undefined): string {
const fallback = `bill-07-${Date.now().toString(36)}`;
return (value ?? fallback).trim().toLowerCase().replace(/[^a-z0-9-]+/gu, "-").replace(/^-+|-+$/gu, "") || fallback;
return (
(value ?? fallback)
.trim()
.toLowerCase()
.replace(/[^a-z0-9-]+/gu, "-")
.replace(/^-+|-+$/gu, "") || fallback
);
}
function positiveSeatQuantity(value: number | undefined): number {
@@ -163,18 +160,29 @@ function createSandboxState(input: Required<Pick<BillingSandboxFlowInput, "planC
}
function createSandboxClient(state: SandboxState): BillingSyncClient & TenantBillingStateClient {
return {
let client: BillingSyncClient & TenantBillingStateClient;
client = {
async $transaction(callback: (transaction: BillingSyncClient & TenantBillingStateClient) => Promise<unknown>) {
return callback(client);
},
async $queryRaw() {
return [];
},
idempotencyKey: {
async findUnique({ where }: IdempotencyFindUniqueArgs) {
const row = state.idempotency.get(`${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.key}`);
const unique = where.idempotency_key_partition_scope_key;
const row = state.idempotency.get(`${unique.partitionKey}:${unique.scope}:${unique.key}`);
return row
? ({
id: "idem_1",
createdAt: new Date("2026-07-04T00:00:00.000Z"),
updatedAt: new Date("2026-07-04T00:00:00.000Z"),
expiresAt: null,
scope: where.idempotency_key_scope_key.scope,
key: where.idempotency_key_scope_key.key,
tenantId: unique.partitionKey.startsWith("tenant:") ? unique.partitionKey.slice("tenant:".length) : null,
partitionKey: unique.partitionKey,
systemOwned: unique.partitionKey === "system",
scope: unique.scope,
key: unique.key,
requestHash: "sandbox",
responseStatus: 200,
responseBody: row.responseBody,
@@ -183,7 +191,7 @@ function createSandboxClient(state: SandboxState): BillingSyncClient & TenantBil
: null;
},
async create({ data }: IdempotencyCreateArgs) {
state.idempotency.set(`${data.scope}:${data.key}`, { responseBody: data.responseBody });
state.idempotency.set(`${data.partitionKey}:${data.scope}:${data.key}`, { responseBody: data.responseBody });
return { id: `idem_${state.idempotency.size}`, createdAt: new Date(), updatedAt: new Date(), ...data } as never;
},
},
@@ -193,7 +201,7 @@ function createSandboxClient(state: SandboxState): BillingSyncClient & TenantBil
},
async create({ data }: AuditCreateArgs) {
state.auditEvents.push(data);
return { id: `audit_${state.auditEvents.length}`, createdAt: new Date(), ...data } as never;
return { ...data } as never;
},
},
activity: {
@@ -298,7 +306,24 @@ function createSandboxClient(state: SandboxState): BillingSyncClient & TenantBil
return { count };
},
},
portalDomainHostnameClaim: {
async findMany() {
return [];
},
async findFirst() {
return null;
},
async updateMany() {
return { count: 0 };
},
},
portalCustomDomain: {
async updateMany() {
return { count: 0 };
},
},
} as unknown as BillingSyncClient & TenantBillingStateClient;
return client;
}
function createSandboxBillingGateway(state: SandboxState, now: Date): BillingGateway {
@@ -352,8 +377,53 @@ function createSandboxBillingGateway(state: SandboxState, now: Date): BillingGat
async getSubscription(subscriptionExternalId) {
return state.providerSubscriptions.get(subscriptionExternalId) ?? null;
},
async activatePendingSubscription(subscriptionExternalId, activatedAt) {
const subscription = state.providerSubscriptions.get(subscriptionExternalId);
if (!subscription) return null;
const active = {
...subscription,
status: "active" as const,
currentBillingPeriodStartedAt: new Date(activatedAt).toISOString(),
};
state.providerSubscriptions.set(subscriptionExternalId, active);
return active;
},
async terminatePendingSubscription(subscriptionExternalId) {
const subscription = state.providerSubscriptions.get(subscriptionExternalId);
if (!subscription || subscription.status !== "pending") return null;
const terminated = { ...subscription, status: "canceled" as const };
state.providerSubscriptions.set(subscriptionExternalId, terminated);
return terminated;
},
async terminateSubscription(subscriptionExternalId) {
const subscription = state.providerSubscriptions.get(subscriptionExternalId);
if (!subscription) return null;
const terminated = { ...subscription, status: "terminated" as const };
state.providerSubscriptions.set(subscriptionExternalId, terminated);
return terminated;
},
async createOneOffInvoice(input) {
const invoice: BillingGatewayInvoice = {
provider: "lago",
providerInvoiceId: `lago_invoice_one_off_${input.tenantId}_${input.addOnCode}`,
number: `HG-ONE-OFF-${input.addOnCode}`,
externalCustomerId: input.tenantId,
status: "finalized",
paymentStatus: "pending",
invoiceType: "one_off",
currency: input.currency.toUpperCase(),
totalAmountCents: input.amountCents * (input.quantity ?? 1),
issuingDate: now.toISOString(),
fileUrl: null,
};
state.invoices.set(input.tenantId, [...(state.invoices.get(input.tenantId) ?? []), invoice]);
return invoice;
},
async listInvoices(input = {}) {
return input.tenantId ? state.invoices.get(input.tenantId) ?? [] : [...state.invoices.values()].flat();
return input.tenantId ? (state.invoices.get(input.tenantId) ?? []) : [...state.invoices.values()].flat();
},
async getInvoice(providerInvoiceId) {
return [...state.invoices.values()].flat().find((invoice) => invoice.providerInvoiceId === providerInvoiceId) ?? null;
},
async downloadInvoice(providerInvoiceId) {
return [...state.invoices.values()].flat().find((invoice) => invoice.providerInvoiceId === providerInvoiceId) ?? null;
@@ -548,9 +618,21 @@ export async function runBillingSandboxFlow(input: BillingSandboxFlowInput = {})
const referencesVisible = Boolean(activeState.lastInvoiceExternalId && activeState.lastPaymentExternalId);
const steps = [
buildStep("lago.customer", customer.externalId === tenantId, `Customer ${customer.providerCustomerId} created for ${tenantId}.`),
buildStep("lago.subscription", subscription.planCode === planCode && subscription.status === "active", `Subscription ${subscription.providerSubscriptionId} uses ${planCode}.`),
buildStep("mollie.payment", payment.status === "open" && paidPayment.status === "paid", `Payment ${payment.providerPaymentId} was created and simulated as paid.`),
buildStep("local.sync", activeState.status === "active" && activeState.lastInvoiceExternalId === invoice.providerInvoiceId, "Provider sync updated the local subscription."),
buildStep(
"lago.subscription",
subscription.planCode === planCode && subscription.status === "active",
`Subscription ${subscription.providerSubscriptionId} uses ${planCode}.`
),
buildStep(
"mollie.payment",
payment.status === "open" && paidPayment.status === "paid",
`Payment ${payment.providerPaymentId} was created and simulated as paid.`
),
buildStep(
"local.sync",
activeState.status === "active" && activeState.lastInvoiceExternalId === invoice.providerInvoiceId,
"Provider sync updated the local subscription."
),
buildStep("module.gate", activeAllowed && !activeState.readOnly, `${moduleKey} is allowed while the subscription is active.`),
buildStep("references.audit", referencesVisible && state.auditEvents.length >= 2, "Invoice/payment references are visible and syncs are audited."),
buildStep(
@@ -9,7 +9,12 @@ import {
LAGO_BILLING_SYNC_EVENT_TYPE,
MOLLIE_PAYMENT_SYNC_EVENT_TYPE,
} from "./sync-outbox.js";
import { buildLagoWebhookSyncOutboxArgs, parseLagoWebhookEvent } from "./webhook.js";
import {
buildLagoWebhookSyncOutboxArgs,
isLagoV1WebhookEvent,
parseLagoWebhookEvent,
resolveLagoWebhookTenantId,
} from "./webhook.js";
describe("Lago billing sync outbox", () => {
it("builds idempotent outbox args for Lago pull sync actions", () => {
@@ -48,12 +53,18 @@ describe("Lago billing sync outbox", () => {
it("maps Lago webhook events to idempotent sync events", () => {
const event = parseLagoWebhookEvent({
event_type: "invoice.finalized",
lago_id: "invoice_1",
external_customer_id: "tenant_1",
data: { status: "finalized" },
webhook_type: "invoice.created",
object_type: "invoice",
organization_id: "organization_1",
invoice: {
lago_id: "invoice_1",
external_customer_id: "tenant_1",
status: "finalized",
},
});
expect(isLagoV1WebhookEvent(event)).toBe(true);
expect(resolveLagoWebhookTenantId(event)).toBe("tenant_1");
expect(
buildLagoWebhookSyncOutboxArgs({
tenantId: "tenant_1",
@@ -71,6 +82,71 @@ describe("Lago billing sync outbox", () => {
},
});
});
it("keeps only recognized invoice reasons eligible for exact webhook correlation", () => {
const starting = parseLagoWebhookEvent({
webhook_type: "invoice.created",
object_type: "invoice",
organization_id: "organization_1",
invoice: {
lago_id: "invoice_1",
billing_periods: [
{
external_subscription_id: "subscription_1",
lago_subscription_id: "lago_subscription_1",
invoicing_reason: "subscription_starting",
},
{
external_subscription_id: "subscription_2",
lago_subscription_id: "lago_subscription_2",
invoicing_reason: "future_lago_reason",
},
],
},
});
expect(starting.invoice?.billing_periods?.map((period) => period.invoicing_reason)).toEqual(["subscription_starting", null]);
});
it("resolves tenant ids from nested Lago v1.50 subscription and customer payloads", () => {
const subscription = parseLagoWebhookEvent({
webhook_type: "subscription.started",
object_type: "subscription",
organization_id: "organization_1",
subscription: {
lago_id: "lago_subscription_1",
external_id: "subscription_1",
external_customer_id: "tenant_subscription",
plan_code: "starter",
status: "active",
},
});
const customer = parseLagoWebhookEvent({
webhook_type: "customer.created",
object_type: "customer",
organization_id: "organization_1",
customer: {
lago_id: "lago_customer_1",
external_id: "tenant_customer",
},
});
expect(resolveLagoWebhookTenantId(subscription)).toBe("tenant_subscription");
expect(resolveLagoWebhookTenantId(customer)).toBe("tenant_customer");
expect(isLagoV1WebhookEvent(subscription)).toBe(true);
expect(isLagoV1WebhookEvent(customer)).toBe(true);
});
it("does not treat the legacy flat fixture shape as a Lago v1 webhook", () => {
const event = parseLagoWebhookEvent({
event_type: "invoice.finalized",
lago_id: "invoice_1",
external_customer_id: "tenant_1",
});
expect(isLagoV1WebhookEvent(event)).toBe(false);
expect(resolveLagoWebhookTenantId(event)).toBe("tenant_1");
});
});
describe("Mollie payment sync outbox", () => {
@@ -1,3 +1,89 @@
export const subscriptionProductKinds = ["base_plan", "recurring_add_on", "one_time_setup", "contract_override"] as const;
export type SubscriptionProductKind = (typeof subscriptionProductKinds)[number];
export const paymentBillingFlows = ["self_service_new", "self_service_change", "product_acquisition", "recurring_invoice"] as const;
export type PaymentBillingFlow = (typeof paymentBillingFlows)[number];
/**
* Customer-present methods which Mollie documents as creating a SEPA
* direct-debit mandate after a successful `sequenceType=first` payment.
*/
export const mollieSepaFirstPaymentMethods = Object.freeze(["bancontact", "belfius", "eps", "ideal", "kbc", "mybank", "paybybank"] as const);
export type MollieSepaFirstPaymentMethod = (typeof mollieSepaFirstPaymentMethods)[number];
export const molliePaymentMethodIds = Object.freeze([
"alma",
"applepay",
"bacs",
"bancomatpay",
"bancontact",
"banktransfer",
"belfius",
"billie",
"bizum",
"blik",
"creditcard",
"directdebit",
"eps",
"giftcard",
"ideal",
"in3",
"kbc",
"klarna",
"mbway",
"mobilepay",
"multibanco",
"mybank",
"paybybank",
"paypal",
"paysafecard",
"pointofsale",
"przelewy24",
"riverty",
"satispay",
"swish",
"trustly",
"twint",
"vipps",
"voucher",
] as const);
export type MolliePaymentMethodId = (typeof molliePaymentMethodIds)[number];
export const mollieLocales = Object.freeze([
"ca_ES",
"cs_CZ",
"da_DK",
"de_AT",
"de_CH",
"de_DE",
"de_LU",
"en_GB",
"en_US",
"es_ES",
"fi_FI",
"fr_BE",
"fr_FR",
"fr_LU",
"hu_HU",
"is_IS",
"it_IT",
"lt_LT",
"lv_LV",
"nb_NO",
"nl_BE",
"nl_NL",
"pl_PL",
"pt_PT",
"sk_SK",
"sv_SE",
] as const);
export type MollieLocale = (typeof mollieLocales)[number];
export type BillingGatewayCustomerInput = {
tenantId: string;
name: string;
@@ -25,6 +111,22 @@ export type BillingGatewaySubscriptionInput = {
name?: string | null;
subscriptionAt?: Date | string | null;
endingAt?: Date | string | null;
paymentMethodType?: "manual" | null;
consolidateInvoice?: boolean | null;
managedPlan?: BillingGatewayManagedPlan | null;
};
export type BillingGatewayManagedPlan = {
code: string;
name: string;
invoiceDisplayName: string;
description: string;
interval: "monthly";
amountCents: number;
currency: string;
payInAdvance: boolean;
taxCodes: readonly string[];
metadata: Readonly<Record<string, string>>;
};
export type BillingGatewaySubscription = {
@@ -40,6 +142,18 @@ export type BillingGatewaySubscription = {
createdAt: string | null;
};
export type BillingGatewaySubscriptionStatus = "active" | "pending";
export const billingGatewayInvoiceInvoicingReasons = ["subscription_starting", "subscription_periodic"] as const;
export type BillingGatewayInvoiceInvoicingReason = (typeof billingGatewayInvoiceInvoicingReasons)[number];
export type BillingGatewayInvoiceBillingPeriod = {
externalSubscriptionId: string | null;
providerSubscriptionId: string | null;
invoicingReason: BillingGatewayInvoiceInvoicingReason | null;
};
export type BillingGatewayInvoice = {
provider: "lago";
providerInvoiceId: string;
@@ -52,20 +166,46 @@ export type BillingGatewayInvoice = {
totalAmountCents: number | null;
issuingDate: string | null;
fileUrl: string | null;
billingPeriods?: readonly BillingGatewayInvoiceBillingPeriod[];
subscriptionExternalIds?: readonly string[];
subscriptionProviderIds?: readonly string[];
metadata?: Readonly<Record<string, string>>;
};
export type BillingGatewayInvoiceListInput = {
tenantId?: string;
page?: number;
perPage?: number;
metadata?: Readonly<Record<string, string>>;
};
export type BillingGatewayOneOffInvoiceInput = {
tenantId: string;
addOnCode: string;
amountCents: number;
currency: string;
quantity?: number;
description?: string | null;
taxCodes?: readonly string[];
metadata?: Readonly<Record<string, string>>;
};
export type BillingGateway = {
createCustomer(input: BillingGatewayCustomerInput): Promise<BillingGatewayCustomer>;
getCustomer(tenantId: string): Promise<BillingGatewayCustomer | null>;
createSubscription(input: BillingGatewaySubscriptionInput): Promise<BillingGatewaySubscription>;
getSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null>;
ensureManagedPlan?(plan: BillingGatewayManagedPlan): Promise<void>;
getSubscription(subscriptionExternalId: string, status?: BillingGatewaySubscriptionStatus): Promise<BillingGatewaySubscription | null>;
activatePendingSubscription(
subscriptionExternalId: string,
activatedAt: Date | string,
endingAt?: Date | string | null
): Promise<BillingGatewaySubscription | null>;
terminatePendingSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null>;
terminateSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null>;
createOneOffInvoice(input: BillingGatewayOneOffInvoiceInput): Promise<BillingGatewayInvoice>;
listInvoices(input?: BillingGatewayInvoiceListInput): Promise<BillingGatewayInvoice[]>;
getInvoice(providerInvoiceId: string): Promise<BillingGatewayInvoice | null>;
downloadInvoice(providerInvoiceId: string): Promise<BillingGatewayInvoice | null>;
updateInvoicePaymentStatus(providerInvoiceId: string, paymentStatus: BillingGatewayInvoice["paymentStatus"]): Promise<BillingGatewayInvoice>;
};
@@ -75,15 +215,79 @@ export type PaymentGatewayCreatePaymentInput = {
invoiceExternalId: string;
amountCents: number;
currency: string;
redirectUrl: string;
redirectUrl?: string | null;
webhookUrl: string;
paymentExternalId?: string | null;
mollieCustomerId?: string | null;
lagoCustomerId?: string | null;
lagoSubscriptionId?: string | null;
lagoProviderSubscriptionId?: string | null;
lagoPlanCode?: string | null;
planCode?: string | null;
subscriptionPriceId?: string | null;
seatQuantity?: number | null;
officeSeatQuantity?: number | null;
fieldSeatQuantity?: number | null;
billingCadence?: string | null;
commitmentEndsAt?: string | null;
storageAddOnCodes?: readonly string[] | null;
description?: string | null;
sequenceType?: "oneoff" | "first" | "recurring";
method?: MolliePaymentMethodId | readonly MollieSepaFirstPaymentMethod[] | null;
mandateId?: string | null;
locale?: MollieLocale | null;
trialEndsAt?: string | null;
changeEffectiveAt?: "immediate" | "period_end" | null;
changeEffectiveAtDate?: string | null;
billingFlow?: PaymentBillingFlow | null;
productAcquisitionId?: string | null;
productKind?: SubscriptionProductKind | null;
productScopeKey?: string | null;
subscriptionProductId?: string | null;
idempotencyKey?: string | null;
};
export type PaymentGatewayCreateCustomerInput = {
tenantId: string;
name: string;
email: string;
locale?: string | null;
idempotencyKey?: string | null;
};
export type PaymentGatewayCustomer = {
provider: "mollie";
providerCustomerId: string;
tenantId: string | null;
name: string | null;
email: string | null;
locale: string | null;
createdAt: string | null;
};
export type PaymentGatewayListMethodsInput = {
amountCents?: number | null;
currency: string;
sequenceType: "oneoff" | "first" | "recurring";
locale?: MollieLocale | null;
};
export type PaymentGatewayPaymentMethod = {
provider: "mollie";
id: MolliePaymentMethodId;
description: string;
};
export const mollieMandatePaymentMethods = Object.freeze(["creditcard", "directdebit", "paypal"] as const);
export type MollieMandatePaymentMethod = (typeof mollieMandatePaymentMethods)[number];
export type PaymentGatewayMandate = {
provider: "mollie";
providerMandateId: string;
status: "valid" | "pending" | "invalid";
method: MollieMandatePaymentMethod;
createdAt: string | null;
};
export type PaymentGatewayPaymentStatus =
@@ -102,10 +306,27 @@ export type PaymentGatewayPaymentMetadata = {
tenantId: string | null;
invoiceExternalId: string | null;
paymentExternalId: string | null;
mollieCustomerId?: string | null;
lagoCustomerId: string | null;
lagoSubscriptionId: string | null;
lagoProviderSubscriptionId?: string | null;
lagoPlanCode?: string | null;
planCode: string | null;
subscriptionPriceId?: string | null;
seatQuantity: number | null;
officeSeatQuantity?: number | null;
fieldSeatQuantity?: number | null;
billingCadence?: string | null;
commitmentEndsAt?: string | null;
storageAddOnCodes?: readonly string[];
trialEndsAt?: string | null;
changeEffectiveAt?: "immediate" | "period_end" | null;
changeEffectiveAtDate?: string | null;
billingFlow?: PaymentBillingFlow | null;
productAcquisitionId?: string | null;
productKind?: SubscriptionProductKind | null;
productScopeKey?: string | null;
subscriptionProductId?: string | null;
};
export type PaymentGatewayPayment = {
@@ -127,3 +348,20 @@ export type PaymentGateway = {
createPayment(input: PaymentGatewayCreatePaymentInput): Promise<PaymentGatewayPayment>;
getPayment(providerPaymentId: string): Promise<PaymentGatewayPayment | null>;
};
export type CustomerPaymentGateway = PaymentGateway & {
createCustomer(input: PaymentGatewayCreateCustomerInput): Promise<PaymentGatewayCustomer>;
listPaymentMethods(input: PaymentGatewayListMethodsInput): Promise<PaymentGatewayPaymentMethod[]>;
listCustomerMandates(mollieCustomerId: string): Promise<PaymentGatewayMandate[]>;
findCustomerPaymentByExternalId(mollieCustomerId: string, paymentExternalId: string): Promise<PaymentGatewayPayment | null>;
};
/**
* Operator-only extension for proving that an ambiguous payment POST did not
* create a Mollie payment. Normal request/reconciliation paths intentionally
* use the bounded single-page lookup above; a destructive retry release must
* exhaust the provider pagination before treating a payment as absent.
*/
export type ExhaustiveCustomerPaymentGateway = CustomerPaymentGateway & {
findCustomerPaymentByExternalIdExhaustive(mollieCustomerId: string, paymentExternalId: string): Promise<PaymentGatewayPayment | null>;
};
@@ -2,11 +2,74 @@ import { z } from "zod";
import { buildLagoBillingSyncOutboxArgs, type LagoBillingSyncAction } from "./sync-outbox.js";
const nullableString = z.string().nullable().optional();
const lagoInvoiceInvoicingReasonSchema = nullableString.transform((value) => {
const normalized = value?.trim();
return normalized === "subscription_starting" || normalized === "subscription_periodic" ? normalized : null;
});
const lagoWebhookCustomerSchema = z
.object({
lago_id: z.string(),
external_id: z.string(),
})
.passthrough();
const lagoWebhookSubscriptionSchema = z
.object({
lago_id: z.string(),
external_id: z.string(),
external_customer_id: z.string(),
plan_code: z.string(),
status: nullableString,
current_billing_period_started_at: nullableString,
current_billing_period_ending_at: nullableString,
started_at: nullableString,
ending_at: nullableString,
})
.passthrough();
const lagoWebhookInvoiceSchema = z
.object({
lago_id: z.string(),
external_customer_id: nullableString,
invoice_type: nullableString,
status: nullableString,
payment_status: nullableString,
currency: nullableString,
total_amount_cents: z.number().int().nullable().optional(),
created_at: nullableString,
billing_periods: z
.array(
z
.object({
external_subscription_id: nullableString,
lago_subscription_id: nullableString,
invoicing_reason: lagoInvoiceInvoicingReasonSchema,
})
.passthrough()
)
.optional(),
customer: z
.object({
external_id: nullableString,
})
.nullable()
.optional(),
})
.passthrough();
export const lagoWebhookEventSchema = z
.object({
event_type: z.string().optional(),
webhook_type: z.string().optional(),
object_type: z.string().optional(),
organization_id: z.string().optional(),
customer: lagoWebhookCustomerSchema.optional(),
subscription: lagoWebhookSubscriptionSchema.optional(),
invoice: lagoWebhookInvoiceSchema.optional(),
// Kept for backwards-compatible parsing of the pre-v1.50 fixture shape.
lago_id: z.string().optional(),
external_id: z.string().optional(),
external_customer_id: z.string().optional(),
@@ -22,7 +85,13 @@ export function parseLagoWebhookEvent(value: unknown): LagoWebhookEvent {
export function buildLagoWebhookSyncOutboxArgs(input: { tenantId: string; event: LagoWebhookEvent; receivedAt?: Date }) {
const action = resolveWebhookAction(input.event);
const externalId = input.event.external_id ?? input.event.lago_id ?? `${action}:${input.tenantId}`;
const externalId =
input.event.subscription?.external_id ??
input.event.invoice?.lago_id ??
input.event.customer?.external_id ??
input.event.external_id ??
input.event.lago_id ??
`${action}:${input.tenantId}`;
return buildLagoBillingSyncOutboxArgs({
tenantId: input.tenantId,
action,
@@ -32,6 +101,25 @@ export function buildLagoWebhookSyncOutboxArgs(input: { tenantId: string; event:
});
}
export function resolveLagoWebhookTenantId(event: LagoWebhookEvent): string | null {
return firstNonEmptyString(
event.subscription?.external_customer_id,
event.invoice?.external_customer_id,
event.invoice?.customer?.external_id,
event.customer?.external_id,
event.external_customer_id
);
}
export function isLagoV1WebhookEvent(event: LagoWebhookEvent): boolean {
const objectType = event.object_type?.trim();
if (!event.webhook_type?.trim() || !objectType || !event.organization_id?.trim()) return false;
if (objectType === "subscription") return event.subscription !== undefined;
if (objectType === "invoice") return event.invoice !== undefined;
if (objectType === "customer") return event.customer !== undefined;
return true;
}
function resolveWebhookAction(event: LagoWebhookEvent): LagoBillingSyncAction {
const type = [event.event_type, event.webhook_type, event.object_type].filter(Boolean).join(":").toLowerCase();
if (type.includes("invoice")) return "invoice.refresh";
@@ -39,3 +127,11 @@ function resolveWebhookAction(event: LagoWebhookEvent): LagoBillingSyncAction {
if (type.includes("customer")) return "customer.upsert";
return "webhook.received";
}
function firstNonEmptyString(...values: Array<string | null | undefined>): string | null {
for (const value of values) {
const normalized = value?.trim();
if (normalized) return normalized;
}
return null;
}