import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ featureFlagFindFirst: vi.fn(), tenantFindMany: vi.fn(), tenantUserCount: vi.fn(), tenantSubscriptionFindUnique: vi.fn(), overrideUpsert: vi.fn(), featureFlagAuditCreate: vi.fn(), recordAdminAction: vi.fn(), runWithRlsContext: vi.fn(), })); vi.mock("~/utils/db.server", () => ({ db: { featureFlag: { findFirst: mocks.featureFlagFindFirst }, tenant: { findMany: mocks.tenantFindMany }, tenantUser: { count: mocks.tenantUserCount }, tenantSubscription: { findUnique: mocks.tenantSubscriptionFindUnique }, $transaction: vi.fn(async (operation: (transaction: unknown) => unknown) => operation({ featureFlag: { findFirst: mocks.featureFlagFindFirst }, tenant: { findMany: mocks.tenantFindMany }, adminFeatureFlagOverride: { upsert: mocks.overrideUpsert }, featureFlagAudit: { create: mocks.featureFlagAuditCreate }, }) ), }, })); vi.mock("@hivegrid/db/rls-context.server", () => ({ runWithRlsContext: (context: unknown, callback: () => unknown) => mocks.runWithRlsContext(context, callback), })); vi.mock("~/services/admin/admin-action-audit.server", () => ({ assertAdminActionReason: (reason: string) => { const normalized = reason.trim(); if (normalized.length < 5) throw new Error("reason"); return normalized; }, recordAdminAction: mocks.recordAdminAction, })); import { AdminFeatureFlagRolloutError, applyAdminFeatureFlagBulkOverride, getAdminFeatureFlagRolloutView, normalizeTenantIds, } from "./feature-flag-rollout.server"; beforeEach(() => { vi.clearAllMocks(); mocks.runWithRlsContext.mockImplementation((_context: unknown, callback: () => unknown) => callback()); }); describe("admin feature flag rollout preview", () => { it("bounds tenant hydration concurrency while preserving full deterministic output", async () => { const tenantIds = Array.from({ length: 6 }, (_, index) => `tenant-${index + 1}`); const gates = new Map(tenantIds.map((tenantId) => [tenantId, createDeferred()])); const started: string[] = []; const completed: string[] = []; let active = 0; let maxActive = 0; mocks.featureFlagFindFirst.mockResolvedValue({ id: "flag-1", key: "sales_workspace", name: "Sales Workspace", description: "Sales Workspace", defaultValue: false, enabled: false, lifecycleStage: "rollout", filters: [ { id: "filter-pilot", name: "Pilot tenants", priority: 10, resultValue: true, active: true, createdAt: new Date("2026-07-01T00:00:00.000Z"), criteria: { tenantIdIn: ["tenant-1", "tenant-3", "tenant-6"] }, }, ], tenantOverrides: [{ tenantId: "tenant-2", value: true, expiresAt: null }], }); mocks.tenantFindMany.mockResolvedValue( tenantIds.map((id, index) => ({ id, name: `Tenant ${index + 1}`, slug: id, createdAt: new Date(`2026-06-0${index + 1}T00:00:00.000Z`), active: id !== "tenant-4", })) ); mocks.tenantUserCount.mockImplementation( async (input: { where: { tenantId: string } }) => ({ "tenant-1": 1, "tenant-2": 11, "tenant-3": 26, "tenant-4": 51, "tenant-5": 101, "tenant-6": 0 })[input.where.tenantId] ); mocks.tenantSubscriptionFindUnique.mockImplementation(async (input: { where: { tenantId: string } }) => { await gates.get(input.where.tenantId)!.promise; return input.where.tenantId === "tenant-1" ? { status: "trialing", products: [{ subscriptionProductId: "product-pro" }] } : null; }); mocks.runWithRlsContext.mockImplementation(async (context: { tenantId: string }, callback: () => Promise) => { active += 1; maxActive = Math.max(maxActive, active); started.push(context.tenantId); try { return await callback(); } finally { active -= 1; completed.push(context.tenantId); } }); const viewPromise = getAdminFeatureFlagRolloutView("sales_workspace", new Date("2026-07-29T00:00:00.000Z")); await vi.waitFor(() => expect(started).toEqual(["tenant-1", "tenant-2", "tenant-3", "tenant-4"])); expect(maxActive).toBe(4); gates.get("tenant-4")!.resolve(); await vi.waitFor(() => expect(started).toEqual(["tenant-1", "tenant-2", "tenant-3", "tenant-4", "tenant-5"])); gates.get("tenant-2")!.resolve(); await vi.waitFor(() => expect(started).toEqual(["tenant-1", "tenant-2", "tenant-3", "tenant-4", "tenant-5", "tenant-6"])); for (const gate of gates.values()) gate.resolve(); const view = await viewPromise; expect(maxActive).toBe(4); expect(completed.slice(0, 2)).toEqual(["tenant-4", "tenant-2"]); expect(view?.tenants.map((tenant) => tenant.id)).toEqual(tenantIds); expect(view?.tenants.map((tenant) => tenant.size)).toEqual(["1-10", "11-25", "26-50", "51-100", "100+", "1-10"]); expect(view?.tenants[0]).toMatchObject({ status: "trialing", subscriptionProductIds: ["product-pro"], }); expect(view?.tenants[3]).toMatchObject({ status: "inactive", subscriptionProductIds: [] }); expect(view?.preview).toEqual({ enabled: 4, disabled: 2, overrides: 1, filtered: 3, defaulted: 2, rows: [ { tenantId: "tenant-1", decision: { value: true, source: "filter", filterId: "filter-pilot" } }, { tenantId: "tenant-2", decision: { value: true, source: "override", filterId: null } }, { tenantId: "tenant-3", decision: { value: true, source: "filter", filterId: "filter-pilot" } }, { tenantId: "tenant-4", decision: { value: false, source: "default", filterId: null } }, { tenantId: "tenant-5", decision: { value: false, source: "default", filterId: null } }, { tenantId: "tenant-6", decision: { value: true, source: "filter", filterId: "filter-pilot" } }, ], }); }); }); describe("admin feature flag bulk override input", () => { it("normalizes, deduplicates and sorts tenant identifiers", () => { expect(normalizeTenantIds([" tenant-b ", "tenant-a", "tenant-b"])).toEqual(["tenant-a", "tenant-b"]); }); it("rejects an empty selection and oversized batches", () => { expect(() => normalizeTenantIds([])).toThrow(AdminFeatureFlagRolloutError); expect(() => normalizeTenantIds(Array.from({ length: 501 }, (_, index) => `tenant-${index}`))).toThrow( AdminFeatureFlagRolloutError ); }); it("persists every override and both append-only audit contracts in one transaction", async () => { mocks.featureFlagFindFirst.mockResolvedValue({ id: "flag-1", key: "sales_workspace", name: "Sales Workspace", }); mocks.tenantFindMany.mockResolvedValue([{ id: "tenant-a" }, { id: "tenant-b" }]); await expect( applyAdminFeatureFlagBulkOverride({ flagKey: "sales_workspace", tenantIds: ["tenant-b", "tenant-a"], value: true, actorAdminUserId: "admin-raffael", reason: "Pilotgruppe freigeben", note: "Vertriebspilot", }) ).resolves.toEqual({ updated: 2 }); expect(mocks.overrideUpsert).toHaveBeenCalledTimes(2); expect(mocks.overrideUpsert.mock.calls.map(([input]) => input.where)).toEqual([ { admin_feature_flag_override_flag_tenant_key: { featureFlagId: "flag-1", tenantId: "tenant-a", }, }, { admin_feature_flag_override_flag_tenant_key: { featureFlagId: "flag-1", tenantId: "tenant-b", }, }, ]); expect(mocks.featureFlagAuditCreate).toHaveBeenCalledWith({ data: expect.objectContaining({ flagId: "flag-1", actorUserId: "admin-raffael", actorType: "admin", action: "bulk_override", metadata: { reason: "Pilotgruppe freigeben", tenantIds: ["tenant-a", "tenant-b"], }, }), }); expect(mocks.recordAdminAction).toHaveBeenCalledWith( expect.objectContaining({ action: "featureFlag.bulkOverride", actorUserId: "admin-raffael", targetKind: "FeatureFlag", targetId: "flag-1", reason: "Pilotgruppe freigeben", }), expect.any(Object) ); }); }); function createDeferred(): { readonly promise: Promise; readonly resolve: () => void } { let resolve!: () => void; const promise = new Promise((resolvePromise) => { resolve = resolvePromise; }); return { promise, resolve }; }