2048 lines
84 KiB
TypeScript
2048 lines
84 KiB
TypeScript
// @vitest-environment node
|
|
import { createHash } from "node:crypto";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { BillingGateway, ExhaustiveCustomerPaymentGateway, PaymentGatewayPayment } from "@hivegrid/billing";
|
|
import { hiveGridBillingCatalogVersion } from "@hivegrid/entitlements";
|
|
|
|
const mocks = vi.hoisted(() => {
|
|
class MockSelfServiceSubscriptionValidationError extends Error {
|
|
override readonly name = "SelfServiceSubscriptionValidationError";
|
|
|
|
constructor(readonly code: string) {
|
|
super(code);
|
|
}
|
|
}
|
|
|
|
return {
|
|
MockSelfServiceSubscriptionValidationError,
|
|
loadWebConfig: vi.fn(),
|
|
createLagoBillingGateway: vi.fn(),
|
|
createMolliePaymentGateway: vi.fn(),
|
|
runWithRlsContext: vi.fn(),
|
|
applyLagoSubscriptionSync: vi.fn(),
|
|
applyMolliePaymentSync: vi.fn(),
|
|
reserveRecurringInvoiceCollection: vi.fn(),
|
|
reserveCanonicalBaseCheckoutSession: vi.fn(),
|
|
withTenantRLS: vi.fn(),
|
|
correlateCheckoutSessionProviderInvoice: vi.fn(),
|
|
claimCheckoutSessionStatus: vi.fn(),
|
|
createCheckoutSessionStatus: vi.fn(),
|
|
getCheckoutSessionStatus: vi.fn(),
|
|
getSubscriptionProduct: vi.fn(),
|
|
getTenantSubscription: vi.fn(),
|
|
updateCheckoutSessionStatus: vi.fn(),
|
|
transitionClaimedCheckoutSessionStatus: vi.fn(),
|
|
previewSelfServiceSubscription: vi.fn(),
|
|
resolveOtherActiveRecurringGrossTotalCents: vi.fn(),
|
|
absolutePublicAppPath: vi.fn(),
|
|
apiUrl: vi.fn(),
|
|
clearTenantSubscriptionCache: vi.fn(),
|
|
invalidateTenantModuleAccessCache: vi.fn(),
|
|
};
|
|
});
|
|
|
|
vi.mock("@hivegrid/config", () => ({ loadWebConfig: () => mocks.loadWebConfig() }));
|
|
vi.mock("@hivegrid/billing", async (importOriginal) => ({
|
|
...(await importOriginal<typeof import("@hivegrid/billing")>()),
|
|
createLagoBillingGateway: (...args: unknown[]) => mocks.createLagoBillingGateway(...args),
|
|
createMolliePaymentGateway: (...args: unknown[]) => mocks.createMolliePaymentGateway(...args),
|
|
mollieSepaFirstPaymentMethods: ["bancontact", "belfius", "eps", "ideal", "kbc", "mybank", "paybybank"],
|
|
}));
|
|
vi.mock("@hivegrid/db/rls-context.server", () => ({
|
|
runWithRlsContext: (context: unknown, callback: () => unknown) => mocks.runWithRlsContext(context, callback),
|
|
}));
|
|
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
|
withTenantRLS: (...args: unknown[]) => mocks.withTenantRLS(...args),
|
|
}));
|
|
vi.mock("@hivegrid/db/billing-sync.server", () => ({
|
|
applyLagoSubscriptionSync: (...args: unknown[]) => mocks.applyLagoSubscriptionSync(...args),
|
|
applyMolliePaymentSync: (...args: unknown[]) => mocks.applyMolliePaymentSync(...args),
|
|
}));
|
|
vi.mock("@hivegrid/db/recurring-invoice-collection.server", () => ({
|
|
reserveRecurringInvoiceCollection: (...args: unknown[]) => mocks.reserveRecurringInvoiceCollection(...args),
|
|
}));
|
|
vi.mock("@hivegrid/db/subscriptions.server", () => ({
|
|
correlateCheckoutSessionProviderInvoice: (...args: unknown[]) => mocks.correlateCheckoutSessionProviderInvoice(...args),
|
|
claimCheckoutSessionStatus: (...args: unknown[]) => mocks.claimCheckoutSessionStatus(...args),
|
|
createCheckoutSessionStatus: (...args: unknown[]) => mocks.createCheckoutSessionStatus(...args),
|
|
getCheckoutSessionStatus: (...args: unknown[]) => mocks.getCheckoutSessionStatus(...args),
|
|
getSubscriptionProduct: (...args: unknown[]) => mocks.getSubscriptionProduct(...args),
|
|
getTenantSubscription: (...args: unknown[]) => mocks.getTenantSubscription(...args),
|
|
updateCheckoutSessionStatus: (...args: unknown[]) => mocks.updateCheckoutSessionStatus(...args),
|
|
transitionClaimedCheckoutSessionStatus: (...args: unknown[]) => mocks.transitionClaimedCheckoutSessionStatus(...args),
|
|
}));
|
|
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({ apiUrl: (...args: unknown[]) => mocks.apiUrl(...args) }));
|
|
vi.mock("~/utils/app/CrossHostUrls", () => ({
|
|
absolutePublicAppPath: (...args: unknown[]) => mocks.absolutePublicAppPath(...args),
|
|
}));
|
|
vi.mock("~/utils/connector/tenantConnector.server", () => ({
|
|
invalidateTenantModuleAccessCache: (...args: unknown[]) => mocks.invalidateTenantModuleAccessCache(...args),
|
|
}));
|
|
vi.mock("~/utils/services/.server/subscriptionService", () => ({
|
|
clearTenantSubscriptionCache: (...args: unknown[]) => mocks.clearTenantSubscriptionCache(...args),
|
|
}));
|
|
vi.mock("./self-service-subscription.server", () => ({
|
|
previewSelfServiceSubscription: (...args: unknown[]) => mocks.previewSelfServiceSubscription(...args),
|
|
resolveOtherActiveRecurringGrossTotalCents: (...args: unknown[]) => mocks.resolveOtherActiveRecurringGrossTotalCents(...args),
|
|
SelfServiceSubscriptionValidationError: mocks.MockSelfServiceSubscriptionValidationError,
|
|
}));
|
|
|
|
import {
|
|
completeSelfServiceCheckout,
|
|
createSelfServiceCheckout,
|
|
projectSelfServiceCheckoutReturnState,
|
|
reserveCanonicalBaseCheckoutSession,
|
|
SelfServiceCheckoutError,
|
|
type CreateSelfServiceCheckoutInput,
|
|
} from "./self-service-checkout.server";
|
|
|
|
const NOW = new Date("2026-07-15T10:00:00.000Z");
|
|
const TRIAL_ENDS_AT = "2026-07-29T10:00:00.000Z";
|
|
const PERIOD_END = "2026-08-15T00:00:00.000Z";
|
|
const CHECKOUT_REQUEST_KEY = "checkout_request_123456789";
|
|
const SESSION_ID = "hgco_19ab0c284115a25beab05eb4e19dffcb";
|
|
const RETRY_SESSION_ID = "hgco_retry_8f79b3ed5cc74fa4a17a";
|
|
|
|
const starterProduct = {
|
|
id: "product_starter",
|
|
code: "starter",
|
|
lagoPlanCode: "starter",
|
|
kind: "base_plan",
|
|
title: "Starter",
|
|
description: "Starter plan",
|
|
badge: null,
|
|
active: true,
|
|
public: true,
|
|
features: [],
|
|
prices: [
|
|
{
|
|
id: "price_starter_monthly",
|
|
subscriptionProductId: "product_starter",
|
|
active: true,
|
|
type: 1,
|
|
billingPeriod: 3,
|
|
currency: "eur",
|
|
price: 29,
|
|
trialDays: 14,
|
|
},
|
|
],
|
|
};
|
|
|
|
const businessProduct = {
|
|
...starterProduct,
|
|
id: "product_business",
|
|
code: "business",
|
|
lagoPlanCode: "business",
|
|
title: "Business",
|
|
prices: [
|
|
{
|
|
...starterProduct.prices[0],
|
|
id: "price_business_monthly",
|
|
subscriptionProductId: "product_business",
|
|
price: 49,
|
|
trialDays: 0,
|
|
},
|
|
],
|
|
};
|
|
|
|
const annualCoreProduct = {
|
|
...starterProduct,
|
|
title: "Core",
|
|
prices: [
|
|
{
|
|
...starterProduct.prices[0],
|
|
id: "price_starter_annual_sepa",
|
|
subscriptionProductId: "product_starter",
|
|
lagoPlanCode: "starter_annual_sepa",
|
|
billingPeriod: 4,
|
|
billingCadence: "annual_sepa",
|
|
contractMonths: 12,
|
|
requiredPaymentMethod: "sepa",
|
|
price: 179,
|
|
trialDays: 0,
|
|
},
|
|
],
|
|
};
|
|
|
|
const lagoCustomer = {
|
|
provider: "lago" as const,
|
|
externalId: "tenant_1",
|
|
providerCustomerId: "lago_customer_1",
|
|
name: "Acme GmbH",
|
|
email: "owner@acme.test",
|
|
currency: "EUR",
|
|
createdAt: NOW.toISOString(),
|
|
};
|
|
|
|
const lagoGateway = {
|
|
createCustomer: vi.fn<BillingGateway["createCustomer"]>(),
|
|
getCustomer: vi.fn<BillingGateway["getCustomer"]>(),
|
|
createSubscription: vi.fn<BillingGateway["createSubscription"]>(),
|
|
ensureManagedPlan: vi.fn(async () => undefined),
|
|
getSubscription: vi.fn<BillingGateway["getSubscription"]>(),
|
|
activatePendingSubscription: vi.fn<BillingGateway["activatePendingSubscription"]>(),
|
|
terminatePendingSubscription: vi.fn<BillingGateway["terminatePendingSubscription"]>(),
|
|
terminateSubscription: vi.fn<BillingGateway["terminateSubscription"]>(),
|
|
createOneOffInvoice: vi.fn<BillingGateway["createOneOffInvoice"]>(),
|
|
listInvoices: vi.fn<BillingGateway["listInvoices"]>(),
|
|
getInvoice: vi.fn<BillingGateway["getInvoice"]>(),
|
|
downloadInvoice: vi.fn<BillingGateway["downloadInvoice"]>(),
|
|
updateInvoicePaymentStatus: vi.fn<BillingGateway["updateInvoicePaymentStatus"]>(),
|
|
} satisfies BillingGateway;
|
|
|
|
const mollieGateway = {
|
|
createCustomer: vi.fn<ExhaustiveCustomerPaymentGateway["createCustomer"]>(),
|
|
listPaymentMethods: vi.fn<ExhaustiveCustomerPaymentGateway["listPaymentMethods"]>(),
|
|
listCustomerMandates: vi.fn<ExhaustiveCustomerPaymentGateway["listCustomerMandates"]>(),
|
|
findCustomerPaymentByExternalId: vi.fn<ExhaustiveCustomerPaymentGateway["findCustomerPaymentByExternalId"]>(),
|
|
findCustomerPaymentByExternalIdExhaustive: vi.fn<ExhaustiveCustomerPaymentGateway["findCustomerPaymentByExternalIdExhaustive"]>(),
|
|
createPayment: vi.fn<ExhaustiveCustomerPaymentGateway["createPayment"]>(),
|
|
getPayment: vi.fn<ExhaustiveCustomerPaymentGateway["getPayment"]>(),
|
|
} satisfies ExhaustiveCustomerPaymentGateway;
|
|
|
|
let persistedCheckoutSession: ReturnType<typeof checkoutSession> | null;
|
|
|
|
function createInput(overrides: Partial<CreateSelfServiceCheckoutInput> = {}): CreateSelfServiceCheckoutInput {
|
|
return {
|
|
request: new Request("https://app.example.test/acme/settings/subscription"),
|
|
checkoutRequestKey: CHECKOUT_REQUEST_KEY,
|
|
tenantId: "tenant_1",
|
|
tenantSlug: "acme",
|
|
tenantName: "Acme GmbH",
|
|
userId: "user_1",
|
|
userEmail: "owner@acme.test",
|
|
userName: "Ada Lovelace",
|
|
productId: "product_starter",
|
|
priceId: "price_starter_monthly",
|
|
billingPeriod: 3,
|
|
currency: "EUR",
|
|
quantity: 2,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function existingTenantSubscription(overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
id: "tenant_subscription_1",
|
|
tenantId: "tenant_1",
|
|
status: "active",
|
|
planCode: "business",
|
|
seatQuantity: 3,
|
|
mollieCustomerId: "mollie_customer_existing",
|
|
products: [
|
|
{
|
|
id: "tenant_product_business",
|
|
subscriptionProductId: "product_business",
|
|
lagoSubscriptionId: "lago_subscription_existing",
|
|
planCode: "business",
|
|
seatQuantity: 3,
|
|
quantity: 3,
|
|
cancelledAt: null,
|
|
endsAt: null,
|
|
currentPeriodEnd: new Date(PERIOD_END),
|
|
subscriptionProduct: businessProduct,
|
|
prices: [],
|
|
},
|
|
],
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function defaultManagedPlanCode() {
|
|
const fingerprint = JSON.stringify({
|
|
catalogVersion: hiveGridBillingCatalogVersion,
|
|
planCode: "starter",
|
|
amountCents: 5_800,
|
|
currency: "EUR",
|
|
officeSeatQuantity: 2,
|
|
fieldSeatQuantity: 0,
|
|
storageAddOnCodes: [],
|
|
});
|
|
const digest = createHash("sha256").update(fingerprint).digest("hex").slice(0, 16);
|
|
return `hg_price_${hiveGridBillingCatalogVersion.replace(/[^A-Za-z0-9]+/gu, "_")}_starter_${digest}`;
|
|
}
|
|
|
|
function defaultRequestFingerprint(overrides: Record<string, unknown> = {}) {
|
|
return createHash("sha256")
|
|
.update(
|
|
JSON.stringify({
|
|
tenantId: "tenant_1",
|
|
userId: "user_1",
|
|
email: "owner@acme.test",
|
|
productId: "product_starter",
|
|
priceId: "price_starter_monthly",
|
|
planCode: "starter",
|
|
quantity: 2,
|
|
officeSeatQuantity: 2,
|
|
fieldSeatQuantity: 0,
|
|
billingCadence: "monthly",
|
|
storageAddOnCodes: [],
|
|
amountCents: 0,
|
|
currency: "EUR",
|
|
lagoSubscriptionId: SESSION_ID,
|
|
managedPlanAmountCents: 5_800,
|
|
paymentPolicyAmountCents: 6_902,
|
|
changeKind: "new",
|
|
changeEffectiveAt: "immediate",
|
|
changeEffectiveAtDate: null,
|
|
paymentMethod: null,
|
|
paymentLocale: "de",
|
|
postActivationEmailMarketingAddOnCode: null,
|
|
...overrides,
|
|
})
|
|
)
|
|
.digest("hex");
|
|
}
|
|
|
|
function encodeIntent(overrides: Record<string, unknown> = {}) {
|
|
const path = "/acme/settings/subscription";
|
|
const intent = {
|
|
v: 1,
|
|
path,
|
|
requestFingerprint: defaultRequestFingerprint(),
|
|
trialEndsAt: TRIAL_ENDS_AT,
|
|
commitmentEndsAt: null,
|
|
changeEffectiveAt: "immediate",
|
|
changeEffectiveAtDate: null,
|
|
managedPlanCode: defaultManagedPlanCode(),
|
|
managedPlanAmountCents: 5_800,
|
|
paymentPolicyAmountCents: 6_902,
|
|
billingFlow: "self_service_new",
|
|
lagoCustomerId: "lago_customer_1",
|
|
mollieCustomerId: "mollie_customer_1",
|
|
lagoProviderSubscriptionId: `provider_${SESSION_ID}`,
|
|
...overrides,
|
|
};
|
|
return `${path}#hivegrid-checkout-v1=${Buffer.from(JSON.stringify(intent), "utf8").toString("base64url")}`;
|
|
}
|
|
|
|
function checkoutSession(overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
id: SESSION_ID,
|
|
createdAt: NOW,
|
|
updatedAt: NOW,
|
|
tenantId: "tenant_1",
|
|
pending: true,
|
|
email: "owner@acme.test",
|
|
fromUrl: encodeIntent(),
|
|
fromUserId: "user_1",
|
|
createdUserId: null,
|
|
createdTenantId: null,
|
|
provider: "mollie",
|
|
providerPaymentId: "tr_checkout_1",
|
|
invoiceExternalId: SESSION_ID,
|
|
subscriptionProductId: "product_starter",
|
|
subscriptionPriceId: "price_starter_monthly",
|
|
lagoSubscriptionId: SESSION_ID,
|
|
lagoProviderSubscriptionId: `provider_${SESSION_ID}`,
|
|
planCode: "starter",
|
|
quantity: 2,
|
|
officeSeatQuantity: 2,
|
|
fieldSeatQuantity: 0,
|
|
billingCadence: "monthly",
|
|
commitmentEndsAt: null,
|
|
storageAddOnCodes: [],
|
|
amountCents: 0,
|
|
currency: "EUR",
|
|
checkoutUrl: "https://mollie.test/checkout/tr_checkout_1",
|
|
status: "open",
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function payment(overrides: Partial<PaymentGatewayPayment> = {}): PaymentGatewayPayment {
|
|
const metadata = {
|
|
tenantId: "tenant_1",
|
|
invoiceExternalId: SESSION_ID,
|
|
paymentExternalId: SESSION_ID,
|
|
mollieCustomerId: "mollie_customer_1",
|
|
lagoCustomerId: "lago_customer_1",
|
|
lagoSubscriptionId: SESSION_ID,
|
|
lagoProviderSubscriptionId: `provider_${SESSION_ID}`,
|
|
lagoPlanCode: defaultManagedPlanCode(),
|
|
planCode: "starter",
|
|
subscriptionPriceId: "price_starter_monthly",
|
|
seatQuantity: 2,
|
|
officeSeatQuantity: 2,
|
|
fieldSeatQuantity: 0,
|
|
billingCadence: "monthly",
|
|
commitmentEndsAt: null,
|
|
storageAddOnCodes: [],
|
|
trialEndsAt: TRIAL_ENDS_AT,
|
|
changeEffectiveAt: "immediate" as const,
|
|
changeEffectiveAtDate: null,
|
|
billingFlow: "self_service_new" as const,
|
|
...overrides.metadata,
|
|
};
|
|
const { metadata: _metadata, ...rest } = overrides;
|
|
return {
|
|
provider: "mollie",
|
|
providerPaymentId: "tr_checkout_1",
|
|
externalId: SESSION_ID,
|
|
status: "open",
|
|
amountCents: 0,
|
|
amountRefundedCents: 0,
|
|
amountRemainingCents: 0,
|
|
currency: "EUR",
|
|
checkoutUrl: "https://mollie.test/checkout/tr_checkout_1",
|
|
paidAt: null,
|
|
expiresAt: null,
|
|
...rest,
|
|
metadata,
|
|
};
|
|
}
|
|
|
|
function checkoutSessionForPayment(value: PaymentGatewayPayment, overrides: Record<string, unknown> = {}) {
|
|
const fromUrl = encodeIntent({
|
|
trialEndsAt: value.metadata.trialEndsAt ?? null,
|
|
commitmentEndsAt: value.metadata.commitmentEndsAt ?? null,
|
|
changeEffectiveAt: value.metadata.changeEffectiveAt,
|
|
changeEffectiveAtDate: value.metadata.changeEffectiveAtDate ?? null,
|
|
managedPlanCode: value.metadata.lagoPlanCode,
|
|
billingFlow: value.metadata.billingFlow,
|
|
lagoCustomerId: value.metadata.lagoCustomerId,
|
|
mollieCustomerId: value.metadata.mollieCustomerId,
|
|
lagoProviderSubscriptionId: value.metadata.lagoProviderSubscriptionId,
|
|
});
|
|
return checkoutSession({
|
|
fromUrl,
|
|
providerPaymentId: value.providerPaymentId,
|
|
subscriptionPriceId: value.metadata.subscriptionPriceId,
|
|
lagoSubscriptionId: value.metadata.lagoSubscriptionId,
|
|
planCode: value.metadata.planCode,
|
|
quantity: value.metadata.seatQuantity,
|
|
officeSeatQuantity: value.metadata.officeSeatQuantity,
|
|
fieldSeatQuantity: value.metadata.fieldSeatQuantity,
|
|
billingCadence: value.metadata.billingCadence,
|
|
commitmentEndsAt: value.metadata.commitmentEndsAt ? new Date(value.metadata.commitmentEndsAt) : null,
|
|
storageAddOnCodes: value.metadata.storageAddOnCodes,
|
|
amountCents: value.amountCents,
|
|
currency: value.currency,
|
|
...overrides,
|
|
});
|
|
}
|
|
|
|
function createDeps() {
|
|
return {
|
|
lagoGateway,
|
|
mollieGateway,
|
|
now: () => new Date(NOW),
|
|
reserveCheckoutSession: mocks.reserveCanonicalBaseCheckoutSession,
|
|
};
|
|
}
|
|
|
|
describe("self-service checkout service", () => {
|
|
beforeEach(() => {
|
|
vi.resetAllMocks();
|
|
vi.useFakeTimers();
|
|
vi.setSystemTime(NOW);
|
|
|
|
mocks.loadWebConfig.mockReturnValue({
|
|
config: {
|
|
appName: "HiveGrid",
|
|
routing: { protocol: "https", apiHost: "api.example.test" },
|
|
lago: { apiUrl: null, apiKey: null, timeoutMs: 1_000 },
|
|
mollie: { apiKey: null, profileId: null, timeoutMs: 1_000 },
|
|
},
|
|
});
|
|
mocks.absolutePublicAppPath.mockImplementation((_routing, path) => `https://app.example.test${String(path)}`);
|
|
mocks.apiUrl.mockReturnValue("https://api.example.test/v1/billing/mollie/webhooks");
|
|
mocks.runWithRlsContext.mockImplementation(async (_context, callback) => await callback());
|
|
mocks.getSubscriptionProduct.mockResolvedValue(starterProduct);
|
|
mocks.getTenantSubscription.mockResolvedValue(null);
|
|
mocks.resolveOtherActiveRecurringGrossTotalCents.mockReturnValue(0);
|
|
persistedCheckoutSession = null;
|
|
mocks.getCheckoutSessionStatus.mockImplementation(async (input) =>
|
|
persistedCheckoutSession?.id === input.id && persistedCheckoutSession.tenantId === input.tenantId ? persistedCheckoutSession : null
|
|
);
|
|
mocks.createCheckoutSessionStatus.mockImplementation(async (data) => {
|
|
persistedCheckoutSession = { ...checkoutSession({ providerPaymentId: null, checkoutUrl: null }), ...data };
|
|
return persistedCheckoutSession;
|
|
});
|
|
mocks.updateCheckoutSessionStatus.mockImplementation(async (_where, data) => ({ ...checkoutSession(), ...data }));
|
|
mocks.claimCheckoutSessionStatus.mockImplementation(async (input) => {
|
|
persistedCheckoutSession = { ...persistedCheckoutSession!, status: input.claimedStatus };
|
|
return persistedCheckoutSession;
|
|
});
|
|
mocks.transitionClaimedCheckoutSessionStatus.mockImplementation(async (input) => {
|
|
persistedCheckoutSession = {
|
|
...persistedCheckoutSession!,
|
|
...input.data,
|
|
providerPaymentId: input.data.providerPaymentId ?? persistedCheckoutSession!.providerPaymentId,
|
|
checkoutUrl: input.data.checkoutUrl ?? persistedCheckoutSession!.checkoutUrl,
|
|
};
|
|
return persistedCheckoutSession;
|
|
});
|
|
mocks.reserveCanonicalBaseCheckoutSession.mockImplementation(async (input) => {
|
|
const sessionId = persistedCheckoutSession?.id === SESSION_ID ? RETRY_SESSION_ID : SESSION_ID;
|
|
const session = await mocks.createCheckoutSessionStatus(input.createSession(sessionId));
|
|
return { session, created: true };
|
|
});
|
|
mocks.applyMolliePaymentSync.mockResolvedValue({ replayed: false });
|
|
mocks.applyLagoSubscriptionSync.mockResolvedValue({ replayed: false });
|
|
mocks.reserveRecurringInvoiceCollection.mockResolvedValue({ collectionId: "hgrc_initial", disposition: "initial_payment" });
|
|
mocks.previewSelfServiceSubscription.mockResolvedValue({
|
|
changeKind: "new",
|
|
effectiveAt: "immediate",
|
|
effectiveAtDate: null,
|
|
recurringTotalCents: 5_800,
|
|
recurringGrossTotalCents: 6_902,
|
|
selectedSeatQuantity: 2,
|
|
trialDays: 14,
|
|
});
|
|
|
|
lagoGateway.getSubscription.mockReset();
|
|
lagoGateway.createSubscription.mockReset();
|
|
lagoGateway.listInvoices.mockReset();
|
|
lagoGateway.getInvoice.mockReset();
|
|
lagoGateway.updateInvoicePaymentStatus.mockReset();
|
|
lagoGateway.getCustomer.mockResolvedValue(null);
|
|
lagoGateway.createCustomer.mockResolvedValue(lagoCustomer);
|
|
lagoGateway.ensureManagedPlan.mockResolvedValue(undefined);
|
|
lagoGateway.getSubscription.mockResolvedValue(null);
|
|
lagoGateway.listInvoices.mockResolvedValue([]);
|
|
lagoGateway.getInvoice.mockResolvedValue(null);
|
|
lagoGateway.createSubscription.mockImplementation(async (input) => ({
|
|
provider: "lago",
|
|
externalId: input.subscriptionExternalId,
|
|
providerSubscriptionId: `provider_${input.subscriptionExternalId}`,
|
|
externalCustomerId: input.tenantId,
|
|
planCode: input.managedPlan?.code ?? input.planCode,
|
|
status: "active",
|
|
name: input.name ?? null,
|
|
currentBillingPeriodStartedAt: null,
|
|
currentBillingPeriodEndingAt: null,
|
|
createdAt: NOW.toISOString(),
|
|
}));
|
|
lagoGateway.activatePendingSubscription.mockImplementation(async (subscriptionExternalId) => ({
|
|
provider: "lago",
|
|
externalId: subscriptionExternalId,
|
|
providerSubscriptionId: `provider_${subscriptionExternalId}`,
|
|
externalCustomerId: "tenant_1",
|
|
planCode: "starter",
|
|
status: "active",
|
|
name: "Acme GmbH · Core",
|
|
currentBillingPeriodStartedAt: NOW.toISOString(),
|
|
currentBillingPeriodEndingAt: null,
|
|
createdAt: NOW.toISOString(),
|
|
}));
|
|
lagoGateway.terminatePendingSubscription.mockResolvedValue(null);
|
|
mollieGateway.createCustomer.mockResolvedValue({
|
|
provider: "mollie",
|
|
providerCustomerId: "mollie_customer_1",
|
|
tenantId: "tenant_1",
|
|
name: "Acme GmbH",
|
|
email: "owner@acme.test",
|
|
locale: null,
|
|
createdAt: NOW.toISOString(),
|
|
});
|
|
mollieGateway.listPaymentMethods.mockResolvedValue([
|
|
{ provider: "mollie", id: "creditcard", description: "Kreditkarte" },
|
|
{ provider: "mollie", id: "ideal", description: "iDEAL" },
|
|
]);
|
|
mollieGateway.findCustomerPaymentByExternalId.mockResolvedValue(null);
|
|
mollieGateway.findCustomerPaymentByExternalIdExhaustive.mockResolvedValue(null);
|
|
mollieGateway.createPayment.mockImplementation(async (input) => {
|
|
const paymentExternalId = input.paymentExternalId ?? SESSION_ID;
|
|
const retry = paymentExternalId !== SESSION_ID;
|
|
return payment({
|
|
providerPaymentId: retry ? "tr_checkout_retry_1" : "tr_checkout_1",
|
|
externalId: paymentExternalId,
|
|
checkoutUrl: retry ? "https://mollie.test/checkout/tr_checkout_retry_1" : "https://mollie.test/checkout/tr_checkout_1",
|
|
amountCents: input.amountCents,
|
|
metadata: {
|
|
tenantId: input.tenantId,
|
|
invoiceExternalId: input.invoiceExternalId,
|
|
paymentExternalId: input.paymentExternalId ?? null,
|
|
mollieCustomerId: input.mollieCustomerId ?? null,
|
|
lagoCustomerId: input.lagoCustomerId ?? null,
|
|
lagoSubscriptionId: input.lagoSubscriptionId ?? null,
|
|
lagoProviderSubscriptionId: input.lagoProviderSubscriptionId ?? null,
|
|
lagoPlanCode: input.lagoPlanCode ?? null,
|
|
planCode: input.planCode ?? null,
|
|
subscriptionPriceId: input.subscriptionPriceId ?? null,
|
|
seatQuantity: input.seatQuantity ?? null,
|
|
officeSeatQuantity: input.officeSeatQuantity ?? null,
|
|
fieldSeatQuantity: input.fieldSeatQuantity ?? null,
|
|
billingCadence: input.billingCadence ?? null,
|
|
commitmentEndsAt: input.commitmentEndsAt ?? null,
|
|
storageAddOnCodes: input.storageAddOnCodes ?? [],
|
|
trialEndsAt: input.trialEndsAt ?? null,
|
|
changeEffectiveAt: input.changeEffectiveAt ?? null,
|
|
changeEffectiveAtDate: input.changeEffectiveAtDate ?? null,
|
|
billingFlow: input.billingFlow ?? null,
|
|
},
|
|
});
|
|
});
|
|
mollieGateway.getPayment.mockResolvedValue(payment());
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
it("creates a new 14-day trial with provider customers, a fixed trial window, and a persisted session", async () => {
|
|
const result = await createSelfServiceCheckout(createInput(), createDeps());
|
|
|
|
expect(result).toEqual({
|
|
sessionId: SESSION_ID,
|
|
checkoutUrl: "https://mollie.test/checkout/tr_checkout_1",
|
|
providerPaymentId: "tr_checkout_1",
|
|
});
|
|
expect(mocks.runWithRlsContext).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1" }, expect.any(Function));
|
|
expect(mocks.previewSelfServiceSubscription).toHaveBeenCalledWith(
|
|
"tenant_1",
|
|
{ productId: "product_starter", priceId: "price_starter_monthly", seatQuantity: 2 },
|
|
NOW
|
|
);
|
|
expect(lagoGateway.createCustomer).toHaveBeenCalledWith({
|
|
tenantId: "tenant_1",
|
|
name: "Acme GmbH",
|
|
email: "owner@acme.test",
|
|
currency: "EUR",
|
|
});
|
|
expect(mollieGateway.createCustomer).toHaveBeenCalledWith({
|
|
tenantId: "tenant_1",
|
|
name: "Acme GmbH",
|
|
email: "owner@acme.test",
|
|
idempotencyKey: "hivegrid-checkout-customer-cc3bd2964c5853d917a8b7188da2fbc36931ea54",
|
|
});
|
|
expect(lagoGateway.createSubscription).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
subscriptionExternalId: SESSION_ID,
|
|
planCode: "starter",
|
|
seatQuantity: 2,
|
|
subscriptionAt: new Date(TRIAL_ENDS_AT),
|
|
})
|
|
);
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
amountCents: 0,
|
|
sequenceType: "first",
|
|
mollieCustomerId: "mollie_customer_1",
|
|
lagoCustomerId: "lago_customer_1",
|
|
lagoSubscriptionId: SESSION_ID,
|
|
trialEndsAt: TRIAL_ENDS_AT,
|
|
changeEffectiveAt: "immediate",
|
|
changeEffectiveAtDate: null,
|
|
})
|
|
);
|
|
expect(mocks.createCheckoutSessionStatus).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
id: SESSION_ID,
|
|
tenantId: "tenant_1",
|
|
amountCents: 0,
|
|
lagoSubscriptionId: SESSION_ID,
|
|
status: expect.stringMatching(/^provider_claimed_/u),
|
|
})
|
|
);
|
|
expect(mocks.createCheckoutSessionStatus.mock.invocationCallOrder[0]).toBeLessThan(mollieGateway.listPaymentMethods.mock.invocationCallOrder[0]!);
|
|
expect(mocks.createCheckoutSessionStatus.mock.invocationCallOrder[0]).toBeLessThan(lagoGateway.createCustomer.mock.invocationCallOrder[0]!);
|
|
expect(mocks.transitionClaimedCheckoutSessionStatus).toHaveBeenLastCalledWith(
|
|
expect.objectContaining({
|
|
id: SESSION_ID,
|
|
tenantId: "tenant_1",
|
|
data: expect.objectContaining({ providerPaymentId: "tr_checkout_1", checkoutUrl: "https://mollie.test/checkout/tr_checkout_1", status: "open" }),
|
|
})
|
|
);
|
|
});
|
|
|
|
it.each(["", "short", "contains whitespace", "x".repeat(129)])(
|
|
"rejects an invalid checkout request key before provider access",
|
|
async (checkoutRequestKey) => {
|
|
await expect(createSelfServiceCheckout(createInput({ checkoutRequestKey }), createDeps())).rejects.toMatchObject({ code: "CHECKOUT_NOT_PAYABLE" });
|
|
|
|
expect(mocks.createCheckoutSessionStatus).not.toHaveBeenCalled();
|
|
expect(lagoGateway.getCustomer).not.toHaveBeenCalled();
|
|
expect(mollieGateway.listPaymentMethods).not.toHaveBeenCalled();
|
|
}
|
|
);
|
|
|
|
it("carries a validated email-marketing follow-up to the hosted-checkout return URL without adding it to the base charge", async () => {
|
|
await createSelfServiceCheckout(createInput({ postActivationEmailMarketingAddOnCode: "email_marketing_s" }), createDeps());
|
|
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
amountCents: 0,
|
|
redirectUrl: `https://app.example.test/subscribe/acme/${SESSION_ID}/success?email_add_on=email_marketing_s`,
|
|
})
|
|
);
|
|
});
|
|
|
|
it("replays an exact completed request without issuing another provider mutation", async () => {
|
|
mocks.getCheckoutSessionStatus.mockResolvedValueOnce(checkoutSession());
|
|
|
|
await expect(createSelfServiceCheckout(createInput(), createDeps())).resolves.toEqual({
|
|
sessionId: SESSION_ID,
|
|
checkoutUrl: "https://mollie.test/checkout/tr_checkout_1",
|
|
providerPaymentId: "tr_checkout_1",
|
|
});
|
|
|
|
expect(mollieGateway.listPaymentMethods).not.toHaveBeenCalled();
|
|
expect(lagoGateway.createCustomer).not.toHaveBeenCalled();
|
|
expect(lagoGateway.createSubscription).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createCustomer).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createPayment).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("returns only the live Mollie checkout URL when replaying a persisted provider payment", async () => {
|
|
mocks.getCheckoutSessionStatus.mockResolvedValueOnce(checkoutSession({ checkoutUrl: "https://stale.example.test/checkout" }));
|
|
mollieGateway.getPayment.mockResolvedValueOnce(payment({ checkoutUrl: "https://mollie.test/checkout/live" }));
|
|
|
|
await expect(createSelfServiceCheckout(createInput(), createDeps())).resolves.toMatchObject({
|
|
checkoutUrl: "https://mollie.test/checkout/live",
|
|
});
|
|
expect(mollieGateway.getPayment).toHaveBeenCalledWith("tr_checkout_1");
|
|
expect(mollieGateway.createPayment).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("never replaces an already paid Mollie checkout", async () => {
|
|
mocks.getCheckoutSessionStatus.mockResolvedValueOnce(checkoutSession());
|
|
mollieGateway.getPayment.mockResolvedValueOnce(payment({ status: "paid" }));
|
|
|
|
await expect(createSelfServiceCheckout(createInput(), createDeps())).rejects.toMatchObject({ code: "NO_CHANGE" });
|
|
expect(mollieGateway.createPayment).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each(["canceled", "failed", "expired"] as const)(
|
|
"starts a fresh durable attempt immediately after a terminal %s Mollie checkout",
|
|
async (status) => {
|
|
persistedCheckoutSession = checkoutSession();
|
|
mollieGateway.getPayment.mockResolvedValueOnce(payment({ status }));
|
|
|
|
await expect(createSelfServiceCheckout(createInput(), createDeps())).resolves.toEqual({
|
|
sessionId: RETRY_SESSION_ID,
|
|
checkoutUrl: "https://mollie.test/checkout/tr_checkout_retry_1",
|
|
providerPaymentId: "tr_checkout_retry_1",
|
|
});
|
|
|
|
expect(mocks.transitionClaimedCheckoutSessionStatus).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
id: SESSION_ID,
|
|
claimedStatus: "open",
|
|
data: { pending: true, status },
|
|
})
|
|
);
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledTimes(1);
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
paymentExternalId: RETRY_SESSION_ID,
|
|
invoiceExternalId: RETRY_SESSION_ID,
|
|
})
|
|
);
|
|
}
|
|
);
|
|
|
|
it("fails a concurrent duplicate while the deterministic session reservation is owned by another request", async () => {
|
|
mocks.getCheckoutSessionStatus.mockResolvedValueOnce(checkoutSession({ providerPaymentId: null, checkoutUrl: null, status: "creating", updatedAt: NOW }));
|
|
|
|
await expect(createSelfServiceCheckout(createInput(), createDeps())).rejects.toMatchObject({ code: "CHECKOUT_IN_PROGRESS" });
|
|
|
|
expect(mollieGateway.listPaymentMethods).not.toHaveBeenCalled();
|
|
expect(lagoGateway.createCustomer).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createPayment).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("converges different tab and user request UUIDs on the same open commercial checkout", async () => {
|
|
let canonicalSession: ReturnType<typeof checkoutSession> | null = null;
|
|
const fingerprints: string[] = [];
|
|
mocks.reserveCanonicalBaseCheckoutSession.mockImplementation(async (input) => {
|
|
fingerprints.push(input.businessFingerprint);
|
|
if (canonicalSession) return { session: canonicalSession, created: false };
|
|
canonicalSession = input.createSession(SESSION_ID) as ReturnType<typeof checkoutSession>;
|
|
persistedCheckoutSession = canonicalSession;
|
|
return { session: canonicalSession, created: true };
|
|
});
|
|
mocks.transitionClaimedCheckoutSessionStatus.mockImplementation(async (input) => {
|
|
canonicalSession = {
|
|
...canonicalSession!,
|
|
...input.data,
|
|
providerPaymentId: input.data.providerPaymentId ?? canonicalSession!.providerPaymentId,
|
|
checkoutUrl: input.data.checkoutUrl ?? canonicalSession!.checkoutUrl,
|
|
};
|
|
persistedCheckoutSession = canonicalSession;
|
|
return canonicalSession;
|
|
});
|
|
|
|
const first = await createSelfServiceCheckout(createInput(), createDeps());
|
|
const second = await createSelfServiceCheckout(
|
|
createInput({
|
|
checkoutRequestKey: "different_tab_request_987654321",
|
|
userId: "user_2",
|
|
userEmail: "second-owner@acme.test",
|
|
userName: "Grace Hopper",
|
|
}),
|
|
createDeps()
|
|
);
|
|
|
|
expect(second).toEqual(first);
|
|
expect(fingerprints).toHaveLength(2);
|
|
expect(fingerprints[1]).toBe(fingerprints[0]);
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledTimes(1);
|
|
expect(mollieGateway.getPayment).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("reserves the canonical business scope under a tenant advisory lock", async () => {
|
|
const businessFingerprint = "a".repeat(64);
|
|
const created = checkoutSession({
|
|
id: "hgco_canonical",
|
|
providerPaymentId: null,
|
|
checkoutUrl: null,
|
|
productKind: "base_plan",
|
|
scopeKey: `base_checkout:v1:${businessFingerprint}`,
|
|
status: "provider_claimed_test",
|
|
});
|
|
const tx = {
|
|
$queryRaw: vi.fn(async (query: TemplateStringsArray) =>
|
|
query.join("").includes("pg_advisory_xact_lock") ? [{ lock: "" }] : []),
|
|
tenantSubscription: {
|
|
findUnique: vi.fn().mockResolvedValue(null),
|
|
},
|
|
checkoutSessionStatus: {
|
|
findMany: vi.fn().mockResolvedValue([]),
|
|
create: vi.fn().mockResolvedValue(created),
|
|
},
|
|
};
|
|
mocks.withTenantRLS.mockImplementation(async (_tenantId, operation) => operation(tx));
|
|
|
|
const result = await reserveCanonicalBaseCheckoutSession({
|
|
tenantId: "tenant_1",
|
|
businessFingerprint,
|
|
selectedRecurringGrossAmountCents: 23_681,
|
|
now: NOW,
|
|
createSession: (id) => ({
|
|
id,
|
|
tenantId: "tenant_1",
|
|
pending: true,
|
|
email: "owner@acme.test",
|
|
fromUrl: "/billing#intent",
|
|
fromUserId: "user_1",
|
|
provider: "mollie",
|
|
providerPaymentId: null,
|
|
invoiceExternalId: id,
|
|
subscriptionProductId: "product_starter",
|
|
subscriptionPriceId: "price_starter_monthly",
|
|
lagoSubscriptionId: id,
|
|
planCode: "starter",
|
|
productKind: "base_plan",
|
|
scopeKey: `base_checkout:v1:${businessFingerprint}`,
|
|
quantity: 2,
|
|
officeSeatQuantity: 2,
|
|
fieldSeatQuantity: 0,
|
|
billingCadence: "monthly",
|
|
commitmentEndsAt: null,
|
|
storageAddOnCodes: [],
|
|
amountCents: 0,
|
|
currency: "EUR",
|
|
checkoutUrl: null,
|
|
status: "provider_claimed_test",
|
|
}),
|
|
});
|
|
|
|
expect(result).toEqual({ session: created, created: true });
|
|
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant_1", expect.any(Function));
|
|
expect(String(tx.$queryRaw.mock.calls[0]?.[0])).toContain("pg_advisory_xact_lock");
|
|
expect(String(tx.$queryRaw.mock.calls[0]?.[0])).toContain("recurring-checkout-policy:");
|
|
expect(tx.checkoutSessionStatus.findMany).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
where: expect.objectContaining({
|
|
tenantId: "tenant_1",
|
|
pending: true,
|
|
scopeKey: { startsWith: "base_checkout:v1:" },
|
|
status: { notIn: ["canceled", "failed", "expired"] },
|
|
}),
|
|
take: 2,
|
|
})
|
|
);
|
|
expect(tx.checkoutSessionStatus.create).toHaveBeenCalledWith({ data: expect.objectContaining({ scopeKey: `base_checkout:v1:${businessFingerprint}` }) });
|
|
});
|
|
|
|
it("fails closed when another commercial base checkout already owns the tenant scope", async () => {
|
|
const existing = checkoutSession({
|
|
scopeKey: `base_checkout:v1:${"b".repeat(64)}`,
|
|
productKind: "base_plan",
|
|
pending: true,
|
|
status: "open",
|
|
});
|
|
const tx = {
|
|
$queryRaw: vi.fn().mockResolvedValue([{ lock: "" }]),
|
|
checkoutSessionStatus: {
|
|
findMany: vi.fn().mockResolvedValue([existing]),
|
|
create: vi.fn(),
|
|
},
|
|
};
|
|
mocks.withTenantRLS.mockImplementation(async (_tenantId, operation) => operation(tx));
|
|
|
|
await expect(
|
|
reserveCanonicalBaseCheckoutSession({
|
|
tenantId: "tenant_1",
|
|
businessFingerprint: "a".repeat(64),
|
|
createSession: vi.fn(),
|
|
})
|
|
).rejects.toMatchObject({ code: "CHECKOUT_IN_PROGRESS" });
|
|
expect(tx.checkoutSessionStatus.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("allows only the recovery owner to mutate providers while a duplicate arrives", async () => {
|
|
persistedCheckoutSession = checkoutSession({ providerPaymentId: null, checkoutUrl: null, status: "provider_recovery_pending" });
|
|
mocks.createCheckoutSessionStatus.mockRejectedValue(Object.assign(new Error("unique"), { code: "P2002" }));
|
|
let releaseProvider!: () => void;
|
|
const providerRelease = new Promise<void>((resolve) => {
|
|
releaseProvider = resolve;
|
|
});
|
|
let providerStarted!: () => void;
|
|
const providerStart = new Promise<void>((resolve) => {
|
|
providerStarted = resolve;
|
|
});
|
|
mollieGateway.createPayment.mockImplementationOnce(async (providerInput) => {
|
|
providerStarted();
|
|
await providerRelease;
|
|
return payment({
|
|
amountCents: providerInput.amountCents,
|
|
metadata: {
|
|
...payment().metadata,
|
|
commitmentEndsAt: providerInput.commitmentEndsAt ?? null,
|
|
trialEndsAt: providerInput.trialEndsAt ?? null,
|
|
},
|
|
});
|
|
});
|
|
|
|
const owner = createSelfServiceCheckout(createInput(), createDeps());
|
|
await providerStart;
|
|
await expect(createSelfServiceCheckout(createInput(), createDeps())).rejects.toMatchObject({ code: "CHECKOUT_IN_PROGRESS" });
|
|
releaseProvider();
|
|
await expect(owner).resolves.toMatchObject({ providerPaymentId: "tr_checkout_1" });
|
|
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("allows only one of two stale takers to acquire the atomic provider claim", async () => {
|
|
const stale = checkoutSession({
|
|
providerPaymentId: null,
|
|
checkoutUrl: null,
|
|
status: "provider_claimed_abandoned",
|
|
updatedAt: new Date(NOW.getTime() - 5 * 60_000),
|
|
});
|
|
mocks.createCheckoutSessionStatus.mockRejectedValue(Object.assign(new Error("unique"), { code: "P2002" }));
|
|
mocks.getCheckoutSessionStatus.mockResolvedValue(stale);
|
|
let claimWon = false;
|
|
mocks.claimCheckoutSessionStatus.mockImplementation(async (claim) => {
|
|
if (claimWon) return null;
|
|
claimWon = true;
|
|
persistedCheckoutSession = { ...stale, status: claim.claimedStatus, updatedAt: NOW };
|
|
return persistedCheckoutSession;
|
|
});
|
|
|
|
await expect(createSelfServiceCheckout(createInput(), createDeps())).resolves.toMatchObject({ providerPaymentId: "tr_checkout_1" });
|
|
await expect(createSelfServiceCheckout(createInput(), createDeps())).rejects.toMatchObject({ code: "CHECKOUT_IN_PROGRESS" });
|
|
|
|
expect(mocks.claimCheckoutSessionStatus).toHaveBeenCalledTimes(2);
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("rejects reuse of a checkout key for a different request fingerprint", async () => {
|
|
mocks.getCheckoutSessionStatus.mockResolvedValueOnce(checkoutSession());
|
|
|
|
await expect(createSelfServiceCheckout(createInput({ paymentMethod: "creditcard" }), createDeps())).rejects.toMatchObject({
|
|
code: "PAYMENT_METADATA_MISMATCH",
|
|
});
|
|
|
|
expect(mollieGateway.listPaymentMethods).not.toHaveBeenCalled();
|
|
expect(lagoGateway.createCustomer).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createPayment).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("recovers a payment whose provider response was lost without creating a second payment or Lago subscription", async () => {
|
|
let persistedSession = checkoutSession({ providerPaymentId: null, checkoutUrl: null, status: "creating" });
|
|
let hasPersistedSession = false;
|
|
mocks.createCheckoutSessionStatus.mockImplementation(async (data) => {
|
|
hasPersistedSession = true;
|
|
persistedSession = { ...persistedSession, ...data };
|
|
return persistedSession;
|
|
});
|
|
mocks.getCheckoutSessionStatus.mockImplementation(async () => (hasPersistedSession ? persistedSession : null));
|
|
mocks.claimCheckoutSessionStatus.mockImplementation(async (input) => {
|
|
persistedSession = { ...persistedSession, status: input.claimedStatus, updatedAt: NOW };
|
|
return persistedSession;
|
|
});
|
|
mocks.transitionClaimedCheckoutSessionStatus.mockImplementation(async (input) => {
|
|
const data = input.data;
|
|
persistedSession = {
|
|
...persistedSession,
|
|
...data,
|
|
providerPaymentId: data.providerPaymentId ?? persistedSession.providerPaymentId,
|
|
checkoutUrl: data.checkoutUrl ?? persistedSession.checkoutUrl,
|
|
updatedAt: NOW,
|
|
};
|
|
return persistedSession;
|
|
});
|
|
|
|
let persistedLagoSubscription: Awaited<ReturnType<BillingGateway["createSubscription"]>> | null = null;
|
|
lagoGateway.getSubscription.mockImplementation(async () => persistedLagoSubscription);
|
|
lagoGateway.createSubscription.mockImplementationOnce(async (input) => {
|
|
persistedLagoSubscription = {
|
|
provider: "lago",
|
|
externalId: input.subscriptionExternalId,
|
|
providerSubscriptionId: `provider_${input.subscriptionExternalId}`,
|
|
externalCustomerId: input.tenantId,
|
|
planCode: input.managedPlan?.code ?? input.planCode,
|
|
status: "active",
|
|
name: input.name ?? null,
|
|
currentBillingPeriodStartedAt: null,
|
|
currentBillingPeriodEndingAt: null,
|
|
createdAt: NOW.toISOString(),
|
|
};
|
|
return persistedLagoSubscription;
|
|
});
|
|
mollieGateway.createPayment.mockRejectedValueOnce(new Error("response lost"));
|
|
|
|
await expect(createSelfServiceCheckout(createInput(), createDeps())).rejects.toThrow("response lost");
|
|
expect(persistedSession.status).toBe("provider_recovery_pending");
|
|
|
|
const recoveredPayment = payment();
|
|
expect(persistedSession).toMatchObject({
|
|
id: recoveredPayment.externalId,
|
|
tenantId: recoveredPayment.metadata.tenantId,
|
|
invoiceExternalId: recoveredPayment.metadata.invoiceExternalId,
|
|
lagoSubscriptionId: recoveredPayment.metadata.lagoSubscriptionId,
|
|
planCode: recoveredPayment.metadata.planCode,
|
|
subscriptionPriceId: recoveredPayment.metadata.subscriptionPriceId,
|
|
quantity: recoveredPayment.metadata.seatQuantity,
|
|
officeSeatQuantity: recoveredPayment.metadata.officeSeatQuantity,
|
|
fieldSeatQuantity: recoveredPayment.metadata.fieldSeatQuantity,
|
|
storageAddOnCodes: recoveredPayment.metadata.storageAddOnCodes,
|
|
amountCents: recoveredPayment.amountCents,
|
|
currency: recoveredPayment.currency,
|
|
});
|
|
mollieGateway.findCustomerPaymentByExternalIdExhaustive.mockResolvedValueOnce(recoveredPayment);
|
|
await expect(createSelfServiceCheckout(createInput(), createDeps())).resolves.toMatchObject({
|
|
sessionId: SESSION_ID,
|
|
providerPaymentId: "tr_checkout_1",
|
|
});
|
|
|
|
expect(lagoGateway.createSubscription).toHaveBeenCalledTimes(1);
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledTimes(1);
|
|
expect(mollieGateway.findCustomerPaymentByExternalIdExhaustive).toHaveBeenCalledWith("mollie_customer_1", SESSION_ID);
|
|
expect(mollieGateway.findCustomerPaymentByExternalId).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
paymentExternalId: SESSION_ID,
|
|
idempotencyKey: "hivegrid-checkout-payment-71891d710e5016d18e50cf5c25acf1a347436a2e",
|
|
})
|
|
);
|
|
});
|
|
|
|
it("keeps the original provider dates and managed plan after a response-loss retry one day later", async () => {
|
|
const fixedTermProduct = {
|
|
...starterProduct,
|
|
prices: [{ ...starterProduct.prices[0], contractMonths: 12 }],
|
|
};
|
|
mocks.getSubscriptionProduct.mockResolvedValue(fixedTermProduct);
|
|
mollieGateway.createPayment.mockRejectedValueOnce(new Error("response lost"));
|
|
|
|
await expect(createSelfServiceCheckout(createInput(), createDeps())).rejects.toThrow("response lost");
|
|
const firstPaymentInput = mollieGateway.createPayment.mock.calls[0]![0];
|
|
const oneDayLater = new Date(NOW.getTime() + 86_400_000);
|
|
|
|
await expect(createSelfServiceCheckout(createInput(), { ...createDeps(), now: () => oneDayLater })).resolves.toMatchObject({
|
|
providerPaymentId: "tr_checkout_1",
|
|
});
|
|
|
|
const retryPaymentInput = mollieGateway.createPayment.mock.calls[1]![0];
|
|
expect(retryPaymentInput).toMatchObject({
|
|
trialEndsAt: firstPaymentInput.trialEndsAt,
|
|
commitmentEndsAt: firstPaymentInput.commitmentEndsAt,
|
|
changeEffectiveAt: firstPaymentInput.changeEffectiveAt,
|
|
changeEffectiveAtDate: firstPaymentInput.changeEffectiveAtDate,
|
|
lagoPlanCode: firstPaymentInput.lagoPlanCode,
|
|
});
|
|
});
|
|
|
|
it("does not let a late provider failure overwrite a checkout already advanced by another actor", async () => {
|
|
mocks.transitionClaimedCheckoutSessionStatus.mockImplementation(async (transition) => {
|
|
if (persistedCheckoutSession.status !== transition.claimedStatus) return null;
|
|
persistedCheckoutSession = { ...persistedCheckoutSession, ...transition.data };
|
|
return persistedCheckoutSession;
|
|
});
|
|
mollieGateway.createPayment.mockImplementationOnce(async () => {
|
|
persistedCheckoutSession = { ...persistedCheckoutSession, status: "paid", pending: false };
|
|
throw new Error("late provider response failure");
|
|
});
|
|
|
|
await expect(createSelfServiceCheckout(createInput(), createDeps())).rejects.toThrow("late provider response failure");
|
|
|
|
expect(persistedCheckoutSession).toMatchObject({ status: "paid", pending: false });
|
|
expect(mocks.updateCheckoutSessionStatus).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps the trial on a retry after a failed first payment created an empty subscription row", async () => {
|
|
mocks.getTenantSubscription.mockResolvedValue({
|
|
...existingTenantSubscription(),
|
|
planCode: null,
|
|
trialStartsAt: null,
|
|
trialEndsAt: null,
|
|
products: [],
|
|
});
|
|
|
|
await createSelfServiceCheckout(createInput(), createDeps());
|
|
|
|
expect(lagoGateway.createSubscription).toHaveBeenCalledWith(expect.objectContaining({ subscriptionAt: new Date(TRIAL_ENDS_AT) }));
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(expect.objectContaining({ amountCents: 0, trialEndsAt: TRIAL_ENDS_AT }));
|
|
});
|
|
|
|
it("does not grant a second trial after a previous trial was consumed", async () => {
|
|
mocks.getTenantSubscription.mockResolvedValue({
|
|
...existingTenantSubscription(),
|
|
planCode: null,
|
|
trialStartsAt: new Date("2026-06-01T00:00:00.000Z"),
|
|
trialEndsAt: new Date("2026-06-15T00:00:00.000Z"),
|
|
products: [],
|
|
});
|
|
|
|
await createSelfServiceCheckout(createInput(), createDeps());
|
|
|
|
expect(lagoGateway.ensureManagedPlan).toHaveBeenCalledTimes(1);
|
|
expect(lagoGateway.createSubscription).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(expect.objectContaining({ amountCents: 6_902, trialEndsAt: undefined }));
|
|
});
|
|
|
|
it("revalidates a selected method before provider mutation and pins it to the hosted checkout", async () => {
|
|
mocks.getTenantSubscription.mockResolvedValue(existingTenantSubscription());
|
|
mocks.previewSelfServiceSubscription.mockResolvedValue({
|
|
changeKind: "upgrade",
|
|
effectiveAt: "immediate",
|
|
effectiveAtDate: null,
|
|
recurringTotalCents: 5_800,
|
|
recurringGrossTotalCents: 6_902,
|
|
selectedSeatQuantity: 2,
|
|
trialDays: 0,
|
|
});
|
|
|
|
await createSelfServiceCheckout(createInput({ paymentMethod: "creditcard", paymentLocale: "en" }), createDeps());
|
|
|
|
expect(mollieGateway.listPaymentMethods).toHaveBeenCalledWith({
|
|
amountCents: 6_902,
|
|
currency: "eur",
|
|
sequenceType: "first",
|
|
locale: "en_GB",
|
|
});
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(expect.objectContaining({ method: "creditcard", locale: "en_GB" }));
|
|
|
|
vi.clearAllMocks();
|
|
persistedCheckoutSession = null;
|
|
mollieGateway.listPaymentMethods.mockResolvedValue([{ provider: "mollie", id: "ideal", description: "iDEAL" }]);
|
|
await expect(createSelfServiceCheckout(createInput({ paymentMethod: "creditcard" }), createDeps())).rejects.toMatchObject({
|
|
code: "PAYMENT_METHOD_UNAVAILABLE",
|
|
});
|
|
expect(lagoGateway.createCustomer).not.toHaveBeenCalled();
|
|
expect(lagoGateway.createSubscription).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createCustomer).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createPayment).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not renew a bootstrap trial whose date markers were not persisted", async () => {
|
|
mocks.getTenantSubscription.mockResolvedValue({
|
|
...existingTenantSubscription(),
|
|
status: "trial",
|
|
planCode: "starter",
|
|
trialStartsAt: null,
|
|
trialEndsAt: null,
|
|
products: [
|
|
{
|
|
id: "tenant_product_starter",
|
|
subscriptionProductId: "product_starter",
|
|
lagoSubscriptionId: null,
|
|
billingProviderSubscriptionId: null,
|
|
planCode: null,
|
|
seatQuantity: null,
|
|
quantity: 1,
|
|
cancelledAt: null,
|
|
endsAt: null,
|
|
currentPeriodEnd: null,
|
|
subscriptionProduct: starterProduct,
|
|
prices: [
|
|
{
|
|
subscriptionPriceId: "price_starter_monthly",
|
|
subscriptionPrice: starterProduct.prices[0],
|
|
},
|
|
],
|
|
},
|
|
],
|
|
});
|
|
|
|
await createSelfServiceCheckout(createInput(), createDeps());
|
|
|
|
expect(lagoGateway.ensureManagedPlan).toHaveBeenCalledTimes(1);
|
|
expect(lagoGateway.createSubscription).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(expect.objectContaining({ amountCents: 6_902, trialEndsAt: undefined }));
|
|
});
|
|
|
|
it("keeps Lago's stable external id without changing the active provider version before payment", async () => {
|
|
mocks.getSubscriptionProduct.mockResolvedValue(businessProduct);
|
|
mocks.getTenantSubscription.mockResolvedValue(existingTenantSubscription());
|
|
mocks.previewSelfServiceSubscription.mockResolvedValue({
|
|
changeKind: "upgrade",
|
|
effectiveAt: "immediate",
|
|
effectiveAtDate: null,
|
|
recurringTotalCents: 14_700,
|
|
recurringGrossTotalCents: 17_493,
|
|
selectedSeatQuantity: 3,
|
|
trialDays: 0,
|
|
});
|
|
lagoGateway.getCustomer.mockResolvedValue(lagoCustomer);
|
|
|
|
await createSelfServiceCheckout(
|
|
createInput({
|
|
productId: "product_business",
|
|
priceId: "price_business_monthly",
|
|
quantity: 3,
|
|
}),
|
|
createDeps()
|
|
);
|
|
|
|
expect(lagoGateway.createCustomer).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createCustomer).not.toHaveBeenCalled();
|
|
expect(lagoGateway.ensureManagedPlan).toHaveBeenCalledTimes(1);
|
|
expect(lagoGateway.createSubscription).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
amountCents: 17_493,
|
|
mollieCustomerId: "mollie_customer_existing",
|
|
lagoSubscriptionId: "lago_subscription_existing",
|
|
lagoProviderSubscriptionId: undefined,
|
|
lagoPlanCode: expect.stringMatching(/^hg_price_/u),
|
|
planCode: "business",
|
|
seatQuantity: 3,
|
|
trialEndsAt: undefined,
|
|
changeEffectiveAt: "immediate",
|
|
})
|
|
);
|
|
expect(mocks.createCheckoutSessionStatus).toHaveBeenCalledWith(expect.objectContaining({ amountCents: 17_493 }));
|
|
});
|
|
|
|
it("uses the active base-plan Lago id when a higher-sorted recurring add-on precedes it", async () => {
|
|
const baseSubscription = existingTenantSubscription();
|
|
mocks.getSubscriptionProduct.mockResolvedValue(businessProduct);
|
|
mocks.getTenantSubscription.mockResolvedValue(
|
|
existingTenantSubscription({
|
|
products: [
|
|
{
|
|
id: "tenant_product_email_marketing",
|
|
subscriptionProductId: "product_email_marketing",
|
|
lagoSubscriptionId: "lago_subscription_email_marketing",
|
|
planCode: "email_marketing_xl",
|
|
seatQuantity: 1,
|
|
quantity: 1,
|
|
cancelledAt: null,
|
|
endsAt: null,
|
|
currentPeriodEnd: new Date(PERIOD_END),
|
|
subscriptionProduct: {
|
|
...businessProduct,
|
|
id: "product_email_marketing",
|
|
code: "email_marketing_xl",
|
|
lagoPlanCode: "email_marketing_xl",
|
|
kind: "recurring_add_on",
|
|
title: "E-Mail-Marketing XL",
|
|
order: 230,
|
|
},
|
|
prices: [],
|
|
},
|
|
...baseSubscription.products,
|
|
],
|
|
})
|
|
);
|
|
mocks.previewSelfServiceSubscription.mockResolvedValue({
|
|
changeKind: "upgrade",
|
|
effectiveAt: "immediate",
|
|
effectiveAtDate: null,
|
|
recurringTotalCents: 14_700,
|
|
recurringGrossTotalCents: 17_493,
|
|
selectedSeatQuantity: 3,
|
|
trialDays: 0,
|
|
});
|
|
lagoGateway.getCustomer.mockResolvedValue(lagoCustomer);
|
|
|
|
await createSelfServiceCheckout(
|
|
createInput({
|
|
productId: "product_business",
|
|
priceId: "price_business_monthly",
|
|
quantity: 3,
|
|
}),
|
|
createDeps()
|
|
);
|
|
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
lagoSubscriptionId: "lago_subscription_existing",
|
|
})
|
|
);
|
|
expect(mocks.createCheckoutSessionStatus).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
lagoSubscriptionId: "lago_subscription_existing",
|
|
})
|
|
);
|
|
});
|
|
|
|
it("creates a 12-month Core commitment with a customer-selected card, roles and storage", async () => {
|
|
mocks.getSubscriptionProduct.mockResolvedValue(annualCoreProduct);
|
|
mocks.previewSelfServiceSubscription.mockResolvedValue({
|
|
changeKind: "new",
|
|
effectiveAt: "immediate",
|
|
effectiveAtDate: null,
|
|
recurringTotalCents: 35_869,
|
|
recurringGrossTotalCents: 42_684,
|
|
selectedSeatQuantity: 12,
|
|
selectedOfficeSeatQuantity: 4,
|
|
selectedFieldSeatQuantity: 8,
|
|
selectedStorageAddOnCodes: ["storage_500gb"],
|
|
trialDays: 0,
|
|
});
|
|
|
|
await createSelfServiceCheckout(
|
|
createInput({
|
|
productId: "product_starter",
|
|
priceId: "price_starter_annual_sepa",
|
|
billingPeriod: 4,
|
|
quantity: undefined,
|
|
officeSeatQuantity: 4,
|
|
fieldSeatQuantity: 8,
|
|
storageAddOnCodes: ["storage_500gb"],
|
|
paymentMethod: "creditcard",
|
|
}),
|
|
createDeps()
|
|
);
|
|
|
|
expect(lagoGateway.createSubscription).not.toHaveBeenCalled();
|
|
expect(lagoGateway.ensureManagedPlan).toHaveBeenCalledWith({
|
|
code: expect.stringMatching(
|
|
new RegExp(`^hg_price_${hiveGridBillingCatalogVersion.replace(/[^a-z0-9]+/giu, "_")}_starter_annual_sepa_[a-f0-9]{16}$`, "u")
|
|
),
|
|
name: "Core · 4 Büro · 8 Baustelle · Speicher: Cloud-Speicher Plus · 500 GB",
|
|
invoiceDisplayName: "Core · 4 Büro · 8 Baustelle · Speicher: Cloud-Speicher Plus · 500 GB",
|
|
description: `Core · Katalog ${hiveGridBillingCatalogVersion}`,
|
|
interval: "monthly",
|
|
amountCents: 35_869,
|
|
currency: "EUR",
|
|
payInAdvance: true,
|
|
taxCodes: ["de-vat-19"],
|
|
metadata: {
|
|
hivegrid_resource_kind: "selected_price",
|
|
hivegrid_catalog_version: hiveGridBillingCatalogVersion,
|
|
hivegrid_base_plan_code: "starter_annual_sepa",
|
|
hivegrid_billing_cadence: "annual_sepa",
|
|
hivegrid_office_seats: "4",
|
|
hivegrid_field_seats: "8",
|
|
hivegrid_storage_add_ons: "storage_500gb",
|
|
},
|
|
});
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
amountCents: 42_684,
|
|
sequenceType: "first",
|
|
method: "creditcard",
|
|
planCode: "starter_annual_sepa",
|
|
officeSeatQuantity: 4,
|
|
fieldSeatQuantity: 8,
|
|
billingCadence: "annual_sepa",
|
|
commitmentEndsAt: "2027-07-15T10:00:00.000Z",
|
|
storageAddOnCodes: ["storage_500gb"],
|
|
})
|
|
);
|
|
expect(mocks.createCheckoutSessionStatus).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
amountCents: 42_684,
|
|
quantity: 12,
|
|
officeSeatQuantity: 4,
|
|
fieldSeatQuantity: 8,
|
|
billingCadence: "annual_sepa",
|
|
commitmentEndsAt: new Date("2027-07-15T10:00:00.000Z"),
|
|
storageAddOnCodes: ["storage_500gb"],
|
|
})
|
|
);
|
|
});
|
|
|
|
it("pins a first payment above EUR 1,000 to credit card before creating provider state", async () => {
|
|
mocks.getSubscriptionProduct.mockResolvedValue(annualCoreProduct);
|
|
mocks.previewSelfServiceSubscription.mockResolvedValue({
|
|
changeKind: "new",
|
|
effectiveAt: "immediate",
|
|
effectiveAtDate: null,
|
|
recurringTotalCents: 84_034,
|
|
recurringGrossTotalCents: 100_001,
|
|
selectedSeatQuantity: 30,
|
|
trialDays: 0,
|
|
});
|
|
|
|
await createSelfServiceCheckout(
|
|
createInput({
|
|
productId: "product_starter",
|
|
priceId: "price_starter_annual_sepa",
|
|
billingPeriod: 4,
|
|
quantity: 30,
|
|
}),
|
|
createDeps()
|
|
);
|
|
|
|
expect(mollieGateway.listPaymentMethods).toHaveBeenCalledWith({
|
|
amountCents: 100_001,
|
|
currency: "eur",
|
|
sequenceType: "first",
|
|
locale: "de_DE",
|
|
});
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(expect.objectContaining({ amountCents: 100_001, sequenceType: "first", method: "creditcard" }));
|
|
|
|
vi.clearAllMocks();
|
|
persistedCheckoutSession = null;
|
|
mocks.getSubscriptionProduct.mockResolvedValue(annualCoreProduct);
|
|
mocks.getTenantSubscription.mockResolvedValue(null);
|
|
mocks.previewSelfServiceSubscription.mockResolvedValue({
|
|
changeKind: "new",
|
|
effectiveAt: "immediate",
|
|
effectiveAtDate: null,
|
|
recurringTotalCents: 84_034,
|
|
recurringGrossTotalCents: 100_001,
|
|
selectedSeatQuantity: 30,
|
|
trialDays: 0,
|
|
});
|
|
mollieGateway.listPaymentMethods.mockResolvedValue([{ provider: "mollie", id: "ideal", description: "iDEAL" }]);
|
|
|
|
await expect(
|
|
createSelfServiceCheckout(
|
|
createInput({
|
|
productId: "product_starter",
|
|
priceId: "price_starter_annual_sepa",
|
|
billingPeriod: 4,
|
|
quantity: 30,
|
|
}),
|
|
createDeps()
|
|
)
|
|
).rejects.toMatchObject({ code: "PAYMENT_METHOD_UNAVAILABLE" });
|
|
expect(lagoGateway.createCustomer).not.toHaveBeenCalled();
|
|
expect(lagoGateway.ensureManagedPlan).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createCustomer).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createPayment).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("pins a sub-EUR 1,000 plan checkout to credit card when active add-ons lift the future invoice above the threshold", async () => {
|
|
mocks.getSubscriptionProduct.mockResolvedValue(annualCoreProduct);
|
|
mocks.previewSelfServiceSubscription.mockResolvedValue({
|
|
changeKind: "new",
|
|
effectiveAt: "immediate",
|
|
effectiveAtDate: null,
|
|
recurringTotalCents: 75_630,
|
|
recurringGrossTotalCents: 90_000,
|
|
selectedSeatQuantity: 30,
|
|
trialDays: 0,
|
|
});
|
|
mocks.resolveOtherActiveRecurringGrossTotalCents.mockReturnValue(10_001);
|
|
|
|
await createSelfServiceCheckout(
|
|
createInput({
|
|
productId: "product_starter",
|
|
priceId: "price_starter_annual_sepa",
|
|
billingPeriod: 4,
|
|
quantity: 30,
|
|
}),
|
|
createDeps()
|
|
);
|
|
|
|
expect(mocks.resolveOtherActiveRecurringGrossTotalCents).toHaveBeenCalledWith(null, { now: NOW });
|
|
expect(mollieGateway.listPaymentMethods).toHaveBeenCalledWith({
|
|
amountCents: 90_000,
|
|
currency: "eur",
|
|
sequenceType: "first",
|
|
locale: "de_DE",
|
|
});
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(expect.objectContaining({ amountCents: 90_000, sequenceType: "first", method: "creditcard" }));
|
|
});
|
|
|
|
it("fails closed before provider access when active recurring add-on economics are ambiguous", async () => {
|
|
mocks.previewSelfServiceSubscription.mockResolvedValue({
|
|
changeKind: "new",
|
|
effectiveAt: "immediate",
|
|
effectiveAtDate: null,
|
|
recurringTotalCents: 84_034,
|
|
recurringGrossTotalCents: 100_001,
|
|
selectedSeatQuantity: 30,
|
|
trialDays: 0,
|
|
});
|
|
mocks.resolveOtherActiveRecurringGrossTotalCents.mockReturnValue(null);
|
|
|
|
await expect(createSelfServiceCheckout(createInput({ quantity: 30 }), createDeps())).rejects.toMatchObject({ code: "CHECKOUT_NOT_PAYABLE" });
|
|
expect(mollieGateway.listPaymentMethods).not.toHaveBeenCalled();
|
|
expect(lagoGateway.createCustomer).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createPayment).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("sends a deferred downgrade as a zero-value first payment with period-end metadata", async () => {
|
|
mocks.getTenantSubscription.mockResolvedValue(existingTenantSubscription());
|
|
mocks.previewSelfServiceSubscription.mockResolvedValue({
|
|
changeKind: "downgrade",
|
|
effectiveAt: "period_end",
|
|
effectiveAtDate: PERIOD_END,
|
|
recurringTotalCents: 11_600,
|
|
recurringGrossTotalCents: 13_804,
|
|
selectedSeatQuantity: 4,
|
|
trialDays: 14,
|
|
});
|
|
lagoGateway.getCustomer.mockResolvedValue(lagoCustomer);
|
|
|
|
await createSelfServiceCheckout(createInput({ quantity: 4 }), createDeps());
|
|
|
|
expect(mollieGateway.createCustomer).not.toHaveBeenCalled();
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
amountCents: 0,
|
|
sequenceType: "first",
|
|
mollieCustomerId: "mollie_customer_existing",
|
|
trialEndsAt: undefined,
|
|
changeEffectiveAt: "period_end",
|
|
changeEffectiveAtDate: PERIOD_END,
|
|
})
|
|
);
|
|
expect(mocks.createCheckoutSessionStatus).toHaveBeenCalledWith(expect.objectContaining({ amountCents: 0 }));
|
|
});
|
|
|
|
it("requires a card authorization for a deferred annual change below EUR 1,000", async () => {
|
|
mocks.getSubscriptionProduct.mockResolvedValue(annualCoreProduct);
|
|
mocks.getTenantSubscription.mockResolvedValue(existingTenantSubscription());
|
|
mocks.previewSelfServiceSubscription.mockResolvedValue({
|
|
changeKind: "billing_period_change",
|
|
effectiveAt: "period_end",
|
|
effectiveAtDate: PERIOD_END,
|
|
recurringTotalCents: 17_900,
|
|
recurringGrossTotalCents: 21_301,
|
|
selectedSeatQuantity: 2,
|
|
selectedOfficeSeatQuantity: 2,
|
|
selectedFieldSeatQuantity: 0,
|
|
selectedStorageAddOnCodes: [],
|
|
trialDays: 0,
|
|
});
|
|
|
|
await expect(
|
|
createSelfServiceCheckout(
|
|
createInput({
|
|
productId: "product_starter",
|
|
priceId: "price_starter_annual_sepa",
|
|
billingPeriod: 4,
|
|
officeSeatQuantity: 2,
|
|
fieldSeatQuantity: 0,
|
|
paymentMethod: "creditcard",
|
|
}),
|
|
createDeps()
|
|
)
|
|
).resolves.toMatchObject({ checkoutUrl: "https://mollie.test/checkout/tr_checkout_1" });
|
|
|
|
expect(lagoGateway.createSubscription).toHaveBeenCalledWith(
|
|
expect.objectContaining({ subscriptionAt: new Date(PERIOD_END), planCode: "starter_annual_sepa", paymentMethodType: "manual" })
|
|
);
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(
|
|
expect.objectContaining({ amountCents: 0, sequenceType: "first", method: "creditcard", billingCadence: "annual_sepa" })
|
|
);
|
|
});
|
|
|
|
it("authorizes a deferred high-value annual change with a zero-value card payment", async () => {
|
|
mocks.getSubscriptionProduct.mockResolvedValue(annualCoreProduct);
|
|
mocks.getTenantSubscription.mockResolvedValue(existingTenantSubscription());
|
|
mocks.previewSelfServiceSubscription.mockResolvedValue({
|
|
changeKind: "billing_period_change",
|
|
effectiveAt: "period_end",
|
|
effectiveAtDate: PERIOD_END,
|
|
recurringTotalCents: 84_034,
|
|
recurringGrossTotalCents: 100_001,
|
|
selectedSeatQuantity: 30,
|
|
selectedOfficeSeatQuantity: 10,
|
|
selectedFieldSeatQuantity: 20,
|
|
selectedStorageAddOnCodes: [],
|
|
trialDays: 0,
|
|
});
|
|
|
|
await createSelfServiceCheckout(
|
|
createInput({
|
|
productId: "product_starter",
|
|
priceId: "price_starter_annual_sepa",
|
|
billingPeriod: 4,
|
|
officeSeatQuantity: 10,
|
|
fieldSeatQuantity: 20,
|
|
}),
|
|
createDeps()
|
|
);
|
|
|
|
expect(mollieGateway.listPaymentMethods).toHaveBeenCalledWith(expect.objectContaining({ amountCents: 0, sequenceType: "first" }));
|
|
expect(mollieGateway.createPayment).toHaveBeenCalledWith(
|
|
expect.objectContaining({ amountCents: 0, sequenceType: "first", method: "creditcard", changeEffectiveAt: "period_end" })
|
|
);
|
|
});
|
|
|
|
it("surfaces forged and below-usage selections only as safe checkout errors", async () => {
|
|
await expect(createSelfServiceCheckout(createInput({ priceId: "forged_price" }), createDeps())).rejects.toMatchObject<SelfServiceCheckoutError>({
|
|
name: "SelfServiceCheckoutError",
|
|
code: "PRICE_NOT_FOUND",
|
|
i18nKey: "billing:selfServiceSubscription.errors.PRICE_NOT_FOUND",
|
|
});
|
|
|
|
mocks.previewSelfServiceSubscription.mockRejectedValueOnce(new mocks.MockSelfServiceSubscriptionValidationError("SEAT_QUANTITY_BELOW_USAGE"));
|
|
await expect(createSelfServiceCheckout(createInput({ quantity: 1 }), createDeps())).rejects.toMatchObject<SelfServiceCheckoutError>({
|
|
name: "SelfServiceCheckoutError",
|
|
code: "SEAT_QUANTITY_BELOW_USAGE",
|
|
i18nKey: "billing:selfServiceSubscription.errors.SEAT_QUANTITY_BELOW_USAGE",
|
|
});
|
|
expect(mollieGateway.createPayment).not.toHaveBeenCalled();
|
|
expect(mocks.createCheckoutSessionStatus).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each([
|
|
["open", "processing"],
|
|
["pending", "processing"],
|
|
["authorized", "processing"],
|
|
["canceled", "cancelled"],
|
|
["failed", "failed"],
|
|
["expired", "expired"],
|
|
["paid", "paid"],
|
|
["unknown", "failed"],
|
|
] as const)("projects Mollie %s as %s", (providerStatus, returnState) => {
|
|
expect(projectSelfServiceCheckoutReturnState(providerStatus)).toBe(returnState);
|
|
});
|
|
|
|
it.each([
|
|
["provider payment id", (value: PaymentGatewayPayment) => ({ ...value, providerPaymentId: "tr_other" })],
|
|
["external payment id", (value: PaymentGatewayPayment) => ({ ...value, externalId: "hgco_other" })],
|
|
["tenant", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, tenantId: "tenant_other" } })],
|
|
["invoice session", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, invoiceExternalId: "invoice_other" } })],
|
|
["Lago subscription", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, lagoSubscriptionId: "lago_other" } })],
|
|
["plan", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, planCode: "swarm" } })],
|
|
["price", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, subscriptionPriceId: "price_other" } })],
|
|
["seat split", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, fieldSeatQuantity: 1 } })],
|
|
["billing cadence", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, billingCadence: "annual_sepa" } })],
|
|
["storage", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, storageAddOnCodes: ["storage_1tb"] } })],
|
|
["commitment", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, commitmentEndsAt: "2028-01-01T00:00:00.000Z" } })],
|
|
["trial", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, trialEndsAt: null } })],
|
|
["effective mode", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, changeEffectiveAt: "period_end" as const } })],
|
|
["effective date", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, changeEffectiveAtDate: PERIOD_END } })],
|
|
["managed Lago plan", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, lagoPlanCode: "hg_price_forged" } })],
|
|
[
|
|
"Lago provider subscription",
|
|
(value: PaymentGatewayPayment) => ({
|
|
...value,
|
|
metadata: { ...value.metadata, lagoProviderSubscriptionId: "provider_forged" },
|
|
}),
|
|
],
|
|
["Lago customer", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, lagoCustomerId: "lago_customer_forged" } })],
|
|
["Mollie customer", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, mollieCustomerId: "mollie_customer_forged" } })],
|
|
["amount", (value: PaymentGatewayPayment) => ({ ...value, amountCents: 1 })],
|
|
["currency", (value: PaymentGatewayPayment) => ({ ...value, currency: "USD" })],
|
|
["billing flow", (value: PaymentGatewayPayment) => ({ ...value, metadata: { ...value.metadata, billingFlow: "product_acquisition" as const } })],
|
|
["refund", (value: PaymentGatewayPayment) => ({ ...value, amountRefundedCents: 1 })],
|
|
] as const)("rejects a paid payment with mismatching %s before any entitlement or provider mutation", async (_label, mutate) => {
|
|
const expectedPayment = payment({ status: "paid", paidAt: NOW.toISOString() });
|
|
mocks.getCheckoutSessionStatus.mockResolvedValue(checkoutSessionForPayment(expectedPayment));
|
|
mollieGateway.getPayment.mockResolvedValue(mutate(expectedPayment));
|
|
|
|
await expect(completeSelfServiceCheckout({ sessionId: SESSION_ID, tenantId: "tenant_1" }, { lagoGateway, mollieGateway })).rejects.toMatchObject({
|
|
code: "PAYMENT_METADATA_MISMATCH",
|
|
});
|
|
|
|
expect(mocks.updateCheckoutSessionStatus).not.toHaveBeenCalled();
|
|
expect(lagoGateway.createSubscription).not.toHaveBeenCalled();
|
|
expect(mocks.applyMolliePaymentSync).not.toHaveBeenCalled();
|
|
expect(mocks.applyLagoSubscriptionSync).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("completes a paid checkout created before versioned intents were deployed", async () => {
|
|
const paidPayment = payment({ status: "paid", paidAt: NOW.toISOString() });
|
|
mocks.getCheckoutSessionStatus.mockResolvedValue(
|
|
checkoutSessionForPayment(paidPayment, {
|
|
fromUrl: "/acme/settings/subscription",
|
|
})
|
|
);
|
|
mollieGateway.getPayment.mockResolvedValue(paidPayment);
|
|
|
|
await expect(completeSelfServiceCheckout({ sessionId: SESSION_ID, tenantId: "tenant_1" }, { lagoGateway, mollieGateway })).resolves.toMatchObject({
|
|
id: SESSION_ID,
|
|
source: "self-service",
|
|
});
|
|
|
|
expect(mocks.applyMolliePaymentSync).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_1", status: "paid" }));
|
|
expect(mocks.applyLagoSubscriptionSync).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant_1", status: "trial" }));
|
|
});
|
|
|
|
it("rejects a manipulated paid legacy checkout before billing activation", async () => {
|
|
const expectedPayment = payment({ status: "paid", paidAt: NOW.toISOString() });
|
|
mocks.getCheckoutSessionStatus.mockResolvedValue(
|
|
checkoutSessionForPayment(expectedPayment, {
|
|
fromUrl: "/acme/settings/subscription",
|
|
})
|
|
);
|
|
mollieGateway.getPayment.mockResolvedValue(
|
|
payment({
|
|
status: "paid",
|
|
paidAt: NOW.toISOString(),
|
|
metadata: { planCode: "business" },
|
|
})
|
|
);
|
|
|
|
await expect(completeSelfServiceCheckout({ sessionId: SESSION_ID, tenantId: "tenant_1" }, { lagoGateway, mollieGateway })).rejects.toMatchObject({
|
|
code: "PAYMENT_METADATA_MISMATCH",
|
|
});
|
|
|
|
expect(mocks.updateCheckoutSessionStatus).not.toHaveBeenCalled();
|
|
expect(mocks.applyMolliePaymentSync).not.toHaveBeenCalled();
|
|
expect(mocks.applyLagoSubscriptionSync).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("never falls back to legacy decoding for a malformed versioned intent", async () => {
|
|
const paidPayment = payment({ status: "paid", paidAt: NOW.toISOString() });
|
|
mocks.getCheckoutSessionStatus.mockResolvedValue(
|
|
checkoutSessionForPayment(paidPayment, {
|
|
fromUrl: "/acme/settings/subscription#hivegrid-checkout-v1=not-valid-base64",
|
|
})
|
|
);
|
|
mollieGateway.getPayment.mockResolvedValue(paidPayment);
|
|
|
|
await expect(completeSelfServiceCheckout({ sessionId: SESSION_ID, tenantId: "tenant_1" }, { lagoGateway, mollieGateway })).rejects.toMatchObject({
|
|
code: "PAYMENT_METADATA_MISMATCH",
|
|
});
|
|
|
|
expect(mocks.updateCheckoutSessionStatus).not.toHaveBeenCalled();
|
|
expect(mocks.applyMolliePaymentSync).not.toHaveBeenCalled();
|
|
expect(mocks.applyLagoSubscriptionSync).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each(["pending", "canceled", "failed", "expired"] as const)("returns the persisted %s checkout without activating billing", async (providerStatus) => {
|
|
mocks.getCheckoutSessionStatus.mockResolvedValue(checkoutSession());
|
|
mollieGateway.getPayment.mockResolvedValue(payment({ status: providerStatus }));
|
|
|
|
const result = await completeSelfServiceCheckout({ sessionId: SESSION_ID, tenantId: "tenant_1" }, { lagoGateway, mollieGateway });
|
|
|
|
expect(result).toMatchObject({
|
|
id: SESSION_ID,
|
|
source: "self-service",
|
|
status: { status: providerStatus, pending: true },
|
|
});
|
|
expect(lagoGateway.createSubscription).not.toHaveBeenCalled();
|
|
expect(lagoGateway.getSubscription).not.toHaveBeenCalled();
|
|
expect(mocks.applyMolliePaymentSync).not.toHaveBeenCalled();
|
|
expect(mocks.applyLagoSubscriptionSync).not.toHaveBeenCalled();
|
|
expect(mocks.clearTenantSubscriptionCache).not.toHaveBeenCalled();
|
|
expect(mocks.invalidateTenantModuleAccessCache).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("activates the isolated Lago subscription only after Mollie reports the payment as paid", async () => {
|
|
const commitmentEndsAt = "2027-07-15T10:00:00.000Z";
|
|
const initialInvoice = {
|
|
provider: "lago" as const,
|
|
providerInvoiceId: "lago_invoice_initial",
|
|
number: "LAG-001",
|
|
externalCustomerId: "tenant_1",
|
|
status: "finalized" as const,
|
|
paymentStatus: "pending" as const,
|
|
invoiceType: "subscription",
|
|
currency: "EUR",
|
|
totalAmountCents: 60_452,
|
|
issuingDate: "2026-07-15",
|
|
fileUrl: null,
|
|
subscriptionExternalIds: [SESSION_ID],
|
|
subscriptionProviderIds: [`provider_${SESSION_ID}`],
|
|
};
|
|
const invoiceListSummary = {
|
|
...initialInvoice,
|
|
subscriptionExternalIds: undefined,
|
|
subscriptionProviderIds: undefined,
|
|
};
|
|
lagoGateway.listInvoices.mockResolvedValue([invoiceListSummary]);
|
|
lagoGateway.getInvoice.mockResolvedValue(initialInvoice);
|
|
lagoGateway.updateInvoicePaymentStatus.mockResolvedValue({ ...initialInvoice, paymentStatus: "succeeded" });
|
|
const paidPayment = payment({
|
|
status: "paid",
|
|
amountCents: 60_452,
|
|
paidAt: NOW.toISOString(),
|
|
metadata: {
|
|
tenantId: "tenant_1",
|
|
invoiceExternalId: SESSION_ID,
|
|
paymentExternalId: SESSION_ID,
|
|
mollieCustomerId: "mollie_customer_1",
|
|
lagoCustomerId: "lago_customer_1",
|
|
lagoSubscriptionId: SESSION_ID,
|
|
lagoPlanCode: "hg_price_swarm_123",
|
|
planCode: "swarm",
|
|
subscriptionPriceId: "price_swarm_monthly",
|
|
seatQuantity: 20,
|
|
officeSeatQuantity: 5,
|
|
fieldSeatQuantity: 15,
|
|
billingCadence: "monthly",
|
|
commitmentEndsAt,
|
|
storageAddOnCodes: ["storage_100gb"],
|
|
trialEndsAt: null,
|
|
changeEffectiveAt: "immediate",
|
|
changeEffectiveAtDate: null,
|
|
billingFlow: "self_service_new",
|
|
},
|
|
});
|
|
mocks.getCheckoutSessionStatus.mockResolvedValue(checkoutSessionForPayment(paidPayment, { commitmentEndsAt: new Date(commitmentEndsAt) }));
|
|
mollieGateway.getPayment.mockResolvedValue(paidPayment);
|
|
|
|
await completeSelfServiceCheckout({ sessionId: SESSION_ID, tenantId: "tenant_1" }, { lagoGateway, mollieGateway });
|
|
|
|
expect(lagoGateway.createSubscription).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
tenantId: "tenant_1",
|
|
subscriptionExternalId: SESSION_ID,
|
|
planCode: "hg_price_swarm_123",
|
|
seatQuantity: 20,
|
|
paymentMethodType: "manual",
|
|
consolidateInvoice: false,
|
|
})
|
|
);
|
|
expect(lagoGateway.createSubscription.mock.invocationCallOrder[0]).toBeLessThan(mocks.applyLagoSubscriptionSync.mock.invocationCallOrder[0]!);
|
|
expect(mocks.applyLagoSubscriptionSync).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
status: "active",
|
|
officeSeatQuantity: 5,
|
|
fieldSeatQuantity: 15,
|
|
storageAddOnCodes: ["storage_100gb"],
|
|
invoiceExternalId: "lago_invoice_initial",
|
|
})
|
|
);
|
|
expect(mocks.applyMolliePaymentSync).toHaveBeenCalledWith(expect.objectContaining({ invoiceExternalId: SESSION_ID }));
|
|
expect(mocks.applyMolliePaymentSync.mock.invocationCallOrder[0]).toBeLessThan(mocks.correlateCheckoutSessionProviderInvoice.mock.invocationCallOrder[0]!);
|
|
expect(mocks.correlateCheckoutSessionProviderInvoice).toHaveBeenCalledWith({
|
|
id: SESSION_ID,
|
|
tenantId: "tenant_1",
|
|
providerPaymentId: "tr_checkout_1",
|
|
lagoSubscriptionId: SESSION_ID,
|
|
sourceInvoiceExternalId: SESSION_ID,
|
|
providerInvoiceExternalId: "lago_invoice_initial",
|
|
});
|
|
expect(lagoGateway.updateInvoicePaymentStatus).toHaveBeenCalledWith("lago_invoice_initial", "succeeded");
|
|
expect(lagoGateway.getInvoice).toHaveBeenCalledWith("lago_invoice_initial");
|
|
expect(mocks.reserveRecurringInvoiceCollection).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
invoiceExternalId: "lago_invoice_initial",
|
|
lagoSubscriptionId: SESSION_ID,
|
|
billingProviderSubscriptionId: `provider_${SESSION_ID}`,
|
|
invoicingReason: "subscription_starting",
|
|
amountCents: 60_452,
|
|
})
|
|
);
|
|
});
|
|
|
|
it("reuses the persisted initial invoice instead of a newer equal recurring invoice", async () => {
|
|
const persistedInvoice = {
|
|
provider: "lago" as const,
|
|
providerInvoiceId: "lago_invoice_initial",
|
|
number: "LAG-001",
|
|
externalCustomerId: "tenant_1",
|
|
status: "finalized" as const,
|
|
paymentStatus: "succeeded" as const,
|
|
invoiceType: "subscription",
|
|
currency: "EUR",
|
|
totalAmountCents: 60_452,
|
|
issuingDate: "2026-07-15",
|
|
fileUrl: null,
|
|
subscriptionExternalIds: [SESSION_ID],
|
|
subscriptionProviderIds: [`provider_${SESSION_ID}`],
|
|
};
|
|
lagoGateway.getInvoice.mockResolvedValue(persistedInvoice);
|
|
lagoGateway.listInvoices.mockResolvedValue([
|
|
{
|
|
...persistedInvoice,
|
|
providerInvoiceId: "lago_invoice_recurring",
|
|
number: "LAG-002",
|
|
issuingDate: "2026-08-15",
|
|
},
|
|
]);
|
|
const paidPayment = payment({
|
|
status: "paid",
|
|
amountCents: 60_452,
|
|
paidAt: NOW.toISOString(),
|
|
metadata: {
|
|
tenantId: "tenant_1",
|
|
invoiceExternalId: SESSION_ID,
|
|
paymentExternalId: SESSION_ID,
|
|
mollieCustomerId: "mollie_customer_1",
|
|
lagoCustomerId: "lago_customer_1",
|
|
lagoSubscriptionId: SESSION_ID,
|
|
lagoPlanCode: "hg_price_swarm_123",
|
|
planCode: "swarm",
|
|
subscriptionPriceId: "price_swarm_monthly",
|
|
seatQuantity: 20,
|
|
officeSeatQuantity: 5,
|
|
fieldSeatQuantity: 15,
|
|
billingCadence: "monthly",
|
|
storageAddOnCodes: ["storage_100gb"],
|
|
trialEndsAt: null,
|
|
changeEffectiveAt: "immediate",
|
|
changeEffectiveAtDate: null,
|
|
billingFlow: "self_service_new",
|
|
},
|
|
});
|
|
mocks.getCheckoutSessionStatus.mockResolvedValue(checkoutSessionForPayment(paidPayment, { invoiceExternalId: persistedInvoice.providerInvoiceId }));
|
|
mollieGateway.getPayment.mockResolvedValue(paidPayment);
|
|
|
|
await completeSelfServiceCheckout({ sessionId: SESSION_ID, tenantId: "tenant_1" }, { lagoGateway, mollieGateway });
|
|
|
|
expect(lagoGateway.getInvoice).toHaveBeenCalledWith("lago_invoice_initial");
|
|
expect(lagoGateway.listInvoices).not.toHaveBeenCalled();
|
|
expect(lagoGateway.updateInvoicePaymentStatus).not.toHaveBeenCalled();
|
|
expect(mocks.correlateCheckoutSessionProviderInvoice).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
sourceInvoiceExternalId: "lago_invoice_initial",
|
|
providerInvoiceExternalId: "lago_invoice_initial",
|
|
})
|
|
);
|
|
});
|
|
|
|
it("fails closed without granting entitlements when the paid Lago subscription cannot be activated", async () => {
|
|
lagoGateway.createSubscription.mockRejectedValueOnce(new Error("Lago unavailable"));
|
|
const paidPayment = payment({
|
|
status: "paid",
|
|
paidAt: NOW.toISOString(),
|
|
metadata: {
|
|
tenantId: "tenant_1",
|
|
invoiceExternalId: SESSION_ID,
|
|
paymentExternalId: SESSION_ID,
|
|
mollieCustomerId: "mollie_customer_1",
|
|
lagoCustomerId: "lago_customer_1",
|
|
lagoSubscriptionId: SESSION_ID,
|
|
lagoPlanCode: "hg_price_swarm_123",
|
|
planCode: "swarm",
|
|
seatQuantity: 20,
|
|
trialEndsAt: null,
|
|
changeEffectiveAt: "immediate",
|
|
changeEffectiveAtDate: null,
|
|
billingFlow: "self_service_new",
|
|
},
|
|
});
|
|
mocks.getCheckoutSessionStatus.mockResolvedValue(checkoutSessionForPayment(paidPayment));
|
|
mollieGateway.getPayment.mockResolvedValue(paidPayment);
|
|
|
|
await expect(completeSelfServiceCheckout({ sessionId: SESSION_ID, tenantId: "tenant_1" }, { lagoGateway, mollieGateway })).rejects.toMatchObject({
|
|
code: "SUBSCRIPTION_ACTIVATION_FAILED",
|
|
});
|
|
expect(mocks.applyMolliePaymentSync).not.toHaveBeenCalled();
|
|
expect(mocks.applyLagoSubscriptionSync).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("completes a paid trial by persisting the Mollie customer and Lago trial window", async () => {
|
|
const paidPayment = payment({
|
|
status: "paid",
|
|
paidAt: NOW.toISOString(),
|
|
metadata: {
|
|
tenantId: "tenant_1",
|
|
invoiceExternalId: SESSION_ID,
|
|
paymentExternalId: SESSION_ID,
|
|
mollieCustomerId: "mollie_customer_trial",
|
|
lagoCustomerId: "lago_customer_1",
|
|
lagoSubscriptionId: SESSION_ID,
|
|
planCode: "starter",
|
|
seatQuantity: 2,
|
|
trialEndsAt: TRIAL_ENDS_AT,
|
|
changeEffectiveAt: "immediate",
|
|
changeEffectiveAtDate: null,
|
|
},
|
|
});
|
|
const session = checkoutSessionForPayment(paidPayment);
|
|
mocks.getCheckoutSessionStatus.mockResolvedValue(session);
|
|
mollieGateway.getPayment.mockResolvedValue(paidPayment);
|
|
|
|
const result = await completeSelfServiceCheckout({ sessionId: SESSION_ID, tenantId: "tenant_1" }, { lagoGateway, mollieGateway, now: () => new Date(NOW) });
|
|
|
|
expect(result).toMatchObject({ id: SESSION_ID, source: "self-service" });
|
|
expect(mocks.runWithRlsContext).toHaveBeenCalledWith({ tenantId: "tenant_1" }, expect.any(Function));
|
|
expect(mocks.updateCheckoutSessionStatus).toHaveBeenCalledWith(
|
|
{ id: SESSION_ID, tenantId: "tenant_1" },
|
|
expect.objectContaining({ pending: false, status: "paid", providerPaymentId: "tr_checkout_1" })
|
|
);
|
|
expect(mocks.applyMolliePaymentSync).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
tenantId: "tenant_1",
|
|
mollieCustomerId: "mollie_customer_trial",
|
|
status: "paid",
|
|
})
|
|
);
|
|
expect(mocks.applyLagoSubscriptionSync).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
tenantId: "tenant_1",
|
|
lagoCustomerId: "lago_customer_1",
|
|
lagoSubscriptionId: SESSION_ID,
|
|
planCode: "starter",
|
|
status: "trial",
|
|
trialStartsAt: NOW,
|
|
trialEndsAt: new Date(TRIAL_ENDS_AT),
|
|
receivedAt: NOW,
|
|
})
|
|
);
|
|
expect(lagoGateway.getSubscription).not.toHaveBeenCalled();
|
|
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant_1");
|
|
expect(mocks.invalidateTenantModuleAccessCache).toHaveBeenCalledWith("tenant_1");
|
|
});
|
|
|
|
it("stores deferred Lago entitlement state without activating it before the effective date", async () => {
|
|
const paidPayment = payment({
|
|
status: "paid",
|
|
paidAt: NOW.toISOString(),
|
|
metadata: {
|
|
tenantId: "tenant_1",
|
|
invoiceExternalId: SESSION_ID,
|
|
paymentExternalId: SESSION_ID,
|
|
mollieCustomerId: "mollie_customer_existing",
|
|
lagoCustomerId: "lago_customer_1",
|
|
lagoSubscriptionId: "lago_subscription_existing",
|
|
planCode: "starter",
|
|
subscriptionPriceId: "price_starter_monthly",
|
|
seatQuantity: 4,
|
|
trialEndsAt: null,
|
|
changeEffectiveAt: "period_end",
|
|
changeEffectiveAtDate: PERIOD_END,
|
|
billingFlow: "self_service_change",
|
|
},
|
|
});
|
|
mocks.getCheckoutSessionStatus.mockResolvedValue(checkoutSessionForPayment(paidPayment));
|
|
mollieGateway.getPayment.mockResolvedValue(paidPayment);
|
|
|
|
await completeSelfServiceCheckout({ sessionId: SESSION_ID, tenantId: "tenant_1" }, { lagoGateway, mollieGateway });
|
|
|
|
expect(mocks.applyMolliePaymentSync).toHaveBeenCalledWith(
|
|
expect.objectContaining({ tenantId: "tenant_1", mollieCustomerId: "mollie_customer_existing", status: "paid" })
|
|
);
|
|
expect(mocks.applyLagoSubscriptionSync).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
deferredUntil: new Date(PERIOD_END),
|
|
subscriptionPriceId: "price_starter_monthly",
|
|
})
|
|
);
|
|
expect(lagoGateway.getSubscription).not.toHaveBeenCalled();
|
|
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant_1");
|
|
expect(mocks.invalidateTenantModuleAccessCache).toHaveBeenCalledWith("tenant_1");
|
|
});
|
|
|
|
it("executes both create and completion reads inside their tenant RLS callbacks", async () => {
|
|
let activeContext: { tenantId: string; userId?: string } | null = null;
|
|
mocks.runWithRlsContext.mockImplementation(async (context, callback) => {
|
|
activeContext = context as { tenantId: string; userId?: string };
|
|
try {
|
|
return await callback();
|
|
} finally {
|
|
activeContext = null;
|
|
}
|
|
});
|
|
mocks.getSubscriptionProduct.mockImplementation(async () => {
|
|
expect(activeContext).toEqual({ tenantId: "tenant_1", userId: "user_1" });
|
|
return starterProduct;
|
|
});
|
|
|
|
await createSelfServiceCheckout(createInput(), createDeps());
|
|
|
|
mocks.getSubscriptionProduct.mockResolvedValue(starterProduct);
|
|
mocks.getCheckoutSessionStatus.mockImplementation(async () => {
|
|
expect(activeContext).toEqual({ tenantId: "tenant_1" });
|
|
return checkoutSession();
|
|
});
|
|
mollieGateway.getPayment.mockResolvedValue(payment({ status: "pending" }));
|
|
|
|
await completeSelfServiceCheckout({ sessionId: SESSION_ID, tenantId: "tenant_1" }, { mollieGateway });
|
|
|
|
expect(mocks.runWithRlsContext.mock.calls.map(([context]) => context)).toEqual([{ tenantId: "tenant_1", userId: "user_1" }, { tenantId: "tenant_1" }]);
|
|
});
|
|
});
|