import { beforeEach, describe, expect, it, vi } from "vitest"; const billingDomainMock = vi.hoisted(() => ({ resolveTenantBillingState: vi.fn(), })); const rlsMock = vi.hoisted(() => ({ getDbClient: vi.fn(() => ({ marker: "rls-client" })), runWithRlsContext: vi.fn((_context: unknown, callback: () => unknown) => callback()), })); const storageMock = vi.hoisted(() => ({ resolveTenantStorageUsage: vi.fn(), })); const dbMock = vi.hoisted(() => ({ tenantSubscription: { findUnique: vi.fn(), }, tenantSubscriptionUsageRecord: { findUnique: vi.fn(), groupBy: vi.fn(), upsert: vi.fn(), }, })); vi.mock("~/utils/db.server", () => ({ db: dbMock, })); vi.mock("@hivegrid/db/billing-domain.server", () => ({ resolveTenantBillingState: billingDomainMock.resolveTenantBillingState, })); vi.mock("@hivegrid/db/client.server", () => ({ getDbClient: rlsMock.getDbClient, })); vi.mock("@hivegrid/db/rls-context.server", () => ({ runWithRlsContext: rlsMock.runWithRlsContext, })); vi.mock("~/services/billing/storage-capacity.server", () => ({ resolveTenantStorageUsage: storageMock.resolveTenantStorageUsage, })); vi.mock("./subscriptionService", () => ({ clearTenantSubscriptionCache: vi.fn(), })); import { assertBillingUsageWithinQuota, BILLING_USAGE_METRICS, BillingUsageQuotaExceededError, getBillingUsageSummary, getTenantBillingReadOnlyState, isTenantBillingReadOnly, recordBillingUsage, } from "./billingStatusService"; describe("billingStatusService", () => { beforeEach(() => { vi.clearAllMocks(); storageMock.resolveTenantStorageUsage.mockResolvedValue({ available: false, reason: "subscription_missing" }); }); it("marks past-due, frozen and cancelled subscriptions as read-only", () => { expect(isTenantBillingReadOnly("trial")).toBe(false); expect(isTenantBillingReadOnly("active")).toBe(false); expect(isTenantBillingReadOnly("past_due")).toBe(true); expect(isTenantBillingReadOnly("frozen")).toBe(true); expect(isTenantBillingReadOnly("cancelled")).toBe(true); }); it("reads tenant billing status for action write guards", async () => { billingDomainMock.resolveTenantBillingState.mockResolvedValue({ status: "frozen", readOnly: true }); await expect(getTenantBillingReadOnlyState("tenant_1")).resolves.toEqual({ readOnly: true, status: "frozen" }); expect(billingDomainMock.resolveTenantBillingState).toHaveBeenCalledWith("tenant_1"); }); it("returns usage summary with quota state from subscription features", async () => { dbMock.tenantSubscription.findUnique.mockResolvedValue(subscriptionWithQuota(10)); dbMock.tenantSubscriptionUsageRecord.groupBy.mockResolvedValue([{ metricCode: BILLING_USAGE_METRICS.automationRuns, _sum: { quantity: 8 } }]); await expect(getBillingUsageSummary("tenant_1", new Date("2026-07-12T00:00:00.000Z"))).resolves.toMatchObject({ periodStart: new Date("2026-07-01T00:00:00.000Z"), periodEnd: new Date("2026-08-01T00:00:00.000Z"), metrics: expect.arrayContaining([ { metricCode: BILLING_USAGE_METRICS.automationRuns, quantity: 8, quota: 10, remaining: 2, exceeded: false, percentUsed: 80, }, ]), }); expect(rlsMock.runWithRlsContext).toHaveBeenCalledWith({ tenantId: "tenant_1" }, expect.any(Function)); }); it("projects stored and reserved bytes against the canonical commercial storage capacity", async () => { const capacityBytes = 350 * 1024 ** 3; dbMock.tenantSubscription.findUnique.mockResolvedValue(subscriptionWithQuota(10)); dbMock.tenantSubscriptionUsageRecord.groupBy.mockResolvedValue([]); storageMock.resolveTenantStorageUsage.mockResolvedValue({ available: true, capacityBytes, storedBytes: 50, reservedBytes: 25, remainingBytes: capacityBytes - 75, }); const summary = await getBillingUsageSummary("tenant_1", new Date("2026-07-12T00:00:00.000Z")); expect(summary.storageUnavailableReason).toBeNull(); expect(summary.metrics).toContainEqual({ metricCode: BILLING_USAGE_METRICS.storageBytes, quantity: 75, quota: capacityBytes, remaining: capacityBytes - 75, exceeded: false, percentUsed: 0, }); expect(storageMock.resolveTenantStorageUsage).toHaveBeenCalledWith({ marker: "rls-client" }, "tenant_1", new Date("2026-07-12T00:00:00.000Z")); }); it("reports unavailable storage without presenting it as an unlimited allowance", async () => { dbMock.tenantSubscription.findUnique.mockResolvedValue(null); dbMock.tenantSubscriptionUsageRecord.groupBy.mockResolvedValue([]); storageMock.resolveTenantStorageUsage.mockResolvedValue({ available: false, reason: "plan_unknown" }); await expect(getBillingUsageSummary("tenant_1")).resolves.toMatchObject({ storageUnavailableReason: "plan_unknown" }); }); it("throws a quota error before usage exceeds the current period limit", async () => { dbMock.tenantSubscription.findUnique.mockResolvedValue(subscriptionWithQuota(10)); dbMock.tenantSubscriptionUsageRecord.groupBy.mockResolvedValue([{ metricCode: BILLING_USAGE_METRICS.automationRuns, _sum: { quantity: 9 } }]); await expect(assertBillingUsageWithinQuota({ tenantId: "tenant_1", metricCode: BILLING_USAGE_METRICS.automationRuns, quantity: 2 })).rejects.toBeInstanceOf( BillingUsageQuotaExceededError ); expect(storageMock.resolveTenantStorageUsage).not.toHaveBeenCalled(); }); it("records usage idempotently and does not double-count retries", async () => { const existing = { id: "usage_1", quantity: 1 }; dbMock.tenantSubscriptionUsageRecord.findUnique.mockResolvedValue(existing); await expect( recordBillingUsage({ tenantId: "tenant_1", metricCode: BILLING_USAGE_METRICS.automationRuns, quantity: 1, idempotencyKey: "job_1" }) ).resolves.toBe(existing); expect(dbMock.tenantSubscription.findUnique).not.toHaveBeenCalled(); expect(dbMock.tenantSubscriptionUsageRecord.upsert).not.toHaveBeenCalled(); }); }); function subscriptionWithQuota(limit: number) { return { id: "subscription_1", products: [ { quantity: 1, subscriptionProduct: { features: [ { code: BILLING_USAGE_METRICS.automationRuns, name: BILLING_USAGE_METRICS.automationRuns, quotaValue: { [BILLING_USAGE_METRICS.automationRuns]: limit }, type: 2, value: limit, accumulate: false, }, ], }, prices: [ { id: "tenant_price_1", subscriptionUsageBasedPrice: { unit: BILLING_USAGE_METRICS.automationRuns, usageType: BILLING_USAGE_METRICS.automationRuns, }, }, ], }, ], }; }