Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/utils/services/.server/billingStatusService.ts
T
2026-07-08 16:15:37 +02:00

342 lines
11 KiB
TypeScript

import { resolveTenantBillingState } from "@hivegrid/db/billing-domain.server";
import { db } from "~/utils/db.server";
import { clearTenantSubscriptionCache } from "./subscriptionService";
export const BILLING_MODULE_KEY = "billing";
export const BILLING_USAGE_METRICS = {
automationRuns: "automation_runs",
storageBytes: "storage_bytes",
} as const;
export type BillingUsageMetric = (typeof BILLING_USAGE_METRICS)[keyof typeof BILLING_USAGE_METRICS];
export type TenantBillingStatus = "trial" | "active" | "past_due" | "cancelled" | "frozen";
const SUBSCRIPTION_FEATURE_LIMIT_MONTHLY = 2;
const SUBSCRIPTION_FEATURE_LIMIT_MAX = 3;
const SUBSCRIPTION_FEATURE_LIMIT_UNLIMITED = 4;
export type BillingStatusBannerVm =
| { visible: false }
| {
visible: true;
severity: "info" | "warning" | "danger";
messageKey: string;
actionHref: string;
};
export class BillingUsageQuotaExceededError extends Error {
readonly messageKey = "billing:usage.limitExceeded";
readonly metricCode: BillingUsageMetric;
readonly limit: number;
readonly requestedQuantity: number;
readonly currentQuantity: number;
constructor(input: { metricCode: BillingUsageMetric; limit: number; requestedQuantity: number; currentQuantity: number }) {
super(`Billing usage quota exceeded for ${input.metricCode}.`);
this.name = "BillingUsageQuotaExceededError";
this.metricCode = input.metricCode;
this.limit = input.limit;
this.requestedQuantity = input.requestedQuantity;
this.currentQuantity = input.currentQuantity;
}
}
function normalizeBillingStatus(value: string | null | undefined): TenantBillingStatus {
if (value === "active" || value === "past_due" || value === "cancelled" || value === "frozen") {
return value;
}
return "trial";
}
export function isTenantBillingReadOnly(status: string | null | undefined): boolean {
const normalized = normalizeBillingStatus(status);
return normalized === "past_due" || normalized === "frozen" || normalized === "cancelled";
}
export function buildBillingStatusBannerVm(input: {
status: string | null | undefined;
tenantSlug: string;
trialEndsAt?: Date | string | null;
}): BillingStatusBannerVm {
const status = normalizeBillingStatus(input.status);
const actionHref = `/${input.tenantSlug}/settings/subscription`;
if (status === "trial" && input.trialEndsAt) {
return { visible: true, severity: "info", messageKey: "billing:status.trial", actionHref };
}
if (status === "past_due") {
return { visible: true, severity: "warning", messageKey: "billing:status.pastDue", actionHref };
}
if (status === "frozen") {
return { visible: true, severity: "danger", messageKey: "billing:status.frozen", actionHref };
}
if (status === "cancelled") {
return { visible: true, severity: "warning", messageKey: "billing:status.cancelled", actionHref };
}
return { visible: false };
}
export async function getTenantBillingStatus(tenantId: string) {
return await db.tenantSubscription.findUnique({
where: { tenantId },
select: {
tenantId: true,
status: true,
trialStartsAt: true,
trialEndsAt: true,
pastDueSince: true,
frozenAt: true,
cancelledAt: true,
dunningAttemptCount: true,
lastDunningSentAt: true,
},
});
}
export async function getTenantBillingReadOnlyState(tenantId: string) {
const status = await resolveTenantBillingState(tenantId);
return {
readOnly: status.readOnly,
status: status.status,
};
}
function getPeriodBounds(now: Date) {
return {
periodStart: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1, 0, 0, 0)),
periodEnd: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 0, 0, 0)),
};
}
function toPositiveInteger(value: unknown): number | null {
if (typeof value !== "number" || !Number.isFinite(value)) {
return null;
}
const normalized = Math.trunc(value);
return normalized > 0 ? normalized : null;
}
function readQuotaFromJson(value: unknown, metricCode: BillingUsageMetric): number | null {
const direct = toPositiveInteger(value);
if (direct !== null) return direct;
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const record = value as Record<string, unknown>;
const keyed = toPositiveInteger(record[metricCode]);
if (keyed !== null) return keyed;
if (record.metricCode === metricCode) {
return toPositiveInteger(record.limit) ?? toPositiveInteger(record.monthlyLimit) ?? toPositiveInteger(record.value);
}
const metrics = record.metrics;
if (metrics && typeof metrics === "object" && !Array.isArray(metrics)) {
return toPositiveInteger((metrics as Record<string, unknown>)[metricCode]);
}
return null;
}
function featureMatchesMetric(feature: { code?: string | null; name?: string | null }, metricCode: BillingUsageMetric): boolean {
return feature.code === metricCode || feature.name === metricCode;
}
function resolveFeatureQuota(
feature: { code?: string | null; name?: string | null; quotaValue?: unknown; type: number; value: number },
metricCode: BillingUsageMetric
): number | "unlimited" | null {
const quotaValue = readQuotaFromJson(feature.quotaValue, metricCode);
if (quotaValue !== null) return quotaValue;
if (!featureMatchesMetric(feature, metricCode)) return null;
if (feature.type === SUBSCRIPTION_FEATURE_LIMIT_UNLIMITED) return "unlimited";
if (feature.type === SUBSCRIPTION_FEATURE_LIMIT_MONTHLY || feature.type === SUBSCRIPTION_FEATURE_LIMIT_MAX) {
return toPositiveInteger(feature.value);
}
return null;
}
function resolveMetricQuota(subscription: Awaited<ReturnType<typeof loadTenantSubscriptionForUsage>>, metricCode: BillingUsageMetric): number | null {
let quota: number | null = null;
let unlimited = false;
for (const product of subscription?.products ?? []) {
const quantity = product.quantity && product.quantity > 0 ? product.quantity : 1;
for (const feature of product.subscriptionProduct.features) {
const featureQuota = resolveFeatureQuota(feature, metricCode);
if (featureQuota === "unlimited") {
unlimited = true;
continue;
}
if (featureQuota === null) continue;
const weightedQuota = feature.accumulate ? featureQuota * quantity : featureQuota;
quota = quota === null ? weightedQuota : feature.accumulate ? quota + weightedQuota : Math.max(quota, weightedQuota);
}
}
return unlimited ? null : quota;
}
async function loadTenantSubscriptionForUsage(tenantId: string) {
return await db.tenantSubscription.findUnique({
where: { tenantId },
include: {
products: {
include: {
subscriptionProduct: {
include: {
features: true,
},
},
prices: {
include: {
subscriptionUsageBasedPrice: true,
},
},
},
},
},
});
}
export async function setTenantBillingStatus(
tenantId: string,
data: {
status: TenantBillingStatus;
trialStartsAt?: Date | null;
trialEndsAt?: Date | null;
pastDueSince?: Date | null;
frozenAt?: Date | null;
cancelledAt?: Date | null;
dunningAttemptCount?: number;
lastDunningSentAt?: Date | null;
}
) {
const item = await db.tenantSubscription.upsert({
where: { tenantId },
create: {
tenantId,
status: data.status,
trialStartsAt: data.trialStartsAt,
trialEndsAt: data.trialEndsAt,
pastDueSince: data.pastDueSince,
frozenAt: data.frozenAt,
cancelledAt: data.cancelledAt,
dunningAttemptCount: data.dunningAttemptCount ?? 0,
lastDunningSentAt: data.lastDunningSentAt,
},
update: data,
});
clearTenantSubscriptionCache(tenantId);
return item;
}
export async function recordBillingUsage(input: {
tenantId: string;
metricCode: BillingUsageMetric;
quantity: number;
idempotencyKey?: string | null;
at?: Date;
}) {
if (input.quantity <= 0) {
return null;
}
const idempotencyKey = input.idempotencyKey ?? `${input.metricCode}:${Date.now()}`;
if (input.idempotencyKey) {
const existing = await db.tenantSubscriptionUsageRecord.findUnique({
where: {
tenantId_metricCode_idempotencyKey: {
tenantId: input.tenantId,
metricCode: input.metricCode,
idempotencyKey: input.idempotencyKey,
},
},
});
if (existing) return existing;
}
const subscription = await loadTenantSubscriptionForUsage(input.tenantId);
if (!subscription) {
return null;
}
await assertBillingUsageWithinQuota({ tenantId: input.tenantId, metricCode: input.metricCode, quantity: input.quantity, at: input.at });
const usagePrice = subscription.products
.flatMap((product) => product.prices)
.find((price) => price.subscriptionUsageBasedPrice?.unit === input.metricCode || price.subscriptionUsageBasedPrice?.usageType === input.metricCode);
if (!usagePrice) {
return null;
}
return await db.tenantSubscriptionUsageRecord.upsert({
where: {
tenantId_metricCode_idempotencyKey: {
tenantId: input.tenantId,
metricCode: input.metricCode,
idempotencyKey,
},
},
create: {
tenantId: input.tenantId,
tenantSubscriptionId: subscription.id,
tenantSubscriptionProductPriceId: usagePrice.id,
metricCode: input.metricCode,
timestamp: Math.floor((input.at ?? new Date()).getTime() / 1000),
quantity: input.quantity,
idempotencyKey,
billingProviderSubscriptionItemId: null,
},
update: {
quantity: input.quantity,
},
});
}
export async function getBillingUsageSummary(tenantId: string, now: Date = new Date()) {
const { periodStart, periodEnd } = getPeriodBounds(now);
const subscription = await loadTenantSubscriptionForUsage(tenantId);
const rows = await db.tenantSubscriptionUsageRecord.groupBy({
by: ["metricCode"],
where: {
tenantId,
timestamp: {
gte: Math.floor(periodStart.getTime() / 1000),
lt: Math.floor(periodEnd.getTime() / 1000),
},
},
_sum: { quantity: true },
});
const quantities = new Map(rows.map((row) => [row.metricCode, row._sum.quantity ?? 0]));
const metricCodes = new Set<string>([...Object.values(BILLING_USAGE_METRICS), ...quantities.keys()]);
return {
periodStart,
periodEnd,
metrics: [...metricCodes].map((metricCode) => {
const quantity = quantities.get(metricCode) ?? 0;
const quota = Object.values(BILLING_USAGE_METRICS).includes(metricCode as BillingUsageMetric)
? resolveMetricQuota(subscription, metricCode as BillingUsageMetric)
: null;
return {
metricCode,
quantity,
quota,
remaining: quota === null ? null : Math.max(0, quota - quantity),
exceeded: quota !== null && quantity >= quota,
percentUsed: quota === null ? null : Math.min(100, Math.round((quantity / quota) * 100)),
};
}),
};
}
export async function assertBillingUsageWithinQuota(input: { tenantId: string; metricCode: BillingUsageMetric; quantity: number; at?: Date }) {
const summary = await getBillingUsageSummary(input.tenantId, input.at);
const metric = summary.metrics.find((item) => item.metricCode === input.metricCode);
if (!metric?.quota) return;
if (metric.quantity + input.quantity > metric.quota) {
throw new BillingUsageQuotaExceededError({
metricCode: input.metricCode,
limit: metric.quota,
requestedQuantity: input.quantity,
currentQuantity: metric.quantity,
});
}
}