342 lines
12 KiB
TypeScript
342 lines
12 KiB
TypeScript
import { resolveTenantBillingState } from "@hivegrid/db/billing-domain.server";
|
|
import { getDbClient } from "@hivegrid/db/client.server";
|
|
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
import { resolveTenantStorageUsage } from "~/services/billing/storage-capacity.server";
|
|
import type { TenantRlsClient } from "~/utils/db/.server/tenantRls.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 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 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(),
|
|
options: { readonly includeCanonicalStorage?: boolean } = {},
|
|
) {
|
|
return runWithRlsContext({ tenantId }, async () => {
|
|
const { periodStart, periodEnd } = getPeriodBounds(now);
|
|
const [subscription, rows, storageUsage] = await Promise.all([
|
|
loadTenantSubscriptionForUsage(tenantId),
|
|
db.tenantSubscriptionUsageRecord.groupBy({
|
|
by: ["metricCode"],
|
|
where: {
|
|
tenantId,
|
|
timestamp: {
|
|
gte: Math.floor(periodStart.getTime() / 1000),
|
|
lt: Math.floor(periodEnd.getTime() / 1000),
|
|
},
|
|
},
|
|
_sum: { quantity: true },
|
|
}),
|
|
options.includeCanonicalStorage === false
|
|
? Promise.resolve(null)
|
|
: resolveTenantStorageUsage(getDbClient() as unknown as TenantRlsClient, tenantId, now),
|
|
]);
|
|
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,
|
|
storageUnavailableReason: storageUsage === null || storageUsage.available ? null : storageUsage.reason,
|
|
metrics: [...metricCodes].map((metricCode) => {
|
|
if (metricCode === BILLING_USAGE_METRICS.storageBytes && storageUsage?.available) {
|
|
const quantity = storageUsage.storedBytes + storageUsage.reservedBytes;
|
|
const quota = storageUsage.capacityBytes;
|
|
return {
|
|
metricCode,
|
|
quantity,
|
|
quota,
|
|
remaining: storageUsage.remainingBytes,
|
|
exceeded: quantity >= quota,
|
|
percentUsed: Math.min(100, Math.round((quantity / quota) * 100)),
|
|
};
|
|
}
|
|
|
|
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, {
|
|
includeCanonicalStorage: input.metricCode === BILLING_USAGE_METRICS.storageBytes,
|
|
});
|
|
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,
|
|
});
|
|
}
|
|
}
|