644 lines
28 KiB
TypeScript
644 lines
28 KiB
TypeScript
import {
|
|
buildSelfServiceSubscriptionCatalogVM,
|
|
buildSelfServiceSubscriptionManagementPolicyVM,
|
|
buildSelfServiceSubscriptionPricePreviewVM,
|
|
type SelfServiceSubscriptionCatalogVM,
|
|
type SelfServiceSubscriptionCurrentSelectionVM,
|
|
type SelfServiceSubscriptionPageVM,
|
|
type SelfServiceSubscriptionPlanVM,
|
|
type SelfServiceSubscriptionPricePreviewVM,
|
|
} from "@hivegrid/view-models";
|
|
import type { TenantSubscriptionWithDetails } from "@hivegrid/db/subscriptions.server";
|
|
import { resolveTenantBillingState, type TenantBillingState } from "@hivegrid/db/billing-domain.server";
|
|
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import { getDbClient } from "@hivegrid/db/client.server";
|
|
import {
|
|
annualSepaExtraPriceEur,
|
|
billingCadences,
|
|
calculateBillingCatalogPrice,
|
|
calculateStorageCapacity,
|
|
calculateHiveGridGrossAmountCents,
|
|
calculateHiveGridVatAmountCents,
|
|
emailMarketingCommercialProducts,
|
|
getBillingCatalogStorageAddOn,
|
|
getSeatPackage,
|
|
hiveGridBasePlans,
|
|
hiveGridPurchasableStorageAddOns,
|
|
hiveGridVat,
|
|
type BillingCatalogBasePlan,
|
|
type BillingCatalogPlanVariant,
|
|
type BillingCadence,
|
|
type StorageAddOnCode,
|
|
} from "@hivegrid/entitlements";
|
|
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
|
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
|
|
import { getTenantSeatCounts } from "~/utils/db/permissions/seatType.db.server";
|
|
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
|
import { getTenantSubscription } from "~/utils/db/tenantSubscriptions.db.server";
|
|
import type { TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
|
import { resolveEmailMarketingQuotaUsage } from "./email-marketing-quota.server";
|
|
import { resolveTenantStorageUsage } from "./storage-capacity.server";
|
|
|
|
const MAX_SELF_SERVICE_SEATS = 10_000;
|
|
|
|
export const SELF_SERVICE_SUBSCRIPTION_EFFECTIVE_AT_POLICY = {
|
|
new: "immediate",
|
|
upgrade: "immediate",
|
|
downgrade: "period_end",
|
|
billing_period_change: "period_end",
|
|
seat_increase: "immediate",
|
|
seat_decrease: "period_end",
|
|
configuration_increase: "immediate",
|
|
configuration_decrease: "period_end",
|
|
configuration_change: "period_end",
|
|
unchanged: "immediate",
|
|
} as const;
|
|
|
|
export class SelfServiceSubscriptionValidationError extends Error {
|
|
override readonly name = "SelfServiceSubscriptionValidationError";
|
|
readonly i18nKey: string;
|
|
|
|
constructor(
|
|
readonly code:
|
|
| "PLAN_NOT_FOUND"
|
|
| "PRICE_NOT_FOUND"
|
|
| "PLAN_NOT_PURCHASABLE"
|
|
| "SEAT_QUANTITY_INVALID"
|
|
| "SEAT_QUANTITY_BELOW_USAGE"
|
|
| "CURRENT_PERIOD_END_MISSING"
|
|
) {
|
|
super(code);
|
|
this.i18nKey = `billing:selfServiceSubscription.errors.${code}`;
|
|
}
|
|
}
|
|
|
|
export type SelfServiceSubscriptionSelection = {
|
|
readonly productId: string;
|
|
readonly priceId: string;
|
|
readonly seatQuantity?: number;
|
|
readonly officeSeatQuantity?: number;
|
|
readonly fieldSeatQuantity?: number;
|
|
readonly storageAddOnCodes?: readonly string[];
|
|
};
|
|
|
|
export type SelfServiceSubscriptionServerContext = {
|
|
readonly catalog: SelfServiceSubscriptionCatalogVM;
|
|
readonly minimumSeatQuantity: number;
|
|
readonly seatCounts: { readonly office: number; readonly field: number };
|
|
readonly storageAddOns: readonly {
|
|
readonly code: string;
|
|
readonly title: string;
|
|
readonly storageGb: number;
|
|
readonly amountCents: number;
|
|
readonly currency: "EUR";
|
|
}[];
|
|
readonly emailMarketingAddOns: SelfServiceSubscriptionPageVM["emailMarketingAddOns"];
|
|
readonly usage: NonNullable<SelfServiceSubscriptionPageVM["usage"]>;
|
|
readonly tenantSubscription: TenantSubscriptionWithDetails | null;
|
|
readonly billingState: TenantBillingState;
|
|
readonly currentSelection: SelfServiceSubscriptionCurrentSelectionVM | null;
|
|
};
|
|
|
|
export function resolveOtherActiveRecurringGrossTotalCents(
|
|
tenantSubscription: TenantSubscriptionWithDetails | null,
|
|
options: { readonly excludedProductCodes?: readonly string[]; readonly now?: Date } = {}
|
|
): number | null {
|
|
try {
|
|
const excludedProductCodes = new Set(options.excludedProductCodes ?? []);
|
|
let otherRecurringGrossAmountCents = 0;
|
|
const now = options.now ?? new Date();
|
|
for (const tenantProduct of tenantSubscription?.products ?? []) {
|
|
const productCode = tenantProduct.subscriptionProduct.code?.trim() ?? "";
|
|
if (
|
|
tenantProduct.subscriptionProduct.kind !== "recurring_add_on" ||
|
|
productCode.startsWith("storage_") ||
|
|
excludedProductCodes.has(productCode) ||
|
|
tenantProduct.cancelledAt ||
|
|
(tenantProduct.endsAt && tenantProduct.endsAt <= now)
|
|
) {
|
|
continue;
|
|
}
|
|
const fixedPrices = tenantProduct.prices.filter((candidate) => !candidate.isMetered && candidate.subscriptionPrice);
|
|
if (fixedPrices.length !== 1) return null;
|
|
const fixedPrice = fixedPrices[0]!;
|
|
const currency = fixedPrice.subscriptionPrice!.currency.toUpperCase();
|
|
const quantity = fixedPrice.quantity;
|
|
const unitNetAmountCents = Math.round(Number(fixedPrice.subscriptionPrice!.price) * 100);
|
|
if (currency !== "EUR" || !Number.isSafeInteger(quantity) || quantity < 1 || !Number.isSafeInteger(unitNetAmountCents) || unitNetAmountCents < 0) {
|
|
return null;
|
|
}
|
|
const netAmountCents = unitNetAmountCents * quantity;
|
|
if (!Number.isSafeInteger(netAmountCents)) return null;
|
|
otherRecurringGrossAmountCents += calculateHiveGridGrossAmountCents(netAmountCents);
|
|
if (!Number.isSafeInteger(otherRecurringGrossAmountCents)) return null;
|
|
}
|
|
return otherRecurringGrossAmountCents;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function resolveCurrentRecurringGrossTotalCents(
|
|
context: Pick<SelfServiceSubscriptionServerContext, "catalog" | "currentSelection" | "tenantSubscription">,
|
|
options: { readonly excludedProductCodes?: readonly string[]; readonly now?: Date } = {}
|
|
): number | null {
|
|
const current = context.currentSelection;
|
|
if (!current?.priceId) return null;
|
|
const plan = context.catalog.plans.find((candidate) => candidate.id === current.planId || candidate.code === current.planCode);
|
|
const price = plan?.prices.find((candidate) => candidate.id === current.priceId);
|
|
if (!plan || !price) return null;
|
|
try {
|
|
const baseGrossAmountCents = calculateBillingCatalogPrice({
|
|
planCode: plan.code,
|
|
cadence: cadenceForBillingPeriod(price.billingPeriod),
|
|
officeSeatQuantity: current.officeSeatQuantity ?? current.seatQuantity,
|
|
fieldSeatQuantity: current.fieldSeatQuantity ?? 0,
|
|
storageAddOnCodes: current.storageAddOnCodes ?? [],
|
|
}).recurringGrossAmountCents;
|
|
const otherRecurringGrossAmountCents = resolveOtherActiveRecurringGrossTotalCents(context.tenantSubscription, options);
|
|
if (otherRecurringGrossAmountCents === null) return null;
|
|
const total = baseGrossAmountCents + otherRecurringGrossAmountCents;
|
|
return Number.isSafeInteger(total) ? total : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function toPlanCode(input: { id?: string; code?: string | null; lagoPlanCode?: string | null }): string {
|
|
return input.lagoPlanCode?.trim() || input.code?.trim() || input.id?.trim() || "";
|
|
}
|
|
|
|
const SAFE_CATALOG_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u;
|
|
|
|
function safeCatalogId(value: string | null | undefined): string | null {
|
|
if (!value || value.length > 191 || value !== value.trim() || !SAFE_CATALOG_ID.test(value)) return null;
|
|
return value;
|
|
}
|
|
|
|
function canonicalVariantForBillingPeriod(plan: BillingCatalogBasePlan, billingPeriod: number): BillingCatalogPlanVariant | null {
|
|
const cadence =
|
|
billingPeriod === SubscriptionBillingPeriod.MONTHLY
|
|
? billingCadences.monthly
|
|
: billingPeriod === SubscriptionBillingPeriod.YEARLY
|
|
? billingCadences.annualSepa
|
|
: null;
|
|
return cadence ? (plan.variants.find((variant) => variant.cadence === cadence) ?? null) : null;
|
|
}
|
|
|
|
function exactCanonicalBasePrice(
|
|
price: Awaited<ReturnType<typeof getAllSubscriptionProducts>>[number]["prices"][number],
|
|
plan: BillingCatalogBasePlan
|
|
): { id: string; variant: BillingCatalogPlanVariant; amountCents: number } | null {
|
|
const id = safeCatalogId(price.id);
|
|
const variant = canonicalVariantForBillingPeriod(plan, price.billingPeriod);
|
|
const amount = Number(price.price);
|
|
const scaledAmount = amount * 100;
|
|
const amountCents = Math.round(scaledAmount);
|
|
if (
|
|
!id ||
|
|
!variant ||
|
|
!price.active ||
|
|
price.type !== SubscriptionPriceType.RECURRING ||
|
|
price.currency.toUpperCase() !== "EUR" ||
|
|
!Number.isFinite(scaledAmount) ||
|
|
!Number.isSafeInteger(amountCents) ||
|
|
Math.abs(scaledAmount - amountCents) > Number.EPSILON * Math.max(1, Math.abs(scaledAmount)) ||
|
|
amountCents !== variant.baseAmountCents ||
|
|
price.billingCadence !== variant.cadence ||
|
|
price.contractMonths !== variant.contractMonths ||
|
|
price.requiredPaymentMethod !== variant.requiredPaymentMethod ||
|
|
price.lagoPlanCode?.trim() !== variant.code ||
|
|
price.trialDays !== 0
|
|
) {
|
|
return null;
|
|
}
|
|
return { id, variant, amountCents };
|
|
}
|
|
|
|
function toCatalogPlan(product: Awaited<ReturnType<typeof getAllSubscriptionProducts>>[number]): SelfServiceSubscriptionPlanVM | null {
|
|
if (product.kind !== "base_plan" || !product.active || !product.public) return null;
|
|
const id = safeCatalogId(product.id);
|
|
const code = product.code?.trim() ?? "";
|
|
if (!id || !code || product.lagoPlanCode?.trim() !== code) return null;
|
|
const commercialPlan = hiveGridBasePlans.find((plan) => plan.technicalCode === code);
|
|
if (!commercialPlan) return null;
|
|
const packageId = commercialPlan.seatPackageId;
|
|
const seatPackage = packageId ? getSeatPackage(packageId) : undefined;
|
|
const packageTranslationBase = packageId ? `settings.subscription.checkout.plans.packages.${packageId}` : null;
|
|
|
|
return {
|
|
id,
|
|
code,
|
|
titleKey: packageTranslationBase ? `${packageTranslationBase}.title` : product.title,
|
|
descriptionKey: packageTranslationBase
|
|
? `${packageTranslationBase}.description`
|
|
: product.description?.trim() || "billing:selfServiceSubscription.plans.descriptionFallback",
|
|
badge: product.badge,
|
|
quantityMode: product.hasQuantity ? "per_seat" : "flat",
|
|
packageTerms: seatPackage
|
|
? {
|
|
packageId: seatPackage.id,
|
|
monthlyCents: seatPackage.monthlyEur * 100,
|
|
annualSepaMonthlyEquivalentCents: seatPackage.annualSepaEur * 100,
|
|
officeSeatsIncluded: seatPackage.seats.office.included,
|
|
fieldSeatsIncluded: seatPackage.seats.field.included,
|
|
storageIncludedGb: seatPackage.storage.includedGb,
|
|
storagePerAdditionalSeatGb: seatPackage.storage.perAdditionalSeatGb,
|
|
officeExtraMonthlyCents: seatPackage.seats.office.extraPriceEur * 100,
|
|
fieldExtraMonthlyCents: seatPackage.seats.field.extraPriceEur * 100,
|
|
officeExtraAnnualSepaCents: Math.round(annualSepaExtraPriceEur(seatPackage.seats.office.extraPriceEur) * 100),
|
|
fieldExtraAnnualSepaCents: Math.round(annualSepaExtraPriceEur(seatPackage.seats.field.extraPriceEur) * 100),
|
|
}
|
|
: null,
|
|
// Feature rows remain part of the provider contract for access evaluation,
|
|
// but package selection is no longer presented as a feature-tier matrix.
|
|
features: [],
|
|
prices: product.prices
|
|
.map((price) => ({ price, canonical: exactCanonicalBasePrice(price, commercialPlan) }))
|
|
.filter(
|
|
(candidate): candidate is { price: (typeof product.prices)[number]; canonical: NonNullable<typeof candidate.canonical> } => candidate.canonical !== null
|
|
)
|
|
.sort((left, right) => left.price.billingPeriod - right.price.billingPeriod || left.canonical.id.localeCompare(right.canonical.id))
|
|
.map(({ price, canonical }) => ({
|
|
id: canonical.id,
|
|
billingPeriod: price.billingPeriod,
|
|
currency: "EUR",
|
|
unitAmountCents: canonical.amountCents,
|
|
trialDays: price.trialDays,
|
|
})),
|
|
};
|
|
}
|
|
|
|
export async function loadSelfServiceSubscriptionCatalog(): Promise<SelfServiceSubscriptionCatalogVM> {
|
|
const products = await getAllSubscriptionProducts(true);
|
|
return buildSelfServiceSubscriptionCatalogVM({
|
|
plans: products
|
|
.slice()
|
|
.sort((left, right) => left.order - right.order || (left.id ?? "").localeCompare(right.id ?? ""))
|
|
.map(toCatalogPlan)
|
|
.filter((plan): plan is SelfServiceSubscriptionPlanVM => plan !== null && plan.prices.length > 0),
|
|
});
|
|
}
|
|
|
|
export function resolveSelfServicePreferredSelection(
|
|
catalog: SelfServiceSubscriptionCatalogVM,
|
|
requestedPriceId: string | null | undefined,
|
|
requestedSeatQuantities?: { readonly officeSeatQuantity: number; readonly fieldSeatQuantity: number } | null
|
|
): { planId: string; priceId: string; officeSeatQuantity?: number; fieldSeatQuantity?: number } | null {
|
|
const priceId = requestedPriceId?.trim() ?? "";
|
|
if (!priceId) return null;
|
|
for (const plan of catalog.plans) {
|
|
if (plan.prices.some((price) => price.id === priceId)) {
|
|
return {
|
|
planId: plan.id,
|
|
priceId,
|
|
...(requestedSeatQuantities
|
|
? {
|
|
officeSeatQuantity: requestedSeatQuantities.officeSeatQuantity,
|
|
fieldSeatQuantity: requestedSeatQuantities.fieldSeatQuantity,
|
|
}
|
|
: {}),
|
|
};
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function minimumSeats(counts: { office: number; field: number }): number {
|
|
return Math.max(1, counts.office + counts.field);
|
|
}
|
|
|
|
export async function loadSelfServiceSubscriptionServerContext(tenantId: string, now: Date = new Date()): Promise<SelfServiceSubscriptionServerContext> {
|
|
// Product and price definitions are deliberately global. Tenant billing and
|
|
// occupied-seat reads stay inside an explicit RLS identity boundary.
|
|
const tenantClient = getDbClient() as unknown as TenantRlsClient;
|
|
const [products, [tenantSubscription, seatCounts, billingState, storageUsage, emailMarketingUsage]] = await Promise.all([
|
|
getAllSubscriptionProducts(true),
|
|
runWithRlsContext({ tenantId }, () =>
|
|
Promise.all([
|
|
getTenantSubscription(tenantId),
|
|
getTenantSeatCounts(tenantId),
|
|
resolveTenantBillingState(tenantId, { now }),
|
|
resolveTenantStorageUsage(tenantClient, tenantId, now),
|
|
resolveEmailMarketingQuotaUsage(tenantClient, tenantId, now),
|
|
])
|
|
),
|
|
]);
|
|
const catalog = buildSelfServiceSubscriptionCatalogVM({
|
|
plans: products
|
|
.slice()
|
|
.sort((left, right) => left.order - right.order || (left.id ?? "").localeCompare(right.id ?? ""))
|
|
.map(toCatalogPlan)
|
|
.filter((plan): plan is SelfServiceSubscriptionPlanVM => plan !== null && plan.prices.length > 0),
|
|
});
|
|
return {
|
|
catalog,
|
|
tenantSubscription,
|
|
billingState,
|
|
usage: {
|
|
storage: storageUsage.available
|
|
? {
|
|
status: "ready",
|
|
capacityBytes: storageUsage.capacityBytes,
|
|
storedBytes: storageUsage.storedBytes,
|
|
reservedBytes: storageUsage.reservedBytes,
|
|
remainingBytes: storageUsage.remainingBytes,
|
|
percentUsed: 0,
|
|
}
|
|
: { status: "unavailable", reason: storageUsage.reason },
|
|
emailMarketing: emailMarketingUsage.available
|
|
? {
|
|
status: "ready",
|
|
periodStart: emailMarketingUsage.periodStart.toISOString(),
|
|
periodEnd: emailMarketingUsage.periodEnd.toISOString(),
|
|
limit: emailMarketingUsage.limit,
|
|
used: emailMarketingUsage.used,
|
|
remaining: emailMarketingUsage.remaining,
|
|
percentUsed: null,
|
|
}
|
|
: { status: "unavailable", reason: emailMarketingUsage.reason },
|
|
},
|
|
seatCounts,
|
|
storageAddOns: hiveGridPurchasableStorageAddOns.map((addOn) => ({
|
|
code: addOn.code,
|
|
title: addOn.publicName,
|
|
storageGb: addOn.includedStorageGb,
|
|
amountCents: addOn.amountCents,
|
|
currency: "EUR",
|
|
})),
|
|
emailMarketingAddOns: emailMarketingCommercialProducts.flatMap((definition) => {
|
|
const matches = products.filter((product) => product.code === definition.code);
|
|
if (matches.length !== 1) return [];
|
|
const product = matches[0]!;
|
|
const prices = product.prices.filter(
|
|
(price) =>
|
|
price.active &&
|
|
price.type === SubscriptionPriceType.RECURRING &&
|
|
price.billingPeriod === 3 &&
|
|
price.billingCadence === billingCadences.monthly &&
|
|
price.contractMonths === 1 &&
|
|
price.requiredPaymentMethod === "any" &&
|
|
price.lagoPlanCode?.trim() === definition.code &&
|
|
price.lagoFeeCode?.trim() === definition.code &&
|
|
price.trialDays === 0 &&
|
|
price.currency.toUpperCase() === definition.currency &&
|
|
Math.round(Number(price.price) * 100) === definition.amountCents &&
|
|
Boolean(price.id)
|
|
);
|
|
if (
|
|
product.kind !== "recurring_add_on" ||
|
|
!product.active ||
|
|
!product.public ||
|
|
!product.id ||
|
|
product.lagoPlanCode?.trim() !== definition.code ||
|
|
prices.length !== 1
|
|
) {
|
|
return [];
|
|
}
|
|
const active = Boolean(
|
|
tenantSubscription?.products.some(
|
|
(tenantProduct) =>
|
|
tenantProduct.subscriptionProduct.code === definition.code && !tenantProduct.cancelledAt && (!tenantProduct.endsAt || tenantProduct.endsAt > now)
|
|
)
|
|
);
|
|
return [
|
|
{
|
|
productId: product.id,
|
|
priceId: prices[0]!.id!,
|
|
code: definition.code,
|
|
title: definition.title,
|
|
monthlyEmailLimit: definition.monthlyEmailLimit,
|
|
amountCents: definition.amountCents!,
|
|
vatRateBasisPoints: hiveGridVat.rateBasisPoints,
|
|
vatAmountCents: calculateHiveGridVatAmountCents(definition.amountCents!),
|
|
grossAmountCents: calculateHiveGridGrossAmountCents(definition.amountCents!),
|
|
currency: definition.currency!,
|
|
active,
|
|
},
|
|
];
|
|
}),
|
|
minimumSeatQuantity: minimumSeats(seatCounts),
|
|
currentSelection: resolveCurrentSelection(tenantSubscription, catalog, now),
|
|
};
|
|
}
|
|
|
|
function activeProduct(subscription: TenantSubscriptionWithDetails | null, now: Date) {
|
|
if (!subscription) return null;
|
|
const byPlanCode = subscription.products.find(
|
|
(product) =>
|
|
(product.planCode === subscription.planCode || product.subscriptionProduct.code === subscription.planCode) &&
|
|
!product.cancelledAt &&
|
|
(!product.currentPeriodStart || product.currentPeriodStart <= now) &&
|
|
(!product.endsAt || product.endsAt > now)
|
|
);
|
|
return (
|
|
byPlanCode ??
|
|
subscription.products.find(
|
|
(product) => !product.cancelledAt && (!product.currentPeriodStart || product.currentPeriodStart <= now) && (!product.endsAt || product.endsAt > now)
|
|
) ??
|
|
null
|
|
);
|
|
}
|
|
|
|
function isProviderManagedProduct(product: TenantSubscriptionWithDetails["products"][number] | null): boolean {
|
|
return Boolean(product?.lagoSubscriptionId?.trim() || product?.billingProviderSubscriptionId?.trim());
|
|
}
|
|
|
|
function resolveCurrentSelection(
|
|
subscription: TenantSubscriptionWithDetails | null,
|
|
catalog: SelfServiceSubscriptionCatalogVM,
|
|
now: Date
|
|
): SelfServiceSubscriptionCurrentSelectionVM | null {
|
|
const product = activeProduct(subscription, now);
|
|
if (!subscription || !product) return null;
|
|
const code = toPlanCode(product.subscriptionProduct) || product.planCode?.trim() || subscription.planCode?.trim() || "";
|
|
const plan = catalog.plans.find((candidate) => candidate.id === product.subscriptionProductId || candidate.code === code);
|
|
if (!plan) return null;
|
|
const linkedPriceId = product.prices.find((price) => !price.isMetered && price.subscriptionPriceId)?.subscriptionPriceId ?? null;
|
|
const priceId = linkedPriceId && plan.prices.some((price) => price.id === linkedPriceId) ? linkedPriceId : null;
|
|
return {
|
|
planId: plan.id,
|
|
planCode: plan.code,
|
|
priceId,
|
|
seatQuantity: Math.max(1, product.seatQuantity ?? subscription.seatQuantity ?? product.quantity ?? 1),
|
|
...(positiveRoleSeatQuantity(product.officeSeatQuantity ?? subscription.officeSeatQuantity) !== null
|
|
? { officeSeatQuantity: positiveRoleSeatQuantity(product.officeSeatQuantity ?? subscription.officeSeatQuantity)! }
|
|
: {}),
|
|
...(positiveRoleSeatQuantity(product.fieldSeatQuantity ?? subscription.fieldSeatQuantity) !== null
|
|
? { fieldSeatQuantity: positiveRoleSeatQuantity(product.fieldSeatQuantity ?? subscription.fieldSeatQuantity)! }
|
|
: {}),
|
|
storageAddOnCodes: [
|
|
...new Set([
|
|
...(product.storageAddOnCodes ?? subscription.storageAddOnCodes ?? []),
|
|
...subscription.products
|
|
.filter(
|
|
(candidate) =>
|
|
candidate.subscriptionProduct.kind === "recurring_add_on" &&
|
|
candidate.subscriptionProduct.code?.startsWith("storage_") &&
|
|
!candidate.cancelledAt &&
|
|
(!candidate.endsAt || candidate.endsAt > now)
|
|
)
|
|
.map((candidate) => candidate.subscriptionProduct.code!),
|
|
]),
|
|
].sort(),
|
|
};
|
|
}
|
|
|
|
function positiveRoleSeatQuantity(value: number | null | undefined): number | null {
|
|
return Number.isSafeInteger(value) && value! > 0 ? value! : null;
|
|
}
|
|
|
|
function requireRoleSeatQuantity(value: number, minimum: number): number {
|
|
if (!Number.isSafeInteger(value) || value < 0 || value > MAX_SELF_SERVICE_SEATS) {
|
|
throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_INVALID");
|
|
}
|
|
if (value < minimum) {
|
|
throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_BELOW_USAGE");
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function selectedRoleSeats(selection: SelfServiceSubscriptionSelection, minimum: { office: number; field: number }): { office: number; field: number } {
|
|
if (selection.officeSeatQuantity !== undefined || selection.fieldSeatQuantity !== undefined) {
|
|
return {
|
|
office: requireRoleSeatQuantity(selection.officeSeatQuantity ?? 0, minimum.office),
|
|
field: requireRoleSeatQuantity(selection.fieldSeatQuantity ?? 0, minimum.field),
|
|
};
|
|
}
|
|
const legacyTotal = selection.seatQuantity;
|
|
if (!Number.isSafeInteger(legacyTotal) || legacyTotal! < 1 || legacyTotal! > MAX_SELF_SERVICE_SEATS) {
|
|
throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_INVALID");
|
|
}
|
|
const minimumTotal = minimum.office + minimum.field;
|
|
if (legacyTotal! < minimumTotal) throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_BELOW_USAGE");
|
|
return {
|
|
office: minimum.office + (legacyTotal! - minimumTotal),
|
|
field: minimum.field,
|
|
};
|
|
}
|
|
|
|
function cadenceForBillingPeriod(billingPeriod: number): BillingCadence {
|
|
return billingPeriod === 4 ? billingCadences.annualSepa : billingCadences.monthly;
|
|
}
|
|
|
|
function requirePurchasableStorageAddOnCodes(
|
|
requestedCodes: readonly string[] | undefined,
|
|
currentCodes: readonly string[]
|
|
): readonly StorageAddOnCode[] | undefined {
|
|
if (requestedCodes === undefined) return undefined;
|
|
const currentCodeSet = new Set(currentCodes);
|
|
for (const code of requestedCodes) {
|
|
const addOn = getBillingCatalogStorageAddOn(code);
|
|
if (!addOn || (!addOn.purchasable && !currentCodeSet.has(code))) {
|
|
throw new SelfServiceSubscriptionValidationError("PLAN_NOT_PURCHASABLE");
|
|
}
|
|
}
|
|
return requestedCodes as readonly StorageAddOnCode[];
|
|
}
|
|
|
|
export async function previewSelfServiceSubscription(
|
|
tenantId: string,
|
|
selection: SelfServiceSubscriptionSelection,
|
|
now: Date = new Date()
|
|
): Promise<SelfServiceSubscriptionPricePreviewVM> {
|
|
const { catalog, tenantSubscription, seatCounts, currentSelection } = await loadSelfServiceSubscriptionServerContext(tenantId, now);
|
|
const selectedPlan = catalog.plans.find((plan) => plan.id === selection.productId);
|
|
if (!selectedPlan) throw new SelfServiceSubscriptionValidationError("PLAN_NOT_PURCHASABLE");
|
|
const selectedPrice = selectedPlan.prices.find((price) => price.id === selection.priceId);
|
|
if (!selectedPrice) throw new SelfServiceSubscriptionValidationError("PRICE_NOT_FOUND");
|
|
const selectedSeats = selectedRoleSeats(selection, seatCounts);
|
|
const selectedSeatQuantity = Math.max(1, selectedSeats.office + selectedSeats.field);
|
|
const selectedStorageAddOnCodes = requirePurchasableStorageAddOnCodes(selection.storageAddOnCodes, currentSelection?.storageAddOnCodes ?? []);
|
|
const priceBreakdown = calculateBillingCatalogPrice({
|
|
planCode: selectedPlan.code,
|
|
cadence: cadenceForBillingPeriod(selectedPrice.billingPeriod),
|
|
officeSeatQuantity: selectedSeats.office,
|
|
fieldSeatQuantity: selectedSeats.field,
|
|
storageAddOnCodes: selectedStorageAddOnCodes,
|
|
});
|
|
const storageCapacity = calculateStorageCapacity({
|
|
planCode: selectedPlan.code,
|
|
officeSeatQuantity: selectedSeats.office,
|
|
fieldSeatQuantity: selectedSeats.field,
|
|
storageAddOnCodes: selectedStorageAddOnCodes,
|
|
});
|
|
|
|
const currentProduct = activeProduct(tenantSubscription, now);
|
|
// Workspace bootstrap assigns a providerless product as a local entitlement.
|
|
// Keep it visible as the current selection, but classify the first explicit
|
|
// Lago/Mollie acquisition as a new billable subscription.
|
|
const billableCurrentProduct = currentProduct && isProviderManagedProduct(currentProduct) ? currentProduct : null;
|
|
const currentCode = billableCurrentProduct
|
|
? toPlanCode(billableCurrentProduct.subscriptionProduct)
|
|
: currentProduct
|
|
? null
|
|
: tenantSubscription?.planCode?.trim() || null;
|
|
const currentPlan = currentCode
|
|
? (catalog.plans.find(
|
|
(plan) => plan.code === currentCode || plan.id === billableCurrentProduct?.subscriptionProductId || plan.code === billableCurrentProduct?.planCode
|
|
) ?? null)
|
|
: null;
|
|
const currentPrice = currentPlan && currentSelection?.priceId ? (currentPlan.prices.find((price) => price.id === currentSelection.priceId) ?? null) : null;
|
|
const currentSeatQuantity = tenantSubscription
|
|
? billableCurrentProduct
|
|
? Math.max(1, billableCurrentProduct.seatQuantity ?? tenantSubscription.seatQuantity ?? billableCurrentProduct.quantity ?? 1)
|
|
: currentProduct
|
|
? 0
|
|
: Math.max(1, tenantSubscription.seatQuantity ?? 1)
|
|
: 0;
|
|
const currentPeriodEnd = billableCurrentProduct?.currentPeriodEnd?.toISOString() ?? null;
|
|
const currentOfficeSeatQuantity = currentSelection?.officeSeatQuantity;
|
|
const currentFieldSeatQuantity = currentSelection?.fieldSeatQuantity;
|
|
const currentStorageAddOnCodes = currentSelection?.storageAddOnCodes ?? [];
|
|
const currentPriceBreakdown =
|
|
currentPlan && currentPrice && currentSelection
|
|
? calculateBillingCatalogPrice({
|
|
planCode: currentPlan.code,
|
|
cadence: cadenceForBillingPeriod(currentPrice.billingPeriod),
|
|
officeSeatQuantity: currentOfficeSeatQuantity ?? currentSelection.seatQuantity,
|
|
fieldSeatQuantity: currentFieldSeatQuantity ?? 0,
|
|
storageAddOnCodes: currentStorageAddOnCodes,
|
|
})
|
|
: null;
|
|
const policy = buildSelfServiceSubscriptionManagementPolicyVM({
|
|
planOrder: catalog.plans.map((plan) => plan.code),
|
|
effectiveAtByChangeKind: SELF_SERVICE_SUBSCRIPTION_EFFECTIVE_AT_POLICY,
|
|
});
|
|
|
|
try {
|
|
return buildSelfServiceSubscriptionPricePreviewVM({
|
|
currentPlan,
|
|
currentPrice,
|
|
currentSeatQuantity,
|
|
currentOfficeSeatQuantity,
|
|
currentFieldSeatQuantity,
|
|
currentStorageAddOnCodes,
|
|
currentRecurringNetTotalCents: currentPriceBreakdown?.recurringNetAmountCents,
|
|
currentPeriodEnd,
|
|
selectedPlan,
|
|
selectedPrice,
|
|
selectedSeatQuantity,
|
|
selectedOfficeSeatQuantity: selectedSeats.office,
|
|
selectedFieldSeatQuantity: selectedSeats.field,
|
|
selectedStorageAddOnCodes: priceBreakdown.storageAddOns.map((addOn) => addOn.code),
|
|
includedStorageGb: storageCapacity.includedStorageGb,
|
|
additionalSeatStorageGb: storageCapacity.additionalSeatStorageGb,
|
|
addOnStorageGb: storageCapacity.addOnStorageGb,
|
|
totalStorageGb: storageCapacity.totalStorageGb,
|
|
baseAmountCents: priceBreakdown.baseAmountCents,
|
|
officeSeatAmountCents: priceBreakdown.officeSeatAmountCents,
|
|
fieldSeatAmountCents: priceBreakdown.fieldSeatAmountCents,
|
|
storageAmountCents: priceBreakdown.storageAmountCents,
|
|
vatRateBasisPoints: priceBreakdown.vatRateBasisPoints,
|
|
vatAmountCents: priceBreakdown.vatAmountCents,
|
|
recurringGrossTotalCents: priceBreakdown.recurringGrossAmountCents,
|
|
policy,
|
|
});
|
|
} catch (error) {
|
|
if (error instanceof Error && error.message.includes("currentPeriodEnd is required")) {
|
|
throw new SelfServiceSubscriptionValidationError("CURRENT_PERIOD_END_MISSING");
|
|
}
|
|
throw error;
|
|
}
|
|
}
|