Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,8 +1,14 @@
import { createLagoBillingGateway, createMolliePaymentGateway, type BillingGateway, type PaymentGateway } from "@hivegrid/billing";
import { loadWebConfig } from "@hivegrid/config";
import { resolveTenantBillingState } from "@hivegrid/db/billing-domain.server";
import { resolveTenantBillingState, resolveTenantBillingStates } from "@hivegrid/db/billing-domain.server";
import { applyLagoSubscriptionSync, applyMolliePaymentSync } from "@hivegrid/db/billing-sync.server";
import {
acquirePortalDomainBillingActivationLocks,
reactivateEntitledPortalDomains,
type PortalDomainBillingFenceClient,
} from "@hivegrid/db/portal-domain-billing-fence.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import type { AdminBillingInputRow } from "@hivegrid/view-models";
import { db } from "~/utils/db.server";
import { invalidateTenantModuleAccessCache } from "~/utils/connector/tenantConnector.server";
@@ -15,7 +21,7 @@ export class AdminBillingError extends Error {
override readonly name = "AdminBillingError";
readonly i18nKey: string;
constructor(readonly code: "TENANT_NOT_FOUND" | "MISSING_PROVIDER_REFERENCE" | "INVALID_PLAN" | "INVALID_SEATS") {
constructor(readonly code: "TENANT_NOT_FOUND" | "MISSING_PROVIDER_REFERENCE" | "INVALID_PLAN" | "INVALID_SEATS" | "INVALID_TRIAL_DAYS") {
super(code);
this.i18nKey = `admin.billing.errors.${code}`;
}
@@ -30,6 +36,7 @@ type TenantSummary = {
export type AdminBillingDeps = {
readonly db: typeof db;
readonly resolveBillingState: typeof resolveTenantBillingState;
readonly resolveBillingStates: typeof resolveTenantBillingStates;
readonly invalidateModuleCache: (tenantId: string) => void;
readonly clearSubscriptionCache: (tenantId: string) => void;
readonly recordAction: (context: AdminActionAuditContext) => Promise<void>;
@@ -64,6 +71,7 @@ function defaultDeps(): AdminBillingDeps {
return {
db,
resolveBillingState: resolveTenantBillingState,
resolveBillingStates: resolveTenantBillingStates,
invalidateModuleCache: invalidateTenantModuleAccessCache,
clearSubscriptionCache: clearTenantSubscriptionCache,
recordAction: recordAdminAction,
@@ -105,30 +113,31 @@ export async function listAdminBillingRows(deps: AdminBillingDeps = defaultDeps(
select: { id: true, name: true, slug: true },
});
return await Promise.all(
tenants.map(async (tenant) => {
const state = await deps.resolveBillingState(tenant.id);
return {
tenantId: tenant.id,
tenantName: tenant.name,
tenantSlug: tenant.slug,
status: state.status,
readOnly: state.readOnly,
planCode: state.planCode,
seatQuantity: state.seatQuantity,
lagoCustomerId: state.lagoCustomerId,
mollieCustomerId: state.mollieCustomerId,
lastInvoiceExternalId: state.lastInvoiceExternalId,
lastPaymentExternalId: state.lastPaymentExternalId,
currentPeriodStart: dateToIso(state.currentPeriodStart),
currentPeriodEnd: dateToIso(state.currentPeriodEnd),
pastDueSince: dateToIso(state.pastDueSince),
frozenAt: dateToIso(state.frozenAt),
cancelledAt: dateToIso(state.cancelledAt),
entitlementCount: state.entitlements.length,
};
})
);
const billingStates = await Promise.all(tenants.map((tenant) => runWithRlsContext({ tenantId: tenant.id }, () => deps.resolveBillingState(tenant.id))));
const billingStatesByTenantId = new Map(billingStates.map((state) => [state.tenantId, state]));
return tenants.map((tenant) => {
const state = billingStatesByTenantId.get(tenant.id);
if (!state) throw new AdminBillingError("TENANT_NOT_FOUND");
return {
tenantId: tenant.id,
tenantName: tenant.name,
tenantSlug: tenant.slug,
status: state.status,
readOnly: state.readOnly,
planCode: state.planCode,
seatQuantity: state.seatQuantity,
lagoCustomerId: state.lagoCustomerId,
mollieCustomerId: state.mollieCustomerId,
lastInvoiceExternalId: state.lastInvoiceExternalId,
lastPaymentExternalId: state.lastPaymentExternalId,
currentPeriodStart: dateToIso(state.currentPeriodStart),
currentPeriodEnd: dateToIso(state.currentPeriodEnd),
pastDueSince: dateToIso(state.pastDueSince),
frozenAt: dateToIso(state.frozenAt),
cancelledAt: dateToIso(state.cancelledAt),
entitlementCount: state.entitlements.length,
};
});
}
export type SetTenantBillingPlanSeatsInput = {
@@ -204,6 +213,10 @@ async function attachMatchingProduct(
}
export async function setTenantBillingPlanSeats(input: SetTenantBillingPlanSeatsInput, deps: AdminBillingDeps = defaultDeps()): Promise<void> {
return runWithRlsContext({ tenantId: input.tenantId }, () => setTenantBillingPlanSeatsInContext(input, deps));
}
async function setTenantBillingPlanSeatsInContext(input: SetTenantBillingPlanSeatsInput, deps: AdminBillingDeps): Promise<void> {
const reason = assertAdminActionReason(input.reason);
const planCode = normalizePlanCode(input.planCode);
const seatQuantity = normalizeSeatQuantity(input.seatQuantity);
@@ -218,6 +231,8 @@ export async function setTenantBillingPlanSeats(input: SetTenantBillingPlanSeats
const product = await findPlanProduct(planCode, deps);
await deps.db.$transaction(async (tx) => {
const billingFenceClient = tx as unknown as PortalDomainBillingFenceClient;
await acquirePortalDomainBillingActivationLocks(billingFenceClient, { tenantId: tenant.id });
const subscription = await tx.tenantSubscription.upsert({
where: { tenantId: tenant.id },
create: {
@@ -239,6 +254,7 @@ export async function setTenantBillingPlanSeats(input: SetTenantBillingPlanSeats
if (product) {
await attachMatchingProduct({ subscriptionId: subscription.id, product, planCode, seatQuantity, now }, tx);
}
await reactivateEntitledPortalDomains(billingFenceClient, { tenantId: tenant.id, now });
});
deps.clearSubscriptionCache(tenant.id);
@@ -257,6 +273,99 @@ export async function setTenantBillingPlanSeats(input: SetTenantBillingPlanSeats
});
}
/** Bounds for a single operator-issued trial extension. */
export const TRIAL_EXTENSION_MIN_DAYS = 1;
export const TRIAL_EXTENSION_MAX_DAYS = 365;
export function normalizeTrialExtensionDays(value: number | string | null | undefined): number {
const days = typeof value === "number" ? value : Number.parseInt(value ?? "", 10);
if (!Number.isInteger(days) || days < TRIAL_EXTENSION_MIN_DAYS || days > TRIAL_EXTENSION_MAX_DAYS) {
throw new AdminBillingError("INVALID_TRIAL_DAYS");
}
return days;
}
/**
* Pure date rule for a trial extension: extends from the current trial end
* when it is still in the future, otherwise from now — an extension can
* therefore never move a trial end backwards.
*/
export function resolveExtendedTrialEnd(currentTrialEnd: Date | null | undefined, now: Date, days: number): Date {
const base = currentTrialEnd && currentTrialEnd.getTime() > now.getTime() ? currentTrialEnd : now;
return new Date(base.getTime() + days * 24 * 60 * 60 * 1000);
}
export type ExtendTenantTrialInput = {
readonly tenantId: string;
readonly days: number | string;
readonly reason: string;
readonly actorUserId: string | null;
readonly actorEmail?: string | null;
readonly request?: Request;
};
/**
* Extends a tenant's trial (DoD #3): reason-gated, 1-365 days, never moves
* the trial end backwards, clears past_due/frozen dunning state and puts
* the subscription back onto `trial`. Audited as `tenant.trialExtended`.
*/
export async function extendTenantTrial(input: ExtendTenantTrialInput, deps: AdminBillingDeps = defaultDeps()): Promise<void> {
return runWithRlsContext({ tenantId: input.tenantId }, () => extendTenantTrialInContext(input, deps));
}
async function extendTenantTrialInContext(input: ExtendTenantTrialInput, deps: AdminBillingDeps): Promise<void> {
const reason = assertAdminActionReason(input.reason);
const days = normalizeTrialExtensionDays(input.days);
const now = deps.now();
const tenant = requireTenant(
await deps.db.tenant.findUnique({
where: { id: input.tenantId },
select: { id: true, name: true, slug: true },
})
);
const existing = await deps.db.tenantSubscription.findUnique({
where: { tenantId: tenant.id },
select: { id: true, status: true, trialEndsAt: true, pastDueSince: true, frozenAt: true },
});
const trialEndsAt = resolveExtendedTrialEnd(existing?.trialEndsAt, now, days);
await deps.db.tenantSubscription.upsert({
where: { tenantId: tenant.id },
create: {
tenantId: tenant.id,
status: "trial",
trialEndsAt,
},
update: {
status: "trial",
trialEndsAt,
pastDueSince: null,
frozenAt: null,
},
});
deps.clearSubscriptionCache(tenant.id);
deps.invalidateModuleCache(tenant.id);
await deps.recordAction({
action: "tenant.trialExtended",
actorUserId: input.actorUserId,
actorEmail: input.actorEmail ?? null,
targetKind: "tenant",
targetId: tenant.id,
reason,
before: {
status: existing?.status ?? null,
trialEndsAt: existing?.trialEndsAt?.toISOString() ?? null,
pastDueSince: existing?.pastDueSince?.toISOString() ?? null,
frozenAt: existing?.frozenAt?.toISOString() ?? null,
},
after: { status: "trial", trialEndsAt: trialEndsAt.toISOString(), extendedByDays: days },
request: input.request,
});
}
export type RequestManualBillingSyncInput = {
readonly tenantId: string;
readonly provider: BillingSyncProvider;
@@ -265,12 +374,15 @@ export type RequestManualBillingSyncInput = {
readonly request?: Request;
};
async function applyManualProviderSync(input: {
provider: BillingSyncProvider;
tenantId: string;
state: Awaited<ReturnType<typeof resolveTenantBillingState>>;
now: Date;
}, deps: AdminBillingDeps): Promise<Record<string, unknown>> {
async function applyManualProviderSync(
input: {
provider: BillingSyncProvider;
tenantId: string;
state: Awaited<ReturnType<typeof resolveTenantBillingState>>;
now: Date;
},
deps: AdminBillingDeps
): Promise<Record<string, unknown>> {
if (input.provider === "lago") {
if (!deps.lagoGateway) throw new AdminBillingError("MISSING_PROVIDER_REFERENCE");
const [customer, invoices] = await Promise.all([
@@ -321,6 +433,10 @@ async function applyManualProviderSync(input: {
}
export async function requestManualBillingSync(input: RequestManualBillingSyncInput, deps: AdminBillingDeps = defaultDeps()): Promise<void> {
return runWithRlsContext({ tenantId: input.tenantId }, () => requestManualBillingSyncInContext(input, deps));
}
async function requestManualBillingSyncInContext(input: RequestManualBillingSyncInput, deps: AdminBillingDeps): Promise<void> {
const tenant = requireTenant(
await deps.db.tenant.findUnique({
where: { id: input.tenantId },