import { getDbClient, type DbClient } from "./client.server.js"; import { getRlsExecutionContext, runWithRlsContext } from "./rls-context.server.js"; import type { Prisma, SubscriptionFeature, SubscriptionPrice, SubscriptionProduct, SubscriptionUsageBasedPrice, SubscriptionUsageBasedTier, TenantSubscription, TenantSubscriptionProduct, TenantSubscriptionProductPrice, TenantSubscriptionUsageRecord, TenantProductAcquisition, CheckoutSessionStatus, } from "./prisma-browser.js"; export const subscriptionProductKindValues = ["base_plan", "recurring_add_on", "one_time_setup", "contract_override"] as const; export type SubscriptionProductKindValue = (typeof subscriptionProductKindValues)[number]; export type SubscriptionPriceWithProduct = SubscriptionPrice & { subscriptionProduct: SubscriptionProduct; }; export type SubscriptionUsageBasedPriceWithProduct = SubscriptionUsageBasedPrice & { subscriptionProduct: SubscriptionProduct; }; export type SubscriptionProductCreateInput = Pick< SubscriptionProduct, | "billingProviderId" | "order" | "title" | "model" | "description" | "badge" | "groupTitle" | "groupDescription" | "active" | "public" | "billingAddressCollection" | "hasQuantity" | "canBuyAgain" > & Partial> & { kind?: SubscriptionProductKindValue }; export type SubscriptionProductUpdateInput = Partial< Pick< SubscriptionProduct, | "billingProviderId" | "code" | "lagoPlanCode" | "order" | "title" | "model" | "description" | "badge" | "groupTitle" | "groupDescription" | "public" | "billingAddressCollection" | "hasQuantity" | "canBuyAgain" > > & { kind?: SubscriptionProductKindValue }; export type SubscriptionPriceCreateInput = Omit< Pick, "price" > & Partial> & { price: SubscriptionPrice["price"] | number | string; }; export type SubscriptionPriceUpdateInput = Partial< Omit< Pick< SubscriptionPrice, | "billingProviderId" | "lagoPlanCode" | "lagoFeeCode" | "molliePriceReference" | "billingCadence" | "contractMonths" | "requiredPaymentMethod" | "type" | "billingPeriod" | "price" | "currency" | "trialDays" | "active" >, "price" > & { price: SubscriptionPrice["price"] | number | string; } >; export type SubscriptionUsageBasedPriceCreateInput = Pick< SubscriptionUsageBasedPrice, | "subscriptionProductId" | "billingProviderId" | "currency" | "billingPeriod" | "unit" | "unitTitle" | "unitTitlePlural" | "usageType" | "aggregateUsage" | "tiersMode" | "billingScheme" >; export type SubscriptionUsageBasedTierCreateInput = Omit< Pick, "perUnitPrice" | "flatFeePrice" > & { perUnitPrice?: SubscriptionUsageBasedTier["perUnitPrice"] | number | string | null; flatFeePrice?: SubscriptionUsageBasedTier["flatFeePrice"] | number | string | null; }; export type SubscriptionFeatureCreateInput = Omit< SubscriptionFeature, "id" | "subscriptionProductId" | "href" | "badge" | "accumulate" | "code" | "quotaValue" > & { href?: string | null; badge?: string | null; accumulate?: boolean; code?: string | null; quotaValue?: Prisma.NullableJsonNullValueInput | Prisma.InputJsonValue; }; export type SubscriptionProductPriceWithDetails = Omit & { id?: string; }; export type SubscriptionProductWithDetails = Omit & { id?: string; kind?: SubscriptionProductKindValue; translatedTitle?: string; tenantProducts: TenantSubscriptionProduct[]; usageBasedPrices: (SubscriptionUsageBasedPrice & { tiers: SubscriptionUsageBasedTier[] })[]; prices: SubscriptionProductPriceWithDetails[]; features: SubscriptionFeature[]; }; export type SubscriptionFeatureSummary = { name: string; code?: string | null; order: number; title: string; type: number; value: number; accumulate: boolean; }; export type TenantSubscriptionProductWithDetails = TenantSubscriptionProduct & { subscriptionProduct: SubscriptionProduct & { features: SubscriptionFeature[] }; acquisition?: TenantProductAcquisition | null; prices: (TenantSubscriptionProductPrice & { subscriptionPrice: SubscriptionPrice | null; subscriptionUsageBasedPrice: (SubscriptionUsageBasedPrice & { tiers: SubscriptionUsageBasedTier[] }) | null; })[]; }; export type TenantSimple = { id: string; name: string; slug: string; icon: string | null; logo: string | null; deactivatedReason: string | null; active: boolean; theme: string | null; themeConfig: string | null; }; export type TenantSubscriptionProductWithTenant = TenantSubscriptionProductWithDetails & { tenantSubscription: TenantSubscription & { tenant: TenantSimple }; }; export type TenantSubscriptionWithDetails = TenantSubscription & { products: TenantSubscriptionProductWithDetails[]; }; export type TenantSubscriptionProductStatusFilter = "active" | "ended" | "active-cancelled" | "active-not-cancelled"; export type TenantSubscriptionProductFilters = { tenantId?: string; subscriptionProductId?: string; status?: TenantSubscriptionProductStatusFilter | string; }; export type TenantSubscriptionProductPagination = { page: number; pageSize: number; }; export type TenantSubscriptionProductPage = { items: TenantSubscriptionProductWithTenant[]; pagination: { page: number; pageSize: number; totalItems: number; totalPages: number; }; }; export type TenantSubscriptionCreateInput = Pick & Partial< Pick< TenantSubscription, | "billingProviderCustomerId" | "lagoCustomerId" | "mollieCustomerId" | "planCode" | "seatQuantity" | "officeSeatQuantity" | "fieldSeatQuantity" | "billingCadence" | "commitmentEndsAt" > >; export type TenantSubscriptionCustomerIdUpdateInput = Partial< Pick< TenantSubscription, | "billingProviderCustomerId" | "lagoCustomerId" | "mollieCustomerId" | "planCode" | "seatQuantity" | "officeSeatQuantity" | "fieldSeatQuantity" | "billingCadence" | "commitmentEndsAt" | "lastInvoiceExternalId" | "lastPaymentExternalId" > >; export type TenantSubscriptionProductCreateInput = Pick< TenantSubscriptionProduct, "tenantSubscriptionId" | "subscriptionProductId" | "billingProviderSubscriptionId" | "quantity" | "fromCheckoutSessionId" > & Partial< Pick< TenantSubscriptionProduct, | "customEntitlementPlanId" | "lagoSubscriptionId" | "planCode" | "seatQuantity" | "officeSeatQuantity" | "fieldSeatQuantity" | "billingCadence" | "commitmentEndsAt" > > & { prices: { subscriptionPriceId?: string; subscriptionUsageBasedPriceId?: string; }[]; }; export type TenantSubscriptionProductUpdateInput = Partial< Pick< TenantSubscriptionProduct, | "quantity" | "seatQuantity" | "officeSeatQuantity" | "fieldSeatQuantity" | "billingCadence" | "commitmentEndsAt" | "planCode" | "lagoSubscriptionId" | "cancelledAt" | "endsAt" | "currentPeriodStart" | "currentPeriodEnd" | "customEntitlementPlanId" > >; export type TenantSubscriptionProductCustomEntitlementPlanUpdateInput = Pick; export type TenantSubscriptionProductCancelInput = Pick; export type TenantSubscriptionUsageRecordCreateInput = Pick< TenantSubscriptionUsageRecord, "tenantId" | "tenantSubscriptionId" | "tenantSubscriptionProductPriceId" | "metricCode" | "timestamp" | "quantity" | "billingProviderSubscriptionItemId" > & Partial>; export type TenantCheckoutSessionStatus = CheckoutSessionStatus & { tenantId: string }; export type CheckoutSessionStatusCreateInput = Pick & Pick & Partial< Pick< CheckoutSessionStatus, | "fromUserId" | "provider" | "providerPaymentId" | "invoiceExternalId" | "subscriptionProductId" | "subscriptionPriceId" | "lagoSubscriptionId" | "planCode" | "quantity" | "officeSeatQuantity" | "fieldSeatQuantity" | "billingCadence" | "commitmentEndsAt" | "storageAddOnCodes" | "amountCents" | "currency" | "checkoutUrl" | "status" > >; export type CheckoutSessionStatusUpdateInput = Pick & Partial< Pick< CheckoutSessionStatus, "createdUserId" | "createdTenantId" | "providerPaymentId" | "invoiceExternalId" | "lagoSubscriptionId" | "checkoutUrl" | "status" | "fromUrl" > >; export type CheckoutSessionStatusClaimInput = { id: string; tenantId: string; expectedStatus: string; claimedStatus: string; updatedBefore?: Date; }; export type CheckoutSessionInvoiceCorrelationInput = { id: string; tenantId: string; providerPaymentId: string; lagoSubscriptionId: string; sourceInvoiceExternalId: string; providerInvoiceExternalId: string; }; export type TenantIdResult = { tenantId: string }; export type BillingProviderTenantSubscriptionProduct = Pick & { tenantSubscription: Pick & { tenant: { id: string; name: string; }; }; subscriptionProduct: Pick; }; export type BillingProviderTenantSubscriptionProductUpdate = { cancelledAt?: Date | null; currentPeriodStart?: Date; currentPeriodEnd?: Date; endsAt?: Date | null; }; const subscriptionProductDetailsInclude = { tenantProducts: true, usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } }, prices: true, features: { orderBy: { order: "asc", }, }, } as const; const tenantSimpleSelect = { id: true, name: true, slug: true, icon: true, logo: true, deactivatedReason: true, active: true, theme: true, themeConfig: true, } as const; const tenantSubscriptionProductDetailsInclude = { subscriptionProduct: { include: { features: true } }, acquisition: true, prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } }, } as const; const tenantSubscriptionProductWithTenantInclude = { ...tenantSubscriptionProductDetailsInclude, tenantSubscription: { include: { tenant: { select: tenantSimpleSelect } }, }, } as const; const tenantSubscriptionDetailsInclude = { products: { include: tenantSubscriptionProductDetailsInclude, orderBy: { subscriptionProduct: { order: "desc", }, }, }, } as const; const billingProviderTenantSubscriptionProductSelect = { id: true, endsAt: true, cancelledAt: true, customEntitlementPlanId: true, tenantSubscription: { select: { tenantId: true, tenant: { select: { id: true, name: true, }, }, }, }, subscriptionProduct: { select: { id: true, title: true, }, }, } as const; export type SubscriptionCatalogClient = { subscriptionProduct: { findMany(args: { where?: { active?: boolean; public?: boolean; id?: { in: string[] }; }; include: typeof subscriptionProductDetailsInclude; orderBy: { order: "asc" } | [{ public: "desc" }, { order: "asc" }]; }): Promise; findUnique(args: { where: { id: string }; include: typeof subscriptionProductDetailsInclude }): Promise; findFirst(args: { where: { billingProviderId: string } }): Promise; create(args: { data: SubscriptionProductCreateInput }): Promise; update(args: { where: { id: string }; data: SubscriptionProductUpdateInput | { billingProviderId: string } }): Promise; delete(args: { where: { id: string } }): Promise; }; subscriptionPrice: { findMany(args: { include: { subscriptionProduct: true }; orderBy: [{ subscriptionProduct: { order: "asc" } }, { price: "asc" }]; }): Promise; findUnique(args: { where: { id: string }; include: { subscriptionProduct: true } }): Promise; findFirst(args: { where: { billingProviderId: string }; include: { subscriptionProduct: true } }): Promise; create(args: { data: SubscriptionPriceCreateInput }): Promise; update(args: { where: { id: string }; data: SubscriptionPriceUpdateInput | { billingProviderId: string } }): Promise; delete(args: { where: { id: string } }): Promise; }; subscriptionUsageBasedPrice: { findFirst(args: { where: { billingProviderId: string }; include: { subscriptionProduct: true } }): Promise; create(args: { data: SubscriptionUsageBasedPriceCreateInput }): Promise; delete(args: { where: { id: string } }): Promise; }; subscriptionUsageBasedTier: { create(args: { data: SubscriptionUsageBasedTierCreateInput }): Promise; delete(args: { where: { id: string } }): Promise; }; subscriptionFeature: { findMany(args: { select: { name: true; code: true; order: true; title: true; type: true; value: true; accumulate: true }; }): Promise; create(args: { data: SubscriptionFeatureCreateInput & { subscriptionProductId: string } }): Promise; deleteMany(args: { where: { subscriptionProductId: string } }): Promise<{ count: number }>; }; }; export type SubscriptionProductReaderClient = SubscriptionCatalogClient; export type SubscriptionProductUsageClient = { adminUser: { findUnique(args: { where: { id: string }; select: { id: true } }): Promise<{ id: string } | null>; }; tenant: { findMany(args: { select: { id: true }; orderBy: { id: "asc" } }): Promise>; }; tenantSubscriptionProduct: { findMany(args: { select: { subscriptionProductId: true } }): Promise>; }; }; type TenantSubscriptionProductWhereInput = { subscriptionProductId?: { equals: string }; tenantSubscription?: { tenantId?: { equals: string } }; OR?: [{ endsAt: { gte: Date } }, { endsAt: null }]; endsAt?: { lt: Date; not: null }; cancelledAt?: { not: null } | null; }; export type TenantSubscriptionReaderClient = { tenantSubscription: { findUnique(args: { where: { tenantId: string }; include: typeof tenantSubscriptionDetailsInclude }): Promise; findMany(args: { include: typeof tenantSubscriptionDetailsInclude }): Promise; }; }; type DbCompatibleDelegate = Pick[TDelegateName]; const getTenantBillingClient = (): TenantBillingClient => getDbClient() as unknown as TenantBillingClient; export type TenantBillingClient = TenantSubscriptionReaderClient & { tenantSubscription: TenantSubscriptionReaderClient["tenantSubscription"] & { create(args: { data: TenantSubscriptionCreateInput; include: typeof tenantSubscriptionDetailsInclude }): Promise; update(args: { where: { tenantId: string }; data: TenantSubscriptionCustomerIdUpdateInput }): Promise; findMany(args: { select: { tenantId: true } }): Promise; }; tenantSubscriptionProduct: DbCompatibleDelegate<"tenantSubscriptionProduct"> & { findMany(args: { skip?: number; take?: number; where: TenantSubscriptionProductWhereInput; include: typeof tenantSubscriptionProductWithTenantInclude; orderBy: { createdAt: "desc" }; }): Promise; count(args: { where: TenantSubscriptionProductWhereInput }): Promise; findFirst(args: { where: | { tenantSubscription: { tenantId: string }; subscriptionProductId: string } | { id: string; tenantSubscription: { tenantId: string } } | { billingProviderSubscriptionId: string }; include: typeof tenantSubscriptionProductWithTenantInclude; }): Promise; findUnique(args: { where: { id: string }; include: typeof tenantSubscriptionProductWithTenantInclude; }): Promise; create(args: { data: Omit & { endsAt: null; cancelledAt: null; prices: { create: TenantSubscriptionProductCreateInput["prices"] }; }; include: { tenantSubscription: true }; }): Promise; update(args: { where: { id: string }; data: TenantSubscriptionProductUpdateInput | TenantSubscriptionProductCancelInput; include: { tenantSubscription: true }; }): Promise; update(args: { where: { id: string }; data: TenantSubscriptionProductCustomEntitlementPlanUpdateInput; select: { tenantSubscription: { select: { tenantId: true } } }; }): Promise<{ tenantSubscription: { tenantId: string } }>; }; checkoutSessionStatus: { findFirst(args: { where: { id: string; tenantId: string } }): Promise; create(args: { data: CheckoutSessionStatusCreateInput & { pending: true; fromUserId: string | null } }): Promise; update(args: { where: { id: string; tenantId: string }; data: CheckoutSessionStatusUpdateInput & { createdUserId: string | null; createdTenantId: string | null }; }): Promise; updateMany(args: { where: Record; data: Record }): Promise<{ count: number }>; }; tenantSubscriptionUsageRecord: { create(args: { data: TenantSubscriptionUsageRecordCreateInput }): Promise; }; }; export type BillingProviderTenantSubscriptionProductClient = { tenantSubscriptionProduct: { findFirst(args: { where: { billingProviderSubscriptionId: string }; select: typeof billingProviderTenantSubscriptionProductSelect; }): Promise; update(args: { where: { id: string }; data: BillingProviderTenantSubscriptionProductUpdate; select: { tenantSubscription: { select: { tenantId: true } } }; }): Promise<{ tenantSubscription: { tenantId: string } }>; }; }; export async function getAllSubscriptionProductsWithTenants( client: SubscriptionProductReaderClient = getDbClient() ): Promise { return await client.subscriptionProduct .findMany({ include: subscriptionProductDetailsInclude, orderBy: [{ public: "desc" }, { order: "asc" }], }) .catch(() => { return []; }); } /** * Returns only aggregate catalog usage. Raw tenant subscription rows remain * behind each tenant's RLS boundary and are never exposed to the admin UI. */ export async function getSubscriptionProductTenantUsageCounts(client: SubscriptionProductUsageClient = getDbClient()): Promise> { const context = getRlsExecutionContext(); if (!context?.userId || context.tenantId) { throw new Error("Subscription catalog usage requires a root platform-operator context"); } const operator = await client.adminUser.findUnique({ where: { id: context.userId }, select: { id: true }, }); if (!operator) throw new Error("Subscription catalog usage requires a platform operator"); const tenants = await client.tenant.findMany({ select: { id: true }, orderBy: { id: "asc" } }); const counts: Record = {}; const concurrency = 8; for (let index = 0; index < tenants.length; index += concurrency) { const batch = tenants.slice(index, index + concurrency); const rowsByTenant = await Promise.all( batch.map(({ id: tenantId }) => runWithRlsContext({ tenantId }, () => client.tenantSubscriptionProduct.findMany({ select: { subscriptionProductId: true } })) ) ); for (const rows of rowsByTenant) { for (const row of rows) counts[row.subscriptionProductId] = (counts[row.subscriptionProductId] ?? 0) + 1; } } return counts; } export async function getAllSubscriptionProducts( isPublic?: boolean, client: SubscriptionProductReaderClient = getDbClient() ): Promise { return await getAllSubscriptionProductsStrict(isPublic, client).catch(() => { return []; }); } /** * Reads the active subscription catalog without the legacy empty-list fallback. * Bootstrap callers use this variant so an unavailable catalog cannot be * mistaken for a valid catalog with no eligible plan. */ export async function getAllSubscriptionProductsStrict( isPublic?: boolean, client: SubscriptionProductReaderClient = getDbClient() ): Promise { if (isPublic) { return await client.subscriptionProduct.findMany({ where: { active: true, public: true, }, include: subscriptionProductDetailsInclude, orderBy: { order: "asc", }, }); } return await client.subscriptionProduct.findMany({ where: { active: true, }, include: subscriptionProductDetailsInclude, orderBy: { order: "asc", }, }); } export async function getSubscriptionProductsInIds( ids: string[], client: SubscriptionProductReaderClient = getDbClient() ): Promise { return await client.subscriptionProduct.findMany({ where: { id: { in: ids }, }, include: subscriptionProductDetailsInclude, orderBy: { order: "asc" }, }); } export async function getAllSubscriptionFeatures(client: SubscriptionProductReaderClient = getDbClient()): Promise { return await client.subscriptionFeature.findMany({ select: { name: true, code: true, order: true, title: true, type: true, value: true, accumulate: true }, }); } export async function getSubscriptionProduct( id: string, client: SubscriptionProductReaderClient = getDbClient() ): Promise { return await client.subscriptionProduct.findUnique({ where: { id, }, include: subscriptionProductDetailsInclude, }); } export async function getSubscriptionProductByBillingProviderId( billingProviderId: string, client: SubscriptionCatalogClient = getDbClient() ): Promise { return await client.subscriptionProduct.findFirst({ where: { billingProviderId, }, }); } export async function getSubscriptionPrices(client: SubscriptionCatalogClient = getDbClient()): Promise { return await client.subscriptionPrice .findMany({ include: { subscriptionProduct: true, }, orderBy: [ { subscriptionProduct: { order: "asc", }, }, { price: "asc", }, ], }) .catch(() => { return []; }); } export async function getSubscriptionPrice(id: string, client: SubscriptionCatalogClient = getDbClient()): Promise { return await client.subscriptionPrice .findUnique({ where: { id }, include: { subscriptionProduct: true, }, }) .catch(() => { return null; }); } export async function getSubscriptionPriceByBillingProviderId( billingProviderId: string, client: SubscriptionCatalogClient = getDbClient() ): Promise { return await client.subscriptionPrice .findFirst({ where: { billingProviderId }, include: { subscriptionProduct: true, }, }) .catch(() => { return null; }); } export async function getSubscriptionUsageBasedPriceByBillingProviderId( billingProviderId: string, client: SubscriptionCatalogClient = getDbClient() ): Promise { return await client.subscriptionUsageBasedPrice .findFirst({ where: { billingProviderId }, include: { subscriptionProduct: true, }, }) .catch(() => { return null; }); } export async function createSubscriptionProduct( data: SubscriptionProductCreateInput, client: SubscriptionCatalogClient = getDbClient() ): Promise { return await client.subscriptionProduct.create({ data }); } export async function updateSubscriptionProduct( id: string, data: SubscriptionProductUpdateInput, client: SubscriptionCatalogClient = getDbClient() ): Promise { return await client.subscriptionProduct.update({ where: { id }, data, }); } export async function updateSubscriptionProductBillingProviderId( id: string, data: { billingProviderId: string }, client: SubscriptionCatalogClient = getDbClient() ): Promise { return await client.subscriptionProduct.update({ where: { id }, data, }); } export async function updateSubscriptionPriceBillingProviderId( id: string, data: { billingProviderId: string }, client: SubscriptionCatalogClient = getDbClient() ): Promise { return await client.subscriptionPrice.update({ where: { id }, data, }); } export async function createSubscriptionPrice( data: SubscriptionPriceCreateInput, client: SubscriptionCatalogClient = getDbClient() ): Promise { return await client.subscriptionPrice.create({ data }); } export async function updateSubscriptionPrice( id: string, data: SubscriptionPriceUpdateInput, client: SubscriptionCatalogClient = getDbClient() ): Promise { return await client.subscriptionPrice.update({ where: { id }, data, }); } export async function createSubscriptionUsageBasedPrice( data: SubscriptionUsageBasedPriceCreateInput, client: SubscriptionCatalogClient = getDbClient() ): Promise { return await client.subscriptionUsageBasedPrice.create({ data }); } export async function createSubscriptionUsageBasedTier( data: SubscriptionUsageBasedTierCreateInput, client: SubscriptionCatalogClient = getDbClient() ): Promise { return await client.subscriptionUsageBasedTier.create({ data }); } export async function createSubscriptionFeature( subscriptionProductId: string, data: SubscriptionFeatureCreateInput, client: SubscriptionCatalogClient = getDbClient() ): Promise { return await client.subscriptionFeature.create({ data: { subscriptionProductId, ...data, }, }); } export async function deleteSubscriptionProduct(id: string, client: SubscriptionCatalogClient = getDbClient()): Promise { return await client.subscriptionProduct.delete({ where: { id }, }); } export async function deleteSubscriptionPrice(id: string, client: SubscriptionCatalogClient = getDbClient()): Promise { return await client.subscriptionPrice.delete({ where: { id }, }); } export async function deleteSubscriptionUsageBasedTier(id: string, client: SubscriptionCatalogClient = getDbClient()): Promise { return await client.subscriptionUsageBasedTier.delete({ where: { id }, }); } export async function deleteSubscriptionUsageBasedPrice(id: string, client: SubscriptionCatalogClient = getDbClient()): Promise { return await client.subscriptionUsageBasedPrice.delete({ where: { id }, }); } export async function deleteSubscriptionFeatures(subscriptionProductId: string, client: SubscriptionCatalogClient = getDbClient()): Promise<{ count: number }> { return await client.subscriptionFeature.deleteMany({ where: { subscriptionProductId }, }); } export async function getTenantSubscription( tenantId: string, client: TenantSubscriptionReaderClient = getDbClient() ): Promise { return await client.tenantSubscription.findUnique({ where: { tenantId, }, include: tenantSubscriptionDetailsInclude, }); } export async function getTenantSubscriptions(client: TenantSubscriptionReaderClient = getDbClient()): Promise { return await client.tenantSubscription.findMany({ include: tenantSubscriptionDetailsInclude, }); } export async function createTenantSubscription( data: TenantSubscriptionCreateInput, client: TenantBillingClient = getTenantBillingClient() ): Promise { return await client.tenantSubscription.create({ data, include: tenantSubscriptionDetailsInclude, }); } export async function updateTenantSubscriptionCustomerId( tenantId: string, data: TenantSubscriptionCustomerIdUpdateInput, client: TenantBillingClient = getTenantBillingClient() ): Promise { return await client.tenantSubscription.update({ where: { tenantId }, data, }); } export async function listTenantSubscriptionIds(client: TenantBillingClient = getTenantBillingClient()): Promise { return await client.tenantSubscription.findMany({ select: { tenantId: true }, }); } function buildTenantSubscriptionProductWhere(filters?: TenantSubscriptionProductFilters, now: Date = new Date()): TenantSubscriptionProductWhereInput { let where: TenantSubscriptionProductWhereInput = { subscriptionProductId: filters?.subscriptionProductId ? { equals: filters.subscriptionProductId } : undefined, tenantSubscription: { tenantId: filters?.tenantId ? { equals: filters.tenantId } : undefined, }, }; if (filters?.status === "active") { where = { ...where, OR: [{ endsAt: { gte: now } }, { endsAt: null }], }; } else if (filters?.status === "ended") { where = { ...where, endsAt: { lt: now, not: null }, }; } else if (filters?.status === "active-cancelled") { where = { ...where, OR: [{ endsAt: { gte: now } }, { endsAt: null }], cancelledAt: { not: null }, }; } else if (filters?.status === "active-not-cancelled") { where = { ...where, OR: [{ endsAt: { gte: now } }, { endsAt: null }], cancelledAt: null, }; } return where; } export async function getAllTenantSubscriptionProducts( filters?: TenantSubscriptionProductFilters, pagination?: TenantSubscriptionProductPagination, client: TenantBillingClient = getTenantBillingClient(), now: Date = new Date() ): Promise { const where = buildTenantSubscriptionProductWhere(filters, now); const items = await client.tenantSubscriptionProduct.findMany({ skip: pagination ? pagination.pageSize * (pagination.page - 1) : undefined, take: pagination ? pagination.pageSize : undefined, where, include: tenantSubscriptionProductWithTenantInclude, orderBy: { createdAt: "desc" }, }); const totalItems = await client.tenantSubscriptionProduct.count({ where }); const page = pagination?.page ?? 1; const pageSize = pagination?.pageSize ?? 10; return { items, pagination: { page, pageSize, totalItems, totalPages: Math.ceil(totalItems / pageSize), }, }; } export async function getTenantSubscriptionProduct( tenantId: string, subscriptionProductId: string, client: TenantBillingClient = getTenantBillingClient() ): Promise { return await client.tenantSubscriptionProduct.findFirst({ where: { tenantSubscription: { tenantId }, subscriptionProductId, }, include: tenantSubscriptionProductWithTenantInclude, }); } export async function adminGetTenantSubscriptionProductById( id: string, client: TenantBillingClient = getTenantBillingClient() ): Promise { return await client.tenantSubscriptionProduct.findUnique({ where: { id }, include: tenantSubscriptionProductWithTenantInclude, }); } export async function getTenantSubscriptionProductById( { id, tenantId }: { id: string; tenantId: string }, client: TenantBillingClient = getTenantBillingClient() ): Promise { return await client.tenantSubscriptionProduct.findFirst({ where: { id, tenantSubscription: { tenantId } }, include: tenantSubscriptionProductWithTenantInclude, }); } export async function getTenantSubscriptionProductByBillingProviderSubscriptionId( billingProviderSubscriptionId: string, client: TenantBillingClient = getTenantBillingClient() ): Promise { return await client.tenantSubscriptionProduct.findFirst({ where: { billingProviderSubscriptionId }, include: tenantSubscriptionProductWithTenantInclude, }); } export async function addTenantSubscriptionProduct( data: TenantSubscriptionProductCreateInput, client: TenantBillingClient = getTenantBillingClient() ): Promise { return await client.tenantSubscriptionProduct.create({ data: { tenantSubscriptionId: data.tenantSubscriptionId, subscriptionProductId: data.subscriptionProductId, billingProviderSubscriptionId: data.billingProviderSubscriptionId, lagoSubscriptionId: data.lagoSubscriptionId, planCode: data.planCode, seatQuantity: data.seatQuantity, officeSeatQuantity: data.officeSeatQuantity, fieldSeatQuantity: data.fieldSeatQuantity, billingCadence: data.billingCadence, commitmentEndsAt: data.commitmentEndsAt, quantity: data.quantity, fromCheckoutSessionId: data.fromCheckoutSessionId, customEntitlementPlanId: data.customEntitlementPlanId, endsAt: null, cancelledAt: null, prices: { create: data.prices, }, }, include: { tenantSubscription: true }, }); } export async function updateTenantSubscriptionProduct( { id, tenantId }: { id: string; tenantId: string }, data: TenantSubscriptionProductUpdateInput, client: TenantBillingClient = getTenantBillingClient() ): Promise { const existing = await getTenantSubscriptionProductById({ id, tenantId }, client); if (!existing) { throw new Error(`Tenant subscription product ${id} not found`); } return await client.tenantSubscriptionProduct.update({ where: { id }, data, include: { tenantSubscription: true }, }); } export function getEffectiveTenantEntitlementPlanId(item: Pick): string { return item.customEntitlementPlanId ?? item.subscriptionProductId; } export async function updateTenantSubscriptionProductCustomEntitlementPlan( { id, tenantId }: { id: string; tenantId: string }, data: TenantSubscriptionProductCustomEntitlementPlanUpdateInput, client: TenantBillingClient = getTenantBillingClient() ): Promise { const existing = await getTenantSubscriptionProductById({ id, tenantId }, client); if (!existing) { throw new Error(`Tenant subscription product ${id} not found`); } const item = await client.tenantSubscriptionProduct.update({ where: { id }, data, select: { tenantSubscription: { select: { tenantId: true, }, }, }, }); return { tenantId: item.tenantSubscription.tenantId }; } export async function cancelTenantSubscriptionProduct( { id, tenantId }: { id: string; tenantId: string }, data: TenantSubscriptionProductCancelInput, client: TenantBillingClient = getTenantBillingClient() ): Promise { const existing = await getTenantSubscriptionProductById({ id, tenantId }, client); if (!existing) { throw new Error(`Tenant subscription product ${id} not found`); } const item = await client.tenantSubscriptionProduct.update({ where: { id }, data: { cancelledAt: data.cancelledAt, endsAt: data.endsAt, }, include: { tenantSubscription: true }, }); return { tenantId: item.tenantSubscription.tenantId }; } export async function getCheckoutSessionStatus( { id, tenantId }: { id: string; tenantId: string }, client: TenantBillingClient = getTenantBillingClient() ): Promise { return runWithRlsContext({ tenantId }, () => client.checkoutSessionStatus.findFirst({ where: { id, tenantId }, }) ); } export async function createCheckoutSessionStatus( data: CheckoutSessionStatusCreateInput, client: TenantBillingClient = getTenantBillingClient() ): Promise { return runWithRlsContext({ tenantId: data.tenantId }, () => client.checkoutSessionStatus.create({ data: { id: data.id, tenantId: data.tenantId, pending: true, email: data.email, fromUrl: data.fromUrl, fromUserId: data.fromUserId ?? null, provider: data.provider ?? null, providerPaymentId: data.providerPaymentId ?? null, invoiceExternalId: data.invoiceExternalId ?? null, subscriptionProductId: data.subscriptionProductId ?? null, subscriptionPriceId: data.subscriptionPriceId ?? null, lagoSubscriptionId: data.lagoSubscriptionId ?? null, planCode: data.planCode ?? null, quantity: data.quantity ?? 1, officeSeatQuantity: data.officeSeatQuantity ?? 0, fieldSeatQuantity: data.fieldSeatQuantity ?? 0, billingCadence: data.billingCadence ?? "monthly", commitmentEndsAt: data.commitmentEndsAt ?? null, storageAddOnCodes: data.storageAddOnCodes ?? [], amountCents: data.amountCents ?? null, currency: data.currency ?? null, checkoutUrl: data.checkoutUrl ?? null, status: data.status ?? "open", }, }) ); } export async function updateCheckoutSessionStatus( { id, tenantId }: { id: string; tenantId: string }, data: CheckoutSessionStatusUpdateInput, client: TenantBillingClient = getTenantBillingClient() ): Promise { return runWithRlsContext({ tenantId }, () => client.checkoutSessionStatus.update({ where: { id, tenantId }, data: { pending: data.pending, createdUserId: data.createdUserId ?? null, createdTenantId: data.createdTenantId ?? null, providerPaymentId: data.providerPaymentId ?? undefined, invoiceExternalId: data.invoiceExternalId ?? undefined, lagoSubscriptionId: data.lagoSubscriptionId ?? undefined, checkoutUrl: data.checkoutUrl ?? undefined, status: data.status ?? undefined, fromUrl: data.fromUrl ?? undefined, }, }) ); } export async function claimCheckoutSessionStatus( input: CheckoutSessionStatusClaimInput, client: TenantBillingClient = getTenantBillingClient() ): Promise { return runWithRlsContext({ tenantId: input.tenantId }, async () => { const claimed = await client.checkoutSessionStatus.updateMany({ where: { id: input.id, tenantId: input.tenantId, pending: true, status: input.expectedStatus, ...(input.updatedBefore ? { updatedAt: { lte: input.updatedBefore } } : {}), }, data: { status: input.claimedStatus }, }); if (claimed.count !== 1) return null; const session = await client.checkoutSessionStatus.findFirst({ where: { id: input.id, tenantId: input.tenantId } }); return session?.status === input.claimedStatus ? session : null; }); } export async function transitionClaimedCheckoutSessionStatus( input: { id: string; tenantId: string; claimedStatus: string; data: CheckoutSessionStatusUpdateInput }, client: TenantBillingClient = getTenantBillingClient() ): Promise { return runWithRlsContext({ tenantId: input.tenantId }, async () => { const transitioned = await client.checkoutSessionStatus.updateMany({ where: { id: input.id, tenantId: input.tenantId, pending: true, status: input.claimedStatus }, data: { pending: input.data.pending, providerPaymentId: input.data.providerPaymentId ?? undefined, invoiceExternalId: input.data.invoiceExternalId ?? undefined, lagoSubscriptionId: input.data.lagoSubscriptionId ?? undefined, checkoutUrl: input.data.checkoutUrl ?? undefined, status: input.data.status ?? undefined, fromUrl: input.data.fromUrl ?? undefined, }, }); if (transitioned.count !== 1) return null; return client.checkoutSessionStatus.findFirst({ where: { id: input.id, tenantId: input.tenantId } }); }); } export async function correlateCheckoutSessionProviderInvoice( input: CheckoutSessionInvoiceCorrelationInput, client: TenantBillingClient = getTenantBillingClient() ): Promise { const normalized = { id: input.id.trim(), tenantId: input.tenantId.trim(), providerPaymentId: input.providerPaymentId.trim(), lagoSubscriptionId: input.lagoSubscriptionId.trim(), sourceInvoiceExternalId: input.sourceInvoiceExternalId.trim(), providerInvoiceExternalId: input.providerInvoiceExternalId.trim(), }; if (Object.values(normalized).some((value) => value.length === 0)) { throw new Error("Checkout invoice correlation requires complete provider references"); } await runWithRlsContext({ tenantId: normalized.tenantId }, async () => { const updated = await client.checkoutSessionStatus.updateMany({ where: { id: normalized.id, tenantId: normalized.tenantId, providerPaymentId: normalized.providerPaymentId, lagoSubscriptionId: normalized.lagoSubscriptionId, invoiceExternalId: normalized.sourceInvoiceExternalId, }, data: { invoiceExternalId: normalized.providerInvoiceExternalId }, }); if (updated.count === 1) return; const replay = await client.checkoutSessionStatus.findFirst({ where: { id: normalized.id, tenantId: normalized.tenantId }, }); if ( replay?.providerPaymentId === normalized.providerPaymentId && replay.lagoSubscriptionId === normalized.lagoSubscriptionId && replay.invoiceExternalId === normalized.providerInvoiceExternalId ) { return; } throw new Error("Checkout invoice correlation did not match the exact payment ledger row"); }); } export async function createTenantSubscriptionUsageRecord( data: TenantSubscriptionUsageRecordCreateInput, client: TenantBillingClient = getTenantBillingClient() ): Promise { return await client.tenantSubscriptionUsageRecord.create({ data }); } export async function findTenantSubscriptionProductByBillingProviderSubscriptionId( billingProviderSubscriptionId: string, client: BillingProviderTenantSubscriptionProductClient = getDbClient() as unknown as BillingProviderTenantSubscriptionProductClient ): Promise { return client.tenantSubscriptionProduct.findFirst({ where: { billingProviderSubscriptionId, }, select: billingProviderTenantSubscriptionProductSelect, }); } export async function updateTenantSubscriptionProductFromBillingProvider( id: string, data: BillingProviderTenantSubscriptionProductUpdate, client: BillingProviderTenantSubscriptionProductClient = getDbClient() as unknown as BillingProviderTenantSubscriptionProductClient ): Promise<{ tenantId: string }> { const item = await client.tenantSubscriptionProduct.update({ where: { id }, data, select: { tenantSubscription: { select: { tenantId: true, }, }, }, }); return { tenantId: item.tenantSubscription.tenantId, }; }