Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/db/src/billing-domain.server.ts
T

375 lines
13 KiB
TypeScript

import { getDbClient } from "./client.server.js";
export const billingSubscriptionStatuses = ["trial", "active", "past_due", "cancelled", "frozen"] as const;
export type BillingSubscriptionStatus = (typeof billingSubscriptionStatuses)[number];
export type TenantBillingEntitlement = {
featureKey: string;
title: string;
enabled: boolean;
limitType: number;
limit: number;
quotaValue: unknown | null;
accumulate: boolean;
sourceProductId: string;
sourcePlanCode: string | null;
};
export type TenantBillingState = {
tenantId: string;
status: BillingSubscriptionStatus;
readOnly: boolean;
planCode: string | null;
seatQuantity: number;
lagoCustomerId: string | null;
mollieCustomerId: string | null;
lastInvoiceExternalId: string | null;
lastPaymentExternalId: string | null;
trialStartsAt: Date | null;
trialEndsAt: Date | null;
pastDueSince: Date | null;
frozenAt: Date | null;
cancelledAt: Date | null;
currentPeriodStart: Date | null;
currentPeriodEnd: Date | null;
entitlements: TenantBillingEntitlement[];
};
export type TenantBillingEntitlements = {
tenantId: string;
status: BillingSubscriptionStatus;
readOnly: boolean;
planCode: string | null;
seatQuantity: number;
features: Record<string, TenantBillingEntitlement>;
};
type TenantBillingFeatureRow = {
code?: string | null;
name: string;
order: number;
title: string;
type: number;
value: number;
quotaValue?: unknown | null;
accumulate: boolean;
};
type TenantBillingProductRow = {
id: string;
createdAt: Date;
customEntitlementPlanId?: string | null;
cancelledAt?: Date | null;
endsAt?: Date | null;
planCode?: string | null;
seatQuantity?: number | null;
quantity?: number | null;
currentPeriodStart?: Date | null;
currentPeriodEnd?: Date | null;
subscriptionProduct: {
id: string;
code?: string | null;
lagoPlanCode?: string | null;
kind?: "base_plan" | "recurring_add_on" | "one_time_setup" | "contract_override";
title: string;
features: TenantBillingFeatureRow[];
};
};
type TenantBillingSubscriptionRow = {
tenantId: string;
status?: string | null;
planCode?: string | null;
seatQuantity?: number | null;
lagoCustomerId?: string | null;
mollieCustomerId?: string | null;
lastInvoiceExternalId?: string | null;
lastPaymentExternalId?: string | null;
trialStartsAt?: Date | null;
trialEndsAt?: Date | null;
pastDueSince?: Date | null;
frozenAt?: Date | null;
cancelledAt?: Date | null;
products: TenantBillingProductRow[];
};
export const tenantBillingStateSelect = {
tenantId: true,
status: true,
planCode: true,
seatQuantity: true,
lagoCustomerId: true,
mollieCustomerId: true,
lastInvoiceExternalId: true,
lastPaymentExternalId: true,
trialStartsAt: true,
trialEndsAt: true,
pastDueSince: true,
frozenAt: true,
cancelledAt: true,
products: {
select: {
id: true,
createdAt: true,
customEntitlementPlanId: true,
cancelledAt: true,
endsAt: true,
planCode: true,
seatQuantity: true,
quantity: true,
currentPeriodStart: true,
currentPeriodEnd: true,
subscriptionProduct: {
select: {
id: true,
code: true,
lagoPlanCode: true,
kind: true,
features: {
select: {
code: true,
name: true,
title: true,
type: true,
value: true,
quotaValue: true,
accumulate: true,
},
},
},
},
},
},
} as const;
export type TenantBillingStateClient = {
tenantSubscription: {
findUnique(args: { where: { tenantId: string }; select: typeof tenantBillingStateSelect }): Promise<TenantBillingSubscriptionRow | null>;
findMany(args: { where: { tenantId: { in: string[] } }; select: typeof tenantBillingStateSelect }): Promise<TenantBillingSubscriptionRow[]>;
};
};
const NOT_INCLUDED_LIMIT_TYPE = 0;
function getTenantBillingStateClient(): TenantBillingStateClient {
return getDbClient() as unknown as TenantBillingStateClient;
}
function isBillingSubscriptionStatus(value: string | null | undefined): value is BillingSubscriptionStatus {
return billingSubscriptionStatuses.includes(value as BillingSubscriptionStatus);
}
export function normalizeBillingSubscriptionStatus(
value: string | null | undefined,
markers: { frozenAt?: Date | null; cancelledAt?: Date | null } = {}
): BillingSubscriptionStatus {
if (markers.cancelledAt) return "cancelled";
if (markers.frozenAt) return "frozen";
return isBillingSubscriptionStatus(value) ? value : "trial";
}
function isReadOnlyStatus(status: BillingSubscriptionStatus): boolean {
return status === "past_due" || status === "cancelled" || status === "frozen";
}
function positiveInteger(value: number | null | undefined): number | null {
if (typeof value !== "number" || !Number.isFinite(value)) return null;
const normalized = Math.trunc(value);
return normalized > 0 ? normalized : null;
}
function activeProducts(products: TenantBillingProductRow[], now: Date): TenantBillingProductRow[] {
return products
.filter(
(product) => !product.cancelledAt && (!product.currentPeriodStart || product.currentPeriodStart <= now) && (!product.endsAt || product.endsAt > now)
)
.sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime());
}
function basePlanProducts(products: TenantBillingProductRow[]): TenantBillingProductRow[] {
// Undefined is treated as the legacy base-plan value so old fixtures and
// pre-migration rows retain their existing semantics during the recut.
return products.filter((product) => !product.subscriptionProduct.kind || product.subscriptionProduct.kind === "base_plan");
}
function resolveProductPlanCode(product: TenantBillingProductRow): string | null {
return (
product.planCode ??
product.customEntitlementPlanId ??
product.subscriptionProduct.code ??
product.subscriptionProduct.lagoPlanCode ??
product.subscriptionProduct.id ??
null
);
}
function resolvePlanCode(subscription: TenantBillingSubscriptionRow | null, products: TenantBillingProductRow[]): string | null {
return products.map(resolveProductPlanCode).find((value): value is string => Boolean(value)) ?? subscription?.planCode ?? null;
}
function resolveSeatQuantity(subscription: TenantBillingSubscriptionRow | null, products: TenantBillingProductRow[]): number {
return (
products.map((product) => positiveInteger(product.seatQuantity) ?? positiveInteger(product.quantity)).find((value): value is number => value !== null) ??
positiveInteger(subscription?.seatQuantity) ??
1
);
}
function resolvePeriod(products: TenantBillingProductRow[]): Pick<TenantBillingState, "currentPeriodStart" | "currentPeriodEnd"> {
const product = products.find((item) => item.currentPeriodStart || item.currentPeriodEnd);
return {
currentPeriodStart: product?.currentPeriodStart ?? null,
currentPeriodEnd: product?.currentPeriodEnd ?? null,
};
}
function resolveEntitlements(products: TenantBillingProductRow[]): TenantBillingEntitlement[] {
const entitlements = new Map<string, TenantBillingEntitlement>();
for (const product of products) {
const sourcePlanCode = resolveProductPlanCode(product);
for (const feature of product.subscriptionProduct.features) {
const featureKey = feature.code ?? feature.name;
if (!featureKey) continue;
const current = entitlements.get(featureKey);
const next: TenantBillingEntitlement = {
featureKey,
title: feature.title,
enabled: feature.type !== NOT_INCLUDED_LIMIT_TYPE,
limitType: feature.type,
limit: feature.value,
quotaValue: feature.quotaValue ?? null,
accumulate: feature.accumulate,
sourceProductId: product.subscriptionProduct.id,
sourcePlanCode,
};
if (!current || next.limitType > current.limitType || (next.limitType === current.limitType && next.limit > current.limit)) {
entitlements.set(featureKey, next);
}
}
}
return [...entitlements.values()].sort((left, right) => left.featureKey.localeCompare(right.featureKey));
}
function buildTenantBillingState(tenantId: string, subscription: TenantBillingSubscriptionRow | null, now: Date): TenantBillingState {
const products = activeProducts(subscription?.products ?? [], now);
const baseProducts = basePlanProducts(products);
const normalizedStatus = normalizeBillingSubscriptionStatus(subscription?.status, {
frozenAt: subscription?.frozenAt,
cancelledAt: subscription?.cancelledAt,
});
const status = normalizedStatus === "trial" && subscription?.trialEndsAt && subscription.trialEndsAt <= now ? "past_due" : normalizedStatus;
const period = resolvePeriod(baseProducts);
return {
tenantId,
status,
readOnly: isReadOnlyStatus(status),
planCode: resolvePlanCode(subscription, baseProducts),
seatQuantity: resolveSeatQuantity(subscription, baseProducts),
lagoCustomerId: subscription?.lagoCustomerId ?? null,
mollieCustomerId: subscription?.mollieCustomerId ?? null,
lastInvoiceExternalId: subscription?.lastInvoiceExternalId ?? null,
lastPaymentExternalId: subscription?.lastPaymentExternalId ?? null,
trialStartsAt: subscription?.trialStartsAt ?? null,
trialEndsAt: subscription?.trialEndsAt ?? null,
pastDueSince: subscription?.pastDueSince ?? null,
frozenAt: subscription?.frozenAt ?? null,
cancelledAt: subscription?.cancelledAt ?? null,
currentPeriodStart: period.currentPeriodStart,
currentPeriodEnd: period.currentPeriodEnd,
entitlements: resolveEntitlements(products),
};
}
export async function resolveTenantBillingState(
tenantId: string,
options: { client?: TenantBillingStateClient; now?: Date } = {}
): Promise<TenantBillingState> {
const subscription = await (options.client ?? getTenantBillingStateClient()).tenantSubscription.findUnique({
where: { tenantId },
select: tenantBillingStateSelect,
});
return buildTenantBillingState(tenantId, subscription, options.now ?? new Date());
}
export async function resolveTenantBillingStates(
tenantIds: readonly string[],
options: { client?: TenantBillingStateClient; now?: Date } = {}
): Promise<TenantBillingState[]> {
const uniqueTenantIds = [...new Set(tenantIds.filter(Boolean))];
if (uniqueTenantIds.length === 0) return [];
const subscriptions = await (options.client ?? getTenantBillingStateClient()).tenantSubscription.findMany({
where: { tenantId: { in: uniqueTenantIds } },
select: tenantBillingStateSelect,
});
const subscriptionsByTenantId = new Map(subscriptions.map((subscription) => [subscription.tenantId, subscription]));
const now = options.now ?? new Date();
return uniqueTenantIds.map((tenantId) => buildTenantBillingState(tenantId, subscriptionsByTenantId.get(tenantId) ?? null, now));
}
export async function resolveTenantEntitlements(
tenantId: string,
options: { client?: TenantBillingStateClient; now?: Date } = {}
): Promise<TenantBillingEntitlements> {
const state = await resolveTenantBillingState(tenantId, options);
return {
tenantId: state.tenantId,
status: state.status,
readOnly: state.readOnly,
planCode: state.planCode,
seatQuantity: state.seatQuantity,
features: Object.fromEntries(state.entitlements.map((entitlement) => [entitlement.featureKey, entitlement])),
};
}
// --- Dunning decision (AK-P20 DoD 2) -------------------------------------
//
// Pure day-mark evaluation for the past_due dunning sequence. One notice per
// mark (day 1 / 3 / 7 after pastDueSince); after the last mark the tenant is
// frozen. The worker sweep (billing-dunning-sweep) drives this daily per
// tenant inside withTenantRLS(); notify()'s sourceKey upsert dedups repeated
// sends, so re-running a tick is a no-op.
export const BILLING_DUNNING_DAY_MARKS = [1, 3, 7] as const;
const DAY_MS = 24 * 60 * 60 * 1000;
export type BillingDunningDecision =
| { kind: "noop" }
| { kind: "send_dunning"; attempt: 1 | 2 | 3; thresholdDays: 1 | 3 | 7 }
| { kind: "freeze"; thresholdDays: 7 };
export type BillingDunningSubscriptionInput = {
status: string | null;
pastDueSince: Date | string | null;
dunningAttemptCount: number | null;
};
function asDunningDate(value: Date | string | null | undefined): Date | null {
if (!value) return null;
const date = value instanceof Date ? value : new Date(value);
return Number.isNaN(date.getTime()) ? null : date;
}
export function evaluateBillingDunning(input: BillingDunningSubscriptionInput, now: Date = new Date()): BillingDunningDecision {
if (input.status !== "past_due") return { kind: "noop" };
const pastDueSince = asDunningDate(input.pastDueSince);
if (!pastDueSince) return { kind: "noop" };
const elapsedDays = Math.floor((now.getTime() - pastDueSince.getTime()) / DAY_MS);
const attempts = Math.max(0, input.dunningAttemptCount ?? 0);
if (attempts >= BILLING_DUNNING_DAY_MARKS.length) {
return elapsedDays >= 7 ? { kind: "freeze", thresholdDays: 7 } : { kind: "noop" };
}
const thresholdDays = BILLING_DUNNING_DAY_MARKS[attempts];
if (elapsedDays < thresholdDays) return { kind: "noop" };
return { kind: "send_dunning", attempt: (attempts + 1) as 1 | 2 | 3, thresholdDays };
}