// @vitest-environment node import type { DbClient } from "@hivegrid/db/client.server"; import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server"; import { customerPortalCommercialProducts, evaluateProductAccess, getDefaultProductBlueprint } from "@hivegrid/entitlements"; import { createHash } from "node:crypto"; import { describe, expect, it, vi } from "vitest"; import { CUSTOMER_PORTAL_UAT_ADMIN_EMAIL, CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG, CUSTOMER_PORTAL_UAT_TENANT_SLUG, type CustomerPortalCommercialFixtureCommand, } from "./contracts"; import { applyCustomerPortalCommercialFixture, applyEnterpriseTenantFixture, assessCustomerPortalCommercialFixture, customerPortalCommercialFixtureIds, starterSubscriptionSafetyMatches, type CustomerPortalCommercialFixtureSnapshot, } from "./commercial-fixture"; vi.mock("../../apps/api/src/auth/password", () => ({ hashCurrentPassword: vi.fn(async () => "safe-password-hash"), verifySupportedPassword: vi.fn(async () => true), })); vi.mock("@hivegrid/db/audit-events.server", () => ({ publishAuditEventViaOutbox: vi.fn(async () => undefined) })); const starterTenantId = "tenant-demo-starter"; const proTenantId = "tenant-demo-pro"; const enterpriseTenantId = "tenant-demo-enterprise"; const enterpriseAcquisitionId = "acquisition-enterprise-contract"; const permissionRows = [ { id: "permission-dashboard", name: "app.dashboard.view" }, { id: "permission-portal-admin", name: "portal.admin" }, { id: "permission-portal-read", name: "portal.read" }, { id: "permission-portal-manage-users", name: "portal.manage_users" }, { id: "permission-portal-manage-access", name: "portal.manage_access" }, { id: "permission-portal-activity-read", name: "portal.activity.read" }, { id: "permission-portal-activity-manage", name: "portal.activity.manage" }, { id: "permission-crm-read-own", name: "crm.read_own" }, { id: "permission-projects-read-own", name: "projects.read_own" }, { id: "permission-projects-read-all", name: "projects.read_all" }, ] as const; type CommercialSubscription = NonNullable["subscription"]>; type CommercialAttachedProduct = CommercialSubscription["products"][number]; function enterpriseProduct() { const definition = customerPortalCommercialProducts.enterpriseContract; return { id: "product-enterprise-contract", code: definition.code, kind: definition.source, active: true, public: false, prices: [], features: definition.featureKeys.map((name) => ({ name })), }; } function attachedStarterBaseProduct() { return { id: "tenant-starter-base-product", customEntitlementPlanId: "starter", cancelledAt: null, endsAt: null, billingProviderSubscriptionId: null, lagoSubscriptionId: null, planCode: "starter", seatQuantity: 2, quantity: 2, fromCheckoutSessionId: null, currentPeriodStart: null, currentPeriodEnd: null, prices: [], acquisition: null, subscriptionProduct: { id: "catalog-starter-product", code: "starter", kind: "base_plan", active: true }, }; } function role(kind: "starter" | "pro" | "enterprise", tenantId: string) { const id = kind === "starter" ? customerPortalCommercialFixtureIds.starterRoleId : kind === "pro" ? customerPortalCommercialFixtureIds.proRoleId : customerPortalCommercialFixtureIds.enterpriseRoleId; return { id, tenantId, name: "Customer Portal UAT Admin", description: "Dedicated VA-P26c staging UAT role. Not for real workspace members.", type: "app", assignToNewUsers: false, isDefault: false, order: 990, permissions: permissionRows.map((permission, index) => ({ id: `role-permission-${kind}-${index}`, permission })), }; } function eligibility( planCode: "starter" | "business" | "pro", portalSource: "base_plan" | "contract_override" | "missing", acquisitionId: string | null = null ) { const contract = portalSource === "contract_override"; return { subscriptionActive: true, planCode, portalAllowed: portalSource !== "missing", portalSource, monthlyAddOnRequired: planCode === "starter" || planCode === "pro", monthlyAddOnActive: portalSource !== "missing", monthlyAddOnSubscriptionProductId: null, domainSetupActive: contract, domainSetupIncludedByContract: contract, domainSetupAcquisitionId: null, enterpriseContractAcquisitionId: acquisitionId, domainScopeKey: null, } as const; } function attachedEnterpriseBaseProduct() { return { id: customerPortalCommercialFixtureIds.enterpriseBaseProductId, customEntitlementPlanId: "pro", cancelledAt: null, endsAt: null, billingProviderSubscriptionId: null, lagoSubscriptionId: null, planCode: "pro", seatQuantity: 1, quantity: 1, fromCheckoutSessionId: null, currentPeriodStart: null, currentPeriodEnd: null, prices: [], acquisition: null, subscriptionProduct: { id: "catalog-pro-product", code: "pro", kind: "base_plan", active: true }, }; } function attachedEnterpriseContractProduct() { return { id: enterpriseAcquisitionId, customEntitlementPlanId: null, cancelledAt: null, endsAt: null, billingProviderSubscriptionId: null, lagoSubscriptionId: null, planCode: null, seatQuantity: null, quantity: 1, fromCheckoutSessionId: null, currentPeriodStart: new Date("2026-07-17T00:00:00.000Z"), currentPeriodEnd: null, prices: [], acquisition: { id: enterpriseAcquisitionId }, subscriptionProduct: { id: "product-enterprise-contract", code: customerPortalCommercialProducts.enterpriseContract.code, kind: "contract_override", active: true, }, }; } function enterpriseRequestHash(): string { return createHash("sha256") .update( JSON.stringify({ tenantId: enterpriseTenantId, productId: "product-enterprise-contract", priceId: null, productKind: "contract_override", scopeKey: "tenant", quantity: 1, amountCents: null, currency: null, sourceReference: "VA-P26c-UAT-demo-enterprise-crm", }) ) .digest("hex"); } function healthySnapshot(): CustomerPortalCommercialFixtureSnapshot { return { userCandidates: [ { id: customerPortalCommercialFixtureIds.userId, email: CUSTOMER_PORTAL_UAT_ADMIN_EMAIL, firstName: "Portal", lastName: "UAT Admin", defaultTenantId: starterTenantId, active: true, pendingDeletion: false, pseudonymized: false, hasPlatformAdmin: false, passwordMatches: true, }, ], permissions: permissionRows, enterpriseProducts: [enterpriseProduct()], starterBaseProducts: [{ id: "catalog-starter-product", code: "starter", kind: "base_plan", active: true }], proBaseProducts: [{ id: "catalog-pro-product", code: "pro", kind: "base_plan", active: true }], enterpriseTenantCandidates: [{ id: enterpriseTenantId, slug: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, name: "Demo Enterprise CRM", active: true }], tenants: [ { kind: "starter", expectedId: starterTenantId, expectedSlug: CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG, tenant: { id: starterTenantId, slug: CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG, name: "Demo Starter CRM", active: true, subscription: { id: "subscription-starter", planCode: "starter", seatQuantity: 2, status: "active", billingProviderCustomerId: null, lagoCustomerId: null, mollieCustomerId: null, lastInvoiceExternalId: null, lastPaymentExternalId: null, trialStartsAt: null, trialEndsAt: null, pastDueSince: null, frozenAt: null, cancelledAt: null, dunningAttemptCount: 0, lastDunningSentAt: null, products: [attachedStarterBaseProduct()], }, }, portal: { id: "portal-starter", subdomain: CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG, title: "Demo Starter CRM Kundenportal", isPublished: true, authRequireEmailVerification: false, authRequireOrganization: false, authRequireName: true, metadata: { uatFixture: "VA-P26c-commercial" }, configuration: { id: "portal-configuration-starter", enabledProjectTypes: [], uploadMaxFiles: 10, uploadMaxFileSizeBytes: 52_428_800, statusEmailsEnabled: true, welcomeMessage: "Willkommen im HiveGrid Test-Kundenportal.", supportEmail: "support@saas-ctrl.com", imprintUrl: "https://saas-ctrl.com/impressum", privacyUrl: "https://saas-ctrl.com/datenschutz", isDemoData: true, }, }, roleCandidates: [role("starter", starterTenantId)], membershipCandidates: [ { id: customerPortalCommercialFixtureIds.starterMembershipId, tenantId: starterTenantId, userId: customerPortalCommercialFixtureIds.userId, type: 1, joined: 1, status: 2, }, ], assignmentCandidates: [ { id: customerPortalCommercialFixtureIds.starterAssignmentId, tenantId: starterTenantId, userId: customerPortalCommercialFixtureIds.userId, roleId: customerPortalCommercialFixtureIds.starterRoleId, }, ], monthlyAcquisitions: [], enterpriseAcquisitions: [], checkoutSessions: [], enterpriseContractClaims: [], commercialEligibility: eligibility("starter", "missing"), enterpriseGrantAudited: false, }, { kind: "pro", expectedId: proTenantId, expectedSlug: CUSTOMER_PORTAL_UAT_TENANT_SLUG, tenant: { id: proTenantId, slug: CUSTOMER_PORTAL_UAT_TENANT_SLUG, name: "Demo Pro CRM", active: true, subscription: { id: "subscription-pro", planCode: "business", seatQuantity: 3, status: "active", billingProviderCustomerId: "staging-customer", lagoCustomerId: "staging-lago-customer", mollieCustomerId: "staging-mollie-customer", lastInvoiceExternalId: null, lastPaymentExternalId: null, trialStartsAt: null, trialEndsAt: null, pastDueSince: null, frozenAt: null, cancelledAt: null, dunningAttemptCount: 0, lastDunningSentAt: null, products: [], }, }, portal: { id: "portal-pro", subdomain: CUSTOMER_PORTAL_UAT_TENANT_SLUG, title: "Demo Business CRM Kundenportal", isPublished: true, authRequireEmailVerification: false, authRequireOrganization: false, authRequireName: true, metadata: { uatFixture: "VA-P26" }, configuration: null, }, roleCandidates: [role("pro", proTenantId)], membershipCandidates: [ { id: customerPortalCommercialFixtureIds.proMembershipId, tenantId: proTenantId, userId: customerPortalCommercialFixtureIds.userId, type: 1, joined: 1, status: 2, }, ], assignmentCandidates: [ { id: customerPortalCommercialFixtureIds.proAssignmentId, tenantId: proTenantId, userId: customerPortalCommercialFixtureIds.userId, roleId: customerPortalCommercialFixtureIds.proRoleId, }, ], monthlyAcquisitions: [], enterpriseAcquisitions: [], checkoutSessions: [], enterpriseContractClaims: [], commercialEligibility: eligibility("business", "base_plan"), enterpriseGrantAudited: false, }, { kind: "enterprise", expectedId: enterpriseTenantId, expectedSlug: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, tenant: { id: enterpriseTenantId, slug: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, name: "Demo Enterprise CRM", active: true, subscription: { id: customerPortalCommercialFixtureIds.enterpriseSubscriptionId, planCode: "pro", seatQuantity: 1, status: "active", billingProviderCustomerId: null, lagoCustomerId: null, mollieCustomerId: null, lastInvoiceExternalId: null, lastPaymentExternalId: null, trialStartsAt: null, trialEndsAt: null, pastDueSince: null, frozenAt: null, cancelledAt: null, dunningAttemptCount: 0, lastDunningSentAt: null, products: [attachedEnterpriseBaseProduct(), attachedEnterpriseContractProduct()], }, }, portal: { id: customerPortalCommercialFixtureIds.enterprisePortalId, subdomain: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, title: "Demo Enterprise CRM Kundenportal", isPublished: true, authRequireEmailVerification: false, authRequireOrganization: false, authRequireName: true, metadata: { uatFixture: "VA-P26c-commercial" }, configuration: { id: customerPortalCommercialFixtureIds.enterpriseConfigurationId, enabledProjectTypes: [], uploadMaxFiles: 10, uploadMaxFileSizeBytes: 52_428_800, statusEmailsEnabled: true, welcomeMessage: "Willkommen im HiveGrid Test-Kundenportal.", supportEmail: "support@saas-ctrl.com", imprintUrl: "https://saas-ctrl.com/impressum", privacyUrl: "https://saas-ctrl.com/datenschutz", isDemoData: true, }, }, roleCandidates: [role("enterprise", enterpriseTenantId)], membershipCandidates: [ { id: customerPortalCommercialFixtureIds.enterpriseMembershipId, tenantId: enterpriseTenantId, userId: customerPortalCommercialFixtureIds.userId, type: 1, joined: 1, status: 2, }, ], assignmentCandidates: [ { id: customerPortalCommercialFixtureIds.enterpriseAssignmentId, tenantId: enterpriseTenantId, userId: customerPortalCommercialFixtureIds.userId, roleId: customerPortalCommercialFixtureIds.enterpriseRoleId, }, ], monthlyAcquisitions: [], enterpriseAcquisitions: [ { id: enterpriseAcquisitionId, subscriptionProductId: "product-enterprise-contract", subscriptionPriceId: null, productKind: "contract_override", scopeKey: "tenant", requestHash: enterpriseRequestHash(), status: "active", version: 3, quantity: 1, amountCents: null, currency: null, checkoutSessionId: null, tenantSubscriptionProductId: enterpriseAcquisitionId, provider: null, providerPaymentId: null, invoiceExternalId: null, lagoSubscriptionId: null, checkoutUrl: null, sourceReference: "VA-P26c-UAT-demo-enterprise-crm", providerStartedAt: null, activatedAt: new Date("2026-07-17T00:00:00.000Z"), failedAt: null, cancelledAt: null, expiredAt: null, refundedAt: null, subscriptionProduct: { id: "product-enterprise-contract", code: customerPortalCommercialProducts.enterpriseContract.code, kind: "contract_override", active: true, public: false, }, }, ], checkoutSessions: [], enterpriseContractClaims: [], commercialEligibility: eligibility("pro", "contract_override", enterpriseAcquisitionId), enterpriseGrantAudited: true, }, ], }; } function command(): CustomerPortalCommercialFixtureCommand { return { target: "commercial-fixture", mode: "apply", databaseUrl: "postgresql://hivegrid_app:secret@staging-db:6432/hivegrid", expectedDatabaseHost: "staging-db", expectedDatabasePort: "6432", expectedDatabaseName: "hivegrid", operatorUserId: "operator-user-id", auditChainSecret: "staging-audit-chain-secret-at-least-32-bytes", expectedStarterTenantId: starterTenantId, expectedProTenantId: proTenantId, expectedEnterpriseTenantId: enterpriseTenantId, password: "Q7!portal-UAT-strong-random-2026", }; } describe("customer-portal commercial staging fixture", () => { it("keeps the dedicated UAT role eligible for the projects module gate", () => { const decision = evaluateProductAccess({ blueprintId: getDefaultProductBlueprint().id, featureKey: "projects", hasSubscription: false, tenantRolePermissionNames: permissionRows.map(({ name }) => name), }); expect(decision).toMatchObject({ allowed: true, requiredTenantRolePermission: "projects.read_own" }); }); it("accepts three distinct commercial paths without masking Starter or Business", () => { const assessment = assessCustomerPortalCommercialFixture(healthySnapshot()); expect(assessment.action).toBe("noop"); expect(assessment.liveProof).toMatchObject({ starterMonthlyCheckoutReady: true, businessBasePlanReady: true, enterpriseCatalogReady: true, enterpriseContractGrantReady: true, enterprisePortalSource: "contract_override", enterpriseDomainSetupIncludedByContract: true, enterpriseCheckoutRows: 0, enterpriseAcquisitionId, }); }); it("plans creation of only the dedicated Enterprise tenant when it is absent", () => { const snapshot = healthySnapshot(); const enterprise = snapshot.tenants[2]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, enterpriseTenantCandidates: [], tenants: [ snapshot.tenants[0]!, snapshot.tenants[1]!, { ...enterprise, tenant: null, portal: null, roleCandidates: [], membershipCandidates: [], assignmentCandidates: [], enterpriseAcquisitions: [], enterpriseGrantAudited: false, commercialEligibility: eligibility("pro", "missing"), }, ], }); expect(assessment.action).toBe("reconcile"); expect(assessment.blockingIssues).toEqual([]); expect(assessment.reconcileIssues).toContain("enterprise: create the dedicated deterministic UAT tenant and contract graph"); expect(assessment.liveProof).toMatchObject({ starterMonthlyCheckoutReady: true, businessBasePlanReady: true, enterpriseContractGrantReady: false, enterprisePortalSource: "missing", enterpriseCheckoutRows: 0, }); }); it.each([ ["request hash", { requestHash: "0".repeat(64) }], ["CAS version", { version: 2 }], ["provider payment", { provider: "mollie", providerPaymentId: "payment_foreign" }], ["checkout URL", { checkoutUrl: "https://pay.example.test/checkout" }], ["price", { subscriptionPriceId: "price_foreign", amountCents: 0, currency: "EUR" }], ])("blocks Enterprise %s drift instead of normalizing it", (_label, patch) => { const snapshot = healthySnapshot(); const enterprise = snapshot.tenants[2]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, tenants: [ snapshot.tenants[0]!, snapshot.tenants[1]!, { ...enterprise, enterpriseAcquisitions: [{ ...enterprise.enterpriseAcquisitions[0]!, ...patch }], }, ], }); expect(assessment.action).toBe("blocked"); expect(assessment.blockingIssues).toContain("enterprise: contract_override ledger, CAS state, attachment, audit, or providerless contract has drifted"); }); it("blocks checkout rows and Enterprise overrides on the Business proof tenant", () => { const snapshot = healthySnapshot(); const business = snapshot.tenants[1]!; const enterprise = snapshot.tenants[2]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, tenants: [ snapshot.tenants[0]!, { ...business, enterpriseAcquisitions: enterprise.enterpriseAcquisitions }, { ...enterprise, checkoutSessions: [ { id: "checkout_forbidden", productKind: "contract_override", subscriptionProductId: "product-enterprise-contract", provider: null, providerPaymentId: null, lagoSubscriptionId: null, checkoutUrl: null, }, ], }, ], }); expect(assessment.action).toBe("blocked"); expect(assessment.blockingIssues).toEqual( expect.arrayContaining([ "pro: Enterprise contract_override would mask the commercial path under test", "enterprise: contract_override ledger, CAS state, attachment, audit, or providerless contract has drifted", ]) ); }); it("reconciles missing Enterprise grant audit without changing the contract ledger", () => { const snapshot = healthySnapshot(); const enterprise = snapshot.tenants[2]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, tenants: [snapshot.tenants[0]!, snapshot.tenants[1]!, { ...enterprise, enterpriseGrantAudited: false }], }); expect(assessment.action).toBe("reconcile"); expect(assessment.blockingIssues).toEqual([]); expect(assessment.reconcileIssues).toContain("enterprise: contract_override grant audit evidence missing"); expect(assessment.liveProof.enterpriseContractGrantReady).toBe(false); }); it("reconciles only an empty unpaid starter trial and missing UAT-owned rows", () => { const snapshot = healthySnapshot(); const starter = snapshot.tenants[0]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, userCandidates: [], tenants: [ { ...starter, tenant: { ...starter.tenant!, subscription: { ...starter.tenant!.subscription!, planCode: null, status: "trial", trialStartsAt: new Date(), trialEndsAt: new Date(), products: [], }, }, portal: null, roleCandidates: [], membershipCandidates: [], assignmentCandidates: [], }, snapshot.tenants[1]!, snapshot.tenants[2]!, ], }); expect(assessment.action).toBe("reconcile"); expect(assessment.blockingIssues).toEqual([]); expect(assessment.reconcileIssues).toEqual( expect.arrayContaining([ "dedicated saas-ctrl.com tenant-admin identity missing", "starter: activate the empty starter base subscription for checkout", "starter: UAT-owned published portal missing", ]) ); }); it("reconciles the exact providerless legacy Starter attachment with null denormalized fields", () => { const snapshot = healthySnapshot(); const starter = snapshot.tenants[0]!; const product = starter.tenant!.subscription!.products[0]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, tenants: [ { ...starter, tenant: { ...starter.tenant!, subscription: { ...starter.tenant!.subscription!, seatQuantity: 1, products: [{ ...product, planCode: null, seatQuantity: null, quantity: 1 }], }, }, }, snapshot.tenants[1]!, snapshot.tenants[2]!, ], }); expect(assessment.action).toBe("reconcile"); expect(assessment.blockingIssues).toEqual([]); expect(assessment.reconcileIssues).toContain("starter: normalize the providerless legacy starter base-plan attachment"); expect(assessment.liveProof.starterMonthlyCheckoutReady).toBe(false); }); it.each<[string, Partial]>([ ["only null planCode", { planCode: null, seatQuantity: 2 }], ["only null seatQuantity", { planCode: "starter", seatQuantity: null }], ["wrong quantity", { planCode: null, seatQuantity: null, quantity: 99 }], ["wrong entitlement", { customEntitlementPlanId: "business", planCode: null, seatQuantity: null }], ["provider identity", { billingProviderSubscriptionId: "foreign", planCode: null, seatQuantity: null }], ])("keeps mixed or unsafe legacy Starter state blocked: %s", (_label, patch) => { const snapshot = healthySnapshot(); const starter = snapshot.tenants[0]!; const product = starter.tenant!.subscription!.products[0]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, tenants: [ { ...starter, tenant: { ...starter.tenant!, subscription: { ...starter.tenant!.subscription!, products: [{ ...product, ...patch }], }, }, }, snapshot.tenants[1]!, snapshot.tenants[2]!, ], }); expect(assessment.action).toBe("blocked"); expect(assessment.blockingIssues).toContain("starter: existing subscription product state is not the single providerless canonical starter base plan"); }); it("blocks provider-owned starter billing state and any existing monthly acquisition", () => { const snapshot = healthySnapshot(); const starter = snapshot.tenants[0]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, tenants: [ { ...starter, tenant: { ...starter.tenant!, subscription: { ...starter.tenant!.subscription!, planCode: null, status: "trial", mollieCustomerId: "foreign-customer" }, }, monthlyAcquisitions: [{ id: "existing-monthly", status: "payment_pending", subscriptionProduct: { code: "customer_portal_monthly" } }], }, snapshot.tenants[1]!, snapshot.tenants[2]!, ], }); expect(assessment.action).toBe("blocked"); expect(assessment.blockingIssues).toEqual( expect.arrayContaining([ "starter: existing base subscription has provider, billing, product, or lifecycle state that the UAT fixture may not replace", "starter: portal monthly add-on already has ledger or subscription state; the UAT fixture must not pre-purchase it", ]) ); }); it.each<[string, Partial]>([ ["provider customer", { billingProviderCustomerId: "foreign" }], ["Lago customer", { lagoCustomerId: "foreign" }], ["Mollie customer", { mollieCustomerId: "foreign" }], ["invoice history", { lastInvoiceExternalId: "foreign" }], ["payment history", { lastPaymentExternalId: "foreign" }], ["trial start", { trialStartsAt: new Date("2026-07-17T00:00:00.000Z") }], ["trial end", { trialEndsAt: new Date("2026-07-24T00:00:00.000Z") }], ["past due", { pastDueSince: new Date("2026-07-17T00:00:00.000Z") }], ["dunning attempts", { dunningAttemptCount: 1 }], ["last dunning", { lastDunningSentAt: new Date("2026-07-17T00:00:00.000Z") }], ])("blocks active Starter %s state and never reports checkout-ready", (_label, patch) => { const snapshot = healthySnapshot(); const starter = snapshot.tenants[0]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, tenants: [ { ...starter, tenant: { ...starter.tenant!, subscription: { ...starter.tenant!.subscription!, ...patch } } }, snapshot.tenants[1]!, snapshot.tenants[2]!, ], }); expect(assessment.action).toBe("blocked"); expect(assessment.liveProof.starterMonthlyCheckoutReady).toBe(false); }); it("blocks dunning state on a supposedly unpaid starter trial", () => { const snapshot = healthySnapshot(); const starter = snapshot.tenants[0]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, tenants: [ { ...starter, tenant: { ...starter.tenant!, subscription: { ...starter.tenant!.subscription!, planCode: null, status: "trial", dunningAttemptCount: 1, products: [] }, }, }, snapshot.tenants[1]!, snapshot.tenants[2]!, ], }); expect(assessment.action).toBe("blocked"); }); it("blocks drift in the attached starter plan and seat quantities", () => { const snapshot = healthySnapshot(); const starter = snapshot.tenants[0]!; const attachedProduct = starter.tenant!.subscription!.products[0]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, tenants: [ { ...starter, tenant: { ...starter.tenant!, subscription: { ...starter.tenant!.subscription!, products: [{ ...attachedProduct, planCode: "business", seatQuantity: 1, quantity: 1 }], }, }, }, snapshot.tenants[1]!, snapshot.tenants[2]!, ], }); expect(assessment.action).toBe("blocked"); expect(assessment.blockingIssues).toContain("starter: existing subscription product state is not the single providerless canonical starter base plan"); expect(assessment.liveProof.starterMonthlyCheckoutReady).toBe(false); }); it.each<[string, Partial]>([ ["custom entitlement", { customEntitlementPlanId: "business" }], ["cancellation", { cancelledAt: new Date("2026-07-17T00:00:00.000Z") }], ["end date", { endsAt: new Date("2026-07-17T00:00:00.000Z") }], ["billing provider subscription", { billingProviderSubscriptionId: "foreign" }], ["Lago subscription", { lagoSubscriptionId: "foreign" }], ["plan code", { planCode: "business" }], ["seat quantity", { seatQuantity: 99 }], ["quantity", { quantity: 99 }], ["checkout session", { fromCheckoutSessionId: "foreign" }], ["period start", { currentPeriodStart: new Date("2026-07-17T00:00:00.000Z") }], ["period end", { currentPeriodEnd: new Date("2026-08-17T00:00:00.000Z") }], ["price attachment", { prices: [{ id: "foreign-price" }] }], ["acquisition", { acquisition: { id: "foreign-acquisition" } }], ["catalog code", { subscriptionProduct: { id: "catalog-starter-product", code: "business", kind: "base_plan", active: true } }], ["catalog kind", { subscriptionProduct: { id: "catalog-starter-product", code: "starter", kind: "recurring_add_on", active: true } }], ["catalog active flag", { subscriptionProduct: { id: "catalog-starter-product", code: "starter", kind: "base_plan", active: false } }], ])("detects %s drift during locked starter activation revalidation", (_label, patch) => { const expected = healthySnapshot().tenants[0]!.tenant!.subscription!; const actual: CommercialSubscription = { ...expected, products: [{ ...expected.products[0]!, ...patch }], }; expect(starterSubscriptionSafetyMatches(actual, expected)).toBe(false); }); it("detects parent subscription lifecycle and billing drift during locked activation revalidation", () => { const expected = healthySnapshot().tenants[0]!.tenant!.subscription!; expect(starterSubscriptionSafetyMatches({ ...expected, dunningAttemptCount: 1 }, expected)).toBe(false); expect(starterSubscriptionSafetyMatches({ ...expected, billingProviderCustomerId: "foreign" }, expected)).toBe(false); expect(starterSubscriptionSafetyMatches({ ...expected, seatQuantity: 3 }, expected)).toBe(false); }); it("blocks id, role, permission, portal, and enterprise catalog collisions", () => { const snapshot = healthySnapshot(); const starter = snapshot.tenants[0]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, userCandidates: [{ ...snapshot.userCandidates[0]!, email: "someone@example.test" }], permissions: snapshot.permissions.filter((permission) => permission.name !== "portal.admin"), enterpriseProducts: [{ ...snapshot.enterpriseProducts[0]!, public: true }], tenants: [ { ...starter, portal: { ...starter.portal!, metadata: null }, roleCandidates: [{ ...starter.roleCandidates[0]!, id: "foreign-role" }], }, snapshot.tenants[1]!, snapshot.tenants[2]!, ], }); expect(assessment.action).toBe("blocked"); expect(assessment.blockingIssues).toEqual( expect.arrayContaining([ "dedicated tenant-admin id/email collides with existing or platform-admin data", "global permission catalog is missing or ambiguous for portal.admin", "enterprise contract_override product is missing or differs from the canonical non-public catalog contract", "starter: existing portal is not owned by the VA-P26c commercial fixture", "starter: deterministic portal-admin role id or name collides with existing data", ]) ); }); it.each(permissionRows)("blocks when the global permission catalog is missing $name", (missingPermission) => { const snapshot = healthySnapshot(); const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, permissions: snapshot.permissions.filter((permission) => permission.name !== missingPermission.name), }); expect(assessment.action).toBe("blocked"); expect(assessment.blockingIssues).toContain(`global permission catalog is missing or ambiguous for ${missingPermission.name}`); }); it("reconciles the previous two-permission UAT role to the exact ten-permission contract", () => { const snapshot = healthySnapshot(); const starter = snapshot.tenants[0]!; const previousPermissions = starter.roleCandidates[0]!.permissions.filter((entry) => ["app.dashboard.view", "portal.admin"].includes(entry.permission.name) ); const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, tenants: [ { ...starter, roleCandidates: [{ ...starter.roleCandidates[0]!, permissions: previousPermissions }], }, snapshot.tenants[1]!, snapshot.tenants[2]!, ], }); expect(assessment.action).toBe("reconcile"); expect(assessment.blockingIssues).toEqual([]); expect(assessment.reconcileIssues).toEqual( expect.arrayContaining([ "starter: dedicated UAT role is missing portal.read", "starter: dedicated UAT role is missing portal.manage_users", "starter: dedicated UAT role is missing portal.manage_access", "starter: dedicated UAT role is missing portal.activity.read", "starter: dedicated UAT role is missing portal.activity.manage", "starter: dedicated UAT role is missing crm.read_own", "starter: dedicated UAT role is missing projects.read_own", "starter: dedicated UAT role is missing projects.read_all", ]) ); }); it("blocks a dedicated UAT role with permissions outside the exact contract", () => { const snapshot = healthySnapshot(); const starter = snapshot.tenants[0]!; const assessment = assessCustomerPortalCommercialFixture({ ...snapshot, tenants: [ { ...starter, roleCandidates: [ { ...starter.roleCandidates[0]!, permissions: [ ...starter.roleCandidates[0]!.permissions, { id: "role-permission-starter-unexpected", permission: { id: "permission-unexpected", name: "projects.write_all" }, }, ], }, ], }, snapshot.tenants[1]!, snapshot.tenants[2]!, ], }); expect(assessment.action).toBe("blocked"); expect(assessment.blockingIssues).toContain("starter: dedicated UAT role has unexpected permissions"); }); it("creates the Enterprise tenant, pro base, portal, access graph, contract ledger, and audit in one transaction", async () => { vi.clearAllMocks(); let subscriptionCreated = false; let ledger: Record | null = null; const subscriptionProductCreates: Array> = []; const db = { $transaction: vi.fn(async (runner) => runner(db)), $queryRaw: vi.fn(async (strings: TemplateStringsArray) => { const sql = strings.join(" "); if (sql.includes('FROM "User" AS uat_user')) return [{ id: customerPortalCommercialFixtureIds.userId }]; if (sql.includes('FROM "SubscriptionProduct" AS product')) { return [ { id: "catalog-pro-product", code: "pro", kind: "base_plan", active: true, public: true }, { id: "product-enterprise-contract", code: customerPortalCommercialProducts.enterpriseContract.code, kind: "contract_override", active: true, public: false, }, ]; } return []; }), tenant: { findFirst: vi.fn(async () => null), create: vi.fn(async ({ data }) => data), }, tenantSubscription: { create: vi.fn(async ({ data }) => { subscriptionCreated = true; return data; }), findUnique: vi.fn(async () => subscriptionCreated ? { id: customerPortalCommercialFixtureIds.enterpriseSubscriptionId, status: "active", planCode: "pro", frozenAt: null, cancelledAt: null, lagoCustomerId: null, mollieCustomerId: null, } : null ), }, tenantSubscriptionProduct: { create: vi.fn(async ({ data }) => { subscriptionProductCreates.push(data); return data; }), findFirst: vi.fn(async () => null), }, subscriptionProduct: { findFirst: vi.fn(async () => ({ id: "product-enterprise-contract", code: customerPortalCommercialProducts.enterpriseContract.code, lagoPlanCode: null, kind: "contract_override", active: true, public: false, })), findUnique: vi.fn(async () => ({ id: "product-enterprise-contract", code: customerPortalCommercialProducts.enterpriseContract.code, lagoPlanCode: null, kind: "contract_override", title: "Customer Portal Enterprise Contract", active: true, public: false, prices: [], })), }, portal: { findUnique: vi.fn(async () => null), create: vi.fn(async ({ data }) => data) }, portalConfiguration: { create: vi.fn(async ({ data }) => data) }, role: { findMany: vi.fn(async () => []), create: vi.fn(async ({ data }) => data), update: vi.fn() }, rolePermission: { findFirst: vi.fn(async () => null), create: vi.fn(async ({ data }) => data) }, permission: { findMany: vi.fn(async () => permissionRows) }, tenantUser: { findMany: vi.fn(async () => []), create: vi.fn(async ({ data }) => data), update: vi.fn() }, userRole: { findMany: vi.fn(async () => []), create: vi.fn(async ({ data }) => data) }, tenantProductAcquisition: { findMany: vi.fn(async () => []), findUnique: vi.fn(async () => ledger), create: vi.fn(async ({ data }) => { ledger = { id: enterpriseAcquisitionId, tenantId: enterpriseTenantId, subscriptionProductId: "product-enterprise-contract", subscriptionPriceId: null, productKind: "contract_override", scopeKey: "tenant", requestHash: data.requestHash, status: "payment_pending", version: 1, quantity: 1, amountCents: null, currency: null, checkoutSessionId: null, tenantSubscriptionProductId: null, provider: null, providerPaymentId: null, invoiceExternalId: null, lagoSubscriptionId: null, checkoutUrl: null, sourceReference: "VA-P26c-UAT-demo-enterprise-crm", providerStartedAt: null, failedAt: null, }; return ledger; }), updateMany: vi.fn(async () => { ledger = { ...ledger, status: "provider_pending", version: 2 }; return { count: 1 }; }), update: vi.fn(async () => { ledger = { ...ledger, status: "active", version: 3, tenantSubscriptionProductId: enterpriseAcquisitionId, activatedAt: new Date("2026-07-17T00:00:00.000Z"), }; return ledger; }), }, checkoutSessionStatus: { findMany: vi.fn(async () => []) }, portalDomainHostnameClaim: { findMany: vi.fn(async () => []), findFirst: vi.fn(async () => null), count: vi.fn(async () => 0) }, auditEvent: { findMany: vi.fn(async () => []) }, outboxEvent: { findMany: vi.fn(async () => []) }, } as unknown as DbClient; await expect(applyEnterpriseTenantFixture(db, command(), "catalog-pro-product", "product-enterprise-contract")).resolves.toBeUndefined(); expect(db.$transaction).toHaveBeenCalledTimes(1); expect(db.tenant.create).toHaveBeenCalledWith({ data: expect.objectContaining({ id: enterpriseTenantId, slug: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, active: true }), }); expect(db.tenantSubscription.create).toHaveBeenCalledWith({ data: expect.objectContaining({ id: customerPortalCommercialFixtureIds.enterpriseSubscriptionId, tenantId: enterpriseTenantId, planCode: "pro", status: "active", lagoCustomerId: null, mollieCustomerId: null, }), }); expect(subscriptionProductCreates).toEqual( expect.arrayContaining([ expect.objectContaining({ id: customerPortalCommercialFixtureIds.enterpriseBaseProductId, subscriptionProductId: "catalog-pro-product", planCode: "pro", customEntitlementPlanId: "pro", }), expect.objectContaining({ id: enterpriseAcquisitionId, subscriptionProductId: "product-enterprise-contract", planCode: null, quantity: 1, prices: undefined, }), ]) ); expect(db.portal.create).toHaveBeenCalledWith({ data: expect.objectContaining({ id: customerPortalCommercialFixtureIds.enterprisePortalId, isPublished: true }), }); expect(db.role.create).toHaveBeenCalledWith({ data: expect.objectContaining({ id: customerPortalCommercialFixtureIds.enterpriseRoleId, tenantId: enterpriseTenantId }), }); expect(db.tenantUser.create).toHaveBeenCalledWith({ data: expect.objectContaining({ id: customerPortalCommercialFixtureIds.enterpriseMembershipId, tenantId: enterpriseTenantId }), }); expect(db.userRole.create).toHaveBeenCalledWith({ data: expect.objectContaining({ id: customerPortalCommercialFixtureIds.enterpriseAssignmentId, tenantId: enterpriseTenantId }), }); expect(db.tenantProductAcquisition.create).toHaveBeenCalledWith({ data: expect.objectContaining({ tenantId: enterpriseTenantId, subscriptionProductId: "product-enterprise-contract", subscriptionPriceId: null, productKind: "contract_override", scopeKey: "tenant", quantity: 1, amountCents: null, currency: null, provider: null, }), }); expect(ledger).toMatchObject({ status: "active", version: 3, checkoutSessionId: null, provider: null, providerPaymentId: null, lagoSubscriptionId: null, checkoutUrl: null, }); expect(vi.mocked(publishAuditEventViaOutbox)).toHaveBeenCalledWith( db, expect.objectContaining({ action: "billing.product_acquisition.contract_granted", targetId: enterpriseAcquisitionId }) ); const lockSql = vi .mocked(db.$queryRaw) .mock.calls.map(([strings]) => (strings as TemplateStringsArray).join(" ")) .join("\n"); expect(lockSql).toContain("pg_advisory_xact_lock"); expect(lockSql).toContain('::text AS "lock"'); expect(lockSql).toContain("FOR UPDATE"); }); it("applies only guarded identity, subscription, attachment, portal, permission, and membership writes", async () => { const snapshot = healthySnapshot(); const starter = snapshot.tenants[0]!; const reconcilable: CustomerPortalCommercialFixtureSnapshot = { ...snapshot, userCandidates: [], tenants: [ { ...starter, tenant: { ...starter.tenant!, subscription: { ...starter.tenant!.subscription!, planCode: null, status: "trial", products: [] }, }, portal: null, roleCandidates: [], membershipCandidates: [], assignmentCandidates: [], }, { ...snapshot.tenants[1]!, roleCandidates: [], membershipCandidates: [], assignmentCandidates: [] }, snapshot.tenants[2]!, ], }; let lockedSnapshot = reconcilable; const db = { $transaction: vi.fn(async (runner) => runner(db)), $queryRaw: vi.fn(async (strings: TemplateStringsArray) => { const sql = strings.join(" "); if (sql.includes('FROM "Tenant" AS target_tenant')) return [{ id: "tenant-lock" }]; if (sql.includes('FROM "User" AS uat_user')) return []; if (sql.includes('FROM "TenantSubscription"')) return [{ id: "subscription-starter" }]; if (sql.includes('FROM "TenantSubscriptionProduct"')) { return lockedSnapshot.tenants[0]!.tenant!.subscription!.products.map((product) => ({ id: product.id })); } if (sql.includes('FROM "SubscriptionProduct"')) return [{ id: "catalog-starter-product", code: "starter", kind: "base_plan", active: true }]; return []; }), user: { findMany: vi.fn(async () => []), findUnique: vi.fn(async () => ({ id: customerPortalCommercialFixtureIds.userId, email: CUSTOMER_PORTAL_UAT_ADMIN_EMAIL, pendingDeletion: false, pseudonymized: false, admin: null, })), create: vi.fn(async () => ({ id: customerPortalCommercialFixtureIds.userId })), update: vi.fn(async () => ({ id: customerPortalCommercialFixtureIds.userId })), }, permission: { findMany: vi.fn(async () => permissionRows) }, tenant: { findFirst: vi.fn(async ({ where }) => (where.id === starterTenantId ? lockedSnapshot.tenants[0]!.tenant : lockedSnapshot.tenants[1]!.tenant)), }, tenantSubscription: { findUnique: vi.fn(async () => lockedSnapshot.tenants[0]!.tenant!.subscription), updateMany: vi.fn(async () => ({ count: 1 })), }, tenantSubscriptionProduct: { findMany: vi.fn(async () => []), create: vi.fn(async ({ data }) => data), updateMany: vi.fn(async () => ({ count: 1 })), }, portal: { findUnique: vi.fn(async ({ where }) => (where.tenantId === starterTenantId ? lockedSnapshot.tenants[0]!.portal : lockedSnapshot.tenants[1]!.portal)), create: vi.fn(async () => ({ id: "portal-starter" })), update: vi.fn(async () => ({ id: "portal-starter" })), }, portalConfiguration: { create: vi.fn(async () => ({ id: "configuration-starter" })), update: vi.fn(async () => ({ id: "configuration-starter" })), }, role: { findMany: vi.fn(async () => []), create: vi.fn(async ({ data }) => ({ id: data.id })), update: vi.fn(async ({ where }) => ({ id: where.id })), }, rolePermission: { findFirst: vi.fn(async () => null), create: vi.fn(async ({ data }) => data) }, tenantUser: { findMany: vi.fn(async () => []), create: vi.fn(async ({ data }) => ({ id: data.id })), update: vi.fn(async ({ where }) => ({ id: where.id })), }, userRole: { findMany: vi.fn(async () => []), create: vi.fn(async ({ data }) => ({ id: data.id })), update: vi.fn(async ({ where }) => ({ id: where.id })), }, tenantProductAcquisition: { findMany: vi.fn(async () => []), create: vi.fn() }, checkoutSessionStatus: { findMany: vi.fn(async () => []) }, portalDomainHostnameClaim: { findMany: vi.fn(async () => []), findFirst: vi.fn(async () => null), count: vi.fn(async () => 0) }, auditEvent: { findMany: vi.fn(async () => []) }, outboxEvent: { findMany: vi.fn(async () => []) }, } as unknown as DbClient; await expect(applyCustomerPortalCommercialFixture(db, command(), reconcilable)).resolves.toBeUndefined(); expect(db.user.create).toHaveBeenCalledTimes(1); expect(db.tenantSubscription.updateMany).toHaveBeenCalledTimes(1); expect(db.tenantSubscriptionProduct.create).toHaveBeenCalledTimes(1); expect(db.portal.create).toHaveBeenCalledTimes(1); expect(db.tenantUser.create).toHaveBeenCalledTimes(2); expect(db.userRole.create).toHaveBeenCalledTimes(2); expect(db.tenantProductAcquisition.create).not.toHaveBeenCalled(); const lockSql = vi .mocked(db.$queryRaw) .mock.calls.map(([strings]) => (strings as TemplateStringsArray).join(" ")) .join("\n"); expect(lockSql).toContain("FOR UPDATE"); expect(lockSql).toContain('FROM "User" AS uat_user'); expect(lockSql).toContain('FROM "Tenant" AS target_tenant'); expect(lockSql).toContain('FROM "Portal" AS portal'); expect(lockSql).toContain('FROM "Role" AS role'); expect(lockSql).toContain('FROM "TenantSubscriptionProduct" AS attached'); expect(db.user.findMany).toHaveBeenCalled(); expect(db.tenant.findFirst).toHaveBeenCalledTimes(2); const legacySnapshot = healthySnapshot(); const legacyStarter = legacySnapshot.tenants[0]!; const legacyProduct = legacyStarter.tenant!.subscription!.products[0]!; lockedSnapshot = { ...legacySnapshot, tenants: [ { ...legacyStarter, tenant: { ...legacyStarter.tenant!, subscription: { ...legacyStarter.tenant!.subscription!, seatQuantity: 1, products: [{ ...legacyProduct, planCode: null, seatQuantity: null, quantity: 1 }], }, }, }, legacySnapshot.tenants[1]!, legacySnapshot.tenants[2]!, ], }; vi.clearAllMocks(); await expect(applyCustomerPortalCommercialFixture(db, command(), lockedSnapshot)).resolves.toBeUndefined(); expect(db.tenantSubscriptionProduct.create).not.toHaveBeenCalled(); expect(db.tenantSubscriptionProduct.updateMany).toHaveBeenCalledTimes(1); expect(db.tenantSubscriptionProduct.updateMany).toHaveBeenCalledWith({ where: expect.objectContaining({ id: legacyProduct.id, tenantSubscriptionId: "subscription-starter", subscriptionProductId: "catalog-starter-product", customEntitlementPlanId: "starter", planCode: null, seatQuantity: null, quantity: 1, billingProviderSubscriptionId: null, lagoSubscriptionId: null, prices: { none: {} }, acquisition: null, }), data: { planCode: "starter", seatQuantity: 1 }, }); expect(db.tenantSubscription.updateMany).toHaveBeenCalledWith( expect.objectContaining({ where: expect.objectContaining({ planCode: "starter", seatQuantity: 1, status: "active" }), }) ); vi.clearAllMocks(); vi.mocked(db.tenantSubscriptionProduct.updateMany).mockResolvedValueOnce({ count: 0 }); await expect(applyCustomerPortalCommercialFixture(db, command(), lockedSnapshot)).rejects.toThrow( "legacy starter attachment changed after guarded preflight" ); }); });