import { describe, expect, it, vi } from "vitest"; import { getRlsExecutionContext, runWithRlsContext } from "./rls-context.server.js"; import { addTenantSubscriptionProduct, adminGetTenantSubscriptionProductById, cancelTenantSubscriptionProduct, claimCheckoutSessionStatus, correlateCheckoutSessionProviderInvoice, createCheckoutSessionStatus, createSubscriptionFeature, createSubscriptionPrice, createSubscriptionProduct, createSubscriptionUsageBasedPrice, createSubscriptionUsageBasedTier, createTenantSubscription, createTenantSubscriptionUsageRecord, deleteSubscriptionFeatures, deleteSubscriptionPrice, deleteSubscriptionProduct, deleteSubscriptionUsageBasedPrice, deleteSubscriptionUsageBasedTier, findTenantSubscriptionProductByBillingProviderSubscriptionId, getEffectiveTenantEntitlementPlanId, getAllSubscriptionFeatures, getAllSubscriptionProducts, getAllSubscriptionProductsStrict, getAllSubscriptionProductsWithTenants, getSubscriptionProductTenantUsageCounts, getSubscriptionPrice, getSubscriptionPriceByBillingProviderId, getSubscriptionPrices, getSubscriptionProduct, getSubscriptionProductByBillingProviderId, getSubscriptionProductsInIds, getSubscriptionUsageBasedPriceByBillingProviderId, getTenantSubscription, getTenantSubscriptionProduct, getTenantSubscriptionProductById, getTenantSubscriptionProductByBillingProviderSubscriptionId, getTenantSubscriptions, getAllTenantSubscriptionProducts, getCheckoutSessionStatus, listTenantSubscriptionIds, updateCheckoutSessionStatus, transitionClaimedCheckoutSessionStatus, updateSubscriptionPrice, updateSubscriptionPriceBillingProviderId, updateSubscriptionProduct, updateSubscriptionProductBillingProviderId, updateTenantSubscriptionCustomerId, updateTenantSubscriptionProduct, updateTenantSubscriptionProductCustomEntitlementPlan, updateTenantSubscriptionProductFromBillingProvider, type BillingProviderTenantSubscriptionProductClient, type SubscriptionCatalogClient, type SubscriptionProductUsageClient, type TenantBillingClient, type TenantSubscriptionReaderClient, } from "./subscriptions.server.js"; function createSubscriptionProductClient(items: unknown[] = []): SubscriptionCatalogClient { return { subscriptionProduct: { findMany: vi.fn().mockResolvedValue(items), findUnique: vi.fn().mockResolvedValue(items[0] ?? null), findFirst: vi.fn().mockResolvedValue(items[0] ?? null), create: vi.fn().mockResolvedValue(items[0] ?? { id: "plan_1" }), update: vi.fn().mockResolvedValue(items[0] ?? { id: "plan_1" }), delete: vi.fn().mockResolvedValue(items[0] ?? { id: "plan_1" }), }, subscriptionPrice: { findMany: vi.fn().mockResolvedValue(items), findUnique: vi.fn().mockResolvedValue(items[0] ?? null), findFirst: vi.fn().mockResolvedValue(items[0] ?? null), create: vi.fn().mockResolvedValue(items[0] ?? { id: "price_1" }), update: vi.fn().mockResolvedValue(items[0] ?? { id: "price_1" }), delete: vi.fn().mockResolvedValue(items[0] ?? { id: "price_1" }), }, subscriptionUsageBasedPrice: { findFirst: vi.fn().mockResolvedValue(items[0] ?? null), create: vi.fn().mockResolvedValue(items[0] ?? { id: "usage_price_1" }), delete: vi.fn().mockResolvedValue(items[0] ?? { id: "usage_price_1" }), }, subscriptionUsageBasedTier: { create: vi.fn().mockResolvedValue(items[0] ?? { id: "tier_1" }), delete: vi.fn().mockResolvedValue(items[0] ?? { id: "tier_1" }), }, subscriptionFeature: { findMany: vi.fn().mockResolvedValue(items), create: vi.fn().mockResolvedValue(items[0] ?? { id: "feature_1" }), deleteMany: vi.fn().mockResolvedValue({ count: 1 }), }, } as unknown as SubscriptionCatalogClient; } function createTenantSubscriptionClient(items: unknown[] = []): TenantSubscriptionReaderClient { return { tenantSubscription: { findMany: vi.fn().mockResolvedValue(items), findUnique: vi.fn().mockResolvedValue(items[0] ?? null), }, } as unknown as TenantSubscriptionReaderClient; } function createBillingProviderTenantSubscriptionProductClient(item: unknown = null): BillingProviderTenantSubscriptionProductClient { return { tenantSubscriptionProduct: { findFirst: vi.fn().mockResolvedValue(item), update: vi.fn().mockResolvedValue({ tenantSubscription: { tenantId: "tenant_1" } }), }, } as unknown as BillingProviderTenantSubscriptionProductClient; } function createTenantBillingClient(items: unknown[] = []): TenantBillingClient { return { tenantSubscription: { findMany: vi.fn().mockResolvedValue(items.length > 0 ? items : [{ tenantId: "tenant_1" }]), findUnique: vi.fn().mockResolvedValue(items[0] ?? null), create: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_sub_1", tenantId: "tenant_1", products: [] }), update: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_sub_1", tenantId: "tenant_1", billingProviderCustomerId: "cus_1" }), }, tenantSubscriptionProduct: { findMany: vi.fn().mockResolvedValue(items), count: vi.fn().mockResolvedValue(items.length), findFirst: vi.fn().mockResolvedValue(items[0] ?? null), findUnique: vi.fn().mockResolvedValue(items[0] ?? null), create: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }), update: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }), }, checkoutSessionStatus: { findFirst: vi.fn().mockResolvedValue(items[0] ?? null), create: vi.fn().mockResolvedValue(items[0] ?? { id: "cs_1", pending: true }), update: vi.fn().mockResolvedValue(items[0] ?? { id: "cs_1", pending: false }), updateMany: vi.fn().mockResolvedValue({ count: 1 }), }, tenantSubscriptionUsageRecord: { create: vi.fn().mockResolvedValue(items[0] ?? { id: "usage_1" }), }, } as unknown as TenantBillingClient; } describe("subscription product reads", () => { it("fetches public active products with details", async () => { const client = createSubscriptionProductClient([]); await expect(getAllSubscriptionProducts(true, client)).resolves.toEqual([]); expect(client.subscriptionProduct.findMany).toHaveBeenCalledWith({ where: { active: true, public: true }, include: { tenantProducts: true, usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } }, prices: true, features: { orderBy: { order: "asc" } }, }, orderBy: { order: "asc" }, }); }); it("fetches all active products when public-only is not requested", async () => { const client = createSubscriptionProductClient([]); await expect(getAllSubscriptionProducts(false, client)).resolves.toEqual([]); expect(client.subscriptionProduct.findMany).toHaveBeenCalledWith({ where: { active: true }, include: { tenantProducts: true, usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } }, prices: true, features: { orderBy: { order: "asc" } }, }, orderBy: { order: "asc" }, }); }); it("preserves legacy empty-list behavior when broad product reads fail", async () => { const client = createSubscriptionProductClient([]); vi.mocked(client.subscriptionProduct.findMany).mockRejectedValueOnce(new Error("database unavailable")); await expect(getAllSubscriptionProductsWithTenants(client)).resolves.toEqual([]); }); it("propagates catalog read failures for strict bootstrap callers", async () => { const client = createSubscriptionProductClient([]); const error = new Error("database unavailable"); vi.mocked(client.subscriptionProduct.findMany).mockRejectedValueOnce(error); await expect(getAllSubscriptionProductsStrict(true, client)).rejects.toBe(error); }); it("keeps the legacy empty-list fallback for non-bootstrap catalog callers", async () => { const client = createSubscriptionProductClient([]); vi.mocked(client.subscriptionProduct.findMany).mockRejectedValueOnce(new Error("database unavailable")); await expect(getAllSubscriptionProducts(true, client)).resolves.toEqual([]); }); it("aggregates catalog usage inside each tenant boundary for platform operators", async () => { const client: SubscriptionProductUsageClient = { adminUser: { findUnique: vi.fn().mockResolvedValue({ id: "operator_1" }) }, tenant: { findMany: vi.fn().mockResolvedValue([{ id: "tenant_a" }, { id: "tenant_b" }]) }, tenantSubscriptionProduct: { findMany: vi.fn(async () => { const tenantId = getRlsExecutionContext()?.tenantId; if (tenantId === "tenant_a") return [{ subscriptionProductId: "plan_1" }, { subscriptionProductId: "plan_2" }]; if (tenantId === "tenant_b") return [{ subscriptionProductId: "plan_1" }]; throw new Error("tenant context missing"); }), }, }; await expect(runWithRlsContext({ userId: "operator_1" }, () => getSubscriptionProductTenantUsageCounts(client))).resolves.toEqual({ plan_1: 2, plan_2: 1 }); expect(client.adminUser.findUnique).toHaveBeenCalledWith({ where: { id: "operator_1" }, select: { id: true }, }); expect(client.tenantSubscriptionProduct.findMany).toHaveBeenCalledTimes(2); }); it("rejects catalog usage aggregation outside a root platform-operator context", async () => { const client: SubscriptionProductUsageClient = { adminUser: { findUnique: vi.fn().mockResolvedValue(null) }, tenant: { findMany: vi.fn() }, tenantSubscriptionProduct: { findMany: vi.fn() }, }; await expect(getSubscriptionProductTenantUsageCounts(client)).rejects.toThrow("root platform-operator context"); await expect(runWithRlsContext({ userId: "member_1" }, () => getSubscriptionProductTenantUsageCounts(client))).rejects.toThrow( "requires a platform operator" ); await expect(runWithRlsContext({ userId: "operator_1", tenantId: "tenant_a" }, () => getSubscriptionProductTenantUsageCounts(client))).rejects.toThrow( "root platform-operator context" ); expect(client.tenant.findMany).not.toHaveBeenCalled(); }); it("fetches selected products by id without swallowing errors", async () => { const client = createSubscriptionProductClient([]); await expect(getSubscriptionProductsInIds(["plan_a", "plan_b"], client)).resolves.toEqual([]); expect(client.subscriptionProduct.findMany).toHaveBeenCalledWith({ where: { id: { in: ["plan_a", "plan_b"] } }, include: { tenantProducts: true, usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } }, prices: true, features: { orderBy: { order: "asc" } }, }, orderBy: { order: "asc" }, }); }); it("fetches one product by id", async () => { const product = { id: "plan_a" }; const client = createSubscriptionProductClient([product]); await expect(getSubscriptionProduct("plan_a", client)).resolves.toBe(product); expect(client.subscriptionProduct.findUnique).toHaveBeenCalledWith({ where: { id: "plan_a" }, include: { tenantProducts: true, usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } }, prices: true, features: { orderBy: { order: "asc" } }, }, }); }); it("fetches subscription feature summaries", async () => { const client = createSubscriptionProductClient([]); await expect(getAllSubscriptionFeatures(client)).resolves.toEqual([]); expect(client.subscriptionFeature.findMany).toHaveBeenCalledWith({ select: { name: true, code: true, order: true, title: true, type: true, value: true, accumulate: true }, }); }); }); describe("subscription catalog helpers", () => { it("fetches a product by billing provider id", async () => { const product = { id: "plan_a", billingProviderId: "prod_123" }; const client = createSubscriptionProductClient([product]); await expect(getSubscriptionProductByBillingProviderId("prod_123", client)).resolves.toBe(product); expect(client.subscriptionProduct.findFirst).toHaveBeenCalledWith({ where: { billingProviderId: "prod_123" }, }); }); it("fetches prices with products in admin ordering", async () => { const client = createSubscriptionProductClient([]); await expect(getSubscriptionPrices(client)).resolves.toEqual([]); expect(client.subscriptionPrice.findMany).toHaveBeenCalledWith({ include: { subscriptionProduct: true }, orderBy: [{ subscriptionProduct: { order: "asc" } }, { price: "asc" }], }); }); it("keeps legacy null and empty read behavior for price lookup failures", async () => { const client = createSubscriptionProductClient([]); vi.mocked(client.subscriptionPrice.findMany).mockRejectedValueOnce(new Error("read failed")); vi.mocked(client.subscriptionPrice.findUnique).mockRejectedValueOnce(new Error("read failed")); vi.mocked(client.subscriptionPrice.findFirst).mockRejectedValueOnce(new Error("read failed")); vi.mocked(client.subscriptionUsageBasedPrice.findFirst).mockRejectedValueOnce(new Error("read failed")); await expect(getSubscriptionPrices(client)).resolves.toEqual([]); await expect(getSubscriptionPrice("price_1", client)).resolves.toBeNull(); await expect(getSubscriptionPriceByBillingProviderId("price_provider_1", client)).resolves.toBeNull(); await expect(getSubscriptionUsageBasedPriceByBillingProviderId("metered_provider_1", client)).resolves.toBeNull(); }); it("creates catalog rows without coercing decimal-compatible values", async () => { const client = createSubscriptionProductClient([]); const productData = { billingProviderId: "prod_123", order: 1, title: "Pro", model: 1, description: null, badge: null, groupTitle: null, groupDescription: null, active: true, public: true, billingAddressCollection: "auto", hasQuantity: false, canBuyAgain: false, }; const priceData = { subscriptionProductId: "plan_a", billingProviderId: "price_123", type: 1, billingPeriod: 1, price: "19.99", currency: "usd", trialDays: 0, active: true, }; const usagePriceData = { subscriptionProductId: "plan_a", billingProviderId: "metered_123", currency: "usd", billingPeriod: 1, unit: "api_call", unitTitle: "API call", unitTitlePlural: "API calls", usageType: "metered", aggregateUsage: "sum", tiersMode: "graduated", billingScheme: "tiered", }; const tierData = { subscriptionUsageBasedPriceId: "usage_price_1", from: 1, to: null, perUnitPrice: "0.10", flatFeePrice: null, }; await createSubscriptionProduct(productData, client); await createSubscriptionPrice(priceData, client); await createSubscriptionUsageBasedPrice(usagePriceData, client); await createSubscriptionUsageBasedTier(tierData, client); await createSubscriptionFeature( "plan_a", { order: 1, title: "Seats", name: "seats", type: 1, value: 5, href: null, badge: null, accumulate: false, }, client ); expect(client.subscriptionProduct.create).toHaveBeenCalledWith({ data: productData }); expect(client.subscriptionPrice.create).toHaveBeenCalledWith({ data: priceData }); expect(client.subscriptionUsageBasedPrice.create).toHaveBeenCalledWith({ data: usagePriceData }); expect(client.subscriptionUsageBasedTier.create).toHaveBeenCalledWith({ data: tierData }); expect(client.subscriptionFeature.create).toHaveBeenCalledWith({ data: { subscriptionProductId: "plan_a", order: 1, title: "Seats", name: "seats", type: 1, value: 5, href: null, badge: null, accumulate: false, }, }); }); it("updates product and price catalog rows", async () => { const client = createSubscriptionProductClient([]); await updateSubscriptionProduct("plan_a", { title: "Business", public: false }, client); await updateSubscriptionProductBillingProviderId("plan_a", { billingProviderId: "prod_new" }, client); await updateSubscriptionPrice("price_a", { price: "29.99", active: false }, client); await updateSubscriptionPriceBillingProviderId("price_a", { billingProviderId: "price_new" }, client); expect(client.subscriptionProduct.update).toHaveBeenNthCalledWith(1, { where: { id: "plan_a" }, data: { title: "Business", public: false }, }); expect(client.subscriptionProduct.update).toHaveBeenNthCalledWith(2, { where: { id: "plan_a" }, data: { billingProviderId: "prod_new" }, }); expect(client.subscriptionPrice.update).toHaveBeenNthCalledWith(1, { where: { id: "price_a" }, data: { price: "29.99", active: false }, }); expect(client.subscriptionPrice.update).toHaveBeenNthCalledWith(2, { where: { id: "price_a" }, data: { billingProviderId: "price_new" }, }); }); it("deletes catalog rows with direct ids and product-scoped features", async () => { const client = createSubscriptionProductClient([]); await deleteSubscriptionProduct("plan_a", client); await deleteSubscriptionPrice("price_a", client); await deleteSubscriptionUsageBasedTier("tier_a", client); await deleteSubscriptionUsageBasedPrice("usage_price_a", client); await deleteSubscriptionFeatures("plan_a", client); expect(client.subscriptionProduct.delete).toHaveBeenCalledWith({ where: { id: "plan_a" } }); expect(client.subscriptionPrice.delete).toHaveBeenCalledWith({ where: { id: "price_a" } }); expect(client.subscriptionUsageBasedTier.delete).toHaveBeenCalledWith({ where: { id: "tier_a" } }); expect(client.subscriptionUsageBasedPrice.delete).toHaveBeenCalledWith({ where: { id: "usage_price_a" } }); expect(client.subscriptionFeature.deleteMany).toHaveBeenCalledWith({ where: { subscriptionProductId: "plan_a" } }); }); it("propagates mutation failures instead of hiding failed billing provider sync", async () => { const client = createSubscriptionProductClient([]); const error = new Error("write failed"); vi.mocked(client.subscriptionPrice.update).mockRejectedValueOnce(error); await expect(updateSubscriptionPrice("price_a", { active: false }, client)).rejects.toBe(error); }); }); describe("tenant subscription reads", () => { it("fetches a tenant subscription with product details", async () => { const subscription = { id: "sub_1" }; const client = createTenantSubscriptionClient([subscription]); await expect(getTenantSubscription("tenant_1", client)).resolves.toBe(subscription); expect(client.tenantSubscription.findUnique).toHaveBeenCalledWith({ where: { tenantId: "tenant_1" }, include: { products: { include: { subscriptionProduct: { include: { features: true } }, acquisition: true, prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } }, }, orderBy: { subscriptionProduct: { order: "desc" } }, }, }, }); }); it("fetches all tenant subscriptions with product details", async () => { const client = createTenantSubscriptionClient([]); await expect(getTenantSubscriptions(client)).resolves.toEqual([]); expect(client.tenantSubscription.findMany).toHaveBeenCalledWith({ include: { products: { include: { subscriptionProduct: { include: { features: true } }, acquisition: true, prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } }, }, orderBy: { subscriptionProduct: { order: "desc" } }, }, }, }); }); }); describe("tenant billing boundary", () => { it("creates and updates tenant subscriptions", async () => { const client = createTenantBillingClient([]); await createTenantSubscription({ tenantId: "tenant_1", billingProviderCustomerId: "cus_1" }, client); await updateTenantSubscriptionCustomerId("tenant_1", { billingProviderCustomerId: "cus_2" }, client); await expect(listTenantSubscriptionIds(client)).resolves.toEqual([{ tenantId: "tenant_1" }]); expect(client.tenantSubscription.create).toHaveBeenCalledWith({ data: { tenantId: "tenant_1", billingProviderCustomerId: "cus_1" }, include: { products: { include: { subscriptionProduct: { include: { features: true } }, acquisition: true, prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } }, }, orderBy: { subscriptionProduct: { order: "desc" } }, }, }, }); expect(client.tenantSubscription.update).toHaveBeenCalledWith({ where: { tenantId: "tenant_1" }, data: { billingProviderCustomerId: "cus_2" }, }); expect(client.tenantSubscription.findMany).toHaveBeenCalledWith({ select: { tenantId: true } }); }); it("maps tenant product filters and pagination for admin lists", async () => { const now = new Date("2026-05-06T12:00:00.000Z"); const client = createTenantBillingClient([]); await getAllTenantSubscriptionProducts( { tenantId: "tenant_1", subscriptionProductId: "plan_1", status: "active-not-cancelled" }, { page: 2, pageSize: 25 }, client, now ); const where = { subscriptionProductId: { equals: "plan_1" }, tenantSubscription: { tenantId: { equals: "tenant_1" } }, OR: [{ endsAt: { gte: now } }, { endsAt: null }], cancelledAt: null, }; expect(client.tenantSubscriptionProduct.findMany).toHaveBeenCalledWith({ skip: 25, take: 25, where, include: { subscriptionProduct: { include: { features: true } }, acquisition: true, prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } }, tenantSubscription: { include: { tenant: { select: { id: true, name: true, slug: true, icon: true, logo: true, deactivatedReason: true, active: true, theme: true, themeConfig: true, }, }, }, }, }, orderBy: { createdAt: "desc" }, }); expect(client.tenantSubscriptionProduct.count).toHaveBeenCalledWith({ where }); }); it("maps ended and active-cancelled tenant product filters", async () => { const now = new Date("2026-05-06T12:00:00.000Z"); const client = createTenantBillingClient([]); await getAllTenantSubscriptionProducts({ status: "ended" }, undefined, client, now); await getAllTenantSubscriptionProducts({ status: "active-cancelled" }, undefined, client, now); expect(client.tenantSubscriptionProduct.findMany).toHaveBeenNthCalledWith( 1, expect.objectContaining({ where: expect.objectContaining({ endsAt: { lt: now, not: null } }), }) ); expect(client.tenantSubscriptionProduct.findMany).toHaveBeenNthCalledWith( 2, expect.objectContaining({ where: expect.objectContaining({ OR: [{ endsAt: { gte: now } }, { endsAt: null }], cancelledAt: { not: null } }), }) ); }); it("looks up tenant products by tenant/product, id, and Billing provider subscription id", async () => { const item = { id: "tenant_product_1" }; const client = createTenantBillingClient([item]); await expect(getTenantSubscriptionProduct("tenant_1", "plan_1", client)).resolves.toBe(item); await expect(adminGetTenantSubscriptionProductById("tenant_product_1", client)).resolves.toBe(item); await expect(getTenantSubscriptionProductById({ id: "tenant_product_1", tenantId: "tenant_1" }, client)).resolves.toBe(item); await expect(getTenantSubscriptionProductByBillingProviderSubscriptionId("sub_1", client)).resolves.toBe(item); expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenNthCalledWith( 1, expect.objectContaining({ where: { tenantSubscription: { tenantId: "tenant_1" }, subscriptionProductId: "plan_1" }, }) ); expect(client.tenantSubscriptionProduct.findUnique).toHaveBeenCalledWith(expect.objectContaining({ where: { id: "tenant_product_1" } })); expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenNthCalledWith( 2, expect.objectContaining({ where: { id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } } }) ); expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenNthCalledWith( 3, expect.objectContaining({ where: { billingProviderSubscriptionId: "sub_1" } }) ); }); it("uses the billing product id when no custom entitlement override exists", () => { expect( getEffectiveTenantEntitlementPlanId({ subscriptionProductId: "plan_standard", customEntitlementPlanId: null, }) ).toBe("plan_standard"); }); it("uses the custom entitlement override ahead of the billing product id", () => { expect( getEffectiveTenantEntitlementPlanId({ subscriptionProductId: "plan_standard", customEntitlementPlanId: "entitlements_enterprise_override", }) ).toBe("entitlements_enterprise_override"); }); it("adds, updates, and cancels tenant products while returning tenant ids for cache invalidation", async () => { const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]); await addTenantSubscriptionProduct( { tenantSubscriptionId: "tenant_sub_1", subscriptionProductId: "plan_1", billingProviderSubscriptionId: "sub_1", quantity: 2, fromCheckoutSessionId: "cs_1", prices: [{ subscriptionPriceId: "price_1" }, { subscriptionUsageBasedPriceId: "usage_price_1" }], }, client ); await updateTenantSubscriptionProduct({ id: "tenant_product_1", tenantId: "tenant_1" }, { quantity: 3, endsAt: null }, client); await expect( cancelTenantSubscriptionProduct( { id: "tenant_product_1", tenantId: "tenant_1" }, { cancelledAt: new Date("2026-05-06T00:00:00.000Z"), endsAt: new Date("2026-06-06T00:00:00.000Z") }, client ) ).resolves.toEqual({ tenantId: "tenant_1" }); expect(client.tenantSubscriptionProduct.create).toHaveBeenCalledWith({ data: { tenantSubscriptionId: "tenant_sub_1", subscriptionProductId: "plan_1", billingProviderSubscriptionId: "sub_1", quantity: 2, fromCheckoutSessionId: "cs_1", customEntitlementPlanId: undefined, endsAt: null, cancelledAt: null, prices: { create: [{ subscriptionPriceId: "price_1" }, { subscriptionUsageBasedPriceId: "usage_price_1" }] }, }, include: { tenantSubscription: true }, }); expect(client.tenantSubscriptionProduct.update).toHaveBeenNthCalledWith(1, { where: { id: "tenant_product_1" }, data: { quantity: 3, endsAt: null }, include: { tenantSubscription: true }, }); expect(client.tenantSubscriptionProduct.update).toHaveBeenNthCalledWith(2, { where: { id: "tenant_product_1" }, data: { cancelledAt: new Date("2026-05-06T00:00:00.000Z"), endsAt: new Date("2026-06-06T00:00:00.000Z") }, include: { tenantSubscription: true }, }); }); it("updates only the custom entitlement plan override and returns tenant id", async () => { const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]); await expect( updateTenantSubscriptionProductCustomEntitlementPlan( { id: "tenant_product_1", tenantId: "tenant_1" }, { customEntitlementPlanId: "entitlements_scale_override" }, client ) ).resolves.toEqual({ tenantId: "tenant_1" }); expect(client.tenantSubscriptionProduct.update).toHaveBeenCalledWith({ where: { id: "tenant_product_1" }, data: { customEntitlementPlanId: "entitlements_scale_override" }, select: { tenantSubscription: { select: { tenantId: true, }, }, }, }); }); it("propagates custom entitlement override update rejections", async () => { const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]); const error = new Error("write rejected"); vi.mocked(client.tenantSubscriptionProduct.update).mockRejectedValueOnce(error); await expect( updateTenantSubscriptionProductCustomEntitlementPlan({ id: "tenant_product_1", tenantId: "tenant_1" }, { customEntitlementPlanId: null }, client) ).rejects.toBe(error); }); it("handles checkout status idempotency reads, creates, updates, and missing status", async () => { const client = createTenantBillingClient([]); vi.mocked(client.checkoutSessionStatus.findFirst).mockImplementationOnce(async () => { expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1"); return null; }); await expect(getCheckoutSessionStatus({ id: "cs_missing", tenantId: "tenant_1" }, client)).resolves.toBeNull(); await createCheckoutSessionStatus({ id: "cs_1", tenantId: "tenant_1", email: "user@example.com", fromUrl: "/subscribe/acme" }, client); await updateCheckoutSessionStatus({ id: "cs_1", tenantId: "tenant_1" }, { pending: false, createdUserId: "user_1" }, client); expect(client.checkoutSessionStatus.findFirst).toHaveBeenCalledWith({ where: { id: "cs_missing", tenantId: "tenant_1" }, }); expect(client.checkoutSessionStatus.create).toHaveBeenCalledWith({ data: expect.objectContaining({ id: "cs_1", tenantId: "tenant_1", pending: true, email: "user@example.com", fromUrl: "/subscribe/acme", fromUserId: null, provider: null, providerPaymentId: null, quantity: 1, status: "open", }), }); expect(client.checkoutSessionStatus.update).toHaveBeenCalledWith({ where: { id: "cs_1", tenantId: "tenant_1" }, data: expect.objectContaining({ pending: false, createdUserId: "user_1", createdTenantId: null }), }); }); it("claims a checkout provider lease with an atomic tenant, status, pending, and stale-time compare-and-swap", async () => { const staleBefore = new Date("2026-07-15T10:00:00.000Z"); const claimed = { id: "cs_1", tenantId: "tenant_1", pending: true, status: "provider_claimed_unique" }; const client = createTenantBillingClient([claimed]); await expect( claimCheckoutSessionStatus( { id: "cs_1", tenantId: "tenant_1", expectedStatus: "provider_claimed_stale", claimedStatus: "provider_claimed_unique", updatedBefore: staleBefore, }, client ) ).resolves.toEqual(claimed); expect(client.checkoutSessionStatus.updateMany).toHaveBeenCalledWith({ where: { id: "cs_1", tenantId: "tenant_1", pending: true, status: "provider_claimed_stale", updatedAt: { lte: staleBefore }, }, data: { status: "provider_claimed_unique" }, }); }); it("lets only one checkout taker win and never reads a row after a lost claim", async () => { const client = createTenantBillingClient([]); vi.mocked(client.checkoutSessionStatus.updateMany).mockResolvedValueOnce({ count: 0 }); await expect( claimCheckoutSessionStatus( { id: "cs_1", tenantId: "tenant_1", expectedStatus: "provider_recovery_pending", claimedStatus: "provider_claimed_loser", }, client ) ).resolves.toBeNull(); expect(client.checkoutSessionStatus.findFirst).not.toHaveBeenCalled(); }); it("finalizes only the matching claim token so a late failure cannot overwrite a paid or open checkout", async () => { const client = createTenantBillingClient([]); vi.mocked(client.checkoutSessionStatus.updateMany).mockResolvedValueOnce({ count: 0 }); await expect( transitionClaimedCheckoutSessionStatus( { id: "cs_1", tenantId: "tenant_1", claimedStatus: "provider_claimed_late", data: { pending: true, status: "provider_recovery_pending", providerPaymentId: "tr_1" }, }, client ) ).resolves.toBeNull(); expect(client.checkoutSessionStatus.updateMany).toHaveBeenCalledWith({ where: { id: "cs_1", tenantId: "tenant_1", pending: true, status: "provider_claimed_late" }, data: expect.objectContaining({ pending: true, status: "provider_recovery_pending", providerPaymentId: "tr_1" }), }); expect(client.checkoutSessionStatus.findFirst).not.toHaveBeenCalled(); }); it("persists the exact provider invoice on the matching checkout ledger row and accepts an idempotent replay", async () => { const correlated = { id: "cs_1", tenantId: "tenant_1", providerPaymentId: "tr_1", lagoSubscriptionId: "cs_1", invoiceExternalId: "invoice_lago_1", }; const client = createTenantBillingClient([correlated]); await correlateCheckoutSessionProviderInvoice( { id: "cs_1", tenantId: "tenant_1", providerPaymentId: "tr_1", lagoSubscriptionId: "cs_1", sourceInvoiceExternalId: "cs_1", providerInvoiceExternalId: "invoice_lago_1", }, client ); expect(client.checkoutSessionStatus.updateMany).toHaveBeenCalledWith({ where: { id: "cs_1", tenantId: "tenant_1", providerPaymentId: "tr_1", lagoSubscriptionId: "cs_1", invoiceExternalId: "cs_1", }, data: { invoiceExternalId: "invoice_lago_1" }, }); vi.mocked(client.checkoutSessionStatus.updateMany).mockResolvedValueOnce({ count: 0 }); vi.mocked(client.checkoutSessionStatus.findFirst).mockResolvedValueOnce(correlated as never); await expect( correlateCheckoutSessionProviderInvoice( { id: "cs_1", tenantId: "tenant_1", providerPaymentId: "tr_1", lagoSubscriptionId: "cs_1", sourceInvoiceExternalId: "cs_1", providerInvoiceExternalId: "invoice_lago_1", }, client ) ).resolves.toBeUndefined(); }); it("creates usage records and propagates write rejections", async () => { const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]); const usageData = { tenantId: "tenant_1", tenantSubscriptionId: "tenant_subscription_1", tenantSubscriptionProductPriceId: "tenant_price_1", metricCode: "usage_metric", timestamp: 1_777_777, quantity: 1, billingProviderSubscriptionItemId: "si_1", }; await createTenantSubscriptionUsageRecord(usageData, client); expect(client.tenantSubscriptionUsageRecord.create).toHaveBeenCalledWith({ data: usageData }); const error = new Error("write rejected"); vi.mocked(client.tenantSubscriptionProduct.update).mockRejectedValueOnce(error); await expect(updateTenantSubscriptionProduct({ id: "tenant_product_1", tenantId: "tenant_1" }, { quantity: 4 }, client)).rejects.toBe(error); }); }); describe("billing provider tenant subscription products", () => { it("fetches the tenant subscription product needed by billing webhooks", async () => { const item = { id: "tenant_product_1" }; const client = createBillingProviderTenantSubscriptionProductClient(item); await expect(findTenantSubscriptionProductByBillingProviderSubscriptionId("sub_123", client)).resolves.toBe(item); expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenCalledWith({ where: { billingProviderSubscriptionId: "sub_123" }, select: { id: true, endsAt: true, cancelledAt: true, customEntitlementPlanId: true, tenantSubscription: { select: { tenantId: true, tenant: { select: { id: true, name: true, }, }, }, }, subscriptionProduct: { select: { id: true, title: true, }, }, }, }); }); it("updates Billing provider subscription dates and returns the owning tenant id", async () => { const client = createBillingProviderTenantSubscriptionProductClient(); const data = { cancelledAt: new Date("2026-05-01T00:00:00.000Z"), currentPeriodStart: new Date("2026-05-01T00:00:00.000Z"), currentPeriodEnd: new Date("2026-06-01T00:00:00.000Z"), endsAt: null, }; await expect(updateTenantSubscriptionProductFromBillingProvider("tenant_product_1", data, client)).resolves.toEqual({ tenantId: "tenant_1" }); expect(client.tenantSubscriptionProduct.update).toHaveBeenCalledWith({ where: { id: "tenant_product_1" }, data, select: { tenantSubscription: { select: { tenantId: true, }, }, }, }); }); });