// @vitest-environment node import { readFileSync } from "node:fs"; import { FormDefinitionSchema } from "../../packages/form-widget/src"; import { describe, expect, it } from "vitest"; import { CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL, CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID, CUSTOMER_PORTAL_UAT_PROJECT_ID, CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN, CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL, CUSTOMER_PORTAL_UAT_TENANT_SLUG, } from "./contracts"; import { assessCustomerPortalFixture, customerPortalUatComplaintDefinition, type CustomerPortalFixtureSnapshot } from "./fixture"; const tenantId = "tenant-demo-pro"; const expectedStageId = "stage-expected"; const forbiddenStageId = "stage-forbidden"; function healthySnapshot(): CustomerPortalFixtureSnapshot { return { tenant: { id: tenantId, slug: CUSTOMER_PORTAL_UAT_TENANT_SLUG, active: true, subscription: { planCode: "business", status: "active", frozenAt: null }, }, projects: [ { id: CUSTOMER_PORTAL_UAT_PROJECT_ID, projektname: "Wärmepumpe Mustermann", projekttyp: "waermepumpe", stageId: expectedStageId, archivedAt: null, stage: { name: "Montage", archivedAt: null }, }, { id: CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID, projektname: "Badsanierung Beispiel", projekttyp: "bad", stageId: forbiddenStageId, archivedAt: null, stage: { name: "Planung", archivedAt: null }, }, ], portal: { id: "portal-1", subdomain: CUSTOMER_PORTAL_UAT_TENANT_SLUG, title: "Demo Pro CRM Kundenportal", isPublished: true, authRequireEmailVerification: false, authRequireOrganization: false, authRequireName: true, metadata: { uatFixture: "VA-P26" }, }, configuration: { lifecycleMode: "customer", enabledProjectTypes: ["waermepumpe", "bad"], 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, }, users: [ { id: "customer-1", emailNormalized: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL, passwordHash: "hash", passwordMatches: true, firstName: "Karla", lastName: "Kundin", kind: "customer", status: "active", archivedAt: null, emailVerifiedAt: new Date("2026-07-17T00:00:00.000Z"), isDemoData: true, }, { id: "subcontractor-1", emailNormalized: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL, passwordHash: "hash", passwordMatches: true, firstName: "Sascha", lastName: "Subunternehmer", kind: "subcontractor", status: "active", archivedAt: null, emailVerifiedAt: new Date("2026-07-17T00:00:00.000Z"), isDemoData: true, }, ], accesses: [ { id: "access-customer", portalUserId: "customer-1", projectId: CUSTOMER_PORTAL_UAT_PROJECT_ID, active: true, revokedAt: null, isDemoData: true, subcontractorAccess: null, }, { id: "access-subcontractor", portalUserId: "subcontractor-1", projectId: CUSTOMER_PORTAL_UAT_PROJECT_ID, active: true, revokedAt: null, isDemoData: true, subcontractorAccess: { active: true, revokedAt: null, canUpload: true, isDemoData: true }, }, ], stageVisibilities: [ { stageId: expectedStageId, visible: true, isDemoData: true }, { stageId: forbiddenStageId, visible: true, isDemoData: true }, ], form: { key: "customer-portal-uat-complaint-key", name: "Kundenportal UAT Reklamation", subtype: "portal_form", status: "published", publishedAt: new Date("2026-07-17T00:00:00.000Z"), isPublic: true, isEnabled: true, isDemoData: true, definition: customerPortalUatComplaintDefinition, targetType: "project", targetEntityId: CUSTOMER_PORTAL_UAT_PROJECT_ID, allowedOrigins: [CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN], notifyEmails: [], config: { honeypotEnabled: false }, }, inbox: { portalId: "portal-1", portalUserId: "customer-1", projectId: CUSTOMER_PORTAL_UAT_PROJECT_ID, kind: "complaint", status: "open", priority: 100, sourceId: "customer-portal-uat", titleKey: "customerPortal.inbox.items.complaint", metadata: { fixture: "VA-P26" }, bundledCount: 1, ownerUserId: null, resolvedAt: null, expiresAt: new Date("2026-07-24T00:00:00.000Z"), isDemoData: true, }, }; } describe("customer-portal UAT fixture contract", () => { it("locks UAT-owned rows and revalidates the fixture inside the write transaction", () => { const source = readFileSync(new URL("./fixture.ts", import.meta.url), "utf8"); expect(source).toContain("lockCustomerPortalFixtureRows(transactionDb, command)"); expect(source).toContain("const lockedSnapshot = await readCustomerPortalFixture(transactionDb, command)"); expect(source.match(/FOR UPDATE/gu)?.length).toBeGreaterThanOrEqual(8); expect(source).toContain("key: UAT_FORM_KEY"); }); it("accepts the complete deterministic fixture and emits safe E2E handoff data", () => { const assessment = assessCustomerPortalFixture(healthySnapshot(), tenantId, new Date("2026-07-17T10:00:00.000Z")); expect(assessment.action).toBe("noop"); expect(assessment.e2e).toEqual({ portalBaseUrl: CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN, tenantSlug: CUSTOMER_PORTAL_UAT_TENANT_SLUG, customerEmail: CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL, subcontractorEmail: CUSTOMER_PORTAL_UAT_SUBCONTRACTOR_EMAIL, subcontractorExpectedProject: "Wärmepumpe Mustermann", subcontractorForbiddenProject: "Badsanierung Beispiel", }); expect(JSON.stringify(assessment)).not.toContain("passwordHash"); }); it("marks missing UAT-owned rows as reconcilable", () => { const snapshot = healthySnapshot(); const assessment = assessCustomerPortalFixture({ ...snapshot, portal: null, configuration: null, users: [], accesses: [] }, tenantId); expect(assessment.action).toBe("reconcile"); expect(assessment.blockingIssues).toEqual([]); }); it("blocks collisions with non-demo identities and access rows", () => { const snapshot = healthySnapshot(); const users = snapshot.users.map((user) => (user.emailNormalized === CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL ? { ...user, isDemoData: false } : user)); const accesses = [ ...snapshot.accesses, { id: "unsafe-extra", portalUserId: "subcontractor-1", projectId: CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID, active: true, revokedAt: null, isDemoData: false, subcontractorAccess: null, }, ]; const assessment = assessCustomerPortalFixture({ ...snapshot, users, accesses }, tenantId); expect(assessment.action).toBe("blocked"); expect(assessment.blockingIssues).toEqual( expect.arrayContaining(["customer UAT identity is not UAT-owned demo data", "subcontractor has a non-demo extra project access"]) ); }); it("does not take over an existing unmarked portal", () => { const snapshot = healthySnapshot(); const assessment = assessCustomerPortalFixture({ ...snapshot, portal: { ...snapshot.portal!, metadata: null } }, tenantId); expect(assessment.action).toBe("blocked"); expect(assessment.blockingIssues).toContain("existing portal is not marked as the VA-P26 UAT fixture"); }); it.each([ ["portal standard-host", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, portal: { ...snapshot.portal!, subdomain: "wrong" } })], ["portal title", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, portal: { ...snapshot.portal!, title: "Wrong" } })], [ "canonical user name", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, users: snapshot.users.map((user) => (user.emailNormalized === CUSTOMER_PORTAL_UAT_CUSTOMER_EMAIL ? { ...user, firstName: "Wrong" } : user)), }), ], ["form definition", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, form: { ...snapshot.form!, definition: { fields: [] } } })], ["form key", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, form: { ...snapshot.form!, key: "wrong-key" } })], ["form config", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, form: { ...snapshot.form!, config: { honeypotEnabled: true } } })], [ "portal configuration", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, configuration: { ...snapshot.configuration!, lifecycleMode: "subcontractor", statusEmailsEnabled: false, supportEmail: "wrong@example.test" }, }), ], ["form origin", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, form: { ...snapshot.form!, allowedOrigins: [CUSTOMER_PORTAL_UAT_STANDARD_ORIGIN, "https://extra.example"] } })], ["inbox project", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, inbox: { ...snapshot.inbox!, projectId: CUSTOMER_PORTAL_UAT_FORBIDDEN_PROJECT_ID } })], ["inbox customer", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, inbox: { ...snapshot.inbox!, portalUserId: "subcontractor-1" } })], ["inbox kind", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, inbox: { ...snapshot.inbox!, kind: "upload" } })], ["inbox source", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, inbox: { ...snapshot.inbox!, sourceId: "foreign" } })], ["inbox title", (snapshot: CustomerPortalFixtureSnapshot) => ({ ...snapshot, inbox: { ...snapshot.inbox!, titleKey: "foreign.title" } })], ])("reports %s drift instead of accepting fixture verify", (_label, drift) => { const assessment = assessCustomerPortalFixture(drift(healthySnapshot()), tenantId, new Date("2026-07-17T10:00:00.000Z")); expect(assessment.action).toBe("reconcile"); }); it("does not reactivate non-UAT subcontractor scopes or stage visibility", () => { const snapshot = healthySnapshot(); const accesses = snapshot.accesses.map((access) => access.portalUserId === "subcontractor-1" ? { ...access, subcontractorAccess: { active: false, revokedAt: new Date("2026-07-16T00:00:00.000Z"), canUpload: false, isDemoData: false }, } : access ); const stageVisibilities = snapshot.stageVisibilities.map((visibility) => visibility.stageId === forbiddenStageId ? { ...visibility, visible: false, isDemoData: false } : visibility ); const assessment = assessCustomerPortalFixture({ ...snapshot, accesses, stageVisibilities }, tenantId); expect(assessment.action).toBe("blocked"); expect(assessment.blockingIssues).toEqual( expect.arrayContaining(["subcontractor scope record is not UAT-owned demo data", `stage visibility ${forbiddenStageId} is not UAT-owned demo data`]) ); }); it("does not take over the deterministic project access when it is not demo-owned", () => { const snapshot = healthySnapshot(); const accesses = snapshot.accesses.map((access) => (access.portalUserId === "customer-1" ? { ...access, isDemoData: false } : access)); const assessment = assessCustomerPortalFixture({ ...snapshot, accesses }, tenantId); expect(assessment.action).toBe("blocked"); expect(assessment.blockingIssues).toContain("customer project access is not UAT-owned demo data"); }); it("keeps the fixture complaint form on the shared FormDefinition contract", () => { expect(FormDefinitionSchema.safeParse(customerPortalUatComplaintDefinition).success).toBe(true); }); });