Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/billing/src/lago.test.ts
T
2026-07-08 16:15:37 +02:00

277 lines
9.0 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { createLagoBillingGateway, LagoBillingGatewayError, normalizeLagoApiUrl, redactLagoValue } from "./lago.js";
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: {
"content-type": "application/json",
},
});
}
describe("LagoBillingGateway", () => {
it("creates customers through the Lago API and maps the response", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
customer: {
lago_id: "lago_customer_1",
external_id: "tenant_1",
name: "ACME GmbH",
email: "billing@example.test",
currency: "EUR",
created_at: "2026-07-04T00:00:00Z",
},
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test/",
apiKey: "secret_lago_key",
fetchImpl,
});
await expect(
gateway.createCustomer({
tenantId: "tenant_1",
name: "ACME GmbH",
email: "billing@example.test",
currency: "EUR",
})
).resolves.toEqual({
provider: "lago",
externalId: "tenant_1",
providerCustomerId: "lago_customer_1",
name: "ACME GmbH",
email: "billing@example.test",
currency: "EUR",
createdAt: "2026-07-04T00:00:00Z",
});
expect(fetchImpl).toHaveBeenCalledWith(
"https://lago.example.test/api/v1/customers",
expect.objectContaining({
method: "POST",
headers: expect.objectContaining({
authorization: "Bearer secret_lago_key",
"content-type": "application/json",
}),
body: JSON.stringify({
customer: {
external_id: "tenant_1",
name: "ACME GmbH",
email: "billing@example.test",
currency: "EUR",
},
}),
})
);
});
it("creates plan subscriptions without storing seat count as unsupported Lago usage", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
subscription: {
lago_id: "lago_subscription_1",
external_id: "sub_tenant_1_business",
external_customer_id: "tenant_1",
plan_code: "business",
status: "active",
name: "business (5 seats)",
current_billing_period_started_at: "2026-07-01T00:00:00Z",
current_billing_period_ending_at: "2026-08-01T00:00:00Z",
created_at: "2026-07-04T00:00:00Z",
},
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl,
});
const subscription = await gateway.createSubscription({
tenantId: "tenant_1",
subscriptionExternalId: "sub_tenant_1_business",
planCode: "business",
seatQuantity: 5,
subscriptionAt: new Date("2026-07-04T00:00:00Z"),
});
expect(subscription).toMatchObject({
provider: "lago",
externalId: "sub_tenant_1_business",
providerSubscriptionId: "lago_subscription_1",
externalCustomerId: "tenant_1",
planCode: "business",
status: "active",
});
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
expect(request.subscription).toMatchObject({
external_customer_id: "tenant_1",
external_id: "sub_tenant_1_business",
plan_code: "business",
billing_time: "anniversary",
subscription_at: "2026-07-04T00:00:00.000Z",
});
expect(request.subscription).not.toHaveProperty("seatQuantity");
});
it("reads invoice status with optional tenant filter", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
invoices: [
{
lago_id: "invoice_1",
number: "LAG-001",
external_customer_id: "tenant_1",
status: "finalized",
payment_status: "succeeded",
invoice_type: "subscription",
currency: "EUR",
total_amount_cents: 4900,
issuing_date: "2026-07-04",
file_url: "https://files.example.test/invoice_1.pdf",
},
],
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl,
});
await expect(gateway.listInvoices({ tenantId: "tenant_1", page: 2, perPage: 10 })).resolves.toEqual([
{
provider: "lago",
providerInvoiceId: "invoice_1",
number: "LAG-001",
externalCustomerId: "tenant_1",
status: "finalized",
paymentStatus: "succeeded",
invoiceType: "subscription",
currency: "EUR",
totalAmountCents: 4900,
issuingDate: "2026-07-04",
fileUrl: "https://files.example.test/invoice_1.pdf",
},
]);
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("downloads an invoice and maps the generated file url", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
invoice: {
lago_id: "invoice_1",
number: "LAG-001",
status: "finalized",
payment_status: "succeeded",
invoice_type: "subscription",
currency: "EUR",
total_amount_cents: 4900,
issuing_date: "2026-07-04",
file_url: "https://files.example.test/invoice_1.pdf",
customer: {
external_id: "tenant_1",
},
},
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl,
});
await expect(gateway.downloadInvoice("invoice_1")).resolves.toMatchObject({
providerInvoiceId: "invoice_1",
externalCustomerId: "tenant_1",
fileUrl: "https://files.example.test/invoice_1.pdf",
});
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://lago.example.test/api/v1/invoices/invoice_1/download");
expect(fetchImpl.mock.calls[0]?.[1]).toMatchObject({ method: "POST" });
});
it("updates an invoice payment status", 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: "succeeded",
invoice_type: "subscription",
currency: "EUR",
total_amount_cents: 99900,
issuing_date: "2026-07-06",
file_url: "https://files.example.test/invoice_1.pdf",
},
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl,
});
await expect(gateway.updateInvoicePaymentStatus("invoice_1", "succeeded")).resolves.toMatchObject({
providerInvoiceId: "invoice_1",
paymentStatus: "succeeded",
});
expect(fetchImpl).toHaveBeenCalledWith(
"https://lago.example.test/api/v1/invoices/invoice_1",
expect.objectContaining({
method: "PUT",
body: JSON.stringify({
invoice: {
payment_status: "succeeded",
},
}),
})
);
});
it("returns null on 404 reads and throws clear errors for failed calls", 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.getCustomer("tenant_missing")).resolves.toBeNull();
fetchImpl.mockResolvedValueOnce(new Response("{}", { status: 500 }));
await expect(gateway.listInvoices()).rejects.toMatchObject({
name: "LagoBillingGatewayError",
code: "REQUEST_FAILED",
status: 500,
message: "Lago request failed with status 500.",
});
});
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);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl: vi.fn<typeof fetch>(async () => jsonResponse({ customer: { external_id: "tenant_1" } })),
});
await expect(gateway.createCustomer({ tenantId: "tenant_1", name: "Tenant" })).rejects.toMatchObject({
code: "RESPONSE_INVALID",
message: "Lago response shape is invalid.",
});
});
it("redacts Lago IDs and tokens for diagnostics", () => {
expect(redactLagoValue("secret_lago_key_123456")).toBe("secr…3456");
expect(redactLagoValue("short")).toBe("[redacted]");
expect(redactLagoValue(undefined)).toBeNull();
});
});