Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/services/billing/self-service-subscription.server.test.ts
T

727 lines
24 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
getAllSubscriptionProducts: vi.fn(),
getTenantSubscription: vi.fn(),
getTenantSeatCounts: vi.fn(),
resolveTenantBillingState: vi.fn(),
resolveTenantStorageUsage: vi.fn(),
resolveEmailMarketingQuotaUsage: vi.fn(),
getDbClient: vi.fn(() => ({})),
runWithRlsContext: vi.fn((_context: unknown, callback: () => unknown) => callback()),
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
runWithRlsContext: (...args: unknown[]) => mocks.runWithRlsContext(...args),
}));
vi.mock("@hivegrid/db/billing-domain.server", () => ({
resolveTenantBillingState: (...args: unknown[]) => mocks.resolveTenantBillingState(...args),
}));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: (...args: unknown[]) => mocks.getDbClient(...args),
}));
vi.mock("./storage-capacity.server", () => ({
resolveTenantStorageUsage: (...args: unknown[]) => mocks.resolveTenantStorageUsage(...args),
}));
vi.mock("./email-marketing-quota.server", () => ({
resolveEmailMarketingQuotaUsage: (...args: unknown[]) => mocks.resolveEmailMarketingQuotaUsage(...args),
}));
vi.mock("~/utils/db/subscriptionProducts.db.server", () => ({
getAllSubscriptionProducts: (...args: unknown[]) => mocks.getAllSubscriptionProducts(...args),
}));
vi.mock("~/utils/db/tenantSubscriptions.db.server", () => ({
getTenantSubscription: (...args: unknown[]) => mocks.getTenantSubscription(...args),
}));
vi.mock("~/utils/db/permissions/seatType.db.server", () => ({
getTenantSeatCounts: (...args: unknown[]) => mocks.getTenantSeatCounts(...args),
}));
import {
loadSelfServiceSubscriptionCatalog,
loadSelfServiceSubscriptionServerContext,
previewSelfServiceSubscription,
resolveCurrentRecurringGrossTotalCents,
resolveOtherActiveRecurringGrossTotalCents,
resolveSelfServicePreferredSelection,
SelfServiceSubscriptionValidationError,
} from "./self-service-subscription.server";
const starter = {
id: "product_starter",
code: "starter",
lagoPlanCode: "starter",
kind: "base_plan",
title: "billing:plans.starter.title",
description: "billing:plans.starter.description",
badge: null,
order: 1,
hasQuantity: true,
active: true,
public: true,
features: [{ code: "crm", name: "crm", title: "billing:features.crm", order: 1 }],
prices: [
{
id: "price_starter",
active: true,
type: 1,
billingPeriod: 3,
billingCadence: "monthly",
contractMonths: 1,
requiredPaymentMethod: "any",
lagoPlanCode: "starter",
currency: "eur",
price: 199,
trialDays: 0,
},
],
};
const pro = {
...starter,
id: "product_pro",
code: "pro",
lagoPlanCode: "pro",
title: "billing:plans.pro.title",
order: 2,
prices: [
{
...starter.prices[0],
id: "price_pro",
lagoPlanCode: "pro",
price: 499,
},
],
};
const business = {
...starter,
id: "product_business",
code: "business",
lagoPlanCode: "business",
title: "billing:plans.business.title",
order: 3,
prices: [
{
...starter.prices[0],
id: "price_business",
lagoPlanCode: "business",
price: 999,
},
],
};
const emailMarketingS = {
...starter,
id: "product_email_s",
code: "email_marketing_s",
lagoPlanCode: "email_marketing_s",
kind: "recurring_add_on",
title: "E-Mail-Marketing S",
order: 200,
prices: [{
id: "price_email_s",
active: true,
type: 1,
billingPeriod: 3,
billingCadence: "monthly",
contractMonths: 1,
requiredPaymentMethod: "any",
lagoPlanCode: "email_marketing_s",
lagoFeeCode: "email_marketing_s",
currency: "eur",
price: 59,
trialDays: 0,
}],
};
describe("self-service subscription server model", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getAllSubscriptionProducts.mockResolvedValue([starter, pro, business]);
mocks.getTenantSeatCounts.mockResolvedValue({ office: 1, field: 1 });
mocks.getTenantSubscription.mockResolvedValue(null);
mocks.resolveTenantStorageUsage.mockResolvedValue({ available: false, reason: "subscription_missing" });
mocks.resolveEmailMarketingQuotaUsage.mockResolvedValue({ available: false, reason: "plan_required" });
mocks.resolveTenantBillingState.mockResolvedValue({
tenantId: "tenant_1",
status: "trial",
readOnly: false,
planCode: null,
seatQuantity: 1,
lagoCustomerId: null,
mollieCustomerId: null,
lastInvoiceExternalId: null,
lastPaymentExternalId: null,
trialStartsAt: null,
trialEndsAt: null,
pastDueSince: null,
frozenAt: null,
cancelledAt: null,
currentPeriodStart: null,
currentPeriodEnd: null,
entitlements: [],
});
});
it("recalculates the canonical current recurring gross total for payment policy checks", async () => {
const catalog = await loadSelfServiceSubscriptionCatalog();
expect(
resolveCurrentRecurringGrossTotalCents({
catalog,
tenantSubscription: null,
currentSelection: {
planId: "product_starter",
planCode: "starter",
priceId: "price_starter",
seatQuantity: 7,
officeSeatQuantity: 2,
fieldSeatQuantity: 5,
storageAddOnCodes: [],
},
})
).toBe(23_681);
expect(resolveCurrentRecurringGrossTotalCents({ catalog, tenantSubscription: null, currentSelection: null })).toBeNull();
expect(
resolveCurrentRecurringGrossTotalCents({
catalog,
tenantSubscription: null,
currentSelection: {
planId: "product_starter",
planCode: "starter",
priceId: "forged-price",
seatQuantity: 7,
officeSeatQuantity: 2,
fieldSeatQuantity: 5,
storageAddOnCodes: [],
},
})
).toBeNull();
});
it("includes active recurring add-ons while allowing a replaced product family to be excluded", async () => {
const catalog = await loadSelfServiceSubscriptionCatalog();
const currentSelection = {
planId: "product_starter",
planCode: "starter",
priceId: "price_starter",
seatQuantity: 7,
officeSeatQuantity: 2,
fieldSeatQuantity: 5,
storageAddOnCodes: [],
};
const tenantSubscription = {
products: [
{
cancelledAt: null,
endsAt: null,
subscriptionProduct: { code: "customer_portal_monthly", kind: "recurring_add_on" },
prices: [{ isMetered: false, quantity: 1, subscriptionPrice: { price: 24.99, currency: "EUR" } }],
},
{
cancelledAt: null,
endsAt: null,
subscriptionProduct: { code: "email_marketing_s", kind: "recurring_add_on" },
prices: [{ isMetered: false, quantity: 1, subscriptionPrice: { price: 59, currency: "EUR" } }],
},
],
} as never;
expect(resolveCurrentRecurringGrossTotalCents({ catalog, tenantSubscription, currentSelection })).toBe(33_676);
expect(resolveCurrentRecurringGrossTotalCents({ catalog, tenantSubscription, currentSelection }, { excludedProductCodes: ["email_marketing_s"] })).toBe(
26_655
);
expect(resolveOtherActiveRecurringGrossTotalCents(tenantSubscription)).toBe(9_995);
expect(resolveOtherActiveRecurringGrossTotalCents(tenantSubscription, { excludedProductCodes: ["email_marketing_s"] })).toBe(2_974);
});
it("publishes only database-backed recurring prices in integer cents", async () => {
const catalog = await loadSelfServiceSubscriptionCatalog();
expect(mocks.getAllSubscriptionProducts).toHaveBeenCalledWith(true);
expect(catalog.plans).toEqual([
expect.objectContaining({
id: "product_starter",
code: "starter",
titleKey: "settings.subscription.checkout.plans.packages.starter.title",
features: [],
packageTerms: expect.objectContaining({
officeSeatsIncluded: 2,
fieldSeatsIncluded: 5,
storageIncludedGb: 100,
storagePerAdditionalSeatGb: 10,
}),
prices: [expect.objectContaining({ id: "price_starter", unitAmountCents: 19_900, currency: "EUR", trialDays: 0 })],
}),
expect.objectContaining({
id: "product_pro",
code: "pro",
titleKey: "settings.subscription.checkout.plans.packages.team.title",
features: [],
packageTerms: expect.objectContaining({
officeSeatsIncluded: 5,
fieldSeatsIncluded: 15,
storageIncludedGb: 500,
storagePerAdditionalSeatGb: 20,
}),
prices: [expect.objectContaining({ id: "price_pro", unitAmountCents: 49_900, currency: "EUR", trialDays: 0 })],
}),
expect.objectContaining({
id: "product_business",
code: "business",
features: [],
packageTerms: expect.objectContaining({
officeSeatsIncluded: 10,
fieldSeatsIncluded: 30,
storageIncludedGb: 2_000,
storagePerAdditionalSeatGb: 40,
}),
prices: [expect.objectContaining({ id: "price_business", unitAmountCents: 99_900, currency: "EUR", trialDays: 0 })],
}),
]);
});
it("publishes monthly and annual variants only when each matches the commercial contract exactly", async () => {
mocks.getAllSubscriptionProducts.mockResolvedValueOnce([
{
...starter,
prices: [
starter.prices[0],
{
...starter.prices[0],
id: "price_starter_annual_sepa",
billingPeriod: 4,
billingCadence: "annual_sepa",
contractMonths: 12,
requiredPaymentMethod: "any",
lagoPlanCode: "starter_annual_sepa",
price: 179,
},
],
},
]);
await expect(loadSelfServiceSubscriptionCatalog()).resolves.toMatchObject({
plans: [
{
code: "starter",
prices: [
{ id: "price_starter", billingPeriod: 3, currency: "EUR", unitAmountCents: 19_900, trialDays: 0 },
{ id: "price_starter_annual_sepa", billingPeriod: 4, currency: "EUR", unitAmountCents: 17_900, trialDays: 0 },
],
},
],
});
});
it.each([
["amount", { price: 198.99 }],
["currency", { currency: "usd" }],
["billing period", { billingPeriod: 5 }],
["cadence", { billingCadence: "annual_sepa" }],
["inactive state", { active: false }],
["unsafe id", { id: " price_starter" }],
["variant code", { lagoPlanCode: "starter_drift" }],
["contract duration", { contractMonths: 12 }],
["payment policy", { requiredPaymentMethod: "sepa" }],
["trial", { trialDays: 14 }],
])("fails closed when the base-plan price drifts in %s", async (_label, drift) => {
mocks.getAllSubscriptionProducts.mockResolvedValueOnce([
{
...starter,
prices: [{ ...starter.prices[0], ...drift }],
},
]);
const catalog = await loadSelfServiceSubscriptionCatalog();
expect(catalog.plans).toEqual([]);
expect(resolveSelfServicePreferredSelection(catalog, "price_starter")).toBeNull();
});
it.each([
["inactive", { active: false }],
["private", { public: false }],
["wrong product kind", { kind: "recurring_add_on" }],
["unsafe product id", { id: "product starter" }],
["provider plan drift", { lagoPlanCode: "starter_drift" }],
])("fails closed for a %s base-plan product", async (_label, drift) => {
mocks.getAllSubscriptionProducts.mockResolvedValueOnce([{ ...starter, ...drift }]);
await expect(loadSelfServiceSubscriptionCatalog()).resolves.toMatchObject({ plans: [] });
});
it("omits arbitrary public base products outside the canonical three-plan catalog", async () => {
mocks.getAllSubscriptionProducts.mockResolvedValue([
starter,
{
...starter,
id: "product_custom",
code: "custom_public_plan",
lagoPlanCode: "custom_public_plan",
kind: "base_plan",
title: "Custom public plan",
},
]);
await expect(loadSelfServiceSubscriptionCatalog()).resolves.toMatchObject({
plans: [{ id: "product_starter", code: "starter" }],
});
});
it("accepts only an exact public catalog price as a registration preference", async () => {
const catalog = await loadSelfServiceSubscriptionCatalog();
expect(resolveSelfServicePreferredSelection(catalog, "price_pro")).toEqual({
planId: "product_pro",
priceId: "price_pro",
});
expect(
resolveSelfServicePreferredSelection(catalog, "price_pro", {
officeSeatQuantity: 5,
fieldSeatQuantity: 15,
})
).toEqual({
planId: "product_pro",
priceId: "price_pro",
officeSeatQuantity: 5,
fieldSeatQuantity: 15,
});
expect(resolveSelfServicePreferredSelection(catalog, "forged_price")).toBeNull();
expect(resolveSelfServicePreferredSelection(catalog, null)).toBeNull();
});
it("keeps global catalog reads separate and binds tenant state reads to RLS", async () => {
await previewSelfServiceSubscription("tenant_1", {
productId: "product_starter",
priceId: "price_starter",
seatQuantity: 2,
});
expect(mocks.runWithRlsContext).toHaveBeenCalledWith({ tenantId: "tenant_1" }, expect.any(Function));
expect(mocks.getAllSubscriptionProducts).toHaveBeenCalledWith(true);
expect(mocks.getTenantSubscription).toHaveBeenCalledWith("tenant_1");
expect(mocks.getTenantSeatCounts).toHaveBeenCalledWith("tenant_1");
expect(mocks.resolveTenantBillingState).toHaveBeenCalledWith("tenant_1", expect.objectContaining({ now: expect.any(Date) }));
});
it("publishes only canonical email-marketing products with exact prices", async () => {
mocks.getAllSubscriptionProducts.mockResolvedValueOnce([
starter,
pro,
business,
emailMarketingS,
{ ...emailMarketingS, id: "product_email_m_drift", code: "email_marketing_m", prices: [{ ...emailMarketingS.prices[0], id: "bad", price: 148 }] },
]);
const context = await loadSelfServiceSubscriptionServerContext("tenant_1");
expect(context.emailMarketingAddOns).toEqual([
{
productId: "product_email_s",
priceId: "price_email_s",
code: "email_marketing_s",
title: "billing:selfServiceSubscription.emailMarketing.packages.s.title",
monthlyEmailLimit: 10_000,
amountCents: 5_900,
vatRateBasisPoints: 1_900,
vatAmountCents: 1_121,
grossAmountCents: 7_021,
currency: "EUR",
active: false,
},
]);
expect(context.catalog.plans.map((plan) => plan.code)).toEqual(["starter", "pro", "business"]);
expect(context.storageAddOns).toEqual([
{ code: "storage_500gb", title: "Cloud-Speicher Plus · 500 GB", storageGb: 500, amountCents: 699, currency: "EUR" },
{ code: "storage_1tb", title: "Cloud-Speicher Plus · 1 TB", storageGb: 1_000, amountCents: 1_299, currency: "EUR" },
{ code: "storage_5tb", title: "Cloud-Speicher Plus · 5 TB", storageGb: 5_000, amountCents: 6_099, currency: "EUR" },
]);
});
it.each([
["product provider plan", { ...emailMarketingS, lagoPlanCode: "email_marketing_legacy" }],
[
"price provider plan",
{ ...emailMarketingS, prices: [{ ...emailMarketingS.prices[0], lagoPlanCode: "email_marketing_legacy" }] },
],
[
"price provider fee",
{ ...emailMarketingS, prices: [{ ...emailMarketingS.prices[0], lagoFeeCode: "email_marketing_legacy" }] },
],
])("fails closed when an email-marketing %s drifts", async (_field, driftedProduct) => {
mocks.getAllSubscriptionProducts.mockResolvedValueOnce([starter, pro, business, driftedProduct]);
await expect(loadSelfServiceSubscriptionServerContext("tenant_1")).resolves.toMatchObject({
emailMarketingAddOns: [],
});
});
it("builds and validates the price preview entirely on the server", async () => {
const preview = await previewSelfServiceSubscription("tenant_1", {
productId: "product_starter",
priceId: "price_starter",
seatQuantity: 3,
});
expect(preview).toMatchObject({
changeKind: "new",
effectiveAt: "immediate",
recurringTotalCents: 19_900,
recurringNetTotalCents: 19_900,
vatRateBasisPoints: 1_900,
vatAmountCents: 3_781,
recurringGrossTotalCents: 23_681,
selectedSeatQuantity: 3,
trialDays: 0,
});
});
it("rejects seat reductions below the tenant's active users", async () => {
mocks.getTenantSeatCounts.mockResolvedValueOnce({ office: 2, field: 2 });
await expect(
previewSelfServiceSubscription("tenant_1", {
productId: "product_starter",
priceId: "price_starter",
seatQuantity: 3,
})
).rejects.toMatchObject<SelfServiceSubscriptionValidationError>({ code: "SEAT_QUANTITY_BELOW_USAGE" });
});
it("uses the current Lago-linked plan and defers downgrades to period end", async () => {
mocks.getTenantSubscription.mockResolvedValueOnce({
id: "subscription_1",
tenantId: "tenant_1",
planCode: "business",
seatQuantity: 4,
products: [
{
id: "tenant_product_business",
subscriptionProductId: "product_business",
lagoSubscriptionId: "lago_subscription_business",
billingProviderSubscriptionId: null,
planCode: "business",
seatQuantity: 4,
quantity: 4,
cancelledAt: null,
endsAt: null,
currentPeriodEnd: new Date("2026-08-15T00:00:00.000Z"),
subscriptionProduct: business,
prices: [],
},
],
});
const preview = await previewSelfServiceSubscription(
"tenant_1",
{ productId: "product_starter", priceId: "price_starter", seatQuantity: 4 },
new Date("2026-07-15T00:00:00.000Z")
);
expect(preview).toMatchObject({
changeKind: "downgrade",
effectiveAt: "period_end",
effectiveAtDate: "2026-08-15T00:00:00.000Z",
});
});
it("treats a providerless bootstrap assignment as a new immediate acquisition", async () => {
mocks.getTenantSubscription.mockResolvedValueOnce({
id: "subscription_1",
tenantId: "tenant_1",
status: "trial",
planCode: "starter",
seatQuantity: 2,
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: starter,
prices: [{ subscriptionPriceId: "price_starter", isMetered: false, subscriptionPrice: starter.prices[0] }],
},
],
});
const preview = await previewSelfServiceSubscription(
"tenant_1",
{ productId: "product_starter", priceId: "price_starter", seatQuantity: 2 },
new Date("2026-07-15T00:00:00.000Z")
);
expect(preview).toMatchObject({
changeKind: "new",
effectiveAt: "immediate",
effectiveAtDate: null,
recurringTotalCents: 19_900,
recurringNetTotalCents: 19_900,
vatRateBasisPoints: 1_900,
vatAmountCents: 3_781,
recurringGrossTotalCents: 23_681,
});
});
it("keeps provider-managed downgrades fail-closed when the period end is missing", async () => {
mocks.getTenantSubscription.mockResolvedValueOnce({
id: "subscription_1",
tenantId: "tenant_1",
planCode: "business",
seatQuantity: 4,
products: [
{
id: "tenant_product_business",
subscriptionProductId: "product_business",
lagoSubscriptionId: "lago_subscription_business",
billingProviderSubscriptionId: null,
planCode: "business",
seatQuantity: 4,
quantity: 4,
cancelledAt: null,
endsAt: null,
currentPeriodEnd: null,
subscriptionProduct: business,
prices: [],
},
],
});
await expect(
previewSelfServiceSubscription(
"tenant_1",
{ productId: "product_starter", priceId: "price_starter", seatQuantity: 4 },
new Date("2026-07-15T00:00:00.000Z")
)
).rejects.toMatchObject<SelfServiceSubscriptionValidationError>({ code: "CURRENT_PERIOD_END_MISSING" });
});
it("allows a storage-only top-up without requiring an unrelated plan or seat change", async () => {
mocks.getTenantSubscription.mockResolvedValueOnce({
id: "subscription_1",
tenantId: "tenant_1",
planCode: "starter",
seatQuantity: 2,
officeSeatQuantity: 1,
fieldSeatQuantity: 1,
storageAddOnCodes: [],
products: [
{
id: "tenant_product_starter",
subscriptionProductId: "product_starter",
lagoSubscriptionId: "lago_subscription_starter",
billingProviderSubscriptionId: null,
planCode: "starter",
seatQuantity: 2,
officeSeatQuantity: 1,
fieldSeatQuantity: 1,
storageAddOnCodes: [],
quantity: 2,
cancelledAt: null,
endsAt: null,
currentPeriodEnd: new Date("2026-08-15T00:00:00.000Z"),
subscriptionProduct: starter,
prices: [{ subscriptionPriceId: "price_starter", isMetered: false, subscriptionPrice: starter.prices[0] }],
},
],
});
const preview = await previewSelfServiceSubscription(
"tenant_1",
{
productId: "product_starter",
priceId: "price_starter",
officeSeatQuantity: 1,
fieldSeatQuantity: 1,
storageAddOnCodes: ["storage_500gb"],
},
new Date("2026-07-15T00:00:00.000Z")
);
expect(preview).toMatchObject({
changeKind: "configuration_increase",
effectiveAt: "immediate",
storageAmountCents: 699,
recurringNetTotalCents: 20_599,
includedStorageGb: 100,
additionalSeatStorageGb: 0,
addOnStorageGb: 500,
totalStorageGb: 600,
});
});
it("rejects a legacy storage package for new purchases but preserves it on an existing contract", async () => {
await expect(
previewSelfServiceSubscription("tenant_1", {
productId: "product_starter",
priceId: "price_starter",
officeSeatQuantity: 1,
fieldSeatQuantity: 1,
storageAddOnCodes: ["storage_100gb"],
})
).rejects.toMatchObject<SelfServiceSubscriptionValidationError>({ code: "PLAN_NOT_PURCHASABLE" });
mocks.getTenantSubscription.mockResolvedValueOnce({
id: "subscription_1",
tenantId: "tenant_1",
planCode: "starter",
seatQuantity: 2,
officeSeatQuantity: 1,
fieldSeatQuantity: 1,
storageAddOnCodes: ["storage_100gb"],
products: [
{
id: "tenant_product_starter",
subscriptionProductId: "product_starter",
lagoSubscriptionId: "lago_subscription_starter",
billingProviderSubscriptionId: null,
planCode: "starter",
seatQuantity: 2,
officeSeatQuantity: 1,
fieldSeatQuantity: 1,
storageAddOnCodes: ["storage_100gb"],
quantity: 2,
cancelledAt: null,
endsAt: null,
currentPeriodEnd: new Date("2026-08-15T00:00:00.000Z"),
subscriptionProduct: starter,
prices: [{ subscriptionPriceId: "price_starter", isMetered: false, subscriptionPrice: starter.prices[0] }],
},
],
});
await expect(
previewSelfServiceSubscription(
"tenant_1",
{
productId: "product_starter",
priceId: "price_starter",
officeSeatQuantity: 1,
fieldSeatQuantity: 1,
storageAddOnCodes: ["storage_100gb"],
},
new Date("2026-07-15T00:00:00.000Z")
)
).resolves.toMatchObject({
changeKind: "unchanged",
storageAmountCents: 125,
selectedStorageAddOnCodes: ["storage_100gb"],
addOnStorageGb: 100,
totalStorageGb: 200,
});
});
it("rejects product and price ids that are not in the public catalog", async () => {
await expect(previewSelfServiceSubscription("tenant_1", { productId: "private", priceId: "price_starter", seatQuantity: 2 })).rejects.toMatchObject({
code: "PLAN_NOT_PURCHASABLE",
});
await expect(previewSelfServiceSubscription("tenant_1", { productId: "product_starter", priceId: "forged", seatQuantity: 2 })).rejects.toMatchObject({
code: "PRICE_NOT_FOUND",
});
});
});