Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+145
-25
@@ -38,6 +38,8 @@ export type TenantBillingState = {
|
||||
|
||||
export type TenantBillingEntitlements = {
|
||||
tenantId: string;
|
||||
status: BillingSubscriptionStatus;
|
||||
readOnly: boolean;
|
||||
planCode: string | null;
|
||||
seatQuantity: number;
|
||||
features: Record<string, TenantBillingEntitlement>;
|
||||
@@ -69,6 +71,7 @@ type TenantBillingProductRow = {
|
||||
id: string;
|
||||
code?: string | null;
|
||||
lagoPlanCode?: string | null;
|
||||
kind?: "base_plan" | "recurring_add_on" | "one_time_setup" | "contract_override";
|
||||
title: string;
|
||||
features: TenantBillingFeatureRow[];
|
||||
};
|
||||
@@ -91,12 +94,49 @@ type TenantBillingSubscriptionRow = {
|
||||
products: TenantBillingProductRow[];
|
||||
};
|
||||
|
||||
export const tenantBillingStateInclude = {
|
||||
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: {
|
||||
include: {
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
customEntitlementPlanId: true,
|
||||
cancelledAt: true,
|
||||
endsAt: true,
|
||||
planCode: true,
|
||||
seatQuantity: true,
|
||||
quantity: true,
|
||||
currentPeriodStart: true,
|
||||
currentPeriodEnd: true,
|
||||
subscriptionProduct: {
|
||||
include: {
|
||||
features: true,
|
||||
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,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -105,7 +145,8 @@ export const tenantBillingStateInclude = {
|
||||
|
||||
export type TenantBillingStateClient = {
|
||||
tenantSubscription: {
|
||||
findUnique(args: { where: { tenantId: string }; include: typeof tenantBillingStateInclude }): Promise<TenantBillingSubscriptionRow | null>;
|
||||
findUnique(args: { where: { tenantId: string }; select: typeof tenantBillingStateSelect }): Promise<TenantBillingSubscriptionRow | null>;
|
||||
findMany(args: { where: { tenantId: { in: string[] } }; select: typeof tenantBillingStateSelect }): Promise<TenantBillingSubscriptionRow[]>;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -121,7 +162,7 @@ function isBillingSubscriptionStatus(value: string | null | undefined): value is
|
||||
|
||||
export function normalizeBillingSubscriptionStatus(
|
||||
value: string | null | undefined,
|
||||
markers: { frozenAt?: Date | null; cancelledAt?: Date | null } = {},
|
||||
markers: { frozenAt?: Date | null; cancelledAt?: Date | null } = {}
|
||||
): BillingSubscriptionStatus {
|
||||
if (markers.cancelledAt) return "cancelled";
|
||||
if (markers.frozenAt) return "frozen";
|
||||
@@ -140,10 +181,18 @@ function positiveInteger(value: number | null | undefined): number | null {
|
||||
|
||||
function activeProducts(products: TenantBillingProductRow[], now: Date): TenantBillingProductRow[] {
|
||||
return products
|
||||
.filter((product) => !product.endsAt || product.endsAt > now)
|
||||
.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 ??
|
||||
@@ -156,13 +205,15 @@ function resolveProductPlanCode(product: TenantBillingProductRow): string | null
|
||||
}
|
||||
|
||||
function resolvePlanCode(subscription: TenantBillingSubscriptionRow | null, products: TenantBillingProductRow[]): string | null {
|
||||
return subscription?.planCode ?? products.map(resolveProductPlanCode).find((value): value is string => Boolean(value)) ?? null;
|
||||
return products.map(resolveProductPlanCode).find((value): value is string => Boolean(value)) ?? subscription?.planCode ?? null;
|
||||
}
|
||||
|
||||
function resolveSeatQuantity(subscription: TenantBillingSubscriptionRow | null, products: TenantBillingProductRow[]): number {
|
||||
return subscription?.seatQuantity && subscription.seatQuantity > 0
|
||||
? subscription.seatQuantity
|
||||
: products.map((product) => positiveInteger(product.seatQuantity) ?? positiveInteger(product.quantity)).find((value): value is number => value !== null) ?? 1;
|
||||
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"> {
|
||||
@@ -204,27 +255,22 @@ function resolveEntitlements(products: TenantBillingProductRow[]): TenantBilling
|
||||
return [...entitlements.values()].sort((left, right) => left.featureKey.localeCompare(right.featureKey));
|
||||
}
|
||||
|
||||
export async function resolveTenantBillingState(
|
||||
tenantId: string,
|
||||
options: { client?: TenantBillingStateClient; now?: Date } = {},
|
||||
): Promise<TenantBillingState> {
|
||||
const subscription = await (options.client ?? getTenantBillingStateClient()).tenantSubscription.findUnique({
|
||||
where: { tenantId },
|
||||
include: tenantBillingStateInclude,
|
||||
});
|
||||
const products = activeProducts(subscription?.products ?? [], options.now ?? new Date());
|
||||
const status = normalizeBillingSubscriptionStatus(subscription?.status, {
|
||||
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 period = resolvePeriod(products);
|
||||
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, products),
|
||||
seatQuantity: resolveSeatQuantity(subscription, products),
|
||||
planCode: resolvePlanCode(subscription, baseProducts),
|
||||
seatQuantity: resolveSeatQuantity(subscription, baseProducts),
|
||||
lagoCustomerId: subscription?.lagoCustomerId ?? null,
|
||||
mollieCustomerId: subscription?.mollieCustomerId ?? null,
|
||||
lastInvoiceExternalId: subscription?.lastInvoiceExternalId ?? null,
|
||||
@@ -240,15 +286,89 @@ export async function resolveTenantBillingState(
|
||||
};
|
||||
}
|
||||
|
||||
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 } = {},
|
||||
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 };
|
||||
}
|
||||
Reference in new issue
Block a user