Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user