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

@@ -8,23 +8,20 @@ import {
createSubscriptionFeature,
updateSubscriptionProductBillingProviderId,
updateSubscriptionPriceBillingProviderId,
deleteSubscriptionPrice,
deleteSubscriptionProduct,
updateSubscriptionProduct,
deleteSubscriptionFeatures,
deleteSubscriptionUsageBasedTier,
deleteSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedTier,
getSubscriptionProduct,
getAllSubscriptionProducts,
getAllSubscriptionProductsStrict,
} from "../../db/subscriptionProducts.db.server";
import { CheckoutSessionStatus, SubscriptionPrice, SubscriptionUsageBasedPrice } from "@hivegrid/db/prisma-browser";
import { getOrPersistTenantSubscription } from "../../db/tenantSubscriptions.db.server";
import { getTenant } from "../../db/tenants.db.server";
import { SubscriptionUsageBasedPriceDto } from "~/application/dtos/subscriptions/SubscriptionUsageBasedPriceDto";
import { TFunction } from "i18next";
import { TenantTypesApi } from "../../api/.server/TenantTypesApi";
import { addTenantSubscriptionProduct } from "../../db/subscriptions/tenantSubscriptionProducts.db.server";
import EventsService from "../../../modules/events/services/.server/EventsService";
import { SubscriptionSubscribedDto } from "~/modules/events/dtos/SubscriptionSubscribedDto";
@@ -35,28 +32,85 @@ import currencies from "~/application/pricing/currencies";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { createScopedLogger } from "~/utils/logger.server";
import { completeSelfServiceCheckout } from "~/services/billing/self-service-checkout.server";
import { db } from "~/utils/db.server";
import { withIdempotency, type IdempotencyClient } from "@hivegrid/foundation";
import type { TenantBillingClient } from "@hivegrid/db/subscriptions.server";
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
const pricingLogger = createScopedLogger("pricing");
const WORKSPACE_TRIAL_AUTOSUBSCRIBE_SCOPE = "tenant-bootstrap/workspace-trial-autosubscribe-v1";
function localBillingProviderId(prefix: string, seed: string) {
return `local_${prefix}_${seed.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 72)}`;
type WorkspaceTrialMarkerBody =
| {
state: "subscribed";
subscriptionProductId: string;
subscriptionPriceId: string | null;
eventData: SubscriptionSubscribedDto;
}
| {
state: "not-subscribed";
tenantId: string;
reason: "default-currency-unavailable" | "no-eligible-plan";
};
type WorkspaceTrialTransactionClient = IdempotencyClient & {
$executeRaw(query: TemplateStringsArray, ...values: unknown[]): Promise<unknown>;
tenantSubscription: {
upsert(args: {
where: { tenantId: string };
create: { tenantId: string; billingProviderCustomerId: string };
update: Record<string, never>;
select: { id: true };
}): Promise<{ id: string }>;
};
};
function readWorkspaceTrialMarkerBody(body: unknown): WorkspaceTrialMarkerBody {
if (!isRecord(body)) throw new Error("Workspace trial idempotency marker is invalid");
const candidate = body;
if (
candidate.state === "not-subscribed" &&
typeof candidate.tenantId === "string" &&
(candidate.reason === "default-currency-unavailable" || candidate.reason === "no-eligible-plan")
) {
return candidate as WorkspaceTrialMarkerBody;
}
const eventData = candidate.eventData;
const tenant = isRecord(eventData) ? eventData.tenant : null;
const subscription = isRecord(eventData) ? eventData.subscription : null;
const product = isRecord(subscription) ? subscription.product : null;
const user = isRecord(eventData) ? eventData.user : undefined;
if (
candidate.state !== "subscribed" ||
typeof candidate.subscriptionProductId !== "string" ||
!(typeof candidate.subscriptionPriceId === "string" || candidate.subscriptionPriceId === null) ||
!isRecord(eventData) ||
!isRecord(tenant) ||
typeof tenant.id !== "string" ||
typeof tenant.name !== "string" ||
typeof tenant.slug !== "string" ||
!isRecord(subscription) ||
!isRecord(product) ||
product.id !== candidate.subscriptionProductId ||
typeof product.title !== "string" ||
!(subscription.session === undefined || typeof subscription.session === "string") ||
!(user === null || (isRecord(user) && typeof user.id === "string" && typeof user.email === "string"))
) {
throw new Error("Workspace trial idempotency marker is invalid");
}
return candidate as WorkspaceTrialMarkerBody;
}
export async function createPlans(plans: SubscriptionProductDto[]) {
for (const plan of plans.sort((a, b) => a.order - b.order)) {
await createPlan(
plan,
plan.prices.map((price) => {
return {
billingPeriod: price.billingPeriod,
currency: price.currency,
price: Number(price.price),
};
}),
plan.features,
plan.usageBasedPrices
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === "object" && !Array.isArray(value));
}
function localBillingProviderId(prefix: string, seed: string) {
return `local_${prefix}_${seed
.toLowerCase()
.replace(/[^a-z0-9]+/g, "_")
.replace(/^_+|_+$/g, "")
.slice(0, 72)}`;
}
export async function createPlan(
@@ -64,7 +118,7 @@ export async function createPlan(
prices: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }[],
features: SubscriptionFeatureDto[],
usageBasedPrices?: SubscriptionUsageBasedPriceDto[],
t?: TFunction
_t?: TFunction
) {
const productBillingProviderId = plan.billingProviderId || localBillingProviderId("product", plan.title);
const product = await createSubscriptionProduct({
@@ -78,6 +132,7 @@ export async function createPlan(
groupDescription: plan.groupDescription ?? null,
active: plan.active,
public: plan.public,
kind: plan.kind ?? "recurring_add_on",
billingAddressCollection: plan.billingAddressCollection ?? "auto",
hasQuantity: plan.hasQuantity ?? false,
canBuyAgain: plan.canBuyAgain ?? false,
@@ -117,13 +172,13 @@ export async function createPlan(
usageBasedPrices.map(async (usageBasedPrice) => {
pricingLogger.info(
{ op: "createUsageBasedPrice", productId: product.id, billingPeriod: usageBasedPrice.billingPeriod, unit: usageBasedPrice.unit },
"Creating usage-based price",
"Creating usage-based price"
);
const createdPrice = await createSubscriptionUsageBasedPrice({
subscriptionProductId: product.id,
billingProviderId: localBillingProviderId(
"usage",
`${product.id}_${usageBasedPrice.billingPeriod}_${usageBasedPrice.currency}_${usageBasedPrice.unit}`,
`${product.id}_${usageBasedPrice.billingPeriod}_${usageBasedPrice.currency}_${usageBasedPrice.unit}`
),
billingPeriod: usageBasedPrice.billingPeriod,
currency: usageBasedPrice.currency,
@@ -202,42 +257,14 @@ export async function updatePlan(plan: SubscriptionProductDto, features: Subscri
}
export async function deletePlan(plan: SubscriptionProductDto) {
if (!plan.id) throw new Error("Subscription product id is required for deletion");
// Catalog children use ON DELETE CASCADE. One product delete is therefore a
// single atomic statement; a tenant-product FK rejects the whole statement
// without leaving partially deleted prices, tiers, or features behind.
await deleteSubscriptionProduct(plan.id);
await clearAllSubscriptionsCache();
pricingLogger.info({ op: "deletePlan.flatPrices", planId: plan.id, count: plan.prices?.length ?? 0 }, "Deleting flat-rate prices");
await Promise.all(
plan.prices
.map(async (price) => {
if (price.id) {
await deleteSubscriptionPrice(price.id);
}
return null;
})
);
pricingLogger.info(
{ op: "deletePlan.usageBasedPrices", planId: plan.id, count: plan.usageBasedPrices?.length ?? 0 },
"Deleting usage-based prices",
);
if (plan.usageBasedPrices) {
await Promise.all(
plan.usageBasedPrices?.map(async (price) => {
await Promise.all(
price.tiers.map(async (tier) => {
return deleteSubscriptionUsageBasedTier(tier.id);
})
);
await deleteSubscriptionUsageBasedPrice(price.id);
return null;
})
);
}
if (plan.id) {
await deleteSubscriptionProduct(plan.id);
}
pricingLogger.info({ op: "deletePlan", planId: plan.id }, "Deleted subscription product atomically");
}
export type CheckoutSessionResponse = {
@@ -273,8 +300,8 @@ export async function addTenantProductsFromCheckoutSession({
tenantId,
user,
checkoutSession,
createdUserId,
createdTenantId,
createdUserId: _createdUserId,
createdTenantId: _createdTenantId,
t,
}: {
request: Request;
@@ -309,7 +336,7 @@ export async function addTenantProductsFromCheckoutSession({
hasSubscribed,
recurringCount: recurringSubscriptions.length,
},
"Cancelling existing subscriptions before new subscribe",
"Cancelling existing subscriptions before new subscribe"
);
if (hasSubscribed && recurringSubscriptions.length > 0) {
await Promise.all(
@@ -321,7 +348,7 @@ export async function addTenantProductsFromCheckoutSession({
subscriptionId: recurringSubscription.id,
productId: recurringSubscription.subscriptionProductId,
},
"Cancelling tenant subscription",
"Cancelling tenant subscription"
);
return await cancelTenantSubscription(recurringSubscription.id, { tenantId, userId: user.id, t });
})
@@ -395,8 +422,6 @@ export async function addTenantProductsFromCheckoutSession({
},
} satisfies SubscriptionSubscribedDto,
});
await TenantTypesApi.setTenantTypes({ tenantId, subscriptionProduct });
}
})
);
@@ -405,52 +430,158 @@ export async function addTenantProductsFromCheckoutSession({
export async function autosubscribeToTrialOrFreePlan({
request,
t,
t: _t,
tenantId,
userId,
throwOnFailure = false,
idempotencyKey,
}: {
request: Request;
t: TFunction;
tenantId: string;
userId: string | null;
throwOnFailure?: boolean;
idempotencyKey?: string;
}) {
pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Starting auto-subscribe to trial/free plan");
const tenant = await getTenant(tenantId);
if (!tenant) {
pricingLogger.warn({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Tenant not found; skipping");
return;
}
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
const defaultCurrency = currencies.find((f) => f.default)?.value;
if (!defaultCurrency) {
return;
}
const allProducts = await getAllSubscriptionProducts(true);
const productsFree: SubscriptionPriceDto[] = [];
const productsWithTrialDays: SubscriptionPriceDto[] = [];
try {
if (idempotencyKey) {
const markerBody = await db.$transaction(async (tx) => {
const client = tx as unknown as WorkspaceTrialTransactionClient;
const lockKey = `${WORKSPACE_TRIAL_AUTOSUBSCRIBE_SCOPE}:${tenantId}:${idempotencyKey}`;
await client.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))`;
const result = await withIdempotency(
{
tenantId,
scope: WORKSPACE_TRIAL_AUTOSUBSCRIBE_SCOPE,
key: idempotencyKey,
fingerprint: {
version: 1,
tenantId,
userId,
},
},
client,
async () => {
const tenant = await getTenant(tenantId);
if (!tenant) {
throw new Error("Tenant unavailable for auto-subscribe");
}
const defaultCurrency = currencies.find((item) => item.default)?.value;
if (!defaultCurrency) {
return {
status: 204,
body: {
state: "not-subscribed",
tenantId,
reason: "default-currency-unavailable",
} satisfies WorkspaceTrialMarkerBody,
};
}
// Strict reads happen only for a new marker. A committed replay must
// remain dispatchable even if the mutable catalog changes later.
const allProducts = await getAllSubscriptionProductsStrict(true);
const candidate = allProducts
.flatMap((product) => product.prices.map((price) => ({ price, productTitle: product.title })))
.find(({ price }) => price.currency === defaultCurrency && (price.trialDays > 0 || price.price === undefined || Number(price.price) === 0));
pricingLogger.debug(
{ op: "autosubscribeToTrialOrFreePlan.products", tenantId, count: allProducts.length },
"Auto-subscribe candidate products loaded"
);
if (!candidate) {
return {
status: 204,
body: {
state: "not-subscribed",
tenantId,
reason: "no-eligible-plan",
} satisfies WorkspaceTrialMarkerBody,
};
}
const tenantSubscription = await client.tenantSubscription.upsert({
where: { tenantId },
create: { tenantId, billingProviderCustomerId: "" },
update: {},
select: { id: true },
});
const { price, productTitle } = candidate;
const user = userId ? await getUser(userId) : null;
const currentMarkerBody: WorkspaceTrialMarkerBody = {
state: "subscribed",
subscriptionProductId: price.subscriptionProductId,
subscriptionPriceId: price.id ?? null,
eventData: {
user: !user ? null : { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
subscription: {
product: {
id: price.subscriptionProductId,
title: productTitle,
},
},
},
};
await addTenantSubscriptionProduct(
{
tenantSubscriptionId: tenantSubscription.id,
subscriptionProductId: price.subscriptionProductId,
quantity: 1,
billingProviderSubscriptionId: null,
fromCheckoutSessionId: null,
prices: [{ subscriptionPriceId: price.id }],
},
{
invalidateCache: false,
client: tx as unknown as TenantBillingClient,
}
);
return { status: 201, body: currentMarkerBody };
}
);
const stored = readWorkspaceTrialMarkerBody(result.body);
const storedTenantId = stored.state === "subscribed" ? stored.eventData.tenant.id : stored.tenantId;
if (storedTenantId !== tenantId) {
throw new Error("Workspace trial idempotency marker is invalid");
}
return stored;
});
pricingLogger.debug(
{ op: "autosubscribeToTrialOrFreePlan.products", tenantId, count: allProducts.length },
"Auto-subscribe candidate products loaded",
);
allProducts.forEach((product) => {
if (product.prices.length === 0) {
if (markerBody.state === "not-subscribed") {
pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.none", tenantId, reason: markerBody.reason }, "No auto-subscription product was selected");
return;
}
clearTenantSubscriptionCache(tenantId);
await EventsService.createIdempotentTenantEvent({
request,
event: "subscription.subscribed",
tenantId,
userId: markerBody.eventData.user?.id ?? null,
data: markerBody.eventData,
idempotencyKey: `tenant-bootstrap:${tenantId}:${idempotencyKey}:trial-subscribed`,
});
return;
}
const allPricesAreZero = product.prices.every((price) => price.currency === defaultCurrency && (price.price === undefined || Number(price.price) === 0));
if (allPricesAreZero) {
productsFree.push(product.prices[0]);
}
const firstPriceWithTrialDays = product.prices.find(
(price) => price.currency === defaultCurrency && (price.trialDays > 0 || price.price === undefined || Number(price.price) === 0)
);
if (firstPriceWithTrialDays) {
productsWithTrialDays.push(firstPriceWithTrialDays);
}
});
try {
const tenant = await getTenant(tenantId);
if (!tenant) {
throw new Error("Tenant unavailable for auto-subscribe");
}
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
const defaultCurrency = currencies.find((item) => item.default)?.value;
if (!defaultCurrency) return;
const allProducts = throwOnFailure ? await getAllSubscriptionProductsStrict(true) : await getAllSubscriptionProducts(true);
const productsFree: SubscriptionPriceDto[] = [];
const productsWithTrialDays: SubscriptionPriceDto[] = [];
allProducts.forEach((product) => {
if (product.prices.length === 0) return;
const allPricesAreZero = product.prices.every((price) => price.currency === defaultCurrency && (price.price === undefined || Number(price.price) === 0));
if (allPricesAreZero) productsFree.push(product.prices[0]);
const firstPriceWithTrialDays = product.prices.find(
(price) => price.currency === defaultCurrency && (price.trialDays > 0 || price.price === undefined || Number(price.price) === 0)
);
if (firstPriceWithTrialDays) productsWithTrialDays.push(firstPriceWithTrialDays);
});
if (productsWithTrialDays.length > 0) {
pricingLogger.info(
{
@@ -459,23 +590,26 @@ export async function autosubscribeToTrialOrFreePlan({
productCount: productsWithTrialDays.length,
productIds: productsWithTrialDays.map((p) => p.subscriptionProductId),
},
"Autosubscribing tenant to trial/free plan",
"Autosubscribing tenant to trial/free plan"
);
const price = productsWithTrialDays[0];
await addTenantSubscriptionProduct({
const subscriptionProductInput = {
tenantSubscriptionId: tenantSubscription.id,
subscriptionProductId: price.subscriptionProductId,
quantity: 1,
billingProviderSubscriptionId: "",
// Workspace auto-trials are local entitlements only. Provider checkout
// and subscription creation remain exclusive to the explicit billing flow.
billingProviderSubscriptionId: null,
fromCheckoutSessionId: null,
prices: [
{
subscriptionPriceId: price.id,
},
],
});
};
await addTenantSubscriptionProduct(subscriptionProductInput);
const user = userId ? await getUser(userId) : null;
await EventsService.create({
const eventArgs = {
request,
event: "subscription.subscribed",
tenantId: tenant.id,
@@ -484,28 +618,26 @@ export async function autosubscribeToTrialOrFreePlan({
user: !user ? null : { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
subscription: {
product: {
id: price.subscriptionProductId,
title: t(price.subscriptionProduct?.title ?? "") || price.subscriptionProduct?.title || "",
},
product: { id: price.subscriptionProductId, title: price.subscriptionProduct?.title ?? "" },
},
} satisfies SubscriptionSubscribedDto,
});
} as const;
await EventsService.create(eventArgs);
} else if (productsFree.length > 0) {
// TODO(pricing): implement free-plan auto-subscribe. Free plans are planned for
// HiveGrid, so this branch must mirror the trial path above (create the free
// subscription + emit "subscription.subscribed") instead of only logging.
pricingLogger.info(
{ op: "autosubscribeToTrialOrFreePlan.free", tenantId, count: productsFree.length },
"Free products available but auto-subscribe-free path not implemented yet",
"Free products available but auto-subscribe-free path not implemented yet"
);
} else {
pricingLogger.info(
{ op: "autosubscribeToTrialOrFreePlan.none", tenantId },
"No auto-subscription products/plans found",
);
pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.none", tenantId }, "No auto-subscription products/plans found");
}
} catch (e: any) {
pricingLogger.error({ err: e, op: "autosubscribeToTrialOrFreePlan", tenantId }, "Auto-subscribe failed");
pricingLogger.error({ ...toSafeErrorLog(e), op: "autosubscribeToTrialOrFreePlan", tenantId }, "Auto-subscribe failed");
if (throwOnFailure) {
throw e;
}
}
}