Refresh HiveGrid Cloud reference snapshot

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

No files matched your search

@@ -0,0 +1,56 @@
import fs from "node:fs";
import path from "node:path";
import { hiveGridBasePlans } from "@hivegrid/entitlements";
import { describe, expect, it } from "vitest";
type CommercialPlanLocale = {
pricing?: {
products?: Record<string, { title?: string }>;
};
settings?: {
subscription?: {
seats?: {
package?: Record<string, string>;
};
checkout?: {
plans?: {
packages?: Record<string, { title?: string }>;
};
};
};
};
};
const repositoryRoot = process.cwd();
const expectedNames = Object.fromEntries(hiveGridBasePlans.map((plan) => [plan.seatPackageId, plan.publicName]));
const expectedLegacyPricingNames = Object.fromEntries(hiveGridBasePlans.map((plan, index) => [`plan${index + 1}`, plan.publicName]));
function readLocale(locale: "de" | "en"): CommercialPlanLocale {
return JSON.parse(fs.readFileSync(path.join(repositoryRoot, `apps/web/public/locales/${locale}/translations.json`), "utf8")) as CommercialPlanLocale;
}
describe("commercial billing plan names", () => {
it.each(["de", "en"] as const)("%s keeps seat usage and checkout labels aligned with the commercial catalog", (locale) => {
const translations = readLocale(locale);
const subscription = translations.settings?.subscription;
const seatPackageNames = subscription?.seats?.package;
const checkoutPackageNames = Object.fromEntries(
Object.entries(subscription?.checkout?.plans?.packages ?? {}).map(([packageId, copy]) => [packageId, copy.title])
);
const legacyPricingNames = Object.fromEntries(Object.entries(translations.pricing?.products ?? {}).map(([planId, copy]) => [planId, copy.title]));
expect(seatPackageNames).toEqual(expectedNames);
expect(checkoutPackageNames).toEqual(expectedNames);
expect(legacyPricingNames).toEqual(expectedLegacyPricingNames);
});
it("keeps the stable middle-tier provider mapping customer-facing as Swarm", () => {
const middleTier = hiveGridBasePlans.find((plan) => plan.technicalCode === "pro");
expect(middleTier).toMatchObject({
technicalCode: "pro",
seatPackageId: "team",
publicName: "Swarm",
});
});
});
@@ -31,7 +31,13 @@ function gateway(overrides: Partial<BillingGateway> = {}): BillingGateway {
getCustomer: vi.fn(),
createSubscription: vi.fn(),
getSubscription: vi.fn(),
terminateSubscription: vi.fn(),
listInvoices: vi.fn(async () => [invoice(), invoice({ providerInvoiceId: "foreign_invoice", externalCustomerId: "tenant_2" })]),
getInvoice: vi.fn(async (providerInvoiceId: string) =>
providerInvoiceId === "invoice_1"
? invoice()
: invoice({ providerInvoiceId, externalCustomerId: "tenant_2" })
),
downloadInvoice: vi.fn(async () => invoice()),
...overrides,
} as BillingGateway;
@@ -54,11 +60,32 @@ describe("customer billing invoices", () => {
downloadHref: "/acme/settings/subscription/invoices/invoice_1/download",
},
]);
expect(deps.gateway.listInvoices).toHaveBeenCalledWith({ tenantId: "tenant_1", perPage: 50 });
expect(deps.gateway.listInvoices).toHaveBeenCalledWith({ tenantId: "tenant_1", page: 1, perPage: 50 });
});
it("returns an empty customer invoice list when Lago is not configured", async () => {
await expect(listCustomerBillingInvoices({ tenantId: "tenant_1", tenantSlug: "acme" }, { gateway: null })).resolves.toEqual([]);
it("surfaces a configuration error instead of pretending that the invoice list is empty", async () => {
await expect(listCustomerBillingInvoices({ tenantId: "tenant_1", tenantSlug: "acme" }, { gateway: null })).rejects.toMatchObject({
name: "CustomerBillingInvoiceError",
code: "CONFIGURATION_MISSING",
});
});
it("loads invoice history beyond the first provider page without duplicating invoices", async () => {
const firstPage = Array.from({ length: 50 }, (_, index) =>
invoice({ providerInvoiceId: `invoice_${index + 1}`, number: `LAG-${String(index + 1).padStart(3, "0")}` })
);
const listInvoices = vi.fn(async ({ page }: { page?: number }) =>
page === 1 ? firstPage : page === 2 ? [invoice({ providerInvoiceId: "invoice_51", number: "LAG-051" })] : []
);
const invoices = await listCustomerBillingInvoices(
{ tenantId: "tenant_1", tenantSlug: "acme" },
{ gateway: gateway({ listInvoices: listInvoices as BillingGateway["listInvoices"] }) }
);
expect(invoices).toHaveLength(51);
expect(invoices.at(-1)).toMatchObject({ id: "invoice_51", number: "LAG-051" });
expect(listInvoices).toHaveBeenNthCalledWith(2, { tenantId: "tenant_1", page: 2, perPage: 50 });
});
it("keeps voided invoices visible but not downloadable", async () => {
@@ -76,7 +103,7 @@ describe("customer billing invoices", () => {
await expect(getCustomerBillingInvoiceDownloadUrl({ tenantId: "tenant_1", invoiceId: "invoice_1" }, deps)).resolves.toBe(
"https://files.example.test/invoice_1.pdf"
);
expect(deps.gateway.listInvoices).toHaveBeenCalledWith({ tenantId: "tenant_1", perPage: 50 });
expect(deps.gateway.getInvoice).toHaveBeenCalledWith("invoice_1");
expect(deps.gateway.downloadInvoice).toHaveBeenCalledWith("invoice_1");
});
@@ -96,7 +123,7 @@ describe("customer billing invoices", () => {
await expect(
getCustomerBillingInvoiceDownloadUrl(
{ tenantId: "tenant_1", invoiceId: "foreign_invoice" },
{ gateway: gateway({ downloadInvoice: vi.fn(async () => invoice({ providerInvoiceId: "foreign_invoice", externalCustomerId: "tenant_2" })) }) }
{ gateway: gateway() }
)
).rejects.toMatchObject({ name: "CustomerBillingInvoiceError", code: "INVOICE_NOT_FOUND" });
});
@@ -107,7 +134,7 @@ describe("customer billing invoices", () => {
{ tenantId: "tenant_1", invoiceId: "invoice_1" },
{
gateway: gateway({
listInvoices: vi.fn(async () => [invoice({ fileUrl: null })]),
getInvoice: vi.fn(async () => invoice({ fileUrl: null })),
downloadInvoice: vi.fn(async () => invoice({ fileUrl: null })),
}),
}
@@ -18,6 +18,9 @@ type CustomerInvoiceDeps = {
loadGateway?: () => BillingGateway | null;
};
const CUSTOMER_INVOICE_PAGE_SIZE = 50;
const CUSTOMER_INVOICE_MAX_PAGES = 100;
export type CustomerBillingInvoiceDownloadTarget = {
fileUrl: string;
filename: string;
@@ -77,11 +80,23 @@ function toServerReachableLagoFileUrl(fileUrl: string): string {
export async function listCustomerBillingInvoices(input: { tenantId: string; tenantSlug: string }, deps: CustomerInvoiceDeps = {}): Promise<CustomerBillingInvoiceDto[]> {
const gateway = resolveGateway(deps);
if (!gateway) return [];
const invoices = await gateway.listInvoices({ tenantId: input.tenantId, perPage: 50 });
return invoices
.filter((invoice) => invoice.externalCustomerId === input.tenantId)
.map((invoice) => toCustomerInvoice(invoice, input.tenantSlug));
if (!gateway) throw new CustomerBillingInvoiceError("CONFIGURATION_MISSING");
const ownedInvoices: BillingGatewayInvoice[] = [];
const seenInvoiceIds = new Set<string>();
for (let page = 1; page <= CUSTOMER_INVOICE_MAX_PAGES; page += 1) {
const invoices = await gateway.listInvoices({ tenantId: input.tenantId, page, perPage: CUSTOMER_INVOICE_PAGE_SIZE });
let addedInvoice = false;
for (const invoice of invoices) {
if (invoice.externalCustomerId !== input.tenantId || seenInvoiceIds.has(invoice.providerInvoiceId)) continue;
seenInvoiceIds.add(invoice.providerInvoiceId);
ownedInvoices.push(invoice);
addedInvoice = true;
}
if (invoices.length < CUSTOMER_INVOICE_PAGE_SIZE || !addedInvoice) break;
}
return ownedInvoices.map((invoice) => toCustomerInvoice(invoice, input.tenantSlug));
}
export async function getCustomerBillingInvoiceDownloadUrl(
@@ -98,10 +113,8 @@ export async function getCustomerBillingInvoiceDownloadTarget(
const gateway = resolveGateway(deps);
if (!gateway) throw new CustomerBillingInvoiceError("CONFIGURATION_MISSING");
const ownedInvoice = (await gateway.listInvoices({ tenantId: input.tenantId, perPage: 50 })).find(
(invoice) => invoice.providerInvoiceId === input.invoiceId && invoice.externalCustomerId === input.tenantId
);
if (!ownedInvoice) {
const ownedInvoice = await gateway.getInvoice(input.invoiceId);
if (!ownedInvoice || ownedInvoice.externalCustomerId !== input.tenantId) {
throw new CustomerBillingInvoiceError("INVOICE_NOT_FOUND");
}
@@ -0,0 +1,131 @@
import { describe, expect, it, vi } from "vitest";
import {
assertEmailMarketingQuotaReservation,
EmailMarketingQuotaError,
resolveEmailMarketingQuotaUsage,
} from "./email-marketing-quota.server";
const now = new Date("2026-07-30T12:00:00.000Z");
function subscription(overrides: Record<string, unknown> = {}) {
return {
tenantId: "tenant_1",
status: "active",
planCode: "starter",
seatQuantity: 2,
lagoCustomerId: "lago_1",
mollieCustomerId: "mollie_1",
lastInvoiceExternalId: null,
lastPaymentExternalId: null,
trialStartsAt: null,
trialEndsAt: null,
pastDueSince: null,
frozenAt: null,
cancelledAt: null,
products: [
{
createdAt: new Date("2026-07-01T00:00:00.000Z"),
cancelledAt: null,
endsAt: null,
currentPeriodStart: new Date("2026-07-15T00:00:00.000Z"),
currentPeriodEnd: new Date("2026-08-15T00:00:00.000Z"),
planCode: "starter",
seatQuantity: 2,
subscriptionProduct: {
id: "base",
code: "starter",
lagoPlanCode: "starter",
kind: "base_plan",
features: [],
},
},
{
createdAt: new Date("2026-07-01T00:00:00.000Z"),
cancelledAt: null,
endsAt: null,
currentPeriodStart: new Date("2026-07-15T00:00:00.000Z"),
currentPeriodEnd: new Date("2026-08-15T00:00:00.000Z"),
planCode: "email_marketing_s",
seatQuantity: 1,
subscriptionProduct: {
id: "email_s",
code: "email_marketing_s",
lagoPlanCode: "email_marketing_s",
kind: "recurring_add_on",
features: [
{
title: "Email marketing",
name: "email-marketing",
code: null,
type: 2,
value: 10_000,
quotaValue: null,
accumulate: true,
},
],
},
},
],
...overrides,
};
}
function tx(row = subscription(), used = 0n) {
return {
$executeRaw: vi.fn().mockResolvedValue(1),
$queryRaw: vi.fn().mockResolvedValue([{ used }]),
tenantSubscription: { findUnique: vi.fn().mockResolvedValue(row) },
};
}
describe("email-marketing quota reservation", () => {
it("counts the active billing period under a tenant advisory lock", async () => {
const client = tx(subscription(), 9_900n);
await expect(assertEmailMarketingQuotaReservation(client as never, "tenant_1", 100, now)).resolves.toEqual({
periodStart: new Date("2026-07-15T00:00:00.000Z"),
periodEnd: new Date("2026-08-15T00:00:00.000Z"),
limit: 10_000,
used: 9_900,
requested: 100,
});
expect(client.$executeRaw).toHaveBeenCalledOnce();
expect(client.$queryRaw).toHaveBeenCalledOnce();
});
it("rejects a campaign that would exceed the paid tier", async () => {
const client = tx(subscription(), 9_901n);
await expect(assertEmailMarketingQuotaReservation(client as never, "tenant_1", 100, now)).rejects.toMatchObject<
EmailMarketingQuotaError
>({ code: "EMAIL_MARKETING_QUOTA_EXCEEDED" });
});
it("projects the current period usage without taking the reservation lock", async () => {
const client = tx(subscription(), 4_200n);
await expect(resolveEmailMarketingQuotaUsage(client as never, "tenant_1", now)).resolves.toEqual({
available: true,
periodStart: new Date("2026-07-15T00:00:00.000Z"),
periodEnd: new Date("2026-08-15T00:00:00.000Z"),
limit: 10_000,
used: 4_200,
remaining: 5_800,
});
expect(client.$executeRaw).not.toHaveBeenCalled();
});
it("fails closed for frozen billing and missing add-ons", async () => {
await expect(
assertEmailMarketingQuotaReservation(
tx(subscription({ status: "frozen", frozenAt: now })) as never,
"tenant_1",
1,
now
)
).rejects.toMatchObject<EmailMarketingQuotaError>({ code: "EMAIL_MARKETING_PLAN_REQUIRED" });
await expect(
assertEmailMarketingQuotaReservation(tx(subscription({ products: [subscription().products[0]] })) as never, "tenant_1", 1, now)
).rejects.toMatchObject<EmailMarketingQuotaError>({ code: "EMAIL_MARKETING_PLAN_REQUIRED" });
});
});
@@ -0,0 +1,120 @@
import { resolveTenantBillingState, type TenantBillingStateClient } from "@hivegrid/db/billing-domain.server";
import { entitlementLimitTypes, featureKeys } from "@hivegrid/entitlements";
import type { TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
export class EmailMarketingQuotaError extends Error {
override readonly name = "EmailMarketingQuotaError";
constructor(readonly code: "EMAIL_MARKETING_PLAN_REQUIRED" | "EMAIL_MARKETING_QUOTA_EXCEEDED") {
super(code);
}
}
export type EmailMarketingQuotaReservation = {
readonly periodStart: Date;
readonly periodEnd: Date;
readonly limit: number | null;
readonly used: number;
readonly requested: number;
};
export type EmailMarketingQuotaUsage =
| {
readonly available: true;
readonly periodStart: Date;
readonly periodEnd: Date;
readonly limit: number | null;
readonly used: number;
readonly remaining: number | null;
}
| {
readonly available: false;
readonly reason: "billing_read_only" | "plan_required" | "limit_invalid";
};
function utcCalendarMonth(now: Date): { periodStart: Date; periodEnd: Date } {
return {
periodStart: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)),
periodEnd: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)),
};
}
function activeBillingPeriod(
now: Date,
currentPeriodStart: Date | null,
currentPeriodEnd: Date | null
): { periodStart: Date; periodEnd: Date } {
if (currentPeriodStart && currentPeriodEnd && currentPeriodStart <= now && currentPeriodEnd > now) {
return { periodStart: currentPeriodStart, periodEnd: currentPeriodEnd };
}
return utcCalendarMonth(now);
}
export async function assertEmailMarketingQuotaReservation(
tx: TenantRlsClient,
tenantId: string,
requested: number,
now: Date = new Date()
): Promise<EmailMarketingQuotaReservation> {
if (!Number.isSafeInteger(requested) || requested < 0) {
throw new EmailMarketingQuotaError("EMAIL_MARKETING_QUOTA_EXCEEDED");
}
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${tenantId}, 26027))`;
const usage = await resolveEmailMarketingQuotaUsage(tx, tenantId, now);
if (!usage.available) throw new EmailMarketingQuotaError("EMAIL_MARKETING_PLAN_REQUIRED");
if (usage.limit !== null && usage.used + requested > usage.limit) {
throw new EmailMarketingQuotaError("EMAIL_MARKETING_QUOTA_EXCEEDED");
}
return {
periodStart: usage.periodStart,
periodEnd: usage.periodEnd,
limit: usage.limit,
used: usage.used,
requested,
};
}
export async function resolveEmailMarketingQuotaUsage(
tx: TenantRlsClient,
tenantId: string,
now: Date = new Date()
): Promise<EmailMarketingQuotaUsage> {
const billing = await resolveTenantBillingState(tenantId, {
client: tx as unknown as TenantBillingStateClient,
now,
});
const entitlement = billing.entitlements.find((candidate) => candidate.featureKey === featureKeys.emailMarketing);
if (billing.readOnly) return { available: false, reason: "billing_read_only" };
if (!entitlement?.enabled) return { available: false, reason: "plan_required" };
const { periodStart, periodEnd } = activeBillingPeriod(now, billing.currentPeriodStart, billing.currentPeriodEnd);
const unlimited = entitlement.limitType === entitlementLimitTypes.unlimited;
if (!unlimited && (entitlement.limitType !== entitlementLimitTypes.monthly || !Number.isSafeInteger(entitlement.limit) || entitlement.limit <= 0)) {
return { available: false, reason: "limit_invalid" };
}
const rows = await tx.$queryRaw<Array<{ used: bigint }>>`
SELECT count(*)::bigint AS "used"
FROM "OutboundEmail"
WHERE "tenantId" = ${tenantId}
AND COALESCE("isPreview", false) = false
AND "sentAt" >= ${periodStart}
AND "sentAt" < ${periodEnd}
`;
const used = Number(rows[0]?.used ?? 0n);
if (!Number.isSafeInteger(used) || used < 0) {
throw new EmailMarketingQuotaError("EMAIL_MARKETING_QUOTA_EXCEEDED");
}
const limit = unlimited ? null : entitlement.limit!;
return {
periodStart,
periodEnd,
limit,
used,
remaining: limit === null ? null : Math.max(0, limit - used),
available: true,
};
}
@@ -0,0 +1,109 @@
// @vitest-environment node
import { describe, expect, test, vi } from "vitest";
import {
createBoundedInvoiceDownloadBody,
fetchInvoiceDownloadFile,
} from "./invoice-download-fetch.server";
describe("invoice download fetch boundary", () => {
test("uses a direct manual-redirect fetch only for the configured provider origin", async () => {
const fetchImpl = vi.fn(async () => new Response("pdf"));
const outboundFetch = vi.fn();
await fetchInvoiceDownloadFile(
"http://lago.internal.test/rails/active_storage/invoice.pdf",
{ trustedProviderOrigin: "http://lago.internal.test/api/v1" },
{ fetchImpl: fetchImpl as typeof fetch, outboundFetch },
);
expect(fetchImpl).toHaveBeenCalledWith(
new URL("http://lago.internal.test/rails/active_storage/invoice.pdf"),
expect.objectContaining({ redirect: "manual", signal: expect.any(AbortSignal) }),
);
expect(outboundFetch).not.toHaveBeenCalled();
});
test("follows a same-origin Active-Storage redirect on the trusted origin", async () => {
const fetchImpl = vi
.fn(async () => new Response("pdf"))
.mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: "/rails/active_storage/disk/abc/invoice.pdf" } }));
const outboundFetch = vi.fn();
const response = await fetchInvoiceDownloadFile(
"http://lago.internal.test/rails/active_storage/blobs/redirect/xyz/invoice.pdf",
{ trustedProviderOrigin: "http://lago.internal.test" },
{ fetchImpl: fetchImpl as typeof fetch, outboundFetch },
);
expect(await response.text()).toBe("pdf");
expect(fetchImpl).toHaveBeenCalledTimes(2);
expect(fetchImpl).toHaveBeenLastCalledWith(new URL("http://lago.internal.test/rails/active_storage/disk/abc/invoice.pdf"), expect.anything());
expect(outboundFetch).not.toHaveBeenCalled();
});
test("hands an off-origin redirect target to the SSRF-safe outbound client", async () => {
const fetchImpl = vi.fn(async () =>
new Response(null, { status: 302, headers: { location: "https://objects.example.test/signed/invoice.pdf?sig=1" } }),
);
const outboundFetch = vi.fn(async () => new Response("pdf"));
const response = await fetchInvoiceDownloadFile(
"http://lago.internal.test/rails/active_storage/blobs/redirect/xyz/invoice.pdf",
{ trustedProviderOrigin: "http://lago.internal.test" },
{ fetchImpl: fetchImpl as typeof fetch, outboundFetch },
);
expect(await response.text()).toBe("pdf");
expect(fetchImpl).toHaveBeenCalledTimes(1);
expect(outboundFetch).toHaveBeenCalledWith(
"https://objects.example.test/signed/invoice.pdf?sig=1",
expect.objectContaining({ headers: expect.any(Object) }),
{ timeoutMs: 10_000 },
);
});
test("stops after the trusted redirect limit instead of looping", async () => {
const fetchImpl = vi.fn(async () => new Response(null, { status: 302, headers: { location: "/rails/active_storage/loop.pdf" } }));
await expect(
fetchInvoiceDownloadFile(
"http://lago.internal.test/rails/active_storage/loop.pdf",
{ trustedProviderOrigin: "http://lago.internal.test" },
{ fetchImpl: fetchImpl as typeof fetch, outboundFetch: vi.fn() },
),
).rejects.toThrow("redirect limit");
});
test("routes any other origin through the SSRF-safe outbound client", async () => {
const fetchImpl = vi.fn();
const outboundFetch = vi.fn(async () => new Response("pdf"));
await fetchInvoiceDownloadFile(
"https://objects.example.test/invoice.pdf",
{ trustedProviderOrigin: "https://lago.example.test" },
{ fetchImpl: fetchImpl as typeof fetch, outboundFetch },
);
expect(fetchImpl).not.toHaveBeenCalled();
expect(outboundFetch).toHaveBeenCalledWith(
"https://objects.example.test/invoice.pdf",
expect.objectContaining({ headers: expect.any(Object) }),
{ timeoutMs: 10_000 },
);
});
test("rejects private network targets outside the configured provider origin", async () => {
await expect(fetchInvoiceDownloadFile("http://127.0.0.1:3000/private")).rejects.toMatchObject({
name: "OutboundHttpUrlValidationError",
});
});
test("bounds both declared and actual streamed response bytes", async () => {
const declaredTooLarge = new Response(new Uint8Array([1]), { headers: { "content-length": "4" } });
expect(() => createBoundedInvoiceDownloadBody(declaredTooLarge, 3)).toThrow("size limit");
const understated = new Response(new Uint8Array([1, 2, 3, 4]), { headers: { "content-length": "2" } });
const body = createBoundedInvoiceDownloadBody(understated, 3);
await expect(new Response(body).arrayBuffer()).rejects.toThrow("size limit");
});
});
@@ -0,0 +1,103 @@
import { fetchOutboundHttpWithRedirects } from "~/utils/outboundHttp.server";
export const INVOICE_DOWNLOAD_MAX_BYTES = 25 * 1024 * 1024;
export const INVOICE_DOWNLOAD_TIMEOUT_MS = 10_000;
export const INVOICE_DOWNLOAD_TRUSTED_REDIRECT_LIMIT = 3;
const INVOICE_DOWNLOAD_ACCEPT = "application/pdf,application/octet-stream;q=0.9";
type InvoiceDownloadFetchDeps = {
fetchImpl?: typeof fetch;
outboundFetch?: typeof fetchOutboundHttpWithRedirects;
};
/**
* Fetch an invoice file. URLs on the trusted provider origin (Lago) are fetched
* directly — Lago answers Active-Storage blob URLs with a redirect (same-origin
* hop for local disk storage, presigned object-storage URL for S3), so trusted
* hops are followed manually and any off-origin hop is handed to the SSRF-safe
* outbound client, which validates the target as a public host.
*/
export async function fetchInvoiceDownloadFile(
fileUrl: string,
options: { trustedProviderOrigin?: string | null } = {},
deps: InvoiceDownloadFetchDeps = {},
): Promise<Response> {
const trustedOrigin = normalizeOrigin(options.trustedProviderOrigin);
let url = new URL(fileUrl);
for (let hop = 0; hop <= INVOICE_DOWNLOAD_TRUSTED_REDIRECT_LIMIT; hop += 1) {
if (!trustedOrigin || url.origin !== trustedOrigin) {
return await (deps.outboundFetch ?? fetchOutboundHttpWithRedirects)(
url.toString(),
{ headers: { accept: INVOICE_DOWNLOAD_ACCEPT } },
{ timeoutMs: INVOICE_DOWNLOAD_TIMEOUT_MS },
);
}
const response = await (deps.fetchImpl ?? fetch)(url, {
headers: { accept: INVOICE_DOWNLOAD_ACCEPT },
redirect: "manual",
signal: AbortSignal.timeout(INVOICE_DOWNLOAD_TIMEOUT_MS),
});
const location = response.status >= 300 && response.status < 400 ? response.headers.get("location") : null;
if (!location) {
return response;
}
void response.body?.cancel().catch(() => undefined);
url = new URL(location, url);
}
throw new Error("Invoice download exceeded the redirect limit.");
}
export function createBoundedInvoiceDownloadBody(
response: Response,
maxBytes = INVOICE_DOWNLOAD_MAX_BYTES,
): ReadableStream<Uint8Array> | null {
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
throw new TypeError("Invoice download limit must be a positive safe integer.");
}
const contentLength = response.headers.get("content-length");
if (contentLength && /^\d+$/u.test(contentLength) && Number(contentLength) > maxBytes) {
void response.body?.cancel().catch(() => undefined);
throw new Error("Invoice download exceeds the configured size limit.");
}
if (!response.body) return null;
const reader = response.body.getReader();
let bytesRead = 0;
return new ReadableStream<Uint8Array>({
async pull(controller) {
try {
const chunk = await reader.read();
if (chunk.done) {
controller.close();
return;
}
bytesRead += chunk.value.byteLength;
if (bytesRead > maxBytes) {
await reader.cancel().catch(() => undefined);
controller.error(new Error("Invoice download exceeds the configured size limit."));
return;
}
controller.enqueue(chunk.value);
} catch (error) {
controller.error(error);
}
},
async cancel(reason) {
await reader.cancel(reason).catch(() => undefined);
},
});
}
function normalizeOrigin(value: string | null | undefined): string | null {
if (!value) return null;
try {
return new URL(value).origin;
} catch {
return null;
}
}
@@ -0,0 +1,165 @@
// @vitest-environment node
import { describe, expect, it, vi } from "vitest";
import type { CustomerPaymentGateway, MolliePaymentMethodId } from "@hivegrid/billing";
import {
assertCheckoutPaymentMethodAvailable,
CheckoutPaymentMethodError,
loadCheckoutPaymentMethods,
toMollieLocale,
} from "./payment-methods.server";
function gateway(methods: Array<{ id: MolliePaymentMethodId; description: string }>): CustomerPaymentGateway {
return {
createCustomer: vi.fn(),
createPayment: vi.fn(),
getPayment: vi.fn(),
findCustomerPaymentByExternalId: vi.fn(),
listPaymentMethods: vi.fn(async () => methods.map((method) => ({ provider: "mollie" as const, ...method }))),
};
}
const input = {
amountCents: 12_900,
currency: "EUR",
sequenceType: "first" as const,
locale: "de",
};
describe("checkout payment methods", () => {
it("maps app locales to supported Mollie locales", () => {
expect(toMollieLocale("de-DE")).toBe("de_DE");
expect(toMollieLocale("en")).toBe("en_GB");
expect(toMollieLocale("pl-PL")).toBe("pl_PL");
expect(toMollieLocale("hu-HU")).toBe("hu_HU");
expect(toMollieLocale("ru-RU")).toBeNull();
expect(toMollieLocale("uk-UA")).toBeNull();
});
it("builds a provider-backed choice list and falls back when discovery fails", async () => {
const provider = gateway([
{ id: "ideal", description: "iDEAL" },
{ id: "creditcard", description: "Credit card" },
]);
await expect(loadCheckoutPaymentMethods(input, { gateway: provider })).resolves.toEqual({
status: "ready",
methods: [
{ id: "ideal", label: "iDEAL" },
{ id: "creditcard", label: "Credit card" },
],
});
expect(provider.listPaymentMethods).toHaveBeenCalledWith({
amountCents: 12_900,
currency: "EUR",
sequenceType: "first",
locale: "de_DE",
});
const unavailable = gateway([]);
unavailable.listPaymentMethods = vi.fn(async () => {
throw new Error("provider unavailable");
});
await expect(loadCheckoutPaymentMethods(input, { gateway: unavailable })).resolves.toEqual({ status: "fallback", methods: [] });
});
it("accepts only a currently available provider method", async () => {
const provider = gateway([{ id: "paypal", description: "PayPal" }]);
await expect(assertCheckoutPaymentMethodAvailable(" PAYPAL ", input, { gateway: provider })).resolves.toBe("paypal");
await expect(assertCheckoutPaymentMethodAvailable("ideal", input, { gateway: provider })).rejects.toEqual(
new CheckoutPaymentMethodError("PAYMENT_METHOD_UNAVAILABLE")
);
await expect(assertCheckoutPaymentMethodAvailable(null, input, { gateway: provider })).resolves.toBeNull();
});
it("filters annual SEPA authorization methods before returning or accepting them", async () => {
const provider = gateway([
{ id: "ideal", description: "iDEAL" },
{ id: "creditcard", description: "Credit card" },
]);
const annualInput = { ...input, requirement: "sepa" as const };
await expect(loadCheckoutPaymentMethods(annualInput, { gateway: provider })).resolves.toEqual({
status: "ready",
methods: [{ id: "ideal", label: "iDEAL" }],
});
await expect(assertCheckoutPaymentMethodAvailable("creditcard", annualInput, { gateway: provider })).rejects.toMatchObject({
code: "PAYMENT_METHOD_UNAVAILABLE",
});
});
it("requires an available credit card above EUR 1,000 and selects it server-side", async () => {
const provider = gateway([
{ id: "ideal", description: "iDEAL" },
{ id: "creditcard", description: "Credit card" },
]);
const highValueInput = { ...input, amountCents: 100_001, requirement: "sepa" as const };
await expect(loadCheckoutPaymentMethods(highValueInput, { gateway: provider })).resolves.toEqual({
status: "ready",
methods: [{ id: "creditcard", label: "Credit card" }],
});
await expect(assertCheckoutPaymentMethodAvailable(null, highValueInput, { gateway: provider })).resolves.toBe("creditcard");
const cardUnavailable = gateway([{ id: "ideal", description: "iDEAL" }]);
await expect(loadCheckoutPaymentMethods(highValueInput, { gateway: cardUnavailable })).resolves.toEqual({
status: "required_card_unavailable",
methods: [],
});
await expect(assertCheckoutPaymentMethodAvailable(null, highValueInput, { gateway: cardUnavailable })).rejects.toMatchObject({
code: "PAYMENT_METHOD_UNAVAILABLE",
});
});
it("keeps SEPA available at exactly EUR 1,000", async () => {
const provider = gateway([
{ id: "ideal", description: "iDEAL" },
{ id: "creditcard", description: "Credit card" },
]);
await expect(loadCheckoutPaymentMethods({ ...input, amountCents: 100_000, requirement: "sepa" }, { gateway: provider })).resolves.toEqual({
status: "ready",
methods: [{ id: "ideal", label: "iDEAL" }],
});
});
it("uses the future recurring amount for a zero-value mandate payment", async () => {
const provider = gateway([
{ id: "ideal", description: "iDEAL" },
{ id: "creditcard", description: "Credit card" },
]);
await expect(
loadCheckoutPaymentMethods({ ...input, amountCents: 0, policyAmountCents: 100_001, requirement: "sepa" }, { gateway: provider })
).resolves.toEqual({
status: "ready",
methods: [{ id: "creditcard", label: "Credit card" }],
});
expect(provider.listPaymentMethods).toHaveBeenCalledWith({
amountCents: 0,
currency: "EUR",
sequenceType: "first",
locale: "de_DE",
});
});
it("requires a card for every zero-value first payment even below the high-value threshold", async () => {
const provider = gateway([
{ id: "ideal", description: "iDEAL" },
{ id: "creditcard", description: "Credit card" },
]);
const zeroValueInput = { ...input, amountCents: 0, policyAmountCents: 12_900, requirement: "any" as const };
await expect(loadCheckoutPaymentMethods(zeroValueInput, { gateway: provider })).resolves.toEqual({
status: "ready",
methods: [{ id: "creditcard", label: "Credit card" }],
});
await expect(assertCheckoutPaymentMethodAvailable(null, zeroValueInput, { gateway: provider })).resolves.toBe("creditcard");
const idealOnly = gateway([{ id: "ideal", description: "iDEAL" }]);
await expect(loadCheckoutPaymentMethods(zeroValueInput, { gateway: idealOnly })).resolves.toEqual({
status: "required_card_unavailable",
methods: [],
});
await expect(assertCheckoutPaymentMethodAvailable(null, zeroValueInput, { gateway: idealOnly })).rejects.toMatchObject({
code: "PAYMENT_METHOD_UNAVAILABLE",
});
});
});
@@ -0,0 +1,128 @@
import {
createMolliePaymentGateway,
mollieSepaFirstPaymentMethods,
resolveMollieCheckoutPaymentMethodRequirement,
type CustomerPaymentGateway,
type MollieCheckoutPaymentMethodRequirement,
type MollieLocale,
type MolliePaymentMethodId,
type PaymentGatewayListMethodsInput,
} from "@hivegrid/billing";
import { loadWebConfig } from "@hivegrid/config";
import { buildSelfServiceCheckoutPaymentMethodsVM, type SelfServiceCheckoutPaymentMethodsVM } from "@hivegrid/view-models";
export type CheckoutPaymentMethodRequirement = MollieCheckoutPaymentMethodRequirement;
export type CheckoutPaymentMethodsInput = {
readonly amountCents: number;
/** Future recurring charge used for mandate policy when the first payment is zero. */
readonly policyAmountCents?: number;
readonly currency: string;
readonly sequenceType: PaymentGatewayListMethodsInput["sequenceType"];
readonly locale: string;
readonly requirement?: CheckoutPaymentMethodRequirement;
};
export class CheckoutPaymentMethodError extends Error {
override readonly name = "CheckoutPaymentMethodError";
constructor(readonly code: "PAYMENT_METHOD_INVALID" | "PAYMENT_METHOD_UNAVAILABLE") {
super(code);
}
}
function configuredGateway(): CustomerPaymentGateway | null {
const config = loadWebConfig().config.mollie;
if (!config.apiKey) return null;
return createMolliePaymentGateway({
apiKey: config.apiKey,
profileId: config.profileId,
timeoutMs: config.timeoutMs,
});
}
export function toMollieLocale(locale: string): MollieLocale | null {
const language = locale.trim().toLowerCase().split(/[-_]/u)[0];
if (language === "de") return "de_DE";
if (language === "en") return "en_GB";
if (language === "hu") return "hu_HU";
if (language === "pl") return "pl_PL";
return null;
}
function filterMethods(methods: Awaited<ReturnType<CustomerPaymentGateway["listPaymentMethods"]>>, requirement: CheckoutPaymentMethodRequirement) {
if (requirement === "any") return methods;
const allowed = new Set<string>(requirement === "card" ? ["creditcard"] : mollieSepaFirstPaymentMethods);
return methods.filter((method) => allowed.has(method.id));
}
function effectiveRequirement(input: CheckoutPaymentMethodsInput): CheckoutPaymentMethodRequirement {
// Mollie only supports a zero-value first payment for mandate-capable card
// checkouts in our enabled method set. iDEAL and the other SEPA setup methods
// require a positive amount, so never let the hosted fallback accept them for
// a trial or deferred change.
if (input.sequenceType === "first" && input.amountCents === 0) return "card";
try {
return resolveMollieCheckoutPaymentMethodRequirement({
amountCents: input.policyAmountCents ?? input.amountCents,
currency: input.currency,
configuredRequirement: input.requirement ?? "any",
});
} catch {
throw new CheckoutPaymentMethodError("PAYMENT_METHOD_INVALID");
}
}
function methodQuery(input: CheckoutPaymentMethodsInput): PaymentGatewayListMethodsInput {
if (!Number.isSafeInteger(input.amountCents) || input.amountCents < 0) {
throw new CheckoutPaymentMethodError("PAYMENT_METHOD_INVALID");
}
return {
amountCents: input.amountCents,
currency: input.currency,
sequenceType: input.sequenceType,
locale: toMollieLocale(input.locale),
};
}
export async function loadCheckoutPaymentMethods(
input: CheckoutPaymentMethodsInput,
deps: { readonly gateway?: CustomerPaymentGateway | null } = {}
): Promise<SelfServiceCheckoutPaymentMethodsVM> {
const gateway = "gateway" in deps ? deps.gateway : configuredGateway();
const requirement = effectiveRequirement(input);
if (!gateway) return buildSelfServiceCheckoutPaymentMethodsVM(null, requirement === "card" ? "card" : undefined);
try {
const methods = filterMethods(await gateway.listPaymentMethods(methodQuery(input)), requirement);
return buildSelfServiceCheckoutPaymentMethodsVM(
methods.map((method) => ({ id: method.id, label: method.description })),
requirement === "card" ? "card" : undefined
);
} catch (error) {
if (error instanceof CheckoutPaymentMethodError) throw error;
return buildSelfServiceCheckoutPaymentMethodsVM(null, requirement === "card" ? "card" : undefined);
}
}
export async function assertCheckoutPaymentMethodAvailable(
method: string | null | undefined,
input: CheckoutPaymentMethodsInput,
deps: { readonly gateway?: CustomerPaymentGateway | null } = {}
): Promise<MolliePaymentMethodId | null> {
const normalized = method?.trim().toLowerCase() ?? "";
const requirement = effectiveRequirement(input);
if (!normalized && requirement !== "card") return null;
const gateway = "gateway" in deps ? deps.gateway : configuredGateway();
if (!gateway) throw new CheckoutPaymentMethodError("PAYMENT_METHOD_UNAVAILABLE");
let methods: Awaited<ReturnType<CustomerPaymentGateway["listPaymentMethods"]>>;
try {
methods = filterMethods(await gateway.listPaymentMethods(methodQuery(input)), requirement);
} catch (error) {
if (error instanceof CheckoutPaymentMethodError) throw error;
throw new CheckoutPaymentMethodError("PAYMENT_METHOD_UNAVAILABLE");
}
const available = methods.find((candidate) => candidate.id === (normalized || "creditcard"));
if (!available) throw new CheckoutPaymentMethodError("PAYMENT_METHOD_UNAVAILABLE");
return available.id;
}
@@ -0,0 +1,204 @@
import { describe, expect, it, vi } from "vitest";
import {
reserveRecurringProductCheckoutLedgerWithClient,
type RecurringCheckoutPolicyClient,
} from "./recurring-checkout-policy.server";
const NOW = new Date("2026-08-03T05:00:00.000Z");
function activeSubscription() {
return {
id: "subscription_1",
tenantId: "tenant_1",
status: "active",
frozenAt: null,
cancelledAt: null,
planCode: "pro",
officeSeatQuantity: 5,
fieldSeatQuantity: 15,
billingCadence: "monthly",
storageAddOnCodes: [],
products: [
{
id: "base_1",
subscriptionProductId: "product_team",
planCode: "pro",
officeSeatQuantity: 5,
fieldSeatQuantity: 15,
billingCadence: "monthly",
storageAddOnCodes: [],
cancelledAt: null,
currentPeriodStart: new Date("2026-08-01T00:00:00.000Z"),
endsAt: null,
subscriptionProduct: { kind: "base_plan", code: "pro" },
prices: [],
},
{
id: "existing_addon_1",
subscriptionProductId: "product_existing",
planCode: "existing_addon",
officeSeatQuantity: null,
fieldSeatQuantity: null,
billingCadence: "monthly",
storageAddOnCodes: [],
cancelledAt: null,
currentPeriodStart: new Date("2026-08-01T00:00:00.000Z"),
endsAt: null,
subscriptionProduct: { kind: "recurring_add_on", code: "existing_addon" },
prices: [
{
isMetered: false,
quantity: 1,
subscriptionPrice: { price: "173.27", currency: "EUR" },
},
],
},
],
};
}
function acquisitionInput(productId: string, priceId: string) {
return {
tenantId: "tenant_1",
tenantName: "ACME",
userId: "user_1",
userEmail: "admin@example.test",
userName: "Admin",
productId,
priceId,
scopeKey: "tenant",
redirectUrl: "https://app.example.test/return",
webhookUrl: "https://api.example.test/webhook",
paymentMethod: "ideal",
};
}
describe("tenant-wide recurring checkout policy", () => {
it("makes a parallel second add-on include the first durable reservation before enforcing the EUR 1,000 card limit", async () => {
const openAcquisitions: Array<{
id: string;
status: "pending";
subscriptionProductId: string;
scopeKey: string;
amountCents: number;
currency: string;
reservationExpiresAt: Date;
productCode: string;
}> = [];
const selectedNetCents = new Map([
["product_plus_100", 10_000],
["product_plus_150", 15_000],
]);
const client = {
$queryRaw: vi.fn(async (query: TemplateStringsArray, ...values: unknown[]) => {
const sql = query.join("");
if (sql.includes("pg_advisory_xact_lock")) return [{ lock: "" }];
if (sql.includes('FROM "CheckoutSessionStatus"')) return [];
if (sql.includes('FROM "TenantProductAcquisition"')) return [...openAcquisitions];
if (sql.includes('FROM "SubscriptionProduct" product')) {
const productId = String(values[0]);
const netAmountCents = selectedNetCents.get(productId);
return netAmountCents
? [{
productId,
priceId: String(values[1]),
productCode: productId,
kind: "recurring_add_on",
productActive: true,
productPublic: true,
hasQuantity: false,
priceActive: true,
priceType: 1,
price: (netAmountCents / 100).toFixed(2),
currency: "EUR",
}]
: [];
}
return [];
}),
tenantSubscription: {
findUnique: vi.fn(async () => activeSubscription()),
},
} as unknown as RecurringCheckoutPolicyClient;
const observedPolicyAmounts: number[] = [];
const reserveLedger = vi.fn(async (input) => {
observedPolicyAmounts.push(input.paymentPolicyAmountCents!);
const amountCents = input.productId === "product_plus_100" ? 11_900 : 17_850;
openAcquisitions.push({
id: `reservation_${openAcquisitions.length + 1}`,
status: "pending",
subscriptionProductId: input.productId,
scopeKey: input.scopeKey,
amountCents,
currency: "EUR",
reservationExpiresAt: new Date(NOW.getTime() + 15 * 60 * 1000),
productCode: input.productId,
});
return {
id: openAcquisitions.at(-1)!.id,
status: "pending",
productKind: "recurring_add_on",
scopeKey: input.scopeKey,
checkoutUrl: null,
providerPaymentId: null,
replayed: false,
} as const;
});
const first = await reserveRecurringProductCheckoutLedgerWithClient(
client,
acquisitionInput("product_plus_100", "price_plus_100"),
{},
{ reserveLedger, now: () => NOW },
);
const second = await reserveRecurringProductCheckoutLedgerWithClient(
client,
acquisitionInput("product_plus_150", "price_plus_150"),
{},
{ reserveLedger, now: () => NOW },
);
expect(first.paymentPolicyAmountCents).toBe(91_900);
expect(second.paymentPolicyAmountCents).toBe(109_750);
expect(observedPolicyAmounts).toEqual([91_900, 109_750]);
expect(String(client.$queryRaw.mock.calls[0]?.[0])).toContain("pg_advisory_xact_lock");
expect(String(client.$queryRaw.mock.calls[4]?.[0])).toContain("pg_advisory_xact_lock");
});
it("fails closed while a base-plan checkout owns the tenant policy", async () => {
const client = {
$queryRaw: vi.fn(async (query: TemplateStringsArray) => {
const sql = query.join("");
if (sql.includes("pg_advisory_xact_lock")) return [{ lock: "" }];
if (sql.includes('FROM "SubscriptionProduct" product')) {
return [{
productId: "product_plus_100",
priceId: "price_plus_100",
productCode: "product_plus_100",
kind: "recurring_add_on",
productActive: true,
productPublic: true,
hasQuantity: false,
priceActive: true,
priceType: 1,
price: "100.00",
currency: "EUR",
}];
}
if (sql.includes('FROM "CheckoutSessionStatus"')) return [{ id: "base_checkout_open" }];
return [];
}),
tenantSubscription: { findUnique: vi.fn(async () => activeSubscription()) },
} as unknown as RecurringCheckoutPolicyClient;
const reserveLedger = vi.fn();
await expect(reserveRecurringProductCheckoutLedgerWithClient(
client,
acquisitionInput("product_plus_100", "price_plus_100"),
{},
{ reserveLedger, now: () => NOW },
)).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" });
expect(reserveLedger).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,399 @@
import {
billingCadences,
calculateBillingCatalogPrice,
calculateHiveGridGrossAmountCents,
} from "@hivegrid/entitlements";
import {
getTenantSubscription,
type TenantSubscriptionReaderClient,
type TenantSubscriptionWithDetails,
} from "@hivegrid/db/subscriptions.server";
import {
ProductAcquisitionError,
reserveProductAcquisitionLedger,
type CreateProductAcquisitionInput,
type ProductAcquisitionClient,
type ProductAcquisitionResult,
} from "./product-acquisition.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
export const BASE_CHECKOUT_SCOPE_PREFIX = "base_checkout:v1:" as const;
type QueryClient = {
$queryRaw<T = unknown>(query: TemplateStringsArray, ...values: unknown[]): Promise<T>;
};
export type RecurringCheckoutPolicyClient = QueryClient & ProductAcquisitionClient;
type OpenRecurringAcquisition = {
readonly id: string;
readonly status: "pending" | "provider_pending" | "payment_pending";
readonly subscriptionProductId: string;
readonly scopeKey: string;
readonly amountCents: number | null;
readonly currency: string | null;
readonly reservationExpiresAt: Date | null;
readonly productCode: string | null;
};
type SelectedRecurringProduct = {
readonly productId: string;
readonly priceId: string;
readonly productCode: string | null;
readonly kind: string;
readonly productActive: boolean;
readonly productPublic: boolean;
readonly hasQuantity: boolean;
readonly priceActive: boolean;
readonly priceType: number;
readonly price: number | string | { toString(): string };
readonly currency: string;
};
type WithTenantPolicyClient = <T>(
tenantId: string,
operation: (client: RecurringCheckoutPolicyClient) => Promise<T>,
) => Promise<T>;
export type RecurringCheckoutReplacement = {
/** Base plan checkouts replace the current base price instead of adding to it. */
readonly replacesBasePlan?: boolean;
/** Product families such as e-mail tiers replace an active/open sibling tier. */
readonly replacedProductCodes?: readonly string[];
};
export type ReservedRecurringProductCheckout = {
readonly reservation: ProductAcquisitionResult;
readonly paymentPolicyAmountCents: number;
};
type ReservePolicyDependencies = {
readonly withTenant?: WithTenantPolicyClient;
readonly reserveLedger?: typeof reserveProductAcquisitionLedger;
readonly now?: () => Date;
};
function failClosed(): never {
throw new ProductAcquisitionError("PAYMENT_METHOD_UNAVAILABLE");
}
function safeAdd(...amounts: readonly number[]): number {
let total = 0;
for (const amount of amounts) {
if (!Number.isSafeInteger(amount) || amount < 0 || !Number.isSafeInteger(total + amount)) failClosed();
total += amount;
}
return total;
}
function activeAt(
product: TenantSubscriptionWithDetails["products"][number],
now: Date,
): boolean {
return !product.cancelledAt
&& (!product.currentPeriodStart || product.currentPeriodStart <= now)
&& (!product.endsAt || product.endsAt > now);
}
function fixedRecurringGrossAmountCents(
product: TenantSubscriptionWithDetails["products"][number],
): number {
const fixedPrices = product.prices.filter((candidate) => !candidate.isMetered && candidate.subscriptionPrice);
if (fixedPrices.length !== 1) failClosed();
const fixed = fixedPrices[0]!;
const currency = fixed.subscriptionPrice!.currency.trim().toUpperCase();
const quantity = fixed.quantity;
const numericPrice = Number(fixed.subscriptionPrice!.price);
const unitNetAmountCents = Math.round(numericPrice * 100);
if (
currency !== "EUR"
|| !Number.isSafeInteger(quantity)
|| quantity < 1
|| !Number.isFinite(numericPrice)
|| numericPrice < 0
|| !Number.isSafeInteger(unitNetAmountCents)
|| Math.abs(numericPrice * 100 - unitNetAmountCents) > 0.000_001
) {
failClosed();
}
const netAmountCents = unitNetAmountCents * quantity;
if (!Number.isSafeInteger(netAmountCents)) failClosed();
return calculateHiveGridGrossAmountCents(netAmountCents);
}
function currentBaseGrossAmountCents(
subscription: TenantSubscriptionWithDetails,
now: Date,
): number {
const activeBaseProducts = subscription.products.filter(
(product) => product.subscriptionProduct.kind === "base_plan" && activeAt(product, now),
);
const matchingBaseProducts = activeBaseProducts.filter((product) => {
const subscriptionPlanCode = subscription.planCode?.trim() ?? "";
return Boolean(
subscriptionPlanCode
&& (product.planCode?.trim() === subscriptionPlanCode || product.subscriptionProduct.code?.trim() === subscriptionPlanCode),
);
});
const baseProduct = matchingBaseProducts.length === 1
? matchingBaseProducts[0]
: activeBaseProducts.length === 1
? activeBaseProducts[0]
: null;
if (!baseProduct) failClosed();
const planCode = baseProduct.subscriptionProduct.code?.trim()
|| baseProduct.planCode?.trim()
|| subscription.planCode?.trim()
|| "";
const billingCadence = baseProduct.billingCadence?.trim() || subscription.billingCadence?.trim();
const cadence = billingCadence === billingCadences.monthly
? billingCadences.monthly
: billingCadence === billingCadences.annualSepa
? billingCadences.annualSepa
: null;
if (!planCode || !cadence) failClosed();
const officeSeatQuantity = baseProduct.officeSeatQuantity ?? subscription.officeSeatQuantity;
const fieldSeatQuantity = baseProduct.fieldSeatQuantity ?? subscription.fieldSeatQuantity;
if (
!Number.isSafeInteger(officeSeatQuantity)
|| officeSeatQuantity < 0
|| !Number.isSafeInteger(fieldSeatQuantity)
|| fieldSeatQuantity < 0
) {
failClosed();
}
const storageAddOnCodes = [...new Set([
...(baseProduct.storageAddOnCodes ?? subscription.storageAddOnCodes ?? []),
...subscription.products
.filter(
(product) => product.subscriptionProduct.kind === "recurring_add_on"
&& product.subscriptionProduct.code?.startsWith("storage_")
&& activeAt(product, now),
)
.map((product) => product.subscriptionProduct.code!),
])].sort();
try {
return calculateBillingCatalogPrice({
planCode,
cadence,
officeSeatQuantity,
fieldSeatQuantity,
storageAddOnCodes,
}).recurringGrossAmountCents;
} catch {
failClosed();
}
}
function currentOtherRecurringGrossAmountCents(
subscription: TenantSubscriptionWithDetails,
now: Date,
replacedProductCodes: ReadonlySet<string>,
): number {
let total = 0;
for (const product of subscription.products) {
const code = product.subscriptionProduct.code?.trim() ?? "";
if (
product.subscriptionProduct.kind !== "recurring_add_on"
|| code.startsWith("storage_")
|| replacedProductCodes.has(code)
|| !activeAt(product, now)
) {
continue;
}
total = safeAdd(total, fixedRecurringGrossAmountCents(product));
}
return total;
}
async function loadOpenRecurringAcquisitions(
client: QueryClient,
tenantId: string,
): Promise<readonly OpenRecurringAcquisition[]> {
return client.$queryRaw<OpenRecurringAcquisition[]>`
SELECT
acquisition."id",
acquisition."status"::text AS "status",
acquisition."subscriptionProductId",
acquisition."scopeKey",
acquisition."amountCents",
acquisition."currency",
acquisition."reservationExpiresAt",
product."code" AS "productCode"
FROM "TenantProductAcquisition" acquisition
INNER JOIN "SubscriptionProduct" product ON product."id" = acquisition."subscriptionProductId"
WHERE acquisition."tenantId" = ${tenantId}
AND acquisition."productKind"::text = 'recurring_add_on'
AND acquisition."status"::text IN ('pending', 'provider_pending', 'payment_pending')
`;
}
async function assertNoOpenBaseCheckout(client: QueryClient, tenantId: string): Promise<void> {
const rows = await client.$queryRaw<Array<{ readonly id: string }>>`
SELECT "id"
FROM "CheckoutSessionStatus"
WHERE "tenantId" = ${tenantId}
AND "productKind" = 'base_plan'
AND "scopeKey" LIKE ${`${BASE_CHECKOUT_SCOPE_PREFIX}%`}
AND "pending" = TRUE
AND "status" NOT IN ('canceled', 'failed', 'expired')
LIMIT 1
`;
if (rows.length > 0) throw new ProductAcquisitionError("IDEMPOTENCY_CONFLICT");
}
async function selectedRecurringGrossAmountCents(
client: QueryClient,
input: Pick<CreateProductAcquisitionInput, "productId" | "priceId" | "quantity">,
): Promise<number> {
const rows = await client.$queryRaw<SelectedRecurringProduct[]>`
SELECT
product."id" AS "productId",
price."id" AS "priceId",
product."code" AS "productCode",
product."kind"::text AS "kind",
product."active" AS "productActive",
product."public" AS "productPublic",
product."hasQuantity",
price."active" AS "priceActive",
price."type" AS "priceType",
price."price",
price."currency"
FROM "SubscriptionProduct" product
INNER JOIN "SubscriptionPrice" price ON price."subscriptionProductId" = product."id"
WHERE product."id" = ${input.productId}
AND price."id" = ${input.priceId}
`;
if (rows.length !== 1) failClosed();
const selected = rows[0]!;
const quantity = input.quantity ?? 1;
const numericPrice = Number(selected.price);
const unitNetAmountCents = Math.round(numericPrice * 100);
if (
selected.kind !== "recurring_add_on"
|| !selected.productActive
|| !selected.productPublic
|| !selected.priceActive
|| selected.priceType !== 1
|| selected.currency.trim().toUpperCase() !== "EUR"
|| !Number.isSafeInteger(quantity)
|| quantity < 1
|| (!selected.hasQuantity && quantity !== 1)
|| !Number.isFinite(numericPrice)
|| numericPrice <= 0
|| !Number.isSafeInteger(unitNetAmountCents)
|| Math.abs(numericPrice * 100 - unitNetAmountCents) > 0.000_001
) {
failClosed();
}
const netAmountCents = unitNetAmountCents * quantity;
if (!Number.isSafeInteger(netAmountCents)) failClosed();
return calculateHiveGridGrossAmountCents(netAmountCents);
}
export async function acquireTenantRecurringCheckoutPolicyLock(
client: QueryClient,
tenantId: string,
): Promise<void> {
await client.$queryRaw`
SELECT pg_catalog.pg_advisory_xact_lock(
pg_catalog.hashtextextended('recurring-checkout-policy:' || ${tenantId}, 26030)
)::text AS "lock"
`;
}
export async function resolveLockedRecurringCheckoutPolicyAmount(
client: QueryClient,
input: {
readonly tenantId: string;
readonly now: Date;
readonly selectedRecurringGrossAmountCents: number;
readonly targetProductId?: string;
readonly targetScopeKey?: string;
readonly replacement?: RecurringCheckoutReplacement;
readonly allowOpenBaseCheckout?: boolean;
},
): Promise<number> {
if (!input.allowOpenBaseCheckout) await assertNoOpenBaseCheckout(client, input.tenantId);
const subscription = await getTenantSubscription(
input.tenantId,
client as unknown as TenantSubscriptionReaderClient,
);
const activeSubscription = Boolean(
subscription
&& subscription.status === "active"
&& subscription.frozenAt === null
&& subscription.cancelledAt === null,
);
if (!activeSubscription && !input.replacement?.replacesBasePlan) {
throw new ProductAcquisitionError("BASE_SUBSCRIPTION_REQUIRED");
}
const replacedProductCodes = new Set(input.replacement?.replacedProductCodes ?? []);
let total = activeSubscription && !input.replacement?.replacesBasePlan
? currentBaseGrossAmountCents(subscription!, input.now)
: 0;
if (activeSubscription) {
total = safeAdd(total, currentOtherRecurringGrossAmountCents(subscription!, input.now, replacedProductCodes));
}
const openAcquisitions = await loadOpenRecurringAcquisitions(client, input.tenantId);
for (const acquisition of openAcquisitions) {
const reservationExpiresAt = acquisition.reservationExpiresAt;
if (!reservationExpiresAt) failClosed();
if (reservationExpiresAt <= input.now) {
if (acquisition.status === "pending") continue;
failClosed();
}
const productCode = acquisition.productCode?.trim() ?? "";
const exactTarget = acquisition.subscriptionProductId === input.targetProductId
&& acquisition.scopeKey === input.targetScopeKey;
if (!exactTarget && replacedProductCodes.has(productCode)) {
throw new ProductAcquisitionError("IDEMPOTENCY_CONFLICT");
}
if (exactTarget) continue;
if (
acquisition.currency?.trim().toUpperCase() !== "EUR"
|| !Number.isSafeInteger(acquisition.amountCents)
|| (acquisition.amountCents ?? 0) <= 0
) {
failClosed();
}
total = safeAdd(total, acquisition.amountCents!);
}
return safeAdd(total, input.selectedRecurringGrossAmountCents);
}
export async function reserveRecurringProductCheckoutLedgerWithClient(
client: RecurringCheckoutPolicyClient,
input: CreateProductAcquisitionInput,
replacement: RecurringCheckoutReplacement = {},
dependencies: Pick<ReservePolicyDependencies, "reserveLedger" | "now"> = {},
): Promise<ReservedRecurringProductCheckout> {
const now = dependencies.now?.() ?? new Date();
await acquireTenantRecurringCheckoutPolicyLock(client, input.tenantId);
const selectedGrossAmountCents = await selectedRecurringGrossAmountCents(client, input);
const paymentPolicyAmountCents = await resolveLockedRecurringCheckoutPolicyAmount(client, {
tenantId: input.tenantId,
now,
selectedRecurringGrossAmountCents: selectedGrossAmountCents,
targetProductId: input.productId,
targetScopeKey: input.scopeKey,
replacement,
});
const lockedInput = { ...input, paymentPolicyAmountCents };
const reservation = await (dependencies.reserveLedger ?? reserveProductAcquisitionLedger)(lockedInput, { client });
return { reservation, paymentPolicyAmountCents };
}
export async function reserveRecurringProductCheckoutLedger(
input: CreateProductAcquisitionInput,
replacement: RecurringCheckoutReplacement = {},
dependencies: ReservePolicyDependencies = {},
): Promise<ReservedRecurringProductCheckout> {
const withTenant = dependencies.withTenant
?? (<T>(tenantId: string, operation: (client: RecurringCheckoutPolicyClient) => Promise<T>) =>
withTenantRLS(tenantId, (tx) => operation(tx as unknown as RecurringCheckoutPolicyClient)));
return withTenant(input.tenantId, (client) =>
reserveRecurringProductCheckoutLedgerWithClient(client, input, replacement, dependencies));
}
@@ -0,0 +1,113 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CatalogError } from "@hivegrid/foundation";
const mocks = vi.hoisted(() => {
const tenantProductConfiguration = {
findUnique: vi.fn(),
upsert: vi.fn(),
};
return {
tenantProductConfiguration,
};
});
vi.mock("~/utils/db.server", () => ({
db: {
tenantProductConfiguration: mocks.tenantProductConfiguration,
},
}));
import {
loadTenantRegistrationBillingPreference,
persistTenantRegistrationBillingPreferenceWithTx,
tenantRegistrationBillingPreferenceMatchesWithTx,
} from "./registration-billing-preference.server";
const preference = {
tenantId: "tenant-1",
selectedSubscriptionPriceId: "price_swarm_monthly",
selectedOfficeSeatQuantity: 5,
selectedFieldSeatQuantity: 15,
};
describe("tenant registration billing preference", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("loads only a complete bounded preference", async () => {
mocks.tenantProductConfiguration.findUnique.mockResolvedValueOnce({
signupSubscriptionPriceId: "price_swarm_monthly",
signupOfficeSeatQuantity: 5,
signupFieldSeatQuantity: 15,
});
await expect(loadTenantRegistrationBillingPreference("tenant-1")).resolves.toEqual({
selectedSubscriptionPriceId: "price_swarm_monthly",
selectedOfficeSeatQuantity: 5,
selectedFieldSeatQuantity: 15,
});
expect(mocks.tenantProductConfiguration.findUnique).toHaveBeenCalledWith({
where: { tenantId: "tenant-1" },
select: {
signupSubscriptionPriceId: true,
signupOfficeSeatQuantity: true,
signupFieldSeatQuantity: true,
},
});
});
it.each([
null,
{ signupSubscriptionPriceId: null, signupOfficeSeatQuantity: null, signupFieldSeatQuantity: null },
{ signupSubscriptionPriceId: "price", signupOfficeSeatQuantity: 0, signupFieldSeatQuantity: 1 },
{ signupSubscriptionPriceId: "price", signupOfficeSeatQuantity: 1, signupFieldSeatQuantity: null },
{ signupSubscriptionPriceId: "p".repeat(192), signupOfficeSeatQuantity: 1, signupFieldSeatQuantity: 0 },
])("ignores an absent, partial, or invalid stored preference", async (stored) => {
mocks.tenantProductConfiguration.findUnique.mockResolvedValueOnce(stored);
await expect(loadTenantRegistrationBillingPreference("tenant-1")).resolves.toBeNull();
});
it("upserts the validated preference through the caller's transaction", async () => {
const tx = { tenantProductConfiguration: mocks.tenantProductConfiguration };
await persistTenantRegistrationBillingPreferenceWithTx(tx as never, preference);
expect(mocks.tenantProductConfiguration.upsert).toHaveBeenCalledTimes(1);
expect(mocks.tenantProductConfiguration.upsert).toHaveBeenCalledWith({
where: { tenantId: "tenant-1" },
create: {
tenantId: "tenant-1",
signupSubscriptionPriceId: "price_swarm_monthly",
signupOfficeSeatQuantity: 5,
signupFieldSeatQuantity: 15,
},
update: {
signupSubscriptionPriceId: "price_swarm_monthly",
signupOfficeSeatQuantity: 5,
signupFieldSeatQuantity: 15,
},
});
});
it("matches only the exact complete preference during a signup replay", async () => {
const tx = { tenantProductConfiguration: mocks.tenantProductConfiguration };
mocks.tenantProductConfiguration.findUnique.mockResolvedValue({
signupSubscriptionPriceId: "price_swarm_monthly",
signupOfficeSeatQuantity: 5,
signupFieldSeatQuantity: 15,
});
await expect(tenantRegistrationBillingPreferenceMatchesWithTx(tx as never, preference)).resolves.toBe(true);
await expect(
tenantRegistrationBillingPreferenceMatchesWithTx(tx as never, { ...preference, selectedFieldSeatQuantity: 16 })
).resolves.toBe(false);
});
it("fails closed before writing malformed values", async () => {
const tx = { tenantProductConfiguration: mocks.tenantProductConfiguration };
await expect(
persistTenantRegistrationBillingPreferenceWithTx(tx as never, { ...preference, selectedOfficeSeatQuantity: 0 })
).rejects.toBeInstanceOf(CatalogError);
expect(mocks.tenantProductConfiguration.upsert).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,102 @@
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import type { TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { db } from "~/utils/db.server";
export type RegistrationBillingPreference = {
readonly selectedSubscriptionPriceId: string;
readonly selectedOfficeSeatQuantity: number;
readonly selectedFieldSeatQuantity: number;
};
type PersistRegistrationBillingPreferenceInput = RegistrationBillingPreference & {
readonly tenantId: string;
};
const preferenceSelect = {
signupSubscriptionPriceId: true,
signupOfficeSeatQuantity: true,
signupFieldSeatQuantity: true,
} as const;
export async function loadTenantRegistrationBillingPreference(tenantId: string): Promise<RegistrationBillingPreference | null> {
const configuration = await db.tenantProductConfiguration.findUnique({
where: { tenantId },
select: preferenceSelect,
});
return readCompletePreference(configuration);
}
/** Persists the validated signup choice inside the deterministic bootstrap transaction. */
export async function persistTenantRegistrationBillingPreferenceWithTx(
tx: Pick<TenantRlsClient, "tenantProductConfiguration">,
input: PersistRegistrationBillingPreferenceInput
): Promise<void> {
const preference = readCompletePreference({
signupSubscriptionPriceId: input.selectedSubscriptionPriceId,
signupOfficeSeatQuantity: input.selectedOfficeSeatQuantity,
signupFieldSeatQuantity: input.selectedFieldSeatQuantity,
});
if (!preference || !input.tenantId.trim()) {
throw new CatalogError(foundationErrors.idempotencyConflict);
}
await tx.tenantProductConfiguration.upsert({
where: { tenantId: input.tenantId },
create: {
tenantId: input.tenantId,
signupSubscriptionPriceId: preference.selectedSubscriptionPriceId,
signupOfficeSeatQuantity: preference.selectedOfficeSeatQuantity,
signupFieldSeatQuantity: preference.selectedFieldSeatQuantity,
},
update: {
signupSubscriptionPriceId: preference.selectedSubscriptionPriceId,
signupOfficeSeatQuantity: preference.selectedOfficeSeatQuantity,
signupFieldSeatQuantity: preference.selectedFieldSeatQuantity,
},
});
}
export async function tenantRegistrationBillingPreferenceMatchesWithTx(
tx: Pick<TenantRlsClient, "tenantProductConfiguration">,
input: PersistRegistrationBillingPreferenceInput
): Promise<boolean> {
const stored = await tx.tenantProductConfiguration.findUnique({
where: { tenantId: input.tenantId },
select: preferenceSelect,
});
const preference = readCompletePreference(stored);
return (
preference?.selectedSubscriptionPriceId === input.selectedSubscriptionPriceId &&
preference.selectedOfficeSeatQuantity === input.selectedOfficeSeatQuantity &&
preference.selectedFieldSeatQuantity === input.selectedFieldSeatQuantity
);
}
function readCompletePreference(
input: {
readonly signupSubscriptionPriceId: string | null;
readonly signupOfficeSeatQuantity: number | null;
readonly signupFieldSeatQuantity: number | null;
} | null
): RegistrationBillingPreference | null {
const priceId = input?.signupSubscriptionPriceId?.trim() ?? "";
if (
!input ||
!priceId ||
priceId.length > 191 ||
!Number.isSafeInteger(input.signupOfficeSeatQuantity) ||
!Number.isSafeInteger(input.signupFieldSeatQuantity) ||
input.signupOfficeSeatQuantity! < 1 ||
input.signupOfficeSeatQuantity! > 10_000 ||
input.signupFieldSeatQuantity! < 0 ||
input.signupFieldSeatQuantity! > 10_000
) {
return null;
}
return {
selectedSubscriptionPriceId: priceId,
selectedOfficeSeatQuantity: input.signupOfficeSeatQuantity!,
selectedFieldSeatQuantity: input.signupFieldSeatQuantity!,
};
}
@@ -0,0 +1,78 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadCatalog: vi.fn(),
}));
vi.mock("./self-service-subscription.server", () => ({
loadSelfServiceSubscriptionCatalog: (...args: unknown[]) => mocks.loadCatalog(...args),
}));
import { loadRegistrationPlanSelection, resolveRegistrationSubscriptionPrice } from "./registration-plan-selection.server";
const plans = [
{
id: "product_starter",
code: "starter",
titleKey: "Core",
descriptionKey: "Core plan",
prices: [
{ id: "price_starter_annual", billingPeriod: 4, currency: "EUR", unitAmountCents: 17_900, trialDays: 0 },
{ id: "price_starter", billingPeriod: 3, currency: "EUR", unitAmountCents: 19_900, trialDays: 0 },
],
},
{
id: "product_pro",
code: "pro",
titleKey: "Swarm",
descriptionKey: "Swarm plan",
prices: [{ id: "price_pro", billingPeriod: 3, currency: "EUR", unitAmountCents: 49_900, trialDays: 0 }],
},
];
describe("registration plan selection", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.loadCatalog.mockResolvedValue({ plans });
});
it("offers one canonical monthly registration choice per base plan", async () => {
await expect(loadRegistrationPlanSelection("pro")).resolves.toMatchObject({
selectedPriceId: "price_pro",
recommendedPriceId: "price_starter",
officeSeatQuantity: 1,
fieldSeatQuantity: 0,
plans: [
expect.objectContaining({ planCode: "starter", priceId: "price_starter", amountCents: 19_900, recommended: true }),
expect.objectContaining({ planCode: "pro", priceId: "price_pro", amountCents: 49_900, recommended: false }),
],
});
});
it("recommends and prices the cheapest complete configuration for the submitted team", async () => {
await expect(loadRegistrationPlanSelection(null, { officeSeatQuantity: 5, fieldSeatQuantity: 15 })).resolves.toMatchObject({
selectedPriceId: "price_pro",
recommendedPriceId: "price_pro",
officeSeatQuantity: 5,
fieldSeatQuantity: 15,
plans: [
expect.objectContaining({ planCode: "starter", amountCents: 62_600, extraOfficeSeatQuantity: 3, extraFieldSeatQuantity: 10 }),
expect.objectContaining({ planCode: "pro", amountCents: 49_900, recommended: true }),
],
});
});
it("accepts only an exact server-catalog price id", async () => {
await expect(resolveRegistrationSubscriptionPrice("price_pro")).resolves.toMatchObject({
planCode: "pro",
priceId: "price_pro",
});
await expect(resolveRegistrationSubscriptionPrice("forged_price")).resolves.toBeNull();
await expect(resolveRegistrationSubscriptionPrice(null)).resolves.toBeNull();
});
it("fails closed when the canonical catalog is unavailable", async () => {
mocks.loadCatalog.mockResolvedValue({ plans: [] });
await expect(loadRegistrationPlanSelection()).rejects.toThrow("No canonical registration plan is available");
});
});
@@ -0,0 +1,89 @@
import { loadSelfServiceSubscriptionCatalog } from "./self-service-subscription.server";
import { adviseRegistrationPlan, getBillingCatalogPlan } from "@hivegrid/entitlements";
export type RegistrationPlanOption = {
readonly planId: string;
readonly planCode: string;
readonly titleKey: string;
readonly descriptionKey: string;
readonly priceId: string;
readonly amountCents: number;
readonly baseAmountCents: number;
readonly currency: string;
readonly billingPeriod: number;
readonly includedOfficeSeatQuantity: number;
readonly includedFieldSeatQuantity: number;
readonly includedStorageGb: number;
readonly storagePerAdditionalSeatGb: number;
readonly extraOfficeSeatQuantity: number;
readonly extraFieldSeatQuantity: number;
readonly recommended: boolean;
};
export type RegistrationPlanSelection = {
readonly plans: readonly RegistrationPlanOption[];
readonly selectedPriceId: string;
readonly recommendedPriceId: string;
readonly officeSeatQuantity: number;
readonly fieldSeatQuantity: number;
};
export async function loadRegistrationPlanSelection(
preferredPlanOrPrice?: string | null,
seatQuantities: { readonly officeSeatQuantity: number; readonly fieldSeatQuantity: number } = {
officeSeatQuantity: 1,
fieldSeatQuantity: 0,
}
): Promise<RegistrationPlanSelection> {
const catalog = await loadSelfServiceSubscriptionCatalog();
const advice = adviseRegistrationPlan(seatQuantities);
const plans = catalog.plans.flatMap((plan) => {
const price = plan.prices.find((candidate) => candidate.billingPeriod === 3);
const canonicalPlan = getBillingCatalogPlan(plan.code);
const advisedOption = advice.options.find((candidate) => candidate.planCode === plan.code);
if (!canonicalPlan || !advisedOption) return [];
return price
? [
{
planId: plan.id,
planCode: plan.code,
titleKey: plan.titleKey,
descriptionKey: plan.descriptionKey,
priceId: price.id,
amountCents: advisedOption.breakdown.recurringNetAmountCents,
baseAmountCents: price.unitAmountCents,
currency: price.currency,
billingPeriod: price.billingPeriod,
includedOfficeSeatQuantity: canonicalPlan.includedSeats.office,
includedFieldSeatQuantity: canonicalPlan.includedSeats.field,
includedStorageGb: canonicalPlan.includedStorageGb,
storagePerAdditionalSeatGb: canonicalPlan.storagePerAdditionalSeatGb,
extraOfficeSeatQuantity: advisedOption.breakdown.extraOfficeSeatQuantity,
extraFieldSeatQuantity: advisedOption.breakdown.extraFieldSeatQuantity,
recommended: advisedOption.recommended,
} satisfies RegistrationPlanOption,
]
: [];
});
if (plans.length === 0) {
throw new Error("No canonical registration plan is available");
}
const recommended = plans.find((plan) => plan.planCode === advice.recommendedPlanCode);
if (!recommended) throw new Error("Recommended registration plan is unavailable");
const preferred = preferredPlanOrPrice?.trim() ?? "";
const selected = plans.find((plan) => plan.priceId === preferred || plan.planId === preferred || plan.planCode === preferred) ?? recommended;
return {
plans,
selectedPriceId: selected.priceId,
recommendedPriceId: recommended.priceId,
officeSeatQuantity: advice.officeSeatQuantity,
fieldSeatQuantity: advice.fieldSeatQuantity,
};
}
export async function resolveRegistrationSubscriptionPrice(selectedPriceId: string | null | undefined): Promise<RegistrationPlanOption | null> {
const normalized = selectedPriceId?.trim() ?? "";
if (!normalized) return null;
const selection = await loadRegistrationPlanSelection();
return selection.plans.find((plan) => plan.priceId === normalized) ?? null;
}
@@ -0,0 +1,726 @@
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",
});
});
});
@@ -0,0 +1,643 @@
import {
buildSelfServiceSubscriptionCatalogVM,
buildSelfServiceSubscriptionManagementPolicyVM,
buildSelfServiceSubscriptionPricePreviewVM,
type SelfServiceSubscriptionCatalogVM,
type SelfServiceSubscriptionCurrentSelectionVM,
type SelfServiceSubscriptionPageVM,
type SelfServiceSubscriptionPlanVM,
type SelfServiceSubscriptionPricePreviewVM,
} from "@hivegrid/view-models";
import type { TenantSubscriptionWithDetails } from "@hivegrid/db/subscriptions.server";
import { resolveTenantBillingState, type TenantBillingState } from "@hivegrid/db/billing-domain.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { getDbClient } from "@hivegrid/db/client.server";
import {
annualSepaExtraPriceEur,
billingCadences,
calculateBillingCatalogPrice,
calculateStorageCapacity,
calculateHiveGridGrossAmountCents,
calculateHiveGridVatAmountCents,
emailMarketingCommercialProducts,
getBillingCatalogStorageAddOn,
getSeatPackage,
hiveGridBasePlans,
hiveGridPurchasableStorageAddOns,
hiveGridVat,
type BillingCatalogBasePlan,
type BillingCatalogPlanVariant,
type BillingCadence,
type StorageAddOnCode,
} from "@hivegrid/entitlements";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
import { getTenantSeatCounts } from "~/utils/db/permissions/seatType.db.server";
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
import { getTenantSubscription } from "~/utils/db/tenantSubscriptions.db.server";
import type { TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { resolveEmailMarketingQuotaUsage } from "./email-marketing-quota.server";
import { resolveTenantStorageUsage } from "./storage-capacity.server";
const MAX_SELF_SERVICE_SEATS = 10_000;
export const SELF_SERVICE_SUBSCRIPTION_EFFECTIVE_AT_POLICY = {
new: "immediate",
upgrade: "immediate",
downgrade: "period_end",
billing_period_change: "period_end",
seat_increase: "immediate",
seat_decrease: "period_end",
configuration_increase: "immediate",
configuration_decrease: "period_end",
configuration_change: "period_end",
unchanged: "immediate",
} as const;
export class SelfServiceSubscriptionValidationError extends Error {
override readonly name = "SelfServiceSubscriptionValidationError";
readonly i18nKey: string;
constructor(
readonly code:
| "PLAN_NOT_FOUND"
| "PRICE_NOT_FOUND"
| "PLAN_NOT_PURCHASABLE"
| "SEAT_QUANTITY_INVALID"
| "SEAT_QUANTITY_BELOW_USAGE"
| "CURRENT_PERIOD_END_MISSING"
) {
super(code);
this.i18nKey = `billing:selfServiceSubscription.errors.${code}`;
}
}
export type SelfServiceSubscriptionSelection = {
readonly productId: string;
readonly priceId: string;
readonly seatQuantity?: number;
readonly officeSeatQuantity?: number;
readonly fieldSeatQuantity?: number;
readonly storageAddOnCodes?: readonly string[];
};
export type SelfServiceSubscriptionServerContext = {
readonly catalog: SelfServiceSubscriptionCatalogVM;
readonly minimumSeatQuantity: number;
readonly seatCounts: { readonly office: number; readonly field: number };
readonly storageAddOns: readonly {
readonly code: string;
readonly title: string;
readonly storageGb: number;
readonly amountCents: number;
readonly currency: "EUR";
}[];
readonly emailMarketingAddOns: SelfServiceSubscriptionPageVM["emailMarketingAddOns"];
readonly usage: NonNullable<SelfServiceSubscriptionPageVM["usage"]>;
readonly tenantSubscription: TenantSubscriptionWithDetails | null;
readonly billingState: TenantBillingState;
readonly currentSelection: SelfServiceSubscriptionCurrentSelectionVM | null;
};
export function resolveOtherActiveRecurringGrossTotalCents(
tenantSubscription: TenantSubscriptionWithDetails | null,
options: { readonly excludedProductCodes?: readonly string[]; readonly now?: Date } = {}
): number | null {
try {
const excludedProductCodes = new Set(options.excludedProductCodes ?? []);
let otherRecurringGrossAmountCents = 0;
const now = options.now ?? new Date();
for (const tenantProduct of tenantSubscription?.products ?? []) {
const productCode = tenantProduct.subscriptionProduct.code?.trim() ?? "";
if (
tenantProduct.subscriptionProduct.kind !== "recurring_add_on" ||
productCode.startsWith("storage_") ||
excludedProductCodes.has(productCode) ||
tenantProduct.cancelledAt ||
(tenantProduct.endsAt && tenantProduct.endsAt <= now)
) {
continue;
}
const fixedPrices = tenantProduct.prices.filter((candidate) => !candidate.isMetered && candidate.subscriptionPrice);
if (fixedPrices.length !== 1) return null;
const fixedPrice = fixedPrices[0]!;
const currency = fixedPrice.subscriptionPrice!.currency.toUpperCase();
const quantity = fixedPrice.quantity;
const unitNetAmountCents = Math.round(Number(fixedPrice.subscriptionPrice!.price) * 100);
if (currency !== "EUR" || !Number.isSafeInteger(quantity) || quantity < 1 || !Number.isSafeInteger(unitNetAmountCents) || unitNetAmountCents < 0) {
return null;
}
const netAmountCents = unitNetAmountCents * quantity;
if (!Number.isSafeInteger(netAmountCents)) return null;
otherRecurringGrossAmountCents += calculateHiveGridGrossAmountCents(netAmountCents);
if (!Number.isSafeInteger(otherRecurringGrossAmountCents)) return null;
}
return otherRecurringGrossAmountCents;
} catch {
return null;
}
}
export function resolveCurrentRecurringGrossTotalCents(
context: Pick<SelfServiceSubscriptionServerContext, "catalog" | "currentSelection" | "tenantSubscription">,
options: { readonly excludedProductCodes?: readonly string[]; readonly now?: Date } = {}
): number | null {
const current = context.currentSelection;
if (!current?.priceId) return null;
const plan = context.catalog.plans.find((candidate) => candidate.id === current.planId || candidate.code === current.planCode);
const price = plan?.prices.find((candidate) => candidate.id === current.priceId);
if (!plan || !price) return null;
try {
const baseGrossAmountCents = calculateBillingCatalogPrice({
planCode: plan.code,
cadence: cadenceForBillingPeriod(price.billingPeriod),
officeSeatQuantity: current.officeSeatQuantity ?? current.seatQuantity,
fieldSeatQuantity: current.fieldSeatQuantity ?? 0,
storageAddOnCodes: current.storageAddOnCodes ?? [],
}).recurringGrossAmountCents;
const otherRecurringGrossAmountCents = resolveOtherActiveRecurringGrossTotalCents(context.tenantSubscription, options);
if (otherRecurringGrossAmountCents === null) return null;
const total = baseGrossAmountCents + otherRecurringGrossAmountCents;
return Number.isSafeInteger(total) ? total : null;
} catch {
return null;
}
}
function toPlanCode(input: { id?: string; code?: string | null; lagoPlanCode?: string | null }): string {
return input.lagoPlanCode?.trim() || input.code?.trim() || input.id?.trim() || "";
}
const SAFE_CATALOG_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u;
function safeCatalogId(value: string | null | undefined): string | null {
if (!value || value.length > 191 || value !== value.trim() || !SAFE_CATALOG_ID.test(value)) return null;
return value;
}
function canonicalVariantForBillingPeriod(plan: BillingCatalogBasePlan, billingPeriod: number): BillingCatalogPlanVariant | null {
const cadence =
billingPeriod === SubscriptionBillingPeriod.MONTHLY
? billingCadences.monthly
: billingPeriod === SubscriptionBillingPeriod.YEARLY
? billingCadences.annualSepa
: null;
return cadence ? (plan.variants.find((variant) => variant.cadence === cadence) ?? null) : null;
}
function exactCanonicalBasePrice(
price: Awaited<ReturnType<typeof getAllSubscriptionProducts>>[number]["prices"][number],
plan: BillingCatalogBasePlan
): { id: string; variant: BillingCatalogPlanVariant; amountCents: number } | null {
const id = safeCatalogId(price.id);
const variant = canonicalVariantForBillingPeriod(plan, price.billingPeriod);
const amount = Number(price.price);
const scaledAmount = amount * 100;
const amountCents = Math.round(scaledAmount);
if (
!id ||
!variant ||
!price.active ||
price.type !== SubscriptionPriceType.RECURRING ||
price.currency.toUpperCase() !== "EUR" ||
!Number.isFinite(scaledAmount) ||
!Number.isSafeInteger(amountCents) ||
Math.abs(scaledAmount - amountCents) > Number.EPSILON * Math.max(1, Math.abs(scaledAmount)) ||
amountCents !== variant.baseAmountCents ||
price.billingCadence !== variant.cadence ||
price.contractMonths !== variant.contractMonths ||
price.requiredPaymentMethod !== variant.requiredPaymentMethod ||
price.lagoPlanCode?.trim() !== variant.code ||
price.trialDays !== 0
) {
return null;
}
return { id, variant, amountCents };
}
function toCatalogPlan(product: Awaited<ReturnType<typeof getAllSubscriptionProducts>>[number]): SelfServiceSubscriptionPlanVM | null {
if (product.kind !== "base_plan" || !product.active || !product.public) return null;
const id = safeCatalogId(product.id);
const code = product.code?.trim() ?? "";
if (!id || !code || product.lagoPlanCode?.trim() !== code) return null;
const commercialPlan = hiveGridBasePlans.find((plan) => plan.technicalCode === code);
if (!commercialPlan) return null;
const packageId = commercialPlan.seatPackageId;
const seatPackage = packageId ? getSeatPackage(packageId) : undefined;
const packageTranslationBase = packageId ? `settings.subscription.checkout.plans.packages.${packageId}` : null;
return {
id,
code,
titleKey: packageTranslationBase ? `${packageTranslationBase}.title` : product.title,
descriptionKey: packageTranslationBase
? `${packageTranslationBase}.description`
: product.description?.trim() || "billing:selfServiceSubscription.plans.descriptionFallback",
badge: product.badge,
quantityMode: product.hasQuantity ? "per_seat" : "flat",
packageTerms: seatPackage
? {
packageId: seatPackage.id,
monthlyCents: seatPackage.monthlyEur * 100,
annualSepaMonthlyEquivalentCents: seatPackage.annualSepaEur * 100,
officeSeatsIncluded: seatPackage.seats.office.included,
fieldSeatsIncluded: seatPackage.seats.field.included,
storageIncludedGb: seatPackage.storage.includedGb,
storagePerAdditionalSeatGb: seatPackage.storage.perAdditionalSeatGb,
officeExtraMonthlyCents: seatPackage.seats.office.extraPriceEur * 100,
fieldExtraMonthlyCents: seatPackage.seats.field.extraPriceEur * 100,
officeExtraAnnualSepaCents: Math.round(annualSepaExtraPriceEur(seatPackage.seats.office.extraPriceEur) * 100),
fieldExtraAnnualSepaCents: Math.round(annualSepaExtraPriceEur(seatPackage.seats.field.extraPriceEur) * 100),
}
: null,
// Feature rows remain part of the provider contract for access evaluation,
// but package selection is no longer presented as a feature-tier matrix.
features: [],
prices: product.prices
.map((price) => ({ price, canonical: exactCanonicalBasePrice(price, commercialPlan) }))
.filter(
(candidate): candidate is { price: (typeof product.prices)[number]; canonical: NonNullable<typeof candidate.canonical> } => candidate.canonical !== null
)
.sort((left, right) => left.price.billingPeriod - right.price.billingPeriod || left.canonical.id.localeCompare(right.canonical.id))
.map(({ price, canonical }) => ({
id: canonical.id,
billingPeriod: price.billingPeriod,
currency: "EUR",
unitAmountCents: canonical.amountCents,
trialDays: price.trialDays,
})),
};
}
export async function loadSelfServiceSubscriptionCatalog(): Promise<SelfServiceSubscriptionCatalogVM> {
const products = await getAllSubscriptionProducts(true);
return buildSelfServiceSubscriptionCatalogVM({
plans: products
.slice()
.sort((left, right) => left.order - right.order || (left.id ?? "").localeCompare(right.id ?? ""))
.map(toCatalogPlan)
.filter((plan): plan is SelfServiceSubscriptionPlanVM => plan !== null && plan.prices.length > 0),
});
}
export function resolveSelfServicePreferredSelection(
catalog: SelfServiceSubscriptionCatalogVM,
requestedPriceId: string | null | undefined,
requestedSeatQuantities?: { readonly officeSeatQuantity: number; readonly fieldSeatQuantity: number } | null
): { planId: string; priceId: string; officeSeatQuantity?: number; fieldSeatQuantity?: number } | null {
const priceId = requestedPriceId?.trim() ?? "";
if (!priceId) return null;
for (const plan of catalog.plans) {
if (plan.prices.some((price) => price.id === priceId)) {
return {
planId: plan.id,
priceId,
...(requestedSeatQuantities
? {
officeSeatQuantity: requestedSeatQuantities.officeSeatQuantity,
fieldSeatQuantity: requestedSeatQuantities.fieldSeatQuantity,
}
: {}),
};
}
}
return null;
}
function minimumSeats(counts: { office: number; field: number }): number {
return Math.max(1, counts.office + counts.field);
}
export async function loadSelfServiceSubscriptionServerContext(tenantId: string, now: Date = new Date()): Promise<SelfServiceSubscriptionServerContext> {
// Product and price definitions are deliberately global. Tenant billing and
// occupied-seat reads stay inside an explicit RLS identity boundary.
const tenantClient = getDbClient() as unknown as TenantRlsClient;
const [products, [tenantSubscription, seatCounts, billingState, storageUsage, emailMarketingUsage]] = await Promise.all([
getAllSubscriptionProducts(true),
runWithRlsContext({ tenantId }, () =>
Promise.all([
getTenantSubscription(tenantId),
getTenantSeatCounts(tenantId),
resolveTenantBillingState(tenantId, { now }),
resolveTenantStorageUsage(tenantClient, tenantId, now),
resolveEmailMarketingQuotaUsage(tenantClient, tenantId, now),
])
),
]);
const catalog = buildSelfServiceSubscriptionCatalogVM({
plans: products
.slice()
.sort((left, right) => left.order - right.order || (left.id ?? "").localeCompare(right.id ?? ""))
.map(toCatalogPlan)
.filter((plan): plan is SelfServiceSubscriptionPlanVM => plan !== null && plan.prices.length > 0),
});
return {
catalog,
tenantSubscription,
billingState,
usage: {
storage: storageUsage.available
? {
status: "ready",
capacityBytes: storageUsage.capacityBytes,
storedBytes: storageUsage.storedBytes,
reservedBytes: storageUsage.reservedBytes,
remainingBytes: storageUsage.remainingBytes,
percentUsed: 0,
}
: { status: "unavailable", reason: storageUsage.reason },
emailMarketing: emailMarketingUsage.available
? {
status: "ready",
periodStart: emailMarketingUsage.periodStart.toISOString(),
periodEnd: emailMarketingUsage.periodEnd.toISOString(),
limit: emailMarketingUsage.limit,
used: emailMarketingUsage.used,
remaining: emailMarketingUsage.remaining,
percentUsed: null,
}
: { status: "unavailable", reason: emailMarketingUsage.reason },
},
seatCounts,
storageAddOns: hiveGridPurchasableStorageAddOns.map((addOn) => ({
code: addOn.code,
title: addOn.publicName,
storageGb: addOn.includedStorageGb,
amountCents: addOn.amountCents,
currency: "EUR",
})),
emailMarketingAddOns: emailMarketingCommercialProducts.flatMap((definition) => {
const matches = products.filter((product) => product.code === definition.code);
if (matches.length !== 1) return [];
const product = matches[0]!;
const prices = product.prices.filter(
(price) =>
price.active &&
price.type === SubscriptionPriceType.RECURRING &&
price.billingPeriod === 3 &&
price.billingCadence === billingCadences.monthly &&
price.contractMonths === 1 &&
price.requiredPaymentMethod === "any" &&
price.lagoPlanCode?.trim() === definition.code &&
price.lagoFeeCode?.trim() === definition.code &&
price.trialDays === 0 &&
price.currency.toUpperCase() === definition.currency &&
Math.round(Number(price.price) * 100) === definition.amountCents &&
Boolean(price.id)
);
if (
product.kind !== "recurring_add_on" ||
!product.active ||
!product.public ||
!product.id ||
product.lagoPlanCode?.trim() !== definition.code ||
prices.length !== 1
) {
return [];
}
const active = Boolean(
tenantSubscription?.products.some(
(tenantProduct) =>
tenantProduct.subscriptionProduct.code === definition.code && !tenantProduct.cancelledAt && (!tenantProduct.endsAt || tenantProduct.endsAt > now)
)
);
return [
{
productId: product.id,
priceId: prices[0]!.id!,
code: definition.code,
title: definition.title,
monthlyEmailLimit: definition.monthlyEmailLimit,
amountCents: definition.amountCents!,
vatRateBasisPoints: hiveGridVat.rateBasisPoints,
vatAmountCents: calculateHiveGridVatAmountCents(definition.amountCents!),
grossAmountCents: calculateHiveGridGrossAmountCents(definition.amountCents!),
currency: definition.currency!,
active,
},
];
}),
minimumSeatQuantity: minimumSeats(seatCounts),
currentSelection: resolveCurrentSelection(tenantSubscription, catalog, now),
};
}
function activeProduct(subscription: TenantSubscriptionWithDetails | null, now: Date) {
if (!subscription) return null;
const byPlanCode = subscription.products.find(
(product) =>
(product.planCode === subscription.planCode || product.subscriptionProduct.code === subscription.planCode) &&
!product.cancelledAt &&
(!product.currentPeriodStart || product.currentPeriodStart <= now) &&
(!product.endsAt || product.endsAt > now)
);
return (
byPlanCode ??
subscription.products.find(
(product) => !product.cancelledAt && (!product.currentPeriodStart || product.currentPeriodStart <= now) && (!product.endsAt || product.endsAt > now)
) ??
null
);
}
function isProviderManagedProduct(product: TenantSubscriptionWithDetails["products"][number] | null): boolean {
return Boolean(product?.lagoSubscriptionId?.trim() || product?.billingProviderSubscriptionId?.trim());
}
function resolveCurrentSelection(
subscription: TenantSubscriptionWithDetails | null,
catalog: SelfServiceSubscriptionCatalogVM,
now: Date
): SelfServiceSubscriptionCurrentSelectionVM | null {
const product = activeProduct(subscription, now);
if (!subscription || !product) return null;
const code = toPlanCode(product.subscriptionProduct) || product.planCode?.trim() || subscription.planCode?.trim() || "";
const plan = catalog.plans.find((candidate) => candidate.id === product.subscriptionProductId || candidate.code === code);
if (!plan) return null;
const linkedPriceId = product.prices.find((price) => !price.isMetered && price.subscriptionPriceId)?.subscriptionPriceId ?? null;
const priceId = linkedPriceId && plan.prices.some((price) => price.id === linkedPriceId) ? linkedPriceId : null;
return {
planId: plan.id,
planCode: plan.code,
priceId,
seatQuantity: Math.max(1, product.seatQuantity ?? subscription.seatQuantity ?? product.quantity ?? 1),
...(positiveRoleSeatQuantity(product.officeSeatQuantity ?? subscription.officeSeatQuantity) !== null
? { officeSeatQuantity: positiveRoleSeatQuantity(product.officeSeatQuantity ?? subscription.officeSeatQuantity)! }
: {}),
...(positiveRoleSeatQuantity(product.fieldSeatQuantity ?? subscription.fieldSeatQuantity) !== null
? { fieldSeatQuantity: positiveRoleSeatQuantity(product.fieldSeatQuantity ?? subscription.fieldSeatQuantity)! }
: {}),
storageAddOnCodes: [
...new Set([
...(product.storageAddOnCodes ?? subscription.storageAddOnCodes ?? []),
...subscription.products
.filter(
(candidate) =>
candidate.subscriptionProduct.kind === "recurring_add_on" &&
candidate.subscriptionProduct.code?.startsWith("storage_") &&
!candidate.cancelledAt &&
(!candidate.endsAt || candidate.endsAt > now)
)
.map((candidate) => candidate.subscriptionProduct.code!),
]),
].sort(),
};
}
function positiveRoleSeatQuantity(value: number | null | undefined): number | null {
return Number.isSafeInteger(value) && value! > 0 ? value! : null;
}
function requireRoleSeatQuantity(value: number, minimum: number): number {
if (!Number.isSafeInteger(value) || value < 0 || value > MAX_SELF_SERVICE_SEATS) {
throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_INVALID");
}
if (value < minimum) {
throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_BELOW_USAGE");
}
return value;
}
function selectedRoleSeats(selection: SelfServiceSubscriptionSelection, minimum: { office: number; field: number }): { office: number; field: number } {
if (selection.officeSeatQuantity !== undefined || selection.fieldSeatQuantity !== undefined) {
return {
office: requireRoleSeatQuantity(selection.officeSeatQuantity ?? 0, minimum.office),
field: requireRoleSeatQuantity(selection.fieldSeatQuantity ?? 0, minimum.field),
};
}
const legacyTotal = selection.seatQuantity;
if (!Number.isSafeInteger(legacyTotal) || legacyTotal! < 1 || legacyTotal! > MAX_SELF_SERVICE_SEATS) {
throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_INVALID");
}
const minimumTotal = minimum.office + minimum.field;
if (legacyTotal! < minimumTotal) throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_BELOW_USAGE");
return {
office: minimum.office + (legacyTotal! - minimumTotal),
field: minimum.field,
};
}
function cadenceForBillingPeriod(billingPeriod: number): BillingCadence {
return billingPeriod === 4 ? billingCadences.annualSepa : billingCadences.monthly;
}
function requirePurchasableStorageAddOnCodes(
requestedCodes: readonly string[] | undefined,
currentCodes: readonly string[]
): readonly StorageAddOnCode[] | undefined {
if (requestedCodes === undefined) return undefined;
const currentCodeSet = new Set(currentCodes);
for (const code of requestedCodes) {
const addOn = getBillingCatalogStorageAddOn(code);
if (!addOn || (!addOn.purchasable && !currentCodeSet.has(code))) {
throw new SelfServiceSubscriptionValidationError("PLAN_NOT_PURCHASABLE");
}
}
return requestedCodes as readonly StorageAddOnCode[];
}
export async function previewSelfServiceSubscription(
tenantId: string,
selection: SelfServiceSubscriptionSelection,
now: Date = new Date()
): Promise<SelfServiceSubscriptionPricePreviewVM> {
const { catalog, tenantSubscription, seatCounts, currentSelection } = await loadSelfServiceSubscriptionServerContext(tenantId, now);
const selectedPlan = catalog.plans.find((plan) => plan.id === selection.productId);
if (!selectedPlan) throw new SelfServiceSubscriptionValidationError("PLAN_NOT_PURCHASABLE");
const selectedPrice = selectedPlan.prices.find((price) => price.id === selection.priceId);
if (!selectedPrice) throw new SelfServiceSubscriptionValidationError("PRICE_NOT_FOUND");
const selectedSeats = selectedRoleSeats(selection, seatCounts);
const selectedSeatQuantity = Math.max(1, selectedSeats.office + selectedSeats.field);
const selectedStorageAddOnCodes = requirePurchasableStorageAddOnCodes(selection.storageAddOnCodes, currentSelection?.storageAddOnCodes ?? []);
const priceBreakdown = calculateBillingCatalogPrice({
planCode: selectedPlan.code,
cadence: cadenceForBillingPeriod(selectedPrice.billingPeriod),
officeSeatQuantity: selectedSeats.office,
fieldSeatQuantity: selectedSeats.field,
storageAddOnCodes: selectedStorageAddOnCodes,
});
const storageCapacity = calculateStorageCapacity({
planCode: selectedPlan.code,
officeSeatQuantity: selectedSeats.office,
fieldSeatQuantity: selectedSeats.field,
storageAddOnCodes: selectedStorageAddOnCodes,
});
const currentProduct = activeProduct(tenantSubscription, now);
// Workspace bootstrap assigns a providerless product as a local entitlement.
// Keep it visible as the current selection, but classify the first explicit
// Lago/Mollie acquisition as a new billable subscription.
const billableCurrentProduct = currentProduct && isProviderManagedProduct(currentProduct) ? currentProduct : null;
const currentCode = billableCurrentProduct
? toPlanCode(billableCurrentProduct.subscriptionProduct)
: currentProduct
? null
: tenantSubscription?.planCode?.trim() || null;
const currentPlan = currentCode
? (catalog.plans.find(
(plan) => plan.code === currentCode || plan.id === billableCurrentProduct?.subscriptionProductId || plan.code === billableCurrentProduct?.planCode
) ?? null)
: null;
const currentPrice = currentPlan && currentSelection?.priceId ? (currentPlan.prices.find((price) => price.id === currentSelection.priceId) ?? null) : null;
const currentSeatQuantity = tenantSubscription
? billableCurrentProduct
? Math.max(1, billableCurrentProduct.seatQuantity ?? tenantSubscription.seatQuantity ?? billableCurrentProduct.quantity ?? 1)
: currentProduct
? 0
: Math.max(1, tenantSubscription.seatQuantity ?? 1)
: 0;
const currentPeriodEnd = billableCurrentProduct?.currentPeriodEnd?.toISOString() ?? null;
const currentOfficeSeatQuantity = currentSelection?.officeSeatQuantity;
const currentFieldSeatQuantity = currentSelection?.fieldSeatQuantity;
const currentStorageAddOnCodes = currentSelection?.storageAddOnCodes ?? [];
const currentPriceBreakdown =
currentPlan && currentPrice && currentSelection
? calculateBillingCatalogPrice({
planCode: currentPlan.code,
cadence: cadenceForBillingPeriod(currentPrice.billingPeriod),
officeSeatQuantity: currentOfficeSeatQuantity ?? currentSelection.seatQuantity,
fieldSeatQuantity: currentFieldSeatQuantity ?? 0,
storageAddOnCodes: currentStorageAddOnCodes,
})
: null;
const policy = buildSelfServiceSubscriptionManagementPolicyVM({
planOrder: catalog.plans.map((plan) => plan.code),
effectiveAtByChangeKind: SELF_SERVICE_SUBSCRIPTION_EFFECTIVE_AT_POLICY,
});
try {
return buildSelfServiceSubscriptionPricePreviewVM({
currentPlan,
currentPrice,
currentSeatQuantity,
currentOfficeSeatQuantity,
currentFieldSeatQuantity,
currentStorageAddOnCodes,
currentRecurringNetTotalCents: currentPriceBreakdown?.recurringNetAmountCents,
currentPeriodEnd,
selectedPlan,
selectedPrice,
selectedSeatQuantity,
selectedOfficeSeatQuantity: selectedSeats.office,
selectedFieldSeatQuantity: selectedSeats.field,
selectedStorageAddOnCodes: priceBreakdown.storageAddOns.map((addOn) => addOn.code),
includedStorageGb: storageCapacity.includedStorageGb,
additionalSeatStorageGb: storageCapacity.additionalSeatStorageGb,
addOnStorageGb: storageCapacity.addOnStorageGb,
totalStorageGb: storageCapacity.totalStorageGb,
baseAmountCents: priceBreakdown.baseAmountCents,
officeSeatAmountCents: priceBreakdown.officeSeatAmountCents,
fieldSeatAmountCents: priceBreakdown.fieldSeatAmountCents,
storageAmountCents: priceBreakdown.storageAmountCents,
vatRateBasisPoints: priceBreakdown.vatRateBasisPoints,
vatAmountCents: priceBreakdown.vatAmountCents,
recurringGrossTotalCents: priceBreakdown.recurringGrossAmountCents,
policy,
});
} catch (error) {
if (error instanceof Error && error.message.includes("currentPeriodEnd is required")) {
throw new SelfServiceSubscriptionValidationError("CURRENT_PERIOD_END_MISSING");
}
throw error;
}
}
@@ -0,0 +1,350 @@
import { describe, expect, it, vi } from "vitest";
import { STORAGE_BYTES_PER_GB } from "@hivegrid/entitlements";
import {
assertTenantStorageReservation,
resolveTenantStorageCapacity,
resolveTenantStorageUsage,
TenantStorageCapacityError,
withTenantStorageWriteReservation,
} from "./storage-capacity.server";
const now = new Date("2026-07-30T12:00:00.000Z");
function subscription(overrides: Record<string, unknown> = {}) {
return {
status: "active",
planCode: "starter",
seatQuantity: 8,
officeSeatQuantity: 3,
fieldSeatQuantity: 6,
storageAddOnCodes: ["storage_100gb"],
trialEndsAt: null,
frozenAt: null,
cancelledAt: null,
products: [
{
createdAt: new Date("2026-07-01T00:00:00.000Z"),
cancelledAt: null,
endsAt: null,
currentPeriodStart: null,
planCode: "starter",
seatQuantity: 9,
officeSeatQuantity: 3,
fieldSeatQuantity: 6,
storageAddOnCodes: ["storage_100gb"],
quantity: 9,
subscriptionProduct: { code: "starter", lagoPlanCode: "starter", kind: "base_plan" },
},
],
...overrides,
};
}
describe("tenant storage capacity", () => {
it("resolves the active commercial plan, role seats, and storage add-ons", async () => {
const client = {
tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) },
};
await expect(resolveTenantStorageCapacity("tenant_1", client, now)).resolves.toEqual({
available: true,
capacity: {
planCode: "starter",
includedStorageGb: 100,
additionalSeatStorageGb: 20,
addOnStorageGb: 100,
totalStorageGb: 220,
totalStorageBytes: 220 * STORAGE_BYTES_PER_GB,
},
});
});
it("fails closed for frozen billing and missing active base products", async () => {
const frozenClient = {
tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription({ status: "frozen", frozenAt: now })) },
};
await expect(resolveTenantStorageCapacity("tenant_1", frozenClient, now)).resolves.toMatchObject({
available: false,
reason: "billing_read_only",
});
const missingPlanClient = {
tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription({ products: [] })) },
};
await expect(resolveTenantStorageCapacity("tenant_1", missingPlanClient, now)).resolves.toMatchObject({
available: false,
reason: "plan_unknown",
});
});
it("counts stored files and in-progress reservations under the tenant lock", async () => {
const tx = {
$executeRaw: vi.fn().mockResolvedValue(1),
$queryRaw: vi.fn().mockResolvedValue([{ storedBytes: 50n, reservedBytes: 25n }]),
tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) },
};
await expect(assertTenantStorageReservation(tx as never, "tenant_1", 100, now)).resolves.toMatchObject({
storedBytes: 50,
reservedBytes: 25,
requestedBytes: 100,
});
expect(tx.$executeRaw).toHaveBeenCalledOnce();
});
it("projects stored and in-progress bytes without taking the reservation lock", async () => {
const tx = {
$executeRaw: vi.fn(),
$queryRaw: vi.fn().mockResolvedValue([{ storedBytes: 50n, reservedBytes: 25n }]),
tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) },
};
await expect(resolveTenantStorageUsage(tx as never, "tenant_1", now)).resolves.toMatchObject({
available: true,
storedBytes: 50,
reservedBytes: 25,
remainingBytes: 220 * STORAGE_BYTES_PER_GB - 75,
});
expect(tx.$executeRaw).not.toHaveBeenCalled();
});
it("rejects reservations that exceed the paid capacity", async () => {
const tx = {
$executeRaw: vi.fn().mockResolvedValue(1),
$queryRaw: vi.fn().mockResolvedValue([{ storedBytes: BigInt(99 * STORAGE_BYTES_PER_GB), reservedBytes: 0n }]),
tenantSubscription: {
findUnique: vi.fn().mockResolvedValue(
subscription({
officeSeatQuantity: 2,
fieldSeatQuantity: 5,
storageAddOnCodes: [],
products: [
{
...subscription().products[0],
officeSeatQuantity: 2,
fieldSeatQuantity: 5,
storageAddOnCodes: [],
},
],
})
),
},
};
await expect(assertTenantStorageReservation(tx as never, "tenant_1", 2 * STORAGE_BYTES_PER_GB, now)).rejects.toMatchObject<TenantStorageCapacityError>({
code: "STORAGE_QUOTA_EXCEEDED",
});
});
it("persists a tenant-wide reservation before upload and swaps it for the File commit under the same lock", async () => {
let reservationStatus = "in_progress";
const events: string[] = [];
const tx = {
$executeRaw: vi.fn().mockImplementation(async () => {
events.push("lock");
return 1;
}),
$queryRaw: vi.fn().mockResolvedValue([{ storedBytes: 50n, reservedBytes: 25n }]),
tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) },
file: { findFirst: vi.fn().mockResolvedValue({ id: "file_1" }) },
fileUpload: {
create: vi.fn().mockImplementation(async ({ data }) => {
events.push("reservation");
return { id: data.id, tenantId: data.tenantId, targetFileId: data.targetFileId, totalSizeBytes: data.totalSizeBytes };
}),
findFirst: vi.fn().mockImplementation(async () => ({ id: "reservation_1", status: reservationStatus })),
updateMany: vi.fn().mockImplementation(async ({ data }) => {
reservationStatus = data.status;
events.push(`reservation:${data.status}`);
return { count: 1 };
}),
},
};
await expect(
withTenantStorageWriteReservation({
reservation: {
reservationId: "reservation_1",
tenantId: "tenant_1",
actorUserId: "user_1",
targetFileId: "file_1",
originalFilename: "invoice.pdf",
mimeType: "application/pdf",
sizeBytes: 100,
now,
},
runTransaction: async (operation) => operation(tx as never),
upload: async () => {
events.push("upload");
return { key: "files/file_1" };
},
commit: async (_commitTx, stored) => {
events.push(`commit:${stored.key}`);
return "committed";
},
rollbackUpload: vi.fn(),
})
).resolves.toBe("committed");
expect(events).toEqual(["lock", "reservation", "upload", "lock", "commit:files/file_1", "reservation:completed"]);
expect(tx.fileUpload.create).toHaveBeenCalledWith({
data: expect.objectContaining({
status: "in_progress",
targetFileId: "file_1",
totalSizeBytes: 100,
expiresAt: new Date("9999-12-31T23:59:59.999Z"),
}),
select: { id: true, tenantId: true, targetFileId: true, totalSizeBytes: true },
});
expect(tx.file.findFirst).toHaveBeenCalledWith({
where: { id: "file_1", tenantId: "tenant_1", sizeBytes: 100 },
select: { id: true },
});
});
it("deletes a failed object before cancelling its paid-capacity reservation", async () => {
let reservationStatus = "in_progress";
const events: string[] = [];
const tx = {
$executeRaw: vi.fn().mockResolvedValue(1),
$queryRaw: vi.fn().mockResolvedValue([{ storedBytes: 0n, reservedBytes: 0n }]),
tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) },
file: { findFirst: vi.fn() },
fileUpload: {
create: vi.fn().mockResolvedValue({ id: "reservation_1", tenantId: "tenant_1", targetFileId: "file_1", totalSizeBytes: 100 }),
findFirst: vi.fn().mockImplementation(async () => ({ id: "reservation_1", status: reservationStatus })),
updateMany: vi.fn().mockImplementation(async ({ data }) => {
reservationStatus = data.status;
events.push(`reservation:${data.status}`);
return { count: 1 };
}),
},
};
await expect(
withTenantStorageWriteReservation({
reservation: {
reservationId: "reservation_1",
tenantId: "tenant_1",
actorUserId: "user_1",
targetFileId: "file_1",
originalFilename: "invoice.pdf",
mimeType: "application/pdf",
sizeBytes: 100,
now,
},
runTransaction: async (operation) => operation(tx as never),
upload: async () => ({ key: "files/file_1" }),
commit: async () => {
throw new Error("database write failed");
},
rollbackUpload: async () => {
events.push("object:deleted");
},
})
).rejects.toThrow("database write failed");
expect(events).toEqual(["object:deleted", "reservation:cancelled"]);
expect(reservationStatus).toBe("cancelled");
});
it("rejects a commit that did not persist the exact reserved File row", async () => {
let reservationStatus = "in_progress";
const rollbackUpload = vi.fn().mockResolvedValue(undefined);
const tx = {
$executeRaw: vi.fn().mockResolvedValue(1),
$queryRaw: vi.fn().mockResolvedValue([{ storedBytes: 0n, reservedBytes: 0n }]),
tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) },
file: { findFirst: vi.fn().mockResolvedValue(null) },
fileUpload: {
create: vi.fn().mockResolvedValue({ id: "reservation_1", tenantId: "tenant_1", targetFileId: "file_1", totalSizeBytes: 100 }),
findFirst: vi.fn().mockImplementation(async () => ({ id: "reservation_1", status: reservationStatus })),
updateMany: vi.fn().mockImplementation(async ({ data }) => {
reservationStatus = data.status;
return { count: 1 };
}),
},
};
await expect(
withTenantStorageWriteReservation({
reservation: {
reservationId: "reservation_1",
tenantId: "tenant_1",
actorUserId: "user_1",
targetFileId: "file_1",
originalFilename: "invoice.pdf",
mimeType: "application/pdf",
sizeBytes: 100,
now,
},
runTransaction: async (operation) => operation(tx as never),
upload: async () => ({ key: "files/file_1" }),
commit: async () => "callback-returned-without-file",
rollbackUpload,
})
).rejects.toMatchObject<TenantStorageCapacityError>({ code: "STORAGE_RESERVATION_INVALID" });
expect(rollbackUpload).toHaveBeenCalledWith({ key: "files/file_1" });
expect(reservationStatus).toBe("cancelled");
});
it("keeps an undeletable object charged through a durable in-progress reservation", async () => {
let reservationStatus = "in_progress";
const tx = {
$executeRaw: vi.fn().mockResolvedValue(1),
$queryRaw: vi.fn().mockResolvedValue([{ storedBytes: 0n, reservedBytes: 0n }]),
tenantSubscription: { findUnique: vi.fn().mockResolvedValue(subscription()) },
file: { findFirst: vi.fn() },
fileUpload: {
create: vi.fn().mockImplementation(async ({ data }) => ({
id: data.id,
tenantId: data.tenantId,
targetFileId: data.targetFileId,
totalSizeBytes: data.totalSizeBytes,
})),
findFirst: vi.fn().mockImplementation(async () => ({ id: "reservation_1", status: reservationStatus })),
updateMany: vi.fn().mockImplementation(async ({ data }) => {
reservationStatus = data.status;
return { count: 1 };
}),
},
};
await expect(
withTenantStorageWriteReservation({
reservation: {
reservationId: "reservation_1",
tenantId: "tenant_1",
actorUserId: "user_1",
targetFileId: "file_1",
originalFilename: "invoice.pdf",
mimeType: "application/pdf",
sizeBytes: 100,
now,
},
runTransaction: async (operation) => operation(tx as never),
upload: async () => ({ key: "files/file_1" }),
commit: async () => {
throw new Error("database write failed");
},
rollbackUpload: async () => {
throw new Error("object delete failed");
},
})
).rejects.toMatchObject({
message: "Storage write and rollback both failed",
errors: [expect.objectContaining({ message: "database write failed" }), expect.objectContaining({ message: "object delete failed" })],
});
expect(reservationStatus).toBe("in_progress");
expect(tx.fileUpload.updateMany).not.toHaveBeenCalled();
expect(tx.fileUpload.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ expiresAt: new Date("9999-12-31T23:59:59.999Z") }),
})
);
});
});
@@ -0,0 +1,15 @@
export {
assertTenantStorageReservation,
createTenantStorageWriteReservation,
resolveTenantStorageCapacity,
resolveTenantStorageUsage,
tenantStorageCapacitySelect,
TenantStorageCapacityError,
withTenantStorageWriteReservation,
type TenantStorageCapacity,
type TenantStorageReservation,
type TenantStorageTransactionRunner,
type TenantStorageUsage,
type TenantStorageWriteReservation,
type TenantStorageWriteReservationInput,
} from "@hivegrid/db/storage-capacity.server";