import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto"; import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod"; import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType"; import { SubscriptionProductDto } from "../../../application/dtos/subscriptions/SubscriptionProductDto"; import { createSubscriptionProduct, createSubscriptionPrice, createSubscriptionFeature, updateSubscriptionProductBillingProviderId, updateSubscriptionPriceBillingProviderId, deleteSubscriptionProduct, updateSubscriptionProduct, deleteSubscriptionFeatures, 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 { addTenantSubscriptionProduct } from "../../db/subscriptions/tenantSubscriptionProducts.db.server"; import EventsService from "../../../modules/events/services/.server/EventsService"; import { SubscriptionSubscribedDto } from "~/modules/events/dtos/SubscriptionSubscribedDto"; import { SubscriptionPriceDto } from "~/application/dtos/subscriptions/SubscriptionPriceDto"; import { getUser } from "../../db/users.db.server"; import { cancelTenantSubscription, clearAllSubscriptionsCache, clearTenantSubscriptionCache, getActiveTenantSubscriptions } from "./subscriptionService"; 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"; 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; tenantSubscription: { upsert(args: { where: { tenantId: string }; create: { tenantId: string; billingProviderCustomerId: string }; update: Record; 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; } function isRecord(value: unknown): value is Record { 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( plan: SubscriptionProductDto, prices: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }[], features: SubscriptionFeatureDto[], usageBasedPrices?: SubscriptionUsageBasedPriceDto[], _t?: TFunction ) { const productBillingProviderId = plan.billingProviderId || localBillingProviderId("product", plan.title); const product = await createSubscriptionProduct({ billingProviderId: productBillingProviderId, order: plan.order, title: plan.title, model: plan.model, description: plan.description ?? null, badge: plan.badge ?? null, groupTitle: plan.groupTitle ?? null, 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, }); if (!product) { throw new Error("Could not create subscription product"); } await Promise.all( prices.map(async (price) => { return await createSubscriptionPrice({ ...price, subscriptionProductId: product.id, billingProviderId: localBillingProviderId("price", `${product.id}_${price.billingPeriod}_${price.currency}_${price.price}`), type: SubscriptionPriceType.RECURRING, billingPeriod: price.billingPeriod, price: price.price, currency: price.currency, trialDays: price.trialDays ?? 0, active: true, }); }) ); await Promise.all( features .sort((a, b) => a.order - b.order) .map(async (feature) => { // Save to db return await createSubscriptionFeature(product.id, feature); }) ); if (usageBasedPrices) { await Promise.all( usageBasedPrices.map(async (usageBasedPrice) => { pricingLogger.info( { op: "createUsageBasedPrice", productId: product.id, billingPeriod: usageBasedPrice.billingPeriod, unit: usageBasedPrice.unit }, "Creating usage-based price" ); const createdPrice = await createSubscriptionUsageBasedPrice({ subscriptionProductId: product.id, billingProviderId: localBillingProviderId( "usage", `${product.id}_${usageBasedPrice.billingPeriod}_${usageBasedPrice.currency}_${usageBasedPrice.unit}` ), billingPeriod: usageBasedPrice.billingPeriod, currency: usageBasedPrice.currency, unit: usageBasedPrice.unit, unitTitle: usageBasedPrice.unitTitle, unitTitlePlural: usageBasedPrice.unitTitlePlural, usageType: usageBasedPrice.usageType, aggregateUsage: usageBasedPrice.aggregateUsage, tiersMode: usageBasedPrice.tiersMode, billingScheme: usageBasedPrice.billingScheme, }); await Promise.all( usageBasedPrice.tiers.map(async (tierPrice) => { await createSubscriptionUsageBasedTier({ subscriptionUsageBasedPriceId: createdPrice.id, from: tierPrice.from, to: tierPrice.to !== null && tierPrice.to !== undefined ? Number(tierPrice.to) : null, perUnitPrice: tierPrice.perUnitPrice !== null && tierPrice.perUnitPrice !== undefined ? Number(tierPrice.perUnitPrice) : null, flatFeePrice: tierPrice.flatFeePrice !== null && tierPrice.flatFeePrice !== undefined ? Number(tierPrice.flatFeePrice) : null, }); }) ); }) ); } } export async function syncPlan( plan: SubscriptionProductDto, prices: { id?: string; billingPeriod: SubscriptionBillingPeriod; price: number; currency: string }[] ) { if (!plan.id) { throw new Error(`Plan ${plan.title} not found on database`); } const productBillingProviderId = plan.billingProviderId || localBillingProviderId("product", plan.title); await updateSubscriptionProductBillingProviderId(plan.id, { billingProviderId: productBillingProviderId, }); prices.map(async (price) => { await updateSubscriptionPriceBillingProviderId(price.id ?? "", { billingProviderId: localBillingProviderId("price", `${plan.id}_${price.billingPeriod}_${price.currency}_${price.price}`), }); }); } export async function updatePlan(plan: SubscriptionProductDto, features: SubscriptionFeatureDto[]) { if (!plan.id) { throw new Error(`Plan ${plan.title} not found on database`); } await updateSubscriptionProduct(plan.id, { order: plan.order, title: plan.title, model: plan.model, description: plan.description ?? null, badge: plan.badge ?? null, groupTitle: plan.groupTitle ?? null, groupDescription: plan.groupDescription ?? null, public: plan.public, billingAddressCollection: plan.billingAddressCollection ?? "auto", hasQuantity: plan.hasQuantity === undefined ? undefined : plan.hasQuantity, canBuyAgain: plan.canBuyAgain === undefined ? undefined : plan.canBuyAgain, }); await deleteSubscriptionFeatures(plan.id ?? ""); await clearAllSubscriptionsCache(); return await Promise.all( features .sort((a, b) => a.order - b.order) .map(async (feature) => { return await createSubscriptionFeature(plan.id ?? "", feature); }) ); } 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", planId: plan.id }, "Deleted subscription product atomically"); } export type CheckoutSessionResponse = { id: string; customer: { id: string; email: string; name: string; }; products: { id: string; title: string; quantity: number; subscription: string | undefined; prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[]; }[]; status: CheckoutSessionStatus | null; source?: "self-service" | "legacy"; }; export async function getAcquiredItemsFromCheckoutSession( session_id: string | null, options?: { tenantId?: string | null } ): Promise { if (!session_id || !options?.tenantId) { pricingLogger.warn({ op: "getAcquiredItemsFromCheckoutSession", sessionId: session_id }, "Checkout session context is missing"); return null; } return await completeSelfServiceCheckout({ sessionId: session_id, tenantId: options.tenantId }); } export async function addTenantProductsFromCheckoutSession({ request, tenantId, user, checkoutSession, createdUserId: _createdUserId, createdTenantId: _createdTenantId, t, }: { request: Request; tenantId: string; user: { id: string; email: string }; checkoutSession: CheckoutSessionResponse; createdUserId?: string | null; createdTenantId?: string | null; t: TFunction; }) { if (checkoutSession.source === "self-service") { return; } clearTenantSubscriptionCache(tenantId); const appConfiguration = await getAppConfiguration({ request }); const tenant = await getTenant(tenantId); if (!tenant) { throw new Error("Tenant not found"); } const tenantSubscription = await getOrPersistTenantSubscription(tenant.id); if (!checkoutSession) { throw new Error(t("settings.subscription.checkout.invalid")); } else { if (!appConfiguration.subscription.multiple) { const hasSubscribed = checkoutSession.products.some((product) => product.subscription); const activeSubscriptions = await getActiveTenantSubscriptions(tenant.id); const recurringSubscriptions = activeSubscriptions?.products.filter((f) => f.billingProviderSubscriptionId) || []; pricingLogger.info( { op: "cancelExistingSubscriptions", tenantId: tenant.id, hasSubscribed, recurringCount: recurringSubscriptions.length, }, "Cancelling existing subscriptions before new subscribe" ); if (hasSubscribed && recurringSubscriptions.length > 0) { await Promise.all( recurringSubscriptions.map(async (recurringSubscription) => { pricingLogger.info( { op: "cancelSubscription", tenantId: tenant.id, subscriptionId: recurringSubscription.id, productId: recurringSubscription.subscriptionProductId, }, "Cancelling tenant subscription" ); return await cancelTenantSubscription(recurringSubscription.id, { tenantId, userId: user.id, t }); }) ); } } await Promise.all( checkoutSession.products.map(async (product) => { // const existingProduct = await getTenantSubscriptionProduct(tenant.id, product.id); // if (!existingProduct) { await addTenantSubscriptionProduct({ tenantSubscriptionId: tenantSubscription.id, subscriptionProductId: product.id ?? "", quantity: product.quantity, billingProviderSubscriptionId: product.subscription ?? "", fromCheckoutSessionId: checkoutSession.id, prices: product.prices.map((price) => { return { subscriptionPriceId: price.flatPrice?.id, subscriptionUsageBasedPriceId: price.usageBasedPrice?.id, }; }), }); // } else { // // is active // if (!existingProduct.endsAt) { // await updateTenantSubscriptionProduct(existingProduct.id, { // quantity: (existingProduct.quantity ?? 1) + 1, // }); // } else { // await updateTenantSubscriptionProduct(existingProduct.id, { // quantity: product.quantity, // endsAt: null, // cancelledAt: null, // }); // } // } const subscriptionProduct = await getSubscriptionProduct(product.id); if (subscriptionProduct) { function checkUpgradeDowngrade(plan: SubscriptionProductDto) { const existing = tenantSubscription?.products.find((f) => f)?.subscriptionProduct; if (existing) { if (plan.order > existing.order) { return { upgrade: true }; } else { return { downgrade: true }; } } } let event: "subscription.subscribed" | "subscription.upgraded" | "subscription.downgraded" = "subscription.subscribed"; if (tenantSubscription.products.length > 0) { const upgradeDowngrade = checkUpgradeDowngrade(subscriptionProduct); if (upgradeDowngrade?.upgrade) { event = "subscription.upgraded"; } else if (upgradeDowngrade?.downgrade) { event = "subscription.downgraded"; } } await EventsService.create({ request, event, tenantId: tenant.id, userId: user.id, data: { user: { id: user.id, email: user.email }, tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug }, subscription: { product: { id: product.id, title: t(subscriptionProduct.title) || subscriptionProduct.title }, session: checkoutSession.id, }, } satisfies SubscriptionSubscribedDto, }); } }) ); } } export async function autosubscribeToTrialOrFreePlan({ request, 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"); 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; }); 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 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( { op: "autosubscribeToTrialOrFreePlan", tenantId: tenant.id, productCount: productsWithTrialDays.length, productIds: productsWithTrialDays.map((p) => p.subscriptionProductId), }, "Autosubscribing tenant to trial/free plan" ); const price = productsWithTrialDays[0]; const subscriptionProductInput = { tenantSubscriptionId: tenantSubscription.id, subscriptionProductId: price.subscriptionProductId, quantity: 1, // 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; const eventArgs = { request, event: "subscription.subscribed", tenantId: tenant.id, userId: user?.id ?? null, data: { 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: 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" ); } else { pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.none", tenantId }, "No auto-subscription products/plans found"); } } catch (e: any) { pricingLogger.error({ ...toSafeErrorLog(e), op: "autosubscribeToTrialOrFreePlan", tenantId }, "Auto-subscribe failed"); if (throwOnFailure) { throw e; } } }