import { expectNoCriticalA11yViolations } from "./utils/axe"; import { getTenantCredentials, loginAsTenantUser } from "./utils/auth"; import { solveCaptchaIfPresent } from "./utils/captcha"; import { expectNoHorizontalOverflow } from "./utils/mobile"; import { skipIfUnavailable } from "./utils/navigation"; import { skipOrFailWhenE2eFixtureMissing, skipOrFailWhenE2eInputsMissing, skipOrFailWhenE2eOptInMissing } from "./utils/readiness"; import { expect, test, type Locator, type Page } from "./utils/test"; const portalBaseUrl = process.env.E2E_PORTAL_BASE_URL; const tenantSlug = process.env.E2E_PORTAL_TENANT_SLUG; const customerEmail = process.env.E2E_PORTAL_EMAIL; const customerPassword = process.env.E2E_PORTAL_PASSWORD; const subcontractorEmail = process.env.E2E_PORTAL_SUBCONTRACTOR_EMAIL; const subcontractorPassword = process.env.E2E_PORTAL_SUBCONTRACTOR_PASSWORD; const expectedSubcontractorProject = process.env.E2E_PORTAL_SUBCONTRACTOR_EXPECTED_PROJECT; const forbiddenSubcontractorProject = process.env.E2E_PORTAL_SUBCONTRACTOR_FORBIDDEN_PROJECT; const tenantCredentials = getTenantCredentials(); const tenantDashboardPath = process.env.E2E_TENANT_DASHBOARD_PATH; const tenantPortalSettingsPath = process.env.E2E_TENANT_CUSTOMER_PORTAL_SETTINGS_PATH ?? tenantDashboardPath?.replace(/\/dashboard\/?$/u, "/settings/customer-portal"); const mutationOptIn = "E2E_ALLOW_CUSTOMER_PORTAL_P26B_MUTATION"; const portalInputs = ["E2E_PORTAL_BASE_URL", "E2E_PORTAL_TENANT_SLUG", "E2E_PORTAL_EMAIL", "E2E_PORTAL_PASSWORD"] as const; test.use({ trace: "off", video: "off" }); test.describe.configure({ mode: "serial" }); test.describe("VA-P26b customer portal interim journeys", () => { test("customer uploads multiple files and submits an authenticated complaint", async ({ page }) => { requirePortalInputs("VA-P26b customer upload and complaint inputs not configured"); requireP26bMutation("upload and complaint journey"); await loginToPortal(page, customerEmail!, customerPassword!); const uploadRunKey = `${Date.now()}-${process.pid}`; const photoAName = `portal-photo-a-${uploadRunKey}.png`; const photoBName = `portal-photo-b-${uploadRunKey}.png`; const uploadUrl = new URL(`/${tenantSlug}/upload`, portalBaseUrl).toString(); const uploadResponse = await page.goto(uploadUrl, { waitUntil: "domcontentloaded" }); await skipIfUnavailable(page, uploadResponse, `VA-P26b portal upload ${uploadUrl} is unavailable`); const interactions = page.locator('[data-ui-id="ui.customerPortal.projectInteractions"]'); await expect(interactions).toBeVisible(); const fileInput = interactions.locator('input[type="file"]'); if (!(await fileInput.isEnabled())) { skipOrFailWhenE2eFixtureMissing("VA-P26b fixture needs an active customer project access with uploads enabled"); } await fileInput.setInputFiles([ { name: photoAName, mimeType: "image/png", buffer: tinyPng("red"), }, { name: photoBName, mimeType: "image/png", buffer: tinyPng("blue"), }, ]); await expect(interactions.getByText(photoAName)).toBeVisible(); await expect(interactions.getByText(photoBName)).toBeVisible(); const csrfCookiePresent = (await page.context().cookies()).some((cookie) => cookie.name === "__Host-hivegrid_portal_csrf"); expect(csrfCookiePresent).toBe(true); await page.evaluate(() => { const originalFetch = window.fetch.bind(window); Object.assign(window, { __p26UploadFetchObservations: [] }); window.fetch = async (...args) => { const input = args[0]; const target = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; const method = args[1]?.method ?? (input instanceof Request ? input.method : "GET"); const csrfValue = args[1]?.body instanceof FormData ? args[1].body.get("csrf") : null; const csrfFieldPresent = typeof csrfValue === "string" && csrfValue.length > 0; try { const response = await originalFetch(...args); (window as typeof window & { __p26UploadFetchObservations: unknown[] }).__p26UploadFetchObservations.push({ target, method, status: response.status, csrfFieldPresent, }); return response; } catch (error) { (window as typeof window & { __p26UploadFetchObservations: unknown[] }).__p26UploadFetchObservations.push({ target, method, csrfFieldPresent, errorName: error instanceof Error ? error.name : "UnknownError", }); throw error; } }; }); await interactions.getByRole("button", { name: /^(Dateien sicher hochladen|Upload files securely)$/iu }).click(); await expect( interactions.getByText(/^(Die Dateien wurden geprüft und dem Projekt zugeordnet\.|The files were checked and linked to the project\.)$/iu) ).toBeVisible(); const uploadPagePath = new URL(uploadUrl).pathname; const projectUploadPrefix = `${uploadPagePath.slice(0, -"/upload".length)}/projects/`; await expect .poll(() => page.evaluate( ({ projectUploadPrefix }) => ( window as typeof window & { __p26UploadFetchObservations?: Array<{ target: string; method: string; csrfFieldPresent: boolean }>; } ).__p26UploadFetchObservations?.filter((observation) => { const targetPath = new URL(observation.target, window.location.href).pathname; return observation.method === "POST" && observation.csrfFieldPresent && targetPath.startsWith(projectUploadPrefix); }).length ?? 0, { projectUploadPrefix }, ), ) .toBe(2); const observations = await page.evaluate( () => (window as typeof window & { __p26UploadFetchObservations?: Array<{ target: string; method: string; status?: number; csrfFieldPresent: boolean }>; }).__p26UploadFetchObservations ?? [], ); const uploadObservations = observations.filter((observation) => { const targetPath = new URL(observation.target, page.url()).pathname; return observation.method === "POST" && observation.csrfFieldPresent && targetPath.startsWith(projectUploadPrefix); }); expect(uploadObservations).toHaveLength(2); for (const observation of uploadObservations) { const targetPath = new URL(observation.target, page.url()).pathname; expect(targetPath.startsWith(projectUploadPrefix)).toBe(true); expect(targetPath.slice(projectUploadPrefix.length)).toMatch(/^[^/]+\/upload$/u); expect(observation.csrfFieldPresent).toBe(true); expect(observation.status).toBe(201); } const interactionButtons = interactions.getByRole("button"); if ((await interactionButtons.count()) < 2) { skipOrFailWhenE2eFixtureMissing("VA-P26b fixture needs an enabled portal_form complaint form"); } const complaintSubmit = interactionButtons.last(); await completeComplaintFields(interactions); if (!(await complaintSubmit.isEnabled())) { skipOrFailWhenE2eFixtureMissing("VA-P26b complaint fixture contains unsupported or unsatisfied required fields"); } await complaintSubmit.click(); await expect( interactions.getByText( /^(Deine Reklamation wurde gespeichert und das Projektteam informiert\.|Your complaint was saved and the project team was notified\.)$/iu ) ).toBeVisible(); await expectNoCriticalA11yViolations(page); await expectNoHorizontalOverflow(page); }); test("subcontractor sees only the explicitly assigned project", async ({ page }) => { skipOrFailWhenE2eInputsMissing( [ "E2E_PORTAL_BASE_URL", "E2E_PORTAL_TENANT_SLUG", "E2E_PORTAL_SUBCONTRACTOR_EMAIL", "E2E_PORTAL_SUBCONTRACTOR_PASSWORD", "E2E_PORTAL_SUBCONTRACTOR_EXPECTED_PROJECT", "E2E_PORTAL_SUBCONTRACTOR_FORBIDDEN_PROJECT", ], "VA-P26b subcontractor isolation inputs not configured" ); await loginToPortal(page, subcontractorEmail!, subcontractorPassword!); const projectsUrl = new URL(`/${tenantSlug}/projects`, portalBaseUrl).toString(); const projectsResponse = await page.goto(projectsUrl, { waitUntil: "domcontentloaded" }); await skipIfUnavailable(page, projectsResponse, `VA-P26b subcontractor project list ${projectsUrl} is unavailable`); const projectCards = page.locator('[data-ui-id="ui.customerPortal.projectCard"]'); if ((await projectCards.count()) === 0) { skipOrFailWhenE2eFixtureMissing("VA-P26b subcontractor fixture needs one active project-scoped access row"); } await expect(projectCards.getByText(expectedSubcontractorProject!, { exact: false })).toBeVisible(); await expect(page.getByText(forbiddenSubcontractorProject!, { exact: false })).toHaveCount(0); await projectCards .filter({ hasText: expectedSubcontractorProject! }) .getByRole("button", { name: /^(Projekt öffnen|Open project)$/iu }) .click(); await expect(page.locator('[data-ui-id="ui.customerPortal.portalShell"]')).toBeVisible(); await expect(page.getByText(expectedSubcontractorProject!, { exact: false }).first()).toBeVisible(); await expect(page.getByText(forbiddenSubcontractorProject!, { exact: false })).toHaveCount(0); await expectNoCriticalA11yViolations(page); await expectNoHorizontalOverflow(page); }); test("tenant admin persists portal configuration and processes the service inbox", async ({ page }) => { skipOrFailWhenE2eInputsMissing(["E2E_TENANT_EMAIL", "E2E_TENANT_PASSWORD", "E2E_TENANT_DASHBOARD_PATH"], "VA-P26b tenant-admin inputs not configured"); requireP26bMutation("tenant configuration and service-inbox journey"); if (!tenantPortalSettingsPath) { skipOrFailWhenE2eFixtureMissing("VA-P26b customer-portal settings path is not derivable from E2E_TENANT_DASHBOARD_PATH"); } await loginAsTenantUser(page, tenantCredentials!); const settingsResponse = await page.goto(tenantPortalSettingsPath!, { waitUntil: "domcontentloaded" }); await skipIfUnavailable(page, settingsResponse, `VA-P26b tenant portal settings ${tenantPortalSettingsPath}`); await expect(page.locator('[data-ui-id="ui.customerPortal.admin"]')).toBeVisible(); await page.getByRole("button", { name: /^(Grundeinstellungen bearbeiten|Edit basic settings)$/iu }).click(); const saveConfiguration = page.getByRole("button", { name: /^(Konfiguration speichern|Save configuration)$/iu, }); if (!(await saveConfiguration.isEnabled())) { skipOrFailWhenE2eFixtureMissing("VA-P26b admin fixture needs portal.admin permission and a writable tenant"); } await saveConfiguration.click(); await expect(page.getByText(/^(Die Kundenportal-Konfiguration wurde aktualisiert\.|The customer portal configuration was updated\.)$/iu)).toBeVisible(); await page.getByRole("tab", { name: /^(Domain & Mail)$/iu }).click(); await page.getByRole("button", { name: /^(Vollständige Inbox öffnen|Open full inbox)$/iu }).click(); await expect(page.locator('[data-ui-id="ui.customerPortal.serviceInbox"]')).toBeVisible(); const startWork = page.getByRole("button", { name: /^(Bearbeitung starten|Start work)$/iu }).first(); const resolve = page.getByRole("button", { name: /^(Erledigen|Resolve)$/iu }).first(); if (!(await resolve.isVisible())) { skipOrFailWhenE2eFixtureMissing("VA-P26b admin fixture needs one open seven-day service-inbox item"); } if (await startWork.isEnabled()) { await startWork.click(); await expect(page.getByText(/^(Die Kundenportal-Konfiguration wurde aktualisiert\.|The customer portal configuration was updated\.)$/iu)).toBeVisible(); } await resolve.click(); await expect(page.getByText(/^(Die Kundenportal-Konfiguration wurde aktualisiert\.|The customer portal configuration was updated\.)$/iu)).toBeVisible(); await expectNoCriticalA11yViolations(page); await expectNoHorizontalOverflow(page); }); test("customer requests an export and exercises the deletion grace-period cancellation", async ({ page }) => { requirePortalInputs("VA-P26b customer lifecycle inputs not configured"); requireP26bMutation("GDPR export and deletion grace-period journey"); await loginToPortal(page, customerEmail!, customerPassword!); const settingsUrl = new URL(`/${tenantSlug}/settings`, portalBaseUrl).toString(); const settingsResponse = await page.goto(settingsUrl, { waitUntil: "domcontentloaded" }); await skipIfUnavailable(page, settingsResponse, `VA-P26b portal lifecycle settings ${settingsUrl} is unavailable`); const lifecycle = page.locator('[data-ui-id="ui.customerPortal.lifecycle"]'); await expect(lifecycle).toBeVisible(); await lifecycle.getByRole("button", { name: /^(Datenauskunft anfordern|Request data export)$/iu }).click(); await expect(lifecycle.getByText(/^(Deine Datenauskunft wird erstellt\.|Your data export is being prepared\.)/iu)).toBeVisible(); const existingCancel = lifecycle.getByRole("button", { name: /^(Kontolöschung widerrufen|Cancel account deletion)$/iu, }); if (await existingCancel.isVisible()) { await existingCancel.click(); await expect(lifecycle.getByText(/^(Die vorgemerkte Kontolöschung wurde widerrufen\.|The scheduled account deletion was cancelled\.)$/iu)).toBeVisible(); } await lifecycle.getByLabel(/^(Aktuelles Passwort|Current password)$/iu).fill(customerPassword!); await lifecycle.getByRole("button", { name: /^(Kontolöschung vormerken|Schedule account deletion)$/iu }).click(); await expect(lifecycle.getByText(/^(Die Kontolöschung ist vorgemerkt\.|Account deletion is scheduled\.)/iu)).toBeVisible(); await lifecycle.getByRole("button", { name: /^(Kontolöschung widerrufen|Cancel account deletion)$/iu }).click(); await expect(lifecycle.getByText(/^(Die vorgemerkte Kontolöschung wurde widerrufen\.|The scheduled account deletion was cancelled\.)$/iu)).toBeVisible(); await expectNoCriticalA11yViolations(page); await expectNoHorizontalOverflow(page); }); }); function requirePortalInputs(reason: string): void { skipOrFailWhenE2eInputsMissing(portalInputs, reason); } function requireP26bMutation(reason: string): void { skipOrFailWhenE2eOptInMissing(mutationOptIn, `skipping mutating VA-P26b ${reason}`); } async function loginToPortal(page: Page, email: string, password: string): Promise { const loginUrl = new URL(`/${tenantSlug}/login`, portalBaseUrl).toString(); const loginResponse = await page.goto(loginUrl, { waitUntil: "domcontentloaded" }); const loginStatus = loginResponse?.status() ?? 0; if (!loginResponse || [400, 403, 404].includes(loginStatus)) { skipOrFailWhenE2eFixtureMissing(`VA-P26b portal login ${loginUrl} returned ${loginStatus || "no response"}`); } expect(loginStatus).toBeGreaterThanOrEqual(200); expect(loginStatus).toBeLessThan(400); await expect(page.locator('[data-ui-id="ui.customerPortal.publicShell"]')).toBeVisible(); await page .getByRole("button", { name: /^(Stattdessen mit Passwort anmelden|Sign in with a password instead)$/iu, }) .click(); await page.locator('input[name="email"]').fill(email); await page.locator('input[name="password"]').fill(password); await solveCaptchaIfPresent(page); await page .getByRole("button", { name: /^(Stattdessen mit Passwort anmelden|Sign in with a password instead)$/iu, }) .click(); await page.waitForURL((url) => url.pathname.replace(/\/$/u, "") === `/${tenantSlug}`, { timeout: 20_000, }); await expect(page.locator('[data-ui-id="ui.customerPortal.portalShell"]')).toBeVisible(); } async function completeComplaintFields(interactions: Locator): Promise { const editableInputs = interactions.locator('input:not([type="file"]):not([type="checkbox"]):not([type="radio"]), textarea'); for (let index = 0; index < (await editableInputs.count()); index += 1) { const input = editableInputs.nth(index); if (!(await input.isVisible()) || !(await input.isEnabled())) continue; const type = await input.getAttribute("type"); await input.fill(type === "number" ? "1" : `E2E Reklamation ${index + 1}`); } const selects = interactions.getByRole("combobox"); for (let index = 0; index < (await selects.count()); index += 1) { const select = selects.nth(index); if (!(await select.isVisible()) || !(await select.isEnabled())) continue; await select.click(); const option = select.page().getByRole("option").first(); if (await option.isVisible()) await option.click(); } const checkboxes = interactions.getByRole("checkbox"); for (let index = 0; index < (await checkboxes.count()); index += 1) { const checkbox = checkboxes.nth(index); if (!(await checkbox.isVisible()) || !(await checkbox.isEnabled())) continue; if ((await checkbox.getAttribute("aria-checked")) !== "true") await checkbox.click(); } } function tinyPng(color: "red" | "blue"): Buffer { const encoded = color === "red" ? "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9ZrS8AAAAASUVORK5CYII=" : "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="; return Buffer.from(encoded, "base64"); }