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

@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { getDefaultProductBlueprint, getProductBlueprint, productBlueprintIds, productBlueprints } from "./index.js";
import { featureKeys, getDefaultProductBlueprint, getProductBlueprint, productBlueprintIds, productBlueprints } from "./index.js";
describe("product blueprint lookups", () => {
it("resolves the CRM SaaS blueprint by id and returns the shared registry instance", () => {
@@ -23,7 +23,7 @@ describe("product blueprint lookups", () => {
expect(blueprint.id).toBe(productBlueprintIds.crmSaas);
expect(blueprint.defaultShowcase).toBe(true);
expect(blueprint.version).toBe("2026.05.15");
expect(blueprint.version).toBe("2026.07.20");
});
it("keeps blueprint fixtures deeply immutable", () => {
@@ -42,7 +42,7 @@ describe("product blueprint lookups", () => {
expect(() => {
(target as { version: string }).version = "tampered";
}).toThrow(TypeError);
expect(getDefaultProductBlueprint().version).toBe("2026.05.15");
expect(getDefaultProductBlueprint().version).toBe("2026.07.20");
});
it("gates every CRM SaaS feature behind a tenant role permission and enables it by default", () => {
@@ -58,4 +58,68 @@ describe("product blueprint lookups", () => {
expect(feature.requiresTenantRolePermission, `${feature.featureKey} non-empty permission`).not.toBe("");
}
});
it("marks core modules as included-in-core and keeps the Email-Marketing add-on subscription-gated (Fundament D)", () => {
const blueprint = getDefaultProductBlueprint();
const includedInCoreByKey = new Map(blueprint.features.map((feature) => [feature.featureKey, feature.includedInCore]));
// Core modules every tenant receives regardless of subscription (plan-gate removed).
for (const coreKey of [
featureKeys.dashboard,
featureKeys.crmBasic,
featureKeys.leads,
featureKeys.projects,
featureKeys.files,
featureKeys.tasks,
featureKeys.hr,
featureKeys.integrations,
featureKeys.telephony,
featureKeys.chat,
featureKeys.booking,
featureKeys.forms,
featureKeys.signature,
featureKeys.billing,
featureKeys.search,
featureKeys.automation,
featureKeys.emailInbox,
featureKeys.api,
featureKeys.workflowEngine,
featureKeys.mcp,
featureKeys.users,
]) {
expect(includedInCoreByKey.get(coreKey), `${coreKey} is a core module`).toBe(true);
}
// The Email-Marketing add-on (incl. its audience lists) stays subscription-gated.
for (const addOnKey of [featureKeys.emailMarketing, featureKeys.importedLists, featureKeys.crmBasedLists]) {
expect(includedInCoreByKey.get(addOnKey), `${addOnKey} is a paid add-on`).toBe(false);
}
for (const addOnKey of [featureKeys.customerPortal, featureKeys.customerPortalCustomDomain]) {
expect(includedInCoreByKey.get(addOnKey), `${addOnKey} is commercially gated`).toBe(false);
}
expect(includedInCoreByKey.get(featureKeys.kwpIntegration), "KWP is a subscription-gated add-on").toBe(false);
});
it("keeps KWP subscription-gated and non-toggleable by tenants", () => {
expect(getDefaultProductBlueprint().features.find((feature) => feature.featureKey === featureKeys.kwpIntegration)).toMatchObject({
defaultEnabled: true,
tenantToggleable: false,
includedInCore: false,
requiresTenantRolePermission: "integrations.read",
});
});
it("does not permit tenant overrides to self-enable portal products", () => {
const blueprint = getDefaultProductBlueprint();
for (const featureKey of [featureKeys.customerPortal, featureKeys.customerPortalCustomDomain]) {
expect(blueprint.features.find((feature) => feature.featureKey === featureKey)).toMatchObject({
defaultEnabled: true,
tenantToggleable: false,
includedInCore: false,
requiresTenantRolePermission: "portal.admin",
});
}
});
});
@@ -10,6 +10,11 @@ export interface ProductBlueprintFeatureDefinition {
readonly featureKey: FeatureKey;
readonly defaultEnabled: boolean;
readonly tenantToggleable: boolean;
// Fundament D: when true the feature is a core module that every tenant receives
// regardless of an active subscription (no plan-gate). When false the feature stays
// subscription-gated (real add-on, e.g. Email-Marketing). This does NOT affect the
// tenant role permission (RBAC) gate below, which is enforced either way.
readonly includedInCore: boolean;
readonly requiresTenantRolePermission?: string;
}
@@ -22,6 +27,36 @@ export interface ProductBlueprintDefinition {
readonly features: readonly ProductBlueprintFeatureDefinition[];
}
// Fundament D: the set of core module feature keys that every tenant receives for
// free, independent of an active subscription (plan-gate removed). Everything NOT in
// this set stays subscription-gated — most importantly the Email-Marketing add-on
// (email-marketing plus its audience lists imported-lists/crm-based-lists) and future
// paid storage packs. Keep this list in sync with the core module surface; a feature
// key omitted here defaults to add-on (subscription-gated).
const coreIncludedFeatureKeys: ReadonlySet<FeatureKey> = new Set<FeatureKey>([
featureKeys.dashboard,
featureKeys.crmBasic,
featureKeys.leads,
featureKeys.projects,
featureKeys.files,
featureKeys.tasks,
featureKeys.hr,
featureKeys.integrations,
featureKeys.telephony,
featureKeys.chat,
featureKeys.booking,
featureKeys.forms,
featureKeys.signature,
featureKeys.billing,
featureKeys.search,
featureKeys.automation,
featureKeys.emailInbox,
featureKeys.api,
featureKeys.workflowEngine,
featureKeys.mcp,
featureKeys.users,
]);
function blueprintFeature(
featureKey: FeatureKey,
defaultEnabled: boolean,
@@ -32,6 +67,7 @@ function blueprintFeature(
featureKey,
defaultEnabled,
tenantToggleable,
includedInCore: coreIncludedFeatureKeys.has(featureKey),
...(requiresTenantRolePermission ? { requiresTenantRolePermission } : {}),
});
}
@@ -39,7 +75,7 @@ function blueprintFeature(
export const productBlueprints = Object.freeze([
Object.freeze({
id: productBlueprintIds.crmSaas,
version: "2026.05.15",
version: "2026.07.20",
title: "CRM SaaS",
description: "Default CRM SaaS product core with support, knowledge base, marketing, billing, search, automation, API, and optional tenant MCP.",
defaultShowcase: true,
@@ -52,10 +88,15 @@ export const productBlueprints = Object.freeze([
blueprintFeature(featureKeys.tasks, true, true, "tasks.read_own"),
blueprintFeature(featureKeys.hr, true, true, "hr.read_own"),
blueprintFeature(featureKeys.integrations, true, true, "integrations.read"),
blueprintFeature(featureKeys.kwpIntegration, true, false, "integrations.read"),
blueprintFeature(featureKeys.telephony, true, true, "telephony.read_own"),
blueprintFeature(featureKeys.chat, true, true, "chat.read_own_channels"),
blueprintFeature(featureKeys.booking, true, true, "bookings.read_own"),
blueprintFeature(featureKeys.forms, true, true, "forms.basic"),
blueprintFeature(featureKeys.signature, true, true, "signature.read"),
blueprintFeature(featureKeys.billing, true, true, "app.settings.subscription.view"),
blueprintFeature(featureKeys.customerPortal, true, false, "portal.admin"),
blueprintFeature(featureKeys.customerPortalCustomDomain, true, false, "portal.admin"),
blueprintFeature(featureKeys.search, true, true, "search.use"),
blueprintFeature(featureKeys.automation, true, true, "automation.read"),
blueprintFeature(featureKeys.supportTickets, true, true, "app.dashboard.view"),
@@ -5,7 +5,8 @@ import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
const sourceRoot = dirname(fileURLToPath(import.meta.url));
const forbiddenImportPattern = /(?:from\s+["']|import\s*\(\s*["'])(~\/|app\/|@hivegrid\/(?:db|config)(?:\/|$)|react(?:\/|$)|react-router(?:\/|$)|@prisma\/client(?:\/|$)|\.prisma\/client(?:\/|$)|prisma(?:\/|$))/;
const forbiddenImportPattern =
/(?:from\s+["']|import\s*\(\s*["'])(~\/|app\/|@hivegrid\/(?:db|config)(?:\/|$)|react(?:\/|$)|react-router(?:\/|$)|@prisma\/client(?:\/|$)|\.prisma\/client(?:\/|$)|prisma(?:\/|$))/;
const diagnosticTemplatePattern = /(?:message\s*[:=]|new\s+\w*Error\s*\()[^;\n]*/g;
const unsafeDiagnosticPattern = /tenant|customer|user|api[-_\s]?key|subscription[-_\s]?id|secret|sk_[a-z0-9]/i;
@@ -22,7 +23,7 @@ async function collectSourceFiles(directory: string): Promise<readonly string[]>
const isSourceFile = extname(entryPath) === ".ts" && !entryPath.endsWith(".test.ts");
return isSourceFile ? [entryPath] : [];
}),
})
);
return files.flat();
@@ -38,11 +39,19 @@ describe("entitlements package boundary", () => {
expect(sourceFiles.map(toPackageRelativePath).sort()).toEqual([
"blueprints.ts",
"commercial-catalog.ts",
"customer-portal-commercial.ts",
"email-marketing-commercial.ts",
"evaluate.ts",
"features.ts",
"index.ts",
"plans.ts",
"product-access.ts",
"registration-plan-advisor.ts",
"seat-packages.ts",
"seat-usage.ts",
"seats.ts",
"storage-capacity.ts",
]);
for (const sourceFile of sourceFiles) {
@@ -0,0 +1,199 @@
import { describe, expect, it } from "vitest";
import {
calculateStorageAddOnGrossMarginAfterEgressBasisPoints,
calculateStorageAddOnGrossMarginBasisPoints,
billingCadences,
calculateBillingCatalogPrice,
calculateHiveGridGrossAmountCents,
calculateHiveGridVatAmountCents,
getBillingCatalogPlan,
getBillingCatalogStorageAddOn,
getBillingCatalogVariant,
getBillingCatalogVariantForSelection,
hiveGridBasePlans,
hiveGridBillingCatalogVersion,
hiveGridPurchasableStorageAddOns,
hiveGridStorageAddOns,
hiveGridVat,
storageAddOnEgressCoverageCycles,
serializeHiveGridBillingCatalog,
} from "./commercial-catalog.js";
describe("HiveGrid commercial billing catalog", () => {
it("maps the stable technical codes to Core, Swarm and Colony", () => {
expect(hiveGridBasePlans.map(({ technicalCode, publicName }) => ({ technicalCode, publicName }))).toEqual([
{ technicalCode: "starter", publicName: "Core" },
{ technicalCode: "pro", publicName: "Swarm" },
{ technicalCode: "business", publicName: "Colony" },
]);
});
it("models annual pricing as a monthly rate with a 12-month commitment and free payment-method choice", () => {
expect(getBillingCatalogPlan("starter")).toMatchObject({
includedSeats: { office: 2, field: 5 },
includedStorageGb: 100,
storagePerAdditionalSeatGb: 10,
variants: [
{
code: "starter",
cadence: "monthly",
lagoInterval: "monthly",
contractMonths: 1,
requiredPaymentMethod: "any",
baseAmountCents: 19_900,
extraSeatAmountCents: { office: 5_900, field: 2_500 },
},
{
code: "starter_annual_sepa",
cadence: "annual_sepa",
lagoInterval: "monthly",
contractMonths: 12,
requiredPaymentMethod: "any",
baseAmountCents: 17_900,
extraSeatAmountCents: { office: 5_310, field: 2_250 },
},
],
});
expect(getBillingCatalogVariantForSelection("pro", billingCadences.annualSepa)).toMatchObject({
code: "pro_annual_sepa",
baseAmountCents: 44_900,
extraSeatAmountCents: { office: 3_510, field: 1_710 },
});
expect(getBillingCatalogVariant("business_annual_sepa")).toMatchObject({
baseAmountCents: 89_900,
extraSeatAmountCents: { office: 3_150, field: 1_350 },
});
});
it("gives larger plans a larger shared pool and more storage per additional license", () => {
expect(
hiveGridBasePlans.map(({ technicalCode, includedStorageGb, storagePerAdditionalSeatGb }) => ({
technicalCode,
includedStorageGb,
storagePerAdditionalSeatGb,
}))
).toEqual([
{ technicalCode: "starter", includedStorageGb: 100, storagePerAdditionalSeatGb: 10 },
{ technicalCode: "pro", includedStorageGb: 500, storagePerAdditionalSeatGb: 20 },
{ technicalCode: "business", includedStorageGb: 2_000, storagePerAdditionalSeatGb: 40 },
]);
});
it("defines the fixed recurring storage packages without usage metering", () => {
expect(hiveGridStorageAddOns).toEqual([
expect.objectContaining({ code: "storage_100gb", includedStorageGb: 100, amountCents: 125, purchasable: false, lagoInterval: "monthly" }),
expect.objectContaining({ code: "storage_500gb", includedStorageGb: 500, amountCents: 699, purchasable: true, lagoInterval: "monthly" }),
expect.objectContaining({ code: "storage_1tb", includedStorageGb: 1_000, amountCents: 1_299, purchasable: true, lagoInterval: "monthly" }),
expect.objectContaining({ code: "storage_5tb", includedStorageGb: 5_000, amountCents: 6_099, purchasable: true, lagoInterval: "monthly" }),
]);
expect(hiveGridPurchasableStorageAddOns.map(({ code, amountCents }) => ({ code, amountCents }))).toEqual([
{ code: "storage_500gb", amountCents: 699 },
{ code: "storage_1tb", amountCents: 1_299 },
{ code: "storage_5tb", amountCents: 6_099 },
]);
expect(getBillingCatalogStorageAddOn("storage_1tb")?.publicName).toBe("Cloud-Speicher Plus · 1 TB");
expect(hiveGridStorageAddOns.map(calculateStorageAddOnGrossMarginBasisPoints)).toEqual([4_623, 5_192, 4_826, 4_490]);
expect(
hiveGridPurchasableStorageAddOns.map((addOn) =>
calculateStorageAddOnGrossMarginAfterEgressBasisPoints(addOn, storageAddOnEgressCoverageCycles)
)
).toEqual([1_352, 693, 88]);
expect(
hiveGridPurchasableStorageAddOns.every(
(addOn) => calculateStorageAddOnGrossMarginAfterEgressBasisPoints(addOn, storageAddOnEgressCoverageCycles) > 0
)
).toBe(true);
expect(calculateStorageAddOnGrossMarginAfterEgressBasisPoints(hiveGridPurchasableStorageAddOns.at(-1)!, 6)).toBeLessThan(0);
expect(() => calculateStorageAddOnGrossMarginAfterEgressBasisPoints(hiveGridPurchasableStorageAddOns[0]!, -1)).toThrow(
/egress cycles/u
);
});
it("calculates role-specific extras and fixed storage packages from the same catalog", () => {
expect(
calculateBillingCatalogPrice({
planCode: "starter",
cadence: billingCadences.monthly,
officeSeatQuantity: 4,
fieldSeatQuantity: 8,
storageAddOnCodes: ["storage_500gb"],
})
).toMatchObject({
variantCode: "starter",
extraOfficeSeatQuantity: 2,
extraFieldSeatQuantity: 3,
baseAmountCents: 19_900,
officeSeatAmountCents: 11_800,
fieldSeatAmountCents: 7_500,
storageAmountCents: 699,
recurringNetAmountCents: 39_899,
vatRateBasisPoints: 1_900,
vatAmountCents: 7_581,
recurringGrossAmountCents: 47_480,
});
expect(
calculateBillingCatalogPrice({
planCode: "starter",
cadence: billingCadences.annualSepa,
officeSeatQuantity: 4,
fieldSeatQuantity: 8,
storageAddOnCodes: ["storage_500gb"],
})
).toMatchObject({
recurringNetAmountCents: 35_969,
vatAmountCents: 6_834,
recurringGrossAmountCents: 42_803,
});
});
it("fails closed for unknown, duplicate or invalid selection values", () => {
expect(() =>
calculateBillingCatalogPrice({
planCode: "unknown",
cadence: billingCadences.monthly,
officeSeatQuantity: 1,
fieldSeatQuantity: 1,
})
).toThrow(/Unknown billing plan/);
expect(() =>
calculateBillingCatalogPrice({
planCode: "starter",
cadence: billingCadences.monthly,
officeSeatQuantity: 2,
fieldSeatQuantity: 5,
storageAddOnCodes: ["storage_100gb", "storage_100gb"],
})
).toThrow(/unique/);
});
it("pins the German VAT contract and emits a deterministic manifest", () => {
expect(hiveGridVat).toEqual({
code: "de-vat-19",
name: "Deutsche Umsatzsteuer 19 %",
countryCode: "DE",
rateBasisPoints: 1_900,
appliedToAmount: "exclusive",
});
expect(hiveGridBillingCatalogVersion).toBe("2026-08-03.3");
expect(serializeHiveGridBillingCatalog()).toBe(serializeHiveGridBillingCatalog());
expect(JSON.parse(serializeHiveGridBillingCatalog())).toMatchObject({
version: "2026-08-03.3",
basePlans: [{ publicName: "Core" }, { publicName: "Swarm" }, { publicName: "Colony" }],
});
});
it("calculates gross product amounts with the same pinned German VAT rounding contract", () => {
expect(calculateHiveGridVatAmountCents(5_900)).toBe(1_121);
expect(calculateHiveGridGrossAmountCents(5_900)).toBe(7_021);
expect(calculateHiveGridGrossAmountCents(1_999)).toBe(2_379);
expect(calculateHiveGridGrossAmountCents(29_999)).toBe(35_699);
expect(() => calculateHiveGridGrossAmountCents(-1)).toThrow(/non-negative safe integer/u);
});
it("returns undefined for unknown public catalog references", () => {
expect(getBillingCatalogPlan("enterprise")).toBeUndefined();
expect(getBillingCatalogVariant("enterprise")).toBeUndefined();
expect(getBillingCatalogStorageAddOn("storage_50tb")).toBeUndefined();
});
});
@@ -0,0 +1,349 @@
import { ANNUAL_SEPA_EXTRA_DISCOUNT, getSeatPackage, seatPackageIds, type SeatPackageId } from "./seat-packages.js";
import { entitlementPlanIds, type EntitlementPlanId } from "./plans.js";
import { emailMarketingCommercialProducts } from "./email-marketing-commercial.js";
import type { SeatType } from "./seats.js";
/**
* Katalogversion fuer den kontrollierten Lago-Sync.
*
* Jede fachliche Aenderung an Namen, Preisen, Laufzeiten, Steuern oder Limits
* erhoeht diese Version. Staging und Production muessen denselben Wert melden.
*/
export const hiveGridBillingCatalogVersion = "2026-08-03.3";
export const billingCadences = Object.freeze({
monthly: "monthly",
annualSepa: "annual_sepa",
} as const);
export type BillingCadence = (typeof billingCadences)[keyof typeof billingCadences];
export const hiveGridVat = Object.freeze({
code: "de-vat-19",
name: "Deutsche Umsatzsteuer 19 %",
countryCode: "DE",
rateBasisPoints: 1_900,
appliedToAmount: "exclusive",
} as const);
export interface BillingCatalogPlanVariant {
readonly code: string;
readonly cadence: BillingCadence;
/** Both variants are invoiced monthly. Annual means commitment, not prepayment. */
readonly lagoInterval: "monthly";
readonly contractMonths: 1 | 12;
readonly requiredPaymentMethod: "any" | "sepa";
readonly baseAmountCents: number;
readonly extraSeatAmountCents: Readonly<Record<SeatType, number>>;
readonly taxCode: typeof hiveGridVat.code;
}
export interface BillingCatalogBasePlan {
readonly technicalCode: EntitlementPlanId;
readonly publicName: "Core" | "Swarm" | "Colony";
readonly seatPackageId: SeatPackageId;
readonly includedSeats: Readonly<Record<SeatType, number>>;
readonly includedStorageGb: number;
readonly storagePerAdditionalSeatGb: number;
readonly variants: readonly [BillingCatalogPlanVariant, BillingCatalogPlanVariant];
}
export const storageAddOnCodes = Object.freeze({
gb100: "storage_100gb",
gb500: "storage_500gb",
tb1: "storage_1tb",
tb5: "storage_5tb",
} as const);
export type StorageAddOnCode = (typeof storageAddOnCodes)[keyof typeof storageAddOnCodes];
export interface BillingCatalogStorageAddOn {
readonly code: StorageAddOnCode;
readonly publicName: string;
readonly includedStorageGb: number;
readonly amountCents: number;
/** False keeps historical contracts resolvable without offering the package to new purchases. */
readonly purchasable: boolean;
readonly lagoInterval: "monthly";
readonly taxCode: typeof hiveGridVat.code;
}
export interface BillingCatalogPriceSelection {
readonly planCode: EntitlementPlanId | string;
readonly cadence: BillingCadence;
readonly officeSeatQuantity: number;
readonly fieldSeatQuantity: number;
readonly storageAddOnCodes?: readonly (StorageAddOnCode | string)[];
}
export interface BillingCatalogPriceBreakdown {
readonly planCode: EntitlementPlanId;
readonly variantCode: string;
readonly cadence: BillingCadence;
readonly contractMonths: 1 | 12;
readonly requiredPaymentMethod: "any" | "sepa";
readonly officeSeatQuantity: number;
readonly fieldSeatQuantity: number;
readonly includedOfficeSeatQuantity: number;
readonly includedFieldSeatQuantity: number;
readonly extraOfficeSeatQuantity: number;
readonly extraFieldSeatQuantity: number;
readonly baseAmountCents: number;
readonly officeSeatAmountCents: number;
readonly fieldSeatAmountCents: number;
readonly storageAmountCents: number;
readonly recurringNetAmountCents: number;
readonly vatRateBasisPoints: typeof hiveGridVat.rateBasisPoints;
readonly vatAmountCents: number;
readonly recurringGrossAmountCents: number;
readonly storageAddOns: readonly BillingCatalogStorageAddOn[];
}
function extraSeatAmountCents(listPriceEur: number, cadence: BillingCadence): number {
const discount = cadence === billingCadences.annualSepa ? ANNUAL_SEPA_EXTRA_DISCOUNT : 0;
return Math.round(listPriceEur * 100 * (1 - discount));
}
function planVariant(
technicalCode: EntitlementPlanId,
cadence: BillingCadence,
baseAmountCents: number,
extraSeatListPricesEur: Readonly<Record<SeatType, number>>
): BillingCatalogPlanVariant {
const annual = cadence === billingCadences.annualSepa;
return Object.freeze({
code: annual ? `${technicalCode}_annual_sepa` : technicalCode,
cadence,
lagoInterval: "monthly",
contractMonths: annual ? 12 : 1,
requiredPaymentMethod: "any",
baseAmountCents,
extraSeatAmountCents: Object.freeze({
office: extraSeatAmountCents(extraSeatListPricesEur.office, cadence),
field: extraSeatAmountCents(extraSeatListPricesEur.field, cadence),
}),
taxCode: hiveGridVat.code,
});
}
function basePlan(input: {
technicalCode: EntitlementPlanId;
publicName: BillingCatalogBasePlan["publicName"];
seatPackageId: SeatPackageId;
}): BillingCatalogBasePlan {
const seatPackage = getSeatPackage(input.seatPackageId);
const extraSeatListPricesEur = {
office: seatPackage.seats.office.extraPriceEur,
field: seatPackage.seats.field.extraPriceEur,
} as const;
return Object.freeze({
technicalCode: input.technicalCode,
publicName: input.publicName,
seatPackageId: input.seatPackageId,
includedSeats: Object.freeze({
office: seatPackage.seats.office.included,
field: seatPackage.seats.field.included,
}),
includedStorageGb: seatPackage.storage.includedGb,
storagePerAdditionalSeatGb: seatPackage.storage.perAdditionalSeatGb,
variants: Object.freeze([
planVariant(input.technicalCode, billingCadences.monthly, seatPackage.monthlyEur * 100, extraSeatListPricesEur),
planVariant(input.technicalCode, billingCadences.annualSepa, seatPackage.annualSepaEur * 100, extraSeatListPricesEur),
]) as BillingCatalogBasePlan["variants"],
});
}
export const hiveGridBasePlans = Object.freeze([
basePlan({
technicalCode: entitlementPlanIds.starter,
publicName: "Core",
seatPackageId: seatPackageIds.starter,
}),
basePlan({
technicalCode: entitlementPlanIds.pro,
publicName: "Swarm",
seatPackageId: seatPackageIds.team,
}),
basePlan({
technicalCode: entitlementPlanIds.business,
publicName: "Colony",
seatPackageId: seatPackageIds.business,
}),
] as const satisfies readonly BillingCatalogBasePlan[]);
function storageAddOn(
code: StorageAddOnCode,
publicName: string,
includedStorageGb: number,
amountCents: number,
purchasable: boolean
): BillingCatalogStorageAddOn {
return Object.freeze({
code,
publicName,
includedStorageGb,
amountCents,
purchasable,
lagoInterval: "monthly",
taxCode: hiveGridVat.code,
});
}
export const hiveGridStorageAddOns = Object.freeze([
storageAddOn(storageAddOnCodes.gb100, "Cloud-Speicher Plus · 100 GB", 100, 125, false),
storageAddOn(storageAddOnCodes.gb500, "Cloud-Speicher Plus · 500 GB", 500, 699, true),
storageAddOn(storageAddOnCodes.tb1, "Cloud-Speicher Plus · 1 TB", 1_000, 1_299, true),
storageAddOn(storageAddOnCodes.tb5, "Cloud-Speicher Plus · 5 TB", 5_000, 6_099, true),
] as const satisfies readonly BillingCatalogStorageAddOn[]);
export const hiveGridPurchasableStorageAddOns = Object.freeze(hiveGridStorageAddOns.filter((addOn) => addOn.purchasable));
/** Current direct marginal Hetzner storage COGS. */
export const hetznerAdditionalStorageCostCentsPerTb = 626;
/** Current external Hetzner egress overage COGS; the account-wide allowance is deliberately not allocated to a package. */
export const hetznerAdditionalEgressCostCentsPerTb = 100;
/** Commercial safety envelope: each package remains contribution-positive after five fully billable read-outs. */
export const storageAddOnEgressCoverageCycles = 5;
/** HiveGrid quotas use GiB-sized units while Hetzner bills storage and traffic in decimal TB. */
export const storageCapacityBytesPerGb = 1_024 ** 3;
const hetznerBytesPerTb = 1_000_000_000_000;
function calculateStorageCostCents(addOn: BillingCatalogStorageAddOn, egressCycles: number): number {
if (!Number.isSafeInteger(egressCycles) || egressCycles < 0 || egressCycles > 10_000) {
throw new RangeError("Storage egress cycles must be a non-negative safe integer up to 10000.");
}
const capacityBytes = addOn.includedStorageGb * storageCapacityBytesPerGb;
const rateCentsPerTb = hetznerAdditionalStorageCostCentsPerTb
+ egressCycles * hetznerAdditionalEgressCostCentsPerTb;
const costCents = (capacityBytes / hetznerBytesPerTb) * rateCentsPerTb;
if (!Number.isFinite(costCents) || costCents < 0) {
throw new RangeError("Storage cost inputs exceed the safe integer range.");
}
return costCents;
}
export function calculateStorageAddOnGrossMarginBasisPoints(addOn: BillingCatalogStorageAddOn): number {
return calculateStorageAddOnGrossMarginAfterEgressBasisPoints(addOn, 0);
}
export function calculateStorageAddOnGrossMarginAfterEgressBasisPoints(
addOn: BillingCatalogStorageAddOn,
egressCycles: number
): number {
if (!Number.isSafeInteger(addOn.amountCents) || addOn.amountCents <= 0) {
throw new RangeError("Storage revenue inputs exceed the safe integer range.");
}
const costCents = calculateStorageCostCents(addOn, egressCycles);
return Math.round(((addOn.amountCents - costCents) / addOn.amountCents) * 10_000);
}
const planByTechnicalCode = new Map<EntitlementPlanId, BillingCatalogBasePlan>(hiveGridBasePlans.map((plan) => [plan.technicalCode, plan]));
const variantByCode = new Map<string, BillingCatalogPlanVariant>(
hiveGridBasePlans.flatMap((plan) => plan.variants.map((variant) => [variant.code, variant] as const))
);
const storageAddOnByCode = new Map<StorageAddOnCode, BillingCatalogStorageAddOn>(hiveGridStorageAddOns.map((addOn) => [addOn.code, addOn]));
export function getBillingCatalogPlan(code: EntitlementPlanId | string): BillingCatalogBasePlan | undefined {
return planByTechnicalCode.get(code as EntitlementPlanId);
}
export function getBillingCatalogVariant(code: string): BillingCatalogPlanVariant | undefined {
return variantByCode.get(code);
}
export function getBillingCatalogVariantForSelection(planCode: EntitlementPlanId | string, cadence: BillingCadence): BillingCatalogPlanVariant | undefined {
return getBillingCatalogPlan(planCode)?.variants.find((variant) => variant.cadence === cadence);
}
export function getBillingCatalogStorageAddOn(code: StorageAddOnCode | string): BillingCatalogStorageAddOn | undefined {
return storageAddOnByCode.get(code as StorageAddOnCode);
}
function requireSeatQuantity(value: number, label: string): number {
if (!Number.isSafeInteger(value) || value < 0 || value > 10_000) {
throw new RangeError(`${label} must be a non-negative safe integer up to 10000.`);
}
return value;
}
function safeAmount(...values: number[]): number {
const amount = values.reduce((total, value) => total + value, 0);
if (!Number.isSafeInteger(amount) || amount < 0) {
throw new RangeError("Billing amount exceeds the safe integer range.");
}
return amount;
}
export function calculateHiveGridVatAmountCents(netAmountCents: number): number {
if (!Number.isSafeInteger(netAmountCents) || netAmountCents < 0) {
throw new RangeError("Billing net amount must be a non-negative safe integer.");
}
const scaled = netAmountCents * hiveGridVat.rateBasisPoints;
if (!Number.isSafeInteger(scaled)) {
throw new RangeError("Billing tax amount exceeds the safe integer range.");
}
return Math.round(scaled / 10_000);
}
export function calculateHiveGridGrossAmountCents(netAmountCents: number): number {
return safeAmount(netAmountCents, calculateHiveGridVatAmountCents(netAmountCents));
}
export function calculateBillingCatalogPrice(selection: BillingCatalogPriceSelection): BillingCatalogPriceBreakdown {
const plan = getBillingCatalogPlan(selection.planCode);
if (!plan) throw new RangeError(`Unknown billing plan: ${selection.planCode}`);
const variant = getBillingCatalogVariantForSelection(plan.technicalCode, selection.cadence);
if (!variant) throw new RangeError(`Unknown billing cadence for ${plan.technicalCode}: ${selection.cadence}`);
const officeSeatQuantity = requireSeatQuantity(selection.officeSeatQuantity, "officeSeatQuantity");
const fieldSeatQuantity = requireSeatQuantity(selection.fieldSeatQuantity, "fieldSeatQuantity");
const storageCodes = selection.storageAddOnCodes ?? [];
if (new Set(storageCodes).size !== storageCodes.length) {
throw new RangeError("Storage add-on codes must be unique.");
}
const storageAddOns = storageCodes.map((code) => {
const addOn = getBillingCatalogStorageAddOn(code);
if (!addOn) throw new RangeError(`Unknown storage add-on: ${code}`);
return addOn;
});
const extraOfficeSeatQuantity = Math.max(0, officeSeatQuantity - plan.includedSeats.office);
const extraFieldSeatQuantity = Math.max(0, fieldSeatQuantity - plan.includedSeats.field);
const officeSeatAmountCents = extraOfficeSeatQuantity * variant.extraSeatAmountCents.office;
const fieldSeatAmountCents = extraFieldSeatQuantity * variant.extraSeatAmountCents.field;
const storageAmountCents = safeAmount(...storageAddOns.map((addOn) => addOn.amountCents));
const recurringNetAmountCents = safeAmount(variant.baseAmountCents, officeSeatAmountCents, fieldSeatAmountCents, storageAmountCents);
const vatAmountCents = calculateHiveGridVatAmountCents(recurringNetAmountCents);
return Object.freeze({
planCode: plan.technicalCode,
variantCode: variant.code,
cadence: variant.cadence,
contractMonths: variant.contractMonths,
requiredPaymentMethod: variant.requiredPaymentMethod,
officeSeatQuantity,
fieldSeatQuantity,
includedOfficeSeatQuantity: plan.includedSeats.office,
includedFieldSeatQuantity: plan.includedSeats.field,
extraOfficeSeatQuantity,
extraFieldSeatQuantity,
baseAmountCents: variant.baseAmountCents,
officeSeatAmountCents,
fieldSeatAmountCents,
storageAmountCents,
recurringNetAmountCents,
vatRateBasisPoints: hiveGridVat.rateBasisPoints,
vatAmountCents,
recurringGrossAmountCents: calculateHiveGridGrossAmountCents(recurringNetAmountCents),
storageAddOns: Object.freeze([...storageAddOns]),
});
}
/** Deterministic provider-neutral manifest used by sync and drift tooling. */
export function serializeHiveGridBillingCatalog(): string {
return JSON.stringify({
version: hiveGridBillingCatalogVersion,
tax: hiveGridVat,
basePlans: hiveGridBasePlans,
storageAddOns: hiveGridStorageAddOns,
emailMarketingAddOns: emailMarketingCommercialProducts,
});
}
@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import {
commercialEntitlementSources,
customerPortalCommercialProducts,
customerPortalPlanCommercialMapping,
enterpriseCustomerPortalContract,
featureKeys,
getCustomerPortalPlanCommercialMapping,
} from "./index.js";
describe("customer portal commercial entitlement contract", () => {
it("maps Starter and Team to the monthly add-on while Business includes the portal", () => {
expect(customerPortalPlanCommercialMapping.starter).toEqual({
portal: commercialEntitlementSources.recurringAddOn,
customDomain: commercialEntitlementSources.oneTimeSetup,
});
expect(customerPortalPlanCommercialMapping.pro).toEqual(customerPortalPlanCommercialMapping.starter);
expect(customerPortalPlanCommercialMapping.business).toEqual({
portal: commercialEntitlementSources.basePlan,
customDomain: commercialEntitlementSources.oneTimeSetup,
});
});
it("keeps exact EUR prices and acquisition scopes in immutable catalog definitions", () => {
expect(customerPortalCommercialProducts.monthlyAddOn).toMatchObject({
source: "recurring_add_on",
featureKeys: [featureKeys.customerPortal],
amountCents: 1_999,
currency: "EUR",
scope: "tenant",
public: true,
});
expect(customerPortalCommercialProducts.customDomainSetup).toMatchObject({
source: "one_time_setup",
featureKeys: [featureKeys.customerPortalCustomDomain],
amountCents: 29_999,
currency: "EUR",
scope: "hostname",
public: true,
});
expect(Object.isFrozen(customerPortalCommercialProducts.monthlyAddOn)).toBe(true);
expect(Object.isFrozen(customerPortalCommercialProducts.monthlyAddOn.featureKeys)).toBe(true);
});
it("keeps Enterprise outside public plans and grants exactly one domain by contract override", () => {
expect(enterpriseCustomerPortalContract).toEqual({
source: "contract_override",
portalIncluded: true,
customDomainIncludedQuantity: 1,
requiresCheckout: false,
});
expect(customerPortalCommercialProducts.enterpriseContract).toMatchObject({
source: "contract_override",
public: false,
amountCents: null,
includedQuantity: 1,
});
expect(getCustomerPortalPlanCommercialMapping("enterprise")).toBeUndefined();
expect(getCustomerPortalPlanCommercialMapping("business")).toBe(customerPortalPlanCommercialMapping.business);
});
});
@@ -0,0 +1,134 @@
import { featureKeys, type FeatureKey } from "./features.js";
import { entitlementLimitTypes, type EntitlementLimitType } from "./evaluate.js";
import { entitlementPlanIds, type EntitlementPlanId } from "./plans.js";
export const commercialEntitlementSources = Object.freeze({
basePlan: "base_plan",
recurringAddOn: "recurring_add_on",
oneTimeSetup: "one_time_setup",
contractOverride: "contract_override",
} as const);
export type CommercialEntitlementSource = (typeof commercialEntitlementSources)[keyof typeof commercialEntitlementSources];
export const customerPortalProductCodes = Object.freeze({
monthlyAddOn: "customer_portal_monthly",
customDomainSetup: "customer_portal_domain_setup",
enterpriseContract: "customer_portal_enterprise_contract",
} as const);
export interface CommercialProductDefinition {
readonly code: string;
readonly title: string;
readonly description: string;
readonly groupTitle: string;
readonly catalogOrder: number;
readonly source: CommercialEntitlementSource;
readonly featureKeys: readonly FeatureKey[];
readonly featureLimits?: Readonly<
Partial<
Record<
FeatureKey,
{
readonly limitType: EntitlementLimitType;
readonly limit: number | null;
}
>
>
>;
readonly public: boolean;
readonly amountCents: number | null;
readonly currency: "EUR" | null;
readonly scope: "tenant" | "hostname";
readonly includedQuantity: number | null;
}
function product(definition: CommercialProductDefinition): CommercialProductDefinition {
return Object.freeze({ ...definition, featureKeys: Object.freeze([...definition.featureKeys]) });
}
export const customerPortalCommercialProducts = Object.freeze({
monthlyAddOn: product({
code: customerPortalProductCodes.monthlyAddOn,
title: "Customer Portal",
description: "Recurring portal access add-on for Starter and Pro workspaces.",
groupTitle: "Customer Portal",
catalogOrder: 100,
source: commercialEntitlementSources.recurringAddOn,
featureKeys: [featureKeys.customerPortal],
public: true,
amountCents: 1_999,
currency: "EUR",
scope: "tenant",
includedQuantity: null,
}),
customDomainSetup: product({
code: customerPortalProductCodes.customDomainSetup,
title: "Customer Portal Domain Setup",
description: "One-time setup for one verified custom portal hostname.",
groupTitle: "Customer Portal",
catalogOrder: 110,
source: commercialEntitlementSources.oneTimeSetup,
featureKeys: [featureKeys.customerPortalCustomDomain],
public: true,
amountCents: 29_999,
currency: "EUR",
scope: "hostname",
includedQuantity: null,
}),
enterpriseContract: product({
code: customerPortalProductCodes.enterpriseContract,
title: "Customer Portal Enterprise Contract",
description: "Non-public portal and custom-domain entitlement granted by contract.",
groupTitle: "Customer Portal",
catalogOrder: 120,
source: commercialEntitlementSources.contractOverride,
featureKeys: [featureKeys.customerPortal, featureKeys.customerPortalCustomDomain],
public: false,
amountCents: null,
currency: null,
scope: "tenant",
includedQuantity: 1,
}),
} as const);
export function getCommercialProductFeatureLimit(
product: CommercialProductDefinition,
featureKey: FeatureKey
): { readonly limitType: EntitlementLimitType; readonly limit: number | null } {
return product.featureLimits?.[featureKey] ?? {
limitType: entitlementLimitTypes.included,
limit: product.includedQuantity,
};
}
export interface CustomerPortalPlanCommercialMapping {
readonly portal: CommercialEntitlementSource;
readonly customDomain: CommercialEntitlementSource;
}
export const customerPortalPlanCommercialMapping = Object.freeze({
[entitlementPlanIds.starter]: Object.freeze({
portal: commercialEntitlementSources.recurringAddOn,
customDomain: commercialEntitlementSources.oneTimeSetup,
}),
[entitlementPlanIds.pro]: Object.freeze({
portal: commercialEntitlementSources.recurringAddOn,
customDomain: commercialEntitlementSources.oneTimeSetup,
}),
[entitlementPlanIds.business]: Object.freeze({
portal: commercialEntitlementSources.basePlan,
customDomain: commercialEntitlementSources.oneTimeSetup,
}),
} as const satisfies Readonly<Record<EntitlementPlanId, CustomerPortalPlanCommercialMapping>>);
export const enterpriseCustomerPortalContract = Object.freeze({
source: commercialEntitlementSources.contractOverride,
portalIncluded: true,
customDomainIncludedQuantity: 1,
requiresCheckout: false,
});
export function getCustomerPortalPlanCommercialMapping(planId: EntitlementPlanId | string): CustomerPortalPlanCommercialMapping | undefined {
return customerPortalPlanCommercialMapping[planId as EntitlementPlanId];
}
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vitest";
import {
emailMarketingCommercialProducts,
emailMarketingProductCodes,
entitlementLimitTypes,
featureKeys,
getEmailMarketingCommercialProduct,
standardEntitlementPlans,
} from "./index.js";
describe("email marketing commercial contract", () => {
it("keeps email marketing outside every base plan", () => {
for (const plan of standardEntitlementPlans) {
for (const featureKey of [featureKeys.emailMarketing, featureKeys.importedLists, featureKeys.crmBasedLists]) {
expect(plan.features.find((feature) => feature.featureKey === featureKey)?.limitType).toBe(entitlementLimitTypes.notIncluded);
}
}
});
it("defines the five exact recurring monthly tiers", () => {
expect(emailMarketingCommercialProducts.map(({ code, monthlyEmailLimit, amountCents }) => ({ code, monthlyEmailLimit, amountCents }))).toEqual([
{ code: emailMarketingProductCodes.s, monthlyEmailLimit: 10_000, amountCents: 5_900 },
{ code: emailMarketingProductCodes.m, monthlyEmailLimit: 50_000, amountCents: 14_900 },
{ code: emailMarketingProductCodes.l, monthlyEmailLimit: 100_000, amountCents: 24_900 },
{ code: emailMarketingProductCodes.xl, monthlyEmailLimit: 250_000, amountCents: 49_900 },
{ code: emailMarketingProductCodes.xxl, monthlyEmailLimit: 500_000, amountCents: 89_900 },
]);
expect(
emailMarketingCommercialProducts.every(
(product) =>
product.source === "recurring_add_on" &&
product.featureLimits?.[featureKeys.emailMarketing]?.limitType === entitlementLimitTypes.monthly &&
product.featureLimits[featureKeys.emailMarketing]?.limit === product.monthlyEmailLimit
)
).toBe(true);
});
it("persists stable translation keys for every catalog label", () => {
expect(emailMarketingCommercialProducts.map(({ code, title, description, groupTitle }) => ({ code, title, description, groupTitle }))).toEqual([
{
code: emailMarketingProductCodes.s,
title: "billing:selfServiceSubscription.emailMarketing.packages.s.title",
description: "billing:selfServiceSubscription.emailMarketing.packages.s.description",
groupTitle: "billing:selfServiceSubscription.emailMarketing.title",
},
{
code: emailMarketingProductCodes.m,
title: "billing:selfServiceSubscription.emailMarketing.packages.m.title",
description: "billing:selfServiceSubscription.emailMarketing.packages.m.description",
groupTitle: "billing:selfServiceSubscription.emailMarketing.title",
},
{
code: emailMarketingProductCodes.l,
title: "billing:selfServiceSubscription.emailMarketing.packages.l.title",
description: "billing:selfServiceSubscription.emailMarketing.packages.l.description",
groupTitle: "billing:selfServiceSubscription.emailMarketing.title",
},
{
code: emailMarketingProductCodes.xl,
title: "billing:selfServiceSubscription.emailMarketing.packages.xl.title",
description: "billing:selfServiceSubscription.emailMarketing.packages.xl.description",
groupTitle: "billing:selfServiceSubscription.emailMarketing.title",
},
{
code: emailMarketingProductCodes.xxl,
title: "billing:selfServiceSubscription.emailMarketing.packages.xxl.title",
description: "billing:selfServiceSubscription.emailMarketing.packages.xxl.description",
groupTitle: "billing:selfServiceSubscription.emailMarketing.title",
},
]);
});
it("resolves only canonical product codes", () => {
expect(getEmailMarketingCommercialProduct(emailMarketingProductCodes.m)?.monthlyEmailLimit).toBe(50_000);
expect(getEmailMarketingCommercialProduct("email_marketing_custom")).toBeUndefined();
});
});
@@ -0,0 +1,67 @@
import { commercialEntitlementSources, type CommercialProductDefinition } from "./customer-portal-commercial.js";
import { entitlementLimitTypes } from "./evaluate.js";
import { featureKeys } from "./features.js";
export const emailMarketingProductCodes = Object.freeze({
s: "email_marketing_s",
m: "email_marketing_m",
l: "email_marketing_l",
xl: "email_marketing_xl",
xxl: "email_marketing_xxl",
} as const);
export type EmailMarketingProductCode = (typeof emailMarketingProductCodes)[keyof typeof emailMarketingProductCodes];
export interface EmailMarketingCommercialProductDefinition extends CommercialProductDefinition {
readonly code: EmailMarketingProductCode;
readonly monthlyEmailLimit: number;
}
type EmailMarketingTier = keyof typeof emailMarketingProductCodes;
const emailMarketingTranslationKeyRoot = "billing:selfServiceSubscription.emailMarketing";
function tier(
tierName: EmailMarketingTier,
monthlyEmailLimit: number,
amountCents: number,
catalogOrder: number
): EmailMarketingCommercialProductDefinition {
return Object.freeze({
code: emailMarketingProductCodes[tierName],
title: `${emailMarketingTranslationKeyRoot}.packages.${tierName}.title`,
description: `${emailMarketingTranslationKeyRoot}.packages.${tierName}.description`,
groupTitle: `${emailMarketingTranslationKeyRoot}.title`,
catalogOrder,
source: commercialEntitlementSources.recurringAddOn,
featureKeys: Object.freeze([featureKeys.emailMarketing, featureKeys.importedLists, featureKeys.crmBasedLists]),
featureLimits: Object.freeze({
[featureKeys.emailMarketing]: Object.freeze({
limitType: entitlementLimitTypes.monthly,
limit: monthlyEmailLimit,
}),
}),
public: true,
amountCents,
currency: "EUR",
scope: "tenant",
includedQuantity: null,
monthlyEmailLimit,
});
}
export const emailMarketingCommercialProducts = Object.freeze([
tier("s", 10_000, 5_900, 200),
tier("m", 50_000, 14_900, 210),
tier("l", 100_000, 24_900, 220),
tier("xl", 250_000, 49_900, 230),
tier("xxl", 500_000, 89_900, 240),
] as const satisfies readonly EmailMarketingCommercialProductDefinition[]);
const tierByCode = new Map<EmailMarketingProductCode, EmailMarketingCommercialProductDefinition>(
emailMarketingCommercialProducts.map((product) => [product.code, product])
);
export function getEmailMarketingCommercialProduct(code: EmailMarketingProductCode | string): EmailMarketingCommercialProductDefinition | undefined {
return tierByCode.get(code as EmailMarketingProductCode);
}
@@ -15,10 +15,15 @@ const currentDefaultFeatureKeys = [
"tasks",
"hr",
"integrations",
"kwp_integration",
"telephony",
"chat",
"booking",
"forms",
"signature",
"billing",
"customer_portal",
"customer_portal_custom_domain",
"search",
"automation",
"api",
@@ -7,10 +7,15 @@ export const featureKeys = {
tasks: "tasks",
hr: "hr",
integrations: "integrations",
kwpIntegration: "kwp_integration",
telephony: "telephony",
chat: "chat",
booking: "booking",
forms: "forms",
signature: "signature",
billing: "billing",
customerPortal: "customer_portal",
customerPortalCustomDomain: "customer_portal_custom_domain",
search: "search",
automation: "automation",
supportTickets: "support-tickets",
@@ -150,6 +155,30 @@ export const featureGateRegistry = Object.freeze([
defaultOrder: 14,
description: "Controls the Apps-Engine integrations framework (OAuth/API-key connections, sync, health).",
}),
Object.freeze({
key: featureKeys.kwpIntegration,
title: "KWP integration",
category: "automation",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 14.25,
description: "Controls access to the KWP pilot connector, its OAuth setup, token lifecycle, and read-only health checks.",
}),
Object.freeze({
key: featureKeys.telephony,
title: "Telephony",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 14.5,
description: "Controls connected calling, inbound call handling, call history, and tenant telephony settings.",
}),
Object.freeze({
key: featureKeys.chat,
title: "Team chat",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 14.75,
description: "Controls access to tenant-scoped realtime channels, direct messages, threads, and chat administration.",
}),
Object.freeze({
key: featureKeys.booking,
title: "Booking",
@@ -182,6 +211,22 @@ export const featureGateRegistry = Object.freeze([
defaultOrder: 17.5,
description: "Controls access to subscription, usage, billing recovery, and tenant-facing billing settings.",
}),
Object.freeze({
key: featureKeys.customerPortal,
title: "Project portal",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 17.6,
description: "Controls access to the separate project portal surface.",
}),
Object.freeze({
key: featureKeys.customerPortalCustomDomain,
title: "Project portal custom domain",
category: "customization",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 17.7,
description: "Controls whether a verified custom hostname may serve the project portal.",
}),
Object.freeze({
key: featureKeys.search,
title: "Global search",
@@ -21,39 +21,42 @@ describe("entitlements package shell", () => {
expect(blueprint).toMatchObject({
id: productBlueprintIds.crmSaas,
version: "2026.05.15",
version: "2026.07.20",
defaultShowcase: true,
});
expect(blueprint.features.map((feature) => feature.featureKey)).toEqual(
expect.arrayContaining([featureKeys.crmBasic, featureKeys.supportTickets, featureKeys.workflowEngine, featureKeys.mcp])
expect.arrayContaining([featureKeys.crmBasic, featureKeys.chat, featureKeys.supportTickets, featureKeys.workflowEngine, featureKeys.mcp])
);
});
it("keeps Starter, Pro, and Business realistically strict", () => {
expect(getStandardEntitlementPlan(entitlementPlanIds.starter)?.features).toEqual(
it("keeps Core, Swarm, and Colony on one HiveGrid core", () => {
const starter = getStandardEntitlementPlan(entitlementPlanIds.starter)!;
const team = getStandardEntitlementPlan(entitlementPlanIds.pro)!;
const business = getStandardEntitlementPlan(entitlementPlanIds.business)!;
const withoutPortal = (plan: typeof starter) =>
plan.features
.filter((feature) => feature.featureKey !== featureKeys.customerPortal)
.map(({ featureKey, limitType, limit }) => ({ featureKey, limitType, limit }));
expect(starter.metadata.publicName).toBe("Core");
expect(team.metadata.publicName).toBe("Swarm");
expect(business.metadata.publicName).toBe("Colony");
expect(withoutPortal(starter)).toEqual(withoutPortal(team));
expect(withoutPortal(team)).toEqual(withoutPortal(business));
expect(starter.features).toEqual(
expect.arrayContaining([
expect.objectContaining({ featureKey: featureKeys.crmBasic, limitType: entitlementLimitTypes.included }),
expect.objectContaining({ featureKey: featureKeys.api, limitType: entitlementLimitTypes.notIncluded }),
expect.objectContaining({ featureKey: featureKeys.workflowEngine, limitType: entitlementLimitTypes.notIncluded }),
])
);
expect(getStandardEntitlementPlan(entitlementPlanIds.pro)?.features).toEqual(
expect.arrayContaining([
expect.objectContaining({ featureKey: featureKeys.emailMarketing, limitType: entitlementLimitTypes.monthly }),
expect.objectContaining({ featureKey: featureKeys.api, limitType: entitlementLimitTypes.included }),
expect.objectContaining({ featureKey: featureKeys.workflowEngine, limitType: entitlementLimitTypes.notIncluded }),
])
);
expect(getStandardEntitlementPlan(entitlementPlanIds.business)?.features).toEqual(
expect.arrayContaining([
expect.objectContaining({ featureKey: featureKeys.workflowEngine, limitType: entitlementLimitTypes.monthly }),
expect.objectContaining({ featureKey: featureKeys.mcp, limitType: entitlementLimitTypes.included }),
expect.objectContaining({ featureKey: featureKeys.advancedBuilder, limitType: entitlementLimitTypes.included }),
expect.objectContaining({ featureKey: featureKeys.workflowEngine, limitType: entitlementLimitTypes.unlimited }),
expect.objectContaining({ featureKey: featureKeys.kwpIntegration, limitType: entitlementLimitTypes.notIncluded }),
])
);
expect(starter.features.some((feature) => feature.featureKey === featureKeys.credits)).toBe(false);
expect(starter.features.some((feature) => feature.featureKey === featureKeys.privateGenerations)).toBe(false);
});
it("evaluates product access through blueprint, plan, tenant override, and tenant-owned role permission", () => {
// Fundament D: workflow-engine is a core module, so a plan listing it as
// not-included no longer blocks it — core access is granted with reason "included".
expect(
evaluateProductAccess({
blueprintId: productBlueprintIds.crmSaas,
@@ -62,7 +65,7 @@ describe("entitlements package shell", () => {
limitType: entitlementLimitTypes.notIncluded,
tenantRolePermissionNames: ["app.settings.roles.set"],
})
).toMatchObject({ allowed: false, reason: "not-included" });
).toMatchObject({ allowed: true, reason: "included" });
expect(
evaluateProductAccess({
@@ -101,10 +104,13 @@ describe("entitlements package shell", () => {
})
).toMatchObject({ allowed: true, reason: "monthly-remaining", remaining: 90 });
// A non-toggleable ADD-ON (ai-credits: not includedInCore) still rejects an "enabled"
// override — a tenant cannot self-enable a paid add-on. Core modules are exempted (see
// product-access.edge.test.ts), so this uses an add-on to keep exercising the path.
expect(
evaluateProductAccess({
blueprintId: productBlueprintIds.crmSaas,
featureKey: featureKeys.crmBasic,
featureKey: featureKeys.credits,
hasSubscription: true,
limitType: entitlementLimitTypes.notIncluded,
tenantOverride: "enabled",
@@ -1,12 +1,6 @@
export const entitlementsPackageName = "@hivegrid/entitlements";
export {
assertKnownFeatureKey,
featureGateRegistry,
featureKeys,
getFeatureGate,
isFeatureKey,
} from "./features.js";
export { assertKnownFeatureKey, featureGateRegistry, featureKeys, getFeatureGate, isFeatureKey } from "./features.js";
export { entitlementLimitTypes, evaluateEntitlement } from "./evaluate.js";
export {
entitlementPlanIds,
@@ -18,19 +12,66 @@ export {
} from "./plans.js";
export { getDefaultProductBlueprint, getProductBlueprint, productBlueprintIds, productBlueprints } from "./blueprints.js";
export { evaluateProductAccess } from "./product-access.js";
export { deriveSeatType, SEAT_TYPES } from "./seats.js";
export {
ANNUAL_SEPA_EXTRA_DISCOUNT,
annualSepaExtraPriceEur,
getSeatPackage,
isSeatPackageId,
listSeatPackageIds,
resolveSeatPackageId,
seatPackageIds,
seatPackages,
} from "./seat-packages.js";
export { computeSeatUsage } from "./seat-usage.js";
export { adviseRegistrationPlan, REGISTRATION_MAX_SEAT_QUANTITY } from "./registration-plan-advisor.js";
export { calculateStorageCapacity, STORAGE_BYTES_PER_GB } from "./storage-capacity.js";
export {
billingCadences,
calculateBillingCatalogPrice,
calculateHiveGridGrossAmountCents,
calculateHiveGridVatAmountCents,
getBillingCatalogPlan,
getBillingCatalogStorageAddOn,
getBillingCatalogVariant,
getBillingCatalogVariantForSelection,
hiveGridBasePlans,
hiveGridBillingCatalogVersion,
hiveGridPurchasableStorageAddOns,
hiveGridStorageAddOns,
hiveGridVat,
serializeHiveGridBillingCatalog,
storageAddOnCodes,
} from "./commercial-catalog.js";
export {
commercialEntitlementSources,
customerPortalCommercialProducts,
customerPortalPlanCommercialMapping,
customerPortalProductCodes,
enterpriseCustomerPortalContract,
getCommercialProductFeatureLimit,
getCustomerPortalPlanCommercialMapping,
} from "./customer-portal-commercial.js";
export { emailMarketingCommercialProducts, emailMarketingProductCodes, getEmailMarketingCommercialProduct } from "./email-marketing-commercial.js";
export type { FeatureCategory, FeatureGateRegistryItem, FeatureKey, FeatureLimitType } from "./features.js";
export type { ProductBlueprintDefinition, ProductBlueprintFeatureDefinition, ProductBlueprintId } from "./blueprints.js";
export type {
EntitlementPlanFeatureAssignment,
EntitlementPlanId,
EntitlementPlanMetadata,
EntitlementPlanStub,
} from "./plans.js";
export type {
EntitlementDecision,
EntitlementDecisionReason,
EntitlementLimitType,
EvaluateEntitlementInput,
} from "./evaluate.js";
export type { EntitlementPlanFeatureAssignment, EntitlementPlanId, EntitlementPlanMetadata, EntitlementPlanStub } from "./plans.js";
export type { EntitlementDecision, EntitlementDecisionReason, EntitlementLimitType, EvaluateEntitlementInput } from "./evaluate.js";
export type { ProductAccessDecision, ProductAccessDecisionReason, ProductAccessInput, TenantFeatureOverride } from "./product-access.js";
export type { DeriveSeatTypeInput, SeatType } from "./seats.js";
export type { SeatCategoryTerms, SeatPackageDefinition, SeatPackageId } from "./seat-packages.js";
export type { ComputeSeatUsageInput, SeatBillingCadence, SeatCategoryUsage, SeatUsageResult } from "./seat-usage.js";
export type { RegistrationPlanAdvice, RegistrationPlanAdviceOption } from "./registration-plan-advisor.js";
export type { StorageCapacity, StorageCapacitySelection } from "./storage-capacity.js";
export type {
BillingCadence,
BillingCatalogBasePlan,
BillingCatalogPlanVariant,
BillingCatalogPriceBreakdown,
BillingCatalogPriceSelection,
BillingCatalogStorageAddOn,
StorageAddOnCode,
} from "./commercial-catalog.js";
export type { CommercialEntitlementSource, CommercialProductDefinition, CustomerPortalPlanCommercialMapping } from "./customer-portal-commercial.js";
export type { EmailMarketingCommercialProductDefinition, EmailMarketingProductCode } from "./email-marketing-commercial.js";
@@ -27,10 +27,15 @@ const expectedFeatureKeys = [
"tasks",
"hr",
"integrations",
"kwp_integration",
"telephony",
"chat",
"booking",
"forms",
"signature",
"billing",
"customer_portal",
"customer_portal_custom_domain",
"search",
"automation",
"api",
@@ -46,9 +51,8 @@ const expectedFeatureKeys = [
"rate-limit-per-minute",
"rate-limit-per-second",
"priority-support",
"ai-credits",
"private-generations",
] as const satisfies readonly FeatureKey[];
const seededFeatureRegistry = featureGateRegistry.filter((feature) => feature.key !== "ai-credits" && feature.key !== "private-generations");
const unsafeFixturePattern =
/(?:prod_[a-z0-9]|price_[a-z0-9]|sk_(?:live|test)|pk_(?:live|test)|api[_ -]?key|secret|password|token|tenant[_ -]?id|customer[_ -]?id|subscription[_ -]?id|acct_[a-z0-9]|cus_[a-z0-9]|sub_[a-z0-9])/i;
@@ -90,12 +94,12 @@ describe("standardEntitlementPlans", () => {
expect(
plan.features.map((feature) => feature.featureKey),
`${plan.id} registry coverage`
).toEqual(featureGateRegistry.map((feature) => feature.key));
).toEqual(seededFeatureRegistry.map((feature) => feature.key));
}
});
it("keeps plan feature assignments in registry order", () => {
const expectedOrders = featureGateRegistry.map((feature) => feature.defaultOrder);
const expectedOrders = seededFeatureRegistry.map((feature) => feature.defaultOrder);
for (const plan of standardEntitlementPlans) {
expect(
@@ -121,21 +125,38 @@ describe("standardEntitlementPlans", () => {
});
it("exposes lookup helpers without mutating fixture order", () => {
expect(getStandardEntitlementPlan("pro")?.metadata.publicName).toBe("Pro");
expect(getStandardEntitlementPlan("pro")?.metadata.publicName).toBe("Swarm");
expect(getStandardEntitlementPlan("pro")?.metadata.billingProviderProductId).toBe(getBillingProviderProductPlaceholder("pro"));
expect(getStandardEntitlementPlan("pro")?.metadata.billingProviderPriceId).toBe(getBillingProviderPricePlaceholder("pro"));
expect(getStandardEntitlementPlan("unknown-plan")).toBeUndefined();
expect(listStandardEntitlementPlanIds()).toEqual(expectedPlanIds);
});
it("keeps portal and custom-domain plan rights separate", () => {
const starter = getStandardEntitlementPlan("starter");
const pro = getStandardEntitlementPlan("pro");
const business = getStandardEntitlementPlan("business");
expect(starter?.features.find((feature) => feature.featureKey === "customer_portal")?.limitType).toBe(entitlementLimitTypes.notIncluded);
expect(pro?.features.find((feature) => feature.featureKey === "customer_portal")?.limitType).toBe(entitlementLimitTypes.notIncluded);
expect(business?.features.find((feature) => feature.featureKey === "customer_portal")?.limitType).toBe(entitlementLimitTypes.included);
for (const plan of [starter, pro, business]) {
expect(plan?.features.find((feature) => feature.featureKey === "customer_portal_custom_domain")?.limitType).toBe(entitlementLimitTypes.notIncluded);
}
});
it("uses deterministic safe Mollie placeholders and no secret-looking fixture strings", () => {
for (const plan of standardEntitlementPlans) {
expect(plan.metadata.billingProviderProductId, `${plan.id} product id placeholder`).toBe(getBillingProviderProductPlaceholder(plan.id));
expect(plan.metadata.billingProviderPriceId, `${plan.id} price id placeholder`).toBe(getBillingProviderPricePlaceholder(plan.id));
expect(plan.metadata.billingProviderProductId, `${plan.id} non-empty product placeholder`).not.toBe("");
expect(plan.metadata.billingProviderPriceId, `${plan.id} non-empty price placeholder`).not.toBe("");
expect(getStandardEntitlementPlan(plan.id)?.metadata.billingProviderProductId, `${plan.id} lookup product placeholder`).toBe(plan.metadata.billingProviderProductId);
expect(getStandardEntitlementPlan(plan.id)?.metadata.billingProviderPriceId, `${plan.id} lookup price placeholder`).toBe(plan.metadata.billingProviderPriceId);
expect(getStandardEntitlementPlan(plan.id)?.metadata.billingProviderProductId, `${plan.id} lookup product placeholder`).toBe(
plan.metadata.billingProviderProductId
);
expect(getStandardEntitlementPlan(plan.id)?.metadata.billingProviderPriceId, `${plan.id} lookup price placeholder`).toBe(
plan.metadata.billingProviderPriceId
);
const strings = [
plan.id,
@@ -3,6 +3,7 @@ import { featureGateRegistry, featureKeys, type FeatureKey } from "./features.js
export const entitlementPlanIds = Object.freeze({
starter: "starter",
/** Stable technical code. The tenant-facing package name is Swarm. */
pro: "pro",
business: "business",
} as const);
@@ -49,13 +50,7 @@ export interface EntitlementPlanStub {
const featureOrderByKey = new Map<FeatureKey, number>(featureGateRegistry.map((feature) => [feature.key, feature.defaultOrder]));
function assignment(featureKey: FeatureKey, limitType: EntitlementLimitType, limit: number | null, label: string): EntitlementPlanFeatureAssignment {
return Object.freeze({
featureKey,
limitType,
limit,
order: featureOrderByKey.get(featureKey) ?? 0,
label,
});
return Object.freeze({ featureKey, limitType, limit, order: featureOrderByKey.get(featureKey) ?? 0, label });
}
function planStub(
@@ -76,135 +71,77 @@ function planStub(
});
}
/**
* All commercial base packages contain the same HiveGrid product core. Package
* differentiation belongs to `seatPackages` (seats, storage and prices), not
* to a second, contradictory feature-tier matrix. KWP stays a separate add-on.
* AI-credit remnants are deliberately absent from the seeded standard plans.
*/
const hiveGridCoreFeatures = Object.freeze([
assignment(featureKeys.dashboard, entitlementLimitTypes.included, null, "Dashboard"),
assignment(featureKeys.crmBasic, entitlementLimitTypes.included, null, "CRM"),
assignment(featureKeys.leads, entitlementLimitTypes.included, null, "Leads"),
assignment(featureKeys.projects, entitlementLimitTypes.included, null, "Projects and pipelines"),
assignment(featureKeys.files, entitlementLimitTypes.included, null, "File storage"),
assignment(featureKeys.tasks, entitlementLimitTypes.included, null, "Tasks"),
assignment(featureKeys.hr, entitlementLimitTypes.included, null, "HR"),
assignment(featureKeys.integrations, entitlementLimitTypes.included, null, "Integrations"),
assignment(featureKeys.kwpIntegration, entitlementLimitTypes.notIncluded, null, "KWP add-on"),
assignment(featureKeys.telephony, entitlementLimitTypes.included, null, "Telephony"),
assignment(featureKeys.chat, entitlementLimitTypes.included, null, "Team chat"),
assignment(featureKeys.booking, entitlementLimitTypes.included, null, "Bookings"),
assignment(featureKeys.forms, entitlementLimitTypes.included, null, "Forms"),
assignment(featureKeys.signature, entitlementLimitTypes.included, null, "Signatures"),
assignment(featureKeys.billing, entitlementLimitTypes.included, null, "Billing"),
assignment(featureKeys.search, entitlementLimitTypes.included, null, "Search"),
assignment(featureKeys.automation, entitlementLimitTypes.unlimited, null, "Automation"),
assignment(featureKeys.supportTickets, entitlementLimitTypes.unlimited, null, "Support tickets"),
assignment(featureKeys.knowledgeBaseRead, entitlementLimitTypes.included, null, "Knowledge base reading"),
assignment(featureKeys.knowledgeBaseTenant, entitlementLimitTypes.included, null, "Knowledge base authoring"),
assignment(featureKeys.users, entitlementLimitTypes.unlimited, null, "Users are governed by seat packages"),
assignment(featureKeys.emailMarketing, entitlementLimitTypes.notIncluded, null, "Email marketing is available as a paid add-on"),
assignment(featureKeys.emailInbox, entitlementLimitTypes.included, null, "Mailbox sync"),
assignment(featureKeys.importedLists, entitlementLimitTypes.notIncluded, null, "Imported lists require the email marketing add-on"),
assignment(featureKeys.crmBasedLists, entitlementLimitTypes.notIncluded, null, "CRM based lists require the email marketing add-on"),
assignment(featureKeys.onboarding, entitlementLimitTypes.included, null, "Onboarding"),
assignment(featureKeys.api, entitlementLimitTypes.included, null, "API access"),
assignment(featureKeys.workflowEngine, entitlementLimitTypes.unlimited, null, "Workflows"),
assignment(featureKeys.mcp, entitlementLimitTypes.included, null, "Tenant MCP"),
assignment(featureKeys.advancedBuilder, entitlementLimitTypes.included, null, "Advanced builder"),
assignment(featureKeys.importExport, entitlementLimitTypes.unlimited, null, "Import and export"),
assignment(featureKeys.rateLimitPerMinute, entitlementLimitTypes.unlimited, null, "Requests per minute"),
assignment(featureKeys.rateLimitPerSecond, entitlementLimitTypes.unlimited, null, "Requests per second"),
assignment(featureKeys.prioritySupport, entitlementLimitTypes.included, null, "Support"),
]);
function standardPlanFeatures(customerPortalIncluded: boolean): readonly EntitlementPlanFeatureAssignment[] {
return [
...hiveGridCoreFeatures,
assignment(
featureKeys.customerPortal,
customerPortalIncluded ? entitlementLimitTypes.included : entitlementLimitTypes.notIncluded,
null,
customerPortalIncluded ? "Customer portal included" : "Customer portal available as a paid add-on"
),
assignment(featureKeys.customerPortalCustomDomain, entitlementLimitTypes.notIncluded, null, "Customer portal custom domain requires one-time setup"),
];
}
export const standardEntitlementPlans = Object.freeze([
planStub(
entitlementPlanIds.starter,
{
publicName: "Starter",
description: "CRM basics, support tickets, knowledge base reading, and small team limits.",
sortOrder: 10,
},
[
assignment(featureKeys.dashboard, entitlementLimitTypes.included, null, "Dashboard included"),
assignment(featureKeys.crmBasic, entitlementLimitTypes.included, null, "CRM basics included"),
assignment(featureKeys.leads, entitlementLimitTypes.included, null, "Lead inbox included"),
assignment(featureKeys.projects, entitlementLimitTypes.included, null, "Projects and pipelines included"),
assignment(featureKeys.files, entitlementLimitTypes.included, null, "Central file storage included"),
assignment(featureKeys.tasks, entitlementLimitTypes.included, null, "Task management included"),
assignment(featureKeys.hr, entitlementLimitTypes.included, null, "HR hub included"),
assignment(featureKeys.integrations, entitlementLimitTypes.included, null, "Integrations framework included"),
assignment(featureKeys.booking, entitlementLimitTypes.included, null, "Booking module included"),
assignment(featureKeys.forms, entitlementLimitTypes.included, null, "Forms module included"),
assignment(featureKeys.signature, entitlementLimitTypes.included, null, "Signature module included"),
assignment(featureKeys.billing, entitlementLimitTypes.included, null, "Billing module included"),
assignment(featureKeys.search, entitlementLimitTypes.included, null, "Global search included"),
assignment(featureKeys.automation, entitlementLimitTypes.notIncluded, null, "Automation engine not included"),
assignment(featureKeys.supportTickets, entitlementLimitTypes.monthly, 50, "50 support tickets per month"),
assignment(featureKeys.knowledgeBaseRead, entitlementLimitTypes.included, null, "Global and tenant knowledge base reading"),
assignment(featureKeys.knowledgeBaseTenant, entitlementLimitTypes.notIncluded, null, "Tenant knowledge base authoring not included"),
assignment(featureKeys.users, entitlementLimitTypes.max, 3, "Up to 3 users"),
assignment(featureKeys.emailMarketing, entitlementLimitTypes.notIncluded, null, "Email marketing not included"),
assignment(featureKeys.emailInbox, entitlementLimitTypes.notIncluded, null, "Mailbox sync not included"),
assignment(featureKeys.importedLists, entitlementLimitTypes.notIncluded, null, "Imported lists not included"),
assignment(featureKeys.crmBasedLists, entitlementLimitTypes.notIncluded, null, "CRM based lists not included"),
assignment(featureKeys.onboarding, entitlementLimitTypes.notIncluded, null, "Onboarding builder not included"),
assignment(featureKeys.api, entitlementLimitTypes.notIncluded, null, "API access not included"),
assignment(featureKeys.workflowEngine, entitlementLimitTypes.notIncluded, null, "Workflow engine not included"),
assignment(featureKeys.mcp, entitlementLimitTypes.notIncluded, null, "Tenant MCP not included"),
assignment(featureKeys.advancedBuilder, entitlementLimitTypes.notIncluded, null, "Advanced builder not included"),
assignment(featureKeys.importExport, entitlementLimitTypes.monthly, 25, "25 import/export operations per month"),
assignment(featureKeys.rateLimitPerMinute, entitlementLimitTypes.max, 60, "60 requests per minute"),
assignment(featureKeys.rateLimitPerSecond, entitlementLimitTypes.max, 2, "2 requests per second"),
assignment(featureKeys.prioritySupport, entitlementLimitTypes.notIncluded, null, "Community support"),
assignment(featureKeys.credits, entitlementLimitTypes.monthly, 250, "250 AI credits per month"),
assignment(featureKeys.privateGenerations, entitlementLimitTypes.notIncluded, null, "Shared generation visibility"),
]
{ publicName: "Core", description: "HiveGrid Core with the Core seat and storage package.", sortOrder: 10 },
standardPlanFeatures(false)
),
planStub(
entitlementPlanIds.pro,
{
publicName: "Pro",
description: "Production CRM SaaS plan with marketing, onboarding, API, and AI credits.",
sortOrder: 20,
},
[
assignment(featureKeys.dashboard, entitlementLimitTypes.included, null, "Dashboard included"),
assignment(featureKeys.crmBasic, entitlementLimitTypes.included, null, "CRM basics included"),
assignment(featureKeys.leads, entitlementLimitTypes.included, null, "Lead inbox included"),
assignment(featureKeys.projects, entitlementLimitTypes.included, null, "Projects and pipelines included"),
assignment(featureKeys.files, entitlementLimitTypes.included, null, "Central file storage included"),
assignment(featureKeys.tasks, entitlementLimitTypes.included, null, "Task management included"),
assignment(featureKeys.hr, entitlementLimitTypes.included, null, "HR hub included"),
assignment(featureKeys.integrations, entitlementLimitTypes.included, null, "Integrations framework included"),
assignment(featureKeys.booking, entitlementLimitTypes.included, null, "Booking module included"),
assignment(featureKeys.forms, entitlementLimitTypes.included, null, "Forms module included"),
assignment(featureKeys.signature, entitlementLimitTypes.included, null, "Signature module included"),
assignment(featureKeys.billing, entitlementLimitTypes.included, null, "Billing module included"),
assignment(featureKeys.search, entitlementLimitTypes.included, null, "Global search included"),
assignment(featureKeys.automation, entitlementLimitTypes.notIncluded, null, "Automation engine not included"),
assignment(featureKeys.supportTickets, entitlementLimitTypes.monthly, 500, "500 support tickets per month"),
assignment(featureKeys.knowledgeBaseRead, entitlementLimitTypes.included, null, "Global and tenant knowledge base reading"),
assignment(featureKeys.knowledgeBaseTenant, entitlementLimitTypes.included, null, "Tenant knowledge base authoring included"),
assignment(featureKeys.users, entitlementLimitTypes.max, 10, "Up to 10 users"),
assignment(featureKeys.emailMarketing, entitlementLimitTypes.monthly, 5000, "5,000 marketing sends per month"),
assignment(featureKeys.emailInbox, entitlementLimitTypes.included, null, "Mailbox sync (Gmail/Microsoft) included"),
assignment(featureKeys.importedLists, entitlementLimitTypes.included, null, "Imported lists included"),
assignment(featureKeys.crmBasedLists, entitlementLimitTypes.included, null, "CRM based lists included"),
assignment(featureKeys.onboarding, entitlementLimitTypes.included, null, "Onboarding builder included"),
assignment(featureKeys.api, entitlementLimitTypes.included, null, "API access included"),
assignment(featureKeys.workflowEngine, entitlementLimitTypes.notIncluded, null, "Workflow engine not included"),
assignment(featureKeys.mcp, entitlementLimitTypes.notIncluded, null, "Tenant MCP not included"),
assignment(featureKeys.advancedBuilder, entitlementLimitTypes.notIncluded, null, "Advanced builder not included"),
assignment(featureKeys.importExport, entitlementLimitTypes.monthly, 500, "500 import/export operations per month"),
assignment(featureKeys.rateLimitPerMinute, entitlementLimitTypes.max, 600, "600 requests per minute"),
assignment(featureKeys.rateLimitPerSecond, entitlementLimitTypes.max, 10, "10 requests per second"),
assignment(featureKeys.prioritySupport, entitlementLimitTypes.included, null, "Priority support included"),
assignment(featureKeys.credits, entitlementLimitTypes.monthly, 5000, "5,000 credits per month"),
assignment(featureKeys.privateGenerations, entitlementLimitTypes.included, null, "Private generation visibility"),
]
{ publicName: "Swarm", description: "HiveGrid Core with the Swarm seat and storage package.", sortOrder: 20 },
standardPlanFeatures(false)
),
planStub(
entitlementPlanIds.business,
{
publicName: "Business",
description: "Advanced CRM SaaS plan with workflow automation, MCP, customization, and high limits.",
sortOrder: 30,
},
[
assignment(featureKeys.dashboard, entitlementLimitTypes.included, null, "Dashboard included"),
assignment(featureKeys.crmBasic, entitlementLimitTypes.included, null, "CRM basics included"),
assignment(featureKeys.leads, entitlementLimitTypes.included, null, "Lead inbox included"),
assignment(featureKeys.projects, entitlementLimitTypes.included, null, "Projects and pipelines included"),
assignment(featureKeys.files, entitlementLimitTypes.included, null, "Central file storage included"),
assignment(featureKeys.tasks, entitlementLimitTypes.included, null, "Task management included"),
assignment(featureKeys.hr, entitlementLimitTypes.included, null, "HR hub included"),
assignment(featureKeys.integrations, entitlementLimitTypes.included, null, "Integrations framework included"),
assignment(featureKeys.booking, entitlementLimitTypes.included, null, "Booking module included"),
assignment(featureKeys.forms, entitlementLimitTypes.included, null, "Forms module included"),
assignment(featureKeys.signature, entitlementLimitTypes.included, null, "Signature module included"),
assignment(featureKeys.billing, entitlementLimitTypes.included, null, "Billing module included"),
assignment(featureKeys.search, entitlementLimitTypes.included, null, "Global search included"),
assignment(featureKeys.automation, entitlementLimitTypes.monthly, 10000, "10,000 automation runs per month"),
assignment(featureKeys.supportTickets, entitlementLimitTypes.unlimited, null, "Unlimited support tickets"),
assignment(featureKeys.knowledgeBaseRead, entitlementLimitTypes.included, null, "Global and tenant knowledge base reading"),
assignment(featureKeys.knowledgeBaseTenant, entitlementLimitTypes.included, null, "Tenant knowledge base authoring included"),
assignment(featureKeys.users, entitlementLimitTypes.unlimited, null, "Unlimited users"),
assignment(featureKeys.emailMarketing, entitlementLimitTypes.monthly, 50000, "50,000 marketing sends per month"),
assignment(featureKeys.emailInbox, entitlementLimitTypes.included, null, "Mailbox sync (Gmail/Microsoft) included"),
assignment(featureKeys.importedLists, entitlementLimitTypes.included, null, "Imported lists included"),
assignment(featureKeys.crmBasedLists, entitlementLimitTypes.included, null, "CRM based lists included"),
assignment(featureKeys.onboarding, entitlementLimitTypes.included, null, "Onboarding builder included"),
assignment(featureKeys.api, entitlementLimitTypes.included, null, "API access included"),
assignment(featureKeys.workflowEngine, entitlementLimitTypes.monthly, 10000, "10,000 workflow runs per month"),
assignment(featureKeys.mcp, entitlementLimitTypes.included, null, "Tenant MCP included when the blueprint enables it"),
assignment(featureKeys.advancedBuilder, entitlementLimitTypes.included, null, "Advanced builder included"),
assignment(featureKeys.importExport, entitlementLimitTypes.monthly, 10000, "10,000 import/export operations per month"),
assignment(featureKeys.rateLimitPerMinute, entitlementLimitTypes.max, 3000, "3,000 requests per minute"),
assignment(featureKeys.rateLimitPerSecond, entitlementLimitTypes.max, 50, "50 requests per second"),
assignment(featureKeys.prioritySupport, entitlementLimitTypes.included, null, "Priority support included"),
assignment(featureKeys.credits, entitlementLimitTypes.monthly, 50000, "50,000 credits per month"),
assignment(featureKeys.privateGenerations, entitlementLimitTypes.included, null, "Private generation visibility"),
]
{ publicName: "Colony", description: "HiveGrid Core with the Colony seat and storage package.", sortOrder: 30 },
standardPlanFeatures(true)
),
] as const satisfies readonly EntitlementPlanStub[]);
@@ -5,14 +5,15 @@ import { entitlementLimitTypes, evaluateProductAccess, featureKeys, productBluep
const crmSaas = productBlueprintIds.crmSaas;
describe("evaluateProductAccess denied-entitlement passthrough", () => {
it("returns the missing-subscription entitlement under inherit without running the role gate", () => {
it("returns the missing-subscription entitlement for an add-on under inherit without running the role gate", () => {
// Email-Marketing is a real add-on (not core-included), so a tenant without an active
// subscription is denied and the decision short-circuits before the RBAC gate.
const decision = evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.crmBasic,
featureKey: featureKeys.emailMarketing,
hasSubscription: false,
limitType: entitlementLimitTypes.included,
// A valid permission is supplied, but the denied entitlement must short-circuit before the gate.
tenantRolePermissionNames: ["app.dashboard.view"],
tenantRolePermissionNames: ["app.settings.roles.set"],
});
expect(decision).toMatchObject({
@@ -24,6 +25,82 @@ describe("evaluateProductAccess denied-entitlement passthrough", () => {
expect(decision.requiredTenantRolePermission).toBeUndefined();
});
it("includes a core module without a subscription (Fundament D: plan-gate removed)", () => {
// crm-basic is a core module, so a tenant without an active subscription still gets
// access. The RBAC gate stays enforced, so a valid permission is supplied.
const decision = evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.crmBasic,
hasSubscription: false,
tenantRolePermissionNames: ["app.dashboard.view"],
});
expect(decision).toMatchObject({
allowed: true,
reason: "included",
blueprintId: crmSaas,
tenantOverride: "inherit",
requiredTenantRolePermission: "app.dashboard.view",
});
});
it("includes team chat without a subscription while preserving its tenant role gate", () => {
const decision = evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.chat,
hasSubscription: false,
tenantRolePermissionNames: ["chat.read_own_channels"],
});
expect(decision).toMatchObject({
allowed: true,
reason: "included",
blueprintId: crmSaas,
tenantOverride: "inherit",
requiredTenantRolePermission: "chat.read_own_channels",
});
});
it("allows a core module under an enabled override even when the feature is not tenant-toggleable", () => {
// dashboard/crm-basic are core modules (includedInCore) but not tenant-toggleable. A
// seed/admin that sets an "enabled" override on them (as the demo tenant does for every
// core feature) must NOT be denied with tenant-override-not-toggleable — core is always on.
const decision = evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.crmBasic,
hasSubscription: false,
tenantOverride: "enabled",
tenantRolePermissionNames: ["app.dashboard.view"],
});
expect(decision).toMatchObject({
allowed: true,
reason: "included",
blueprintId: crmSaas,
tenantOverride: "enabled",
requiredTenantRolePermission: "app.dashboard.view",
});
});
it("still rejects an enabled override on a non-toggleable add-on (cannot self-enable a paid add-on)", () => {
// ai-credits is an add-on (not core-included) and not tenant-toggleable, so an "enabled"
// override must stay rejected — the core carve-out above must not leak to add-ons.
const decision = evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.credits,
hasSubscription: false,
tenantOverride: "enabled",
tenantRolePermissionNames: ["app.dashboard.view"],
});
expect(decision).toMatchObject({
allowed: false,
reason: "tenant-override-not-toggleable",
blueprintId: crmSaas,
tenantOverride: "enabled",
});
});
it("passes an exhausted monthly quota straight through under an inherited override", () => {
const decision = evaluateProductAccess({
blueprintId: crmSaas,
@@ -151,6 +151,23 @@ describe("evaluateProductAccess", () => {
});
});
it("cannot self-enable contract-backed portal rights through TenantFeatureOverride", () => {
expect(
evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.customerPortal,
hasSubscription: true,
limitType: entitlementLimitTypes.notIncluded,
tenantOverride: "enabled",
tenantRolePermissionNames: ["portal.admin"],
})
).toMatchObject({
allowed: false,
reason: "tenant-override-not-toggleable",
featureKey: featureKeys.customerPortal,
});
});
it("treats a missing role permission list as no permissions", () => {
expect(
evaluateProductAccess({
@@ -58,7 +58,13 @@ export function evaluateProductAccess(input: ProductAccessInput): ProductAccessD
};
}
if (tenantOverride === "enabled" && !blueprintFeature.tenantToggleable) {
// A non-toggleable feature cannot be self-enabled by a tenant override — EXCEPT for
// core modules. Fundament D guarantees every tenant already receives each core module
// (`includedInCore`), so a redundant "enabled" override on a non-toggleable core module
// (e.g. dashboard, crm-basic, users) is a harmless no-op, not a denial. Real add-ons
// (`includedInCore: false`, e.g. Email-Marketing credits) keep the not-toggleable
// rejection: a tenant must not self-enable an add-on it did not purchase.
if (tenantOverride === "enabled" && !blueprintFeature.tenantToggleable && blueprintFeature.includedInCore !== true) {
return {
...base,
allowed: false,
@@ -76,7 +82,16 @@ export function evaluateProductAccess(input: ProductAccessInput): ProductAccessD
period: input.period,
});
if (!entitlement.allowed && tenantOverride !== "enabled") {
// Fundament D: core modules are always included. A tenant without an active
// subscription (or on a plan that lists the feature as not-included/exhausted) still
// gets full access to every core module — the plan-gate is removed for core. Only
// real add-ons (Email-Marketing) keep the subscription plan-gate and fall through to
// the denied passthrough below. The tenant role permission (RBAC) check further down
// is NOT a plan-gate: it stays enforced for core and add-on features alike.
const includedInCore = blueprintFeature.includedInCore === true;
const entitlementAllowed = entitlement.allowed || includedInCore;
if (!entitlementAllowed && tenantOverride !== "enabled") {
return { ...entitlement, blueprintId: input.blueprintId, tenantOverride };
}
@@ -98,7 +113,9 @@ export function evaluateProductAccess(input: ProductAccessInput): ProductAccessD
blueprintId: input.blueprintId,
tenantOverride,
allowed: true,
reason: tenantOverride === "enabled" && !entitlement.allowed ? "included" : entitlement.reason,
// Access rescued by core-inclusion or an explicit enabled override: the underlying
// entitlement reason is a denial, so surface a clean "included" instead.
reason: entitlement.allowed ? entitlement.reason : "included",
requiredTenantRolePermission: requiredPermission,
};
}
@@ -0,0 +1,55 @@
import { describe, expect, it } from "vitest";
import { adviseRegistrationPlan, REGISTRATION_MAX_SEAT_QUANTITY } from "./registration-plan-advisor.js";
describe("registration plan advisor", () => {
it("recommends Core while small extra-seat quantities are still cheaper than an upgrade", () => {
const advice = adviseRegistrationPlan({ officeSeatQuantity: 3, fieldSeatQuantity: 6 });
expect(advice.recommendedPlanCode).toBe("starter");
expect(advice.options.map(({ planCode, recommended, breakdown }) => ({
planCode,
recommended,
net: breakdown.recurringNetAmountCents,
}))).toEqual([
{ planCode: "starter", recommended: true, net: 28_300 },
{ planCode: "pro", recommended: false, net: 49_900 },
{ planCode: "business", recommended: false, net: 99_900 },
]);
});
it("recommends Swarm from the complete base-plus-extra-seat price", () => {
const advice = adviseRegistrationPlan({ officeSeatQuantity: 5, fieldSeatQuantity: 15 });
expect(advice.recommendedPlanCode).toBe("pro");
expect(advice.options.find((option) => option.planCode === "starter")?.breakdown).toMatchObject({
extraOfficeSeatQuantity: 3,
extraFieldSeatQuantity: 10,
recurringNetAmountCents: 62_600,
});
expect(advice.options.find((option) => option.planCode === "pro")?.breakdown.recurringNetAmountCents).toBe(49_900);
});
it("recommends Colony only when it is actually cheaper than Swarm with extras", () => {
expect(adviseRegistrationPlan({ officeSeatQuantity: 10, fieldSeatQuantity: 30 }).recommendedPlanCode).toBe("pro");
expect(adviseRegistrationPlan({ officeSeatQuantity: 12, fieldSeatQuantity: 35 }).recommendedPlanCode).toBe("business");
});
it("uses the stable catalog order as the only tie-breaker", () => {
const advice = adviseRegistrationPlan({ officeSeatQuantity: 1, fieldSeatQuantity: 0 });
const minimum = Math.min(...advice.options.map((option) => option.breakdown.recurringNetAmountCents));
const firstMinimum = advice.options.find((option) => option.breakdown.recurringNetAmountCents === minimum);
expect(advice.recommendedPlanCode).toBe(firstMinimum?.planCode);
expect(advice.options.map((option) => option.planCode)).toEqual(["starter", "pro", "business"]);
});
it.each([
{ officeSeatQuantity: 0, fieldSeatQuantity: 1 },
{ officeSeatQuantity: 1.5, fieldSeatQuantity: 1 },
{ officeSeatQuantity: 1, fieldSeatQuantity: -1 },
{ officeSeatQuantity: 1, fieldSeatQuantity: REGISTRATION_MAX_SEAT_QUANTITY + 1 },
])("fails closed for invalid registration quantities: %o", (input) => {
expect(() => adviseRegistrationPlan(input)).toThrow(RangeError);
});
});
@@ -0,0 +1,73 @@
import {
billingCadences,
calculateBillingCatalogPrice,
hiveGridBasePlans,
type BillingCatalogPriceBreakdown,
} from "./commercial-catalog.js";
import type { EntitlementPlanId } from "./plans.js";
export const REGISTRATION_MAX_SEAT_QUANTITY = 10_000;
export type RegistrationPlanAdviceOption = {
readonly planCode: EntitlementPlanId;
readonly publicName: "Core" | "Swarm" | "Colony";
readonly breakdown: BillingCatalogPriceBreakdown;
readonly recommended: boolean;
};
export type RegistrationPlanAdvice = {
readonly officeSeatQuantity: number;
readonly fieldSeatQuantity: number;
readonly recommendedPlanCode: EntitlementPlanId;
readonly options: readonly RegistrationPlanAdviceOption[];
};
function requireRegistrationSeatQuantity(value: number, label: string, minimum: number): number {
if (!Number.isSafeInteger(value) || value < minimum || value > REGISTRATION_MAX_SEAT_QUANTITY) {
throw new RangeError(`${label} must be a safe integer between ${minimum} and ${REGISTRATION_MAX_SEAT_QUANTITY}.`);
}
return value;
}
/**
* Recommends the cheapest monthly HiveGrid base-plan configuration for a team.
*
* The catalog order is the deterministic tie-breaker: Core, then Swarm, then
* Colony. This function deliberately compares the complete recurring net
* amount including extra seats instead of upgrading as soon as an included
* quantity is exceeded.
*/
export function adviseRegistrationPlan(input: {
readonly officeSeatQuantity: number;
readonly fieldSeatQuantity: number;
}): RegistrationPlanAdvice {
const officeSeatQuantity = requireRegistrationSeatQuantity(input.officeSeatQuantity, "officeSeatQuantity", 1);
const fieldSeatQuantity = requireRegistrationSeatQuantity(input.fieldSeatQuantity, "fieldSeatQuantity", 0);
const pricedOptions = hiveGridBasePlans.map((plan) => ({
planCode: plan.technicalCode,
publicName: plan.publicName,
breakdown: calculateBillingCatalogPrice({
planCode: plan.technicalCode,
cadence: billingCadences.monthly,
officeSeatQuantity,
fieldSeatQuantity,
}),
}));
const recommended = pricedOptions.reduce((cheapest, candidate) =>
candidate.breakdown.recurringNetAmountCents < cheapest.breakdown.recurringNetAmountCents ? candidate : cheapest
);
return Object.freeze({
officeSeatQuantity,
fieldSeatQuantity,
recommendedPlanCode: recommended.planCode,
options: Object.freeze(
pricedOptions.map((option) =>
Object.freeze({
...option,
recommended: option.planCode === recommended.planCode,
})
)
),
});
}
@@ -0,0 +1,92 @@
import { describe, expect, it } from "vitest";
import { annualSepaExtraPriceEur, getSeatPackage, isSeatPackageId, listSeatPackageIds, resolveSeatPackageId, seatPackageIds, seatPackages } from "./seat-packages.js";
describe("seat-package catalog", () => {
it("defines exactly the three commercial packages", () => {
expect(listSeatPackageIds()).toEqual([seatPackageIds.starter, seatPackageIds.team, seatPackageIds.business]);
});
it("carries the Kostenmodell prices (Stand 07.07.) verbatim", () => {
expect(getSeatPackage("starter")).toEqual({
id: "starter",
monthlyEur: 199,
annualSepaEur: 179,
seats: {
office: { included: 2, extraPriceEur: 59 },
field: { included: 5, extraPriceEur: 25 },
},
storage: { includedGb: 100, perAdditionalSeatGb: 10 },
});
expect(getSeatPackage("team")).toEqual({
id: "team",
monthlyEur: 499,
annualSepaEur: 449,
seats: {
office: { included: 5, extraPriceEur: 39 },
field: { included: 15, extraPriceEur: 19 },
},
storage: { includedGb: 500, perAdditionalSeatGb: 20 },
});
expect(getSeatPackage("business")).toEqual({
id: "business",
monthlyEur: 999,
annualSepaEur: 899,
seats: {
office: { included: 10, extraPriceEur: 35 },
field: { included: 30, extraPriceEur: 15 },
},
storage: { includedGb: 2_000, perAdditionalSeatGb: 40 },
});
});
it("returns undefined for an unknown package id", () => {
expect(getSeatPackage("enterprise")).toBeUndefined();
expect(isSeatPackageId("enterprise")).toBe(false);
expect(isSeatPackageId("team")).toBe(true);
expect(isSeatPackageId(null)).toBe(false);
});
it("derives the annual-SEPA extra price with the 10% advantage", () => {
expect(annualSepaExtraPriceEur(59)).toBeCloseTo(53.1, 5);
expect(annualSepaExtraPriceEur(25)).toBeCloseTo(22.5, 5);
});
it("freezes the catalog entries", () => {
expect(Object.isFrozen(seatPackages)).toBe(true);
expect(Object.isFrozen(seatPackages[0])).toBe(true);
expect(Object.isFrozen(seatPackages[0].seats.office)).toBe(true);
expect(Object.isFrozen(seatPackages[0].storage)).toBe(true);
});
});
describe("resolveSeatPackageId (best-effort plan mapping)", () => {
it("matches a package id anywhere in a candidate, case-insensitively", () => {
expect(resolveSeatPackageId("HiveGrid Starter")).toBe("starter");
expect(resolveSeatPackageId("team-annual")).toBe("team");
expect(resolveSeatPackageId("BUSINESS")).toBe("business");
});
it("maps the standard entitlement mid-tier 'pro' plan to the team seat package", () => {
expect(resolveSeatPackageId("pro")).toBe("team");
expect(resolveSeatPackageId("HiveGrid Pro")).toBe("team");
});
it("prefers a direct package-id over the 'pro' alias", () => {
// "Business Pro" must resolve to business, not team.
expect(resolveSeatPackageId("Business Pro")).toBe("business");
});
it("never fires the 'pro' alias on unrelated words", () => {
expect(resolveSeatPackageId("product plan")).toBeNull();
});
it("scans multiple candidates and skips empties", () => {
expect(resolveSeatPackageId(null, "", undefined, "Team Plan")).toBe("team");
});
it("returns null when nothing matches", () => {
expect(resolveSeatPackageId("Enterprise", null)).toBeNull();
expect(resolveSeatPackageId()).toBeNull();
});
});
@@ -0,0 +1,144 @@
import type { SeatType } from "./seats.js";
/**
* Seat-package catalog (Fundament E).
*
* The three commercial base packages bind the subscription price to a fixed
* number of included seats per seat category (`office` = Büro back-office,
* `field` = Baustelle on-site). Every seat above the included amount is billed
* as an "extra seat" at the per-category extra price.
*
* Prices originate from `docs/pricing-draft.md` and are consumed by the
* versioned commercial catalog. This module stays pure data + pure helpers; the
* Lago/Mollie materialization and recurring-payment flow live in the billing
* catalog/operator services rather than calling a provider from this package.
*/
export const seatPackageIds = Object.freeze({
starter: "starter",
team: "team",
business: "business",
} as const);
export type SeatPackageId = (typeof seatPackageIds)[keyof typeof seatPackageIds];
/** Per-category commercial terms of a seat package. */
export interface SeatCategoryTerms {
/** Seats of this category included in the base package price. */
readonly included: number;
/** Monthly list price of one extra seat of this category, in whole euros. */
readonly extraPriceEur: number;
}
export interface SeatPackageDefinition {
readonly id: SeatPackageId;
/** Monthly list price of the base package, in whole euros. */
readonly monthlyEur: number;
/** Annual-SEPA monthly-equivalent price of the base package, in whole euros. */
readonly annualSepaEur: number;
/** Commercial terms keyed by seat category so usage math can iterate them. */
readonly seats: Readonly<Record<SeatType, SeatCategoryTerms>>;
/** Shared file-storage pool sold with the package and expanded by extra seats. */
readonly storage: Readonly<{
includedGb: number;
/** Every paid seat above the package allowance expands the shared pool equally. */
perAdditionalSeatGb: number;
}>;
}
/**
* Annual-SEPA extra-seat discount: extra seats booked on the yearly SEPA plan
* carry a 10 % advantage per the Kostenmodell. Exposed so the annual extra price
* is a derived, single-source value rather than a second hardcoded column.
*/
export const ANNUAL_SEPA_EXTRA_DISCOUNT = 0.1;
/** Annual-SEPA per-seat extra price derived from the monthly list extra price. */
export function annualSepaExtraPriceEur(listExtraPriceEur: number): number {
return listExtraPriceEur * (1 - ANNUAL_SEPA_EXTRA_DISCOUNT);
}
export const seatPackages: readonly SeatPackageDefinition[] = Object.freeze([
Object.freeze({
id: seatPackageIds.starter,
monthlyEur: 199,
annualSepaEur: 179,
seats: Object.freeze({
office: Object.freeze({ included: 2, extraPriceEur: 59 }),
field: Object.freeze({ included: 5, extraPriceEur: 25 }),
}),
storage: Object.freeze({
includedGb: 100,
perAdditionalSeatGb: 10,
}),
}),
Object.freeze({
id: seatPackageIds.team,
monthlyEur: 499,
annualSepaEur: 449,
seats: Object.freeze({
office: Object.freeze({ included: 5, extraPriceEur: 39 }),
field: Object.freeze({ included: 15, extraPriceEur: 19 }),
}),
storage: Object.freeze({
includedGb: 500,
perAdditionalSeatGb: 20,
}),
}),
Object.freeze({
id: seatPackageIds.business,
monthlyEur: 999,
annualSepaEur: 899,
seats: Object.freeze({
office: Object.freeze({ included: 10, extraPriceEur: 35 }),
field: Object.freeze({ included: 30, extraPriceEur: 15 }),
}),
storage: Object.freeze({
includedGb: 2_000,
perAdditionalSeatGb: 40,
}),
}),
] as const satisfies readonly SeatPackageDefinition[]);
const seatPackageById = new Map<SeatPackageId, SeatPackageDefinition>(seatPackages.map((pkg) => [pkg.id, pkg]));
export function getSeatPackage(id: SeatPackageId): SeatPackageDefinition;
export function getSeatPackage(id: string): SeatPackageDefinition | undefined;
export function getSeatPackage(id: string): SeatPackageDefinition | undefined {
return seatPackageById.get(id as SeatPackageId);
}
export function listSeatPackageIds(): readonly SeatPackageId[] {
return seatPackages.map((pkg) => pkg.id);
}
export function isSeatPackageId(value: string | null | undefined): value is SeatPackageId {
return value != null && seatPackageById.has(value as SeatPackageId);
}
/**
* Best-effort mapping of a subscription/plan to a seat package.
*
* Fed with candidate strings from the tenant's subscription (product title,
* product code, plan slug). Matches — case-insensitively — a package id anywhere
* in a candidate, so "HiveGrid Team" or "team-annual" both resolve to `team`.
* The `pro` mid-tier of the standard entitlement plans is treated as the `team`
* seat package (same commercial position). Returns `null` when nothing matches,
* so the caller shows the raw seat counts without package limits.
*/
export function resolveSeatPackageId(...candidates: readonly (string | null | undefined)[]): SeatPackageId | null {
const normalized = candidates.map((candidate) => candidate?.trim().toLowerCase() ?? "").filter((value) => value.length > 0);
// First pass: a direct package-id substring always wins.
for (const value of normalized) {
if (value.includes(seatPackageIds.business)) return seatPackageIds.business;
if (value.includes(seatPackageIds.starter)) return seatPackageIds.starter;
if (value.includes(seatPackageIds.team)) return seatPackageIds.team;
}
// Second pass: the standard entitlement mid-tier "pro" plan maps to the `team`
// seat package (same commercial position). Word-boundary match only, so it
// never fires on unrelated words like "product".
for (const value of normalized) {
if (/\bpro\b/.test(value)) return seatPackageIds.team;
}
return null;
}
@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import { getSeatPackage, seatPackageIds } from "./seat-packages.js";
import { computeSeatUsage } from "./seat-usage.js";
const starter = getSeatPackage(seatPackageIds.starter);
const team = getSeatPackage(seatPackageIds.team);
describe("computeSeatUsage", () => {
it("reports no extra when both categories are within the included limit", () => {
const result = computeSeatUsage({ package: starter, officeUsed: 2, fieldUsed: 3 });
expect(result.office).toMatchObject({ included: 2, used: 2, extra: 0, extraCostEur: 0, overLimit: false });
expect(result.field).toMatchObject({ included: 5, used: 3, extra: 0, extraCostEur: 0, overLimit: false });
expect(result.totalExtraCostEur).toBe(0);
expect(result.hasOverage).toBe(false);
});
it("computes extra seats and cost when the office category is over the limit", () => {
// starter: 2 office included at 59 EUR/extra. 5 used => 3 extra => 177 EUR.
const result = computeSeatUsage({ package: starter, officeUsed: 5, fieldUsed: 5 });
expect(result.office).toMatchObject({ included: 2, used: 5, extra: 3, extraPriceEur: 59, extraCostEur: 177, overLimit: true });
expect(result.field).toMatchObject({ extra: 0, overLimit: false });
expect(result.totalExtraCostEur).toBe(177);
expect(result.hasOverage).toBe(true);
});
it("computes extra cost across both categories at once", () => {
// starter: office 3 used => 1 extra × 59 = 59; field 7 used => 2 extra × 25 = 50.
const result = computeSeatUsage({ package: starter, officeUsed: 3, fieldUsed: 7 });
expect(result.office).toMatchObject({ extra: 1, extraCostEur: 59 });
expect(result.field).toMatchObject({ extra: 2, extraCostEur: 50 });
expect(result.totalExtraCostEur).toBe(109);
expect(result.hasOverage).toBe(true);
});
it("boundary: exactly at the included limit is not an overage", () => {
const result = computeSeatUsage({ package: team, officeUsed: 5, fieldUsed: 15 });
expect(result.hasOverage).toBe(false);
expect(result.office.extra).toBe(0);
expect(result.field.extra).toBe(0);
});
it("clamps negative / non-finite used counts to zero", () => {
const result = computeSeatUsage({ package: starter, officeUsed: -4, fieldUsed: Number.NaN });
expect(result.office.used).toBe(0);
expect(result.field.used).toBe(0);
expect(result.hasOverage).toBe(false);
});
it("bills extra seats at the discounted annual-SEPA price when requested", () => {
// starter office extra list price 59 => annual-SEPA 53.1 per seat.
const result = computeSeatUsage({ package: starter, officeUsed: 4, fieldUsed: 0, cadence: "annualSepa" });
expect(result.office.extra).toBe(2);
expect(result.office.extraPriceEur).toBeCloseTo(53.1, 5);
expect(result.office.extraCostEur).toBeCloseTo(106.2, 5);
});
});
@@ -0,0 +1,72 @@
import type { SeatType } from "./seats.js";
import type { SeatPackageDefinition } from "./seat-packages.js";
import { annualSepaExtraPriceEur } from "./seat-packages.js";
/**
* Seat-usage computation (Fundament E).
*
* Pure function: given a seat package and the number of occupied seats per
* category, it derives included / used / extra seats and the resulting extra
* cost. No side effects, no billing-provider calls — this is the in-app
* projection only; real metering/charging is a separate follow-up.
*/
/** Which price column to bill extra seats at. Default is the monthly list price. */
export type SeatBillingCadence = "monthly" | "annualSepa";
export interface ComputeSeatUsageInput {
readonly package: SeatPackageDefinition;
readonly officeUsed: number;
readonly fieldUsed: number;
/** Extra-seat pricing column. Defaults to `monthly`. */
readonly cadence?: SeatBillingCadence;
}
export interface SeatCategoryUsage {
readonly seatType: SeatType;
readonly included: number;
readonly used: number;
/** Seats above the included amount: max(0, used - included). */
readonly extra: number;
/** Per-seat extra price applied (respects the billing cadence), in euros. */
readonly extraPriceEur: number;
/** extra × extraPriceEur, in euros. */
readonly extraCostEur: number;
readonly overLimit: boolean;
}
export interface SeatUsageResult {
readonly office: SeatCategoryUsage;
readonly field: SeatCategoryUsage;
/** Sum of both categories' extra cost, in euros. */
readonly totalExtraCostEur: number;
/** True when either category is over its included limit. */
readonly hasOverage: boolean;
}
function computeCategory(seatType: SeatType, included: number, listExtraPriceEur: number, used: number, cadence: SeatBillingCadence): SeatCategoryUsage {
const safeUsed = Number.isFinite(used) && used > 0 ? Math.trunc(used) : 0;
const extra = Math.max(0, safeUsed - included);
const extraPriceEur = cadence === "annualSepa" ? annualSepaExtraPriceEur(listExtraPriceEur) : listExtraPriceEur;
return {
seatType,
included,
used: safeUsed,
extra,
extraPriceEur,
extraCostEur: extra * extraPriceEur,
overLimit: extra > 0,
};
}
export function computeSeatUsage(input: ComputeSeatUsageInput): SeatUsageResult {
const cadence = input.cadence ?? "monthly";
const office = computeCategory("office", input.package.seats.office.included, input.package.seats.office.extraPriceEur, input.officeUsed, cadence);
const field = computeCategory("field", input.package.seats.field.included, input.package.seats.field.extraPriceEur, input.fieldUsed, cadence);
return {
office,
field,
totalExtraCostEur: office.extraCostEur + field.extraCostEur,
hasOverage: office.overLimit || field.overLimit,
};
}
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { deriveSeatType, SEAT_TYPES } from "./index.js";
describe("deriveSeatType", () => {
it("lets an explicit admin override win over the role-derived seat", () => {
// Override to `field` even though an office role would otherwise promote to office.
expect(deriveSeatType({ roleSeatCategories: ["office"], override: "field" })).toBe("field");
// Override to `office` even though only field roles are present.
expect(deriveSeatType({ roleSeatCategories: ["field"], override: "office" })).toBe("office");
});
it("promotes to office when at least one role is an office role", () => {
expect(deriveSeatType({ roleSeatCategories: ["office"] })).toBe("office");
});
it("stays field when every role is a field role", () => {
expect(deriveSeatType({ roleSeatCategories: ["field", "field"] })).toBe("field");
});
it("defaults to field when the user holds no roles", () => {
expect(deriveSeatType({ roleSeatCategories: [] })).toBe("field");
});
it("promotes a mixed office/field role set to office (the more expensive seat)", () => {
expect(deriveSeatType({ roleSeatCategories: ["field", "office", "field"] })).toBe("office");
});
it("treats a null/undefined override as no override", () => {
expect(deriveSeatType({ roleSeatCategories: ["office"], override: null })).toBe(SEAT_TYPES.office);
expect(deriveSeatType({ roleSeatCategories: ["field"], override: undefined })).toBe(SEAT_TYPES.field);
});
});
@@ -0,0 +1,46 @@
/**
* Seat-type derivation (Fundament C).
*
* A "seat" is the billing bucket / default UI mode a workspace member occupies:
* `office` = back-office desk work, `field` = on-site (Baustelle) work. One human
* occupies exactly one seat.
*
* `SeatType` mirrors the Prisma enum of the same name (`Role.seatCategory`,
* `TenantUser.seatType`). It is redeclared here as a string union so this
* entitlements package stays dependency-free (same convention as `FeatureKey`).
* The app-side server helper feeds the real Prisma enum values into
* `deriveSeatType`, so any divergence between the two surfaces as a compile error
* there rather than silently going unnoticed.
*/
export type SeatType = "office" | "field";
export const SEAT_TYPES = {
office: "office",
field: "field",
} as const satisfies Record<SeatType, SeatType>;
export interface DeriveSeatTypeInput {
/** Seat category of every role the user holds in the tenant. */
readonly roleSeatCategories: readonly SeatType[];
/**
* Explicit `TenantUser.seatType` admin billing override. `null`/`undefined`
* means "no override — derive from the roles".
*/
readonly override?: SeatType | null;
}
/**
* Effective seat of a member:
* 1. an explicit admin override always wins, otherwise
* 2. any `office` role promotes the member to the (more expensive) office seat,
* 3. and a member with only field roles — or no roles at all — stays on a field seat.
*
* "One human, one seat; every office role means an office desk — the pricier one.
* No middle ground."
*/
export function deriveSeatType(input: DeriveSeatTypeInput): SeatType {
if (input.override != null) {
return input.override;
}
return input.roleSeatCategories.some((category) => category === SEAT_TYPES.office) ? SEAT_TYPES.office : SEAT_TYPES.field;
}
@@ -0,0 +1,85 @@
import { describe, expect, it } from "vitest";
import { calculateStorageCapacity, STORAGE_BYTES_PER_GB } from "./storage-capacity.js";
describe("calculateStorageCapacity", () => {
it("combines base, extra-seat, and recurring add-on storage", () => {
expect(
calculateStorageCapacity({
planCode: "starter",
officeSeatQuantity: 4,
fieldSeatQuantity: 6,
storageAddOnCodes: ["storage_100gb", "storage_500gb"],
}),
).toEqual({
planCode: "starter",
includedStorageGb: 100,
additionalSeatStorageGb: 30,
addOnStorageGb: 600,
totalStorageGb: 730,
totalStorageBytes: 730 * STORAGE_BYTES_PER_GB,
});
});
it("does not grant extra storage for seats already included in the package", () => {
expect(
calculateStorageCapacity({
planCode: "pro",
officeSeatQuantity: 5,
fieldSeatQuantity: 15,
}),
).toMatchObject({
includedStorageGb: 500,
additionalSeatStorageGb: 0,
addOnStorageGb: 0,
totalStorageGb: 500,
});
});
it("grows the shared pool with every additional paid license at the plan rate", () => {
expect(
calculateStorageCapacity({
planCode: "pro",
officeSeatQuantity: 6,
fieldSeatQuantity: 16,
}),
).toMatchObject({
includedStorageGb: 500,
additionalSeatStorageGb: 40,
totalStorageGb: 540,
});
expect(
calculateStorageCapacity({
planCode: "business",
officeSeatQuantity: 11,
fieldSeatQuantity: 31,
}),
).toMatchObject({
includedStorageGb: 2_000,
additionalSeatStorageGb: 80,
totalStorageGb: 2_080,
});
});
it("rejects unknown plans, add-ons, and duplicate add-ons", () => {
expect(() =>
calculateStorageCapacity({ planCode: "unknown", officeSeatQuantity: 1, fieldSeatQuantity: 0 }),
).toThrow("Unknown billing plan");
expect(() =>
calculateStorageCapacity({
planCode: "starter",
officeSeatQuantity: 1,
fieldSeatQuantity: 0,
storageAddOnCodes: ["storage_unknown"],
}),
).toThrow("Unknown storage add-on");
expect(() =>
calculateStorageCapacity({
planCode: "starter",
officeSeatQuantity: 1,
fieldSeatQuantity: 0,
storageAddOnCodes: ["storage_100gb", "storage_100gb"],
}),
).toThrow("must be unique");
});
});
@@ -0,0 +1,65 @@
import { getBillingCatalogPlan, getBillingCatalogStorageAddOn, type StorageAddOnCode } from "./commercial-catalog.js";
export const STORAGE_BYTES_PER_GB = 1024 * 1024 * 1024;
export type StorageCapacitySelection = {
readonly planCode: string;
readonly officeSeatQuantity: number;
readonly fieldSeatQuantity: number;
readonly storageAddOnCodes?: readonly (StorageAddOnCode | string)[];
};
export type StorageCapacity = {
readonly planCode: string;
readonly includedStorageGb: number;
readonly additionalSeatStorageGb: number;
readonly addOnStorageGb: number;
readonly totalStorageGb: number;
readonly totalStorageBytes: number;
};
function requireSeatQuantity(value: number, label: string): number {
if (!Number.isSafeInteger(value) || value < 0 || value > 10_000) {
throw new RangeError(`${label} must be a non-negative safe integer up to 10000.`);
}
return value;
}
function safeStorageBytes(totalStorageGb: number): number {
const bytes = totalStorageGb * STORAGE_BYTES_PER_GB;
if (!Number.isSafeInteger(bytes) || bytes < 0) {
throw new RangeError("Storage capacity exceeds the safe integer range.");
}
return bytes;
}
export function calculateStorageCapacity(selection: StorageCapacitySelection): StorageCapacity {
const plan = getBillingCatalogPlan(selection.planCode);
if (!plan) throw new RangeError(`Unknown billing plan: ${selection.planCode}`);
const officeSeatQuantity = requireSeatQuantity(selection.officeSeatQuantity, "officeSeatQuantity");
const fieldSeatQuantity = requireSeatQuantity(selection.fieldSeatQuantity, "fieldSeatQuantity");
const storageAddOnCodes = selection.storageAddOnCodes ?? [];
if (new Set(storageAddOnCodes).size !== storageAddOnCodes.length) {
throw new RangeError("Storage add-on codes must be unique.");
}
const addOnStorageGb = storageAddOnCodes.reduce((total, code) => {
const addOn = getBillingCatalogStorageAddOn(code);
if (!addOn) throw new RangeError(`Unknown storage add-on: ${code}`);
return total + addOn.includedStorageGb;
}, 0);
const additionalSeatQuantity =
Math.max(0, officeSeatQuantity - plan.includedSeats.office) + Math.max(0, fieldSeatQuantity - plan.includedSeats.field);
const additionalSeatStorageGb = additionalSeatQuantity * plan.storagePerAdditionalSeatGb;
const totalStorageGb = plan.includedStorageGb + additionalSeatStorageGb + addOnStorageGb;
return Object.freeze({
planCode: plan.technicalCode,
includedStorageGb: plan.includedStorageGb,
additionalSeatStorageGb,
addOnStorageGb,
totalStorageGb,
totalStorageBytes: safeStorageBytes(totalStorageGb),
});
}