import { hashCurrentPassword, verifySupportedPassword } from "../../apps/api/src/auth/password"; import { createHash } from "node:crypto"; import { isDeepStrictEqual } from "node:util"; import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server"; import type { DbClient } from "@hivegrid/db/client.server"; import { runWithRlsContext } from "@hivegrid/db/rls-context.server"; import { customerPortalCommercialProducts } from "@hivegrid/entitlements"; import { grantContractProductAcquisition, type ProductAcquisitionClient } from "../../apps/web/app/services/billing/product-acquisition.server"; import { getCustomerPortalCommercialEligibility, grantEnterpriseCustomerPortalContract, portalEnterpriseClaimScopeKey, type CustomerPortalCommercialEligibility, } from "../../apps/web/app/services/customer-portal/portal-domain-commercial.server"; import { CUSTOMER_PORTAL_UAT_ADMIN_EMAIL, CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG, CUSTOMER_PORTAL_UAT_TENANT_SLUG, CustomerPortalUatError, type CustomerPortalCommercialFixtureCommand, } from "./contracts"; const UAT_ADMIN_USER_ID = "customer-portal-uat-tenant-admin"; const UAT_ROLE_NAME = "Customer Portal UAT Admin"; const UAT_ROLE_DESCRIPTION = "Dedicated VA-P26c staging UAT role. Not for real workspace members."; const UAT_PORTAL_MARKER = "VA-P26c-commercial"; const UAT_ENTERPRISE_TENANT_NAME = "Demo Enterprise CRM"; const UAT_ENTERPRISE_SUBSCRIPTION_ID = "customer-portal-uat-enterprise-subscription"; const UAT_ENTERPRISE_BASE_PRODUCT_ID = "customer-portal-uat-enterprise-base-product"; const UAT_ENTERPRISE_PORTAL_ID = "customer-portal-uat-demo-enterprise-crm"; const UAT_ENTERPRISE_CONFIGURATION_ID = "customer-portal-uat-enterprise-configuration"; const UAT_ENTERPRISE_CONTRACT_REFERENCE = "VA-P26c-UAT-demo-enterprise-crm"; const UAT_ENTERPRISE_SCOPE_KEY = "tenant"; const UAT_ENTERPRISE_AUDIT_ACTION = "billing.product_acquisition.contract_granted"; const UAT_REQUIRED_PERMISSIONS = [ "app.dashboard.view", "portal.admin", "portal.read", "portal.manage_users", "portal.manage_access", "portal.activity.read", "portal.activity.manage", "crm.read_own", "projects.read_own", "projects.read_all", ] as const; const UAT_LEGAL_ORIGIN = "https://saas-ctrl.com"; type CommercialTenantKind = "starter" | "pro" | "enterprise"; type UatUserSnapshot = { readonly id: string; readonly email: string; readonly firstName: string; readonly lastName: string; readonly defaultTenantId: string | null; readonly active: boolean; readonly pendingDeletion: boolean; readonly pseudonymized: boolean; readonly hasPlatformAdmin: boolean; readonly passwordMatches: boolean; }; type UatTenantSnapshot = { readonly kind: CommercialTenantKind; readonly expectedId: string; readonly expectedSlug: string; readonly tenant: { readonly id: string; readonly slug: string; readonly name: string; readonly active: boolean; readonly subscription: { readonly id: string; readonly planCode: string | null; readonly seatQuantity: number; readonly status: string; readonly billingProviderCustomerId: string | null; readonly lagoCustomerId: string | null; readonly mollieCustomerId: string | null; readonly lastInvoiceExternalId: string | null; readonly lastPaymentExternalId: string | null; readonly trialStartsAt: Date | null; readonly trialEndsAt: Date | null; readonly pastDueSince: Date | null; readonly frozenAt: Date | null; readonly cancelledAt: Date | null; readonly dunningAttemptCount: number; readonly lastDunningSentAt: Date | null; readonly products: readonly { readonly id: string; readonly customEntitlementPlanId: string | null; readonly cancelledAt: Date | null; readonly endsAt: Date | null; readonly billingProviderSubscriptionId: string | null; readonly lagoSubscriptionId: string | null; readonly planCode: string | null; readonly seatQuantity: number | null; readonly quantity: number | null; readonly fromCheckoutSessionId: string | null; readonly currentPeriodStart: Date | null; readonly currentPeriodEnd: Date | null; readonly prices: readonly { readonly id: string }[]; readonly acquisition: { readonly id: string } | null; readonly subscriptionProduct: { readonly id: string; readonly code: string | null; readonly kind: string; readonly active: boolean }; }[]; } | null; } | null; readonly portal: { readonly id: string; readonly subdomain: string; readonly title: string; readonly isPublished: boolean; readonly authRequireEmailVerification: boolean; readonly authRequireOrganization: boolean; readonly authRequireName: boolean; readonly metadata: unknown; readonly configuration: { readonly id: string; readonly enabledProjectTypes: readonly string[]; readonly uploadMaxFiles: number; readonly uploadMaxFileSizeBytes: number; readonly statusEmailsEnabled: boolean; readonly welcomeMessage: string | null; readonly supportEmail: string | null; readonly imprintUrl: string | null; readonly privacyUrl: string | null; readonly isDemoData: boolean; } | null; } | null; readonly roleCandidates: readonly { readonly id: string; readonly tenantId: string | null; readonly name: string; readonly description: string; readonly type: string; readonly assignToNewUsers: boolean; readonly isDefault: boolean; readonly order: number; readonly permissions: readonly { readonly id: string; readonly permission: { readonly id: string; readonly name: string } }[]; }[]; readonly membershipCandidates: readonly { readonly id: string; readonly tenantId: string; readonly userId: string; readonly type: number; readonly joined: number; readonly status: number; }[]; readonly assignmentCandidates: readonly { readonly id: string; readonly tenantId: string | null; readonly userId: string; readonly roleId: string; }[]; readonly monthlyAcquisitions: readonly { readonly id: string; readonly status: string; readonly subscriptionProduct: { readonly code: string | null }; }[]; readonly enterpriseAcquisitions: readonly { readonly id: string; readonly subscriptionProductId: string; readonly subscriptionPriceId: string | null; readonly productKind: string; readonly scopeKey: string; readonly requestHash: string; readonly status: string; readonly version: number; readonly quantity: number; readonly amountCents: number | null; readonly currency: string | null; readonly checkoutSessionId: string | null; readonly tenantSubscriptionProductId: string | null; readonly provider: string | null; readonly providerPaymentId: string | null; readonly invoiceExternalId: string | null; readonly lagoSubscriptionId: string | null; readonly checkoutUrl: string | null; readonly sourceReference: string | null; readonly providerStartedAt: Date | null; readonly activatedAt: Date | null; readonly failedAt: Date | null; readonly cancelledAt: Date | null; readonly expiredAt: Date | null; readonly refundedAt: Date | null; readonly subscriptionProduct: { readonly id: string; readonly code: string | null; readonly kind: string; readonly active: boolean; readonly public: boolean; }; }[]; readonly checkoutSessions: readonly { readonly id: string; readonly productKind: string; readonly subscriptionProductId: string | null; readonly provider: string | null; readonly providerPaymentId: string | null; readonly lagoSubscriptionId: string | null; readonly checkoutUrl: string | null; }[]; readonly enterpriseContractClaims: readonly { readonly id: string; readonly billingScopeKey: string | null }[]; readonly commercialEligibility: CustomerPortalCommercialEligibility; readonly enterpriseGrantAudited: boolean; }; export type CustomerPortalCommercialFixtureSnapshot = { readonly userCandidates: readonly UatUserSnapshot[]; readonly permissions: readonly { readonly id: string; readonly name: string }[]; readonly enterpriseProducts: readonly { readonly id: string; readonly code: string | null; readonly kind: string; readonly active: boolean; readonly public: boolean; readonly prices: readonly { readonly id: string }[]; readonly features: readonly { readonly name: string }[]; }[]; readonly starterBaseProducts: readonly { readonly id: string; readonly code: string | null; readonly kind: string; readonly active: boolean; }[]; readonly proBaseProducts: readonly { readonly id: string; readonly code: string | null; readonly kind: string; readonly active: boolean; }[]; readonly enterpriseTenantCandidates: readonly { readonly id: string; readonly slug: string; readonly name: string; readonly active: boolean; }[]; readonly tenants: readonly UatTenantSnapshot[]; }; export type CustomerPortalCommercialFixtureAssessment = { readonly action: "noop" | "reconcile" | "blocked"; readonly reconcileIssues: readonly string[]; readonly blockingIssues: readonly string[]; readonly liveProof: { readonly adminEmail: typeof CUSTOMER_PORTAL_UAT_ADMIN_EMAIL; readonly starterTenantSlug: typeof CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG; readonly proTenantSlug: typeof CUSTOMER_PORTAL_UAT_TENANT_SLUG; readonly enterpriseTenantSlug: typeof CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG; readonly starterMonthlyCheckoutReady: boolean; readonly businessBasePlanReady: boolean; readonly enterpriseCatalogReady: boolean; readonly enterpriseContractGrantReady: boolean; readonly enterprisePortalSource: CustomerPortalCommercialEligibility["portalSource"]; readonly enterpriseDomainSetupIncludedByContract: boolean; readonly enterpriseCheckoutRows: number; readonly enterpriseAcquisitionId: string | null; }; }; function roleId(kind: CommercialTenantKind): string { return `customer-portal-uat-${kind}-admin-role`; } function membershipId(kind: CommercialTenantKind): string { return `customer-portal-uat-${kind}-membership`; } function assignmentId(kind: CommercialTenantKind): string { return `customer-portal-uat-${kind}-role-assignment`; } function isUatPortal(metadata: unknown): boolean { return typeof metadata === "object" && metadata !== null && "uatFixture" in metadata && metadata.uatFixture === UAT_PORTAL_MARKER; } function isDemoProPortal(metadata: unknown): boolean { return typeof metadata === "object" && metadata !== null && "uatFixture" in metadata && metadata.uatFixture === "VA-P26"; } function hasProviderIdentity(value: string | null): boolean { return Boolean(value?.trim()); } type UatSubscription = NonNullable["subscription"]>; type UatSubscriptionProduct = UatSubscription["products"][number]; function dateValue(value: Date | null): number | null { return value?.getTime() ?? null; } function subscriptionProductSafetyProjection(product: UatSubscriptionProduct): unknown { return { id: product.id, customEntitlementPlanId: product.customEntitlementPlanId, cancelledAt: dateValue(product.cancelledAt), endsAt: dateValue(product.endsAt), billingProviderSubscriptionId: product.billingProviderSubscriptionId, lagoSubscriptionId: product.lagoSubscriptionId, planCode: product.planCode, seatQuantity: product.seatQuantity, quantity: product.quantity, fromCheckoutSessionId: product.fromCheckoutSessionId, currentPeriodStart: dateValue(product.currentPeriodStart), currentPeriodEnd: dateValue(product.currentPeriodEnd), priceIds: product.prices.map((price) => price.id).sort(), acquisitionId: product.acquisition?.id ?? null, subscriptionProduct: product.subscriptionProduct, }; } export function starterSubscriptionSafetyMatches(actual: UatSubscription, expected: UatSubscription): boolean { return isDeepStrictEqual( { id: actual.id, planCode: actual.planCode, seatQuantity: actual.seatQuantity, status: actual.status, billingProviderCustomerId: actual.billingProviderCustomerId, lagoCustomerId: actual.lagoCustomerId, mollieCustomerId: actual.mollieCustomerId, lastInvoiceExternalId: actual.lastInvoiceExternalId, lastPaymentExternalId: actual.lastPaymentExternalId, trialStartsAt: dateValue(actual.trialStartsAt), trialEndsAt: dateValue(actual.trialEndsAt), pastDueSince: dateValue(actual.pastDueSince), frozenAt: dateValue(actual.frozenAt), cancelledAt: dateValue(actual.cancelledAt), dunningAttemptCount: actual.dunningAttemptCount, lastDunningSentAt: dateValue(actual.lastDunningSentAt), products: actual.products .map(subscriptionProductSafetyProjection) .sort((left, right) => String((left as { id: string }).id).localeCompare(String((right as { id: string }).id))), }, { id: expected.id, planCode: expected.planCode, seatQuantity: expected.seatQuantity, status: expected.status, billingProviderCustomerId: expected.billingProviderCustomerId, lagoCustomerId: expected.lagoCustomerId, mollieCustomerId: expected.mollieCustomerId, lastInvoiceExternalId: expected.lastInvoiceExternalId, lastPaymentExternalId: expected.lastPaymentExternalId, trialStartsAt: dateValue(expected.trialStartsAt), trialEndsAt: dateValue(expected.trialEndsAt), pastDueSince: dateValue(expected.pastDueSince), frozenAt: dateValue(expected.frozenAt), cancelledAt: dateValue(expected.cancelledAt), dunningAttemptCount: expected.dunningAttemptCount, lastDunningSentAt: dateValue(expected.lastDunningSentAt), products: expected.products .map(subscriptionProductSafetyProjection) .sort((left, right) => String((left as { id: string }).id).localeCompare(String((right as { id: string }).id))), } ); } function hasSafeAttachedStarterProductEnvelope( product: NonNullable["subscription"]>["products"][number], expectedSeatQuantity: number ): boolean { return ( product.subscriptionProduct.code === "starter" && product.subscriptionProduct.kind === "base_plan" && product.subscriptionProduct.active && (product.customEntitlementPlanId === null || product.customEntitlementPlanId === "starter") && product.cancelledAt === null && product.endsAt === null && !hasProviderIdentity(product.billingProviderSubscriptionId) && !hasProviderIdentity(product.lagoSubscriptionId) && product.quantity === expectedSeatQuantity && product.fromCheckoutSessionId === null && product.currentPeriodStart === null && product.currentPeriodEnd === null && product.prices.length === 0 && product.acquisition === null ); } function isCanonicalAttachedStarterProduct( product: NonNullable["subscription"]>["products"][number], expectedSeatQuantity: number ): boolean { return ( hasSafeAttachedStarterProductEnvelope(product, expectedSeatQuantity) && product.planCode === "starter" && product.seatQuantity === expectedSeatQuantity ); } function isLegacyNormalizableAttachedStarterProduct(product: UatSubscriptionProduct, expectedSeatQuantity: number): boolean { return ( hasSafeAttachedStarterProductEnvelope(product, expectedSeatQuantity) && product.customEntitlementPlanId === "starter" && product.planCode === null && product.seatQuantity === null ); } function starterBaseProductsAreSafe(subscription: NonNullable["subscription"]>): boolean { return subscription.products.length <= 1 && subscription.products.every((product) => isCanonicalAttachedStarterProduct(product, subscription.seatQuantity)); } function hasNoStarterBillingHistory(subscription: UatSubscription): boolean { return ( !hasProviderIdentity(subscription.billingProviderCustomerId) && !hasProviderIdentity(subscription.lagoCustomerId) && !hasProviderIdentity(subscription.mollieCustomerId) && !hasProviderIdentity(subscription.lastInvoiceExternalId) && !hasProviderIdentity(subscription.lastPaymentExternalId) && subscription.pastDueSince === null && subscription.frozenAt === null && subscription.cancelledAt === null && subscription.dunningAttemptCount === 0 && subscription.lastDunningSentAt === null ); } function isCanonicalActiveStarterSubscription(subscription: UatSubscription): boolean { return ( subscription.planCode === "starter" && subscription.status.toLowerCase() === "active" && subscription.trialStartsAt === null && subscription.trialEndsAt === null && hasNoStarterBillingHistory(subscription) ); } function hasLegacyNormalizableStarterAttachment(subscription: UatSubscription): boolean { return ( isCanonicalActiveStarterSubscription(subscription) && subscription.products.length === 1 && isLegacyNormalizableAttachedStarterProduct(subscription.products[0]!, subscription.seatQuantity) ); } function isSafeUnpaidStarterSubscription(subscription: NonNullable["subscription"]>): boolean { return ( (subscription.planCode === null || subscription.planCode === "starter") && subscription.status.toLowerCase() === "trial" && hasNoStarterBillingHistory(subscription) && starterBaseProductsAreSafe(subscription) ); } function enterpriseCatalogIsCanonical(snapshot: CustomerPortalCommercialFixtureSnapshot): boolean { const product = snapshot.enterpriseProducts[0]; const expected = customerPortalCommercialProducts.enterpriseContract; return ( snapshot.enterpriseProducts.length === 1 && product?.code === expected.code && product.kind === expected.source && product.active && !product.public && product.prices.length === 0 && product.features.length === expected.featureKeys.length && expected.featureKeys.every((featureKey) => product.features.some((feature) => feature.name === featureKey)) ); } function expectedEnterpriseRequestHash(tenantId: string, productId: string): string { return createHash("sha256") .update( JSON.stringify({ tenantId, productId, priceId: null, productKind: "contract_override", scopeKey: UAT_ENTERPRISE_SCOPE_KEY, quantity: 1, amountCents: null, currency: null, sourceReference: UAT_ENTERPRISE_CONTRACT_REFERENCE, }) ) .digest("hex"); } function isCanonicalEnterpriseBaseProduct(product: UatSubscriptionProduct): boolean { return ( product.id === UAT_ENTERPRISE_BASE_PRODUCT_ID && product.subscriptionProduct.code === "pro" && product.subscriptionProduct.kind === "base_plan" && product.subscriptionProduct.active && product.customEntitlementPlanId === "pro" && product.planCode === "pro" && product.seatQuantity === 1 && product.quantity === 1 && product.cancelledAt === null && product.endsAt === null && !hasProviderIdentity(product.billingProviderSubscriptionId) && !hasProviderIdentity(product.lagoSubscriptionId) && product.fromCheckoutSessionId === null && product.currentPeriodStart === null && product.currentPeriodEnd === null && product.prices.length === 0 && product.acquisition === null ); } function isCanonicalEnterpriseContractAttachment(product: UatSubscriptionProduct, acquisitionId: string, productId: string): boolean { return ( product.id === acquisitionId && product.subscriptionProduct.id === productId && product.subscriptionProduct.code === customerPortalCommercialProducts.enterpriseContract.code && product.subscriptionProduct.kind === "contract_override" && product.subscriptionProduct.active && product.customEntitlementPlanId === null && product.planCode === null && product.seatQuantity === null && product.quantity === 1 && product.cancelledAt === null && product.endsAt === null && !hasProviderIdentity(product.billingProviderSubscriptionId) && !hasProviderIdentity(product.lagoSubscriptionId) && product.fromCheckoutSessionId === null && product.currentPeriodStart instanceof Date && product.currentPeriodEnd === null && product.prices.length === 0 && product.acquisition?.id === acquisitionId ); } function isProviderlessEnterpriseSubscription(subscription: UatSubscription): boolean { return ( subscription.id === UAT_ENTERPRISE_SUBSCRIPTION_ID && subscription.planCode === "pro" && subscription.seatQuantity === 1 && subscription.status === "active" && !hasProviderIdentity(subscription.billingProviderCustomerId) && !hasProviderIdentity(subscription.lagoCustomerId) && !hasProviderIdentity(subscription.mollieCustomerId) && !hasProviderIdentity(subscription.lastInvoiceExternalId) && !hasProviderIdentity(subscription.lastPaymentExternalId) && subscription.trialStartsAt === null && subscription.trialEndsAt === null && subscription.pastDueSince === null && subscription.frozenAt === null && subscription.cancelledAt === null && subscription.dunningAttemptCount === 0 && subscription.lastDunningSentAt === null ); } function enterprisePortalConfigurationIsCanonical(snapshot: NonNullable): boolean { const configuration = snapshot.configuration; return Boolean( snapshot.id === UAT_ENTERPRISE_PORTAL_ID && snapshot.subdomain === CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG && snapshot.title === "Demo Enterprise CRM Kundenportal" && snapshot.isPublished && !snapshot.authRequireEmailVerification && !snapshot.authRequireOrganization && snapshot.authRequireName && isUatPortal(snapshot.metadata) && configuration && configuration.id === UAT_ENTERPRISE_CONFIGURATION_ID && configuration.enabledProjectTypes.length === 0 && configuration.uploadMaxFiles === 10 && configuration.uploadMaxFileSizeBytes === 52_428_800 && configuration.statusEmailsEnabled && configuration.welcomeMessage === "Willkommen im HiveGrid Test-Kundenportal." && configuration.supportEmail === "support@saas-ctrl.com" && configuration.imprintUrl === `${UAT_LEGAL_ORIGIN}/impressum` && configuration.privacyUrl === `${UAT_LEGAL_ORIGIN}/datenschutz` && configuration.isDemoData ); } function canonicalEnterpriseAcquisition(snapshot: UatTenantSnapshot, requireAudit = true) { const acquisition = snapshot.enterpriseAcquisitions[0]; const subscription = snapshot.tenant?.subscription; if (!acquisition || !subscription) return null; const expectedContractScope = portalEnterpriseClaimScopeKey(acquisition.id); const claimsCanonical = snapshot.enterpriseContractClaims.length <= 1 && snapshot.enterpriseContractClaims.every((claim) => claim.billingScopeKey === expectedContractScope); const contractAttachment = subscription.products.find((product) => product.id === acquisition.id); const exact = snapshot.enterpriseAcquisitions.length === 1 && acquisition.subscriptionProduct.code === customerPortalCommercialProducts.enterpriseContract.code && acquisition.subscriptionProduct.kind === "contract_override" && acquisition.subscriptionProduct.active && !acquisition.subscriptionProduct.public && acquisition.subscriptionPriceId === null && acquisition.productKind === "contract_override" && acquisition.scopeKey === UAT_ENTERPRISE_SCOPE_KEY && acquisition.requestHash === expectedEnterpriseRequestHash(snapshot.expectedId, acquisition.subscriptionProductId) && acquisition.status === "active" && acquisition.version === 3 && acquisition.quantity === 1 && acquisition.amountCents === null && acquisition.currency === null && acquisition.checkoutSessionId === null && acquisition.tenantSubscriptionProductId === acquisition.id && !hasProviderIdentity(acquisition.provider) && !hasProviderIdentity(acquisition.providerPaymentId) && !hasProviderIdentity(acquisition.invoiceExternalId) && !hasProviderIdentity(acquisition.lagoSubscriptionId) && !hasProviderIdentity(acquisition.checkoutUrl) && acquisition.sourceReference === UAT_ENTERPRISE_CONTRACT_REFERENCE && acquisition.providerStartedAt === null && acquisition.activatedAt instanceof Date && acquisition.failedAt === null && acquisition.cancelledAt === null && acquisition.expiredAt === null && acquisition.refundedAt === null && snapshot.checkoutSessions.length === 0 && claimsCanonical && Boolean(contractAttachment && isCanonicalEnterpriseContractAttachment(contractAttachment, acquisition.id, acquisition.subscriptionProductId)) && (!requireAudit || snapshot.enterpriseGrantAudited); return exact ? acquisition : null; } function assessTenant(snapshot: UatTenantSnapshot, reconcileIssues: string[], blockingIssues: string[]): void { const label = snapshot.kind; if (!snapshot.tenant) { if (snapshot.kind === "enterprise") { reconcileIssues.push("enterprise: create the dedicated deterministic UAT tenant and contract graph"); } else { blockingIssues.push(`${label}: explicitly bound tenant is not visible under RLS`); } return; } if (snapshot.tenant.id !== snapshot.expectedId || snapshot.tenant.slug !== snapshot.expectedSlug) { blockingIssues.push(`${label}: tenant id and slug do not match the explicit binding`); } if (!snapshot.tenant.active) blockingIssues.push(`${label}: tenant is inactive`); const subscription = snapshot.tenant.subscription; if (!subscription) { blockingIssues.push(`${label}: base subscription is missing`); } else if (snapshot.kind === "starter") { const activeStarter = isCanonicalActiveStarterSubscription(subscription); const legacyNormalizableAttachment = hasLegacyNormalizableStarterAttachment(subscription); if (!activeStarter) { if (isSafeUnpaidStarterSubscription(subscription)) reconcileIssues.push("starter: activate the empty starter base subscription for checkout"); else blockingIssues.push("starter: existing base subscription has provider, billing, product, or lifecycle state that the UAT fixture may not replace"); } if (legacyNormalizableAttachment) { reconcileIssues.push("starter: normalize the providerless legacy starter base-plan attachment"); } else if (!starterBaseProductsAreSafe(subscription)) { blockingIssues.push("starter: existing subscription product state is not the single providerless canonical starter base plan"); } else if (subscription.products.length === 0) { reconcileIssues.push("starter: providerless canonical starter base-plan entitlement row missing"); } if (snapshot.monthlyAcquisitions.length > 0 || subscription.products.some((product) => product.subscriptionProduct.code === "customer_portal_monthly")) { blockingIssues.push("starter: portal monthly add-on already has ledger or subscription state; the UAT fixture must not pre-purchase it"); } } else if ( snapshot.kind === "pro" && (subscription.planCode !== "business" || subscription.status.toLowerCase() !== "active" || subscription.frozenAt !== null || subscription.cancelledAt !== null) ) { blockingIssues.push("pro: expected the existing active business fixture that proves the included base-plan path"); } else if (snapshot.kind === "enterprise") { const baseProducts = subscription.products.filter((product) => product.subscriptionProduct.kind === "base_plan"); const structuralContract = canonicalEnterpriseAcquisition(snapshot, false); const allowedProductIds = new Set([UAT_ENTERPRISE_BASE_PRODUCT_ID, ...(structuralContract ? [structuralContract.id] : [])]); if (!isProviderlessEnterpriseSubscription(subscription)) { blockingIssues.push("enterprise: the dedicated UAT tenant does not have the exact providerless active pro base subscription"); } if (baseProducts.length !== 1 || !isCanonicalEnterpriseBaseProduct(baseProducts[0]!)) { blockingIssues.push("enterprise: the exact providerless pro base-plan attachment is missing or drifted"); } if (subscription.products.some((product) => !allowedProductIds.has(product.id))) { blockingIssues.push("enterprise: unexpected subscription products would make the contract proof ambiguous"); } if (snapshot.enterpriseAcquisitions.length === 0) { reconcileIssues.push("enterprise: canonical contract_override acquisition missing"); } else if (!structuralContract) { blockingIssues.push("enterprise: contract_override ledger, CAS state, attachment, audit, or providerless contract has drifted"); } else if (!snapshot.enterpriseGrantAudited) { reconcileIssues.push("enterprise: contract_override grant audit evidence missing"); } if ( snapshot.commercialEligibility.portalSource !== "contract_override" || !snapshot.commercialEligibility.portalAllowed || !snapshot.commercialEligibility.domainSetupActive || !snapshot.commercialEligibility.domainSetupIncludedByContract || snapshot.commercialEligibility.enterpriseContractAcquisitionId !== structuralContract?.id || snapshot.commercialEligibility.domainSetupAcquisitionId !== null ) { if (snapshot.enterpriseAcquisitions.length === 0) { reconcileIssues.push("enterprise: canonical commercial eligibility still lacks the contract override"); } else { blockingIssues.push("enterprise: canonical eligibility does not resolve portalSource=contract_override and one included domain"); } } } if (snapshot.kind !== "enterprise" && snapshot.enterpriseAcquisitions.length > 0) { blockingIssues.push(`${label}: Enterprise contract_override would mask the commercial path under test`); } const expectedRoleId = roleId(snapshot.kind); const role = snapshot.roleCandidates.find((candidate) => candidate.id === expectedRoleId); if (snapshot.roleCandidates.length === 0) reconcileIssues.push(`${label}: dedicated portal-admin role missing`); else if (snapshot.roleCandidates.length !== 1 || !role || role.tenantId !== snapshot.expectedId || role.name !== UAT_ROLE_NAME) { blockingIssues.push(`${label}: deterministic portal-admin role id or name collides with existing data`); } else { const permissionNames = role.permissions.map((entry) => entry.permission.name); const extraPermissions = permissionNames.filter((name) => !UAT_REQUIRED_PERMISSIONS.includes(name as (typeof UAT_REQUIRED_PERMISSIONS)[number])); if (extraPermissions.length > 0) blockingIssues.push(`${label}: dedicated UAT role has unexpected permissions`); for (const permission of UAT_REQUIRED_PERMISSIONS) { if (!permissionNames.includes(permission)) reconcileIssues.push(`${label}: dedicated UAT role is missing ${permission}`); } if (role.description !== UAT_ROLE_DESCRIPTION || role.type !== "app" || role.assignToNewUsers || role.isDefault || role.order !== 990) { reconcileIssues.push(`${label}: dedicated UAT role metadata differs from the guarded contract`); } } const expectedMembershipId = membershipId(snapshot.kind); const membership = snapshot.membershipCandidates.find((candidate) => candidate.id === expectedMembershipId); if (snapshot.membershipCandidates.length === 0) reconcileIssues.push(`${label}: dedicated admin membership missing`); else if ( snapshot.membershipCandidates.length !== 1 || !membership || membership.tenantId !== snapshot.expectedId || membership.userId !== UAT_ADMIN_USER_ID ) { blockingIssues.push(`${label}: deterministic membership id or user binding collides with existing data`); } else if (membership.type !== 1 || membership.joined !== 1 || membership.status !== 2) { reconcileIssues.push(`${label}: dedicated admin membership is inactive or has the wrong tenant-admin contract`); } const expectedAssignmentId = assignmentId(snapshot.kind); const assignment = snapshot.assignmentCandidates.find((candidate) => candidate.id === expectedAssignmentId); if (snapshot.assignmentCandidates.length === 0) reconcileIssues.push(`${label}: dedicated portal-admin role assignment missing`); else if ( snapshot.assignmentCandidates.length !== 1 || !assignment || assignment.tenantId !== snapshot.expectedId || assignment.userId !== UAT_ADMIN_USER_ID || assignment.roleId !== expectedRoleId ) { blockingIssues.push(`${label}: dedicated UAT user has an unexpected role assignment or id collision`); } if (snapshot.kind === "starter") { if (!snapshot.portal) reconcileIssues.push("starter: UAT-owned published portal missing"); else if (!isUatPortal(snapshot.portal.metadata)) blockingIssues.push("starter: existing portal is not owned by the VA-P26c commercial fixture"); else { if ( snapshot.portal.subdomain !== CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG || !snapshot.portal.isPublished || snapshot.portal.authRequireEmailVerification ) { reconcileIssues.push("starter: UAT portal publication or login contract differs"); } if (!snapshot.portal.configuration) reconcileIssues.push("starter: UAT portal configuration missing"); else if (!snapshot.portal.configuration.isDemoData) blockingIssues.push("starter: existing portal configuration is not UAT-owned demo data"); else if ( snapshot.portal.configuration.enabledProjectTypes.length !== 0 || snapshot.portal.configuration.uploadMaxFiles < 2 || snapshot.portal.configuration.uploadMaxFileSizeBytes < 1_024 || !snapshot.portal.configuration.imprintUrl || !snapshot.portal.configuration.privacyUrl ) { reconcileIssues.push("starter: UAT portal configuration differs from the checkout-ready contract"); } } } else if (snapshot.kind === "pro" && (!snapshot.portal || !isDemoProPortal(snapshot.portal.metadata) || !snapshot.portal.isPublished)) { blockingIssues.push("pro: the separate VA-P26 portal fixture must be applied and published before commercial UAT"); } else if (snapshot.kind === "enterprise" && (!snapshot.portal || !enterprisePortalConfigurationIsCanonical(snapshot.portal))) { blockingIssues.push("enterprise: the deterministic UAT-owned Portal or configuration is missing or drifted"); } } export function assessCustomerPortalCommercialFixture(snapshot: CustomerPortalCommercialFixtureSnapshot): CustomerPortalCommercialFixtureAssessment { const reconcileIssues: string[] = []; const blockingIssues: string[] = []; const user = snapshot.userCandidates.find((candidate) => candidate.id === UAT_ADMIN_USER_ID); if (snapshot.userCandidates.length === 0) reconcileIssues.push("dedicated saas-ctrl.com tenant-admin identity missing"); else if ( snapshot.userCandidates.length !== 1 || !user || user.email !== CUSTOMER_PORTAL_UAT_ADMIN_EMAIL || user.hasPlatformAdmin || user.pendingDeletion || user.pseudonymized ) { blockingIssues.push("dedicated tenant-admin id/email collides with existing or platform-admin data"); } else if ( !user.active || !user.passwordMatches || user.firstName !== "Portal" || user.lastName !== "UAT Admin" || user.defaultTenantId !== snapshot.tenants.find((tenant) => tenant.kind === "starter")?.expectedId ) { reconcileIssues.push("dedicated tenant-admin identity differs from the login contract"); } for (const permissionName of UAT_REQUIRED_PERMISSIONS) { if (snapshot.permissions.filter((permission) => permission.name === permissionName).length !== 1) { blockingIssues.push(`global permission catalog is missing or ambiguous for ${permissionName}`); } } if ( snapshot.starterBaseProducts.length !== 1 || snapshot.starterBaseProducts[0]?.code !== "starter" || snapshot.starterBaseProducts[0].kind !== "base_plan" || !snapshot.starterBaseProducts[0].active ) { blockingIssues.push("canonical active starter base-plan catalog product is missing or ambiguous"); } if ( snapshot.proBaseProducts.length !== 1 || snapshot.proBaseProducts[0]?.code !== "pro" || snapshot.proBaseProducts[0].kind !== "base_plan" || !snapshot.proBaseProducts[0].active ) { blockingIssues.push("canonical active pro base-plan catalog product is missing or ambiguous"); } if ( snapshot.enterpriseTenantCandidates.length > 1 || (snapshot.enterpriseTenantCandidates.length === 1 && (snapshot.enterpriseTenantCandidates[0]?.id !== snapshot.tenants.find((tenant) => tenant.kind === "enterprise")?.expectedId || snapshot.enterpriseTenantCandidates[0]?.slug !== CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG || snapshot.enterpriseTenantCandidates[0]?.name !== UAT_ENTERPRISE_TENANT_NAME)) ) { blockingIssues.push("enterprise: deterministic tenant id or slug collides with non-UAT staging data"); } if (!enterpriseCatalogIsCanonical(snapshot)) { blockingIssues.push("enterprise contract_override product is missing or differs from the canonical non-public catalog contract"); } for (const tenant of snapshot.tenants) assessTenant(tenant, reconcileIssues, blockingIssues); const starter = snapshot.tenants.find((tenant) => tenant.kind === "starter"); const business = snapshot.tenants.find((tenant) => tenant.kind === "pro"); const enterprise = snapshot.tenants.find((tenant) => tenant.kind === "enterprise"); const enterpriseAcquisition = enterprise ? canonicalEnterpriseAcquisition(enterprise) : null; const starterSubscription = starter?.tenant?.subscription; const starterMonthlyCheckoutReady = Boolean( starterSubscription && isCanonicalActiveStarterSubscription(starterSubscription) && starterSubscription.products.length === 1 && starterSubscription.products.every((product) => isCanonicalAttachedStarterProduct(product, starterSubscription.seatQuantity)) && starter?.monthlyAcquisitions.length === 0 && !starterSubscription.products.some((product) => product.subscriptionProduct.code === "customer_portal_monthly") ); return { action: blockingIssues.length > 0 ? "blocked" : reconcileIssues.length > 0 ? "reconcile" : "noop", reconcileIssues, blockingIssues, liveProof: { adminEmail: CUSTOMER_PORTAL_UAT_ADMIN_EMAIL, starterTenantSlug: CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG, proTenantSlug: CUSTOMER_PORTAL_UAT_TENANT_SLUG, enterpriseTenantSlug: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, starterMonthlyCheckoutReady, businessBasePlanReady: business?.commercialEligibility.portalSource === "base_plan" && business.commercialEligibility.enterpriseContractAcquisitionId === null, enterpriseCatalogReady: enterpriseCatalogIsCanonical(snapshot), enterpriseContractGrantReady: Boolean(enterpriseAcquisition), enterprisePortalSource: enterprise?.commercialEligibility.portalSource ?? "missing", enterpriseDomainSetupIncludedByContract: enterprise?.commercialEligibility.domainSetupIncludedByContract ?? false, enterpriseCheckoutRows: enterprise?.checkoutSessions.length ?? 0, enterpriseAcquisitionId: enterpriseAcquisition?.id ?? null, }, }; } async function readTenantSnapshot( db: DbClient, input: { readonly kind: CommercialTenantKind; readonly expectedId: string; readonly expectedSlug: string } ): Promise { const expectedRoleId = roleId(input.kind); const expectedMembershipId = membershipId(input.kind); const expectedAssignmentId = assignmentId(input.kind); const tenant = await db.tenant.findFirst({ where: { id: input.expectedId, slug: input.expectedSlug }, select: { id: true, slug: true, name: true, active: true, subscription: { select: { id: true, planCode: true, seatQuantity: true, status: true, billingProviderCustomerId: true, lagoCustomerId: true, mollieCustomerId: true, lastInvoiceExternalId: true, lastPaymentExternalId: true, trialStartsAt: true, trialEndsAt: true, pastDueSince: true, frozenAt: true, cancelledAt: true, dunningAttemptCount: true, lastDunningSentAt: true, products: { select: { id: true, customEntitlementPlanId: true, cancelledAt: true, endsAt: true, billingProviderSubscriptionId: true, lagoSubscriptionId: true, planCode: true, seatQuantity: true, quantity: true, fromCheckoutSessionId: true, currentPeriodStart: true, currentPeriodEnd: true, prices: { select: { id: true } }, acquisition: { select: { id: true } }, subscriptionProduct: { select: { id: true, code: true, kind: true, active: true } }, }, }, }, }, }, }); // Keep the operator inspection sequential. Every model operation owns a // short RLS transaction, and overlapping those transactions on the tiny // two-connection operator pool can otherwise make the Pg adapter reuse a // connection while it is still completing the previous query. const portal = await db.portal.findUnique({ where: { tenantId: input.expectedId }, select: { id: true, subdomain: true, title: true, isPublished: true, authRequireEmailVerification: true, authRequireOrganization: true, authRequireName: true, metadata: true, configuration: { select: { id: true, enabledProjectTypes: true, uploadMaxFiles: true, uploadMaxFileSizeBytes: true, statusEmailsEnabled: true, welcomeMessage: true, supportEmail: true, imprintUrl: true, privacyUrl: true, isDemoData: true, }, }, }, }); const roleCandidates = await db.role.findMany({ where: { OR: [{ id: expectedRoleId }, { tenantId: input.expectedId, name: UAT_ROLE_NAME }] }, select: { id: true, tenantId: true, name: true, description: true, type: true, assignToNewUsers: true, isDefault: true, order: true, permissions: { select: { id: true, permission: { select: { id: true, name: true } } } }, }, }); const membershipCandidates = await db.tenantUser.findMany({ where: { OR: [{ id: expectedMembershipId }, { tenantId: input.expectedId, userId: UAT_ADMIN_USER_ID }] }, select: { id: true, tenantId: true, userId: true, type: true, joined: true, status: true }, }); const assignmentCandidates = await db.userRole.findMany({ where: { OR: [{ id: expectedAssignmentId }, { tenantId: input.expectedId, userId: UAT_ADMIN_USER_ID }] }, select: { id: true, tenantId: true, userId: true, roleId: true }, }); const monthlyAcquisitions = await db.tenantProductAcquisition.findMany({ where: { tenantId: input.expectedId, subscriptionProduct: { code: "customer_portal_monthly" } }, select: { id: true, status: true, subscriptionProduct: { select: { code: true } } }, }); const enterpriseAcquisitions = await db.tenantProductAcquisition.findMany({ where: { tenantId: input.expectedId, subscriptionProduct: { code: customerPortalCommercialProducts.enterpriseContract.code } }, select: { id: true, subscriptionProductId: true, subscriptionPriceId: true, productKind: true, scopeKey: true, requestHash: true, status: true, version: true, quantity: true, amountCents: true, currency: true, checkoutSessionId: true, tenantSubscriptionProductId: true, provider: true, providerPaymentId: true, invoiceExternalId: true, lagoSubscriptionId: true, checkoutUrl: true, sourceReference: true, providerStartedAt: true, activatedAt: true, failedAt: true, cancelledAt: true, expiredAt: true, refundedAt: true, subscriptionProduct: { select: { id: true, code: true, kind: true, active: true, public: true } }, }, }); const checkoutSessions = await db.checkoutSessionStatus.findMany({ where: { tenantId: input.expectedId }, select: { id: true, productKind: true, subscriptionProductId: true, provider: true, providerPaymentId: true, lagoSubscriptionId: true, checkoutUrl: true, }, }); const enterpriseContractClaims = await db.portalDomainHostnameClaim.findMany({ where: { tenantId: input.expectedId, billingScopeKey: { startsWith: "enterprise-contract:" } }, select: { id: true, billingScopeKey: true }, orderBy: [{ createdAt: "asc" }, { id: "asc" }], }); const eligibilityClaimId = enterpriseContractClaims.length === 1 ? enterpriseContractClaims[0]?.id : undefined; const commercialEligibility = await getCustomerPortalCommercialEligibility( { tenantId: input.expectedId, ...(eligibilityClaimId ? { claimId: eligibilityClaimId } : {}) }, { withTenant: async (_tenantId, operation) => operation(db as never) } ); const acquisitionIds = new Set(enterpriseAcquisitions.map((acquisition) => acquisition.id)); const auditEvents = acquisitionIds.size === 0 ? [] : await db.auditEvent.findMany({ where: { tenantId: input.expectedId, action: UAT_ENTERPRISE_AUDIT_ACTION, targetId: { in: [...acquisitionIds] } }, select: { targetId: true }, }); const auditOutboxEvents = await db.outboxEvent.findMany({ where: { tenantId: input.expectedId, eventType: "audit.event.create" }, select: { payload: true }, }); const enterpriseGrantAudited = auditEvents.some((event) => Boolean(event.targetId && acquisitionIds.has(event.targetId))) || auditOutboxEvents.some((event) => { const payload = event.payload; if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false; const record = payload as Record; return record.action === UAT_ENTERPRISE_AUDIT_ACTION && typeof record.targetId === "string" && acquisitionIds.has(record.targetId); }); return { ...input, tenant, portal, roleCandidates, membershipCandidates, assignmentCandidates, monthlyAcquisitions, enterpriseAcquisitions, checkoutSessions, enterpriseContractClaims, commercialEligibility, enterpriseGrantAudited, }; } export async function readCustomerPortalCommercialFixture( db: DbClient, command: CustomerPortalCommercialFixtureCommand ): Promise { const rawUsers = await db.user.findMany({ where: { OR: [{ id: UAT_ADMIN_USER_ID }, { email: CUSTOMER_PORTAL_UAT_ADMIN_EMAIL }] }, select: { id: true, email: true, passwordHash: true, firstName: true, lastName: true, defaultTenantId: true, active: true, pendingDeletion: true, pseudonymized: true, admin: { select: { userId: true } }, }, }); const permissions = await db.permission.findMany({ where: { name: { in: [...UAT_REQUIRED_PERMISSIONS] } }, select: { id: true, name: true }, }); const enterpriseProducts = await db.subscriptionProduct.findMany({ where: { code: customerPortalCommercialProducts.enterpriseContract.code }, select: { id: true, code: true, kind: true, active: true, public: true, prices: { select: { id: true } }, features: { select: { name: true } }, }, }); const starterBaseProducts = await db.subscriptionProduct.findMany({ where: { code: "starter", kind: "base_plan" }, select: { id: true, code: true, kind: true, active: true }, }); const proBaseProducts = await db.subscriptionProduct.findMany({ where: { code: "pro", kind: "base_plan" }, select: { id: true, code: true, kind: true, active: true }, }); const enterpriseTenantCandidates = await db.tenant.findMany({ where: { OR: [{ id: command.expectedEnterpriseTenantId }, { slug: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG }], }, select: { id: true, slug: true, name: true, active: true }, }); const starter = await runWithRlsContext({ tenantId: command.expectedStarterTenantId }, () => readTenantSnapshot(db, { kind: "starter", expectedId: command.expectedStarterTenantId, expectedSlug: CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG, }) ); const pro = await runWithRlsContext({ tenantId: command.expectedProTenantId }, () => readTenantSnapshot(db, { kind: "pro", expectedId: command.expectedProTenantId, expectedSlug: CUSTOMER_PORTAL_UAT_TENANT_SLUG }) ); const enterprise = await runWithRlsContext({ tenantId: command.expectedEnterpriseTenantId }, () => readTenantSnapshot(db, { kind: "enterprise", expectedId: command.expectedEnterpriseTenantId, expectedSlug: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, }) ); const userCandidates = await Promise.all( rawUsers.map(async ({ passwordHash, admin, ...user }) => ({ ...user, hasPlatformAdmin: Boolean(admin), passwordMatches: passwordHash ? await verifySupportedPassword(command.password, passwordHash) : false, })) ); return { userCandidates, permissions, enterpriseProducts, starterBaseProducts, proBaseProducts, enterpriseTenantCandidates, tenants: [starter, pro, enterprise], }; } async function applyGlobalAdminIdentity(db: DbClient, command: CustomerPortalCommercialFixtureCommand): Promise { const passwordHash = await hashCurrentPassword(command.password); await db.$transaction(async (tx) => { await tx.$queryRaw` SELECT uat_user."id" FROM "User" AS uat_user WHERE uat_user."id" = ${UAT_ADMIN_USER_ID} OR uat_user."email" = ${CUSTOMER_PORTAL_UAT_ADMIN_EMAIL} FOR UPDATE `; const currentCandidates = await tx.user.findMany({ where: { OR: [{ id: UAT_ADMIN_USER_ID }, { email: CUSTOMER_PORTAL_UAT_ADMIN_EMAIL }] }, select: { id: true, email: true, pendingDeletion: true, pseudonymized: true, admin: { select: { userId: true } }, }, }); const current = currentCandidates[0]; if ( currentCandidates.length > 1 || (current && (current.id !== UAT_ADMIN_USER_ID || current.email !== CUSTOMER_PORTAL_UAT_ADMIN_EMAIL || current.pendingDeletion || current.pseudonymized || Boolean(current.admin))) ) { throw new CustomerPortalUatError("customer-portal UAT: dedicated tenant-admin ownership changed after guarded preflight"); } const userData = { email: CUSTOMER_PORTAL_UAT_ADMIN_EMAIL, passwordHash, firstName: "Portal", lastName: "UAT Admin", defaultTenantId: command.expectedStarterTenantId, locale: "de", active: true, } as const; if (!current) { await tx.user.create({ data: { id: UAT_ADMIN_USER_ID, ...userData, }, }); } else { await tx.user.update({ where: { id: UAT_ADMIN_USER_ID }, data: userData, }); } await publishAuditEventViaOutbox(tx, { tenantId: command.expectedStarterTenantId, actorId: command.operatorUserId, actorType: "operator", action: "customer_portal.uat_commercial_admin.provisioned", targetType: "User", targetId: UAT_ADMIN_USER_ID, sourceModule: "customer-portal-uat", outcome: "success", dataSensitivity: "internal", regulatoryScope: ["none"], metadata: { tenantCount: 3, emailDomain: "saas-ctrl.com" }, }); }); } async function lockCommercialTenantFixtureRows(db: DbClient, tenant: UatTenantSnapshot): Promise { const tenantLocks = await db.$queryRaw>` SELECT target_tenant."id" FROM "Tenant" AS target_tenant WHERE target_tenant."id" = ${tenant.expectedId} AND target_tenant."slug" = ${tenant.expectedSlug} FOR UPDATE `; if (tenantLocks.length !== 1) { throw new CustomerPortalUatError("customer-portal UAT: commercial tenant changed after guarded preflight"); } await db.$queryRaw` SELECT uat_user."id" FROM "User" AS uat_user WHERE uat_user."id" = ${UAT_ADMIN_USER_ID} AND uat_user."email" = ${CUSTOMER_PORTAL_UAT_ADMIN_EMAIL} FOR UPDATE `; await db.$queryRaw` SELECT portal."id" FROM "Portal" AS portal WHERE portal."tenantId" = ${tenant.expectedId} FOR UPDATE `; await db.$queryRaw` SELECT configuration."id" FROM "PortalConfiguration" AS configuration WHERE configuration."tenantId" = ${tenant.expectedId} FOR UPDATE `; await db.$queryRaw` SELECT role."id" FROM "Role" AS role WHERE role."id" = ${roleId(tenant.kind)} OR (role."tenantId" = ${tenant.expectedId} AND role."name" = ${UAT_ROLE_NAME}) FOR UPDATE `; await db.$queryRaw` SELECT role_permission."id" FROM "RolePermission" AS role_permission JOIN "Role" AS role ON role."id" = role_permission."roleId" WHERE role."id" = ${roleId(tenant.kind)} OR (role."tenantId" = ${tenant.expectedId} AND role."name" = ${UAT_ROLE_NAME}) FOR UPDATE OF role_permission `; await db.$queryRaw` SELECT membership."id" FROM "TenantUser" AS membership WHERE membership."id" = ${membershipId(tenant.kind)} OR (membership."tenantId" = ${tenant.expectedId} AND membership."userId" = ${UAT_ADMIN_USER_ID}) FOR UPDATE `; await db.$queryRaw` SELECT assignment."id" FROM "UserRole" AS assignment WHERE assignment."id" = ${assignmentId(tenant.kind)} OR (assignment."tenantId" = ${tenant.expectedId} AND assignment."userId" = ${UAT_ADMIN_USER_ID}) FOR UPDATE `; await db.$queryRaw` SELECT acquisition."id" FROM "TenantProductAcquisition" AS acquisition JOIN "SubscriptionProduct" AS product ON product."id" = acquisition."subscriptionProductId" WHERE acquisition."tenantId" = ${tenant.expectedId} AND product."code" = 'customer_portal_monthly' FOR UPDATE OF acquisition, product `; } async function applyTenantFixture( db: DbClient, command: CustomerPortalCommercialFixtureCommand, preflightTenant: UatTenantSnapshot, starterBaseProductId: string ): Promise { const expectedRoleId = roleId(preflightTenant.kind); await db.$transaction(async (tx) => { const transactionDb = tx as unknown as DbClient; await lockCommercialTenantFixtureRows(transactionDb, preflightTenant); const tenant = await readTenantSnapshot(transactionDb, { kind: preflightTenant.kind, expectedId: preflightTenant.expectedId, expectedSlug: preflightTenant.expectedSlug, }); const blockingIssues: string[] = []; assessTenant(tenant, [], blockingIssues); const currentUser = await tx.user.findUnique({ where: { id: UAT_ADMIN_USER_ID }, select: { id: true, email: true, pendingDeletion: true, pseudonymized: true, admin: { select: { userId: true } } }, }); if ( blockingIssues.length > 0 || !currentUser || currentUser.email !== CUSTOMER_PORTAL_UAT_ADMIN_EMAIL || currentUser.pendingDeletion || currentUser.pseudonymized || Boolean(currentUser.admin) ) { throw new CustomerPortalUatError("customer-portal UAT: commercial fixture ownership changed after guarded preflight"); } const permissionByName = new Map( ( await tx.permission.findMany({ where: { name: { in: [...UAT_REQUIRED_PERMISSIONS] } }, select: { id: true, name: true }, }) ).map((permission) => [permission.name, permission.id]) ); if (permissionByName.size !== UAT_REQUIRED_PERMISSIONS.length) { throw new CustomerPortalUatError("customer-portal UAT: commercial permission catalog changed after guarded preflight"); } if (tenant.kind === "starter") { const subscription = tenant.tenant?.subscription; if (!subscription) throw new CustomerPortalUatError("customer-portal UAT: starter base subscription disappeared before apply"); const subscriptionLocks = await tx.$queryRaw>` SELECT subscription."id" FROM "TenantSubscription" AS subscription WHERE subscription."id" = ${subscription.id} AND subscription."tenantId" = ${tenant.expectedId} FOR UPDATE `; const productLocks = await tx.$queryRaw>` SELECT attached."id" FROM "TenantSubscriptionProduct" AS attached JOIN "SubscriptionProduct" AS catalog ON catalog."id" = attached."subscriptionProductId" WHERE attached."tenantSubscriptionId" = ${subscription.id} ORDER BY attached."id" FOR UPDATE OF attached, catalog `; const starterCatalogLocks = await tx.$queryRaw>` SELECT catalog."id", catalog."code", catalog."kind"::text AS "kind", catalog."active" FROM "SubscriptionProduct" AS catalog WHERE catalog."id" = ${starterBaseProductId} FOR UPDATE `; if ( subscriptionLocks.length !== 1 || productLocks.length !== subscription.products.length || starterCatalogLocks.length !== 1 || starterCatalogLocks[0]?.code !== "starter" || starterCatalogLocks[0].kind !== "base_plan" || !starterCatalogLocks[0].active ) { throw new CustomerPortalUatError("customer-portal UAT: starter subscription or catalog changed after guarded preflight"); } const currentSubscriptionRow = await tx.tenantSubscription.findUnique({ where: { id: subscription.id }, select: { id: true, planCode: true, seatQuantity: true, status: true, billingProviderCustomerId: true, lagoCustomerId: true, mollieCustomerId: true, lastInvoiceExternalId: true, lastPaymentExternalId: true, trialStartsAt: true, trialEndsAt: true, pastDueSince: true, frozenAt: true, cancelledAt: true, dunningAttemptCount: true, lastDunningSentAt: true, products: { select: { id: true, customEntitlementPlanId: true, cancelledAt: true, endsAt: true, billingProviderSubscriptionId: true, lagoSubscriptionId: true, planCode: true, seatQuantity: true, quantity: true, fromCheckoutSessionId: true, currentPeriodStart: true, currentPeriodEnd: true, prices: { select: { id: true } }, acquisition: { select: { id: true } }, subscriptionProduct: { select: { id: true, code: true, kind: true, active: true } }, }, }, }, }); const currentSubscription = currentSubscriptionRow ? { ...currentSubscriptionRow, products: currentSubscriptionRow.products.map((product) => ({ ...product, subscriptionProduct: { ...product.subscriptionProduct, kind: String(product.subscriptionProduct.kind) }, })), } : null; if (!currentSubscription || !starterSubscriptionSafetyMatches(currentSubscription, subscription)) { throw new CustomerPortalUatError("customer-portal UAT: starter subscription safety state changed after guarded preflight"); } const legacyNormalizableProduct = subscription.products.length === 1 && isLegacyNormalizableAttachedStarterProduct(subscription.products[0]!, subscription.seatQuantity) && subscription.products[0]!.subscriptionProduct.id === starterBaseProductId ? subscription.products[0]! : null; if (hasLegacyNormalizableStarterAttachment(subscription) && !legacyNormalizableProduct) { throw new CustomerPortalUatError("customer-portal UAT: legacy starter attachment catalog changed after guarded preflight"); } const subscriptionUpdate = await tx.tenantSubscription.updateMany({ where: { id: subscription.id, tenantId: tenant.expectedId, planCode: subscription.planCode, seatQuantity: subscription.seatQuantity, status: subscription.status, billingProviderCustomerId: subscription.billingProviderCustomerId, lagoCustomerId: subscription.lagoCustomerId, mollieCustomerId: subscription.mollieCustomerId, lastInvoiceExternalId: subscription.lastInvoiceExternalId, lastPaymentExternalId: subscription.lastPaymentExternalId, trialStartsAt: subscription.trialStartsAt, trialEndsAt: subscription.trialEndsAt, pastDueSince: subscription.pastDueSince, frozenAt: subscription.frozenAt, cancelledAt: subscription.cancelledAt, dunningAttemptCount: subscription.dunningAttemptCount, lastDunningSentAt: subscription.lastDunningSentAt, products: { none: { subscriptionProduct: { code: "customer_portal_monthly" } } }, }, data: { planCode: "starter", status: "active", trialStartsAt: null, trialEndsAt: null, pastDueSince: null, frozenAt: null, cancelledAt: null, }, }); if (subscriptionUpdate.count !== 1) { throw new CustomerPortalUatError("customer-portal UAT: starter subscription changed after guarded preflight"); } if (subscription.products.length === 0) { await tx.tenantSubscriptionProduct.create({ data: { id: "customer-portal-uat-starter-base-product", tenantSubscriptionId: subscription.id, subscriptionProductId: starterBaseProductId, billingProviderSubscriptionId: null, lagoSubscriptionId: null, planCode: "starter", customEntitlementPlanId: "starter", seatQuantity: subscription.seatQuantity, quantity: subscription.seatQuantity, fromCheckoutSessionId: null, }, }); } else if (legacyNormalizableProduct) { const productUpdate = await tx.tenantSubscriptionProduct.updateMany({ where: { id: legacyNormalizableProduct.id, tenantSubscriptionId: subscription.id, subscriptionProductId: starterBaseProductId, customEntitlementPlanId: "starter", cancelledAt: null, endsAt: null, billingProviderSubscriptionId: null, lagoSubscriptionId: null, planCode: null, seatQuantity: null, quantity: subscription.seatQuantity, fromCheckoutSessionId: null, currentPeriodStart: null, currentPeriodEnd: null, prices: { none: {} }, acquisition: null, subscriptionProduct: { id: starterBaseProductId, code: "starter", kind: "base_plan", active: true }, }, data: { planCode: "starter", seatQuantity: subscription.seatQuantity }, }); if (productUpdate.count !== 1) { throw new CustomerPortalUatError("customer-portal UAT: legacy starter attachment changed after guarded preflight"); } } const portal = tenant.portal ? await tx.portal.update({ where: { id: tenant.portal.id }, data: { createdByUserId: UAT_ADMIN_USER_ID, subdomain: CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG, title: "Demo Starter CRM Kundenportal", isPublished: true, authRequireEmailVerification: false, authRequireOrganization: false, authRequireName: true, }, select: { id: true }, }) : await tx.portal.create({ data: { id: "customer-portal-uat-demo-starter-crm", tenantId: tenant.expectedId, createdByUserId: UAT_ADMIN_USER_ID, subdomain: CUSTOMER_PORTAL_UAT_STARTER_TENANT_SLUG, title: "Demo Starter CRM Kundenportal", isPublished: true, authRequireEmailVerification: false, authRequireOrganization: false, authRequireName: true, metadata: { uatFixture: UAT_PORTAL_MARKER }, }, select: { id: true }, }); const portalConfigurationData = { lifecycleMode: "customer" as const, enabledProjectTypes: [] as string[], uploadMaxFiles: 10, uploadMaxFileSizeBytes: 52_428_800, statusEmailsEnabled: true, welcomeMessage: "Willkommen im HiveGrid Test-Kundenportal.", supportEmail: "support@saas-ctrl.com", imprintUrl: `${UAT_LEGAL_ORIGIN}/impressum`, privacyUrl: `${UAT_LEGAL_ORIGIN}/datenschutz`, isDemoData: true, }; if (tenant.portal?.configuration) { await tx.portalConfiguration.update({ where: { id: tenant.portal.configuration.id }, data: portalConfigurationData, }); } else { await tx.portalConfiguration.create({ data: { id: "customer-portal-uat-starter-configuration", tenantId: tenant.expectedId, portalId: portal.id, ...portalConfigurationData, }, }); } } const roleData = { description: UAT_ROLE_DESCRIPTION, type: "app", assignToNewUsers: false, isDefault: false, order: 990, } as const; if (tenant.roleCandidates.length === 0) { await tx.role.create({ data: { id: expectedRoleId, tenantId: tenant.expectedId, name: UAT_ROLE_NAME, ...roleData, }, }); } else { await tx.role.update({ where: { id: expectedRoleId }, data: roleData, }); } for (const permissionName of UAT_REQUIRED_PERMISSIONS) { const permissionId = permissionByName.get(permissionName); if (!permissionId) throw new CustomerPortalUatError(`customer-portal UAT: required permission ${permissionName} disappeared before apply`); const existing = await tx.rolePermission.findFirst({ where: { roleId: expectedRoleId, permissionId }, select: { id: true } }); if (!existing) { await tx.rolePermission.create({ data: { id: `${expectedRoleId}-${permissionName.replaceAll(".", "-")}`, roleId: expectedRoleId, permissionId }, }); } } const tenantUserData = { type: 1, joined: 1, status: 2, seatType: "office" as const }; if (tenant.membershipCandidates.length === 0) { await tx.tenantUser.create({ data: { id: membershipId(tenant.kind), tenantId: tenant.expectedId, userId: UAT_ADMIN_USER_ID, ...tenantUserData, }, }); } else { await tx.tenantUser.update({ where: { id: membershipId(tenant.kind) }, data: tenantUserData, }); } if (tenant.assignmentCandidates.length === 0) { await tx.userRole.create({ data: { id: assignmentId(tenant.kind), tenantId: tenant.expectedId, userId: UAT_ADMIN_USER_ID, roleId: expectedRoleId, }, }); } await publishAuditEventViaOutbox(tx, { tenantId: tenant.expectedId, actorId: command.operatorUserId, actorType: "operator", action: "customer_portal.uat_commercial_fixture.provisioned", targetType: "Tenant", targetId: tenant.expectedId, sourceModule: "customer-portal-uat", outcome: "success", dataSensitivity: "internal", regulatoryScope: ["none"], metadata: { tenantSlug: tenant.expectedSlug, packagePath: tenant.kind === "starter" ? "recurring_add_on" : "base_plan", portalMonthlyAcquisitionCreated: false, enterpriseContractAcquisitionCreated: false, }, }); }); } export async function applyEnterpriseTenantFixture( db: DbClient, command: CustomerPortalCommercialFixtureCommand, enterpriseBaseProductId: string, enterpriseContractProductId: string ): Promise { const tenantId = command.expectedEnterpriseTenantId; const expectedRoleId = roleId("enterprise"); await db.$transaction(async (tx) => { const transactionDb = tx as unknown as DbClient; await tx.$queryRaw` SELECT pg_catalog.pg_advisory_xact_lock( pg_catalog.hashtextextended(${`customer-portal-uat:${CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG}`}, 26026) )::text AS "lock" `; await tx.$queryRaw` SELECT target_tenant."id" FROM "Tenant" AS target_tenant WHERE target_tenant."id" = ${tenantId} OR target_tenant."slug" = ${CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG} FOR UPDATE `; const userLocks = await tx.$queryRaw>` SELECT uat_user."id" FROM "User" AS uat_user WHERE uat_user."id" = ${UAT_ADMIN_USER_ID} AND uat_user."email" = ${CUSTOMER_PORTAL_UAT_ADMIN_EMAIL} FOR UPDATE `; await tx.$queryRaw` SELECT subscription."id" FROM "TenantSubscription" AS subscription WHERE subscription."tenantId" = ${tenantId} FOR UPDATE `; await tx.$queryRaw` SELECT attached."id" FROM "TenantSubscriptionProduct" AS attached JOIN "TenantSubscription" AS subscription ON subscription."id" = attached."tenantSubscriptionId" WHERE subscription."tenantId" = ${tenantId} ORDER BY attached."id" FOR UPDATE OF attached `; const catalogLocks = await tx.$queryRaw>` SELECT product."id", product."code", product."kind"::text AS "kind", product."active", product."public" FROM "SubscriptionProduct" AS product WHERE product."id" IN (${enterpriseBaseProductId}, ${enterpriseContractProductId}) ORDER BY product."id" FOR UPDATE `; await tx.$queryRaw` SELECT acquisition."id" FROM "TenantProductAcquisition" AS acquisition WHERE acquisition."tenantId" = ${tenantId} ORDER BY acquisition."id" FOR UPDATE `; await tx.$queryRaw` SELECT checkout."id" FROM "CheckoutSessionStatus" AS checkout WHERE checkout."tenantId" = ${tenantId} ORDER BY checkout."id" FOR UPDATE `; await tx.$queryRaw` SELECT portal."id" FROM "Portal" AS portal WHERE portal."tenantId" = ${tenantId} FOR UPDATE `; await tx.$queryRaw` SELECT configuration."id" FROM "PortalConfiguration" AS configuration WHERE configuration."tenantId" = ${tenantId} FOR UPDATE `; await tx.$queryRaw` SELECT role."id" FROM "Role" AS role WHERE role."id" = ${expectedRoleId} OR (role."tenantId" = ${tenantId} AND role."name" = ${UAT_ROLE_NAME}) FOR UPDATE `; await tx.$queryRaw` SELECT role_permission."id" FROM "RolePermission" AS role_permission JOIN "Role" AS role ON role."id" = role_permission."roleId" WHERE role."id" = ${expectedRoleId} FOR UPDATE OF role_permission `; await tx.$queryRaw` SELECT membership."id" FROM "TenantUser" AS membership WHERE membership."id" = ${membershipId("enterprise")} OR (membership."tenantId" = ${tenantId} AND membership."userId" = ${UAT_ADMIN_USER_ID}) FOR UPDATE `; await tx.$queryRaw` SELECT assignment."id" FROM "UserRole" AS assignment WHERE assignment."id" = ${assignmentId("enterprise")} OR (assignment."tenantId" = ${tenantId} AND assignment."userId" = ${UAT_ADMIN_USER_ID}) FOR UPDATE `; const baseCatalog = catalogLocks.find((product) => product.id === enterpriseBaseProductId); const contractCatalog = catalogLocks.find((product) => product.id === enterpriseContractProductId); if ( userLocks.length !== 1 || catalogLocks.length !== 2 || baseCatalog?.code !== "pro" || baseCatalog.kind !== "base_plan" || !baseCatalog.active || contractCatalog?.code !== customerPortalCommercialProducts.enterpriseContract.code || contractCatalog.kind !== "contract_override" || !contractCatalog.active || contractCatalog.public ) { throw new CustomerPortalUatError("customer-portal UAT: Enterprise identity or catalog changed after guarded preflight"); } const current = await readTenantSnapshot(transactionDb, { kind: "enterprise", expectedId: tenantId, expectedSlug: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, }); const currentBlockingIssues: string[] = []; assessTenant(current, [], currentBlockingIssues); if (currentBlockingIssues.length > 0) { throw new CustomerPortalUatError("customer-portal UAT: Enterprise fixture ownership or commercial state changed after guarded preflight"); } if (!current.tenant) { await tx.tenant.create({ data: { id: tenantId, slug: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, name: UAT_ENTERPRISE_TENANT_NAME, icon: "", active: true, }, }); await tx.tenantSubscription.create({ data: { id: UAT_ENTERPRISE_SUBSCRIPTION_ID, tenantId, planCode: "pro", seatQuantity: 1, status: "active", billingProviderCustomerId: null, lagoCustomerId: null, mollieCustomerId: null, }, }); await tx.tenantSubscriptionProduct.create({ data: { id: UAT_ENTERPRISE_BASE_PRODUCT_ID, tenantSubscriptionId: UAT_ENTERPRISE_SUBSCRIPTION_ID, subscriptionProductId: enterpriseBaseProductId, customEntitlementPlanId: "pro", planCode: "pro", seatQuantity: 1, quantity: 1, billingProviderSubscriptionId: null, lagoSubscriptionId: null, fromCheckoutSessionId: null, }, }); await tx.portal.create({ data: { id: UAT_ENTERPRISE_PORTAL_ID, tenantId, createdByUserId: UAT_ADMIN_USER_ID, subdomain: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, title: "Demo Enterprise CRM Kundenportal", isPublished: true, authRequireEmailVerification: false, authRequireOrganization: false, authRequireName: true, metadata: { uatFixture: UAT_PORTAL_MARKER }, }, }); await tx.portalConfiguration.create({ data: { id: UAT_ENTERPRISE_CONFIGURATION_ID, tenantId, portalId: UAT_ENTERPRISE_PORTAL_ID, lifecycleMode: "customer", enabledProjectTypes: [], uploadMaxFiles: 10, uploadMaxFileSizeBytes: 52_428_800, statusEmailsEnabled: true, welcomeMessage: "Willkommen im HiveGrid Test-Kundenportal.", supportEmail: "support@saas-ctrl.com", imprintUrl: `${UAT_LEGAL_ORIGIN}/impressum`, privacyUrl: `${UAT_LEGAL_ORIGIN}/datenschutz`, isDemoData: true, }, }); } const permissionByName = new Map( ( await tx.permission.findMany({ where: { name: { in: [...UAT_REQUIRED_PERMISSIONS] } }, select: { id: true, name: true }, }) ).map((permission) => [permission.name, permission.id]) ); if (permissionByName.size !== UAT_REQUIRED_PERMISSIONS.length) { throw new CustomerPortalUatError("customer-portal UAT: commercial permission catalog changed before Enterprise apply"); } const roleData = { description: UAT_ROLE_DESCRIPTION, type: "app", assignToNewUsers: false, isDefault: false, order: 990, } as const; if (current.roleCandidates.length === 0) { await tx.role.create({ data: { id: expectedRoleId, tenantId, name: UAT_ROLE_NAME, ...roleData } }); } else { await tx.role.update({ where: { id: expectedRoleId }, data: roleData }); } for (const permissionName of UAT_REQUIRED_PERMISSIONS) { const permissionId = permissionByName.get(permissionName); if (!permissionId) throw new CustomerPortalUatError(`customer-portal UAT: required permission ${permissionName} disappeared before Enterprise apply`); const existing = await tx.rolePermission.findFirst({ where: { roleId: expectedRoleId, permissionId }, select: { id: true } }); if (!existing) { await tx.rolePermission.create({ data: { id: `${expectedRoleId}-${permissionName.replaceAll(".", "-")}`, roleId: expectedRoleId, permissionId }, }); } } const tenantUserData = { type: 1, joined: 1, status: 2, seatType: "office" as const }; if (current.membershipCandidates.length === 0) { await tx.tenantUser.create({ data: { id: membershipId("enterprise"), tenantId, userId: UAT_ADMIN_USER_ID, ...tenantUserData }, }); } else { await tx.tenantUser.update({ where: { id: membershipId("enterprise") }, data: tenantUserData }); } if (current.assignmentCandidates.length === 0) { await tx.userRole.create({ data: { id: assignmentId("enterprise"), tenantId, userId: UAT_ADMIN_USER_ID, roleId: expectedRoleId }, }); } const grant = await grantEnterpriseCustomerPortalContract( { tenantId, actorUserId: command.operatorUserId, productId: enterpriseContractProductId, contractReference: UAT_ENTERPRISE_CONTRACT_REFERENCE, quantity: 1, }, { withTenant: async (_tenantId, operation) => operation(transactionDb as never), grantContract: (input) => grantContractProductAcquisition(input, { client: transactionDb as unknown as ProductAcquisitionClient, activationTransaction: async (operation) => operation(transactionDb as never), }), } ); if ( grant.status !== "active" || grant.productKind !== "contract_override" || grant.scopeKey !== UAT_ENTERPRISE_SCOPE_KEY || grant.checkoutUrl !== null || grant.providerPaymentId !== null ) { throw new CustomerPortalUatError("customer-portal UAT: Enterprise contract grant did not converge without checkout"); } if (!current.enterpriseGrantAudited || !grant.replayed) { await publishAuditEventViaOutbox(tx, { tenantId, actorId: command.operatorUserId, actorType: "operator", action: UAT_ENTERPRISE_AUDIT_ACTION, targetType: "TenantProductAcquisition", targetId: grant.id, sourceModule: "billing", outcome: "success", dataSensitivity: "internal", regulatoryScope: ["none"], metadata: { tenantSlug: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, subscriptionProductCode: customerPortalCommercialProducts.enterpriseContract.code, productKind: "contract_override", scopeKey: UAT_ENTERPRISE_SCOPE_KEY, quantity: 1, checkoutCreated: false, replayed: grant.replayed, }, }); } await publishAuditEventViaOutbox(tx, { tenantId, actorId: command.operatorUserId, actorType: "operator", action: "customer_portal.uat_commercial_fixture.provisioned", targetType: "Tenant", targetId: tenantId, sourceModule: "customer-portal-uat", outcome: "success", dataSensitivity: "internal", regulatoryScope: ["none"], metadata: { tenantSlug: CUSTOMER_PORTAL_UAT_ENTERPRISE_TENANT_SLUG, packagePath: "contract_override", basePlan: "pro", portalMonthlyAcquisitionCreated: false, enterpriseContractAcquisitionId: grant.id, checkoutCreated: false, }, }); }); } export async function applyCustomerPortalCommercialFixture( db: DbClient, command: CustomerPortalCommercialFixtureCommand, snapshot: CustomerPortalCommercialFixtureSnapshot ): Promise { const assessment = assessCustomerPortalCommercialFixture(snapshot); if (assessment.action === "blocked") { throw new CustomerPortalUatError("customer-portal UAT: commercial fixture apply is blocked by mismatched or non-UAT staging state"); } if (assessment.action === "noop") return; await runWithRlsContext({ tenantId: command.expectedStarterTenantId }, () => applyGlobalAdminIdentity(db, command)); const starterBaseProductId = snapshot.starterBaseProducts[0]?.id; const enterpriseBaseProductId = snapshot.proBaseProducts[0]?.id; const enterpriseContractProductId = snapshot.enterpriseProducts[0]?.id; if (!starterBaseProductId || !enterpriseBaseProductId || !enterpriseContractProductId) { throw new CustomerPortalUatError("customer-portal UAT: canonical commercial catalog disappeared before apply"); } for (const tenant of snapshot.tenants.filter((candidate) => candidate.kind !== "enterprise")) { await runWithRlsContext({ tenantId: tenant.expectedId }, () => applyTenantFixture(db, command, tenant, starterBaseProductId)); } const enterprise = snapshot.tenants.find((tenant) => tenant.kind === "enterprise"); if (!enterprise) throw new CustomerPortalUatError("customer-portal UAT: Enterprise snapshot disappeared before apply"); const enterpriseReconcileIssues: string[] = []; const enterpriseBlockingIssues: string[] = []; assessTenant(enterprise, enterpriseReconcileIssues, enterpriseBlockingIssues); if (enterpriseBlockingIssues.length > 0) { throw new CustomerPortalUatError("customer-portal UAT: Enterprise snapshot became unsafe before apply"); } if (enterpriseReconcileIssues.length > 0) { await runWithRlsContext({ tenantId: command.expectedEnterpriseTenantId }, () => applyEnterpriseTenantFixture(db, command, enterpriseBaseProductId, enterpriseContractProductId) ); } } export const customerPortalCommercialFixtureIds = Object.freeze({ userId: UAT_ADMIN_USER_ID, starterRoleId: roleId("starter"), proRoleId: roleId("pro"), enterpriseRoleId: roleId("enterprise"), starterMembershipId: membershipId("starter"), proMembershipId: membershipId("pro"), enterpriseMembershipId: membershipId("enterprise"), starterAssignmentId: assignmentId("starter"), proAssignmentId: assignmentId("pro"), enterpriseAssignmentId: assignmentId("enterprise"), enterpriseSubscriptionId: UAT_ENTERPRISE_SUBSCRIPTION_ID, enterpriseBaseProductId: UAT_ENTERPRISE_BASE_PRODUCT_ID, enterprisePortalId: UAT_ENTERPRISE_PORTAL_ID, enterpriseConfigurationId: UAT_ENTERPRISE_CONFIGURATION_ID, });